Skip to content

fix(server): hold the disconnect cleanup until Neovim allows window changes - #499

Merged
ThomasK33 merged 11 commits into
mainfrom
fix/defer-window-changes
Nov 11, 2026
Merged

ThomasK33 merged 11 commits into
mainfrom
fix/defer-window-changes

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Why

The operator's goal is to land the behavior fixes of this plugin on main in small PRs, fixes first. This PR fixes one defect of a class: the plugin changes windows at moments when Neovim forbids it.

What a user sees on main: Claude disconnects while the user is in the command-line window (q:) with two diffs open. The cleanup raises E11 in diffoff, the user gets a vim.schedule callback error, one openDiff call can stay unanswered, and a diff stays on screen after the user leaves the window. In the headless runs and in the spec, one call stays unanswered and one rejected diff stays. On a live terminal, main answered both calls and left a proposal on screen with no registry entry. The same happens under textlock (E565), for example when code in an <expr> mapping runs vim.wait while Claude disconnects. Nothing runs the cleanup again.

What changed

  • utils.when_windows_allowed(fn) runs fn at once when Neovim lets the plugin change windows, and else holds it. One 50 ms timer checks for all held functions. Neovim has no flag for textlock, so the gate asks: setting the current window to itself raises E11 in the command-line window and E565 under textlock. Otherwise it clears Neovim's kept message (set_keep_msg, read in the Neovim source), and 26 mode runs on two Neovim versions showed no effect a user can notice.
  • The server's disconnect cleanup goes through the gate. After the user leaves the window, or the textlock ends, both diffs close, each openDiff call has its answer, and no error shows.
  • A connection that closes before its handshake starts no cleanup: it ran no tool, so it owns no diff.

Scope

  • This PR covers the disconnect cleanup. The other paths of the same class (a replacing openDiff, the server stop, close_tab, closeAllDiffTabs, openFile, the reload after a save) go through the same gate in a follow-up PR after this one merges.
  • Outside those two states nothing changes: the cleanup runs on the next loop turn, as before.

Tradeoffs

  • A timer, not CmdwinLeave: that event runs while the command-line window is still open, so a close there still raises on 0.8. eventignore can drop it, and textlock has no event at all.
  • No order between held functions: each one reads the editor's state when it runs, in its own scheduled callback, so one that raises does not stop the others.

Verification

  • tests/integration/diff_disconnect_window_lock_spec.lua drives the real server over a socket in both states. It fails on main (E11 and E565) and passes with the fix, on Neovim 0.12.3 and 0.8.0. Two unit specs pin the gate and the server's use of it, and fail on main.
  • A replay over a real socket on a pty (the user types q:, Claude exits, the user leaves with Enter, Ctrl-C, :close, or reopens the window at once, one or two clients) ends with no diff and no waiting call on 0.12.3. Without the command-line window, the replay output is the same as on main.
  • 200 connections that close before their handshake, inside the command-line window on 0.12.3: the earlier head of this PR kept 201 active libuv timers there, this head keeps 1 (the ping timer).
  • Gates on this head: mise run format-check (344 files, 0 changed), mise run check (0 warnings / 0 errors in 172 files), mise run test (1463 successes / 0 failures / 0 errors / 19 pending), scripts/run_integration_tests_individually.sh (289 test cases passed, 0 failed on 0.12.3; 202 passed, 0 failed on 0.8.0).
  • .agents/skills/verify-diff-lifecycle/check.sh --record, then check.sh: == RESULT: PASS. The model is unchanged. SKILL.md names the new fairness assumption.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: xhigh

…window changes

Claude disconnects while the user is in the command-line window, or while code under
textlock runs vim.wait. The cleanup that the server schedules then runs where Neovim
refuses window changes (E11, E565), raises in diffoff, leaves one openDiff call
unanswered and one diff on screen, and nothing runs it again.

The real-Neovim spec drives the server over a socket in both states. The unit tests
pin the gate that the next commit adds: the cleanup waits and runs once Neovim allows
window changes. All of them fail on main.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
…hanges

utils.when_windows_allowed runs a function at once when Neovim lets the plugin
change windows, and else retries it every 50 ms until it does. Neovim has no flag
for textlock, so the gate asks: setting the current window to itself raises E11 in
the command-line window and E565 under textlock, and changes nothing otherwise
(probed on 0.12.3 and 0.8.0). A timer, not CmdwinLeave: that event runs while the
window is still open, 'eventignore' can drop it, and textlock has no event.

The disconnect cleanup goes through the gate. After the user leaves the
command-line window, or the textlock ends, both diffs close, each openDiff call has
its answer, and no error shows. Outside those states the cleanup runs on the next
loop turn, as before.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
…ifecycle lock

The server README says the disconnect cleanup waits until Neovim allows window
changes, and the module README lists utils.when_windows_allowed.

The lifecycle model is unchanged: it has no window locks, and DisconnectRejects
still reads the scheduled close_diffs_for_client. SKILL.md names the new
fairness assumption (a user in the command-line window leaves it, and textlock
ends) and lists a cleanup that raises partway as not modeled, with the closes
that do not wait yet. check.sh --record, then check.sh: RESULT: PASS.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
The longer utils.lua row made prettier realign the whole table. The row now fits the
old width, so the diff shows only the lines that changed.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
…ifecycle lock

A comment review removed narration and history from the new code and specs. The
spec helpers that waited on scheduled functions and the retry timer now carry
names instead. check.sh --record, then check.sh: RESULT: PASS.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@ThomasK33
ThomasK33 marked this pull request as ready for review November 11, 2026 08:38
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@ThomasK33

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T10:46:23.626434Z ffce833 Manual request
🔒 Security Review ✅ Completed 2026-11-11T10:47:41.972142Z ffce833 Manual request

Security findings

Advisory findings (1)

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 2e4408bb70

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛡️ Codex Security Review

Here are some automated security review suggestions for this pull request.

Reviewed commit: 2e4408bb70

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread lua/claudecode/utils.lua Resolved
main changed server/init.lua and covered.lock. covered.lock is re-recorded on the
merged tree: check.sh --record, then check.sh: RESULT: PASS.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
Codex security review, round 1: a local process that connects and closes before
the handshake still starts a cleanup, and while Neovim refuses window changes each
held cleanup keeps its own 50 ms timer, so N disconnects keep N timers. The tests
want no cleanup for a connection that never completed its handshake, one retry
timer for every held function, and a raise in one held function that does not stop
the others.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
…ion without a handshake

Codex security review, round 1 (P3): any local process could connect and close
before the handshake, and while the user stayed in the command-line window or
under textlock, each such close kept its own 50 ms retry timer.

A connection that never completed its handshake ran no tool and owns no diff, so
its disconnect starts no cleanup. The gate holds functions in one list with one
timer: while Neovim refuses window changes it checks once per 50 ms for all of
them. Once it allows them, each held function runs in its own scheduled callback,
so one that raises does not stop the others.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
The server README says which disconnects start a cleanup and that one timer checks
for every waiting cleanup. covered.lock is re-recorded: check.sh --record, then
check.sh: RESULT: PASS.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@ThomasK33

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: c12b40b92f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: c12b40b92f

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

No conflicts. covered.lock is recorded again on the merged tree: check.sh --record,
then check.sh: RESULT: PASS.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `xhigh`_
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@ThomasK33

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: ffce833be5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: ffce833be5

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@ThomasK33
ThomasK33 added this pull request to the merge queue Nov 11, 2026
Merged via the queue into main with commit d8e767c Nov 11, 2026
7 checks passed
@ThomasK33
ThomasK33 deleted the fix/defer-window-changes branch November 11, 2026 11:44
ThomasK33 added a commit that referenced this pull request Nov 11, 2026
#499 changed the disconnect cleanup in lua/claudecode/server/init.lua (`on_disconnect`: a client without a
handshake owns no diff, and the cleanup waits until Neovim allows window changes). It is outside M.broadcast and
the on_connect callback, which the model describes, and it cannot reach the selection state, a timer, or a send. Only
the file hash changed. The model passes (178,962 distinct states) and all 24 facts read TRUE.

SKILL.md gives the second measured `--mutants` time of the head with the HeldInTerminal rule: 4990 s.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
hareki pushed a commit to hareki/claudecode.nvim that referenced this pull request Nov 12, 2026
…32602 (coder#500)

## Why

The maintainer wants the behavior fixes that a code-shape refactor of
this plugin found to land on main first, as small PRs. coder#497 and coder#499
landed before this one. The refactor rule behind it is to check data
once, where it comes in, and then use it.

Claude still gets wrong answers to malformed `tools/call` requests. On
main, 43 of the 175 answers in the probe below hold a file path or a Lua
position on Neovim 0.12.3. On v0.8.0 it is 48, because 5 `openDiff`
calls with a wrong-typed `new_file_contents` also answer with
`vim/shared.lua:0` there.

- `params` that is a number, `true` or null gets `-32603` with Lua error
text and a file path in `data`.
- A call without `arguments` to `openFile`, `openDiff`,
`checkDocumentDirty`, `saveDocument`, `getDiagnostics` or `close_tab`
gets `-32000` with a file path in `data`.
- A required string parameter with the wrong type is not handled on
purpose.
- `openFile` answers `-32000` with a Lua error and a file path in `data`
for every wrong type except `false`. `close_tab` does the same, except
that a number `tab_name` succeeds.
- `checkDocumentDirty`, `saveDocument` and `getDiagnostics` answer
`-32000` with Neovim's own error text for null, `true`, a list and an
object. A number `uri` answers `-32001` "File must be open to retrieve
diagnostics: 5".
- Four calls succeed: a number `filePath` for `checkDocumentDirty` and
`saveDocument`, a number `tab_name` for `close_tab`, and `uri` set to
`false` for `getDiagnostics`. `false` already gets `-32602` for
`openFile`, `checkDocumentDirty`, `saveDocument` and `close_tab`.
- `openDiff` with a null `old_file_path` starts a diff that nobody
answers.
- `arguments` that is a JSON array, such as `[]` or `[1]`, reaches the
tool, although `arguments` must be an object.
- `params` that is a string, a JSON array, `false` or missing answers
`-32602`, but `data` names `name`, not `params`.

## What changed

- The server's `tools/call` handler checks the shape first, before it
runs a tool. `params` must be an object, `name` a string, and
`arguments` absent or an object. A wrong shape gets `-32602` "Invalid
params" with the plain `data` string `Missing or invalid parameter:
<field> (<need>)`. The text for a bad `name` is the one from coder#497.
- A JSON array is not an object, as `arguments` or as `params`. `[]` and
`[1]` both answer `-32602`, naming `arguments` or `params`. The check
uses `vim.islist` (`vim.tbl_islist` before Neovim 0.10).
`vim.json.decode` gives `{}` a table with the empty-dict mark and `[]` a
table without it, on Neovim 0.12.3 and v0.8.0, so the check tells them
apart.
- A request without `params` (and `"params": false`) reaches the handler
as a plain `{}`, because `_handle_request` passes `request.params or
{}`. A plain `{}` counts as a list, so it answers `-32602` naming
`params`. `"params": {}` is an object and still names `name`.
- `handle_invoke` passes `{}` to a tool called without `arguments`. The
six tools that crashed now answer as they do for `{}`.
- A required string parameter is checked as a string at the top of its
handler: `filePath` for `openFile`, `checkDocumentDirty` and
`saveDocument`, all four parameters of `openDiff`, and `tab_name` for
`close_tab`. `getDiagnostics` checks that `uri`, which is optional, is a
string when it is given, and it does so before it checks that the editor
has diagnostics. A wrong type gets `-32602` with the text the tool
already used for a missing parameter.
- Dead re-checks are gone: the name check in `handle_invoke` from coder#497,
the `params and` guards in the two server log lines, and
`tostring(params.name)`. The server-level spec holds each of those cases
and still passes.
- A rejected call logs one debug line, `Rejected tools/call: <field>
(<need>)`, because it no longer reaches the `Received` and `Response`
lines.
- Two log specs no longer pass `arguments = {}`. Busted's mock `vim`
cannot tell `{}` from `[]`, and a real call never passes a plain Lua
`{}`.
- In the unit spec, the no-params and list-as-params cases moved from
the `name` cases to the `params` cases. The answer for `"params": {}` is
asserted only in the real-Neovim spec, because the mock cannot tell `{}`
from `[]`.
- The tools and server READMEs state the rules. `covered.lock` is
re-recorded.

## Verification

- Differential on main (`d10fecf`) and on this head. A real server, a
real WebSocket client, `terminal.provider = "none"`, 175 cases (every
`params` shape, every `arguments` shape for 10 tools, each parameter
with each wrong type, controls, notifications). Neovim 0.12.3 and v0.8.0
print the same line: `COUNT wire3 cases=175 changed=132 same-or-equal=43
malformed-rules=128 unexpected=0 head-leaks=0
new-close_tab-error-lines=17`.
- The rule for each case is fixed before the run. A malformed shape, a
list included, must answer `-32602` with no path. A call without
`arguments` must answer exactly like `{}`. Every other case,
notifications included, must match main, debug lines too. Warn and error
lines of a rejected call can differ only by the `close_tab`
missing-parameter line and the `Diff setup failed` line, because a
rejected call no longer reaches diff setup.
- Of the 132 changed cases, 37 succeeded on main and now answer
`-32602`. They are 21 calls with `arguments` of a wrong type and 12
calls with a list as `arguments`, to tools that ignore it or read it as
optional, and 4 calls with a wrong-typed required string. One call
changes from `-32000` to success, `getDiagnostics` without `arguments`.
9 `openDiff` calls that left an unanswered diff now answer `-32602`. 3
calls with `params` of null, a number or `true` change from `-32603` to
`-32602`, and 5 calls (`params` of a string, `[]`, `[1]`, `false`, or
missing) still answer `-32602` but now name `params` where main names
`name`.
- The probe goes red on main used as the head: `unexpected=115
head-leaks=43` on Neovim 0.12.3 and `unexpected=115 head-leaks=48` on
v0.8.0.
- Tests that fail without the fix. New unit tests, all red on unfixed
code, and 4 name tests moved from `tools_spec` to the server spec.
Mutants killed by name, each run against the whole unit suite on this
head (unit tests red, then real-Neovim tests red on 0.12.3 and on
v0.8.0, which agree): `params` check off 8 (7 in
`tools_call_params_spec`, 1 in `server_tool_call_log_spec`), 1 in the
null spec and 4 in the arrays spec. `arguments` check off 6, 1 and 6.
`name` check off 5 (4 in `tools_call_params_spec`, 1 in
`server_tool_call_log_spec`), 1 (the null `name` case) and 1 (`"params":
{}` names `name`). No default `{}` 6 and 1 in the arrays spec. Wrong
code 17, 3 and 11. The `params` list test (`or islist(params)`)
reverted: 4 unit tests (`tools_call_params_spec`) and 4 arrays-spec
tests. The same test always true: 26, 8 and 8. Each of the five
required-string checks and the `uri` check turns its own tests red (3 to
12). The list rule has three mutants (the `islist` test dropped from
`arguments`, `islist` never true, `islist` always true: 2, 6 and 21 red
tests in the unit specs `tools_call_params_spec`,
`server_tool_call_log_spec` and `get_diagnostics_spec`). The `uri` check
moved after the feature guard is an order mutant of `getDiagnostics`,
not of the list rule, and turns 1 test red. The no-op controls stay
green.
- A JSON null and a JSON array, in real Neovim, because busted's mock
vim decodes null to nil and cannot tell a list from `{}`.
`tests/integration/tools_call_json_null_spec.lua` has 10 cases (8 fail
on main). `tests/integration/tools_call_json_arrays_spec.lua` has 15
cases (6 fail with the `arguments` check off, 4 with the `params` list
test reverted). All pass on Neovim 0.12.3 and v0.8.0.
- Gates on this head. `mise run format-check`: `formatted 346 files (0
changed)`. `mise run check`: `Total: 0 warnings / 0 errors in 174
files`. `BUSTED_SEED=424242 mise run test`: `1531 successes / 0 failures
/ 0 errors / 21 pending`.
`scripts/run_integration_tests_individually.sh`: 23 files and 315
passing case rows on Neovim 0.12.3, 23 files and 228 passing rows with 8
pending on v0.8.0, 0 failures and 0 errors on both.
- `bash .agents/skills/verify-diff-lifecycle/check.sh --record`, then
`check.sh` ends `== RESULT: PASS`. For a well-formed call, no diff
state, openDiff answer or disconnect path changes. A malformed
`openDiff` is rejected before `diff.open_diff_blocking` runs. On main,
one with a null `old_file_path` left 1 active diff, 1 extra window and
no answer. Now it answers `-32602` and leaves none. The edit of the
`params` check changes only the file hash of `server/init.lua`: the
`tools/call` handler is not a covered block, and a rejected call never
reaches a tool. The model and its facts need no edit.

## Limits

- A wrong-typed required string gets the text of a missing one, for
example "Missing filePath parameter". Every answer that was already
correct keeps its text.
- `arguments` must be absent or an object. MCP makes it an optional
object, and the Claude CLI calls recorded in this repo send an object
(`scripts/repro_issue_277.sh`, `scripts/repro_issue_248.sh`). `{}` and
an absent `arguments` give the same answer. null, a number, a string, a
boolean and a list get `-32602`.
- The `params` of other methods, such as `initialize` and `tools/list`,
are not checked. The optional `openFile` parameters `preview`,
`makeFrontmost` and `selectToEndOfLine` still accept any value.
- The mock server's `mcp.tool.invoke` calls `handle_invoke` without the
entry check, and `handle_invoke` raises a Lua error for a missing or
non-string `name`. Only the real server takes data from a socket, and
only the mock's own spec loads that module.
- The wire probe scripts and their classifier are not part of this PR,
so the counts above cannot be rerun from this branch.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
hareki pushed a commit to hareki/claudecode.nvim that referenced this pull request Nov 13, 2026
…n tracking (coder#477)

## Status

coder#524 is merged (`a41254a4`). It changed the flush on visual exit: the
changedtick comparison is gone, and a `visual_entry` that the buffer
listener marks takes its place. This PR models it. Codex round 4
(`91660323`) raised two P2 threads, fixed in round 5 (`f974ee06`: both
lanes clean). The Opus and GPT verifiers of `f974ee06` found one
documentation defect and three minors, fixed in this round 6 (the last).
The replays also found a family of bugs that coder#524 left: any edit made
while you select whose check has not run when the next key arrives.
Three are reproduced (a mapping, a key that arrives during the plugin's
callback, an autocmd edit at a mode change), and fix PR coder#540 fixes all
three. Their replays print `BUG` on `main` until coder#540 merges.

## What this adds

`.agents/skills/verify-selection-tracking/`: a TLA+ model of what Claude
sees as the user's current selection (`lua/claudecode/selection.lua`),
checked by TLC against guards that `check.sh` reads from the Lua code,
on the shared harness from coder#450. The model has no clock, so it covers
every `visual_demotion_delay_ms`. A change that removes or rewords a
guard makes a rule break or the covered code read STALE.

The model describes `main` as it is now: the four bugs it found are
fixed (coder#452), and so are the cases that reviews found afterwards (coder#471,
coder#481, and the recursion of coder#481's code that coder#493 fixed).

## The ten rules, as plain sentences

| Rule | Plain sentence |
| --- | --- |
| `ReleaseSent` | Right after you release a selection in a file (Esc),
Claude holds it, also when you made it faster than the 100 ms debounce
(issue coder#246), and when a plugin edited another line or a `:write` ran
while you selected. |
| `NoPhantomSelection` | Claude only gets text you selected, never the
text at the `'<,'>` marks after an operator such as `d` changed it. |
| `NoTerminalSelection` | Claude never gets a selection in the Claude
terminal buffer. |
| `HeldUntilMoved` | Once events settle in a file, a selection you
released stays with Claude while the cursor has not moved and its text
is unchanged. |
| `HeldInTerminal` | Once events settle in the Claude terminal, Claude
still holds the selection you released while its text is unchanged. |
| `HeldEndsWhenMoved` | Once events settle in a file, Claude holds a
released selection only while the cursor has not moved since you
released it. |
| `SameFile` | Once events settle in a file, Claude's selection is in
that file. |
| `ClaudeSeesCursor` | Once events settle in a file, a cursor-only
selection that Claude holds is where the cursor is, and in visual mode
Claude holds the live selection. |
| `NoDeletedText` | Once events settle, Claude holds no selection text
that its buffer no longer has. |
| `TimerClosedOnce` | No timer handle is closed twice (Neovim would
raise `handle ... is already closing`). |

"Once events settle" means no debounce or demotion timer runs, no timer
callback waits in the `vim.schedule` queue, and the check that the
buffer listener queued with `vim.schedule` has run.

## Bugs this model found

The first version of the model broke four rules on the code before coder#452.
Each path was replayed on Neovim 0.12.3. **coder#452 fixed all four**:

1. `HeldEndsWhenMoved`: Claude kept a released selection after the
cursor left it (`vb` Esc `gv` `d`, or `ve` Esc `l` `h` inside 100 ms).
2. `NoDeletedText`: Claude kept a held selection after you edited its
text without moving the cursor (`viw` Esc `x` `x`).
3. `SameFile`: with a long `visual_demotion_delay_ms`, Claude held
another file's cursor (`:b b.txt`, `:b a.txt`).
4. `ClaudeSeesCursor`: with a long `visual_demotion_delay_ms`, Claude
held a cursor position you had left (Esc `l`, wait, `h`).

**coder#471** closed the case a Codex review of coder#452 found: an operator
consumes a second selection and you enter the Claude terminal within the
debounce. The model's flush-skip step (`FlushSkipReports`) describes the
fixed code, and `tests/integration/selection_held_spec.lua` replays the
path with a real terminal buffer.

**coder#481** closed the case a reviewer of this PR found, and no step of the
model could express it: Claude holds selection A, you go to the Claude
terminal, and A's file changes while you are there (Claude rewrites it
and Neovim reloads it, or a plugin deletes the selected text). Claude
kept the deleted text until you came back. The model now has a step for
it (`YouEditOtherBuffer`) and three facts: `ListensToSelectionBuffer`,
`TerminalReportsHeldBuffer` and `UpdateChecksHeldText`.
`replays/held_after_reload_in_terminal.lua` and
`replays/held_after_edit_in_terminal.lua` replay the two triggers on
real Neovim.

**coder#524** closed the case an advisor of this PR found, and no step of the
model could express it: you select, a plugin edits another line (or a
`:write` runs) while you are still in visual mode, and you press Esc
inside the 100 ms debounce. The flush took a moved changedtick for an
operator that consumed the selection, so Claude got the cursor and not
the selection. The model now has two steps that move only the
changedtick (`YouEditByPluginInVisual`, `YouWriteInVisual`) and three
facts for the new code (`FlushSkipsOperator` rewritten,
`ListenerNotesVisualEdit`, `VisualCheckSparesPluginEdit`).
`FlushIgnoresTick` is the old comparison as a fact: it reads `FALSE` on
the code before coder#524, and the model then breaks `ReleaseSent` and
`HeldUntilMoved` (`NoPhantomSelection` still holds, because the old
guard did stop operators). Three replays
(`release_after_plugin_edit_in_visual.lua`,
`release_after_plugin_append_in_visual.lua`,
`release_after_write_in_visual.lua`) print `BUG` on `fcea49af` (the
commit before coder#524) and `OK` on `main`, on Neovim 0.12.3 and 0.8.0.

**Still open, found by the replays:** the flush on Esc skips a selection
that has an edit nobody checked yet, and the check that clears a
plugin's edit runs in `vim.schedule`, after the command or callback that
made the edit returns. When a key comes first, the flush takes the edit
for an operator's and Claude gets the cursor, not the selection,
although its text is untouched. The model runs that check in the step of
the edit, so it does not show this, and a PASS says nothing about it.
Three ways to get there print `BUG` on Neovim 0.8.0 and 0.12.3 (3 of 3
runs each): a mapping that edits another line and presses Esc in one
typeahead (`release_in_same_typeahead_as_plugin_edit.lua`), a key that
arrives while a timer callback of the plugin still runs
(`release_with_key_during_plugin_callback.lua`, with `nvim_input`; the
Opus verifier found it with an attached UI), and an autocmd that edits
when visual mode starts with the Esc already in the typeahead
(`release_after_autocmd_edit_in_visual.lua`, a `ModeChanged` handler for
`n:v`; the GPT verifier found it). In a tree with coder#540 (a `vim.on_key`
listener runs the check at the next key) all 16 replays print `OK` on
both versions. A plugin edit whose check runs before the next key is not
affected (`release_after_plugin_edit_in_visual.lua`).

**coder#457** and **coder#463** changed `getCurrentSelection` and moved the
terminal check into `M.is_claude_terminal_buffer`. The model follows
that move (`FlushSkipsTerminal`, `UpdateSkipsTerminal`). It makes no
claim about what `getCurrentSelection` answers when nothing is tracked.

## What changed from the model that found those bugs

- The model now describes the fixed code: `clear_held_state`,
`reconcile_held_selection` (called from `CursorMoved`, `BufEnter` and
`TextChanged`), the changedtick record `selection_tick`,
`cursor_at_flush.left` and `.away`, and the flush-skip report. That adds
nine facts (21 in all), the coder#481 guards add three (24 in all), and the
coder#524 guards add three more (27 in all).
- `SameFile` and `ClaudeSeesCursor` no longer break on the code as
written. The special case that ran their mutants with
`DelayBelowDebounce = TRUE` is gone, and the check uses `FALSE` (every
delay).
- Five guards break no rule alone, because another guard covers for them
(`FlushSkipReports` only together with `EntryClearsHeld`). `--mutants`
removes each with its partner (four `A+B` keys in `EXPECT`):
`DemotionClearsHeldState` + `MoveReports` and `PendingClearsHeld` +
`ReconcileOnCursorMoved` break `ClaudeSeesCursor`, `ElseClearsHeldState`
+ `LeaveNoted` breaks `SameFile`, `EntryClearsHeld` + `FlushSkipReports`
breaks `HeldEndsWhenMoved`. I found these pairs by running each such
guard together with each other guard. SKILL.md lists them.
- The model has a `YouEditByPlugin` step: `TextChanged` without
`CursorMoved`. In the model, `ReconcileOnTextChanged` and
`TextChangeReports` each break `NoDeletedText` alone because of it. On
real Neovim they do not: the buffer listener (`on_lines`) also fires for
an edit of the current buffer and runs the same check.
`replays/held_after_plugin_edit.lua` prints `OK` with either call
removed from `lua/` (I removed each: all 18 replay runs print `OK`,
while `check.sh` reports `BROKEN: NoDeletedText`). So a `BROKEN` trace
for these two guards is a counterexample of the model, not a failure of
the running plugin. SKILL.md says so. `--mutants` still requires both
guards, because the model has no other way to end the hold at that edit.
- The model keeps the changedtick as one bit on the visual entry ("moved
since visual mode started"), not as a number per buffer: the code before
coder#524 only compared it with the value recorded at entry, and a
changedtick only grows. A number per buffer multiplies the states and
the `--mutants` time by an estimated 5 to 10 and adds no behavior (I did
not build it). The bit is kept only while an entry exists and a guard
reads it, so the main run has fewer states (129,986) than before
(178,962).
- `LeaveNoted` breaks `HeldEndsWhenMoved` alone only when the user can
visit a second file, so `--mutants` runs that rule with two files.
- The model has a `YouEditOtherBuffer(b)` step: the text of a buffer
that is not current changes, `TextChanged` does not fire for it, and the
plugin sees the change only through its `nvim_buf_attach` listener
(`on_lines`, `on_reload`, `on_detach`) or when you come back. The
listener only queues its check with `vim.schedule`, so the model sets a
queued-check bit at the edit and runs the check in its own step
(`ListenerCheckRuns`), after any other step (Codex round 2).
`ListensToSelectionBuffer`, `TerminalReportsHeldBuffer` and
`UpdateChecksHeldText` are the guards of coder#481 that break `NoDeletedText`
when removed.
- `HeldInTerminal` is new in this round (Opus verifier).
`HeldUntilMoved` only holds in a file, so two regressions that drop a
released selection in the Claude terminal passed every rule:
`update_selection` in the terminal that reports the cursor although the
text did not change, and a demotion in the terminal that publishes the
cursor of the held buffer. The new rule says that Claude keeps the
selection there. It passes on the model, and six guard removals break
it, so it is not vacuous.
- The 16 replays (`replays/`) exit 0 on `OK` and 1 on `BUG`. Eleven
replay a path that once broke a rule and show the promise kept (the
three added for coder#524 are the plugin edit, the plugin append and the
`:write` in visual mode). `held_after_line_inserted_above.lua` (a line
inserted above a held selection makes Claude lose the selection and get
the cursor, although the text still exists) and
`v_escape_selects_one_character.lua` (a bare `v` and Esc selects the
character under the cursor, so it is a selection) show things that are
not rules. Three replay known bugs and print `BUG` until coder#540 merges
(see "Still open"). `replays/run.sh` works without GNU `timeout` (macOS)
and with a checkout path that has a space, a comma or a quote (Codex
round 2).

## Proof

All on this branch, Neovim 0.12.3, Java from mise:

- `check.sh`: `main: pass (129986 distinct states found)`, `== RESULT:
PASS` (exit 0, a fresh lock), all 27 facts `TRUE`.
- `check.sh --mutants` (4486 s, about 75 min, at a load average of 22 to
31): 26 keys (22 single guards and four `A+B` pairs), `== mutants: every
guard is caught`, no rule is vacuous (exit 0). The new facts are caught
as `EXPECT` says: `FlushSkipsOperator` and `ListenerNotesVisualEdit`
break `NoPhantomSelection`, `VisualCheckSparesPluginEdit` and
`FlushIgnoresTick` break `ReleaseSent`. The run is on `c731ebae`. Since
then the model changed only in its comments (the spec without comments
is identical, and `check.sh` still reports 129,986 states), and
`check.sh` changed in one regex and its comment (the
`ListensToSelectionBuffer` regex now reads both forms of `on_lines`, see
below). The TLC inputs of `--mutants` (model, constants, `EXPECT`, and
the fact values, which are all `TRUE` on `main`) are the same, so I did
not run it again. The verifiers ran it on `f974ee06` (Opus 5075 s, GPT
5201 s): 26 keys caught, exit 0.
- The code before coder#524: `check.sh` runs on the `selection.lua` of
`fcea49af` once two stand-in blocks (`visual_entry_of`,
`note_visual_edit`, which the old code does not have) are added at the
end of the file. Exactly four facts read `FALSE`: `FlushSkipsOperator`,
`ListenerNotesVisualEdit`, `VisualCheckSparesPluginEdit` and
`FlushIgnoresTick`. `check.sh` exits 1 with `main: BROKEN: ReleaseSent`,
the first broken rule it prints (trace: you select, a plugin edits
another line, you press Esc). TLC with that fact set breaks
`ReleaseSent` and `HeldUntilMoved` (the Opus and GPT verifiers ran it
too), `--mutants` lists `HeldInTerminal` as well for `FlushIgnoresTick`,
and `NoPhantomSelection` holds. Putting the old comparison back into the
`selection.lua` of this tree gives the same: `check.sh` exits 1,
`FlushSkipsOperator FALSE`, `FlushIgnoresTick FALSE`, `main: BROKEN:
ReleaseSent`.
- Each new guard removed alone from `selection.lua` flips only its own
fact: the flush condition (`FlushSkipsOperator`, `main: BROKEN:
NoPhantomSelection`), the `note_visual_edit(entry)` call in `on_lines`
(`ListenerNotesVisualEdit`, `NoPhantomSelection`), and the mode test of
the check (`VisualCheckSparesPluginEdit`, `ReleaseSent`).
- Scratch breaks on this tree (edit `lua/`, run, then `git checkout --
lua/` and an empty `git diff --shortstat`):
- Dropping `reconcile_held_selection(not entered_buffer)` from
`M.on_cursor_moved`: `check.sh` exits 1, `ReconcileOnCursorMoved FALSE`,
`main: BROKEN: HeldEndsWhenMoved`, and
`replays/held_after_quick_move.lua` prints `BUG the cursor moved after
the release, but Claude still holds "alpha"`.
- Making the `selection_text_is_there` test in
`demote_if_selection_text_changed` always true: `check.sh` exits 1,
`TextChangeReports FALSE`, `main: BROKEN: NoDeletedText`, and
`replays/held_after_edit.lua` prints `BUG Claude holds "alpha" at 0-5,
the buffer has "alphb" there`.
- Dropping `watch_selection_buffer(bufnr)` from `record_selection_read`:
`check.sh` exits 1, `ListensToSelectionBuffer FALSE`, `main: BROKEN:
NoDeletedText`, and `replays/held_after_reload_in_terminal.lua` prints
`BUG Claude holds "alpha", but a.txt is "beta gamma"`.
- `scripts/tla/test-check-lib.sh`: `COUNT cases=44 failed=0 skipped=0`.
- Replays: 16 probes on Neovim 0.12.3 and 0.8.0, each at the default
delay and with `DELAY_MS=50` (that setting changes only the two
long-delay probes): 13 print `OK` and the three known-bug probes print
`BUG` (coder#540). On `fcea49af` the three probes for coder#524 print `BUG` on
both versions. In a tree with coder#540 (a scratch copy of the skill, not
part of this PR) all 16 print `OK` on both versions, and the two new
known-bug replays ran 4 times each on both versions with the same
result.
- At `91660323`, a script that removed each of the 24 guards from
`selection.lua` alone showed that exactly its own fact turns `FALSE`
(seven regexes read a second guard before; the Opus verifier found three
of them). The regexes of `FlushOnVisualExit`, `ReconcileOnCursorMoved`
and `ReconcileOnTextChanged` are anchored now, because a commented-out
handler call used to leave the fact `TRUE`: with each call commented out
in `selection.lua`, only its own fact reads `FALSE`. This round I did
the same by hand for the three new guards (see above), and I rewrote the
`ListensToSelectionBuffer` regex twice: in round 5 for the code after
coder#524 (`on_lines` and `on_reload` call `check_soon` inside `if
holds_selection_of(buf) then`), and in this round to read both forms (it
read `FALSE` on the `selection.lua` of `fcea49af`, which listens). It is
`TRUE` on `fcea49af` and on this head, and `FALSE` when `check_soon()`
is removed from `on_lines` or from `on_reload`, and when
`watch_selection_buffer(bufnr)` is removed from `record_selection_read`
(only its own fact in each case).
- `shfmt -i 2`, `shellcheck --exclude=SC1091,SC2016`, `stylua --check`,
`prettier --check` and `treefmt --ci` (379 files, 0 changed): clean.
`luacheck` 0 warnings in 181 files. `tests/selection_test.lua` and
`tests/unit/visual_delay_timing_spec.lua`: 156 successes, 0 failures.
This PR changes no `lua/` or `tests/` file.
- `covered.lock` is recorded last. This round the flush,
`on_mode_changed` and `watch_selection_buffer` blocks changed (coder#524),
and `visual_entry_of` and `note_visual_edit` are new blocks. The file
hashes of `init.lua` and `server/init.lua` changed with `main`. In round
6 the `on_connect` block changed too (coder#539 moved a debug log line: no
send, no timer, no selection state), and the lock is re-recorded. I
merged `origin/main` several times and read each diff of the covered
code: coder#454 (`server.broadcast` returns, mention queue), coder#481, and coder#493,
whose change in `demote_if_selection_text_changed` made the regex of
`TerminalReportsHeldBuffer` read `FALSE`. I re-pointed it and
re-recorded the lock. coder#467 and coder#491 touch no covered file of this skill.
coder#497 changed one debug log argument in the `tools/call` handler of
`server/init.lua`, and coder#499 changed the disconnect cleanup in the same
file (`on_disconnect`: a client without a handshake owns no diff, and
the cleanup waits until Neovim allows window changes). Both are outside
`M.broadcast` and the `on_connect` callback, and neither can reach the
selection state, a timer or a send, so only the file hash changed and I
re-recorded the lock.

## Run it

```bash
.agents/skills/verify-selection-tracking/check.sh            # about 1 min
.agents/skills/verify-selection-tracking/check.sh --mutants  # about 1 to 1.5 h (4486 s in the last run), after you edit the model or a fact
.agents/skills/verify-selection-tracking/check.sh --hash-only  # about 5 s, only compares covered.lock with the code
NVIM=~/.local/share/mise/installs/neovim/0.12.3/bin/nvim \
  .agents/skills/verify-selection-tracking/replays/run.sh held_after_operator.lua
```

CI runs every `.agents/skills/verify-*/check.sh` in the `covered-lock`
job, as for `verify-diff-lifecycle`.

## Review record

- Codex round 1 (`ac7f243`): clean in both lanes.
- Codex round 2 (`f91391f`): security clean. Code lane, three P2s: the
model ran the listener check atomically with the edit, `replays/run.sh`
needed GNU `timeout`, and it put raw paths into Neovim commands. All
three are fixed.
- GPT and Opus verifiers on `f91391f`: ISSUES. F1 (SKILL.md scope
omitted a held buffer that becomes a Claude terminal, now a scope
bullet) and minors F3 to F10 are applied, except F4 (six blind-spot
mutants remove a guard's effect without touching a line a fact reads:
the fact stays `TRUE`, but `covered.lock` reads STALE, so `check.sh`
exits 3, not 0). F2 and the GPT finding of the same kind stay a
disclosed limit: the model runs the buffer listener only for a buffer
that is not current, although `on_lines` also fires for an edit of the
current buffer, so a `BROKEN` trace for `ReconcileOnTextChanged` or
`TextChangeReports` is a counterexample of the model, not a failure of
the running plugin (SKILL.md, "Read the result").
- Codex round 3 (`e18a1cf`): clean in both lanes.
- GPT and Opus verifiers on `e18a1cf`: ISSUES. Opus N2 (impact: the
`HeldUntilMoved` row promised more than its rule checks, and two
regressions in the terminal passed): new rule `HeldInTerminal`, rows
fixed, `--mutants` rerun. GPT F1 (impact: SKILL.md said a bare `v` and
Esc keeps the held selection, but Claude gets the one selected
character): the text now says what the code does, and a replay shows it.
Minors fixed: N1 anchored autocmd-call regexes, N3 a demotion in a
terminal that only its name marks does not take Condition 3, N4 "once
events settle" includes the listener's queued check, N5 the shrink step
names the three two-file rules, N6 the update step names the listener
operators, N7 the `held_after_plugin_edit.lua` comment, N8 statechart
labels for the listener steps, N9 user impact of the listener and
`holdLoose` items, N10 the `--hash-only` time.

- Codex round 4 (`91660323`): security clean. Code lane, two P2 threads,
both fixed in this round: the Rules table delimiter (`2c88f30e`) and the
model that restricted `YouEditByPlugin` to normal mode, so TLC could not
reach a moved changedtick on release (`YouEditByPluginInVisual`,
`YouWriteInVisual`, `FlushIgnoresTick`).
- GPT and Opus verifiers on `91660323`: PASS, with minors. Fixed here:
M1 the Rules table, M4 the `holdLoose` exemption names `HeldInTerminal`,
M5 "the rows whose rule is `none`", M6 the return for an unloaded buffer
in the Claude terminal is in the not-modeled list (I replayed it on
0.8.0 and 0.12.3). M2 and M3 (a regex that misses a blind-spot mutant or
reads through a shared helper) are not changed: the lock reads STALE for
them, as for F4 above.
- Codex round 5 (`f974ee06`): both lanes clean, CI green, no open
threads.
- Opus and GPT verifiers on `f974ee06`: ISSUES, one documentation defect
(F1) and three minors, all fixed in round 6. F1: SKILL.md said that an
edit from a timer, a job or an autocmd cannot hit the same-typeahead
bug. The true boundary is any edit whose check has not run when the next
key arrives. Two more ways to get there are reproduced and have replays
(a key that arrives during the plugin's callback, an autocmd edit at a
mode change), the model, replay and SKILL.md text now say so, and coder#540
fixes all three. M1: `check.sh` prints only the first broken rule, and
`--mutants` shows the others. M2: the operator order sentence
(`on_lines` first, with the mode already normal, then `ModeChanged`) is
fixed. M3: the `ListensToSelectionBuffer` regex and the old fact set
(four facts, shown with `check.sh` itself).
- Codex round 6: this head (the last round).

## Notes for the reviewer

- The diff is one new skill folder: SKILL.md, `check.sh`,
`covered.lock`, `model/` (the TLA+ spec and a `/statechart` view) and
`replays/`. It touches no `lua/` code.
- `DEVELOPMENT.md` is not edited here: the skill-listing change belongs
to the PR that owns it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
hareki pushed a commit to hareki/claudecode.nvim that referenced this pull request Nov 14, 2026
## Why

Neovim refuses window changes in two states: while the user is in the
command-line window (`q:`, E11) and under textlock (E565, for example
while an `<expr>` mapping waits for a key). coder#499 holds the disconnect
cleanup in those states. Five other paths still tear a diff down at that
moment and raise:

- the server stops (`:ClaudeCodeStop`, or the plugin stops itself),
- Claude calls `close_tab`,
- Claude calls `closeAllDiffTabs`,
- a second Claude client sends `openDiff` with the `tab_name` of an open
diff (a replacing openDiff),
- a bulk close of many diffs.

What the user sees on `main` at `d8e767c` (coder#499): `stop` raises E11 or
E565 before the TCP teardown, a pending openDiff call is never answered,
the server keeps running, and the next start says "Already running". A
replacing openDiff raises in `diffoff`, and the old rejected diff stays
on screen after the user leaves the window. The unified layout is worse:
nothing raises, but the registry entry is dropped while its windows
stay, so nothing can close them.

`main` has moved since (`700209ee`, with coder#485 and coder#536), and a replacing
openDiff in the command-line window now behaves differently there. On
Neovim 0.12.3 it no longer raises in `diffoff`. It drops the registry
entry and leaves the old windows, and the new call gets "Diff setup
failed". On v0.8.0 the cleanup still raises E11, and the old rejected
diff stays registered and on screen. This PR's `diff_cleanup_locked`
spec fails 15 of 24 cases on `700209ee` with 0.12.3 and 14 of 24 with
v0.8.0.

## What changed

- `_cleanup_diff_state` now hands the teardown to
`utils.when_windows_allowed`, the gate from coder#499. The old body is
`teardown_diff`, and only the gate calls it. When Neovim allows window
changes, it runs at once, as before. Otherwise the diff stays registered
and the gate's one 50 ms timer runs the teardown later.
- The held teardown runs only while `active_diffs[tab_name]` still holds
the entry that waited, because a new diff can take the tab name before
the timer fires.
- The answer to each waiting call goes out before the teardown, so the
server stop, `close_tab`, `closeAllDiffTabs` and the bulk closes answer
every call at once.
- Many held cleanups share the gate's one timer. A spec pins this with
20 held diffs.
- A replacing openDiff that finds its old diff held by the gate fails at
once with error `-32000` ("Diff setup failed") and runs no setup. A
waiting old call gets `DIFF_REJECTED` (an old diff the user already
accepted keeps its `FILE_SAVED` answer), and the held teardown closes
the old diff after the user leaves the locked state.
- `.agents/skills/verify-diff-lifecycle`: the model has a lock on window
changes. Three facts (`CleanupHoldsWhenLocked`, `CleanupRetries`,
`RetryChecksEntry`) read the gate and `teardown_diff`, and the liveness
rule `DeferredCleanupDone` says a held cleanup runs once windows can
change. After the merge the model also holds coder#536's reject pass and exit
cleanup, about 256,000 states.
- `.agents/skills/verify-claudecode-nvim`: two journeys,
`journey-diff-disconnect-cmdwin.sh` and
`journey-diff-replace-cmdwin.sh`, drive the paths in a real Neovim
terminal with the scripted Claude client.

## Merge of main

This head merges `origin/main` at `700209ee` (coder#485 is in) into the
branch with a normal merge commit (`9baedc48`). No rebase, no force
push. Eight files conflicted. I kept main's code in each one and put
this PR's gate around it.

| File | Resolution |
| --- | --- |
| `lua/claudecode/diff.lua` | Kept main's `end_diff_mode_if_alone`,
`end_diff_mode_in_windows_that_show_the_file`,
`release_surviving_diff_tab` and the `diffoff` changes. `teardown_diff`
now holds main's whole body, including the new-tab release from coder#485.
`_cleanup_diff_state` still calls the gate. The replace loop of coder#536
asserted that the old entry is gone after `_cleanup_diff_state`. With
the gate the entry can stay while windows are locked. The merge turned
the assert into a `break`, and a verifier found that this was wrong (see
"Finding F1" below). `ebff0dc2` replaced the `break` with the call that
fails at once. |
| `lua/claudecode/README.md` | Kept main's bullets and this PR's gate
bullet. The bullet on a refused `:diffoff` now says the cleanup waits
for the gate. |
| `verify-diff-lifecycle/model/DiffLifecycle.tla` | Kept both sides:
main's `RejectEach`, `DiffCleanupAtExit`, `ExitInSetup` and the exit
constants, and this PR's `DeferredCleanupRuns`. `Next` lists all of
them. |
| `verify-diff-lifecycle/check.sh` | The rules end with main's
`ExitedCallsAnswered`. The live properties are
`DisconnectedCallsAnswered` and `DeferredCleanupDone`. |
| `verify-diff-lifecycle/model/statechart-view.ts` and `SKILL.md` | Both
sides kept. The notes state the merged model's size and the replace
loop's exit. |
| `verify-claudecode-nvim/SKILL.md` | Main's journey list plus this PR's
two journeys. |

`covered.lock` of `verify-diff-lifecycle` came from main and I
re-recorded it in its own commit. It was the only STALE lock of the
five. Two more re-records followed, one for a comment-only edit of
`diff.lua` and one for the replace-loop fix. The model's facts still
match the code, and the model never lets a replacing openDiff find
windows locked (its `SKILL.md` says what the code does there).

Every teardown path that main added since `ef610b7d`:

| Path | Gate |
| --- | --- |
| coder#485 new-tab release (`release_surviving_diff_tab`) | Behind the gate.
`teardown_diff` calls it, directly in the split layout and through
`cleanup_inline_diff` in the unified layout, and nothing else calls it.
|
| coder#573 and the split-close helpers (`_close_proposal_window`,
`end_diff_mode_in_windows_that_show_the_file`) | Behind the gate through
`teardown_diff`. |
| coder#536 exit cleanup (`cleanup_at_exit`) | The reject pass resolves
statuses, and its one window change (`keep_empty`) calls
`_cleanup_diff_state`. The cleanup pass calls
`_cleanup_all_active_diffs`. Both go through the gate. |
| coder#536 replace loop in `open_diff_blocking` | Calls
`_cleanup_diff_state`, so it is gated. When the gate holds the old diff,
the loop fails the call before any setup. |
| Setup-failure cleanup and `remove_failed_proposal` | No gate for the
setup's own leftovers (the branch for a diff that the setup already
registered goes through the gate). They run only for a setup that
failed, and they tell a diff that the setup registered from one that was
already registered only by `active_diffs[tab_name]`. The merge's `break`
broke that assumption (F1). The replace loop now fails the call before
its setup runs, so these handlers see only an entry that the setup
registered, or none. |

## Finding F1 (found by a verifier on `0b34b13c`, fixed in `ebff0dc2`)

The merge turned coder#536's assert into a `break`. A replacing openDiff B
then ran its setup while the old diff A was still registered under the
same `tab_name`. When that setup failed in a locked state, its failure
handlers saw A's entry. They held A's teardown a second time and skipped
B's own cleanup. What B's setup had made stayed behind:

- on Neovim 0.8, a window that shows the `[Command Line]` buffer after
the user leaves `q:`,
- a hidden proposal buffer that is marked modified, so `:qa` stops with
E37 on v0.8.0,
- a buffer name that made every later openDiff of that kind and tab name
fail with E95 ("Failed to rename buffer" on v0.8.0).

It needs a second openDiff with the `tab_name` of an open diff while the
user is in `q:` or under textlock. PROTOCOL.md says Claude Code sends a
new random `tab_name` per call, so only other clients that reuse a
`tab_name` reach it.

Fix: when the gate kept A's entry, the replace loop fails B's call with
`-32000` ("Diff setup failed") before any setup. I used this form and
not the verifier's alternative (the failure handlers compare the entry
with the one registered before the setup). Every setup fails in those
states anyway, so the first form runs nothing that would need undoing.
It changes one place, where the alternative changes the failure handlers
in `diff.lua` and in `diff_inline.lua` and still runs a setup that
cannot work. The loop holds A's teardown once. B's setup used to hold it
a second time.

## Known limit

`close_tab` of a diff the user already saved still raises E11 in those
states. The file reload that runs 100 ms after the close
(`reload_file_buffers_manual` from `close_diff_by_tab_name`) does not go
through the gate yet. I re-ran it on this head on 0.12.3 and on v0.8.0,
in the command-line window (E11) and under textlock (E565). The reload
raises from `edit`, and the file's buffer keeps its old text, because
the reload never runs. The diff itself closes after the lock. `main` is
no better: its `close_tab` itself fails in those states, the diff stays
registered, and the reload raises the same way. A follow-up PR routes
the reload through the gate.

A replacing openDiff in those states holds the old diff, and the new
call fails with error `-32000` ("Diff setup failed") before it sets
anything up, so it leaves no window or buffer. The old diff closes once
the user leaves the window. Holding the new openDiff itself is not part
of this PR.

## Tests

I used the `test-audit` authoring gate,
`principle-test-behavior-not-implementation` and `tdd` (failing check
before the fix, then pass after) for every test change after the merge:

- New `diff_replace_locked_spec.lua` (24 cases on each build) drives a
replacing openDiff through `tools.handle_invoke` in the command-line
window and under textlock, in the split and unified layouts, with the
old and the new file of different kinds (existing and new, both orders),
while the user is in another tab. Per combination it checks three
behaviors. The old call gets `DIFF_REJECTED` once, the new call gets one
`-32000` answer, and the old diff stays registered while locked. After
the lock the old diff closes, no window shows `[Command Line]`, no
proposal buffer is left and no window is left over. A later openDiff
with the same tab name and the new call's kind opens and is answered
once. On `0b34b13c` 10 of the 24 cases fail on both builds (the
command-line window, the leftover proposal buffer, and the later
openDiff). With the fix all 24 pass on 0.12.3 and on v0.8.0.
- `diff_left_window_spec.lua`, case "answers close_tab from the
command-line window...": it pinned the pre-gate behavior (the copy keeps
its diff mode). It now expects the diff to stay registered while the
window is open, to close after the window closes, and to end diff mode
in the copy afterwards. The `no gate` mutant turns it red.
- `diff_locked_paths_spec.lua`, replacing openDiff cases: the old
assertion looked for `"error"` in the reply. The mutant that restores
coder#536's "entry is gone" assert in the replace loop survived it (0 red).
The assertion now looks for "Diff setup failed", and the same mutant
turns 2 cases red (command-line window and textlock).
- `diff_cleanup_locked_spec.lua`: I removed its skip of the unified
layout below Neovim 0.9. Main dropped that claim in coder#564, so all 24
cases now run on v0.8.0.
- `diff_locked_paths_spec.lua` counts `vim.defer_fn` calls and uses
`nvim_replace_termcodes` through `tests/helpers/window_lock.lua`,
because v0.8.0 has no `vim.keycode` and `uv.walk` crashes there.
- `journey-diff-replace-cmdwin.sh` no longer sends Enter at a "Press
ENTER" prompt. The refused call now logs nothing, and Enter would run
the command line and close the window.

## Verification

On `d8e767c` I replayed each path over a real socket in headless Neovim
0.12.3 (the textlock cases use `getchar()` in a typed `<expr>` mapping).
Result after the change:

| Path | `main` | this branch |
| --- | --- | --- |
| stop in the command-line window | `stop` raises E11, server keeps
running, restart says "Already running" | stop returns true, both calls
answered, both diffs close after the window, restart works |
| stop under textlock | raises E565, same leftovers | same as above |
| replacing openDiff, command-line window | error names `diffoff`, old
rejected diff stays | new call gets -32000 before its setup, old diff
closes after the window |
| replacing openDiff, textlock | same | same |
| 30 held cleanups | `close_pending_diffs` raises E11 after the first |
30 diffs close, 1 timer armed |

Replacing openDiff, all combinations (a verifier's matrix, rerun by me
on this fix and on `700209ee`, headless, one fresh Neovim per row): 288
scenarios on each of 0.12.3 and v0.8.0, 576 rows. Scenario axes are
layout (vertical, horizontal, unified), new-tab diff or not, lock (`q:`,
textlock, none), user in the same or another tab, old and new file
existing or new, and the old diff pending or saved. Each row also opens
a later openDiff, accepts it and closes its tab.

- No row is worse than `700209ee`, and 376 rows are strictly better. The
384 rows with a lock have no leftover. The other 192 rows have no lock
and give the same result line as `700209ee` in every row.
- `0b34b13c` is worse than `700209ee` in 40 rows (a row can count in
more than one: 24 with a later openDiff that fails, 16 with a leftover
buffer, 8 with an extra window), and none of them is worse on this head.
- With the new call arriving through `vim.schedule` (the way a socket
message arrives), the result is the same: 0 worse rows, 376 better.
- coder#536's close-handler probe (224 runs) and split-path probe (320 runs)
give identical output on `700209ee` and on this head in every run. The
locked close-handler orders (448 runs): 0 problems on this head, 358 on
`700209ee`, none worse.
- The verifier's standalone repro (user in another tab, textlock, new
file, then two later new-file openDiffs) answers both later calls with
E95 on `0b34b13c` and opens both on this head, as `700209ee` does, on
0.12.3 and on v0.8.0.

Gates on the merged head `74bbd458`, one run each, none passed only on
retry:

- `mise run clean` and `mise run all`: exit 0, 2026 successes, 0
failures, 0 errors, 54 pending, luacheck 0 warnings in 227 files, and
all 5 static proofs ok. The new spec is one more pending case under
busted, because it needs a real Neovim.
- Twelve specs, each run in real Neovim on 0.12.3 and on v0.8.0, native
exit 0 each time: `diff_cleanup_locked` 24 cases, `diff_locked_paths` 7,
`diff_disconnect_window_lock` 2, `diff_new_tab_autocmds` 14,
`diff_new_tab_close_mode` 10, `diff_new_tab_last_tab` 12,
`diff_new_tab_mode` 12, `utils_without_autocmds` 4,
`diff_answer_every_call` 9, `diff_close_save` 77, `diff_left_window` 40
and `diff_replace_locked` 24. All 0 failures and 0 errors. The first two
and the last are this PR's specs. The other nine cover the new-tab,
answer-every-call, close-save and left-window teardown code that main
changed, and the disconnect window lock from coder#499.
- `scripts/run_integration_tests_individually.sh` with the stub `claude`
first on `PATH`: 1161 successes on 0.12.3 and 1157 on v0.8.0, 0
failures, 0 errors, exit 0. Each ran twice, once with a plain `TMPDIR`
and once with a `TMPDIR` that holds a space and a percent sign.
- `check.sh` of all five skills: PASS. States: `verify-diff-lifecycle`
255,881 (the two live properties 13,509 each), `verify-mention-queue`
540,240, `verify-selection-tracking` 95,938, `verify-terminal-lifecycle`
279,492, `verify-ws-connection` 262,285. The three fact mutants of the
merged model fail as expected (run before the F1 fix, which does not
touch the model): `CleanupHoldsWhenLocked=FALSE` breaks
`NoRejectedLeftover`, `CleanupRetries=FALSE` breaks
`DeferredCleanupDone`, and `RetryChecksEntry=FALSE` breaks
`NoStrandedCall`.
- `journey-diff-disconnect-cmdwin.sh` and
`journey-diff-replace-cmdwin.sh` both print PASS on this head in a real
Neovim terminal, and `vcn.sh cleanup` leaves no process. They read `OUT`
and `WORK` through `vcn.sh get`, because main's `no-source-run-env`
static proof refused the `source` of `run.env`.
- Eight mutants, each run on the five spec files that cover the gate and
the replace loop (`diff_cleanup_locked`, `diff_locked_paths`,
`diff_disconnect_window_lock`, `diff_left_window`,
`diff_replace_locked`). The count is red cases on 0.12.3 and on v0.8.0,
and a no-op control is green on both:
- no gate (`_cleanup_diff_state` calls `teardown_diff` directly): 38 and
35,
- no identity check (the held function drops the `active_diffs[tab_name]
== diff_data` test): 12 and 12,
- own timer per cleanup (`when_windows_allowed` arms a `vim.defer_fn` on
every call): 3 and 3,
- held function never runs (the retry loop walks an empty list): 39 and
39,
- entry dropped while held (the entry is removed before the gate holds
the teardown): 39 and 37,
  - probe always allows (`windows_allowed` returns true): 40 and 37,
- replace loop breaks (the merge's form, the cause of F1): 10 and 10,
all in `diff_replace_locked`,
- replace loop asserts the entry is gone (coder#536's assert): 2 and 2, both
in `diff_locked_paths`.
The counts depend on the exact edit, so they are not comparable with the
counts of an earlier head.
- Earlier on `d8e767c`: 6 of the 7 `diff_locked_paths_spec.lua` cases
and 16 of the 24 `diff_cleanup_locked_spec.lua` cases fail there.
`journey-diff-replace-cmdwin.sh` fails there at the `diffoff` step. On
`700209ee` this PR's specs fail 15 and 14 of the 24
`diff_cleanup_locked` cases (0.12.3 and v0.8.0), 6 of the 7
`diff_locked_paths` cases on both, and 16 and 14 of the 24
`diff_replace_locked` cases.

Refs coder#483, coder#485, coder#499. coder#485 is merged, and this PR resolves the overlap
in `_cleanup_diff_state`.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant