Introducing a new way to review your PRs.

Read the announcement

triliumnext / trilium

Build your personal knowledge base with Trilium Notes

View on GitHub

20 documents · Updated Nov 23, 2026

docs / core-domain-and-common-contracts

Core domain and common contracts

@triliumnext/core is the shared product engine for storing and changing knowledge-base notes. @triliumnext/commons is the shared contract layer that keeps the server, desktop shell, browser client, editor, and other workspace surfaces aligned on domain data and cross-runtime behavior.

Package roles

Commons package

packages/…/index.ts is the public entry point for shared types and helpers. It gives hosts and clients one vocabulary for notes, branches, attributes, attachments, options, API responses, Markdown content, table of contents data, resources, transcripts, model chat, native actions, and live messages.

The package also holds rules that must not drift between runtimes. These include MIME values, note types, attachment roles, block links, content embeds, locales, dates, rendering terms, task states, and typed option names. Modules with large dependencies, such as the Markdown renderer and spreadsheet tools, remain available through their own subpaths instead of the common barrel.

References: packages/…/index.ts• L1-68 packages/…/options_interface.ts• L62-102 packages/…/server_api.ts• L329-418

Core package

packages/trilium-core applies the shared vocabulary to the knowledge-base domain. It coordinates durable records with a loaded note view and exposes domain behavior through routes, services, events, imports, exports, sync, scripts, and model features.

Core is not tied to one host. A host supplies storage, cryptography, requests, archives, translation, logging, messaging, image work, and setup behavior. Core then exposes the same product rules through HTTP, IPC, or a worker boundary.

References: packages/…/index.ts• L197-264 packages/…/index.ts• L128-185 packages/…/index.ts• L57-125

Runtime composition

Core sits between host capabilities and application surfaces. Commons gives both sides stable names and shapes. Core applies product rules and returns typed state, errors, and live events.

The shared route table maps requests to core handlers, while each host supplies route guards, authentication, request handling, and transport details. This lets the server, desktop app, and standalone build share domain behavior without sharing one process model.

This diagram shows the relationship between host capabilities, the core domain, and consuming surfaces.

flowchart LR
    Host[Host runtime] --> Capabilities[Platform capabilities]
    Commons[Shared contracts] --> Core[Trilium Core]
    Capabilities --> Core
    Core --> State[Knowledge-base state]
    Core --> Responses[Typed responses and errors]
    Core --> Events[Live events]
    Responses --> Surfaces[Client and content surfaces]
    Events --> Surfaces

References: packages/…/index.ts• L197-264 packages/…/index.ts• L91-125 packages/…/index.ts• L261-269

Domain model

Note records

The note model separates note identity from tree placement. A note owns its title, type, MIME value, protection state, and content. A branch places that note below a parent, so one note can appear in more than one place without copying its content.

Content is loaded when a caller needs it. This keeps ordinary metadata work separate from large bodies and binary data. Virtual notes use the same read model but obtain content from an application-owned provider rather than durable note rows.

Domain objectProduct meaning
NoteA knowledge-base item with content and metadata.
BranchA placement of a note in the tree.
AttributeA label or relation attached to a note.
AttachmentFile or image content owned by a note or revision.
RevisionA saved historical form of a note.
BlobContent bytes shared by notes, attachments, or revisions.
OptionA named application value with a sync policy.

References: packages/…/rows.ts• L4-22 packages/…/rows.ts• L82-160 packages/…/bnote.ts• L83-190

Note creation and change flow

Note creation is one domain action. It creates the note, its branch, its initial attributes, and its content under one transaction. Parent rules, templates, type defaults, and inherited child attributes decide the resulting note.

Later content saves also update attachment links and relations. Core can copy a foreign attachment into the new owner before the source attachment becomes unused. This keeps pasted content valid after a cut, copy, or import operation.

flowchart LR
    Request[Create or save request] --> Validate[Validate parent, type, and content]
    Validate --> Entity[Create or update note and branch]
    Entity --> Links[Scan links and attachments]
    Links --> State[Persist domain state]
    State --> Events[Return response and publish changes]

References: packages/…/notes.ts• L246-417 packages/…/notes.ts• L563-735 packages/…/notes.ts• L72-113

Revision snapshots

Revisions preserve earlier note content when a save, restore, or unsaved editor draft needs a recoverable version. A revision carries the note format and its own attachment copies, so a historical view remains valid even when the live note changes.

The retention contract distinguishes automatic snapshots from named snapshots and allows a note-level versioning limit to override the global option. Drafts can represent a whole note or an edited block range. A fragment that cannot be safely merged remains a fragment revision and cannot be restored as a complete note.

References: packages/…/server_api.ts• L32-89 packages/…/bnote.ts• L1353-1499 packages/…/revisions.ts• L189-320

Attachments and resources

Blobs hold bytes shared by notes, attachments, and revisions. An attachment adds ownership, title, MIME value, role, and optional position. An attachment role is a shared rule set that tells every consumer whether the content is a picture, embedded, derived, deduplicated, user-copied, or named by a role-specific icon.

The built-in roles cover user files and images, link-preview pictures, view state, canvas library data, import sources, transcripts, and table-of-contents caches. Core tracks which attachments content uses. It schedules unused embedded attachments for cleanup and copies foreign attachments into the current note when content refers to them.

Resources are different from attachments. They are large runtime files such as model or transcription data that are installed for a device and reported through a shared download task contract rather than owned by a note.

References: packages/…/attachment_roles.ts• L12-75 packages/…/attachment_roles.ts• L84-112 packages/…/resources.ts• L1-91 packages/…/notes.ts• L563-735

Image ingestion

Image ingestion turns uploaded, pasted, inline, or remote pictures into note-owned attachments. The content then points at the local attachment instead of depending on a remote URL or repeating base64 bytes inside every revision.

Image processing is asynchronous, so callers use a completion barrier when they must return a URL whose bytes are already readable. Remote downloads accept only HTTP(S) URLs and store bytes only after image inspection confirms that the response is an image. User settings control whether remote images are fetched and how images are resized or re-encoded.

References: packages/…/image.ts• L18-93 packages/…/image_download.ts• L38-117 packages/…/image_download.ts• L183-245 packages/…/server_api.ts• L778-1002

Note references

Note references are stable links to places inside content. Commons names the target kinds and link parameters. Core asks the first matching reference provider to list targets and to add a reference when the content supports it.

Text notes expose headings and anchors. A heading without a block ID receives a generated block ID; an existing valid ID is reused. Markdown notes use the same link meaning, but store the marker in Markdown source. A reference write is invisible to the reader, so it does not create a revision.

References: packages/…/reference_targets.ts• L4-43 packages/…/index.ts• L25-57 packages/…/text.ts• L14-40 packages/…/markdown.ts• L9-26

Block references

Block references identify one block or an ordered range inside a text or Markdown note. Commons gives blocks a shared identity based on kind, ancestry, text, and order. The same contract works with browser DOM nodes and server-side HTML nodes, so links, focused editing, and shared views resolve the same content.

The block range contract also protects format changes. Core can compare block IDs before and after conversion, extract an editable run, preserve ordered-list numbering, and reject a range that cannot be separated without changing unrelated structure.

References: packages/…/block_reference.ts• L23-53 packages/…/block_reference.ts• L157-246 packages/…/block_keys.ts• L9-23 packages/…/block_ranges.ts• L9-102

Markdown source contracts

The Markdown contract keeps source text, rendered blocks, headings, anchors, and block IDs connected. The shared renderer creates the same CKEditor-compatible HTML shape used by readers and the editor. It also accepts configured task states and can opt into Obsidian comments and callout aliases without changing generic Markdown behavior.

The renderer protects code and formulas before parsing, normalizes headings and block markers, sanitizes through a caller-provided function, and exposes indexed tokens for source-to-rendered mapping. Reference creation checks the rendered result after each source edit. It keeps a marker only when the intended block receives the ID and other blocks keep their identity.

References: packages/…/markdown_renderer.ts• L158-205 packages/…/markdown_renderer.ts• L793-886 packages/…/markdown_renderer.ts• L892-1048 packages/…/markdown.ts• L9-30

Content embeds

Content embeds show a note, a note block, or an attachment inside another note. Commons defines the saved target shape, display size, link fallback, nesting rules, and cycle guard so the editor, read-only renderer, share renderer, import, and export agree on what an embed means.

An embed can expand content, show a compact row, or become a reference link. Nested expansion tracks only the current path, so the same note can appear in sibling branches while a true cycle becomes a link instead of an endless render.

References: packages/…/content_embeds.ts• L8-37 packages/…/content_embeds.ts• L67-123 packages/…/content_embeds.ts• L179-229 packages/…/markdown.ts• L482-502

Tree placement and deletion

The tree uses branches for placement and notes for identity. Move, clone, delete, restore, and sort actions operate on that distinction. Deleting one branch can leave a cloned note alive under another parent.

Deletion is soft by default and can later erase records and blobs. Restore can use a fallback parent when the original parent is gone. A delete preview reports both the notes affected and relations that may break.

References: packages/…/notes.ts• L190-236 packages/…/notes.ts• L320-379 packages/…/notes.ts• L382-455

Virtual notes

Virtual notes let an application-owned provider expose a read-only subtree through the same note view as saved notes. They support common reads and links without becoming user data.

Core keeps virtual IDs in provider namespaces and prevents them from replacing persisted records. Virtual notes cannot receive normal content, revision, or protection writes.

References: packages/…/notes.ts• L465-475 packages/…/notes.ts• L181-187 packages/…/bnote.ts• L234-275

Metadata and application state

Options

Options provide one key-value contract for preferences and application state. Commons defines the option names and value types. Core stores values and records whether each value belongs to the shared knowledge base or to one device.

The options API exposes readable values, masks secrets, and allows writes only for an explicit set of names. Batch updates stay transactional. A locale update also changes the active language after the stored values are committed. Read-only values can describe host configuration, such as the effective sync address or security settings, without becoming database options.

References: packages/…/options_interface.ts• L62-102 packages/…/options_interface.ts• L193-235 packages/…/options.ts• L16-28 packages/…/options.ts• L189-280

Option initialization

New-database setup separates local defaults from synced defaults. Local settings can be created for both a new database and an empty database that will receive a sync pull. Synced defaults are created only for a genuinely new document, so a fresh device does not overwrite values from the source database.

The same initialization rules cover transcription, model providers, model resources, image handling, OCR, permission mode, and MCP access. Missing options are filled at startup without replacing existing values. The declared sync flag is reused when a missing known option is created later.

References: packages/…/options_init.ts• L16-107 packages/…/options_init.ts• L131-191 packages/…/options_init.ts• L387-465

Bootstrap metadata

Bootstrap data gives the first client render the state it needs before normal API calls begin. It describes setup state, theme and font resources, icon resources, locale, protected-session availability, and initial change markers.

An uninitialized database receives a small setup payload. An initialized database receives stored options and user theme, font, icon, and change information. Safe mode withholds custom theme URLs.

References: packages/…/bootstrap_utils.ts• L19-108 packages/…/server_api.ts• L1355-1430

Server response contracts

Commons defines the records returned by core routes. These types keep client views aligned with core without exposing private entity objects.

The contracts distinguish states that have different product meaning. Search separates matching IDs from lazy result details. Space usage separates live, deleted, unused, and revision content. Setup separates a first run, an interrupted sync, an existing database, and an authentication gate. Image work reports both what it visited and why each item changed or stayed untouched. Revision responses report whether a draft was kept and whether it can be restored.

References: packages/…/server_api.ts• L26-61 packages/…/server_api.ts• L647-747 packages/…/server_api.ts• L778-1002 packages/…/server_api.ts• L1355-1430

Model, resource, and transcript contracts

Model chat

Commons defines the model-chat protocol shared by clients and providers. Messages can contain text, images, native files, text attachments, and note context. The stream contract carries text, reasoning, tool calls, approvals, citations, usage, errors, and completion.

Core resolves attachment IDs to bytes only when a provider needs them. Models that do not accept a file kind receive a clear attachment placeholder instead. The client can approve a tool call for one call or for the rest of the chat.

References: packages/…/llm_api.ts• L7-60 packages/…/llm_api.ts• L85-133 packages/…/llm_api.ts• L204-308 packages/…/base_provider.ts• L98-143

Model provider discovery

Provider discovery gives the setup screen a current model list without requiring a saved provider configuration. Core can use live endpoint data and enrich it with shared pricing, context, and capability metadata. A successful list is cached and concurrent requests share one lookup.

Self-hosted providers use the same chat contract as OpenAI-compatible endpoints. Named local runtimes can expose richer native model data, while generic endpoints use their model list. The pricing table is supplemental metadata; a missing model entry must not change whether the provider can be used.

References: packages/…/llm.ts• L25-63 packages/…/base_provider.ts• L53-95 packages/…/local.ts• L119-205 packages/…/model_prices.json• L1-20

Model network boundary

Model calls use the host request provider instead of the global fetch function. This lets the host apply its network policy while still allowing local model servers, which are a supported product use case.

Model listing failures keep their cause. Invalid credentials, unreachable endpoints, and invalid response shapes reach the setup screen as useful errors instead of silently becoming an empty or default list.

References: packages/…/fetch.ts• L1-40 packages/…/base_provider.ts• L243-295 packages/…/local.ts• L209-261

Model stream flow

The chat stream separates request lifetime from completion lifetime. The client starts a stream with its own ID, core returns at once, and the completion publishes shared chunks until it sends a final end message. This supports both server-sent events and transports that carry chunks over the shared message channel.

Tool approval and abort requests address the running turn by its stream ID. Every failure still produces an error chunk and an end marker, so clients can release their waiting state.

sequenceDiagram
    participant Client
    participant Core as Core route
    participant Provider as Model provider
    participant Events as Shared message channel
    Client->>Core: Start stream with streamId
    Core-->>Client: Immediate acknowledgement
    Core->>Provider: Run completion
    Provider-->>Core: Stream chunks
    Core->>Events: llm-stream chunks
    Events-->>Client: Text, tools, usage, or error
    Client->>Core: Tool approval or abort
    Core->>Events: llm-stream-end
    Events-->>Client: Completion end

References: packages/…/llm.ts• L91-188 packages/…/index.ts• L261-269

Web search and page reading

Web search is an optional model tool backed by a configured search provider. It returns normalized titles, URLs, and snippets. A second page-reading tool fetches a public HTML or text page and returns a bounded Markdown view.

Search errors tell the model whether the user must fix provider settings or whether it can continue by reading a known page. Page reads reject local and private network targets and cap both response bytes and returned text.

References: packages/…/web_search.ts• L18-73 packages/…/web_search.ts• L75-145 packages/…/web_search.ts• L154-206

Resource contracts

Resources are large runtime files that do not ship inside the application. A resource has a stable ID, source and license metadata, expected size, and verification state. Clients request resources by ID and receive installation state without passing private file paths through ordinary product APIs.

The shared task contract reports active downloads, partial progress, cancellation, failure, and success. This supports model and transcription resources while keeping download progress consistent across HTTP, WebSocket, and desktop surfaces.

References: packages/…/resources.ts• L1-37 packages/…/resources.ts• L39-91 packages/…/ws_api.ts• L220-237

Transcript contracts

Meeting transcription stores a versioned JSON transcript as a managed attachment. Each utterance carries its source, time offset, optional duration, optional speaker, and text. Speaker names are separate so a rename does not rewrite every utterance.

The desktop state contract covers support, idle and recording phases, pending sources, source issues, start time, errors, and audio levels. Audio stays in the main process while the renderer starts, stops, and observes the recording. The selected recognition model maps to the resource IDs that the recording needs.

References: packages/…/transcript.ts• L5-114 packages/…/electron_api_interface.ts• L793-884 packages/…/options_interface.ts• L218-235

Table of contents

The table-of-contents contract gives notes and file-like attachments stable heading targets. Commons defines normalized heading data, cache shape, heading IDs, format selection, size limits, and link parameters. Core reads PDF, DOCX, ODT, and EPUB outlines when the host can do so, or accepts a viewer-built cache when it cannot.

Heading IDs are derived from the heading path and sibling order. Ambiguous or cut outlines bind IDs to the document blob, and protected content carries a protected marker. Core stores a cache against the document blob. A changed blob makes the cache stale, so a link or preview never silently uses headings from older content.

flowchart LR
    Document[Note or file attachment] --> Reader[Format reader or viewer]
    Reader --> Outline[Normalized headings and targets]
    Outline --> Cache[Blob-bound ToC cache]
    Cache --> Links[Reference lists and links]
    Cache --> Preview[Marked document preview]

References: packages/…/toc.ts• L4-20 packages/…/toc.ts• L59-166 packages/…/index.ts• L23-85 packages/…/toc.ts• L10-62

Errors and host boundaries

HTTP error classes

Core errors give route handlers one shared way to describe expected request failures. The status and name tell a caller whether it must change input, request access, find another resource, or resolve a state conflict.

Error contractStatusCaller meaning
ValidationError400The request does not meet input rules.
ForbiddenError403The request is understood but access is not allowed.
NotFoundError404The named resource is not available.
ConflictError409The request conflicts with current state.
GoneError410The resource existed but is no longer available.

Routes also use shared response helpers for common boundary states. A missing document or unavailable protected content can become an explicit unavailable result, while detailed conflicts preserve the reason needed for a client to recover.

References: packages/…/errors.ts• L1-72 packages/…/helpers.ts• L12-48 packages/…/toc.ts• L10-37 packages/…/index.ts• L104-135

Content delivery boundary

Core serves note and attachment bytes through a boundary that checks protection state and an optional expected blob ID. The blob check stops a viewer from displaying bytes that changed after it requested them.

Inline content follows a safer path than downloads. SVG content is sanitized and sent with a content security policy and nosniff; downloaded files keep their stored bytes and use attachment disposition. The public share boundary applies the same protected-content rule and exposes filtered note and attachment projections rather than private entity state.

References: packages/…/helpers.ts• L51-123 packages/…/handlers.ts• L154-195 packages/…/handlers.ts• L584-718 packages/…/snote.ts• L514-529

Native bridge

The Electron bridge gives the renderer a narrow typed surface for native work. It covers window and OS actions, clipboard and shell access, printing, navigation, setup, backup protection, import and export, messaging, and transcription.

Privileged work stays in the main process. Native file import gives the renderer short-lived capability tokens instead of paths. Native subtree export streams large archives to disk. Backup passphrases are write-only through the bridge and remain in the OS keyring.

References: packages/…/electron_api_interface.ts• L257-384 packages/…/electron_api_interface.ts• L646-733 packages/…/electron_api_interface.ts• L580-624 packages/…/electron_api_interface.ts• L886-932

Live messages

The shared message contract is the event language for open clients. It carries entity updates, task progress, setup and protected-session state, sync state, model stream chunks, resource work, and error notices.

Core depends on a messaging provider rather than on one transport. The server can use WebSocket, desktop can use IPC, and standalone can use a worker channel while keeping event meaning stable.

References: packages/…/llm.ts• L150-188 packages/…/index.ts• L261-269 packages/…/ws_api.ts• L1-12 packages/…/electron_api_interface.ts• L500-521

Execution context

The execution context carries request-local state across core services. It identifies the client component, hoisted note, migration or import mode, event policy, and entity changes that the current operation produces.

Asynchronous work starts a context of its own when it runs after the original request. This keeps delayed image writes, downloads, and imports connected to the right change and prevents background work from inheriting a stale client identity.

References: packages/…/context.ts• L1-18 packages/…/context.ts• L36-105 packages/…/context.ts• L107-130 packages/…/image.ts• L95-165

Security controls

Backend scripting, the SQL console, and desktop LAN access are security controls rather than ordinary database options. Their values live outside the database so a script that can write rows cannot grant itself more power.

Secret options are writable but are not returned. The client receives only a presence flag. Native confirmation and restart rules protect controls that change process or network access.

References: packages/…/options_interface.ts• L193-205 packages/…/options.ts• L182-216 packages/…/electron_api_interface.ts• L563-578

Shared utilities and consumer flow

Shared vocabulary

Commons keeps note types, MIME rules, attachment roles, block references, embeds, locales, task states, sort criteria, and content terms in shared modules. Editors, routes, imports, exports, and clients use these values to describe the same product behavior.

The core services use the same vocabulary when they scan links, classify content, build bootstrap data, convert notes, build document outlines, or turn note records into public response objects. This reduces drift between stored state and its presentation.

References: packages/…/notes.ts• L339-417 packages/…/mime_type.ts• L19-39 packages/…/attachment_roles.ts• L140-182 packages/…/index.ts• L63-91

Archive import

Archive import maps an external tree into the note and attachment model. It can restore exported IDs, create new IDs for ordinary imports, preserve branches and attributes, rewrite internal note and attachment links, and convert supported source formats into editable notes.

The importer separates archive reading from durable writes. It gathers enough metadata to resolve parents and IDs, prepares conversions such as spreadsheets or Markdown, then saves ordered batches and post-processes links and attachments. Safe import limits relations that can point outside the archive.

References: packages/…/zip.ts• L62-203 packages/…/zip.ts• L672-845 packages/…/zip.ts• L881-1045

Contract flow

When a product action crosses a workspace boundary, data moves through shared contracts rather than private shapes. A client or host sends a request. Core validates and applies the domain rule. The consumer receives a typed response and may receive a live event for the new state.

sequenceDiagram
    participant User as Client or host
    participant Boundary as HTTP, IPC, or worker
    participant Core as Trilium Core
    participant Store as Durable state
    participant Events as Shared event channel
    User->>Boundary: Shared request
    Boundary->>Core: Domain operation
    Core->>Store: Read or write state
    Store-->>Core: Result and changed entities
    Core-->>Boundary: Shared response or error
    Core->>Events: Entity or task event
    Events-->>User: State refresh

References: packages/…/index.ts• L91-125 packages/…/notes.ts• L108-145 packages/…/toc.ts• L10-43

Page relationships

The shared foundations page places core and commons in the wider workspace foundation. The editing, rendering, and presentation packages page describes the user-facing consumers of note, Markdown, and content rules. The server platform page describes a host that supplies the HTTP boundary and platform services.

References: packages/…/index.ts• L38-68 packages/…/index.ts• L197-264

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep commons records, server responses, route handlers, stream unions, resource events, and client state aligned when a shared field changes.
  • Keep note identity separate from branch placement when changing tree, clone, ordering, deletion, restore, or sync behavior.
  • Keep attachment role traits aligned with blob ownership, foreign-attachment copying, preview links, generated pictures, transcript storage, ToC caches, and cleanup.
  • Keep reference target order, block IDs, bookmark names, ToC heading IDs, blob checks, conflict behavior, and provider registration aligned.
  • Keep block-key collection, Markdown source positions, rendered block identity, DOM slicing, list numbering, and editable-run rules aligned between commons, routes, imports, exports, and editors.
  • Keep option type, write allowlist, secret masking, sync scope, local defaults, and new-database defaults aligned.
  • Keep bootstrap setup state, theme URLs, font CSS, icon registry data, and first-render preload data aligned.
  • Keep model message parts, attachment resolution, provider listing metadata, local endpoint rules, resource requirements, and stream chunks aligned.
  • Keep stream IDs, abort behavior, tool approval scope, error chunks, end markers, and transport adapters aligned.
  • Keep native bridge methods aligned between commons, preload, main-process validation, and renderer callers. File imports must use user-selected capabilities rather than renderer paths.
  • Keep transcript versioning, source issues, speaker keys, recording storage, selected model resources, and transcription options aligned.
  • Keep ToC reader versions, cache blob hashes, format-specific heading fields, preview marks, and reference link parameters aligned.
  • Keep image completion barriers, remote URL checks, image role names, compression settings, and attachment rewrite timing aligned.
  • Keep share projections, credential checks, hidden-tree rules, protected-content checks, and raw-content headers aligned.

Important failure modes

TriggerConsequenceGuard
A shared response, option, resource state, or event changes without all producers and consumers changing.A client or transport reads incomplete or incorrect state.Treat commons records and unions as boundary contracts.
A note and branch are treated as one object.A clone, move, delete, or restore changes the wrong placement or content.Keep note identity separate from branch placement.
A role loses its embedded, derived, or copied-as meaning.A file is cleaned up too early, rebuilt at the wrong time, or shown as the wrong kind of attachment.Read attachment behavior from the central role traits.
Content keeps a foreign attachment ID after a copy or cut.Images or files break when the source attachment is cleaned up.Scan content and copy or reuse an attachment owned by the receiving note.
An image URL is returned before asynchronous processing writes its bytes.A newly inserted image loads as an empty or broken attachment.Await the entity-specific image write before handing the URL to a client.
Remote image content is trusted from its URL or downloaded over a non-HTTP scheme.A page or error response becomes stored as an image, or a request reaches an unintended local target.Allow only HTTP(S) and inspect the returned bytes before storing them.
A block marker is placed without checking the rendered result.A link points to another block or a format conversion loses the target.Re-index the source and require the intended block and its neighbors to remain stable.
A block range is parsed as valid but cannot form an editable run.A focused edit can remove unrelated structure or return misleading content.Require both endpoints and valid container edges before editing.
A reference or ToC request uses a stale blob or ambiguous heading.Core writes the wrong link or exposes a stale target.Compare the listed blob with the live blob and return a conflict when it changed.
A ToC cache keeps a reader version or blob hash from older content.A document preview and its links use outdated headings or destinations.Rebuild or request a viewer cache when the format reader or document changes.
A fresh sync database receives synced defaults as local writes.The new device can overwrite shared settings before the first pull.Create sync defaults only for a genuinely new document.
A provider listing failure is treated as an empty list.The setup screen hides a bad credential or unreachable endpoint.Preserve network, authentication, and response-shape errors.
A model stream fails without an end marker.The client waits forever for a turn that has already stopped.Send an error chunk and llm-stream-end in the final path.
A web page tool follows a private or oversized target.The model can reach internal services or consume excess memory.Validate public HTTP(S) targets and enforce byte and text limits.
An archive rewrites IDs without checking rendered Markdown candidates.IDs in code or comments change, or links point to the wrong imported entity.Map only candidates that the shared renderer proves are active attributes or links.
A renderer supplies an arbitrary native path or backup secret.A compromised script can access unintended files or exfiltrate a passphrase.Use main-process validation, capability tokens, and write-only keyring access.
Protected note or attachment text is returned without a protected session or share check.Locked content becomes visible through a read, search, model, reference, or transcript path.Apply content availability checks to source bytes and derived text.
A virtual provider reuses a persisted ID.Provider content can replace saved data in the shared note view.Validate provider namespaces and let persisted rows win conflicts.

Key files

FileWhy to read it
packages/…/index.tsShows the public shared contract surface and its deliberate subpath boundaries.
packages/…/rows.tsDefines the shared note, branch, attribute, attachment, revision, blob, and option records.
packages/…/server_api.tsDefines route response shapes for notes, references, ToC state, search, setup, usage, media work, images, and revisions.
packages/…/options_interface.tsDefines typed application state and the local-versus-synced option vocabulary.
packages/…/attachment_roles.tsDefines attachment ownership, cleanup, derivation, copy, and display rules.
packages/…/block_reference.tsDefines block links, range resolution, slicing, and editable boundaries.
packages/…/block_keys.tsDefines shared block identity and format-change reports.
packages/…/markdown_renderer.tsDefines the common Markdown-to-HTML contract used by server and client consumers.
packages/…/markdown_block_index.tsMaps Markdown source lines and markers to rendered blocks.
packages/…/markdown_references.tsDefines safe heading reference placement and block-ID replay for Markdown.
packages/…/content_embeds.tsDefines embed targets, sizes, nesting, cycle handling, and link fallbacks.
packages/…/toc.tsDefines normalized table-of-contents caches, heading IDs, and document limits.
packages/…/resources.tsDefines resource identity, verification, installation, and download progress.
packages/…/transcript.tsDefines transcript storage, speaker keys, models, and resource requirements.
packages/…/electron_api_interface.tsDefines the typed desktop bridge and native capability boundaries.
packages/…/index.tsShows core's host-provided initialization and public exports.
packages/…/index.tsShows the shared API surface and host-supplied route guards.
packages/…/helpers.tsShows common unavailable, conflict, protected-content, and safe-delivery responses.
packages/…/bnote.tsShows note identity, lazy content, attributes, attachments, revisions, and protection state.
packages/…/notes.tsShows note creation, content scanning, attachment ownership, image links, and protection behavior.
packages/…/revisions.tsShows revision listing, restoration, draft preservation, and retention controls.
packages/…/notes.tsShows note metadata, block editing, references, deletion, restore, and creation routes.
packages/…/image.tsShows asynchronous image writes and their completion barriers.
packages/…/image_download.tsShows remote and inline image localization into note-owned attachments.
packages/…/index.tsDefines the provider model for targets inside note and attachment content.
packages/…/index.tsCoordinates format readers, blob-bound caches, viewer fallbacks, and ToC responses.
packages/…/toc.tsShows the note and attachment ToC API boundary.
packages/…/zip.tsShows archive ID mapping, format conversion, link rewriting, batching, and safe import.
packages/…/options_init.tsDefines local and synced defaults for new and existing databases.
packages/…/context.tsDefines request-local state and the boundary for delayed work.
packages/…/bootstrap_utils.tsBuilds setup, theme, font, icon, and change metadata for the first client render.
packages/…/options.tsShows option read, write, secret masking, and host-derived state rules.
packages/…/llm.tsShows model discovery, detached streaming, abort, and tool approval boundaries.
packages/…/base_provider.tsShows shared provider model metadata, attachment mapping, tools, and stream setup.
packages/…/model_prices.jsonShows the supplemental provider and model price and context metadata.
packages/…/local.tsShows the local-runtime and OpenAI-compatible provider boundary.
packages/…/fetch.tsShows the request-provider boundary for model network calls.
packages/…/web_search.tsShows normalized search results, public page reads, and fetch limits.
packages/…/handlers.tsShows public share routing, access checks, filtered content, and safe media delivery.
packages/…/snote.tsShows the share-side note projection and inherited metadata rules.