Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .agents/skills/verify-diff-lifecycle/covered.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ file lua/claudecode/config.lua 3afb1bdeff27bfb6
== lua/claudecode/cwd.lua
file lua/claudecode/cwd.lua b034e82c76e8dee4
== lua/claudecode/diff.lua
file lua/claudecode/diff.lua 44c686c5bff3fc80
file lua/claudecode/diff.lua 2b7fd97e91645f00
block resolve_saved 36fd89d5b97f0173
block resolve_rejected c7a620816abff9a1
block open_blocking f2f5ae6216c0457a
Expand Down Expand Up @@ -211,10 +211,10 @@ file lua/claudecode/tools/get_workspace_folders.lua 80f38bdf62e55c3e
file lua/claudecode/tools/init.lua a8ff3ef7cd3c9df9
block handle_invoke 5c2422dfe7e2ea93
== lua/claudecode/tools/open_diff.lua
file lua/claudecode/tools/open_diff.lua d4050352cb09dfb9
block open_diff_tool 1a0e157e8e0a9452
file lua/claudecode/tools/open_diff.lua c2eef8418b600af3
block open_diff_tool fa7326d9e69eb708
== lua/claudecode/tools/open_file.lua
file lua/claudecode/tools/open_file.lua b277cbe8b86ac7c8
file lua/claudecode/tools/open_file.lua 8ce0857bca852c81
== lua/claudecode/tools/save_document.lua
file lua/claudecode/tools/save_document.lua 584b046bec6cb1f6
== lua/claudecode/types.lua
Expand Down
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ M.register("openFile", {
required = { "filePath" }
}, function(params)
-- Implementation
vim.cmd("edit " .. params.filePath)
vim.cmd.edit(vim.fn.fnameescape(params.filePath))
return { content = {{ type = "text", text = "Opened" }} }
end)

Expand Down
6 changes: 3 additions & 3 deletions lua/claudecode/diff.lua
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ local function load_original_buffer(original_win, old_file_path, is_new_file, ex
end

vim.api.nvim_set_current_win(original_win)
vim.cmd("edit " .. vim.fn.fnameescape(old_file_path))
vim.cmd.edit(vim.fn.fnameescape(old_file_path))
return vim.api.nvim_win_get_buf(original_win)
end

Expand Down Expand Up @@ -858,11 +858,11 @@ local function show_native_diff(old_file_path, new_file_path, tmp_file)
end
end

vim.cmd("edit " .. vim.fn.fnameescape(old_file_path))
vim.cmd.edit(vim.fn.fnameescape(old_file_path))
local original_win = vim.api.nvim_get_current_win()
create_split()
-- Without a swap file, the rename below cannot meet another Neovim's swap file for "<path> (New)" (E325).
vim.cmd("noswapfile edit " .. vim.fn.fnameescape(tmp_file))
vim.cmd.edit({ vim.fn.fnameescape(tmp_file), mods = { noswapfile = true } })
vim.api.nvim_buf_set_name(0, new_file_path .. " (New)")

-- Propagate filetype to the proposed buffer for proper syntax highlighting (#20)
Expand Down
3 changes: 2 additions & 1 deletion lua/claudecode/tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ Sources: [tools/init.lua:M.register_all], [tools/close_tab.lua:schema], [tools/o
- A call without `arguments` runs the tool with `{}`. A tool with a required parameter then raises `-32602`, and `getDiagnostics` returns the diagnostics of all buffers. No handler enforces `additionalProperties = false` [tools/init.lua:M.handle_invoke] [tools/get_diagnostics.lua:handler]
- Tools with `requires_coroutine` run in `coroutine.create`. If the coroutine yields, `handle_invoke` returns `{ _deferred = true, coroutine, client, params }` and sends no response yet. Only `openDiff` sets `requires_coroutine = true` [tools/init.lua:M.handle_invoke]
- `handle_invoke` and the answer to a deferred `openDiff` resume the tool's coroutine through `utils.resume_tool_coroutine`. On a LuaJIT build older than 2023-09-21 (the release builds of Neovim 0.8 and 0.9 are such builds), or one whose `jit.version` the plugin cannot read, it turns the JIT off and flushes the compiled traces before it resumes the coroutine, and it gives the JIT back as it was when the resume returns. This guards against LuaJIT issue 1066, which aborts Neovim. On those builds each such resume discards the compiled traces of the whole editor, which LuaJIT compiles again when the code gets hot. Any other LuaJIT build gets a plain `coroutine.resume` [utils.lua:M.resume_tool_coroutine] [tools/init.lua:M.handle_invoke] [diff.lua:M.open_diff_blocking]
- `openDiff` raises `-32602` when a required parameter is missing or is not a string. Outside a non-main coroutine it raises `-32000` with `message = "Internal server error"` and `data = "openDiff must run in coroutine context"`. It raises `-32000` with `data = "Failed to load diff module"` when `claudecode.diff` does not load [tools/open_diff.lua:handler]
- `openDiff` raises `-32602` when a required parameter is missing or is not a string, and with `data = "<name> must not contain a line break or a NUL"` when `old_file_path` or `new_file_path` holds a line feed, a carriage return or a NUL. Outside a non-main coroutine it raises `-32000` with `message = "Internal server error"` and `data = "openDiff must run in coroutine context"`. It raises `-32000` with `data = "Failed to load diff module"` when `claudecode.diff` does not load [tools/open_diff.lua:handler]
- After a deferred `openDiff` yields, `diff.open_diff_blocking` maps the outcome with `build_response` and sends it through `_G.claude_deferred_responses[tostring(co)]`, then clears that entry [diff.lua:M.open_diff_blocking]
- `openDiff` calls `diff.open_diff_blocking(old, new, contents, tab_name, client.id)`. Structured errors pass through. Other errors become `-32000` "Error opening blocking diff" [tools/open_diff.lua:handler]
- `openFile`, `checkDocumentDirty`, and `saveDocument` raise `-32602` "Missing filePath parameter" when `filePath` is missing or is not a string [tools/open_file.lua:handler]
- `openFile` raises `-32602` with `data = "filePath must not contain a line break or a NUL"` when `filePath` holds a line feed, a carriage return or a NUL, before any other check reads the path: `vim.fn.filereadable` raises E976 on a NUL [tools/open_file.lua:handler]
- `openFile` raises `-32602` before it opens the file when `startLine` or `endLine` is given but is not an integer (`false` included), `startLine` is below 1 or past the last line, or `endLine` is below `startLine`. The last line comes from the loaded buffer that `:edit` would reuse, which `bufexists()` and `bufadd()` find by name or by the inode Neovim cached for it, so a symlink or hard link finds it. Without one it comes from the file on disk. A buffer made before its file existed has no cached inode when another program creates the file, so a symlink to that file does not find it. For a loaded buffer without unsaved changes the file on disk counts too, because openFile loads the file again when it changed. When the buffer openFile then shows has fewer lines than `startLine`, openFile selects its last line. An `endLine` past the last line selects through the last line, and the answer names the lines it selected [tools/open_file.lua:handler]
- `openFile` raises `-32000` with `message = "File operation error"` and `data = "File not found: <path>"` when the file is not readable, and with `data = "No preview window shows the file"` when the preview window is closed or no longer has 'previewwindow' set after it gets the file, for example because an autocommand cleared it. It raises `-32000` and changes nothing while the command-line window is open, and when the user is in the middle of a command in the preview window, which openFile would reuse. Its defaults are `preview=false`, `makeFrontmost=true`, and `selectToEndOfLine=false` [tools/open_file.lua:handler]
- `openFile` expands `~` only when `filePath` is `~` or starts with `~/` (`utils.expand_tilde`). When only `endLine` is given, `startLine` is 1. When only `startLine` is given, `endLine` equals it [tools/open_file.lua:handler]
Expand Down
11 changes: 11 additions & 0 deletions lua/claudecode/tools/open_diff.lua
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ local function handler(params, client)
})
end
end
-- An Ex command built from a path with a line break would run the text after the break, and Neovim's file functions
-- raise on a NUL (E976), so such a path stops here, before any step below reads it. tab_name is not a path.
for _, param_name in ipairs({ "old_file_path", "new_file_path" }) do
if params[param_name]:find("[%z\r\n]") then
error({
code = -32602,
message = "Invalid params",
data = param_name .. " must not contain a line break or a NUL",
})
end
end

-- Ensure we're running in a coroutine context for blocking operation
local co, is_main = coroutine.running()
Expand Down
8 changes: 7 additions & 1 deletion lua/claudecode/tools/open_file.lua
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,8 @@ local function open_from(win, file_path, preview, keep_mode)
else
show_buffer(buf, win, keep_mode, function()
vim.api.nvim_win_call(win, function()
vim.cmd("edit " .. vim.fn.fnameescape(file_path))
-- One command: vim.cmd() with a string would run the text after a line break in the name as another one.
vim.cmd.edit(vim.fn.fnameescape(file_path))
end)
end)
end
Expand Down Expand Up @@ -506,6 +507,11 @@ local function handler(params)
if type(params.filePath) ~= "string" then
error({ code = -32602, message = "Invalid params", data = "Missing filePath parameter" })
end
-- An Ex command built from a path with a line break would run the text after the break, and Neovim's file functions
-- raise on a NUL (E976), so such a path stops here, before any step below reads it.
if params.filePath:find("[%z\r\n]") then
error({ code = -32602, message = "Invalid params", data = "filePath must not contain a line break or a NUL" })
end

if vim.fn.getcmdwintype() ~= "" then
error({ code = -32000, message = "File operation error", data = "The command-line window is open" })
Expand Down
32 changes: 32 additions & 0 deletions tests/helpers/ex_command.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
--- A stand-in for `vim.cmd`. Neovim's `vim.cmd` runs a string when it is called, and gives a function for each command
--- name, as in `vim.cmd.edit(path)` or `vim.cmd.edit({ path, mods = { noswapfile = true } })`. Both forms reach `run`
--- as one string, the second as "<mods> <name> <args>", so a spec that records the strings sees the same string for a
--- command in either form.
---@param run fun(command: string): any
---@return table cmd
return function(run)
return setmetatable({}, {
__call = function(_, command)
return run(command)
end,
__index = function(_, name)
return function(...)
local args, parts = { ... }, {}
if #args == 1 and type(args[1]) == "table" then
args = args[1]
for mod, on in pairs(args.mods or {}) do
if on == true then
parts[#parts + 1] = mod
end
end
table.sort(parts)
end
parts[#parts + 1] = name
for _, arg in ipairs(args) do
parts[#parts + 1] = arg
end
return run(table.concat(parts, " "))
end
end,
})
end
112 changes: 112 additions & 0 deletions tests/integration/file_name_line_break_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
-- Real-Neovim check that a file name with a line break runs nothing: openFile refuses it, and the diff opens the file
-- that has the name. fnameescape() puts a backslash before a line break but keeps it, and vim.cmd() with a string runs
-- each of its lines as an Ex command, so `vim.cmd("edit " .. vim.fn.fnameescape(path))` ran the text after the line
-- break. The diff specs call the diff module itself, past openDiff's check of the path. Busted's mock vim runs no Ex
-- commands, so under busted this is pending; scripts/run_integration_tests_individually.sh runs it in Neovim.
if vim == nil or vim.fn.has("nvim") ~= 1 then
describe("file names with a line break", function()
pending("needs a real Neovim")
end)
return
end

describe("file names with a line break", function()
local diff = require("claudecode.diff")
-- After the line break comes an Ex command that sets g:claudecode_injected. fnameescape() changes none of its
-- characters, and the `--` turns the `.new` that the legacy diff adds to its temp file into a Lua comment.
local name = "x\nlua(vim.g).claudecode_injected=1--"
local dir, saved_cache_home

---@return integer? buf The buffer named `buf_name`
local function buffer_named(buf_name)
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
if vim.api.nvim_buf_get_name(buf) == buf_name then
return buf
end
end
end

before_each(function()
vim.g.claudecode_injected = nil
-- Neovim resolves links in the folder of a buffer name (macOS: /var is /private/var), so compare real paths.
dir = vim.fn.tempname()
vim.fn.mkdir(dir, "p")
dir = (vim.uv or vim.loop).fs_realpath(dir)
-- The legacy diff writes its proposal under stdpath("cache"); keep that out of the real cache folder.
saved_cache_home = vim.env.XDG_CACHE_HOME
vim.env.XDG_CACHE_HOME = dir .. "/cache"
diff.setup({ terminal = { provider = "none" }, diff_opts = {} })
_G.claude_deferred_responses = {}
end)

after_each(function()
diff._cleanup_all_active_diffs("test cleanup")
vim.cmd("silent! diffoff!")
vim.cmd("silent! tabonly!")
vim.cmd("silent! only!")
vim.cmd("silent! %bwipeout!")
vim.env.XDG_CACHE_HOME = saved_cache_home
vim.fn.delete(dir, "rf")
_G.claude_deferred_responses = nil
vim.g.claudecode_injected = nil
end)

it("openFile runs nothing in the name", function()
local path = dir .. "/" .. name
vim.fn.writefile({ "old text" }, path)

pcall(require("claudecode.tools.open_file").handler, { filePath = path })

assert.is_nil(vim.g.claudecode_injected, "the text after the line break ran as an Ex command")
end)

it("openDiff opens the original that has the name, and runs nothing in it", function()
local path = dir .. "/" .. name
vim.fn.writefile({ "old text" }, path)

local co = coroutine.create(function()
return diff.open_diff_blocking(path, path, "new text\n", "line break name", nil)
end)
local ok, err = coroutine.resume(co)
_G.claude_deferred_responses[tostring(co)] = function() end

assert.is_nil(vim.g.claudecode_injected, "the text after the line break ran as an Ex command")
assert.is_true(ok, vim.inspect(err))
assert.equal("suspended", coroutine.status(co), "openDiff waits for the user")
local original = buffer_named(path)
assert.is_not_nil(original, "a buffer has the file's name")
assert.same({ "old text" }, vim.api.nvim_buf_get_lines(original, 0, -1, false))
local win = vim.fn.win_findbuf(original)[1]
assert.is_not_nil(win, "a window shows the original")
assert.is_true(vim.wo[win].diff, "the original is in diff mode")
end)

it("the legacy open_diff opens the original that has the name, and runs nothing in it", function()
local path = dir .. "/" .. name
vim.fn.writefile({ "old text" }, path)

local ok, result = pcall(diff.open_diff, path, dir .. "/new.txt", "new text\n", "legacy line break old")

assert.is_nil(vim.g.claudecode_injected, "the text after the line break ran as an Ex command")
assert.is_true(ok, vim.inspect(result))
assert.is_true(result.success)
local original = buffer_named(path)
assert.is_not_nil(original, "a buffer has the file's name")
assert.same({ "old text" }, vim.api.nvim_buf_get_lines(original, 0, -1, false))
end)

it("the legacy open_diff opens its temp file named after the new file, and runs nothing in the name", function()
local old = dir .. "/old.txt"
vim.fn.writefile({ "old text" }, old)
local new_path = dir .. "/" .. name

local ok, result = pcall(diff.open_diff, old, new_path, "new text\n", "legacy line break new")

assert.is_nil(vim.g.claudecode_injected, "the text after the line break ran as an Ex command")
assert.is_true(ok, vim.inspect(result))
assert.is_true(result.success)
local proposal = buffer_named(new_path .. " (New)")
assert.is_not_nil(proposal, "the proposal has the new file's name")
assert.same({ "new text" }, vim.api.nvim_buf_get_lines(proposal, 0, -1, false))
end)
end)
5 changes: 3 additions & 2 deletions tests/mocks/vim.lua
Original file line number Diff line number Diff line change
Expand Up @@ -770,7 +770,8 @@ local vim = {
end,
},

cmd = function(command)
-- Callable with a command string, and indexable by command name (`vim.cmd.edit(path)`), as in Neovim.
cmd = require("tests.helpers.ex_command")(function(command)
-- Store the last command for test assertions.
vim._last_command = command
-- Implement minimal behavior for essential commands
Expand Down Expand Up @@ -902,7 +903,7 @@ local vim = {
else
-- other commands (wincmd etc.) are recorded but not simulated
end
end,
end),

json = {
encode = function(data)
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/diff_buffer_cleanup_spec.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
-- luacheck: globals expect
require("tests.busted_setup")
local ex_command = require("tests.helpers.ex_command")

describe("Diff Buffer Cleanup Edge Cases", function()
local diff_module
Expand Down Expand Up @@ -125,7 +126,7 @@ describe("Diff Buffer Cleanup Edge Cases", function()
end

-- Mock command execution
mock_vim.cmd = function(command) end
mock_vim.cmd = ex_command(function(command) end)

_G.vim = mock_vim
end
Expand Down
15 changes: 8 additions & 7 deletions tests/unit/diff_spec.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
-- luacheck: globals expect
require("tests.busted_setup")
local ex_command = require("tests.helpers.ex_command")
local temp_dir = require("tests.helpers.temp_dir")

describe("Diff Module", function()
Expand Down Expand Up @@ -324,9 +325,9 @@ describe("Diff Module", function()
if _G.vim and rawget(original_vim_functions, "cmd") == nil then
original_vim_functions["cmd"] = _G.vim.cmd
end
_G.vim.cmd = function(cmd)
_G.vim.cmd = ex_command(function(cmd)
table.insert(commands, cmd)
end
end)

local mock_file = {
write = function() end,
Expand Down Expand Up @@ -379,9 +380,9 @@ describe("Diff Module", function()
if _G.vim and rawget(original_vim_functions, "cmd") == nil then
original_vim_functions["cmd"] = _G.vim.cmd
end
_G.vim.cmd = function(cmd)
_G.vim.cmd = ex_command(function(cmd)
table.insert(commands, cmd)
end
end)

local mock_file = {
write = function() end,
Expand Down Expand Up @@ -550,7 +551,7 @@ describe("Diff Module", function()
_G.vim.api.nvim_buf_set_name = function() end
_G.vim.api.nvim_buf_set_lines = function() end
_G.vim.api.nvim_set_option_value = function() end
_G.vim.cmd = function() end
_G.vim.cmd = ex_command(function() end)
local old_io_open = io.open
rawset(io, "open", function()
return {
Expand Down Expand Up @@ -661,7 +662,7 @@ describe("Diff Module", function()
_G.vim.api.nvim_buf_set_name = function() end
_G.vim.api.nvim_buf_set_lines = function() end
_G.vim.api.nvim_set_option_value = function() end
_G.vim.cmd = function() end
_G.vim.cmd = ex_command(function() end)
local old_io_open = io.open
rawset(io, "open", function()
return {
Expand Down Expand Up @@ -714,7 +715,7 @@ describe("Diff Module", function()
_G.vim.api.nvim_buf_set_name = function() end
_G.vim.api.nvim_buf_set_lines = function() end
_G.vim.api.nvim_set_option_value = function() end
_G.vim.cmd = function() end
_G.vim.cmd = ex_command(function() end)
local old_io_open = io.open
rawset(io, "open", function()
return {
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/tools/open_diff_mcp_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,39 @@ describe("openDiff tool MCP compliance", function()
end
end)

-- A line break in a file name ended the Ex command that opened it, so the rest ran as another command. A NUL makes
-- Neovim's file functions raise (E976).
describe("paths that hold a line break or a NUL", function()
for _, param_name in ipairs({ "old_file_path", "new_file_path" }) do
for _, case in ipairs({
{ label = "a line feed", value = "/test/a.txt\nlua vim.g.ran = 1" },
{ label = "a carriage return", value = "/test/a.txt\rlua vim.g.ran = 1" },
{ label = "a NUL", value = "/test/a.txt\0b" },
}) do
it("should refuse " .. param_name .. " with " .. case.label, function()
local params = {
old_file_path = test_old_file,
new_file_path = test_new_file,
new_file_contents = test_content_new,
tab_name = test_tab_name,
}
params[param_name] = case.value

local co = coroutine.create(function()
open_diff_tool.handler(params)
end)

local success, err = coroutine.resume(co)
assert.is_false(success)
assert.is_table(err)
assert.equal(-32602, err.code)
assert.equal("Invalid params", err.message)
assert_contains(err.data, param_name)
end)
end
end
end)

describe("coroutine context requirement", function()
it("should error when not in coroutine context", function()
local params = {
Expand Down
Loading
Loading