SPNotesAPI — the network layer
SPNotesAPI is the only module that talks to the backend (note-spboucher-ai, contract in
docs/reference/BACKEND_CONTRACT.md). It depends on Foundation, Security and AuthenticationServices only, and on
none of the other modules: note content and properties travel as RawJSON (serialised JSON bytes) and are interpreted by
SPNotesDocument.
| Type | Role |
|---|---|
APIConfiguration |
base URL, Origin, User-Agent, timeouts, cookie names |
SessionTokenStore, KeychainTokenStore, InMemoryTokenStore |
where the session token lives |
HTTPClient (actor) |
transport: cookies by hand, headers, uploads, downloads, event streams, session events |
APIError |
every failure, typed |
NotesAPI |
one method per route |
PasskeyCeremony, PasskeyAuthorizing, SystemPasskeyAuthorizer, AuthService |
passkeys and sign-in flows |
SSEParser, AIEvent |
server-sent events of the AI routes |
1. Setting up
import SPNotesAPI
let configuration = APIConfiguration.production(appVersion: "1.0.0") // https://note.spboucher.ai
let tokens = KeychainTokenStore(configuration: configuration, accessGroup: "3YM54G49SN.ai.spboucher.spnotes.shared")
let client = HTTPClient(configuration: configuration, tokenStore: tokens)
let api = NotesAPI(client: client)APIConfiguration(baseURL:userAgent:requestTimeout:resourceTimeout:streamIdleTimeout:sessionCookieName:ceremonyCookieName:);originis derived from the base URL (scheme://host[:port], default ports omitted);relyingPartyIDis its host.APIConfiguration.userAgent(appVersion:device:osVersion:)buildsSPNotes/1.0.0 (iPhone; iOS 18.1) native(devicedefaults to.current:iPhone,iPadorMacintosh, detected without UIKit).- Test server:
APIConfiguration(baseURL: URL(string: "http://localhost:8482")!).
Token storage
public protocol SessionTokenStore: Sendable {
func load() -> String?
func save(_ token: String) throws
func clear() throws
}KeychainTokenStore(service:account:accessGroup:useDataProtectionKeychain:) stores a generic password with
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly and kSecAttrSynchronizable = false. The account defaults to the origin
(init(configuration:…)), so a test server never shares a token with production. On macOS the data-protection keychain is used
(needs a signed app with a keychain access group); pass useDataProtectionKeychain: false in unsigned tools.
InMemoryTokenStore(token:) is for tests and previews. The token is never logged; APIError descriptions never contain request data.
2. Transport rules implemented by HTTPClient
- One dedicated ephemeral
URLSession: no cookie storage (httpShouldSetCookies = false, accept policynever), no URL cache, no credential storage, TLS ≥ 1.2. Redirects are refused (the cookie never follows one). An injectedURLSessionConfiguration(tests:protocolClasses) is hardened the same way. Cookie: __Host-note_session=<token>is written by hand from the token store.Set-Cookie: __Host-note_session=…on any answer (sign-in, step-up rotation) replaces the token and saves it. A cleared cookie (Max-Age=0, empty value, pastExpires) or a401answering a request that carried the current token clears the store and emitsSessionEvent.signedOutexactly once. (A late 401 for a token that has since been rotated is ignored.)- The WebAuthn ceremony cookie
__Host-note_wais captured from theoptionscall (HTTPRequest.Ceremony.begin(key)) and sent only on the matchingverifycall (.complete(key)), once. OriginandIdempotency-Keyonly on POST / PATCH / PUT / DELETE;x-request-idon every request (generated when absent);Accept: application/json; the configuredUser-Agent.- JSON bodies are encoded with sorted keys (same request → same bytes); dates are
2026-11-18T19:07:04.808Z. Answers are decoded with ISO 8601 dates with or without fractional seconds (and the PostgreSQL form2026-11-18 14:08:56.283-05that/api/searchreturns).
// Session events (each call returns an independent stream)
Task {
for await event in await client.sessionEvents() {
switch event {
case .signedOut(let reason): showSignIn(reason) // .unauthorized | .cookieCleared | .local
case .signedIn, .tokenRotated: break
}
}
}
let signedIn = await client.hasSession
await client.clearSession() // local sign-out, no network
await client.setSessionToken(devToken) // development token of the test serverLow-level calls, when a route has no typed method yet:
let response = try await client.send(.get("/api/health"))
let page: Page = try await client.decode(Page.self, .json(.post, "/api/pages", body: PageDraft(title: "Hello"), idempotencyKey: key))
response.status; response.header("x-request-id"); response.isExisting; response.isIdempotentReplayHTTPClient also exposes upload(_:fromFile:progress:), download(_:to:progress:) and openStream(_:).
Retries (2.0)
HTTPClient.send never retried in 1.x and still does not unless asked: a request carries an optional retry: RetryPolicy.
let health = try await client.send(HTTPRequest.get("/api/health/knowledge").retrying()) // GET: safe by nature
let created = try await client.send(try HTTPRequest.json(.post, "/api/tasks", body: draft).retrying()) // gets an Idempotency-Key- A policy is honoured only when the request
isSafeToRetry: a GET, or any request carrying anIdempotency-Key(the server runs it at most once per key). WebAuthn ceremony calls are never retried (their cookie is single-use). On any other request the policy is ignored: exactly one attempt, as before. retrying(_ policy: = .standard, addingKey: = true)sets the policy and gives a mutating request a fresh key when it has none (HTTPRequest.newIdempotencyKey(), 32 hex characters). The same key and the same body are sent at every attempt; the request id changes.- Retried failures are those for which
APIError.isRetryableis true (offline, transport, timeout, 408, 429, 5xx,409 in_progress). Never 401 (the session ended), other 4xx,503 not_configured | no_model. RetryPolicy(maxAttempts:baseDelay:multiplier:maxDelay:jitter:):.standard= 3 attempts, 0.4 s then 0.8 s;.patient= 5 attempts from 1 s, at most 30 s;.none. ARetry-Afterheader (seconds) longer than the computed delay replaces it, capped bymaxDelay. Cancelling the task during the wait throwsAPIError.cancelled.- Not retried:
upload,download,openStream(the sync engine has its own policy for transfers). The existingNotesAPImethods are unchanged (no policy): the engine keeps deciding when to send again.
3. Errors
public enum APIError: Error, Sendable, Equatable {
case offline // no connectivity
case transport(URLError.Code) // DNS, TLS, connection lost…
case timeout
case cancelled
case invalidResponse
case decoding(String) // 2xx with an unexpected body
case file(String) // local file problem (upload source, download destination)
case http(status: Int, code: String?, message: String, body: Data)
case conflict(server: PageConflict, message: String) // 409 conflict with the server copy
case confirmExpensive(plan: RawJSON, message: String) // 409 confirm_expensive
}Accessors: status, code, message, serverCopy, plan. Classification: isConflict, needsReauth (403 reauth_required),
isUnauthenticated (401), isRateLimited, isNotFound, isOffline, isCancelled, and isRetryable (offline, transport,
timeout, 5xx, 408, 429 and 409 in_progress; not 503 not_configured / no_model). Stable codes: APIError.Code.*.
do {
let result = try await api.patchPage(id: id, PagePatch(title: title, content: content, baseVersion: localVersion))
localVersion = result.version
} catch let error as APIError {
if case .conflict(let server, _) = error {
// server.version, server.title, server.content (RawJSON), server.properties (RawJSON), server.updatedAt
try await api.resolveConflict(pageID: id, choice: .both, serverVersion: server.version, mine: ConflictMine(title: title, content: content))
} else if error.needsReauth {
try await auth.stepUp()
} else if error.isRetryable {
// keep the operation in the outbox with the same idempotency key
}
} 4. Endpoints (NotesAPI)
Identifiers are the server's lower-case UUID strings: NotesAPI.newID(). NotesAPI.newIdempotencyKey() makes a key to store with
a pending operation and to send again unchanged on a retry (every mutating method that the outbox may replay takes idempotencyKey:).
Change feed
func sync(since: Int64, limit: Int? = nil) async throws -> SyncPage
var cursor: Int64 = storedCursor // 0 = full copy
repeat {
let page = try await api.sync(since: cursor, limit: 200)
if page.reset { cursor = 0; wipeLocalCopy(); continue }
apply(page.pages, page.attachments, page.tombstones, page.tags)
cursor = page.cursor
if !page.more { break }
} while trueSyncPage: cursor, head, more, reset, serverTime, workspace {id, name}, user {displayName}, pages: [Page],
attachments: [SyncAttachment], tombstones: [Tombstone], tags: [TagColor]. limit applies to each list separately.
The reset answer is abbreviated (cursor: 0, no user).
Page: id, parentId, databaseId, type, section, title, icon, cover, content: RawJSON, properties: RawJSON, position, pinned, archived, version, wordCount, createdAt, updatedAt, lastOpenedAt, deletedAt, inboxAt, captureKind, rev, tags (tags only in the
feed; plainText, workspaceId only in the page routes).
Pages
func createPage(_ draft: PageDraft = PageDraft(), idempotencyKey: String? = nil) async throws -> Created<Page> // .existing = x-existing: 1
func page(id: String, open: Bool = false) async throws -> PageDetail // page + breadcrumb + backlinks
func pageHead(id: String) async throws -> PageHead // id, version, updatedAt, deletedAt
func patchPage(id: String, _ patch: PagePatch, idempotencyKey: String? = nil) async throws -> PagePatchResult
func resolveConflict(pageID: String, choice: ConflictChoice, serverVersion: Int, mine: ConflictMine, idempotencyKey: String? = nil) async throws -> ResolvedPage
func trashPage(id: String, idempotencyKey: String? = nil) async throws -> TrashResult
func purgePage(id: String) async throws -> OKResult // fresh verification
func emptyTrash(olderThanDays: Int? = nil) async throws -> PurgeResult // fresh verification
func restorePage(id: String, idempotencyKey: String? = nil) async throws -> OKResult
func duplicatePage(id: String, idempotencyKey: String? = nil) async throws -> Page
func pageVersions(pageID: String) async throws -> [PageVersionSummary]
func pageVersion(pageID: String, version: Int) async throws -> PageVersionSnapshot
func restorePageVersion(pageID: String, version: Int, idempotencyKey: String? = nil) async throws -> VersionRestoreResult
func pageTags(pageID: String) async throws -> [String]
func setPageTags(pageID: String, tags: [String], idempotencyKey: String? = nil) async throws -> [String]
func tags() async throws -> [TagSummary]PagePatch — every field optional; only what is set is sent. parentId, icon and cover are PatchValue<String>?:
nil = absent, .null = JSON null, .value(x) = the value.
PagePatch(title: "New title", baseVersion: 4) // {"baseVersion":4,"title":"New title"}
PagePatch(parentId: .null) // {"parentId":null} → move to the root
PagePatch(icon: .value("📝"), pinned: true) // not version-guarded
PagePatch(content: RawJSON(data: documentJSON), versionReason: "manual", baseVersion: 4)let id = NotesAPI.newID()
let created = try await api.createPage(PageDraft(id: id, title: "Offline note", content: RawJSON(data: json)))
if created.existing { /* a retry: the stored page came back untouched */ }Attachments
func uploadAttachment(fileURL: URL, id: String? = nil, pageID: String? = nil, filename: String? = nil, mimeType: String? = nil,
progress: TransferProgressHandler? = nil) async throws -> Created<UploadedAttachment>
func attachments(pageID: String? = nil) async throws -> [AttachmentInfo]
func deleteAttachment(id: String, idempotencyKey: String? = nil) async throws -> OKResult
func downloadFile(id: String, to destination: URL, progress: TransferProgressHandler? = nil) async throws -> DownloadedFile
static func filePath(id: String) -> String // "/api/files/<id>"
static func fileID(fromSource: String) -> String?Uploads build the multipart body in a temporary file (MultipartForm, fields id, pageId, file) and send it with
URLSession.upload(for:fromFile:); downloads go straight to disk. Nothing is held in memory, both report
TransferProgress(completedBytes:totalBytes:) (fraction) on a background queue, and both stop when the calling task is cancelled.
let upload = Task {
try await api.uploadAttachment(fileURL: movieURL, id: attachmentID, pageID: pageID) { progress in
Task { @MainActor in bar.value = progress.fraction ?? 0 }
}
}
upload.cancel() // → APIError.cancelled
let file = try await api.downloadFile(id: attachmentID, to: cacheURL)Authentication
func loginOptions() async throws -> PasskeyRequestOptions
func loginVerify(_ credential: PasskeyAssertionCredential) async throws -> LoginResult
func reauthOptions() async throws -> PasskeyRequestOptions
func reauthVerify(_ credential: PasskeyAssertionCredential) async throws -> ReauthResult
func authState() async throws -> AuthState
func logout() async throws -> OKResult
func sessions() async throws -> [SessionInfo]
func revokeSession(id: String) async throws -> OKResult // fresh verification
func revokeAllSessions(includeCurrent: Bool = false) async throws -> RevokeSessionsResult // fresh verification
func passkeys() async throws -> [PasskeyInfo]
func passkeyRegistrationOptions() async throws -> PasskeyCreationOptions // fresh verification
func passkeyRegistrationVerify(_ credential: PasskeyRegistrationCredential, label: String? = nil) async throws -> PasskeyAdded
func renamePasskey(id: String, label: String) async throws
func deletePasskey(id: String) async throwsApps normally use AuthService (§5) instead of the four ceremony calls.
AI (server-sent events)
func aiAction(_ request: AIActionRequest) async throws -> AsyncThrowingStream<AIEvent, Error>
func aiChat(_ request: AIChatRequest) async throws -> AsyncThrowingStream<AIEvent, Error>
public enum AIEvent { case meta(AIMeta), text(String), done(AIDone), error(AIStreamError), needsConfirmation(AIConfirmation), other(type: String, raw: RawJSON) }Errors raised before the stream starts are thrown by the call itself: APIError.confirmExpensive(plan:message:),
503 not_configured | no_model, 400. Provider failures during the stream arrive as .error events. The stream ends at
data: [DONE]. Cancelling the consuming task (or dropping the stream) closes the connection.
let generation = Task {
do {
for try await event in try await api.aiAction(AIActionRequest(action: .summarize, text: selection)) {
switch event {
case .meta(let meta): model = meta.model
case .text(let delta): preview += delta
case .done(let done): cost = done.costUsd
case .error(let failure): show(failure.message, retry: failure.retryable)
case .needsConfirmation(let c): ask(c.plan) // chat only
case .other: break
}
}
} catch let error as APIError {
if case .confirmExpensive(let plan, let message) = error { askThenResend(plan, message) } // resend with confirmExpensive: true
}
}
generation.cancel() // stops the request and the generationSearch, tasks, inbox, capture, health
func search(_ query: SearchQuery) async throws -> [SearchHit] // SearchQuery("text", mode: .quick | .hybrid, limit:, semantic:, section:, since:, until:, includeArchived:)
func tasks(includeDone: Bool = false) async throws -> [TaskItem]
func createTask(_ draft: TaskDraft, idempotencyKey: String? = nil) async throws -> TaskItem
func updateTask(_ patch: TaskPatch, idempotencyKey: String? = nil) async throws -> TaskItem // dueAt / project / pageId: PatchValue (.null clears)
func deleteTask(id: String, idempotencyKey: String? = nil) async throws -> OKResult
func inbox() async throws -> [InboxItem]
func triageInboxItem(id: String, _ action: InboxAction, idempotencyKey: String? = nil) async throws -> TriageResult
func undoInboxAction(actionID: String) async throws -> UndoResult
func capture(_ request: CaptureRequest, idempotencyKey: String? = nil) async throws -> CaptureResult
func health() async throws -> Health// A reminder = a task with a page and a date. Priorities are low | medium | high.
let reminder = try await api.createTask(TaskDraft(title: "Call back", dueAt: date, priority: .high, pageId: pageID))
try await api.updateTask(TaskPatch(id: reminder.id, dueAt: .null, status: .done))
let captured = try await api.capture(CaptureRequest(kind: .link, url: "https://example.com"), idempotencyKey: storedKey)
try await api.triageInboxItem(id: captured.id, .keep(section: .notes))5. Passkeys
PasskeyCeremony holds the pure JSON work (no system objects needed, fully unit-tested):
static func decodeRequestOptions(_ json: Data) throws -> PasskeyRequestOptions // accepts {options: …} or the bare object
static func decodeCreationOptions(_ json: Data) throws -> PasskeyCreationOptions
static func assertionCredential(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) -> PasskeyAssertionCredential
static func registrationCredential(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> PasskeyRegistrationCredential
static func assertionVerifyBody(_ credential: PasskeyAssertionCredential) throws -> Data // {"response":{…}}
static func registrationVerifyBody(_ credential: PasskeyRegistrationCredential, label: String?) throws -> Data
static func assertionCredential(from: ASAuthorizationPlatformPublicKeyCredentialAssertion) -> PasskeyAssertionCredential
static func registrationCredential(from: ASAuthorizationPlatformPublicKeyCredentialRegistration) throws -> PasskeyRegistrationCredentialBinary fields are base64url without padding (Base64URL.encode / .decode, the decoder tolerates padding and plain base64);
clientExtensionResults is {}, authenticatorAttachment is "platform", registration transports is ["internal","hybrid"].
The device half is a protocol, so tests and previews can replace it:
@MainActor public protocol PasskeyAuthorizing: AnyObject, Sendable {
func assertion(for options: PasskeyRequestOptions) async throws -> PasskeyAssertionCredential
func registration(for options: PasskeyCreationOptions) async throws -> PasskeyRegistrationCredential
}SystemPasskeyAuthorizer(fallbackRelyingParty:preferImmediatelyAvailableCredentials:anchor:) runs ASAuthorizationController for
platform passkeys (relying party from the options, user verification required, allowedCredentials / excludedCredentials when
provided). It throws PasskeyError: .cancelled, .noCredentials, .alreadyRegistered, .notInteractive, .inProgress,
.notAssociated, .invalidOptions, .failed(code:message:).
let authorizer = SystemPasskeyAuthorizer(fallbackRelyingParty: configuration.relyingPartyID) { window } // ASPresentationAnchor
let auth = AuthService(api: api, authorizer: authorizer)
try await auth.signIn() // options → system sheet → verify → token stored
try await auth.stepUp() // fresh for 5 minutes, token rotated
try await auth.addPasskey(label: "iPhone") // steps up by itself when the server asks (stepUpIfNeeded: true)
let purged = try await auth.withFreshSession { try await api.purgePage(id: id) } // step-up + one retry on reauth_required
await auth.signOut() // server logout (best effort) + token forgotten
let signedIn = await auth.isSignedInThe apps need the associated-domains entitlement webcredentials:note.spboucher.ai.
6. Server-sent events
var parser = SSEParser()
for event in parser.feed(chunk) { // any chunking: mid UTF-8 sequence, between \r and \n
if event.isDone { break } // data: [DONE]
handle(event.data) // also event.event, event.id
}
let tail = parser.finish() // flushes an unterminated last event7. Tests
cd SPNotesCore
SPN_ONLY=API swift build --scratch-path .build-api && SPN_ONLY=API swift test --scratch-path .build-apiUnit tests use a URLProtocol stub (Tests/SPNotesAPITests/TestSupport.swift). The live tests (LiveBackendTests) only run when
SPN_LIVE_URL and SPN_LIVE_TOKEN are set, refuse any *.spboucher.ai host, and clean up what they create:
ssh -f -N -L 8482:localhost:8482 M4M64c
TOKEN=$(ssh M4M64c 'bash -lc "cd ~/dev/note-native && set -a && . ./.env && set +a && node_modules/.bin/tsx scripts/dev-session.ts"')
SPN_LIVE_URL=http://localhost:8482 SPN_LIVE_TOKEN=$TOKEN SPN_ONLY=API swift test --scratch-path .build-api
# optional: SPN_LIVE_TOKEN_DISPOSABLE / SPN_LIVE_TOKEN_DISPOSABLE2 = two more tokens (one is revoked, one logs out)A development token is "fresh" for 5 minutes: within that window the purge and revocation paths run for real, afterwards the tests
check the typed reauth_required error instead.
8. Differences observed between the contract and the test server (2026-11-18)
GET /api/syncwith a cursor ahead of the server answers{reset: true, cursor: 0, more: true, …}withoutuser.limitbounds each list (pages, attachments, tombstones) separately. A non-numeric or negativesince→400 bad_cursor.GET /api/search?mode=quickreturnsupdatedAtin PostgreSQL text form (2026-11-18 14:08:56.283-05), not ISO 8601.- Page rows of
POST/GET /api/pages…carryworkspaceId,plainText,tsvand notags(the feed has them). POST /api/pages/<id>?action=duplicateanswers200(not 201).- Task
priorityislow | medium | high(400otherwise); task rows also carryworkspaceId,deletedAt; the list addspageTitle,pageIcon. POST /api/inbox/<id>also returnscreated;POST /api/inbox/undoreturns{ok, already}; triage actions arekeep | task | database | reference | archive | trash.DELETE /api/auth/sessions/<id>needs a fresh verification (403 reauth_required), like the global revocation.- Idempotency: a replayed answer has
idempotent-replay: truebut notx-existing; a key reused with a different body on the same method and path is replayed as well (422idempotency_mismatchonly when the method or the path differs). - Extra error codes:
bad_request(400),challenge_missing(400),no_instruction/bad_language(400, AI action),last_passkey(409),bad_cursor(400).not_enrolledis a 409. Validation errors are400without a code. A malformed UUID in a path (/api/pages/not-a-uuid,DELETE /api/tasks?id=) answers500. GET /api/healthis public and does not echox-request-id; it also returnspgvectorandtime.GET /api/tagsreportspages: 0for tags carried by live pages.DELETE /api/attachments?id=is a soft delete:/api/files/<id>keeps serving the bytes. Purging a page leaves its attachments alive withpageId: null(no tombstone).
9. SPNotesCore 2.0 — the 3.0 backend (API-NEXT) and the 2.x parity routes
Everything below is additive: the 1.x methods keep their signatures. Every DTO is Codable, tolerant of unknown fields, and
decoded in a test from a real answer of the scratch backend (Tests/SPNotesAPITests/Fixtures/next/<group>/, recorded by
Scripts/record-next-fixtures.sh — scenarios in Scripts/recorders/*.py, library Scripts/spn_recorder.py), except the
AI-workstream answers, transcribed from API-NEXT-AI.md (ai-doc/, ai-doc-parity/, each with a README saying so).
9.1 Meta, feed, tasks, canvas (NextCoreModels.swift, NotesAPI+NextCore.swift)
func meta() async throws -> ServerMeta // 404 on a 2.x server → .legacy (api 2, no feature); ServerFeature.*
func sync(since:limit:kinds: [String]) async throws -> SyncPage // SyncPage.entities: [kind: [SyncEntityRow]]; SyncKind.all
func tasks(includeDone:pageId:since:) async throws -> [TaskItem]
func createTaskIdempotent(_ draft: TaskDraft) async throws -> Created<TaskItem> // TaskDraft.id / blockId / status / due
func task(id:) ; func updateTask(id:_ TaskChanges, idempotencyKey:) ; func removeTask(id:) -> TaskDeleteResult
func canvas(pageID:) -> CanvasEnvelope ; func saveCanvas(pageID:data:baseVersion:) -> CanvasSaveResult // 409 → error.canvasConflict (CanvasServerCopy)A cursor is only valid for the set of kinds it was obtained with (the engine handles it, SYNC_ENGINE.md §7.2).
PageType.canvas, TaskStatus.doing, TaskItem.blockId / deletedAt / rev are new.
9.2 Knowledge graph, journal, time machine, health, brief, living blocks, zoom
graph(_ GraphQuery), legacyGraph, createRelation / relations / relation / updateRelation / deleteRelation,
concepts / createConcept / concept / updateConcept / patchConcepts / deleteConcept, graphInsights / runGraphInsights / decideInsight; events(_ JournalQuery) -> EventPage, timeMachine(pageID: | projectID:, at:), restoreHistoryEntry;
knowledgeHealth, brief, summarizeBrief (paid), query(_ LiveQuery), pageZoom(pageID:level:), pageSynopsis,
regeneratePageSynopsis (paid). String-constant namespaces (GraphView, RelationType, EventKind, LiveQuerySource…)
instead of closed enums: an unknown value never fails decoding.
9.3 Files: ranges and resumable downloads (NotesAPI+Files.swift)
func fileRange(id:range: ByteRange, ifRange:) async throws -> FileRange // 206 / 200 / 416 (returned, not thrown)
func downloadFile(id:to:resumingFrom partial: URL, etag:verifyChecksum:progress:) async throws -> ResumedDownloadThe resumable download keeps the partial file and its ETag (sidecar), sends Range: bytes=<size>- + If-Range, appends on
206, starts over on 200 (changed file), handles 416, and checks the ETag (sha256 of the content) at the end.
9.4 AI (AICatalogModels.swift, NotesAPI+AINext.swift, AudioModels.swift)
aiModelCatalog(_ AIModelQuery) -> AIModelCatalog (creator, route, logo, prices, capabilities, availability),
AIChatRequest.scope / projectId / selection / selectionBlockId, AIMeta.sources / scope / scopePages, AIDone.sources / invalidCitations / uncited (AISourceRef.blockId / blockIds / anchor / quote), aiAction(_ AIActionCall) for the 3.0 action
ids (AIActionID) with AIEvent.linkSuggestions, transcribeAudio / audioTranscription, databaseAIConfig / setDatabaseAIConfig / runDatabaseAI / databaseAIRuns.
9.5 Parity with the web (2.x routes without a native client until now)
Databases (databases, database, updateDatabase, duplicateDatabase, databaseTemplates, applyDatabaseTemplate, properties,
views, rows — single and bulk —, queryDatabase, CSV), search (SearchQuery.kinds / group, SearchQuery.keywords, extra hit
fields, duplicatePages, searchIndexState), graph links (backlinks, graphNeighbors, linkSuggestions,
decideLinkSuggestion), inbox (inboxCount, capture(_ CaptureDraft), inboxSuggestions, applyInboxSuggestions), research
(references, extracts, DOI, BibTeX, experiments, research tasks, overview, LaTeX export), AI conversations / usage / plans,
agents (catalogue, run, execution, approve / reject / undo proposals), dashboard, settings, audit log, page lists, trash purge.
9.6 Errors (API-NEXT §5)
No case was added to APIError. Constants: APIError.NextCode, APIError.AICode, ParityCode. Accessors: canvasConflict,
detail(_:), detailString(_:), isNotImplemented, isBadRequest, existingRelation, existingConcept, badNodeField,
isDerivedEdge, unknownPageIDs, validKinds, isRouteMissing (501, or the HTML 404 / 405 of a server without the route),
isAIUnavailable, isNotInInbox, isRowDeleted, isIDTaken, needsCostConfirmation, runningExecutionID.
Note: isRetryable is true for a 501 — test isRouteMissing first.
9.7 Live tests against the scratch backend of API-NEXT
The scratch server only accepts Origin: http://localhost:8483: tunnel the same port so that the derived origin matches.
ssh -f -N -L 8483:127.0.0.1:8483 M4M64c
export SPN_LIVE_URL=http://localhost:8483
export SPN_LIVE_TOKEN=$(ssh M4M64c 'cd ~/dev/note-next && bash scripts/next-dev-server.sh token') # fresh for 5 min (purges)
SPN_ONLY=API swift test --scratch-path .build-api # 243 tests, 32 of them live
SPN_ONLY=Sync swift test --scratch-path .build-sync # 121 tests, 3 of them liveWith another local port, the new live helpers (LiveNext, LiveParity) read SPN_LIVE_ORIGIN or ask GET /api/auth/state
for the origin; the 1.x LiveBackendTests derive it from the URL and fail with 403 csrf.
9.8 Differences observed between API-NEXT and the scratch server (2026-11-19)
GET /api/sync?kinds=…with a cursor ahead of the head answersentitieswith one empty list per kind (documented{}).POST /api/databases/<id>/query: a bare rule asfilter(not a{and|or}group) is silently dropped — every row matches.GET /api/search?mode=hybridembeds the query (a paid provider call) unlesssemantic=0.- 404 / 400 without
codeon several routes (/api/events?projectId=,/api/pages/<id>/zoom,/api/querywith an unknown database, every/api/databases/…error,PATCH /api/pages/<id>with itself as parent). DELETE /api/graph/relations/<id>andDELETE /api/concepts/<id>are not idempotent (second call 404), unlike tasks.GET /api/graph/insights?limit=does not capinsights; out-of-rangelimit/inactiveDaysare clamped, not refused.POST /api/capturerefuses the 3.0 kindsscreenshot,selection,document./api/research/references?ids=|projectId=are ignored by the foundation branch (the whole library comes back).- The AI-workstream routes (
/zoom/ai,/api/audio/…,/api/databases/<id>/ai/config|runs,/api/inbox/<id>/suggestions|apply,/api/research/export.tex) do not exist on the foundation branch: HTML 404.