feat: add conflict resolution, linter validation, and SEARCH/REPLACE system
- Add git-style conflict resolution with visual diff highlighting - Add buffer-local keymaps: co/ct/cb/cn for conflict resolution - Add floating menu with auto-show after code injection - Add linter validation that auto-checks LSP diagnostics after accepting code - Add SEARCH/REPLACE block parsing with fuzzy matching - Add new commands: CoderConflictMenu, CoderLintCheck, CoderLintFix - Update README with complete keymaps reference and issue reporting guide - Update CHANGELOG and llms.txt with full documentation - Clean up code comments and documentation Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
---@mod codetyper.agent.agentic Agentic loop with proper tool calling
|
||||
---@brief [[
|
||||
--- Full agentic system that handles multi-file changes via tool calling.
|
||||
--- Inspired by avante.nvim and opencode patterns.
|
||||
--- Multi-file agent system with tool orchestration.
|
||||
---@brief ]]
|
||||
|
||||
local M = {}
|
||||
|
||||
1071
lua/codetyper/agent/conflict.lua
Normal file
1071
lua/codetyper/agent/conflict.lua
Normal file
File diff suppressed because it is too large
Load Diff
302
lua/codetyper/agent/context_builder.lua
Normal file
302
lua/codetyper/agent/context_builder.lua
Normal file
@@ -0,0 +1,302 @@
|
||||
---@mod codetyper.agent.context_builder Context builder for agent prompts
|
||||
---
|
||||
--- Builds rich context including project structure, memories, and conventions
|
||||
--- to help the LLM understand the codebase.
|
||||
|
||||
local M = {}
|
||||
|
||||
local utils = require("codetyper.utils")
|
||||
|
||||
--- Get project structure as a tree string
|
||||
---@param max_depth? number Maximum depth to traverse (default: 3)
|
||||
---@param max_files? number Maximum files to show (default: 50)
|
||||
---@return string Project tree
|
||||
function M.get_project_structure(max_depth, max_files)
|
||||
max_depth = max_depth or 3
|
||||
max_files = max_files or 50
|
||||
|
||||
local root = utils.get_project_root() or vim.fn.getcwd()
|
||||
local lines = { "PROJECT STRUCTURE:", root, "" }
|
||||
local file_count = 0
|
||||
|
||||
-- Common ignore patterns
|
||||
local ignore_patterns = {
|
||||
"^%.", -- Hidden files/dirs
|
||||
"node_modules",
|
||||
"%.git$",
|
||||
"__pycache__",
|
||||
"%.pyc$",
|
||||
"target", -- Rust
|
||||
"build",
|
||||
"dist",
|
||||
"%.o$",
|
||||
"%.a$",
|
||||
"%.so$",
|
||||
"%.min%.",
|
||||
"%.map$",
|
||||
}
|
||||
|
||||
local function should_ignore(name)
|
||||
for _, pattern in ipairs(ignore_patterns) do
|
||||
if name:match(pattern) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function traverse(path, depth, prefix)
|
||||
if depth > max_depth or file_count >= max_files then
|
||||
return
|
||||
end
|
||||
|
||||
local entries = {}
|
||||
local handle = vim.loop.fs_scandir(path)
|
||||
if not handle then
|
||||
return
|
||||
end
|
||||
|
||||
while true do
|
||||
local name, type = vim.loop.fs_scandir_next(handle)
|
||||
if not name then
|
||||
break
|
||||
end
|
||||
if not should_ignore(name) then
|
||||
table.insert(entries, { name = name, type = type })
|
||||
end
|
||||
end
|
||||
|
||||
-- Sort: directories first, then alphabetically
|
||||
table.sort(entries, function(a, b)
|
||||
if a.type == "directory" and b.type ~= "directory" then
|
||||
return true
|
||||
elseif a.type ~= "directory" and b.type == "directory" then
|
||||
return false
|
||||
else
|
||||
return a.name < b.name
|
||||
end
|
||||
end)
|
||||
|
||||
for i, entry in ipairs(entries) do
|
||||
if file_count >= max_files then
|
||||
table.insert(lines, prefix .. "... (truncated)")
|
||||
return
|
||||
end
|
||||
|
||||
local is_last = (i == #entries)
|
||||
local branch = is_last and "└── " or "├── "
|
||||
local new_prefix = prefix .. (is_last and " " or "│ ")
|
||||
|
||||
local icon = entry.type == "directory" and "/" or ""
|
||||
table.insert(lines, prefix .. branch .. entry.name .. icon)
|
||||
file_count = file_count + 1
|
||||
|
||||
if entry.type == "directory" then
|
||||
traverse(path .. "/" .. entry.name, depth + 1, new_prefix)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
traverse(root, 1, "")
|
||||
|
||||
if file_count >= max_files then
|
||||
table.insert(lines, "")
|
||||
table.insert(lines, "(Structure truncated at " .. max_files .. " entries)")
|
||||
end
|
||||
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
--- Get key files that are important for understanding the project
|
||||
---@return table<string, string> Map of filename to description
|
||||
function M.get_key_files()
|
||||
local root = utils.get_project_root() or vim.fn.getcwd()
|
||||
local key_files = {}
|
||||
|
||||
local important_files = {
|
||||
["package.json"] = "Node.js project config",
|
||||
["Cargo.toml"] = "Rust project config",
|
||||
["go.mod"] = "Go module config",
|
||||
["pyproject.toml"] = "Python project config",
|
||||
["setup.py"] = "Python setup config",
|
||||
["Makefile"] = "Build configuration",
|
||||
["CMakeLists.txt"] = "CMake config",
|
||||
[".gitignore"] = "Git ignore patterns",
|
||||
["README.md"] = "Project documentation",
|
||||
["init.lua"] = "Neovim plugin entry",
|
||||
["plugin.lua"] = "Neovim plugin config",
|
||||
}
|
||||
|
||||
for filename, desc in pairs(important_files) do
|
||||
-- Check in root
|
||||
local path = root .. "/" .. filename
|
||||
if vim.fn.filereadable(path) == 1 then
|
||||
key_files[filename] = { path = path, description = desc }
|
||||
end
|
||||
|
||||
-- Check in lua/ for Neovim plugins
|
||||
local lua_path = root .. "/lua/" .. filename
|
||||
if vim.fn.filereadable(lua_path) == 1 then
|
||||
key_files["lua/" .. filename] = { path = lua_path, description = desc }
|
||||
end
|
||||
end
|
||||
|
||||
return key_files
|
||||
end
|
||||
|
||||
--- Detect project type and language
|
||||
---@return table { type: string, language: string, framework?: string }
|
||||
function M.detect_project_type()
|
||||
local root = utils.get_project_root() or vim.fn.getcwd()
|
||||
|
||||
local indicators = {
|
||||
["package.json"] = { type = "node", language = "javascript/typescript" },
|
||||
["Cargo.toml"] = { type = "rust", language = "rust" },
|
||||
["go.mod"] = { type = "go", language = "go" },
|
||||
["pyproject.toml"] = { type = "python", language = "python" },
|
||||
["setup.py"] = { type = "python", language = "python" },
|
||||
["Gemfile"] = { type = "ruby", language = "ruby" },
|
||||
["pom.xml"] = { type = "maven", language = "java" },
|
||||
["build.gradle"] = { type = "gradle", language = "java/kotlin" },
|
||||
}
|
||||
|
||||
-- Check for Neovim plugin specifically
|
||||
if vim.fn.isdirectory(root .. "/lua") == 1 then
|
||||
local plugin_files = vim.fn.glob(root .. "/plugin/*.lua", false, true)
|
||||
if #plugin_files > 0 or vim.fn.filereadable(root .. "/init.lua") == 1 then
|
||||
return { type = "neovim-plugin", language = "lua", framework = "neovim" }
|
||||
end
|
||||
end
|
||||
|
||||
for file, info in pairs(indicators) do
|
||||
if vim.fn.filereadable(root .. "/" .. file) == 1 then
|
||||
return info
|
||||
end
|
||||
end
|
||||
|
||||
return { type = "unknown", language = "unknown" }
|
||||
end
|
||||
|
||||
--- Get memories/patterns from the brain system
|
||||
---@return string Formatted memories context
|
||||
function M.get_memories_context()
|
||||
local ok_memory, memory = pcall(require, "codetyper.indexer.memory")
|
||||
if not ok_memory then
|
||||
return ""
|
||||
end
|
||||
|
||||
local all = memory.get_all()
|
||||
if not all then
|
||||
return ""
|
||||
end
|
||||
|
||||
local lines = {}
|
||||
|
||||
-- Add patterns
|
||||
if all.patterns and next(all.patterns) then
|
||||
table.insert(lines, "LEARNED PATTERNS:")
|
||||
local count = 0
|
||||
for _, mem in pairs(all.patterns) do
|
||||
if count >= 5 then
|
||||
break
|
||||
end
|
||||
if mem.content then
|
||||
table.insert(lines, " - " .. mem.content:sub(1, 100))
|
||||
count = count + 1
|
||||
end
|
||||
end
|
||||
table.insert(lines, "")
|
||||
end
|
||||
|
||||
-- Add conventions
|
||||
if all.conventions and next(all.conventions) then
|
||||
table.insert(lines, "CODING CONVENTIONS:")
|
||||
local count = 0
|
||||
for _, mem in pairs(all.conventions) do
|
||||
if count >= 5 then
|
||||
break
|
||||
end
|
||||
if mem.content then
|
||||
table.insert(lines, " - " .. mem.content:sub(1, 100))
|
||||
count = count + 1
|
||||
end
|
||||
end
|
||||
table.insert(lines, "")
|
||||
end
|
||||
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
--- Build the full context for agent prompts
|
||||
---@return string Full context string
|
||||
function M.build_full_context()
|
||||
local sections = {}
|
||||
|
||||
-- Project info
|
||||
local project_type = M.detect_project_type()
|
||||
table.insert(sections, string.format(
|
||||
"PROJECT INFO:\n Type: %s\n Language: %s%s\n",
|
||||
project_type.type,
|
||||
project_type.language,
|
||||
project_type.framework and ("\n Framework: " .. project_type.framework) or ""
|
||||
))
|
||||
|
||||
-- Project structure
|
||||
local structure = M.get_project_structure(3, 40)
|
||||
table.insert(sections, structure)
|
||||
|
||||
-- Key files
|
||||
local key_files = M.get_key_files()
|
||||
if next(key_files) then
|
||||
local key_lines = { "", "KEY FILES:" }
|
||||
for name, info in pairs(key_files) do
|
||||
table.insert(key_lines, string.format(" %s - %s", name, info.description))
|
||||
end
|
||||
table.insert(sections, table.concat(key_lines, "\n"))
|
||||
end
|
||||
|
||||
-- Memories
|
||||
local memories = M.get_memories_context()
|
||||
if memories ~= "" then
|
||||
table.insert(sections, "\n" .. memories)
|
||||
end
|
||||
|
||||
return table.concat(sections, "\n")
|
||||
end
|
||||
|
||||
--- Get a compact context summary for token efficiency
|
||||
---@return string Compact context
|
||||
function M.build_compact_context()
|
||||
local root = utils.get_project_root() or vim.fn.getcwd()
|
||||
local project_type = M.detect_project_type()
|
||||
|
||||
local lines = {
|
||||
"CONTEXT:",
|
||||
" Root: " .. root,
|
||||
" Type: " .. project_type.type .. " (" .. project_type.language .. ")",
|
||||
}
|
||||
|
||||
-- Add main directories
|
||||
local main_dirs = {}
|
||||
local handle = vim.loop.fs_scandir(root)
|
||||
if handle then
|
||||
while true do
|
||||
local name, type = vim.loop.fs_scandir_next(handle)
|
||||
if not name then
|
||||
break
|
||||
end
|
||||
if type == "directory" and not name:match("^%.") and not name:match("node_modules") then
|
||||
table.insert(main_dirs, name .. "/")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if #main_dirs > 0 then
|
||||
table.sort(main_dirs)
|
||||
table.insert(lines, " Main dirs: " .. table.concat(main_dirs, ", "))
|
||||
end
|
||||
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -19,6 +19,7 @@ local state = {
|
||||
original_event = nil,
|
||||
callback = nil,
|
||||
llm_response = nil,
|
||||
attached_files = nil,
|
||||
}
|
||||
|
||||
--- Close the context modal
|
||||
@@ -59,15 +60,99 @@ local function submit()
|
||||
M.close()
|
||||
|
||||
if callback and original_event then
|
||||
callback(original_event, additional_context)
|
||||
-- Pass attached_files as third optional parameter
|
||||
callback(original_event, additional_context, state.attached_files)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
--- Parse requested file paths from LLM response and resolve to full paths
|
||||
local function parse_requested_files(response)
|
||||
if not response or response == "" then
|
||||
return {}
|
||||
end
|
||||
|
||||
local cwd = vim.fn.getcwd()
|
||||
local candidates = {}
|
||||
local seen = {}
|
||||
|
||||
for path in response:gmatch("`([%w%._%-%/]+%.[%w_]+)`") do
|
||||
if not seen[path] then
|
||||
table.insert(candidates, path)
|
||||
seen[path] = true
|
||||
end
|
||||
end
|
||||
for path in response:gmatch("([%w%._%-%/]+%.[%w_]+)") do
|
||||
if not seen[path] then
|
||||
table.insert(candidates, path)
|
||||
seen[path] = true
|
||||
end
|
||||
end
|
||||
|
||||
-- Resolve to full paths using cwd and glob
|
||||
local resolved = {}
|
||||
for _, p in ipairs(candidates) do
|
||||
local full = nil
|
||||
if p:sub(1,1) == "/" and vim.fn.filereadable(p) == 1 then
|
||||
full = p
|
||||
else
|
||||
local try1 = cwd .. "/" .. p
|
||||
if vim.fn.filereadable(try1) == 1 then
|
||||
full = try1
|
||||
else
|
||||
local tail = p:match("[^/]+$") or p
|
||||
local matches = vim.fn.globpath(cwd, "**/" .. tail, false, true)
|
||||
if matches and #matches > 0 then
|
||||
full = matches[1]
|
||||
end
|
||||
end
|
||||
end
|
||||
if full and vim.fn.filereadable(full) == 1 then
|
||||
table.insert(resolved, full)
|
||||
end
|
||||
end
|
||||
return resolved
|
||||
end
|
||||
|
||||
|
||||
--- Attach parsed files into the modal buffer and remember them for submission
|
||||
local function attach_requested_files()
|
||||
if not state.llm_response or state.llm_response == "" then
|
||||
return
|
||||
end
|
||||
local files = parse_requested_files(state.llm_response)
|
||||
if #files == 0 then
|
||||
vim.api.nvim_buf_set_lines(state.buf, vim.api.nvim_buf_line_count(state.buf), -1, false, { "", "-- No files detected in LLM response --" })
|
||||
return
|
||||
end
|
||||
|
||||
state.attached_files = state.attached_files or {}
|
||||
|
||||
for _, full in ipairs(files) do
|
||||
local ok, lines = pcall(vim.fn.readfile, full)
|
||||
if ok and lines and #lines > 0 then
|
||||
table.insert(state.attached_files, { path = vim.fn.fnamemodify(full, ":~:." ) , full_path = full, content = table.concat(lines, "\n") })
|
||||
local insert_at = vim.api.nvim_buf_line_count(state.buf)
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at, insert_at, false, { "", "-- Attached: " .. full .. " --" })
|
||||
for i, l in ipairs(lines) do
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at + 1 + i, insert_at + 1 + i, false, { l })
|
||||
end
|
||||
else
|
||||
local insert_at = vim.api.nvim_buf_line_count(state.buf)
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at, insert_at, false, { "", "-- Failed to read: " .. full .. " --" })
|
||||
end
|
||||
end
|
||||
-- Move cursor to end and enter insert mode
|
||||
vim.api.nvim_win_set_cursor(state.win, { vim.api.nvim_buf_line_count(state.buf), 0 })
|
||||
vim.cmd("startinsert")
|
||||
end
|
||||
|
||||
--- Open the context modal
|
||||
---@param original_event table Original prompt event
|
||||
---@param llm_response string LLM's response asking for context
|
||||
---@param callback function(event: table, additional_context: string)
|
||||
function M.open(original_event, llm_response, callback)
|
||||
---@param callback function(event: table, additional_context: string, attached_files?: table)
|
||||
---@param suggested_commands table[]|nil Optional list of {label,cmd} suggested shell commands
|
||||
function M.open(original_event, llm_response, callback, suggested_commands)
|
||||
-- Close any existing modal
|
||||
M.close()
|
||||
|
||||
@@ -119,6 +204,17 @@ function M.open(original_event, llm_response, callback)
|
||||
table.insert(header_lines, "-- " .. line)
|
||||
end
|
||||
|
||||
-- If suggested commands were provided, show them in the header
|
||||
if suggested_commands and #suggested_commands > 0 then
|
||||
table.insert(header_lines, "")
|
||||
table.insert(header_lines, "-- Suggested commands: --")
|
||||
for i, s in ipairs(suggested_commands) do
|
||||
local label = s.label or s.cmd
|
||||
table.insert(header_lines, string.format("[%d] %s: %s", i, label, s.cmd))
|
||||
end
|
||||
table.insert(header_lines, "-- Press <leader><n> to run a command, or <leader>r to run all --")
|
||||
end
|
||||
|
||||
table.insert(header_lines, "")
|
||||
table.insert(header_lines, "-- Enter additional context below (Ctrl-Enter to submit, Esc to cancel) --")
|
||||
table.insert(header_lines, "")
|
||||
@@ -137,6 +233,65 @@ function M.open(original_event, llm_response, callback)
|
||||
vim.keymap.set("n", "<leader>s", submit, opts)
|
||||
vim.keymap.set("n", "<CR><CR>", submit, opts)
|
||||
|
||||
-- Attach parsed files (from LLM response)
|
||||
vim.keymap.set("n", "a", function()
|
||||
attach_requested_files()
|
||||
end, opts)
|
||||
|
||||
-- Confirm and submit with 'c' (convenient when doing question round)
|
||||
vim.keymap.set("n", "c", submit, opts)
|
||||
|
||||
-- Quick run of project inspection from modal with <leader>r / <C-r> in insert mode
|
||||
vim.keymap.set("n", "<leader>r", run_project_inspect, opts)
|
||||
vim.keymap.set("i", "<C-r>", function()
|
||||
vim.schedule(run_project_inspect)
|
||||
end, { buffer = state.buf, noremap = true, silent = true })
|
||||
|
||||
-- If suggested commands provided, create per-command keymaps <leader>1..n to run them
|
||||
state.suggested_commands = suggested_commands
|
||||
if suggested_commands and #suggested_commands > 0 then
|
||||
for i, s in ipairs(suggested_commands) do
|
||||
local key = "<leader>" .. tostring(i)
|
||||
vim.keymap.set("n", key, function()
|
||||
-- run this single command and append output
|
||||
if not s or not s.cmd then
|
||||
return
|
||||
end
|
||||
local ok, out = pcall(vim.fn.systemlist, s.cmd)
|
||||
local insert_at = vim.api.nvim_buf_line_count(state.buf)
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at, insert_at, false, { "", "-- Output: " .. s.cmd .. " --" })
|
||||
if ok and out and #out > 0 then
|
||||
for j, line in ipairs(out) do
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at + j, insert_at + j, false, { line })
|
||||
end
|
||||
else
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at + 1, insert_at + 1, false, { "(no output or command failed)" })
|
||||
end
|
||||
vim.api.nvim_win_set_cursor(state.win, { vim.api.nvim_buf_line_count(state.buf), 0 })
|
||||
vim.cmd("startinsert")
|
||||
end, opts)
|
||||
end
|
||||
-- Also map <leader>0 to run all suggested commands
|
||||
vim.keymap.set("n", "<leader>0", function()
|
||||
for _, s in ipairs(suggested_commands) do
|
||||
pcall(function()
|
||||
local ok, out = pcall(vim.fn.systemlist, s.cmd)
|
||||
local insert_at = vim.api.nvim_buf_line_count(state.buf)
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at, insert_at, false, { "", "-- Output: " .. s.cmd .. " --" })
|
||||
if ok and out and #out > 0 then
|
||||
for j, line in ipairs(out) do
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at + j, insert_at + j, false, { line })
|
||||
end
|
||||
else
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_at + 1, insert_at + 1, false, { "(no output or command failed)" })
|
||||
end
|
||||
end)
|
||||
end
|
||||
vim.api.nvim_win_set_cursor(state.win, { vim.api.nvim_buf_line_count(state.buf), 0 })
|
||||
vim.cmd("startinsert")
|
||||
end, opts)
|
||||
end
|
||||
|
||||
-- Close with Esc or q
|
||||
vim.keymap.set("n", "<Esc>", M.close, opts)
|
||||
vim.keymap.set("n", "q", M.close, opts)
|
||||
@@ -154,6 +309,51 @@ function M.open(original_event, llm_response, callback)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Run a small set of safe project inspection commands and insert outputs into the modal buffer
|
||||
local function run_project_inspect()
|
||||
if not state.buf or not vim.api.nvim_buf_is_valid(state.buf) then
|
||||
return
|
||||
end
|
||||
|
||||
local cmds = {
|
||||
{ label = "List files (ls -la)", cmd = "ls -la" },
|
||||
{ label = "Git status (git status --porcelain)", cmd = "git status --porcelain" },
|
||||
{ label = "Git top (git rev-parse --show-toplevel)", cmd = "git rev-parse --show-toplevel" },
|
||||
{ label = "Show repo files (git ls-files)", cmd = "git ls-files" },
|
||||
}
|
||||
|
||||
local insert_pos = vim.api.nvim_buf_line_count(state.buf)
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_pos, insert_pos, false, { "", "-- Project inspection results --" })
|
||||
|
||||
for _, c in ipairs(cmds) do
|
||||
local ok, out = pcall(vim.fn.systemlist, c.cmd)
|
||||
if ok and out and #out > 0 then
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_pos + 2, insert_pos + 2, false, { "-- " .. c.label .. " --" })
|
||||
for i, line in ipairs(out) do
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_pos + 2 + i, insert_pos + 2 + i, false, { line })
|
||||
end
|
||||
insert_pos = vim.api.nvim_buf_line_count(state.buf)
|
||||
else
|
||||
vim.api.nvim_buf_set_lines(state.buf, insert_pos + 2, insert_pos + 2, false, { "-- " .. c.label .. " --", "(no output or command failed)" })
|
||||
insert_pos = vim.api.nvim_buf_line_count(state.buf)
|
||||
end
|
||||
end
|
||||
|
||||
-- Move cursor to end
|
||||
vim.api.nvim_win_set_cursor(state.win, { vim.api.nvim_buf_line_count(state.buf), 0 })
|
||||
vim.cmd("startinsert")
|
||||
end
|
||||
|
||||
-- Provide a keybinding in the modal to run project inspection commands
|
||||
pcall(function()
|
||||
if state.buf and vim.api.nvim_buf_is_valid(state.buf) then
|
||||
vim.keymap.set("n", "<leader>r", run_project_inspect, { buffer = state.buf, noremap = true, silent = true })
|
||||
vim.keymap.set("i", "<C-r>", function()
|
||||
vim.schedule(run_project_inspect)
|
||||
end, { buffer = state.buf, noremap = true, silent = true })
|
||||
end
|
||||
end)
|
||||
|
||||
--- Check if modal is open
|
||||
---@return boolean
|
||||
function M.is_open()
|
||||
|
||||
384
lua/codetyper/agent/diff_review.lua
Normal file
384
lua/codetyper/agent/diff_review.lua
Normal file
@@ -0,0 +1,384 @@
|
||||
---@mod codetyper.agent.diff_review Diff review UI for agent changes
|
||||
---
|
||||
--- Provides a lazygit-style window interface for reviewing all changes
|
||||
--- made during an agent session.
|
||||
|
||||
local M = {}
|
||||
|
||||
local utils = require("codetyper.utils")
|
||||
|
||||
---@class DiffEntry
|
||||
---@field path string File path
|
||||
---@field operation string "create"|"edit"|"delete"
|
||||
---@field original string|nil Original content (nil for new files)
|
||||
---@field modified string New/modified content
|
||||
---@field approved boolean Whether change was approved
|
||||
---@field applied boolean Whether change was applied
|
||||
|
||||
---@class DiffReviewState
|
||||
---@field entries DiffEntry[] List of changes
|
||||
---@field current_index number Currently selected entry
|
||||
---@field list_buf number|nil File list buffer
|
||||
---@field list_win number|nil File list window
|
||||
---@field diff_buf number|nil Diff view buffer
|
||||
---@field diff_win number|nil Diff view window
|
||||
---@field is_open boolean Whether review UI is open
|
||||
|
||||
local state = {
|
||||
entries = {},
|
||||
current_index = 1,
|
||||
list_buf = nil,
|
||||
list_win = nil,
|
||||
diff_buf = nil,
|
||||
diff_win = nil,
|
||||
is_open = false,
|
||||
}
|
||||
|
||||
--- Clear all collected diffs
|
||||
function M.clear()
|
||||
state.entries = {}
|
||||
state.current_index = 1
|
||||
end
|
||||
|
||||
--- Add a diff entry
|
||||
---@param entry DiffEntry
|
||||
function M.add(entry)
|
||||
table.insert(state.entries, entry)
|
||||
end
|
||||
|
||||
--- Get all entries
|
||||
---@return DiffEntry[]
|
||||
function M.get_entries()
|
||||
return state.entries
|
||||
end
|
||||
|
||||
--- Get entry count
|
||||
---@return number
|
||||
function M.count()
|
||||
return #state.entries
|
||||
end
|
||||
|
||||
--- Generate unified diff between two strings
|
||||
---@param original string|nil
|
||||
---@param modified string
|
||||
---@param filepath string
|
||||
---@return string[]
|
||||
local function generate_diff_lines(original, modified, filepath)
|
||||
local lines = {}
|
||||
local filename = vim.fn.fnamemodify(filepath, ":t")
|
||||
|
||||
if not original then
|
||||
-- New file
|
||||
table.insert(lines, "--- /dev/null")
|
||||
table.insert(lines, "+++ b/" .. filename)
|
||||
table.insert(lines, "@@ -0,0 +1," .. #vim.split(modified, "\n") .. " @@")
|
||||
for _, line in ipairs(vim.split(modified, "\n")) do
|
||||
table.insert(lines, "+" .. line)
|
||||
end
|
||||
else
|
||||
-- Modified file - use vim's diff
|
||||
table.insert(lines, "--- a/" .. filename)
|
||||
table.insert(lines, "+++ b/" .. filename)
|
||||
|
||||
local orig_lines = vim.split(original, "\n")
|
||||
local mod_lines = vim.split(modified, "\n")
|
||||
|
||||
-- Simple diff: show removed and added lines
|
||||
local max_lines = math.max(#orig_lines, #mod_lines)
|
||||
local context_start = 1
|
||||
local in_change = false
|
||||
|
||||
for i = 1, max_lines do
|
||||
local orig = orig_lines[i] or ""
|
||||
local mod = mod_lines[i] or ""
|
||||
|
||||
if orig ~= mod then
|
||||
if not in_change then
|
||||
table.insert(lines, string.format("@@ -%d,%d +%d,%d @@",
|
||||
math.max(1, i - 2), math.min(5, #orig_lines - i + 3),
|
||||
math.max(1, i - 2), math.min(5, #mod_lines - i + 3)))
|
||||
in_change = true
|
||||
end
|
||||
if orig ~= "" then
|
||||
table.insert(lines, "-" .. orig)
|
||||
end
|
||||
if mod ~= "" then
|
||||
table.insert(lines, "+" .. mod)
|
||||
end
|
||||
else
|
||||
if in_change then
|
||||
table.insert(lines, " " .. orig)
|
||||
in_change = false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return lines
|
||||
end
|
||||
|
||||
--- Update the diff view for current entry
|
||||
local function update_diff_view()
|
||||
if not state.diff_buf or not vim.api.nvim_buf_is_valid(state.diff_buf) then
|
||||
return
|
||||
end
|
||||
|
||||
local entry = state.entries[state.current_index]
|
||||
if not entry then
|
||||
vim.bo[state.diff_buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(state.diff_buf, 0, -1, false, { "No changes to review" })
|
||||
vim.bo[state.diff_buf].modifiable = false
|
||||
return
|
||||
end
|
||||
|
||||
local lines = {}
|
||||
|
||||
-- Header
|
||||
local status_icon = entry.applied and "" or (entry.approved and "" or "")
|
||||
local op_icon = entry.operation == "create" and "+" or (entry.operation == "delete" and "-" or "~")
|
||||
|
||||
table.insert(lines, string.format("╭─ %s %s %s ─────────────────────────────────────",
|
||||
status_icon, op_icon, vim.fn.fnamemodify(entry.path, ":t")))
|
||||
table.insert(lines, "│ " .. entry.path)
|
||||
table.insert(lines, "│ Operation: " .. entry.operation)
|
||||
table.insert(lines, "│ Status: " .. (entry.applied and "Applied" or (entry.approved and "Approved" or "Pending")))
|
||||
table.insert(lines, "╰────────────────────────────────────────────────────")
|
||||
table.insert(lines, "")
|
||||
|
||||
-- Diff content
|
||||
local diff_lines = generate_diff_lines(entry.original, entry.modified, entry.path)
|
||||
for _, line in ipairs(diff_lines) do
|
||||
table.insert(lines, line)
|
||||
end
|
||||
|
||||
vim.bo[state.diff_buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(state.diff_buf, 0, -1, false, lines)
|
||||
vim.bo[state.diff_buf].modifiable = false
|
||||
vim.bo[state.diff_buf].filetype = "diff"
|
||||
end
|
||||
|
||||
--- Update the file list
|
||||
local function update_file_list()
|
||||
if not state.list_buf or not vim.api.nvim_buf_is_valid(state.list_buf) then
|
||||
return
|
||||
end
|
||||
|
||||
local lines = {
|
||||
"╭─ Changes (" .. #state.entries .. ") ──────────╮",
|
||||
"│ │",
|
||||
"│ j/k: navigate │",
|
||||
"│ Enter: view diff │",
|
||||
"│ a: approve r: reject │",
|
||||
"│ A: approve all │",
|
||||
"│ q: close │",
|
||||
"╰──────────────────────────────╯",
|
||||
"",
|
||||
}
|
||||
|
||||
for i, entry in ipairs(state.entries) do
|
||||
local prefix = (i == state.current_index) and "▶ " or " "
|
||||
local status = entry.applied and "" or (entry.approved and "" or "○")
|
||||
local op = entry.operation == "create" and "[+]" or (entry.operation == "delete" and "[-]" or "[~]")
|
||||
local filename = vim.fn.fnamemodify(entry.path, ":t")
|
||||
|
||||
table.insert(lines, string.format("%s%s %s %s", prefix, status, op, filename))
|
||||
end
|
||||
|
||||
if #state.entries == 0 then
|
||||
table.insert(lines, " No changes to review")
|
||||
end
|
||||
|
||||
vim.bo[state.list_buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(state.list_buf, 0, -1, false, lines)
|
||||
vim.bo[state.list_buf].modifiable = false
|
||||
|
||||
-- Highlight current line
|
||||
if state.list_win and vim.api.nvim_win_is_valid(state.list_win) then
|
||||
local target_line = 9 + state.current_index - 1
|
||||
if target_line <= vim.api.nvim_buf_line_count(state.list_buf) then
|
||||
vim.api.nvim_win_set_cursor(state.list_win, { target_line, 0 })
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Navigate to next entry
|
||||
function M.next()
|
||||
if state.current_index < #state.entries then
|
||||
state.current_index = state.current_index + 1
|
||||
update_file_list()
|
||||
update_diff_view()
|
||||
end
|
||||
end
|
||||
|
||||
--- Navigate to previous entry
|
||||
function M.prev()
|
||||
if state.current_index > 1 then
|
||||
state.current_index = state.current_index - 1
|
||||
update_file_list()
|
||||
update_diff_view()
|
||||
end
|
||||
end
|
||||
|
||||
--- Approve current entry
|
||||
function M.approve_current()
|
||||
local entry = state.entries[state.current_index]
|
||||
if entry and not entry.applied then
|
||||
entry.approved = true
|
||||
update_file_list()
|
||||
update_diff_view()
|
||||
end
|
||||
end
|
||||
|
||||
--- Reject current entry
|
||||
function M.reject_current()
|
||||
local entry = state.entries[state.current_index]
|
||||
if entry and not entry.applied then
|
||||
entry.approved = false
|
||||
update_file_list()
|
||||
update_diff_view()
|
||||
end
|
||||
end
|
||||
|
||||
--- Approve all entries
|
||||
function M.approve_all()
|
||||
for _, entry in ipairs(state.entries) do
|
||||
if not entry.applied then
|
||||
entry.approved = true
|
||||
end
|
||||
end
|
||||
update_file_list()
|
||||
update_diff_view()
|
||||
end
|
||||
|
||||
--- Apply approved changes
|
||||
function M.apply_approved()
|
||||
local applied_count = 0
|
||||
|
||||
for _, entry in ipairs(state.entries) do
|
||||
if entry.approved and not entry.applied then
|
||||
if entry.operation == "create" or entry.operation == "edit" then
|
||||
local ok = utils.write_file(entry.path, entry.modified)
|
||||
if ok then
|
||||
entry.applied = true
|
||||
applied_count = applied_count + 1
|
||||
end
|
||||
elseif entry.operation == "delete" then
|
||||
local ok = os.remove(entry.path)
|
||||
if ok then
|
||||
entry.applied = true
|
||||
applied_count = applied_count + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
update_file_list()
|
||||
update_diff_view()
|
||||
|
||||
if applied_count > 0 then
|
||||
utils.notify(string.format("Applied %d change(s)", applied_count))
|
||||
end
|
||||
|
||||
return applied_count
|
||||
end
|
||||
|
||||
--- Open the diff review UI
|
||||
function M.open()
|
||||
if state.is_open then
|
||||
return
|
||||
end
|
||||
|
||||
if #state.entries == 0 then
|
||||
utils.notify("No changes to review", vim.log.levels.INFO)
|
||||
return
|
||||
end
|
||||
|
||||
-- Create list buffer
|
||||
state.list_buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[state.list_buf].buftype = "nofile"
|
||||
vim.bo[state.list_buf].bufhidden = "wipe"
|
||||
vim.bo[state.list_buf].swapfile = false
|
||||
|
||||
-- Create diff buffer
|
||||
state.diff_buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[state.diff_buf].buftype = "nofile"
|
||||
vim.bo[state.diff_buf].bufhidden = "wipe"
|
||||
vim.bo[state.diff_buf].swapfile = false
|
||||
|
||||
-- Create layout: list on left (30 cols), diff on right
|
||||
vim.cmd("tabnew")
|
||||
state.diff_win = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(state.diff_win, state.diff_buf)
|
||||
|
||||
vim.cmd("topleft vsplit")
|
||||
state.list_win = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(state.list_win, state.list_buf)
|
||||
vim.api.nvim_win_set_width(state.list_win, 35)
|
||||
|
||||
-- Window options
|
||||
for _, win in ipairs({ state.list_win, state.diff_win }) do
|
||||
vim.wo[win].number = false
|
||||
vim.wo[win].relativenumber = false
|
||||
vim.wo[win].signcolumn = "no"
|
||||
vim.wo[win].wrap = false
|
||||
vim.wo[win].cursorline = true
|
||||
end
|
||||
|
||||
-- Set up keymaps for list buffer
|
||||
local list_opts = { buffer = state.list_buf, noremap = true, silent = true }
|
||||
vim.keymap.set("n", "j", M.next, list_opts)
|
||||
vim.keymap.set("n", "k", M.prev, list_opts)
|
||||
vim.keymap.set("n", "<Down>", M.next, list_opts)
|
||||
vim.keymap.set("n", "<Up>", M.prev, list_opts)
|
||||
vim.keymap.set("n", "<CR>", function() vim.api.nvim_set_current_win(state.diff_win) end, list_opts)
|
||||
vim.keymap.set("n", "a", M.approve_current, list_opts)
|
||||
vim.keymap.set("n", "r", M.reject_current, list_opts)
|
||||
vim.keymap.set("n", "A", M.approve_all, list_opts)
|
||||
vim.keymap.set("n", "q", M.close, list_opts)
|
||||
vim.keymap.set("n", "<Esc>", M.close, list_opts)
|
||||
|
||||
-- Set up keymaps for diff buffer
|
||||
local diff_opts = { buffer = state.diff_buf, noremap = true, silent = true }
|
||||
vim.keymap.set("n", "j", M.next, diff_opts)
|
||||
vim.keymap.set("n", "k", M.prev, diff_opts)
|
||||
vim.keymap.set("n", "<Tab>", function() vim.api.nvim_set_current_win(state.list_win) end, diff_opts)
|
||||
vim.keymap.set("n", "a", M.approve_current, diff_opts)
|
||||
vim.keymap.set("n", "r", M.reject_current, diff_opts)
|
||||
vim.keymap.set("n", "A", M.approve_all, diff_opts)
|
||||
vim.keymap.set("n", "q", M.close, diff_opts)
|
||||
vim.keymap.set("n", "<Esc>", M.close, diff_opts)
|
||||
|
||||
state.is_open = true
|
||||
state.current_index = 1
|
||||
|
||||
-- Initial render
|
||||
update_file_list()
|
||||
update_diff_view()
|
||||
|
||||
-- Focus list window
|
||||
vim.api.nvim_set_current_win(state.list_win)
|
||||
end
|
||||
|
||||
--- Close the diff review UI
|
||||
function M.close()
|
||||
if not state.is_open then
|
||||
return
|
||||
end
|
||||
|
||||
-- Close the tab (which closes both windows)
|
||||
pcall(vim.cmd, "tabclose")
|
||||
|
||||
state.list_buf = nil
|
||||
state.list_win = nil
|
||||
state.diff_buf = nil
|
||||
state.diff_win = nil
|
||||
state.is_open = false
|
||||
end
|
||||
|
||||
--- Check if review UI is open
|
||||
---@return boolean
|
||||
function M.is_open()
|
||||
return state.is_open
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
local M = {}
|
||||
local utils = require("codetyper.utils")
|
||||
local logs = require("codetyper.agent.logs")
|
||||
|
||||
---@class ExecutionResult
|
||||
---@field success boolean Whether the execution succeeded
|
||||
@@ -11,6 +12,72 @@ local utils = require("codetyper.utils")
|
||||
---@field requires_approval boolean Whether user approval is needed
|
||||
---@field diff_data? DiffData Data for diff preview (if requires_approval)
|
||||
|
||||
--- Open a file in a buffer (in a non-agent window)
|
||||
---@param path string File path to open
|
||||
---@param jump_to_line? number Optional line number to jump to
|
||||
local function open_file_in_buffer(path, jump_to_line)
|
||||
if not path or path == "" then
|
||||
return
|
||||
end
|
||||
|
||||
-- Check if file exists
|
||||
if vim.fn.filereadable(path) ~= 1 then
|
||||
return
|
||||
end
|
||||
|
||||
vim.schedule(function()
|
||||
-- Find a suitable window (not the agent UI windows)
|
||||
local target_win = nil
|
||||
local agent_ui_ok, agent_ui = pcall(require, "codetyper.agent.ui")
|
||||
|
||||
for _, win in ipairs(vim.api.nvim_list_wins()) do
|
||||
local buf = vim.api.nvim_win_get_buf(win)
|
||||
local buftype = vim.bo[buf].buftype
|
||||
|
||||
-- Skip special buffers (agent UI, nofile, etc.)
|
||||
if buftype == "" or buftype == "acwrite" then
|
||||
-- Check if this is not an agent UI window
|
||||
local is_agent_win = false
|
||||
if agent_ui_ok and agent_ui.is_open() then
|
||||
-- Skip agent windows by checking if it's one of our special buffers
|
||||
local bufname = vim.api.nvim_buf_get_name(buf)
|
||||
if bufname == "" then
|
||||
-- Could be agent buffer, check by buffer option
|
||||
is_agent_win = vim.bo[buf].buftype == "nofile"
|
||||
end
|
||||
end
|
||||
|
||||
if not is_agent_win then
|
||||
target_win = win
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- If no suitable window found, create a new split
|
||||
if not target_win then
|
||||
-- Get the rightmost non-agent window or create one
|
||||
vim.cmd("rightbelow vsplit")
|
||||
target_win = vim.api.nvim_get_current_win()
|
||||
end
|
||||
|
||||
-- Open the file in the target window
|
||||
vim.api.nvim_set_current_win(target_win)
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(path))
|
||||
|
||||
-- Jump to line if specified
|
||||
if jump_to_line and jump_to_line > 0 then
|
||||
local line_count = vim.api.nvim_buf_line_count(0)
|
||||
local target_line = math.min(jump_to_line, line_count)
|
||||
vim.api.nvim_win_set_cursor(target_win, { target_line, 0 })
|
||||
vim.cmd("normal! zz")
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
--- Expose open_file_in_buffer for external use
|
||||
M.open_file_in_buffer = open_file_in_buffer
|
||||
|
||||
---@class DiffData
|
||||
---@field path string File path
|
||||
---@field original string Original content
|
||||
@@ -50,15 +117,28 @@ end
|
||||
---@param callback fun(result: ExecutionResult)
|
||||
function M.handle_read_file(params, callback)
|
||||
local path = M.resolve_path(params.path)
|
||||
|
||||
-- Log the read operation in Claude Code style
|
||||
local relative_path = vim.fn.fnamemodify(path, ":~:.")
|
||||
logs.read(relative_path)
|
||||
|
||||
local content = utils.read_file(path)
|
||||
|
||||
if content then
|
||||
-- Log how many lines were read
|
||||
local lines = vim.split(content, "\n", { plain = true })
|
||||
logs.add({ type = "result", message = string.format(" ⎿ Read %d lines", #lines) })
|
||||
|
||||
-- Open the file in a buffer so user can see it
|
||||
open_file_in_buffer(path)
|
||||
|
||||
callback({
|
||||
success = true,
|
||||
result = content,
|
||||
requires_approval = false,
|
||||
})
|
||||
else
|
||||
logs.add({ type = "error", message = " ⎿ File not found" })
|
||||
callback({
|
||||
success = false,
|
||||
result = "Could not read file: " .. path,
|
||||
@@ -72,9 +152,15 @@ end
|
||||
---@param callback fun(result: ExecutionResult)
|
||||
function M.handle_edit_file(params, callback)
|
||||
local path = M.resolve_path(params.path)
|
||||
local relative_path = vim.fn.fnamemodify(path, ":~:.")
|
||||
|
||||
-- Log the edit operation
|
||||
logs.add({ type = "action", message = string.format("Edit(%s)", relative_path) })
|
||||
|
||||
local original = utils.read_file(path)
|
||||
|
||||
if not original then
|
||||
logs.add({ type = "error", message = " ⎿ File not found" })
|
||||
callback({
|
||||
success = false,
|
||||
result = "File not found: " .. path,
|
||||
@@ -88,6 +174,7 @@ function M.handle_edit_file(params, callback)
|
||||
local new_content, count = original:gsub(escaped_find, params.replace, 1)
|
||||
|
||||
if count == 0 then
|
||||
logs.add({ type = "error", message = " ⎿ Content not found" })
|
||||
callback({
|
||||
success = false,
|
||||
result = "Could not find content to replace in: " .. path,
|
||||
@@ -96,6 +183,18 @@ function M.handle_edit_file(params, callback)
|
||||
return
|
||||
end
|
||||
|
||||
-- Calculate lines changed
|
||||
local original_lines = #vim.split(original, "\n", { plain = true })
|
||||
local new_lines = #vim.split(new_content, "\n", { plain = true })
|
||||
local diff = new_lines - original_lines
|
||||
if diff > 0 then
|
||||
logs.add({ type = "result", message = string.format(" ⎿ +%d lines (pending approval)", diff) })
|
||||
elseif diff < 0 then
|
||||
logs.add({ type = "result", message = string.format(" ⎿ %d lines (pending approval)", diff) })
|
||||
else
|
||||
logs.add({ type = "result", message = " ⎿ Modified (pending approval)" })
|
||||
end
|
||||
|
||||
-- Requires user approval - show diff
|
||||
callback({
|
||||
success = true,
|
||||
@@ -115,9 +214,29 @@ end
|
||||
---@param callback fun(result: ExecutionResult)
|
||||
function M.handle_write_file(params, callback)
|
||||
local path = M.resolve_path(params.path)
|
||||
local relative_path = vim.fn.fnamemodify(path, ":~:.")
|
||||
local original = utils.read_file(path) or ""
|
||||
local operation = original == "" and "create" or "overwrite"
|
||||
|
||||
-- Log the write operation
|
||||
if operation == "create" then
|
||||
logs.add({ type = "action", message = string.format("Write(%s)", relative_path) })
|
||||
local new_lines = #vim.split(params.content, "\n", { plain = true })
|
||||
logs.add({ type = "result", message = string.format(" ⎿ New file (%d lines, pending approval)", new_lines) })
|
||||
else
|
||||
logs.add({ type = "action", message = string.format("Update(%s)", relative_path) })
|
||||
local original_lines = #vim.split(original, "\n", { plain = true })
|
||||
local new_lines = #vim.split(params.content, "\n", { plain = true })
|
||||
local diff = new_lines - original_lines
|
||||
if diff > 0 then
|
||||
logs.add({ type = "result", message = string.format(" ⎿ +%d lines (pending approval)", diff) })
|
||||
elseif diff < 0 then
|
||||
logs.add({ type = "result", message = string.format(" ⎿ %d lines (pending approval)", diff) })
|
||||
else
|
||||
logs.add({ type = "result", message = " ⎿ Modified (pending approval)" })
|
||||
end
|
||||
end
|
||||
|
||||
-- Ensure parent directory exists
|
||||
local dir = vim.fn.fnamemodify(path, ":h")
|
||||
if dir ~= "" and dir ~= "." then
|
||||
@@ -143,6 +262,10 @@ end
|
||||
function M.handle_bash(params, callback)
|
||||
local command = params.command
|
||||
|
||||
-- Log the bash operation
|
||||
logs.add({ type = "action", message = string.format("Bash(%s)", command:sub(1, 50) .. (#command > 50 and "..." or "")) })
|
||||
logs.add({ type = "result", message = " ⎿ Pending approval" })
|
||||
|
||||
-- Requires user approval first
|
||||
callback({
|
||||
success = true,
|
||||
@@ -258,7 +381,8 @@ function M.handle_search_files(params, callback)
|
||||
for _, file in ipairs(files) do
|
||||
-- Skip common ignore patterns
|
||||
if not file:match("node_modules") and not file:match("%.git/") then
|
||||
table.insert(results, file:gsub(search_path .. "/", ""))
|
||||
local relative = file:gsub(search_path .. "/", "")
|
||||
table.insert(results, relative)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -272,7 +396,8 @@ function M.handle_search_files(params, callback)
|
||||
if handle then
|
||||
for line in handle:lines() do
|
||||
if not line:match("node_modules") and not line:match("%.git/") then
|
||||
table.insert(grep_results, line:gsub(search_path .. "/", ""))
|
||||
local relative = line:gsub(search_path .. "/", "")
|
||||
table.insert(grep_results, relative)
|
||||
end
|
||||
end
|
||||
handle:close()
|
||||
@@ -348,7 +473,8 @@ function M.apply_change(diff_data, callback)
|
||||
-- Write file
|
||||
local success = utils.write_file(diff_data.path, diff_data.modified)
|
||||
if success then
|
||||
-- Reload buffer if it's open
|
||||
-- Open and/or reload buffer so user can see the changes
|
||||
open_file_in_buffer(diff_data.path)
|
||||
M.reload_buffer_if_open(diff_data.path)
|
||||
callback({
|
||||
success = true,
|
||||
|
||||
@@ -8,6 +8,8 @@ local tools = require("codetyper.agent.tools")
|
||||
local executor = require("codetyper.agent.executor")
|
||||
local parser = require("codetyper.agent.parser")
|
||||
local diff = require("codetyper.agent.diff")
|
||||
local diff_review = require("codetyper.agent.diff_review")
|
||||
local resume = require("codetyper.agent.resume")
|
||||
local utils = require("codetyper.utils")
|
||||
local logs = require("codetyper.agent.logs")
|
||||
|
||||
@@ -21,8 +23,11 @@ local state = {
|
||||
conversation = {},
|
||||
pending_tool_results = {},
|
||||
is_running = false,
|
||||
max_iterations = 10,
|
||||
max_iterations = 25, -- Increased for complex tasks (env setup, tests, fixes)
|
||||
current_iteration = 0,
|
||||
original_prompt = "", -- Store for resume functionality
|
||||
current_context = nil, -- Store context for resume
|
||||
current_callbacks = nil, -- Store callbacks for continue
|
||||
}
|
||||
|
||||
---@class AgentCallbacks
|
||||
@@ -38,6 +43,8 @@ function M.reset()
|
||||
state.pending_tool_results = {}
|
||||
state.is_running = false
|
||||
state.current_iteration = 0
|
||||
-- Clear collected diffs
|
||||
diff_review.clear()
|
||||
end
|
||||
|
||||
--- Check if agent is currently running
|
||||
@@ -67,6 +74,9 @@ function M.run(prompt, context, callbacks)
|
||||
|
||||
state.is_running = true
|
||||
state.current_iteration = 0
|
||||
state.original_prompt = prompt
|
||||
state.current_context = context
|
||||
state.current_callbacks = callbacks
|
||||
|
||||
-- Add user message to conversation
|
||||
table.insert(state.conversation, {
|
||||
@@ -91,9 +101,9 @@ function M.agent_loop(context, callbacks)
|
||||
logs.info(string.format("Agent loop iteration %d/%d", state.current_iteration, state.max_iterations))
|
||||
|
||||
if state.current_iteration > state.max_iterations then
|
||||
logs.error("Max iterations reached")
|
||||
callbacks.on_error("Max iterations reached (" .. state.max_iterations .. ")")
|
||||
state.is_running = false
|
||||
logs.info("Max iterations reached, asking user to continue or stop")
|
||||
-- Ask user if they want to continue
|
||||
M.prompt_continue(context, callbacks)
|
||||
return
|
||||
end
|
||||
|
||||
@@ -222,8 +232,20 @@ function M.process_tool_calls(tool_calls, index, context, callbacks)
|
||||
end
|
||||
logs.tool(tool_call.name, "approved", log_msg)
|
||||
|
||||
-- Apply the change
|
||||
-- Apply the change and collect for review
|
||||
executor.apply_change(result.diff_data, function(apply_result)
|
||||
-- Collect the diff for end-of-session review
|
||||
if result.diff_data.operation ~= "bash" then
|
||||
diff_review.add({
|
||||
path = result.diff_data.path,
|
||||
operation = result.diff_data.operation,
|
||||
original = result.diff_data.original,
|
||||
modified = result.diff_data.modified,
|
||||
approved = true,
|
||||
applied = true,
|
||||
})
|
||||
end
|
||||
|
||||
-- Store result for sending back to LLM
|
||||
table.insert(state.pending_tool_results, {
|
||||
tool_use_id = tool_call.id,
|
||||
@@ -280,21 +302,16 @@ function M.continue_with_results(context, callbacks)
|
||||
local codetyper = require("codetyper")
|
||||
local config = codetyper.get_config()
|
||||
|
||||
-- Copilot uses Claude-like format for tool results
|
||||
-- Copilot uses OpenAI format for tool results (role: "tool")
|
||||
if config.llm.provider == "copilot" then
|
||||
-- Claude-style tool_result blocks
|
||||
local content = {}
|
||||
-- OpenAI-style tool messages - each result is a separate message
|
||||
for _, result in ipairs(state.pending_tool_results) do
|
||||
table.insert(content, {
|
||||
type = "tool_result",
|
||||
tool_use_id = result.tool_use_id,
|
||||
table.insert(state.conversation, {
|
||||
role = "tool",
|
||||
tool_call_id = result.tool_use_id,
|
||||
content = result.result,
|
||||
})
|
||||
end
|
||||
table.insert(state.conversation, {
|
||||
role = "user",
|
||||
content = content,
|
||||
})
|
||||
else
|
||||
-- Ollama format: plain text describing results
|
||||
local result_text = "Tool results:\n"
|
||||
@@ -325,4 +342,114 @@ function M.set_max_iterations(max)
|
||||
state.max_iterations = max
|
||||
end
|
||||
|
||||
--- Get the count of collected changes
|
||||
---@return number
|
||||
function M.get_changes_count()
|
||||
return diff_review.count()
|
||||
end
|
||||
|
||||
--- Show the diff review UI for all collected changes
|
||||
function M.show_diff_review()
|
||||
diff_review.open()
|
||||
end
|
||||
|
||||
--- Check if diff review is open
|
||||
---@return boolean
|
||||
function M.is_review_open()
|
||||
return diff_review.is_open()
|
||||
end
|
||||
|
||||
--- Prompt user to continue or stop at max iterations
|
||||
---@param context table File context
|
||||
---@param callbacks AgentCallbacks
|
||||
function M.prompt_continue(context, callbacks)
|
||||
vim.schedule(function()
|
||||
vim.ui.select({ "Continue (25 more iterations)", "Stop and save for later" }, {
|
||||
prompt = string.format("Agent reached %d iterations. Continue?", state.max_iterations),
|
||||
}, function(choice)
|
||||
if choice and choice:match("^Continue") then
|
||||
-- Reset iteration counter and continue
|
||||
state.current_iteration = 0
|
||||
logs.info("User chose to continue, resetting iteration counter")
|
||||
M.agent_loop(context, callbacks)
|
||||
else
|
||||
-- Save state for later resume
|
||||
logs.info("User chose to stop, saving state for resume")
|
||||
resume.save(
|
||||
state.conversation,
|
||||
state.pending_tool_results,
|
||||
state.current_iteration,
|
||||
state.original_prompt
|
||||
)
|
||||
state.is_running = false
|
||||
callbacks.on_text("Agent paused. Use /continue to resume later.")
|
||||
callbacks.on_complete()
|
||||
end
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Continue a previously stopped agent session
|
||||
---@param callbacks AgentCallbacks
|
||||
---@return boolean Success
|
||||
function M.continue_session(callbacks)
|
||||
if state.is_running then
|
||||
utils.notify("Agent is already running", vim.log.levels.WARN)
|
||||
return false
|
||||
end
|
||||
|
||||
local saved = resume.load()
|
||||
if not saved then
|
||||
utils.notify("No saved agent session to continue", vim.log.levels.WARN)
|
||||
return false
|
||||
end
|
||||
|
||||
logs.info("Resuming agent session")
|
||||
logs.info(string.format("Loaded %d messages, iteration %d", #saved.conversation, saved.iteration))
|
||||
|
||||
-- Restore state
|
||||
state.conversation = saved.conversation
|
||||
state.pending_tool_results = saved.pending_tool_results or {}
|
||||
state.current_iteration = 0 -- Reset for fresh iterations
|
||||
state.original_prompt = saved.original_prompt
|
||||
state.is_running = true
|
||||
state.current_callbacks = callbacks
|
||||
|
||||
-- Build context from current state
|
||||
local llm = require("codetyper.llm")
|
||||
local context = {}
|
||||
local current_file = vim.fn.expand("%:p")
|
||||
if current_file ~= "" and vim.fn.filereadable(current_file) == 1 then
|
||||
context = llm.build_context(current_file, "agent")
|
||||
end
|
||||
state.current_context = context
|
||||
|
||||
-- Clear saved state
|
||||
resume.clear()
|
||||
|
||||
-- Add continuation message
|
||||
table.insert(state.conversation, {
|
||||
role = "user",
|
||||
content = "Continue where you left off. Complete the remaining tasks.",
|
||||
})
|
||||
|
||||
-- Continue the loop
|
||||
callbacks.on_text("Resuming agent session...")
|
||||
M.agent_loop(context, callbacks)
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
--- Check if there's a saved session to continue
|
||||
---@return boolean
|
||||
function M.has_saved_session()
|
||||
return resume.has_saved_state()
|
||||
end
|
||||
|
||||
--- Get info about saved session
|
||||
---@return table|nil
|
||||
function M.get_saved_session_info()
|
||||
return resume.get_info()
|
||||
end
|
||||
|
||||
return M
|
||||
|
||||
@@ -62,6 +62,11 @@ local intent_patterns = {
|
||||
"bug",
|
||||
"error",
|
||||
"issue",
|
||||
"update",
|
||||
"modify",
|
||||
"change",
|
||||
"adjust",
|
||||
"tweak",
|
||||
},
|
||||
scope_hint = "function",
|
||||
action = "replace",
|
||||
|
||||
431
lua/codetyper/agent/linter.lua
Normal file
431
lua/codetyper/agent/linter.lua
Normal file
@@ -0,0 +1,431 @@
|
||||
---@mod codetyper.agent.linter Linter validation for generated code
|
||||
---@brief [[
|
||||
--- Validates generated code by checking LSP diagnostics after injection.
|
||||
--- Automatically saves the file and waits for LSP to update before checking.
|
||||
---@brief ]]
|
||||
|
||||
local M = {}
|
||||
|
||||
--- Configuration
|
||||
local config = {
|
||||
-- Auto-save file after code injection
|
||||
auto_save = true,
|
||||
-- Delay in ms to wait for LSP diagnostics to update
|
||||
diagnostic_delay_ms = 500,
|
||||
-- Severity levels to check (1=Error, 2=Warning, 3=Info, 4=Hint)
|
||||
min_severity = vim.diagnostic.severity.WARN,
|
||||
-- Auto-offer to fix lint errors
|
||||
auto_offer_fix = true,
|
||||
}
|
||||
|
||||
--- Diagnostic results for tracking
|
||||
---@type table<number, table>
|
||||
local validation_results = {}
|
||||
|
||||
--- Configure linter behavior
|
||||
---@param opts table Configuration options
|
||||
function M.configure(opts)
|
||||
for k, v in pairs(opts) do
|
||||
if config[k] ~= nil then
|
||||
config[k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Get current configuration
|
||||
---@return table
|
||||
function M.get_config()
|
||||
return vim.deepcopy(config)
|
||||
end
|
||||
|
||||
--- Save buffer if modified
|
||||
---@param bufnr number Buffer number
|
||||
---@return boolean success
|
||||
local function save_buffer(bufnr)
|
||||
if not vim.api.nvim_buf_is_valid(bufnr) then
|
||||
return false
|
||||
end
|
||||
|
||||
-- Skip if buffer is not modified
|
||||
if not vim.bo[bufnr].modified then
|
||||
return true
|
||||
end
|
||||
|
||||
-- Skip if buffer has no name (unsaved file)
|
||||
local bufname = vim.api.nvim_buf_get_name(bufnr)
|
||||
if bufname == "" then
|
||||
return false
|
||||
end
|
||||
|
||||
-- Save the buffer
|
||||
local ok, err = pcall(function()
|
||||
vim.api.nvim_buf_call(bufnr, function()
|
||||
vim.cmd("silent! write")
|
||||
end)
|
||||
end)
|
||||
|
||||
if not ok then
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "warning",
|
||||
message = "Failed to save buffer: " .. tostring(err),
|
||||
})
|
||||
end)
|
||||
return false
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
--- Get LSP diagnostics for a buffer
|
||||
---@param bufnr number Buffer number
|
||||
---@param start_line? number Start line (1-indexed)
|
||||
---@param end_line? number End line (1-indexed)
|
||||
---@return table[] diagnostics List of diagnostics
|
||||
function M.get_diagnostics(bufnr, start_line, end_line)
|
||||
if not vim.api.nvim_buf_is_valid(bufnr) then
|
||||
return {}
|
||||
end
|
||||
|
||||
local all_diagnostics = vim.diagnostic.get(bufnr)
|
||||
local filtered = {}
|
||||
|
||||
for _, diag in ipairs(all_diagnostics) do
|
||||
-- Filter by severity
|
||||
if diag.severity <= config.min_severity then
|
||||
-- Filter by line range if specified
|
||||
if start_line and end_line then
|
||||
local diag_line = diag.lnum + 1 -- Convert to 1-indexed
|
||||
if diag_line >= start_line and diag_line <= end_line then
|
||||
table.insert(filtered, diag)
|
||||
end
|
||||
else
|
||||
table.insert(filtered, diag)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return filtered
|
||||
end
|
||||
|
||||
--- Format a diagnostic for display
|
||||
---@param diag table Diagnostic object
|
||||
---@return string
|
||||
local function format_diagnostic(diag)
|
||||
local severity_names = {
|
||||
[vim.diagnostic.severity.ERROR] = "ERROR",
|
||||
[vim.diagnostic.severity.WARN] = "WARN",
|
||||
[vim.diagnostic.severity.INFO] = "INFO",
|
||||
[vim.diagnostic.severity.HINT] = "HINT",
|
||||
}
|
||||
local severity = severity_names[diag.severity] or "UNKNOWN"
|
||||
local line = diag.lnum + 1
|
||||
local source = diag.source or "lsp"
|
||||
return string.format("[%s] Line %d (%s): %s", severity, line, source, diag.message)
|
||||
end
|
||||
|
||||
--- Check if there are errors in generated code region
|
||||
---@param bufnr number Buffer number
|
||||
---@param start_line number Start line (1-indexed)
|
||||
---@param end_line number End line (1-indexed)
|
||||
---@return table result {has_errors, has_warnings, diagnostics, summary}
|
||||
function M.check_region(bufnr, start_line, end_line)
|
||||
local diagnostics = M.get_diagnostics(bufnr, start_line, end_line)
|
||||
|
||||
local errors = 0
|
||||
local warnings = 0
|
||||
|
||||
for _, diag in ipairs(diagnostics) do
|
||||
if diag.severity == vim.diagnostic.severity.ERROR then
|
||||
errors = errors + 1
|
||||
elseif diag.severity == vim.diagnostic.severity.WARN then
|
||||
warnings = warnings + 1
|
||||
end
|
||||
end
|
||||
|
||||
return {
|
||||
has_errors = errors > 0,
|
||||
has_warnings = warnings > 0,
|
||||
error_count = errors,
|
||||
warning_count = warnings,
|
||||
diagnostics = diagnostics,
|
||||
summary = string.format("%d error(s), %d warning(s)", errors, warnings),
|
||||
}
|
||||
end
|
||||
|
||||
--- Validate code after injection and report issues
|
||||
---@param bufnr number Buffer number
|
||||
---@param start_line? number Start line of injected code (1-indexed)
|
||||
---@param end_line? number End line of injected code (1-indexed)
|
||||
---@param callback? function Callback with (result) when validation completes
|
||||
function M.validate_after_injection(bufnr, start_line, end_line, callback)
|
||||
-- Save the file first
|
||||
if config.auto_save then
|
||||
save_buffer(bufnr)
|
||||
end
|
||||
|
||||
-- Wait for LSP to process changes
|
||||
vim.defer_fn(function()
|
||||
if not vim.api.nvim_buf_is_valid(bufnr) then
|
||||
if callback then callback(nil) end
|
||||
return
|
||||
end
|
||||
|
||||
local result
|
||||
if start_line and end_line then
|
||||
result = M.check_region(bufnr, start_line, end_line)
|
||||
else
|
||||
-- Check entire buffer
|
||||
local line_count = vim.api.nvim_buf_line_count(bufnr)
|
||||
result = M.check_region(bufnr, 1, line_count)
|
||||
end
|
||||
|
||||
-- Store result for this buffer
|
||||
validation_results[bufnr] = {
|
||||
timestamp = os.time(),
|
||||
result = result,
|
||||
start_line = start_line,
|
||||
end_line = end_line,
|
||||
}
|
||||
|
||||
-- Log results
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
if result.has_errors then
|
||||
logs.add({
|
||||
type = "error",
|
||||
message = string.format("Linter found issues: %s", result.summary),
|
||||
})
|
||||
-- Log individual errors
|
||||
for _, diag in ipairs(result.diagnostics) do
|
||||
if diag.severity == vim.diagnostic.severity.ERROR then
|
||||
logs.add({
|
||||
type = "error",
|
||||
message = format_diagnostic(diag),
|
||||
})
|
||||
end
|
||||
end
|
||||
elseif result.has_warnings then
|
||||
logs.add({
|
||||
type = "warning",
|
||||
message = string.format("Linter warnings: %s", result.summary),
|
||||
})
|
||||
else
|
||||
logs.add({
|
||||
type = "success",
|
||||
message = "Linter check passed - no errors or warnings",
|
||||
})
|
||||
end
|
||||
end)
|
||||
|
||||
-- Notify user
|
||||
if result.has_errors then
|
||||
vim.notify(
|
||||
string.format("Generated code has lint errors: %s", result.summary),
|
||||
vim.log.levels.ERROR
|
||||
)
|
||||
|
||||
-- Offer to fix if configured
|
||||
if config.auto_offer_fix and #result.diagnostics > 0 then
|
||||
M.offer_fix(bufnr, result)
|
||||
end
|
||||
elseif result.has_warnings then
|
||||
vim.notify(
|
||||
string.format("Generated code has warnings: %s", result.summary),
|
||||
vim.log.levels.WARN
|
||||
)
|
||||
end
|
||||
|
||||
if callback then
|
||||
callback(result)
|
||||
end
|
||||
end, config.diagnostic_delay_ms)
|
||||
end
|
||||
|
||||
--- Offer to fix lint errors using AI
|
||||
---@param bufnr number Buffer number
|
||||
---@param result table Validation result
|
||||
function M.offer_fix(bufnr, result)
|
||||
if not result.has_errors and not result.has_warnings then
|
||||
return
|
||||
end
|
||||
|
||||
-- Build error summary for prompt
|
||||
local error_messages = {}
|
||||
for _, diag in ipairs(result.diagnostics) do
|
||||
table.insert(error_messages, format_diagnostic(diag))
|
||||
end
|
||||
|
||||
vim.ui.select(
|
||||
{ "Yes - Auto-fix with AI", "No - I'll fix manually", "Show errors in quickfix" },
|
||||
{
|
||||
prompt = string.format("Found %d issue(s). Would you like AI to fix them?", #result.diagnostics),
|
||||
},
|
||||
function(choice)
|
||||
if not choice then return end
|
||||
|
||||
if choice:match("^Yes") then
|
||||
M.request_ai_fix(bufnr, result)
|
||||
elseif choice:match("quickfix") then
|
||||
M.show_in_quickfix(bufnr, result)
|
||||
end
|
||||
end
|
||||
)
|
||||
end
|
||||
|
||||
--- Show lint errors in quickfix list
|
||||
---@param bufnr number Buffer number
|
||||
---@param result table Validation result
|
||||
function M.show_in_quickfix(bufnr, result)
|
||||
local qf_items = {}
|
||||
local bufname = vim.api.nvim_buf_get_name(bufnr)
|
||||
|
||||
for _, diag in ipairs(result.diagnostics) do
|
||||
table.insert(qf_items, {
|
||||
bufnr = bufnr,
|
||||
filename = bufname,
|
||||
lnum = diag.lnum + 1,
|
||||
col = diag.col + 1,
|
||||
text = diag.message,
|
||||
type = diag.severity == vim.diagnostic.severity.ERROR and "E" or "W",
|
||||
})
|
||||
end
|
||||
|
||||
vim.fn.setqflist(qf_items, "r")
|
||||
vim.cmd("copen")
|
||||
end
|
||||
|
||||
--- Request AI to fix lint errors
|
||||
---@param bufnr number Buffer number
|
||||
---@param result table Validation result
|
||||
function M.request_ai_fix(bufnr, result)
|
||||
if not vim.api.nvim_buf_is_valid(bufnr) then
|
||||
return
|
||||
end
|
||||
|
||||
local filepath = vim.api.nvim_buf_get_name(bufnr)
|
||||
|
||||
-- Build fix prompt
|
||||
local error_list = {}
|
||||
for _, diag in ipairs(result.diagnostics) do
|
||||
table.insert(error_list, format_diagnostic(diag))
|
||||
end
|
||||
|
||||
-- Get the affected code region
|
||||
local start_line = result.diagnostics[1] and (result.diagnostics[1].lnum + 1) or 1
|
||||
local end_line = start_line
|
||||
for _, diag in ipairs(result.diagnostics) do
|
||||
local line = diag.lnum + 1
|
||||
if line < start_line then start_line = line end
|
||||
if line > end_line then end_line = line end
|
||||
end
|
||||
|
||||
-- Expand range by a few lines for context
|
||||
start_line = math.max(1, start_line - 5)
|
||||
end_line = math.min(vim.api.nvim_buf_line_count(bufnr), end_line + 5)
|
||||
|
||||
local lines = vim.api.nvim_buf_get_lines(bufnr, start_line - 1, end_line, false)
|
||||
local code_context = table.concat(lines, "\n")
|
||||
|
||||
-- Create fix prompt using inline tag
|
||||
local fix_prompt = string.format(
|
||||
"Fix the following linter errors in this code:\n\nERRORS:\n%s\n\nCODE (lines %d-%d):\n%s",
|
||||
table.concat(error_list, "\n"),
|
||||
start_line,
|
||||
end_line,
|
||||
code_context
|
||||
)
|
||||
|
||||
-- Queue the fix through the scheduler
|
||||
local scheduler = require("codetyper.agent.scheduler")
|
||||
local queue = require("codetyper.agent.queue")
|
||||
local patch_mod = require("codetyper.agent.patch")
|
||||
|
||||
-- Ensure scheduler is running
|
||||
if not scheduler.status().running then
|
||||
scheduler.start()
|
||||
end
|
||||
|
||||
-- Take snapshot
|
||||
local snapshot = patch_mod.snapshot_buffer(bufnr, {
|
||||
start_line = start_line,
|
||||
end_line = end_line,
|
||||
})
|
||||
|
||||
-- Enqueue fix request
|
||||
queue.enqueue({
|
||||
id = queue.generate_id(),
|
||||
bufnr = bufnr,
|
||||
range = { start_line = start_line, end_line = end_line },
|
||||
timestamp = os.clock(),
|
||||
changedtick = snapshot.changedtick,
|
||||
content_hash = snapshot.content_hash,
|
||||
prompt_content = fix_prompt,
|
||||
target_path = filepath,
|
||||
priority = 1, -- High priority for fixes
|
||||
status = "pending",
|
||||
attempt_count = 0,
|
||||
intent = {
|
||||
type = "fix",
|
||||
action = "replace",
|
||||
confidence = 0.9,
|
||||
},
|
||||
scope_range = { start_line = start_line, end_line = end_line },
|
||||
source = "linter_fix",
|
||||
})
|
||||
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "info",
|
||||
message = "Queued AI fix request for lint errors",
|
||||
})
|
||||
end)
|
||||
|
||||
vim.notify("Queued AI fix request for lint errors", vim.log.levels.INFO)
|
||||
end
|
||||
|
||||
--- Get last validation result for a buffer
|
||||
---@param bufnr number Buffer number
|
||||
---@return table|nil result
|
||||
function M.get_last_result(bufnr)
|
||||
return validation_results[bufnr]
|
||||
end
|
||||
|
||||
--- Clear validation results for a buffer
|
||||
---@param bufnr number Buffer number
|
||||
function M.clear_result(bufnr)
|
||||
validation_results[bufnr] = nil
|
||||
end
|
||||
|
||||
--- Check if buffer has any lint errors currently
|
||||
---@param bufnr number Buffer number
|
||||
---@return boolean has_errors
|
||||
function M.has_errors(bufnr)
|
||||
local diagnostics = vim.diagnostic.get(bufnr, {
|
||||
severity = vim.diagnostic.severity.ERROR,
|
||||
})
|
||||
return #diagnostics > 0
|
||||
end
|
||||
|
||||
--- Check if buffer has any lint warnings currently
|
||||
---@param bufnr number Buffer number
|
||||
---@return boolean has_warnings
|
||||
function M.has_warnings(bufnr)
|
||||
local diagnostics = vim.diagnostic.get(bufnr, {
|
||||
severity = { min = vim.diagnostic.severity.WARN },
|
||||
})
|
||||
return #diagnostics > 0
|
||||
end
|
||||
|
||||
--- Validate all buffers with recent changes
|
||||
function M.validate_all_changed()
|
||||
for bufnr, data in pairs(validation_results) do
|
||||
if vim.api.nvim_buf_is_valid(bufnr) then
|
||||
M.validate_after_injection(bufnr, data.start_line, data.end_line)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -165,10 +165,83 @@ function M.add(entry)
|
||||
M.log(entry.type or "info", entry.message or "", entry.data)
|
||||
end
|
||||
|
||||
--- Log thinking/reasoning step
|
||||
--- Log thinking/reasoning step (Claude Code style)
|
||||
---@param step string Description of what's happening
|
||||
function M.thinking(step)
|
||||
M.log("debug", "> " .. step)
|
||||
M.log("thinking", step)
|
||||
end
|
||||
|
||||
--- Log a reasoning/explanation message (shown prominently)
|
||||
---@param message string The reasoning message
|
||||
function M.reason(message)
|
||||
M.log("reason", message)
|
||||
end
|
||||
|
||||
--- Log file read operation
|
||||
---@param filepath string Path of file being read
|
||||
---@param lines? number Number of lines read
|
||||
function M.read(filepath, lines)
|
||||
local msg = string.format("Read(%s)", vim.fn.fnamemodify(filepath, ":~:."))
|
||||
if lines then
|
||||
msg = msg .. string.format("\n ⎿ Read %d lines", lines)
|
||||
end
|
||||
M.log("action", msg)
|
||||
end
|
||||
|
||||
--- Log explore/search operation
|
||||
---@param description string What we're exploring
|
||||
function M.explore(description)
|
||||
M.log("action", string.format("Explore(%s)", description))
|
||||
end
|
||||
|
||||
--- Log explore done
|
||||
---@param tool_uses number Number of tool uses
|
||||
---@param tokens number Tokens used
|
||||
---@param duration number Duration in seconds
|
||||
function M.explore_done(tool_uses, tokens, duration)
|
||||
M.log("result", string.format(" ⎿ Done (%d tool uses · %.1fk tokens · %.1fs)", tool_uses, tokens / 1000, duration))
|
||||
end
|
||||
|
||||
--- Log update/edit operation
|
||||
---@param filepath string Path of file being edited
|
||||
---@param added? number Lines added
|
||||
---@param removed? number Lines removed
|
||||
function M.update(filepath, added, removed)
|
||||
local msg = string.format("Update(%s)", vim.fn.fnamemodify(filepath, ":~:."))
|
||||
if added or removed then
|
||||
local parts = {}
|
||||
if added and added > 0 then
|
||||
table.insert(parts, string.format("Added %d lines", added))
|
||||
end
|
||||
if removed and removed > 0 then
|
||||
table.insert(parts, string.format("Removed %d lines", removed))
|
||||
end
|
||||
if #parts > 0 then
|
||||
msg = msg .. "\n ⎿ " .. table.concat(parts, ", ")
|
||||
end
|
||||
end
|
||||
M.log("action", msg)
|
||||
end
|
||||
|
||||
--- Log a task/step that's in progress
|
||||
---@param task string Task name
|
||||
---@param status string Status message (optional)
|
||||
function M.task(task, status)
|
||||
local msg = task
|
||||
if status then
|
||||
msg = msg .. " " .. status
|
||||
end
|
||||
M.log("task", msg)
|
||||
end
|
||||
|
||||
--- Log task completion
|
||||
---@param next_task? string Next task (optional)
|
||||
function M.task_done(next_task)
|
||||
local msg = " ⎿ Done"
|
||||
if next_task then
|
||||
msg = msg .. "\n✶ " .. next_task
|
||||
end
|
||||
M.log("result", msg)
|
||||
end
|
||||
|
||||
--- Register a listener for new log entries
|
||||
@@ -223,6 +296,27 @@ end
|
||||
---@param entry LogEntry
|
||||
---@return string
|
||||
function M.format_entry(entry)
|
||||
-- Claude Code style formatting for thinking/action entries
|
||||
local thinking_types = { "thinking", "reason", "action", "task", "result" }
|
||||
local is_thinking = vim.tbl_contains(thinking_types, entry.level)
|
||||
|
||||
if is_thinking then
|
||||
local prefix = ({
|
||||
thinking = "⏺",
|
||||
reason = "⏺",
|
||||
action = "⏺",
|
||||
task = "✶",
|
||||
result = "",
|
||||
})[entry.level] or "⏺"
|
||||
|
||||
if prefix ~= "" then
|
||||
return prefix .. " " .. entry.message
|
||||
else
|
||||
return entry.message
|
||||
end
|
||||
end
|
||||
|
||||
-- Traditional log format for other types
|
||||
local level_prefix = ({
|
||||
info = "i",
|
||||
debug = ".",
|
||||
@@ -248,6 +342,60 @@ function M.format_entry(entry)
|
||||
return base
|
||||
end
|
||||
|
||||
--- Format entry for display in chat (compact Claude Code style)
|
||||
---@param entry LogEntry
|
||||
---@return string|nil Formatted string or nil to skip
|
||||
function M.format_for_chat(entry)
|
||||
-- Skip certain log types in chat view
|
||||
local skip_types = { "debug", "queue", "patch" }
|
||||
if vim.tbl_contains(skip_types, entry.level) then
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Claude Code style formatting
|
||||
local thinking_types = { "thinking", "reason", "action", "task", "result" }
|
||||
if vim.tbl_contains(thinking_types, entry.level) then
|
||||
local prefix = ({
|
||||
thinking = "⏺",
|
||||
reason = "⏺",
|
||||
action = "⏺",
|
||||
task = "✶",
|
||||
result = "",
|
||||
})[entry.level] or "⏺"
|
||||
|
||||
if prefix ~= "" then
|
||||
return prefix .. " " .. entry.message
|
||||
else
|
||||
return entry.message
|
||||
end
|
||||
end
|
||||
|
||||
-- Tool logs
|
||||
if entry.level == "tool" then
|
||||
return "⏺ " .. entry.message:gsub("^%[.-%] ", "")
|
||||
end
|
||||
|
||||
-- Info/success
|
||||
if entry.level == "info" or entry.level == "success" then
|
||||
return "⏺ " .. entry.message
|
||||
end
|
||||
|
||||
-- Errors
|
||||
if entry.level == "error" then
|
||||
return "⚠ " .. entry.message
|
||||
end
|
||||
|
||||
-- Request/response (compact)
|
||||
if entry.level == "request" then
|
||||
return "⏺ " .. entry.message
|
||||
end
|
||||
if entry.level == "response" then
|
||||
return " ⎿ " .. entry.message
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Estimate token count for a string (rough approximation)
|
||||
---@param text string
|
||||
---@return number
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---@mod codetyper.agent.loop Agent loop with tool orchestration
|
||||
---@brief [[
|
||||
--- Main agent loop that handles multi-turn conversations with tool use.
|
||||
--- Inspired by avante.nvim's agent_loop pattern.
|
||||
--- Agent execution loop with tool calling support.
|
||||
---@brief ]]
|
||||
|
||||
local M = {}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
---@brief [[
|
||||
--- Manages code patches with buffer snapshots for staleness detection.
|
||||
--- Patches are queued for safe injection when completion popup is not visible.
|
||||
--- Uses smart injection for intelligent import merging.
|
||||
--- Uses SEARCH/REPLACE blocks for reliable code editing.
|
||||
---@brief ]]
|
||||
|
||||
local M = {}
|
||||
@@ -12,6 +12,24 @@ local function get_inject_module()
|
||||
return require("codetyper.agent.inject")
|
||||
end
|
||||
|
||||
--- Lazy load search_replace module
|
||||
local function get_search_replace_module()
|
||||
return require("codetyper.agent.search_replace")
|
||||
end
|
||||
|
||||
--- Lazy load conflict module
|
||||
local function get_conflict_module()
|
||||
return require("codetyper.agent.conflict")
|
||||
end
|
||||
|
||||
--- Configuration for patch behavior
|
||||
local config = {
|
||||
-- Use conflict markers instead of direct apply (allows interactive review)
|
||||
use_conflict_mode = true,
|
||||
-- Auto-jump to first conflict after applying
|
||||
auto_jump_to_conflict = true,
|
||||
}
|
||||
|
||||
---@class BufferSnapshot
|
||||
---@field bufnr number Buffer number
|
||||
---@field changedtick number vim.b.changedtick at snapshot time
|
||||
@@ -27,11 +45,13 @@ end
|
||||
---@field original_snapshot BufferSnapshot Snapshot at event creation
|
||||
---@field generated_code string Code to inject
|
||||
---@field injection_range {start_line: number, end_line: number}|nil
|
||||
---@field injection_strategy string "append"|"replace"|"insert"
|
||||
---@field injection_strategy string "append"|"replace"|"insert"|"search_replace"
|
||||
---@field confidence number Confidence score (0.0-1.0)
|
||||
---@field status string "pending"|"applied"|"stale"|"rejected"
|
||||
---@field created_at number Timestamp
|
||||
---@field applied_at number|nil When applied
|
||||
---@field use_search_replace boolean Whether to use SEARCH/REPLACE block parsing
|
||||
---@field search_replace_blocks table[]|nil Parsed SEARCH/REPLACE blocks
|
||||
|
||||
--- Patch storage
|
||||
---@type PatchCandidate[]
|
||||
@@ -194,6 +214,10 @@ function M.create_from_event(event, generated_code, confidence, strategy)
|
||||
end
|
||||
end
|
||||
|
||||
-- Detect if this is an inline prompt (source == target, not a .coder. file)
|
||||
local is_inline = (source_bufnr == target_bufnr) or
|
||||
(event.target_path and not event.target_path:match("%.coder%."))
|
||||
|
||||
-- Take snapshot of the scope range in target buffer (for staleness detection)
|
||||
local snapshot_range = event.scope_range or event.range
|
||||
local snapshot = M.snapshot_buffer(
|
||||
@@ -201,22 +225,67 @@ function M.create_from_event(event, generated_code, confidence, strategy)
|
||||
snapshot_range
|
||||
)
|
||||
|
||||
-- Check if the response contains SEARCH/REPLACE blocks
|
||||
local search_replace = get_search_replace_module()
|
||||
local sr_blocks = search_replace.parse_blocks(generated_code)
|
||||
local use_search_replace = #sr_blocks > 0
|
||||
|
||||
-- Determine injection strategy and range based on intent
|
||||
local injection_strategy = strategy
|
||||
local injection_range = nil
|
||||
|
||||
if not injection_strategy and event.intent then
|
||||
-- If we have SEARCH/REPLACE blocks, use that strategy
|
||||
if use_search_replace then
|
||||
injection_strategy = "search_replace"
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "info",
|
||||
message = string.format("Using SEARCH/REPLACE mode with %d block(s)", #sr_blocks),
|
||||
})
|
||||
end)
|
||||
elseif not injection_strategy and event.intent then
|
||||
local intent_mod = require("codetyper.agent.intent")
|
||||
if intent_mod.is_replacement(event.intent) then
|
||||
injection_strategy = "replace"
|
||||
-- Use scope range for replacement
|
||||
if event.scope_range then
|
||||
|
||||
-- INLINE PROMPTS: Always use tag range
|
||||
-- The LLM is told specifically to replace the tagged region
|
||||
if is_inline and event.range then
|
||||
injection_range = {
|
||||
start_line = event.range.start_line,
|
||||
end_line = event.range.end_line,
|
||||
}
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "info",
|
||||
message = string.format("Inline prompt: will replace tag region (lines %d-%d)",
|
||||
event.range.start_line, event.range.end_line),
|
||||
})
|
||||
end)
|
||||
-- CODER FILES: Use scope range for replacement
|
||||
elseif event.scope_range then
|
||||
injection_range = event.scope_range
|
||||
else
|
||||
-- Fallback: no scope found (treesitter didn't find function)
|
||||
-- Use tag range - the generated code will replace the tag region
|
||||
injection_range = {
|
||||
start_line = event.range.start_line,
|
||||
end_line = event.range.end_line,
|
||||
}
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "warning",
|
||||
message = "No scope found, using tag range as fallback",
|
||||
})
|
||||
end)
|
||||
end
|
||||
elseif event.intent.action == "insert" then
|
||||
injection_strategy = "insert"
|
||||
-- Insert at prompt location
|
||||
injection_range = { start_line = event.range.start_line, end_line = event.range.start_line }
|
||||
-- Insert at prompt location (use full tag range)
|
||||
injection_range = { start_line = event.range.start_line, end_line = event.range.end_line }
|
||||
elseif event.intent.action == "append" then
|
||||
injection_strategy = "append"
|
||||
-- Will append to end of file
|
||||
@@ -244,6 +313,11 @@ function M.create_from_event(event, generated_code, confidence, strategy)
|
||||
scope = event.scope,
|
||||
-- Store the prompt tag range so we can delete it after applying
|
||||
prompt_tag_range = event.range,
|
||||
-- Mark if this is an inline prompt (tags in source file, not coder file)
|
||||
is_inline_prompt = is_inline,
|
||||
-- SEARCH/REPLACE support
|
||||
use_search_replace = use_search_replace,
|
||||
search_replace_blocks = use_search_replace and sr_blocks or nil,
|
||||
}
|
||||
end
|
||||
|
||||
@@ -464,13 +538,15 @@ function M.apply(patch)
|
||||
-- Prepare code lines
|
||||
local code_lines = vim.split(patch.generated_code, "\n", { plain = true })
|
||||
|
||||
-- FIRST: Remove the prompt tags from the SOURCE buffer (coder file), not target
|
||||
-- The tags are in the coder file where the user wrote the prompt
|
||||
-- Code goes to target file, tags get removed from source file
|
||||
-- Use the stored inline prompt flag (computed during patch creation)
|
||||
-- For inline prompts, we replace the tag region directly instead of separate remove + inject
|
||||
local source_bufnr = patch.source_bufnr
|
||||
local is_inline_prompt = patch.is_inline_prompt or (source_bufnr == target_bufnr)
|
||||
local tags_removed = 0
|
||||
|
||||
if source_bufnr and vim.api.nvim_buf_is_valid(source_bufnr) then
|
||||
-- For CODER FILES (source != target): Remove tags from source, inject into target
|
||||
-- For INLINE PROMPTS (source == target): Include tag range in injection, no separate removal
|
||||
if not is_inline_prompt and source_bufnr and vim.api.nvim_buf_is_valid(source_bufnr) then
|
||||
tags_removed = remove_prompt_tags(source_bufnr)
|
||||
|
||||
pcall(function()
|
||||
@@ -490,6 +566,76 @@ function M.apply(patch)
|
||||
-- Get filetype for smart injection
|
||||
local filetype = vim.fn.fnamemodify(patch.target_path or "", ":e")
|
||||
|
||||
-- SEARCH/REPLACE MODE: Use fuzzy matching to find and replace text
|
||||
if patch.use_search_replace and patch.search_replace_blocks and #patch.search_replace_blocks > 0 then
|
||||
local search_replace = get_search_replace_module()
|
||||
|
||||
-- Remove the /@ @/ tags first (they shouldn't be in the file anymore)
|
||||
if is_inline_prompt and source_bufnr and vim.api.nvim_buf_is_valid(source_bufnr) then
|
||||
tags_removed = remove_prompt_tags(source_bufnr)
|
||||
if tags_removed > 0 then
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "info",
|
||||
message = string.format("Removed %d prompt tag(s)", tags_removed),
|
||||
})
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
-- Apply SEARCH/REPLACE blocks
|
||||
local success, err = search_replace.apply_to_buffer(target_bufnr, patch.search_replace_blocks)
|
||||
|
||||
if success then
|
||||
M.mark_applied(patch.id)
|
||||
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "success",
|
||||
message = string.format("Patch %s applied via SEARCH/REPLACE (%d block(s))",
|
||||
patch.id, #patch.search_replace_blocks),
|
||||
data = {
|
||||
target_path = patch.target_path,
|
||||
blocks_applied = #patch.search_replace_blocks,
|
||||
},
|
||||
})
|
||||
end)
|
||||
|
||||
-- Learn from successful code generation
|
||||
pcall(function()
|
||||
local brain = require("codetyper.brain")
|
||||
if brain.is_initialized() then
|
||||
local intent_type = patch.intent and patch.intent.type or "unknown"
|
||||
brain.learn({
|
||||
type = "code_completion",
|
||||
file = patch.target_path,
|
||||
timestamp = os.time(),
|
||||
data = {
|
||||
intent = intent_type,
|
||||
method = "search_replace",
|
||||
language = filetype,
|
||||
confidence = patch.confidence or 0.5,
|
||||
},
|
||||
})
|
||||
end
|
||||
end)
|
||||
|
||||
return true, nil
|
||||
else
|
||||
-- SEARCH/REPLACE failed, log the error
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "warning",
|
||||
message = string.format("SEARCH/REPLACE failed: %s. Falling back to line-based injection.", err or "unknown"),
|
||||
})
|
||||
end)
|
||||
-- Fall through to line-based injection as fallback
|
||||
end
|
||||
end
|
||||
|
||||
-- Use smart injection module for intelligent import handling
|
||||
local inject = get_inject_module()
|
||||
local inject_result = nil
|
||||
@@ -508,10 +654,10 @@ function M.apply(patch)
|
||||
local start_line = patch.injection_range.start_line
|
||||
local end_line = patch.injection_range.end_line
|
||||
|
||||
-- Adjust for tag removal - find the new range by searching for the scope
|
||||
-- After removing tags, line numbers may have shifted
|
||||
if patch.scope and patch.scope.type then
|
||||
-- Try to find the scope using treesitter if available
|
||||
-- For inline prompts, use scope range directly (tags are inside scope)
|
||||
-- No adjustment needed since we didn't remove tags yet
|
||||
if not is_inline_prompt and patch.scope and patch.scope.type then
|
||||
-- For coder files, tags were already removed, so we may need to find the scope again
|
||||
local found_range = nil
|
||||
pcall(function()
|
||||
local parsers = require("nvim-treesitter.parsers")
|
||||
@@ -562,7 +708,31 @@ function M.apply(patch)
|
||||
|
||||
inject_opts.range = { start_line = start_line, end_line = end_line }
|
||||
elseif patch.injection_strategy == "insert" and patch.injection_range then
|
||||
inject_opts.range = { start_line = patch.injection_range.start_line }
|
||||
-- For inline prompts with "insert" strategy, replace the TAG RANGE
|
||||
-- (the tag itself gets replaced with the new code)
|
||||
if is_inline_prompt and patch.prompt_tag_range then
|
||||
inject_opts.range = {
|
||||
start_line = patch.prompt_tag_range.start_line,
|
||||
end_line = patch.prompt_tag_range.end_line
|
||||
}
|
||||
-- Switch to replace strategy for the tag range
|
||||
inject_opts.strategy = "replace"
|
||||
else
|
||||
inject_opts.range = { start_line = patch.injection_range.start_line }
|
||||
end
|
||||
end
|
||||
|
||||
-- Log inline prompt handling
|
||||
if is_inline_prompt then
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "info",
|
||||
message = string.format("Inline prompt: replacing lines %d-%d",
|
||||
inject_opts.range and inject_opts.range.start_line or 0,
|
||||
inject_opts.range and inject_opts.range.end_line or 0),
|
||||
})
|
||||
end)
|
||||
end
|
||||
|
||||
-- Use smart injection - handles imports automatically
|
||||
@@ -729,4 +899,202 @@ function M.clear()
|
||||
patches = {}
|
||||
end
|
||||
|
||||
--- Configure patch behavior
|
||||
---@param opts table Configuration options
|
||||
--- - use_conflict_mode: boolean Use conflict markers instead of direct apply
|
||||
--- - auto_jump_to_conflict: boolean Auto-jump to first conflict after applying
|
||||
function M.configure(opts)
|
||||
if opts.use_conflict_mode ~= nil then
|
||||
config.use_conflict_mode = opts.use_conflict_mode
|
||||
end
|
||||
if opts.auto_jump_to_conflict ~= nil then
|
||||
config.auto_jump_to_conflict = opts.auto_jump_to_conflict
|
||||
end
|
||||
end
|
||||
|
||||
--- Get current configuration
|
||||
---@return table
|
||||
function M.get_config()
|
||||
return vim.deepcopy(config)
|
||||
end
|
||||
|
||||
--- Check if conflict mode is enabled
|
||||
---@return boolean
|
||||
function M.is_conflict_mode()
|
||||
return config.use_conflict_mode
|
||||
end
|
||||
|
||||
--- Apply a patch using conflict markers for interactive review
|
||||
--- Instead of directly replacing code, inserts git-style conflict markers
|
||||
---@param patch PatchCandidate
|
||||
---@return boolean success
|
||||
---@return string|nil error
|
||||
function M.apply_with_conflict(patch)
|
||||
-- Check if safe to modify (not in insert mode)
|
||||
if not is_safe_to_modify() then
|
||||
return false, "user_typing"
|
||||
end
|
||||
|
||||
-- Check staleness first
|
||||
local is_stale, stale_reason = M.is_stale(patch)
|
||||
if is_stale then
|
||||
M.mark_stale(patch.id, stale_reason)
|
||||
return false, "patch_stale: " .. (stale_reason or "unknown")
|
||||
end
|
||||
|
||||
-- Ensure target buffer is valid
|
||||
local target_bufnr = patch.target_bufnr
|
||||
if target_bufnr == -1 or not vim.api.nvim_buf_is_valid(target_bufnr) then
|
||||
target_bufnr = vim.fn.bufadd(patch.target_path)
|
||||
if target_bufnr == 0 then
|
||||
M.mark_rejected(patch.id, "buffer_not_found")
|
||||
return false, "target buffer not found"
|
||||
end
|
||||
vim.fn.bufload(target_bufnr)
|
||||
patch.target_bufnr = target_bufnr
|
||||
end
|
||||
|
||||
local conflict = get_conflict_module()
|
||||
local source_bufnr = patch.source_bufnr
|
||||
local is_inline_prompt = patch.is_inline_prompt or (source_bufnr == target_bufnr)
|
||||
|
||||
-- Remove tags from coder files
|
||||
if not is_inline_prompt and source_bufnr and vim.api.nvim_buf_is_valid(source_bufnr) then
|
||||
remove_prompt_tags(source_bufnr)
|
||||
end
|
||||
|
||||
-- For SEARCH/REPLACE blocks, convert each block to a conflict
|
||||
if patch.use_search_replace and patch.search_replace_blocks and #patch.search_replace_blocks > 0 then
|
||||
local search_replace = get_search_replace_module()
|
||||
local content = table.concat(vim.api.nvim_buf_get_lines(target_bufnr, 0, -1, false), "\n")
|
||||
local applied_count = 0
|
||||
|
||||
-- Sort blocks by position (bottom to top) to maintain line numbers
|
||||
local sorted_blocks = {}
|
||||
for _, block in ipairs(patch.search_replace_blocks) do
|
||||
local match = search_replace.find_match(content, block.search)
|
||||
if match then
|
||||
block._match = match
|
||||
table.insert(sorted_blocks, block)
|
||||
end
|
||||
end
|
||||
table.sort(sorted_blocks, function(a, b)
|
||||
return (a._match and a._match.start_line or 0) > (b._match and b._match.start_line or 0)
|
||||
end)
|
||||
|
||||
-- Apply each block as a conflict
|
||||
for _, block in ipairs(sorted_blocks) do
|
||||
local match = block._match
|
||||
if match then
|
||||
local new_lines = vim.split(block.replace, "\n", { plain = true })
|
||||
conflict.insert_conflict(
|
||||
target_bufnr,
|
||||
match.start_line,
|
||||
match.end_line,
|
||||
new_lines,
|
||||
"AI SUGGESTION"
|
||||
)
|
||||
applied_count = applied_count + 1
|
||||
-- Re-read content for next match (line numbers changed)
|
||||
content = table.concat(vim.api.nvim_buf_get_lines(target_bufnr, 0, -1, false), "\n")
|
||||
end
|
||||
end
|
||||
|
||||
if applied_count > 0 then
|
||||
-- Remove tags for inline prompts after inserting conflicts
|
||||
if is_inline_prompt and source_bufnr and vim.api.nvim_buf_is_valid(source_bufnr) then
|
||||
remove_prompt_tags(source_bufnr)
|
||||
end
|
||||
|
||||
-- Process conflicts (highlight, keymaps) and show menu
|
||||
conflict.process_and_show_menu(target_bufnr)
|
||||
|
||||
M.mark_applied(patch.id)
|
||||
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "success",
|
||||
message = string.format(
|
||||
"Created %d conflict(s) for review - use co/ct/cb/cn to resolve",
|
||||
applied_count
|
||||
),
|
||||
})
|
||||
end)
|
||||
|
||||
return true, nil
|
||||
end
|
||||
end
|
||||
|
||||
-- Fallback: Use injection range if available
|
||||
if patch.injection_range then
|
||||
local start_line = patch.injection_range.start_line
|
||||
local end_line = patch.injection_range.end_line
|
||||
local new_lines = vim.split(patch.generated_code, "\n", { plain = true })
|
||||
|
||||
-- Remove tags for inline prompts
|
||||
if is_inline_prompt and source_bufnr and vim.api.nvim_buf_is_valid(source_bufnr) then
|
||||
remove_prompt_tags(source_bufnr)
|
||||
end
|
||||
|
||||
-- Insert conflict markers
|
||||
conflict.insert_conflict(target_bufnr, start_line, end_line, new_lines, "AI SUGGESTION")
|
||||
|
||||
-- Process conflicts (highlight, keymaps) and show menu
|
||||
conflict.process_and_show_menu(target_bufnr)
|
||||
|
||||
M.mark_applied(patch.id)
|
||||
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({
|
||||
type = "success",
|
||||
message = "Created conflict for review - use co/ct/cb/cn to resolve",
|
||||
})
|
||||
end)
|
||||
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- No suitable range found, fall back to direct apply
|
||||
return M.apply(patch)
|
||||
end
|
||||
|
||||
--- Smart apply - uses conflict mode if enabled, otherwise direct apply
|
||||
---@param patch PatchCandidate
|
||||
---@return boolean success
|
||||
---@return string|nil error
|
||||
function M.smart_apply(patch)
|
||||
if config.use_conflict_mode then
|
||||
return M.apply_with_conflict(patch)
|
||||
else
|
||||
return M.apply(patch)
|
||||
end
|
||||
end
|
||||
|
||||
--- Flush all pending patches using smart apply
|
||||
---@return number applied_count
|
||||
---@return number stale_count
|
||||
---@return number deferred_count
|
||||
function M.flush_pending_smart()
|
||||
local applied = 0
|
||||
local stale = 0
|
||||
local deferred = 0
|
||||
|
||||
for _, p in ipairs(patches) do
|
||||
if p.status == "pending" then
|
||||
local success, err = M.smart_apply(p)
|
||||
if success then
|
||||
applied = applied + 1
|
||||
elseif err == "user_typing" then
|
||||
deferred = deferred + 1
|
||||
else
|
||||
stale = stale + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return applied, stale, deferred
|
||||
end
|
||||
|
||||
return M
|
||||
|
||||
155
lua/codetyper/agent/resume.lua
Normal file
155
lua/codetyper/agent/resume.lua
Normal file
@@ -0,0 +1,155 @@
|
||||
---@mod codetyper.agent.resume Resume context for agent sessions
|
||||
---
|
||||
--- Saves and loads agent state to allow continuing long-running tasks.
|
||||
|
||||
local M = {}
|
||||
|
||||
local utils = require("codetyper.utils")
|
||||
|
||||
--- Get the resume context directory
|
||||
---@return string|nil
|
||||
local function get_resume_dir()
|
||||
local root = utils.get_project_root() or vim.fn.getcwd()
|
||||
return root .. "/.coder/tmp"
|
||||
end
|
||||
|
||||
--- Get the resume context file path
|
||||
---@return string|nil
|
||||
local function get_resume_path()
|
||||
local dir = get_resume_dir()
|
||||
if not dir then
|
||||
return nil
|
||||
end
|
||||
return dir .. "/agent_resume.json"
|
||||
end
|
||||
|
||||
--- Ensure the resume directory exists
|
||||
---@return boolean
|
||||
local function ensure_resume_dir()
|
||||
local dir = get_resume_dir()
|
||||
if not dir then
|
||||
return false
|
||||
end
|
||||
return utils.ensure_dir(dir)
|
||||
end
|
||||
|
||||
---@class ResumeContext
|
||||
---@field conversation table[] Message history
|
||||
---@field pending_tool_results table[] Pending results
|
||||
---@field iteration number Current iteration count
|
||||
---@field original_prompt string Original user prompt
|
||||
---@field timestamp number When saved
|
||||
---@field project_root string Project root path
|
||||
|
||||
--- Save the current agent state for resuming later
|
||||
---@param conversation table[] Conversation history
|
||||
---@param pending_results table[] Pending tool results
|
||||
---@param iteration number Current iteration
|
||||
---@param original_prompt string Original prompt
|
||||
---@return boolean Success
|
||||
function M.save(conversation, pending_results, iteration, original_prompt)
|
||||
if not ensure_resume_dir() then
|
||||
return false
|
||||
end
|
||||
|
||||
local path = get_resume_path()
|
||||
if not path then
|
||||
return false
|
||||
end
|
||||
|
||||
local context = {
|
||||
conversation = conversation,
|
||||
pending_tool_results = pending_results,
|
||||
iteration = iteration,
|
||||
original_prompt = original_prompt,
|
||||
timestamp = os.time(),
|
||||
project_root = utils.get_project_root() or vim.fn.getcwd(),
|
||||
}
|
||||
|
||||
local ok, json = pcall(vim.json.encode, context)
|
||||
if not ok then
|
||||
utils.notify("Failed to encode resume context", vim.log.levels.ERROR)
|
||||
return false
|
||||
end
|
||||
|
||||
local success = utils.write_file(path, json)
|
||||
if success then
|
||||
utils.notify("Agent state saved. Use /continue to resume.", vim.log.levels.INFO)
|
||||
end
|
||||
return success
|
||||
end
|
||||
|
||||
--- Load saved agent state
|
||||
---@return ResumeContext|nil
|
||||
function M.load()
|
||||
local path = get_resume_path()
|
||||
if not path then
|
||||
return nil
|
||||
end
|
||||
|
||||
local content = utils.read_file(path)
|
||||
if not content or content == "" then
|
||||
return nil
|
||||
end
|
||||
|
||||
local ok, context = pcall(vim.json.decode, content)
|
||||
if not ok or not context then
|
||||
return nil
|
||||
end
|
||||
|
||||
return context
|
||||
end
|
||||
|
||||
--- Check if there's a saved resume context
|
||||
---@return boolean
|
||||
function M.has_saved_state()
|
||||
local path = get_resume_path()
|
||||
if not path then
|
||||
return false
|
||||
end
|
||||
return vim.fn.filereadable(path) == 1
|
||||
end
|
||||
|
||||
--- Get info about saved state (for display)
|
||||
---@return table|nil
|
||||
function M.get_info()
|
||||
local context = M.load()
|
||||
if not context then
|
||||
return nil
|
||||
end
|
||||
|
||||
local age_seconds = os.time() - (context.timestamp or 0)
|
||||
local age_str
|
||||
if age_seconds < 60 then
|
||||
age_str = age_seconds .. " seconds ago"
|
||||
elseif age_seconds < 3600 then
|
||||
age_str = math.floor(age_seconds / 60) .. " minutes ago"
|
||||
else
|
||||
age_str = math.floor(age_seconds / 3600) .. " hours ago"
|
||||
end
|
||||
|
||||
return {
|
||||
prompt = context.original_prompt,
|
||||
iteration = context.iteration,
|
||||
messages = #context.conversation,
|
||||
saved_at = age_str,
|
||||
project = context.project_root,
|
||||
}
|
||||
end
|
||||
|
||||
--- Clear saved resume context
|
||||
---@return boolean
|
||||
function M.clear()
|
||||
local path = get_resume_path()
|
||||
if not path then
|
||||
return false
|
||||
end
|
||||
|
||||
if vim.fn.filereadable(path) == 1 then
|
||||
os.remove(path)
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -124,7 +124,7 @@ end
|
||||
--- Retry event with additional context
|
||||
---@param original_event table Original prompt event
|
||||
---@param additional_context string Additional context from user
|
||||
local function retry_with_context(original_event, additional_context)
|
||||
local function retry_with_context(original_event, additional_context, attached_files)
|
||||
-- Create new prompt content combining original + additional
|
||||
local combined_prompt = string.format(
|
||||
"%s\n\nAdditional context:\n%s",
|
||||
@@ -138,6 +138,10 @@ local function retry_with_context(original_event, additional_context)
|
||||
new_event.prompt_content = combined_prompt
|
||||
new_event.attempt_count = 0
|
||||
new_event.status = nil
|
||||
-- Preserve any attached files provided by the context modal
|
||||
if attached_files and #attached_files > 0 then
|
||||
new_event.attached_files = attached_files
|
||||
end
|
||||
|
||||
-- Log the retry
|
||||
pcall(function()
|
||||
@@ -152,6 +156,79 @@ local function retry_with_context(original_event, additional_context)
|
||||
queue.enqueue(new_event)
|
||||
end
|
||||
|
||||
--- Try to parse requested file paths from an LLM response asking for more context
|
||||
---@param response string
|
||||
---@return string[] list of resolved full paths
|
||||
local function parse_requested_files(response)
|
||||
if not response or response == "" then
|
||||
return {}
|
||||
end
|
||||
|
||||
local cwd = vim.fn.getcwd()
|
||||
local results = {}
|
||||
local seen = {}
|
||||
|
||||
-- Heuristics: capture backticked paths, lines starting with - or *, or raw paths with slashes and extension
|
||||
for path in response:gmatch("`([%w%._%-%/]+%.[%w_]+)`") do
|
||||
if not seen[path] then
|
||||
table.insert(results, path)
|
||||
seen[path] = true
|
||||
end
|
||||
end
|
||||
|
||||
for path in response:gmatch("([%w%._%-%/]+%.[%w_]+)") do
|
||||
if not seen[path] then
|
||||
-- Filter out common English words that match the pattern
|
||||
if not path:match("^[Ii]$") and not path:match("^[Tt]his$") then
|
||||
table.insert(results, path)
|
||||
seen[path] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Also capture list items like '- src/foo.lua'
|
||||
for line in response:gmatch("[^\\n]+") do
|
||||
local m = line:match("^%s*[-*]%s*([%w%._%-%/]+%.[%w_]+)%s*$")
|
||||
if m and not seen[m] then
|
||||
table.insert(results, m)
|
||||
seen[m] = true
|
||||
end
|
||||
end
|
||||
|
||||
-- Resolve each candidate to a full path by checking cwd and globbing
|
||||
local resolved = {}
|
||||
for _, p in ipairs(results) do
|
||||
local candidate = p
|
||||
local full = nil
|
||||
|
||||
-- If absolute or already rooted
|
||||
if candidate:sub(1,1) == "/" and vim.fn.filereadable(candidate) == 1 then
|
||||
full = candidate
|
||||
else
|
||||
-- Try relative to cwd
|
||||
local try1 = cwd .. "/" .. candidate
|
||||
if vim.fn.filereadable(try1) == 1 then
|
||||
full = try1
|
||||
else
|
||||
-- Try globbing for filename anywhere in project
|
||||
local basename = candidate
|
||||
-- If candidate contains slashes, try the tail
|
||||
local tail = candidate:match("[^/]+$") or candidate
|
||||
local matches = vim.fn.globpath(cwd, "**/" .. tail, false, true)
|
||||
if matches and #matches > 0 then
|
||||
full = matches[1]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if full and vim.fn.filereadable(full) == 1 then
|
||||
table.insert(resolved, full)
|
||||
end
|
||||
end
|
||||
|
||||
return resolved
|
||||
end
|
||||
|
||||
--- Process worker result and decide next action
|
||||
---@param event table PromptEvent
|
||||
---@param result table WorkerResult
|
||||
@@ -166,7 +243,87 @@ local function handle_worker_result(event, result)
|
||||
})
|
||||
end)
|
||||
|
||||
-- Open the context modal
|
||||
-- Try to auto-attach any files the LLM specifically requested in its response
|
||||
local requested = parse_requested_files(result.response or "")
|
||||
|
||||
-- Detect suggested shell commands the LLM may want executed (e.g., "run ls -la", "please run git status")
|
||||
local function detect_suggested_commands(response)
|
||||
if not response then
|
||||
return {}
|
||||
end
|
||||
local cmds = {}
|
||||
-- capture backticked commands: `ls -la`
|
||||
for c in response:gmatch("`([^`]+)`") do
|
||||
if #c > 1 and not c:match("%-%-help") then
|
||||
table.insert(cmds, { label = c, cmd = c })
|
||||
end
|
||||
end
|
||||
-- capture phrases like: run ls -la or run `ls -la`
|
||||
for m in response:gmatch("[Rr]un%s+([%w%p%s%-_/]+)") do
|
||||
local cand = m:gsub("^%s+",""):gsub("%s+$","")
|
||||
if cand and #cand > 1 then
|
||||
-- ignore long sentences; keep first line or command-like substring
|
||||
local line = cand:match("[^\n]+") or cand
|
||||
line = line:gsub("and then.*","")
|
||||
line = line:gsub("please.*","")
|
||||
if not line:match("%a+%s+files") then
|
||||
table.insert(cmds, { label = line, cmd = line })
|
||||
end
|
||||
end
|
||||
end
|
||||
-- dedupe
|
||||
local seen = {}
|
||||
local out = {}
|
||||
for _, v in ipairs(cmds) do
|
||||
if v.cmd and not seen[v.cmd] then
|
||||
seen[v.cmd] = true
|
||||
table.insert(out, v)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local suggested_cmds = detect_suggested_commands(result.response or "")
|
||||
if suggested_cmds and #suggested_cmds > 0 then
|
||||
-- Open modal and show suggested commands for user approval
|
||||
context_modal.open(result.original_event or event, result.response or "", retry_with_context, suggested_cmds)
|
||||
queue.update_status(event.id, "needs_context", { response = result.response })
|
||||
return
|
||||
end
|
||||
if requested and #requested > 0 then
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
logs.add({ type = "info", message = string.format("Auto-attaching %d requested file(s)", #requested) })
|
||||
end)
|
||||
|
||||
-- Build attached_files entries
|
||||
local attached = event.attached_files or {}
|
||||
for _, full in ipairs(requested) do
|
||||
local ok, content = pcall(function()
|
||||
return table.concat(vim.fn.readfile(full), "\n")
|
||||
end)
|
||||
if ok and content then
|
||||
table.insert(attached, {
|
||||
path = vim.fn.fnamemodify(full, ":~:."),
|
||||
full_path = full,
|
||||
content = content,
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
-- Retry automatically with same prompt but attached files
|
||||
local new_event = vim.deepcopy(result.original_event or event)
|
||||
new_event.id = nil
|
||||
new_event.attached_files = attached
|
||||
new_event.attempt_count = 0
|
||||
new_event.status = nil
|
||||
queue.enqueue(new_event)
|
||||
|
||||
queue.update_status(event.id, "needs_context", { response = result.response })
|
||||
return
|
||||
end
|
||||
|
||||
-- If no files parsed, open modal for manual context entry
|
||||
context_modal.open(result.original_event or event, result.response or "", retry_with_context)
|
||||
|
||||
-- Mark original event as needing context (not failed)
|
||||
@@ -321,7 +478,7 @@ function M.schedule_patch_flush()
|
||||
local safe, reason = M.is_safe_to_inject()
|
||||
if safe then
|
||||
waiting_to_flush = false
|
||||
local applied, stale = patch.flush_pending()
|
||||
local applied, stale = patch.flush_pending_smart()
|
||||
if applied > 0 or stale > 0 then
|
||||
pcall(function()
|
||||
local logs = require("codetyper.agent.logs")
|
||||
@@ -382,7 +539,7 @@ local function setup_autocmds()
|
||||
callback = function()
|
||||
vim.defer_fn(function()
|
||||
if not M.is_completion_visible() then
|
||||
patch.flush_pending()
|
||||
patch.flush_pending_smart()
|
||||
end
|
||||
end, state.config.completion_delay_ms)
|
||||
end,
|
||||
@@ -394,7 +551,7 @@ local function setup_autocmds()
|
||||
group = augroup,
|
||||
callback = function()
|
||||
if not M.is_insert_mode() and not M.is_completion_visible() then
|
||||
patch.flush_pending()
|
||||
patch.flush_pending_smart()
|
||||
end
|
||||
end,
|
||||
desc = "Flush pending patches on CursorHold",
|
||||
@@ -563,7 +720,7 @@ end
|
||||
|
||||
--- Force flush all pending patches (ignores completion check)
|
||||
function M.force_flush()
|
||||
return patch.flush_pending()
|
||||
return patch.flush_pending_smart()
|
||||
end
|
||||
|
||||
--- Update configuration
|
||||
@@ -574,4 +731,33 @@ function M.configure(config)
|
||||
end
|
||||
end
|
||||
|
||||
--- Queue a prompt for processing
|
||||
--- This is a convenience function that creates a proper PromptEvent and enqueues it
|
||||
---@param opts table Prompt options
|
||||
--- - bufnr: number Source buffer number
|
||||
--- - filepath: string Source file path
|
||||
--- - target_path: string Target file for injection (can be same as filepath)
|
||||
--- - prompt_content: string The cleaned prompt text
|
||||
--- - range: {start_line: number, end_line: number} Line range of prompt tag
|
||||
--- - source: string|nil Source identifier (e.g., "transform_command", "autocmd")
|
||||
--- - priority: number|nil Priority (1=high, 2=normal, 3=low) default 2
|
||||
---@return table The enqueued event
|
||||
function M.queue_prompt(opts)
|
||||
-- Build the PromptEvent structure
|
||||
local event = {
|
||||
bufnr = opts.bufnr,
|
||||
filepath = opts.filepath,
|
||||
target_path = opts.target_path or opts.filepath,
|
||||
prompt_content = opts.prompt_content,
|
||||
range = opts.range,
|
||||
priority = opts.priority or 2,
|
||||
source = opts.source or "manual",
|
||||
-- Capture buffer state for staleness detection
|
||||
changedtick = vim.api.nvim_buf_get_changedtick(opts.bufnr),
|
||||
}
|
||||
|
||||
-- Enqueue through the queue module
|
||||
return queue.enqueue(event)
|
||||
end
|
||||
|
||||
return M
|
||||
|
||||
@@ -282,13 +282,21 @@ function M.resolve_scope_heuristic(bufnr, row, col)
|
||||
ending = nil, -- Python uses indentation
|
||||
},
|
||||
javascript = {
|
||||
start = "^%s*function%s+",
|
||||
start_alt = "^%s*const%s+%w+%s*=%s*",
|
||||
start = "^%s*export%s+function%s+",
|
||||
start_alt = "^%s*function%s+",
|
||||
start_alt2 = "^%s*export%s+const%s+%w+%s*=",
|
||||
start_alt3 = "^%s*const%s+%w+%s*=%s*",
|
||||
start_alt4 = "^%s*export%s+async%s+function%s+",
|
||||
start_alt5 = "^%s*async%s+function%s+",
|
||||
ending = "^%s*}%s*$",
|
||||
},
|
||||
typescript = {
|
||||
start = "^%s*function%s+",
|
||||
start_alt = "^%s*const%s+%w+%s*=%s*",
|
||||
start = "^%s*export%s+function%s+",
|
||||
start_alt = "^%s*function%s+",
|
||||
start_alt2 = "^%s*export%s+const%s+%w+%s*=",
|
||||
start_alt3 = "^%s*const%s+%w+%s*=%s*",
|
||||
start_alt4 = "^%s*export%s+async%s+function%s+",
|
||||
start_alt5 = "^%s*async%s+function%s+",
|
||||
ending = "^%s*}%s*$",
|
||||
},
|
||||
}
|
||||
@@ -302,8 +310,13 @@ function M.resolve_scope_heuristic(bufnr, row, col)
|
||||
local start_line = nil
|
||||
for i = row, 1, -1 do
|
||||
local line = lines[i]
|
||||
if line:match(lang_patterns.start) or
|
||||
(lang_patterns.start_alt and line:match(lang_patterns.start_alt)) then
|
||||
-- Check all start patterns
|
||||
if line:match(lang_patterns.start)
|
||||
or (lang_patterns.start_alt and line:match(lang_patterns.start_alt))
|
||||
or (lang_patterns.start_alt2 and line:match(lang_patterns.start_alt2))
|
||||
or (lang_patterns.start_alt3 and line:match(lang_patterns.start_alt3))
|
||||
or (lang_patterns.start_alt4 and line:match(lang_patterns.start_alt4))
|
||||
or (lang_patterns.start_alt5 and line:match(lang_patterns.start_alt5)) then
|
||||
start_line = i
|
||||
break
|
||||
end
|
||||
|
||||
570
lua/codetyper/agent/search_replace.lua
Normal file
570
lua/codetyper/agent/search_replace.lua
Normal file
@@ -0,0 +1,570 @@
|
||||
---@mod codetyper.agent.search_replace Search/Replace editing system
|
||||
---@brief [[
|
||||
--- Implements SEARCH/REPLACE block parsing and fuzzy matching for reliable code edits.
|
||||
--- Parses and applies SEARCH/REPLACE blocks from LLM responses.
|
||||
---@brief ]]
|
||||
|
||||
local M = {}
|
||||
|
||||
---@class SearchReplaceBlock
|
||||
---@field search string The text to search for
|
||||
---@field replace string The text to replace with
|
||||
---@field file_path string|nil Optional file path for multi-file edits
|
||||
|
||||
---@class MatchResult
|
||||
---@field start_line number 1-indexed start line
|
||||
---@field end_line number 1-indexed end line
|
||||
---@field start_col number 1-indexed start column (for partial line matches)
|
||||
---@field end_col number 1-indexed end column
|
||||
---@field strategy string Which matching strategy succeeded
|
||||
---@field confidence number Match confidence (0.0-1.0)
|
||||
|
||||
--- Parse SEARCH/REPLACE blocks from LLM response
|
||||
--- Supports multiple formats:
|
||||
--- Format 1 (dash style):
|
||||
--- ------- SEARCH
|
||||
--- old code
|
||||
--- =======
|
||||
--- new code
|
||||
--- +++++++ REPLACE
|
||||
---
|
||||
--- Format 2 (claude style):
|
||||
--- <<<<<<< SEARCH
|
||||
--- old code
|
||||
--- =======
|
||||
--- new code
|
||||
--- >>>>>>> REPLACE
|
||||
---
|
||||
--- Format 3 (simple):
|
||||
--- [SEARCH]
|
||||
--- old code
|
||||
--- [REPLACE]
|
||||
--- new code
|
||||
--- [END]
|
||||
---
|
||||
---@param response string LLM response text
|
||||
---@return SearchReplaceBlock[]
|
||||
function M.parse_blocks(response)
|
||||
local blocks = {}
|
||||
|
||||
-- Try dash-style format: ------- SEARCH ... ======= ... +++++++ REPLACE
|
||||
for search, replace in response:gmatch("%-%-%-%-%-%-%-?%s*SEARCH%s*\n(.-)\n=======%s*\n(.-)\n%+%+%+%+%+%+%+?%s*REPLACE") do
|
||||
table.insert(blocks, { search = search, replace = replace })
|
||||
end
|
||||
|
||||
if #blocks > 0 then
|
||||
return blocks
|
||||
end
|
||||
|
||||
-- Try claude-style format: <<<<<<< SEARCH ... ======= ... >>>>>>> REPLACE
|
||||
for search, replace in response:gmatch("<<<<<<<[%s]*SEARCH%s*\n(.-)\n=======%s*\n(.-)\n>>>>>>>[%s]*REPLACE") do
|
||||
table.insert(blocks, { search = search, replace = replace })
|
||||
end
|
||||
|
||||
if #blocks > 0 then
|
||||
return blocks
|
||||
end
|
||||
|
||||
-- Try simple format: [SEARCH] ... [REPLACE] ... [END]
|
||||
for search, replace in response:gmatch("%[SEARCH%]%s*\n(.-)\n%[REPLACE%]%s*\n(.-)\n%[END%]") do
|
||||
table.insert(blocks, { search = search, replace = replace })
|
||||
end
|
||||
|
||||
if #blocks > 0 then
|
||||
return blocks
|
||||
end
|
||||
|
||||
-- Try markdown diff format: ```diff ... ```
|
||||
local diff_block = response:match("```diff\n(.-)\n```")
|
||||
if diff_block then
|
||||
local old_lines = {}
|
||||
local new_lines = {}
|
||||
for line in diff_block:gmatch("[^\n]+") do
|
||||
if line:match("^%-[^%-]") then
|
||||
-- Removed line (starts with single -)
|
||||
table.insert(old_lines, line:sub(2))
|
||||
elseif line:match("^%+[^%+]") then
|
||||
-- Added line (starts with single +)
|
||||
table.insert(new_lines, line:sub(2))
|
||||
elseif line:match("^%s") or line:match("^[^%-%+@]") then
|
||||
-- Context line
|
||||
table.insert(old_lines, line:match("^%s?(.*)"))
|
||||
table.insert(new_lines, line:match("^%s?(.*)"))
|
||||
end
|
||||
end
|
||||
if #old_lines > 0 or #new_lines > 0 then
|
||||
table.insert(blocks, {
|
||||
search = table.concat(old_lines, "\n"),
|
||||
replace = table.concat(new_lines, "\n"),
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
return blocks
|
||||
end
|
||||
|
||||
--- Get indentation of a line
|
||||
---@param line string
|
||||
---@return string
|
||||
local function get_indentation(line)
|
||||
if not line then
|
||||
return ""
|
||||
end
|
||||
return line:match("^(%s*)") or ""
|
||||
end
|
||||
|
||||
--- Normalize whitespace in a string (collapse multiple spaces to one)
|
||||
---@param str string
|
||||
---@return string
|
||||
local function normalize_whitespace(str)
|
||||
-- Wrap in parentheses to only return first value (gsub returns string + count)
|
||||
return (str:gsub("%s+", " "):gsub("^%s*", ""):gsub("%s*$", ""))
|
||||
end
|
||||
|
||||
--- Trim trailing whitespace from each line
|
||||
---@param str string
|
||||
---@return string
|
||||
local function trim_lines(str)
|
||||
local lines = vim.split(str, "\n", { plain = true })
|
||||
for i, line in ipairs(lines) do
|
||||
-- Wrap in parentheses to only get string, not count
|
||||
lines[i] = (line:gsub("%s+$", ""))
|
||||
end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
--- Calculate Levenshtein distance between two strings
|
||||
---@param s1 string
|
||||
---@param s2 string
|
||||
---@return number
|
||||
local function levenshtein(s1, s2)
|
||||
local len1, len2 = #s1, #s2
|
||||
if len1 == 0 then
|
||||
return len2
|
||||
end
|
||||
if len2 == 0 then
|
||||
return len1
|
||||
end
|
||||
|
||||
local matrix = {}
|
||||
for i = 0, len1 do
|
||||
matrix[i] = { [0] = i }
|
||||
end
|
||||
for j = 0, len2 do
|
||||
matrix[0][j] = j
|
||||
end
|
||||
|
||||
for i = 1, len1 do
|
||||
for j = 1, len2 do
|
||||
local cost = (s1:sub(i, i) == s2:sub(j, j)) and 0 or 1
|
||||
matrix[i][j] = math.min(
|
||||
matrix[i - 1][j] + 1,
|
||||
matrix[i][j - 1] + 1,
|
||||
matrix[i - 1][j - 1] + cost
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
return matrix[len1][len2]
|
||||
end
|
||||
|
||||
--- Calculate similarity ratio (0.0-1.0) between two strings
|
||||
---@param s1 string
|
||||
---@param s2 string
|
||||
---@return number
|
||||
local function similarity(s1, s2)
|
||||
if s1 == s2 then
|
||||
return 1.0
|
||||
end
|
||||
local max_len = math.max(#s1, #s2)
|
||||
if max_len == 0 then
|
||||
return 1.0
|
||||
end
|
||||
local distance = levenshtein(s1, s2)
|
||||
return 1.0 - (distance / max_len)
|
||||
end
|
||||
|
||||
--- Strategy 1: Exact match
|
||||
---@param content_lines string[]
|
||||
---@param search_lines string[]
|
||||
---@return MatchResult|nil
|
||||
local function exact_match(content_lines, search_lines)
|
||||
if #search_lines == 0 then
|
||||
return nil
|
||||
end
|
||||
|
||||
for i = 1, #content_lines - #search_lines + 1 do
|
||||
local match = true
|
||||
for j = 1, #search_lines do
|
||||
if content_lines[i + j - 1] ~= search_lines[j] then
|
||||
match = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if match then
|
||||
return {
|
||||
start_line = i,
|
||||
end_line = i + #search_lines - 1,
|
||||
start_col = 1,
|
||||
end_col = #content_lines[i + #search_lines - 1],
|
||||
strategy = "exact",
|
||||
confidence = 1.0,
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Strategy 2: Line-trimmed match (ignore trailing whitespace)
|
||||
---@param content_lines string[]
|
||||
---@param search_lines string[]
|
||||
---@return MatchResult|nil
|
||||
local function line_trimmed_match(content_lines, search_lines)
|
||||
if #search_lines == 0 then
|
||||
return nil
|
||||
end
|
||||
|
||||
local trimmed_search = {}
|
||||
for _, line in ipairs(search_lines) do
|
||||
table.insert(trimmed_search, (line:gsub("%s+$", "")))
|
||||
end
|
||||
|
||||
for i = 1, #content_lines - #search_lines + 1 do
|
||||
local match = true
|
||||
for j = 1, #search_lines do
|
||||
local trimmed_content = content_lines[i + j - 1]:gsub("%s+$", "")
|
||||
if trimmed_content ~= trimmed_search[j] then
|
||||
match = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if match then
|
||||
return {
|
||||
start_line = i,
|
||||
end_line = i + #search_lines - 1,
|
||||
start_col = 1,
|
||||
end_col = #content_lines[i + #search_lines - 1],
|
||||
strategy = "line_trimmed",
|
||||
confidence = 0.95,
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Strategy 3: Indentation-flexible match (normalize indentation)
|
||||
---@param content_lines string[]
|
||||
---@param search_lines string[]
|
||||
---@return MatchResult|nil
|
||||
local function indentation_flexible_match(content_lines, search_lines)
|
||||
if #search_lines == 0 then
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Get base indentation from search (first non-empty line)
|
||||
local search_indent = ""
|
||||
for _, line in ipairs(search_lines) do
|
||||
if line:match("%S") then
|
||||
search_indent = get_indentation(line)
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
-- Strip common indentation from search
|
||||
local stripped_search = {}
|
||||
for _, line in ipairs(search_lines) do
|
||||
if line:match("^" .. vim.pesc(search_indent)) then
|
||||
table.insert(stripped_search, line:sub(#search_indent + 1))
|
||||
else
|
||||
table.insert(stripped_search, line)
|
||||
end
|
||||
end
|
||||
|
||||
for i = 1, #content_lines - #search_lines + 1 do
|
||||
-- Get content indentation at this position
|
||||
local content_indent = ""
|
||||
for j = 0, #search_lines - 1 do
|
||||
local line = content_lines[i + j]
|
||||
if line:match("%S") then
|
||||
content_indent = get_indentation(line)
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
local match = true
|
||||
for j = 1, #search_lines do
|
||||
local content_line = content_lines[i + j - 1]
|
||||
local expected = content_indent .. stripped_search[j]
|
||||
|
||||
-- Compare with normalized indentation
|
||||
if content_line:gsub("%s+$", "") ~= expected:gsub("%s+$", "") then
|
||||
match = false
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
if match then
|
||||
return {
|
||||
start_line = i,
|
||||
end_line = i + #search_lines - 1,
|
||||
start_col = 1,
|
||||
end_col = #content_lines[i + #search_lines - 1],
|
||||
strategy = "indentation_flexible",
|
||||
confidence = 0.9,
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Strategy 4: Block anchor match (match first/last lines, fuzzy middle)
|
||||
---@param content_lines string[]
|
||||
---@param search_lines string[]
|
||||
---@return MatchResult|nil
|
||||
local function block_anchor_match(content_lines, search_lines)
|
||||
if #search_lines < 2 then
|
||||
return nil
|
||||
end
|
||||
|
||||
local first_search = search_lines[1]:gsub("%s+$", "")
|
||||
local last_search = search_lines[#search_lines]:gsub("%s+$", "")
|
||||
|
||||
-- Find potential start positions
|
||||
local candidates = {}
|
||||
for i = 1, #content_lines - #search_lines + 1 do
|
||||
local first_content = content_lines[i]:gsub("%s+$", "")
|
||||
if similarity(first_content, first_search) > 0.8 then
|
||||
-- Check if last line also matches
|
||||
local last_idx = i + #search_lines - 1
|
||||
if last_idx <= #content_lines then
|
||||
local last_content = content_lines[last_idx]:gsub("%s+$", "")
|
||||
if similarity(last_content, last_search) > 0.8 then
|
||||
-- Calculate overall similarity
|
||||
local total_sim = 0
|
||||
for j = 1, #search_lines do
|
||||
local c = content_lines[i + j - 1]:gsub("%s+$", "")
|
||||
local s = search_lines[j]:gsub("%s+$", "")
|
||||
total_sim = total_sim + similarity(c, s)
|
||||
end
|
||||
local avg_sim = total_sim / #search_lines
|
||||
if avg_sim > 0.7 then
|
||||
table.insert(candidates, { start = i, similarity = avg_sim })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Return best match
|
||||
if #candidates > 0 then
|
||||
table.sort(candidates, function(a, b)
|
||||
return a.similarity > b.similarity
|
||||
end)
|
||||
local best = candidates[1]
|
||||
return {
|
||||
start_line = best.start,
|
||||
end_line = best.start + #search_lines - 1,
|
||||
start_col = 1,
|
||||
end_col = #content_lines[best.start + #search_lines - 1],
|
||||
strategy = "block_anchor",
|
||||
confidence = best.similarity * 0.85,
|
||||
}
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Strategy 5: Whitespace-normalized match
|
||||
---@param content_lines string[]
|
||||
---@param search_lines string[]
|
||||
---@return MatchResult|nil
|
||||
local function whitespace_normalized_match(content_lines, search_lines)
|
||||
if #search_lines == 0 then
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Normalize search lines
|
||||
local norm_search = {}
|
||||
for _, line in ipairs(search_lines) do
|
||||
table.insert(norm_search, normalize_whitespace(line))
|
||||
end
|
||||
|
||||
for i = 1, #content_lines - #search_lines + 1 do
|
||||
local match = true
|
||||
for j = 1, #search_lines do
|
||||
local norm_content = normalize_whitespace(content_lines[i + j - 1])
|
||||
if norm_content ~= norm_search[j] then
|
||||
match = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if match then
|
||||
return {
|
||||
start_line = i,
|
||||
end_line = i + #search_lines - 1,
|
||||
start_col = 1,
|
||||
end_col = #content_lines[i + #search_lines - 1],
|
||||
strategy = "whitespace_normalized",
|
||||
confidence = 0.8,
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Find the best match for search text in content
|
||||
---@param content string File content
|
||||
---@param search string Text to search for
|
||||
---@return MatchResult|nil
|
||||
function M.find_match(content, search)
|
||||
local content_lines = vim.split(content, "\n", { plain = true })
|
||||
local search_lines = vim.split(search, "\n", { plain = true })
|
||||
|
||||
-- Remove trailing empty lines from search
|
||||
while #search_lines > 0 and search_lines[#search_lines]:match("^%s*$") do
|
||||
table.remove(search_lines)
|
||||
end
|
||||
|
||||
if #search_lines == 0 then
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Try strategies in order of strictness
|
||||
local strategies = {
|
||||
exact_match,
|
||||
line_trimmed_match,
|
||||
indentation_flexible_match,
|
||||
block_anchor_match,
|
||||
whitespace_normalized_match,
|
||||
}
|
||||
|
||||
for _, strategy in ipairs(strategies) do
|
||||
local result = strategy(content_lines, search_lines)
|
||||
if result then
|
||||
return result
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Apply a single SEARCH/REPLACE block to content
|
||||
---@param content string Original file content
|
||||
---@param block SearchReplaceBlock
|
||||
---@return string|nil new_content
|
||||
---@return MatchResult|nil match_info
|
||||
---@return string|nil error
|
||||
function M.apply_block(content, block)
|
||||
local match = M.find_match(content, block.search)
|
||||
if not match then
|
||||
return nil, nil, "Could not find search text in file"
|
||||
end
|
||||
|
||||
local content_lines = vim.split(content, "\n", { plain = true })
|
||||
local replace_lines = vim.split(block.replace, "\n", { plain = true })
|
||||
|
||||
-- Adjust indentation of replacement to match original
|
||||
local original_indent = get_indentation(content_lines[match.start_line])
|
||||
local replace_indent = ""
|
||||
for _, line in ipairs(replace_lines) do
|
||||
if line:match("%S") then
|
||||
replace_indent = get_indentation(line)
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
-- Apply indentation adjustment
|
||||
local adjusted_replace = {}
|
||||
for _, line in ipairs(replace_lines) do
|
||||
if line:match("^" .. vim.pesc(replace_indent)) then
|
||||
table.insert(adjusted_replace, original_indent .. line:sub(#replace_indent + 1))
|
||||
elseif line:match("^%s*$") then
|
||||
table.insert(adjusted_replace, "")
|
||||
else
|
||||
table.insert(adjusted_replace, original_indent .. line)
|
||||
end
|
||||
end
|
||||
|
||||
-- Build new content
|
||||
local new_lines = {}
|
||||
for i = 1, match.start_line - 1 do
|
||||
table.insert(new_lines, content_lines[i])
|
||||
end
|
||||
for _, line in ipairs(adjusted_replace) do
|
||||
table.insert(new_lines, line)
|
||||
end
|
||||
for i = match.end_line + 1, #content_lines do
|
||||
table.insert(new_lines, content_lines[i])
|
||||
end
|
||||
|
||||
return table.concat(new_lines, "\n"), match, nil
|
||||
end
|
||||
|
||||
--- Apply multiple SEARCH/REPLACE blocks to content
|
||||
---@param content string Original file content
|
||||
---@param blocks SearchReplaceBlock[]
|
||||
---@return string new_content
|
||||
---@return table results Array of {success: boolean, match: MatchResult|nil, error: string|nil}
|
||||
function M.apply_blocks(content, blocks)
|
||||
local current_content = content
|
||||
local results = {}
|
||||
|
||||
for _, block in ipairs(blocks) do
|
||||
local new_content, match, err = M.apply_block(current_content, block)
|
||||
if new_content then
|
||||
current_content = new_content
|
||||
table.insert(results, { success = true, match = match })
|
||||
else
|
||||
table.insert(results, { success = false, error = err })
|
||||
end
|
||||
end
|
||||
|
||||
return current_content, results
|
||||
end
|
||||
|
||||
--- Apply SEARCH/REPLACE blocks to a buffer
|
||||
---@param bufnr number Buffer number
|
||||
---@param blocks SearchReplaceBlock[]
|
||||
---@return boolean success
|
||||
---@return string|nil error
|
||||
function M.apply_to_buffer(bufnr, blocks)
|
||||
if not vim.api.nvim_buf_is_valid(bufnr) then
|
||||
return false, "Invalid buffer"
|
||||
end
|
||||
|
||||
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
|
||||
local content = table.concat(lines, "\n")
|
||||
|
||||
local new_content, results = M.apply_blocks(content, blocks)
|
||||
|
||||
-- Check for any failures
|
||||
local failures = {}
|
||||
for i, result in ipairs(results) do
|
||||
if not result.success then
|
||||
table.insert(failures, string.format("Block %d: %s", i, result.error or "unknown error"))
|
||||
end
|
||||
end
|
||||
|
||||
if #failures > 0 then
|
||||
return false, table.concat(failures, "; ")
|
||||
end
|
||||
|
||||
-- Apply to buffer
|
||||
local new_lines = vim.split(new_content, "\n", { plain = true })
|
||||
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, new_lines)
|
||||
|
||||
return true, nil
|
||||
end
|
||||
|
||||
--- Check if response contains SEARCH/REPLACE blocks
|
||||
---@param response string
|
||||
---@return boolean
|
||||
function M.has_blocks(response)
|
||||
return #M.parse_blocks(response) > 0
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -219,4 +219,11 @@ function M.get_tool_names()
|
||||
return names
|
||||
end
|
||||
|
||||
--- Optional setup function for future extensibility
|
||||
---@param opts table|nil Configuration options
|
||||
function M.setup(opts)
|
||||
-- Currently a no-op. Plugins or tests may call setup(); keep for compatibility.
|
||||
end
|
||||
|
||||
return M
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
---@brief [[
|
||||
--- Tool for making targeted edits to files using search/replace.
|
||||
--- Implements multiple fallback strategies for robust matching.
|
||||
--- Inspired by opencode's 9-strategy approach.
|
||||
--- Multi-strategy approach for reliable editing.
|
||||
---@brief ]]
|
||||
|
||||
local Base = require("codetyper.agent.tools.base")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---@mod codetyper.agent.tools Tool registry and orchestration
|
||||
---@brief [[
|
||||
--- Registry for LLM tools with execution and schema generation.
|
||||
--- Inspired by avante.nvim's tool system.
|
||||
--- Tool system for agent mode.
|
||||
---@brief ]]
|
||||
|
||||
local M = {}
|
||||
|
||||
@@ -29,6 +29,7 @@ local state = {
|
||||
is_open = false,
|
||||
log_listener_id = nil,
|
||||
referenced_files = {},
|
||||
selection_context = nil, -- Visual selection passed when opening
|
||||
}
|
||||
|
||||
--- Namespace for highlights
|
||||
@@ -121,7 +122,9 @@ local function add_log_entry(entry)
|
||||
local lines = vim.api.nvim_buf_get_lines(state.logs_buf, 0, -1, false)
|
||||
local line_num = #lines
|
||||
|
||||
vim.api.nvim_buf_set_lines(state.logs_buf, -1, -1, false, { formatted })
|
||||
-- Split formatted log into individual lines to avoid passing newline-containing items
|
||||
local formatted_lines = vim.split(formatted, "\n")
|
||||
vim.api.nvim_buf_set_lines(state.logs_buf, -1, -1, false, formatted_lines)
|
||||
|
||||
-- Apply highlighting based on level
|
||||
local hl_map = {
|
||||
@@ -234,8 +237,16 @@ local function create_callbacks()
|
||||
|
||||
on_complete = function()
|
||||
vim.schedule(function()
|
||||
add_message("system", "Done.", "DiagnosticHint")
|
||||
logs.info("Agent loop completed")
|
||||
local changes_count = agent.get_changes_count()
|
||||
if changes_count > 0 then
|
||||
add_message("system",
|
||||
string.format("Done. %d file(s) changed. Press <leader>d to review changes.", changes_count),
|
||||
"DiagnosticHint")
|
||||
logs.info(string.format("Agent completed with %d change(s)", changes_count))
|
||||
else
|
||||
add_message("system", "Done.", "DiagnosticHint")
|
||||
logs.info("Agent loop completed")
|
||||
end
|
||||
M.focus_input()
|
||||
end)
|
||||
end,
|
||||
@@ -303,12 +314,15 @@ local function submit_input()
|
||||
"╔═══════════════════════════════════════════════════════════════╗",
|
||||
"║ [AGENT MODE] Can read/write files ║",
|
||||
"╠═══════════════════════════════════════════════════════════════╣",
|
||||
"║ @ attach file | C-f current file | :CoderType switch mode ║",
|
||||
"║ @ attach | C-f current file | <leader>d review changes ║",
|
||||
"╚═══════════════════════════════════════════════════════════════╝",
|
||||
"",
|
||||
})
|
||||
vim.bo[state.chat_buf].modifiable = false
|
||||
end
|
||||
-- Also clear collected diffs
|
||||
local diff_review = require("codetyper.agent.diff_review")
|
||||
diff_review.clear()
|
||||
return
|
||||
end
|
||||
|
||||
@@ -317,6 +331,30 @@ local function submit_input()
|
||||
return
|
||||
end
|
||||
|
||||
if input == "/continue" then
|
||||
if agent.is_running() then
|
||||
add_message("system", "Agent is already running. Use /stop first.")
|
||||
return
|
||||
end
|
||||
|
||||
if not agent.has_saved_session() then
|
||||
add_message("system", "No saved session to continue.")
|
||||
return
|
||||
end
|
||||
|
||||
local info = agent.get_saved_session_info()
|
||||
if info then
|
||||
add_message("system", string.format("Resuming session from %s...", info.saved_at))
|
||||
logs.info(string.format("Resuming: %d messages, iteration %d", info.messages, info.iteration))
|
||||
end
|
||||
|
||||
local success = agent.continue_session(create_callbacks())
|
||||
if not success then
|
||||
add_message("system", "Failed to resume session.")
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
-- Build file context
|
||||
local file_context = build_file_context()
|
||||
local file_count = vim.tbl_count(state.referenced_files)
|
||||
@@ -359,8 +397,15 @@ local function submit_input()
|
||||
|
||||
-- Append file context to input
|
||||
local full_input = input
|
||||
|
||||
-- Add selection context if present
|
||||
local selection_ctx = M.get_selection_context()
|
||||
if selection_ctx then
|
||||
full_input = full_input .. "\n\n" .. selection_ctx
|
||||
end
|
||||
|
||||
if file_context ~= "" then
|
||||
full_input = input .. "\n\nATTACHED FILES:" .. file_context
|
||||
full_input = full_input .. "\n\nATTACHED FILES:" .. file_context
|
||||
end
|
||||
|
||||
logs.thinking("Starting...")
|
||||
@@ -494,12 +539,20 @@ local function update_logs_title()
|
||||
end
|
||||
|
||||
--- Open the agent UI
|
||||
function M.open()
|
||||
---@param selection table|nil Visual selection context {text, start_line, end_line, filepath, filename, language}
|
||||
function M.open(selection)
|
||||
if state.is_open then
|
||||
-- If already open and new selection provided, add it as context
|
||||
if selection and selection.text and selection.text ~= "" then
|
||||
M.add_selection_context(selection)
|
||||
end
|
||||
M.focus_input()
|
||||
return
|
||||
end
|
||||
|
||||
-- Store selection context
|
||||
state.selection_context = selection
|
||||
|
||||
-- Clear previous state
|
||||
logs.clear()
|
||||
state.referenced_files = {}
|
||||
@@ -574,7 +627,7 @@ function M.open()
|
||||
"╔═══════════════════════════════════════════════════════════════╗",
|
||||
"║ [AGENT MODE] Can read/write files ║",
|
||||
"╠═══════════════════════════════════════════════════════════════╣",
|
||||
"║ @ attach file | C-f current file | :CoderType switch mode ║",
|
||||
"║ @ attach | C-f current file | <leader>d review changes ║",
|
||||
"╚═══════════════════════════════════════════════════════════════╝",
|
||||
"",
|
||||
})
|
||||
@@ -607,6 +660,7 @@ function M.open()
|
||||
vim.keymap.set("n", "<Tab>", M.focus_chat, input_opts)
|
||||
vim.keymap.set("n", "q", M.close, input_opts)
|
||||
vim.keymap.set("n", "<Esc>", M.close, input_opts)
|
||||
vim.keymap.set("n", "<leader>d", M.show_diff_review, input_opts)
|
||||
|
||||
-- Set up keymaps for chat buffer
|
||||
local chat_opts = { buffer = state.chat_buf, noremap = true, silent = true }
|
||||
@@ -617,6 +671,7 @@ function M.open()
|
||||
vim.keymap.set("n", "<C-f>", M.include_current_file, chat_opts)
|
||||
vim.keymap.set("n", "<Tab>", M.focus_logs, chat_opts)
|
||||
vim.keymap.set("n", "q", M.close, chat_opts)
|
||||
vim.keymap.set("n", "<leader>d", M.show_diff_review, chat_opts)
|
||||
|
||||
-- Set up keymaps for logs buffer
|
||||
local logs_opts = { buffer = state.logs_buf, noremap = true, silent = true }
|
||||
@@ -650,6 +705,26 @@ function M.open()
|
||||
M.focus_input()
|
||||
logs.info("Agent ready")
|
||||
|
||||
-- Check for saved session and notify user
|
||||
if agent.has_saved_session() then
|
||||
vim.schedule(function()
|
||||
local info = agent.get_saved_session_info()
|
||||
if info then
|
||||
add_message("system",
|
||||
string.format("Saved session available (%s). Type /continue to resume.", info.saved_at),
|
||||
"DiagnosticHint")
|
||||
logs.info("Saved session found: " .. (info.prompt or ""):sub(1, 30) .. "...")
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
-- If we have a selection, show it as context
|
||||
if selection and selection.text and selection.text ~= "" then
|
||||
vim.schedule(function()
|
||||
M.add_selection_context(selection)
|
||||
end)
|
||||
end
|
||||
|
||||
-- Log provider info
|
||||
local ok, codetyper = pcall(require, "codetyper")
|
||||
if ok then
|
||||
@@ -732,4 +807,101 @@ function M.is_open()
|
||||
return state.is_open
|
||||
end
|
||||
|
||||
--- Show the diff review for all changes made in this session
|
||||
function M.show_diff_review()
|
||||
local changes_count = agent.get_changes_count()
|
||||
if changes_count == 0 then
|
||||
utils.notify("No changes to review", vim.log.levels.INFO)
|
||||
return
|
||||
end
|
||||
agent.show_diff_review()
|
||||
end
|
||||
|
||||
--- Add visual selection as context in the chat
|
||||
---@param selection table Selection info {text, start_line, end_line, filepath, filename, language}
|
||||
function M.add_selection_context(selection)
|
||||
if not state.chat_buf or not vim.api.nvim_buf_is_valid(state.chat_buf) then
|
||||
return
|
||||
end
|
||||
|
||||
state.selection_context = selection
|
||||
|
||||
vim.bo[state.chat_buf].modifiable = true
|
||||
|
||||
local lines = vim.api.nvim_buf_get_lines(state.chat_buf, 0, -1, false)
|
||||
|
||||
-- Format the selection display
|
||||
local location = ""
|
||||
if selection.filename then
|
||||
location = selection.filename
|
||||
if selection.start_line then
|
||||
location = location .. ":" .. selection.start_line
|
||||
if selection.end_line and selection.end_line ~= selection.start_line then
|
||||
location = location .. "-" .. selection.end_line
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local new_lines = {
|
||||
"",
|
||||
"┌─ Selected Code ─────────────────────",
|
||||
"│ " .. location,
|
||||
"│",
|
||||
}
|
||||
|
||||
-- Add the selected code
|
||||
for _, line in ipairs(vim.split(selection.text, "\n")) do
|
||||
table.insert(new_lines, "│ " .. line)
|
||||
end
|
||||
|
||||
table.insert(new_lines, "│")
|
||||
table.insert(new_lines, "└──────────────────────────────────────")
|
||||
table.insert(new_lines, "")
|
||||
table.insert(new_lines, "Describe what you'd like to do with this code.")
|
||||
|
||||
for _, line in ipairs(new_lines) do
|
||||
table.insert(lines, line)
|
||||
end
|
||||
|
||||
vim.api.nvim_buf_set_lines(state.chat_buf, 0, -1, false, lines)
|
||||
vim.bo[state.chat_buf].modifiable = false
|
||||
|
||||
-- Scroll to bottom
|
||||
if state.chat_win and vim.api.nvim_win_is_valid(state.chat_win) then
|
||||
local line_count = vim.api.nvim_buf_line_count(state.chat_buf)
|
||||
vim.api.nvim_win_set_cursor(state.chat_win, { line_count, 0 })
|
||||
end
|
||||
|
||||
-- Also add the file to referenced_files for context
|
||||
if selection.filepath and selection.filepath ~= "" then
|
||||
state.referenced_files[selection.filename or "selection"] = selection.filepath
|
||||
end
|
||||
|
||||
logs.info("Selection added: " .. location)
|
||||
end
|
||||
|
||||
--- Get selection context for agent prompt
|
||||
---@return string|nil Selection context string
|
||||
function M.get_selection_context()
|
||||
if not state.selection_context or not state.selection_context.text then
|
||||
return nil
|
||||
end
|
||||
|
||||
local sel = state.selection_context
|
||||
local location = sel.filename or "unknown"
|
||||
if sel.start_line then
|
||||
location = location .. ":" .. sel.start_line
|
||||
if sel.end_line and sel.end_line ~= sel.start_line then
|
||||
location = location .. "-" .. sel.end_line
|
||||
end
|
||||
end
|
||||
|
||||
return string.format(
|
||||
"SELECTED CODE (%s):\n```%s\n%s\n```",
|
||||
location,
|
||||
sel.language or "",
|
||||
sel.text
|
||||
)
|
||||
end
|
||||
|
||||
return M
|
||||
|
||||
@@ -83,6 +83,19 @@ local function needs_more_context(response)
|
||||
return false
|
||||
end
|
||||
|
||||
--- Check if response contains SEARCH/REPLACE blocks
|
||||
---@param response string
|
||||
---@return boolean
|
||||
local function has_search_replace_blocks(response)
|
||||
if not response then
|
||||
return false
|
||||
end
|
||||
-- Check for any of the supported SEARCH/REPLACE formats
|
||||
return response:match("<<<<<<<%s*SEARCH") ~= nil
|
||||
or response:match("%-%-%-%-%-%-%-?%s*SEARCH") ~= nil
|
||||
or response:match("%[SEARCH%]") ~= nil
|
||||
end
|
||||
|
||||
--- Clean LLM response to extract only code
|
||||
---@param response string Raw LLM response
|
||||
---@param filetype string|nil File type for language detection
|
||||
@@ -107,6 +120,13 @@ local function clean_response(response, filetype)
|
||||
-- Use [%s%S] to match any character including newlines (Lua's . doesn't match newlines)
|
||||
cleaned = cleaned:gsub("/@[%s%S]-@/", "")
|
||||
|
||||
-- IMPORTANT: If response contains SEARCH/REPLACE blocks, preserve them!
|
||||
-- Don't extract from markdown or remove "explanations" that are actually part of the format
|
||||
if has_search_replace_blocks(cleaned) then
|
||||
-- Just trim whitespace and return - the blocks will be parsed by search_replace module
|
||||
return cleaned:match("^%s*(.-)%s*$") or cleaned
|
||||
end
|
||||
|
||||
-- Try to extract code from markdown code blocks
|
||||
-- Match ```language\n...\n``` or just ```\n...\n```
|
||||
local code_block = cleaned:match("```[%w]*\n(.-)\n```")
|
||||
@@ -352,6 +372,45 @@ local function format_indexed_context(indexed_context)
|
||||
return "\n\n--- Project Context ---\n" .. table.concat(parts, "\n")
|
||||
end
|
||||
|
||||
--- Check if this is an inline prompt (tags in target file, not a coder file)
|
||||
---@param event table
|
||||
---@return boolean
|
||||
local function is_inline_prompt(event)
|
||||
-- Inline prompts have a range with start_line/end_line from tag detection
|
||||
-- and the source file is the same as target (not a .coder. file)
|
||||
if not event.range or not event.range.start_line then
|
||||
return false
|
||||
end
|
||||
-- Check if source path (if any) equals target, or if target has no .coder. in it
|
||||
local target = event.target_path or ""
|
||||
if target:match("%.coder%.") then
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
--- Build file content with marked region for inline prompts
|
||||
---@param lines string[] File lines
|
||||
---@param start_line number 1-indexed
|
||||
---@param end_line number 1-indexed
|
||||
---@param prompt_content string The prompt inside the tags
|
||||
---@return string
|
||||
local function build_marked_file_content(lines, start_line, end_line, prompt_content)
|
||||
local result = {}
|
||||
for i, line in ipairs(lines) do
|
||||
if i == start_line then
|
||||
-- Mark the start of the region to be replaced
|
||||
table.insert(result, ">>> REPLACE THIS REGION (lines " .. start_line .. "-" .. end_line .. ") <<<")
|
||||
table.insert(result, "--- User request: " .. prompt_content:gsub("\n", " "):sub(1, 100) .. " ---")
|
||||
end
|
||||
table.insert(result, line)
|
||||
if i == end_line then
|
||||
table.insert(result, ">>> END OF REGION TO REPLACE <<<")
|
||||
end
|
||||
end
|
||||
return table.concat(result, "\n")
|
||||
end
|
||||
|
||||
--- Build prompt for code generation
|
||||
---@param event table PromptEvent
|
||||
---@return string prompt
|
||||
@@ -361,11 +420,13 @@ local function build_prompt(event)
|
||||
|
||||
-- Get target file content for context
|
||||
local target_content = ""
|
||||
local target_lines = {}
|
||||
if event.target_path then
|
||||
local ok, lines = pcall(function()
|
||||
return vim.fn.readfile(event.target_path)
|
||||
end)
|
||||
if ok and lines then
|
||||
target_lines = lines
|
||||
target_content = table.concat(lines, "\n")
|
||||
end
|
||||
end
|
||||
@@ -458,6 +519,93 @@ local function build_prompt(event)
|
||||
system_prompt = intent_mod.get_prompt_modifier(event.intent)
|
||||
end
|
||||
|
||||
-- SPECIAL HANDLING: Inline prompts with /@ ... @/ tags
|
||||
-- Uses SEARCH/REPLACE block format for reliable code editing
|
||||
if is_inline_prompt(event) and event.range and event.range.start_line then
|
||||
local start_line = event.range.start_line
|
||||
local end_line = event.range.end_line or start_line
|
||||
|
||||
-- Build full file content WITHOUT the /@ @/ tags for cleaner context
|
||||
local file_content_clean = {}
|
||||
for i, line in ipairs(target_lines) do
|
||||
-- Skip lines that are part of the tag
|
||||
if i < start_line or i > end_line then
|
||||
table.insert(file_content_clean, line)
|
||||
end
|
||||
end
|
||||
|
||||
user_prompt = string.format(
|
||||
[[You are editing a %s file: %s
|
||||
|
||||
TASK: %s
|
||||
|
||||
FULL FILE CONTENT:
|
||||
```%s
|
||||
%s
|
||||
```
|
||||
|
||||
IMPORTANT: The instruction above may ask you to make changes ANYWHERE in the file (e.g., "at the top", "after function X", etc.). Read the instruction carefully to determine WHERE to apply the change.
|
||||
|
||||
INSTRUCTIONS:
|
||||
You MUST respond using SEARCH/REPLACE blocks. This format lets you precisely specify what to find and what to replace it with.
|
||||
|
||||
FORMAT:
|
||||
<<<<<<< SEARCH
|
||||
[exact lines to find in the file - copy them exactly including whitespace]
|
||||
=======
|
||||
[new lines to replace them with]
|
||||
>>>>>>> REPLACE
|
||||
|
||||
RULES:
|
||||
1. The SEARCH section must contain EXACT lines from the file (copy-paste them)
|
||||
2. Include 2-3 context lines to uniquely identify the location
|
||||
3. The REPLACE section contains the modified code
|
||||
4. You can use multiple SEARCH/REPLACE blocks for multiple changes
|
||||
5. Preserve the original indentation style
|
||||
6. If adding new code at the start/end of file, include the first/last few lines in SEARCH
|
||||
|
||||
EXAMPLES:
|
||||
|
||||
Example 1 - Adding code at the TOP of file:
|
||||
Task: "Add a comment at the top"
|
||||
<<<<<<< SEARCH
|
||||
// existing first line
|
||||
// existing second line
|
||||
=======
|
||||
// NEW COMMENT ADDED HERE
|
||||
// existing first line
|
||||
// existing second line
|
||||
>>>>>>> REPLACE
|
||||
|
||||
Example 2 - Modifying a function:
|
||||
Task: "Add validation to setValue"
|
||||
<<<<<<< SEARCH
|
||||
export function setValue(key, value) {
|
||||
cache.set(key, value);
|
||||
}
|
||||
=======
|
||||
export function setValue(key, value) {
|
||||
if (!key) throw new Error("key required");
|
||||
cache.set(key, value);
|
||||
}
|
||||
>>>>>>> REPLACE
|
||||
|
||||
Now apply the requested changes using SEARCH/REPLACE blocks:]],
|
||||
filetype,
|
||||
vim.fn.fnamemodify(event.target_path or "", ":t"),
|
||||
event.prompt_content,
|
||||
filetype,
|
||||
table.concat(file_content_clean, "\n"):sub(1, 8000) -- Limit size
|
||||
)
|
||||
|
||||
context.system_prompt = system_prompt
|
||||
context.formatted_prompt = user_prompt
|
||||
context.is_inline_prompt = true
|
||||
context.use_search_replace = true
|
||||
|
||||
return user_prompt, context
|
||||
end
|
||||
|
||||
-- If we have a scope (function/method), include it in the prompt
|
||||
if event.scope_text and event.scope and event.scope.type ~= "file" then
|
||||
local scope_type = event.scope.type
|
||||
@@ -490,6 +638,11 @@ Return ONLY the complete %s with implementation. No explanations, no duplicates.
|
||||
event.prompt_content,
|
||||
scope_type
|
||||
)
|
||||
-- Remind the LLM not to repeat the original file content; ask for only the new/updated code or a unified diff
|
||||
user_prompt = user_prompt .. [[
|
||||
|
||||
IMPORTANT: Do NOT repeat the existing code provided above. Return ONLY the new or modified code (the updated function body). If you modify the file, prefer outputting a unified diff patch using standard diff headers (--- a/<file> / +++ b/<file> and @@ hunks). No explanations, no markdown, no code fences.
|
||||
]]
|
||||
-- For other replacement intents, provide the full scope to transform
|
||||
elseif event.intent and intent_mod.is_replacement(event.intent) then
|
||||
user_prompt = string.format(
|
||||
@@ -530,6 +683,18 @@ Output only the code to insert, no explanations.]],
|
||||
extra_context,
|
||||
event.prompt_content
|
||||
)
|
||||
|
||||
-- Remind the LLM not to repeat the full file content; ask for only the new/modified code or unified diff
|
||||
user_prompt = user_prompt .. [[
|
||||
|
||||
IMPORTANT: Do NOT repeat the full file content shown above. Return ONLY the new or modified code required to satisfy the request. If you modify the file, prefer outputting a unified diff patch using standard diff headers (--- a/<file> / +++ b/<file> and @@ hunks). No explanations, no markdown, no code fences.
|
||||
]]
|
||||
|
||||
-- Remind the LLM not to repeat the original file content; ask for only the inserted code or a unified diff
|
||||
user_prompt = user_prompt .. [[
|
||||
|
||||
IMPORTANT: Do NOT repeat the surrounding code provided above. Return ONLY the code to insert (the new snippet). If you modify multiple parts of the file, prefer outputting a unified diff patch using standard diff headers (--- a/<file> / +++ b/<file> and @@ hunks). No explanations, no markdown, no code fences.
|
||||
]]
|
||||
end
|
||||
else
|
||||
-- No scope resolved, use full file context
|
||||
|
||||
Reference in New Issue
Block a user