Repository Public
1<!--2SP Notes Core3File: docs/API_CLIENT.md4Description: Public API of the SPNotesAPI module (network layer of the native SP Notes apps), with short examples.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->89# SPNotesAPI — the network layer1011`SPNotesAPI` is the only module that talks to the backend (`note-spboucher-ai`, contract in12`docs/reference/BACKEND_CONTRACT.md`). It depends on Foundation, Security and AuthenticationServices only, and on13none of the other modules: note `content` and `properties` travel as `RawJSON` (serialised JSON bytes) and are interpreted by14`SPNotesDocument`.1516| Type | Role |17|---|---|18| `APIConfiguration` | base URL, `Origin`, User-Agent, timeouts, cookie names |19| `SessionTokenStore`, `KeychainTokenStore`, `InMemoryTokenStore` | where the session token lives |20| `HTTPClient` (actor) | transport: cookies by hand, headers, uploads, downloads, event streams, session events |21| `APIError` | every failure, typed |22| `NotesAPI` | one method per route |23| `PasskeyCeremony`, `PasskeyAuthorizing`, `SystemPasskeyAuthorizer`, `AuthService` | passkeys and sign-in flows |24| `SSEParser`, `AIEvent` | server-sent events of the AI routes |2526## 1. Setting up2728```swift29import SPNotesAPI3031let configuration = APIConfiguration.production(appVersion: "1.0.0") // https://note.spboucher.ai32let tokens = KeychainTokenStore(configuration: configuration, accessGroup: "3YM54G49SN.ai.spboucher.spnotes.shared")33let client = HTTPClient(configuration: configuration, tokenStore: tokens)34let api = NotesAPI(client: client)35```3637- `APIConfiguration(baseURL:userAgent:requestTimeout:resourceTimeout:streamIdleTimeout:sessionCookieName:ceremonyCookieName:)`;38 `origin` is derived from the base URL (`scheme://host[:port]`, default ports omitted); `relyingPartyID` is its host.39- `APIConfiguration.userAgent(appVersion:device:osVersion:)` builds `SPNotes/1.0.0 (iPhone; iOS 18.1) native`40 (`device` defaults to `.current`: `iPhone`, `iPad` or `Macintosh`, detected without UIKit).41- Test server: `APIConfiguration(baseURL: URL(string: "http://localhost:8482")!)`.4243### Token storage4445```swift46public protocol SessionTokenStore: Sendable {47 func load() -> String?48 func save(_ token: String) throws49 func clear() throws50}51```5253`KeychainTokenStore(service:account:accessGroup:useDataProtectionKeychain:)` stores a generic password with54`kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` and `kSecAttrSynchronizable = false`. The account defaults to the origin55(`init(configuration:…)`), so a test server never shares a token with production. On macOS the data-protection keychain is used56(needs a signed app with a keychain access group); pass `useDataProtectionKeychain: false` in unsigned tools.57`InMemoryTokenStore(token:)` is for tests and previews. The token is never logged; `APIError` descriptions never contain request data.5859## 2. Transport rules implemented by `HTTPClient`6061- One dedicated **ephemeral** `URLSession`: no cookie storage (`httpShouldSetCookies = false`, accept policy `never`), no URL cache,62 no credential storage, TLS ≥ 1.2. Redirects are refused (the cookie never follows one). An injected63 `URLSessionConfiguration` (tests: `protocolClasses`) is hardened the same way.64- `Cookie: __Host-note_session=<token>` is written by hand from the token store.65- `Set-Cookie: __Host-note_session=…` on **any** answer (sign-in, step-up rotation) replaces the token and saves it.66 A cleared cookie (`Max-Age=0`, empty value, past `Expires`) or a `401` answering a request that carried the *current* token67 clears the store and emits `SessionEvent.signedOut` **exactly once**. (A late 401 for a token that has since been rotated is ignored.)68- The WebAuthn ceremony cookie `__Host-note_wa` is captured from the `options` call (`HTTPRequest.Ceremony.begin(key)`) and sent69 only on the matching `verify` call (`.complete(key)`), once.70- `Origin` and `Idempotency-Key` only on POST / PATCH / PUT / DELETE; `x-request-id` on every request (generated when absent);71 `Accept: application/json`; the configured `User-Agent`.72- JSON bodies are encoded with sorted keys (same request → same bytes); dates are `2026-11-18T19:07:04.808Z`.73 Answers are decoded with ISO 8601 dates with or without fractional seconds (and the PostgreSQL form `2026-11-18 14:08:56.283-05`74 that `/api/search` returns).7576```swift77// Session events (each call returns an independent stream)78Task {79 for await event in await client.sessionEvents() {80 switch event {81 case .signedOut(let reason): showSignIn(reason) // .unauthorized | .cookieCleared | .local82 case .signedIn, .tokenRotated: break83 }84 }85}86let signedIn = await client.hasSession87await client.clearSession() // local sign-out, no network88await client.setSessionToken(devToken) // development token of the test server89```9091Low-level calls, when a route has no typed method yet:9293```swift94let response = try await client.send(.get("/api/health"))95let page: Page = try await client.decode(Page.self, .json(.post, "/api/pages", body: PageDraft(title: "Hello"), idempotencyKey: key))96response.status; response.header("x-request-id"); response.isExisting; response.isIdempotentReplay97```9899`HTTPClient` also exposes `upload(_:fromFile:progress:)`, `download(_:to:progress:)` and `openStream(_:)`.100101### Retries (2.0)102103`HTTPClient.send` never retried in 1.x and still does not unless asked: a request carries an optional `retry: RetryPolicy`.104105```swift106let health = try await client.send(HTTPRequest.get("/api/health/knowledge").retrying()) // GET: safe by nature107let created = try await client.send(try HTTPRequest.json(.post, "/api/tasks", body: draft).retrying()) // gets an Idempotency-Key108```109110- A policy is honoured only when the request `isSafeToRetry`: a GET, or any request carrying an `Idempotency-Key` (the server runs111 it at most once per key). WebAuthn ceremony calls are never retried (their cookie is single-use). On any other request the112 policy is ignored: exactly one attempt, as before.113- `retrying(_ policy: = .standard, addingKey: = true)` sets the policy and gives a mutating request a fresh key when it has none114 (`HTTPRequest.newIdempotencyKey()`, 32 hex characters). The same key and the same body are sent at every attempt; the request115 id changes.116- Retried failures are those for which `APIError.isRetryable` is true (offline, transport, timeout, 408, 429, 5xx,117 `409 in_progress`). Never 401 (the session ended), other 4xx, `503 not_configured | no_model`.118- `RetryPolicy(maxAttempts:baseDelay:multiplier:maxDelay:jitter:)`: `.standard` = 3 attempts, 0.4 s then 0.8 s; `.patient` =119 5 attempts from 1 s, at most 30 s; `.none`. A `Retry-After` header (seconds) longer than the computed delay replaces it, capped120 by `maxDelay`. Cancelling the task during the wait throws `APIError.cancelled`.121- Not retried: `upload`, `download`, `openStream` (the sync engine has its own policy for transfers). The existing `NotesAPI`122 methods are unchanged (no policy): the engine keeps deciding when to send again.123124## 3. Errors125126```swift127public enum APIError: Error, Sendable, Equatable {128 case offline // no connectivity129 case transport(URLError.Code) // DNS, TLS, connection lost…130 case timeout131 case cancelled132 case invalidResponse133 case decoding(String) // 2xx with an unexpected body134 case file(String) // local file problem (upload source, download destination)135 case http(status: Int, code: String?, message: String, body: Data)136 case conflict(server: PageConflict, message: String) // 409 conflict with the server copy137 case confirmExpensive(plan: RawJSON, message: String) // 409 confirm_expensive138}139```140141Accessors: `status`, `code`, `message`, `serverCopy`, `plan`. Classification: `isConflict`, `needsReauth` (403 `reauth_required`),142`isUnauthenticated` (401), `isRateLimited`, `isNotFound`, `isOffline`, `isCancelled`, and `isRetryable` (offline, transport,143timeout, 5xx, 408, 429 and 409 `in_progress`; **not** 503 `not_configured` / `no_model`). Stable codes: `APIError.Code.*`.144145```swift146do {147 let result = try await api.patchPage(id: id, PagePatch(title: title, content: content, baseVersion: localVersion))148 localVersion = result.version149} catch let error as APIError {150 if case .conflict(let server, _) = error {151 // server.version, server.title, server.content (RawJSON), server.properties (RawJSON), server.updatedAt152 try await api.resolveConflict(pageID: id, choice: .both, serverVersion: server.version, mine: ConflictMine(title: title, content: content))153 } else if error.needsReauth {154 try await auth.stepUp()155 } else if error.isRetryable {156 // keep the operation in the outbox with the same idempotency key157 }158}159```160161## 4. Endpoints (`NotesAPI`)162163Identifiers are the server's lower-case UUID strings: `NotesAPI.newID()`. `NotesAPI.newIdempotencyKey()` makes a key to store with164a pending operation and to send again unchanged on a retry (every mutating method that the outbox may replay takes `idempotencyKey:`).165166### Change feed167168```swift169func sync(since: Int64, limit: Int? = nil) async throws -> SyncPage170171var cursor: Int64 = storedCursor // 0 = full copy172repeat {173 let page = try await api.sync(since: cursor, limit: 200)174 if page.reset { cursor = 0; wipeLocalCopy(); continue }175 apply(page.pages, page.attachments, page.tombstones, page.tags)176 cursor = page.cursor177 if !page.more { break }178} while true179```180181`SyncPage`: `cursor`, `head`, `more`, `reset`, `serverTime`, `workspace {id, name}`, `user {displayName}`, `pages: [Page]`,182`attachments: [SyncAttachment]`, `tombstones: [Tombstone]`, `tags: [TagColor]`. `limit` applies to each list separately.183The `reset` answer is abbreviated (`cursor: 0`, no `user`).184185`Page`: `id, parentId, databaseId, type, section, title, icon, cover, content: RawJSON, properties: RawJSON, position, pinned,186archived, version, wordCount, createdAt, updatedAt, lastOpenedAt, deletedAt, inboxAt, captureKind, rev, tags` (`tags` only in the187feed; `plainText`, `workspaceId` only in the page routes).188189### Pages190191```swift192func createPage(_ draft: PageDraft = PageDraft(), idempotencyKey: String? = nil) async throws -> Created<Page> // .existing = x-existing: 1193func page(id: String, open: Bool = false) async throws -> PageDetail // page + breadcrumb + backlinks194func pageHead(id: String) async throws -> PageHead // id, version, updatedAt, deletedAt195func patchPage(id: String, _ patch: PagePatch, idempotencyKey: String? = nil) async throws -> PagePatchResult196func resolveConflict(pageID: String, choice: ConflictChoice, serverVersion: Int, mine: ConflictMine, idempotencyKey: String? = nil) async throws -> ResolvedPage197func trashPage(id: String, idempotencyKey: String? = nil) async throws -> TrashResult198func purgePage(id: String) async throws -> OKResult // fresh verification199func emptyTrash(olderThanDays: Int? = nil) async throws -> PurgeResult // fresh verification200func restorePage(id: String, idempotencyKey: String? = nil) async throws -> OKResult201func duplicatePage(id: String, idempotencyKey: String? = nil) async throws -> Page202func pageVersions(pageID: String) async throws -> [PageVersionSummary]203func pageVersion(pageID: String, version: Int) async throws -> PageVersionSnapshot204func restorePageVersion(pageID: String, version: Int, idempotencyKey: String? = nil) async throws -> VersionRestoreResult205func pageTags(pageID: String) async throws -> [String]206func setPageTags(pageID: String, tags: [String], idempotencyKey: String? = nil) async throws -> [String]207func tags() async throws -> [TagSummary]208```209210`PagePatch` — every field optional; only what is set is sent. `parentId`, `icon` and `cover` are `PatchValue<String>?`:211`nil` = absent, `.null` = JSON `null`, `.value(x)` = the value.212213```swift214PagePatch(title: "New title", baseVersion: 4) // {"baseVersion":4,"title":"New title"}215PagePatch(parentId: .null) // {"parentId":null} → move to the root216PagePatch(icon: .value("📝"), pinned: true) // not version-guarded217PagePatch(content: RawJSON(data: documentJSON), versionReason: "manual", baseVersion: 4)218```219220```swift221let id = NotesAPI.newID()222let created = try await api.createPage(PageDraft(id: id, title: "Offline note", content: RawJSON(data: json)))223if created.existing { /* a retry: the stored page came back untouched */ }224```225226### Attachments227228```swift229func uploadAttachment(fileURL: URL, id: String? = nil, pageID: String? = nil, filename: String? = nil, mimeType: String? = nil,230 progress: TransferProgressHandler? = nil) async throws -> Created<UploadedAttachment>231func attachments(pageID: String? = nil) async throws -> [AttachmentInfo]232func deleteAttachment(id: String, idempotencyKey: String? = nil) async throws -> OKResult233func downloadFile(id: String, to destination: URL, progress: TransferProgressHandler? = nil) async throws -> DownloadedFile234static func filePath(id: String) -> String // "/api/files/<id>"235static func fileID(fromSource: String) -> String?236```237238Uploads build the multipart body in a temporary file (`MultipartForm`, fields `id`, `pageId`, `file`) and send it with239`URLSession.upload(for:fromFile:)`; downloads go straight to disk. Nothing is held in memory, both report240`TransferProgress(completedBytes:totalBytes:)` (`fraction`) on a background queue, and both stop when the calling task is cancelled.241242```swift243let upload = Task {244 try await api.uploadAttachment(fileURL: movieURL, id: attachmentID, pageID: pageID) { progress in245 Task { @MainActor in bar.value = progress.fraction ?? 0 }246 }247}248upload.cancel() // → APIError.cancelled249let file = try await api.downloadFile(id: attachmentID, to: cacheURL)250```251252### Authentication253254```swift255func loginOptions() async throws -> PasskeyRequestOptions256func loginVerify(_ credential: PasskeyAssertionCredential) async throws -> LoginResult257func reauthOptions() async throws -> PasskeyRequestOptions258func reauthVerify(_ credential: PasskeyAssertionCredential) async throws -> ReauthResult259func authState() async throws -> AuthState260func logout() async throws -> OKResult261func sessions() async throws -> [SessionInfo]262func revokeSession(id: String) async throws -> OKResult // fresh verification263func revokeAllSessions(includeCurrent: Bool = false) async throws -> RevokeSessionsResult // fresh verification264func passkeys() async throws -> [PasskeyInfo]265func passkeyRegistrationOptions() async throws -> PasskeyCreationOptions // fresh verification266func passkeyRegistrationVerify(_ credential: PasskeyRegistrationCredential, label: String? = nil) async throws -> PasskeyAdded267func renamePasskey(id: String, label: String) async throws268func deletePasskey(id: String) async throws269```270271Apps normally use `AuthService` (§5) instead of the four ceremony calls.272273### AI (server-sent events)274275```swift276func aiAction(_ request: AIActionRequest) async throws -> AsyncThrowingStream<AIEvent, Error>277func aiChat(_ request: AIChatRequest) async throws -> AsyncThrowingStream<AIEvent, Error>278279public enum AIEvent { case meta(AIMeta), text(String), done(AIDone), error(AIStreamError), needsConfirmation(AIConfirmation), other(type: String, raw: RawJSON) }280```281282Errors raised **before** the stream starts are thrown by the call itself: `APIError.confirmExpensive(plan:message:)`,283`503 not_configured | no_model`, `400`. Provider failures during the stream arrive as `.error` events. The stream ends at284`data: [DONE]`. Cancelling the consuming task (or dropping the stream) closes the connection.285286```swift287let generation = Task {288 do {289 for try await event in try await api.aiAction(AIActionRequest(action: .summarize, text: selection)) {290 switch event {291 case .meta(let meta): model = meta.model292 case .text(let delta): preview += delta293 case .done(let done): cost = done.costUsd294 case .error(let failure): show(failure.message, retry: failure.retryable)295 case .needsConfirmation(let c): ask(c.plan) // chat only296 case .other: break297 }298 }299 } catch let error as APIError {300 if case .confirmExpensive(let plan, let message) = error { askThenResend(plan, message) } // resend with confirmExpensive: true301 }302}303generation.cancel() // stops the request and the generation304```305306### Search, tasks, inbox, capture, health307308```swift309func search(_ query: SearchQuery) async throws -> [SearchHit] // SearchQuery("text", mode: .quick | .hybrid, limit:, semantic:, section:, since:, until:, includeArchived:)310func tasks(includeDone: Bool = false) async throws -> [TaskItem]311func createTask(_ draft: TaskDraft, idempotencyKey: String? = nil) async throws -> TaskItem312func updateTask(_ patch: TaskPatch, idempotencyKey: String? = nil) async throws -> TaskItem // dueAt / project / pageId: PatchValue (.null clears)313func deleteTask(id: String, idempotencyKey: String? = nil) async throws -> OKResult314func inbox() async throws -> [InboxItem]315func triageInboxItem(id: String, _ action: InboxAction, idempotencyKey: String? = nil) async throws -> TriageResult316func undoInboxAction(actionID: String) async throws -> UndoResult317func capture(_ request: CaptureRequest, idempotencyKey: String? = nil) async throws -> CaptureResult318func health() async throws -> Health319```320321```swift322// A reminder = a task with a page and a date. Priorities are low | medium | high.323let reminder = try await api.createTask(TaskDraft(title: "Call back", dueAt: date, priority: .high, pageId: pageID))324try await api.updateTask(TaskPatch(id: reminder.id, dueAt: .null, status: .done))325let captured = try await api.capture(CaptureRequest(kind: .link, url: "https://example.com"), idempotencyKey: storedKey)326try await api.triageInboxItem(id: captured.id, .keep(section: .notes))327```328329## 5. Passkeys330331`PasskeyCeremony` holds the pure JSON work (no system objects needed, fully unit-tested):332333```swift334static func decodeRequestOptions(_ json: Data) throws -> PasskeyRequestOptions // accepts {options: …} or the bare object335static func decodeCreationOptions(_ json: Data) throws -> PasskeyCreationOptions336static func assertionCredential(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) -> PasskeyAssertionCredential337static func registrationCredential(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> PasskeyRegistrationCredential338static func assertionVerifyBody(_ credential: PasskeyAssertionCredential) throws -> Data // {"response":{…}}339static func registrationVerifyBody(_ credential: PasskeyRegistrationCredential, label: String?) throws -> Data340static func assertionCredential(from: ASAuthorizationPlatformPublicKeyCredentialAssertion) -> PasskeyAssertionCredential341static func registrationCredential(from: ASAuthorizationPlatformPublicKeyCredentialRegistration) throws -> PasskeyRegistrationCredential342```343344Binary fields are base64url without padding (`Base64URL.encode` / `.decode`, the decoder tolerates padding and plain base64);345`clientExtensionResults` is `{}`, `authenticatorAttachment` is `"platform"`, registration `transports` is `["internal","hybrid"]`.346347The device half is a protocol, so tests and previews can replace it:348349```swift350@MainActor public protocol PasskeyAuthorizing: AnyObject, Sendable {351 func assertion(for options: PasskeyRequestOptions) async throws -> PasskeyAssertionCredential352 func registration(for options: PasskeyCreationOptions) async throws -> PasskeyRegistrationCredential353}354```355356`SystemPasskeyAuthorizer(fallbackRelyingParty:preferImmediatelyAvailableCredentials:anchor:)` runs `ASAuthorizationController` for357platform passkeys (relying party from the options, user verification required, `allowedCredentials` / `excludedCredentials` when358provided). It throws `PasskeyError`: `.cancelled`, `.noCredentials`, `.alreadyRegistered`, `.notInteractive`, `.inProgress`,359`.notAssociated`, `.invalidOptions`, `.failed(code:message:)`.360361```swift362let authorizer = SystemPasskeyAuthorizer(fallbackRelyingParty: configuration.relyingPartyID) { window } // ASPresentationAnchor363let auth = AuthService(api: api, authorizer: authorizer)364365try await auth.signIn() // options → system sheet → verify → token stored366try await auth.stepUp() // fresh for 5 minutes, token rotated367try await auth.addPasskey(label: "iPhone") // steps up by itself when the server asks (stepUpIfNeeded: true)368let purged = try await auth.withFreshSession { try await api.purgePage(id: id) } // step-up + one retry on reauth_required369await auth.signOut() // server logout (best effort) + token forgotten370let signedIn = await auth.isSignedIn371```372373The apps need the associated-domains entitlement `webcredentials:note.spboucher.ai`.374375## 6. Server-sent events376377```swift378var parser = SSEParser()379for event in parser.feed(chunk) { // any chunking: mid UTF-8 sequence, between \r and \n380 if event.isDone { break } // data: [DONE]381 handle(event.data) // also event.event, event.id382}383let tail = parser.finish() // flushes an unterminated last event384```385386## 7. Tests387388```sh389cd SPNotesCore390SPN_ONLY=API swift build --scratch-path .build-api && SPN_ONLY=API swift test --scratch-path .build-api391```392393Unit tests use a `URLProtocol` stub (`Tests/SPNotesAPITests/TestSupport.swift`). The live tests (`LiveBackendTests`) only run when394`SPN_LIVE_URL` and `SPN_LIVE_TOKEN` are set, refuse any `*.spboucher.ai` host, and clean up what they create:395396```sh397ssh -f -N -L 8482:localhost:8482 M4M64c398TOKEN=$(ssh M4M64c 'bash -lc "cd ~/dev/note-native && set -a && . ./.env && set +a && node_modules/.bin/tsx scripts/dev-session.ts"')399SPN_LIVE_URL=http://localhost:8482 SPN_LIVE_TOKEN=$TOKEN SPN_ONLY=API swift test --scratch-path .build-api400# optional: SPN_LIVE_TOKEN_DISPOSABLE / SPN_LIVE_TOKEN_DISPOSABLE2 = two more tokens (one is revoked, one logs out)401```402403A development token is "fresh" for 5 minutes: within that window the purge and revocation paths run for real, afterwards the tests404check the typed `reauth_required` error instead.405406## 8. Differences observed between the contract and the test server (2026-11-18)407408- `GET /api/sync` with a cursor ahead of the server answers `{reset: true, cursor: 0, more: true, …}` **without `user`**.409 `limit` bounds each list (pages, attachments, tombstones) separately. A non-numeric or negative `since` → `400 bad_cursor`.410- `GET /api/search?mode=quick` returns `updatedAt` in PostgreSQL text form (`2026-11-18 14:08:56.283-05`), not ISO 8601.411- Page rows of `POST/GET /api/pages…` carry `workspaceId`, `plainText`, `tsv` and **no `tags`** (the feed has them).412- `POST /api/pages/<id>?action=duplicate` answers `200` (not 201).413- Task `priority` is `low | medium | high` (`400` otherwise); task rows also carry `workspaceId`, `deletedAt`; the list adds414 `pageTitle`, `pageIcon`.415- `POST /api/inbox/<id>` also returns `created`; `POST /api/inbox/undo` returns `{ok, already}`; triage actions are416 `keep | task | database | reference | archive | trash`.417- `DELETE /api/auth/sessions/<id>` needs a fresh verification (`403 reauth_required`), like the global revocation.418- Idempotency: a replayed answer has `idempotent-replay: true` but **not** `x-existing`; a key reused with a *different body* on419 the same method and path is replayed as well (422 `idempotency_mismatch` only when the method or the path differs).420- Extra error codes: `bad_request` (400), `challenge_missing` (400), `no_instruction` / `bad_language` (400, AI action),421 `last_passkey` (409), `bad_cursor` (400). `not_enrolled` is a 409. Validation errors are `400` without a code.422 A malformed UUID in a path (`/api/pages/not-a-uuid`, `DELETE /api/tasks?id=`) answers `500`.423- `GET /api/health` is public and does not echo `x-request-id`; it also returns `pgvector` and `time`.424- `GET /api/tags` reports `pages: 0` for tags carried by live pages.425- `DELETE /api/attachments?id=` is a soft delete: `/api/files/<id>` keeps serving the bytes. Purging a page leaves its attachments426 alive with `pageId: null` (no tombstone).427428## 9. SPNotesCore 2.0 — the 3.0 backend (API-NEXT) and the 2.x parity routes429430Everything below is additive: the 1.x methods keep their signatures. Every DTO is `Codable`, tolerant of unknown fields, and431decoded in a test from a real answer of the scratch backend (`Tests/SPNotesAPITests/Fixtures/next/<group>/`, recorded by432`Scripts/record-next-fixtures.sh` — scenarios in `Scripts/recorders/*.py`, library `Scripts/spn_recorder.py`), except the433AI-workstream answers, transcribed from `API-NEXT-AI.md` (`ai-doc/`, `ai-doc-parity/`, each with a README saying so).434435### 9.1 Meta, feed, tasks, canvas (`NextCoreModels.swift`, `NotesAPI+NextCore.swift`)436437```swift438func meta() async throws -> ServerMeta // 404 on a 2.x server → .legacy (api 2, no feature); ServerFeature.*439func sync(since:limit:kinds: [String]) async throws -> SyncPage // SyncPage.entities: [kind: [SyncEntityRow]]; SyncKind.all440func tasks(includeDone:pageId:since:) async throws -> [TaskItem]441func createTaskIdempotent(_ draft: TaskDraft) async throws -> Created<TaskItem> // TaskDraft.id / blockId / status / due442func task(id:) ; func updateTask(id:_ TaskChanges, idempotencyKey:) ; func removeTask(id:) -> TaskDeleteResult443func canvas(pageID:) -> CanvasEnvelope ; func saveCanvas(pageID:data:baseVersion:) -> CanvasSaveResult // 409 → error.canvasConflict (CanvasServerCopy)444```445446A cursor is only valid for the set of kinds it was obtained with (the engine handles it, `SYNC_ENGINE.md` §7.2).447`PageType.canvas`, `TaskStatus.doing`, `TaskItem.blockId / deletedAt / rev` are new.448449### 9.2 Knowledge graph, journal, time machine, health, brief, living blocks, zoom450451`graph(_ GraphQuery)`, `legacyGraph`, `createRelation / relations / relation / updateRelation / deleteRelation`,452`concepts / createConcept / concept / updateConcept / patchConcepts / deleteConcept`, `graphInsights / runGraphInsights /453decideInsight`; `events(_ JournalQuery) -> EventPage`, `timeMachine(pageID: | projectID:, at:)`, `restoreHistoryEntry`;454`knowledgeHealth`, `brief`, `summarizeBrief` (paid), `query(_ LiveQuery)`, `pageZoom(pageID:level:)`, `pageSynopsis`,455`regeneratePageSynopsis` (paid). String-constant namespaces (`GraphView`, `RelationType`, `EventKind`, `LiveQuerySource`…)456instead of closed enums: an unknown value never fails decoding.457458### 9.3 Files: ranges and resumable downloads (`NotesAPI+Files.swift`)459460```swift461func fileRange(id:range: ByteRange, ifRange:) async throws -> FileRange // 206 / 200 / 416 (returned, not thrown)462func downloadFile(id:to:resumingFrom partial: URL, etag:verifyChecksum:progress:) async throws -> ResumedDownload463```464465The resumable download keeps the partial file and its ETag (sidecar), sends `Range: bytes=<size>-` + `If-Range`, appends on466206, starts over on 200 (changed file), handles 416, and checks the ETag (sha256 of the content) at the end.467468### 9.4 AI (`AICatalogModels.swift`, `NotesAPI+AINext.swift`, `AudioModels.swift`)469470`aiModelCatalog(_ AIModelQuery) -> AIModelCatalog` (creator, route, logo, prices, capabilities, availability),471`AIChatRequest.scope / projectId / selection / selectionBlockId`, `AIMeta.sources / scope / scopePages`, `AIDone.sources /472invalidCitations / uncited` (`AISourceRef.blockId / blockIds / anchor / quote`), `aiAction(_ AIActionCall)` for the 3.0 action473ids (`AIActionID`) with `AIEvent.linkSuggestions`, `transcribeAudio / audioTranscription`, `databaseAIConfig /474setDatabaseAIConfig / runDatabaseAI / databaseAIRuns`.475476### 9.5 Parity with the web (2.x routes without a native client until now)477478Databases (`databases, database, updateDatabase, duplicateDatabase, databaseTemplates, applyDatabaseTemplate`, properties,479views, rows — single and bulk —, `queryDatabase`, CSV), search (`SearchQuery.kinds / group`, `SearchQuery.keywords`, extra hit480fields, `duplicatePages`, `searchIndexState`), graph links (`backlinks`, `graphNeighbors`, `linkSuggestions`,481`decideLinkSuggestion`), inbox (`inboxCount`, `capture(_ CaptureDraft)`, `inboxSuggestions`, `applyInboxSuggestions`), research482(references, extracts, DOI, BibTeX, experiments, research tasks, overview, LaTeX export), AI conversations / usage / plans,483agents (catalogue, run, execution, approve / reject / undo proposals), dashboard, settings, audit log, page lists, trash purge.484485### 9.6 Errors (API-NEXT §5)486487No case was added to `APIError`. Constants: `APIError.NextCode`, `APIError.AICode`, `ParityCode`. Accessors: `canvasConflict`,488`detail(_:)`, `detailString(_:)`, `isNotImplemented`, `isBadRequest`, `existingRelation`, `existingConcept`, `badNodeField`,489`isDerivedEdge`, `unknownPageIDs`, `validKinds`, `isRouteMissing` (501, or the HTML 404 / 405 of a server without the route),490`isAIUnavailable`, `isNotInInbox`, `isRowDeleted`, `isIDTaken`, `needsCostConfirmation`, `runningExecutionID`.491Note: `isRetryable` is true for a 501 — test `isRouteMissing` first.492493### 9.7 Live tests against the scratch backend of API-NEXT494495The scratch server only accepts `Origin: http://localhost:8483`: tunnel the same port so that the derived origin matches.496497```sh498ssh -f -N -L 8483:127.0.0.1:8483 M4M64c499export SPN_LIVE_URL=http://localhost:8483500export SPN_LIVE_TOKEN=$(ssh M4M64c 'cd ~/dev/note-next && bash scripts/next-dev-server.sh token') # fresh for 5 min (purges)501SPN_ONLY=API swift test --scratch-path .build-api # 243 tests, 32 of them live502SPN_ONLY=Sync swift test --scratch-path .build-sync # 121 tests, 3 of them live503```504505With another local port, the new live helpers (`LiveNext`, `LiveParity`) read `SPN_LIVE_ORIGIN` or ask `GET /api/auth/state`506for the origin; the 1.x `LiveBackendTests` derive it from the URL and fail with `403 csrf`.507508### 9.8 Differences observed between API-NEXT and the scratch server (2026-11-19)509510- `GET /api/sync?kinds=…` with a cursor ahead of the head answers `entities` with one empty list per kind (documented `{}`).511- `POST /api/databases/<id>/query`: a bare rule as `filter` (not a `{and|or}` group) is silently dropped — every row matches.512- `GET /api/search?mode=hybrid` embeds the query (a paid provider call) unless `semantic=0`.513- 404 / 400 without `code` on several routes (`/api/events?projectId=`, `/api/pages/<id>/zoom`, `/api/query` with an unknown514 database, every `/api/databases/…` error, `PATCH /api/pages/<id>` with itself as parent).515- `DELETE /api/graph/relations/<id>` and `DELETE /api/concepts/<id>` are not idempotent (second call 404), unlike tasks.516- `GET /api/graph/insights?limit=` does not cap `insights`; out-of-range `limit` / `inactiveDays` are clamped, not refused.517- `POST /api/capture` refuses the 3.0 kinds `screenshot`, `selection`, `document`.518- `/api/research/references?ids=|projectId=` are ignored by the foundation branch (the whole library comes back).519- The AI-workstream routes (`/zoom/ai`, `/api/audio/…`, `/api/databases/<id>/ai/config|runs`, `/api/inbox/<id>/suggestions|apply`,520 `/api/research/export.tex`) do not exist on the foundation branch: HTML 404.521522