Lutra/docs/architecture.md
danny 4bdfe521f2 F1: remote checkout without a remote, git.lastMessage, shared git status store
- vcs: checking out a remote-tracking branch reads remote.<name>.fetch;
  without a matching refspec it creates the local branch with --no-track
  instead of leaving a dirty tree after git fails to set up tracking.
- vcs + engine: git.lastMessage returns HEAD's full message (null before
  the first commit); the Changes window prefills Amend with it.
- ui: stores/vcsStatus.ts is the only git.status caller; the Changes
  window, tree/tab colours and the branch item read its snapshot, so a
  gitChanged costs one status query. RepoSummary carries upstream,
  ahead and behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:16:53 +01:00

698 lines
160 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, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5) · **Last updated:** 2026-10-26
## 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, mcp; later diff, perf, bench
crates/control (L5) JSON-lines control channel (--control PORT)
crates/mcp (L5) MCP server over stdio (the CLI supplies the connection)
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/vcs (L3) Git through the installed git command
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/proc (L0) child processes that die with Lutra (job objects, process groups)
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).
- **Data directory isolation (H6):** `lutra-desktop --data-dir DIR` or `LUTRA_DATA_DIR=DIR` makes an isolated instance (`apps/lutra-desktop/src/datadir.rs`): `EngineConfig { config_dir: DIR, data_dir: DIR }` (settings, `recovery/`), the rendezvous file in `DIR`, and the webview's own data in `DIR/webview` (`WebviewWindowBuilder::data_directory`, the WebView2 user data folder, so local storage is separate too). `--control PORT` without either uses `<temp>/lutra-control/<port>/`, kept between runs. The managed tools stay shared: `Engine::share_tools_from(user app_data_dir)` makes the toolchain look for (and, only if missing, download) `tools/phpactor/<version>/` there, SHA-256 checked as before. Rendezvous order: `LUTRA_RENDEZVOUS_DIR` if set; else none for `--control`; else the isolated directory; else the default. `rendezvous::dir()` (CLI, `lutra mcp`) honours `LUTRA_DATA_DIR` after `LUTRA_RENDEZVOUS_DIR`, so `lutra` finds an isolated instance started with the same environment. An isolated instance therefore never forwards to, or registers as, the user's main instance.
- **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`. Response lines are capped at 64 MiB. `lutra mcp` (M3.8) uses this API from the CLI, so the CLI's `launch` logic stayed in the CLI.
### MCP server (M3.8)
- **Shape:** `crates/mcp` (L5) holds the protocol, the tools and the event buffer but opens no sockets and starts no processes; it reaches Lutra through the `lutra_mcp::Connector` / `Connection` traits (`request(method, params)`, `next_event(timeout)`). `lutra mcp` in `apps/lutra-cli` (L6) implements them with `lutra_control::client`: the rendezvous file and token by default (starting Lutra like `lutra PATH` when none runs), `--port PORT` for an open `--control` channel, `--no-start` to never start Lutra. Register it with `claude mcp add lutra -- lutra mcp`. No SDK: the official Rust SDK brings an async runtime and schema generators, and the protocol needed here is small.
- **Transport:** stdio, one JSON-RPC 2.0 message per line (UTF-8, at most 16 MiB; a longer or non-UTF-8 line gets a parse error and the next line is read). Batches are rejected. stdout carries only MCP messages; the server exits 0 when stdin closes. Every request runs under `lutra_engine::guard`.
- **Protocol versions (dual era):** modern **2026-07-28** (stateless: each request carries `_meta` `io.modelcontextprotocol/protocolVersion` and `io.modelcontextprotocol/clientCapabilities`; `server/discover`; results get `resultType: "complete"` and `_meta` `io.modelcontextprotocol/serverInfo`; another version gets `-32022` with `data {supported, requested}`, missing capabilities `-32602`) and legacy **2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05** through `initialize` (the client's version if known, else 2025-11-25). Only the handshake and the result decoration differ; both eras share every method and tool. A request with neither `_meta` nor a prior `initialize` is served with legacy shapes.
- **Methods:** `server/discover`, `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list` (empty). Notifications are accepted silently; any other method is `-32601`. Capabilities: `tools {listChanged: false}`, `resources {}` (no subscriptions yet). Lists come whole (a cursor is ignored).
- **Tools (D16):**
- `list_commands {filter?, enabledOnly?}`: `engine.listCommands` (id, label, menu path, shortcut, params doc, enabled, ui).
- `execute_command {command, params?, confirm?}`: `engine.execute` for every engine and UI command. **`app.quit` is refused with `confirmation_required` unless `confirm: true`.**
- `screenshot {path?}`: `ui.screenshot` into a temporary file (deleted afterwards) or `path`, returned as `image/png` content; at most 32 MiB, PNG signature checked.
- `read_buffer {path | id}`: the current text with unsaved changes plus `{id, path, version, dirty, lineEnding, truncated}`; a project-relative or absolute path inside the project; cut at 4 MiB.
- `get_events {since?, max?, kinds?, waitMs?}`: see Events below.
- Results carry `structuredContent` and the same JSON as text. Bad arguments, engine errors and an unreachable Lutra are tool errors (`isError: true`, text `code: message`, `structuredContent.error {code, message}`) with the engine's code, or `invalid_params`, `confirmation_required`, `not_open`, `screenshot_failed`, `unavailable`. An unknown tool is `-32602`.
- **Events:** the first connection starts a pump thread with its own subscribed connection (`events.subscribe`). It keeps the last 1000 events in a ring, numbered by a growing `seq`, each capped at 16 KiB (a bigger one keeps only `kind` and `truncated: true`). `get_events` returns the events after `since` (default 100, at most 1000, optionally only `kinds`, optionally waiting up to `waitMs` ≤ 30 s), `latest` to pass as `since` next time, `missed` when the ring dropped events after `since` or the subscription was down, and `subscribed`. A lost subscription reconnects every 0.5 s without starting Lutra. Events from before the first connection are not seen.
- **Resources:** one per open buffer (`buffer.list`), URI `lutra://buffer/<project-relative path>` with every byte outside the RFC 3986 unreserved set (except `/`) percent-encoded, a MIME type from the extension, and a description for unsaved changes. `resources/read` returns the text with unsaved changes; an unknown or closed buffer is `-32602` with `data {uri}`, an unreachable Lutra `-32603`.
- **Connection:** made on the first call that needs Lutra (listing tools never starts it) and pinged (`app.ping`) before each use; a dead one is replaced, which starts Lutra again if it quit.
- **Tests:** JSON-RPC and protocol units, a proptest fuzz of message lines and tool arguments (no panic, exactly one valid response line), integration against `lutra_testkit::EngineBackend` behind a real token listener (`crates/mcp/tests/tcp.rs`), and the `lutra mcp` binary on stdio (`apps/lutra-cli/tests/mcp.rs`).
## 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 {skipConflicts?}` (`Mod+Alt+S`; see Autosave), `buffer.close {id, force?}`, `buffer.list` (M3.8: `[{id, path, version, dirty}]` without text, empty without a project). Everything except `project.open` and `buffer.list` 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), `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (M3.6, see Terminal). 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. Since M3.10 changes are also saved automatically (see 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, tuned to the raspberry accent (H5: keyword = a muted raspberry, 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`), the autosave keys `editor.autosave.onBlur`, `editor.autosave.onTabSwitch` (bool, default true) and `editor.autosave.idleSeconds` (int 0–600, default 15; M3.10), the assist keys `editor.completion.autoPopup` (bool, default true), `editor.completion.delayMs` (int 0–2000, default 0) and `editor.hover.delayMs` (int 100–3000, default 350; H4). 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.
- **Brand alignment (H5, approved by the owner 2026-10-25):** the palettes follow the README banner (raspberry #bc3c79, plum #83224b, cream #f2ecd7) without taking it over: surfaces stay calm and near-neutral (light: cream-tinted, `bg` #f3efe3; dark: a faint plum tint, `bg` #1e1b1e, cream `fg`), the raspberry is only the accent (light #a32c66, dark #e27ba6: cursor, modified dot, focus, active tab, selection and match tints), and the terminal follows the editor surface (ANSI magenta = accent). No new UI fonts.
- **Diagnostic and VCS tokens (H5):** `theme::DIAGNOSTIC_TOKENS` → `--lt-diag-error|warning|info|hint` (lint underlines, gutter dots, tooltip stripes, Problems icons; warning is amber, info blue, hint muted) and `theme::VCS_TOKENS` → `--lt-vcs-added|modified|deleted|untracked|ignored|conflicted` (tree and tab file names, change markers; M4.4). Each reaches 4.5:1 on `editor-bg`, `editor-active-line-bg` and `bg` (lowest: `vcs-ignored` 4.67 dark, 4.73 light on the active line). Completion kind icons (Lucide) take `--lt-syntax-*` by kind (`assist/icons.ts` `KIND_COLOURS`), at least 3:1 on the popup and the selected row.
- `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, plus the diagnostic, VCS and completion-icon colours (H5). 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+,`, `terminal.open` `Mod+Shift+T` (M3.6), `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`, `terminal.open` → `View/Terminal`, `settings.open`), Go (`goto.fileOpen`, `goto.classOpen`, `goto.symbolOpen`), Help (`app.about`). Edit stays empty until there are edit commands.
- **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, string → text field (H4). The theme picker is the `appearance.theme` select; the engine answers with `themeChanged`.
- **String and path settings (H4, `stringSetting.ts`):** every `string` setting from `settings.list` gets a text field, applied when committed, so a new key (M4.1's `git.executable`) needs no UI change. A string setting whose key's last segment ends in `path` or `executable` is a path: it gets "Browse…", which calls the desktop's `pick_file {title}` IPC (the dialog plugin's native file picker, run off the main thread; `ipc.ts › pickFile`) and applies the chosen file through `settings.set`; a path with an empty default shows "Detected automatically" while empty. Checks before `settings.set`, each with its own catalog message: at most 4,096 UTF-8 bytes and no control characters (every string), no surrounding quotes and no spaces at either end (paths). The engine validates everything else. String rows stack the field under the label at full width. `settings.open {section?, query?}` opens on a section or with a search (for agents and live checks).
- **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. Since M3.6 it also holds the Terminal tool window and shows tabs while both are visible (see Terminal).
- **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).
### Child processes (H1)
`lutra_proc::spawn(Command) -> io::Result<lutra_proc::Child>` starts every external tool Lutra runs (Phpactor and the `php -v` probe now; git, `php -l` and others next) in a group the OS tears down when Lutra's process ends, even when Lutra is killed hard.
- **Windows:** one job object per child with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (`windows-sys`). Lutra holds the only handle, so dropping the `Child` or the end of Lutra's process (the kernel closes its handles) kills the child and everything it started. Jobs nest (Windows 8+), so this works when Lutra itself runs in a job (terminal, `cargo`, CI). `crates/proc/src/windows.rs` is the only module that allows `unsafe` (FFI).
- **Unix:** the child leads a new process group; a `/bin/sh` watchdog in its own group blocks on a pipe only Lutra holds and sends `SIGKILL` to the child's group when the pipe closes (drop, kill, quit, or a `SIGKILL` of Lutra). Left behind after a `SIGKILL` of Lutra: processes that left the group themselves (`setsid`/`setpgid`, daemons), and the child if Lutra dies between starting it and starting its watchdog. Compiled and tested by CI only (no Unix machine here).
- `Child` dereferences to `std::process::Child`. `Child::kill` replaces the standard `kill` and takes the whole group; `kill_and_wait` also reaps; `Drop` kills the group and reaps.
- A child runs for a moment before it joins its job (Windows) or before its watchdog exists (Unix); a grandchild started in those microseconds can escape.
- Tests: `crates/proc/tests/process_tree.rs` starts `lutra-proc-helper`, which starts a sleeping grandchild holding the test's pipe. A hard kill of the helper (`TerminateProcess` / `SIGKILL`, with and without the helper itself in a group), `Child::kill` and drop each end the tree; the pipe reaches end of file. Without `KILL_ON_JOB_CLOSE` the hard-kill tests fail.
- The integrated terminal (portable-pty) does not use it yet. On Unix portable-pty makes the shell a session leader, and closing the PTY master on Lutra's exit hangs it up. On Windows the ConPTY host ends its clients when its pipes break; joining the shell to a job needs an adopt-by-handle API (`portable_pty::Child::as_raw_handle`), a follow-up.
### Terminal (M3.6)
- **Library:** `crates/terminal` (L3) wraps `portable-pty` (MIT; ConPTY on Windows, a Unix pty elsewhere). `Session::spawn(SpawnOptions {shell, cwd, cols, rows, env})` starts the shell with `TERM=xterm-256color`, `COLORTERM=truecolor`, `TERM_PROGRAM=Lutra`. Each session has three threads, so no call blocks the caller: a reader (16 KiB reads, `Utf8Chunker` joins a character split across reads and turns invalid bytes into U+FFFD like `from_utf8_lossy`), a writer (input queue of at most 64 pieces of 64 KiB; a full queue fails with `InputFull` instead of blocking), and a waiter that records the exit code and then closes the pty, because ConPTY reports the end of output only once the pseudo console is closed. `default_shell()`: `pwsh.exe` from `PATH` (with `-NoLogo`), then `powershell.exe`, then `%COMSPEC%`/`cmd.exe` on Windows; `$SHELL` or `/bin/sh` on Unix.
- **Buffer and drop policy:** each session buffers at most 1 MiB of decoded text (`OUTPUT_CAP`). When it is full the reader stops reading, so the shell blocks on its next write (backpressure): nothing is dropped while a session runs. Output still buffered when a session is closed or killed is dropped. `exit()` reports the code once the shell exited, its output was read to the end (or 500 ms passed, for a background process that keeps the pty open) and the buffer is empty, so the exit always follows the last output.
- **Engine:** `cmd/terminal.rs`. `terminal.create {cwd?, shell?, cols, rows}` → `{terminalId}` (enabled with a project; cwd project-relative or absolute, default the root; 1–1000 columns and rows; at most 16 terminals), `terminal.input {terminalId, data}` (≤ 1 MiB), `terminal.resize {terminalId, cols, rows}`, `terminal.close {terminalId}` → `{closed}`. Events `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (`code: null` when Lutra closed the terminal) are the variants of `cmd::terminal::TerminalEvent`, appended to `Event` as one untagged variant so that `event.rs` takes a one-line append and each variant keeps its own `kind`. The pump emits one `terminalOutput` per terminal with at most 64 KiB, at most 256 KiB over all terminals, round-robin; with the desktop's 100 ms pump that caps the stream at about 2.5 MB/s and the shell waits beyond it. Under the engine lock only spawning, queueing input, resizing and killing happen.
- **Lifecycle:** a terminal belongs to the project open when it was created. `cmd::terminal::sync_project` runs after every command and every pump and closes terminals whose project is gone (`project.close`, another `project.open`); `app.quit` closes all of them. Dropping a session kills its shell; when the process ends without that, the OS closes the pseudo console (ConPTY) or hangs up the pty (Unix).
- **Cursor query:** ConPTY starts with `ESC[6n` and waits for the answer. xterm.js answers in the app; tests answer it themselves (`crates/terminal/tests/session.rs`, `crates/engine/tests/terminal.rs`, `crates/control/tests/terminal.rs`).
- **Store:** `ui/src/stores/terminal.ts` (Pinia `terminal`): tabs, the active terminal, visibility and expansion of the Terminal tab, an output history per terminal (at most 512 Ki UTF-16 units, oldest event chunks dropped first) that a view replays when it mounts, output that arrives before `terminal.create` answered kept by id, input sent in order with one `terminal.input` in flight (keys typed meanwhile go together), sizes deduplicated. `projectClosed` drops everything.
- **Views:** `ui/src/components/terminal/TerminalToolWindow.vue` has the sub-tab strip ("Local", "Local (2)"…, close buttons, a new-terminal button; Left/Right/Home/End/Delete on a tab) and one `TerminalView.vue` per terminal, kept mounted with `v-show`, so switching sub-tabs keeps xterm's screen; collapsing or hiding the panel unmounts them and the history restores them. `xterm.ts` is the only file that imports `@xterm/xterm` and `@xterm/addon-fit` (MIT), so tests mock it. The fit addon follows a `ResizeObserver` and reports the size with `terminal.resize`. Colours come from the `--lt-terminal-*` tokens (`terminal-bg`, `-fg`, `-cursor`, `-selection-bg` and 16 `-ansi-*` colours, Lutra's own palette), font and size from `--lt-font-mono` and `--lt-font-size-editor`; `themeChanged` re-themes running terminals. Every ANSI colour that shows as text reaches 4.5:1 on `terminal-bg` (contrast test), except the one meant to vanish (black in dark, white and bright white in light); xterm's `minimumContrastRatio` is 4.5, so text a program prints in such a colour (PSReadLine uses white) is darkened or lightened until it is readable. xterm's stylesheet paints the viewport black; the view overrides it with `--lt-terminal-bg`.
- **Focus and shortcut rule** (`ui/src/components/terminal/keys.ts`, applied by the commands store's keydown listener): while a terminal has the focus, only shortcuts with Mod+Shift or Mod+Alt reach Lutra (on macOS every Cmd shortcut); plain Ctrl keys (`Ctrl+C`, `Ctrl+W`, `Ctrl+P`, `Ctrl+1`…) go to the shell. Copy: `Mod+Shift+C`, or `Ctrl+C` with a selection (`Cmd+C` on macOS) through `navigator.clipboard.writeText`. Paste: `Mod+Shift+V` or `Ctrl+V` (`Cmd+V`) are left to the browser, whose `paste` event xterm handles, so no clipboard-read permission is needed.
- **Bottom panel tabs:** `BottomPanel.vue` takes `tabs` and `v-model:active`; with tabs the header shows a tab list instead of the title. `MainLayout.vue` shows Find and Terminal as tabs while both are visible; `find.open` and `terminal.open` make their tool window the active tab, the close button hides the active one, and expansion is kept per tool window.
- **`terminal.open`** (UI command, `Mod+Shift+T`, Lutra's own; enabled with a project): shows the Terminal tab, creates a terminal if none is running (always with `{new: true}`) and focuses it.
### Engine wiring and diagnostics (M3.3)
- **Where:** `crates/engine/src/lsp/` (`mod.rs`: state, pump, sync, diagnostics; `session.rs`: the session thread), commands in `crates/engine/src/cmd/lsp_diagnostics.rs`. One-line hooks in `buffer.edit` (`lsp::record_edits`), the pump (`lsp::pump`), `app.quit` (`lsp::shutdown_now`), `State`, `Event` and the registry.
- **Lifecycle:** one session per open project.
- It starts at the first pump where a project is open and `toolchain.status` reports a usable PHP and a ready Phpactor (`php <phar> language-server` in the project root). With a host-set server (`Engine::set_language_server`, the fake server in tests) it starts at once.
- A change of root, PHP or PHAR replaces the session. Closing the project, `lsp.restart` and dropping the engine stop it.
- `app.quit` stops it synchronously (`shutdown`, `exit`, kill; quit measured at 1.55 s on Windows). The host exits right after, which would cut a background shutdown short and leave `php.exe` running.
- **Nothing heavy under the lock:** each session has one thread (`lsp-session`) that owns the `lutra_lsp::Server`, and it also spawns the process. The engine lock only enqueues jobs on the thread's FIFO:
- `Open`/`Full` carry an O(1) rope clone of the buffer; the text is built on the thread.
- `Change` carries the edit batch that `buffer.edit` applied.
- `Save`, `Close`, and `Run(closure)` for requests.
Requests from M3.4/M3.5 go through `lsp::submit` on the same queue, so a request never overtakes an edit's `didChange` (tested).
- **Document sync:** PHP buffers (`.php`, `.phtml`, `.inc`) are opened when the pump first sees them and closed when they close.
- `buffer.edit` queues its batch as `didChange` when the server's copy is at the edit's base version.
- Otherwise the next pump resends the whole text: after a reload from disk, a restore, or a `didChange` the client copy rejected.
- When the saved version of a clean buffer moves, the pump sends `didSave`.
- Property-tested with random edits (incremental and full sync): the fake server's copy always ends equal to the buffer.
- **Events and commands:**
- `lspStatus {state: starting|ready|restarting|failed|stopped, message?}` follows the client's status. `failed` (spawn error, too many crashes) also raises `notification.lsp.failed`.
- `diagnosticsChanged {path, items: [{range: {start: {line, column}, end}, severity: error|warning|info|hint, message, source?, code?}]}` per project file.
- Columns are UTF-16, and files outside the project are ignored.
- A missing severity counts as error.
- Caps: at most 10,000 files, and 10,000 items each from the client.
- `diagnostics.list {path?}` returns `{files: [{path, items}]}` sorted by path. `lsp.status` returns `{state, message?, startupMs?, progress}`. `lsp.restart` is in the Tools menu.
- `lspProgress {active, title?, message?, percentage?}` and `lsp.log` (H3), see Phpactor UX below.
- Diagnostics are cleared (an empty `diagnosticsChanged` per file) when the session ends or the server fails, so stale ones never stay. The pump handles at most 2,000 server events per call.
- **UI:**
- **Editor:** `ui/src/components/editor/lint.ts` feeds CodeMirror's lint extension (`@codemirror/lint`, MIT) with wavy underlines, a gutter dot, and the message with source and code on hover.
- Colours come only from the severity tokens `--lt-diag-error`, `--lt-diag-warning`, `--lt-diag-info`, `--lt-diag-hint` (H5).
- A view plugin per editor state applies its path's list when the view shows the state and on every change. CodeMirror maps ranges through edits until the next publication.
- **Problems:** `ui/src/components/problems/` holds the store and the tab.
- The store loads `diagnostics.list` and `lsp.status` on start and on project open, follows the events, and hands each file to `lint.ts`.
- The Problems tab in the bottom panel groups by file, errors first; click or Enter runs `editor.reveal`.
- `problems.open` is `Mod+Alt+P`, menu View/Problems.
- **Phpactor 2026.06.25.0 on Windows:** the live check found two problems, worked around without touching the user's project.
- **The event loop stalls.** Its amphp event loop only runs when a message arrives on stdin, so timers stall while the client is quiet: the diagnostics debounce (`language_server.diagnostic_sleep_time`) and the file watcher.
- Seen: the server answered `initialize` in 0.8 s, but published nothing after `didOpen` and only a clearing empty list after `didChange`.
- Fix: while busy (a job in the last 60 s and the server ready), the session thread sends the no-op notification `$/lutra/tick`. It comes from the thread's own loop, so it does not depend on the host's pump. H3 adds a fast tick while Phpactor indexes (see Phpactor UX).
- The interval sets the latency, because Phpactor's analysis advances one step per message. Edit to diagnostics (engine test with the real PHAR, measured): 5.9 s at 200 ms, 2.5 s at 50 ms, 1.5 s at 20 ms. Lutra uses 25 ms.
- The same stall means Phpactor rarely answers `shutdown` in time, so the shutdown timeout is 500 ms before the kill.
- **Subprocesses fail.** Every subprocess it starts through amphp fails with `CreateProcess failed`: outsourced diagnostics, the PHP lint provider, the indexer's `find` watcher.
- Fix: `initializationOptions` set `language_server.diagnostic_outsource: false` (diagnostics run in the server process) and `indexer.enabled_watchers: ["php"]` (a polling watcher).
- The PHP lint provider still fails once and removes itself; its `window/showMessage` warning is only logged (`lsp::is_hidden_message`).
- Lutra runs `php -l` itself instead (H3, see Phpactor UX). The worse-reflection diagnostics (missing members, unknown classes, …) work.
- These adjustments (tick, initialization options, short shutdown timeout) apply on Windows only (`lsp::phpactor_launch`). macOS and Linux are untested.
- **Phpactor UX (H3):** `crates/engine/src/lsp/` (`mod.rs`: progress, messages, log, merge; `session.rs`: fast tick; `php_lint.rs`), `lsp.log` in `cmd/lsp_diagnostics.rs`, the status-bar item `ui/src/components/problems/LspProgressItem.vue`.
- **Fast tick.** Phpactor's indexer waits for a 1 ms timer after every file, and on Windows that timer only fires when a message arrives, so it indexes one file per tick. While Phpactor reports work-done progress, and during the first 120 s of a session, the tick is 1 ms (`FAST_TICK_INTERVAL`, `tick_interval`); otherwise 25 ms and the 60 s window as before. The pump sets a flag the session thread reads.
- A channel `recv_timeout` wakes at most ~64 times a second on Windows (15.6 ms timer resolution; measured 63–67 wakes/s for 1, 2 and 5 ms timeouts), so intervals below 16 ms poll the queue and `thread::sleep` (high resolution; 697 wakes/s at 1 ms). A job waits at most one interval.
- Measured on a generated 2,000-class project (`real_phpactor_first_completion`, Windows 11, PHP 8.4, debug build), project open to the first completion list with a method of the last class: 71.6 s with the 25 ms tick (before), 47.8 s with a 2 ms `recv_timeout` (really ~16 ms), 29.9 s at 5 ms, 23.8–26.9 s at 2 ms, 20.7–22.6 s at 1 ms with sleep. Phpactor then indexes ~110–190 files/s.
- Cost while the window runs and Phpactor is idle: about 10% of one core for Phpactor and 4.5% for the session thread at 1 ms (9% and 3% at 2 ms). After the window it is the old 25 ms tick.
- **Progress.** `$/progress` begin/report/end (at most 32 tasks) become `lspProgress {active, title?, message?, percentage?}` with the newest running task; `lsp.status` has it as `progress`. It clears when the session stops, restarts or fails. The status bar shows title and percentage with the message as tooltip (Phpactor: `Indexing workspace 25%`, `500/2001 (24.99%, …)`).
- **Messages.** `window/showMessage` becomes a notification of the same level, `notification.lsp.message {message}`; the same text again within 30 s is not shown. Phpactor's known lint-provider complaint on Windows is only logged. `window/showMessage`, `window/logMessage` and stderr lines go to a log of the last 1,000 lines, `lsp.log` → `{lines}` (`[level] …`, `[show level] …`, `[stderr] …`).
- **`php -l`.** On Windows Lutra runs the toolchain's `php -n -l -d display_errors=1 -d log_errors=0` itself for each open PHP buffer when first seen and after each save (a clean buffer whose saved version moved), on one worker thread through `lutra_proc::spawn`, with the saved text on stdin. Queued runs of one file collapse to the newest; files over 8 MiB are skipped; a run is killed after 10 s; output is capped at 64 KiB. `Parse error` / `Fatal error` lines become error diagnostics on the whole line with `source: "php -l"` (at most 100 per file). They merge after the server's into `diagnosticsChanged` and `diagnostics.list`, stay until the file's next run, survive a server restart and clear on project close. Elsewhere it is off (Phpactor lints itself); `Engine::set_php_lint` overrides it.
- **Completion delay (H4's `editor.completion.delayMs`).** Phpactor answers every completion with `isIncomplete: true`, so CodeMirror asks again on every keystroke. Measured on 2,000 classes: a member completion costs ~6 ms of Phpactor CPU (median 21 ms), a class-name completion ~180 ms CPU (median 270 ms, 100 items). A Vitest model of CodeMirror's behaviour (server latency 40 or 150 ms, 80/150/250 ms per key) gave the same number of requests at 0 and 100 ms for 150 ms per key and slower (`->price`: 6, `ProductRepository`: 17); only typing faster than the delay (80 ms per key) cut them (6 → 1, 17 → 1), and then no list showed until the typing paused. The default stays 0: 100 ms only delays the list. The real lever is cancelling superseded requests (a follow-up).
- Tests: `crates/engine/tests/lsp_ux.rs` (scripted fake-server messages and progress, `php -l` on open and save, merge with the server and a restart, off without PHP; the ignored real-Phpactor measurement), unit tests (tick rule, hidden message, `php -l` output parsing with a proptest), Vitest `ui/tests/problems/LspProgressItem.test.ts`.
- **Measured** (Windows 11, PHP 8.4.24, debug build, 16-line file):
- Phpactor is ready 0.8–0.9 s after the session starts (`startupMs`).
- First diagnostics after `file.open`: 1.7 s in the engine test, 2.7 s in the app over the control channel.
- After an edit: 1.8 s and 2.7–2.9 s, including Phpactor's 1 s debounce.
- Without the adjustments: no diagnostics within 180 s.
- **Known gaps:**
- ~~A Phpactor process outlives Lutra when Lutra is killed.~~ Fixed by H1: Phpactor starts through `lutra_proc::spawn` (see Child processes).
- ~~`window/showMessage` and `logMessage` are dropped, and server-initiated progress is not shown.~~ Fixed by H3.
- **Tests:**
- `crates/engine/tests/lsp.rs` has 10 tests against `lutra-lsp-fake`: sync incl. UTF-16 and CRLF edits, diagnostics list/clear, reload resync, requests after edits, project close, restart, quit, missing server, crash and give-up, no server without a project, and a proptest of random edits. The ignored `real_phpactor_reports_diagnostics` runs with `LUTRA_PHPACTOR=<phar>`.
- Unit tests cover severity, paths, the Phpactor launch and the tick rule.
- `crates/control/tests/lsp.rs` runs over TCP with ticks on.
- Vitest: `ui/tests/editor/lint.test.ts` and `ui/tests/problems/ProblemsToolWindow.test.ts`.
### Pending outcomes: commands that wait for the language server (M3.5)
- **Why:** `lsp.definition` returns `{locations}`, `lsp.completion` returns items. The answer comes from Phpactor, and nothing may wait for it under the engine lock (M3.3).
- **API** (`crates/engine/src/command.rs`, `engine.rs`):
- A command queues its request with `lsp::submit(state, |server| server.request_with(…, callback))`; the callback sends into an `mpsc` channel.
- The command returns `Outcome::pending(Pending::new(receiver, timeout, finish))` at once.
- The host calls `Pending::wait()` *without* the lock. It returns when the answer arrives, the sender is dropped or the deadline passes (timeout + 1 s of grace; the request's own timeout should be shorter, so it reports first).
- Then, with the lock again, `Engine::resolve(answered)` runs `finish(state, reply)` in the guard. `reply` is `Some(Ok(value))`, `Some(Err(LspError))` or `None` (no answer). The finish builds the value and may change the state; a rename applies its edit here.
- `lutra_engine::run_waiting(lock, command, params, publish)` does all three steps for a host. Events of each step are published while the lock is held. Effects come from the first step.
- **Hosts:** `Host::run` (desktop), `testkit::EngineBackend` and the control protocol's test backend use `run_waiting`. Control-channel and MCP callers (one thread per connection) get the final value directly.
- **IPC and ordering:**
- `engine_execute` stays a synchronous Tauri command on the main thread, so every ordinary command (`buffer.edit` above all) runs in call order, as before.
- The new `engine_execute_waiting` (`#[tauri::command(async)]`, `runWaiting` in `ui/src/ipc.ts`) runs `Host::run` off the main thread, so the window stays responsive while Phpactor works. Only `lsp.*` requests use it.
- `engine_execute` itself did not move off the main thread, unlike the first plan: moving it would let two ordinary commands race for the lock, and the order of `buffer.edit` calls must stay the call order.
- The order towards Phpactor is fixed under the engine lock: `buffer.edit` queues its `didChange` on the session queue (`lsp::record_edits`) before it returns, and `submit` queues the request on the same FIFO queue. A request therefore sees every edit whose `buffer.edit` returned before it, and the frontend awaits the buffer sync's `idle()` before sending one.
- **Failures:**
- Phpactor stalls: the request times out in `lutra-lsp`; the waiter's deadline is the backstop.
- `lsp.restart`, project close, `app.quit` (`shutdown_now`) or a crash: queued jobs are dropped and in-flight requests resolve with `Stopped`/`ServerCrashed`, so the waiter gets an error at once instead of hanging (test: `crates/engine/tests/pending.rs`).
- A finish must check that its answer still applies to the state; `lsp.rename` refuses when a buffer's version changed since the request.
### Code assistance: completion, hover, signature help (M3.4)
- **Where:** `crates/engine/src/cmd/lsp_assist.rs` (commands and conversion), `ui/src/components/editor/assist/` (CodeMirror extensions, Markdown renderer, UI commands). One-line hooks: `editorExtensions(path, buffer)` in `extensions.ts`, the buffer handle in the editor store's `adopt`, three `provide` calls in `EditorArea.vue`.
- **Commands:**
- `lsp.completion {id, position, triggerCharacter?}` returns `{items: [{label, kind, detail?, documentation?, insertText, textEdit?, additionalTextEdits?, sortText?, filterText?, deprecated?}], incomplete}`.
- Items are sorted by `sortText`, then label, and cut at 500; a cut list is `incomplete`.
- Snippet texts become plain text (tab stops dropped, placeholders kept), because Lutra announces no snippet support.
- Plain-text documentation is escaped into Markdown.
- `lsp.hover {id, position}` returns `{contents (markdown, empty for nothing), range?}`.
- `lsp.signatureHelp {id, position}` returns `{signatures: [{label, documentation?, parameters: [{label: [start, end] | null, documentation?}], activeParameter?}], activeSignature, activeParameter}`. Parameter labels become UTF-16 offsets into the signature label.
- The position is checked against the buffer (UTF-16 column, not past the line end, not inside a surrogate pair). A non-PHP buffer, or a server without the provider, gives the empty result. Without a session the command fails with `failed`.
- Every string and list from the server is capped (labels 1 KiB, documentation 64 KiB, 32 imports per item, 32 signatures).
- **Off the lock** (on M3.5's pending outcomes):
- Under the lock the command validates, runs the LSP pump once (so a buffer opened a moment ago is opened on the server first) and queues a closure with `lsp::submit`. That runs after every queued `didChange`.
- The closure sends the request with `request_with` (timeout 10 s). The reply callback converts the answer on the client thread, so a big list is never converted under the lock.
- It sends the result into the `Pending`'s channel. The host waits without the lock (wait 11 s + 1 s grace) and resolves.
- The UI calls these commands with `runWaiting` (`engine_execute_waiting`, off the main thread).
- **Editor:**
- **Before a request,** the UI awaits the buffer sync's `idle()` and drops the request if the document changed meanwhile. Positions are lines and UTF-16 columns, which CodeMirror counts the same way within a line, so CRLF files need no conversion.
- **Completion source** (overrides CodeMirror's word completion in PHP files).
- Lutra's triggers: identifiers (not after a digit), `$`, `->`, `?->`, `::` and namespace `\`, sent as `triggerCharacter`. Nothing inside strings or comments unless asked (`Ctrl-Space`, `editor.complete`).
- The server's order becomes the boost. A complete list is filtered locally while typing; an incomplete one is asked again on each keystroke.
- Applying an item uses its `textEdit` (else replaces the typed word with `insertText`) and its `additionalTextEdits` in one transaction. Text typed after the request is accounted for, and overlapping imports are skipped.
- The kind icon is a Lucide component rendered into the list row.
- **Hover:** `hoverTooltip` after `editor.hover.delayMs` (default 350 ms); `editor.quickDocumentation` (`Mod+I`) shows the same tooltip at the cursor.
- **Settings (H4, `assist/settings.ts`):** `editor.completion.autoPopup` (typing opens the list; the shortcut always does), `editor.completion.delayMs` (CodeMirror's `activateOnTypingDelay`) and `editor.hover.delayMs` (`hoverTime`), read from the settings store (defaults without a Pinia, numbers clamped to the engine's ranges). Completion and hover sit in compartments; a view plugin follows the store and reconfigures every open PHP editor when a value changes, and a state field remembers the values a state was built with, so a state shown again later catches up. A reconfiguration recreates the hover extension, which closes an open hover tooltip.
- **Signature help:**
- A state field holds the tooltip; a view plugin asks on `(` and `,`, and while open on every edit or cursor move (120 ms debounce), dropping stale answers.
- `Escape` closes it, `Mod-Shift-Space` and `editor.parameterInfo` open it.
- **Markdown:** Lutra's own renderer builds DOM nodes with `createElement`/`textContent` from a fixed element set (paragraphs, code blocks, emphasis, lists, quotes, rules). HTML in the source stays text; links and images show their text only (no `href`, no `src`). No Markdown or sanitizer dependency.
- Colours come only from tokens. New dependency: `@codemirror/autocomplete` (MIT, already transitive).
- **Measured** with the real Phpactor (Windows 11, PHP 8.4, debug build, 25 ms tick, `real_phpactor_assist_latency`):
- **Latency:** completion while typing 61–109 ms (median 76 ms), ~107 ms through the control channel in the app; hover median 15–16 ms; signature help median 16 ms.
- **After 70 s idle** (ticks stopped): the first completion takes 92–262 ms.
- **Indexing first:** Phpactor answers an empty `incomplete` list until it has indexed the project, which takes 2.3 s for 20 classes and ~65 s for 2,000. Its loop advances one step per stdin message, so indexing uses only ~15% of one core.
- **Phpactor process:** 56–59 MB working set for 20 classes and 70–71 MB for 2,000. CPU while typing ~6% of one core; idle 1.5–4% while the tick window runs, ~0.1% after it.
- **Tests:**
- `crates/engine/tests/lsp_assist.rs`: 6 tests against `lutra-lsp-fake`, which now answers completion and signature help. They cover conversion, the trigger character, an edit seen before the request, the 500 cap, positions on CRLF and emoji lines, non-PHP buffers and no server. There is also the ignored real-PHAR test above.
- Unit tests: kinds, lists, snippets, hover parts, signature spans, caps.
- Vitest `ui/tests/editor/assist/`: triggers, the query, applying (text edits, typing since the request, imports, CRLF), the Markdown renderer (incl. an XSS set), hover, signature help and the UI commands.
### Definition, references, rename (M3.5)
- **Commands** (`crates/engine/src/cmd/lsp_nav.rs`). All take `{id, position: {line, column}}` (buffer id, 0-based, UTF-16 column) and return a pending outcome (see above):
- `lsp.definition` (F12) returns `{locations: [{path, range}]}`.
- `lsp.references` (Shift+F12, `includeDeclaration?` default true) returns `{locations: [{path, range, preview, previewColumn}]}`, sorted.
- `lsp.prepareRename` returns `{range, placeholder}` or null. It uses the word at the cursor when the server has no `prepareProvider`.
- `lsp.rename {…, newName}` (F2) returns `{files: [{path, edits, bufferId?, version?}], edits, written}`.
- Locations are project-relative, deduplicated and capped at 10,000. Locations outside the project are dropped: Phpactor stubs inside the PHAR, other folders, symlinks that resolve outside.
- A position outside the buffer is `invalid_params`; no running server is `failed`.
- **Workspace edits** (`cmd/lsp_nav/edit.rs`), all or nothing as far as a file system allows:
1. **Check everything first:**
- The edit is complete and has no file operations.
- Every document is inside the project.
- Every range converts (UTF-16 columns, CRLF as one break) and applies to a copy.
- Every open buffer is still at the version it had when the request was sent.
2. **Write closed files**, each atomically through the VFS, keeping the BOM and line endings. If a write fails, the files written so far get their old text back; a failed restore is named in the error. No buffer is touched then.
3. **Change open buffers** through `buffer.edit`, one batch per buffer. They become dirty and get journal, LSP and syntax updates like typing.
4. **Follow-up:** each written file is sent to Phpactor as `didOpen` → `didSave` → `didClose` with its new text (files the user opened meanwhile are skipped), plus `workspace/didChangeWatchedFiles` for servers that watch through the client. Phpactor ignored the notification alone and kept the old names until its polling watcher noticed: in the live check a "method does not exist" error stayed, and renaming back found one use instead of four. `didOpen` alone reindexed only class files, not the member references of a function file. With all three, its index followed in 140 ms (`real_phpactor_navigates_and_renames_across_files`). Then the notification `notification.lsp.renamed {name, edits, files, written}`.
- **Undo:** the frontend calls `BufferSync.beginUndoableRemote()` on every tab before `lsp.rename` and `endUndoableRemote(version)` after it. The engine's change to an open buffer then enters the CodeMirror history as one step, and Mod+Z reverts it through `buffer.edit`. Files written on disk are not part of any editor history. Without the UI (control channel, MCP) the change is applied the same way but is not undoable in an editor.
- **UI** (`ui/src/components/editor/nav/`):
- `nav.ts` (store) supplies the context of the three engine commands with `commands.provide` and calls them with `runWaiting` after the sync is idle.
- `navExtension.ts`: Mod+click goes to the definition; the cursor becomes a pointer while Mod is held; the extension remembers the view for placing the rename field.
- `NavPicker.vue` (exclusive modal `navPicker`), `RenameInput.vue` (exclusive modal `rename`, the preview count from `lsp.references`), `ReferencesToolWindow.vue` (bottom panel tab `references`), all mounted by `NavLayer.vue`.
- **Tests:**
- `crates/engine/tests/lsp_nav.rs` runs against the fake server's `--script` answers. It covers definition, bad positions, references (sorted, deduplicated, outside dropped), prepareRename with and without the server, a multi-file rename over an open buffer and two closed files (one CRLF), refusals (outside the project, a bad range, a buffer edited meanwhile, bad names) and no server.
- The ignored `real_phpactor_navigates_and_renames_across_files` runs with `LUTRA_PHPACTOR=<phar>`.
- Vitest: `ui/tests/nav/nav.test.ts`.
- **Live** (Phpactor 2026.06.25.0, Windows 11, debug build, tick on, a 3-file temp project), measured:
| Request | Latency |
|---|---|
| definition across files | 93 ms cold, 7–18 ms warm |
| references (4 uses in 3 files) | 137–150 ms |
| prepareRename | 10–11 ms |
| rename (4 edits, 2 files written) | 28 ms in the app, 44–59 ms in the real test |
| index follows the written files | 140 ms |
- Phpactor took 57 MB working set (45 MB private) and 4 s of CPU over the session, about 1.6% of one core while ticking idle.
- The keys and Mod+click were not pressed in the live app: sending keys would need the window focused, and the owner was using another app. Vitest covers them.
### 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, and since H4 a text field with "Browse…" for the two paths). 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.
### Autosave and flushDirty (M3.10)
- **One entry point:** `useAutosaveStore().flushDirty(options?)` (`ui/src/stores/autosave.ts`) waits until every tab's sync has no pending edits (`editor.settleAll()`), then runs `file.saveAll {skipConflicts: true}` and resolves with `{saved, failed: [{id, path, message}], skipped, error}`; it never rejects. Calls are serialised; a call made while a flush runs queues one more flush, which later callers share. Autosave uses it, and so must every feature that needs the files on disk first (deployment after the MVP, D18; run configurations; terminal commands). Nothing is uploaded on save ("save when deploying, not deploy when saving").
- **Engine helper:** `file.saveAll` got the optional flag `skipConflicts` instead of a new command, so there is one save-all with one result shape (`{saved, failed: [{id, path, message}], skipped}`; `skipped` is always present). The flag leaves a dirty buffer alone while it is in conflict with its file: `Buffers` remembers the buffers it reported with `fileChangedOnDisk` (changed or removed while dirty); an explicit `file.save`/`file.saveAll`, a reload from disk or closing the buffer clears it. `Buffers` also keeps the FNV hash and BOM of what the file held when Lutra last read or wrote it; a dirty buffer whose file still matches it is not a conflict (our own save reported by the watcher after the user typed again, or a touch). The engine has no untitled buffers; every buffer has a path.
- **Triggers** (each on by default, `stores/autosave.ts`, started by `App.vue`):
- `editor.autosave.onBlur`: the DOM `blur` event of `window` and `visibilitychange` to hidden. In the Tauri WebView they fire when the native window loses focus or is minimised; they need no Tauri capability (the window may only listen to engine events) and behave the same in Vitest. Tauri's window focus events would add a permission and an IPC hop for the same signal.
- `editor.autosave.onTabSwitch`: the editor store's active tab changes (also when a newly opened tab becomes active).
- `editor.autosave.idleSeconds`: no `bufferChanged` / `dirtyChanged {dirty: true}` event for that many seconds; edits over the control channel or from an agent count too. 0 turns it off; a changed value restarts a running timer.
- A trigger does nothing while no tab is dirty and no sync has pending edits.
- **Errors:** one error toast per failed file, `notification.save.failed {name, reason}`; a failure of `file.saveAll` itself becomes `notification.command.failed`. Autosave shows the same failure of the same file only once until it saves again; `flushDirty()` called by a feature shows it every time. Skipped conflicts raise no toast: the tab already shows the changed-on-disk notice.
- **Safety net:** the recovery journal is unchanged; it covers everything between saves.
### Git backend (M4.1)
- **Owner decision D20:** Git runs through the user's installed `git` (minimum 2.30), found through the setting `git.executable` (string, section `git`; `""` means `git` from `PATH`). No network operation exists (no fetch, pull, push), and no call can open a credential or terminal prompt.
- **Crate `lutra-vcs` (L3, `crates/vcs`):**
- `runner::run` is the only way git starts, and `runner::spawn` the only place a process starts, through H1's `lutra_proc::spawn`, so git and its hooks die with Lutra. Arguments are an array, never a shell. Every call gets `--no-pager --literal-pathspecs -c core.quotepath=false -c color.ui=false`, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, `GIT_OPTIONAL_LOCKS=0` for reads, no console window on Windows, and the variables that redirect git (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`, …) removed.
- Timeouts: 30 s; commit, checkout and branch creation 120 s (hooks). A call past its timeout, or whose stdout passes its cap, is killed (a guard kills and reaps the child on every early return).
- Caps: status 64 MiB, one file 32 MiB, other reads 16 MiB, stderr 16 KiB (the error text, also a failing hook's output; stdout is used when stderr is empty).
- Output is read only from machine formats: `status --porcelain=v2 -z --branch`, `cat-file --batch-check`, `for-each-ref` with NUL-separated fields, `show -s --format=%H%x00%s`. The parsers are property-tested with random bytes. Paths git prints that are not UTF-8 (Unix only) become U+FFFD instead of failing the status.
- `Git::detect(setting)` runs `git --version`; `Git::open(dir)` runs `rev-parse --show-toplevel --absolute-git-dir --git-common-dir --show-prefix` and gives `None` outside a work tree (the repository containing the project root; a nested repository wins). Paths in and out of `Repo` are project-relative with `/`; the prefix maps them to the repository root, and files outside the project are left out of the status. Input paths are refused when empty, absolute, with `..`, NUL or line breaks; they go to git through `--pathspec-from-file=- --pathspec-file-nul`, so any count and any name works.
- Operations: `status` (untracked files one by one, ignored files not listed), `head` (branch information only, `--untracked-files=no`), `stage` (`add -A`), `unstage` (`reset -q HEAD`, or `rm --cached` before the first commit), `commit` (`-F -` from stdin, `--cleanup=whitespace` so lines starting with `#` stay), `show` (the blob as stored: no smudge filters, no line-ending conversion, so LFS stays a pointer and nothing reaches the network; binary when a NUL is in the first 8000 bytes, the text is not UTF-8, or the entry is a submodule; a UTF-8 BOM is dropped), `branches`, `checkout` (local branch: `switch`; remote branch `origin/x`: `switch -c x --track` when a configured `remote.<name>.fetch` refspec maps a branch to it, the local name taken from that refspec as git does; otherwise, such as a removed remote or a hand-made ref, `switch -c x --no-track`, because git would update the work tree before failing on the tracking setup and leave it dirty; C6 F1), `last_message` (`show -s --format=%B HEAD`, none before the first commit; C6 F1), `create_branch` (name checked with `check-ref-format --branch`, which must echo the name unchanged, so `@{-1}` is refused; `switch -c` or `branch --end-of-options`). Names and revisions starting with `-` are refused. Changes hold a per-repository mutex.
- `RepoWatch` polls `HEAD`, `index`, `MERGE_HEAD`, `ORIG_HEAD`, `packed-refs` and the files under `refs/heads` and `refs/remotes` (at most 4,096) every 250 ms on its own thread, comparing size and modification time. The project watcher never sees `.git`, and OS notifications on a directory whose object store churns on every commit would be noisier than a few `stat` calls. `rebase()` takes the current state as the baseline after Lutra's own change.
- **Engine (`crates/engine/src/cmd/git.rs`):** every `git.*` command returns a pending outcome (M3.5). Under the lock it parses its params and takes the setting, the cached git and the cached repository; a `lutra-git` thread detects git and opens the repository when they are not cached, runs the call and fills a reply slot (the `Pending` channel only signals). The finish caches git (per setting value) and the repository (per project root), starts the watch, and emits `gitChanged` after a change. At most 32 calls run at once. Hosts and the UI call these commands with `run_waiting` / `runWaiting`.
- **Commands** (all need a project):
- `git.status` → `{available, error?, repo: {root, branch?, detached, head?, upstream?, ahead?, behind?} | null, files: [{path, origPath?, index, worktree}]}`. Without a usable git: `available: false` and the reason. Outside a repository: `repo: null, files: []` (and `error` if git refused, such as an unsafe owner). `root` is the work tree root as git prints it (absolute, `/`).
- `git.stage {paths}` / `git.unstage {paths}` → `{}`; for a staged rename pass both paths.
- `git.commit {message, amend?}` → `{commit, summary}`; a blank message is `invalid_params`.
- `git.show {path, ref: "HEAD"|"index"}` → `{text|null, binary, tooLarge}`.
- `git.branches` → `{current|null, local: [{name, head, upstream?}], remote: [{name, head}]}` sorted by name, without `origin/HEAD`.
- `git.lastMessage` → `{message|null}`: the full message of HEAD without trailing line breaks, null before the first commit (C6 F1, for the Amend prefill). Read-only, no `gitChanged`.
- `git.checkout {branch}` → `{}`; git's refusal is the error text. A remote branch without a configured remote becomes an untracked local branch (C6 F1). Open buffers follow through the file watcher.
- `git.createBranch {name, from?, checkout}` → `{}`.
- Bad paths, names or messages are `invalid_params`; everything git refuses is `failed` with git's message; no project is `disabled`.
- **Event `gitChanged {available, repo, filesChanged: true}`:** after every successful change (in the same outcome), and 300 ms after the last change the `.git` watch or the project watcher reported (at most 2 s after the first), from a `head()` query on its own thread. The UI re-queries `git.status`.
- **Measured** (debug build, Windows 11, git 2.47.1, over the control channel on port 7941, so each number includes the round trip and the pending wait):
- A temp repository: the first `git.status` 367 ms (it detects git and opens the repository), then 80–96 ms; `git.stage` 171 ms, `git.show` 153 ms, `git.commit` 279 ms, `git.createBranch` 244 ms, `git.branches` 73 ms, `git.checkout` 247–257 ms. A blank message is refused at once (`invalid_params`).
- The Lutra repository (336 tracked files): first `git.status` 208 ms, then 102–111 ms.
- A generated repository with 20,000 committed PHP files, 5 modified and 1 untracked: first `git.status` 1.5 s (cold file cache), then 90–98 ms.
- **Tests:** `crates/vcs/tests/repo.rs` (13 tests against real temp repositories: initial repository without HEAD, stage/unstage/commit, amend, modified/deleted/renamed, CRLF with `core.autocrlf`, Unicode and space paths, literal pathspecs and a non-UTF-8 name on Unix, detached HEAD, branches, remote tracking checkout from a clone, a refused checkout, a file over the cap, binary, BOM and Latin-1 files, a failing pre-commit hook, nothing staged, a project inside a repository, the watch); unit and property tests of the parsers; `crates/engine/tests/git.rs` (4 tests through `run_waiting`: the command shapes, `gitChanged` after changes and from outside changes, no repository, a missing git, no project). Tests skip with a message when git is not installed.
### Changes tool window (M4.2)
- **Where:** a Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): `changes.ts` is the Pinia store, `ChangesToolWindow.vue` the window. The main layout starts the store when it mounts, so the status is current before the tab opens, and supplies the UI commands.
- **Commands** (UI commands, menu group Git): `vcs.openChanges` `Mod+Alt+Shift+G` shows the tab; `vcs.commit` `Mod+Alt+Shift+M` shows it and focuses the message box; `vcs.refresh` re-reads the status (enabled while `git.status` is). The shortcuts are Lutra's own: checked against the public default keymaps (Windows and macOS) so they copy no default there, and against Lutra's registered shortcuts and CodeMirror's `basicSetup` keys (`Mod+Alt+G` is its go to line, which the global listener would swallow).
- **Status:** read from the shared status store (`ui/src/stores/vcsStatus.ts`, since C6 F1), which runs `git.status` on start, on `projectOpened`, on `gitChanged` and on `vcs.refresh`; `projectClosed` clears it and with it the rows and the selection. The result is untrusted: unknown states and malformed entries are dropped, at most 50,000 files.
- **Amend prefill (C6 F1):** checking Amend with an empty message box fills it from `git.lastMessage`; clearing Amend empties a box that still holds exactly that text. A message already typed is never replaced. The event type `gitChanged` is now part of `EngineEventPayload` in `ui/src/ipc.ts`.
- **Groups:** Staged (the index side changed), Changes (the work tree side changed, or conflicted), Untracked. A partly staged file is in Staged and Changes. Names are coloured with `--lt-vcs-*` (renamed and modified use `modified`, copied uses `added`); a deleted file is struck through. A staged rename shows "from <old path>".
- **Staging:** a checkbox per file and per group header: checked in Staged (clearing it unstages), clear elsewhere (checking it stages). `git.stage {paths}` / `git.unstage {paths}`, both through `runWaiting`; unstaging a staged rename passes both paths, as M4.1 requires. Keyboard: Up/Down, Page Up/Down, Home, End move; Space stages or unstages; Enter opens. Failures toast git's message (`notification.command.failed`).
- **Opening:** Enter or a double-click runs the UI command `vcs.showDiff {path, staged}` when something provides it (the diff viewer, M4.3, registers and provides it); until then the file opens with `file.open`, and a deleted file does nothing.
- **Commit:** a message box, an Amend checkbox and Commit (`Mod+Enter` in the box as well). Commit is enabled with a non-blank message and staged files, or with Amend. It runs `flushDirty()` first; a failed save cancels the commit with a warning (`notification.vcs.commitNotSaved`) and changes nothing. Then `git.commit {message, amend}`; success toasts "Committed <short hash>: <summary>" (7 characters), clears the box and Amend; a refusal (a hook, nothing to commit) toasts git's message and keeps the box.
- **States without a repository:** git missing or too old shows git's reason and a hint to Settings › Git executable; a project outside a repository and a clean tree say so; the status line names the branch, or the short hash when detached, or "no commits yet".
- **Tests:** `ui/tests/vcs/ChangesToolWindow.test.ts` (19 Vitest tests against a fake engine: parsing and grouping, rename unstaging, refresh triggers and serialisation, staging per file and group, git's error as a toast, commit after `flushDirty` with the short hash, a commit cancelled by a failed save, amend without staged files, the window's status lines, checkboxes, keyboard, `vcs.showDiff` and the `file.open` fallback, the commands' shortcuts and menu paths in the layout).
### Line changes, gutter markers and status colours (M4.4)
- **`git.lineChanges {id}`** (`crates/engine/src/cmd/git_lines.rs`, a pending outcome) → `{ranges: [{kind: added|modified|deleted, startLine, endLine}], version}`: the buffer's lines against the file's blob in the index. Lines are 0-based, `endLine` exclusive; a `deleted` range has `startLine = endLine`, the removed lines were before it (at the line count when they were at the end). `version` is the buffer version the ranges are for (an addition to the C5 contract). No ranges, not an error, when the project has no repository, git is unusable or the file is not in the index (untracked, binary, over 32 MiB, conflicted); an unknown buffer is `failed`.
- **Off the lock:** under the lock the command clones the buffer's rope (shared chunks, no copy) and takes the cached lookups; a `lutra-git-lines` thread detects git and opens the repository through `lutra-vcs` when needed, reads the blob with `Repo::show(path, Rev::Index)` when it is not cached, and diffs. At most 8 calls run at once. It keeps its own repository lookup instead of reaching into `cmd::git`'s state (no change to M4.1's file).
- **Line endings:** both texts are split at `\n`, `\r\n` and a lone `\r`, without an empty line after a final break, so a CRLF buffer equals its LF index blob (autocrlf) and a missing final newline is not a change. The lines match CodeMirror's.
- **Diff:** `similar` 2.7.0 (Apache-2.0, no default features, no dependencies), Myers with a 1 s deadline, adjacent deletes and inserts merged into replacements (`Replace` hook), at most 10,000 ranges. Its `Compact` step is not used: in 2.7.0 it moved a delete to a wrong position in the new text (found by the property test, kept as a unit test).
- **Cache:** index texts per path (at most 256 files or 64 MiB, cleared when full), dropped on every `gitChanged`: `State::emit` calls `git_lines::observe` for each event (one line in `state.rs`), and a generation counter keeps a thread that started before from storing stale text. A project change drops everything. "No repository" and "no usable git" are kept for 10 s only, because no `gitChanged` arrives without a repository.
- **Gutter** (`ui/src/components/editor/gitGutter.ts`, appended to `editorExtensions` for buffers): a 4 px gutter beside the code with a bar on added (`--lt-vcs-added`) and modified (`--lt-vcs-modified`) lines and a 3 px notch at the top of the line after deleted ones (`--lt-vcs-deleted`; at the bottom of the last line for deletions at the end), each with a catalog tooltip. A view plugin asks with `runWaiting` when the view shows the state, 150 ms after the last edit, and on `refreshGitGutters()` (every `gitChanged`); it waits for the buffer sync's `idle()` and drops answers for a document that changed meanwhile. Between answers the markers are mapped through the edits. A failure keeps the markers. Background tabs refresh when shown again.
- **Status colours** (`ui/src/stores/vcsStatus.ts`, Pinia `vcsStatus`, started by `App.vue`): `git.status` through `runWaiting` on start, `projectOpened` and every `gitChanged` (never polled), one query at a time plus one more for requests made meanwhile, answers for a closed project dropped. A file's two states fold into one token: conflicted, untracked, ignored, added (unless deleted again in the work tree), deleted, otherwise modified. The project tree and the editor tabs colour file names with `--lt-vcs-*` classes; inside a repository the tree also gives ignored entries `--lt-vcs-ignored` (`git.status` does not list them). Directories are not coloured. The contrast test also checks the status colours on the active tab.
- **Shared status store (C6 F1):** `vcsStatus` is the only caller of `git.status` in the UI. It keeps the snapshot (`snapshot`, read by `toStatus`: files, `repo` with branch, head, upstream, ahead and behind), `loading`, `loadError` (a failure keeps the last snapshot; `disabled` drops it) and the colours. The Changes window, the tree and tab colours and the branch status-bar item (M4.5) all read it, so each `gitChanged` costs one `git.status`; one round at a time, requests during a round share one more. `start` / `stop` are counted (`App.vue` and the main layout both hold it). Later features read `snapshot` and call `refresh()`, never `git.status`.
- **Measured** (debug build with the bundled UI, Windows 11, git 2.47.1, control port 7944, a temp repository with the owner's global `core.autocrlf`; each number includes the control round trip and the pending wait): the first `git.lineChanges` 332 ms (git detection, opening the repository, reading the blob), then 0.4–1.4 ms with the index text cached; after `git.stage` (158 ms) the next call reads the blob again and returns no ranges. Screenshots read in both themes: a modified bar, a deleted notch and an added bar where expected, no markers after staging, tabs in the modified and untracked colours, no markers for the untracked file. No keys were sent (owner at the PC).
- **Tests:** `cmd::git_lines` unit and property tests (line splitting, kinds, line endings, empty files, cache caps and generation, ranges in order and inside the buffer); `crates/engine/tests/git_lines.rs` (4 tests against real temp repositories: added/modified/deleted, a CRLF buffer against an autocrlf LF blob, staging drops the cache, an untracked file and no repository, bad params); Vitest `ui/tests/editor/gitGutter.test.ts` (12: reading, building, query on show, debounce, stale answers, failures, refresh, mapping), `ui/tests/vcs/vcsStatus.test.ts` (colours, reading, coalescing, events, tabs) and one tree test in `ui/tests/project/ProjectTree.test.ts`.
### Diff viewer (M4.3)
- **Where:** `ui/src/components/vcs/diff/`: `diff.ts` is the Pinia store of the diff tabs, `DiffView.vue` the view (loaded with `defineAsyncComponent`, so `@codemirror/merge` sits in its own 27 kB chunk, 9.7 kB gzip, not in the start bundle), `navigation.ts` the bridge to the next/previous change commands, `commands.ts` the handlers, supplied by the editor area. The project tree's context menu is `ui/src/components/project/TreeContextMenu.vue`.
- **Dependency:** `@codemirror/merge` 6.12 (MIT, Marijn Haverbeke; depends only on CodeMirror packages, `@lezer/highlight` and `style-mod`).
- **Commands** (UI commands, menu group Git): `vcs.showDiff {path?, staged?}` `Mod+Alt+Shift+D` opens the diff of a file (without a path: the active diff's or editor tab's file; enabled while a project is open); `vcs.nextChange` `Alt+Shift+]` and `vcs.previousChange` `Alt+Shift+[` move the cursor of the focused side (else the working copy) to the next or previous changed chunk, wrapping, and are enabled while a diff with changes shows. The shortcuts are Lutra's own: checked against the public default keymaps (Windows, macOS; the target uses other keys for show diff and next/previous difference), Lutra's registered shortcuts and CodeMirror's `basicSetup` keys.
- **Entry points:** double-click or Enter in the Changes window (`staged` true for a Staged row), the project tree's context menu (right click on a file, or Shift+F10 / the context-menu key on the selected file: Open, Show Diff), the palette and the menu.
- **Tabs:** diff tabs live in the diff store, not in the editor store: one per path and side (`staged:` / `work:` key), shown after the file tabs and titled "Diff: <name>" ("Diff: <name> (staged)" for the staged view). A diff covers the editor tab that was active when it was activated (the anchor; a synchronous watch on `editor.activeId` re-anchors while the diff opens its file and hides the diff when any other editor tab becomes active). Clicking a file tab hides it; closing the working copy's buffer, a project open or a project close closes diff tabs.
- **Left side:** `git.show {path, ref}` through `runWaiting`: `staged: true` compares with HEAD, otherwise with the index (equal to HEAD without staged changes, so a partly staged file shows only what is left to stage). A path missing at the ref is an empty side (a new file). Line breaks are normalised to `
` (git returns the blob as stored, LF under `core.autocrlf`; CodeMirror compares lines, so a CRLF working copy lines up). Re-read on `gitChanged`; a changed text replaces the left document in place. Binary or too large (`git.show`'s flags) shows a notice and opens nothing; a failed `git.show` shows git's message.
- **Right side:** the working copy is opened as an ordinary engine buffer through the editor store (it also gets its own file tab, hidden while the diff shows), so edits, saves, autosave, the journal and diagnostics work as in any tab. The right editor starts from the buffer's `BufferSync` state with the normal editor extensions; an update listener hands each local change to the sync (`sync.dispatch`, the diff of the documents if they ever differ), which sends `buffer.edit` as usual. Engine changes of the buffer (reload, an agent's edit) arrive as `bufferChanged`; once the sync has taken them over (`idle()`), the difference is applied to the right editor outside its undo history. A file missing from the working copy (deleted) shows an empty read-only side and a notice; the editor's error line is not raised for it.
- **Look:** both sides use the Lutra editor theme and the file's language; changed lines are tinted with `color-mix` of `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right) into `--lt-editor-bg`, changed words more strongly, a change bar in each gutter, unchanged stretches over 8 lines collapse to a row (3 lines of context). No colour outside the tokens.
- **Tests:** `ui/tests/vcs/DiffView.test.ts` (21 Vitest tests against a fake engine: params and `git.show` parsing, EOL normalisation, index and HEAD sides, one tab per side, the palette without a path, bad params and no file as toasts, disabled without a project, edits on the right reaching `buffer.edit`, engine changes reaching the right side, the left side refresh on `gitChanged`, closing with the buffer, binary / too large / git error / deleted / new file, switching between diff and file tabs, next/previous change with wrap-around, the tree context menu by right click and by Shift+F10 with Escape).
### Branches (M4.5)
- **Where:** `ui/src/components/vcs/branches/`: `branches.ts` is the Pinia store, `BranchStatusItem.vue` the status-bar item (one line in `StatusBar.vue`, after H3's progress item), `BranchPopup.vue` the popup. The item supplies the UI commands, so they exist wherever the status bar is.
- **Status-bar item:** the current branch from the Changes store's `git.status` (no second query; it follows `gitChanged`), or the first 7 characters of HEAD when detached; hidden outside a repository, while git is missing and before the first status. A click runs `vcs.branches`.
- **Popup:** above the status bar's right end. A filter field (every word must occur in the name, ignoring case), "New branch…", then Local and Remote headings with their branches sorted by name; the current branch has a check and "current", a local branch shows its upstream. `git.branches` (through `runWaiting`) is read each time it opens; the first branch is selected once the list arrives. Up/Down/Page Up/Page Down move, Enter or a click chooses, Escape or a click outside closes and gives the focus back. Choosing the current branch only closes it. It is an exclusive modal (`ModalId` `branches`). The answer is untrusted: malformed entries are dropped, at most 10,000 per kind.
- **Checkout:** choosing a branch closes the popup and runs `vcs.checkout {branch}`: `flushDirty()` first; a failed save cancels with a warning (`notification.vcs.checkoutNotSaved`) and git is not called. Then `git.checkout`; git's refusal (local changes would be overwritten, an unknown branch) becomes an error toast `notification.vcs.checkoutFailed {branch, reason}` with git's text, success an info toast. A remote branch (`origin/x`) checks out its tracking branch (M4.1). Open buffers whose files changed reload through the watcher; the status follows `gitChanged`.
- **New branch:** "New branch…" (taking the filter text as a first name) or `vcs.newBranch` shows a name field and a "Check out" checkbox (on). Create runs `git.createBranch {name, checkout}` from HEAD; nothing is saved first because creating and switching from HEAD leaves the files alone. A blank name or git's refusal (invalid name, an existing branch) shows under the field (`role="alert"`) and the popup stays; Escape goes back to the list.
- **Commands** (UI commands, menu group Git, no default shortcuts): `vcs.branches` (Git › Branches…), `vcs.newBranch {name?, checkout?}` (Git › New Branch…; with a `name` it creates the branch without the popup, checked out unless `checkout: false`, and toasts a refusal), `vcs.checkout {branch}` (without `branch`, as from the palette, it opens the popup; a `branch` that is no non-blank string toasts an error). All are enabled while `git.branches` is (an open project).
- **Tests:** `ui/tests/vcs/Branches.test.ts` (16 Vitest tests against a fake engine: parsing, filter, head label, the item's states, popup order and marking, filtering, keyboard, checkout after `flushDirty` through `runWaiting`, a refusal toast, a cancelled checkout, creating with a blank name, a refusal and success, Escape back to the list, the commands' registration, params and enabled state).
## 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-27 | minor | C6 F1: remote branch checkout without a configured remote (`--no-track`), `git.lastMessage` and the Amend prefill, one shared git status store |
| 2026-10-26 | minor | M4.5: branches (status-bar item, popup, `vcs.branches`, `vcs.newBranch`, `vcs.checkout`) |
| 2026-10-26 | minor | M4.3: diff viewer (`vcs.showDiff`, `vcs.nextChange`, `vcs.previousChange`, `@codemirror/merge` loaded lazily, the project tree's context menu) |
| 2026-10-25 | minor | M4.4: `git.lineChanges` (index cache, `similar` line diff off the lock), gutter change markers, Git status colours in the tree and tabs |
| 2026-10-25 | minor | M4.2: Changes tool window (`vcs.openChanges`, `vcs.commit`, `vcs.refresh`, staging, commit after `flushDirty`) |
| 2026-10-25 | minor | M4.1: Git backend (`lutra-vcs`, `git.*` commands, `gitChanged`, `git.executable`) |
| 2026-10-24 | minor | H4: string and path controls in the settings dialog (`pick_file` IPC), assist settings (auto popup, completion delay, hover delay) read live |
| 2026-10-25 | minor | H5: banner-aligned light and dark palettes, `DIAGNOSTIC_TOKENS` and `VCS_TOKENS`, completion icon colours by kind, contrast test extended |
| 2026-10-25 | minor | H3: Phpactor UX: fast tick while indexing (1 ms, sleep-based), `lspProgress` and the status-bar item, `window/showMessage` as notifications, `lsp.log`, Lutra's own `php -l` on Windows |
| 2026-10-25 | minor | H6: isolated data directory (`--data-dir`, `LUTRA_DATA_DIR`, `--control` temp dir), shared tools dir, rendezvous order |
| 2026-10-24 | minor | H1: `crates/proc` (L0), child processes in kill-on-close groups (Windows job objects, Unix process groups with a watchdog); Phpactor and the PHP probe use it |
| 2026-10-22 | minor | M3.5: definition, references, rename (`lsp_nav`, workspace edits, undoable remote edits, nav UI) |
| 2026-10-22 | minor | M3.4: code assistance (`lsp.completion`, `lsp.hover`, `lsp.signatureHelp` on pending outcomes; editor completion source, hover, signature help, safe Markdown, assist UI commands), Phpactor latency and resources |
| 2026-10-22 | minor | M3.5 step 1: pending outcomes (`Pending`, `Engine::resolve`, `run_waiting`), `engine_execute_waiting` / `runWaiting` |
| 2026-10-20 | minor | M3.10: autosave (blur, tab switch, idle), `flushDirty`, `file.saveAll {skipConflicts}`, disk conflicts and own-write hashes in `Buffers` |
| 2026-10-21 | minor | M3.3: engine ↔ Phpactor wiring (session thread, ordered sync, `lspStatus`, `diagnosticsChanged`, `diagnostics.list`, `lsp.status`, `lsp.restart`), Phpactor-on-Windows workarounds, lint extension, Problems tab |
| 2026-10-19 | minor | M3.8: MCP server (`lutra mcp`, dual era 2026-07-28 + legacy `initialize`), tools, resources, event buffer; `buffer.list` |
| 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.6: integrated terminal (`crates/terminal` sessions, backpressure, `terminal.*`, `terminalOutput`/`terminalExited` via the pump, lifecycle, xterm.js views, terminal tokens, focus rule, bottom panel tabs) |
| 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 |