Skip to content

Build your personal knowledge base with Trilium Notes

chore(skills): add data-model, API-route and release skills

Elian Doranb81141562d8b
diff --git a/.claude/skills/adding-internal-api-route/SKILL.md b/.claude/skills/adding-internal-api-route/SKILL.md
new file mode 100644
index 0000000000..4484c32d31
--- /dev/null
+++ b/.claude/skills/adding-internal-api-route/SKILL.md
@@ -0,0 +1,133 @@
+---
+name: adding-internal-api-route
+description: Use when adding, moving, or wiring an internal REST endpoint in Trilium (a new `/api/*` route) — choosing between a core-shared handler (`packages/trilium-core/src/routes/index.ts` `buildSharedApiRoutes`, ~140 routes that ALSO run in the standalone sql.js WASM build) and a server-only one (`apps/server/src/routes/routes.ts`), picking the `apiRoute` vs `asyncApiRoute` vs `route`/`asyncRoute` wrapper, and getting the implicit return conventions (object→200, `undefined`→204, `[status, body]` tuple→that status) and `convertEntitiesToPojo`'s narrow entity-unwrapping right. Most routes are core-shared (and run under WASM); `apps/server/src/routes/api/` is the minority case. Pairs with writing-unit-tests for the cross-runtime CoreApiTester spec.
+---
+
+# Adding an internal API route in Trilium
+
+**The first decision is which `routes/api/` directory.** There are **TWO**, and the common assumption that all routes live server-side in `apps/server/src/routes/api/` is wrong — that's the *minority* case. ~140 of the routes live in the **core** one:
+
+| Directory | Wired by | Runs in | Testable by |
+|---|---|---|---|
+| **`packages/trilium-core/src/routes/api/*`** (default, ~140 routes) | `buildSharedApiRoutes` in [`packages/trilium-core/src/routes/index.ts:84`](../../../packages/trilium-core/src/routes/index.ts) | server **+ desktop + standalone WASM** | `CoreApiTester` (cross-runtime) **and** supertest |
+| `apps/server/src/routes/api/*` (server-only) | `register()` in [`apps/server/src/routes/routes.ts:47`](../../../apps/server/src/routes/routes.ts) | server + desktop only | supertest only |
+
+A route you add only in `routes.ts` is **invisible to the standalone build and cannot be driven by `CoreApiTester`**. A core handler that imports `node:*` or touches `process.env` **breaks the WASM build**. Pick the wrong side and you either lose standalone support or break it.
+
+## Footgun checklist (read before you start)
+
+1. **Default to core.** Note/branch/attribute/tree/search/revision/import logic is browser-safe → put it in `packages/trilium-core/src/routes/api/` and register in `index.ts`'s `buildSharedApiRoutes`. Only Node-only or genuinely server-scoped routes go in `routes.ts`. (Step 1.)
+2. **Async handler ⇒ `asyncApiRoute`, never `apiRoute`.** `apiRoute` runs `sql.transactional(cb)` **synchronously** ([`route_api.ts:100`](../../../apps/server/src/routes/route_api.ts)) — hand it an async function and it commits an empty transaction *immediately*; your awaited writes land outside any transaction. (Step 2.)
+3. **Return conventions are implicit.** object/array/string → `200`; `undefined`/nothing → `204`; `[integerStatus, body]` tuple → that status. Throw `ValidationError`/`NotFoundError` for 400/404. (Step 3.)
+4. **`convertEntitiesToPojo` only unwraps narrow shapes.** A `BNote` nested under `result.notes[]`, `result.parentNote`, `result.attributes[]` serializes raw/broken — call `.getPojo()` yourself or shape under `note`/`branch`. (Step 4.)
+5. **Core handlers must be browser-safe:** no `process.env` (use `getPlatform().getEnv()`), no `node:path`/`import path` (use [`services/utils/path.ts`](../../../packages/trilium-core/src/services/utils/path.ts) `extname`/`basename`), no Node built-ins.
+6. **Registration order matters cross-runtime** — register a literal path before a same-method `:param` catch-all on the same prefix. (Step 5.)
+7. **Don't write the test by hand** — core route ⇒ `CoreApiTester`; Express transport ⇒ supertest. Hand off to the **writing-unit-tests** skill. (Step 6.)
+
+## Step 1 — Decide: core-shared vs server-only
+
+| Put the handler in… | When |
+|---|---|
+| **core** `packages/trilium-core/src/routes/api/<m>.ts` + register in `index.ts` `buildSharedApiRoutes` | logic uses only browser-safe deps (`becca`, `getSql()`, core services, platform providers) AND the feature should work in standalone. **Default** for note/branch/attribute/tree/search/etc. |
+| **server-only** `apps/server/src/routes/api/<m>.ts` + register in `routes.ts` `register()` | needs Node-only deps not behind a platform provider (multer fs paths, OCR/LLM SDKs, metrics, sender, electron), or is genuinely server-scoped (etapi-tokens, totp, recovery codes) |
+
+The server-only set is small and specific — clipper, database, llm_chat, ocr, metrics, sender, totp, fonts, link_embed, recovery_codes, system_info, etapi_tokens, plus a few `files` extras. See the `register()` body in `routes.ts` (the shared set is wired by `buildSharedApiRoutes` at `routes.ts:97`). Everything else is core.
+
+**Browser-safe rule for core handlers:** no `process.env`, no `node:path`/`import path`, no Node built-ins — they run in the sql.js WASM standalone build. (`script.ts:75,86` reads `process.env.TRILIUM_SAFE_MODE` directly — that is a **latent violation**, not a pattern to copy.)
+
+## Step 2 — Pick the wrapper
+
+All four wrappers live in [`apps/server/src/routes/route_api.ts`](../../../apps/server/src/routes/route_api.ts) (`apiRoute:69`, `asyncApiRoute:73`, `route:77`, `asyncRoute:81`). Their names arrive via the `buildSharedApiRoutes` context object, so **registering once in `index.ts` auto-wires all three call sites** (server `routes.ts:97`, standalone `browser_routes.ts:281`, `api_tester.ts:264`).
+
+A fifth name, `asyncRouteWithoutTransaction`, is also in the context object (`index.ts:84`) — use it for a long-running async handler that must not hold a transaction open.
+
+| Wrapper | Handler shape | Transaction | Auth + CSRF | Result handling |
+|---|---|---|---|---|
+| `apiRoute(method, path, h)` | **synchronous** `(req) => value` | `sql.transactional` (**sync**) | `checkApiAuth` + csrf, auto | `apiResultHandler` |
+| `asyncApiRoute(method, path, h)` | **async** `(req) => Promise` | async (no sync wrap) | `checkApiAuth` + csrf, auto | `apiResultHandler` |
+| `route(method, path, [mw], h, resultHandler?)` | sync; writes `res` directly OR custom `[mw]` (image/file download, setup, sync) | sync | **explicit** `[mw]` | optional |
+| `asyncRoute(method, path, [mw], h, resultHandler?)` | async + explicit `[mw]` (import/export, multipart) | async | **explicit** `[mw]` | optional |
+
+**The sync-transactional trap (`route_api.ts:100`):**
+
+```ts
+return transactional ? sql.transactional(cb) : cb();
+```
+
+`apiRoute` → `route(...true)` → `internalRoute(..., transactional=true)`; `asyncApiRoute` → `asyncRoute(...false)` → `transactional=false`. So `apiRoute` calls `sql.transactional(cb)` **synchronously**. If `cb` is `async`, `sql.transactional` sees a returned Promise, commits the (empty) transaction, and your `await`ed writes run *after* the commit, outside any transaction. The standalone adapter documents this exact trap in `browser_routes.ts:127-133` ("would commit an empty transaction immediately when passed an async callback"). **Async handler ⇒ `asyncApiRoute`. Always.**
+
+**Auth/CSRF:** `apiRoute`/`asyncApiRoute` attach `auth.checkApiAuth` + `csrfMiddleware` automatically (`route_api.ts:70,74`). Mutating endpoints therefore carry CSRF for free. Routes called from outside a browser session (setup, sync, sender, image/file download) use bare `route()`/`asyncRoute()` with an explicit `[middleware]` array (often `checkApiAuthOrElectron` or `checkApiAuth`) — see the `route(...)`/`asyncRoute(...)` registrations in `index.ts` and `routes.ts`.
+
+## Step 3 — Return value conventions
+
+From `apiResultHandler` ([`route_api.ts:29-47`](../../../apps/server/src/routes/route_api.ts)), mirrored by the standalone `apiResultHandler` (`browser_routes.ts:227`) and `CoreApiTester.formatApiResult` (`api_tester.ts:100`):
+
+| Your handler returns… | HTTP status | Real example |
+|---|---|---|
+| object / array / string | `200` | most handlers |
+| `undefined` / nothing | `204` | `branches.ts` `setPrefix`, `setExpanded` |
+| `[integer, body]` (first elem is an int) | that status code | `branches.ts:42,90` `[200, …]`; `import.ts:67,71,126` `[500, msg]`; `revisions.ts:123` `[400, "Description must be a string."]` |
+| `throw new ValidationError(...)` / `NotFoundError(...)` | `400` / `404` | mapped by `handleException` (`route_api.ts:130`); `CoreApiTester` maps `HttpError`→status at `api_tester.ts:335` |
+
+Direct-response handlers (image/download) write to `res` themselves and use `route()`, not `apiRoute()` — see the direct-response registrations in `index.ts`.
+
+## Step 4 — Entity serialization (`convertEntitiesToPojo`)
+
+[`index.ts:365-390`](../../../packages/trilium-core/src/routes/index.ts) only unwraps `AbstractBeccaEntity` instances in **five** shapes:
+
+1. the **top-level** result is an entity (`:366`)
+2. the **top-level** result is an **array** of entities (`:368-372`)
+3. `result.note` (`:375-376`)
+4. `result.branch` (`:379-380`)
+5. (recursively) `result.executionResult`, from `runOnBackend()` (`:384-387`)
+
+**Anything else serializes raw.** A `BNote` under `result.notes[]`, `result.parentNote`, `result.attributes[]`, `result.attachment`, or any other key is **not** unwrapped — `JSON.stringify` then ships the live entity (lazy getters, becca back-references) and the response is wrong or throws. Fix: call `.getPojo()` yourself when building the response, or place the entity under a recognized `note`/`branch` key. `createTextNote` relies on this: the create handler returns `{ note, branch }` and both get unwrapped.
+
+## Step 5 — Registration order
+
+Both Express **and** `CoreApiTester` match in **registration order, first match wins** — the tester iterates `this.routes` and returns on the first match (`api_tester.ts:301`). Register a literal path *before* a same-method `:param` catch-all on the same prefix. Precedent (etapi side): `routes.ts:190` — "Register revisions routes BEFORE notes routes so /etapi/notes/history is matched before /etapi/notes/:noteId". Current core `/api/notes/...` literals avoid collisions only because they differ by HTTP method (e.g. `POST /api/notes/erase-deleted-notes-now` vs `GET /api/notes/:noteId`) — if you add a literal that shares a method with an existing `:param` route on the same prefix, **put the literal first**.
+
+## Step 6 — Test it (handoff, don't reinvent)
+
+Don't hand-roll a route test. Use the existing harness:
+
+| What you added | Test with | Where |
+|---|---|---|
+| **core** handler | `CoreApiTester.build()` ([`packages/trilium-core/src/test/api_tester.ts`](../../../packages/trilium-core/src/test/api_tester.ts)) | co-located `packages/trilium-core/src/routes/api/<m>.spec.ts` — runs under **both** server and standalone suites |
+| Express transport (CSRF/auth wiring) | supertest agent + `bootLoggedInApp()` | `apps/server/src/routes/api/core_routes_http.spec.ts` |
+| **server-only** route | supertest agent | co-located `apps/server/src/routes/api/<m>.spec.ts` |
+
+Minimal core spec (full patterns + fixtures live in the **writing-unit-tests** skill, `server-and-core.md` Pattern 0/1 — reference it, don't restate):
+
+```ts
+import { beforeAll, describe, expect, it } from "vitest";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+let api: CoreApiTester;
+describe("Widget API (core)", () => {
+ beforeAll(() => { api = CoreApiTester.build(); });
+ it("returns the widget", async () => {
+ const note = await createTextNote(api, { title: "Source" });
+ const res = await api.get(`/api/widgets/${note.noteId}`);
+ expect(res.status).toBe(200);
+ });
+});
+```
+
+`createTextNote(api, {...})` → `{ noteId, branchId }` lives in `packages/trilium-core/src/test/api_fixtures.ts`. A core spec runs cross-runtime — **run both suites** before calling it done (`pnpm --filter server exec vitest run <spec>` AND `pnpm --filter standalone exec vitest run <spec>`); the providers differ. See **writing-unit-tests** for the cross-runtime traps and the Windows/sandbox vitest invocation.
+
+## Quick recipe (core route, the common case)
+
+1. Write `getX`/`putX` in `packages/trilium-core/src/routes/api/<m>.ts` as a **sync** `(req) => value` (or `async` if it awaits) handler; default-export the object of handlers.
+2. Add the registration line to `buildSharedApiRoutes` in `index.ts` — `apiRoute(GET, "/api/...", <m>Route.getX)` for sync, `asyncApiRoute(...)` for async. That single line wires server + desktop + standalone + `CoreApiTester`.
+3. Return a value (Step 3); keep it browser-safe (Step 1); unwrap entities under `note`/`branch` or via `.getPojo()` (Step 4); mind ordering (Step 5).
+4. Add a co-located `<m>.spec.ts` with `CoreApiTester` and run both suites (Step 6).
+
+## Reference map
+
+| File | What it covers |
+|---|---|
+| [references/wrappers-and-conventions.md](references/wrappers-and-conventions.md) | Full wrapper matrix (handler shape, sync vs async transaction, middleware, result handler), the return-value table with real call sites, the `convertEntitiesToPojo` unwrap table, and how the three `buildSharedApiRoutes` call sites (Express `route_api.ts`, standalone `browser_routes.ts`, `CoreApiTester` `api_tester.ts`) each implement the same context. |
+
+**Related skills:** **writing-unit-tests** (`server-and-core.md` Pattern 0 = `CoreApiTester`, Pattern 1 = supertest transport) for testing; **analyzing-coverage** for chasing the new handler's coverage.
diff --git a/.claude/skills/adding-internal-api-route/references/wrappers-and-conventions.md b/.claude/skills/adding-internal-api-route/references/wrappers-and-conventions.md
new file mode 100644
index 0000000000..25d55572e6
--- /dev/null
+++ b/.claude/skills/adding-internal-api-route/references/wrappers-and-conventions.md
@@ -0,0 +1,115 @@
+# Wrappers, conventions & the three call sites
+
+Depth for the SKILL.md decision tables. Every claim cites a real file:line — line numbers drift, so re-open before quoting.
+
+## 1. The four wrappers (`apps/server/src/routes/route_api.ts`)
+
+```ts
+// :66
+export function apiRoute<P>(method, path, routeHandler /* sync */) {
+ route(method, path, [auth.checkApiAuth, csrfMiddleware], routeHandler, apiResultHandler);
+}
+// :70
+export function asyncApiRoute<P>(method, path, routeHandler /* async */) {
+ asyncRoute(method, path, [auth.checkApiAuth, csrfMiddleware], routeHandler, apiResultHandler);
+}
+// :74
+export function route<P>(method, path, middleware, routeHandler, resultHandler = null) {
+ internalRoute(method, path, middleware, routeHandler, resultHandler, /* transactional */ true);
+}
+// :78
+export function asyncRoute<P>(method, path, middleware, routeHandler, resultHandler = null) {
+ internalRoute(method, path, middleware, routeHandler, resultHandler, /* transactional */ false);
+}
+```
+
+| Wrapper | Handler signature (TS type) | Transaction (`internalRoute:97`) | Middleware | Result handler | Use for |
+|---|---|---|---|---|---|
+| `apiRoute` | `SyncRouteRequestHandler` — `(req,res,next) => object \| number \| string \| void \| null` (the `NotAPromise<object>` type **forbids** a Promise return) | `sql.transactional(cb)` — **synchronous** | fixed `[checkApiAuth, csrf]` | always `apiResultHandler` | sync read/write that returns a value |
+| `asyncApiRoute` | `ApiRequestHandler` — `(req,res,next) => unknown` (Promise allowed) | `cb()` — no sync wrap | fixed `[checkApiAuth, csrf]` | always `apiResultHandler` | async handler returning a value |
+| `route` | `SyncRouteRequestHandler` | `sql.transactional(cb)` | **explicit array** | optional (`null` ⇒ handler owns `res`) | direct-to-`res` (image/file), externally-called (setup/sync), custom mw |
+| `asyncRoute` | `ApiRequestHandler` | `cb()` | **explicit array** | optional | async + multipart/streaming (import/export) |
+
+### The synchronous-transactional footgun, in full (`internalRoute:82-98`)
+
+```ts
+const result = cls.init(() => {
+ cls.set("componentId", req.headers["trilium-component-id"]);
+ cls.set("localNowDateTime", req.headers["trilium-local-now-datetime"]);
+ cls.set("hoistedNoteId", req.headers["trilium-hoisted-note-id"] || "root");
+ const cb = () => routeHandler(req, res, next);
+ return transactional ? sql.transactional(cb) : cb(); // :97
+});
+```
+
+`sql.transactional(cb)` runs `cb` and commits **when `cb` returns**. If `cb` is `async` it returns a Promise immediately, so the commit fires before any `await` inside resolves — the transaction is empty and every subsequent write runs un-transacted. The downstream `if (result instanceof Promise) { result.then(...) }` (`:104`) still resolves the response correctly, which is why this is silent: the HTTP response looks fine, but durability/atomicity is gone. **That is why `asyncApiRoute` exists and threads `transactional=false`** — async work uses the promise path with no synchronous commit. The standalone adapter spells it out:
+
+> `browser_routes.ts:127-133` — "Uses transactionalAsync (manual BEGIN/COMMIT/ROLLBACK) instead of the synchronous transactional() wrapper, which would commit an empty transaction immediately when passed an async callback."
+
+TypeScript helps a little: `apiRoute`'s `SyncRouteRequestHandler` (`route_api.ts:27`) is typed `NotAPromise<object> | number | string | void | null`, so an `async` handler that returns `Promise<object>` is a type error at the registration site. Don't defeat it — switch to `asyncApiRoute`.
+
+## 2. Return-value conventions (`apiResultHandler`, `route_api.ts:29-47`)
+
+```ts
+result = routes.convertEntitiesToPojo(result); // :29
+if (Array.isArray(result) && result.length > 0 && Number.isInteger(result[0])) {
+ const [statusCode, response] = result; // :33 [status, body] tuple
+ // 200/201/204 are not logged; everything else is logged as a non-OK response (:35)
+ return send(res, statusCode, response); // :39
+} else if (result === undefined) {
+ return send(res, 204, ""); // :41 nothing → 204
+}
+return send(res, 200, result); // :43 object/array/string → 200
+```
+
+`send` (`:47`) sets `text/plain` for string bodies with status ≥ 400, else JSON. Errors thrown by the handler are caught in `internalRoute` and mapped by `handleException` (`:127`): `ValidationError`/`NotFoundError` → their `.statusCode`, anything else → 500.
+
+| Return | Status | Notes |
+|---|---|---|
+| `{ ... }` / `[ ... ]` (non-int-first) / `"..."` | 200 | the common case |
+| `undefined` (no `return`) | 204 | empty body |
+| `[200, body]` | 200 | `branches.ts:42,90` — validation-failed-but-OK results |
+| `[400, "msg"]` | 400 | `revisions.ts:123` |
+| `[500, "msg"]` | 500 | `import.ts:67,71,126` |
+| `throw new ValidationError("...")` | 400 | core `errors` (`branches.ts:27,278,283`) |
+| `throw new NotFoundError("...")` | 404 | core `errors` |
+
+## 3. `convertEntitiesToPojo` unwrap table (`index.ts:365-390`)
+
+| Result shape | Unwrapped? | Line |
+|---|---|---|
+| top-level `AbstractBeccaEntity` | yes → `.getPojo()` | :257-258 |
+| top-level `Array` of entities | yes, element-wise | :259-264 |
+| `result.note` is an entity | yes | :266-267 |
+| `result.branch` is an entity | yes | :270-271 |
+| `result.executionResult` (from `runOnBackend()`) | yes, **recursively** | :275-277 |
+| `result.notes[]`, `result.parentNote`, `result.attributes[]`, `result.attachment`, any other key | **NO** | — |
+
+The function header comment is the warning: *"If entity is not caught, serialization to JSON will fail"* (`:255`). For an unrecognized shape, call `.getPojo()` when assembling the response, or nest under `note`/`branch`. (Handlers that return many notes typically map to plain objects already, e.g. tree/search build POJOs directly rather than returning live `BNote`s.)
+
+## 4. One registration, three runtimes
+
+`buildSharedApiRoutes` (`index.ts:84`) takes a context of injected helpers and registers ~140 routes against them. Each runtime supplies its own implementations of that context, so a single `apiRoute(...)` line lights up everywhere:
+
+| Call site | File | What it injects | Auth/CSRF | Multipart |
+|---|---|---|---|---|
+| **Express server** | `apps/server/src/routes/routes.ts:97` | the real `route_api.ts` wrappers + `auth.*` middleware + `csrfMiddleware` + multer | enforced | real multer (`uploadMiddlewareWithErrorHandling`) |
+| **Standalone (WASM)** | `apps/standalone/src/lightweight/browser_routes.ts:281` | `BrowserRouter`-bound wrappers; `transactional()` for sync, `transactionalAsync()` for async (`createAsyncRoute:135`); all auth/csrf/rate-limit are no-ops (`noopMiddleware:251`) | none (no network) | mock `req.file` |
+| **CoreApiTester** | `packages/trilium-core/src/test/api_tester.ts:264` | in-process wrappers; `getContext().init` + `getSql().transactional`; `noop` middleware; first-match-wins routing | skipped by design | pass `file:` in `RequestOptions` |
+
+Implications:
+
+- **Standalone parity is automatic for core routes.** If your handler is browser-safe, registering in `index.ts` makes it work in standalone with zero extra code. If it isn't (Node-only dep), the WASM bundle breaks — that's the signal it belongs in `routes.ts` instead.
+- **`CoreApiTester` is "supertest for core" with no socket.** `request()` (`api_tester.ts:281`) builds an Express-like `req`, matches `this.routes` in registration order (`:301`), runs the handler inside `getContext().init` + transaction, applies the same `convertEntitiesToPojo` + `[status,body]`/`undefined→204` formatting (`formatApiResult:100`), JSON-round-trips the body, and maps thrown `HttpError`→status (`:335`). It deliberately skips auth/CSRF/rate-limit/multipart middleware (`api_tester.ts:26-31`) — those are Express concerns, covered by supertest.
+- **Ordering is shared.** Because `CoreApiTester.request` returns on first match (`:316`), a literal-vs-`:param` collision misbehaves identically in tests and in Express — so a `CoreApiTester` spec will actually catch an ordering bug.
+- **The standalone `apiResultHandler` (`browser_routes.ts:227`) drops the tuple status code** (`const [_statusCode, response] = result; res.result = response;`) — it captures only the body, since the BrowserRouter conveys status separately. Don't rely on the HTTP status surfacing through that adapter the way it does on Express; assert behavior via `CoreApiTester` (which *does* preserve the tuple status in `formatApiResult:100`) and the supertest transport spec.
+
+## 5. Browser-safe checklist for core handlers
+
+| Don't | Do | Why |
+|---|---|---|
+| `process.env.FOO` | `getPlatform().getEnv("FOO")` | no `process` in WASM (`script.ts:75,86` is a latent violation) |
+| `import path from "path"` / `node:path` | `extname`/`basename` from `packages/trilium-core/src/services/utils/path.ts` (`:7`, `:15`) | `path` is externalized in the browser build |
+| any `node:*` built-in | a platform provider or a portable util | core runs in Node **and** the browser |
+
+See `CLAUDE.md` → "Platform Abstraction" and "Critical rules for `trilium-core`" for the full list.
diff --git a/.claude/skills/analyzing-coverage/SKILL.md b/.claude/skills/analyzing-coverage/SKILL.md
index 7b522ab1c6..f939986516 100644
--- a/.claude/skills/analyzing-coverage/SKILL.md
+++ b/.claude/skills/analyzing-coverage/SKILL.md
@@ -54,6 +54,9 @@ trilium-core has **no runner of its own** — its coverage is measured *through*
|---|---|---|
| `apps/client/src/**` | client | `apps/client/test-output/vitest/coverage/lcov.info` |
| `apps/server/src/**`, `packages/trilium-core/src/**` | server | `apps/server/test-output/vitest/coverage/lcov.info` |
+| `apps/standalone/src/**`, or `packages/trilium-core/src/**` under the sqlite-wasm runtime | standalone | `apps/standalone/test-output/vitest/coverage/lcov.info` |
+
+`packages/trilium-core/src/**` is covered by **both** the server and standalone suites (its specs are pulled into each via the core `include` glob), so a core file shows two separate lcov entries. They aren't identical: the standalone suite runs core through happy-dom + sqlite-wasm, so a line uncovered there but covered under server (or vice-versa) is a real runtime-specific gap, not noise. Pick the suite matching the runtime you care about; to chase core to 100% everywhere, check both.
Run the suite (or a scoped subset) with coverage, then analyze the lcov:
@@ -61,6 +64,7 @@ Run the suite (or a scoped subset) with coverage, then analyze the lcov:
# Whole package (slow but complete):
pnpm --filter @triliumnext/client test --coverage
pnpm --filter server test --coverage
+pnpm --filter @triliumnext/standalone coverage # core under sqlite-wasm; lcov anchored to apps/standalone/test-output
# Scoped to specific specs (fast iteration). On Windows/sandbox, pnpm exec can
# EPERM — call the hoisted binary in the REPO-ROOT node_modules directly:
diff --git a/.claude/skills/cutting-a-release/SKILL.md b/.claude/skills/cutting-a-release/SKILL.md
new file mode 100644
index 0000000000..bc6fdc76da
--- /dev/null
+++ b/.claude/skills/cutting-a-release/SKILL.md
@@ -0,0 +1,101 @@
+---
+name: cutting-a-release
+description: Use when cutting, preparing, or debugging a Trilium release — bumping the monorepo version, tagging, or diagnosing a failed "Release" workflow run. Covers the ordered bump recipe (edit root package.json → chore:update-version → commit → v-prefixed tag → push), which of the TWO divergent version scripts to use (update-version for releases vs update-nightly-version for CI nightlies), why the CI version-consistency gate validates only 5 of the 8 files update-version writes, the exact `docs/Release Notes/Release Notes/<tag>.md` path the publish step hard-requires, the substring-based rc/beta "latest" labeling, and the RELEASE_PAT (not GITHUB_TOKEN) dependency. Bundles a pre-flight verifier that catches what the CI gate misses before you push the tag.
+---
+
+# Cutting a Trilium release
+
+Releases are a tag push, not a button. Pushing a `v*` tag to `main` triggers `.github/workflows/release.yml`, which builds every artifact and creates the GitHub release. Get the version bump and the release-notes file right *before* you tag, because three of the failure modes below pass CI and ship anyway.
+
+## Five traps that bite before you read anything else
+
+1. **Edit the ROOT `package.json` only, then propagate.** Root is the single source of truth. `pnpm chore:update-version` (`scripts/update-version.ts:26-37`) reads root and writes 8 *other* package.jsons. Hand-editing the children desyncs the tree.
+2. **There are TWO version scripts — use `update-version`, not `update-nightly-version`.** The nightly one (`scripts/update-nightly-version.ts`) writes a *different* set of files and appends a `-test-YYMMDD-HHMMSS` suffix; it's CI-only. Running it for a release poisons the version. ([§ The two scripts](#the-two-version-scripts--pick-the-right-one))
+3. **The CI version gate is a strict SUBSET — don't trust it.** `scripts/check-version-consistency.ts` validates only 5 files; `update-version` writes 8. The 4 gaps (standalone, edit-docs, pdfjs-viewer, trilium-core) can be wrong and still ship. Run the bundled pre-flight, which checks all 9.
+4. **The release-notes file must exist BEFORE you tag, at a DOUBLED path.** `docs/Release Notes/Release Notes/v<X.Y.Z>.md` — note `Release Notes/Release Notes/` twice, and the `v` prefix in the filename. The publish step `ENOENT`s without it (`release.yml:155`).
+5. **The tag must be `v`-prefixed.** `release.yml` triggers only on `push: tags: v*` (`release.yml:3-5`). A bare `0.103.0` tag runs nothing, silently.
+
+Don't hand-roll a version checker — run the bundled pre-flight, a superset of the CI gate:
+
+```bash
+npx tsx .claude/skills/cutting-a-release/scripts/preflight-release-check.mts v0.103.0
+```
+
+It asserts all 9 package.jsons match, that the release-notes file exists at the doubled path, and warns on the rc/beta labeling footgun (trap below). Run it right before pushing the tag.
+
+## The recipe (order is load-bearing)
+
+| # | Step | Command / file | Gotcha |
+|---|------|----------------|--------|
+| 1 | Write release notes | create `docs/Release Notes/Release Notes/v<X.Y.Z>.md` | filename = tag incl. `v`; publish hard-fails without it (`release.yml:155`) |
+| 2 | Bump ROOT only | edit `package.json` `version` | do NOT hand-edit the other package.jsons |
+| 3 | Propagate | `pnpm chore:update-version` | rewrites 8 package.jsons from root; never the reverse |
+| 4 | Pre-flight | `npx tsx .claude/skills/cutting-a-release/scripts/preflight-release-check.mts v<X.Y.Z>` | catches the 4 files CI never checks + a missing notes file |
+| 5 | Commit | `chore(release): prepare for v<X.Y.Z>` | stage every changed package.json + the new release-notes md |
+| 6 | Tag (`v`-prefixed) | `git tag v<X.Y.Z>` | `release.yml` only fires on `v*` |
+| 7 | Push commit + tag | `git push && git push --tags` | |
+| 8 | Watch CI, then download + smoke-test the GitHub release | — | see [references/ci-pipeline.md](references/ci-pipeline.md) to map a red job |
+
+The upstream doc (`docs/Developer Guide/Developer Guide/Building/Releasing a new version.md`, 9 steps) is the same recipe but **wrong on step 4**: it tells you to run `pnpm i` "to update the package lock" and calls it `package-lock.json`. A version-only bump does **not** change `pnpm-lock.yaml` (see footgun below), and the lockfile is `pnpm-lock.yaml`. Skip that step unless you also changed a real dependency.
+
+## The two version scripts — pick the right one
+
+| | `scripts/update-version.ts` | `scripts/update-nightly-version.ts` |
+|---|---|---|
+| npm script | `chore:update-version` (`package.json:38`) | `chore:ci-update-nightly-version` (`package.json:34`) |
+| Use for | **releases — manual, this skill** | CI nightlies only |
+| Invoked by | you | `nightly.yml:75`, `main-docker.yml:163` |
+| Reads root version? | yes (`update-version.ts:27`) | yes, then mutates it |
+| Writes root? | **no** | **yes** (`update-nightly-version.ts:47`) |
+| Files written | **8**: apps server/client/standalone/desktop/edit-docs + packages commons/pdfjs-viewer/trilium-core (`update-version.ts:30,34`) | **6**: root + apps server/client/standalone/desktop + pdfjs-viewer (`update-nightly-version.ts:50,55`) |
+| Version shape | root version, verbatim | strips `-beta`, appends `-test-YYMMDD-HHMMSS` (`update-nightly-version.ts:19-24`) |
+
+The two sets diverge in both directions: `update-version` touches edit-docs/commons/trilium-core (nightly doesn't); nightly touches root (update-version doesn't). Run the wrong one and the tree desyncs — e.g. running nightly during a release stamps `0.103.0-test-260613-...` into root and leaves commons/trilium-core untouched.
+
+## The CI gate checks 5 of 8 — verify all 9 yourself
+
+`scripts/check-version-consistency.ts:5-11` validates exactly:
+
+```
+package.json, apps/server, apps/client, apps/desktop, packages/commons
+```
+
+(stripping a leading `v` from the tag arg, lines 20-22). But `update-version` writes **8**, so **`apps/standalone`, `apps/edit-docs`, `packages/pdfjs-viewer`, and `packages/trilium-core` are written but never validated.** A stale version in any of those passes the `sanity-check` job (`release.yml:30-31`) and ships.
+
+This isn't theoretical — real release-prep commits touched *different* file subsets because `update-version` only produces a git diff for files that were previously stale: `v0.103.0` (`44f5be88b7`) changed 7 package.jsons including pdfjs-viewer; `v0.102.1` (`8ac9daa5d3`) changed 6, no pdfjs-viewer. The CI gate would not have caught a wrong value in the un-checked four either time. The bundled pre-flight checks all 9 — use it instead of trusting the gate.
+
+## The publish step — exact strings that hard-fail
+
+`release.yml` job `publish_release` (uses `softprops/[email protected]`, lines 151-161):
+
+| Field (`release.yml`) | Value | Hard-fail / footgun |
+|---|---|---|
+| `body_path` (155) | `docs/Release Notes/Release Notes/${{ github.ref_name }}.md` | doubled folder + `v` prefix; `ENOENT` if missing |
+| `make_latest` (159) | `${{ !contains(github.ref, 'rc') }}` | pure substring on the full ref `refs/tags/...` |
+| `prerelease` (160) | `${{ contains(github.ref, 'rc') }}` | only `rc` is special-cased |
+| `token` (161) | `${{ secrets.RELEASE_PAT }}` | **not** `GITHUB_TOKEN` — needs PAT to open the Releases discussion |
+| `discussion_category_name` (158) | `Releases` | with `discussions: write` (`release.yml:8`) |
+| `fail_on_unmatched_files` (156) | `true` | fails if no `upload/*.*` artifacts (an upstream build job failed) |
+
+**The labeling footgun:** because only the literal substring `rc` flips `prerelease`, a `-beta` (or `-alpha`/`-dev`) tag does NOT match — it publishes with `make_latest=true` and `prerelease=false`, i.e. **marked the latest stable release.** If you want a pre-release that isn't the latest, the tag must contain `rc` (e.g. `v0.103.0-rc.1`). The pre-flight warns on this.
+
+## Footgun list (each with a real cite)
+
+- **Lockfile is NOT touched by a version-only bump.** Internal deps are `workspace:*` (resolve to `link:`, no version recorded — `grep 0.103.0 pnpm-lock.yaml` = 0 hits), and the release-prep commits above never touched `pnpm-lock.yaml`. CI installs `--frozen-lockfile` *before* any bump (`nightly.yml:71` then bump at `:75`; `release.yml:28`). `--frozen-lockfile` only fails if the release *also* changes a real dependency. The upstream doc's "run `pnpm i`" step is precautionary and misnames the file.
+- **Tag must be `v`-prefixed** — `release.yml:3-5` triggers only on `v*`. A bare `0.103.0` tag does nothing.
+- **`RELEASE_PAT`, not `GITHUB_TOKEN`** — `release.yml:161`. Confirmed the only PAT in the release flow; winget (downstream) uses a separate `WINGET_PAT` (`release-winget.yml:19`).
+- **Don't hand-edit child package.jsons** — let `update-version` propagate from root, or they desync silently past the 5-file gate.
+- **`update-version` is idempotent but partial in the diff** — it rewrites all 8 unconditionally; only the previously-stale ones show up in `git status`. "Only 6 files changed" is normal and not a sign you missed one.
+
+## Hotfix variant
+
+Same recipe, different branch. Per `docs/Developer Guide/Developer Guide/Branching strategy.md:20-30`: create a `hotfix` branch **from the release tag**, cherry-pick the needed fixes from `main`, bump + release from `hotfix` (the recipe above), then merge `hotfix` back into `main` via PR. The tag still triggers `release.yml` the same way — nothing about the bump/notes/labeling rules changes.
+
+## Reference map
+
+| File | When to open |
+|---|---|
+| [references/ci-pipeline.md](references/ci-pipeline.md) | Debugging a red "Release" run — job-by-job anatomy (sanity-check → make-electron matrix + build_server → publish_release), the exact failing string per job, and the downstream `release-winget.yml`. |
+| [scripts/preflight-release-check.mts](scripts/preflight-release-check.mts) | Run before pushing the tag — superset of the CI gate (all 9 package.jsons + notes file + rc/beta labeling warning). |
+
+Related skills: **writing-unit-tests** / **analyzing-coverage** if a build job's *test* step is what failed (the release builds run the suites); **evolving-the-data-model** if the release includes a DB migration whose version you also need to sanity-check.
diff --git a/.claude/skills/cutting-a-release/references/ci-pipeline.md b/.claude/skills/cutting-a-release/references/ci-pipeline.md
new file mode 100644
index 0000000000..4cce6a665b
--- /dev/null
+++ b/.claude/skills/cutting-a-release/references/ci-pipeline.md
@@ -0,0 +1,67 @@
+# Release CI pipeline anatomy (`release.yml`)
+
+For debugging a red **Release** run. Everything here is `.github/workflows/release.yml` unless noted. Trigger: `push: tags: v*` (lines 3-5) — only `v`-prefixed tags.
+
+## Job graph
+
+```
+sanity-check ──┬──> make-electron (matrix: 6 builds) ──┐
+ └──> build_server (matrix: 2 builds) ──┴──> publish_release
+ │
+ (on release: published)
+ ▼
+ release-winget.yml
+```
+
+`make-electron` and `build_server` both `needs: sanity-check` (lines 34, 103). `publish_release` `needs: [make-electron, build_server]` (lines 133-135), so it runs only after every build artifact exists.
+
+## Job 1 — `sanity-check` (the version gate)
+
+- Installs `--frozen-lockfile --ignore-scripts` (line 28), then runs `pnpm tsx scripts/check-version-consistency.ts ${{ github.ref_name }}` (line 31). `github.ref_name` is the tag (e.g. `v0.103.0`); the script strips the leading `v` (`check-version-consistency.ts:20-22`).
+- **Validates only 5 files** (`check-version-consistency.ts:5-11`): root, `apps/server`, `apps/client`, `apps/desktop`, `packages/commons`. The other 4 that `update-version` writes (standalone, edit-docs, pdfjs-viewer, trilium-core) are **never checked here** — see the main SKILL.md.
+- **Fails when:** any of those 5 versions ≠ the tag. Message: `Version mismatch in <file>: expected <tag>, found <ver>` (`check-version-consistency.ts:29`).
+- Fix: bump root, re-run `pnpm chore:update-version`, re-commit, re-tag.
+
+## Job 2 — `make-electron` (Electron desktop matrix)
+
+- Matrix `arch: [x64, arm64] × os: [macos-latest, ubuntu-22.04, win-signing]`, **excluding** arm64-linux from that cross and **adding** a native `ubuntu-24.04-arm` arm64-linux runner (lines 36-65). The exclude+include is a runner swap, so it's a net 6 builds (mac x64/arm64, win x64/arm64, linux x64 + native linux arm64).
+- Installs `--frozen-lockfile` (line 76), then `./.github/actions/build-electron` (line 78) with Apple notarization / Windows signing / GPG secrets (lines 84-93).
+- Uploads `release-desktop-${os}-${arch}` from `apps/desktop/upload/*.*` (lines 95-99).
+- **Fails when:** the build or test step inside `build-electron` fails, or signing secrets are missing on a signed runner. `fail-fast: false` (line 37) so one arch failing doesn't cancel the rest — but `publish_release` still won't run.
+- If the failure is a *test* step: see the **writing-unit-tests** / **analyzing-coverage** skills.
+
+## Job 3 — `build_server` (Linux server tarballs)
+
+- Matrix `arch: [x64, arm64]` on `ubuntu-22.04` / `ubuntu-24.04-arm` (lines 105-114), `./.github/actions/build-server` (line 119).
+- Uploads `release-server-linux-${arch}` from `upload/*.*` (lines 124-128).
+
+## Job 4 — `publish_release`
+
+- `mkdir upload` (137); sparse-checkout of just `docs/Release Notes` (lines 139-142); downloads **all** `release-*` artifacts merged into `upload/` (`download-artifact`, `pattern: release-*`, `merge-multiple: true`, lines 144-149); then `softprops/[email protected]` (line 152).
+- The release-body / labeling / token fields are the hard-fail surface — table below.
+
+| Field (line) | Value | Fails when |
+|---|---|---|
+| `body_path` (155) | `docs/Release Notes/Release Notes/${{ github.ref_name }}.md` | the file doesn't exist (doubled folder + `v` prefix) → `ENOENT` |
+| `fail_on_unmatched_files` (156) | `true` | `upload/*.*` is empty (an upstream build job produced no artifact) |
+| `files` (157) | `upload/*.*` | — |
+| `discussion_category_name` (158) | `Releases` | the `Releases` discussion category doesn't exist, or token lacks `discussions: write` |
+| `make_latest` (159) | `${{ !contains(github.ref, 'rc') }}` | (no fail) substring on `refs/tags/...`; non-`rc` ⇒ marked latest |
+| `prerelease` (160) | `${{ contains(github.ref, 'rc') }}` | (no fail) only `rc` ⇒ prerelease; `-beta` does NOT |
+| `token` (161) | `${{ secrets.RELEASE_PAT }}` | PAT missing/expired/insufficient scope (needs `repo` + discussion write) |
+
+## Downstream — `release-winget.yml`
+
+Separate workflow, fires on `release: types: [published]` (lines 2-4) — i.e. after `publish_release` succeeds. Also `workflow_dispatch` with a `release_tag` input (lines 5-10). Calls `vedantmgoyal9/winget-releaser` with `identifier: TriliumNext.Notes` and **`token: ${{ secrets.WINGET_PAT }}`** (lines 16-19) — a different PAT from `RELEASE_PAT`. A winget failure does **not** affect the GitHub release; re-dispatch this workflow with the tag to retry.
+
+## Failure → job cheat-sheet
+
+| Symptom | Job | Root cause / fix |
+|---|---|---|
+| `Version mismatch in <file>` | sanity-check | one of the 5 checked files is stale; re-bump from root. Run the pre-flight to also catch the 4 it *doesn't* check. |
+| Release created with wrong/empty notes, or `ENOENT` on body | publish_release | release-notes file missing/misnamed at `docs/Release Notes/Release Notes/<tag>.md` |
+| `make_latest`/prerelease wrong | publish_release | tag's `rc` substring (or absence) — only `rc` flips it; rename the tag |
+| `fail_on_unmatched_files` / no artifacts | publish_release | an upstream `make-electron` / `build_server` matrix leg failed — open that job |
+| 403 / can't create discussion | publish_release | `RELEASE_PAT` (not `GITHUB_TOKEN`) missing or under-scoped |
+| GitHub release fine, winget never updates | release-winget | `WINGET_PAT` problem; re-run `release-winget.yml` via dispatch with the tag |
+| Electron/server build step red | make-electron / build_server | a real build or test break — see **writing-unit-tests** / **analyzing-coverage** |
diff --git a/.claude/skills/cutting-a-release/scripts/preflight-release-check.mts b/.claude/skills/cutting-a-release/scripts/preflight-release-check.mts
new file mode 100644
index 0000000000..978bd607a1
--- /dev/null
+++ b/.claude/skills/cutting-a-release/scripts/preflight-release-check.mts
@@ -0,0 +1,147 @@
+#!/usr/bin/env -S npx tsx
+/**
+ * @module
+ *
+ * Pre-flight verifier for a Trilium release — a strict SUPERSET of the CI gate.
+ *
+ * The CI sanity-check (scripts/check-version-consistency.ts, run from
+ * .github/workflows/release.yml:31) validates only 5 of the 9 package.json files
+ * that must agree: root, apps/server, apps/client, apps/desktop, packages/commons.
+ * But `pnpm chore:update-version` (scripts/update-version.ts) propagates the root
+ * version into 8 files — so apps/standalone, apps/edit-docs, packages/pdfjs-viewer
+ * and packages/trilium-core are WRITTEN but NEVER validated. A stale version in any
+ * of those four passes CI and ships.
+ *
+ * This script checks all 9, confirms the release-notes file the publish step
+ * hard-requires exists at the exact doubled path, and warns about the rc/beta
+ * "latest"/prerelease labeling so it is intentional.
+ *
+ * Usage (from the repo root):
+ * npx tsx .claude/skills/cutting-a-release/scripts/preflight-release-check.mts v0.103.0
+ * # or omit the arg to use the root package.json version as the source of truth:
+ * npx tsx .claude/skills/cutting-a-release/scripts/preflight-release-check.mts
+ *
+ * Exit code 0 = ready to tag/push. Non-zero = a hard failure CI would (or wouldn't!) catch.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT_PKG_NAME = "@triliumnext/source";
+
+// All 9 files that must agree: root + the 8 that scripts/update-version.ts writes.
+const ALL_PACKAGE_JSONS = [
+ "package.json",
+ "apps/server/package.json",
+ "apps/client/package.json",
+ "apps/standalone/package.json",
+ "apps/desktop/package.json",
+ "apps/edit-docs/package.json",
+ "packages/commons/package.json",
+ "packages/pdfjs-viewer/package.json",
+ "packages/trilium-core/package.json"
+];
+
+// The subset the CI gate (scripts/check-version-consistency.ts:5-11) actually validates.
+const CI_GATE_FILES = new Set([
+ "package.json",
+ "apps/server/package.json",
+ "apps/client/package.json",
+ "apps/desktop/package.json",
+ "packages/commons/package.json"
+]);
+
+function readPackageVersion(packageJsonPath: string): string {
+ return JSON.parse(readFileSync(packageJsonPath, "utf-8")).version;
+}
+
+function findRepoRoot(start: string): string {
+ let dir = start;
+ for (;;) {
+ const pkg = join(dir, "package.json");
+ if (existsSync(pkg)) {
+ try {
+ if (JSON.parse(readFileSync(pkg, "utf-8")).name === ROOT_PKG_NAME) {
+ return dir;
+ }
+ } catch {
+ // not valid JSON — keep walking up
+ }
+ }
+ const parent = dirname(dir);
+ if (parent === dir) {
+ return start;
+ }
+ dir = parent;
+ }
+}
+
+function main(): void {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const root = findRepoRoot(process.cwd() === here ? here : process.cwd());
+
+ // Accept "v0.103.0" or "0.103.0"; default to the root version (single source of truth).
+ let arg = process.argv[2];
+ if (!arg) {
+ arg = readPackageVersion(join(root, "package.json"));
+ console.log(`No version argument — using root package.json version: ${arg}`);
+ }
+ const expectedVersion = arg.startsWith("v") ? arg.substring(1) : arg;
+ const tag = `v${expectedVersion}`;
+
+ console.log(`\nPre-flight for tag ${tag} (version ${expectedVersion}) in ${root}\n`);
+
+ const failures: string[] = [];
+
+ // 1. All 9 package.json versions must equal the target. Flag the 4 the CI gate ignores.
+ for (const file of ALL_PACKAGE_JSONS) {
+ const full = join(root, file);
+ if (!existsSync(full)) {
+ failures.push(`${file} is missing`);
+ console.log(`[FAIL] ${file} — file not found`);
+ continue;
+ }
+ const version = readPackageVersion(full);
+ const blindSpot = CI_GATE_FILES.has(file) ? "" : " (CI gate does NOT check this)";
+ if (version === expectedVersion) {
+ console.log(`[ OK ] ${file} = ${version}${blindSpot}`);
+ } else {
+ failures.push(`${file}: expected ${expectedVersion}, found ${version}`);
+ console.log(`[FAIL] ${file} = ${version}, expected ${expectedVersion}${blindSpot}`);
+ }
+ }
+
+ // 2. The publish step hard-requires the release-notes file at the DOUBLED path.
+ const notesRel = join("docs", "Release Notes", "Release Notes", `${tag}.md`);
+ if (existsSync(join(root, notesRel))) {
+ console.log(`[ OK ] ${notesRel} exists`);
+ } else {
+ failures.push(`release-notes file missing: ${notesRel}`);
+ console.log(`[FAIL] ${notesRel} — softprops/action-gh-release will ENOENT (release.yml:155)`);
+ }
+
+ // 3. rc/beta labeling — release.yml:159-160 substring-matches the ref.
+ if (tag.includes("rc")) {
+ console.log(`[INFO] tag contains "rc" -> prerelease=true, make_latest=false (intended for a release candidate)`);
+ } else if (/beta|alpha|dev|test/i.test(tag)) {
+ console.log(`[WARN] tag "${tag}" is pre-release-looking but does NOT contain "rc":`);
+ console.log(` release.yml only special-cases "rc", so this publishes as make_latest=true`);
+ console.log(` and prerelease=false — i.e. marked the LATEST STABLE release. Use an "rc" tag`);
+ console.log(` (e.g. v0.103.0-rc.1) if you do not want that.`);
+ } else {
+ console.log(`[INFO] tag "${tag}" -> make_latest=true, prerelease=false (published as the latest stable release)`);
+ }
+
+ console.log("");
+ if (failures.length > 0) {
+ console.error(`Pre-flight FAILED with ${failures.length} problem(s):`);
+ for (const f of failures) {
+ console.error(` - ${f}`);
+ }
+ process.exit(1);
+ }
+ console.log("Pre-flight passed. Safe to commit, tag, and push.");
+}
+
+main();
diff --git a/.claude/skills/evolving-the-data-model/SKILL.md b/.claude/skills/evolving-the-data-model/SKILL.md
new file mode 100644
index 0000000000..72cbce7eb0
--- /dev/null
+++ b/.claude/skills/evolving-the-data-model/SKILL.md
@@ -0,0 +1,99 @@
+---
+name: evolving-the-data-model
+description: Use when adding a DB migration or a new column/field to a Becca entity in Trilium ("add a migration", "new column on notes/attributes", "ALTER TABLE", "add a field to BNote/BAttribute/BBranch", schema change). Migrations are NOT dated .sql files — they are integer-versioned entries in the DESCENDING MIGRATIONS array in packages/trilium-core/src/migrations/migrations.ts (dbVersion is auto-derived from MIGRATIONS[0]), and the schema lives at packages/trilium-core/src/assets/schema.sql. Covers the full file chain for a column-add, the hashedProperties cross-instance sync-hash hazard, CLS-wrapped JS migrations, and the spec harness.
+---
+
+# Evolving the Trilium data model
+
+## Migrations are not dated `.sql` files — start here
+
+The intuitive guess — dated SQL files under `apps/server` plus a matching `schema.sql` there — is wrong on both counts. **Neither of these paths exists:**
+
+| Easy wrong guess | Reality |
+|---|---|
+| `apps/server/src/migrations/YYMMDD_HHMM__description.sql` | No such directory. Migrations are **not** dated `.sql` files — they're entries in the `MIGRATIONS` array (below). |
+| `apps/server/src/assets/db/schema.sql` | No such file. The schema for fresh installs lives in core. |
+
+Verified absent: `Glob apps/server/src/migrations/**` and `Glob apps/server/src/assets/db/schema.sql` both return nothing.
+
+**Ground truth:**
+
+- **Migrations** — `packages/trilium-core/src/migrations/migrations.ts`. One `MIGRATIONS` array of `{ version, sql, ignoreErrors? }` (SQL) or `{ version, module }` (JS) objects, kept in **DESCENDING** version order (newest first). Top entry today is `version: 240` (`migrations.ts:15`).
+- **Schema for fresh installs** — `packages/trilium-core/src/assets/schema.sql`.
+- **`dbVersion` is auto-derived**, never hand-bumped: `getMaxMigrationVersion()` returns `MIGRATIONS[0].version` (`migrations.ts:6-8`) → `appInfo.dbVersion` (`app_info.ts:11`) → `isDbUpToDate()` compares `dbVersion >= appInfo.dbVersion` (`migration.ts:120-130`, the comparison at `:123`).
+
+## The two un-guarded hazards (most data-model bugs are one of these)
+
+`migrations.spec.ts` already asserts **unique + descending** versions (`migrations.spec.ts:5-18`), so a misordered/duplicate version IS caught at CI *if you run the tests*. The genuinely silent traps are:
+
+1. **schema.sql parity.** Fresh installs run `sql.executeScript(schema)` and **never replay migrations** (`sql_init.ts:154`, also `:288` for sync setup). A column added only via `ALTER TABLE` in a migration is **MISSING on every freshly-created DB** unless you hand-mirror it into `schema.sql`. No test compares fresh-vs-migrated schema.
+2. **becca_loader positional misalignment.** `notes`, `branches`, `attributes` load via `sql.getRawRows(...)` (positional arrays) fed to `new BAttribute().update(row)`, whose destructure order must match the `SELECT` column order **exactly** (`becca_loader.ts:53` ↔ `battribute.ts:57`). Add a column to one and not the other (or in the wrong position) and every loaded entity silently gets shifted field values — no compile error, no test failure.
+
+A third, deliberate-only hazard: changing **`hashedProperties`** breaks cross-instance sync — see below.
+
+## Decision: what are you doing?
+
+| Task | Files to touch | Template / reference |
+|---|---|---|
+| Pure schema/data fix (rename option, drop table, add index, plain `ALTER`) | `migrations.ts` (top entry) + `schema.sql` (mirror) | [assets/sql-migration.snippet.md](assets/sql-migration.snippet.md) |
+| Data transform needing becca/note APIs | new `0NNN__*.ts` + `migrations.ts` (`module:` entry) | [assets/0NNN__migration.template.ts](assets/0NNN__migration.template.ts) |
+| Add a **column/field** to an existing entity | migration + `schema.sql` + `rows.ts` Row + entity (property, `updateFromRow`/`update`/`getPojo`) + `becca_loader` SELECT | [references/column-add-checklist.md](references/column-add-checklist.md) |
+| Change which fields are **sync-hashed** | entity `hashedProperties` only — STOP, read the hazard first | [references/sync-hash-hazard.md](references/sync-hash-hazard.md) |
+
+## Recipe: add a migration (SQL)
+
+1. Append a new object at the **TOP** of `MIGRATIONS` with `version: <current MIGRATIONS[0].version + 1>` (so today, `241`).
+2. For `ALTER TABLE ... ADD COLUMN`, set `ignoreErrors: true` (re-running over an already-patched DB must not halt the whole transaction — see `238`/`236`, the only two entries that set it, and the `ignoreErrors` doc at `migrations.ts:370-371`).
+3. **Mirror** the column/table change into `schema.sql` so fresh installs match.
+4. No `appInfo` bump — `dbVersion` reads `MIGRATIONS[0]` automatically.
+
+```ts
+// migrations.ts — TOP of the MIGRATIONS array
+{
+ version: 241,
+ sql: /*sql*/`
+ ALTER TABLE notes ADD COLUMN color TEXT DEFAULT '' NOT NULL;
+ `,
+ ignoreErrors: true
+},
+```
+
+## Recipe: add a migration (JS/TS)
+
+Use this only when the transform needs becca/note APIs (content, attachments, relations). Pure SQL? Stay in SQL.
+
+1. Create `packages/trilium-core/src/migrations/0NNN__<desc>.ts` with a **default-exported function**.
+2. Wrap all becca/note work in `getContext().init(() => { becca_loader.load(); ... })` — without CLS context `note.save()`/`setContent()` throw. Models: `0233__migrate_geo_map_to_collection.ts:6-8`, `0234__migrate_ai_chat_to_code.ts:5-7`.
+3. Reference it from `MIGRATIONS` with `{ version: N, module: async () => import("./0NNN__<desc>.js") }` — note the `.js` extension (ESM output), exactly like `migrations.ts:73-74`.
+4. Add a `.spec.ts` (see the harness below).
+
+The runner preloads JS modules (`prepareMigrations`, `migration.ts:80-101`) then runs everything inside **one** `sql.transactional` (`migration.ts:46`); a failure without `ignoreErrors` crashes the app so the user can stay on the old version.
+
+## Spec harness — don't reinvent it
+
+Two proven styles, both already in-tree:
+
+- **Per-migration unit test** — fixture `test/fixtures/document.db`, insert rows, run the migration fn, assert post-state. Model: `migrations/0233__migrate_geo_map_to_collection.spec.ts`.
+- **End-to-end** — `migration.migrateIfNecessary()` against `test/fixtures/document_v214.db`, assert a post-migration count. Model: `services/migration.spec.ts` (asserts `SELECT count(*) FROM blobs` is `118`).
+
+Three harness traps, each load-bearing (copy [assets/migration-spec.template.ts](assets/migration-spec.template.ts)):
+
+- Resolve `getSql()` **inside** `beforeEach`, not at describe-collection time — `describe` callbacks run before the suite's `initializeCore` `beforeAll`, so capturing it eagerly throws `"SQL not initialized"` (`0233__*.spec.ts:33-39` has the explanatory comment).
+- `sql.rebuildFromBuffer(readFileSync(fixture))` **per test** to avoid cross-test leakage (`0233__*.spec.ts:43-44`).
+- Call `becca_loader.load()` **after** raw `INSERT`s *and again after* running the migration, all inside `cls.getContext().init(...)`, so becca reflects the new DB state (`0233__*.spec.ts:112` and `:130`).
+
+Run a single migration spec:
+```
+pnpm --filter server test packages/trilium-core/src/migrations/0233__migrate_geo_map_to_collection.spec.ts
+```
+For writing the assertions themselves, see the **writing-unit-tests** skill (real-DB vs mocked-becca, the `cls.init` pattern, single-file runner footguns) and **analyzing-coverage** for chasing the migration's uncovered branches.
+
+## Reference map
+
+| File | When to open |
+|---|---|
+| [references/column-add-checklist.md](references/column-add-checklist.md) | Adding a column/field to notes/attributes/branches — the exact 5-file chain + the `SELECT` ↔ `update([...])` positional diagram, with a full worked `attributes` example. |
+| [references/sync-hash-hazard.md](references/sync-hash-hazard.md) | Touching `hashedProperties`, or deciding whether a new column should sync-hash. `generateHash()` → entity_changes → cross-instance content-hash break, with every entity's current `hashedProperties` list. |
+| [assets/sql-migration.snippet.md](assets/sql-migration.snippet.md) | Copy-paste SQL `MIGRATIONS` entries (ALTER ADD COLUMN + generic DDL/data) and the paired `schema.sql` reminder. |
+| [assets/0NNN__migration.template.ts](assets/0NNN__migration.template.ts) | JS/TS migration skeleton with the `getContext().init` wrapper + the `MIGRATIONS` entry snippet. |
+| [assets/migration-spec.template.ts](assets/migration-spec.template.ts) | Vitest harness with all three traps pre-handled. |
diff --git a/.claude/skills/evolving-the-data-model/assets/0NNN__migration.template.ts b/.claude/skills/evolving-the-data-model/assets/0NNN__migration.template.ts
new file mode 100644
index 0000000000..571ca137bb
--- /dev/null
+++ b/.claude/skills/evolving-the-data-model/assets/0NNN__migration.template.ts
@@ -0,0 +1,61 @@
+/**
+ * TEMPLATE — JS/TS data migration.
+ *
+ * Copy to: packages/trilium-core/src/migrations/0NNN__<description>.ts
+ * (replace 0NNN with the zero-padded version number, e.g. 0239).
+ *
+ * Use a JS migration ONLY when the transform needs becca / note APIs
+ * (content, attachments, relations, templates). For pure schema or data
+ * SQL, use an `{ version, sql }` entry instead — see sql-migration.snippet.md.
+ *
+ * Models in-tree: 0233__migrate_geo_map_to_collection.ts,
+ * 0234__migrate_ai_chat_to_code.ts
+ *
+ * ---------------------------------------------------------------------------
+ * Wire it into packages/trilium-core/src/migrations/migrations.ts by adding
+ * this object at the TOP of the MIGRATIONS array (newest first). Note the
+ * `.js` extension on the import — the build emits ESM:
+ *
+ * // <one-line description of what this migration does>
+ * {
+ * version: 241,
+ * module: async () => import("./0239__<description>.js")
+ * },
+ *
+ * Do NOT bump appInfo.dbVersion — it is derived from MIGRATIONS[0].version.
+ * ---------------------------------------------------------------------------
+ */
+
+import becca from "../becca/becca";
+import becca_loader from "../becca/becca_loader";
+import { getContext } from "../services/context";
+
+export default () => {
+ // CLS context is mandatory: without it note.save() / note.setContent()
+ // throw. becca_loader.load() (re)populates the in-memory cache from the
+ // DB the runner just migrated up to this point.
+ getContext().init(() => {
+ becca_loader.load();
+
+ for (const note of Object.values(becca.notes)) {
+ // Narrow to just the rows this migration cares about.
+ if (note.type as string !== "someOldType") {
+ continue;
+ }
+
+ console.log(`Migrating note '${note.noteId}' ...`);
+
+ // Mutate via becca/note APIs so EntityChange records are created
+ // for sync. Do NOT issue raw UPDATEs against the cached tables here.
+ note.type = "code";
+ note.mime = "application/json";
+ note.save();
+
+ // Content / attachment / relation transforms also go here, e.g.:
+ // const content = note.getContent();
+ // note.saveAttachment({ role: "...", title: "...", mime: "...", content });
+ // note.setContent("");
+ // note.setRelation("template", "_template_xyz");
+ }
+ });
+};
diff --git a/.claude/skills/evolving-the-data-model/assets/migration-spec.template.ts b/.claude/skills/evolving-the-data-model/assets/migration-spec.template.ts
new file mode 100644
index 0000000000..e4dbcd4c70
--- /dev/null
+++ b/.claude/skills/evolving-the-data-model/assets/migration-spec.template.ts
@@ -0,0 +1,87 @@
+/**
+ * TEMPLATE — per-migration unit test.
+ *
+ * Copy to: packages/trilium-core/src/migrations/0NNN__<description>.spec.ts
+ * Model in-tree: 0233__migrate_geo_map_to_collection.spec.ts
+ * End-to-end variant (whole migrate chain): services/migration.spec.ts
+ *
+ * Run a single spec:
+ * pnpm --filter server test packages/trilium-core/src/migrations/0NNN__<description>.spec.ts
+ *
+ * Three harness traps are pre-handled below:
+ * 1. getSql() is resolved INSIDE beforeEach — not at describe-collection
+ * time. describe callbacks run before the suite's initializeCore beforeAll,
+ * so capturing sql eagerly throws "SQL not initialized".
+ * 2. sql.rebuildFromBuffer(fixture) runs PER TEST so mutations don't leak.
+ * 3. becca_loader.load() is called after raw INSERTs AND again after the
+ * migration, all inside cls.getContext().init(...), so becca mirrors the DB.
+ */
+
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { beforeEach, describe, expect, it } from "vitest";
+import * as cls from "../services/context.js";
+import { getSql } from "../services/sql/index.js";
+import becca from "../becca/becca.js";
+import becca_loader from "../becca/becca_loader.js";
+import migration from "./0NNN__<description>.js";
+
+// Spec files only ever run under vitest (ESM via Vite), so import.meta.url is
+// available. The CLAUDE.md ban on import.meta.url targets production code that
+// gets bundled to CJS, not test files.
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+describe("Migration 0NNN: <description>", () => {
+ let sql: ReturnType<typeof getSql>;
+
+ beforeEach(async () => {
+ sql = getSql();
+
+ // Fresh DB per test from the shared fixture.
+ const dbBytes = readFileSync(join(__dirname, "../test/fixtures/document.db"));
+ sql.rebuildFromBuffer(dbBytes);
+
+ await new Promise<void>((resolve) => {
+ cls.getContext().init(() => {
+ becca_loader.load();
+ resolve();
+ });
+ });
+ });
+
+ it("transforms the targeted rows and leaves others untouched", async () => {
+ await new Promise<void>((resolve) => {
+ cls.getContext().init(() => {
+ // Arrange: insert the pre-migration state directly via SQL.
+ const noteId = "test_note_1";
+ const blobId = "test_blob_1";
+ sql.execute(/*sql*/`
+ INSERT INTO notes (noteId, title, type, mime, blobId, dateCreated, dateModified, utcDateCreated, utcDateModified)
+ VALUES (?, ?, ?, ?, ?, datetime('now'), datetime('now'), datetime('now'), datetime('now'))
+ `, [noteId, "Test Note", "someOldType", "application/json", blobId]);
+ sql.execute(/*sql*/`
+ INSERT INTO blobs (blobId, content, dateModified, utcDateModified)
+ VALUES (?, ?, datetime('now'), datetime('now'))
+ `, [blobId, "{}"]);
+
+ // Reload becca so it sees the inserted rows.
+ becca_loader.load();
+ expect(becca.getNote(noteId)?.type).toBe("someOldType");
+
+ // Act.
+ migration();
+
+ // Reload becca so it reflects the migrated DB.
+ becca_loader.load();
+
+ // Assert.
+ const migrated = becca.getNote(noteId);
+ expect(migrated?.type).toBe("code");
+ expect(migrated?.mime).toBe("application/json");
+
+ resolve();
+ });
+ });
+ });
+});
diff --git a/.claude/skills/evolving-the-data-model/assets/sql-migration.snippet.md b/.claude/skills/evolving-the-data-model/assets/sql-migration.snippet.md
new file mode 100644
index 0000000000..19f438c0ed
--- /dev/null
+++ b/.claude/skills/evolving-the-data-model/assets/sql-migration.snippet.md
@@ -0,0 +1,59 @@
+# SQL migration snippets
+
+Paste a new object at the **TOP** of the `MIGRATIONS` array in
+`packages/trilium-core/src/migrations/migrations.ts` (the array is kept in
+**descending** order, newest first). The new `version` is
+`MIGRATIONS[0].version + 1`. Do **not** bump `appInfo.dbVersion` — it is derived
+from `MIGRATIONS[0].version` via `getMaxMigrationVersion()`.
+
+## A. `ALTER TABLE ... ADD COLUMN` (needs `ignoreErrors`)
+
+`ignoreErrors: true` lets a re-run over an already-patched DB log-and-continue
+instead of crashing the single migration transaction.
+
+```ts
+// Add <column> to <table> for <reason>
+{
+ version: 241,
+ sql: /*sql*/`
+ ALTER TABLE notes ADD COLUMN color TEXT DEFAULT '' NOT NULL;
+ `,
+ ignoreErrors: true
+},
+```
+
+Then **mirror it into `packages/trilium-core/src/assets/schema.sql`** — add the
+column to the matching `CREATE TABLE`. Fresh installs run the schema directly and
+never replay migrations (`sql_init.ts:154`), so a column that exists only in a
+migration is missing on every new database.
+
+## B. Generic data / DDL change (no column add)
+
+Idempotent statements (`IF NOT EXISTS`, `DELETE`, `UPDATE`) usually do **not**
+need `ignoreErrors`; add it only if re-execution could throw. Real examples in
+`migrations.ts`: index creation (`235`), option cleanup (`237`), table drops
+(`232`).
+
+```ts
+// Rename the 'openTabs' option to 'openNoteContexts'
+{
+ version: 242,
+ sql: /*sql*/`
+ UPDATE options SET name = 'openNoteContexts' WHERE name = 'openTabs';
+ UPDATE entity_changes SET entityId = 'openNoteContexts'
+ WHERE entityName = 'options' AND entityId = 'openTabs';
+ `
+},
+```
+
+When a DDL change alters a table's shape (new index that fresh installs should
+have, dropped/renamed column, new table), reflect it in `schema.sql` too.
+
+## Checklist
+
+- [ ] New entry at the **top** of `MIGRATIONS`, `version` = previous top + 1
+- [ ] `ignoreErrors: true` on `ALTER TABLE ... ADD COLUMN`
+- [ ] `schema.sql` mirrors any structural change (column / table / index fresh installs need)
+- [ ] `migrations.spec.ts` (unique + descending guard) still green
+- [ ] If a column was added to notes/branches/attributes, follow the full
+ [column-add checklist](../references/column-add-checklist.md)
diff --git a/.claude/skills/evolving-the-data-model/references/column-add-checklist.md b/.claude/skills/evolving-the-data-model/references/column-add-checklist.md
new file mode 100644
index 0000000000..14fd3ecdb8
--- /dev/null
+++ b/.claude/skills/evolving-the-data-model/references/column-add-checklist.md
@@ -0,0 +1,143 @@
+# Adding a column to a Becca entity — the 5-file chain
+
+Adding a column to `notes` / `attributes` / `branches` is **not** a one-file change. Miss any link and you get a silent failure (no compile error, no test failure) on either fresh installs or becca load. The worked example below adds a hypothetical `color TEXT` column to `attributes`.
+
+> Verify every line number against the live file before editing — they drift. The citations here were checked against the tree at the time of writing.
+
+## The chain (in order)
+
+### 1. `migrations.ts` — the `ALTER TABLE`
+
+Top of the `MIGRATIONS` array (`migrations.ts:11`), new version = `MIGRATIONS[0].version + 1`:
+
+```ts
+{
+ version: 241,
+ sql: /*sql*/`
+ ALTER TABLE attributes ADD COLUMN color TEXT DEFAULT '' NOT NULL;
+ `,
+ ignoreErrors: true
+},
+```
+
+`ignoreErrors: true` so re-running over an already-patched DB doesn't halt the single migration transaction (`migration.ts:46`; the flag is documented at `migrations.ts:370-371` and used on the recent column-adds at `238`/`236`).
+
+### 2. `assets/schema.sql` — mirror it into the `CREATE TABLE`
+
+Fresh installs run `sql.executeScript(schema)` and **never replay migrations** (`sql_init.ts:154`). The `attributes` table lives at `schema.sql:67-78`:
+
+```sql
+CREATE TABLE IF NOT EXISTS "attributes"
+(
+ attributeId TEXT not null primary key,
+ noteId TEXT not null,
+ type TEXT not null,
+ name TEXT not null,
+ value TEXT default '' not null,
+ position INT default 0 not null,
+ utcDateModified TEXT not null,
+ isDeleted INT not null,
+ `deleteId` TEXT DEFAULT NULL,
+ isInheritable int DEFAULT 0 NULL,
+ color TEXT default '' not null); -- ← add here
+```
+
+There is **no parity test** comparing a fresh schema against a migrated one, so a miss here is invisible until a brand-new DB hits code that reads `color`.
+
+### 3. `packages/commons/src/lib/rows.ts` — the Row interface
+
+`AttributeRow` (`rows.ts:87-96`) is the shared client/server shape:
+
+```ts
+export interface AttributeRow {
+ attributeId?: string;
+ noteId?: string;
+ type: AttributeType;
+ name: string;
+ position?: number | null;
+ value?: string;
+ isInheritable?: boolean;
+ color?: string; // ← add
+ utcDateModified?: string;
+}
+```
+
+### 4. `entities/battribute.ts` — property + the three accessors
+
+`BAttribute` (`battribute.ts`) needs four edits. **Add the property:**
+
+```ts
+color!: string;
+```
+
+**`updateFromRow`** (`battribute.ts:53-55`) builds the positional array passed to `update()` — append the new field:
+
+```ts
+updateFromRow(row: AttributeRow) {
+ this.update([row.attributeId, row.noteId, row.type, row.name, row.value, row.isInheritable, row.position, row.utcDateModified, row.color]);
+}
+```
+
+**`update([...])`** (`battribute.ts:57-72`) destructures positionally — append in the **same** position:
+
+```ts
+update([attributeId, noteId, type, name, value, isInheritable, position, utcDateModified, color]: any) {
+ // ...existing assignments...
+ this.color = color || "";
+ return this;
+}
+```
+
+**`getPojo()`** (`battribute.ts:222-234`) is what gets written back to SQL on `save()` — add the field or it never persists:
+
+```ts
+getPojo() {
+ return {
+ attributeId: this.attributeId,
+ // ...
+ color: this.color,
+ utcDateModified: this.utcDateModified,
+ isDeleted: false
+ };
+}
+```
+
+**Decide, deliberately, about `hashedProperties`** (`battribute.ts:25-27`). A new column is sync-safe **only if you leave it OUT** of `hashedProperties`. Adding it is a cross-instance hash-format break — read [sync-hash-hazard.md](../references/sync-hash-hazard.md) before touching it.
+
+### 5. `becca/becca_loader.ts` — the raw `SELECT` (the positional trap)
+
+`attributes` are bulk-loaded with a **raw positional query** (`becca_loader.ts:53`):
+
+```ts
+for (const row of sql.getRawRows<AttributeRow>(/*sql*/`SELECT attributeId, noteId, type, name, value, isInheritable, position, utcDateModified, color FROM attributes WHERE isDeleted = 0`)) {
+ new BAttribute().update(row).init();
+}
+```
+
+`getRawRows` returns **arrays, not objects**, so the `SELECT` column order *is* the `update([...])` parameter order.
+
+## The positional coupling — diagram
+
+```
+becca_loader.ts SELECT (raw array, by position)
+ SELECT attributeId, noteId, type, name, value, isInheritable, position, utcDateModified, color
+ [0] [1] [2] [3] [4] [5] [6] [7] [8]
+ ↓ same order ↓
+battribute.ts update([...]) destructure
+ update([attributeId, noteId, type, name, value, isInheritable, position, utcDateModified, color])
+ [0] [1] [2] [3] [4] [5] [6] [7] [8]
+```
+
+If you append `color` to the `SELECT` but forget the `update()` destructure (or insert it mid-list in one place only), **every** attribute loads with shifted values — `color` lands in `utcDateModified`, etc. No exception is thrown.
+
+> Which entities have this trap? Only the ones loaded via `getRawRows` + `.update(row)`: **notes** (`becca_loader.ts:41`), **branches** (`:45`), **attributes** (`:53`). `options` and `etapi_tokens` use `sql.getRows` (named objects) + constructor (`:57`, `:61`), so they are **not** positional. Entities loaded lazily (revisions, attachments, blobs) have no `becca_loader` SELECT at all — their `updateFromRow` is field-by-field (e.g. `brevision.ts:59`), so step 5 doesn't apply, but steps 1–4 still do.
+
+## Sanity checklist
+
+- [ ] `migrations.ts` top entry, version = old top + 1, `ignoreErrors: true` for the ALTER
+- [ ] `schema.sql` `CREATE TABLE` mirrors the column (fresh-install parity)
+- [ ] `rows.ts` Row interface has the field
+- [ ] entity: property declared; `updateFromRow`, `update([...])`, `getPojo()` all updated; `hashedProperties` decision made
+- [ ] `becca_loader.ts` SELECT lists the column in the **same position** as `update([...])` (notes/branches/attributes only)
+- [ ] spec written (see [assets/migration-spec.template.ts](../assets/migration-spec.template.ts))
+- [ ] `pnpm --filter server test packages/trilium-core/src/migrations/...` green; `migrations.spec.ts` (unique+descending guard) still green
diff --git a/.claude/skills/evolving-the-data-model/references/sync-hash-hazard.md b/.claude/skills/evolving-the-data-model/references/sync-hash-hazard.md
new file mode 100644
index 0000000000..b0c03c5fa2
--- /dev/null
+++ b/.claude/skills/evolving-the-data-model/references/sync-hash-hazard.md
@@ -0,0 +1,71 @@
+# The `hashedProperties` sync-hash hazard
+
+**Adding a property to an entity's `hashedProperties` is a BREAKING cross-instance sync change — not a "make this field sync" switch.** A new column already syncs (it rides in the entity row); `hashedProperties` only controls the *content hash* used to detect divergence. Touch it only when you intend a hash-format break and coordinate it across every instance in a sync cluster at the same time.
+
+## How the hash is built and used
+
+`generateHash()` (`abstract_becca_entity.ts:63-76`) concatenates `|<value>` for each property in the entity's `hashedProperties`, then truncates to 10 chars:
+
+```ts
+generateHash(isDeleted?: boolean): string {
+ const constructorData = this.constructor as unknown as ConstructorData<T>;
+ let contentToHash = "";
+
+ for (const propertyName of constructorData.hashedProperties) {
+ contentToHash += `|${(this as any)[propertyName]}`;
+ }
+
+ if (isDeleted) {
+ contentToHash += "|deleted";
+ }
+
+ return hash(contentToHash).substr(0, 10);
+}
+```
+
+That hash is stamped onto every `entity_changes` row in `putEntityChange()` (`abstract_becca_entity.ts:51-61`):
+
+```ts
+entityChangesService.putEntityChange({
+ entityName: constructorData.entityName,
+ entityId: (this as any)[constructorData.primaryKeyName],
+ hash: this.generateHash(isDeleted),
+ // ...
+});
+```
+
+`ConstructorData.hashedProperties` is typed `(keyof T)[]` (`becca-interface.ts:353-357`), so the compiler only checks that names are real properties — it cannot warn you that you changed the *meaning* of the hash. Sync uses these `entity_changes` hashes to decide which side is authoritative during the push→pull→push content-hash verification loop.
+
+## Why adding to `hashedProperties` breaks a cluster
+
+Concatenation order and membership are part of the hash contract. In a multi-instance / multi-version cluster:
+
+- An instance on **old** code computes `hash("|attributeId|noteId|type|name|value|isInheritable")`.
+- An instance on **new** code (you added `color`) computes `hash("|attributeId|noteId|type|name|value|isInheritable|color")`.
+
+For the **same** unchanged entity the two hashes differ. Sync now sees perpetual "divergence" it can never reconcile — undebuggable hash mismatches, ping-pong updates, content-hash retry loops. Even reordering the existing list (not adding) breaks it, because the concatenation order changes.
+
+## Decision: should the new column be in `hashedProperties`?
+
+| Situation | In `hashedProperties`? |
+|---|---|
+| New column is local-only derived/cache data, or you just want it to round-trip through sync | **NO** — leave it out. It still syncs in the row; this is the sync-SAFE default. |
+| The column is genuinely part of the entity's synced identity AND you accept a coordinated hash-format break across all instances on the same release | YES — and only then. Treat it like a sync-protocol bump. |
+
+When unsure: **leave it out.** A column omitted from `hashedProperties` still persists and still syncs; the only thing you lose is the field participating in divergence detection — which is exactly what you want for additive, backward-compatible columns.
+
+## Current `hashedProperties` lists (reference)
+
+| Entity | File:line | `hashedProperties` |
+|---|---|---|
+| BNote | `bnote.ts:61-62` | `["noteId", "title", "isProtected", "type", "mime", "blobId"]` |
+| BAttribute | `battribute.ts:25-27` | `["attributeId", "noteId", "type", "name", "value", "isInheritable"]` |
+| BBranch | `bbranch.ts:29-30` | `["branchId", "noteId", "parentNoteId", "prefix"]` |
+| BRevision | `brevision.ts:33-34` | `["revisionId", "noteId", "title", "description", "source", "isProtected", "dateLastEdited", "dateCreated", "utcDateLastEdited", "utcDateCreated", "utcDateModified", "blobId"]` |
+| BAttachment | `battachment.ts:44-45` | `["attachmentId", "ownerId", "role", "mime", "title", "blobId", "utcDateScheduledForErasureSince"]` |
+| BBlob | `bblob.ts:11-12` | `["blobId", "content"]` |
+| BOption | `boption.ts:17-18` | `["name", "value"]` |
+| BEtapiToken | `betapi_token.ts:24-25` | `["etapiTokenId", "name", "tokenHash", "utcDateCreated", "utcDateModified", "isDeleted"]` |
+| BRecentNote | `brecent_note.ts:18-19` | `["noteId", "notePath"]` |
+
+Note that even `BAttribute`'s list omits `position` and `utcDateModified` — position reordering and modified-time alone are intentionally *not* treated as content divergence. Mirror that judgment for any new column.
diff --git a/.claude/skills/translating-locales/SKILL.md b/.claude/skills/translating-locales/SKILL.md
index ce7dd652a4..fa0e419403 100644
--- a/.claude/skills/translating-locales/SKILL.md
+++ b/.claude/skills/translating-locales/SKILL.md
@@ -7,6 +7,8 @@ description: Use when filling in or improving a lagging UI translation locale in
Trilium's UI is localized with **i18next**. English is the source of truth; other locales are normally crowd-translated via **Hosted Weblate**. This skill is for the *maintainer* case: deliberately filling a locale that lags behind (the recurring one is Romanian, `ro`).
+**Scope — this skill *fills* an already-registered locale.** To **add a brand-new locale** (e.g. Polish) you must first do the one-time registration and build wiring; that's a separate task. Follow `docs/Developer Guide/Developer Guide/Concepts/Internationalisation Translations/Adding a new locale.md` to register it, then come back here to translate the strings.
+
Every mechanical step is [locale.mjs](locale.mjs) — measure, export, validate, merge, audit. Read [romanian.md](romanian.md) for Romanian grammar and terminology.
```bash
diff --git a/.claude/skills/writing-unit-tests/SKILL.md b/.claude/skills/writing-unit-tests/SKILL.md
index 1216645516..39ef3c99a3 100644
--- a/.claude/skills/writing-unit-tests/SKILL.md
+++ b/.claude/skills/writing-unit-tests/SKILL.md
@@ -26,6 +26,16 @@ Also follow `CLAUDE.md`: write **concise** tests (group related assertions in on
| An ETAPI endpoint | `supertest` + basic-auth via `spec/etapi/utils.ts` | [server-and-core.md](server-and-core.md) |
| Pure logic (parsers, formatters, math, data maps) | Plain Vitest, no harness | any reference |
+### Specialized harnesses (owned by sibling skills)
+
+Some layers have a purpose-built spec harness documented in the skill that owns the feature — route there instead of re-deriving it:
+
+| You're testing… | Harness shape | Skill |
+|---|---|---|
+| A DB migration (`packages/trilium-core/src/migrations/*`) | `getSql()` captured **in `beforeEach`** (not at describe time — core isn't initialized yet) + `sql.rebuildFromBuffer(fixtureDb)` per test, mutated inside `cls.getContext().init` | **evolving-the-data-model** |
+| An Electron preload bridge method (`apps/desktop/src/preload.ts`) | `vi.mock("electron", …)` mirroring the IPC channels into in-memory maps; assert the exposed `window.electronApi` shape (`apps/desktop/src/preload.spec.ts`) | **developing-electron-desktop** |
+| A CKEditor 5 plugin in Trilium's own bundle (`packages/ckeditor5`) | Browser-mode headless Chrome: `ClassicEditor.create` + `licenseKey: "GPL"` + `_setModelData`, co-located `src/**/*.spec.ts` | **ckeditor5-testing** |
+
## Running tests
> **Run the narrowest thing that covers the change, and never the full suite.** `pnpm test:all`,
@@ -70,4 +80,11 @@ coverage: {
- **`vi.mock` is hoisted** above imports. Put component/module imports *after* the `vi.mock(...)` calls; mock factories can't reference outer non-hoisted variables. Partial-mock with `async (importOriginal) => ({ ...(await importOriginal()), onlyThis: vi.fn() })`.
- **Don't assert on translated (i18n) strings** — assert structure/keys/behavior (classes, counts, ids), not human-readable English.
- **happy-dom is not a browser:** `getBoundingClientRect()` returns zeros, `ResizeObserver`/layout/visibility are stubs. Anything pixel/size/scroll-based needs `@vitest/browser`, not happy-dom.
-- Reserve `@vitest/browser` (already a dependency, currently unconfigured) for real-layout/integration needs (CKEditor, Excalidraw, Modal transitions, size measurement) — not for normal unit tests.
+- **`@vitest/browser` real-browser mode IS configured** — the `packages/ckeditor5`, `-mermaid` and `-math` bundles run their co-located `src/**/*.spec.ts` in headless Chrome (`@vitest/browser-webdriverio`; see `packages/ckeditor5/vitest.config.ts`). These are the browser-mode `test:sequential` suites. Reserve real-browser mode for genuine layout/integration needs (CKEditor, Excalidraw, Modal transitions, size measurement); normal unit tests stay on happy-dom.
+- **WASM scrypt is ~10× slower** under the standalone suite (pure-JS `scrypt-js` under V8 coverage instrumentation, vs Node's native `scryptSync`) — enough to blow the 5s default. A core spec that hashes a password bumps the timeout for the standalone runtime only; copy the guard from `packages/trilium-core/src/routes/api/login.spec.ts:13`:
+ ```ts
+ const isBrowserRuntime = typeof window !== "undefined";
+ if (isBrowserRuntime) {
+ vi.setConfig({ testTimeout: 60000, hookTimeout: 60000 });
+ }
+ ```