Skip to content

Build your personal knowledge base with Trilium Notes

chore(ai): add skill for writing unit tests

Elian Doran0dc5d73f9fd7
diff --git a/.claude/skills/writing-unit-tests/SKILL.md b/.claude/skills/writing-unit-tests/SKILL.md
new file mode 100644
index 0000000000..22695b8b10
--- /dev/null
+++ b/.claude/skills/writing-unit-tests/SKILL.md
@@ -0,0 +1,61 @@
+---
+name: writing-unit-tests
+description: Use when writing, extending, or debugging Vitest unit tests anywhere in the Trilium monorepo — Preact components, jQuery widgets, client services, or the server/trilium-core backend. Covers how to render components (zero new deps), the easy-froca/becca fixtures, supertest API patterns, the honest coverage config, running a single test, and the known gotchas.
+---
+
+# Writing unit tests in Trilium
+
+Trilium is a pnpm monorepo tested with **Vitest** (v8 coverage). This skill captures the patterns that actually work here, plus the footguns that waste time. Read the per-layer reference file for the area you're touching.
+
+## First principle: prefer extracting pure logic
+
+The dominant, lowest-risk pattern across this repo is **extract the decision/transform logic out of a component/widget/route into a top-level `export function` that takes plain inputs and returns a plain value, then test that function.** Rendering and side effects stay thin; the logic gets covered cheaply. `apps/client/src/widgets/ribbon/FormattingToolbar.tsx` (`getFormattingToolbarState`, tested in `FormattingToolbar.spec.ts`) is the canonical example. Reach for rendering/integration only when the behavior *is* the DOM/HTTP.
+
+Also follow `CLAUDE.md`: write **concise** tests (group related assertions in one `it`, don't make one test per trivial passthrough), and when you add pure business logic, extract + unit-test it.
+
+## Which technique? (decision tree)
+
+| You're testing… | Technique | Reference |
+|---|---|---|
+| A reusable Preact component (`apps/client/src/widgets/react/`) | Render with raw `preact` `render()` into a happy-dom div | [client-components.md](client-components.md) |
+| A jQuery widget / type widget | Extract logic → test fn; or instantiate + assert on `$widget` | [client-logic-and-services.md](client-logic-and-services.md) |
+| A client service (`apps/client/src/services/`) | `easy-froca` + override `server.*`; or pure logic | [client-logic-and-services.md](client-logic-and-services.md) |
+| A server service (`apps/server/src` or `packages/trilium-core/src`) | Real in-memory DB (`sql_init` + `cls.init`) or mocked becca | [server-and-core.md](server-and-core.md) |
+| An internal REST API route | `supertest` agent + `/login` + `/bootstrap` CSRF | [server-and-core.md](server-and-core.md) |
+| 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 |
+
+## Running tests
+
+- Whole package: `pnpm --filter <pkg> test` (e.g. `@triliumnext/client`, `@triliumnext/server`, `@triliumnext/commons`).
+- Single file (server): `pnpm --filter server test spec/etapi/search.spec.ts`
+- Single file (client): `pnpm --filter @triliumnext/client exec vitest run src/widgets/react/Button.spec.tsx`
+- Coverage: append `--coverage`.
+- Server tests run **sequentially** (shared DB, `pool: "forks"`, fork isolation is **per file**). Client/package tests run in parallel.
+
+> **Windows/sandbox note:** `pnpm --filter … exec vitest` can trigger a pnpm auto-install that hits `EPERM`. If so, run the hoisted binary directly (it lives in the **repo-root** `node_modules`): `CI=true node node_modules/vitest/vitest.mjs run <spec> --root apps/client`, or `node_modules/.bin/vitest.CMD run <spec> --root apps/<app>`.
+
+## Coverage config rules (Vitest 4)
+
+Each project's test config (`vite.config.*` / `vitest.config.*`) measures coverage honestly via:
+
+```ts
+coverage: {
+ provider: "v8" as const,
+ include: ["src/**/*.{ts,tsx}"], // makes UNTESTED files count too
+ exclude: ["**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}", "**/*.d.ts"],
+ reporter: ["text", "lcov"]
+}
+```
+
+- **Do NOT use `all: true`** — it was removed in Vitest 4 and is a type error; `include` already pulls in untested files.
+- If a config sets Vite `root: "src"` (e.g. `apps/standalone`), coverage `include` globs resolve **relative to `src`**, so use `["**/*.{ts,tsx}"]`, not `["src/**/…"]`.
+- v8 does **not** traverse `../../` paths outside the project root; `trilium-core` coverage is measured *through* `apps/server` (and `apps/standalone`), which already list it in their `include`.
+- For provably-unreachable defensive branches, mark them with `/* v8 ignore next */` / `/* v8 ignore start */…/* v8 ignore stop */` and a one-line reason — don't delete the guard or write a fake test.
+
+## Universal gotchas
+
+- **`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.
diff --git a/.claude/skills/writing-unit-tests/client-components.md b/.claude/skills/writing-unit-tests/client-components.md
new file mode 100644
index 0000000000..51f847861a
--- /dev/null
+++ b/.claude/skills/writing-unit-tests/client-components.md
@@ -0,0 +1,158 @@
+# Testing Preact components (`apps/client/src/widgets/react/`)
+
+You can render real components **with zero new dependencies**. The test env is already `happy-dom`, esbuild compiles JSX with `jsxImportSource: "preact"`, and `apps/client/src/test/setup.ts` already injects `$`/`glob`/`ws` and auto-mocks `services/server`. Rendering uses Preact's own `render()` — the exact mechanism the app uses in `apps/client/src/widgets/react/react_utils.tsx`.
+
+> This recipe is **proven**: Icon, Button, FormTextBox, FormSelect, and ActionButton were rendered and asserted (events + DOM) with all tests passing.
+
+## The render helper
+
+Put this in a shared `apps/client/src/test/render.ts` (recommended) or inline per spec:
+
+```ts
+import { render } from "preact";
+import { afterEach } from "vitest";
+
+let container: HTMLDivElement | undefined;
+export function renderInto(vnode: any) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ render(vnode, container);
+ return container;
+}
+// Always tear down, or bootstrap Tooltips / listeners leak between tests.
+afterEach(() => { if (container) { render(null, container); container.remove(); container = undefined; } });
+```
+
+Spec files that use JSX must be named `*.spec.tsx`.
+
+## Firing events — match Preact's delegated event names
+
+Set the value, then dispatch the **native** event Preact listens for, always with `{ bubbles: true }`:
+
+| Handler | Dispatch | Notes |
+|---|---|---|
+| `onClick` | `el.click()` | simplest |
+| `onInput` | `new Event("input", { bubbles: true })` | text inputs |
+| `onChange` (on `<select>`) | `new Event("change", { bubbles: true })` | |
+| **`onBlur`** | **`new Event("focusout", { bubbles: true })`** | ⚠️ Preact delegates blur→`focusout`; a `"blur"` event silently does **nothing** |
+
+## Tier A — presentational (props → DOM + click)
+
+```tsx
+import { describe, expect, it, vi } from "vitest";
+import { renderInto } from "../../test/render";
+import Icon from "./Icon";
+import Button from "./Button";
+
+describe("Icon", () => {
+ it("composes icon + extra classes and passes through title", () => {
+ const span = renderInto(<Icon icon="bx bx-search" className="extra" title="Search" />).querySelector("span")!;
+ expect(span.className).toBe("bx bx-search extra tn-icon");
+ expect(span.getAttribute("title")).toBe("Search");
+ });
+ it("falls back to bx-empty when no icon given", () => {
+ expect(renderInto(<Icon />).querySelector("span")!.className).toBe("bx bx-empty tn-icon");
+ });
+});
+
+describe("Button", () => {
+ it("applies kind class, becomes type=button with a handler, fires onClick", () => {
+ const onClick = vi.fn();
+ const btn = renderInto(<Button text="Save" onClick={onClick} kind="primary" />).querySelector("button")!;
+ expect(btn.className).toContain("btn-primary");
+ expect(btn.getAttribute("type")).toBe("button"); // submit only when no handler/command
+ btn.click();
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+ it("does not fire onClick when disabled", () => {
+ const onClick = vi.fn();
+ renderInto(<Button text="Nope" disabled onClick={onClick} />).querySelector("button")!.click();
+ expect(onClick).not.toHaveBeenCalled();
+ });
+});
+```
+
+## Tier B — stateful / controlled form components
+
+```tsx
+import { describe, expect, it, vi } from "vitest";
+import { renderInto } from "../../test/render";
+import FormTextBox from "./FormTextBox";
+import FormSelect from "./FormSelect";
+
+function typeInto(input: HTMLInputElement, value: string) {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+}
+
+describe("FormTextBox", () => {
+ it("clamps number inputs to [min,max] on change", () => {
+ const onChange = vi.fn();
+ const input = renderInto(<FormTextBox type="number" min={1} max={10} currentValue="5" onChange={onChange} />).querySelector("input")!;
+ typeInto(input, "999");
+ expect(onChange).toHaveBeenLastCalledWith("10", expect.anything()); // applyLimits() clamps
+ });
+ it("fires onBlur with the clamped value", () => {
+ const onBlur = vi.fn();
+ const input = renderInto(<FormTextBox type="number" min={2} onBlur={onBlur} />).querySelector("input")!;
+ input.value = "0";
+ input.dispatchEvent(new Event("focusout", { bubbles: true })); // NOT "blur"
+ expect(onBlur).toHaveBeenCalledWith("2");
+ });
+});
+
+describe("FormSelect", () => {
+ it("renders options, marks current, emits key on change", () => {
+ const onChange = vi.fn();
+ const values = [{ key: "a", label: "Apple" }, { key: "b", label: "Banana" }];
+ const select = renderInto(<FormSelect values={values} keyProperty="key" titleProperty="label" currentValue="b" onChange={onChange} />).querySelector("select")!;
+ expect(select.value).toBe("b");
+ select.value = "a";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ expect(onChange).toHaveBeenCalledWith("a");
+ });
+});
+```
+
+## Tier C — components importing services / i18n / bootstrap
+
+`vi.mock` the side-effectful service and partial-mock `./hooks` so the real DOM still renders:
+
+```tsx
+import { describe, expect, it, vi } from "vitest";
+import { renderInto } from "../../test/render";
+
+vi.mock("../../services/keyboard_actions", () => ({
+ default: { getAction: vi.fn().mockResolvedValue({ effectiveShortcuts: [] }) }
+}));
+vi.mock("./hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./hooks")>()),
+ useStaticTooltip: vi.fn() // stub only the bootstrap-Tooltip hook
+}));
+import ActionButton from "./ActionButton"; // import AFTER the mocks (they're hoisted)
+
+describe("ActionButton", () => {
+ it("renders icon-action button and forwards trigger command", () => {
+ const onClick = vi.fn();
+ const btn = renderInto(<ActionButton text="Delete" icon="bx bx-trash" triggerCommand="saveToNoteMap" onClick={onClick} />).querySelector("button")!;
+ expect(btn.className).toContain("icon-action");
+ expect(btn.getAttribute("data-trigger-command")).toBe("saveToNoteMap");
+ btn.click();
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+});
+```
+
+## Component-specific gotchas
+
+- **`isMobile()`/`isDesktop()` are cached at module load** (`const cachedIsMobile = isMobile()` in `Button`/`ActionButton`). To exercise both branches, `vi.mock("../../services/utils")` **before** importing the component — a runtime spy is too late.
+- **`Modal`** visibility is driven by the bootstrap Modal instance + `openDialog` (jQuery) inside `useEffect`; show/hide won't behave under happy-dom. Treat it as integration-tier; in happy-dom only assert its static structure with `show`.
+- Pre-existing stderr noise (KaTeX "quirks mode", the `setup.ts` "vi.mock not at top level" warning) is **not** a failure — ignore it.
+
+## Optional ergonomic upgrade
+
+Once the raw approach is established, you may add `@testing-library/preact` (+ `@testing-library/jest-dom`) as client devDeps. The concrete win: `fireEvent.blur()` hides the focusout gotcha, `cleanup` removes the manual `afterEach`, and `getByRole`/jest-dom matchers (`toBeDisabled`, `toHaveValue`) read better. It's a convenience layer, not a requirement — neither is installed today.
+
+## Best first targets (high branch density)
+
+`Icon` → `Button` (kind/size/type/`<kbd>` branches) → `FormTextBox` (`applyLimits` clamping) → `FormSelect` (optgroups) → `ActionButton` / `Badge` (Tier C). Defer `Modal`.
diff --git a/.claude/skills/writing-unit-tests/client-logic-and-services.md b/.claude/skills/writing-unit-tests/client-logic-and-services.md
new file mode 100644
index 0000000000..24977501c3
--- /dev/null
+++ b/.claude/skills/writing-unit-tests/client-logic-and-services.md
@@ -0,0 +1,74 @@
+# Testing client widgets & services (`apps/client/src/`)
+
+Two harnesses already exist and do the heavy lifting — use them instead of inventing new ones.
+
+## The fixtures you already have
+
+- **`apps/client/src/test/setup.ts`** (registered as `setupFiles`, runs for every spec): runs under happy-dom, injects `window.$` (jQuery), `window.glob`, a WebSocket stub, and **globally `vi.mock`s `services/ws.js` and `services/server.js`** so froca never hits the network. The default `server` mock returns canned data for `options`/`keyboard-actions`/`tree` GETs and **throws on `tree/load` POST** to force you to seed froca instead.
+- **`apps/client/src/test/easy-froca.ts`** — `buildNote(def)` / `buildNotes(def[])` construct real `FNote`/`FAttribute`/`FBranch`/`FBlob`, register them in froca + `noteAttributeCache`, and wire parent/child branches.
+ - Labels: `"#color"`; relations: `"~template"`; inheritable: `"#x(inheritable)"`; children: `children: [...]`; content via `content`.
+ - ⚠️ It does **not** model template inheritance — `~template`-derived inherited attributes won't behave like production. Cover those in E2E.
+
+## Widgets
+
+### (Primary) Extract pure logic, then test the function
+
+Mirror `apps/client/src/widgets/ribbon/FormattingToolbar.tsx` → `getFormattingToolbarState(...)`, tested in `FormattingToolbar.spec.ts`. Move the widget's "what to show / how to map data" out into a top-level `export function` taking an `FNote` (from `buildNote`), a `NoteContext`, primitives; the widget becomes a thin caller. `vi.mock` only the few services the logic transitively touches (e.g. `services/tree.ts`).
+
+```ts
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import NoteContext from "../../components/note_context";
+import { buildNote } from "../../test/easy-froca";
+import { getFormattingToolbarState } from "./FormattingToolbar";
+
+describe("getFormattingToolbarState", () => {
+ beforeAll(() => {
+ vi.mock("../../services/tree.ts", () => ({ default: { getActiveContextNotePath: () => "root", resolveNotePath: (p: string) => p } }));
+ buildNote({ id: "root", title: "Root" });
+ });
+ it("is hidden for a read-only text note", async () => {
+ const note = buildNote({ title: "N", type: "text" });
+ const ctx = new NoteContext("abc");
+ ctx.noteId = note.noteId;
+ ctx.isReadOnly = async () => true;
+ ctx.getMainContext = () => ctx; ctx.getSubContexts = () => [ctx];
+ expect(await getFormattingToolbarState(ctx, note, "ckeditor-classic")).toBe("hidden");
+ });
+});
+```
+
+### Extract `entitiesReloadedEvent` predicates
+
+The valuable, testable part of a refresh handler is the predicate "given these entity changes, should I refresh?". `LoadResults` (`apps/client/src/services/load_results.ts`) is a plain class built from an `EntityChange[]`. Extract `export function shouldRefreshFor(loadResults, noteId, note)` from the inline handler (e.g. in `toc.ts`, `highlights_list.ts`) and test it with a hand-built `LoadResults`. `vi.mock` `services/attributes` if it calls `isAffecting`.
+
+### (Secondary) Instantiate a legacy `BasicWidget` and assert on `$widget`
+
+`new TheWidget()` then `widget.render()` returns the jQuery `$widget` (see `basic_widget.ts`), queryable with `.find()`/`.html()`/`.hasClass()`. `highlights_list.spec.ts` shows the pattern. Keep these to **leaf** widgets and single methods — a top-level note-detail widget's `doRender` cascades into CKEditor/child widgets and is not unit-testable. Assert on classes (`hidden-int`/`visible`), not computed visibility (happy-dom has no layout).
+
+## Services (`apps/client/src/services/`)
+
+Because `setup.ts` already mocks `server.js` globally, **override specific methods per test** rather than re-mocking the whole module (re-mocking loses the canned `tree`/`options` responses froca needs):
+
+```ts
+import { describe, expect, it, vi } from "vitest";
+import server from "../services/server";
+import { buildNote } from "../test/easy-froca";
+import attributeService from "./attributes";
+
+it("setLabel calls server.put and updates froca", async () => {
+ const note = buildNote({ title: "N" });
+ server.put = vi.fn(async () => ({})) as typeof server.put;
+ await attributeService.setLabel(note.noteId, "color", "red");
+ expect(server.put).toHaveBeenCalled();
+});
+```
+
+Rules of thumb:
+- Reading froca? `buildNote(...)` it **first** — `froca.getNote` for an unknown id triggers the throwing `tree/load` POST.
+- froca is a **singleton** with no reset between tests — use fresh/unique ids (the `buildNote` default) and don't assume an empty cache.
+- Many services `await ws.waitForMaxKnownEntityChangeId()`. The global stub provides it; if you locally `vi.mock("./ws.js")` you must re-provide both `subscribeToMessages` and `waitForMaxKnownEntityChangeId` or the await hangs.
+- Module-load side effects exist (`branches.ts`/`tree.ts` call `ws.subscribeToMessages` at import); harmless under the global stub.
+
+### Highest-ROI untested service
+
+`apps/client/src/services/load_results.ts` — ~253 lines, **zero deps, pure class**, ~20 branchy methods. 0% → ~95% in one mock-free spec. Then: `tree.ts` string helpers (`getNoteIdFromUrl`, `resolveNotePathToSegments`), `options.ts` (`getJson`/`getInt`/`save`), `branches.ts` (move/delete guards), `mime_types.ts`, `bulk_action.ts` (`parseActions`).
diff --git a/.claude/skills/writing-unit-tests/server-and-core.md b/.claude/skills/writing-unit-tests/server-and-core.md
new file mode 100644
index 0000000000..23e5e033fd
--- /dev/null
+++ b/.claude/skills/writing-unit-tests/server-and-core.md
@@ -0,0 +1,105 @@
+# Testing the server & trilium-core (`apps/server/`, `packages/trilium-core/`)
+
+`apps/server/spec/setup.ts` boots an **in-memory SQLite fixture** once per spec file: it loads `packages/trilium-core/src/test/fixtures/document.db` (password **`demo1234`**) and calls `initializeCore(...)`. With `pool: "forks"`, each spec file gets a fresh writable copy — **mutations isolate per file, not per `it()`**.
+
+`trilium-core` cannot run tests standalone (its `test` script just prints a note — it needs a host runtime's platform providers). Its specs run **through** `apps/server` (and `apps/standalone`), which already list `../../packages/trilium-core/src/**` in both their test `include` and `coverage.include`. Add core specs next to the core source or under `apps/server/spec` — both feed the same coverage number. A dedicated core vitest project is **not** needed.
+
+There are **two distinct HTTP code paths** — testing one does not cover the other:
+- **ETAPI** (`apps/server/src/etapi/*`): basic-auth token, helpers in `spec/etapi/utils.ts`.
+- **Internal API** (`apps/server/src/routes/api/*` + `packages/trilium-core/src/routes/api/*`): session cookie + CSRF. **This is the large uncovered surface.**
+
+## Pattern 1 — internal REST API via supertest agent
+
+Reuse the agent + CSRF flow from `apps/server/src/routes/api/options.spec.ts`. Start with read/transform handlers (`tree`, `recent_changes`, `note_map`, `similar_notes`, `stats`) — they need no setup beyond the seeded demo content. One spec file per handler keeps fork isolation clean.
+
+```ts
+import type { Application } from "express";
+import supertest from "supertest";
+import { beforeAll, describe, expect, it } from "vitest";
+
+let app: Application, agent: ReturnType<typeof supertest.agent>, csrfToken: string;
+
+describe("Tree API", () => {
+ beforeAll(async () => {
+ app = await (await import("../../app.js")).default();
+ agent = supertest.agent(app);
+ await agent.post("/login").send({ password: "demo1234" }).expect(302);
+ csrfToken = (await agent.get("/bootstrap").expect(200)).body.csrfToken;
+ });
+ it("loads the tree rooted at root", async () => {
+ const res = await agent.post("/api/tree/load").set("x-csrf-token", csrfToken)
+ .send({ subTreeNoteId: "root", noteIds: ["root"] }).expect(200);
+ expect(res.body.notes.some((n: any) => n.noteId === "root")).toBe(true);
+ });
+});
+```
+
+## Pattern 2 — ETAPI contract via supertest + basic auth
+
+Use `spec/etapi/utils.ts` (`login`, `createNote`). The suite is mature on happy paths — the cheap wins are **error/edge paths** (404 missing id, 400 malformed body, validation rejection), which exercise the shared etapi handlers/validators currently only hit on success.
+
+```ts
+it("returns 404 for a non-existent note", async () => {
+ await supertest(app).get("/etapi/notes/doesNotExist123/content")
+ .auth("etapi", token, { type: "basic" }).expect(404);
+});
+```
+
+## Pattern 3 — real-DB service test (write paths)
+
+For the big write-path files (`notes.ts` is the largest cold file, 1303 lines), test **against the real in-memory DB**, not with sql stubbed — stubbing only covers pure helpers and leaves the shipping SQL/cache/entity-change path cold. Follow `apps/server/src/services/hidden_subtree.spec.ts`:
+
+```ts
+import { becca, cls, note_service as notes } from "@triliumnext/core";
+import { beforeAll, describe, expect, it } from "vitest";
+import sql_init from "./sql_init.js";
+
+describe("createNewNote (real DB)", () => {
+ beforeAll(async () => { sql_init.initializeDb(); await sql_init.dbReady; });
+ it("creates a text note under root with content + branch", () => {
+ const { note, branch } = cls.init(() => notes.createNewNote({
+ parentNoteId: "root", title: "Spec note", content: "<p>hello</p>", type: "text"
+ }));
+ expect(becca.notes[note.noteId]).toBe(note);
+ expect(note.getContent()).toBe("<p>hello</p>");
+ expect(branch.parentNoteId).toBe("root");
+ });
+});
+```
+
+**Mutations require CLS:** wrap `setContent`/`createNewNote`/etc. in `cls.init(() => ...)`. Supertest route tests get CLS for free; direct service calls do not.
+
+## Pattern 4 — pure service, zero infra
+
+Cheapest wins: services that are deterministic string/data builders with no DB. `apps/server/src/services/anonymization.ts`, `totp.ts`. Lock the output like `blob.spec.ts` locks a hash; extract inner builders if not exported (per `CLAUDE.md`'s "extract and test business logic").
+
+## Pattern 5 — mock external SDKs
+
+For network/AI/OCR code, two proven idioms:
+- `vi.mock` the SDK directly: `tesseract.js` (see `ocr/ocr_service.spec.ts`), `@ai-sdk/*` + `ai` (use `vi.hoisted`).
+- **Partial-mock `@triliumnext/core`** to override only what you need:
+
+```ts
+const mockBecca = { getNote: vi.fn(), notes: {} as Record<string, any> };
+vi.mock("@triliumnext/core", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@triliumnext/core")>()),
+ becca: mockBecca
+}));
+```
+
+Target the `mutates:false` `execute()` of LLM tools (`llm/tools/*`). Don't try to test actual model/OCR output. **Mock-path correctness:** production imports `becca`/`sql`/`options`/`getLog` from `@triliumnext/core` directly (the old `apps/server/src/services/*` wrappers were removed), so mock `@triliumnext/core`, not the old wrapper paths.
+
+## Server gotchas
+
+- **Fork isolation is per file**, and `it()`s share the DB within a file. Order-dependent tests inside a file can interfere; re-establish a baseline before rollback tests (`options.spec.ts` does this).
+- **becca goes stale vs the DB on rollback** — becca is mutated *before* the SQL write and left stale after a rollback. When testing transaction/rollback behavior, assert against the DB row (`getSql().getRowOrNull(...)`), not becca.
+- `llm/providers/*` and `ocr/*` need heavy SDK mocking; the existing provider specs assert construction/message-shape invariants, not inference. `open_id.ts`/`request.ts` hit the network — mock the transport.
+
+## Best ROI targets
+
+1. `packages/trilium-core/src/services/notes.ts` (real-DB) — largest cold file; also pulls in blob hashing, entity_changes, saveLinks.
+2. `packages/trilium-core/src/routes/api/*` internal handlers (supertest) — untouched by ETAPI specs. Read handlers first, then `branches`/`cloning`/`bulk_action`/`attributes`.
+3. `apps/server/src/services/anonymization.ts`, `totp.ts` (pure).
+4. `packages/trilium-core/src/services/date_notes.ts`, `export/markdown.ts`, `import/enex.ts`, `special_notes.ts`.
+5. `apps/server/src/services/llm/tools/*` + `request.ts`/`open_id.ts` (mocked).
+6. Broaden ETAPI error-path assertions (low effort, harness exists).
diff --git a/.gitignore b/.gitignore
index 8d21481869..244291c7c4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -52,6 +52,8 @@ site/
apps/*/coverage
scripts/translation/.language*.json
-.claude
+# Ignore local Claude Code settings, but keep shared project skills.
+.claude/*
+!.claude/skills/
.pnpm-store
apps/edit-docs/output.zip