Lutra/docs/architecture.md
danny d4e1ba0981 PM: merge M3.9 hamburger app menu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/architecture.md
#	docs/gaps.md
2026-10-19 18:26:05 +02:00

372 lines
88 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu · **Last updated:** 2026-10-19
## Overview
```
apps/lutra-desktop (L6) Tauri 2 shell: windows, menus, IPC bridge to the engine
ui/ (L6) Vue 3 + TypeScript + Vite frontend, Pinia, CodeMirror 6
apps/lutra-cli (L6) the `lutra` command: open, --wait; later diff, mcp, perf, bench
crates/control (L5) JSON-lines control channel (--control PORT)
crates/mcp (L5) MCP server over stdio
crates/engine (L4) command registry, workspace state, guard, recovery journal, theme tokens
crates/lsp (L3) LSP client (Phpactor first), later DAP client
crates/terminal (L3) pseudo-terminal sessions (portable-pty)
crates/index (L2) symbol index, usages, later type inference
crates/vfs (L2) project model, file watching, ignore rules, encodings
crates/search (L2) find in files (ignore + grep-searcher crates)
crates/syntax (L1) tree-sitter parsing (PHP first), outlines, highlight tokens
crates/text (L0) rope buffer, positions, UTF-8/UTF-16 conversion, edits
crates/testkit (—) test helpers and fixtures, tests only
xtask (—) ci, layers, assets, cleanroom, dev, fixtures, lints-selftest, ui-licences
```
Each crate declares its layer in its manifest:
```toml
[package.metadata.lutra]
layer = 4 # or "tool" for testkit and xtask
```
`cargo xtask layers` reads `cargo metadata` and fails when
- a crate has no layer;
- a normal or build dependency points to a workspace crate of the same or a higher layer;
- a crate with a numeric layer has a tool crate (`testkit`, `xtask`) as a normal or build dependency (dev-dependencies are fine);
- a crate below L6 reaches a `tauri` or `tauri-*` package through its normal dependencies, directly or transitively.
## Commands
Every user-visible action is a command: `id`, `label`, `menu_path`, `default_shortcut`, `params` (documented schema), `enabled(&State) -> bool`, `run(&mut State, Params) -> Result<Output, EngineError>`. Menus, the palette, keymaps, the CLI, the control channel and MCP all call the registry. Long-running commands report progress and can be cancelled.
As built in M0:
- `lutra_engine::Command` is a trait with `spec()`, `enabled()` and `run()`. `spec()` returns a `CommandSpec` with the static metadata. Params and results are `serde_json::Value`; each command documents its params in `CommandSpec::params`.
- `Engine::execute(id, params)` looks the command up, checks `enabled`, runs it inside the guard and returns an `Outcome { value, effects, events }`. Commands queue events with `State::emit`; the engine moves them into the outcome. Events queued by a command that then fails stay queued and arrive with the next outcome, `Engine::pump_vfs` or `Engine::take_events`.
- Effects are requests the engine cannot fulfil below L6 (`Effect::Quit` so far). The host (desktop, tests) applies them after the command returns. Commands never call into Tauri.
- `EngineError` has a stable string `code()` used by the control channel and the frontend: `unknown_command`, `disabled` (e.g. a file command without a project), `invalid_params`, `stale_version` (a `buffer.edit` based on an old version), `unsaved_changes` (closing a dirty buffer or project without `force`), `failed`, `internal`.
- Shortcut notation: `Mod` is Ctrl on Windows and Linux and Cmd on macOS (`Mod+Q`). Default shortcuts are Lutra's own.
- UI commands (M1.8) are the frontend's own commands, listed next to the engine's; see UI commands, palette and keymap below.
## Guard
`lutra_engine::guard::run` wraps a closure in `std::panic::catch_unwind` and turns a panic into `EngineError::Internal`. Release builds keep `panic = "unwind"` for this reason; `panic = "abort"` is never set. The engine is held in a `Mutex` by the hosts; because the guard runs inside the lock, a panicking command never poisons it, and hosts still recover a poisoned lock with `into_inner` instead of unwrapping.
## Control channel
`--control PORT` binds `127.0.0.1:PORT` only. If binding fails, the desktop app prints the error and exits with status 1.
- Transport: one JSON object per line, UTF-8, at most 16 MiB per line; longer lines get an error response and the connection is closed.
- Request: `{"id": <number|string>, "method": "<name>", "params": {...}}`. Response: `{"id": ..., "result": ...}` or `{"id": ..., "error": {"code": "...", "message": "..."}}`. A line that is not valid JSON gets an error response with `"id": null`.
- Methods: `app.ping`, `app.auth {token}`, `app.focus`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`, `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`.
- `events.subscribe` answers `{subscribed: true}` and from then on writes `{"event": {...}}` lines for every engine event on that connection, between responses; a shared writer writes each line whole. Subscribing twice is a no-op. Each subscriber has a queue of 4096 events (`lutra_control::EVENT_QUEUE`); a subscriber that falls behind or disconnects is dropped by `Subscribers::publish`, and the connection gets a final `{"event": {"kind": "subscriptionLost"}}` line if it is still open.
- `lutra_control` defines a `Backend` trait; the desktop app implements it (engine access, effects, screenshots, event subscribers), tests implement it with a bare engine (`lutra_testkit::EngineBackend`). Hosts publish each outcome's events through `lutra_control::Subscribers`. One thread accepts connections and each connection gets its own thread; no async runtime is needed in the crate.
- Screenshots: `xcap` does not enumerate windows of its own process (querying their titles can deadlock), so the desktop focuses its main window, reads the client area's physical position and size from Tauri and captures that region of the monitor with `xcap::Monitor::capture_region`. Windows covering Lutra at that moment appear in the image. A webview-native capture (WebView2 `CapturePreview`, WKWebView snapshots) can replace it later.
### CLI and single instance (M3.7)
- **Rendezvous file:** a desktop that owns the single instance serves a second, token-protected control listener on a free port of `127.0.0.1` (`lutra_control::start_with_token`) and writes `<data_dir>/instance.json` = `{port, token, pid, version}` (`lutra_control::rendezvous`). The token is 32 bytes from the OS generator (`getrandom`), hex. The file is written to a temporary file and renamed, so readers never see half a file; on exit the app removes it if it still holds its own token.
- **Directory:** `LUTRA_RENDEZVOUS_DIR` if set, else `rendezvous::default_data_dir()`, which computes Tauri's `app_data_dir()` for the identifier `dev.lutra.desktop` without Tauri (`%APPDATA%\dev.lutra.desktop` on Windows, `~/Library/Application Support/dev.lutra.desktop` on macOS, `$XDG_DATA_HOME` or `~/.local/share` + the identifier elsewhere), so the CLI and the desktop agree without sharing a runtime.
- **Security:** only the user may read the token. Unix: the file is created with mode `0600`. Windows: it lives in the user's roaming AppData folder, whose inherited ACL grants the user, `SYSTEM` and Administrators only (checked with `icacls` in the M3.7 live check); Lutra sets no ACL of its own. Both listeners bind `127.0.0.1` only. On the token listener the first request must be `app.auth {token}` within 10 s (`AUTH_TIMEOUT`); a wrong token, another method or garbage gets `unauthorized` and the connection is closed. Tokens are compared in constant time. The `--control PORT` listener stays open (no token) for development and agents; it is opt-in and documented as such.
- **Second start:** `lutra-desktop [PATH]` without `--control` reads the rendezvous file first. If the listener answers, accepts the token and pings, the start forwards `PATH` (folder → `project.open`, file → `file.open`), calls `app.focus` and exits 0. If the file is missing, unreadable, invalid, or its port refuses or rejects the token, it is stale: this start becomes the instance and replaces the file. Two starts in the same instant can both become instances; the later file wins (accepted, rare).
- **Development instances:** a start with `--control PORT` skips the single instance (no forwarding, no rendezvous file) so parallel agents' instances never forward to each other, unless `LUTRA_RENDEZVOUS_DIR` is set, which opts it into the single instance in that directory (used for isolated live checks).
- **New methods:** `app.auth {token}` (always succeeds on the open listener) and `app.focus` (restore, show and focus the main window; `focus_failed` without a window; `Backend::focus` has a default that fails, so test backends need no change).
- **`lutra` CLI** (`apps/lutra-cli`, binary `lutra`, now L6 so it can use `lutra-control`): `lutra [--wait] [PATH[:LINE[:COLUMN]]]...`.
- **Targets:** up to two trailing `:N` groups are a 1-based line and column (`N` all digits, something before it; on Windows a lone drive letter is never split). If the path part does not exist but the whole argument does, the argument is the path. Paths are made absolute against the current directory without resolving symlinks.
- **Opening:** a folder (at most one, no position) → `project.open`. A file → `file.open`; with no project open its parent folder is opened first. **A file outside the open project is refused** (exit 1, the engine's `… is outside the project`), because Lutra has one window and replacing the project behind the user's back could lose their context; out-of-project buffers are a gap (G7). A line → `editor.reveal {path, line-1, column-1}`, retried for up to 20 s while the window has not registered its UI commands yet (`unknown_command`).
- **Starting Lutra:** if no instance answers, the CLI starts the desktop detached (`LUTRA_DESKTOP`, else `lutra-desktop` next to `lutra`, else on `PATH`) and polls the rendezvous file for up to 60 s.
- **`--wait`:** subscribes before opening, then blocks until every opened file's `bufferClosed` arrived (or `projectClosed`, or the connection ends because Lutra quit). A `subscriptionLost` renews the subscription and checks the remaining ids with `buffer.get`. Folders are not waited for.
- **Exit codes:** 0 ok, 1 error (cannot start, open failed, missing path), 2 bad usage (unknown option, line or column 0 or too big, two folders, a positioned folder, non-Unicode argument). Arguments are untrusted; parsing is property-tested.
- **Rendezvous API for M3.8 (`lutra mcp`):** `lutra_control::client::connect_live(&rendezvous::dir()?, timeout)` returns the `Instance` and an authenticated `Client`; `Client::request(method, params)`, `execute(command, params)`, `subscribe()`, `next_event(timeout)` (events read while waiting for a response are queued, at most 4096), `open_folder`, `open_file`, `reveal`, `focus`. To start Lutra when none runs, reuse the CLI's `launch` logic (move it into the client if MCP needs it outside the CLI binary). Response lines are capped at 64 MiB.
## Frontend ↔ engine
The frontend calls `run(id, params)` over Tauri IPC (`engine_execute`, `engine_list_commands`) and subscribes to state events. Buffer contents live in the engine; CodeMirror sends edits as transactions and receives authoritative changes back.
Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS custom properties (`--lt-*`). The desktop injects the stored theme with the window's initialization script, so the first frame is already themed and the frontend needs no round trip. Components use only `var(--lt-…)`; switching is described under Themes.
### Workspace (M1.3)
- `State` holds `project: Option<Workspace>` (the `lutra_vfs::Project`, its watcher and the watched directories) and `buffers` (id → `OpenBuffer { buffer: lutra_text::Buffer, path, version, saved_version, bom }`). A buffer is dirty when `version != saved_version`. Ids are never reused.
- Commands: `project.open {path, force?}`, `project.close {force?}`, `project.children {dir?}`, `file.open {path}` (returns the existing buffer if the file is already open), `buffer.get {id}`, `buffer.edit {id, baseVersion, edits}`, `file.save {id}` (`Mod+S`), `file.saveAll` (`Mod+Alt+S`), `buffer.close {id, force?}`. Everything except `project.open` is disabled without a project. Paths are project-relative with `/`; absolute paths are accepted when they lie inside the project; `..` escapes are rejected by the VFS.
- Edit protocol: `edits` are `{from, to, insert}` in UTF-16 code units, all relative to the text at `baseVersion` (CodeMirror change-set semantics), non-overlapping, applied atomically. A `baseVersion` other than the current version fails with `stale_version` and changes nothing; the client refetches with `buffer.get` and reapplies its pending changes. Each successful batch increments the version by one. Limits: 100,000 edits and 64 MiB inserted per call.
- Saving writes `Buffer::save_text` (the file's dominant line ending) atomically through the VFS and keeps a UTF-8 byte order mark.
### Events
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump.
Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched. The parent directory of every open buffer is pinned (M1.13, `workspace::sync_buffer_dirs`, run by `Engine::execute` after every command): it is watched even if the tree never listed it, so reloads and `fileChangedOnDisk` arrive for files opened by path from never-expanded folders. Pinned directories count against the cap but are never evicted while a buffer in them is open (with more pinned directories than the cap, the watched set exceeds it); after the last buffer in a directory closes, it ages out like a listed one. A buffer inside an ignored or hidden directory is still not watched.
### Desktop bridge (M1.4)
- The desktop host publishes every event, from commands and from its pump thread, to control channel subscribers and to the window as the Tauri event `engine://event` with the engine `Event` as payload. Events are published while the engine lock is held, so their order is the engine's order.
- `ui/src/ipc.ts` exposes `onEngineEvent(handler) => unsubscribe` with the typed union `EngineEventPayload`. Once the subscriptions started together (all of them while the page mounts) are registered, `ipc.ts` calls the IPC command `engine_ready` once; the host then replays `projectOpened` and `bufferOpened` for the current state, followed by the notifications and `watchFailed` events published before (M1.12), to the window only. A project opened from the command line (`lutra-desktop --control 7979 PATH`) or before a page reload therefore still reaches the UI.
- `project.openDialog` returns `Effect::PickFolder`; the host shows the native folder picker (`tauri-plugin-dialog`, from Rust, non-blocking) and runs `project.open` with the choice. At most one picker is open; cancelling does nothing. A folder that cannot be opened becomes a `notification` (M1.12): `unsaved_changes` a warning, anything else an error.
- Capabilities: the main window may only listen to and unlisten from events (`core:event:allow-listen`, `core:event:allow-unlisten`). Engine commands are app commands and need no permission; the dialog plugin is used from Rust only, so the frontend gets no dialog permission.
- Contract fix: the project UI from M1.5 was written against assumed shapes. `ui/src/components/project/engineEvents.ts` is now the adapter between the engine contract and the UI types: `toProjectEvent` translates `{kind: "projectOpened", root, name}` and friends into the store's events, and `toTreeEntries` translates `project.children`'s `{dir, entries: [{name, path, kind: file|directory|other, ignored, role}], truncated}` into tree entries (`kind: dir|file`, `role`, `excluded`, `special` for `other`) plus `truncated`. Malformed entries are skipped; a result without `entries` becomes an `ipc` error on the directory.
### Tabs and editor (M1.6)
- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it; `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them.
- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text.
- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table.
- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context; since M1.8 through the global keymap (see UI commands, palette and keymap). Saving and closing wait until the sync has no pending edits.
- Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Lutra saves only on request for now (no autosave).
- Theme: the editor reads colours only from `--lt-*` tokens, including the editor tokens from M1.10 (selection, active line, cursor, gutter, match, editor font size); no fallbacks remain.
### Highlighting and editor.reveal (M2.2)
- **Languages:** `ui/src/components/editor/language.ts` picks a language once per tab from the file extension (`languageOf`): PHP (`php`, `phtml`, `inc`, `php3`–`php8`, `phps`) through `@codemirror/lang-php`, whose Lezer grammar also parses the HTML, CSS and JavaScript around `<?php … ?>` blocks; HTML, CSS, JavaScript/TypeScript (with JSX), JSON, YAML and Markdown through their `@codemirror/lang-*` packages (all MIT). Other files stay plain text. The editor store passes the tab's path to `editorExtensions(path)` when it creates the tab's state.
- **Colours:** the highlighter is a `tagHighlighter` that only sets classes: a span gets `lt-syntax-<token>` for one of the eleven tokens `keyword`, `string`, `number`, `comment`, `variable`, `function`, `type`, `constant`, `tag`, `attribute`, `operator`. The editor theme (`extensions.ts`) colours each class with its `--lt-syntax-<token>` variable. Lezer tags that are not mapped fall back to their parent tag (`controlKeyword` → `keyword`); tags without a mapped ancestor (punctuation, plain names such as the class after `extends`) keep `--lt-fg`. CodeMirror's default highlight style is never active, so no colour bypasses the tokens.
- **Tokens:** `lutra_engine::theme::SYNTAX_TOKENS` lists the names; both themes define `syntax-*` values. It is Lutra's own palette, derived from the copper accent and the warm neutrals (keyword = accent, comment near `fg-muted`, operator = `statusbar-fg`). The contrast test checks each one at 4.5:1 on `editor-bg` and on `editor-active-line-bg` in both themes, and that the themes define no syntax token it does not check. Lowest ratios: dark comment 5.42 on the editor background and 4.86 on the active line; light keyword 5.32 and 4.84. Text on the selection colour is not held to 4.5:1 (syntax colours reach 3.06–5.96 there).
- **Two highlighters:** Lezer in the UI highlights on every keystroke without IPC; tree-sitter in `crates/syntax` (M2.1) drives outline, folding and the index. They can disagree on broken code; that is accepted (see Decisions).
- **Performance:** keystroke to highlight on a 1 MB PHP file (30k lines), measured with `LUTRA_PERF=1 pnpm vitest run tests/editor/highlightPerf.test.ts` in jsdom (the JavaScript work of one `view.dispatch`, no layout or paint), Windows 11, three runs while other builds ran: median 3.0–3.8 ms near the top of the file and 6.3–11.4 ms in the middle; p95 10–16 ms in two runs (one disturbed run: 82 ms). The plain-text baseline is 0.4–0.6 ms. The initial full parse takes 0.7–1.5 s, which CodeMirror spreads over idle slices after the visible part. Not measured in the WebView itself yet (follow-up for `lutra perf`).
- **`editor.reveal {path, line, column}`** (`reveal.ts`; a UI command registered through `ui.registerCommands`, label `command.editor.reveal`, provided by `EditorArea.vue`):
- **Steps:** it opens the file with `file.open` unless a tab has that exact path, activates the tab and waits one render tick so the view shows it. Then it places the cursor and scrolls it to the centre (`EditorView.scrollIntoView(pos, {y: "center"})`).
- **Positions:** `line` is 0-based and `column` counts UTF-16 code units in the line (C3 contract). `positionOf` in `engineText.ts` converts them to a CodeMirror position. Engine and CodeMirror split lines at the same breaks and a `\r\n` is one break on both sides, so the line carries over, and `EngineText.toEngine` maps the result back to the engine offset. Values are clamped into the document: past the end → end of line or last line; negative, fractional or non-finite → truncated or 0.
- **Without `path`** it centres the active tab's cursor, which is what running it from the palette does.
- **Errors:** wrong types fail with `editor.reveal.invalidParams`, an open failure with the engine's message; both reach the caller as an error toast.
- **Agents:** `engine.execute editor.reveal {...}` over the control channel becomes a `uiCommand`. No default shortcut.
### Message catalog (M1.11)
- Every interface string comes from `ui/src/i18n/en.json`: flat dotted keys grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`), kept sorted. Components and stores call `t(key, params?)` from `ui/src/i18n`; `{name}` placeholders are filled from `params`, a placeholder without a value stays as it is. A missing key returns the key itself and warns on the console in development builds; it never throws. `hasMessage(key)` tells whether a key exists, for keys that arrive at runtime (settings `labelKey`, notification `messageKey`).
- No i18n dependency: the helper is ~20 lines, and plurals, a reactive locale and a second language are G14 work. `vue-i18n` (MIT) remains an option then.
- Enforcement: ESLint `vue/no-bare-strings-in-template` is an error (bare text and `title`/`aria-label`/`placeholder`/`alt` attributes); the allowlist is the rule's punctuation plus `;`, `…` and `×`. The test `ui/tests/i18n/catalog.test.ts` scans `ui/src` for `t("…")` calls and fails on a key that is not in `en.json` and on a catalog key that no source uses. Keys used only at runtime need an exception there when they arrive.
- Engine messages (`EngineError.message`, the `app.about` slogan, `watchFailed`) are English text from the engine and shown as they are; they move to message keys with G14. Frontend-made errors (`unexpected result of …`) use the catalog.
### Engine construction (M1.9a)
- `EngineConfig { config_dir, data_dir }` and `Engine::with_config(config) -> Result<Engine, EngineError>`. The desktop builds the Tauri app first, takes `app_config_dir()` and `app_data_dir()` from its path resolver, creates the engine, the host and the control channel, and creates the window in the setup hook. `Engine::new()` has no persistence (settings in memory only) and serves tests and the control test backend; `lutra_testkit::engine_config(root)` gives temp dirs for tests.
- Construction never fails because of the settings file. Problems are queued as a warning `notification` event; the desktop takes the startup events and publishes them, and the window receives them on `engine_ready` (M1.12).
### Settings (M1.9a)
- `<config_dir>/settings.json`, a flat JSON object of dotted keys, written with `lutra_vfs::write_atomic` on every change. Unknown keys are kept; a stored value that fails validation counts as unset. Read with a 1 MiB cap.
- A file that is not a JSON object (invalid JSON, not UTF-8, too large) is renamed to `settings.json.bad-<YYYYMMDDTHHMMSSZ>` (with `-n` if taken), the defaults are used and a `notification {level: "warning", messageKey: "notification.settings.corrupt", message, params: {reason, backup}}` is queued. If it cannot be moved, or the directory or file cannot be read, settings stay in memory for the session (`notification.settings.corruptNotMoved`, `notification.settings.unavailable`) so the file is never overwritten.
- Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`). Defined in `lutra_engine::settings::DEFS`.
- Commands: `settings.list` → `[{key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section}]` (catalog keys `settings.<key>.label` / `.description`; `section` is an id shown with `settings.section.<id>`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing.
- Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…).
### Notifications (M1.12)
- **Event:** `notification {id, level: info|warning|error, messageKey?, message?, params?}`; ids `n1`, `n2`… from one sequence per engine. `messageKey` is a catalog key, `message` the English fallback. The engine emits them for settings (M1.9a) and journal (M1.7) problems; the host asks the engine for one with `Engine::notify` (same id sequence) for errors that have no caller to return to:
- folder picker and command-line path: `notification.project.unsavedChanges {path, what}` (warning) for `unsaved_changes`, `notification.project.openFailed {path, reason}` (error) otherwise, `notification.project.notLocal {reason}` (error) for a picked folder that is not a local path;
- pump: `notification.vfs.pumpFailed {reason}` (warning), once until a pump succeeds again.
- **Replay:** the host keeps notifications and `watchFailed` published before the window called `engine_ready` (at most 50) and sends them after the state replay; afterwards nothing is kept. The store ignores an id it already shows, so a second replay does not duplicate.
- **`watchFailed`** stays an engine event (control channel clients use it); the frontend maps it to a warning toast `notification.watch.failed {reason}`. `workspace.rs` is unchanged.
- **UI:** `ui/src/stores/notifications.ts` (Pinia) turns events into toasts (catalog text with params if the key exists, else `message`, else the key; untrusted fields checked, unknown levels count as errors) and offers `notify` / `notifyError(command, error)` to frontend code. Failed commands that have no UI of their own raise an error toast `notification.command.failed {command, message}` (today `theme.systemPreference` and loading the editor keymap); errors shown in place (tree listings, editor and project errors, the restore dialog) stay in place. `ui/src/components/notifications/NotificationStack.vue`, mounted in `App.vue`, stacks the toasts at the bottom right, newest at the bottom: info as `role="status"`, dismissed after 5 s; warnings and errors as `role="alert"`, until closed. Each toast has a close button and closes with Escape while focused; at most 5 show, older ones collapse into a "+n more" button that expands the stack; at most 100 are kept. Colours are the editor notices' (`--lt-notice-bg`, error tint), with a level stripe (muted, accent, error).
### Themes (M1.10)
- `lutra_engine::theme` defines `DARK` (`lutra-dark`) and `LIGHT` (`lutra-light`) with the same token names, plus shared font tokens. Besides the base colours (`bg`, `editor-bg`, `fg`, `fg-muted`, `border`, `accent`, `error`, `statusbar-*`) both define `editor-selection-bg`, `editor-active-line-bg`, `editor-cursor`, `editor-gutter-bg`, `editor-gutter-fg`, `editor-match-bg`, `tab-active-bg`, `tab-modified`, `notice-bg`; `font-size-editor` is shared (14px). Values are opaque `#rrggbb` derived from the palette (selection, match and notice are the accent mixed into the background); the designer may change values, never names.
- `appearance.theme` selects the theme: a theme id or `system`. `theme::resolve(setting, system_dark)` picks the theme; `system` follows the OS preference the frontend reports, and counts as dark until it has.
- Commands: `theme.list` → `[{id, label, dark}]` (`label` is a catalog key, `theme.lutraDark`/`theme.lutraLight`); `theme.systemPreference {dark}` stores the OS preference and returns the resolved theme `{id, dark, tokens}`. Switching goes through `settings.set appearance.theme` (or `settings.reset`).
- Event: `themeChanged {id, dark, tokens: {"--lt-…": value}}` (every token, shared ones included) whenever the resolved theme changes: after `settingsChanged` for `appearance.theme`, or after `theme.systemPreference` in system mode. A change that resolves to the same theme (`lutra-dark` → `system` on a dark OS) emits nothing.
- First frame: the desktop reads `appearance.theme` before creating the window and passes `theme::init_script(setting)`, which installs `<style id="lt-theme">`. For `system` the CSS is the dark theme plus the light one inside `@media (prefers-color-scheme: light)`, so the first frame follows the OS without a round trip; the native window background is set from the resolved theme (`Window::theme()` for system).
- Live switch: `ui/src/theme.ts` (`startTheme`, called by `App.vue`) reports `matchMedia("(prefers-color-scheme: dark)")` now and on every change, applies the result and every `themeChanged`: tokens go onto `:root`'s inline style (which wins over the injected style element), `color-scheme` is set, and `data-theme` holds the id. No reload.
- Accessibility: `ui/tests/theme/contrast.test.ts` checks every text/background pair the components draw with against WCAG AA (4.5:1 text, 3:1 cursor and modified dot) in both themes. It reads `ui/tests/theme/themes.json`, which the Rust test `theme::tests::ui_snapshot_is_current` keeps equal to the Rust definition (`LUTRA_UPDATE_SNAPSHOTS=1` rewrites it). `ui/tests/theme/theme.test.ts` fails on a `var(--lt-x)` the themes lack and on a fallback for a token they define.
- Not themed yet: the native title bar follows the OS, not the Lutra theme; spacing and size tokens (`--lt-space-*`, `--lt-radius`, `--lt-row-height`…) are still CSS fallbacks in components. `editor.fontSize` drives `--lt-font-size-editor` since M1.9b (see Settings dialog).
### Recovery journal (M1.7)
- **Storage:** `<data_dir>/recovery/<project-id>/<entry-id>.json`. The project id is the FNV-1a 64-bit hash of the canonical project root, the entry id the same hash of the project-relative path, each as 16 hex digits (FNV instead of `std`'s hasher, whose output may change between Rust versions). One file per dirty buffer: `{path, text, lineEnding, bom, savedAt}`; `text` is the buffer text as held in memory (mixed line breaks included), `lineEnding` the ending it saves with, `savedAt` milliseconds since the Unix epoch. Engines without a config (`Engine::new`) keep no journal. Code: `crates/engine/src/journal.rs`, commands in `cmd/recovery.rs`.
- **Writing:** `buffer.edit` only records the edit time. `Engine::pump_vfs` (the desktop's pump thread, every 100 ms) writes a buffer once it has been idle for 1 s, or 2 s after its first unwritten edit while typing continues, so an entry is on disk at most ~1.1 s after the last edit and never per keystroke. Writes use `lutra_vfs::write_atomic`. `Engine::flush_journal()` writes everything now (tests, hosts about to stop). Cost for a 1 MiB buffer (measured on Windows 11, `journal_write_cost_for_a_one_megabyte_buffer`): median 8.5 ms in a release build, 67 ms in a debug build, under the engine lock; a keystroke arriving meanwhile waits that long. Moving the write to a background thread is a follow-up if large files make it noticeable.
- **Removal:** `file.save`/`file.saveAll`, `buffer.close` (also `force`), `project.close`/`project.open` with `force` and `recovery.discard` remove entries. Save and close remove only entries this session wrote or restored; entries left by a crashed session stay until restored or discarded. Editing such a file without restoring it overwrites its entry.
- **Commands and event:** after `project.open`, `recoveryAvailable {entries: [{path, savedAt, diskChanged}]}` when the journal is not empty. `recovery.list` → `{entries}`; `recovery.restore {paths?}` → `{restored: [{path, id}], failed: [{path, message}]}` opens each file as a dirty buffer (version 1, saved version 0) with the journal text, line ending and BOM, or puts the text into a clean open buffer; a buffer with unsaved changes is newer than the journal and is left alone (`failed`); a file gone from disk is restored too and saving recreates it. `recovery.discard {paths?}` → `{discarded}`; a discarded entry of an open dirty buffer is written again on the next tick. Both emit `recoveryResolved {paths}` (sorted, only when not empty) with the restored or discarded paths (M1.15): a restored entry stays in the journal as the dirty buffer's own entry, so "journal empty" is not the signal; the settled paths are. `diskChanged` is true when the file's modification time is after `savedAt` or the file is gone.
- **Untrusted input:** entries are read with a 512 MiB cap, at most 1,000 per project. An entry that is not valid JSON of that shape, whose path escapes the project or does not match its file name is renamed to `<entry>.bad`, skipped, and reported once as `notification {level: warning, messageKey: "notification.recovery.corrupt", params: {file, reason}}`. A failed write is reported once until a write succeeds (`notification.recovery.writeFailed {path, reason}`); an unreadable journal directory gives `notification.recovery.unavailable {reason}`. Neither stops editing or opening.
- **UI:** `ui/src/components/recovery/` (store `recovery.ts`, `RecoveryDialog.vue`, mounted in `App.vue`). The list comes from `recoveryAvailable` and, because that event is not replayed after a page reload, from `recovery.list` on `projectOpened`. Restore all, Restore selected (the rest stay listed) and Discard always pass explicit paths; Escape closes and keeps the journal for the next open. `recoveryResolved` drops the settled paths from the list, so a restore or discard over the control channel closes the dialog when nothing is left (M1.15). The dialog is queued behind the other modals (see UI commands › Modal rule).
- **Limits:** two Lutra instances on the same project share one journal directory; `diskChanged` misses a disk change that happened before the last journal write.
### UI commands, palette and keymap (M1.8)
- **Registration:** the frontend calls `ui.registerCommands {commands: [{id, labelKey, menuPath?, defaultShortcut?}]}` when it starts (`ui/src/commands/store.ts`). A registration replaces the previous one, so a page reload registers again. The engine keeps them in `State::ui_commands` (`crates/engine/src/cmd/ui.rs`). It checks every entry and changes nothing on a bad one (`invalid_params`):
- ids have the `area.action` shape (ASCII alphanumeric parts), at most 128 bytes;
- an id may not be an engine command or listed twice;
- `labelKey` is not empty;
- texts are at most 256 bytes; at most 1,000 commands.
- **Listing:** `listCommands` returns one list in id order: engine commands and UI commands. `CommandInfo` has `ui: bool`; UI commands also carry `labelKey`, use it as `label` (the engine has no English for them) and are always `enabled` as far as the engine knows.
- **Running from outside:** `Engine::execute` on a UI command id queues `uiCommand {id, params}` and returns `null` (params are passed on unchanged). The desktop publishes the event to the window and to control subscribers like any other. The frontend runs the command, so `engine.execute palette.open` over the control channel opens the palette. A `uiCommand` the frontend cannot run (no handler, or disabled) becomes a warning toast.
- **Frontend:** `ui/src/commands/`:
- `uiCommands.ts` lists the UI commands: `editor.reveal` (no shortcut, M2.2), `find.open` `Mod+Alt+F` (M2.4), `menu.open` `Alt+M` (M3.9), `palette.open` `Mod+Shift+P`, `settings.open` `Mod+,`, `view.toggleProjectTree` `Mod+1`. Since M3.9 the user-facing ones carry a `menuPath`.
- `keymap.ts` parses Lutra notation and matches by key code (letters, digits and US punctuation by `code`, so Alt and Shift layout effects don't matter). It also formats shortcuts for display with catalog modifier names.
- `rank.ts` ranks for the palette.
- `store.ts` (Pinia `commands`) holds the merged list, the keymap, the handlers and the recent commands.
- **Handlers:** components supply behaviour with `provide(id, {run, enabled?})`:
- the palette provides `palette.open`;
- the main layout provides `view.toggleProjectTree`;
- the editor area provides `file.save`, `file.saveAll` and `buffer.close` with the active buffer as context (they replace the editor-only keymap of M1.6), and `editor.reveal` (M2.2).
- A UI command without a handler is disabled. The settings dialog provides `settings.open` (M1.9b).
- An engine command without a handler runs through `run(id, {})`.
- **Modal rule (M1.15, `ui/src/commands/modals.ts`):** at most one modal is open. The palette, the settings dialog and the close question are exclusive: each reports `opened(id, close)` / `closed(id)` to the Pinia `modals` store, and opening one closes the open one (the close question closes as Cancel; the store follows `editor.closePrompt`, so the editor has no code for it). Running any command but `palette.open` through `execute` (keyboard, palette, `uiCommand`) closes the palette first. The restore dialog is queued instead: hidden while an exclusive modal is open, shown again with its list intact when it closes. Reason: its offer must survive a palette or settings dialog opened by an agent, and closing it would only hide the journal until the next open.
- **Enabled state:** a handler's `enabled` decides, else the engine's. The list is refreshed on `projectOpened`/`projectClosed` and whenever the palette opens.
- **Keyboard:** one window `keydown` listener in the capture phase (works while CodeMirror or an input has focus). A matching shortcut is always swallowed; a disabled command does nothing. A failure raises `notification.command.failed`.
- **Palette** (`ui/src/components/palette/CommandPalette.vue`, mounted in `App.vue`):
- **Contents:** it offers UI commands and engine commands that have a menu path or a default shortcut. Protocol commands such as `buffer.edit` are left out.
- **Ranking:** labels are catalog text for UI commands and the engine's label otherwise. Tiers: prefix, word prefix, query spread over consecutive word starts, substring, in-order characters; the label or the id may match. Within a tier recent commands come first (in memory, 20, not `palette.open` itself), then shorter texts, then the label.
- **Keys:** arrow keys wrap, Enter runs an enabled row, Escape or a click outside closes.
- **Running:** the command runs after the palette closed and returned the focus.
- **Rows:** disabled rows are dimmed with `aria-disabled`.
- **Accessibility:** combobox with listbox and `aria-activedescendant`.
### App menu (M3.9)
- **Where:** `MainLayout.vue` has a slim header bar (28 px, `--lt-bg`, a `header` slot) whose default content is `ui/src/components/menu/AppMenu.vue`: a button with the Lucide `menu` icon top left.
- **Contents (`menu.ts`):** every command in the store's entries with a `menuPath` (engine and UI), grouped by the path's first segment. Groups in Lutra's order File, Edit, View, Go, Help (unknown groups before Help, empty ones hidden), group headings from the catalog (`menu.group.*`). Items follow a fixed id order, others sorted by label after them. A UI command shows its catalog label; an engine command shows the rest of its path (the engine has no catalog, and the path is written for menus), so `buffer.close` reads Close Tab. Deeper paths are flattened as `A › B`.
- **Paths:** File (`project.openDialog`, `file.save`, `file.saveAll`, `buffer.close` → `File/Close Tab`, `project.close`, `app.quit`), View (`palette.open`, `view.toggleProjectTree`, `view.toggleStructure`, `find.open`, `settings.open`), Go (`goto.fileOpen`, `goto.classOpen`, `goto.symbolOpen`), Help (`app.about`). Edit stays empty until there are edit commands; the terminal toggle gets `View/Terminal` when M3.6 lands (its id is already in the order list).
- **Opening:** the button (a second click closes) or `menu.open` (`Alt+M`, Lutra's own; also as `uiCommand`). It refreshes the enabled states and focuses the first item.
- **Keyboard:** WAI-ARIA menu with roving focus: arrows wrap, Home/End, Enter/Space runs, Escape or Tab closes, printable keys type ahead (500 ms buffer; one letter cycles through items with that initial). Disabled items are focusable, dimmed (`aria-disabled`) and do nothing.
- **Modal rule:** `menu` is an exclusive `ModalId`; the menu is a launcher like the palette: `commands/store.ts` › `execute` closes it for every command but `menu.open`, so a shortcut, a palette command or an agent's `uiCommand` never leaves it open. A chosen command runs after the menu closed and returned the focus.
- **Why a dropdown with headings instead of a menu bar:** one keyboard path (open, type, Enter) like the palette, no nested popups to manage, and it fits the slim header. A native macOS menu bar and a display-mode setting are follow-ups.
### Settings dialog (M1.9b)
- **Store:** `ui/src/stores/settings.ts` (Pinia `settings`, started by `App.vue`) loads `settings.list` and `settings.get`, reads both defensively (unknown types and malformed entries dropped, values must be scalars), changes values through `settings.set`/`settings.reset` and keeps a refused change's message per key. `settingsChanged` reloads the named keys with `settings.get {keys}` and drops their errors, so changes from the control channel or an agent show at once.
- **Text:** labels, descriptions and section names come from the catalog keys the engine sends (`settings.<key>.label`, `.description`, `settings.section.<id>`); enum values use `settings.<key>.value.<value in camelCase>`. A key the catalog lacks shows the setting key (or the raw value). These keys are in the catalog test's runtime list.
- **Font size:** `theme.ts` has `setTokenOverride(name, value)`: a value above the theme's that `applyTheme` keeps across theme switches. The store sets `--lt-font-size-editor` to `editor.fontSize` px; the editor reads only that token.
- **Dialog:** `ui/src/components/settings/SettingsDialog.vue` (mounted in `App.vue`) provides `settings.open` (`Mod+,`, palette, `uiCommand`). Sections on the left, the chosen section's settings on the right; enum → select, int → number field (min/max, applied when committed; text that is no whole number in range is refused in place with `settings.error.intRange`), bool → switch. The theme picker is the `appearance.theme` select; the engine answers with `themeChanged`.
- **Search** matches label, description, key and section name (every word, ignoring case); while it has text every match shows, grouped by section, and sections without matches are dimmed.
- **Reset to default** per setting, enabled while the value differs from the default.
- **Errors** show under the control (`role="alert"`, `aria-invalid`) and keep the typed text until the value changes.
- **Keyboard:** Escape or a click outside closes; Tab and Shift+Tab wrap inside the dialog, focus that leaves it is pulled back to the search field, and focus returns to where it was on close.
- No OK/Apply/Cancel: every change applies at once, as agents change settings through the same commands.
### Syntax (M2.1)
`crates/syntax` (L1, depends on `lutra-text` only) parses PHP with tree-sitter (`tree-sitter` 0.26, `tree-sitter-php` 0.25, both MIT; the grammar variant that accepts inline HTML around `<?php` tags). It has no engine types; M2.7 wires it to buffers and M2.5 builds the index on it.
- **API:** `Parser::new()?`, `parser.parse(&str) -> Tree` (never fails), `parser.reparse(&Tree, &[lutra_text::Edit]) -> Result<Tree, SyntaxError>`, `outline(&Tree) -> Vec<OutlineItem>`, `folding(&Tree) -> Vec<Range>`. `Tree` carries the text it was parsed from (a `lutra_text::Buffer`, cheap to clone) plus `truncated()` and `has_errors()`; that is why `outline` takes no separate text argument (the contract sketch had `outline(tree, text)`): a tree and a mismatching text can't be combined.
- **Reparse:** the edit batch has `Buffer::apply` semantics (ranges against the old text, any order). It is mapped to one tree-sitter `InputEdit` covering the smallest start to the largest end, with points (row, byte column, rows by `\n` as tree-sitter counts them) computed from the old and new text. Proptests check that a reparse gives the same tree, outline and folding as a fresh parse whenever the edited text is error-free, and that an undo round trip ends at the original tree. On broken code tree-sitter's error recovery may legitimately differ between an incremental and a fresh parse; the engine can reparse from scratch when it wants a canonical tree (for example on save).
- **Outline:** `OutlineItem {kind, name, detail, range, selection_range, children}`; `OutlineKind::as_str()` gives the contract names (`namespace`, `class`, …, `enumCase`). Braced and unbraced namespaces (an unbraced one owns everything up to the next namespace statement), promoted constructor parameters as properties after the constructor, enum cases with backing values, multi-element `const`/property declarations as one item each, attributes inside the declaration range. Anonymous classes are classes named `class@anonymous` (`OutlineItem::is_anonymous`, for the index to skip). Function, method and closure bodies are not searched; statements at file level are (`if (!function_exists(…)) { function … }`). Error nodes are transparent and nameless declarations are dropped. The search descends at most 96 levels.
- **Folding:** multi-line brace blocks (class-like bodies, function and control bodies, `switch`/`match`), arrays, comments, heredoc/nowdoc, `use A\{…}` groups and runs of two or more `use` statements; ranges include the delimiters. The walk is iterative and skips the inside of single-line nodes.
- **Positions:** 0-based line and UTF-16 column through `Buffer::offset_to_position` (about 1 µs per conversion on a 1 MB rope; the parse dominates).
- **Limits:** texts over 8 MiB (`MAX_PARSE_BYTES`) are not parsed (`truncated`, empty outline and folding). The grammar's identifier rule covers the Basic Multilingual Plane only: PHP accepts any byte ≥ 0x80 in names, so an identifier with an emoji is an error node in tree-sitter.
- **Timing** (release, Windows 11, MSVC `/O2`, generated 1 MB file, best of 5, other builds running in parallel, measured): full parse 364–553 ms, reparse after one inserted character 7–11 ms, outline 70–133 ms, folding 61–73 ms (143 ms before skipping single-line nodes). The full parse misses the 50 ms target by about 8×: tree-sitter-php runs at roughly 2–3 MB/s here. Consequences: parse off the engine lock and debounce (M2.7), parse files in parallel for the index (M2.5); `cargo test --release -p lutra-syntax --test perf -- --ignored --nocapture` repeats the measurement.
### Search (M2.3)
- `crates/search` (L2) is the library: `Search::new(&Query)` compiles a literal or regex (`grep-regex`; empty, invalid, oversized or newline-matching patterns and bad globs fail up front), `run` walks the project with the `ignore` crate's parallel walker (at most 8 threads) and searches each file with `grep-searcher`; `spawn` runs it on a thread of its own and delivers `SearchEvent::File` per file with matches, then one `SearchEvent::Done`. A `CancelToken` stops it between files and lines.
- Which files: the same rules as `lutra-vfs` (`.gitignore`, `.ignore`, `.git/info/exclude`, global excludes, applied without a git repository; ignore files above the root are not read). `.git` and `node_modules` are skipped, the root's `vendor/` is searched as library code even when an ignore file lists it (it is walked as a second root, so its own nested ignore files still apply), dot files are searched, symbolic links are not followed. Include globs keep matching files, exclude globs drop files and whole directories; a glob without `/` matches the name, one with `/` the project-relative path. Files over 8 MiB, binary files (a NUL byte) and unreadable files are skipped silently. The library does not depend on `lutra-vfs`: the walker is configured to the same rules instead, because the VFS reads rules per directory listing and the walker needs them per walk.
- Results: positions are 0-based, columns and lengths in UTF-16 code units, lines end at `
` (a preceding `
` is not part of the line; a lone `
` is not a line break here, unlike in `lutra-text`). Invalid UTF-8 is replaced before matching. The preview is the line, or a window of 300 characters starting up to 80 characters before the match. Files arrive in no fixed order. The cap (`maxResults`, default 10,000, at most 100,000) counts matches; `truncated` is set only when a match was left out.
- Engine: `search.find {query, regex?, caseSensitive?, wholeWord?, include?, exclude?, maxResults?}` (disabled without a project) snapshots the text of every dirty buffer as an overlay (searched instead of the file; only for files the walk visits), starts the search and returns `{searchId}` at once. Searches run outside the engine lock. Each search's results wait in its own channel in `State::searches`; `Engine::pump_vfs` drains them (`cmd::search::pump`) into `searchResults` events (one per file) and a final `searchDone`. Hosts already publish the pump's events, so the desktop (pump every 100 ms) and the control channel get them without new plumbing; there are at most 10 batches per second and at most 500 `searchResults` per pump (`MAX_RESULTS_PER_PUMP`), which keeps a control subscriber's queue of 4096 events from overflowing; the rest wait for the next pump. `search.cancel {searchId}` returns `{cancelled}` (false once the search ended) and the search still ends with `searchDone {cancelled: true}`. Starting a search does not cancel older ones. A search whose project is no longer open is cancelled by the next pump, its remaining results are dropped and it ends with `cancelled: true`.
- Measured (release, Windows 11, 16 threads, generated 20,006-file tree from `lutra_testkit::generate_search_tree`, other builds running): common literal `function` first result 10–43 ms, capped at 10,000 matches after 112–209 ms; a rare literal (full walk, 376 files) first result 17–22 ms, total 0.66–1.43 s (the first round cold); `function` with the 100,000 cap 0.53 s. Through the engine add up to one pump interval (100 ms) before results reach clients. Live check over the control channel against the running app (debug build, 5,900-file project with a dirty buffer): `search.find` answered in 4.5 ms, first `searchResults` line after 55 ms, `searchDone` after 386 ms; vendor hits present, `var/`, `node_modules` and the binary file absent; the dirty buffer's text was found; `search.cancel` ended a search with `cancelled: true`.
### Find tool window (M2.4)
- **Bottom panel:** `ui/src/components/layout/BottomPanel.vue`, under the editor and the left tool window, above the status bar: header with title, collapse/expand and close; a splitter on the top edge (pointer, or Up/Down with Shift for larger steps; 80–900 px, at most 75 % of the window). Height is view state of `MainLayout.vue`; later bottom tool windows (Problems, Terminal) reuse it. Only Find lives there today, so the panel shows while the Find store's `visible` is set; a tab strip comes with the second tool window.
- **Store:** `ui/src/stores/find.ts` (Pinia `find`, started by the main layout) holds the query, the options (`regex`, `caseSensitive`, `wholeWord`, include/exclude as comma-separated globs), the current `searchId`, the files with their matches (a `shallowRef`, replaced per event, kept sorted by path because files arrive in no fixed order), the `searchDone` summary and an inline error.
- **One search at a time:** a new search cancels the running one with `search.cancel` (the engine does not); results of other searches are ignored, and the answer of a search overtaken by a newer one is dropped and cancelled.
- **Event race:** events and the `search.find` answer travel on different channels (Tauri event vs. invoke response), and the pump may publish results before the answer arrives. While `search.find` has not answered, search events are held (at most 5,000) and replayed for the returned id.
- **Errors:** a refused search (`invalid_params` for a bad regex or glob) shows its message under the fields (`role="alert"`, `aria-invalid`), not as a toast.
- **Untrusted fields:** non-integer positions or a non-string preview drop the match; the highlight is clamped into the preview. `projectOpened`/`projectClosed` clear everything.
- **Window:** `ui/src/components/find/FindToolWindow.vue`. Enter in a field searches, a toggle repeats the last search, cancel while running. The status line shows counts while streaming, then matches, files and elapsed time, "No matches" or "Cancelled"; a truncated search adds a hint. Results are a listbox with `aria-activedescendant`: file headers (name, directory, count) and one option per match (1-based line number, preview without leading indentation, the match in a `<mark>` with `--lt-editor-match-bg`). Down in a field enters the list; Up/Down, Page Up/Down (10), Home, End move; Enter or a click runs `editor.reveal {path, line, column}` through the command store. Every match is rendered; with the default cap of 10,000 that stays a plain DOM list (virtual scrolling is a follow-up if it shows up as slow).
- **`find.open`** (UI command, `Mod+Alt+F`, Lutra's own; provided by `MainLayout.vue`, so it works before the panel exists): shows and expands the panel and focuses and selects the query field. Without params it takes the main selection (single line, at most 1,000 characters) or else the word at the cursor of the active editor state (`prefillFrom`), and waits for Enter. With a string `query` (and optional `regex`, `caseSensitive`, `wholeWord`, `include`, `exclude`), as an agent sends it through `uiCommand`, it searches at once. The panel is a tool window, not a modal: it is not part of the modal rule.
### Index and go-to (M2.5)
- `crates/index` (L2, depends on `lutra-syntax`, `lutra-text`, `ignore` and `nucleo-matcher` 0.3, MPL-2.0 as a separate crate, built without its `unicode-segmentation` feature) lists every file of the project and the declarations of its PHP files. A `Symbol` is `{name, fqn, kind, container, line, column}`: names as written (`$id` for properties), FQNs without a leading `\` (`App\Models\User`, members `App\Models\User::find`), `container` the declaring class-like FQN, the position of the name (0-based line, UTF-16 column) from the outline's `selectionRange`. Namespaces only prefix FQNs; anonymous classes and their members are skipped; at most 20,000 symbols per file.
- Which files: the walk is configured to the same rules as `crates/search` (ignore files without a git repository, `.git` and `node_modules` skipped, the root's `vendor/` walked as a second root even when gitignored and marked `library`, dot files listed, links not followed). Every file is listed for Go to File; only `.php` files up to 2 MiB (`MAX_PARSE_BYTES`) are parsed, larger ones are listed without symbols. At most 200,000 files (`MAX_FILES`); further files are left out (`Summary::capped`).
- Build: `build`/`spawn_build` walk first (parallel `ignore` walker), report non-PHP files at once, then parse PHP files on `default_threads()` workers (cores − 1, at most 32), each with its own `Parser` and one file in memory, taking files from a shared counter: project files before library files, larger files first in each group. Workers send `Update::Files` batches of 64 files (or every 100 ms) and `Update::Progress {done, total}`; the build ends with `Update::Ready(Summary)`. A panic while parsing a file (a parser bug) is caught per file: the file is listed without symbols and the worker gets a fresh parser. Reads are capped, invalid UTF-8 is replaced, a BOM dropped.
- Incremental: `Updater` is one background thread taking `Job::File {path, text?}` (re-index from a buffer's text, or re-read from disk; a file no longer found or now excluded is reported `Removed`) and `Job::Dir {path}` (drop the subtree, list it again with a walk restricted to the path, so ignore files on the way still apply). Jobs queued while it works are coalesced to the last per path, so a burst of keystrokes parses a buffer once.
- Queries: `Index` (a `BTreeMap` by path, so a directory's files drop with one range) answers `find_files`, `find_classes` and `find_symbols`. Every whitespace-separated query word must match fuzzily (fzf-style scoring, smart case, no other special syntax); queries are capped at 256 characters and 1,000 results. Files: a query without `/` (a `\` counts as `/`) is matched against the file name first with double weight, else the path; match ranges are merged UTF-16 ranges in the path. Classes: by name, by FQN when the query has a `\`. Symbols: by name; `Class::member` matches the container's short name (FQN with a `\`) and the member separately, `Class::` lists members. Order: project before library, higher score, shorter name, byte order. Indexes over 20,000 files plus symbols are scanned on `default_threads()` threads, each keeping its own best hits.
- Engine (`cmd/goto.rs`): `State::index` holds the index of the open project. `goto::sync` runs on every `Engine::pump_vfs` and before every index command: it starts the build and the updater when a project is open and the index belongs to another root (or none), drops them without a project (dropping cancels the threads; `project.close` also drops it at once), merges up to 4,096 updates, emits `indexProgress {done, total}` at most every 250 ms while building and `indexReady {files, symbols, elapsedMs}` at the end, and re-indexes buffers. The engine lock is held only for inserts and queries; walking and parsing never run under it. Updater results that arrive while the build runs mark their paths, and later build results for those paths are ignored, so a buffer edit or a disk change is never overwritten by the stale build.
- Incremental sources: `workspace::pump` hands the VFS events to `goto::note_disk_changes` (removed paths dropped at once, created or modified files re-read, created directories and rename targets rescanned); the watcher is not recursive, so only watched directories (root, listed, pinned) report changes. A buffer whose version changed is re-indexed from its text when its path is in the index (or the build still runs); while it is dirty, disk changes for it are ignored; closing it dirty re-reads the file.
- Commands: `index.status` → `{state: "idle"|"indexing", files, symbols}` (idle and zero without a project). `goto.file {query, limit?}` → `{items: [{path, score, matches: [[start, end]], library}], indexing}` (`library` added by M2.6, PM decision: vendor files, as in class and symbol items); `goto.class` → `{items: [{name, fqn, kind, path, line, column, library}], indexing}`; `goto.symbol` → the same plus `container` (FQN or `null`), for functions, methods, properties, constants and enum cases. `limit` defaults to 50 (at most 1,000); an empty query returns no items. The go-to commands are disabled without a project; none has a menu path or shortcut; the popup's UI commands do (below).
- Measured (release, Windows 11, 8 cores / 16 threads, 15 workers, generated `lutra_testkit::generate_php_project(20_000)`: 20,001 files, 19,000 PHP of ~5 KB, 87.7 MB, 324,080 symbols): build 3.9–4.2 s on an idle machine (target < 5 s met), 4.6–5.7 s while other agents' builds ran; the walk takes 25–35 ms and the first batch arrives after ~30 ms, so the parse dominates (~21 MB/s over 15 workers, ~1.4 MB/s per worker). Queries on the full index, median of 7: `goto.class` 2–4 ms, `goto.symbol` 7–11 ms, `Class::member` 11–12 ms, `goto.file` 2 ms (single-threaded before the parallel scan: `goto.symbol` 72–100 ms). `cargo test --release -p lutra-index --test perf -- --ignored --nocapture` repeats it.
- Live check over the control channel against the running app (debug build, port 7825, generated 6,002-file project with gitignored `vendor/` and `var/`): `index.status` answered `indexing` right after `project.open`, a go-to query during the build returned `indexing: true`, 25 `indexProgress` events at least 251 ms apart, `indexReady` after 8.2 s (debug build: the tree-sitter C code and the workers are unoptimised) with 6,002 files and 62,000 symbols; `goto.file`, `goto.class` (vendor marked `library`), `goto.symbol` with `Class::member` answered in 5–25 ms; the gitignored `var/` class was absent; a `buffer.edit` renaming a class and a file created on disk were found within a second; `project.close` reset the status to idle.
### Structure (M2.7)
- **Engine:** `crates/engine/src/cmd/syntax.rs` keeps a syntax tree per open PHP buffer (`.php`, `.phtml`, `.inc`) in `State::syntax`. Nothing is parsed under the engine lock. `buffer.edit` records each applied batch (byte-offset `lutra_text` edits, at most 64 batches or 8 MiB of inserted text per buffer, beyond that the record is dropped). `Engine::pump_vfs` (`cmd::syntax::pump`) adds new buffers, drops closed ones, notices version changes that did not come through `buffer.edit` (reload from disk, restore), and once a buffer has been quiet for 200 ms (a new buffer at once) hands its text snapshot (a rope clone), the last tree and the recorded batches to one worker thread (`lutra-syntax`, its own `Parser`, created lazily). At most one parse per buffer is in flight. The worker reparses batch by batch, checks that the result's text equals the snapshot, otherwise parses from scratch, builds the outline as JSON and compares it with the previous one. The next pump stores tree and outline and queues `outlineChanged {id}` if the outline changed, at most once per 200 ms per buffer; the first outline is always announced. Replaced trees and outlines go back to the worker to be freed (dropping a 1 MB file's outline took 60–80 ms on the lock before). A panic in a parse is caught on the worker (the parser is recreated, that version is not retried); a vanished worker is restarted by the next pump.
- **`syntax.outline {id}`** answers from the stored outline: `{items, truncated, version}`, items `{kind, name, detail?, range, selectionRange, children}` with `{start, end}` of `{line, column}` (0-based, UTF-16). `version` is the buffer version the items describe, `null` before the first parse finished. `version` is part of the C3 contract (added by M2.7, accepted by the PM on 2026-10-17): it lets an agent or the UI tell "not parsed yet" from "no declarations"; non-PHP buffers have no items.
- **UI:** `MainLayout.vue` has a left stripe (a vertical tab list, Lucide `FolderTree` and `ListTree`) with Project and Structure; the left tool window shows one of them, both stay mounted while it is open (`v-show`). Clicking the shown one's tab or running its command again hides the window. UI commands `view.toggleProjectTree` (`Mod+1`) and `view.toggleStructure` (`Mod+2`, Lutra's own). `ui/src/components/structure/structure.ts` (Pinia `structure`, started by the window) follows the editor's active tab and `outlineChanged` for that buffer, drops answers overtaken by a newer request, validates the untrusted outline (depth cap 64, at most 50,000 items) and remembers collapsed nodes per buffer by the path of kinds and names. `StructureToolWindow.vue` is a WAI-ARIA tree: kind icons from Lucide coloured with `--lt-syntax-*` tokens, the name and the signature; arrows, Home/End, Left/Right fold, Enter or a click jumps through `editor.reveal` to the start of the name; empty states for no file, no declarations, still parsing and too large.
- **Measured** (release, Windows 11, generated 1 MB PHP file with 16,281 outline items, other builds running): `buffer.edit` under the lock at most 0.07–0.25 ms, `pump_vfs` at most 3.8 ms; first outline 0.9–1.3 s after `file.open` (full parse ~0.75 s plus outline); edit to `outlineChanged` 0.43–0.76 s (200 ms debounce, incremental reparse 9–14 ms, outline with JSON 0.2–0.3 s, pump interval). `syntax.outline` itself takes 82 ms on that file, because the engine deep-copies the stored JSON into the command result; typing is not blocked by it (the editor syncs asynchronously), but the engine lock is. Typical files (10–50 KB) are a few milliseconds end to end. `cargo test --release -p lutra-engine --test syntax -- --ignored --nocapture` repeats it.
### Go-to popup (M2.6)
- `ui/src/components/goto/GotoPopup.vue` (mounted in `App.vue`) with the state in `ui/src/stores/goto.ts`. One popup, three modes (`file`, `class`, `symbol`) as tabs; Tab / Shift+Tab or a click switches the mode and re-runs the same text in it.
- UI commands `goto.fileOpen` (`Mod+P`), `goto.classOpen` (`Mod+Alt+C`), `goto.symbolOpen` (`Mod+T`), each with an optional `{query}` so an agent can open the popup on a query over `uiCommand`; enabled only while a project is open. The shortcuts are Lutra's own.
- Live query: typing waits 60 ms after the last keystroke, then runs the mode's `goto.*` with `limit: 100`; every query takes a sequence number, and an answer that is not the newest is dropped (also after the popup closed). Mode switches and a `{query}` from the params query at once.
- Rows: file items split `matches` at the file name (name marked in the label, directory in the second column); class and symbol answers carry no ranges, so the popup marks the query's characters in order in the name (after `::` for `Class::member`). The second column is the namespace, or the container for members. `library: true` rows are dimmed and labelled. Untrusted fields are checked; malformed items and ranges are dropped or clamped.
- Indexing: `indexing: true` shows a hint with the latest `indexProgress {done, total}`; `indexReady` re-runs the open query.
- Opening: Enter or a click closes the popup (focus goes back) and runs `editor.reveal` with `{path}` for files (the file's cursor stays) or `{path, line, column}` for symbols. The popup is an exclusive modal (`ModalId` `goto` in `commands/modals.ts`). Like the palette it is a launcher: running any command other than the three open commands closes it (`commands/store.ts` › `execute`), so an agent's `editor.reveal` never leaves it open.
- Live check (debug build, bundled UI, port 7826, temp project with 34 files and a `vendor/` folder): `goto.fileOpen {query: "user"}` listed the two project files before the vendor one with its `library` label; `goto.classOpen {query: "usr"}` and `goto.symbolOpen {query: "User::find"}` switched the tab with marks shown; `palette.open` then `goto.fileOpen` left only the popup; an `editor.reveal` of the symbol item closed the popup and put the cursor on `find`. `goto.file` answered in < 1 ms over the control channel. Enter and clicks cannot be sent over the control channel; Vitest covers them.
### LSP client (M3.2)
- `crates/lsp` (L3; the client depends on `lutra-text` and `serde_json` only, the toolchain module of M3.1 adds `lutra-vfs`, `ureq`, `rustls`, `ring` and `rustls-native-certs`) is a library; the engine wiring is M3.3. `Server::spawn(command, args, root, ServerOptions)` starts the process in `root` with piped stdio (on Windows with `CREATE_NO_WINDOW`) and returns at once with the server and a bounded `Receiver<ServerEvent>` (capacity 4096; overflow drops and counts, `dropped_events()`). A spawn error (missing executable, relative root) is returned synchronously.
- Threads, no async runtime: per process a writer (the only one touching stdin, fed by a channel), a reader (frames from stdout), a stderr drain; per server a supervisor that watches the process, expires timeouts every 20 ms, restarts and shuts down. A server is a few blocking pipes and the engine pump is synchronous, so threads with channels are simpler than pulling an executor into L3. All writes happen under the client's one mutex, so messages leave in the order the state changed; callbacks always run outside it (a panicking callback is caught).
- Framing (`jsonrpc`): `Content-Length` headers (case-insensitive, other headers ignored, header lines capped at 1 KiB and 16 per frame), bodies capped at 32 MiB (`MAX_MESSAGE_BYTES`; an oversized body is read and discarded without buffering). A malformed header block, invalid JSON or a message that is neither request, response nor notification becomes `ServerEvent::ProtocolError(reason)` (the log line) and the reader carries on with the next frame. serde_json's recursion limit bounds nesting. Proptests: message round trips, random bytes, header-like noise, recovery after bad frames, random JSON bodies.
- Initialize: `initialize` (processId, clientInfo, rootUri/rootPath, one workspace folder, `initializationOptions` from the options) with the capabilities of `client_capabilities()`: incremental sync with `didSave`, completion (no snippets, markdown/plain documentation, context), hover, signatureHelp, definition (links), references, rename with prepare, `publishDiagnostics` with versions, `workspace/configuration`, workspace folders, work-done progress, `positionEncodings: ["utf-16"]`; no dynamic registration and no `applyEdit`. Then `initialized`, every open document is (re)opened, queued requests are sent, and the status becomes `Ready`. A server choosing another encoding is logged. `initialize` times out after 30 s; a failed or late `initialize` counts as a crash.
- Requests: `request`/`request_timeout` return a `RequestHandle` (`wait`, `wait_timeout`, `try_result`, `cancel`); `request_with` takes a callback instead. Typed helpers: `completion(path, position, trigger)`, `hover`, `signature_help`, `definition`, `references(..., include_declaration)`, `prepare_rename`, `rename(..., new_name)`; results are raw JSON, with parsers in `types` for `Location::list_from_json`, `WorkspaceEdit::from_json` (documentChanges or changes; resource operations flagged, malformed edits mark it `incomplete`) and `PublishDiagnostics`. Requests issued before `Ready` are queued (the timeout runs from the call). Every request resolves exactly once: result, `Response` error, `Timeout` (default 10 s; `$/cancelRequest` is sent), `Cancelled` (also sends `$/cancelRequest`), `ServerCrashed`, or `Stopped`. At most 1024 requests are pending.
- Server requests: `workspace/configuration` gets one `null` per item (at most 1000); `window/workDoneProgress/create` and capability (un)registration are acknowledged with `null`; `window/showMessageRequest` is shown as a `ShowMessage` event and answered `null`; `workspace/workspaceFolders` returns the root; everything else gets `MethodNotFound`. Notifications become `Diagnostics`, `LogMessage`, `ShowMessage`, `Progress` or the generic `Notification`; stderr lines become `Stderr` (4 KiB cap).
- Supervision: a process exit, a failed `initialize` or a broken watch is a crash. Requests sent to that process fail with `ServerCrashed`, queued ones wait. The status goes to `Restarting {crashes, delay, reason}` with delays 1 s, 2 s, 4 s ... capped at 30 s (doubling per crash in the window); the fifth crash within 2 min ends in `Failed {message}` and fails everything with `Stopped`. All of it is `RestartPolicy` in the options (the tests use milliseconds). After a restart every open document is reopened with its current text and version.
- Document sync: the client keeps each open document in a `lutra_text::Buffer`. `did_open(path, language_id, text)` (version 1), `did_change(path, &[Edit])` with byte-range edits as in `Buffer::apply`, `did_change_full(path, text)`, `did_save(path)` (with the text if the server asks), `did_close(path)`; each change bumps the version and returns it. Edits become UTF-16 content changes (`content_changes`): touching edits are merged and the changes are sent from the end of the text to the start, so sequential application on the server equals the atomic batch, also across CRLF and surrogate pairs (property-tested). The server's `textDocumentSync` decides incremental, full or no `didChange`. Edits that do not fit the client's copy fail with `LspError::Text` and leave it unchanged. Document operations never fail because of the server's state: before `Ready` or while restarting they only update the copy.
- Shutdown: `shutdown(self)` sends `shutdown` (waits up to 2 s), `exit`, kills after 1 s, fails what is pending with `Stopped` and reports `Stopped`; it blocks for up to about 3 s, so callers run it off the engine lock. Dropping the `Server` requests the same stop in the background.
- URIs (`uri`): `path_to_uri` percent-encodes everything except unreserved characters, `/` and a drive colon (`file:///C:/a%20b.php`, UNC as `file://host/share`); `uri_to_path` accepts escapes in any case, an encoded drive colon and `localhost`, and upper-cases the drive letter; bad escapes, NUL and other schemes give `None`.
- Tests: the fake server `src/bin/lutra-lsp-fake.rs` (a test fixture, started via `CARGO_BIN_EXE_lutra-lsp-fake`) covers initialize, server requests, log and stderr, typed requests and errors, queueing before ready, timeout and cancel with `$/cancelRequest`, incremental and full sync (the fake applies the changes and publishes the text as a diagnostic), malformed output, crash, restart and reopen, initialize errors, giving up with the backoff sequence, shutdown and spawn errors (13 tests, about 0.5 s). `real_phpactor` is ignored and runs with `LUTRA_PHPACTOR` (path to `phpactor.phar`, `LUTRA_PHP` for PHP); it was not run in M3.2 (no Phpactor on the dev machine yet; M3.1 downloads it).
### Toolchain (M3.1)
- **Owner decision D15:** Lutra downloads the Phpactor PHAR itself; PHP is the user's (found through `php.executable` or `PATH`). Library code lives in `crates/lsp/src/toolchain/` (L3), the engine side in `crates/engine/src/cmd/toolchain.rs`.
- **Network access:** downloading the pinned Phpactor is the only network access in Lutra. It is minimal (one GET of one URL, following at most 5 redirects, HTTPS only, also on redirects), visible (a notification when it starts, ends or fails) and verifiable (pinned version, URL and SHA-256 as constants in `lutra_lsp::toolchain::phpactor`; the body is checked before it is written). `phpactor.autoDownload: false` turns the automatic download off, `phpactor.path` replaces the managed PHAR. An engine downloads nothing until the host calls `Engine::allow_downloads()`; the desktop does, tests never do, so no test reaches the network (download tests use a local HTTP server on 127.0.0.1).
- **Pin:** phpactor `2026.06.25.0`, SHA-256 `832510fe4cdaf27ba056b8cb66a779d18352585c74fdaac54e45a37b589559e9` (4,474,352 bytes, equal to GitHub's published asset digest). The newer releases (from 2026.06.23.0 on, latest 2026.10.07.0) require `ext-posix`, which PHP on Windows does not have; they refuse to start there. The pin needs PHP ≥ 8.2 (`"php": "^8.2"`), not 8.1 as first planned, so `php::MIN_VERSION` is 8.2.0. Updating the pin means changing version, URL, hash and size together after checking the PHAR on all three platforms.
- **HTTP client:** `ureq` 3 with `rustls` (the `ring` provider) and the operating system's trusted roots loaded with `rustls-native-certs` (Windows store, macOS keychain, Linux files or `SSL_CERT_FILE`). `rustls-platform-verifier` and ureq's default `webpki-roots` were rejected: both pull a CDLA-Permissive-2.0 crate (`webpki-root-certs` / `webpki-roots`), outside the licence allow list. Proxies come from `HTTPS_PROXY`/`ALL_PROXY`/`NO_PROXY`. Timeouts: 15 s connect, 300 s per attempt.
- **Download:** `download::install` reads the body into memory with a cap of 32 MiB (Content-Length checked first, then the bytes read), compares its SHA-256 with the pin and only then writes `<data_dir>/tools/phpactor/<version>/phpactor.phar` with `lutra_vfs::write_atomic`. A mismatch discards the body and leaves an existing file untouched; nothing unverified ever lies at the target path. `install_with_retry` retries network errors, 5xx, 408 and 429 up to 4 attempts with 2 s, 4 s, 8 s backoff; a mismatch, an oversized body and other client errors are final. A managed PHAR that no longer matches its hash counts as missing and is downloaded again.
- **PHP detection:** `php::detect` resolves the setting (a path, or a bare name looked up in `PATH`; empty means `php`, on Windows `php.exe`, `php.bat`, `php.cmd`), runs `php -v` without a console window, with a 5 s timeout (killed after it) and at most 64 KiB of output read, and parses the first line starting with `PHP <major>.<minor>[.<patch>]` (suffixes such as `-dev` or `-1ubuntu1` are ignored; property-tested with random bytes).
- **Engine:** settings `php.executable` (string, default `""`), `phpactor.path` (string, default `""`) and `phpactor.autoDownload` (bool, default `true`), section `php`; `settings.list` now has the types `bool` and `string` (the settings dialog shows bool switches; a text control for string settings is a UI follow-up). One worker thread (`lutra-toolchain`) runs checks and the download; commands and the pump only queue jobs (merged while it works, the strongest mode wins), and its reports reach the state through `Engine::pump_vfs` (`cmd::toolchain::pump`), like search results. Jobs start with the first `toolchain.status`, when a project opens (a download if the project has PHP files: a root `composer.json` or a `.php`/`.phtml`/`.inc` file within 6 levels, at most 20,000 entries, skipping `vendor`, `node_modules`, hidden and cache directories; PHP is usable; Phpactor is missing; auto-download is on), when one of the three settings changes after the first check, and with `toolchain.downloadPhpactor` (also with auto-download off; `failed` if the host allows no downloads).
- **Commands and event:** `toolchain.status` → `{php: {found, path, version, error?}, phpactor: {state: missing|downloading|ready|failed|disabled, path?, version?, error?}}` as last checked (the first call starts a check); `toolchain.downloadPhpactor` → `{started}`; event `toolchainChanged` with the same shape whenever it changes. A `phpactor.path` PHAR is ready if it is a file, with no version and no hash check (the user chose it).
- **Notifications:** `notification.toolchain.phpMissing {reason, min}` (warning, when the PHP result changes to unusable), `notification.toolchain.downloadStarted {version}` and `notification.toolchain.downloadDone {version, seconds}` (info), `notification.toolchain.downloadFailed {version, reason}` (error).
- **Live check** (debug build, bundled UI, port 7931, Windows 11, PHP 8.4.24 from WinGet, a temp project with one PHP file, empty data directory): `project.open` → PHP found after 0.15 s, `downloadStarted` after 0.35 s, the real download from GitHub plus SHA-256 check took 2.8 s (notification to notification, measured), `toolchain.status` then `ready` with `<data_dir>/tools/phpactor/2026.06.25.0/phpactor.phar`, whose hash on disk equals the pin. A second run through `toolchain.downloadPhpactor` after deleting the PHAR took 0.3 s; both toasts showed in the window.
## Decisions (M0)
| Question | Decision | Why |
|---|---|---|
| Highlighting | A Lezer grammar (`@lezer/php`, MIT) in CodeMirror highlights instantly on the UI thread. tree-sitter in `crates/syntax` stays the structural source (outline, folding, index) and later adds semantic tokens on top. | The keystroke-to-highlight budget (< 16 ms) leaves no room for an IPC round trip per keystroke; Lezer is incremental inside CodeMirror. tree-sitter gives the core one parser for every structural feature. |
| Git library | `gix` (MIT OR Apache-2.0) for reading: status, log, diff, blame, refs. Writes the library doesn't cover well (push, pull, rebase, merge, hooks, signing) run the user's `git` executable. `git2`/libgit2 is not used. | gix is pure Rust and permissively licensed; libgit2 is GPL-2.0 with a linking exception, outside the permitted licences. Shelling out for writes keeps the user's hooks, credential helpers and config working. |
| Terminal | `portable-pty` (MIT) in the new L3 crate `crates/terminal`; xterm.js (MIT) renders in the frontend. Output is streamed as events, input goes through commands. | ConPTY on Windows and Unix PTYs behind one API; xterm.js is the standard web terminal. A separate crate keeps PTY code out of the engine. |
| Text buffer | `ropey` (MIT) in `crates/text`. | Mature rope with line and UTF-16 helpers. |
| Clippy panic lints | `unwrap_used`, `expect_used`, `panic`, `unreachable`, `todo`, `unimplemented`, `indexing_slicing`, `string_slice` are denied workspace-wide; `clippy.toml` allows them in `#[test]`/`#[cfg(test)]`; integration tests in `tests/` and `testkit` allow them at crate level. `missing_docs` is denied too, to back the doc-comment code style. `unsafe_code` is denied; a crate that needs it allows it locally with a doc comment saying why. | AGENTS.md › Never crash. |
| Desktop dev mode | Plain `cargo build`/`cargo run -p lutra-desktop` is a Tauri dev build that loads the Vite dev server. `cargo xtask dev [-- ARGS]` starts both. A self-contained build embeds `ui/dist` through the `bundled-ui` feature. | Keeps `cargo build --workspace` independent of the frontend build. |
| App identifier | `dev.lutra.desktop` is a placeholder. The final reverse-DNS identifier depends on the project's domain and hosting, which are the owner's decision (execution plan §4); bundling stays off until then. | Tauri requires an identifier to build. |
| App icon | `apps/lutra-desktop/build.rs` downscales the owner's master `assets/app-icon/icon.png` (720 px, see ASSETS.md) with an area-averaging box filter into the gitignored `apps/lutra-desktop/icons/`: `icon.png` (256 px window icon) and a multi-size `icon.ico` (16, 32, 48, 64, 128, 256 px, PNG entries). If the master is missing or unreadable, the build prints a cargo warning and uses the placeholder generated in code (rounded otter-brown square with a pale stone). | The icon is the owner's (M1.14); decoding uses the `png` build dependency already present, so no new dependency. The fallback keeps a checkout without the asset buildable and never fails the build over an icon. |
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-19 | minor | M3.9: app menu (header bar, `menu.open`, grouping by `menuPath`, launcher under the modal rule); menu paths for user commands |
| 2026-10-18 | minor | M3.1: toolchain (PHP detection, pinned Phpactor download with SHA-256 check, network access note, D15), `toolchain.status`/`toolchain.downloadPhpactor`, `toolchainChanged`, bool and string settings |
| 2026-10-18 | minor | M3.2: LSP client library (`crates/lsp`: framing, supervision and restart, initialize, requests with timeout and cancel, server requests, document sync, fake server tests) |
| 2026-10-17 | minor | M3.7: `lutra` CLI, single instance, rendezvous file and token listener, `app.auth`/`app.focus`, CLI to L6 |
| 2026-10-17 | minor | M2.6: go-to popup (store, debounce and stale drop, modes, `editor.reveal`), `library` on `goto.file` items |
| 2026-10-17 | minor | M2.7: per-buffer syntax tree off the engine lock, `syntax.outline`, `outlineChanged`, left stripe, Structure tool window |
| 2026-10-17 | minor | M2.5: symbol index (`crates/index`: parallel build, updater, fuzzy queries), `index.status`, `goto.file`/`goto.class`/`goto.symbol`, `indexProgress`/`indexReady` via the pump, timing |
| 2026-10-17 | minor | M2.4: bottom panel, Find tool window (store, event race, one search at a time), `find.open` |
| 2026-10-16 | minor | M2.2: highlighting by file extension (Lezer), `--lt-syntax-*` tokens and classes, `editor.reveal`, keystroke-to-highlight measurement |
| 2026-10-16 | minor | M2.3: find in files backend (`crates/search`, `search.find`/`search.cancel`, `searchResults`/`searchDone` via the pump) |
| 2026-10-16 | minor | M2.1: syntax layer (tree-sitter PHP parser, incremental reparse, outline, folding, size cap, timing) |
| 2026-10-16 | minor | M1.15: modal rule (one modal at a time, restore dialog queued), `recoveryResolved` event |
| 2026-10-16 | minor | M1.9b: settings dialog (store, search, controls by type, reset, live updates, font-size token override) |
| 2026-10-16 | minor | M1.14: app icon from the owner's master, multi-size ICO, placeholder as fallback |
| 2026-10-16 | minor | M1.8: UI commands (`ui.registerCommands`, `uiCommand`, `ui` in listCommands), global keymap, command palette |
| 2026-10-16 | minor | M1.12: notifications (host emission, early-event replay, toast store and stack, deferred engine_ready) |
| 2026-10-16 | minor | M1.13: open buffers pin their parent directory in the watcher, `bufferFocused`, truncated listing row |
| 2026-10-16 | minor | M1.7: recovery journal (storage, debounce, removal, commands, recoveryAvailable, restore dialog) |
| 2026-10-16 | minor | M1.10: themes (light theme, editor tokens, theme.list, theme.systemPreference, themeChanged, init script from the setting, live switch, contrast test) |
| 2026-10-16 | minor | M1.9a: engine construction (EngineConfig, with_config) and settings (file, commands, settingsChanged, notification) |
| 2026-10-15 | minor | M1.11: message catalog (`t`, lint rule, catalog test, engine messages stay English) |
| 2026-10-15 | minor | M1.6: tabs and editor (buffer sync, CRLF offsets, shortcuts from command specs) |
| 2026-10-15 | minor | M1.4: desktop bridge (engine://event, engine_ready replay, folder picker, capabilities), UI contract fix |
| 2026-10-14 | minor | M1.3: workspace commands, edit protocol, events, events.subscribe, watched-directory limits |
| 2026-10-14 | minor | Screenshot method, placeholder app identifier |
| 2026-10-13 | major | M0: layers metadata, command and guard design, control protocol, open questions decided |
| 2026-10-13 | major | Initial draft |