# Writ Architecture
Writ is a text editor that opens any text file, edits and searches every file in its folder, and
renders Markdown inline when the file is Markdown. Chat, rewrite, connected programs (the MCP
server), connections, the graph and tags are apps switched on in Settings (ADR-041, ADR-042).
It is built with Tauri v2, SolidJS and CodeMirror 6. The design keeps the binary small, separates
business logic from framework code at the compiler level, and types the contract across every
layer of the stack.
## System Diagram
```
┌─────────────────────────────────────────────────────────────────┐
│ Tauri Shell │
│ │
│ ┌──────────────────────────┐ ┌───────────────────────────┐ │
│ │ Rust Backend │ │ SolidJS Frontend │ │
│ │ │ │ │ │
│ │ ┌────────────────────┐ │ │ ┌──────────────────────┐ │ │
│ │ │ writ-core │ │ │ │ Components │ │ │
│ │ │ (domain model) │ │ │ │ (editor, sidebar, │ │ │
│ │ │ buffer, config, │ │ │ │ tabs, statusbar) │ │ │
│ │ │ events, policy │ │ │ └──────────┬───────────┘ │ │
│ │ └────────┬───────────┘ │ │ │ │ │
│ │ │ │ │ ┌──────────▼───────────┐ │ │
│ │ ┌────────▼───────────┐ │ │ │ Stores │ │ │
│ │ │ writ-storage │ │ │ │ (buffer, config, │ │ │
│ │ │ SQLite, file I/O │ │ │ │ session, search) │ │ │
│ │ │ TOML, FTS5 │ │ │ └──────────┬───────────┘ │ │
│ │ └────────┬───────────┘ │ │ │ │ │
│ │ │ │ │ ┌──────────▼───────────┐ │ │
│ │ │ │ │ │ Services │ │ │
│ │ │ │ │ │ tauri.ts (IPC) │ │ │
│ │ │ │ │ │ typed commands │ │ │
│ │ │ │ │ └──────────┬───────────┘ │ │
│ │ │ │ │ │ │ │
│ │ ┌────────▼───────────┐ │◄──┼─────────────┘ │ │
│ │ │ src-tauri │ │ │ IPC Bridge │ │
│ │ │ (thin adapter) │ │──►│ invoke() / events │ │
│ │ │ commands, events │ │ │ │ │
│ │ └────────────────────┘ │ └───────────────────────────┘ │
│ └──────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
The diagram shows the runtime path. The full set of cargo dependency edges between
workspace members, which is what the build enforces:
```
src-tauri ─┬─▶ writ-core
├─▶ writ-storage ──▶ writ-core
├─▶ writ-plugin ───▶ writ-core
├─▶ writ-lint ─────▶ writ-core
├─▶ writ-audio ────▶ writ-core
└─▶ writ-render (no workspace dependencies)
writ-cli ─┬─▶ writ-core (no Tauri; ships beside the app binary as a
└─▶ writ-storage Tauri sidecar, not linked into it)
```
`writ-storage`, `writ-plugin`, `writ-lint` and `writ-audio` are siblings on `writ-core`. None of
them depends on another.
## Crate Responsibilities
### writ-core
Domain model and policy. Zero Tauri, no framework imports, no async runtime. Contains:
- Buffer model: open/close lifecycle, dirty state, cursor positions
- Config schema: typed structs for user preferences, keybindings, theme tokens
- Domain events: `BufferOpened`, `BufferSaved`, `ConfigChanged`, etc.
- Recovery policy: what a save's outcome does to the unsaved-text journal, and which notes a
relaunch may write back (ADR-044)
- File classification: the open-mode ladder in `file_ops`, which decides whether a path opens
normally, as a large file, after asking (over 50 MiB), or is refused (over 500 MiB); the
last two are answers carried as data, never errors (ADR-019)
- Notes-folder policy: the default folder `~/Writ`, the containment rule for paths inside it,
the title sanitiser shared by the migration, rename and auto-title, and the write guard
(`notes::guard::decide_save` over a recorded `DiskState`) that decides whether a save may land
on a file that changed under Writ
- Watcher ignore stamps keyed by canonical absolute path rather than by bare filename, so a save
of one note cannot suppress a genuine external change to another
The notes-folder policy and the re-keyed stamps arrive with the storage change in release 0.4
([ADR-028](./adr/028-files-are-the-only-copy.md)).
`writ-core` is not I/O-free. `file_ops` makes bounded `std::fs` probes (`metadata` for size, a
head-of-file read to sniff for NUL bytes, `canonicalize` on argv paths) because classification
cannot be decided without them. Reading and writing file contents is `writ-storage`'s job and
stays there.
The enforced constraint is the dependency direction: `writ-core` depends on no other
workspace crate, and if any Tauri type appears here the workspace fails to build. Its
external dependencies are `serde`, `serde_json`, `uuid`, `chrono`, `tracing`, `thiserror`,
`sha2`, `url` and `unicode-segmentation`.
### writ-storage
All persistence. Depends on `writ-core` for domain types, but not on Tauri.
The file on disk is the only copy of a note's text. SQLite holds derived data only: the FTS5
index keyed by canonical path under the notes folder, the index tables created by migration
`040_notes_migration.sql`, per-file history metadata, session and layout state, and tab order.
Deleting `writ.db` costs a reindex and the session layout, and loses no note. The mirror files
under `~/.writ/buffers/` are retired by the same migration, which verifies every mirror against the
file that now holds its text before unlinking it and keeps a rollback copy at
`writ.db.pre-notes-migration`. One copy of text outside a file stays legitimate: the unsaved-text
journal, holding text no file holds (ADR-044).
Contains:
- SQLite layer via `rusqlite` with WAL mode enabled
- FTS5 search index over the notes folder, keyed by canonical file path (ADR-028)
- The `files`, `links`, `properties`, `tags` and `headings` index tables, created empty by
migration `040_notes_migration.sql` and keyed by canonical path
- File I/O: reading and writing files to disk with atomic renames. A save is refused with
`StorageError::SourceChangedOnDisk` when the hash of the bytes on disk differs both from the
last known hash and from the content being written
- TOML parsing for config files using `toml` crate
- Crash recovery (wired, ADR-044): `recovery::journal` is the `unsaved_text` table of text no file
holds: what a save could not write, and what a bar held back, which the frontend hands over on
the autosave's debounce. A tab owns at most one entry per note: the save command writes it as it
returns, with a synchronous commit when its hash differs from the entry's, and the next save of
that tab that lands clears it, as does closing the tab with "Close and lose changes"
(`discard_unsaved_text`). An entry outlives its note's row, and a launch writes such text to a
dated copy of its own. Reopening a closed note
(`BufferStore::restore`) and every launch release the entries from their tabs, so no save of a
tab that shows the file clears them. `AppState` reads the journal on every launch (before the
watcher starts and before empty-scratch reclaim) and writes each entry into the note's file or
beside it, removing what lands; a row that does not decode is logged and kept.
`recovery::legacy` moves the text of a 0.5 snapshot into the journal once.
`recovery::snapshot` keeps session markers with no text: the heartbeat records an unclean one
once per session from a thread that wakes every 120 s, `ExitRequested` records a clean one, and
`recovery::dirty_shutdown` reads the latest for the launch's log. The heartbeat reads no note's
file; the quit reads only the files whose index updates saves deferred (ADR-020).
The journal policy lives in `writ-core::recovery`; mechanism lives here.
`AppState::initialize` also runs the read-only `ConsistencyChecker` on boot, logging
orphaned backing files and rows whose content file is missing (repair policy is deferred).
### writ-plugin
Defines the extension boundary. Provides a stable API surface that plugins target. Depends on
`writ-core` types. Isolates the plugin ABI from Tauri internals so the host runtime can evolve
independently of published extension contracts. Also holds the shipped text-transform runtime:
the `TextTransform` trait, the registry, and the built-in and composite transforms
(see [ADR-006](./adr/006-plugin-runtime-v1.md) and [ADR-012](./adr/012-composite-transforms.md)).
### writ-render
Markdown to HTML-fragment core. Turns buffer text into the fragment the preview pane renders,
including fenced-diagram blocks. `pulldown-cmark` is its only non-optional dependency and it
depends on no workspace crate, so it stays callable outside the app; `crate-type` includes
`cdylib` and an optional `wasm` feature compiles it to WebAssembly. `src-tauri`'s preview
renderers are the in-tree consumer.
### writ-lint
Spell check and mechanical-writing rules (ADR-050). Spelling runs on `spellbook` against the
SCOWL Hunspell dictionaries bundled in the crate, one per English variant, with the words Harper's
dictionary accepted added to them; repeated words, repeated spaces, a wrong apostrophe and a/an
are the crate's own rules. `pulldown-cmark` finds the prose, so code, HTML, front matter and URLs
are never checked. Depends on `writ-core`. Style and
readability rules are left out by design: Writ flags mistakes, not prose taste. The rules work in
byte offsets and CodeMirror measures UTF-16 code units, so the crate converts every range before
returning.
### writ-audio
Microphone capture for dictation ([ADR-058](./adr/058-dictation.md)). `Recorder` opens the
default input device through `cpal` (CoreAudio, WASAPI, ALSA) and delivers `AudioFrame`s of
16 kHz mono Int16, downmixed and resampled with `rubato`, the one format both dictation engines
take. Depends on `writ-core` and has no Tauri dependency. Where a segment ends, which engine runs
and what an error tells the person are `writ_core::dictation` policy; the session that drives
capture, transcription and the per-session event `Channel` lives in `src-tauri`. Audio is held in
memory only.
### writ-cli
The `writ` command line binary. Two surfaces. The open path parses argv and stdin into an
open target (a file list, a workspace directory, or piped text, which becomes a note in the
notes folder like any other new note) and hands it to the app: by bundle id on macOS, by the
sibling app binary elsewhere, with the OS default handler as the fallback. The note verbs
(`links`, `backlinks`, `properties`, `tags`, `new`, `rename`, `trash`) answer from the notes
folder and from a read-only connection to the note index, and open no window.
Depends on `writ-core` and `writ-storage` so link resolution, note naming and the note
operations have one definition each rather than a copy in the CLI; it has no Tauri
dependency, so it is testable without an app handle. Bundled as a Tauri sidecar that ships
beside the app executable. See [ADR-017](./adr/017-command-line-surface.md),
[ADR-028](./adr/028-files-are-the-only-copy.md) section 1 for the piped-text target, and
[the verb record](./cli-verbs.md).
### src-tauri
The only crate that imports `tauri`. Thin adapter responsibilities only:
- Registers Tauri commands that delegate immediately to `writ-core` or `writ-storage`
- Translates Tauri events to domain events and vice versa
- Manages application lifecycle (setup, teardown, window configuration)
- Blesses the notes-folder root as a containment root in
`src-tauri/src/security/authorized_paths.rs`, so any note inside the folder is writable,
including one a sync client delivered and the sidebar opened
- Refuses to start when the data directory resolves inside a sync provider's tree, and asserts
that the database is not inside the notes folder
([ADR-028](./adr/028-files-are-the-only-copy.md) section 9)
- No business logic; if logic accumulates here, it must be pushed down into `writ-core`
## Frontend Architecture
```
Components → Stores → Services (tauri.ts) → IPC → Rust commands
```
- **Components** are pure-reactive SolidJS. They read from stores and dispatch actions; they do
not call `invoke()` directly.
- **Stores** hold derived and authoritative UI state using SolidJS signals and `createStore`.
- **Services / tauri.ts** is the single file that calls `@tauri-apps/api/core` `invoke()`.
All IPC payloads and responses are typed with generated or hand-maintained TypeScript interfaces
that mirror the Rust command signatures.
- **Services / events.ts** is the single file that imports `@tauri-apps/api/event`. Every
`listen` and `emit` goes through it, so the set of live subscriptions is readable in one place.
- **IPC** layer carries typed JSON. Command names and payload shapes are the contract; breaking
changes require updating both sides atomically.
Two rules keep the DOM out of the reactive graph:
- No `document.querySelector` in components or stores. Reach an element with a ref, or keep the
state in a store. Test files are exempt.
- No `document.addEventListener` outside `onMount` or `createEffect`, and every listener is
removed in a matching `onCleanup`. A listener registered at module scope outlives the
component that wanted it.
### Design tokens
Every colour, radius, type step, shadow and duration is a DTCG token under `design/tokens/`.
`pnpm tokens:build` emits four files, all of them read-only:
| Output | Consumer |
|---|---|
| `src/styles/generated/theme.css` | the app, imported by `src/styles/global.css` after `fonts.css` |
| `src/styles/generated/tokens.ts` | TypeScript that needs a token value or an accent id |
| `src-tauri/assets/generated/preview-tokens.css` | the `writ-preview://` iframe, inlined by `renderers/theme.rs` |
| `site/design-system/generated/tokens.css` | nothing yet: no page imports it, and the demo window declares its own `--writ-*` values in `site/src/styles/writ-window.css` |
A component stylesheet spends `var(--writ-*)`; it never declares one. Three architecture tests
hold the line: `no-literal-color`, `no-raw-radius-or-easing`, and `legacy-aliases`, which carries
the pre-ADR-030 names and fails any file that still reads one. A new token is added to
`design/tokens/` and the outputs regenerated in the same commit, which CI checks by rebuilding
and diffing ([ADR-030](./adr/030-design-system-tokens.md)).
## Design Principles
1. **Compiler-enforced boundaries** — workspace dependency constraints prevent accidental coupling.
The build is the enforcer, not code review comments.
2. **Policy in core, mechanism in adapter** — `writ-core` decides what should happen; `src-tauri`
decides how to surface that to Tauri's event loop. Core never imports Tauri; adapter never
contains business logic.
3. **Typed events end-to-end** — Rust enums serialize to JSON, TypeScript interfaces deserialize
from JSON. The `tauri.ts` service layer owns the mapping and is the only place where
`as unknown as T` casts are tolerated.
4. **No speculative complexity** — features are added when needed. The plugin crate exists to
define a boundary, not to ship a full extension runtime on day one.
## Decisions in short
Each of these is recorded in [`docs/adr/`](./adr/).
- **Files are the only copy of the text.** A file lives in the Writ folder or wherever it was opened from, and saves back to its own path. `writ.db` holds what Writ works out from the files: the search index, links, tags, properties and window state. Delete it and Writ rebuilds it from the files.
- **Resident, not launched.** The app keeps running with its window hidden, so the global hotkey shows a window instead of starting a program. Open at login, a switch in Settings that sets a login item through `tauri-plugin-autostart`, starts it hidden with `--login`, so the hotkey works after a restart; `general.launch_at_login` records the last choice and turns the item on once at the end of a first launch. The hotkey needs Cmd, Ctrl or Alt unless its key is F13 to F24, a new chord is registered before the old one is released, and a chord another app holds or a Wayland session cannot deliver is shown as such in the titlebar and Settings. A second chord opens the quick capture note, a window of its own that adds one entry to Today's File (ADR-055).
- **Keyboard first.** Every command, setting and file is reachable from the command palette.
- **Dictation is a stream into one pane.** `dictation_start` returns a session and streams `DictationEvent`s over a Tauri `Channel`; `writ-audio` captures, `writ_core::dictation` cuts segments at pauses, and each segment is transcribed on the Mac or by an OpenAI-compatible endpoint, then inserted at an anchor in the pane that started the session, one undo step per segment. Audio stays in memory and has its own consent list (ADR-058).
- **The preview trusts nothing.** Markdown, HTML, Mermaid and KaTeX render from runtimes bundled into the app, and the preview blocks all network access.
- **The core does not know Tauri exists.** `writ-core`, `writ-storage`, `writ-render`, `writ-lint`, `writ-mcp`, `writ-audio` and `writ-plugin` are plain Rust crates with no Tauri dependency; the shell is a thin adapter, and the build enforces the boundary.
- **One guarded write.** The editor, the `writ` command, a rename, a link rewrite, a connected program and a chat proposal all write a file through the same path, which refuses to overwrite a newer file and leaves a conflict copy beside it.
- **Files from anywhere.** The CLI, the watched folder, default-app registration and the MCP server let another program make or read a file that Writ then opens, renders and searches.
```mermaid
flowchart LR
classDef entry fill:#2f5d50,color:#fff,stroke:none
classDef data fill:#1f3a33,color:#e6efeb,stroke:none
classDef crate fill:#eef4f1,color:#14231e,stroke:#b9d0c6
classDef zone fill:none,stroke:#6f9a8b,stroke-dasharray:3 3
HK([global hotkey]):::entry
CLI([writ CLI]):::entry
MCP([writ mcp, stdio]):::entry
ASSOC([default app for .md, .log, .toml]):::entry
subgraph FRONT [frontend · SolidJS]
direction LR
UI[components] --> ST[stores] --> SV[services]
end
subgraph SHELL [src-tauri · thin adapter]
direction LR
CMD[IPC commands]
EVT[event emitter]
FSW[file watcher]
end
subgraph CORE [pure Rust · no Tauri imports]
direction LR
WC[writ-core
policy]:::crate
WR[writ-render
markdown · mermaid · katex]:::crate
WS[writ-storage
guarded writes · index]:::crate
end
HK & CLI & ASSOC --> SHELL
MCP --> WS
SV -- invoke --> CMD
EVT -. events .-> SV
FSW -. fs changes .-> EVT
CMD --> WC
WC --> WR --> PV[offline preview
network blocked]
WC --> WS
WS --> DB[(SQLite index
FTS5 · links · tags)]:::data
WS --> FS[(Writ folder
.txt and .md files)]:::data
class FRONT,SHELL,CORE zone
```
## Architecture Decision Records
Individual decisions are documented in [`docs/adr/`](./adr/). Start with
[ADR-001](./adr/001-tauri-over-electron.md) for the top-level shell choice and work forward.
[ADR-028](./adr/028-files-are-the-only-copy.md) is the record for where a note's text lives,
[ADR-030](./adr/030-design-system-tokens.md) for the token layer, and
[ADR-031](./adr/031-the-ai-harness-and-what-leaves-the-machine.md) for what the AI surfaces reach
and what leaves the machine. The assertions ADR-031 is walked against are listed in
[the threat-model checklist](./threat-model.md).