Repository Public
1# SP Note Next Generation — code audit of SPNotesCore and SP Notes (macOS)23Audit date: 2026-11-19. Read-only: nothing was edited, built or launched.4Sources read: `~/Desktop/Cluster/apple/SPNotesCore` (git `main` @ `267a673`, clean, origin `gitsrv:srv/git/sp-notes-core.git`)5and `~/Desktop/Cluster/apple/SPNotes` (git `main` @ `bc6ea93`, clean, origin `gitsrv:srv/git/sp-notes-macos.git`).6The production server route list was read over SSH on `M4M64c:~/apps/note-spboucher-ai` (HEAD `77ef5f0`) with `find`.78Legend: **[code]** = read in the source; **[doc]** = taken from the project's own docs and not re-checked line by line;9**[not verified]** = not checked. No test was run during this audit: every test count below is a count of declarations10or a number reported by the projects' docs.1112---1314## A. SPNotesCore1516### A.6 Package.swift (first, because it frames the rest) [code]1718- `swift-tools-version: 6.0`, every target `.swiftLanguageMode(.v6)`.19- Platforms: `.iOS(.v18)`, `.macOS(.v15)`. `defaultLocalization: "fr"`.20- **No external dependency.** Only the system `sqlite3` (linker setting on `SPNotesStore`).21- Products: libraries `SPNotesDocument`, `SPNotesStore`, `SPNotesAPI`, `SPNotesSync`, plus umbrella `SPNotesCore`22 (`Sources/SPNotesCore/SPNotesCore.swift` = four `@_exported import`).23- Dependencies between modules: Document, Store, API are independent of each other. Sync depends on the three.24 `SPNotesStore` does not import `SPNotesDocument`: content is opaque `Data`, the caller supplies plain text, word count, preview.25- `SPN_ONLY=Document|Store|API|Sync` (read from the environment inside `Package.swift`) declares a single module and its26 tests; `SPN_ONLY=Sync` also declares the three it depends on. The umbrella product exists only when `SPN_ONLY` is unset.27- Size: 44 source files / about 12 500 lines, 27 test files / about 9 000 lines.28- Stale scratch directories are present in the tree: `.build-api`, `.build-doc`, `.build-main`, `.build-store`, `.build-synctest`.2930Name clashes to know before importing the umbrella: `SearchHit`, `PurgeResult` and `Tombstone` exist in both `SPNotesAPI`31and `SPNotesStore` (the sync engine already writes `SPNotesStore.Tombstone`). `JSONValue` exists twice: public in32`SPNotesDocument/Model.swift:14`, internal in `SPNotesAPI/JSONSupport.swift:72` (the API exposes `RawJSON` instead).3334### A.1 SPNotesDocument [code]3536Files (`Sources/SPNotesDocument/`): `Model.swift` 406, `Schema.swift` 271, `Commands.swift` 609, `InlineCommands.swift` 135,37`Inline.swift` 181, `MarkdownImport.swift` 605, `MarkdownExport.swift` 89, `HTMLExport.swift` 179, `Text.swift` 245,38`Merge.swift` 138, `SchemaValidation.swift` 96, `Tables.swift` 120, `BlockIds.swift` 64, `JSONValue.swift` 329.3940**Model types** (`Model.swift`)4142| Type | Role |43|---|---|44| `JSONValue` (l.14) | `null, bool, int(Int64), double, string, array, object`; integers stay integers |45| `PMMark` (l.61) | `type: String`, `attrs: [String: JSONValue]?` |46| `PMNode` (l.99) | `type, attrs?, content?, text?, marks?, extra` — the raw ProseMirror node |47| `NoteDocument` (l.232) | `lines: [Line]` + internal `root: PMNode` (the `doc` shell) + `nextKey` |48| `Line` (l.209) | `path: [Container]`, `type: String`, `attrs`, `content: LineContent`, internal `preserved` |49| `Container` (l.177) | `key: Int` (local, not persisted), `type`, `attrs`, internal `preserved` |50| `LineContent` (l.200) | `.inline([InlineRun])` or `.blockAtom(PMNode)` |51| `InlineRun` (l.192) | `.text(String, marks: [PMMark])` or `.atom(PMNode)` |52| `MergeResult` (l.226) | `.merged(NoteDocument)` or `.conflict` |5354There is **no per-node Swift type**. A node type is a `String`; "typed support" means: a constant in `enum NodeType`,55membership in the `Schema` sets, default attributes, a factory, and a `case` in each exporter. Classification happens in56one function, `NoteDocument.shape(of:)` (`Model.swift:320-327`):57581. a node with `text` → atom;592. type in `Schema.textBlocks` → text line;603. type in `Schema.blockAtoms` → block atom line;614. no children → atom;625. type in `Schema.containers` → container frame;636. otherwise: any child that is text or in `Schema.inlineTypes` → text line, else container.6465**Known node types** (`Schema.swift:11-42`, 30 constants, identical to `docs/reference/web-editor-schema.txt`, recorded from66backend commit `2c18f85`):6768| Class | Types |69|---|---|70| text blocks (`Schema.textBlocks`, l.85) | `paragraph`, `heading`, `codeBlock`, `footnote`, `detailsSummary` |71| block atoms (`Schema.blockAtoms`, l.86) | `table` (whole subtree raw), `image`, `fileBlock`, `blockMath`, `horizontalRule`, `youtube` |72| containers (`Schema.containers`, l.87) | `bulletList`, `orderedList`, `taskList`, `listItem`, `taskItem`, `blockquote`, `callout`, `aiBlock`, `details`, `detailsContent` |73| inline (`Schema.inlineTypes`, l.89) | `text`, `hardBreak`, `mention`, `inlineMath`, `footnoteRef`, and the legacy name `"math"` |74| structural only | `doc`, `tableRow`, `tableHeader`, `tableCell` |7576Marks: `Schema.markOrder` (l.107) = `link, bold, code, italic, strike, underline, highlight, subscript, superscript`.77`MarkKind` (l.45) is the toggleable set (all but `link`); `code` excludes the others.7879None of `mermaid`, `drawing`, `chart`, `citation`, `pdf`, `blockRef`, `aiResult`, `queryView`, `runnableCode` exists80anywhere in Core or in the reference schema file. A grep for these names returns only `"mermaid"` as a *code block81language* in the macOS syntax highlighter (mapped to "no grammar").8283**Unknown content: how it survives the round trip**8485- Unknown node type: falls through `shape(of:)` rules 4-6. A leaf becomes `.blockAtom(node)` (block level) or86 `.atom(node)` (inline), kept as the raw `PMNode`. A node with block children becomes a `Container` frame of that type;87 a node with inline children becomes a text line of that type.88- Unknown attributes: `attrs` is a dictionary, nothing is filtered.89- Unknown keys on a node: `PMNode.extra` (`Model.swift:106`), also used for a known key with an unexpected shape90 (`attrs: null`, malformed `marks`). For lines and containers the same data is carried by `Preserved` (`Model.swift:166`:91 `emptyAttrs`, `emptyContent`, `marks`, `extra`).92- Unknown marks: `PMMark.type` is a string; marks are kept in document order on the run. `PMMark(json:)` refuses a mark93 with keys other than `type`/`attrs` (l.74), in which case the whole `marks` array stays in `extra`.94- Text nodes the model could not give back identically (adjacent same-mark text nodes, empty text, `marks: []`, text with95 `attrs` or extra keys) are kept as raw `.atom` runs of type `text` (`Model.swift:366-374`).96- Absent vs empty `attrs` / `content` is preserved.97- Stated guarantee [doc, `DOCUMENT_API.md`]: unmodified document → `jsonData()` semantically identical, key order aside.98 Output is canonical JSON with sorted keys.99100Consequence for the upgrade: a new *leaf* node type already round-trips with zero change in Core. A new node type that has101children is where behaviour depends on the `Schema` sets (see "adding a type" below).102103**Block ids**104105- `BlockID.generate()` (`Schema.swift:147`): 10 characters of the 64-character nanoid alphabet.106- `Schema.idTypes` (l.91) = the server's `ID_TYPES`: `paragraph, heading, blockquote, codeBlock, bulletList, orderedList,107 taskList, table, callout, details, aiBlock, blockMath, image, fileBlock`. Not in the list: `horizontalRule`, `youtube`,108 `footnote`, `listItem`, `taskItem`, table rows and cells.109- `NoteDocument.ensureBlockIds()` → `assignBlockIds()` (`BlockIds.swift:12`): pre-order walk, assigns an id when missing or110 when it duplicates an earlier one. Described as equivalent to the server's `ensureBlockIds`.111- New nodes get an id at creation through `Schema.attrs(_:_:)` (`Schema.swift:138`).112113**Exports and text** (all `switch n.type` with a `default` that recurses into children)114115| Function | File | Unknown node |116|---|---|---|117| `markdown()` | `MarkdownExport.swift:45` (`block`) and `:11` (`inline`) | children concatenated, a leaf yields nothing |118| `html(title:)`, `htmlBody()` | `HTMLExport.swift:73` (`block`) and `:42` (`inline`) | `default:` at l.127 [branch body not read] |119| `plainText()`, `wordCount`, `preview(maxLength:)` | `Text.swift:141-170` | text of descendants |120| `pageReferences()` | `Text.swift:179` | `mention` ids (not `kind: "user"`) and link hrefs containing `/p/<uuid>` |121| `attachmentReferences()` | `Text.swift:192` | any node `attrs.src` with `/api/files/<uuid>`, plus `fileBlock.attachmentId` |122| `taskItems()` | `Text.swift:204` | — |123| `init(markdown:)` | `MarkdownImport.swift` | port of the server's `marked`-based import |124125`plainText`, `wordCount` and `markdown` are stated to match the server byte for byte [doc]. That contract is the reason126every new node type needs the same `case` on the server (`text.ts`, `html.ts`) and here, in the same commit.127`attachmentReferences()` already picks up any new node type that stores a file in `attrs.src`.128129**Three-way merge** (`Merge.swift`, 138 lines)130131- Granularity: **top-level blocks of `doc`**, each compared as a whole canonical JSON string. An entire list, quote,132 callout or table is one block: two edits inside the same list conflict.133- Identity: the block id; a block without an id is identified by its content plus occurrence rank (l.19-36).134- Order: diff3 over the identity sequences using an LCS (`mergeOrder`, l.63).135- `.conflict` when: same block changed differently on both sides; changed on one side and deleted on the other; both sides136 inserted or reordered differently at the same place; the `doc` shell changed on both sides; the result would be empty;137 duplicate ids (top level before, any nested id after the merge).138- No intra-block text merge, no CRDT, no operational transform.139- Title and properties are merged outside this module, in `SyncEngine.merge` (`SyncEngine.swift:946`) and `mergeObjects`140 (l.968): title "one side changed", properties key by key.141142**Schema validation** (`SchemaValidation.swift`): `SchemaChecker.known` (l.31) is a closed set; `check` reports143`unknown node type` for anything else and `strict` mode compares attribute key sets with `Schema.nodeDefaults`. Used by tests144and debug assertions.145146**Commands** (`Commands.swift`, `InlineCommands.swift`, `Tables.swift`): `setLineType`, `toggleList`, `indentListItems`,147`outdentListItems`, `toggleBlockquote`, `toggleCallout`, `setTaskChecked`, `splitLine`, `mergeWithPrevious`,148`insertBlockAtom`, `replaceBlockAtom`, `deleteLine`, `replaceText`, `insertInlineAtom`, `toggleMark`, `setLink`,149`removeLink`, queries (`listKind`, `listDepth`, `isListItemHead`, `isTaskChecked`, `listItemNumber`), and table helpers on150`PMNode` (`tableGrid`, `setTableCellText`, `insert/deleteTableRow`, `insert/deleteTableColumn`, `toggleTableHeaderRow`).151Table helpers do not resolve `colspan`/`rowspan` geometry [doc]. Headings are clamped to levels 1-3.152153**What it takes to add typed support for a new node type** — exact places:154155| # | Place | What to add |156|---|---|---|157| 1 | `Schema.swift:11` `enum NodeType` | a `public static let` |158| 2 | `Schema.swift:85-89` | the type in exactly one of `textBlocks`, `blockAtoms`, `containers`, `inlineTypes` |159| 3 | `Schema.swift:95` `blockGroup` or `:99` `inlineGroup` | group membership (drives the validator) |160| 4 | `Schema.swift:91` `idTypes` | only if the server's `ID_TYPES` gains it too |161| 5 | `Schema.swift:111` `nodeDefaults` | the full default attribute set, as the web editor serializes it |162| 6 | `Schema.swift:178+` `extension PMNode` | a factory (`PMNode.mermaid(source:)`, …) |163| 7 | `SchemaValidation.swift:29` `leaves`, `:31` `known`, `:44` `switch n.type` | leaf or content rule |164| 8 | `MarkdownExport.swift:45` and `:27` | a `case` identical to the server's `toMarkdown` |165| 9 | `HTMLExport.swift:73` and `:62` | a `case` identical to the server's print view |166| 10 | `Text.swift:141` `nodeText` | only if the plain text is not "text of descendants" |167| 11 | `MarkdownImport.swift` | only if Markdown should produce the node (e.g. a ```` ```mermaid ```` fence) |168| 12 | `docs/reference/web-editor-schema.txt` and `Tests/SPNotesDocumentTests/Fixtures/*.json` | re-record from the web app |169| 13 | `Merge.swift` | nothing: whole-block comparison |170171Suggested class for each requested type (my reading of the model, to be confirmed against the web schema once it exists):172173| Type | Class | Note |174|---|---|---|175| `mermaid`, `chart`, `pdf`, `drawing`, `queryView`, `blockRef` (block embed) | block atom, attrs only | zero structural risk; round-trips today as an unknown leaf |176| `citation`, inline `blockRef` | inline atom | add to `inlineTypes` and `inlineGroup`; counts as 1 UTF-16 unit |177| `aiResult` | container of blocks, like `aiBlock` | also add to `Schema.wrappers` (l.103) and `blockParents` (l.105) if blocks may be lifted out |178| `runnableCode` | text block like `codeBlock`, or block atom | as a text block it must join every `codeBlock` special case: grep `NodeType.codeBlock` in `Commands.swift`, `Inline.swift`, `SchemaValidation.swift:49`; and `ParaStyle.isCode` in both native editors |179180Hazard: a node type that holds text and is *not* registered falls to rule 6 and is flattened into an editable text line181of an unknown type. The codec keeps it, but an editor that does not know the type will let the user type into it.182183### A.2 SPNotesStore [code]184185Files: `Schema.swift` 204, `SQLite.swift` 254, `NotesStore.swift` 341, `+Pages` 434, `+Queries` 242, `+Sync` 445,186`+Queue` 276, `+History` 216, `Models.swift` 554. `public actor NotesStore`.187188**Connection**: `SQLITE_OPEN_FULLMUTEX`, `journal_mode=WAL`, `synchronous=FULL`, `foreign_keys=ON`, `busy_timeout` 8 s,189write transactions `BEGIN IMMEDIATE` [doc, `STORE_API.md` §1]. One file may be opened by several processes; a read-only190store never creates or migrates.191192**Migrations** (`Schema.swift:9-38`): `PRAGMA user_version`; `Schema.migrations: [Migration] = [v1]`; `currentVersion` =193array count; each step runs in one transaction with its version bump; a file newer than the build is refused194(`StoreError.schema`). **To add tables: append a `v2` closure to the array (l.13). Never edit `v1`.** The current schema195version is 1, so the first schema change of the upgrade is the first migration this code has ever run on real user files.196197**Schema v1** — 10 tables + 1 FTS5 virtual table:198199| Table | Columns |200|---|---|201| `pages` | `rid` INTEGER PK AUTOINCREMENT, `id` TEXT UNIQUE, `parent_id`, `database_id`, `type` ('page'), `section` ('notes'), `title`, `icon`, `cover`, `content` BLOB, `properties` BLOB, `position` REAL, `pinned`, `archived`, `server_version`, `word_count`, `created_at`, `updated_at`, `last_opened_at`, `deleted_at`, `inbox_at`, `capture_kind`, `rev`, `needs_create`, `dirty_content`, `dirty_meta` TEXT, `tags_dirty`, `edit_seq`, `sync_state` ('synced'), `sync_error`, `plain_text`, `preview`, `favorite`, `is_folder`, `local_updated_at` |202| `page_bases` | `page_id` PK, `title`, `content`, `properties`, `version` |203| `tags` | `name` PK, `color` |204| `page_tags` | (`page_rid` → `pages.rid` ON DELETE CASCADE, `name`) PK |205| `pages_fts` | FTS5 `(title, body, tags)`, `tokenize='unicode61 remove_diacritics 2'`, rowid = `pages.rid` |206| `attachments` | `id` PK, `page_id`, `filename`, `mime`, `size`, `sha256`, `page_count`, `created_at`, `deleted_at`, `rev`, `state` ('remote'), `local_path`, `keep_offline`, `uploaded`, `upload_attempts`, `last_error`, `last_accessed_at` |207| `ops` | `seq` PK AUTOINCREMENT, `kind`, `target_id`, `payload` BLOB, `idem_key` UNIQUE, `created_at`, `attempts`, `next_attempt_at`, `leased_until`, `handed_out`, `coalescable`, `last_error` |208| `conflicts` | `page_id` PK, `version`, `title`, `content`, `properties`, `updated_at`, `detected_at` |209| `local_versions` | `seq` PK AUTOINCREMENT, `id` UNIQUE, `page_id`, `created_at`, `title`, `content`, `word_count`, `reason`, `plain_text`, `preview` |210| `reminders` | `id` PK, `page_id`, `title`, `due_at`, `done`, `server_task_id`, `dirty`, `deleted`, `edit_seq`, `created_at`, `updated_at` |211| `meta` | `key` PK, `value` |212213Indexes on `pages`: `pages_parent`, `pages_live_updated`, `pages_live_recent`, `pages_pinned`, `pages_favorite`,214`pages_inbox`, `pages_archived`, `pages_trash`, `pages_folders`, `pages_section_root`, `pages_dirty` (partial, on215`Schema.dirtyPredicate`, which must stay textually identical to the index), `pages_unsynced_state`. Others:216`page_tags_name`, `attachments_page`, `attachments_not_uploaded`, `attachments_local`, `ops_target`, `local_versions_page`,217`reminders_page`, `reminders_due`, `reminders_dirty`.218219Only `page_tags` has a declared foreign key; every other relation is by page id in code. Timestamps are integer220milliseconds. Ids are lowercase UUID strings.221222**Entity kinds stored**: pages (which also stand for folders = `properties.folder`, and can hold database pages and rows223through `type` / `database_id`), base copies, tags, attachments metadata, queued ops, conflict copies, local versions,224reminders, key/value meta. **Not stored**: tasks as the server models them (only "reminders"), database schemas / views /225properties, graph edges or backlinks, embeddings, AI conversations, research references, agents, saved searches,226comments, canvases, user settings.227228**Public API surface** [doc `STORE_API.md`, signatures spot-checked]:229230- Engine: `init(url:readOnly:)`, `inMemory()`, `close()`, `integrityCheck()`, `checkpoint()`, `rebuildSearchIndex()`, `wipeAll()`.231- Pages, local mutations (one transaction each): `createPage`, `createPages`, `updateContent`, `setProperties`,232 `setFavorite`, `setFolder`, `setPinned`, `setArchived`, `setIcon`, `setCover`, `setInbox`, `move`, `setTags`, `trash`,233 `restore`, `purge`, `duplicate`, `markOpened`.234- Queries: `page`, `summary`, `pageCount`, `summaries(list:)` with `SmartList` (`all, recent, pinned, favorites, inbox,235 archived, trash`), `children(of:)`, `folderTree`, `ancestors`, `summaries(tag:)`, `tags()`, `counts()`.236- Search: `search(query:filters:limit:)`, bm25 weights title 10 / tags 4 / body 1, last term as prefix, input always quoted.237- Sync primitives: `syncCursor`/`setSyncCursor`, `pagesNeedingPush`, `pendingPushCount`, `pageBase`, `markPushed`,238 `markPushFailed`, `applyRemote(pages:attachments:tombstones:tags:cursor:)`, `resetSyncState`,239 `removeSyncedPages(notIn:)`, `resolveConflictUsingCopy`, `resolveConflictKeepingLocal`.240- Conflicts: `recordConflict`, `conflict`, `conflicts`, `clearConflict`.241- Ops queue: `enqueueOp(kind:targetId:payload:)`, `nextOps` (leases, per-target ordering), `completeOp`, `failOp`242 (backoff 5 s doubling to 900 s), `releaseOp`, `releaseAllOpLeases`, `queuedOps`, `opCount`.243- Attachments: `addLocalAttachment`, `attachment`, `attachments(pageId:)`, `pendingUploads`, the `markAttachment…` family,244 `setAttachmentKeepOffline`, `touchAttachment`, `evictionCandidates`, `attachmentsWantedOffline`,245 `resetTransientAttachmentStates`.246- Local versions: `snapshot`, `localVersions`, `localVersion`, `restoreVersion`; 100 per page.247- Reminders: `createReminder`, `updateReminder`, `deleteReminder`, `reminder`, `reminders(pageId:)`,248 `upcomingReminders`, `dirtyReminders`, `markReminderSynced`.249- Meta: `meta`, `setMeta`, `allMeta`.250- Change stream: `changes() -> AsyncStream<StoreChange>` with `pages(Set<String>), tags, attachments(Set<String>), queue,251 conflicts, reminders, meta(String), reset`; `noteExternalChange()` for another process's writes.252253### A.3 SPNotesAPI [code]254255Files: `NotesAPI.swift` 432, `HTTPClient.swift` 546, `APIError.swift` 201, `AuthService.swift` 80,256`PasskeyAuthorizer.swift` 137, `PasskeyCeremony.swift` 335, `SessionTokenStore.swift` 117, `SSEParser.swift` 111,257`AIModels.swift` 161, `PageModels.swift` 412, `ServiceModels.swift` 377, `JSONSupport.swift` 321, `MultipartForm.swift` 113,258`APIConfiguration.swift` 136.259260**Every endpoint method** (`NotesAPI.swift`, line of the method):261262| Method (line) | Verb and path |263|---|---|264| `sync(since:limit:)` (32) | GET `/api/sync?since=&limit=` |265| `createPage` (45) | POST `/api/pages` |266| `page(id:open:)` (52) | GET `/api/pages/{id}[?open=1]` |267| `pageHead` (57) | GET `/api/pages/{id}?head=1` |268| `patchPage` (63) | PATCH `/api/pages/{id}` |269| `resolveConflict` (75) | POST `/api/pages/{id}/resolve` |270| `trashPage` (82) | DELETE `/api/pages/{id}` |271| `purgePage` (88) | DELETE `/api/pages/{id}?purge=1` |272| `emptyTrash` (95) | DELETE `/api/trash[?olderThanDays=]` |273| `restorePage` (102) | POST `/api/pages/{id}?action=restore` |274| `duplicatePage` (107) | POST `/api/pages/{id}?action=duplicate` |275| `pageVersions` (114) | GET `/api/pages/{id}/versions` |276| `pageVersion` (119) | GET `/api/pages/{id}/versions?v=` |277| `restorePageVersion` (126) | POST `/api/pages/{id}/versions` |278| `pageTags` (133) / `setPageTags` (141) | GET / PUT `/api/pages/{id}/tags` |279| `tags` (146) | GET `/api/tags` |280| `uploadAttachment` (159) | POST `/api/attachments` (multipart, streamed from a file, progress callback) |281| `attachments(pageID:)` (174) | GET `/api/attachments[?pageId=]` |282| `deleteAttachment` (181) | DELETE `/api/attachments?id=` |283| `downloadFile` (187) | GET `/api/files/{id}` (to a file, progress callback) |284| `loginOptions` (237) / `loginVerify` (242) | POST `/api/auth/login/options` / `…/verify` |285| `reauthOptions` (247) / `reauthVerify` (252) | POST `/api/auth/reauth/options` / `…/verify` |286| `authState` (257) | GET `/api/auth/state` |287| `logout` (264) | POST `/api/auth/logout` |288| `sessions` (269), `revokeSession` (276), `revokeAllSessions` (285) | GET `/api/auth/sessions`, DELETE `…/{id}`, DELETE `/api/auth/sessions` |289| `passkeys` (290) | GET `/api/auth/passkeys` |290| `passkeyRegistrationOptions` (295) / `…Verify` (301) | POST `/api/auth/passkeys/options` / `…/verify` |291| `renamePasskey` (310) / `deletePasskey` (315) | PATCH / DELETE `/api/auth/passkeys/{id}` |292| `aiAction` (327) | POST `/api/ai/action` (SSE) |293| `aiChat` (333) | POST `/api/ai/chat` (SSE) |294| `search` (366) | GET `/api/search` (`mode=quick|hybrid`, `semantic`, `section`, `since`, `until`, `archived`) |295| `tasks` (380), `createTask` (385), `updateTask` (390), `deleteTask` (396) | GET / POST / PATCH / DELETE `/api/tasks` |296| `inbox` (403), `triageInboxItem` (408), `undoInboxAction` (416) | GET `/api/inbox`, POST `/api/inbox/{id}`, POST `/api/inbox/undo` |297| `capture` (422) | POST `/api/capture` |298| `health` (429) | GET `/api/health` |299300Helpers: `NotesAPI.newID()`, `newIdempotencyKey()`, `filePath(id:)`, `fileID(fromSource:)`.301302**Auth and session** (`HTTPClient.swift`, an `actor`):303304- The backend authenticates with an HttpOnly **cookie**, not a bearer header. The client uses an ephemeral `URLSession`305 with cookie storage, cookie handling, credential storage and URL cache switched off (l.189-197), reads the token from306 `Set-Cookie` itself (`absorb`, l.381-402) and sends `Cookie: __Host-note_session=<token>` by hand (l.365-371).307- Mutating requests (everything but GET) carry `Origin: <configuration.origin>` and, when given, `Idempotency-Key` (l.360-363).308- `User-Agent: SPNotes/<x.y.z> (iPhone|iPad|Macintosh; <os>) native` (`APIConfiguration.userAgent`); the server labels the session from it.309- Redirects are refused (session delegate, l.494). TLS ≥ 1.2 [doc].310- Token rotation: a `Set-Cookie` with a new value replaces the token and is saved to the `SessionTokenStore`; a cleared311 cookie or a 401 ends the session; `sessionEvents()` yields `signedIn`, `tokenRotated`, `signedOut(reason)`.312- WebAuthn ceremony state travels in a second cookie `__Host-note_wa`: captured on an `options` call313 (`HTTPRequest.Ceremony.begin(key)`), replayed once on the matching `verify` (`.complete(key)`), keys `login | reauth | register`.314- `SessionTokenStore` protocol; `KeychainTokenStore` (`SessionTokenStore.swift:33`): generic password, service315 `ai.spboucher.spnotes.session` by default, account = the backend origin, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`,316 not synchronizable, optional access group, data-protection keychain on macOS by default. `InMemoryTokenStore` for tests.317- `AuthService` (`AuthService.swift`): `signIn()`, `stepUp()`, `addPasskey(label:stepUpIfNeeded:)`,318 `withFreshSession { }` (one automatic step-up on `403 reauth_required`), `signOut()`.319- `SystemPasskeyAuthorizer` (`PasskeyAuthorizer.swift:24`): `ASAuthorizationController` for assertion and registration;320 `PasskeyCeremony` does the JSON/base64url work; `PasskeyError` = `cancelled, noCredentials, alreadyRegistered,321 notInteractive, inProgress, notAssociated, invalidOptions, failed(code:message:)`.322- There is no client for first enrolment (`/api/auth/enroll/*`): the first passkey is created on the web.323324**Streaming**: `HTTPClient.openStream` (l.313) uses `URLSession.bytes(for:)` with `Accept: text/event-stream` and325`streamIdleTimeout` (120 s). `SSEParser` is a byte-fed parser. `NotesAPI.events(from:)` (l.343) turns it into326`AsyncThrowingStream<AIEvent, Error>`, ends at `data: [DONE]`, and cancels the reader when the stream is dropped.327`AIEvent` (`AIModels.swift:128`) = `meta, text, done, error, needsConfirmation, other(type:raw:)`. The `other` case means328new server event types (tool calls, citations, agent steps) do not break old clients, but they are untyped: sources of329grounded chat answers arrive today as `.other` or inside `AIMeta.raw` and nothing decodes them.330SSE is used for the two AI routes only. There is no general event channel (no WebSocket, no SSE feed for sync or presence).331332**Error model** (`APIError.swift:30`): `offline, transport(URLError.Code), timeout, cancelled, invalidResponse,333decoding(String), file(String), http(status:code:message:body:), conflict(server: PageConflict, message:),334confirmExpensive(plan: RawJSON, message:)`. Stable codes in `APIError.Code`. Helpers: `isRetryable` (offline, transport,335timeout, 429, 408, 5xx, `409 in_progress`; not `not_configured`/`no_model`), `isConflict`, `needsReauth`,336`isUnauthenticated`, `isRateLimited`, `isOffline`, `isNotFound`, `serverCopy`, `plan`. Descriptions never include request data.337**`HTTPClient` does not retry by itself**; retry policy lives in `SyncEngine`.338339**Server areas with no client** — production route tree (`M4M64c:~/apps/note-spboucher-ai/src/app/api`) versus `NotesAPI`:340341| Area | Routes on the server with no method in `NotesAPI` |342|---|---|343| Databases | `/api/databases`, `/api/databases/templates`, `/api/databases/[id]`, `…/properties`, `…/views`, `…/rows`, `…/rows/restore`, `…/query`, `…/import`, `…/duplicate`, `…/apply-template`, `…/ai` |344| Graph | `/api/graph`, `/api/graph/backlinks`, `/api/graph/neighbors`, `/api/graph/suggestions` |345| Research | `/api/research/overview`, `…/papers`, `…/references` (+ `[id]`, `[id]/extracts`, `[id]/links`, `doi`, `import-bibtex`, `export.bib`), `…/experiments` (+ `[id]`), `…/tasks` (+ `[id]`), `…/ai` |346| Agents and jobs | `/api/agents`, `/api/agents/[id]`, `/api/jobs` |347| AI beyond action/chat | `/api/ai/models`, `/api/ai/conversations`, `/api/ai/usage`, `/api/ai/chat/plan`, `/api/ai/compare`, `/api/ai/compare/vote` |348| Search extras | `/api/search/duplicates`, `/api/search/index-state` |349| Dashboard | `/api/dashboard`, `/api/dashboard/summary` |350| Import / export | `/api/import`, `/api/export` |351| Settings | `/api/settings`, `/api/settings/audit` |352| Tree | `/api/tree` |353| Pages | `/api/pages/[id]/beacon`; list `GET /api/pages` |354| Auth | `/api/auth/enroll/options`, `/api/auth/enroll/verify` |355356Covered by a client method but used by no macOS code: `search`, `tasks`/`createTask`/`updateTask`/`deleteTask` (the engine357uses the last three for reminders), `inbox`/`triageInboxItem`/`undoInboxAction` (engine only, for queued triage),358`capture`, `tags`, `pageTags`, `attachments`, `duplicatePage`, `emptyTrash`, `authState`, `health`, `renamePasskey`,359`deletePasskey`, `revokeAllSessions`.360361The dev worktree `M4M64c:~/dev/note-v2` additionally has `/api/backups` and has **no** `/api/sync` and no362`apple-app-site-association` route; production has both. The request and response shapes of the uncovered routes were363not read. [not verified]364365### A.4 SPNotesSync [code + doc]366367One file, `SyncEngine.swift` (1 014 lines): `public actor SyncEngine`, `SyncOptions` (`autoDownloadLimit` 25 MiB,368`includeDatabaseRows = false`, `feedPageSize = 200`), `SyncStatus`, `SyncOutcome`, `ConflictResolution`,369`AttachmentFileLocating`, `ContentDigest`, `QueuedTriage`.370371**There is no general op journal.** State-based sync with two mechanisms:3723731. **Dirty flags on the page row** for page state: `needs_create`, `dirty_content` (title / content / properties, the374 version-guarded fields), `dirty_meta` (a set among `parentId, section, position, pinned, archived, icon, cover, inboxAt`),375 `tags_dirty`, plus `edit_seq` incremented by every local change to push. The base copy in `page_bases` is the last376 state common with the server.3772. **The `ops` table** for actions that are not state: `OpKind` (`Models.swift:395`) = `trash, restore, purge,378 deleteAttachment, createTask, updateTask, deleteTask, triage`. A row is `seq`, `kind` (free string), `target_id`,379 `payload` (opaque BLOB; JSON `QueuedTriage` for triage), `idem_key` (32 hex characters generated once), `attempts`,380 `next_attempt_at`, `leased_until`. The dispatch is the `switch op.kind` at `SyncEngine.swift:574-589`; only `trash,381 restore, purge, deleteAttachment, triage` are handled. **An unknown kind falls to `default: break` and is then382 completed, i.e. silently dropped** (l.587-590). `createTask`/`updateTask`/`deleteTask` are declared but not dispatched:383 reminders go through `pushReminders()` (l.608) from the `reminders` table.384385**Cycle** (`cycle()`, l.179): up to 4 rounds of push then pull, then downloads.386387- Push (`push()`, l.263): creations, parents first (`POST /api/pages` with the local id, then one unguarded PATCH and388 `PUT tags`); uploads (`uploadPending`, l.529); edits of known pages (`sendChanges`, l.385): unguarded fields and tags,389 then title/content/properties with `baseVersion`; queue (`runQueue`, l.563); reminders (`pushReminders`, l.608).390- Pull (`pull()`, l.651): `GET /api/sync?since=<cursor>` until `more` is false; each answer applied by391 `store.applyRemote` in one transaction with its cursor.392- Downloads (`downloadWanted`, l.814): up to 40 files [doc].393394**Cursor**: `meta["sync.cursor"]`, an `Int64` equal to the server `rev`, a single sequence bumped by database triggers on395every write. `since=0` = full copy. `reset: true` → `resetSyncState()` and a full re-download, at most twice per cycle.396The feed must strictly advance while `more`.397398**Conflicts** (`reconcile`, l.485): server copy equal to local → adopted; equal to what this device sent before a lost399answer (`sync.sent.<pageId>` fingerprint) → base moved; server older than the base → local sent again with a snapshot;400otherwise three-way merge (title, `NoteDocument.merge`, properties key by key); otherwise a `conflicts` row, local text401untouched, the page leaves the push list until `resolveConflict(pageId:choice:)` (`keepMine | keepTheirs | keepBoth`).402Flags, tags, moves, icon, cover, position are last-writer-wins.403404**Idempotency**: page creation and upload rely on the client-chosen id and deliberately send **no** key; guarded PATCH on405`baseVersion`; ops on their stored key; task creation on `spn-task-<reminder id>`; resolution on a key built from page,406server version, choice and a fingerprint of the local text.407408**Entity kinds that flow**409410| Kind | Push | Pull |411|---|---|---|412| pages (notes, folders) | yes | yes |413| tags (per page, and the workspace tag list with colours) | yes | yes |414| attachments (metadata + bytes) | yes | yes |415| tombstones (`page`, `attachment`) | — | yes |416| trash / restore / purge / attachment deletion / inbox triage | yes (ops) | effects arrive as page changes |417| reminders → server tasks | yes | **no** — tasks created or changed on the web never come back |418| database row pages | no | filtered out at `SyncEngine.swift:680` unless `includeDatabaseRows` |419| workspace name, user display name | — | yes, into `meta` |420| databases (schema, views, properties), graph edges, research, agents, AI conversations, settings | no | no |421422The feed (`SyncPage`, `PageModels.swift:24`) carries `pages, attachments, tombstones, tags` only. `Tombstone.kind` is a423string; the engine maps it with `SPNotesStore.Tombstone.Kind(rawValue:)` and **drops unknown kinds** (l.682-685).424425**How to extend the engine to new entity kinds** (database rows, tasks, graph edges, canvases)426427The engine has no entity abstraction: no protocol, no registry. Each kind is hand-written across four layers. Per new kind:4284291. Server: add the kind to the `GET /api/sync` payload and to the `rev` triggers, with tombstones.4302. `SPNotesAPI/PageModels.swift:24` `SyncPage`: a new optional array (decoding must tolerate its absence so old servers431 still work) and the DTO; endpoint methods in `NotesAPI`.4323. `SPNotesStore/Schema.swift:13`: migration `v2` (table with `rev`, dirty flags, `edit_seq`, optional base copy);433 `Models.swift`: record types, a new `Tombstone.Kind`, a new `StoreChange` case; `NotesStore+Sync.swift`: extend434 `applyRemote(…)` and `ApplySummary`, add `…NeedingPush` / `mark…Pushed`.4354. `SyncEngine.swift`: a push phase in `push()` (l.263), mapping in `pull()` (l.680-687), a `case` in `runQueue()` (l.574)436 for any new op kind, and the tombstone mapping (l.682).437438Cheaper routes that avoid a new kind:439440- **Database rows are already pages** (`database_id`, `type`). Setting `includeDatabaseRows = true` brings rows into the441 existing page pipeline, with versioned `properties` and the key-by-key merge. What is still missing is the database442 *definition* (properties, views), which has no feed entry and no table. `NoteSession.isEditable` in the macOS app443 currently makes such pages read-only.444- **Canvases, drawings, charts** stored as page content (a node type) or as a page of a new `type` need no engine change;445 only the 3-way merge granularity (whole top-level block) limits concurrent editing.446- **Graph edges** are derivable from content (`pageReferences()` exists); a local `links` table filled by the store at447 write time would give offline backlinks without syncing anything. The store does not import `SPNotesDocument`, so the448 caller would have to supply the references, as it does for plain text.449- **Tasks**: two models exist on the server — task items inside documents (`taskItem` nodes, counted by `taskItems()`)450 and `/api/tasks` rows. The store's `reminders` table is a push-only shadow of the second. Bidirectional tasks need the451 feed entry and an "apply remote reminder".452453Known limits listed by the project [doc `SYNC_ENGINE.md` §6]: reminders push-only; moves are last-writer-wins and the454server does not check cycles; no compare-and-set on the conflict helpers; a restored server whose head has passed the455cursor is undetectable; 500 pages per round, 4 rounds per cycle; ops refused for good are retried forever; `stop()` reads456as `.offline`.457Doc inconsistency: `SYNC_ENGINE.md` §6 says a purged folder queues one op for the root only; `STORE_API.md` §2.2 and the458macOS 1.0.1 release notes say one op per page of the subtree. The second is the later text. [not verified in code]459460### A.5 Tests [declarations counted; nothing run]461462| Target | Framework | Suites → declared tests |463|---|---|---|464| `SPNotesDocumentTests` | Swift Testing | Command 35, Model 22, Text 16, Merge 7, Dump 1 = **81** |465| `SPNotesStoreTests` | Swift Testing | Sync 15, Page 12, Engine 11, Search 6, QueueHistory 5 = **49** |466| `SPNotesAPITests` | XCTest | HTTPClient 22, ErrorAndModel 17, PasskeyAndAuth 15, RoutesAndMultipart 12, SSEAndAI 11, LiveBackend 11 = **88** |467| `SPNotesSyncTests` | Swift Testing | Fault 26, MergeConflict 16, TrashAttachmentQueue 14, SyncEngine 7, RandomConvergence 1, LiveSmoke 1 = **65** |468469Total 283, matching the README. Fixtures: `Tests/SPNotesDocumentTests/Fixtures/{rich,unknown,expected,md-samples,470md-server,random-server}.json`. `Tests/SPNotesSyncTests/FakeBackend.swift` (1 072 lines) is an in-memory backend written471from the server's route handlers; it will need every new route and feed field.472473How they are run:474475```sh476swift test # everything477SPN_ONLY=Document swift test --scratch-path .build-document478SPN_ONLY=Store swift test --scratch-path .build-store479SPN_ONLY=API swift test --scratch-path .build-api480SPN_ONLY=Sync swift test --scratch-path .build-sync481```482483Environment variables: `SPN_ONLY`; `SPN_LIVE_URL` + `SPN_LIVE_TOKEN` (live tests, skipped with `XCTSkip` when unset, and484any `*.spboucher.ai` host is refused); `SPN_LIVE_TOKEN_DISPOSABLE`, `SPN_LIVE_TOKEN_DISPOSABLE2`; `SPN_RANDOM_SEEDS`,485`SPN_RANDOM_ONLY`; `SPN_DUMP`. Live server = SSH tunnel to `M4M64c:8482` (`~/dev/note-native`, database486`note_native_dev`), token minted by `scripts/dev-session.ts` on the node. `swift test` writes every emitted document to487`/tmp/spn-docs.json` for validation against the real web schema on `M4M64c:~/dev/note-v2`.488489Flakiness: no test is marked flaky and no known-flaky note exists in the docs. Time- or environment-dependent items:490the live tests' "fresh" window (a dev token is fresh for 5 minutes; after that the purge and revocation tests assert491`reauth_required` instead), and the keychain test, which skips when no usable keychain exists. `/tmp/spn-dev-token.txt`492exists on this laptop from an earlier session (not opened).493494---495496## B. macOS app (SP Notes 1.0.2, build 3)49749844 Swift files, about 6 600 lines. `project.yml` (XcodeGen) + a local SwiftPM package for the editor.499500### B.1 Structure — every file501502**App/**503504| File | Lines | Role |505|---|---|---|506| `SPNotesApp.swift` | 44 | `@main`; scenes: `WindowGroup("SP Notes", id: "main")`, `WindowGroup("Note", id: "note", for: String.self)`, `Settings`, `MenuBarExtra` |507| `AppEnvironment.swift` | 170 | `LaunchOptions`, `Connectivity` (NWPathMonitor), `AttachmentFiles`, `AppEnvironment` (the dependency container: HTTP, API, auth, store, sync, preferences, account, library, sync monitor, lock, note sessions) |508| `MainWindow.swift` | 140 | `WindowModel` (per-window state), `MainWindow` (3-column `NavigationSplitView`), `LockScreen`, `AppEnvironment.start()` |509| `AppCommands.swift` | 102 | the menu bar: File, Edit additions, Format, Insérer, Note, View additions, Synchronisation |510| `AppDelegate.swift` | 206 | `DeepLink`, `AppDelegate` (URL open, Service, terminate flush), `GlobalHotKey` (Carbon), `QuickNotePanel`, `QuickNoteModel`, `QuickNoteView` |511| `SyncMonitor.swift` | 133 | `SyncMonitor` (drives `SyncEngine`, 75 s timer), `ToastCenter`, `ImageCache` |512| `AppLock.swift` | 40 | optional local lock through LocalAuthentication |513| `Preferences.swift` | 64 | `AppearanceMode`, `NoteSort`, `Preferences` (16 UserDefaults keys) |514515**Components/**516517| File | Lines | Role |518|---|---|---|519| `DesignSystem.swift` | 91 | `Palette`, `Format`, `SyncDot`, `ToastOverlay`, `EmptyState`, `HighlightedText`, `onChangeAsync` |520| `EditorController.swift` | 62 | owns one `NoteTextView` + scroll view, implements `NoteTextViewDelegate` and `AtomResources`; `NoteEditorView` (`NSViewRepresentable`) |521522**Features/**523524| File | Lines | Role |525|---|---|---|526| `Account/AccountModel.swift` | 101 | phases `local | signedIn | expired`, sign-in, sign-out with or without local erase |527| `Account/AccountSheet.swift` | 113 | sign-in, passkey list, session list, sync box, reauth button |528| `Account/WelcomeView.swift` | 37 | first-launch screen |529| `AI/AssistantPanel.swift` | 155 | `AssistantModel` + side panel |530| `Attachments/AttachmentService.swift` | 133 | import and validation of files and images, Quick Look, save copy, disk usage, eviction |531| `History/HistoryAndConflicts.swift` | 147 | `HistorySheet` (local + server versions), `ConflictBanner`, `ConflictSheet` |532| `Home/LibraryModel.swift` | 191 | `SidebarItem`, `FolderNode`, `LibraryModel` (lists, folders, tags, search, all organisational actions) |533| `Home/SidebarView.swift` | 119 | sidebar + `SyncStatusBar` |534| `Notes/NoteSession.swift` | 156 | one open note: editor, title, autosave, snapshots, merge of remote changes |535| `Notes/NoteDetailView.swift` | 287 | `NoteDetailView`, `NoteEditorPane`, `Banner`, `FormatBar`, `StatusBar` |536| `Notes/AtomEditors.swift` | 220 | `AtomEditorSheet`, `TableEditor`, `MathEditor`, `ImageDetails`, `FileDetails`, `UnknownBlock`, `LinkEditorSheet` |537| `Notes/InspectorPanel.swift` | 104 | tags, organisation, info, attachments, links; `FlowLayout` |538| `Notes/NoteListView.swift` | 168 | middle column, `NoteRow`, `SearchFilterBar` |539| `Notes/Exporter.swift` | 171 | export Markdown / text / HTML / RTF / PDF / ZIP, print, import |540| `Search/CommandPalette.swift` | 114 | palette (⇧⌘P) and quick open (⌘O), `AppActions` |541| `Settings/SettingsView.swift` | 116 | General, Editor, Sync, Security, Storage tabs |542543**Editor/** (SwiftPM target `SPNotesEditor`, AppKit only, depends on `SPNotesDocument` and SwiftMath 1.7.3)544545| File | Lines | Role |546|---|---|---|547| `NoteTextView.swift` | 642 | the `NSTextView` subclass on TextKit 2: load, serialize, `applyRemote`, incremental styling, the `replace` primitive, Return / Tab / Backspace, Markdown shortcuts, mouse handling |548| `EditorCommands.swift` | 341 | `BlockKind`, `SelectionState`, block and mark commands, atom insertion, Markdown insertion |549| `DocumentCodec.swift` | 151 | `NoteDocument` ⇄ `NSAttributedString` |550| `EditorAttributes.swift` | 162 | `.spPara`, `.spMarks`, `.spDecoration`, `ParaStyle`, `MarkSet`, `ParaDecoration`, `EditorTheme`, `KeyAllocator` |551| `Styler.swift` | 185 | fonts, colours, indents, decorations for the touched paragraphs |552| `BlockLayoutFragment.swift` | 100 | `NSTextLayoutFragment` subclass drawing markers, quote bars, panels |553| `AtomAttachment.swift` | 267 | `NodeBox`, `AtomResources`, `AtomAttachment`, `AtomRenderer` |554| `Completion.swift` | 215 | "/" and "@" menus, `CompletionPanel`, `EditorImages` |555| `NoteFragment.swift` | 158 | pasteboard: private structured type, RTF, plain text, foreign rich text |556| `SyntaxHighlighter.swift` | 119 | hand-written tokenizer, about 20 language families |557| `ExportComposer.swift` | 96 | attributed string for RTF / PDF / print |558| `MathRenderer.swift` | 46 | SwiftMath typesetting with a cache |559560**Tests/**: `EditorTests/EditorTests.swift` (288, SwiftPM), `EditorTests/SnapshotSupport.swift`, `AppTests/EndToEndTests.swift`561(305, hosted), `UITests/SPNotesUITests.swift` (45).562563### B.2 Editor architecture [code]564565**Storage ⇄ model mapping.** The text view's `NSTextStorage` is the live model; `NoteDocument` exists only at load and at566save. Conventions (`DocumentCodec.swift:7-12`):567568- every line ends with `\n`, the last included; the newline carries the paragraph attributes;569- `.spPara` → a `ParaStyle` object (`EditorAttributes.swift:18`) = the `Line` without its content (`template`), so unknown570 node keys survive; the paragraphs of one code block share **the same instance** (identity is the block);571- `.spMarks` → a `MarkSet` of raw `PMMark`, unknown marks included;572- a block atom = a paragraph made of one `U+FFFC` attachment character carrying an `AtomAttachment`;573- an inline atom = one attachment character; a `hardBreak` = `U+2028` tagged `.spInlineNode` with a `NodeBox`;574- `.spDecoration` → `ParaDecoration`, derived, never serialized.575576`DocumentCodec.attributedString(from:)` (l.23) and `DocumentCodec.lines(from:in:)` (l.70) are the two directions. Save:577`NoteSession.saveNow` → `editor.document()` → `jsonData()` → `ContentDigest` → `store.updateContent`. So **every autosave578(350 ms after the last keystroke) re-serializes the whole document**; measured 32 ms for 4 000 blocks [doc `TEST_REPORT.md`].579580**Styling.** `NSTextStorageDelegate.textStorage(_:didProcessEditing:…)` (`NoteTextView.swift:202`) calls581`Styler.affectedRange` then `Styler.style`, which restyles the edited paragraphs widened to their top-level structure.582`Styler.apply` (`Styler.swift:73`) walks `ParaStyle.path` and switches on the container type (l.79-110).583584**How each block type is rendered**585586| Node | Rendering | Where |587|---|---|---|588| paragraph, heading 1-3, footnote | fonts / sizes from `EditorTheme` | `Styler.swift:134-154` |589| marks bold, italic, underline, strike, code, highlight, sub, superscript, link | attributes | `Styler.swift:135-153` |590| codeBlock | monospaced font, panel, token colours | `Styler.swift:114-117`, `highlightCode` l.158, panel in `BlockLayoutFragment.draw` |591| bulletList / orderedList / taskList | indent + marker (`bullet(level)`, `number`, `checkbox`) drawn by the layout fragment | `Styler.swift:86-108`, `BlockLayoutFragment.swift:70-90` |592| blockquote | bars | `Styler.swift:80`, fragment |593| callout | tinted panel + icon | `Styler.swift:81`, fragment |594| aiBlock | tinted panel | `Styler.swift:83`, fragment |595| details | disclosure marker on the summary, content indented; **no collapse** — `open` is ignored | `Styler.swift:85, 113` |596| table | **bitmap** of the grid | `AtomRenderer.table`, `AtomAttachment.swift:246` |597| image | bitmap, max width 720; placeholder card when the file is not local | `picture`, l.143 |598| blockMath / inlineMath | SwiftMath bitmap; fallback = source text | l.158, l.173 |599| fileBlock, youtube | a generic "card" bitmap (symbol + title + subtitle) | l.106-107 |600| mention, footnoteRef | "pill" bitmap | l.108, l.110 |601| horizontalRule | 1-pt line bitmap | l.137 |602| unknown block | card "Bloc « type » — Conservé tel quel — modifiable sur le site web" | l.112 |603| unknown inline | pill `⟨type⟩` | l.113 |604605**Atoms are static images.** `AtomAttachment` is an `NSTextAttachment` whose `image` is produced by `AtomRenderer` into a6062× `NSBitmapImageRep` and cached per (width, dark). There is no `NSTextAttachmentViewProvider`, no live subview, no607in-place interaction: a table cannot be edited in the text, an image cannot be resized, a video does not play. Interaction608is **double-click → `noteDelegate.noteTextView(_:activate:at:)` → `EditorController.activeAtom` → a SwiftUI sheet**609(`AtomEditorSheet`, `AtomEditors.swift:22` `switch atom.node.type`). The bitmap scale is hard-coded to 2 (l.120).610611**Commands and toolbar.** Everything goes through `NoteTextView.replace(_:with:select:actionName:)`612(`NoteTextView.swift:239`) or `restyleParagraphs` (l.256): one undo step each, with the view's own `UndoManager`.613`EditorCommands.swift`: `setBlock(_:toggle:)` (l.51) over `BlockKind` (`paragraph, heading(Int), code, bullet,614ordered(start:), task, quote, callout`), `indent`, `outdent`, `moveBlock(up:)`, `toggleMark`, `clearFormatting`,615`setLink`, `insertBlockAtom` (l.239), `insertInlineAtom` (l.258), `replaceAtom` (l.267), `insertRule`, `insertTable`,616`insertBlockMath`, `insertInlineMath`, `insertMention`, `insertImage`, `insertFile`, `insert(_ doc:)`, `insertMarkdown`,617`selectedMarkdown`. The SwiftUI `FormatBar` (`NoteDetailView.swift:196`) and `AppCommands` call these directly and read618`EditorController.selection: SelectionState`. The same command list is written three times: `AppCommands.swift`,619`FormatBar`, and the palette in `CommandPalette.swift`.620621**Slash and mention menus.** `Completion.swift`: `builtinSlashItems()` (l.17) returns 14 static entries (text, h1-h3,622bullet, ordered, todo, quote, callout, divider, code, table, math, inline math); the app appends its own through623`NoteTextViewDelegate.noteTextView(_:completionsFor:query:)` — `NoteEditorPane.slashItems()` (`NoteDetailView.swift:128`:624image, file, link to a note, new sub-note, ask the assistant) and `mentionItems(_:)` (l.139: local FTS `quickFind`, plus625"create the note"). The menu is a borderless non-key `NSPanel` (`CompletionPanel`, l.102) with AppKit rows.626Markdown shortcuts at the start of a line: `NoteTextView.applyMarkdownShortcut` (l.396).627628**Exactly where to add rendering for a new atom or block type**629630For a new **atom** (block or inline) — the minimum, three places:6316321. `Editor/AtomAttachment.swift:100` `AtomRenderer.image(for:isBlock:width:)` — a `case "<type>":` returning an image633 (reuse `card`, `pill`, or write a drawer like `table`).6342. `Features/Notes/AtomEditors.swift:22` `AtomEditorSheet.content` — a `case "<type>":` with its SwiftUI editor.6353. Insertion: a method next to `EditorCommands.swift:282-290` built on `insertBlockAtom` / `insertInlineAtom`; an entry in636 `Completion.swift:19` (built-in) or `NoteDetailView.swift:129` (needs app services); menu items in `AppCommands.swift:68`637 and `FormatBar` (`NoteDetailView.swift:232`); the palette.638639Plus, when relevant: `NoteTextView.idTypes` (`NoteTextView.swift:346`) if the node takes an id; `ExportComposer.swift:52`640(`switch` for RTF / PDF / print text fallbacks); `AtomAttachment.rendered` l.50 (the "do not cache a placeholder" rule is641written for `image` only — any atom whose rendering depends on an asynchronous resource needs the same);642`AtomRenderer.inlineDescent` (l.95) for inline atoms with a baseline.643644For a new **container** (e.g. `aiResult`): `Styler.swift:79` `switch c.type` (indent + `deco.panel`),645`EditorAttributes.swift:80` `ParaDecoration.Panel` (new case), `BlockLayoutFragment.swift:44` (panel colour `switch`),646`EditorTheme` (colour), `EditorCommands.swift:124` `toggleWrapper`, `BlockKind` (l.7) and `selectionState` (l.27),647`NoteTextView.lifted` (l.549) for leaving the container.648649For a new **text block** like `runnableCode`: `ParaStyle.isCode` (`EditorAttributes.swift:39`) is tested throughout650`NoteTextView` (Return, Tab, Backspace, `codeBlockRange`), `DocumentCodec` (line joining, l.89), `Styler` and651`Completion`. A second code-like type means generalising `isCode`.652653For anything **interactive in place** (a chart that responds, a query view that scrolls, a drawing, a PDF page, a Mermaid654diagram that re-renders, a runnable cell with output): the bitmap model is the wall. It needs655`NSTextAttachmentViewProvider` (hosting an `NSView` / `NSHostingView`) or overlay views positioned from layout fragments.656Neither exists in the codebase; `AtomAttachment` overrides the image and bounds methods only.657658### B.3 Design [code]659660**Tokens that exist**661662- `Components/DesignSystem.swift:7` `enum Palette`: `amber = Color("AccentColor")`, `subtle = Color.primary.opacity(0.06)`,663 `tag(_:)` mapping seven colour names to system colours. That is the whole SwiftUI palette.664- `Resources/Assets.xcassets/AccentColor.colorset`: light sRGB (0.890, 0.520, 0.040), dark (1.000, 0.690, 0.200).665 The catalog holds `AccentColor` and `AppIcon` only.666- `Editor/EditorAttributes.swift:99` `EditorTheme`: `fontSize` 15, `fontDesign` (`system | serif | rounded | monospaced`),667 `lineSpacing` 3, `indentWidth` 26; heading scale 1.75 / 1.4 / 1.18; code font 0.9×; static dynamic `NSColor`s `accent`668 (a second, slightly different amber: light (0.80, 0.45, 0.02)), `link`, `codeBackground`, `inlineCodeBackground`,669 `highlight`, `quoteBar`, `calloutBackground`, `aiBackground`; `tokenColor(_:)` for syntax.670- `Preferences`: `fontSize` (12-22 through the menu), `fontDesign`, `columnWidth` 780.671672**What does not exist**: no spacing scale, no radius scale, no typography scale for the chrome, no elevation or material673tokens, no semantic colour roles, no shared button / field / card styles. Spacing and radii are literals in the views674(`padding(12)`, `padding(18)`, `cornerRadius: 5/6/7/8/9`, widths 270 / 330 / 560). Fonts are SwiftUI text styles or675literals (`.system(size: 26, weight: .bold)` for the title). Editor metrics are literals in `Styler` (18, 38, 12) and in676`BlockLayoutFragment`.677678**Appearance**: `AppearanceMode` (`system | light | dark`) applied with `.preferredColorScheme` on the main window and679Settings. Editor colours are dynamic `NSColor(name:)` providers. `NoteTextView.viewDidChangeEffectiveAppearance` (l.191)680→ `refreshAtoms()` invalidates the atom bitmaps. `.tint(Palette.amber)`. Materials used: `.ultraThinMaterial` (lock),681`.regularMaterial` (welcome, quick note, toast), `.bar` (status bar), `NSVisualEffectView.material = .menu` (completion).682No increase-contrast or differentiate-without-colour handling (grep: no hit).683684**Animations** (complete list, by grep): `.transition(.opacity)` on the welcome view, the palette and the filter bar;685toast `.transition(.move(edge: .bottom).combined(with: .opacity))` with `.animation(.spring(duration: 0.3))`;686`$showFilters.animation()`; `.symbolEffect(.pulse)` on the sync icon. Nothing else: no `withAnimation`, no687`matchedGeometryEffect`, no animated panel open/close (assistant and inspector appear by `if`).688689**Reduced motion**: **not handled.** No `accessibilityReduceMotion`, no `NSWorkspace.accessibilityDisplayShouldReduceMotion`.690691Language: every user-facing string is a French literal in the Swift source. `developmentLanguage: fr`; no string catalog692or `.strings` file is present in `Resources/`.693694### B.4 Navigation and windows [code]695696- Scenes (`SPNotesApp.swift`): main `WindowGroup` (default 1180×760), a second `WindowGroup` keyed by note id697 (980×720) that reuses the same `MainWindow` view, `Settings`, `MenuBarExtra` (off by default; three items: quick note,698 open, quit).699- `MainWindow`: one `NavigationSplitView` with three columns — `SidebarView` (190-320), `NoteListView` (240-460),700 `NoteDetailView`. The navigation model is `LibraryModel.selection: SidebarItem` (`list(SmartList) | section(String) |701 folder(String) | tag(String) | unsynced`) plus `WindowModel.selectedNotes`. The detail column can only show a note702 editor or an empty state: there is no router and no notion of a non-note destination (database, graph, tasks, home,703 search results page). `LibraryModel.selection` lives in the shared `LibraryModel`, so **the sidebar selection is shared704 by every window**, while the note selection is per window.705- Sidebar sections: Bibliothèque (all, recent, favourites, pinned, inbox when not empty, unsynced when not empty),706 Espaces (`notes, documents, projects, research` — the server's `databases` section is not listed), Dossiers707 (`OutlineGroup`), Tags, then archives and trash; `SyncStatusBar` at the bottom.708- Inspector and assistant: **not** the SwiftUI `.inspector` modifier. Both are fixed-width columns (270 and 330) appended709 in an `HStack` inside the detail pane (`NoteDetailView.swift:46-47`), not resizable.710- Sheets: account, atom editors, link editor, history, conflict. Overlays in a `ZStack`: lock screen, welcome, command711 palette, toasts.712- Quick note: `QuickNotePanel`, a floating non-activating `NSPanel` hosting SwiftUI with a plain `TextEditor` (not the note713 editor); first line = title; global hot key ⌃⌥⌘N registered through Carbon `RegisterEventHotKey` (no permission needed),714 on by default.715- Commands: see B.1; shortcuts include ⌘N, ⇧⌘N, ⌥⌘N, ⌘O, ⇧⌘P, ⌘S (snapshot), ⇧⌘I (import), ⌘P, ⌥⌘F, ⌘K, ⌥⌘0-3,716 ⇧⌘7/8/9, ⌘]/[, ⌃⌘↑/↓, ⌥⌘I (inspector), ⇧⌘A (assistant), ⌘R (sync), ⌃⌘L (lock), ⌘+/−.717- Deep links (`AppDelegate.swift:10`): `spnotes://note/<uuid>` (or `/p/`), `spnotes://new?text=…`. Nothing else. No718 universal links (the entitlement has `webcredentials:` only, no `applinks:`).719- Services: one, "Nouvelle note SP Notes avec la sélection" (`NSServices` in `Info.plist`, `newNoteFromSelection`).720- File open: `application(_:open:)` imports file URLs through `Exporter.importFiles`. No document types are declared in721 `Info.plist`, so the Finder does not offer the app for any file type.722- Window tabbing allowed; secure restorable state on; a 900 ms launch guard reopens a main window when restoration723 brought none.724- Quit: `applicationShouldTerminate` flushes every session and checkpoints the database before replying.725726### B.5 AI features [code]727728- Endpoints used: **`POST /api/ai/action`** and **`POST /api/ai/chat`** only (`AssistantPanel.swift:31, 39`).729- UI: one side panel (`AssistantPanel`, 330 pt, ⇧⌘A or the toolbar sparkle, hidden when `preferences.aiEnabled` is off).730 Quick action buttons (a static list of `AIActionKind` values: summarize, rewrite, fix, shorten, …), a Translate menu731 with six languages, a free instruction field (`.custom`), then a question field with a three-way scope picker mapped to732 `AIChatMode`: "Cette note" → `.summarise`, "Toutes mes notes" → `.notes`, "Général" → `.general`.733- Input is the selection or the whole note converted to Markdown (`selectedMarkdown()`), cut to 120 000 characters.734- Output: streamed plain `Text` (Markdown is **not rendered** in the panel), with model name and cost. Actions on the735 result: replace the selection, insert after / into the note (`insertMarkdown`, one undo step), copy, new note, ignore.736 Nothing is written without a click.737- `confirm_expensive` handled both as a thrown error and as a stream event.738- Absent: conversation history (each question is a single turn; `conversationId` is never sent, only a fresh `clientId`),739 model picker (`AIActionRequest.model` / `AIChatRequest.model` never set; `/api/ai/models` has no client), citations740 and sources display, usage view, compare, chat plan, agents, AI over a database, research AI, inline AI in the text741 (no "continue writing" at the caret, no AI block insertion — `aiBlock` is rendered but nothing native creates one).742743### B.6 Account and passkeys [code]744745- Flow: `WelcomeView` (first launch) or `AccountSheet` → `AccountModel.signIn()` → `AuthService.signIn()` →746 `loginOptions` → system passkey sheet (`ASAuthorizationController`) → `loginVerify` → the session cookie value is stored747 by `HTTPClient` in the keychain. Phases: `local` (fully usable without an account), `signedIn`, `expired` (a session748 ended by the server never erases anything). Store meta keys: `account.everSignedIn`, `account.displayName`.749- Keychain (`AppEnvironment.swift:119`): `KeychainTokenStore(configuration:, service: (bundleIdentifier ?? "ai.spboucher.spnotes") + ".session", useDataProtectionKeychain: false)`,750 account = the server origin, **no access group passed**. So the session token lives in the **legacy file-based login751 keychain**, not the data-protection keychain, and the `keychain-access-groups` entitlement is unused. A share extension752 or widget could not read the token as things stand. In-memory store for tests, UI tests and injected dev sessions.753- Entitlements, Release (`Resources/SPNotes.entitlements`): app sandbox, `network.client`,754 `files.user-selected.read-write`, `print`, `com.apple.developer.associated-domains` = `webcredentials:note.spboucher.ai`,755 application identifier `3YM54G49SN.ai.spboucher.spnotes`, team `3YM54G49SN`, keychain access group756 `3YM54G49SN.ai.spboucher.spnotes`. Debug (`SPNotes-Debug.entitlements`): sandbox, network client, user-selected files,757 print — **no associated domain**, so passkeys cannot work in a Debug build; Debug uses a session minted on the dev server.758- Not in the entitlements: app groups, iCloud, push (`aps-environment`), camera, microphone, calendars, `applinks`.759- The server's AASA lists `3YM54G49SN.ai.spboucher.spnotes` (macOS) and `…spnotes.ios` [doc `BACKEND_CONTRACT.md`].760 The Debug bundle id `ai.spboucher.spnotes.debug` is deliberately different so a dev copy never shadows the installed app.761- `WelcomeView.isInstalled` warns when the app does not run from `/Applications/`.762- Device management UI (`AccountSheet`): list of passkeys (label, "synchronisée"), "add a passkey on this Mac"763 (`auth.addPasskey(label: "Mac · SP Notes")`), list of sessions with "Déconnecter" per other session764 (`withFreshSession { revokeSession }`), "confirm with my passkey" when a purge waits (`stepUp`), sign-out with the choice765 to keep or erase the local copy. Rename and delete of a passkey, and "revoke all sessions", have API methods but no UI766 (the passkey row shows label, "synchronisée" and last use only).767- Local lock (`AppLock`): Touch ID or the Mac password, on launch and/or after N minutes; a screen lock, not encryption.768769### B.7 Build, release, tests [code + doc]770771**`project.yml`**772773- Deployment target macOS 15.0; `SWIFT_VERSION` 6.0; `SWIFT_STRICT_CONCURRENCY: complete`; hardened runtime; team `3YM54G49SN`.774- `MARKETING_VERSION` 1.0.2, `CURRENT_PROJECT_VERSION` 3.775- App target `SPNotes`: sources `App`, `Features`, `Components`, `Resources`; product name "SP Notes"; module `SPNotes`;776 bundle id `ai.spboucher.spnotes` (Debug: `ai.spboucher.spnotes.debug`);777 **`SWIFT_DEFAULT_ACTOR_ISOLATION: MainActor`** and `SWIFT_APPROACHABLE_CONCURRENCY: YES` (app target only).778- Release: manual signing, identity "Developer ID Application", profile specifier **"SP Notes Developer ID"**,779 `--timestamp`, whole-module, universal. Debug: ad hoc (`-`), automatic.780- `SPNotesTests` (hosted unit tests, `Tests/AppTests`, bundle id `…spnotes.tests`), `SPNotesUITests` (`Tests/UITests`,781 `…spnotes.uitests`, hardened runtime off).782- Schemes `SPNotes` (build, test = `SPNotesTests`, archive = Release) and `SPNotesUITests`.783- Packages: `../SPNotesCore` (product `SPNotesCore`) and `.` (product `SPNotesEditor`); the editor package pins784 SwiftMath `exact: "1.7.3"` from GitHub — the only third-party dependency.785786**Scripts/**787788| Script | What it does | Needs |789|---|---|---|790| `build.sh generate|debug|core-test|app-test|ui-test|run` | xcodegen, Debug build, `swift test` (editor), hosted tests, UI tests; **`run` uses `open`** | `xcodegen`, Xcode; `LINES_MAX` optional |791| `integration-test.sh [--server]` | hosted tests; with `--server` also the end-to-end sync tests | `--server`: SSH to `M4M64c`; passes `TEST_RUNNER_SPNOTES_IT_SERVER` / `TEST_RUNNER_SPNOTES_IT_TOKEN` |792| `dev-session.sh` | opens the tunnel to the dev backend and mints a session; prints `export SPNOTES_SERVER=… SPNOTES_SESSION_TOKEN=…` | `DEV_NODE` (M4M64c), `DEV_DIR` (`dev/note-native`), `DEV_PORT` (8482) |793| `run-dev.sh [--local] [--shot …]` | launches the Debug build against the dev backend in the background; **uses `pkill -f` on the Debug app path and `open`** | a Debug build; `APP` optional |794| `shot.sh`, `window-shot.swift` | captures the app window to a PNG | — |795| `release.sh` | finds the "Developer ID Application" identity in the keychain, installs `Build/SPNotes_Developer_ID.provisionprofile`, xcodegen, archive Release, copies `dist/SP Notes.app` | the identity; the profile file |796| `verify-release.sh [app]` | checks signature, hardened runtime, timestamp, sandbox, associated domain, no debug entitlement, embedded profile, **no WebKit / JavaScriptCore linked, no HTML / JS / CSS resource**, no secret patterns | — |797| `notarize.sh` | notarizes and staples the app, builds / signs / notarizes / staples the DMG, writes the SHA-256 | `NOTARY_PROFILE` (default `MacLustr-Notarize`) |798| `provision.py`, `asc.py` | registers the bundle id, the Associated Domains capability and the Developer ID profile through the App Store Connect API | `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_KEY_PATH` (falls back to values read from `maclustr-ios-v2/app/scripts/testflight-archive-upload.sh`) |799| `make-icon.sh` | SVG → AppIcon set, light and dark | `rsvg-convert` |800| `check-headers.sh` | fails when a source file lacks the author header | git |801802`verify-release.sh` **fails the release if a web engine is linked or any HTML/JS/CSS file is in the bundle.** Rendering803Mermaid, charts or other content through `WKWebView` breaks this gate; the choice is native renderers or a deliberate804change of that policy.805806`release.sh` mixes `build/` and `Build/` paths (the same directory on a case-insensitive volume).807Distribution: DMGs in `dist/` (1.0.0, 1.0.1, 1.0.2). No auto-update: `SPNotesUpdateFeedURL` is empty; Sparkle 2 is the808stated plan [doc `UPDATES.md`].809810**Tests** [declarations counted; none run]811812| Suite | Count | How |813|---|---|---|814| Editor (`Tests/EditorTests`, SwiftPM) | 30 declared (docs say 31 including the offscreen render) | `swift test` / `Scripts/build.sh core-test` |815| App, hosted (`Tests/AppTests/EndToEndTests.swift`) | 13 (7 without server, 6 with) | `Scripts/integration-test.sh [--server]`; env `SPNOTES_IT_SERVER`, `SPNOTES_IT_TOKEN` |816| UI (`Tests/UITests`) | 2 | `Scripts/build.sh ui-test` |817818Launch arguments honoured by the app: `-SPNotesDataDir`, `-SPNotesInMemory`; DEBUG only: `-SPNotesServer` /819`SPNOTES_SERVER` (loopback hosts only), `SPNOTES_SESSION_TOKEN`, `-SPNotesUITest`, `-SPNotesOffline`, `-SPNotesOpen`,820`-SPNotesRoute` (`assistant | inspector | palette | account`), `-SPNotesNoActivate`.821822**`TEST_REPORT.md` (1.0.2, 2026-11-18) — verified** [doc]: editor codec round trip on all schema types, typing,823commands, undo, remote apply, pasteboard, completion; a 4 000-block document (load 95 ms, 3.3 ms per keystroke,824serialize 32 ms); hosted tests: autosave, crash safety, organisation, local history, exports, two windows on one note,8255 000-note library (lists 2-3 ms, FTS 4-5 ms); with the dev server: the offline scenario end to end, remote change into826an open editor, merge and conflict on two devices, image upload, trash both ways, "Résumer" streamed; release checks and827notarization (Accepted for app and DMG).828829**`TEST_REPORT.md` — NOT verified** [doc]: passkey sign-in in the signed app (Touch ID sheet, domain association);830a real reboot and a physical network cut; **the XCUITests were written and compiled but never executed**; all mouse831interactions (checkbox click, double-click on a table, file drag and drop); window restoration, full screen, multiple832windows on screen; quick note hot key, the Service, `spnotes://` links, the menu bar extra, Quick Look, printing, the833share sheet, the Touch ID lock; assistant actions other than "Résumer" and all questions; server history in the app;834passkey and device lists; a purge pushed to the server; VoiceOver; any other Mac, Intel, macOS 15 or 26 (the x86_64 slice835never ran); Instruments.836837So the passkey sign-in — the only way into sync in a release build — has never been confirmed in the shipped app by the838project's own account.839840### B.8 Absent natively vs the web — confirmed against code841842| Capability | In the macOS code? | Evidence |843|---|---|---|844| Databases (tables, views, properties, rows) | **No.** Database pages show a read-only banner | `NoteSession.swift:37`, `NoteDetailView.swift:90`; rows filtered by the engine; `databases` section not in the sidebar; no API client |845| Graph view, graph API | **No** | no client; no view |846| Backlinks | **No.** The inspector lists *outgoing* links only, computed locally from `document().pageReferences()` (first 12), although its file header says "to and from" | `InspectorPanel.swift:83`; no `backlink` in the app; `PageDetail.backlinks` from `GET /api/pages/{id}` is never requested |847| Tasks view | **No.** Task lists render and toggle inside a note; no cross-note task list | no use of `api.tasks`; no reminder call in the app |848| Reminders | **No UI.** The store table and the engine push exist; the app never creates one | grep `reminder` in App / Features / Components: no hit |849| Inbox triage | **No.** The inbox is a smart list shown when non-empty; no keep / task / archive actions, no undo | `SidebarView.swift:22`; no `triage` / `enqueueOp` in the app |850| Capture (`/api/capture`) | **No** | quick note creates an ordinary page |851| Research (references, papers, experiments, BibTeX) | **No** | "Recherche" is only a page section |852| Semantic / hybrid search | **No.** Local FTS5 only | `api.search` never called |853| AI: model choice, conversations, usage, compare, agents, jobs | **No** | B.5 |854| Dashboard / home | **No** | — |855| Canvas / whiteboard | **No** | — |856| Drawing | **No** native drawing. A PencilKit drawing from iOS is an `image` node + `.pkdrawing` attachment and shows as a picture | data convention in `BACKEND_CONTRACT.md` |857| Voice notes, dictation capture, audio | **No** | no AVFoundation / Speech import; no microphone entitlement |858| PDF viewing in place, PDF annotation | **No.** PDFs are file cards opened in Quick Look | no PDFKit import |859| Mermaid, charts, runnable code, citations, block references, query views | **No** | A.1; shown as unknown-block cards if the web produced them |860| Spotlight indexing | **No** | no CoreSpotlight import |861| Notifications | **No** | no UserNotifications import, no push entitlement |862| App Intents / Shortcuts, widgets, share extension | **No** | no AppIntents / WidgetKit import; no extension target in `project.yml` |863| Handoff / `NSUserActivity` | **No** | grep |864| Universal links | **No** | `webcredentials` only |865| Auto-update | **No** | `UPDATES.md` |866| In-place table editing, image resize, video playback, collapsible details | **No** | B.2 |867| Drag handle per block | **No** (keyboard move ⌃⌘↑/↓ only) | `ARCHITECTURE.md` §5 |868| Real-time collaboration / presence | **No** | no socket; 75 s polling + 2 s debounce |869| Localisation other than French | **No** | B.3 |870| Server-side import/export, settings, audit | **No** | export and import are local (`Exporter.swift`) |871872What it does have that is worth keeping: full offline use with no account, durable autosave, local + server history,873conflict UI, attachments with keep-offline and eviction, six export formats and print, command palette, quick note,874local lock, multi-window with shared sessions.875876### B.9 Code smells and risks for a large upgrade877878**Architecture**8798801. **Three implementations of the editing logic.** Core has `Commands.swift` + `InlineCommands.swift` (744 lines,881 tested by 35 command tests). The macOS editor does not call them: `Editor/EditorCommands.swift` and `NoteTextView.swift`882 re-implement lists, indent, split, merge, marks and links directly on `NSTextStorage`. The iOS app883 (`../SPNotes-iOS/Editor/`, 9 files, 2 237 lines: `AttributedCodec`, `EditorStyler`, `EditorLayoutFragment`,884 `AtomRenderer`, `StructureCommands`, …) is a separate editor that does call Core's commands (grep hits in885 `StructureCommands.swift`, `NoteTextView.swift`, `NoteEditorModel.swift`). Every new block type must therefore be886 implemented in Core, in the macOS editor and in the iOS editor, with three renderers. `Package.swift` of the editor887 declares `platforms: [.macOS(.v15)]` and imports AppKit throughout, so it cannot be shared as it is.8882. **Duplicated schema knowledge in the macOS editor**: `NoteTextView.idTypes` and `idAlphabet` / `newBlockID()`889 (l.344-346) copy `Schema.idTypes` and `BlockID.generate()` because `Schema` is `internal` to Core; `Styler.listTypes` /890 `itemTypes` copy `Schema.lists` / `items`; node type names are string literals everywhere in `Editor/` and `Features/`891 instead of `NodeType.*`. A type added to the server's `ID_TYPES` must be changed in two Swift places.8923. **Atoms are bitmaps** (B.2). This is the largest single constraint on mermaid / chart / pdf / drawing / queryView /893 runnable code.8944. **`verify-release.sh` forbids web engines** (B.7), which removes the cheapest way around item 3.8955. **Navigation cannot express non-note destinations** (B.4), and the sidebar selection is global across windows.8966. **The sync engine has no extension seam** (A.4): one 1 014-line actor, hand-written per kind; unknown op kinds are897 dropped as completed and unknown tombstone kinds are ignored, so a client older than the server loses those silently.8987. **Store schema is at version 1**: the migration path has one step and has never been exercised on shipped data.899 A newer file is refused by an older build, so a downgrade after the upgrade means the old app will not open the store900 (`AppEnvironment.swift:130-131` then falls back to an **in-memory store** and records `storeOpenError`).901 **`storeOpenError` is read by no view** (grep: declared and assigned only; the failure goes to `NSLog`). The user would902 see an empty library, and anything typed would be lost at quit. This path needs a blocking error screen before any903 schema migration ships.9048. **Whole-document serialization on every autosave** and whole-block merge granularity: fine for prose, costly and905 conflict-prone for large structured blocks (a big table or a canvas is one block and one JSON value).9069. **No design system** (B.3): a redesign starts from literals in about 20 view files, plus a separate set of colours and907 metrics inside the editor package.908909**Concurrency (Swift 6, strict)**91091110. The app target compiles with `SWIFT_DEFAULT_ACTOR_ISOLATION: MainActor`; the editor package does not and is annotated912 by hand (`@MainActor` on `DocumentCodec`, `Styler`, `AtomRenderer`, …). Code moved between the two changes isolation913 silently. `Editor/` types reference `SPNotesDocument` value types only, which keeps this manageable.91411. Escape hatches, counted over App / Features / Components / Editor: `nonisolated(unsafe)` 15, `@unchecked Sendable` 6915 (`ParaStyle`, `MarkSet`, `ParaDecoration`, `NodeBox`, `AtomAttachment`, `KeyAllocator`), `MainActor.assumeIsolated` 9.916 They cluster where AppKit calls back from `nonisolated` requirements: the four `NSTextAttachment` overrides917 (`AtomAttachment.swift:54-86`), `textStorage(_:didProcessEditing:)` and `textLayoutManager(_:textLayoutFragmentFor:)`918 (`NoteTextView.swift:202, 224`), the Quick Look data source, the Carbon hot key. `assumeIsolated` traps if TextKit919 ever calls these off the main thread (background layout, printing, or a view provider on another queue). Moving to920 view-based attachments adds more of these callbacks.92112. `AppDelegate.environment` is a static mutable set from `SPNotesApp.init`; `MainWindowOpener.open` and922 `OpenNoteWindow.open` are static closures captured from whichever window appeared last; `ImageCache.shared` and923 `QuickLook.shared` are singletons holding an environment-dependent state. Fragile with several windows and in tests.92413. `GlobalHotKey.actions` is a `nonisolated(unsafe)` static dictionary mutated from `init` and from a925 `DispatchQueue.main.async` in `deinit`.92614. Unstructured tasks: 110 `Task {` occurrences, most fire-and-forget from button closures with no cancellation or927 ordering; `NoteSession.saveNow` handles re-entrancy with a 30 ms sleep-and-retry (`NoteSession.swift:83-85`).92815. `NoteSession.storeChanged()` runs on store change events while `saveNow` may be in flight; correctness rests on929 `lastSavedContent` comparisons and the `isApplying` flag rather than on a serial queue.930931**Error handling and robustness**93293316. 99 `try?` in the app code: store and network failures in the library, inspector, account and settings paths are934 dropped without a message (e.g. `loadSecurity()` shows empty lists on any error).93517. `AppEnvironment.init` uses `try! NotesStore.inMemory()` as the fallback when the on-disk store cannot be opened.93618. `ASPresentationAnchorFallback.window` creates a bare `NSWindow` as the passkey anchor when no window is visible.93719. `Scripts/run-dev.sh` uses `pkill -f` (it targets the local Debug app path on the laptop; still worth knowing given the938 standing rule against `pkill -f` on shared nodes).939940**Code shape**94194220. No file is large (the biggest are `NoteTextView.swift` 642 and `EditorCommands.swift` 341), but the code is943 **horizontally dense**: 208 lines longer than 200 characters, the longest 769; many functions are a single line944 with several statements separated by `;`. Worst files: `NoteDetailView.swift` (19 such lines), `AssistantPanel.swift`945 (17), `AccountSheet.swift` (15), `SyntaxHighlighter.swift` (15), `NoteTextView.swift` (13). Diffs and reviews on these946 are harder than the line counts suggest.94721. `NoteDetailView.swift` holds five views (pane, banner, format bar, status bar, plus an extension on `NoteTextView`);948 `AppDelegate.swift` holds six types; `SyncMonitor.swift` also holds `ToastCenter` and `ImageCache`.94922. Duplicates inside the app: `activateAtomBeforeCaret()` (`Completion.swift:38`) and `activateInsertedAtom()`950 (`NoteDetailView.swift:281`) are the same function; the "Untitled → Sans titre" rule is repeated in at least six951 places; the command list exists in three places (B.2).95223. `ParaDecoration.isEqual` (l.91) ignores `struck`, and `hash` uses only `markerX` and `quoteBars.count`.95324. Dead or odd code noticed: `insertBlockAtom` has `let path = style.isCode ? style.path : style.path`;954 `TableEditor` ends with `.disabled(!editable && false)`; `textStorage(_:didProcessEditing:)` contains an empty `if`955 body where the "last paragraph is terminated" invariant was meant to be enforced.95625. Tests do not cover the UI layer: 2 UI tests, never executed; no snapshot tests of the SwiftUI chrome (only the editor957 has an offscreen render).958959**Product and ops**96096126. Min OS macOS 15 while development and all testing happened on macOS 27 only; iOS 18 for Core.96227. One language, hard-coded.96328. No telemetry, crash reporting or structured logging: grep for Sentry, Crashlytics, MetricKit, `OSLog`, `Logger(`964 returns nothing; the only log call seen is one `NSLog`. Fine for privacy, but there is no field signal after a risky965 migration.96629. Documentation drift inside Core (A.4) and a stale hard-coded user agent in `Scripts/dev-session.sh`967 (`SPNotes/1.0.0`).968969---970971## Appendix — things I did not verify972973- No build, no test run, no app launch. All performance numbers and "green" statements are the projects' own.974- Request / response shapes of the server routes that have no native client (only the route tree was listed).975- `HTMLExport.swift` default branch body; `MarkdownImport.swift` in full; `Commands.swift` in full (signatures only);976 `NotesStore+*.swift` bodies (schema and docs read, method bodies spot-checked); `SyncEngine.swift` l.179-560 and977 l.740-1014 (outlined, with `runQueue`, `pushReminders` and `pull` read in full).978- In the app: the tails of lines longer than 230 characters were cut in my reading (the three that mattered were re-read:979 `AppEnvironment.swift:119`, `AccountSheet.swift:60`, `InspectorPanel.swift:83`). `InspectorPanel`, `NoteListView`, `Exporter`, `SettingsView`,980 `HistoryAndConflicts`, `CommandPalette`, `AttachmentService`, `LibraryModel` were read as outlines (declarations and981 key lines), not line by line.982- `docs/AUDIT.md`, `SECURITY.md`, `INSTALL.md` of the macOS app were not read. `FEATURE_MATRIX.md` was skipped as you983 have it.984- The iOS project was only listed and grepped, to establish the editor duplication.985