SPB Git

Repository Public

REPOSITORIES.md 12.5 KB

# Repositories — the API of the apps (SPNotesCore 2.0)

The repositories sit on top of the store, the API client and the sync engine. They live in the SPNotesSync module (Sources/SPNotesSync/Repositories/; a deliberate choice: no new product, nothing to add to the app projects — import SPNotesCore is enough). They are Sendable structs with async methods, safe to hold in an @Observable model.

swift
let repos = NotesRepositories(store: store, api: api, engine: engine)

@Observable @MainActor final class TasksModel {
    var tasks: [TaskItem] = []
    let repo: TasksRepository
    init(_ repos: NotesRepositories) { repo = repos.tasks }
    func load() async { tasks = (try? await repo.list(.open)) ?? [] }
    func observe() async { for await _ in await repo.changes() { await load() } }
    func add(_ title: String) async throws { try await repo.create(title: title); await load() }   // works offline
}

Gate UI on the server features: await repos.features()?.has(ServerFeature.canvas) (nil = never asked yet).

# 1. What works offline (SPEC §6)

Repository Read offline Write offline Write online
TasksRepository yes (entity copy) yes — outbox, client ids, idempotent —
CanvasRepository yes yes — merge by node / edge id, conflicts kept refresh
DatabasesRepository yes (definition, properties, views, rows; local filter / sort / group) no → .offline yes; the answer updates the local copy
GraphRepository relations, backlinks, concepts (entity copy); views and insights from the cache no → .offline relations create / accept / reject / edit / delete, concepts, insight decisions
ResearchRepository references, citation resolution no → .offline references, DOI, BibTeX, experiments
TimelineRepository events already fetched; cached time-machine states — restore a history entry
KnowledgeRepository health, brief, zoom, query results from the cache, with their date — brief summary (paid, explicit)
InboxRepository last list no → .offline (the 1.0 queued triage still exists) capture, triage, undo, suggestions
SearchRepository local full-text — server results merged in
AssistantRepository model catalogue from the cache — ask, actions
AudioRepository — — upload, transcribe, poll

No silent queueing. A write of a kind that is online-only never goes to an outbox: unreachable server → RepositoryError.offline, and nothing changed locally. Disable the control or tell the user; do not retry in the background.

# 2. Errors

swift
public enum RepositoryError: Error { case offline, signedOut, unsupported(feature:), notCached, notFound(String), server(APIError), store(String), invalid(String), stale }
  • .offline — no connectivity, connection failure or timeout.
  • .unsupported — the server does not have the feature (a 2.x server, 501, or a route that answers the HTML 404).
  • .notCached — offline (or .cacheOnly) and this read model was never fetched.
  • .server(error) — the server said no: error.code is the stable code (relation_exists, concept_exists, derived_edge, bad_node, row_deleted, conflict…), with typed accessors (error.existingRelation, error.existingConcept, error.badNodeField, error.isConflict, error.needsReauth, error.plan for confirm_expensive).
  • .stale — what a decision was made on changed since it was read (canvas conflict): read again, ask again.

# 3. Cached read models

Every read model returns Cached<T> { value, fetchedAt, source: .network | .cache }; isStale(maxAge:) and Staleness.brief / .health / .graph / .insights / .events / .zoom / .query / .models / .timeMachine give suggested ages. Policies: .networkFirst (default: ask, fall back to the copy when offline), .cacheFirst(maxAge:), .cacheOnly, .networkOnly. Nothing is ever recomputed on the device: when source == .cache, show the date (« mis à jour il y a … »).

swift
let brief = try await repos.knowledge.brief(policy: .cacheFirst(maxAge: Staleness.brief))
if brief.source == .cache { banner = "Mis à jour \(brief.fetchedAt.formatted(.relative(presentation: .named)))" }

# 4. The repositories

# Tasks — TasksRepository

list(_ filter: .open | .done | .all, pageId:), task(id:), isPending(id:), create(title:dueAt:dueDay:priority:status:project:pageId:blockId:id:), update(id:_ TaskEdit), setDone(id:_:), delete(id:), pendingOperations(), retry(operation:), discard(operation:), changes(). A bare day (dueDay: "2026-11-21") is noon UTC, as on the server: display the UTC date part. Operations the server refuses for good are state == .rejected in pendingOperations() and counted in SyncStatus.rejected: show lastError, offer retry or discard. A taskItem linked to a task (taskId): put a fresh UUID in the node and save the page — the server creates the task; completing a linked task from a list does not tick the box in the page (API-NEXT §4.2): tick it too when the page is open. On a 2.x server writes throw .unsupported(feature: "tasks-v2") once the features are known.

# Canvas — CanvasRepository

state(pageId:), create(title:parentId:section:document:id:) (offline), save(pageId:_:editedFrom:) (use this one in an editor: it merges your edit into the stored canvas when a sync moved it under you, and returns the document to continue from), save(pageId:_:) (unconditional), refresh(pageId:), conflicts(), conflict(pageId:), resolve(_ conflict:_:) with .keepMine | .keepTheirs | .merged(document), changes(). A conflict (SyncStatus.canvasConflicts, state.hasConflict) never changed anything: conflict.local is what the user sees, conflict.remote the server copy, conflict.merge.merged the proposal (local version of each conflicting card; an edited card is kept when the other side deleted it) and conflict.merge.conflicts the list to show; build the decision with merged.resolving(conflict, takingRemote:). resolve throws .stale when the canvas moved since the conflict was read.

# Databases — DatabasesRepository

Local: list(), database(id:) (database id or host page id) → LocalDatabase { info, properties, views }, localRows, evaluateLocally(databaseId:viewId:query:). Mixed: rows(databaseId:viewId:search:limit:offset:) → server when reachable (source == .server, computed values included), local evaluation otherwise. Online: refresh(id:), update, createProperty / updateProperty / deleteProperty, createView / updateView / deleteView, createRow / updateRow / deleteRows / restoreRows. DatabaseEvaluator applies the server's rules (query.ts): the 15 operators per property type, and / or trees, search, multi-key sorts with empty values last, pagination, and grouping (a client feature on the web too). It evaluates the stored types (title, text, url, number, date, checkbox, select, status, multi_select, created_time, ai); a rule or a sort on a relation, rollup or formula is not applied and the result has isExact == false and notEvaluated (names): show the rows as "approximate offline" or ask the server. Calendar days are those of the server's time zone (America/Toronto). Verified row for row against the real server on 14 filter / sort / search cases (LiveRepositoryTests). A filter sent to the server must be a group at the top level: use DatabaseViewFilter.topLevelJSON.

# Graph — GraphRepository

view(_ GraphQuery, policy:), insights(_:policy:), runInsights(_:) (default deterministic = free), decideInsight, localRelations(touching:), localBacklinks(pageId:), relations(_:), createRelation, accept / reject / update(relationId:), deleteRelation, localConcepts, concepts, concept(id:), createConcept / updateConcept / deleteConcept. Anything with origin == "ai" must be shown as AI, accepted or not.

# Timeline — TimelineRepository

events(_ JournalQuery, policy:) → TimelinePage { events: [EventRecord], nextCursor, source, fetchedAt } (pass nextCursor back as query.cursor; offline the local events are filtered by page, kinds and dates), timeMachine(pageId: | projectId:, at:), restore(pageId:versionId:baseVersion:).

# Knowledge — KnowledgeRepository

health, brief(timeZone:), summarizeBrief (paid), query(_ LiveQuery) for queryView / chart blocks, zoom(pageId:level:) (2 = outline, 3 = full), synopsis(pageId:cachedOnly:) (level 1, AI; cachedOnly: true by default so that nothing is spent without a user action).

# Research — ResearchRepository

localReferences(pageId:), resolveLocally(ids:), resolve(ids:) (for citation nodes; falls back to the local copy offline), create / update / delete / restore, lookupDOI, addByDOI, importBibTeX(_:pageId:dryRun:), exportBibTeX, exportLaTeX, experiments, createExperiment / updateExperiment / deleteExperiment, overview.

# Inbox — InboxRepository

items(policy:), count(), capture(_ CaptureDraft), triage(id:_ InboxAction) → actionId, undo(actionId:), suggestions(id:cachedOnly:) (AI, suggestions only), apply(id:_ InboxSuggestionSelection).

# Search — SearchRepository

local(_:filters:limit:) for search-as-you-type; search(_:scope:filters:limit:) → SearchOutcome { results, usedServer, serverError } where each UnifiedSearchResult is labelled .local | .server | .both, carries the server's blockId / heading when there is one, and one snippet convention (the local highlight markers). Scopes: .serverLexical (default, free), .hybrid (the server embeds the query: one paid provider call per search — only on an explicit "search by meaning"), .localOnly. A failing server never fails the search.

# Assistant — AssistantRepository

ask(_:scope:pageId:projectId:selection:selectionBlockId:conversationId:model:) → stream of AIEvent; citations(of:) gives AssistantCitation { n, pageId, blockId, title, heading, quote, anchor } for meta and done events (scroll to the node whose id is blockId); actions() (the 21 historical ids + coherence, questions, synthesis, structure, links), run(action:text:…) (links yields event.linkSuggestions, nothing is written); models(_:policy:) → AIModelCatalog (group by creator, show the route badge, never select available == false, "Auto" = model: nil), logoURL(_:).

# Audio — AudioRepository

upload(fileURL:pageId:) → attachment id, transcribe(attachmentId:summarize:force:) (paid), status, waitForTranscription (polls every 2.5 s), transcribeRecording(fileURL:pageId:) (all three), nodeAttributes(from:) — the editor writes the transcript into the audio node and saves the page; the server never edits the page. .unsupported(feature: "voice") on a server without the routes.

# 5. Unit tests in the apps: the fake backend

Add the product SPNotesTestSupport to the test targets only. FakeBackend is an in-memory server behind a URLProtocol: session and Origin checks, idempotency keys, the change feed with one revision sequence, pages, tags, conflicts, attachments, tasks, inbox triage, and — at apiLevel: 3 (default) — /api/meta, the entity feed (kinds), tasks with client ids, canvases with versions, opaque rows for the other kinds. FakeBackend(apiLevel: 2) answers like a 2.x server.

swift
let fake = FakeBackend()
let client = HTTPClient(configuration: APIConfiguration(baseURL: fake.baseURL, userAgent: "tests"),
                        tokenStore: InMemoryTokenStore(token: fake.issueToken()), sessionConfiguration: FakeBackend.sessionConfiguration())
fake.webCreateTask(title: "Du web"); fake.webSaveCanvas(id, data: json); fake.webPutEntity(kind: "concept", id: id, json: "{…}")
fake.stub("GET", path: "^/api/health/knowledge$", json: recordedAnswer)         // any route the fake does not model
fake.setOffline(true); fake.inject(.dropResponse, method: "PUT", path: "^/api/canvases/"); fake.inject(.status(500), path: "^/api/tasks")
defer { fake.shutdown() }

The real answers recorded from the scratch backend are in Tests/SPNotesAPITests/Fixtures/next/ (about 480 files in 20 groups, one _index.json per group): use them as stub bodies, as RepositoryOnlineTests does.

Files main
Menu

Theme