# will-save-wait-until ## Goal Serve `textDocument/willSaveWaitUntil`, the protocol's own format-on-save hook: the client asks the server for edits *before* it writes the file, waits for the answer, and applies whatever comes back. VS Code users already have `editor.formatOnSave`, which runs the ordinary `textDocument/formatting` request — this exists for the editors that have no format-on-save of their own, and for users who would rather the server owned the decision than their editor config. Because a capable client sends this on **every** save of every buffer, and because a server that formats uninvited would fight (and double up on) an editor that already formats, the hook is gated on a new `lucisv.formatOnSave` setting that is **off** by default and answers `null` in one comparison. When it is on, this is `textDocument/formatting` with a different trigger — the same engine, the same settings, the same all-or-nothing contract (CLAUDE.md invariant #1) — so a save can never write anything a manual format would not. ## Assumptions - **Off by default, and the decline is cheap.** `lucisv.formatOnSave` unset, `false`, or wrong-typed all mean off. The handler returns `null` before it looks at the buffer, the workspace, or a `lucisv.toml`. The safe direction for a setting that rewrites the user's file on every save is the one that does nothing, so a value that is not the JSON boolean `true` is dropped exactly as every other wrong-typed setting in `settings.rs` is. - **A plain `bool`, not an `Option`.** Every other field of `ClientSettings` is "no opinion until a client says otherwise" because it has a rung below it to fall through to. This one does not: unset and off are the same answer, and there is no `lucisv.toml` key for it (the config file describes *style*, and whether an editor formats on save is not style — it is an editor behavior, and it belongs to the person at the editor). - **Every save reason formats.** `Manual`, `AfterDelay` and `FocusOut` all write the file, and a user who asked for their saves to be formatted asked about all three. The `reason` field is decoded and deliberately not read. A future knob could restrict it; none is built, because no one has asked for one. - **The text is the buffer the server holds.** The request carries no text — it arrives *before* `didSave`, and before the client has written — so what gets formatted is what `didOpen`/`didChange` built. That is the same text every other request in this server answers from. A buffer the server does not hold answers `null` rather than reading the file from disk: the file on disk is precisely the stale copy the save is about to replace. - **No `tabSize` on this path, and it can differ from a manual format.** The protocol sends `FormattingOptions` with `textDocument/formatting` and `rangeFormatting`; it sends nothing of the sort with `willSaveWaitUntil`. So the settings ladder in `format::settings_for` runs with rung 3 missing — `lucisv.toml` > `lucisv.indent` > the built-in 2 — exactly as it already does for a lint fix's indent (`format::indent_width`). **Honest consequence:** a user with no `lucisv.toml` and no `lucisv.indent`, whose editor tab size is 4, gets 4-space indent from a manual format and 2-space indent from a save. That is a gap in the protocol, not a bug we can close from here — the request simply does not carry the number — and the fix a user has is to say what they want once, in a `lucisv.toml` or in `lucisv.indent`. It is written down in `editors/vscode/package.json`'s setting description and in `editors/nvim/README.md` so nobody has to discover it by diffing a save. - **A formatter refusal is shown on every save, on purpose.** `edits()` is reused unchanged, so an unparsable buffer produces no edit and one ERROR message — per save, not once per file change. The alternative (dedup, the way `warn_about_config` dedups a broken `lucisv.toml`) was rejected: that warning is about a *config file* the user is not editing, while this is about the save the user just performed. A save the user asked to be formatted, that was not formatted, is worth saying every time it happens; going quiet would leave the user believing their file was formatted when it was not. The repetition is bounded by the user's own saves, and the broken-config warning keeps its dedup — though QA sharpened what that dedup actually is (see the QA log): it is cleared by `set_document`, so a save whose own edit comes back through `didChange` re-arms it for the *next* save. Once per buffer state, not once per broken config; still bounded by the user's saves either way. - **The capability is advertised unconditionally**, even though the default answers `null`. It has to be: the setting can be pushed mid-session, and `initialize` is the only time the sync options are sent. A client whose user never turns it on pays one round trip per save for a `null`. - **`willSave` (the notification) stays unadvertised.** It carries no reply, so there is nothing this server could do with it that `didSave` does not already cover. ## Handshakes - **Consumes `format::settings_for` / `format::formatting`** — the same two calls `Server::formatting` makes, in the same order, so the two paths cannot drift. Added one function to `format.rs`, `settings_without_editor_options(doc, client)`, which is `settings_for` with a `FormattingOptions` that opts out of rung 3 (hard tabs, zero width — values `config_from` already refuses). It is the options-less sibling of `indent_width`, and it lives in `format.rs` so the reasoning about the precedence ladder stays in one file. - **Consumes `Server::edits`** unchanged — the all-or-nothing reply shape, and the ERROR message on a refusal. `Ok(None)` becomes `[]`, matching what `textDocument/formatting` answers for an already-formatted buffer; a test asserts the two are byte-identical rather than merely equivalent. - **Consumes `Server::warn_about_config`** unchanged — a broken `lucisv.toml` is reported once per buffer state (the dedup is cleared by `set_document`; see the Assumptions bullet and the QA log for the exact bound), which keeps a save loop that changes nothing from repeating it. - **Adds one field to `settings::ClientSettings`** (`format_on_save: bool`, from `lucisv.formatOnSave`). `Workspace::set_client_settings` needed no change: the field moves no files, so it does not ask for a reindex, and it is read afresh by each save exactly as `indent`/`lineLength` are read afresh by each format. - **Changes what the client is told at `initialize`:** `text_document_sync.will_save_wait_until` moves from `None` to `Some(true)`. Nothing else in the sync options moves — `will_save` stays `None`, `change: INCREMENTAL` and `save.includeText: false` are untouched — so no client's sync or save behavior changes beyond gaining one request it may now send. - **Editor packaging:** `lucisv.formatOnSave` declared in `editors/vscode/package.json` (default `false`); no `extension.js` change was needed, because the client already pushes the whole `lucisv` section (`synchronize.configurationSection: 'lucisv'`) and `vscode-languageclient` registers the will-save feature from the advertised capability on its own. `editors/nvim/README.md` documents the setting next to the `BufWritePre` autocmd it is an alternative to, including the tab-settings caveat above. - **No other crate is touched, and no new dependency.** ## Status / TODO - [x] Advertise `will_save_wait_until: Some(true)`; leave `will_save` `None`. - [x] `lucisv.formatOnSave` in `settings.rs`, default off, wrong types dropped. - [x] `WillSaveWaitUntil` arm in the request dispatch + `will_save_wait_until` handler: off → `null`, unopened → `null`, on → the formatting path. - [x] `format::settings_without_editor_options` — the ladder with no `tabSize` rung. - [x] Reuse `edits()` and `warn_about_config()` unchanged. - [x] Settings unit tests (present true/false, absent, wrong types, the default VS Code payload). - [x] `format.rs` unit test for the options-less ladder. - [x] Server-level tests: off → `null` and silent; on → the edit; identical to what `textDocument/formatting` answers; every save reason; unopened buffer; already-formatted buffer → `[]`; unparsable buffer → no edits + one ERROR per save; setting toggled on and off mid-session. - [x] Idempotency guard: apply the edit, ask again, get no edits. - [x] e2e: the capability on the wire, the push, the edit, the second save. - [x] `editors/vscode/package.json` + `editors/nvim/README.md`. - [x] `docs/features/lucisv-server/README.md` capability table. - [x] TODO.md §9b item checked off. ## Work log **2026-08-26 — dev.** Implemented in one round; no deviations from the plan. - **`main.rs`**: one field of the existing `TextDocumentSyncOptions` moved, `will_save_wait_until: None` → `Some(true)`, with the reasoning in a comment next to it. New test `the_sync_options_ask_for_the_save_hook_and_not_the_ notification` pins both that and `will_save: None`, since "advertise exactly what we implement" is the rule that block already lives by. - **`settings.rs`**: `format_on_save: bool`, parsed with the existing `flag()` helper plus `.unwrap_or(false)`. Chose `bool` over `Option` deliberately — see Assumptions; the type says "unset is off", which is the actual semantics, and it keeps every reader from writing `.unwrap_or(false)` at the use site. The `vscode_payload` test helper gained `"formatOnSave": false` so it stays the real shape of what the extension pushes, and `the_default_vscode_payload_is_no_opinion_about_anything` still passes unchanged (the default *is* the `Default` value). - **`format.rs`**: `settings_without_editor_options`. The alternative — calling `settings_for` with `FormattingOptions::default()` from the handler — works (its `insert_spaces: false` makes rung 3 inert), but it makes server.rs depend on a default value being inert somewhere else. A named function with the reasoning attached costs three lines and makes the precedence decision greppable from the module that owns precedence. - **`server.rs`**: one dispatch arm and one handler. The handler is five statements and reads top to bottom: setting → buffer → settings → format → warn → `edits()`. The setting check comes *first*, before the workspace lookup, because the decline is the hot path — this arrives on every save. - **The error-on-every-save decision** was the one real judgement call; it is argued in Assumptions and pinned by `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`, which drives two saves and asserts exactly one ERROR each time. If a user ever complains, the change is a dedup keyed on (uri, generation) — but guessing at that now would mean shipping silence for a failed save, which is the worse failure. - **Tests: 1 settings unit + 1 format unit + 1 capability unit + 7 server-level + 1 e2e = 11 new.** The idempotency guard (`applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`) applies the returned edit through a real `didChange` and asserts the next save has nothing to do — the formatter's own invariant #2, asserted through this new path rather than assumed from the engine's suite. The byte-identity test (`the_save_hook_answers_exactly_what_the_formatting_request_answers`) compares the two JSON results directly; it is what would catch the two paths drifting apart. - Nothing outside `crates/lucisv_server` changed in code. The three documentation/packaging files touched outside this feature dir (`TODO.md`, `docs/features/lucisv-server/README.md`, `editors/vscode/package.json`, `editors/nvim/README.md`) are additions in the house style; no QA log or Review section anywhere was edited. ## QA log **2026-08-26 — QA.** Re-ran all gates, then attacked the six surfaces the lead called out plus one I found on my own. No masked-corruption test was needed (CLAUDE.md invariant #4): this feature touches nothing in `verify.rs` and adds no new normalization to it. **Verdict: committable as-is.** Five findings below, none blocking — one small fix made directly (pre-authorized), four are new regression tests that now guard behavior the dev's suite did not exercise, plus one real documentation gap for the dev to word better (not a code fix). **Gates, re-run clean:** - `cargo fmt --all -- --check` — clean. - `cargo clippy --all-targets --workspace` — clean, no warnings. - `cargo test --workspace` — all green (643 in the `lucisv_server` unit binary after my additions, up from the dev's 638; every other crate unchanged and green). - `cargo test -p vlog_formatter` — 114 passed. - `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` — `smoke: OK`. **A. Hard invariants ride through the new path — verified clean.** - (a) No partial output on a refusal: structural, not just tested — `format::formatting` (`format.rs:83-89`) uses `?` on `format_source`'s `Result` before it ever constructs a `TextEdit`, so an `Err` cannot reach an edit. `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown` (`server.rs`) confirms it end to end: `[]` plus one ERROR, twice. - (b) The runtime safety net runs inside this path: read the call chain — `Server::will_save_wait_until` → `format::formatting` (`format.rs:83`) → `vlog_formatter::format_source` (`crates/vlog_formatter/src/format.rs:80`), which calls `verify_equivalence` then reformats and calls `verify_convergence` before returning `Ok`. This is the exact same call `Server::formatting` makes (`server.rs:410` vs `server.rs:463`) — same function, same arguments shape, no bypass. - (c) The idempotency guard is real, not string arithmetic: `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` sends a genuine `textDocument/didChange` notification through `Session::notify`/`Server::notification` (the real dispatch), which lands in `set_document` (`server.rs:816`) exactly as an editor's own edit would, and then re-asks `willSaveWaitUntil` against the workspace's own copy of the buffer. Confirmed by reading `change()`/`buffer()` (`server.rs:1821-1834`) — they are the same helpers the pre-existing incremental-sync suite uses. **B2. Byte-identity and the tab-size asymmetry — verified clean, gap confirmed real by test, not just documented.** Added two tests to `server.rs` (`the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`, `a_lucisv_toml_erases_the_tab_size_gap`) that construct exactly the case the README's Assumptions section describes: no `lucisv.toml`, no `lucisv.indent`, editor `tabSize: 4` — manual format indents 4 (`config_from`'s rung 3), the save hook indents 2 (the built-in default, since `settings_without_editor_options` sends `insert_spaces: false`, which short-circuits rung 3's `options.insert_spaces && INDENT_RANGE.contains(...)` check in `format.rs:162` regardless of the tab size carried). With a `lucisv.toml { indent = 4 }` present, the two paths land on byte-identical JSON even when the manual request's `tabSize` is 8 — rung 1 outranks both. This matches the README exactly; nothing to fix. **B3. Setting plumbing — verified clean, plus one gap closed.** - `vscode_payload`'s shape matches `extension.js`'s actual `synchronize: { configurationSection: 'lucisv' }` (`editors/vscode/extension.js:68`, unmodified by this diff) and `DidChangeConfigurationParams::settings`'s unwrap in `server.rs`'s notification handler — traced, matches. - Mid-session toggle both directions: `the_save_hook_declines_until_format_on_save_is_pushed` covers on then off. Wrong types (`"true"`, `1`, `null`, `[true]`, `{"on": true}`) → off, no panic: `format_on_save_is_off_until_a_client_asks_for_it` (`settings.rs`) — ran clean. - Reindex / generation: `set_client_settings` (`state.rs:163-168`) computes its rescan bool from `exclude`/`filelist` equality only, so a `format_on_save` change can never trigger it — verified by reading the code, but the dev's own `only_an_exclude_change_asks_for_a_rescan` test (`state.rs`) predates this field and so never actually exercised it (it builds `ClientSettings { line_length, indent, ..Default::default() }`, which defaults `format_on_save` to `false` either way — a no-op assertion for this field). **Finding (low severity, fixed directly):** extended that test with an explicit `ClientSettings { format_on_save: true, ..Default::default() }` case (`state.rs`). Also added `toggling_format_on_save_neither_rescans_nor_bumps_the_generation` (`server.rs`) at the session level, asserting `session.server.generation` is unmoved by a `formatOnSave` push in either direction — this is what would catch it bumping a pull-diagnostics client's `resultId` for free. All new assertions pass against the dev's code unchanged; this was a test gap, not a behavior bug. **B4. Error-spam decision — verified clean, plus one real finding on the "warns once" framing.** - Two saves of an unparsable buffer → exactly two ERRORs: already covered by the dev's `a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown`. Confirmed passing, no changes needed. - formatOnSave on + buffer fine + broken config → formats with defaults, warns once: added `a_broken_config_still_saves_with_defaults_and_warns_once` (`server.rs`). Had to build it carefully — see the finding below. - **Finding (moderate, not fixed — needs a documentation call from the dev, not a code change).** "Warns once" (Assumptions, work log) is **not** once-per-broken-config; it is once-per-buffer-state. `warn_about_config`'s dedup (`config_warnings: HashSet`) is cleared by `set_document` (`server.rs:816-817`, doc comment: "re-arming its `lucisv.toml` warning"), and `set_document` is exactly what runs when the client applies a save hook's returned edit and the resulting `didChange` reaches the server — the same sequence `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do` already models on purpose. So: a save that itself needs reformatting under a broken config warns on save 1, and warns **again** on save 2 (because the intervening apply-and-write re-armed the dedup), and only goes quiet from save 3 onward once the buffer stops changing. Proved by a new test, `a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save` (`server.rs`) — three saves, shown-counts 1, 1, 0. This is consistent with `warn_about_config`'s own doc comment ("once per change of a file"), so it is not a bug against that contract; it is the save-hook feature's own Assumptions prose ("warns once") reading as a stronger guarantee than the mechanism actually gives. Left to the dev to reword — a single edit to the Assumptions bullet, not a behavior change, and QA does not redesign. - Interaction case is otherwise as documented: single-edit-free saves (the buffer already at the fallback default) stay deduped indefinitely, which is the common case a per-save-loop actually cares about. **B5. Capability shape on the wire — verified clean, no strengthening needed.** The new e2e test pins `willSaveWaitUntil: true` and `willSave` absent (`sync.get("willSave").is_none()` — checked against the JSON, not a Rust `Option`, so this really is "key missing" and not "key present as `null`" — confirmed against `lsp-types`' `#[serde(skip_serializing_if = "Option::is_none")]` on both fields). `change: 2` / `openClose: true` / `save.includeText: false` are **not** re-pinned in the new test, but they already are, unmodified, by the pre-existing `incremental_changes_land_the_same_buffer_as_one_full_change`-adjacent e2e test (`crates/lucisv_server/tests/e2e.rs:2805-2808`) against the same `initialize` response shape — the two tests together pin the complete set this attack surface asks for. Nothing to strengthen. **B6. CLAUDE.md compliance — verified clean.** - No `unwrap()`/`expect()`/`panic!()` outside `#[cfg(test)]` in any of `format.rs`, `main.rs`, `server.rs`, `settings.rs` — checked by line number, every hit is inside a `mod tests` block. - Doc comments present on `settings_without_editor_options` (`format.rs:63-71`) and the `format_on_save` field (`settings.rs:47-53`) — both explain why, not just what. - `grep -c '^## ' docs/features/will-save-wait-until/README.md` → 7 matches, one per section (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log, Review — "Status / TODO" and each of the six headers count once each); no duplicates. - `TODO.md`'s §9b item text is untouched — only the checkbox flipped and an indented `→ ...` continuation appended, the same pattern every other checked-off item in that file already uses. - `editors/vscode/package.json`'s new entry sits between `inlineTemplates` and `lineLength`, matching the file's feature-introduction ordering (not alphabetical — confirmed against the surrounding keys); `editors/nvim/README.md`'s new section matches the surrounding prose voice. **C. Pre-authorized small fix — done.** Checked `main.rs`'s `capabilities()` against `editors/nvim/README.md:101-102`'s claim ("Not advertised by the server ... range formatting, completion, rename, signature help, and cross-file references"): false for all four named capabilities — `document_range_formatting_provider`, `completion_provider`, `rename_provider`, and `signature_help_provider` are all `Some(...)` in `capabilities()` (`main.rs`, unchanged by this feature). Fixed the two lines to state that all four are advertised and Neovim's built-in client wires them up with no extra config, dropping the stale "your client will correctly refuse them" claim. Left `cross-file references` out of the corrected line — it was never a capability separate from `references_provider` (which *is* advertised); the real limitation is the in-file-only scope already stated two lines above (line 96), so restating it here as "not advertised" would have been wrong in a different way. **D. Beyond the list — nothing further broken.** Checked and found clean, no test added (already structurally impossible or already covered): `TextDocumentSaveReason` is `#[serde(transparent)]` around a bare `i32` (`lsp-types-0.97.0`), so an out-of-range `reason` (not 1/2/3) still decodes without error — consistent with "decoded, deliberately unread," no panic risk. `will_save_wait_until`'s dispatch arm decodes params before checking the setting, same as every other request — not a new cost surface. Verified `editors/vscode/package.json` is syntactically valid JSON after the edit. **Tests added this round (7, all passing):** `server.rs`: `the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent`, `a_lucisv_toml_erases_the_tab_size_gap`, `a_broken_config_still_saves_with_defaults_and_warns_once`, `a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save`, `toggling_format_on_save_neither_rescans_nor_bumps_the_generation`. `state.rs`: one case added inside `only_an_exclude_change_asks_for_a_rescan`. `editors/nvim/README.md:101-102`: one-line-pair fix (not a test). ## Review ### 2026-08-26 — lead Reviewed the diff, the work log and the QA log; re-ran all gates myself, clean. The design holds the line where it matters: the new door into the formatter goes through the same `format::formatting` call — and so through the runtime safety net — as the manual request, with the all-or-nothing `edits()` contract unchanged; QA traced the chain to `format_source`'s verification and I confirm the reading. Default-off was the right call (a save hook that formats uninvited fights the editor's own format-on-save), and `settings_without_editor_options` keeping the precedence reasoning inside `format.rs` is the correct home for it. On QA's finding (the config warning's dedup is per buffer *state*, not per broken config — a reformatting save re-arms it): accepted, and I have reworded the Assumptions bullet to say exactly what QA proved; the pinning test stays. The behavior itself is acceptable — the warning is still bounded by the user's own saves, and a user who both breaks their lucisv.toml and saves in a loop is being told something true each time. The error-on-every-save decision for refusals stands as argued. QA's tab-size-gap tests turned the README's honesty into executable fact, which is the standard here. Accepted as shipped.