M3.7: lutra CLI and single instance

- crates/control: rendezvous file (<data_dir>/instance.json, port + random
  token, atomic write, 0600 on Unix, stale detection), token-protected
  listener (start_with_token, app.auth first, constant-time compare,
  10 s auth timeout), app.focus, and a blocking client (connect_live,
  request/execute/subscribe/next_event, open_folder/open_file/reveal)
- lutra-desktop: a normal start forwards its path to a running instance
  and exits, otherwise claims the rendezvous; --control instances skip it
  unless LUTRA_RENDEZVOUS_DIR is set; non-Unicode args are usage errors
- lutra-cli (binary lutra, now L6): path[:line[:column]] targets, folder ->
  project.open, file -> file.open (parent opened without a project, outside
  the project refused), editor.reveal, starts the desktop if needed,
  --wait until bufferClosed, --version/--help, exit codes 0/1/2
- tests: proptest target parsing, rendezvous read/write/stale, token check
  over TCP, forwarding against a test backend, --wait end to end
- docs: architecture, G7, ROADMAP (agent automation 18% est.), roadmap,
  README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-18 00:23:09 +02:00
parent 9ccfc1bf6a
commit 9b278099cf
26 changed files with 2162 additions and 37 deletions

View file

@ -1,13 +1,13 @@
# 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 · **Last updated:** 2026-10-17
> **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 · **Last updated:** 2026-10-17
## 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 (L5) the `lutra` command: open, diff, --wait, mcp, perf, bench
apps/lutra-cli (L6) the `lutra` command: open, --wait; later diff, mcp, perf, bench
crates/control (L5) JSON-lines control channel (--control PORT)
crates/mcp (L5) MCP server over stdio
crates/engine (L4) command registry, workspace state, guard, recovery journal, theme tokens
@ -59,11 +59,27 @@ As built in M0:
- 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`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`, `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`.
- Methods: `app.ping`, `app.auth {token}`, `app.focus`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`, `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`.
- `events.subscribe` answers `{subscribed: true}` and from then on writes `{"event": {...}}` lines for every engine event on that connection, between responses; a shared writer writes each line whole. Subscribing twice is a no-op. Each subscriber has a queue of 4096 events (`lutra_control::EVENT_QUEUE`); a subscriber that falls behind or disconnects is dropped by `Subscribers::publish`, and the connection gets a final `{"event": {"kind": "subscriptionLost"}}` line if it is still open.
- `lutra_control` defines a `Backend` trait; the desktop app implements it (engine access, effects, screenshots, event subscribers), tests implement it with a bare engine (`lutra_testkit::EngineBackend`). Hosts publish each outcome's events through `lutra_control::Subscribers`. One thread accepts connections and each connection gets its own thread; no async runtime is needed in the crate.
- Screenshots: `xcap` does not enumerate windows of its own process (querying their titles can deadlock), so the desktop focuses its main window, reads the client area's physical position and size from Tauri and captures that region of the monitor with `xcap::Monitor::capture_region`. Windows covering Lutra at that moment appear in the image. A webview-native capture (WebView2 `CapturePreview`, WKWebView snapshots) can replace it later.
### CLI and single instance (M3.7)
- **Rendezvous file:** a desktop that owns the single instance serves a second, token-protected control listener on a free port of `127.0.0.1` (`lutra_control::start_with_token`) and writes `<data_dir>/instance.json` = `{port, token, pid, version}` (`lutra_control::rendezvous`). The token is 32 bytes from the OS generator (`getrandom`), hex. The file is written to a temporary file and renamed, so readers never see half a file; on exit the app removes it if it still holds its own token.
- **Directory:** `LUTRA_RENDEZVOUS_DIR` if set, else `rendezvous::default_data_dir()`, which computes Tauri's `app_data_dir()` for the identifier `dev.lutra.desktop` without Tauri (`%APPDATA%\dev.lutra.desktop` on Windows, `~/Library/Application Support/dev.lutra.desktop` on macOS, `$XDG_DATA_HOME` or `~/.local/share` + the identifier elsewhere), so the CLI and the desktop agree without sharing a runtime.
- **Security:** only the user may read the token. Unix: the file is created with mode `0600`. Windows: it lives in the user's roaming AppData folder, whose inherited ACL grants the user, `SYSTEM` and Administrators only (checked with `icacls` in the M3.7 live check); Lutra sets no ACL of its own. Both listeners bind `127.0.0.1` only. On the token listener the first request must be `app.auth {token}` within 10 s (`AUTH_TIMEOUT`); a wrong token, another method or garbage gets `unauthorized` and the connection is closed. Tokens are compared in constant time. The `--control PORT` listener stays open (no token) for development and agents; it is opt-in and documented as such.
- **Second start:** `lutra-desktop [PATH]` without `--control` reads the rendezvous file first. If the listener answers, accepts the token and pings, the start forwards `PATH` (folder → `project.open`, file → `file.open`), calls `app.focus` and exits 0. If the file is missing, unreadable, invalid, or its port refuses or rejects the token, it is stale: this start becomes the instance and replaces the file. Two starts in the same instant can both become instances; the later file wins (accepted, rare).
- **Development instances:** a start with `--control PORT` skips the single instance (no forwarding, no rendezvous file) so parallel agents' instances never forward to each other, unless `LUTRA_RENDEZVOUS_DIR` is set, which opts it into the single instance in that directory (used for isolated live checks).
- **New methods:** `app.auth {token}` (always succeeds on the open listener) and `app.focus` (restore, show and focus the main window; `focus_failed` without a window; `Backend::focus` has a default that fails, so test backends need no change).
- **`lutra` CLI** (`apps/lutra-cli`, binary `lutra`, now L6 so it can use `lutra-control`): `lutra [--wait] [PATH[:LINE[:COLUMN]]]...`.
- **Targets:** up to two trailing `:N` groups are a 1-based line and column (`N` all digits, something before it; on Windows a lone drive letter is never split). If the path part does not exist but the whole argument does, the argument is the path. Paths are made absolute against the current directory without resolving symlinks.
- **Opening:** a folder (at most one, no position) → `project.open`. A file → `file.open`; with no project open its parent folder is opened first. **A file outside the open project is refused** (exit 1, the engine's `… is outside the project`), because Lutra has one window and replacing the project behind the user's back could lose their context; out-of-project buffers are a gap (G7). A line → `editor.reveal {path, line-1, column-1}`, retried for up to 20 s while the window has not registered its UI commands yet (`unknown_command`).
- **Starting Lutra:** if no instance answers, the CLI starts the desktop detached (`LUTRA_DESKTOP`, else `lutra-desktop` next to `lutra`, else on `PATH`) and polls the rendezvous file for up to 60 s.
- **`--wait`:** subscribes before opening, then blocks until every opened file's `bufferClosed` arrived (or `projectClosed`, or the connection ends because Lutra quit). A `subscriptionLost` renews the subscription and checks the remaining ids with `buffer.get`. Folders are not waited for.
- **Exit codes:** 0 ok, 1 error (cannot start, open failed, missing path), 2 bad usage (unknown option, line or column 0 or too big, two folders, a positioned folder, non-Unicode argument). Arguments are untrusted; parsing is property-tested.
- **Rendezvous API for M3.8 (`lutra mcp`):** `lutra_control::client::connect_live(&rendezvous::dir()?, timeout)` returns the `Instance` and an authenticated `Client`; `Client::request(method, params)`, `execute(command, params)`, `subscribe()`, `next_event(timeout)` (events read while waiting for a response are queued, at most 4096), `open_folder`, `open_file`, `reveal`, `focus`. To start Lutra when none runs, reuse the CLI's `launch` logic (move it into the client if MCP needs it outside the CLI binary). Response lines are capped at 64 MiB.
## Frontend ↔ engine
The frontend calls `run(id, params)` over Tauri IPC (`engine_execute`, `engine_list_commands`) and subscribes to state events. Buffer contents live in the engine; CodeMirror sends edits as transactions and receives authoritative changes back.
@ -290,6 +306,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 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 |