diff --git a/.gitignore b/.gitignore
index 6f518ec..89b869f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,7 @@ node_modules/
dist/
.astro/
.sources/
+/content/.mdbase/
.DS_Store
diff --git a/DESIGN.md b/DESIGN.md
deleted file mode 100644
index bcd99d8..0000000
--- a/DESIGN.md
+++ /dev/null
@@ -1,83 +0,0 @@
----
-name: mdbase.dev
-description: Product and developer documentation for the mdbase ecosystem.
-colors:
- paper: "oklch(99.5% 0.002 255)"
- paper-soft: "oklch(97.5% 0.004 255)"
- ink: "oklch(21% 0.018 255)"
- ink-soft: "oklch(39% 0.014 255)"
- line: "oklch(92% 0.006 255)"
- accent: "oklch(45% 0.105 238)"
-typography:
- display: "Atkinson Hyperlegible"
- body: "Atkinson Hyperlegible"
- utility: "Azeret Mono"
-rounded:
- default: "4px"
----
-
-# Design System: mdbase.dev
-
-## Direction
-
-mdbase is understated. Pages sit on **Silver sky**: a pale blue-grey canvas
-(`oklch(97% 0.009 245)`, dark `oklch(20.5% 0.018 245)`) with soft cloud and fine
-grain. Text stays on clean canvas; the sky lives at the edges and never sits
-under body copy. Fine rules, plain language and small structural labels carry
-the hierarchy.
-
-Colour roles come from `mdbase-connect/packages/ui/styles.css` and are
-synchronised by the build. The site overrides only the canvas, in
-`src/styles/global.css` and `src/styles/home.css`.
-
-The mark is the square-bar icon (`src/components/BrandMark.astro`). It sits
-beside the wordmark in the header, and a hover ripple runs through the bars in
-reading order, matching the apps. The favicon and the social card
-(`public/og-card.jpg`, 1200×630) use the same mark.
-
-The homepage pairs a moving sky (`public/mdbase-atmosphere.js`) with one field
-of 361 record particles (`public/mdbase-murmuration.js`). The field begins as a
-murmuration and becomes concrete diagrams as the reader scrolls: files, apps,
-sync, apps reaching the collection through mdbase, permissions, and sharing.
-Canvas surfaces, labels, edges and particles use the page's colour roles.
-Dashed boxes mark copies that are offline, switched off or removed; they keep a solid surface so
-they read against the sky.
-
-## Typography
-
-Atkinson Hyperlegible is the reading and display face. Azeret Mono is reserved
-for paths, package names, versions, operations, and structural labels, with
-ligatures off so code shows every character as typed. Page titles are large
-and regular (about 2.4rem); section headings are 1.3rem semibold; body text is
-17px. Paragraphs keep to about 75 characters a line (`34em`), and no text
-that carries meaning is set below 12px.
-
-## Layout
-
-The homepage has long chapters in a left reading column, a fixed canvas on the
-right. On narrow screens, the canvas moves above each chapter. Interior pages open with a
-visible title and lede (`.page-intro`) under a still band of sky at the top
-right; documentation pages keep their three-column layout. Navigation, buttons,
-tables, callouts, and footer links remain visually quiet.
-
-The header is the same on every page: the wordmark (the link home), then
-Search, the theme control and a boxed "Sign up" on one row, and the five
-section links on a ruled row below. The current section is not underlined
-and carries a short bar on the lower rule. Below 28rem the section links fold behind a "Menu" button. Header
-controls keep a 44px-high target.
-
-## Motion
-
-Only the homepage moves: the sky drifts and the particle field explains the
-current chapter. A "Pause motion" control stops both. Reduced-motion
-preferences stop the sky and place particles directly into each formation.
-The header mark's hover ripple is the only motion on interior pages, and it
-also respects reduced motion.
-
-## Language
-
-Use literal headings and ordinary sentences. State the current artifact,
-profile, security boundary, or release status directly. Avoid slogans,
-competitive framing, and language that comments on how candid or precise the
-site itself is. Avoid correlative contrast constructions such as “not X, but
-Y,” “without X,” and “rather than X.” State the relevant behavior directly.
diff --git a/PRODUCT.md b/PRODUCT.md
index d291688..ec60564 100644
--- a/PRODUCT.md
+++ b/PRODUCT.md
@@ -37,6 +37,14 @@ about data ownership, and repetitive card grids. Do not imply that Connect is
the mdbase specification, that TaskNotes owns the ecosystem, or that hosted
collections are zero-knowledge.
+## Language
+
+Use literal headings and ordinary sentences. State the current artifact,
+profile, security boundary, or release status directly. Avoid slogans,
+competitive framing, and language that comments on how candid or precise the
+site itself is. Avoid correlative contrast constructions such as “not X, but
+Y,” “without X,” and “rather than X.” State the relevant behavior directly.
+
## Design Principles
- Show a real collection and its routes before making abstract claims.
diff --git a/astro.config.mjs b/astro.config.mjs
index 96fcbf7..f7c4f12 100644
--- a/astro.config.mjs
+++ b/astro.config.mjs
@@ -1,5 +1,7 @@
import { defineConfig } from "astro/config";
import sitemap from "@astrojs/sitemap";
+import { satteri } from "@astrojs/markdown-satteri";
+import { codeFigures, codeTitle, includeFiles, recordings } from "./src/markdown/doc-records.mjs";
const site = process.env.MDBASE_SITE_ORIGIN ?? "https://mdbase.dev";
@@ -11,5 +13,19 @@ export default defineConfig({
integrations: [sitemap()],
build: {
format: "directory"
+ },
+ // The documentation records in content/ (see src/content.config.ts).
+ markdown: {
+ processor: satteri({
+ // Text is kept as written: no curly quotes or dashes added.
+ features: { headingAttributes: true, smartPunctuation: false },
+ mdastPlugins: [includeFiles, recordings],
+ hastPlugins: [codeFigures]
+ }),
+ shikiConfig: {
+ // Colours come from the --syntax-* roles in global.css.
+ theme: "css-variables",
+ transformers: [codeTitle]
+ }
}
});
diff --git a/content/_types/doc-page.md b/content/_types/doc-page.md
new file mode 100644
index 0000000..bac1007
--- /dev/null
+++ b/content/_types/doc-page.md
@@ -0,0 +1,47 @@
+---
+kind: mdbase.type
+name: doc-page
+version: 1
+description: One page of the documentation on mdbase.dev.
+match:
+ path_glob: "**/*.md"
+schema:
+ dialect: json-schema-2020-12
+ value:
+ $schema: "https://json-schema.org/draft/2020-12/schema"
+ type: object
+ additionalProperties: false
+ required: [title, description, section]
+ properties:
+ title:
+ type: string
+ minLength: 1
+ description:
+ type: string
+ minLength: 1
+ section:
+ enum: [sdk, mcp, editor, reader, writer]
+collection:
+ display:
+ name_field: title
+---
+
+# Documentation page
+
+Each record is one page of the documentation on mdbase.dev. The site serves
+`sdk/react.md` at `/sdk/react/`, and a folder's `index.md` at the folder's own
+address, so `apps/reader/index.md` is `/apps/reader/`.
+
+`title` is the page's heading and `description` the sentence under it.
+`section` is the documentation set the page belongs to, which picks its
+sidebar.
+
+The body is ordinary Markdown with three additions the site understands:
+
+- A heading can keep a fixed anchor: `## Saved views {#views}`.
+- A code block can name its file: ` ```ts title="src/mdbase.ts" `. With
+ `file="examples/worklog/src/mdbase.ts"` it shows that file from the site's
+ repository instead of its own contents; `pick="scripts"` keeps one key of a
+ JSON file.
+- An image whose address is a recording in `/videos/` is shown as that
+ recording, with its captions and text description.
diff --git a/content/apps/editor/index.md b/content/apps/editor/index.md
new file mode 100644
index 0000000..1af9602
--- /dev/null
+++ b/content/apps/editor/index.md
@@ -0,0 +1,42 @@
+---
+title: Get started
+description: "mdbase Editor is a browser editor for a whole mdbase collection: notes, frontmatter, links and types."
+section: editor
+---
+
+## What it is {#what}
+
+mdbase Editor opens one mdbase collection and shows every record as a note. It edits the Markdown files in place. Paths, frontmatter and type definitions stay as ordinary files that other tools, such as a text editor, Obsidian or an AI client, can keep using.
+
+It works with Cloud copy and Private collections. A Cloud copy collection opens whenever you are online. The Editor reaches a Private collection through one of your devices, so one of them must be online, such as a computer running the [desktop app](/downloads/).
+
+## Open a collection {#open}
+
+1. Go to [editor.mdbase.dev](https://editor.mdbase.dev/).
+2. Sign in to mdbase Connect. If you do not have an account, [sign up](https://connect.mdbase.dev/signup) first.
+3. Choose a collection.
+4. Approve the Editor's access to that one collection. Reading is required. Creating, editing and deleting notes, managing types and adding files are optional, and you can turn each one off. The Editor is read-only for anything you do not approve.
+
+The Editor opens mdbase 0.3 collections. For an older collection, upgrade a copy with mdbase, check the copy, and then open it. Your original files can stay untouched while you check the result.
+
+## Find your way around {#layout}
+
+| Area | What it holds |
+| --- | --- |
+| Collection rail | Switches between All notes, Types and Settings, filters notes by folder, tag or type, shows the connection status and opens the Connect workspace. |
+| Note list | The notes, and attached files, in the current filter. Sort by modified date, title or path from view options. |
+| Editor | The note's Markdown body, with the title, properties and backlinks around it. |
+
+Press CtrlP (⌘P on a Mac) to open any note by name, and ? to see the main shortcuts. On a phone, each level of navigation is a separate screen.
+
+## Connection status {#status}
+
+The rail shows whether the collection is connected or reconnecting. A Private collection can only be read and saved while one of your devices is online to serve it.
+
+## Switch collections {#switch}
+
+Open the collection switcher from the rail. It lists collections you opened before in this browser, and **Connect another collection** starts a new approval. **Forget from this browser** in Settings removes a collection from the Editor without changing its files.
+
+## The Connect workspace {#connect}
+
+[editor.mdbase.dev/connect](https://editor.mdbase.dev/connect) is where you manage your mdbase Connect account: collections, storage and sync, sharing, connected applications, devices, sign-in methods and browser sessions. It uses your account session, not a collection grant, so it can list your collections but cannot read their contents.
diff --git a/content/apps/editor/links.md b/content/apps/editor/links.md
new file mode 100644
index 0000000..f4e92dd
--- /dev/null
+++ b/content/apps/editor/links.md
@@ -0,0 +1,44 @@
+---
+title: Links, embeds and files
+description: Connect notes to each other, include one note inside another, and attach files.
+section: editor
+---
+
+## Link to a note {#links}
+
+Type [[ and start typing a title or path. The Editor suggests notes and files from the collection and completes the link:
+
+```markdown title="note.md"
+[[projects/alpha]]
+[[projects/alpha|Project Alpha]]
+[[projects/alpha#Goals]]
+[[projects/alpha#^decision-1]]
+```
+
+After a note name, type # to link to one of its headings, or #^ to link to a block. Links are stored as ordinary Markdown wikilinks, so other mdbase tools and Obsidian read them the same way. Links that do not resolve to a note are marked as you write.
+
+## Link with @ {#mentions}
+
+Typing @ at the start of a line, after a space or after an opening bracket opens the same suggestions and inserts a `[[wikilink]]`. To limit suggestions to one type, type @/, choose the type, and continue typing. For example, `@/person/sam` suggests only records of the `person` type that match "sam".
+
+## Embed a note or file {#embeds}
+
+Add ! before a link to show its content inside the current note. You can embed a whole note, a section or block of it (`#^id`), or a file:
+
+```markdown title="note.md"
+![[meeting-notes#Decisions]]
+![[Attachments/diagram.png]]
+![[Attachments/contract.pdf]]
+```
+
+The embedded content is read from the other file each time, so it stays up to date. The Editor tells you when an embed points to a missing note or heading, matches more than one note, or would include itself.
+
+## Backlinks
+
+**Backlinks** lists every note that links to the one you are reading. The button in the note header shows how many there are.
+
+## Attach files {#attachments}
+
+Choose **Attach file…** from the note's action menu. Each file is uploaded to an `Attachments` folder next to the note, and an embed or link to each file is added to the note. You can choose several files at once. An existing file with the same name is never replaced. The new file gets a numbered name instead. Images, PDFs, audio, video and text files preview in the Editor. Other files show their name and path and are stored as they are, for other tools to open.
+
+If the Editor's approval does not include file access, the menu shows **Request attachment access** instead, which asks you to approve it in Connect.
diff --git a/content/apps/editor/notes.md b/content/apps/editor/notes.md
new file mode 100644
index 0000000..b3c3aff
--- /dev/null
+++ b/content/apps/editor/notes.md
@@ -0,0 +1,58 @@
+---
+title: Writing notes
+description: Create, edit, find and organise the Markdown records in a collection.
+section: editor
+---
+
+## Create a note {#create}
+
+Choose **New note** or press CtrlShiftN. A note is not written to the collection until you create it, so you can fill in everything first:
+
+- **Type.** Pick one of the collection's types, or **General note** for a note without a type.
+- **Required properties.** The fields the type requires are shown up front. Nested objects and lists follow the type's schema.
+- **Path.** The Editor suggests where the file will live. Edit it to choose another folder or file name. A new folder appears once its first note is created.
+
+Press CtrlEnter to create the note.
+
+## Write
+
+The body is plain Markdown. Changes save automatically. Type / at the start of a line for Markdown commands such as headings, lists, tasks, quotes, code blocks, tables and links.
+
+CtrlB and CtrlI set bold and italic, CtrlShiftC sets inline code, CtrlK adds a link, and pasting a URL over selected text turns it into a link. Tab and ShiftTab indent and outdent list items.
+
+**Quiet Markdown**, on by default, softens Markdown punctuation away from the line you are editing and makes task checkboxes clickable. Vim key bindings can be turned on in Settings. See [Shortcuts and settings](/apps/editor/shortcuts/).
+
+## Properties
+
+Open **Note properties** to see and edit frontmatter. It has three views:
+
+| View | Shows |
+| --- | --- |
+| Fields | Structured inputs based on the note's types, including dates, links, lists and nested objects. |
+| JSON | The frontmatter stored in the file, as JSON. |
+| Source | The exact Markdown file, including YAML frontmatter and body. |
+
+## Find notes {#find}
+
+- **Quick open** (CtrlP) searches titles, paths, properties and text. Start with > to search actions instead.
+- Folders, Tags and By type in the collection rail filter the note list. Its view options sort by modified date, title or path.
+- AltJ and AltK move to the next and previous note. Alt← and Alt→ go back and forward through notes you opened.
+- CtrlF finds text within the open note.
+
+## Rename and move {#rename}
+
+Click the path in the note header to rename or move the Markdown file; the new path must end in `.md`. If other notes link to it, the Editor asks whether to **Rename and update links**, which rewrites those links, or **Rename only**. Otherwise it renames the file and updates links straight away.
+
+## Check a note {#check}
+
+**Check note**, in the note's action menu, validates the note against its types and reports any fields that do not fit. Links that do not resolve are marked in the editor as you write.
+
+## Edits made elsewhere {#conflicts}
+
+Every save checks that the file has not changed since the Editor read it. If another app, a text editor or another person changed the note, the Editor does not overwrite it. It shows **This note changed elsewhere** and lets you compare the title and body before choosing **Keep my edits** or **Use latest**.
+
+Edits that were not saved, for example because the browser closed, stay in this browser for up to seven days. Reopening the note offers **Restore unsaved edits** or **Discard recovered edits**.
+
+## Delete a note {#delete}
+
+**Delete note** is in the note's action menu. It asks for confirmation, then removes the Markdown file from the collection.
diff --git a/content/apps/editor/sharing.md b/content/apps/editor/sharing.md
new file mode 100644
index 0000000..a6355d6
--- /dev/null
+++ b/content/apps/editor/sharing.md
@@ -0,0 +1,42 @@
+---
+title: Sharing a collection
+description: Invite other people to view or edit a collection, and manage their access.
+section: editor
+---
+
+## Which collections can be shared {#which}
+
+Cloud copy and Private collections can both be shared. Sharing covers the whole collection; to share part of one, make a separate collection. Sharing is managed in the Connect workspace at [editor.mdbase.dev/connect](https://editor.mdbase.dev/connect). Open the collection and find **People & sharing**. Only the collection's owner sees it.
+
+## Roles
+
+| Role | Can |
+| --- | --- |
+| Owner | Everything, including inviting and removing people. |
+| Editor | Edit notes, manage types, rename the collection, and connect apps. |
+| Viewer | Read the collection and connect read-only apps. |
+
+Each member’s devices keep a full copy of the collection, like yours. A viewer who opens the collection in mdbase Editor sees it read-only.
+
+## Invite someone {#invite}
+
+1. Choose **Invite person**.
+2. Under **Invite using**, choose **Verified email** and enter their email address, or choose **Sharing code** and enter the code they gave you.
+3. Choose **Viewer** or **Editor**, then **Create invitation**.
+4. Copy the invitation link and send it to them yourself.
+
+Email invitations only work for someone who already has a Connect account with that email address verified. If they signed up after you created the invitation, create a new one.
+
+## Sharing codes {#code}
+
+Use a sharing code when you cannot invite someone by email, for example if they sign in with a different address. The person you are inviting creates the code on the **Account & sessions** page in the Connect workspace, under **Sharing code** → **Generate code**, and sends it to you. A code can be used once. Invitations and sharing codes expire after seven days.
+
+## Accept an invitation {#accept}
+
+Open the invitation link while signed in to the account it was created for. Connect shows **A collection was shared with you**. Choose **Accept** to add the collection to your collections, then open it in the Editor or approve other apps to use it.
+
+In a Private collection, an owner or editor approves the new member’s first device. You and the new member compare a six-digit code, in person or on a call, before that device gets the collection’s keys.
+
+## Change or remove access {#manage}
+
+In **People & sharing**, change a person's role from the list, or choose **Remove**. Removing someone also revokes their devices and the apps they connected to the collection. They keep the files they already had, but get no further changes. Invitations that have not been accepted are listed under **Pending invitations**, where you can cancel them.
diff --git a/content/apps/editor/shortcuts.md b/content/apps/editor/shortcuts.md
new file mode 100644
index 0000000..9a713ab
--- /dev/null
+++ b/content/apps/editor/shortcuts.md
@@ -0,0 +1,47 @@
+---
+title: Shortcuts and settings
+description: Keyboard shortcuts and the preferences you can change in mdbase Editor.
+section: editor
+---
+
+## Keyboard shortcuts {#shortcuts}
+
+On a Mac, use ⌘ in place of Ctrl. Press ? anywhere outside a text field to see the guide in the Editor.
+
+| Keys | Action |
+| --- | --- |
+| Ctrl P | Quick open |
+| Ctrl K | Quick open, outside the note text |
+| > | Actions, typed at the start of quick open |
+| Ctrl Shift N | New note |
+| Ctrl Enter | Create the note being composed |
+| Ctrl Shift L | Show or hide the notes sidebar |
+| ↑ / ↓ | Move through the note list |
+| Alt J / Alt K | Next or previous note |
+| Alt ← / Alt → | Back or forward through opened notes |
+| Ctrl F | Find in note |
+| Ctrl B / Ctrl I | Bold or italic |
+| Ctrl Shift C | Inline code |
+| Ctrl K | Add a link, in the note text |
+| Tab / Shift Tab | Indent or outdent a list item |
+| / | Markdown commands, at the start of a line |
+| [[ | Link to a note or file |
+| @ | Link to a note, optionally filtered by type |
+| ? | Show the shortcut guide |
+| Esc | Close quick open or the shortcut guide |
+
+## Editor settings {#settings}
+
+Open **Settings** from the collection rail. These preferences are stored in this browser only.
+
+| Setting | Effect |
+| --- | --- |
+| Color theme | Follow the system appearance, or keep a light or dark theme in this browser. |
+| Text size | Compact, Comfortable or Large note text, without changing the rest of the interface. |
+| Wrap long lines | Keep Markdown within the writing width. On by default. |
+| Quiet Markdown | Soften punctuation away from the active line and make tasks checkable. On by default. |
+| Vim key bindings | Use normal, insert, visual and command modes in the note editor. Off by default. |
+
+## Collection settings {#collection}
+
+Settings also shows the open collection: its ID, the specification version it uses, its types folder, the frontmatter keys that declare a type, its validation level, and the operations the Editor is approved for. **Forget from this browser** removes the collection from the Editor without changing its files.
diff --git a/content/apps/editor/types.md b/content/apps/editor/types.md
new file mode 100644
index 0000000..3ab2e4c
--- /dev/null
+++ b/content/apps/editor/types.md
@@ -0,0 +1,52 @@
+---
+title: Types
+description: Define the shape of a collection's notes, how notes are assigned to types, and how types work with other apps.
+section: editor
+---
+
+## What a type is {#what}
+
+A type is a Markdown file in the collection's types folder. It names a kind of record, such as a task or a person, and describes its frontmatter fields with JSON Schema. The Editor uses types to build property forms, check notes, and suggest links. Other apps use the same files. The format is defined in the [mdbase specification](/spec/).
+
+Open **Types** from the collection rail to see every type. Changing types needs the collection's definition management permission, which the Editor requests when you approve it.
+
+## Create a type {#create}
+
+In the Types list, choose **Add a type**, then one of:
+
+- **New type** starts from an empty definition. Give the type a unique name and add your own fields.
+- **Ready-made types** is a catalog. Each type comes with an application contract, so apps built for that contract can use your notes. Adding one creates a new, editable type. Existing files are never overwritten. Installing one needs permission to install type packs; without it, the catalog offers to request that access.
+
+## Fields
+
+The visual editor covers the field shapes most collections need: text, numbers, dates and times, choices, links, lists, nested objects, lists of objects, and required fields. You can also set **Read defaults**, which are used when a note leaves a property out. Source files stay unchanged.
+
+Link rules say which fields point to other records, which types they may point to, and whether the target must exist. Uniqueness rules require a value to be unique within the type, across the collection, or among records that match a path pattern.
+
+Anything the visual editor cannot represent stays in the YAML source, marked where it appears. Switch to **YAML** to edit the complete definition directly.
+
+## Type membership {#membership}
+
+**Type membership** decides which notes belong to the type. A note that names a type in one of the collection's type keys (`type` or `types` by default) belongs to the types it names, and the automatic rules below are skipped. Otherwise the note belongs when every configured condition matches:
+
+| Condition | Matches when |
+| --- | --- |
+| Path | Its path matches one of the path patterns. |
+| Field presence | Its frontmatter contains all the listed fields. |
+| Expression | Each extra rule on its fields is true. These rules are edited in YAML. |
+
+Some collections turn explicit assignment off. Then every note is classified by the other rules.
+
+## Collection behaviour {#behaviour}
+
+**Collection behaviour** controls how the type appears and acts across tools: the field used as a record's name, description and colour, an icon, and a path policy. The path policy tells tools where to put new records of this type and how to name them. Changing it affects future files only. Existing files are not moved.
+
+## Works with applications {#apps}
+
+An application contract describes the fields an app expects, such as a task manager's due date and status. **Works with applications** connects a type to an installed contract and maps each contract field to one of your field names. The app reads your notes through that mapping, and your notes keep their own field names. A mapping copies values as they are. It does not convert them.
+
+The Editor suggests contracts that might fit, based on field names and shapes. Check that the meanings match before you accept a suggestion.
+
+## Review and save {#save}
+
+A type change can affect every note of that type. Before saving, the Editor shows the fields added, changed and removed, the YAML differences, and which existing notes would need attention. You can open the list of affected notes. The collection checks the complete definition when you confirm.
diff --git a/content/apps/mcp/collections.md b/content/apps/mcp/collections.md
new file mode 100644
index 0000000..a705fe9
--- /dev/null
+++ b/content/apps/mcp/collections.md
@@ -0,0 +1,53 @@
+---
+title: Collections and access
+description: How approvals work, how to add or reconnect collections, and how to take access away.
+section: mcp
+---
+
+## One approval per collection {#model}
+
+The client does not get general access to your account. Each collection is approved on its own, with its own list of operations. There is no query or write that spans collections, and no collection is used unless you approved it.
+
+## Connection IDs
+
+`list_connections` returns one entry for each approved collection:
+
+| Field | Meaning |
+| --- | --- |
+| `id` | The connection ID. Every collection tool requires it as `connection_id`. |
+| `collection_id` | The collection's ID in Connect. |
+| `display_name` | The collection name shown in Connect. |
+| `operations` | The operations you approved, such as `read`, `query` or `update`. |
+| `authority` | `local` when requests go to one of your devices, `remote` when mdbase serves them. |
+
+Connection IDs are opaque. They are not collection paths and do not reveal where the collection is stored.
+
+## Connect more collections {#more}
+
+Ask the client to connect another collection. It calls `add_connection`, which returns a link for you to open in a browser. The link can be used once and expires after ten minutes.
+
+The link opens the same Connect approval screen as the first setup. Choose the collection and its operations, approve, then ask the client to list collections again.
+
+## Reconnect or broaden access {#broaden}
+
+If a collection's approval expires, or you want to allow operations you previously left out, the client calls `reconnect_collection` with that connection ID. The returned link opens Connect on that collection only. You review and approve its operations, or decline.
+
+## Read and write access {#write}
+
+Two separate approvals control writing. The first is the MCP sign-in scope the client requests: `mdbase:read`, `mdbase:write`, or both. A client that does not ask for a specific scope gets both. The client only sees the write tools when the scope includes `mdbase:write`.
+
+The second is the set of operations you approve for each collection in Connect. This one decides what can actually happen. If you approved a collection for reading only, a write tool fails with `insufficient_collection_access`. It never expands your approval by itself. If you narrow access in Connect, calls may fail with a different code until the MCP server's sign-in next refreshes, within an hour.
+
+## Revoke access {#revoke}
+
+Open the [Applications](https://editor.mdbase.dev/connect/applications) page in the Connect workspace. The MCP server is listed as **mdbase**. You can narrow or revoke its access to each collection there. The next tool call for a revoked collection fails, and other collections keep working.
+
+Removing the server from your MCP client stops that client from using it, but does not remove the approvals held in Connect. Revoke them in Connect as well if you no longer use them.
+
+## Cloud copy and Private {#modes}
+
+Your approval travels with the collection, so every copy checks it before it answers a request. A grant you revoked is refused by your devices and by the cloud copy too.
+
+For a **Cloud copy** collection, requests go to the readable copy mdbase keeps, so tools work while your devices are off.
+
+For a **Private** collection, requests travel from the MCP server through the mdbase relay to one of your devices. They are encrypted end to end between the MCP server and that device, and the relay cannot read them. One of your devices must be online. If none is, tools return `connector_offline`. A new approval for a Private collection takes effect once one of your signed-in devices has recorded it. See [Troubleshooting](/apps/mcp/troubleshooting/).
diff --git a/content/apps/mcp/data-handling.md b/content/apps/mcp/data-handling.md
new file mode 100644
index 0000000..441e08c
--- /dev/null
+++ b/content/apps/mcp/data-handling.md
@@ -0,0 +1,39 @@
+---
+title: Data handling
+description: What the mdbase MCP server stores, what it can see while it works, and what stays with Connect.
+section: mcp
+---
+
+## Why it is a separate service {#boundary}
+
+The Connect control plane, which handles accounts and approvals, does not see collection content. Requests to a Private collection are encrypted before they reach the mdbase relay, and only your device decrypts them. A Cloud copy collection is answered by the readable copy mdbase keeps, held by a separate service that can read it to perform operations.
+
+An AI client cannot perform that encryption itself, so the MCP server does it on the client's behalf. That means the MCP server sees operation inputs and results in memory while it handles a tool call, for Cloud copy and Private collections alike. It runs as its own service, with its own database, so that this access stays outside the control plane. It is not a zero-knowledge service.
+
+## What is stored {#stored}
+
+- Client registrations (name and redirect URLs), hashes of access and refresh tokens, and short-lived sign-in state.
+- For each approved collection: its ID, display name, approved operations and contract scope.
+- The credentials the MCP server uses to reach Connect, encrypted.
+- A key pair for each connection, with the private key encrypted, and a plain message counter for each key.
+
+Expired sign-in records are not currently deleted automatically. The server does not log individual requests. Unexpected errors are logged for diagnosis.
+
+## What is not stored {#not-stored}
+
+The MCP server's database does not hold:
+
+- Record contents, including frontmatter and bodies.
+- Tool call results.
+- Record paths within a collection.
+- Filesystem paths on your computer. These are never sent to the MCP server or to Connect.
+
+## Your MCP client {#client}
+
+Whatever a tool returns goes to your MCP client and, through it, to the AI model you are using. That client's own data policies apply to it. Approve only the collections and permissions you are comfortable sharing with that client.
+
+## Your controls {#controls}
+
+- Each collection is approved separately, with its own permissions.
+- Revoking a collection on the [Applications](https://editor.mdbase.dev/connect/applications) page stops the next tool call. Every copy of the collection, on your devices or in the cloud copy, also refuses a revoked approval on its own.
+- See the [privacy notice](/privacy/) and [security page](/security/) for how mdbase handles account data in general.
diff --git a/content/apps/mcp/index.md b/content/apps/mcp/index.md
new file mode 100644
index 0000000..6daf7f7
--- /dev/null
+++ b/content/apps/mcp/index.md
@@ -0,0 +1,61 @@
+---
+title: Set up mdbase MCP
+description: Connect an AI client to the mdbase collections you approve, through one remote MCP endpoint.
+section: mcp
+---
+
+## What it does {#what}
+
+mdbase MCP is a remote Model Context Protocol server. An MCP client, such as Claude, uses it to read and change records in mdbase collections you have approved. It works the same way with Cloud copy and Private collections.
+
+The client never receives your Connect account. You approve one collection at a time, with the exact operations you want to allow, and you can revoke that approval from Connect at any time.
+
+## Before you start {#before}
+
+- An mdbase Connect account. [Sign up](https://connect.mdbase.dev/signup) if you do not have one.
+- At least one collection. A Cloud copy collection works immediately. A Private collection is reached through one of your devices, so one must be online whenever the client uses it, such as a computer running the [desktop app](/downloads/).
+- An MCP client that supports remote servers over Streamable HTTP with OAuth sign-in, including dynamic client registration and PKCE.
+
+## Add the server to your client {#add}
+
+Every client uses the same endpoint:
+
+```text title="MCP endpoint"
+https://mcp.mdbase.dev/mcp
+```
+
+In Claude on the web, desktop or mobile, open [mdbase in the Claude connectors directory](https://claude.ai/directory/connectors/mdbase) and connect it from there. You can also add the endpoint yourself as a custom connector. In Claude Code, add it from a terminal:
+
+```sh title="terminal"
+claude mcp add --transport http mdbase https://mcp.mdbase.dev/mcp
+```
+
+Other clients have their own screens for adding a remote MCP server. Give them the endpoint above. There is no API key to paste in. The client discovers the sign-in flow from the server.
+
+## Approve a collection {#approve}
+
+When the client first connects, it opens a browser window for sign-in.
+
+1. Sign in to mdbase Connect.
+2. Choose one collection.
+3. Review the permissions. **Read this collection** is required. **Create records**, **Edit records**, **Delete records** and **Manage definitions** are optional, and you can leave any of them out. They appear when the client asked for write access, which it does by default.
+4. Approve. The browser returns you to your client.
+
+Each approval covers one collection. To use more than one, ask the client to connect another collection after setup. See [Connect more collections](/apps/mcp/collections/#more).
+
+## Check the connection {#check}
+
+Ask your client something that needs the collection:
+
+```text title="prompt"
+List my mdbase collections, then describe the first one.
+```
+
+The client should call `list_connections` and then `describe_collection`. `list_connections` shows each collection's approved operations; `describe_collection` returns its types, fields and contracts.
+
+## Next steps {#next}
+
+- [Collections and access](/apps/mcp/collections/) explains how approvals, reconnecting and revocation work.
+- [Working with records](/apps/mcp/working-with-records/) covers queries, edits and safe retries.
+- [Tool reference](/apps/mcp/tools/) lists every tool and its inputs.
+- [Data handling](/apps/mcp/data-handling/) describes what the MCP server stores and what it can see.
diff --git a/content/apps/mcp/troubleshooting.md b/content/apps/mcp/troubleshooting.md
new file mode 100644
index 0000000..51b3259
--- /dev/null
+++ b/content/apps/mcp/troubleshooting.md
@@ -0,0 +1,39 @@
+---
+title: Troubleshooting
+description: What common mdbase MCP errors mean and how to recover from them.
+section: mcp
+---
+
+Failed calls return an error with a `code` and a message. Most clients show the message; ask the client for the code if it does not. Some rejections, such as conflicts and validation problems, instead return a result marked `valid: false` with diagnostics that carry the code.
+
+## Error codes {#errors}
+
+| Code | What happened | What to do |
+| --- | --- | --- |
+| `connector_offline` | No device that can serve this collection is online. Private collections are reached through one of your devices. | Start the desktop app on one of your computers and check it is online, then retry. |
+| `connector_busy` | The device serving the collection is handling other work. | Retry after a moment. |
+| `connector_upgrade_required` | The desktop app serving the collection is too old for this request. | Install the latest desktop app from [Downloads](/downloads/). |
+| `insufficient_collection_access` | You did not approve this operation for the collection. | Ask the client to reconnect the collection, then approve the extra permission. |
+| `connection_expired` | The collection's approval is no longer valid. | Ask the client to reconnect the collection. |
+| `connection_not_found` | The connection ID does not belong to this client's approvals. | Ask the client to list collections again and use a current ID. |
+| `concurrent_modification` | The record changed after the client read it. Reported as a diagnostic. | Let the client read the record again before changing it. |
+| `invalid_query` | The query does not follow the mdbase query format. | The message names the problem. The client should correct the query. |
+| `encryption_binding_stale` | Access to a collection served by one of your devices changed in Connect. | Retry later, or reconnect the collection. |
+| `generation_expired`, `query_cursor_expired` | The query cursor expired. | Run the query again. |
+| `mutation_request_conflict` | A `mutation_id` was reused for a different change. | Use a new ID, or repeat exactly the original change. |
+
+## Sign-in does not finish {#sign-in}
+
+If you closed the browser window or declined the approval, start the connection again from your client. Links from `add_connection` and `reconnect_collection` can be used once and expire after ten minutes, so ask the client for a new one if a link no longer works.
+
+## A collection is missing {#missing}
+
+The client only sees collections you approved for it. Ask it to connect another collection, or check the [Applications](https://editor.mdbase.dev/connect/applications) page in Connect to see which collections **mdbase** can use.
+
+## The client cannot write {#no-write}
+
+If the client says it has no tool to create or change records, it signed in with read-only scope. Remove the server from the client and add it again. If the tools exist but fail with `insufficient_collection_access`, reconnect the collection and approve the write permissions. See [Read and write access](/apps/mcp/collections/#write).
+
+## Self-hosted servers {#self-hosted}
+
+Running your own MCP server alongside a self-hosted Connect is covered in the [MCP gateway operator guide](https://github.com/mdbase-dev/mdbase-connect/blob/main/docs/mcp-gateway.md).
diff --git a/content/apps/mcp/working-with-records.md b/content/apps/mcp/working-with-records.md
new file mode 100644
index 0000000..4e9e8a8
--- /dev/null
+++ b/content/apps/mcp/working-with-records.md
@@ -0,0 +1,94 @@
+---
+title: Working with records
+description: How the MCP tools read, query and change records without losing concurrent edits.
+section: mcp
+---
+
+You do not need to call these tools yourself. Your MCP client chooses them. This page explains what they do, so you can tell the client what you want and understand what it did.
+
+## Start with the collection {#start}
+
+`describe_collection` returns the collection's types, their fields and its contracts. A client that reads it first can use your field names and types instead of guessing them from a few files.
+
+## Query records {#query}
+
+`query_records` uses the mdbase query format from the [specification](/spec/). `where` is an expression over record fields, `types` limits the query to declared types, and `order_by` sorts the results.
+
+```json title="query_records input"
+{
+ "connection_id": "…",
+ "types": ["task"],
+ "where": "status != \"done\" && priority >= 3",
+ "order_by": [{ "field": "due", "direction": "asc" }],
+ "limit": 20
+}
+```
+
+Record bodies are left out unless `include_body` is `true`. `frontmatter_mode` chooses between the frontmatter stored in the file (`persisted`), the values after type defaults and computed fields are applied (`effective`), or both.
+
+## Large result sets {#pages}
+
+`limit` can be at most 1,000. For large result sets, set `pagination` to `"cursor"`. Pages may be smaller than `limit`. Each page's result includes a cursor for the next page, and every page reads from the same snapshot of the collection.
+
+```json title="query_records input"
+{
+ "connection_id": "…",
+ "types": ["note"],
+ "pagination": "cursor",
+ "limit": 200
+}
+```
+
+A cursor that is no longer needed can be released with `release_query_cursor`. Unused cursors expire after a short idle period, from seconds to minutes, so continue promptly. To continue, repeat the same query with the `cursor`.
+
+## Read one record {#read}
+
+`read_record` takes a path relative to the collection root, such as `projects/alpha.md`. The result includes the frontmatter, body, the types the record belongs to, and its current `revision`.
+
+## Create and change records {#change}
+
+These tools are available when the client has write access and you approved the matching operation for the collection.
+
+| Tool | Use |
+| --- | --- |
+| `create_record` | Create a record from a type, frontmatter and body. The path can be given or left to the collection's path rules. |
+| `update_record` | Change fields with `patch` and replace the `body`, or replace the whole Markdown source with `document`. A `document` cannot be combined with the other two. |
+| `rename_record` | Move a record. Links to it are updated unless `update_refs` is `false` or the collection turns this off. |
+| `delete_record` | Delete a record. With `check_backlinks: true`, the result lists records whose links to it are now broken. |
+
+Changes are validated against every type the record belongs to. At the default validation level, an invalid change is rejected with details and nothing is written. A collection can lower its validation level in its configuration.
+
+## Revisions prevent lost edits {#revisions}
+
+Each record has a revision that changes whenever the file changes. When a client passes the revision it read as `if_revision`, the change is applied only if nobody else has changed the record since. That includes you, in another app or a text editor.
+
+```json title="update_record input"
+{
+ "connection_id": "…",
+ "path": "tasks/renew-passport.md",
+ "patch": { "status": "done" },
+ "if_revision": "…revision from read_record…"
+}
+```
+
+If the record changed in the meantime, the change is not applied. The result is marked `valid: false` with a `concurrent_modification` diagnostic. The client should read the record again and decide what to do with the newer content, rather than overwrite it.
+
+## Retrying safely {#retries}
+
+Every change returns a receipt containing a request ID:
+
+```json title="tool result"
+{
+ "mutation_receipt": {
+ "request_id": "5b0d…",
+ "retry": "Reuse this request_id as mutation_id when retrying the exact mutation."
+ },
+ "outcome": { … }
+}
+```
+
+If a call times out and the client cannot tell whether it happened, it can repeat the same change with that ID as `mutation_id`. The change is applied at most once. Reusing an ID for a different change fails with `mutation_request_conflict`.
+
+## Type definitions {#types}
+
+`read_type` returns a type definition by name or path. `create_type` and `update_type` take the complete type file as `document`. Updating a type always requires its current revision. A type change can affect every record of that type, so the **Manage definitions** permission is approved separately in Connect.
diff --git a/content/apps/reader/annotating.md b/content/apps/reader/annotating.md
new file mode 100644
index 0000000..f8d0613
--- /dev/null
+++ b/content/apps/reader/annotating.md
@@ -0,0 +1,63 @@
+---
+title: Reading and annotating
+description: Highlight passages, comment on them, capture areas of a PDF, and bookmark your place.
+section: reader
+---
+
+## Reading
+
+Reader opens PDFs, EPUBs and saved web pages. Open a document's contents from the document toolbar. **Enter reading mode** (Ctrl.) hides everything except the document. Press it again or Esc to leave.
+
+Text size, typeface and line length can be changed from **Text and display** in the header. These apply to EPUBs and saved web pages. PDFs keep their layout. When you come back to a source, Reader restores its saved reading position when it matches the open document.
+
+## Highlight a passage {#highlight}
+
+Select text in the document. A toolbar appears next to the selection:
+
+- **Highlight** (H) saves the passage as a highlight straight away.
+- **Comment** (C) opens a comment field. Choose **Save highlight** to save the highlight with your comment.
+- **Copy text** copies the passage, and **Copy with citation** copies it as a quote citing the source.
+
+Esc dismisses the toolbar. By default, selecting text does not create an annotation until you choose an action. Use the colour controls to choose a highlight colour; highlights are also identified by their text and annotation details.
+
+If you highlight a lot, set **Selecting text** to **Highlight at once** in **Text and display**. Every selection is then saved as a highlight as soon as you make it.
+
+## Capture a PDF area {#area}
+
+For a figure, table or equation in a PDF, choose **Select area** in the document toolbar and drag across the part of the page you want. The captured image is saved as a PNG file in the collection's `files` folder, and the annotation embeds it. You can add a comment before saving. A new crop is held in memory until it is saved; reloading can lose the unsaved image and comment.
+
+## Comment on the source {#comment}
+
+**New comment** in the annotation panel records a thought about the source as a whole, with no passage attached.
+
+## Bookmarks {#bookmark}
+
+**Bookmark this position** in the document toolbar, or the command of the same name, saves your current place as an annotation. The document must be open.
+
+## The annotation list {#list}
+
+Open a source's **Annotations** view, or the side panel while reading. You can search annotations, filter them to highlights, area captures, comments on the source, bookmarks or those with commentary, and order them by position in the document or newest first.
+
+**Show in document** jumps to an annotation's passage. **Add to literature note** embeds it in the source's note. See [Notes and citations](/apps/reader/notes/).
+
+## Edit and delete {#edit}
+
+Comments save automatically about a second after you stop typing. If a save fails, your text stays in the editor with **Retry save**. Unsaved comments are kept in memory only, so a forced reload or a crash can lose text that was not saved yet. Reader warns you before you close a tab with unsaved changes.
+
+If the annotation was changed elsewhere, for example in another app, Reader keeps your version and lets you compare it with the collection version before choosing. An annotation can be edited in one pane at a time.
+
+Deleting an annotation asks for confirmation. If literature notes embed it, Reader lists them first, because those embeds will break.
+
+## When a file changes {#changed-files}
+
+Each annotation records the exact version of the file it was made on. Reader will not silently move an annotation to a passage it cannot confirm.
+
+- PDF highlights and bookmarks stay attached when a PDF is re-saved without its pages changing, for example after a metadata edit.
+- Web page highlights are found again by their quoted text.
+- EPUB positions belong to one version of the book. After the file changes, Reader checks the quoted text before it follows an old position.
+
+## Connection and unsaved work {#connection}
+
+Reader needs Connect access to open collection files and save changes. A document already loaded may remain readable during a connection failure, but this is not an offline-library mode. The former **Available offline** feature has been removed.
+
+Wait for annotation saves to finish before closing or reloading. Pending annotation text and new PDF crops are held in memory. Literature notes have a separate local-draft recovery path; see [Saving and conflicts](/apps/reader/notes/#saving).
diff --git a/content/apps/reader/data.md b/content/apps/reader/data.md
new file mode 100644
index 0000000..7ffa1b1
--- /dev/null
+++ b/content/apps/reader/data.md
@@ -0,0 +1,125 @@
+---
+title: How Reader stores data
+description: The folders, records and fields Reader writes, so other tools can read and change them.
+section: reader
+---
+
+Everything Reader saves is an ordinary Markdown record or file in your collection. There is no separate Reader database. You can read, edit, back up or move the records with any tool.
+
+## Collection layout {#layout}
+
+```text title="collection"
+sources/
+ src_7d7c62fd-….md one record per source
+annotations/
+ ann_fa4cdc4f-….md one record per annotation
+files/
+ reader/src_7d7c62fd-…/
+ distant-reading.pdf the source's original file
+ annotation-9b21….png an area capture
+views/
+ reading-this-month.md a saved library view
+_types/
+ reader-source.md
+ reader-annotation.md
+```
+
+This is an illustrative layout for the starter types; names and type folders follow the collection's configuration. Imported files go under `files/reader/imports`. Record links point to source paths, so tools such as Obsidian can resolve them.
+
+## Source records {#sources}
+
+A source record describes one work. Its body is your literature note.
+
+```markdown title="sources/src_7d7c62fd-….md"
+---
+type: reader-source
+id: src_7d7c62fd-…
+title: Distant Reading
+kind: document
+authors: [Franco Moretti]
+saved_at: 2026-08-10T06:17:37.487Z
+reading:
+ status: reading
+documents:
+ - file: '[[files/reader/src_7d7c62fd-…/distant-reading.pdf]]'
+ file_id: 019fea51-…
+ role: primary
+ format: pdf
+ media_type: application/pdf
+ revision: sha256:c8b2e7…
+csl:
+ id: morettiDistant13
+ type: book
+ title: Distant Reading
+---
+Argues that close reading scales poorly to large corpora. [@morettiDistant13]
+
+![[annotations/ann_fa4cdc4f-…]]
+```
+
+| Field | Holds |
+| --- | --- |
+| `id`, `title`, `kind`, `saved_at` | Required. The source's stable identity, title, kind and when it was added. |
+| `authors`, `published`, `url`, `description`, `language`, `tags` | Optional details shown in the library. |
+| `documents` | The source's files. Each entry links to a file and records its format and the SHA-256 revision that was saved. |
+| `reading` | Reading status, progress from 0 to 1, and the saved position associated with a document file. |
+| `relations` | Links to related sources. |
+| `csl` | One CSL-JSON item. Its `id` is the citation key. |
+
+Unknown fields are kept, so you can add your own.
+
+## Annotation records {#annotations}
+
+Each highlight, comment, bookmark or area capture is its own record. Its body holds the quoted passage, your comment, or both.
+
+```markdown title="annotations/ann_fa4cdc4f-….md"
+---
+type: reader-annotation
+id: ann_fa4cdc4f-…
+source: '[[sources/src_7d7c62fd-…|Distant Reading]]'
+annotation_type: highlight
+motivation: commenting
+color: yellow
+document:
+ file: '[[files/reader/src_7d7c62fd-…/distant-reading.pdf]]'
+ file_id: 019fea51-…
+ revision: sha256:c8b2e7…
+target:
+ quote:
+ exact: the trouble with close reading
+ prefix: 'And '
+ pdf: { … }
+created_at: 2026-08-11T09:02:14.120Z
+created_by: dev.mdbase.reader
+tags: []
+---
+> the trouble with close reading
+
+This is the claim to test against the sampling chapter.
+```
+
+| Field | Holds |
+| --- | --- |
+| `source` | A link to the source record. |
+| `annotation_type` | `highlight`, `note` (a comment on the source), `bookmark` or `area`. |
+| `document` | The file and the exact revision the annotation was made on. |
+| `target` | Where the annotation points: the quoted text with its surrounding context, plus a PDF position, EPUB CFI or web page selector. |
+| `locator` | A readable position label, such as a page. |
+| `motivation`, `color`, `tags` | Why it was made, its colour and its tags. |
+| `created_at`, `modified_at`, `created_by` | When and by which app it was made. |
+
+## Types and contracts {#types}
+
+Reader reads and writes through two application contracts, `dev.mdbase.reader.source` and `dev.mdbase.reader.annotation`. The starter types `reader-source` and `reader-annotation` implement them with the field names shown above. A collection can use its own types and field names instead, as long as they implement the contracts. See [Contracts and adapters](/sdk/contracts/).
+
+The starter types assign records by folder and fields: records in `sources` with `id`, `title` and `kind` are sources, and records in `annotations` with `id`, `source` and `annotation_type` are annotations.
+
+## What stays on the device {#device}
+
+- Pane arrangement and display preferences.
+- Literature note drafts that have not reached the collection yet.
+- Connect access grants used by this browser, subject to your collection approval.
+
+Pending annotation comments and new PDF crops are held in memory and can be lost on reload. Local source-note drafts are best-effort browser recovery, not backups. Reader no longer provides the former offline-document copy feature.
+
+Open [mdbase writer](/apps/writer/) with the same collection to reuse citation metadata and Reader quotations in manuscripts.
diff --git a/content/apps/reader/extension.md b/content/apps/reader/extension.md
new file mode 100644
index 0000000..e39cabb
--- /dev/null
+++ b/content/apps/reader/extension.md
@@ -0,0 +1,55 @@
+---
+title: Browser extension
+description: Save the page you are reading, with highlights and notes, from Chrome's side panel.
+section: reader
+---
+
+## Capture and highlight {#watch}
+
+
+
+## Install
+
+Install [mdbase Reader from the Chrome Web Store](https://chromewebstore.google.com/detail/mdbase-reader/kimdfjefhbfgfecconmaiaaindjccidp) in Chrome 123 or newer. Store-installed copies receive Chrome's automatic updates. Pin Reader from Chrome's extensions menu so its button is easy to reach.
+
+If you used an unpacked development copy, disable it to avoid duplicate capture actions. The store copy has its own identity and needs a fresh Connect approval; settings and grants do not migrate automatically.
+
+If you have an unpacked development build, open `chrome://extensions`, enable **Developer mode** and choose **Load unpacked**. Select the folder containing `manifest.json`. Unpacked copies need manual updates; use the store version for ordinary reading.
+
+The extension saves the page you are viewing in your browser. Because it reads the page you already have open, it works for pages that Reader's own capture service cannot fetch, such as articles behind a sign-in.
+
+## Connect a collection {#connect}
+
+Open the extension and choose **Connect**. It opens an mdbase Connect approval for a collection, like any other app. Choose the destination collection. The extension remembers it for next time.
+
+## Save a page {#save}
+
+Click the toolbar button or press AltShiftS. Reader opens in Chrome's side panel for that tab. Check the title, add tags and a note if you like, then choose **Save page** or **Save PDF**. Opening the panel or changing collections does not save a page. Once saved, **Open in Reader** takes you to the source.
+
+- For an article, Reader extracts the main text and saves a readable copy, plus an archive of the page without any form values you typed.
+- For a PDF open in Chrome's viewer, it saves the PDF. The file is downloaded from the page itself, so your own access applies.
+
+If the page is already in the collection, the panel finds the existing source instead of creating a duplicate. Addresses are compared without tracking parameters, `www.`, AMP variants or trailing slashes.
+
+## Highlight as you read {#highlights}
+
+The panel stays open while you read. Each new text selection appears in it, so you can highlight several passages in a row. Add a comment or tags if you like, then choose a colour to save the passage. CtrlEnter (⌘Enter on a Mac) also saves the selected passage, or the unsaved page if no passage is selected. You can also press AltShiftH, or right-click and choose **Save highlight to mdbase Reader** or **Add a note in mdbase Reader**.
+
+Highlights are anchored to the saved copy of the page. When a passage appears more than once, Reader uses the occurrence whose surrounding text matches best, and only if one clearly does. Otherwise the highlight is not saved, and your note stays in the panel so you can try again.
+
+Unsaved capture drafts are kept per tab and page for the browser session, so closing the side panel does not discard them. They are not collection backups. For PDF highlighting, save the file and choose **Open in Reader to highlight**.
+
+## Citation details {#citations}
+
+When a page carries a DOI or scholarly metadata, the panel shows the citation it will store. With a DOI, the citation comes from the DOI registry, and only the DOI is sent. Otherwise it comes from the page's own metadata tags. If you turn on Wikimedia's Citoid lookup in Settings, which is off by default, a page without a DOI citation can also be looked up by sending its address to Wikimedia.
+
+## Mark pages you have saved {#marks}
+
+The extension asks for access to HTTPS websites when you install it. It checks the pages you visit against your selected collection, shows a badge with a highlight count or a saved-page check mark, and displays saved highlights. Opening the side panel can also show highlights for that page. If you limit the extension's site access in Chrome, it stops marking saved pages, and **Settings → Pages you visit** offers to allow it on all sites again.
+
+## Permissions
+
+- It has access to HTTPS websites from installation, which it uses to follow the tab you are on and mark saved pages. If you limit site access in Chrome, it reads a page only where you allow it or when you open the panel on it.
+- It also has access to the mdbase Connect API and the mdbase collection log service (`log.mdbase.dev`), which it uses to reach your collection.
+- Its access to your collection comes from the Connect approval, which you can revoke in Connect.
+- See the [extension privacy policy](/apps/reader/extension/privacy/) for capture data, permissions and third-party lookups.
diff --git a/content/apps/reader/import.md b/content/apps/reader/import.md
new file mode 100644
index 0000000..e30a2b9
--- /dev/null
+++ b/content/apps/reader/import.md
@@ -0,0 +1,48 @@
+---
+title: Importing a library
+description: Bring sources, files, highlights and notes from Zotero or Readwise Reader into an mdbase collection.
+section: reader
+---
+
+> **Importing is experimental.**
+>
+> Try it on a new or test collection first. An import only adds records and files. It does not change your Zotero or Readwise library.
+
+## Start an import {#start}
+
+Run **Import a library…** from the command palette, or open [Reader's import page](https://reader.mdbase.dev/import). Choose Zotero or Readwise Reader. Keep the import tab open while it runs.
+
+## From Zotero {#zotero}
+
+Zotero imports bring references, original files, notes, collections and Zotero's own annotations. They use a small Zotero plugin that writes an export folder for Reader.
+
+1. Download the Zotero exporter (`.xpi`) from the import page. It supports Zotero 10.0.x.
+2. In Zotero, choose **Tools → Plugins → Install Plugin From File…** and select the file.
+3. Choose **Tools → Export for mdbase Reader…** and save the export folder.
+4. In Reader, select the whole exported folder. Do not select Zotero's data directory.
+
+The experimental exporter includes all of **My Library**, not a selected collection or group library. Finish syncing and avoid editing Zotero while exporting. Only a completed export can be imported.
+
+Reader checks every payload file against its checksum before collection writes. Selecting a folder needs a supporting browser such as Chrome. Export bundles contain private notes and attachment content; keep them private.
+
+## From Readwise Reader {#readwise}
+
+Readwise imports bring Reader documents and files, plus highlights from classic Readwise sources such as Kindle, Apple Books and Instapaper. Classic sources import as metadata and highlights, without the book text.
+
+1. Get your [Readwise access token](https://readwise.io/access_token) and paste it into Reader.
+2. Choose whether to include unsaved Feed items. Archived library items are always included.
+3. Choose **Scan Readwise library**.
+
+The token stays in memory in that browser tab and is sent only to Readwise. The importer only reads from Readwise. Scanning reads metadata, highlights and saved article pages. Original PDFs and EPUBs are downloaded only after you confirm. A large library can take several minutes to scan.
+
+## Review and confirm {#review}
+
+Reader shows what it found: the number of sources, annotations and notes, and the content files and their size. Then choose a destination collection. If the collection does not have Reader's setup yet, you review and apply it first. Nothing is written until you confirm.
+
+Imported files are stored under `files/reader/imports`. When the import finishes, **Open imported collection** takes you to it.
+
+## Stopping and resuming {#resume}
+
+Choose **Stop safely** to pause an active import. Everything already written is kept, and **Resume import** continues the confirmed job. The job stays bound to its destination; switching collections cannot redirect it.
+
+After reloading, reselect the same export folder or reconnect Readwise, choose the same collection and scan again. Check the destination before resuming. Records already imported are kept; review the completion warnings for missing or unavailable content.
diff --git a/content/apps/reader/index.md b/content/apps/reader/index.md
new file mode 100644
index 0000000..8a6f650
--- /dev/null
+++ b/content/apps/reader/index.md
@@ -0,0 +1,55 @@
+---
+title: Get started
+description: mdbase Reader turns an mdbase collection into a reading library for PDFs, EPUBs and saved web pages.
+section: reader
+---
+
+> Reader is prerelease software.
+>
+> Keep backups of important collections and check the save status before closing or reloading. Sources, notes and annotations remain ordinary mdbase records.
+
+## What it is {#what}
+
+Reader is for reading, annotating, organising and citing source material. Each source, such as a paper, a book or an article, is a Markdown record in your collection. Its file sits beside it, and every highlight or comment is a separate Markdown record. Other mdbase tools, a text editor or Obsidian can read the collection records and files. See [How Reader stores data](/apps/reader/data/). To write a manuscript using your library's citations and highlights, open [mdbase writer](/apps/writer/) with the same collection.
+
+Reader works with Cloud copy and Private collections. Reader reaches a Private collection through one of your devices, so keep one online, such as a computer running the [desktop app](/downloads/).
+
+## Highlight to Markdown {#watch}
+
+
+
+See also the recordings for [views and panes](/apps/reader/library/#watch) and [web capture](/apps/reader/extension/#watch).
+
+## Open a collection {#open}
+
+1. Open [reader.mdbase.dev](https://reader.mdbase.dev/) and connect a collection.
+2. Sign in to mdbase Connect. If you do not have an account, [sign up](https://connect.mdbase.dev/signup) first.
+3. Choose the collection you want to use as your library.
+4. Review and approve Reader's access to that collection.
+
+You can use an existing collection or a new, empty one. Reader keeps its records in their own folders, so it can share a collection with notes from other apps.
+
+## Reader setup {#setup}
+
+The first time you open a collection, Reader may show **Set up this reading collection**. It lists the exact changes it needs: the source and annotation contracts and two starter types, `reader-source` and `reader-annotation`. Nothing else in the collection changes. Choose **Apply reviewed setup** to add them.
+
+You can adapt the starter types later, for example in the [mdbase Editor](https://editor.mdbase.dev/). Reader reads your records through its contracts, so your types can use their own field names.
+
+## The workspace {#workspace}
+
+| Area | What it holds |
+| --- | --- |
+| Sources sidebar | Find a source by title, author or tag, and see open and recent sources. |
+| Library | Every source as a table or cards, with filters and saved views. |
+| Documents | Each open source in a tab, showing its document, literature note, annotations or citation. |
+| Side panel | Annotations and details for the source you are reading. |
+
+Tabs and panels can be moved and split. Drag a tab onto another tab strip to move it, or onto the edge of a pane to split. A tab's context menu and the pane's **⋯** menu offer the same actions without dragging. Your arrangement is saved per collection, and **Reset pane arrangement** in the command palette restores the default without closing tabs. On a phone, one pane is shown at a time.
+
+Press CtrlK (⌘K on a Mac) to search sources and run any command.
+
+## Switch collections {#switch}
+
+Open the collection-name menu in the header to choose another connected collection or connect a new one. Review any pending saves before switching. If a collection is unavailable, follow Reader's reconnect or access-review prompt.
+
+See [Support](/support/) to report bugs or request help. Remove private notes, collection paths and credentials from reports.
diff --git a/content/apps/reader/library.md b/content/apps/reader/library.md
new file mode 100644
index 0000000..b5354e6
--- /dev/null
+++ b/content/apps/reader/library.md
@@ -0,0 +1,53 @@
+---
+title: Library and views
+description: Browse, filter, search and bulk-edit your sources, and save the result as a view in your collection.
+section: reader
+---
+
+## Views and panes {#watch}
+
+
+
+## Open the library {#open}
+
+Run **Open library** from the command palette. The library opens as a tab, so it can sit beside a document. Show sources as a table or as cards, and choose which columns the table shows. Any frontmatter field can be a column.
+
+For a quick lookup without opening the library, use the Sources sidebar. Press CtrlShiftF, or / when you are not typing, and search by title, author or tag.
+
+## Lenses
+
+Lenses are ready-made starting points:
+
+- All sources, Recently opened, Currently reading and Unread inbox
+- Has annotations and Missing citation data
+- PDF, EPUB and Saved web pages
+
+## Filter and sort {#filter}
+
+Filter by reading status, format, tag, or conditions on any frontmatter field. Every condition must match. Sort by when a source was saved or last opened, title, creator, publication date, status, or any field.
+
+## Search
+
+The search box has three scopes:
+
+| Scope | Searches |
+| --- | --- |
+| Library | Source details such as title, authors and tags. |
+| Notes & annotations | Literature notes and annotation text. It does not search inside PDFs, EPUBs or saved pages. |
+| Open documents | Text from loaded, supported document renderers. Unopened and suspended documents are not included, even if a suspended source still has a tab. |
+
+## Reading status {#status}
+
+Each source can have a reading status: inbox, queued, reading, finished, archived or abandoned. It is stored in the source record, so other apps can see it too.
+
+## Edit several sources {#bulk}
+
+Select sources in the table to set their reading status together, or to set any field to a value. Leaving the value empty removes that field from every selected source. You can also export a bibliography of just the selected sources. Esc clears the selection.
+
+## Saved views {#views}
+
+When a filtered, sorted arrangement is worth keeping, save it as a new view. Views are ordinary collection records implementing `mdbase.view`, normally in the `views` folder. The filter, sort and presentation can be reopened on another device or used by other mdbase tools. Choose **Save view** to update an editable Reader-owned view; save a new view to keep a separate arrangement.
+
+## All annotations {#annotations}
+
+Choose **Annotations** beside **Sources** in a library view to browse annotations across sources. Search by passage, note, source or tag, filter by type or tag, and sort by source or creation date. This arrangement can be saved as an annotation view too. The annotation text loads separately from the source list; wait for loading to finish before treating a search result or count as complete.
diff --git a/content/apps/reader/notes.md b/content/apps/reader/notes.md
new file mode 100644
index 0000000..639ea91
--- /dev/null
+++ b/content/apps/reader/notes.md
@@ -0,0 +1,49 @@
+---
+title: Notes and citations
+description: Write a literature note for each source, embed annotations in it, and keep citation data in CSL-JSON.
+section: reader
+---
+
+## The literature note {#note}
+
+Every source has a literature note: the Markdown body of its source record. Open it with **Open literature note**, or switch the source's tab to its note view. Reader never rewrites the note from your annotations. It contains only what you write or insert.
+
+## Insert annotations and citations {#insert}
+
+Use the insert menu in the note editor, or **Add to literature note** on an annotation:
+
+- **Annotations** are inserted as embeds, so the note shows the current text of the highlight or comment. If you edit the annotation, the note shows the change.
+- **Citation** inserts a Pandoc-style citation such as `[@morettiDistant13]` at the cursor. It needs the source to have citation data with a citation key.
+
+```markdown title="literature note"
+Argues that close reading scales poorly to large corpora. [@morettiDistant13]
+
+![[annotations/ann_6f1c…]]
+
+My disagreement: the sampling problem cuts both ways.
+```
+
+## Saving and conflicts {#saving}
+
+The note saves automatically about a second after you stop typing. The same note can be open in several panes. They share its text but keep their own cursor, scroll position and undo history.
+
+If a save fails, keep the note open and follow the retry prompt. Reader keeps recoverable source-note drafts in this browser, scoped to the collection and source. On reopening, review any recovered draft before saving it. Browser storage is best-effort and can be cleared; it is not a collection backup.
+
+If the note changed in the collection while you were editing, Reader shows **This note changed in the collection** and lets you compare your draft with the collection version. Check the save status before closing. Annotation comments use a different, memory-only buffer.
+
+## Citation data {#citation}
+
+Citation data is optional. When you add it, it is stored as one CSL-JSON item in the source record's `csl` field, the format used by Zotero, Pandoc and most citation tools. Its `id` is the citation key, which must be unique in the collection.
+
+Open **Open citation data** to edit it as a form or as raw CSL-JSON. Every official CSL field is kept exactly as entered, and less common fields can be added from the form. Problems are marked before you save. The **Missing citation data** lens in the library lists sources without it. The same source metadata and citekey are available in [mdbase writer](/apps/writer/citations/) when you open the same collection.
+
+## Find citation details {#lookup}
+
+**Find citation details** searches by DOI, ISBN, URL or title. Reader shows the details it found for you to review before saving. DOIs are looked up in the DOI registry. Everything else goes to Wikimedia's Citoid service. Only the identifier, address or title you searched for is sent; the result is not saved until you approve it.
+
+## Export
+
+| Command | Produces |
+| --- | --- |
+| **Export bibliography** | `references.json`, a CSL-JSON file of every source with citation data. You can also export only the sources selected in the library. |
+| **Export current source** | A zip file with the source and annotation records as they are stored, a single Markdown file combining the note and its annotations, the source's references, and the original files. An `EXPORT-REPORT.md` lists anything that could not be included. |
diff --git a/content/apps/reader/shortcuts.md b/content/apps/reader/shortcuts.md
new file mode 100644
index 0000000..20a6290
--- /dev/null
+++ b/content/apps/reader/shortcuts.md
@@ -0,0 +1,45 @@
+---
+title: Shortcuts and display
+description: Keyboard shortcuts and display settings in mdbase Reader.
+section: reader
+---
+
+## Keyboard shortcuts {#shortcuts}
+
+On a Mac, use ⌘ in place of Ctrl, except for CtrlTab. Single-key shortcuts such as H and / do nothing while you are typing in a field.
+
+| Keys | Action |
+| --- | --- |
+| Ctrl K | Search sources and run commands |
+| Ctrl Shift F | Filter sources in the sidebar |
+| / | Search the library view, or the sidebar elsewhere |
+| H | Highlight the selected text |
+| C | Comment on the selected text |
+| Esc | Dismiss the selection toolbar, or leave reading mode |
+| Ctrl . | Enter or leave reading mode |
+| Ctrl \ | Show or hide the left sidebar |
+| Ctrl Shift \ | Show or hide the right sidebar |
+| Ctrl Tab / Ctrl Shift Tab | Next or previous tab |
+| Ctrl Shift T | Reopen the last closed tab |
+| Alt ← / Alt → | Back or forward |
+| F6 | Move focus to the next pane |
+| Ctrl Enter | Open the selected sidebar source beside the current one |
+
+For the browser extension's shortcuts, see [Browser extension](/apps/reader/extension/#highlights). Chrome can change extension shortcuts at `chrome://extensions/shortcuts`.
+
+## Command palette {#palette}
+
+CtrlK opens the command palette. Type part of a source title or author to open it, or a command name to run it. Commands include opening the library, adding or importing sources, switching between open tabs, opening a source's note, annotations or citation, arranging and resetting panes, exporting, bookmarking and changing the theme. The **Reset pane arrangement** command keeps your tabs open; **Import a library…** opens the import flow in a new tab.
+
+## Text and display {#display}
+
+Open **Text and display** in the header. These settings are stored in this browser. Light, dark and system themes are also available from the command palette. Reading preferences change reflowable documents; PDFs retain their page layout.
+
+| Setting | Effect |
+| --- | --- |
+| Text size | Larger or smaller text for EPUBs and saved web pages. |
+| Typeface | Serif or sans serif. |
+| Line length | Narrow or standard. |
+| Density | Comfortable or compact lists and tables. |
+| Sidebar while reading | Keep the sidebar open or hide it while a document is focused. |
+| Selecting text | Show actions, or highlight at once. |
diff --git a/content/apps/reader/sources.md b/content/apps/reader/sources.md
new file mode 100644
index 0000000..6d7a45a
--- /dev/null
+++ b/content/apps/reader/sources.md
@@ -0,0 +1,39 @@
+---
+title: Adding sources
+description: Add PDFs, EPUBs and web pages, or start from a DOI, arXiv ID, ISBN or PubMed ID.
+section: reader
+---
+
+Choose **Add source** in the library, or run **Add source…** from the command palette. You can add a file or paste a link or identifier.
+
+## Add a file {#file}
+
+Choose a PDF, an EPUB, or a web page you saved earlier. You can also drop a file onto Reader. The original file is stored unchanged in your collection, and Reader creates a source record that points to it.
+
+## Add a link or identifier {#link}
+
+Paste a web address, DOI, arXiv ID, ISBN or PubMed ID into **Link or identifier** and choose **Add**. Reader shows each step as it works: fetching the page, looking up citation details, or looking for an open-access PDF.
+
+## Web pages {#web}
+
+For a web address, Reader fetches the page and saves a readable copy. If the address points to a PDF, it saves the PDF instead. When the page cannot be fetched, Reader may find citation details and offer to save a citation-only source. Review that offer before accepting it.
+
+Pages behind a sign-in or paywall cannot be fetched this way. Use the [browser extension](/apps/reader/extension/), which saves the page you are already viewing, or save the page yourself and add the file.
+
+## Identifiers
+
+For a DOI, arXiv ID, ISBN or PubMed ID, Reader first looks up the citation details. For a DOI or arXiv ID, it then looks for a freely available PDF. It tries direct PDF links first, then open-access article pages. Paywalled and blocked sites are skipped.
+
+If no PDF is found, you can keep a source with citation details and attach a file later. Review any follow-up message: **Open source** opens a source already added, while a citation-only offer needs your approval. If citation data could not be stored, Reader says so; use the source's citation tab to review or add it.
+
+## What is sent where {#privacy}
+
+| Step | Service | What is sent |
+| --- | --- | --- |
+| Fetching a web page or PDF | Reader's capture service | The address to fetch. Private and local network addresses are refused. |
+| DOI and arXiv citations | The DOI registry (doi.org) | The DOI only. |
+| Other citations: ISBN, PubMed, URL or title | Wikimedia Citoid | The identifier, address or title only. |
+| Open-access search for a DOI | OpenAlex, and Unpaywall where enabled | The DOI only. PDFs it finds are then fetched by Reader's capture service. |
+| Open-access search for an arXiv ID | arXiv, through Reader's capture service | The arXiv ID only. |
+
+Citation lookups send the identifier, address or search text needed for that lookup, not your notes or annotations. Fetching a page sends its address; check that it does not contain a private access token. See the [privacy policy](/privacy/) for data handling.
diff --git a/content/apps/writer/chapters.md b/content/apps/writer/chapters.md
new file mode 100644
index 0000000..d5d3d65
--- /dev/null
+++ b/content/apps/writer/chapters.md
@@ -0,0 +1,43 @@
+---
+title: Chapters and embeds
+description: Assemble a longer manuscript from Markdown records in the same collection.
+section: writer
+---
+
+## Building a book {#watch}
+
+
+
+## Include a chapter {#include}
+
+Put an embed on a line of its own in the main manuscript. Writer includes the referenced record at that point in the document. The chapter is an ordinary Markdown record; it needs no special manuscript type.
+
+```markdown title="main manuscript body"
+![[chapters/introduction]]
+
+![[chapters/results]]
+
+![[chapters/discussion]]
+```
+
+Use paths belonging to records in your collection. Writer resolves record links in the collection; an unresolved link appears in Problems. A main manuscript can also contain its own prose around the chapter embeds.
+
+## Navigate and reorder {#navigate}
+
+Outline lists the included chapters in document order. Open one there or from its card in the editor. Cards show the chapter title, word count and problems. Each chapter has its own editing session and autosave status.
+
+Drag a chapter in Outline, or use Alt↑ and Alt↓, to reorder its embed in the main manuscript. Outline can also add a new chapter at the end. Review the preview after changing the order.
+
+## References across chapters {#references}
+
+Writer assembles the complete manuscript before formatting citations and references. Footnotes, citations and labels can work across records. Choose unique figure, section and equation labels throughout the manuscript so a reference has one intended target.
+
+Images belong to the collection, and relative image paths are resolved from the chapter containing them. A chapter's file links should still work when it is included from another record.
+
+## Embed a Reader annotation {#annotations}
+
+An embed referring to a Reader annotation uses its quotation and available source citation. For example, `![[annotations/your-highlight]]` can include a saved passage. Keep the source's CSL metadata and citekey available in the same collection, and verify the quoted text and locator.
+
+## Missing and recursive embeds {#missing}
+
+Missing records and cyclic includes appear in Problems. A cycle happens when a manuscript eventually embeds itself, directly or through another record. Remove the recursive embed or move shared prose into a separate record. Check all included chapters and images before [exporting](/apps/writer/export/).
diff --git a/content/apps/writer/citations.md b/content/apps/writer/citations.md
new file mode 100644
index 0000000..3893e91
--- /dev/null
+++ b/content/apps/writer/citations.md
@@ -0,0 +1,45 @@
+---
+title: Sources and citations
+description: Cite the sources in your Reader library and insert highlighted quotations into a manuscript.
+section: writer
+---
+
+## Use your Reader library {#library}
+
+Connect Writer to the collection containing your [Reader library](/apps/reader/). Each citable source has CSL-JSON citation metadata with a citekey in `csl.id`. The manuscript uses that citekey; the source record and its metadata remain in the collection.
+
+Add sources and review their citation data in [Reader's citation editor](/apps/reader/notes/#citation). Citekeys must be unique. If a source has no citation data, add it before trying to cite the source in Writer.
+
+## Insert a citation {#insert}
+
+1. Open **Sources**, or press CtrlShiftE (⌘ on a Mac).
+2. Search by author, title, year or citekey.
+3. Select a source, add a page number if needed, and insert its citation.
+
+Sources already cited in the manuscript appear before the rest of the library. The panel marks the source under your cursor and can step through its citations. You can also type `@` or `[@` in the editor to open source completion suggestions.
+
+```markdown title="Pandoc citations"
+A parenthetical citation [@smith2024].
+
+A specific passage [@smith2024, p. 12].
+
+Several sources [@smith2024; @jones2023].
+```
+
+Replace the example citekeys with your own. Hover a citation to inspect its bibliography entry.
+
+## Reader quotations {#quotations}
+
+Sources can show quotations from Reader annotations. Insert one to bring the highlighted text into the manuscript with its citation and available page information. Check the quotation and page against the original source before using it in submitted work.
+
+[Embedding an annotation record](/apps/writer/chapters/#annotations) is another way to use a quotation. Quoted text and commentary stay separate; commentary is not part of the source's words.
+
+## Style and language {#style}
+
+Choose **Citation style** and **Language** in Manuscript settings. Six citation styles and eight locales are bundled. A `.csl` file in the collection can provide another citation style. The selected style controls author/date or note-style formatting, bibliography entries and repeated citations across all included chapters.
+
+Preview and Word export use the same citation metadata and style, with separate rendering engines. Review both the citation text and bibliography in the final export.
+
+## Missing or unknown sources {#missing}
+
+An unknown citekey appears in Problems and may offer a similar known key. Check its spelling, the selected collection and the source's citation data. Editing a source citekey can leave older manuscript citations unresolved; update those references as well.
diff --git a/content/apps/writer/data.md b/content/apps/writer/data.md
new file mode 100644
index 0000000..66ecdf8
--- /dev/null
+++ b/content/apps/writer/data.md
@@ -0,0 +1,47 @@
+---
+title: Saving and collection data
+description: Understand where your manuscript lives, how edits save, and what to do about a conflict or failed save.
+section: writer
+---
+
+## Manuscript records {#records}
+
+A manuscript is a Markdown record implementing `dev.mdbase.writer.manuscript`. Its body is your writing; frontmatter holds its title, authors, abstract, layout, citation style and language. The following example uses the starter type's field names:
+
+```markdown title="illustrative manuscript record"
+---
+type: writer-manuscript
+title: A research paper
+authors:
+ - name: Alex Researcher
+ affiliation: Example University
+template: article
+csl: chicago-notes-bibliography
+lang: en-GB
+---
+# Introduction
+
+A claim supported by a source [@smith2024, p. 12].
+```
+
+Chapters remain separate Markdown records. Reader sources hold their own citation data and annotations, and comments use collection records too. Other mdbase tools can read these records. Writer does not delete or rename them.
+
+## Autosave {#saving}
+
+Manuscript text, chapter text and settings save through Connect record sessions. Each included record has its own session. Watch the save status and wait for changes to be saved before closing, reloading or changing collections.
+
+A failed save displays **Not saved**. The editor keeps the current text, and saving retries when you type. Keep the tab open while restoring access. If saving still fails, copy your writing somewhere safe before reloading; do not assume an unsent edit is in the collection.
+
+## Conflicts
+
+If a record changes elsewhere while you are editing it, Writer reports the conflict. **Keep mine** retains your version; **Use theirs** adopts the collection version. Check both versions and copy any text you need before choosing. A conflict in one chapter belongs to that chapter's record.
+
+## Browser state {#device}
+
+Layout, zoom, theme and the last-used export format are remembered in the browser. These preferences are separate from the manuscript settings stored in the collection. Browser state is not a backup of your writing.
+
+## Access and availability {#access}
+
+You approve Writer's collection access through Connect. A Private collection needs one of your devices online to serve it. If a collection cannot be opened, follow the reconnect prompt, check its availability or choose another collection.
+
+When reporting a problem, include the browser, steps to reproduce and the displayed error. Remove private manuscript text, paths and credentials. Keep your collection backups independent of the browser.
diff --git a/content/apps/writer/export.md b/content/apps/writer/export.md
new file mode 100644
index 0000000..0d8ddc8
--- /dev/null
+++ b/content/apps/writer/export.md
@@ -0,0 +1,39 @@
+---
+title: Layouts and export
+description: Choose the manuscript's appearance and download PDF, Word or a Pandoc/Quarto bundle.
+section: writer
+---
+
+## Manuscript settings {#settings}
+
+Open **Settings** to edit title, subtitle, authors, abstract, date, citation style, layout and language. Enter authors one per line; `Name; Affiliation` adds an affiliation. Settings update the manuscript's frontmatter and preview as you edit.
+
+A problem with a setting appears beside that field. Check the save status after changing settings, just as you do after writing body text.
+
+## Layouts
+
+The bundled **Article** and **Thesis** layouts typeset the manuscript with appropriate title and document structure. You can also choose a Typst template stored as a `.typ` file in the collection. Custom layouts require Typst knowledge and a template function accepting title, subtitle, authors, abstract, date and body.
+
+A collection template is one file: files it imports are not loaded. Its layout affects the PDF. A manuscript's citation style can be a bundled style or a `.csl` file in the collection.
+
+## Export formats {#formats}
+
+Open the menu beside **Export** to choose a format. The main button repeats the format you used last in this browser. You can also open the export menu with CtrlShiftS (⌘ on macOS).
+
+| Format | Contents |
+| --- | --- |
+| PDF | The typeset manuscript using the selected layout. It is available once the manuscript typesets. |
+| Word (DOCX) | An editable document with formatted citations, resolved cross-references and Word document styles. |
+| Pandoc bundle (ZIP) | Materialised Markdown, references, citation style and supporting files for building with Pandoc or Quarto. Follow the bundle's README. |
+
+Exports are generated in the browser. The first Word export downloads about 16 MB of additional software. Keep the tab open while it prepares the file. A slow first export does not mean the manuscript needs to be reopened.
+
+## PDF and Word differences {#differences}
+
+PDF uses the Typst layout; Word uses its own styles and Pandoc's document structure. Word is not a page-for-page copy of the preview. A custom Typst layout uses article styles for Word output. The bundled article and thesis layouts have their corresponding Word reference styles.
+
+The Word export resolves cross-reference numbers before conversion. A Pandoc/Quarto bundle leaves cross-references for the external build tools; follow its instructions for Quarto or an appropriate Pandoc filter.
+
+## Check before sharing {#check}
+
+Review Problems and export warnings, then inspect the downloaded file. Missing records or images can leave output incomplete. Check page breaks, figures, cross-references, citations and bibliography before submitting or sharing. The bundle includes manuscript text and supporting content; treat it as private research material.
diff --git a/content/apps/writer/index.md b/content/apps/writer/index.md
new file mode 100644
index 0000000..b1b0874
--- /dev/null
+++ b/content/apps/writer/index.md
@@ -0,0 +1,56 @@
+---
+title: Get started
+description: Write Markdown manuscripts with a typeset preview, citations from Reader, and PDF or Word export.
+section: writer
+---
+
+> Writer is prerelease software.
+>
+> Keep backups of important work and check the save status before closing or reloading.
+
+mdbase writer is for papers, theses and books. Your manuscript stays a Markdown record in your collection. Writer typesets it as you write and uses your [Reader library](/apps/reader/) for citations and quotations. The bundled layouts need no Typst or LaTeX knowledge.
+
+## Writing a paper {#watch}
+
+
+
+The recordings use a separate Darwin-themed sample library. The live demo may contain different sample manuscripts. See also [building a book from chapters](/apps/writer/chapters/#watch).
+
+## Connect a collection {#connect}
+
+1. Open [writer.mdbase.dev](https://writer.mdbase.dev/) and choose **Connect a collection**.
+2. Sign in through mdbase Connect, choose a collection and review Writer's requested access.
+3. Choose the same collection as your Reader library to cite its sources.
+4. If prompted, review the proposed manuscript and source types, then choose **Set up collection**.
+
+Setup adds the contracts and types Writer needs after your approval. It does not rewrite existing manuscript text. Writer works with Cloud copy and Private collections. It reaches a Private collection through one of your devices, so keep one online, such as a computer running the [desktop app](/downloads/).
+
+## Create a manuscript {#create}
+
+1. Choose **New manuscript**.
+2. Enter a title and choose an article or thesis layout and a citation style.
+3. Choose **Create manuscript** and begin writing.
+
+To use an existing note, choose **Use a note you already have…** in the same dialog. Select the note and choose **Use as manuscript**. This adds the manuscript type while retaining its other types, text and location.
+
+## The workspace {#workspace}
+
+| Area | What it does |
+| --- | --- |
+| Editor | Write Markdown. Edits autosave through Connect. |
+| Preview | See the typeset pages. Click a block to return to its text. |
+| Outline | Navigate headings, open chapters and reorder chapter embeds. |
+| Sources | Find library sources, insert citations and use Reader quotations. |
+| Comments | Review comments, replies and suggested edits. |
+| Settings | Edit the title, authors, abstract, date, language, citation style and layout. |
+| Problems | Find citation, cross-reference, image, embed and typesetting problems. |
+
+Settings changes update the manuscript's frontmatter and preview. Your sidebar, editor/preview arrangement and zoom are remembered in this browser. On a phone, switch between writing, preview and outline views.
+
+## Next steps {#next}
+
+- [Write and review](/apps/writer/writing/) Markdown, figures, footnotes and comments.
+- [Find and cite sources](/apps/writer/citations/) from your Reader library.
+- [Assemble chapters](/apps/writer/chapters/) from separate Markdown records.
+- [Choose a layout and export](/apps/writer/export/) PDF, Word or a Pandoc bundle.
+- [Check saving and conflicts](/apps/writer/data/) before leaving the manuscript.
diff --git a/content/apps/writer/writing.md b/content/apps/writer/writing.md
new file mode 100644
index 0000000..7e77661
--- /dev/null
+++ b/content/apps/writer/writing.md
@@ -0,0 +1,62 @@
+---
+title: Writing and reviewing
+description: Write Markdown, label figures and headings, navigate the preview, and review comments and suggested edits.
+section: writer
+---
+
+## Markdown and labels {#markdown}
+
+Use Markdown headings, emphasis, lists, tables, links and footnotes. Writer also understands Pandoc citations and Quarto-style labels and references. This example uses a library citekey and an image stored in the collection:
+
+```markdown title="manuscript body"
+# Introduction {#sec-introduction}
+
+A claim supported by a source [@smith2024, p. 12].
+
+See @sec-introduction and @fig-results.
+
+{#fig-results}
+
+A sentence with a footnote.[^note]
+
+[^note]: A longer explanation.
+```
+
+Replace `smith2024` with one of your source citekeys and the image path with your own file. Labels such as `{#sec-introduction}` identify headings; `@sec-introduction` refers to them. Figures use a `fig-` label. Keep labels unique across the whole manuscript.
+
+Image paths are resolved relative to the record containing them. Store the image in the collection where Writer can read it. Missing files appear in Problems and can affect the downloaded document.
+
+## Preview and navigation {#preview}
+
+The preview typesets your manuscript as you type and follows the cursor's block. Click a preview block to jump to its Markdown. Hover over a citation to see its bibliography entry, or a cross-reference to see its target. Ctrl-click (⌘-click on a Mac) follows a reference.
+
+Outline lists your sections and chapters with word counts. Manuscript search can find text across the included records and open the result in its editor. The command palette is another way to find sources or run commands.
+
+## Problems
+
+Writer marks unknown citekeys, missing labels, unavailable records and images, footnote problems, malformed LaTeX and typesetting errors at the affected Markdown line. Open Problems to jump to one. F8 moves to the next problem; ShiftF8 moves back.
+
+Unknown citekeys and labels can offer close matches. Problems with a manuscript setting take you to that field in Settings. Check Problems before exporting and review the downloaded document.
+
+## Comments and suggestions {#comments}
+
+Select text and choose a comment or suggested edit from the selection toolbar or command palette. Open Comments to read threads and reply. A suggested edit includes replacement text; accepting it changes the record through its editing session. Review the replacement before accepting.
+
+Comments are collection records anchored to quoted text. Writer looks for the quote again after edits and reports a detached comment when it cannot find a reliable target. A comment can be signed with your collection person record when identity access is available; otherwise it is unsigned.
+
+## Shortcuts
+
+On macOS, use ⌘ in place of Ctrl. Writer's keyboard-shortcuts dialog lists the available commands.
+
+| Keys | Action |
+| --- | --- |
+| Ctrl K | Open the command palette |
+| Ctrl Shift F | Search across the manuscript's records |
+| Ctrl Shift E | Find a source |
+| Ctrl , | Open manuscript settings |
+| Ctrl \ | Show or hide the sidebar |
+| Ctrl Shift \ | Cycle the editor/preview arrangement |
+| Ctrl Alt M | Comment on a selection |
+| Ctrl Alt S | Suggest an edit to a selection |
+| Ctrl Shift S | Choose an export format |
+| F8 / Shift F8 | Next or previous problem |
diff --git a/content/mdbase.yaml b/content/mdbase.yaml
new file mode 100644
index 0000000..ce4a8c3
--- /dev/null
+++ b/content/mdbase.yaml
@@ -0,0 +1,7 @@
+spec_version: "0.3.0"
+name: "mdbase.dev documentation"
+description: "The SDK and app guides published on mdbase.dev, one record per page"
+settings:
+ types_folder: _types
+ record_extensions: [md]
+ validation: error
diff --git a/content/sdk/authorization.md b/content/sdk/authorization.md
new file mode 100644
index 0000000..d11cb04
--- /dev/null
+++ b/content/sdk/authorization.md
@@ -0,0 +1,86 @@
+---
+title: Authorization
+description: "Your app gets a grant: access to one collection with the capabilities the user approved. Ask for what you use, and check what you got."
+section: sdk
+---
+
+## Grants {#flows}
+
+When a user connects your app to a collection, mdbase records a **grant**: your app, one collection, the capabilities the user approved, and your app’s session key. The replica checks the grant on every session.
+
+A grant never exceeds the user’s own role in the collection. A viewer can’t give your app write access. When the grant or the role doesn’t allow a request, it fails with `forbidden`; `details` names the capability.
+
+## Capabilities
+
+Declare capabilities in your manifest. The user can’t turn off a `required` one without declining your app. Each `optional` one gets its own switch.
+
+```json title="Manifest fragment"
+"requirements": {
+ "access": "full_collection",
+ "contracts": [],
+ "capabilities": {
+ "contract_version": 2,
+ "required": ["collection.read", "records.edit"],
+ "optional": ["records.create"]
+ },
+ "files": {
+ "required": ["list", "read", "replace", "move"],
+ "optional": ["add"],
+ "scope": { "kind": "selected_folders", "folders": ["attachments"] }
+ }
+}
+```
+
+| Capability | Allows |
+| --- | --- |
+| `collection.read` | Describe the collection; read, query and watch records; list and run saved views; read types; validate |
+| `records.create` | Create records |
+| `records.edit` | Update and rename records |
+| `records.delete` | Delete records |
+| `views.manage` | Create, update and delete saved views |
+| `definitions.manage` | Create and update types; check and apply type packs |
+| `background.schedule` | Timers; see [Notifications and timers](/sdk/notifications/) |
+| `offline.replica` | Keep a replica of the collection in the app. Only mdbase’s own apps can hold it. |
+
+A manifest without `capabilities` asks for read-only access.
+
+## Files
+
+Files that aren’t records, such as images and PDFs, are requested under `requirements.files`. Each file action pairs with a record capability. A file action works only when your app also holds that capability:
+
+| Capability | File actions |
+| --- | --- |
+| `collection.read` | `list`, `read` |
+| `records.create` | `add` |
+| `records.edit` | `replace`, `move` |
+| `records.delete` | `delete` |
+
+The scope is the whole collection (`{ "kind": "collection" }`) or named folders. Ask for folders when you can.
+
+## Check what you got {#step-up}
+
+The user may approve less than you asked for. Read the grant from `db.hello` and hide what your app can’t do.
+
+```ts title="grant.ts"
+const { capabilities, role, fileFolders } = db.hello.grant;
+
+newEntryButton.hidden = !capabilities.includes("records.create");
+
+try {
+ await db.create({ type: "task", frontmatter: { title } });
+} catch (e) {
+ if (isMdbaseError(e, "forbidden") || isMdbaseError(e, "unauthenticated")) {
+ showReconnectPrompt(); // recovery: "reauthorize"
+ } else {
+ throw e;
+ }
+}
+```
+
+## Private collections {#private}
+
+In a Private collection, mdbase can’t read the content. Your app reaches it through one of the user’s devices. Approving your app in mdbase is the only consent: a signed-in device applies the same grant automatically, with nothing more to approve. While none of their devices is online, your app can’t reach the collection.
+
+## Revocation {#disconnect}
+
+The user can revoke your app’s access at any time. Open sessions close straight away, and requests fail with `unauthenticated`. Treat both `unauthenticated` and `forbidden` as a reason to ask the user to reconnect, never to retry in a loop.
diff --git a/content/sdk/connect-dev.md b/content/sdk/connect-dev.md
new file mode 100644
index 0000000..76f467f
--- /dev/null
+++ b/content/sdk/connect-dev.md
@@ -0,0 +1,114 @@
+---
+title: Developer kit
+description: "@mdbase-dev/connect-dev checks a manifest before you ship it and builds the type packs a manifest carries."
+section: sdk
+---
+
+A build-time package. Nothing from it runs in your app; install it as a development dependency.
+
+## Install
+
+```sh title="Terminal"
+npm install --save-dev --save-exact @mdbase-dev/connect-dev
+```
+
+## Check a manifest {#cli}
+
+```sh title="Terminal"
+npx mdbase-connect-dev validate-manifest mdbase-app.json
+npx mdbase-connect-dev validate-manifest mdbase-app.dev.json --allow-local
+npx mdbase-connect-dev validate-contract contracts/example.work-item.json
+```
+
+`validate-manifest` runs the parser mdbase uses when your app registers. It exits non-zero with a list of problems, each with the path of the field at fault.
+
+An HTTP homepage is refused unless you pass `--allow-local`. Use the flag for a [development manifest](/sdk/local-development/) and leave it off for the one you publish, so a localhost address cannot reach production by mistake.
+
+## Check it in a build {#build}
+
+```js title="scripts/write-manifest.mjs"
+import { formatValidationIssues, validateAppManifest } from "@mdbase-dev/connect-dev";
+
+const result = validateAppManifest(manifest, { allowLocal: false });
+if (!result.valid) {
+ // Each issue has a JSON pointer, such as /requirements/capabilities/required/2.
+ console.error(formatValidationIssues(result.issues));
+ process.exit(1);
+}
+```
+
+The SDK also validates the manifest when the app starts. Checking in the build moves the failure from your users’ browsers to your own terminal.
+
+## Build a type pack {#type-packs}
+
+A [type pack](/sdk/manifest/#provisioning) carries the type and contract files your app adds to a collection. Inside a manifest every file is pinned by a SHA-256 digest. `defineTypePack()` reads the documents, computes the digests and returns the object to place under `provisions.type_packs`:
+
+```js title="scripts/write-manifest.mjs"
+import { defineTypePack } from "@mdbase-dev/connect-dev";
+
+const types = defineTypePack({
+ id: "dev.example.worklog",
+ version: "1.0.0",
+ name: "Worklog",
+ resources: [
+ {
+ kind: "type",
+ mode: "seed",
+ source: "types/worklog-entry.md",
+ target: "_types/worklog-entry.md",
+ document: await readFile("mdbase/types/worklog-entry.md", "utf8"),
+ },
+ ],
+});
+
+// In the manifest:
+// "provisions": { "type_packs": [types] }
+```
+
+| Resource field | Meaning |
+| --- | --- |
+| `kind` | `"type"`, `"contract"` or `"schema"` |
+| `mode` | `"seed"` or `"managed"`; see below |
+| `source` | The file’s name inside the pack |
+| `target` | Where it goes in the collection, such as `_types/worklog-entry.md`. Defaults to `source`. |
+| `document` | The file’s exact text |
+| `upgradeFrom` | Seed types only: earlier versions you shipped, oldest first, that a collection may be upgraded from |
+
+Keep the documents as real files in your repository and read them in the script. They are then reviewable in a pull request, and the manifest is a build output.
+
+## Seed and managed {#modes}
+
+| Mode | Who owns the file after setup | Use it for |
+| --- | --- | --- |
+| `seed` | The user. Your app writes it once; later edits by the user stay. | A type people may want to extend with fields of their own |
+| `managed` | Your app. A new version of your pack updates it. | A contract, or a type whose exact shape your app depends on |
+
+Adding files to a collection needs the `definitions.manage` capability in your manifest, and the user sees and accepts the change first. See [Setup](/sdk/lifecycle/#setup).
+
+## Contracts
+
+`defineDataContract()` validates a [contract](/sdk/contracts/) document as you write it, and `dataContractDigest()` computes the digest a manifest names it by.
+
+```js title="contracts.mjs"
+import { dataContractDigest, defineDataContract } from "@mdbase-dev/connect-dev";
+
+const workItem = defineDataContract({
+ // the contract document; see Contracts and adapters
+});
+
+// The digest to put in requirements.contracts and in a type pack's provides.
+const digest = dataContractDigest(workItem);
+```
+
+`validate-contract` on the command line checks a contract file the same way.
+
+## A whole manifest script {#script}
+
+The Worklog example writes its development and deployed manifests from one script, validating each:
+
+```js title="scripts/write-manifest.mjs" file="examples/worklog/scripts/write-manifest.mjs"
+```
+
+## The sandbox {#sandbox}
+
+The package also exports `createSandbox()`. It is for the older `@mdbase-dev/connect` client. With `@mdbase-dev/sdk`, test against `MemoryReplica` and `createApplicationFixture()`; see [Testing](/sdk/testing/).
diff --git a/content/sdk/connect-quickstart.md b/content/sdk/connect-quickstart.md
new file mode 100644
index 0000000..ca6e4aa
--- /dev/null
+++ b/content/sdk/connect-quickstart.md
@@ -0,0 +1,166 @@
+---
+title: Build an app
+description: "Build Worklog, a small React app that keeps its entries in the user’s mdbase collection, from an empty folder to a deployed site."
+section: sdk
+---
+
+## What you build {#result}
+
+Worklog is a one-screen app: a form that adds an entry, and a list of entries that stays current. Each entry is a Markdown file in the user’s collection, so the user can also open it in the [mdbase apps](/apps/), in Obsidian, or in any text editor.
+
+The finished app is about 150 lines. mdbase supplies sign-in, the collection picker, storage, sync and conflict handling. The complete project is in [`examples/worklog`](https://github.com/mdbase-dev/mdbase.dev/tree/main/examples/worklog); every listing on this page is a file from it.
+
+> **What you need**
+>
+> Node 20 or later. You need no account to start: the app first runs in a collection kept in your browser. Signing in to an mdbase account comes at step 7. Developing on `http://localhost` needs an `@mdbase-dev/sdk` release after `0.1.0-beta.168`.
+
+## 1. Create the project {#project}
+
+```sh title="Terminal"
+npm create vite@latest worklog -- --template react-ts
+cd worklog
+
+npm install --save-exact @mdbase-dev/sdk @mdbase-dev/ui @mdbase-dev/i18n \
+ @lingui/core@6.9.0 @lingui/react@6.9.0
+npm install --save-dev --save-exact @mdbase-dev/connect-dev
+```
+
+`@mdbase-dev/sdk` is the client. `@mdbase-dev/ui` has the sign-in and collection screens; `@mdbase-dev/i18n` and the two Lingui packages are its peer dependencies. `@mdbase-dev/connect-dev` checks the manifest at build time. The packages are in beta, so the versions are pinned exactly.
+
+Delete the template’s `src/App.tsx`, `src/App.css` and `src/index.css`; the steps below replace them. Then fix the development port, because the manifest names the exact origin the app is served from:
+
+```ts title="vite.config.ts" file="examples/worklog/vite.config.ts"
+```
+
+## 2. Describe your records {#type}
+
+Every record in a collection has a type, and a type is itself a Markdown file in the collection’s `_types/` folder. Worklog needs one. Write the copy your app will offer to a collection that lacks it:
+
+```md title="mdbase/types/worklog-entry.md" file="examples/worklog/mdbase/types/worklog-entry.md"
+```
+
+The schema is JSON Schema. mdbase checks every write against it, so an entry with no `summary` is refused before it is saved. `additionalProperties: true` lets the user and other apps keep fields of their own on the same records.
+
+## 3. Write the manifest {#manifest}
+
+The manifest tells mdbase who your app is and what it needs. It names the origin the app is served from, so development and the deployed site each need their own. A short script writes either one:
+
+```js title="scripts/write-manifest.mjs" file="examples/worklog/scripts/write-manifest.mjs"
+```
+
+- **`id`** is a lowercase reverse-domain name with at least three parts. Use a domain you control.
+- **`homepage` and `redirect_uris`** are on the app’s origin. A browser app can list its homepage as the one redirect URI.
+- **`capabilities` and `files`** are what the user is asked to approve. Ask for what you use; [Authorization](/sdk/authorization/) lists them. `definitions.manage` is there so the app can add its type to a collection the user already has.
+- **`provisions.type_packs`** carries the type document from step 2. See [Provisioning](/sdk/manifest/#provisioning).
+
+Run the script before the development server and before a build:
+
+```json title="package.json" file="examples/worklog/package.json" pick="scripts"
+```
+
+Add `src/mdbase-app.json` to `.gitignore`: it is generated.
+
+## 4. Declare the app {#entry}
+
+```ts title="src/mdbase.ts" file="examples/worklog/src/mdbase.ts"
+```
+
+Create one entry for the whole app. Creating it does no work; the SDK starts on the first call. It registers the manifest with mdbase when the app starts, so there is no application ID to request first.
+
+- `origin` must be the exact origin the page is served from. Reading it from the manifest keeps the two in step.
+- `environment` is `"production"` on localhost too. Your development build talks to the same mdbase service your users do.
+- `unsynced: true` lets people use the app before they sign in. Their work is kept in the browser until they connect a collection. See [Work before connecting](/sdk/unsynced/).
+
+## 5. Sign-in and collections {#gate}
+
+Between opening the app and seeing their entries, a user may need to sign in, pick or create a collection, approve your app’s access, and let it add its type. `CollectionGate` from `@mdbase-dev/ui` shows each of those screens and renders your app once a collection is open.
+
+```tsx title="src/App.tsx" file="examples/worklog/src/App.tsx"
+```
+
+The gate hands your app a `connection`. Its `records` property is an `MdbaseClient` for the open collection. `CollectionSwitcher` is the control for changing collection, adding one and signing out. Keying the screen on `connection.id` resets it when the user switches.
+
+The entry point loads the gate’s stylesheet:
+
+```tsx title="src/main.tsx" file="examples/worklog/src/main.tsx"
+```
+
+[UI components](/sdk/ui/) covers restyling and the other components. To draw these screens yourself, see [Sign-in and collections](/sdk/lifecycle/).
+
+## 6. Read and write records {#records}
+
+```tsx title="src/Worklog.tsx" file="examples/worklog/src/Worklog.tsx"
+```
+
+- **The list is a live query.** `db.live()` sends the current entries and then every change, including ones made in another app or on another device. Nothing in this file refetches.
+- **Writes return at once.** `db.create()` resolves when the entry is saved on this device, and the live query already shows it. Sync continues in the background, online or offline.
+- **A record needs a path.** Records are files. Pass `path`, or give the type a path pattern.
+- **A refused write does not throw.** When the collection refuses a write, such as an entry the type does not allow, the returned `Write` has `state: "rejected"` and `receipt.problem` says why. `describeError()` turns that, or a thrown error, into a sentence you can show.
+
+[Records and operations](/sdk/operations/) has the rest: queries, updates, renames, attachments.
+
+## 7. Run it on localhost {#run}
+
+```sh title="Terminal"
+npm run dev
+```
+
+Open `http://localhost:5173`. The app opens straight away in its unsynced collection. Add an entry: a line appears saying the work is saved only in this browser. Reload, and the entry is still there.
+
+Choose **Connect to sync your work** to sign in. mdbase opens in a window and asks you to approve the app. Because the app is on `localhost`, that screen calls it “an app running on this computer” and says its identity is unverified. Then:
+
+- A collection you create during sign-in gets the `worklog-entry` type automatically.
+- A collection you already had shows a short review first: “Set up (collection) for Worklog”, listing the type file to be added. Nothing changes until you accept it.
+- The entries you made before signing in are offered to the collection you opened. Bringing them in keeps their IDs, and running it twice creates nothing twice.
+
+Open the same collection in the [Editor](https://editor.mdbase.dev/): your entries are files under `worklog/`. Change one there and the list in your app updates.
+
+[Develop on localhost](/sdk/local-development/) explains what is different about a development build.
+
+## 8. Deploy {#deploy}
+
+```sh title="Terminal"
+WORKLOG_ORIGIN=https://worklog.example.com npm run build
+# Upload dist/ to the static host that serves https://worklog.example.com
+```
+
+The build is a folder of static files. Host it anywhere that serves HTTPS at the origin you built for. There is no server component, no API key and no secret: the app holds nothing until a user signs in and approves it.
+
+- The manifest’s `homepage` origin and the site’s origin must match exactly, including `www` and any port.
+- The deployed app is a separate application from your localhost build. Users approve it on its own, and its storage is its own.
+- Before you ship, change `id` from `dev.example.worklog` to a name under your own domain.
+
+## Other frameworks
+
+Only `App.tsx` and the hooks in `Worklog.tsx` are React. The entry is a plain object with a snapshot you subscribe to, and a `phase` that says where the user is:
+
+```ts title="main.ts"
+import { mdbase } from "./mdbase";
+
+mdbase.subscribe(() => render(mdbase.getSnapshot()));
+await mdbase.start();
+
+// Call signIn() straight from the click, so the browser allows its window.
+signInButton.onclick = () => mdbase.signIn();
+
+function render(snapshot) {
+ const { phase } = snapshot;
+ if (phase.kind === "ready" || phase.kind === "unsynced") {
+ showWorklog(phase.connection.records);
+ } else if (phase.kind === "choosing") {
+ showPicker(snapshot.collections, (id) => mdbase.select(id));
+ } else {
+ showScreen(phase.kind); // "signed_out", "authorizing", "needs_setup", …
+ }
+}
+```
+
+You can draw each phase yourself, or mount the shared screens into an element with `mountCollectionUi()`; see [UI components](/sdk/ui/#mount).
+
+## Next steps {#next}
+
+- [Records and operations](/sdk/operations/): queries, updates, renames and attachments.
+- [Editing records](/sdk/editing/): a screen where people type into one record.
+- [Pending writes and sync status](/sdk/offline-sync/): show what is saved and what is waiting.
+- [Contracts and adapters](/sdk/contracts/): work with records other apps also use.
+- [Testing](/sdk/testing/): run the same code against an in-memory collection.
diff --git a/content/sdk/contracts.md b/content/sdk/contracts.md
new file mode 100644
index 0000000..f8a50b3
--- /dev/null
+++ b/content/sdk/contracts.md
@@ -0,0 +1,85 @@
+---
+title: Contracts and adapters
+description: Build on shared contracts, so your app works with collections that use their own field names.
+section: sdk
+---
+
+Every `mdbase.contract` has a stable ID, a semantic version, an exact digest and a JSON Schema. Its `contract_type` says what it describes: a **record** view, an **event**, or an **action**. Browse published ones in the [contract catalog](/contracts/).
+
+Only record contracts are implemented by type files. A type opts in with `implements` and maps contract field names to its own frontmatter fields. One type can implement several contracts, and several apps can read the same contract.
+
+## Implement a contract in the type file {#type-file}
+
+```yaml title="_types/project_item.md"
+kind: mdbase.type
+name: project_item
+version: 1
+schema:
+ dialect: json-schema-2020-12
+ value:
+ type: object
+ required: [heading, stage]
+ properties:
+ heading: { type: string, minLength: 1 }
+ stage: { type: string }
+implements:
+ - contract: example.work-item
+ version: 1.0.0
+ fields:
+ title: heading
+ status: stage
+ binding:
+ status:
+ completed_values: [done, cancelled]
+```
+
+The type’s schema governs what is stored. `fields` maps contract fields to the type’s fields; it does not transform values. The optional `binding` records choices the contract allows, such as which status values count as complete, without changing what is stored. Keep unknown fields and extensions when you edit a type.
+
+## Read the collection’s contracts {#contract}
+
+```ts title="contract.ts"
+const description = await db.describe();
+
+const workItem = description.contracts.find(
+ (c) => c.id === "example.work-item" && c.version === "1.0.0",
+);
+if (!workItem) {
+ throw new Error("This collection has no example.work-item 1.0.0 contract");
+}
+
+for (const type of description.types) {
+ for (const impl of type.implements) {
+ if (impl.contract === workItem.id && impl.version === workItem.version) {
+ console.log(type.name, Object.fromEntries(impl.fields)); // contract field → type field
+ }
+ }
+}
+```
+
+`describe()` lists each contract with its `id`, `version`, `digest`, `contractType` and the types that implement it. Each type lists its `implements` entries with the field mapping and binding. Don’t look for meaning in `x-*` extensions.
+
+## Query through a contract {#own-adapter}
+
+```ts title="work-items.ts"
+import { toPlain, type MdbaseClient } from "@mdbase-dev/sdk";
+
+export async function listWorkItems(db: MdbaseClient) {
+ const result = await db.queryContract(
+ { id: "example.work-item", version: "1.0.0" },
+ { pageSize: 100 },
+ );
+ // Each record lists one projection per type that implements the contract.
+ return result.records.map((record) => ({
+ id: record.id,
+ fields: toPlain(record.implementations[0].fields),
+ }));
+}
+```
+
+`queryContract()` returns records under the contract’s field names, across every type that implements it. Each projection carries the type name and any validation `issues`. It returns one page at a time, up to 128 records; pass `cursor` for the next. To write under the contract’s field names, pass `contract: { id, version }` to `create()` or `update()`. The replica maps the fields to the type’s own fields, and refuses fields it can’t map.
+
+## Keep domain behaviour with its app {#ownership}
+
+The SDK is application-neutral. An app owns its contract vocabulary, model and adapter code. That keeps app conventions out of the protocol and lets more than one app read the same collection in its own way.
+
+Event sources and action providers declare their implementations through the [interoperability profile](https://github.com/mdbase-dev/mdbase-spec/blob/main/interop/0.1.md), not through a type file.
diff --git a/content/sdk/editing.md b/content/sdk/editing.md
new file mode 100644
index 0000000..a9e2257
--- /dev/null
+++ b/content/sdk/editing.md
@@ -0,0 +1,90 @@
+---
+title: Editing records
+description: "Keep one record open while people type: autosave, conflicts, lost responses and deletions handled by one shared session."
+section: sdk
+---
+
+An app that lets people type into a record should not call `update()` on every keystroke. Open the record as a session instead. The session saves after a pause in typing, never runs two saves for the same record at once, and tells your interface what state the record is in.
+
+## Open a record {#open}
+
+```ts title="editor.ts"
+const lease = await db.records.open({ path: "notes/today.md" }, {
+ autosave: { idleMs: 1_000 }, // leave out for explicit flush() only
+});
+const { session } = lease;
+
+const unsubscribe = session.subscribe(() => render(session.getSnapshot()));
+editor.onChange((text) => session.setBody(text));
+properties.onChange((patch) => session.patchFrontmatter(patch)); // undefined unsets a key
+```
+
+`db.records.open()` takes an ID, a `{ path }` or a record you read. It returns a lease: the `session` and a `release()` function for this view. Every view that opens the same record on the same client shares one session, so your app never has two competing writers for it. Views that share a session must use the same autosave setting.
+
+The lease is local to your app. It does not lock the record for anyone else.
+
+## Stay current while it is open {#follow}
+
+An open session follows the collection’s change feed. When the record changes elsewhere, the session reads it again. Without local changes, it shows the newer record. With local changes, it moves to `conflict` and keeps both: your text, and the newer record in `snapshot.remote`.
+
+## States
+
+- `saved`: the text is the record, confirmed by the log.
+- `saved_on_device`: the text is kept on this device and syncs when the log can be reached.
+- `unsaved`: local changes wait for autosave or `flush()`.
+- `saving`: a save is in flight. Typing continues; newer text is saved next.
+- `conflict`: the record changed elsewhere while you had unsaved changes, or it is held.
+- `recovery`: a save’s outcome is not known yet. The session waits for that save’s own receipt and never sends a replacement.
+- `error`: the last save failed. Your text is kept.
+- `deleted`: the record no longer exists. Your text is kept.
+
+`snapshot.problem` holds the error behind `error` and `recovery`. `snapshot.dirty` tells you whether there are unsaved changes.
+
+## Conflicts
+
+Each save also checks the revision your text was based on, so a change the session hasn’t seen yet still can’t be overwritten. In `conflict`, let the user choose:
+
+```ts title="conflict.ts"
+session.resolve({ keep: "mine" }); // put your changes on top of the newer record
+session.resolve({ keep: "theirs" }); // take the newer record
+session.resolve({ body: merged }); // save text the user merged
+```
+
+A session can’t resolve a [hold](/sdk/offline-sync/#holds). Held records stay protected until the user resolves the hold itself.
+
+## Leave safely {#leave}
+
+```ts title="leave.ts"
+const result = await session.flush({ timeoutMs: 8_000 });
+if (!result.ok) {
+ const snapshot = session.getSnapshot();
+ if (snapshot.state === "conflict") {
+ showConflict(snapshot.body, snapshot.remote); // your text and the newer record
+ } else {
+ showProblem(result.problem);
+ }
+}
+unsubscribe();
+lease.release();
+```
+
+`flush()` resolves once there is nothing left to save and the log has confirmed it, or tells you why it can’t. If the change is kept on this device but not confirmed yet, it resolves with `ok: true` and `saved: "on_device"`. Releasing the last view stops autosave but keeps unsaved text, so opening the record again on the same client picks it up. A client keeps at most 64 sessions with unsaved text; settle some before opening more.
+
+## Survive a reload {#custom}
+
+Unsaved text lives in memory. If a save was sent but its outcome is not yet known when the page reloads, keep the session’s recovery reference and pass it back to `open()`. The session then finishes that same save instead of writing again.
+
+```ts title="recover.ts"
+// Keep this with your own saved state, for example in IndexedDB.
+const recovery = session.getSnapshot().recovery;
+if (recovery) {
+ saveRecovery({
+ mutationId: recovery.mutationId,
+ recordId: recovery.recordId,
+ baseRevision: recovery.baseRevision,
+ });
+}
+
+// After a reload:
+const lease = await db.records.open(recordId, { recovery: loadRecovery() });
+```
diff --git a/content/sdk/index.md b/content/sdk/index.md
new file mode 100644
index 0000000..69b9f98
--- /dev/null
+++ b/content/sdk/index.md
@@ -0,0 +1,124 @@
+---
+title: SDK overview
+description: "Build apps whose data lives in the user’s own mdbase collection. @mdbase-dev/sdk is the TypeScript client: local reads, optimistic writes, live queries and sign-in."
+section: sdk
+---
+
+An mdbase collection is a folder of Markdown files with typed frontmatter, synced across a person’s devices. An app built with the SDK reads and writes the records in a collection its user chooses.
+
+## Where to start {#start}
+
+**Build an app**
+
+Build Worklog, a small app that signs a user in and keeps its entries in their collection, from an empty folder to a deployed site. It uses React, and its last section shows the same app without React.
+
+[Follow the tutorial](/sdk/connect-quickstart/)
+
+**Try the SDK in memory**
+
+Run a short script against an in-memory collection. It needs no account or service, and shows reads, writes and live queries.
+
+[Run the script](/sdk/quickstart/)
+
+**Develop on localhost**
+
+Run your app from a development server against real accounts and collections.
+
+[Set up local development](/sdk/local-development/)
+
+**The format**
+
+Build tools that read and write mdbase collections as files, with no SDK.
+
+[Read the specification](/spec/)
+
+## Why build on mdbase {#why}
+
+- **You run no backend.** The user’s collection is your app’s database. A finished app is a folder of static files: no server, no database to operate and no API key to guard.
+- **Sign-in, sync and offline are done.** The SDK signs the user in, keeps a copy of the collection on the device, saves writes there at once and syncs them when it can. Edits made on two devices merge field by field, and a value that loses is kept for review.
+- **Users bring their data, and keep it.** Records are Markdown files the user owns. They can open them in mdbase’s [Editor, Reader and Writer](/apps/), in Obsidian, or in a text editor, and they still have them if they stop using your app.
+- **Apps can share records.** A [contract](/sdk/contracts/) names a shape of record, such as a task. Two apps that use the same contract work on the same records in one collection, with no integration between them.
+- **Access is the user’s decision.** Your app asks for the capabilities in its [manifest](/sdk/manifest/), the user approves them for one collection, and can withdraw them later. See the [security model](/sdk/security/).
+
+## How the SDK works {#model}
+
+Your app talks to a **replica** of the collection: a copy that applies changes in the order the collection’s log confirms them. The SDK gives you that replica’s view, plus your own writes that are still waiting.
+
+- **Reads are local.** `get`, `query` and `live` answer from the replica’s view. They include your pending writes.
+- **Writes are intents.** Each write returns at once with a receipt in the `pending` state. It becomes `confirmed` when the log accepts it, or `rejected` with a reason.
+- **Nothing is lost silently.** Concurrent edits to the same field are merged, and the losing value is kept as a conflict you can review. A file-backed replica can also put a local edit on hold instead of overwriting it.
+
+[Pending writes and sync status](/sdk/offline-sync/) covers receipts, holds and conflicts.
+
+## Getting a client {#choose-a-surface}
+
+Every client comes from `connect()`, given a **connector** that says how to reach a replica:
+
+| You are building | How you reach the collection |
+| --- | --- |
+| A web or mobile app | `createMdbase()` signs the user in and hands you a connection. Its client is an ordinary `MdbaseClient`. See [Build an app](/sdk/connect-quickstart/). |
+| A script or plugin on a computer running the mdbase desktop app | Connectors from `@mdbase-dev/sdk/node` reach the desktop app’s replica on the same machine. See [How apps reach a collection](/sdk/routing/). |
+| Tests and demo modes | `MemoryReplica` from `@mdbase-dev/sdk/testing`. See [Testing](/sdk/testing/). |
+
+## Application shape
+
+Keep domain code on `MdbaseClient`. It then runs unchanged against any connector.
+
+```ts title="tasks.ts"
+import type { MdbaseClient } from "@mdbase-dev/sdk";
+
+// Accept the client, not a connector, so the same code runs against
+// a real collection and against MemoryReplica in tests.
+export async function listOpenTasks(db: MdbaseClient) {
+ const page = await db.query({
+ types: ["task"],
+ where: 'status == "open"',
+ order_by: [{ field: "due", direction: "asc" }],
+ limit: 50,
+ });
+ return page.records;
+}
+```
+
+## Packages {#package-map}
+
+| Package | What it is for |
+| --- | --- |
+| `@mdbase-dev/sdk` | The client. `createMdbase` for apps, `connect` and `MdbaseClient` for everything that reads and writes records. [API reference](/sdk/api/). |
+| `@mdbase-dev/ui` | The sign-in, collection picker, approval and setup screens as React components. [UI components](/sdk/ui/). |
+| `@mdbase-dev/connect-dev` | Build-time tools: the manifest checker and the type pack builder. [Developer kit](/sdk/connect-dev/). |
+
+The SDK has several entry points:
+
+| Import | What it gives you |
+| --- | --- |
+| `@mdbase-dev/sdk` | `createMdbase`, `connect`, `MdbaseClient`, errors and status helpers |
+| `@mdbase-dev/sdk/describe` | `describeError`: a title, message and action for any failure |
+| `@mdbase-dev/sdk/testing` | `MemoryReplica` and test fixtures |
+| `@mdbase-dev/sdk/node` | Connectors to the desktop app over local IPC or localhost |
+| `@mdbase-dev/sdk/browser` | The same surface as a browser module. The package also ships a classic-script bundle; see [Browser bundle](/sdk/portable-apps/). |
+| `@mdbase-dev/sdk/account` | Encryption password and recovery key set-up for Private collections |
+
+The SDK needs Node 20 or later outside the browser. It is what apps use instead of the `@mdbase-dev/connect` beta.
+
+## Publishing an app {#publish}
+
+There is no review, registration form or API key. The SDK registers your manifest with mdbase the first time your app starts, and each user approves the app for their own collection. To publish, deploy the built files to an HTTPS origin; the [tutorial](/sdk/connect-quickstart/#deploy) ends with that step.
+
+The approval screen shows your app’s name and the site it is served from. mdbase does not verify who publishes an app, and an application ID is a label, so serve your app from an origin your users recognise.
+
+The [apps page](/apps/) lists the apps mdbase makes. There is no directory of other apps yet. If you build one, write to [callum@mdbase.dev](mailto:callum@mdbase.dev).
+
+## Stability {#status}
+
+`@mdbase-dev/sdk`, `@mdbase-dev/ui` and `@mdbase-dev/connect-dev` are in beta on npm.
+
+- The API can change between betas. Pin exact versions in an app you ship, and read the [release notes](https://github.com/mdbase-dev/mdbase-connect/releases) before you upgrade.
+- Publishing a new beta does not change an app that is already deployed; it keeps the SDK it was built with. If the service ever needs a newer one, the SDK reports a problem whose action is `update_app`.
+- The [collection format](/spec/) is specified separately and does not change with SDK releases. Records your app writes stay readable.
+
+## Getting help {#help}
+
+- Report a bug or ask a question in [GitHub issues](https://github.com/mdbase-dev/mdbase-connect/issues).
+- Email [callum@mdbase.dev](mailto:callum@mdbase.dev).
+- Report a security problem as the [security page](/security/) describes.
diff --git a/content/sdk/lifecycle.md b/content/sdk/lifecycle.md
new file mode 100644
index 0000000..36e1b50
--- /dev/null
+++ b/content/sdk/lifecycle.md
@@ -0,0 +1,251 @@
+---
+title: Sign-in and collections
+description: The phases an app moves through between opening and showing a collection, and the call that moves it from each one.
+section: sdk
+---
+
+`createMdbase()` returns one object for your whole app. It holds a snapshot of where the user is, and the actions that move them on. [`CollectionGate`](/sdk/ui/) draws every screen on this page for you; read on if you draw them yourself, or want to know what the gate is doing.
+
+## The snapshot {#snapshot}
+
+`mdbase.getSnapshot()` returns the current state, and `mdbase.subscribe(listener)` calls you when it changes. The snapshot object is replaced on every change, so it works with [`useSyncExternalStore`](/sdk/react/) and with plain equality checks.
+
+| Field | Meaning |
+| --- | --- |
+| `phase` | Where the user is. Render from this. |
+| `collections` | The collections this app may open, for a picker. |
+| `selectedCollectionId` | The open collection, or null. |
+| `sync` | Sync state of the open collection, as `summarizeStatus()` returns it. |
+| `writes` | Unconfirmed and refused writes of the open collection. See [Pending writes and sync status](/sdk/offline-sync/). |
+| `links` | `account` and `manageAccess`: mdbase pages to link to for the account and for who can reach the collection. |
+| `unsyncedWork` | Set when work saved before connecting has not been brought in. See [Work before connecting](/sdk/unsynced/). |
+
+## Phases
+
+`snapshot.phase.kind` is always exactly one of these. Switch on it; do not build a ready check from other fields.
+
+```ts title="main.ts"
+import { describeError } from "@mdbase-dev/sdk/describe";
+import { mdbase } from "./mdbase";
+
+mdbase.subscribe(() => render(mdbase.getSnapshot()));
+await mdbase.start();
+
+function render(snapshot) {
+ const { phase } = snapshot;
+ switch (phase.kind) {
+ case "starting":
+ return showSplash();
+ case "signed_out":
+ return showSignIn(phase.notice?.message);
+ case "authorizing":
+ return showWaiting("Continue in the mdbase window");
+ case "choosing":
+ return showPicker(snapshot.collections);
+ case "opening":
+ return showOpening(phase.displayName, { slow: phase.slow });
+ case "needs_approval":
+ return showApprove(phase.displayName);
+ case "needs_setup":
+ return showSetup(phase.collection);
+ case "ready":
+ case "unsynced":
+ return showApp(phase.connection);
+ case "problem":
+ case "unavailable":
+ return showProblem(phase.problem);
+ case "closed":
+ return;
+ }
+}
+```
+
+| Phase | The user is | What moves them on |
+| --- | --- | --- |
+| `starting` | Waiting for the SDK to restore a signed-in device | Nothing; it settles by itself |
+| `signed_out` | Not signed in. `notice` says why when sign-in just ended. | `signIn()` |
+| `authorizing` | In the mdbase window. `purpose` is `sign_in`, `add` or `approve`. | The user finishes or closes the window |
+| `choosing` | Signed in with nothing open | `select(id)`, `addCollection()` |
+| `opening` | Waiting for a collection to open. `slow` turns true after 15 seconds. | Nothing; `chooseAnother()` to leave |
+| `needs_approval` | Looking at a collection this app is not approved for, usually from a shared link | `approve()` |
+| `needs_setup` | In a collection that lacks something the manifest provides, such as your types | `setup.plan()` then `setup.apply(plan)` |
+| `ready` | In an open collection. Use `phase.connection`. | |
+| `unsynced` | Working before connecting. Use `phase.connection` as when ready. | `signIn()` to connect |
+| `problem` | Stopped. `phase.problem` has the wording and one action. | The action in `problem.action` |
+| `unavailable` | Somewhere the SDK cannot run: server rendering, or an unsupported browser | |
+| `closed` | After `close()` | |
+
+Once a collection is `ready` it stays ready through re-checks and passing problems; `phase.rechecking` and `phase.problem` report them for a status line. Your app screen is not torn down while the network drops and returns.
+
+`phase.connection` has `records` (the [`MdbaseClient`](/sdk/operations/)), `files`, `people` and, when the manifest asks for them, `timers`.
+
+## Calls that open a window {#gestures}
+
+Sign-in and approval happen on mdbase’s own pages, in a window the SDK opens. Browsers only allow that during a click or key press.
+
+```ts title="main.ts"
+// Each of these opens the mdbase window, so call it directly in the
+// click handler. After an await, the browser blocks the window.
+signInButton.onclick = () => mdbase.signIn();
+addButton.onclick = () => mdbase.addCollection();
+approveButton.onclick = () => mdbase.approve();
+reconnectButton.onclick = () => mdbase.reauthorize();
+```
+
+| Call | What the user does in the window |
+| --- | --- |
+| `signIn()` | Signs in, then picks or creates a collection and approves your app for it |
+| `addCollection()` | Picks another collection or creates one. Nothing is preselected. |
+| `approve(id?)` | Approves one named collection; by default, the one the URL asks for |
+| `reauthorize()` | Approves the open collection again, after access was lost or the app’s manifest asks for more |
+| `requestAccess()` | Allows an optional file action. See [below](#access). |
+
+Each call resolves with the new snapshot when the window closes. In the `choosing` phase, `phase.lastApproval.outcome` says how the last one ended: `added`, `unchanged`, `declined` or `closed`.
+
+## Collections
+
+```ts title="picker.ts"
+const { collections, selectedCollectionId } = mdbase.getSnapshot();
+
+for (const item of collections) {
+ // item.collectionId, item.displayName, item.role: "owner" | "editor" | "viewer"
+ addRow(item.displayName, () => mdbase.select(item.collectionId));
+}
+
+// Back to the list; the browser's Back button returns to the collection.
+switchButton.onclick = () => mdbase.chooseAnother();
+
+// Hide one on this device. It stays approved and nothing is deleted.
+await mdbase.forget(collectionId);
+```
+
+- The list is re-read when the page regains focus. Call `refreshCollectionList()` to re-read it at another moment, such as when a menu opens.
+- `deleteCollection(id, { confirmName })` deletes a collection for everyone, on every device. Only its owner can, and `confirmName` must be the collection’s name as the user typed it.
+- A collection kept on the user’s own computers has `kind: "private"`. It opens the same way; see [Private collections](/sdk/authorization/#private).
+
+## The URL {#url}
+
+The SDK keeps the open collection in the page URL as `?collection=` and follows Back and Forward. A link with that parameter opens that collection for anyone the app is approved for, and takes others to `needs_approval`. The rest of the URL, path and hash included, is yours.
+
+## Setup
+
+A collection is in `needs_setup` when it lacks something your manifest’s [provisions](/sdk/manifest/#provisioning) supply. Setup shows the user what would be added and applies it only when they accept.
+
+```ts title="setup.ts"
+const plan = await mdbase.setup.plan();
+
+if (plan.status === "current") {
+ // Nothing to do.
+} else if (plan.canApply) {
+ showReview(plan.summary, plan.changes.map((change) => change.message));
+ // When the user accepts:
+ const result = await mdbase.setup.apply(plan);
+ if (result.outcome === "changed") {
+ // The collection changed while the user was reading. Plan again.
+ }
+} else {
+ showBlocked(plan.refusal?.message, plan.conflicts.map((c) => c.message));
+}
+```
+
+- `plan.summary` and each `change.message` are written to be shown as they are. `plan.staged` has the documents themselves, for a details view.
+- Setup needs the `definitions.manage` capability. An app that lacks it gets a plan with `refusal.code` `"setup_forbidden"`.
+- When a file already in the collection differs from yours, the plan has `status: "conflict"`. Conflicts listed in `plan.adoptable` can be resolved by taking your version: pass them back as `setup.plan({ adopt })`.
+- `setup.plan({ records })` adds starter records, such as a welcome note, written with the setup when their path is free.
+- `configure()` plans and applies in one call, for an app with nothing to review.
+
+A collection the user creates while signing in to your app is set up during sign-in, so new users do not see this screen.
+
+## Asking for more access {#access}
+
+File actions listed as `optional` in the manifest are asked for at the moment the user first needs them.
+
+```ts title="attach.ts"
+// The manifest lists "add" under files.optional.
+attachButton.onclick = async () => {
+ const result = await mdbase.requestAccess(
+ { files: ["add"] },
+ { reason: "Attach images to your entries" },
+ );
+ if (result.status === "granted") await attachImage();
+};
+```
+
+The result is `granted`, `declined` or `cancelled`. An action that is already allowed resolves `granted` at once and opens nothing. The reason is one line of at most 140 characters, shown to the user. The collection stays open throughout.
+
+## Lost access {#lost}
+
+A user can remove your app’s access on their account page at any time. The collection then stops with a problem whose action is `approve`; offer a button that calls `reauthorize()`. Link to `snapshot.links.manageAccess` wherever your app says who can reach the collection; that page is where access is managed.
+
+## Signing out {#sign-out}
+
+```ts title="account.ts"
+import { isMdbaseError } from "@mdbase-dev/sdk";
+
+try {
+ await mdbase.signOut();
+} catch (error) {
+ if (isMdbaseError(error) && error.reason === "sign_out_pending_writes") {
+ // Changes on this device have not reached mdbase yet.
+ if (await confirmDiscard()) await mdbase.signOut({ discard: true });
+ } else {
+ throw error;
+ }
+}
+```
+
+Signing out ends the session and removes this browser’s copy of the account’s collections and keys. It is refused while changes are still waiting to sync, so that work is not thrown away by accident.
+
+## Problems
+
+```ts title="problem.ts"
+import { describeError } from "@mdbase-dev/sdk/describe";
+
+function showProblem(problem) {
+ // problem.title, problem.message, and one action to offer.
+ title.textContent = problem.title;
+ body.textContent = problem.message;
+}
+
+// The same for anything a call throws:
+try {
+ await mdbase.select(id);
+} catch (error) {
+ const described = describeError(error);
+ if (described) showProblem(described);
+}
+```
+
+`describeError()` accepts a thrown error, a refused write’s `receipt.problem`, or a phase’s problem, and returns a title, a message and one action. It returns `null` when there is nothing to show, such as a request your own code aborted.
+
+| `action` | What to offer |
+| --- | --- |
+| `sign_in` | A button that calls `signIn()` |
+| `approve` | A button that calls `approve()` or `reauthorize()` |
+| `choose_collection` | `chooseAnother()` |
+| `set_up` | Your [setup](#setup) review |
+| `retry` | `start()`, or the call that failed |
+| `wait` | Nothing to press; `retryAfterMs` may say how long |
+| `reload` | Reload the page |
+| `update_app` | A link to `updateUrl` |
+| `free_space`, `check_connection`, `resolve_outcome`, `contact_support`, `none` | The message says what to do; there is nothing to call |
+
+`actionLabel` is the button’s wording, and `transient` is true for problems the SDK clears by itself, which can be shown quietly.
+
+## Sign-in outside a popup {#opener}
+
+A native shell or a browser extension cannot open a popup. Pass a `signIn` opener and the SDK gives it the URL to show:
+
+```ts title="mdbase.ts"
+import { Browser } from "@capacitor/browser";
+
+export const mdbase = createMdbase(declaration, {
+ signIn: {
+ open: (url) => Browser.open({ url }),
+ close: () => Browser.close(),
+ returnUrl: "dev.example.worklog://auth/mdbase/callback",
+ },
+});
+```
+
+`returnUrl` must be one of the manifest’s `redirect_uris`. mdbase sends the browser there when sign-in ends. It carries no credential; the SDK learns the result itself.
diff --git a/content/sdk/local-development.md b/content/sdk/local-development.md
new file mode 100644
index 0000000..cecb6ec
--- /dev/null
+++ b/content/sdk/local-development.md
@@ -0,0 +1,126 @@
+---
+title: Develop on localhost
+description: Run your app from a local development server against real mdbase accounts and collections.
+section: sdk
+---
+
+You develop against the same mdbase service your users use. There is no development mode, sandbox key or allowlist to apply for.
+
+> **SDK version**
+>
+> Use an `@mdbase-dev/sdk` release after `0.1.0-beta.168`. Earlier releases refuse an `http://localhost` origin and fail to load under `vite dev`.
+
+## What is accepted {#rule}
+
+Your app’s origin may be plain HTTP when it is on this computer:
+
+- `http://localhost:`
+- `http://127.0.0.1:`
+- `http://[::1]:`
+
+Any port works. Every other app origin must be HTTPS, including a development machine reached by its LAN address or a tunnel hostname.
+
+## A development manifest {#manifest}
+
+A manifest names the origin its app is served from, so keep two: the one you publish, with your HTTPS homepage, and one for development whose `homepage` and `redirect_uris` use the development server’s origin.
+
+```json title="mdbase-app.dev.json"
+{
+ "manifest_version": 1,
+ "id": "dev.example.worklog",
+ "name": "Worklog (development)",
+ "homepage": "http://localhost:5173/",
+ "redirect_uris": ["http://localhost:5173/"],
+ "requirements": {
+ "access": "full_collection",
+ "contracts": [],
+ "capabilities": {
+ "contract_version": 2,
+ "required": ["collection.read", "records.create", "records.edit"]
+ }
+ }
+}
+```
+
+Everything else can be the same. You can keep two files, or write both from one script as the [Worklog tutorial](/sdk/connect-quickstart/#manifest) does.
+
+The manifest checker refuses an HTTP homepage by default, so that a development manifest is caught before it ships. Pass `--allow-local` for the development one:
+
+```sh title="Terminal"
+npx mdbase-connect-dev validate-manifest mdbase-app.dev.json --allow-local
+npx mdbase-connect-dev validate-manifest mdbase-app.json
+```
+
+The published [JSON Schema](/connect/schemas/mdbase-app.v1.json) describes the deployed form, so an editor that validates against it marks an HTTP homepage. The checker with `--allow-local` is the authority for a development manifest.
+
+## Declare the app {#entry}
+
+```ts title="mdbase.ts"
+import { createMdbase } from "@mdbase-dev/sdk";
+import manifest from "./mdbase-app.json"; // the development or the deployed one
+
+export const mdbase = createMdbase({
+ id: manifest.id,
+ name: manifest.name,
+ origin: new URL(manifest.homepage).origin, // "http://localhost:5173"
+ environment: "production",
+ manifest,
+});
+```
+
+`environment` stays `"production"`. It names the mdbase service your app talks to, and that is the same one in development. Only `origin` and the manifest change between development and your deployed site.
+
+## A separate application {#separate}
+
+mdbase identifies an app by its manifest and binds what a user approves to the exact origin, port included. Your localhost build is therefore its own application:
+
+- Collections approved on `localhost:5173` are approved for that origin only. Your deployed app asks its users separately.
+- Sign-in state and the on-device copy of a collection belong to the origin. Changing the port starts again from signed out.
+- Give the development manifest its own `name`, such as “Worklog (development)”, so the two are easy to tell apart on your account page.
+
+The records are real. A development build that opens your own collection reads and writes your own files, so use a collection made for testing.
+
+## What the user sees {#consent}
+
+When a localhost app asks for access, the approval screen calls it “an app running on this computer”, says its identity is unverified, and shows no icon. A page on the internet cannot give itself a localhost origin, so the only program that can be there is one already running on the person’s machine. The screen says that plainly instead of presenting the manifest’s name as a brand.
+
+Account sign-in, the collection choice and the list of capabilities are the same as for a deployed app.
+
+## Redirect URIs {#redirect}
+
+`redirect_uris` must list at least one URL on the app’s origin. A browser app needs no page there. Sign-in happens in a window that the SDK opens, and the SDK learns the result itself; that window never navigates to your redirect URI and no token is delivered to it. Listing the homepage is enough.
+
+The redirect URI is used when you pass your own sign-in opener, as a native shell or browser extension does. mdbase then sends the person’s browser to `returnUrl` when sign-in ends, to bring them back to your app. It carries no credential, so any page or deep link of yours can receive it. See [Sign-in outside a popup](/sdk/lifecycle/#opener).
+
+## Development servers {#server}
+
+The SDK runs its engine in a Web Worker and loads WebAssembly files that ship inside the package. With Vite, `vite dev` and `vite build` both work with the default configuration.
+
+Fix the port, since the manifest names it:
+
+```ts title="vite.config.ts"
+import { defineConfig } from "vite";
+
+export default defineConfig({
+ server: { port: 5173, strictPort: true },
+});
+```
+
+With another bundler, the requirement is that the files under the package’s `dist/` are served from your own origin, beside the SDK’s modules. For a page with no bundler, use the [browser bundle](/sdk/portable-apps/).
+
+## Working with no account {#no-account}
+
+Much of an app can be built before you sign in at all:
+
+- `createMdbase(declaration, { unsynced: true })` opens a real collection kept in the browser. See [Work before connecting](/sdk/unsynced/).
+- `MemoryReplica` and `createApplicationFixture()` run the same client in tests. See [Testing](/sdk/testing/).
+
+## Common problems {#problems}
+
+| What you see | Cause |
+| --- | --- |
+| “The app couldn’t load” as soon as the page opens | The SDK release predates localhost support, or the SDK’s files are not served from your origin. |
+| The entry refuses to start with an origin error | `origin` differs from the page’s origin, or from the manifest’s `homepage` origin. `localhost` and `127.0.0.1` are different origins. |
+| Signed out after restarting the development server | The server picked another port. Set `strictPort`. |
+| The checker reports `/homepage` | An HTTP homepage needs `--allow-local`, or `allowLocal: true` when you call `validateAppManifest()`. |
+| The sign-in window does not open | `signIn()` was called after an `await`. Call it directly in the click handler. |
diff --git a/content/sdk/manifest.md b/content/sdk/manifest.md
new file mode 100644
index 0000000..041e671
--- /dev/null
+++ b/content/sdk/manifest.md
@@ -0,0 +1,128 @@
+---
+title: Application manifest
+description: One JSON file says who your app is, which collections suit it, and what it may do.
+section: sdk
+---
+
+Ship the manifest with your app and pass it to `createMdbase()`. The SDK validates it with the same parser mdbase uses. Schema: [`mdbase-app.v1.json`](/connect/schemas/mdbase-app.v1.json). The whole file may be at most 512 KiB.
+
+```json title="mdbase-app.json"
+{
+ "manifest_version": 1,
+ "id": "dev.example.worklog",
+ "name": "Worklog",
+ "homepage": "https://worklog.example",
+ "icon": "https://worklog.example/icon.png",
+ "redirect_uris": [
+ "https://worklog.example/auth/mdbase/callback",
+ "dev.example.worklog://auth/mdbase/callback"
+ ],
+ "requirements": {
+ "access": "full_collection",
+ "contracts": [
+ {
+ "id": "example.work-item",
+ "version": "1.0.0",
+ "digest": "sha256:9cd7f8e4b23ba20aaeaec3f7e209c6ba8de3fa5cd224204f2baef4e14dd69936"
+ }
+ ],
+ "capabilities": {
+ "contract_version": 2,
+ "required": ["collection.read", "records.create", "records.edit"],
+ "optional": ["records.delete"]
+ }
+ }
+}
+```
+
+## Identity
+
+| Field | Rule |
+| --- | --- |
+| `manifest_version` | `1` |
+| `id` | Lowercase reverse-domain name with at least three parts, such as `dev.example.worklog`. It is a label, not proof of who publishes the app. |
+| `name` | Shown to the user when they approve your app; up to 100 characters |
+| `icon` | Optional HTTPS URL |
+
+## Web apps {#web}
+
+A web app declares an HTTPS `homepage` and between one and ten `redirect_uris` on the homepage’s origin. `distribution` may be left out; it defaults to `"web"`.
+
+For development, the homepage and redirect URIs may instead be on `http://localhost`, `http://127.0.0.1` or `http://[::1]`, with any port. That manifest is a separate application from your published one; see [Develop on localhost](/sdk/local-development/).
+
+A browser app that signs in through the SDK’s own window can list its homepage as its one redirect URI. See [Redirect URIs](/sdk/local-development/#redirect).
+
+You do not have to write the manifest by hand. [`@mdbase-dev/connect-dev`](/sdk/connect-dev/) checks it and builds its type packs.
+
+## Requirements
+
+| Field | Meaning |
+| --- | --- |
+| `access` | Required. Always `"full_collection"`. |
+| `contracts` | Required, may be empty. Each entry names a contract by `id`, `version` and exact `digest`. A collection suits your app when its types implement them. See [Contracts and adapters](/sdk/contracts/). |
+| `capabilities` | What your app may do. See [Authorization](/sdk/authorization/). Without it, your app gets read-only access. |
+| `files` | File actions and the folders they apply to |
+| `people` | `identity` (who the user is) and `members` (the collection’s members), as `required` or `optional`, with `"version": 1` |
+| `configuration` | Values the collection’s settings must contain, each with an `id`, a `path`, the predicate `"contains"` and a `value` |
+
+## Provisioning
+
+If a collection lacks the contract you need, your manifest can carry a type pack that adds it. Every resource is pinned by digest. The pack is checked as a whole and written all at once or not at all. A pack may only provide contracts listed in `requirements.contracts`. A target file that already exists with different bytes is a conflict. If your app didn’t put it there and the resource is `managed`, the user can choose to replace it with your app’s version. Otherwise it is left alone.
+
+```json title="Manifest fragment (digests shortened)"
+"provisions": {
+ "type_packs": [
+ {
+ "provides": [
+ {
+ "id": "example.work-item",
+ "version": "1.0.0",
+ "digest": "sha256:9cd7f8e4…"
+ }
+ ],
+ "manifest": {
+ "kind": "mdbase.type-pack",
+ "id": "example.work-items",
+ "version": "1.0.0",
+ "name": "Work items",
+ "resources": [
+ {
+ "kind": "contract",
+ "mode": "managed",
+ "source": "contracts/example.work-item.md",
+ "target": "_contracts/example.work-item.md",
+ "digest": "sha256:9cd7f8e4…"
+ },
+ {
+ "kind": "type",
+ "mode": "managed",
+ "source": "types/work-item.md",
+ "target": "_types/work-item.md",
+ "digest": "sha256:2be7d8a5…"
+ }
+ ]
+ },
+ "resources": [
+ { "source": "contracts/example.work-item.md", "document": "---\nkind: mdbase.contract\n…" },
+ { "source": "types/work-item.md", "document": "---\nkind: mdbase.type\n…" }
+ ]
+ }
+ ]
+}
+```
+
+`provisions.configuration` can likewise add a value to the collection’s settings, with the operation `"set_add"`, to meet a `configuration` requirement.
+
+## Notifications {#portable}
+
+`notifications.criteria` declares the notifications your app may send, with fixed titles and text. See [Notifications and timers](/sdk/notifications/).
+
+## Native apps {#native}
+
+A native app can list a private-use URI scheme in `redirect_uris`. The scheme must match or extend the application ID, as in `dev.example.worklog://auth/mdbase/callback`.
+
+The `origin` you give `createMdbase()` is normally the manifest’s `homepage` origin. A Capacitor shell ( `capacitor://`) or Chrome extension ( `chrome-extension://`) origin must also be listed under the manifest’s `installation_origins`. Firefox extension origins are not accepted. These apps sign in through an opener; see [Sign-in outside a popup](/sdk/lifecycle/#opener).
+
+## Changing the manifest {#changes}
+
+A changed manifest never widens an existing grant on its own. If your new version needs more, such as a new capability or contract, the user approves it again.
diff --git a/content/sdk/notifications.md b/content/sdk/notifications.md
new file mode 100644
index 0000000..2ba08b2
--- /dev/null
+++ b/content/sdk/notifications.md
@@ -0,0 +1,98 @@
+---
+title: Notifications and timers
+description: Schedule reminders that fire even when every device is off. mdbase learns when they fire, never what they are about.
+section: sdk
+---
+
+Timers live with mdbase, not in the collection. They fire whether or not any of the user’s devices are on, for Cloud copy and Private collections alike. When a timer fires, mdbase sends a notification with the fixed text from your manifest.
+
+> **Timer access comes from the app connection.**
+>
+> `connection.timers` is on the connection you get from `createMdbase()` once a collection is ready. See [Sign-in and collections](/sdk/lifecycle/).
+
+## Declare notifications in the manifest {#criteria}
+
+```json title="Manifest fragment"
+{
+ "notifications": {
+ "criteria": [{
+ "id": "task.reminder",
+ "event": {
+ "id": "mdbase.runtime.timer.fired",
+ "version": "1.0.0",
+ "digest": "sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"
+ },
+ "presentation": {
+ "title": "Task reminder",
+ "body": "Open Worklog to see what’s due.",
+ "tag": "task-reminder"
+ }
+ }]
+ }
+}
+```
+
+Timer notifications use the event `mdbase.runtime.timer.fired` at version `1.0.0`. The title (up to 80 characters) and body (up to 160) are fixed in the manifest, so no record content can reach a notification. You also need the `background.schedule` capability.
+
+## Schedule timers {#timers}
+
+```ts title="reminders.ts"
+const timers = connection.timers;
+if (!timers) throw new Error("This connection has no timer access");
+
+// Replace this app’s whole set of reminders in one call.
+const result = await timers.reconcile({
+ namespace: "task-reminders",
+ criterionId: "task.reminder",
+ timers: reminders.map((r) => ({
+ id: r.timerId, // opaque: don’t put record IDs or titles here
+ fireAt: r.at.toISOString(),
+ })),
+});
+console.log(result.cancelledIds);
+```
+
+- `reconcile()` replaces the active timers in a namespace in one step. Unchanged timers are kept. Changed ones are rescheduled. Ones you leave out are cancelled and returned in `cancelledIds`. An empty list cancels the namespace.
+- `put()`, `cancel()` and `list()` handle one timer at a time.
+- Times are UTC instants. There is no recurrence: work out local times on the device and reconcile again when they change.
+- A timer that is due while mdbase is catching up fires once, late.
+- Namespaces are 1–64 characters, IDs 1–128, and one reconcile holds at most 10,000 timers.
+
+## Register browser push from a user action {#browser}
+
+```ts title="enable-notifications.ts"
+const worker = await navigator.serviceWorker.register("/service-worker.js");
+
+await connection.timers?.registerWebPush({
+ serviceWorker: worker,
+ criteria: ["task.reminder"],
+});
+```
+
+Native apps use `registerFcm({ token })`. `unregisterWebPush()` and `unregisterFcm()` stop delivery when the user opts out.
+
+## Signed webhooks {#webhooks}
+
+If your app sends its own pushes, declare an HTTPS webhook as `notifications.native_delivery` with `"mode": "webhook"`. Verify each delivery against the exact raw body before parsing it.
+
+```ts title="notification-webhook.ts"
+import { verifyNotificationWebhook } from "@mdbase-dev/connect-webhooks";
+
+const event = verifyNotificationWebhook({
+ body: rawRequestBody, // the exact bytes, before JSON parsing
+ headers: request.headers,
+ keys: cachedSigningKeys,
+});
+
+if (await deliveries.claim(event.delivery_id)) {
+ await sendPush(event.connection_id, event.notification);
+}
+```
+
+Cache the signing keys from `/v1/notifications/webhook-signing-keys`. Deliveries older than five minutes are refused. Store `delivery_id` before doing any work: mdbase retries until your endpoint succeeds.
+
+## What mdbase sees {#privacy}
+
+mdbase stores each timer’s namespace, ID, criterion and time, under your app’s grant. It learns when reminders are due and how many there are. It never sees record content or record IDs, unless you put them in timer IDs. Use opaque IDs, such as a hash.
+
+In a Private collection, timers work once a signed-in device has applied your app’s grant, which it does automatically. Opening the app from a notification still needs one of their devices to be online.
diff --git a/content/sdk/offline-sync.md b/content/sdk/offline-sync.md
new file mode 100644
index 0000000..b8f0b9f
--- /dev/null
+++ b/content/sdk/offline-sync.md
@@ -0,0 +1,118 @@
+---
+title: Pending writes and sync status
+description: Writes return at once and confirm later. Show the user where their changes are, and handle the cases where mdbase keeps an edit back instead of overwriting it.
+section: sdk
+---
+
+## What your app sees {#model}
+
+Each replica applies changes in the order the collection’s log confirms them. Reads return the replica’s **local view**: everything confirmed so far, plus writes that are still pending. Each record says which it is: `record.state.state` is `"confirmed"` or `"pending"`.
+
+## Write receipts {#receipts}
+
+Every write returns a `Write` with a receipt. Its `state` moves from `pending` to one of:
+
+| State | Meaning |
+| --- | --- |
+| `confirmed` | The log accepted it. `receipt.seq` is its position. |
+| `rejected` | It was not applied, and the local view drops it. `receipt.problem` says why. |
+| `unknown` | Rare. The replica can’t tell whether it was applied. Read the record again and let the user decide. |
+
+```ts title="save.ts"
+import { isMdbaseError } from "@mdbase-dev/sdk";
+
+const write = await db.update(task, { patch: { status: "done" } });
+// write.state === "pending": reads and live queries already show the change.
+
+try {
+ const receipt = await write.confirmed;
+ console.log(`Confirmed at log position ${receipt.seq}`);
+} catch (e) {
+ if (isMdbaseError(e, "outcome_unknown")) {
+ // Rare: the replica can't tell whether this write was applied.
+ const current = await db.find(task.id);
+ askUserToCheck(current);
+ } else if (isMdbaseError(e)) {
+ // Rejected: the local view has already dropped the change.
+ showProblem(e.code, e.reason);
+ } else {
+ throw e;
+ }
+}
+```
+
+- Each write has a mutation ID. Submitting the same ID again returns the existing receipt and does nothing else, so retries are safe. Pass your own `mutationId` if you need to keep it across a reload.
+- `write.onReceipt(fn)` calls you on every receipt change. `db.pendingWrites()` lists the writes still waiting.
+- Pass `wait: "confirmed"` if the call itself should wait for the log. That suits scripts, not interactive screens.
+
+## Offline
+
+There are two kinds of offline, and they behave differently.
+
+- **The replica can’t reach the log.** Writes still succeed as `pending` and confirm when it reconnects. Status shows the backlog. This is not an error.
+- **Your app can’t reach the replica.** An app connected through the relay keeps no copy of its own. While the link is down, reads and writes wait for it to come back. Pass a `signal` to give up after a while. A write that never left your app was not saved.
+
+For a Private collection, your app can only reach a replica while one of the user’s devices is online. See [When no device is online](/sdk/routing/#waiting).
+
+## Sync status {#status}
+
+Status is a count, not a guess: “confirmed through position N, plus k changes waiting”. `db.getStatus()` reads it once; `db.onStatus()` pushes changes, at most four times a second. `summarizeStatus()` turns it into a short line of text.
+
+```ts title="status.ts"
+import { summarizeStatus } from "@mdbase-dev/sdk";
+
+const stop = db.onStatus((status) => {
+ const summary = summarizeStatus(status);
+ // summary.kind: "local" | "synced" | "catching_up" | "offline" | "installing"
+ statusLine.textContent = summary.text; // e.g. "Offline; synced through 3, 1 change waiting"
+ holdsBadge.hidden = summary.holds === 0;
+ conflictsBadge.hidden = summary.conflicts === 0;
+});
+```
+
+Holds and conflicts are counted separately, so an edit that needs the user never looks like sync is stuck.
+
+## Holds
+
+A replica that writes to real files, such as the desktop app, can **hold** an edit instead of overwriting it. The file stays as the user left it, and the change is not synced until they choose what to keep. Reasons are `conflict`, `unknown_provenance`, `deleted_elsewhere`, `read_only`, `editor_busy` and `suspect_write`.
+
+```ts title="holds.ts"
+import { describeHold } from "@mdbase-dev/sdk";
+
+db.onHolds((holds) => {
+ for (const hold of holds) {
+ const view = describeHold(hold, { collectionId });
+ // view.title is "mdbase protected your edit"; view.cause and view.detail explain why.
+ renderHold(view.path, view.cause, view.actions.map((a) => a.label));
+ }
+});
+
+// When the user picks an action for one hold:
+await db.resolveHold(holdId, "keep_mine");
+```
+
+`describeHold()` gives you the cause in plain words and the actions that apply: `keep_mine`, `take_theirs`, `use` (with merged text), `delete` and `keep_both`. Resolving is an ordinary write, so the earlier version stays in the collection’s history.
+
+## Conflicts
+
+When two devices change the same field at the same time, the replica keeps one value and records the other as a conflict. Conflicts sync to every device. Nothing is lost: show them, and let the user choose.
+
+```ts title="conflicts.ts"
+import { toPlain } from "@mdbase-dev/sdk";
+
+for (const entry of await db.listConflicts(recordId)) {
+ const { kind, field, kept, lost } = entry.conflict;
+ // kept and lost are tagged by form; a frontmatter value is { form: "value", value }.
+ if (kind === "field" && field && lost.form === "value" && await userPrefers(field, kept, lost)) {
+ await db.resolveConflict(entry, field, toPlain(lost.value));
+ } else {
+ await db.dismissConflict(entry); // keep what the record has now
+ }
+}
+```
+
+To refuse a write instead of merging it, pass `conflictMode: "reject"`, or `ifRevision` to require the exact revision you read.
+
+## Resets
+
+A live query can be reset, for example while a replica reinstalls a snapshot. `live.stale` is true until the next snapshot arrives, and the previous records stay visible meanwhile. The change feed answers an expired cursor with `reset: true` instead of an error: drop what you built from it and read again.
diff --git a/content/sdk/operations.md b/content/sdk/operations.md
new file mode 100644
index 0000000..5dd9bda
--- /dev/null
+++ b/content/sdk/operations.md
@@ -0,0 +1,159 @@
+---
+title: Records and operations
+description: Read, query, watch, create, update, rename and delete records. Writes are optimistic and merge field by field.
+section: sdk
+---
+
+All examples use `db`, an `MdbaseClient` from `connect()` or from an app connection’s `records`.
+
+## Records and errors {#outcomes}
+
+A record is a `RecordView`: `id`, `path`, `revision`, `types`, `frontmatter` (a `Map`), and `state`. Ask for more with the `include` argument: `body`, `effective` (values with type defaults applied), `document`, `links` and `diagnostics`.
+
+Failures throw `MdbaseError`. Check them with `isMdbaseError(e, code)`. Each error has a `code`, a `recovery` that says what to do, and often a `reason`. The full list is in the [API reference](/sdk/api/#errors).
+
+## Read and query {#read-query}
+
+```ts title="read.ts"
+import { isMdbaseError, toPlain } from "@mdbase-dev/sdk";
+
+// By ID, or by path. get() throws not_found; find() returns null.
+const task = await db.get({ path: "tasks/plan.md" }, { body: true });
+const maybe = await db.find(taskId);
+
+console.log(task.revision); // "sha256:…"
+console.log(toPlain(task.frontmatter)); // plain object
+console.log(task.state.state); // "confirmed" or "pending"
+
+// One page of a query. Pass page.cursor to get the next.
+const page = await db.query({
+ types: ["task"],
+ where: 'status != "done"',
+ order_by: [{ field: "due", direction: "asc" }],
+ limit: 50,
+});
+
+// Or every page in turn.
+for await (const p of db.pages({ types: ["task"], limit: 200 })) {
+ render(p.records);
+}
+```
+
+Queries use the [mdbase query format](/spec/): `types`, `where`, `order_by`, `select`, `limit` and more. Reads answer from the replica’s local view, including your pending writes.
+
+A cursor can expire. `pages()` then throws `invalid_request` with reason `cursor_expired` or `cursor_stale`. Pass `{ onReset }` as its fourth argument to restart from the first page instead; clear what you collected when it is called.
+
+## Live queries {#live}
+
+A live query keeps its result current. The replica sends a snapshot, then a diff for each change.
+
+```ts title="task-list.ts"
+const open = db.live(
+ { types: ["task"], where: 'status == "open"', limit: 100 },
+ { effective: true },
+);
+
+const stop = open.subscribe((state) => {
+ // Called now, then after every snapshot, diff or reset.
+ renderList(state.records, { stale: state.stale });
+});
+
+// Widen the window later without a new subscription.
+await open.setQuery({ types: ["task"], where: 'status == "open"', limit: 200 });
+
+// When the screen closes:
+stop();
+open.close();
+```
+
+Keep live lists cheap: use a `limit` window and leave bodies out. `state.stale` is true until the first snapshot and after a reset; the previous records stay visible meanwhile.
+
+## Write
+
+```ts title="write.ts"
+const created = await db.create({
+ type: "task",
+ path: "tasks/review.md",
+ frontmatter: { title: "Review the draft", status: "open" },
+ body: "Check the numbers.\n",
+});
+const id = created.records[0].id; // usable straight away
+
+// Pass the record you read. Only the fields you change are sent, each with
+// the value you saw, so concurrent edits to other fields merge.
+const task = await db.get(id, { body: true });
+await db.update(task, {
+ patch: { status: "in-progress" },
+ add: { tags: ["review"] },
+ body: task.body + "Add a summary.\n",
+});
+
+await db.rename(task, "tasks/review-q3.md"); // updates links by default
+await db.delete(id);
+```
+
+Every write returns a `Write` at once, in the `pending` state. Your reads and live queries show it straight away. Await `write.confirmed` if you need to know the log accepted it; see [Pending writes and sync status](/sdk/offline-sync/).
+
+When you pass a `RecordView` to `update()`, the SDK sends the values you saw with the fields you change. A new body is sent as edits against the body you read and merged with other changes. Patch keys whose value didn’t change are dropped, so they can’t cause conflicts.
+
+`replaceDocument(record, source)` replaces the whole Markdown source when you need to. For a screen where people type into a record, use a [record session](/sdk/editing/) instead.
+
+## Preconditions
+
+- `ifRevision: record.revision` applies the write only if the record is still at that revision. Otherwise it is rejected with `conflict` and reason `revision`.
+- `conflictMode: "reject"` in the write options rejects the whole write if any part of it conflicts. The default, `"record"`, applies what merges and records the rest as conflicts.
+
+## Watch changes {#watch}
+
+The change feed lists what changed since a cursor. Use it to keep an index or an export up to date.
+
+```ts title="changes.ts"
+let cursor = loadCursor();
+
+const watch = db.watchChanges(cursor, (batch) => {
+ if (batch.reset) {
+ rebuildFromScratch(); // the cursor expired: start again
+ } else {
+ applyChanges(batch.changes);
+ }
+ saveCursor(batch.cursor);
+});
+await watch.ready;
+
+// Later:
+watch();
+```
+
+An expired cursor gives `reset: true`, not an error. `db.changes(cursor, limit)` reads one batch without watching.
+
+## Check before writing {#preflight}
+
+```ts title="preflight.ts"
+const preview = await db.update(task, { patch: { status: "done" } }, { dryRun: true });
+console.log(preview.receipt.preflight);
+
+const issues = await db.validate([{ path: "tasks/review.md" }]);
+```
+
+`dryRun: true` runs every check without writing. `preflightRename()` and `preflightDelete()` show what a rename or delete would touch, such as links in other records. `validate()` checks records against their types.
+
+## Attachments {#files}
+
+Files that aren’t records, such as images and PDFs, use `db.files`.
+
+```ts title="files.ts"
+const upload = await db.files.upload("attachments/plan.pdf", file, {
+ onProgress: (p) => showProgress(p),
+});
+await upload.confirmed; // the bytes are stored
+
+const bytes = await db.files.download({ path: "attachments/plan.pdf" });
+
+for await (const f of db.files.list()) {
+ console.log(f.path, f.size, f.state); // state: "materialized", "remote", …
+}
+```
+
+- Uploads go in 1 MiB chunks. To resume an interrupted upload, call `upload()` again with the same `transferId`. Pass `fileId` to replace an existing file.
+- `download()` reads up to 64 MiB into memory. For anything larger, use `downloadStream()`, which also takes a byte `range`.
+- `move()` and `delete()` take `ifRevision`, like records.
diff --git a/content/sdk/portable-apps.md b/content/sdk/portable-apps.md
new file mode 100644
index 0000000..96d93be
--- /dev/null
+++ b/content/sdk/portable-apps.md
@@ -0,0 +1,31 @@
+---
+title: Browser bundle
+description: Use the SDK from a plain script tag, without a bundler.
+section: sdk
+---
+
+Most apps import `@mdbase-dev/sdk` through a bundler. If yours doesn’t use one, the package also ships a classic-script build.
+
+## Classic-script bundle {#bundle}
+
+The package includes `dist/browser/mdbase-sdk.js` and a minified `mdbase-sdk.min.js`. Copy one into your app and serve it from your own origin. mdbase does not publish it on a CDN.
+
+```sh title="Terminal"
+npm install @mdbase-dev/sdk
+cp node_modules/@mdbase-dev/sdk/dist/browser/mdbase-sdk.min.js public/vendor/
+```
+
+```html title="index.html"
+
+
+```
+
+Loading the bundle does nothing on its own. It doesn’t open a session, touch storage or grant access. Module code can import the same surface from `@mdbase-dev/sdk/browser`.
+
+## Downloaded HTML files {#status}
+
+The manifest format has a `"portable"` distribution for a single HTML file that runs without a web origin. The launch SDK has no sign-in flow for portable files, so this guide doesn’t cover one. Build a web app with an HTTPS origin instead.
diff --git a/content/sdk/quickstart.md b/content/sdk/quickstart.md
new file mode 100644
index 0000000..caa0783
--- /dev/null
+++ b/content/sdk/quickstart.md
@@ -0,0 +1,115 @@
+---
+title: Try the SDK in memory
+description: "Run a short script against an in-memory replica, with no account: read, watch, write and see a stale write refused."
+section: sdk
+---
+
+This script needs no account, no service and no collection. It uses `MemoryReplica`, an in-memory replica from `@mdbase-dev/sdk/testing` that speaks the same protocol as a real one. Your code talks to it through the same `MdbaseClient` it would use with a real collection.
+
+## Prerequisites
+
+- Node 20 or later.
+- npm.
+
+## 1. Install the SDK {#build}
+
+```sh title="Terminal"
+mkdir mdbase-quickstart && cd mdbase-quickstart
+npm init -y
+npm install @mdbase-dev/sdk
+```
+
+> **The SDK is in beta.**
+>
+> `npm install @mdbase-dev/sdk` installs the latest beta from [npm](https://www.npmjs.com/package/@mdbase-dev/sdk). A new beta is published as Connect changes, and the API can change between betas, so pin an exact version in an app you ship.
+
+## 2. Run the example {#run}
+
+Save this as `quickstart.mjs` and run `node quickstart.mjs`. It prints its results and exits.
+
+```js title="quickstart.mjs"
+import { connect, isMdbaseError, summarizeStatus } from "@mdbase-dev/sdk";
+import { MemoryReplica } from "@mdbase-dev/sdk/testing";
+
+// An in-memory stand-in for a replica. Writes stay pending until confirmAll().
+const replica = new MemoryReplica({ confirmDelayMs: null });
+replica.seed({
+ path: "tasks/first.md",
+ types: ["task"],
+ frontmatter: { title: "Read the collection", status: "open" },
+});
+
+const db = await connect({
+ connector: replica.connector(),
+ app: { name: "dev.example.quickstart", version: "0.1.0" },
+});
+
+// A live query: a snapshot first, then a diff for every change.
+const tasks = db.live({
+ types: ["task"],
+ order_by: [{ field: "file.path", direction: "asc" }],
+});
+await tasks.ready;
+console.log(`Tasks: ${tasks.records.map((r) => r.path).join(", ")}`);
+
+// Writes return at once with the optimistic result.
+const created = await db.create({
+ type: "task",
+ path: "tasks/second.md",
+ frontmatter: { title: "Update one record", status: "open" },
+});
+console.log(`Created: ${created.records[0].path} (${created.state})`);
+console.log(`Status: ${summarizeStatus(await db.getStatus()).text}`);
+
+// Pass the record you read, so only the fields you change are sent.
+const first = await db.get({ path: "tasks/first.md" });
+const done = await db.update(first, { patch: { status: "done" } });
+
+replica.confirmAll(); // The log accepts both writes.
+const receipt = await done.confirmed;
+console.log(`Confirmed at position ${receipt.seq}`);
+
+// A whole-record check fails if the record changed since you read it.
+try {
+ const stale = await db.update(first, { patch: { status: "open" }, ifRevision: first.revision });
+ await stale.confirmed;
+} catch (e) {
+ if (!isMdbaseError(e, "conflict")) throw e;
+ console.log(`Stale revision: ${e.code} (${e.reason})`);
+}
+
+console.log(`Status: ${summarizeStatus(await db.getStatus()).text}`);
+console.log(`Open tasks: ${tasks.records.filter((r) => r.frontmatter.get("status") === "open").length}`);
+tasks.close();
+db.close();
+```
+
+## 3. Check the result {#result}
+
+```text title="Expected output"
+Tasks: tasks/first.md
+Created: tasks/second.md (pending)
+Status: Synced through 1, 1 change waiting
+Confirmed at position 3
+Stale revision: conflict (revision)
+Status: Synced through 3
+Open tasks: 1
+```
+
+## 4. What it shows {#read}
+
+- **Writes are optimistic.** `create()` and `update()` return a `Write` straight away, in the `pending` state. Your reads and live queries already show the change. `write.confirmed` resolves when the collection’s log accepts it.
+- **Live queries stay current.** `db.live()` keeps `records` up to date as writes land, so the count at the end already includes both changes.
+- **Frontmatter is a `Map`.** Read fields with `record.frontmatter.get("status")`, or convert with `toPlain()`.
+- **Stale writes are refused.** With `ifRevision`, a write against an old revision fails with the error code `conflict` and reason `revision`.
+
+`MemoryReplica` is not the real replica. It applies patches blindly and has no query planner or merge. Use it for unit tests and demo modes, not to test merge behaviour.
+
+## 5. Next steps {#next}
+
+To sign a user in and work with one of their collections, follow [Build an app](/sdk/connect-quickstart/). The code that reads and writes records stays the same; only the connector changes.
+
+- [Build an app](/sdk/connect-quickstart/)
+- [Read and write records](/sdk/operations/)
+- [Pending writes and sync status](/sdk/offline-sync/)
+- [Test with MemoryReplica](/sdk/testing/)
diff --git a/content/sdk/react.md b/content/sdk/react.md
new file mode 100644
index 0000000..6bec173
--- /dev/null
+++ b/content/sdk/react.md
@@ -0,0 +1,137 @@
+---
+title: React
+description: "Use the SDK from React: the snapshot as a store, a hook for live queries, and where the shared components fit."
+section: sdk
+---
+
+## What there is {#packages}
+
+The SDK has no React dependency and needs no provider. Two things make it fit React directly:
+
+- The entry from `createMdbase()` is an external store: `subscribe` and `getSnapshot` have the shapes `useSyncExternalStore` expects.
+- [`@mdbase-dev/ui`](/sdk/ui/) has the sign-in and collection screens as components. With `CollectionGate` you may not need the first hook on this page at all.
+
+The [Worklog tutorial](/sdk/connect-quickstart/) is a complete React app built this way.
+
+## The snapshot as a store {#snapshot}
+
+```ts title="use-mdbase.ts"
+import { useSyncExternalStore } from "react";
+import { mdbase } from "./mdbase";
+
+export function useMdbase() {
+ return useSyncExternalStore(mdbase.subscribe, mdbase.getSnapshot, mdbase.getSnapshot);
+}
+```
+
+The snapshot is replaced only when something changes, so components re-render only then. The third argument is the server snapshot: where the SDK cannot run, the phase is `unavailable`, so a server-rendered page gets a defined state.
+
+```tsx title="App.tsx"
+import { useEffect } from "react";
+import { mdbase } from "./mdbase";
+import { useMdbase } from "./use-mdbase";
+
+export function App() {
+ const { phase } = useMdbase();
+
+ useEffect(() => {
+ void mdbase.start();
+ }, []);
+
+ switch (phase.kind) {
+ case "ready":
+ case "unsynced":
+ return ;
+ case "signed_out":
+ return ;
+ default:
+ return ;
+ }
+}
+```
+
+Create the entry once, in a module, as the tutorial’s `mdbase.ts` does. Do not create it inside a component.
+
+## A live query hook {#live}
+
+```ts title="use-live-query.ts"
+import type { MdbaseClient, Query, RecordView } from "@mdbase-dev/sdk";
+import { useEffect, useState } from "react";
+
+export function useLiveQuery(db: MdbaseClient, query: Query) {
+ const [state, setState] = useState<{ records: readonly RecordView[]; stale: boolean }>({
+ records: [],
+ stale: true,
+ });
+ // A query is plain data, so its JSON is a stable dependency.
+ const key = JSON.stringify(query);
+
+ useEffect(() => {
+ const live = db.live(JSON.parse(key) as Query);
+ const stop = live.subscribe((next) => setState({ records: next.records, stale: next.stale }));
+ return () => {
+ stop();
+ live.close();
+ };
+ }, [db, key]);
+
+ return state;
+}
+```
+
+```tsx title="Entries.tsx"
+function Entries({ db }: { db: MdbaseClient }) {
+ const { records, stale } = useLiveQuery(db, {
+ types: ["worklog-entry"],
+ order_by: [{ field: "date", direction: "desc" }],
+ limit: 100,
+ });
+
+ return (
+
+ {records.map((entry) => (
+
{String(entry.frontmatter.get("summary"))}
+ ))}
+
+ );
+}
+```
+
+- The effect’s cleanup both unsubscribes and closes the query. Closing tells the collection to stop sending changes.
+- `stale` is true until the first result arrives, and again while a query is reset. The previous records stay in place meanwhile, so the list does not flash empty.
+- Give lists a `limit` and leave bodies out. To page, raise the limit; `live.setQuery()` changes a running query without a new subscription.
+
+## Writes
+
+Call the client from event handlers. A write resolves when it is saved on the device, and a live query already shows it, so there is no cache to update and nothing to refetch.
+
+```tsx title="Tasks.tsx"
+async function complete(task: RecordView) {
+ const write = await db.update(task, { patch: { status: "done" } });
+ if (write.state === "rejected") {
+ setProblem(describeError(write.receipt.problem)?.message ?? null);
+ }
+}
+```
+
+For a screen where someone types into one record, use a [record session](/sdk/editing/). It keeps the text field and the record in step while other devices edit the same record.
+
+## Sync status {#status}
+
+```tsx title="SyncStatus.tsx"
+import { useMdbase } from "./use-mdbase";
+
+export function SyncStatus() {
+ const { sync } = useMdbase();
+ return sync ? {sync.text} : null;
+}
+```
+
+`snapshot.sync` is the open collection’s status as a short line of text with counts, and `snapshot.writes` lists writes that are still waiting or were refused. See [Pending writes and sync status](/sdk/offline-sync/).
+
+## Things to get right {#rules}
+
+- **Key your screen on the connection.** `key={connection.id}` resets component state when the user switches collection.
+- **Call sign-in from the click.** `onClick={() => mdbase.signIn()}` works. Awaiting something first loses the browser’s permission to open the window.
+- **Strict Mode is fine.** `start()` is safe to call twice, and the live query hook above cleans up after the first mount.
+- **Server rendering.** The SDK runs in the browser. Creating the entry and reading its snapshot on the server is safe; the phase there is `unavailable`. Call `start()` only in the browser, from an effect: on the server it rejects.
diff --git a/content/sdk/routing.md b/content/sdk/routing.md
new file mode 100644
index 0000000..5c4fcc3
--- /dev/null
+++ b/content/sdk/routing.md
@@ -0,0 +1,87 @@
+---
+title: How apps reach a collection
+description: "Your app always talks to a replica. Which replica depends on the collection’s sync option: mdbase’s copy for Cloud copy, one of your devices for Private."
+section: sdk
+---
+
+## Apps talk to a replica {#automatic}
+
+Every client connects to one **replica**: a full copy of the collection that checks your app’s grant and answers its requests. Your code is the same whichever replica it reaches. The collection’s sync option decides which one that is. You don’t choose a route.
+
+| Sync option | Your app reaches | Works while the user’s devices are off |
+| --- | --- | --- |
+| Cloud copy (the default) | mdbase’s hosted replica | Yes |
+| Private | One of the user’s own devices, through the relay | No |
+
+The log is encrypted in both options. What differs is who holds the keys.
+
+## Cloud copy
+
+mdbase keeps a readable copy of the collection and runs a replica for it. Your app connects to that replica over an encrypted session. It works at any time, including when every one of the user’s devices is off. mdbase can read the content of a Cloud copy collection.
+
+## Private
+
+Only the user’s devices hold the keys, so only they can run a replica. Your app connects to whichever of the user’s devices is online, through mdbase’s relay. mdbase cannot read the content. If no device is online, your app cannot reach the collection.
+
+The user approves your app once, in mdbase. A signed-in device applies that grant automatically; there is no second approval on the device.
+
+## The relay {#relay}
+
+The relay is a pipe, not storage. It pairs your app’s connection with the device’s and forwards encrypted messages. It sees which app connects to which device, and the sizes and timing of messages. It never sees content.
+
+The session inside is end-to-end between your app and the replica. It uses the Noise protocol (`Noise_IK_25519_ChaChaPoly_SHA256`), and both sides prove their keys:
+
+- your app’s key is the one registered with its grant when the user approved it;
+- the replica’s key is the one enrolled for that device.
+
+The session is bound to one collection, grant and device. It ends after 24 hours and the SDK reconnects with a new handshake. Revoking the grant closes it at once.
+
+In a browser, `loadOrCreateClientKey()` keeps your app’s key in IndexedDB as a non-extractable key where the browser allows it. Otherwise the key is stored in your origin’s storage. Either way, script running on your origin can use it, so a cross-site scripting bug in your app is a bug in your app’s access.
+
+## When no device is online {#waiting}
+
+When a Private collection has no device online, connecting fails with `unavailable` and reason `no_device_online`. Pass `waitForDevice: true` to keep retrying instead, and tell the user what to do.
+
+```ts title="connect.ts"
+const db = await connect({
+ connector,
+ app: { name: "dev.example.worklog", version: "1.4.0" },
+ // Private collections: keep retrying until one of the user's devices is online.
+ waitForDevice: true,
+ onWaiting: () => showBanner("Open mdbase on one of your devices to continue."),
+});
+
+db.onLink((state, why) => {
+ // "open", "reconnecting" or "closed"
+ renderConnection(state, why?.reason);
+});
+```
+
+The SDK reconnects by itself when the link drops. `db.link` and `onLink()` report the link to the replica, not the sync state; for that, use [sync status](/sdk/offline-sync/).
+
+## On the same computer {#local}
+
+A script or plugin on a computer running the mdbase desktop app can talk to the desktop app’s replica directly, without the relay. `@mdbase-dev/sdk/node` has two connectors:
+
+| Connector | How it connects |
+| --- | --- |
+| `connectDaemonLocalhost({ collection })` | A localhost WebSocket. The user links your key to the collection on screen in the desktop app, once per collection and key. |
+| `ipcConnector({ collection, grant, staticKey })` | A local socket or named pipe, with your app’s grant and key. |
+
+```ts title="export.mjs"
+import { connect } from "@mdbase-dev/sdk";
+import { connectDaemonLocalhost } from "@mdbase-dev/sdk/node";
+
+const db = await connect({
+ connector: connectDaemonLocalhost({ collection: collectionId }),
+ app: { name: "dev.example.export-script", version: "0.1.0" },
+});
+```
+
+Both read the desktop app’s identity from its state directory and pin its key, so another process listening on the same port fails the handshake.
+
+`connectDaemonLocalhost` uses a new key each time, so the user is asked to link it on every run. To be asked once, use `localLinkConnector({ link: () => readLocalLink(), collection, staticKey })` with a key you keep. Outside a browser, `loadOrCreateClientKey()` keeps keys in memory only, unless you pass your own `storage`.
+
+## mdbase’s own apps {#first-party}
+
+mdbase’s own web apps can keep a replica of their own in the browser, so they open and edit while offline. Other apps reach a replica as described above. Running your own replica in the browser is not open to other apps at launch.
diff --git a/content/sdk/security.md b/content/sdk/security.md
new file mode 100644
index 0000000..e0f2fae
--- /dev/null
+++ b/content/sdk/security.md
@@ -0,0 +1,49 @@
+---
+title: Security model
+description: "Who can read what, where your app’s key lives, and what to check before you release."
+section: sdk
+---
+
+## Who can read content {#payloads}
+
+The collection’s log is encrypted in both sync options. The difference is who holds the keys.
+
+| | Can read records | Sees |
+| --- | --- | --- |
+| Your app | Yes, within its grant | What it reads |
+| The user’s devices | Yes | Everything the user can see |
+| mdbase, Cloud copy | Yes: it keeps a readable copy | Content and metadata |
+| mdbase, Private | No | Metadata: which app connects to which device, message sizes and timing, and timer times and counts |
+
+Your app’s session with the replica is end-to-end encrypted with Noise, whether it runs through the relay or straight to mdbase’s hosted replica. Both sides prove their keys. TLS runs underneath on every hop. See [How apps reach a collection](/sdk/routing/).
+
+## Ask for least privilege {#least-privilege}
+
+- Request only the capabilities you use. Mark the rest optional.
+- Ask for file access to named folders, not the whole collection.
+- Check `db.hello.grant` and hide what the user didn’t approve.
+
+## Your app’s key {#credentials}
+
+Your app’s grant is bound to a key. In a browser, `loadOrCreateClientKey()` keeps it in IndexedDB as a non-extractable key where the browser supports it. Pass `requireNonExtractable: true` to refuse to fall back to a raw key.
+
+Non-extractable means script can’t copy the key out. It does not stop script on your origin from using it. Any code running in your page has your app’s access, so keep third-party scripts out and fix cross-site scripting bugs as access bugs.
+
+## Origins and callbacks {#origins}
+
+- Your homepage, icon and browser callbacks use HTTPS. The one exception is an app on this computer: [a localhost origin](/sdk/local-development/) may use HTTP, and the approval screen then says the app’s identity is unverified.
+- Browser callbacks stay on the homepage’s origin.
+- Native callback schemes match or extend your application ID.
+- The `origin` you give `createMdbase()` is the exact origin you serve from.
+
+## Release checklist {#checklist}
+
+- Validate your manifest with the production parser.
+- Test revocation and narrowed grants: your app should ask the user to reconnect, not retry.
+- Test a Private collection with no device online.
+- Show pending writes, holds and conflicts. Never present a pending write as saved.
+- Pass `ifRevision` on overwrites and deletes where losing a concurrent edit matters.
+- Show what a rename or delete will touch before doing it.
+- Keep record content out of timer IDs and notification text.
+- Deduplicate signed webhook deliveries before acting on them.
+- Tell your users that in a Cloud copy collection, mdbase can read their content.
diff --git a/content/sdk/testing.md b/content/sdk/testing.md
new file mode 100644
index 0000000..944ffcd
--- /dev/null
+++ b/content/sdk/testing.md
@@ -0,0 +1,93 @@
+---
+title: Testing
+description: Test your app against MemoryReplica, an in-memory replica that speaks the real protocol. Keep merge and permission behaviour for tests against a real collection.
+section: sdk
+---
+
+`MemoryReplica` from `@mdbase-dev/sdk/testing` is an in-memory replica. It speaks the same protocol as a real one: frames, pushes and receipts. Your code connects to it with `connect()` and gets an ordinary `MdbaseClient`.
+
+## Unit tests {#sandbox}
+
+```ts title="tasks.test.ts"
+import { describe, expect, it } from "vitest";
+import { connect, isMdbaseError } from "@mdbase-dev/sdk";
+import { MemoryReplica } from "@mdbase-dev/sdk/testing";
+import { completeTask } from "../src/tasks";
+
+async function setup() {
+ const replica = new MemoryReplica({ confirmDelayMs: null });
+ const { id } = replica.seed({
+ path: "tasks/plan.md",
+ types: ["task"],
+ frontmatter: { title: "Plan", status: "open" },
+ });
+ const db = await connect({
+ connector: replica.connector(),
+ app: { name: "dev.example.test", version: "0.0.0" },
+ });
+ return { replica, db, id };
+}
+
+describe("completeTask", () => {
+ it("shows the change before it is confirmed", async () => {
+ const { replica, db, id } = await setup();
+ const write = await completeTask(db, id);
+ expect(write.state).toBe("pending");
+ expect((await db.get(id)).frontmatter.get("status")).toBe("done");
+
+ replica.confirmAll();
+ await expect(write.confirmed).resolves.toMatchObject({ state: "confirmed" });
+ db.close();
+ });
+
+ it("reports a rejected write", async () => {
+ const { replica, db, id } = await setup();
+ const write = await completeTask(db, id);
+ replica.reject(write.mutationId);
+ await expect(write.confirmed).rejects.toSatisfy((e) => isMdbaseError(e));
+ db.close();
+ });
+});
+```
+
+## What it covers {#coverage}
+
+- Reads, queries with cursors, live queries and the change feed.
+- Creates, updates, renames and deletes, with receipts and `ifRevision`.
+- Sync status and pending writes. Holds and conflicts are empty until you add one with `hold(ref)` or `conflict(ref, { field, kept, lost })`.
+- Files: upload, download and listing.
+- Record sessions from `db.records.open()`.
+
+`where` needs an evaluator you supply. `order_by` sorts on `file.path` and top-level frontmatter fields.
+
+```ts title="where.ts"
+const replica = new MemoryReplica({
+ // MemoryReplica does not parse expressions. Supply your own evaluator.
+ where: (expr, record) =>
+ expr === 'status == "open"' && record.frontmatter.get("status") === "open",
+});
+```
+
+## Controls {#editing}
+
+| Call | Use it to |
+| --- | --- |
+| `new MemoryReplica({ confirmDelayMs })` | Confirm writes after a delay (0 ms by default), or pass `null` to confirm only when you say so |
+| `seed({ path, types, frontmatter, body })` | Add a confirmed record before the test |
+| `confirmAll()` | Confirm every pending write |
+| `reject(mutationId, problem?)` | Reject one write (by default with `conflict`, reason `revision`) |
+| `setOnline(false)` | Act as if the log can’t be reached: status reports offline and writes stay pending |
+| `dropConnections()` | Cut the link, to test reconnects |
+| `refuse`, `role`, `capabilities` options | Refuse the connection with a problem, or set what `hello` reports |
+
+`createApplicationFixture()` stands in for `MdbaseConnect`, so you can test your app’s sign-in and readiness screens with snapshots you control.
+
+## What it doesn’t cover {#real}
+
+`MemoryReplica` is not the replica. It applies patches blindly, has no query planner and does not merge. Test these against a real collection:
+
+- field and body merges;
+- query expressions, type validation and defaults;
+- grants and permission errors;
+- when real holds and conflicts happen;
+- routing to a Private collection.
diff --git a/content/sdk/ui.md b/content/sdk/ui.md
new file mode 100644
index 0000000..fb07eab
--- /dev/null
+++ b/content/sdk/ui.md
@@ -0,0 +1,188 @@
+---
+title: UI components
+description: "@mdbase-dev/ui has the sign-in, collection picker, approval and setup screens that mdbase’s own apps use, as React components."
+section: sdk
+---
+
+Every app built on mdbase needs the same screens before its own: sign in, pick a collection, approve access, review setup, and explain a problem. This package has them, so users meet the same flow in every app and you write none of it.
+
+## Install
+
+```sh title="Terminal"
+npm install --save-exact @mdbase-dev/ui @mdbase-dev/i18n \
+ @lingui/core@6.9.0 @lingui/react@6.9.0
+```
+
+The components need React 19.2 or later. `@mdbase-dev/i18n` and the two Lingui packages are peer dependencies. Import the stylesheet once, anywhere in your app:
+
+```ts title="main.tsx"
+import "@mdbase-dev/ui/collections.css";
+```
+
+## CollectionGate {#gate}
+
+The gate takes your [`createMdbase()`](/sdk/lifecycle/) entry and shows the right screen for each phase. It renders its children once a collection is open, and starts the SDK itself.
+
+```tsx title="App.tsx" file="examples/worklog/src/App.tsx"
+```
+
+| Prop | Meaning |
+| --- | --- |
+| `mdbase` | The entry from `createMdbase()`. |
+| `app` | `name`, and optionally `mark`: an element shown as your app’s icon. |
+| `children` | A function of the open connection. Called in the `ready` and `unsynced` phases. |
+| `layout` | `"page"` (default) fills the viewport. `"panel"` sits inside your own shell or dialog. |
+| `unsynced` | Show the [work before connecting](/sdk/unsynced/) screens. Pass `true`, or `{ storage, map }`. |
+| `extraActions` | Your own links or buttons on the gate’s screens, such as “Try a sample”. |
+| `onBeforeLeave` | Called before anything that leaves the open collection. Return `false`, or a promise of it, to stay. |
+| `autoStart` | Call `mdbase.start()` on mount. Default true. |
+| `copy` | Replacement wording. See [below](#wording). |
+
+```tsx title="App.tsx"
+ }}
+ layout="panel"
+ extraActions={What is Worklog?}
+ onBeforeLeave={(intent) => (hasUnsavedDraft() ? confirmLeave(intent) : true)}
+ unsynced
+>
+ {(connection) => }
+
+```
+
+While a collection is open, the gate shows a banner above your app for a live problem, such as access that was removed.
+
+## CollectionSwitcher {#switcher}
+
+The control inside your app for the open collection. It lists the approved collections, and has “Add a collection”, “Manage access” and the account with sign-out. It takes the same `mdbase`, `app`, `unsynced` and `onBeforeLeave` props as the gate.
+
+```tsx title="Header.tsx"
+// In a header: the collection's name, opening the list.
+
+
+// In a toolbar: a button with an icon only.
+
+
+// Opened from an item in your own menu.
+const [open, setOpen] = useState(false);
+const menuButton = useRef(null);
+
+
+```
+
+## Smaller parts {#parts}
+
+| Export | Use |
+| --- | --- |
+| `CollectionPanel` | The gate’s screens and the switcher’s list in one panel, for a settings dialog or an app that opens on its own screen first. |
+| `CollectionProblem` | One problem with its fix, as a block or a banner. |
+| `CollectionSetupReview` | The setup review on its own. |
+| `CollectionUnsyncedLine`, `CollectionBringIn` | The “saved only in this browser” line and the offer to bring that work in. |
+| `CollectionSaveWarning` | A warning when unsaved changes sit in storage the browser may clear. |
+| `useCollectionUi()` | The state and actions behind the components, for a layout of your own. |
+
+```tsx title="Problem.tsx"
+import { CollectionProblem } from "@mdbase-dev/ui/collections";
+
+// The current phase's problem, as a banner above your content:
+
+
+// An error from one of your own calls:
+
+```
+
+All of them are exported from `@mdbase-dev/ui/collections`.
+
+## Restyle {#style}
+
+The stylesheet is self-contained. It follows the system’s light or dark setting; put `data-theme="light"` or `data-theme="dark"` on the root element to fix one. Set `--mdbase-collections-*` custom properties on any ancestor to match your app:
+
+```css title="worklog.css"
+.worklog {
+ --mdbase-collections-accent: #0f766e;
+ --mdbase-collections-on-accent: #ffffff;
+ --mdbase-collections-font: "Inter", system-ui, sans-serif;
+ --mdbase-collections-radius: 6px;
+}
+```
+
+| Properties | Control |
+| --- | --- |
+| `-accent`, `-on-accent` | Primary buttons and focus |
+| `-canvas`, `-surface`, `-border`, `-current-bg` | Backgrounds and lines |
+| `-text`, `-text-soft`, `-danger`, `-warning` | Text and status colours |
+| `-font`, `-font-size`, `-font-size-caption`, `-font-size-section`, `-font-size-heading`, `-font-weight-strong` | Type |
+| `-radius-sm`, `-radius`, `-radius-lg`, `-control-height` | Shape and size |
+| `-elevation-low`, `-elevation-high`, `-scrim` | Shadows and the dialog backdrop |
+
+## Wording and language {#wording}
+
+The components are in English by default and need no provider. Pass `copy` to replace individual strings; `defaultCollectionCopy` lists every key.
+
+The package also ships its strings in French, German, Spanish, Italian, Portuguese, Russian, Japanese, Korean and Chinese. `@mdbase-dev/ui/i18n` exports them as `uiCatalogues`, for an app that sets up `@mdbase-dev/i18n` with its own Lingui catalogue.
+
+## Apps that do not use React {#mount}
+
+`mountCollectionUi()` renders a component into an element you give it. Your app needs no React code of its own, though the `react` and `react-dom` packages must be installed.
+
+```ts title="main.ts"
+import { mountCollectionUi } from "@mdbase-dev/ui/collections";
+import "@mdbase-dev/ui/collections.css";
+import { mdbase } from "./mdbase";
+
+const app = { name: "Worklog" };
+
+// Sign-in, choosing and the list, inside your own dialog or page.
+const panel = mountCollectionUi(document.querySelector("#collections"), {
+ part: "panel",
+ mdbase,
+ app,
+});
+
+// The header control.
+mountCollectionUi(document.querySelector("#switcher"), {
+ part: "switcher",
+ variant: "compact",
+ mdbase,
+ app,
+});
+
+mdbase.subscribe(() => {
+ const { phase } = mdbase.getSnapshot();
+ const open = phase.kind === "ready" || phase.kind === "unsynced";
+ document.querySelector("#collections").hidden = open;
+ if (open) showWorklog(phase.connection.records);
+});
+
+// Later: panel.update({ ... }) to change options, panel.unmount() to remove it.
+```
+
+`part` is `"panel"`, `"switcher"` or `"problem"`. To draw everything yourself and keep only the logic, `collectionView()` turns a snapshot into the screen to show:
+
+```ts title="view.ts"
+import { collectionView } from "@mdbase-dev/ui/collections";
+
+const view = collectionView(mdbase.getSnapshot(), { appName: "Worklog" });
+// view.kind names the screen to draw, with that screen's wording and controls.
+```
+
+## Links to the mdbase apps {#apps}
+
+A collection your app uses can also be opened in mdbase’s [Editor, Reader and Writer](/apps/). `mdbaseAppHref()` builds a link to one of them that opens the collection named in the current page’s URL:
+
+```ts title="links.ts"
+import { mdbaseAppHref } from "@mdbase-dev/ui/apps";
+
+// The collection open in this page, opened in the Editor.
+editorLink.href = mdbaseAppHref("https://editor.mdbase.dev/", location.href);
+```
+
+The `AppSwitcher` component in the same package is the menu mdbase’s own apps show under their name. It lists only those three apps, so it is not a place to add yours.
diff --git a/content/sdk/unsynced.md b/content/sdk/unsynced.md
new file mode 100644
index 0000000..4cb253c
--- /dev/null
+++ b/content/sdk/unsynced.md
@@ -0,0 +1,120 @@
+---
+title: Work before connecting
+description: Let people use your app before they sign in. Their work is kept in the browser and brought into a collection when they connect one.
+section: sdk
+---
+
+## What it is {#what}
+
+With the `unsynced` option, a signed-out visitor gets a working app straight away. The SDK opens an **unsynced collection**: a real collection, with your types installed, stored in this browser and nowhere else. Your code reads and writes it through the same `MdbaseClient` as a synced one.
+
+When the person later signs in and opens a collection, the work they did can be brought into it.
+
+The [shared UI](/sdk/ui/) handles all of this when you pass `unsynced` to `CollectionGate` and `CollectionSwitcher`. The rest of this page is for apps that draw it themselves.
+
+## Turn it on {#enable}
+
+```ts title="mdbase.ts"
+import { createMdbase } from "@mdbase-dev/sdk";
+import manifest from "./mdbase-app.json";
+
+export const mdbase = createMdbase(
+ { id: manifest.id, name: manifest.name, origin: location.origin, environment: "production", manifest },
+ { unsynced: true },
+);
+```
+
+With the option set, `start()` opens the unsynced collection whenever the person is signed out and the URL names no collection. The phase is `unsynced`. The types in your manifest’s [provisions](/sdk/manifest/#provisioning) are installed in it automatically.
+
+## Show it {#render}
+
+```ts title="main.ts"
+function render(snapshot) {
+ const { phase } = snapshot;
+ if (phase.kind === "ready" || phase.kind === "unsynced") {
+ showApp(phase.connection.records);
+ savedOnlyHere.hidden = phase.kind !== "unsynced" || !snapshot.unsyncedWork;
+ }
+}
+
+// "Connect to sync your work"
+connectButton.onclick = () => mdbase.signIn();
+
+// On a sign-in screen: "Continue without connecting"
+continueButton.onclick = () => mdbase.unsynced.open();
+```
+
+- Treat `unsynced` like `ready`: `phase.connection` is the same kind of connection.
+- Tell the person where their work is. Once something has been saved, `snapshot.unsyncedWork` is set; show a line such as “Saved only in this browser” with a way to connect.
+- The unsynced collection is never listed in `snapshot.collections`.
+- A signed-in person with no collection open is in the `choosing` phase as usual. `mdbase.unsynced.open()` opens the unsynced collection from there, or from a sign-in screen that offers “Continue without connecting”.
+
+## Bring the work in {#transfer}
+
+After the person connects, `snapshot.unsyncedWork` stays set while the collection they opened does not have the work yet. Plan the transfer, show what it would do when there is something to decide, then run it.
+
+```ts title="bring-in.ts"
+// A collection is open (phase "ready") and snapshot.unsyncedWork is set.
+const plan = await mdbase.unsynced.planTransfer();
+
+// plan.counts: { create, present, skipped, renamed, changed }
+// plan.missingTypes: types the records use that this collection lacks
+if (plan.missingTypes.length > 0 && (await userAgreesToAddTypes(plan.missingTypes))) {
+ return bringIn(await mdbase.unsynced.planTransfer({ addTypes: true }));
+}
+await bringIn(plan);
+
+async function bringIn(plan) {
+ const result = await mdbase.unsynced.transfer(plan, {
+ onProgress: ({ done, total }) => showProgress(done, total),
+ });
+ if (result.failed.length > 0) {
+ // Plan and transfer again to retry. Nothing already done repeats.
+ }
+}
+```
+
+| Item outcome | Meaning |
+| --- | --- |
+| `create` | The record will be created, with the same ID. |
+| `present` | An earlier transfer already brought it in. |
+| `skipped` | Your `map` left it out. |
+| `changed` | It was brought in earlier and has changed here since. The newer version is created beside the first as a copy. |
+
+- Planning writes nothing. A plan is safe to throw away.
+- A transfer can be interrupted by a reload or a lost connection. Plan and transfer again: only what is missing is created.
+- When a path is already taken in the destination, the record goes to a free path beside it; the item’s `renamedFrom` has the path you asked for.
+- The destination’s own types and settings are never replaced. With `addTypes`, types it lacks are added from the unsynced collection.
+- When everything is in the destination, `result.retired` is true and the unsynced collection starts again empty.
+
+## Reshape records {#map}
+
+By default each record keeps its path and its whole Markdown source. Pass `map` to change where records go, or to leave some out:
+
+```ts title="bring-in.ts"
+const plan = await mdbase.unsynced.planTransfer({
+ map: (record) => {
+ if (!record.types.includes("worklog-entry")) return null; // leave it out
+ // Each record arrives with its body and complete source.
+ return { path: `journal/${record.path}`, document: record.document };
+ },
+});
+```
+
+The function returns a `CreateInput`, or `null` to leave the record out. A record always keeps its ID; returning a different `id` is refused.
+
+## Discard
+
+```ts title="discard.ts"
+if (await confirm("Delete the work saved in this browser? This cannot be undone.")) {
+ await mdbase.unsynced.discard();
+}
+```
+
+Discarding erases the unsynced collection from this browser. Ask first.
+
+## Limits
+
+- The work is in browser storage. Clearing site data, or a browser that evicts storage under pressure, removes it. Say so in your interface, and offer connecting early.
+- It is per browser and per origin. It is not on the person’s other devices, and a development build on another port has its own.
+- There is one unsynced collection per app in a browser.
diff --git a/package.json b/package.json
index 775cc77..ebad77e 100644
--- a/package.json
+++ b/package.json
@@ -27,6 +27,7 @@
"test": "pnpm test:spec && pnpm test:home && pnpm test:docs && pnpm test:deploy:dev && pnpm test:release-update && pnpm check:release && pnpm check && pnpm build && pnpm import:spec && pnpm index:site && pnpm check:links"
},
"dependencies": {
+ "@astrojs/markdown-satteri": "0.3.4",
"@astrojs/sitemap": "^3.7.3",
"@fontsource/atkinson-hyperlegible": "^5.3.0",
"@fontsource/azeret-mono": "^5.3.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c109d08..561528c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,6 +8,9 @@ importers:
.:
dependencies:
+ '@astrojs/markdown-satteri':
+ specifier: 0.3.4
+ version: 0.3.4
'@astrojs/sitemap':
specifier: ^3.7.3
version: 3.7.3
diff --git a/scripts/app-docs.test.mjs b/scripts/app-docs.test.mjs
index 5adc726..b94c668 100644
--- a/scripts/app-docs.test.mjs
+++ b/scripts/app-docs.test.mjs
@@ -1,17 +1,22 @@
import assert from "node:assert/strict";
import { readFileSync, existsSync } from "node:fs";
import { test } from "node:test";
-import { fileURLToPath } from "node:url";
const root = new URL("../", import.meta.url);
const read = (path) => readFileSync(new URL(path, root), "utf8");
const videos = JSON.parse(read("src/data/doc-videos.json"));
const placements = {
- "reader-markdown": "src/pages/apps/reader/index.astro",
- "extension-capture": "src/pages/apps/reader/extension/index.astro",
- "reader-library": "src/pages/apps/reader/library/index.astro",
- "writer-paper": "src/pages/apps/writer/index.astro",
- "writer-book": "src/pages/apps/writer/chapters/index.astro"
+ "reader-markdown": "content/apps/reader/index.md",
+ "extension-capture": "content/apps/reader/extension.md",
+ "reader-library": "content/apps/reader/library.md",
+ "writer-paper": "content/apps/writer/index.md",
+ "writer-book": "content/apps/writer/chapters.md"
+};
+// A documentation address is served by a record in content/ or, for the
+// generated reference pages, by an Astro page.
+const pageSources = (href) => {
+ const path = href.replace(/^\/|\/$/g, "");
+ return [`content/${path}.md`, `content/${path}/index.md`, `src/pages/${path}/index.astro`];
};
test("The domain challenge is packaged into the Pages deployment", () => {
@@ -36,8 +41,12 @@ test("Every documentation navigation entry resolves to a site page", () => {
assert.equal(links.filter((href) => href.startsWith("/apps/reader/")).length, 9);
assert.equal(links.filter((href) => href.startsWith("/apps/writer/")).length, 6);
for (const href of links) {
- const page = new URL(`src/pages${href}index.astro`, root);
- assert.ok(existsSync(page), `Missing navigation target: ${fileURLToPath(page)}`);
+ const sources = pageSources(href);
+ assert.equal(
+ sources.filter((path) => existsSync(new URL(path, root))).length,
+ 1,
+ `Navigation target ${href} needs exactly one of: ${sources.join(", ")}`,
+ );
}
assert.match(sections, /meta: { label: "@mdbase-dev\/sdk"/);
});
@@ -53,12 +62,13 @@ test("Five sample recordings have local playable files, posters and text equival
assert.match(metadata.duration, /^\d+:\d{2}$/);
assert.ok(metadata.width > 0 && metadata.height > 0);
assert.ok(metadata.steps.length >= 4, `${name}: text description of the actions`);
- assert.ok(read(placements[name]).includes(``));
+ assert.ok(read(placements[name]).includes(`](/videos/${name}.mp4)`), `${name}: placed in ${placements[name]}`);
}
});
-test("Video controls are opt-in and have accessible labels and descriptions", () => {
- const component = read("src/components/DocVideo.astro");
+test("Video controls are opt-in and have accessible labels and descriptions", async () => {
+ const { videoFigure } = await import("../src/markdown/doc-records.mjs");
+ const component = videoFigure("reader-markdown");
const attributes = component.match(/