repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(neovim): make a pivi tool call as legible as the work it did

d40c346f5269628f7f8f7809790b847b0f1a562b

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (17)

+1219 / −54 text lines

Diff layout

neovim/lua/bugabinga/pivi/AGENTS.md

Modified

+12 / −1 text lines

777720. **Never force a parse per streamed delta.** Markdown rendering is `vim.treesitter.start` and stays redraw-driven; a forced parse per delta measured roughly five hundred times slower.
7878 Keep the streaming budget spec in `tests/bugabinga/pivi/editor/render_spec.lua`.
8021. **Contract tests guard assumptions,** not features. They skip unless `pi` is on `PATH` and opt-in is set. When Pi changes behavior, they fail before users do.
8021. **Never invent an outcome.** `bugabinga.pivi.tool` derives everything from what a tool reported in its result details, and a tool that reported nothing gets no outcome, no language, and no change.
81 Pi reports a change on every `edit`, progress on `bash`, and truncation only at a limit; `write` reports nothing at all.
82 Every interpretation needs a spec for the reporting tool and a spec for the silent one.
8422. **Entry shape changes without the buffer changing.** Re-anchoring an entry moves its bounds while touching no character, so anything cached per buffer must key on `entry.version` as well as `b:changedtick`.
85 A fold cache keyed on the tick alone silently goes stale the moment an entry is rewritten.
8723. **Contract tests guard assumptions,** not features. They skip unless `pi` is on `PATH` and opt-in is set. When Pi changes behavior, they fail before users do.
8289## Commands
115122| Rejections | name the command the user should type, not the internal state |
116123| Transcript keys | buffer-local only, plus a `<Plug>` mapping; Neovim already ships `]m` and `[m` globally, so assert on mapping descriptions rather than on the absence of a key |
117124| Folds | one fold per entry through `foldexpr`; appended text does not recompute folds until a redraw, so `apply` runs `zX` first and then drives folds from recorded intent |
125| Tool outcome | end-of-line virtual text on the entry's opening line, and repeated in the fold line so a collapsed entry stays useful |
126| Reported change | written as the tool formatted it and highlighted with `DiffAdd`/`DiffDelete` per line; `bugabinga.pivi.diff` rebuilds the prior content from the change itself and states when the file has moved on |
127| Streaming output | rewrite only the entry tail, skip per-line decoration while it runs, and never run `fold.apply` mid-stream |
128| Output language | parsed as a standalone string and applied as highlight extmarks, never as a fence, so transcript text stays what the tool produced |
119130## Gotchas

neovim/lua/bugabinga/pivi/command.lua

Modified

+18 / −0 text lines

55local follow = require 'bugabinga.pivi.follow'
66local publish = require 'bugabinga.pivi.publish'
77local runtime = require 'bugabinga.pivi.runtime'
8local comparison = require 'bugabinga.pivi.diff'
910local INPUT_FILETYPE = 'pivi-input'
285286 current.clear_queue( function() notify 'queue cleared' end )
286287end
289subcommands.diff = function()
290 local bufnr = vim.api.nvim_get_current_buf()
291 if vim.bo[bufnr].filetype ~= transcript.filetype then
292 notify( 'move the cursor into a transcript first', vim.log.levels.WARN )
293 return
294 end
296 local changed, _, faithful = comparison.open( bufnr )
297 if not changed then
298 notify( 'this entry reports no change to compare', vim.log.levels.WARN )
299 return
300 end
301 if faithful == false then
302 notify( 'the file has moved on since this change', vim.log.levels.WARN )
303 end
304end
288306subcommands.follow = function( arguments )
289307 follow.toggle( arguments ~= '' and arguments or nil )
290308 notify( 'follow ' .. ( follow.mode() or 'off' ) )

neovim/lua/bugabinga/pivi/diff.lua

Added
new file mode 100644

+136 / −0 text lines

1local entry = require 'bugabinga.pivi.entry'
2local navigate = require 'bugabinga.pivi.navigate'
3local tool = require 'bugabinga.pivi.tool'
4
5local state = { window = nil, buffer = nil, }
6
7--- Reads a reported change back into the lines it added and removed.
8--- The tool numbers every changed line, so the change can be undone on the
9--- content it produced.
10local parse = function( change )
11 local removed, added = {}, {}
12 for _, line in ipairs( vim.split( change or '', '\n', { plain = true, } ) ) do
13 local mark = line:sub( 1, 1 )
14 local number, text = line:sub( 2 ):match '^%s*(%d+) (.*)$'
15 if number then
16 local record = { line = tonumber( number ), text = text, }
17 if mark == '+' then
18 table.insert( added, record )
19 elseif mark == '-' then
20 table.insert( removed, record )
21 end
22 end
23 end
24 return removed, added
25end
27--- The content that existed before a change, rebuilt from the change itself.
28--- @return string[] lines
29--- @return boolean faithful whether the content still matches what was changed
30local before = function( current, change )
31 local removed, added = parse( change )
32 local lines = vim.deepcopy( current )
33 local faithful = true
35 for _, record in ipairs( added ) do
36 if lines[record.line] ~= record.text then faithful = false end
37 end
39 local descending = vim.deepcopy( added )
40 table.sort( descending, function( left, right ) return left.line > right.line end )
41 for _, record in ipairs( descending ) do
42 if lines[record.line] ~= nil then table.remove( lines, record.line ) end
43 end
45 local ascending = vim.deepcopy( removed )
46 table.sort( ascending, function( left, right ) return left.line < right.line end )
47 for _, record in ipairs( ascending ) do
48 table.insert( lines, math.min( record.line, #lines + 1 ), record.text )
49 end
51 return lines, faithful
52end
54local close = function()
55 if state.window and vim.api.nvim_win_is_valid( state.window ) then
56 pcall( vim.api.nvim_win_call, state.window, function() vim.cmd 'diffoff' end )
57 pcall( vim.api.nvim_win_close, state.window, true )
58 end
59 if state.buffer and vim.api.nvim_buf_is_valid( state.buffer ) then
60 pcall( vim.api.nvim_buf_delete, state.buffer, { force = true, } )
61 end
62 state.window, state.buffer = nil, nil
63end
65--- Opens a completed change as an editor comparison.
66--- The change is compared against the content the tool produced, so ordinary
67--- diff motions and diff folds apply.
68--- @return number? changed the window showing the file
69--- @return number? original the window showing the content before the change
70--- @return boolean? faithful whether the file still matches what was changed
71local open = function( bufnr, line_number )
72 local item = entry.at( bufnr, line_number or vim.api.nvim_win_get_cursor( 0 )[1] )
73 if not item or item.kind ~= 'tool' then return nil end
75 local change = tool.diff( item.meta )
76 local location = navigate.location_of( item )
77 if not change or not location then return nil end
79 local working = vim.api.nvim_get_current_win()
80 local changed = navigate.locate( bufnr, item.first )
81 if not changed then return nil end
83 close()
85 local target = vim.api.nvim_win_get_buf( changed )
86 local current = vim.api.nvim_buf_get_lines( target, 0, -1, false )
87 local original, faithful = before( current, change )
89 state.buffer = vim.api.nvim_create_buf( false, true )
90 vim.bo[state.buffer].buftype = 'nofile'
91 vim.bo[state.buffer].bufhidden = 'wipe'
92 vim.bo[state.buffer].swapfile = false
93 vim.api.nvim_buf_set_lines( state.buffer, 0, -1, false, original )
94 vim.bo[state.buffer].modifiable = false
95 vim.bo[state.buffer].filetype = vim.bo[target].filetype
97 local label = 'pivi://' .. vim.fs.basename( location.path ) .. '/before'
98 if not faithful then label = label .. ' (the file has moved on)' end
99 pcall( vim.api.nvim_buf_set_name, state.buffer, label )
101 local opened = pcall( vim.api.nvim_win_call, changed, function()
102 vim.cmd 'diffthis'
103 vim.cmd 'leftabove vsplit'
104 vim.api.nvim_win_set_buf( 0, state.buffer )
105 vim.cmd 'diffthis'
106 state.window = vim.api.nvim_get_current_win()
107 end )
109 if not opened then
110 close()
111 return nil
112 end
114 if vim.api.nvim_win_is_valid( working ) then
115 vim.api.nvim_set_current_win( working )
116 end
118 return changed, state.window, faithful
119end
121local bind = function( bufnr )
122 local action = function() open( bufnr ) end
123 vim.keymap.set( 'n', 'gD', action, { buffer = bufnr, desc = 'pivi compare the change of the entry', } )
124 vim.keymap.set( 'n', '<Plug>(pivi-compare-change)', action,
125 { buffer = bufnr, desc = 'pivi compare the change of the entry', } )
126end
128require( 'bugabinga.pivi.transcript' ).on_buffer( bind )
130return {
131 parse = parse,
132 before = before,
133 open = open,
134 close = close,
135 bind = bind,
136}

neovim/lua/bugabinga/pivi/entry.lua

Modified

+31 / −0 text lines

1212local records = {}
13local versions = {}
15--- Bumped whenever the entries of a buffer change shape.
16--- Buffer text alone is not enough to know that: re-anchoring an entry moves
17--- its bounds without touching a single character.
18local version = function( bufnr )
19 return versions[bufnr] or 0
20end
22local touch = function( bufnr )
23 versions[bufnr] = version( bufnr ) + 1
24end
1426local namespace = function()
1527 return vim.api.nvim_create_namespace( NAMESPACE )
3244--- Fixed line numbers would drift as later entries are appended, so bounds
3345--- are extmark-backed and re-anchored whenever the entry grows.
3446local anchor = function( bufnr, id, first, last )
47 touch( bufnr )
3548 vim.api.nvim_buf_set_extmark( bufnr, namespace(), first, 0, {
3649 id = id,
3750 end_row = last,
6982 } )
7184 of_buffer( bufnr )[id] = { id = id, kind = kind, meta = meta or {}, }
85 touch( bufnr )
7286 return id
7387end
110124 extend( bufnr, id )
111125end
127--- Replaces everything an entry shows below its opening line.
128--- A tool that reports progress rewrites its own tail, so the entry keeps its
129--- identity and its bounds while its content changes.
130local rewrite = function( bufnr, id, text )
131 if not id or not vim.api.nvim_buf_is_valid( bufnr ) then return end
132 if not of_buffer( bufnr )[id] then return end
134 local first = start_row( bufnr, id )
135 if not first then return end
137 transcript.replace( bufnr, first + 1, content_row( bufnr, first ) + 1, text )
138 extend( bufnr, id )
139end
113141local close = function( bufnr, id )
114142 extend( bufnr, id )
115143 return nil
173201local clear = function( bufnr )
174202 records[bufnr] = nil
203 versions[bufnr] = nil
175204 if vim.api.nvim_buf_is_valid( bufnr ) then
176205 vim.api.nvim_buf_clear_namespace( bufnr, namespace(), 0, -1 )
177206 end
182211return {
183212 namespace = namespace,
213 version = version,
184214 kinds = KINDS,
185215 open = open,
186216 write = write,
187217 line = line,
218 rewrite = rewrite,
188219 extend = extend,
189220 close = close,
190221 range = range,

neovim/lua/bugabinga/pivi/fold.lua

Modified

+15 / −2 text lines

11local entry = require 'bugabinga.pivi.entry'
22local transcript = require 'bugabinga.pivi.transcript'
3local tool = require 'bugabinga.pivi.tool'
45local EXPRESSION = "v:lua.require'bugabinga.pivi.fold'.expr()"
56local TEXT = "v:lua.require'bugabinga.pivi.fold'.text()"
2122 return item.kind == 'tool' and item.last > item.first
2223end
25--- Fold levels, recomputed whenever entry bounds could have moved.
26--- Buffer text alone is not a sufficient key, because an entry is re-anchored
27--- after its text is written and that never changes a character.
2428local folds_of = function( bufnr )
2529 local tick = vim.api.nvim_buf_get_changedtick( bufnr )
30 local shape = entry.version( bufnr )
2631 local cached = levels[bufnr]
27 if cached and cached.tick == tick then return cached.rows end
32 if cached and cached.tick == tick and cached.shape == shape then return cached.rows end
2934 local rows = {}
3035 for _, item in ipairs( entry.list( bufnr ) ) do
3439 end
3540 end
37 levels[bufnr] = { tick = tick, rows = rows, }
42 levels[bufnr] = { tick = tick, shape = shape, rows = rows, }
3843 return rows
3944end
4651end
4853--- One readable line standing in for a collapsed entry.
54--- A collapsed tool entry still states what it acted on and how it ended,
55--- because that is the whole reason a reader leaves it collapsed.
4956local text = function()
5057 local bufnr = vim.api.nvim_get_current_buf()
5158 local first = vim.v.foldstart or 1
5259 local item = entry.at( bufnr, first )
5360 local headline = vim.api.nvim_buf_get_lines( bufnr, first - 1, first, false )[1] or ''
5461 local icon = item and ICONS[item.kind] or '\u{25b8}'
63 if item and item.kind == 'tool' then
64 local ended = tool.outcome( item.meta )
65 if ended then headline = vim.trim( headline ) .. ' ' .. ended end
66 end
5568 return ( '%s %s (%d more lines)' ):format( icon, vim.trim( headline ), vim.v.foldend - first )
5669end

neovim/lua/bugabinga/pivi/init.lua

Modified

+4 / −0 text lines

1717local fold = require 'bugabinga.pivi.fold'
1818local navigate = require 'bugabinga.pivi.navigate'
1919local detail = require 'bugabinga.pivi.detail'
20local tool = require 'bugabinga.pivi.tool'
21local comparison = require 'bugabinga.pivi.diff'
2123--- Reads cached status only. Safe to call from a statusline.
2224local summary = function( name ) return publish.summary( name ) end
4951 fold = fold,
5052 navigate = navigate,
5153 detail = detail,
54 tool = tool,
55 comparison = comparison,
5256 summary = summary,
5357 reset = reset,

neovim/lua/bugabinga/pivi/navigate.lua

Modified

+7 / −2 text lines

11local entry = require 'bugabinga.pivi.entry'
22local transcript = require 'bugabinga.pivi.transcript'
33local follow = require 'bugabinga.pivi.follow'
4local tool = require 'bugabinga.pivi.tool'
56local matching = function( bufnr, kind )
67 local found = {}
4950 if not item then return nil end
5051 local meta = item.meta or {}
5152 local args = type( meta.args ) == 'table' and meta.args or {}
52 local path = meta.path or args.path or args.file_path or args.filePath
53 -- A result kept only in part still has somewhere it lives in full.
54 local path = meta.path or args.path or args.file_path or args.filePath or tool.full_output( meta )
5355 if type( path ) ~= 'string' or path == '' then return nil end
5557 if meta.cwd and not vim.startswith( path, '/' ) and not path:match '^%a:' then
5658 path = vim.fs.normalize( meta.cwd .. '/' .. path )
5759 end
59 return { path = path, line = meta.line or args.line or args.lnum, }
61 -- An edit is worth reaching where it changed something, not at the top of a
62 -- file the change may be nowhere near.
63 local line = tool.first_changed_line( meta ) or meta.line or args.line or args.lnum
64 return { path = path, line = line, }
6065end
6267--- Reaches the place the entry under the cursor names.

neovim/lua/bugabinga/pivi/render.lua

Modified

+73 / −3 text lines

11local entry = require 'bugabinga.pivi.entry'
22local transcript = require 'bugabinga.pivi.transcript'
3local tool = require 'bugabinga.pivi.tool'
45local NAMESPACE = 'pivi-render'
2122 vim.api.nvim_buf_clear_namespace( bufnr, namespace(), first - 1, last )
2223end
25--- Presents a tool's output in the language it came from.
26--- The output is parsed as a standalone string and the result is applied as
27--- decoration, so the transcript text stays exactly what the tool produced.
28local speak = function( bufnr, item, lang )
29 if item.last <= item.first then return false end
31 local text = table.concat(
32 vim.api.nvim_buf_get_lines( bufnr, item.first, item.last, false ), '\n'
33 )
34 if text == '' then return false end
36 local parsed, parser = pcall( vim.treesitter.get_string_parser, text, lang )
37 if not parsed or not parser then return false end
39 local trees = parser:parse( true )
40 if not trees or not trees[1] then return false end
42 local query = vim.treesitter.query.get( lang, 'highlights' )
43 if not query then return false end
45 local offset = item.first
46 for id, node in query:iter_captures( trees[1]:root(), text ) do
47 local first_row, first_column, last_row, last_column = node:range()
48 pcall( vim.api.nvim_buf_set_extmark, bufnr, namespace(), offset + first_row, first_column, {
49 end_row = offset + last_row,
50 end_col = last_column,
51 hl_group = '@' .. query.captures[id] .. '.' .. lang,
52 priority = 90,
53 } )
54 end
56 return true
57end
2459--- Decorates one entry.
2560--- Only the entry's own lines are touched, so decoration cost stays
2661--- proportional to the entry rather than to the whole transcript.
27local decorate = function( bufnr, id )
62--- @param options table? head_only limits decoration to the opening line
63local decorate = function( bufnr, id, options )
2864 if not vim.api.nvim_buf_is_valid( bufnr ) then return end
3066 local item = nil
4783 } )
4884 end
86 -- What a tool reported about its own work, beside what it acted on.
87 if item.kind == 'tool' then
88 local ended = tool.outcome( item.meta )
89 if ended then
90 pcall( vim.api.nvim_buf_set_extmark, bufnr, namespace(), item.first - 1, 0, {
91 virt_text = { { ' ' .. ended, item.meta.failed and 'ErrorMsg' or 'Comment', }, },
92 virt_text_pos = 'eol',
93 right_gravity = false,
94 priority = 60,
95 } )
96 end
97 end
5099 if not frame.prefix and not frame.line_hl then return end
52 for row = item.first - 1, item.last - 1 do
101 -- A reported change reads as a change: added and removed lines stay distinct
102 -- from the dimmed body around them.
103 local change = item.kind == 'tool' and tool.diff( item.meta ) ~= nil
105 -- While a tool still reports progress its body is rewritten repeatedly, so
106 -- only its opening line is decorated until it finishes.
107 local final_row = options and options.head_only and item.first - 1 or item.last - 1
109 for row = item.first - 1, final_row do
53110 local heads = row == item.first - 1
54111 local prefix = frame.prefix and ( heads or frame.every_line ) and frame.prefix or nil
113 local line_hl = frame.line_hl
114 if change and not heads then
115 local text = vim.api.nvim_buf_get_lines( bufnr, row, row + 1, false )[1]
116 line_hl = tool.diff_highlight( text ) or line_hl
117 end
55119 pcall( vim.api.nvim_buf_set_extmark, bufnr, namespace(), row, 0, {
56120 virt_text = prefix and { { prefix, frame.prefix_hl, }, } or nil,
57121 virt_text_pos = prefix and 'inline' or nil,
58 line_hl_group = frame.line_hl,
122 line_hl_group = line_hl,
59123 right_gravity = false,
60124 priority = 60,
61125 } )
62126 end
128 if item.kind == 'tool' and not ( options and options.head_only ) then
129 local lang = tool.language( item.meta )
130 if lang then speak( bufnr, item, lang ) end
131 end
63132end
65134--- Renders message formatting, and presents embedded code in its own language.
99168 namespace = namespace,
100169 frames = FRAMES,
101170 decorate = decorate,
171 speak = speak,
102172 highlight = highlight,
103173 highlighted = highlighted,
104174 conceal = conceal,

neovim/lua/bugabinga/pivi/session.lua

Modified

+18 / −45 text lines

1313local entry = require 'bugabinga.pivi.entry'
1414local render = require 'bugabinga.pivi.render'
1515local fold = require 'bugabinga.pivi.fold'
16local tool = require 'bugabinga.pivi.tool'
1718local registry = {}
1819local counter = 0
7273 return name
7374end
75local relative = function( self, path )
76 if type( path ) ~= 'string' or path == '' then return nil end
77 local root = self.cwd and vim.fs.normalize( self.cwd ) or nil
78 local full = vim.fs.normalize( path )
79 if root and full:sub( 1, #root + 1 ) == root .. '/' then return full:sub( #root + 2 ) end
80 return vim.fs.basename( full )
81end
83--- Describes a tool call the way a reader wants to scan it.
84local describe_tool = function( self, name, arguments )
85 local subject = type( arguments ) == 'table'
86 and ( arguments.path or arguments.file_path or arguments.filePath
87 or arguments.command or arguments.pattern or arguments.tag or arguments.title )
88 or nil
90 if type( subject ) ~= 'string' or subject == '' then return tostring( name ) end
91 if subject:find( '[/\\]' ) then subject = relative( self, subject ) or subject end
93 subject = subject:gsub( '%s+', ' ' )
94 if #subject > 60 then subject = subject:sub( 1, 59 ) .. '…' end
95 return tostring( name ) .. ' ' .. subject
96end
98--- The text a tool produced, as the tool produced it.
99local result_text = function( result )
100 if type( result ) ~= 'table' then return nil end
101 local pieces = {}
102 for _, block in ipairs( result.content or {} ) do
103 if block.type == 'text' and type( block.text ) == 'string' then
104 table.insert( pieces, block.text )
105 end
106 end
107 local joined = vim.trim( table.concat( pieces, '\n' ) )
108 if joined == '' then return nil end
109 return joined
110end
11277--- Ends the entry currently being written, if any.
11378local seal = function( self )
155120 end
156121 end
157122 elseif event.type == 'tool_execution_start' then
123 self.streamed = nil
158124 begin( self, 'tool', {
159125 tool = event.toolName,
160126 args = event.args,
161127 call = event.toolCallId,
162128 cwd = self.cwd,
163129 } )
164 entry.line( bufnr, self.entry, describe_tool( self, event.toolName, event.args ) )
130 entry.line( bufnr, self.entry, tool.headline( entry.meta( bufnr, self.entry ) ) )
131 elseif event.type == 'tool_execution_update' then
132 -- Output arrives while the tool still runs, so the entry shows it now
133 -- rather than only once the tool ends.
134 if self.entry_kind == 'tool' and event.partialResult then
135 entry.annotate( bufnr, self.entry, { result = event.partialResult, } )
136 local shown = tool.body( entry.meta( bufnr, self.entry ) )
137 local joined = table.concat( shown, '\n' )
138 if joined ~= self.streamed then
139 self.streamed = joined
140 entry.rewrite( bufnr, self.entry, shown )
141 render.decorate( bufnr, self.entry, { head_only = true, } )
142 end
143 end
165144 elseif event.type == 'tool_execution_end' then
166145 if self.entry_kind == 'tool' then
167146 entry.annotate( bufnr, self.entry, { result = event.result, failed = event.isError == true, } )
168 local produced = result_text( event.result )
169 if produced then
170 for _, piece in ipairs( vim.split( produced, '\n', { plain = true, } ) ) do
171 entry.line( bufnr, self.entry, piece )
172 end
173 elseif event.isError then
174 entry.line( bufnr, self.entry, 'failed' )
175 end
147 entry.rewrite( bufnr, self.entry, tool.body( entry.meta( bufnr, self.entry ) ) )
148 self.streamed = nil
176149 seal( self )
177150 end
178151 elseif event.type == 'agent_settled' then

neovim/lua/bugabinga/pivi/skills/pivi/SKILL.md

Modified

+8 / −1 text lines

4242- Markdown is rendered rather than shown as markup, and fenced code is presented in its own language.
4343- Every submission, answer, tool call and error is an entry with its own bounds and metadata.
4444- Tool output lands inside its tool entry and arrives collapsed; the conversation itself stays open.
45- A tool entry states what it acted on and, once finished, how it ended: an edit shows how many lines it added and removed, a truncated result says so, a failure says so.
46- A completed edit shows its change, with added and removed lines distinct, and `:Pi diff` or `gD` opens it as a real editor comparison.
47- Going to an edit lands on its first changed line; going from a truncated result reaches the file its full output was spilled to.
48- Output of a running tool appears as it arrives, and output that came from a known language is presented in it.
49- Nothing here is invented: a tool that reports nothing about its own work simply names its subject.
4651| Key in a transcript | Effect |
4752| --- | --- |
5055| `]t` / `[t` | move to the next or previous tool call |
5156| `gf` | go to the location the entry names |
5257| `K` | inspect the entry, including tool arguments and result |
58| `gD` | compare a completed change as a real editor diff |
5359| `zR` / `zM` | expand or collapse everything, as in any buffer |
55These keys are buffer-local, and `<Plug>(pivi-toggle-entry)`, `<Plug>(pivi-next-entry)`, `<Plug>(pivi-previous-entry)`, `<Plug>(pivi-next-tool)`, `<Plug>(pivi-previous-tool)`, `<Plug>(pivi-goto-location)` and `<Plug>(pivi-inspect-entry)` exist alongside them.
61These keys are buffer-local, and `<Plug>(pivi-toggle-entry)`, `<Plug>(pivi-next-entry)`, `<Plug>(pivi-previous-entry)`, `<Plug>(pivi-next-tool)`, `<Plug>(pivi-previous-tool)`, `<Plug>(pivi-goto-location)`, `<Plug>(pivi-inspect-entry)` and `<Plug>(pivi-compare-change)` exist alongside them.
5763## Surfaces the user has
6571| `:Pi prompt` | open a prompt buffer; `<c-s>` submits |
6672| `:Pi start` / `stop` / `sessions` / `show` | session lifetime and presentation |
6773| `:Pi abort` / `queue` / `clear` | run and queue control |
74| `:Pi diff` | compare the change of the entry under the cursor |
6875| `:Pi follow [window\|tab\|current]` | toggle follow mode |
7077`<Plug>(pivi-show)`, `<Plug>(pivi-prompt)`, `<Plug>(pivi-abort)`, and `<Plug>(pivi-follow)` exist; pivi sets no global mappings.

neovim/lua/bugabinga/pivi/tool.lua

Added
new file mode 100644

+203 / −0 text lines

1local MAX_SUBJECT = 60
2
3--- What a tool reports about its own work.
4--- Everything here is derived from that report; a tool that reports nothing
5--- gets no outcome rather than an invented one.
6local details_of = function( meta )
7 local result = meta and meta.result
8 if type( result ) ~= 'table' then return nil end
9 if type( result.details ) ~= 'table' then return nil end
10 return result.details
11end
13local relative = function( path, cwd )
14 if type( path ) ~= 'string' or path == '' then return nil end
15 local root = cwd and vim.fs.normalize( cwd ) or nil
16 local full = vim.fs.normalize( path )
17 if root and full:sub( 1, #root + 1 ) == root .. '/' then return full:sub( #root + 2 ) end
18 return vim.fs.basename( full )
19end
21--- What the tool acted on, short enough to scan.
22local subject = function( meta )
23 local args = meta and type( meta.args ) == 'table' and meta.args or {}
24 local found = args.path or args.file_path or args.filePath
25 or args.command or args.pattern or args.tag or args.title
27 if type( found ) ~= 'string' or found == '' then return nil end
28 if found:find( '[/\\]' ) then found = relative( found, meta.cwd ) or found end
30 found = found:gsub( '%s+', ' ' )
31 if #found > MAX_SUBJECT then found = found:sub( 1, MAX_SUBJECT - 1 ) .. '\u{2026}' end
32 return found
33end
35local counts = function( diff )
36 local added, removed = 0, 0
37 for _, line in ipairs( vim.split( diff or '', '\n', { plain = true, } ) ) do
38 local mark = line:sub( 1, 1 )
39 if mark == '+' then
40 added = added + 1
41 elseif mark == '-' then
42 removed = removed + 1
43 end
44 end
45 return added, removed
46end
48local LIMITS = {
49 { field = 'matchLimitReached', label = 'match limit', },
50 { field = 'resultLimitReached', label = 'result limit', },
51 { field = 'entryLimitReached', label = 'entry limit', },
52}
54--- How the tool ended, or nothing when it reported nothing.
55local outcome = function( meta )
56 if not meta then return nil end
57 local details = details_of( meta )
58 local parts = {}
60 if details and type( details.diff ) == 'string' then
61 local added, removed = counts( details.diff )
62 table.insert( parts, ( '+%d -%d' ):format( added, removed ) )
63 end
65 if details and type( details.truncation ) == 'table' and details.truncation.truncated then
66 table.insert( parts, 'truncated' )
67 end
69 for _, limit in ipairs( LIMITS ) do
70 if details and details[limit.field] then table.insert( parts, limit.label ) end
71 end
73 if meta.failed then table.insert( parts, 'failed' ) end
75 if #parts == 0 then return nil end
76 return table.concat( parts, ' ' )
77end
79--- The change a completed edit reported, as the tool formatted it.
80local diff = function( meta )
81 local details = details_of( meta )
82 if not details or type( details.diff ) ~= 'string' then return nil end
83 local text = details.diff:gsub( '\n+$', '' )
84 if text == '' then return nil end
85 return text
86end
88--- The line a reported change starts at, when the tool reported one.
89local first_changed_line = function( meta )
90 local details = details_of( meta )
91 local line = details and details.firstChangedLine
92 if type( line ) ~= 'number' or line < 1 then return nil end
93 return math.floor( line )
94end
96--- How one line of a reported change should read.
97local diff_highlight = function( text )
98 local mark = ( text or '' ):sub( 1, 1 )
99 if mark == '+' then return 'DiffAdd' end
100 if mark == '-' then return 'DiffDelete' end
101 return nil
102end
104--- The text a tool produced, as the tool produced it.
105local produced = function( meta )
106 local result = meta and meta.result
107 if type( result ) ~= 'table' then return nil end
108 local pieces = {}
109 for _, block in ipairs( result.content or {} ) do
110 if block.type == 'text' and type( block.text ) == 'string' then
111 table.insert( pieces, block.text )
112 end
113 end
114 local joined = vim.trim( table.concat( pieces, '\n' ) )
115 if joined == '' then return nil end
116 return joined
117end
119--- What a tool entry shows below its headline.
120--- A reported change reads better than a sentence about it, so an edit shows
121--- its change and every other tool shows what it produced.
122local body = function( meta )
123 local change = diff( meta )
124 if change then return vim.split( change, '\n', { plain = true, } ) end
126 local output = produced( meta )
127 if output then return vim.split( output, '\n', { plain = true, } ) end
129 if meta and meta.failed then return { 'failed', } end
130 return {}
131end
133--- Tools whose output is the content of the file they name.
134local CONTENT_TOOLS = { read = true, }
136--- The language a tool's output came from, when that is known.
137--- Only a tool that returns file content can claim one; anything else would
138--- be a guess dressed up as syntax.
139local language = function( meta )
140 if not meta or not CONTENT_TOOLS[meta.tool] then return nil end
141 if diff( meta ) then return nil end
143 local args = type( meta.args ) == 'table' and meta.args or {}
144 local path = args.path or args.file_path or args.filePath
145 if type( path ) ~= 'string' or path == '' then return nil end
147 local filetype = vim.filetype.match { filename = path, }
148 if not filetype then return nil end
150 local resolved = vim.treesitter.language.get_lang( filetype )
151 if not resolved then return nil end
152 if not pcall( vim.treesitter.language.add, resolved ) then return nil end
153 return resolved
154end
156--- Whether a tool kept less than it produced.
157local truncated = function( meta )
158 local details = details_of( meta )
159 local truncation = details and details.truncation
160 return type( truncation ) == 'table' and truncation.truncated == true
161end
163--- Where everything a tool produced still lives, when it reported that.
164local full_output = function( meta )
165 local details = details_of( meta )
166 local path = details and details.fullOutputPath
167 if type( path ) ~= 'string' or path == '' then return nil end
168 return path
169end
171--- The line a tool entry opens with: the tool and what it acted on.
172local headline = function( meta )
173 local name = tostring( meta and meta.tool or 'tool' )
174 local acted_on = subject( meta )
175 if not acted_on then return name end
176 return name .. ' ' .. acted_on
177end
179--- Tool, subject and outcome in one line, for a collapsed entry.
180local summary = function( meta )
181 local ended = outcome( meta )
182 if not ended then return headline( meta ) end
183 return headline( meta ) .. ' ' .. ended
184end
186return {
187 max_subject = MAX_SUBJECT,
188 details = details_of,
189 relative = relative,
190 subject = subject,
191 counts = counts,
192 diff = diff,
193 first_changed_line = first_changed_line,
194 diff_highlight = diff_highlight,
195 produced = produced,
196 body = body,
197 language = language,
198 outcome = outcome,
199 truncated = truncated,
200 full_output = full_output,
201 headline = headline,
202 summary = summary,
203}

neovim/lua/bugabinga/pivi/transcript.lua

Modified

+11 / −0 text lines

101101 append( bufnr, text .. '\n' )
102102end
104--- Replaces a range of rows, leaving everything around it alone.
105--- Rows are zero based and the end row is exclusive, as in the buffer API.
106local replace = function( bufnr, first, last, text )
107 if not vim.api.nvim_buf_is_valid( bufnr ) then return end
108 writable( bufnr, function()
109 vim.api.nvim_buf_set_lines( bufnr, first, last, false, text )
110 end )
111 follow_windows( bufnr )
112end
104114local lines = function( bufnr )
105115 if not vim.api.nvim_buf_is_valid( bufnr ) then return {} end
106116 return vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
191201 set_state = set_state,
192202 append = append,
193203 line = line,
204 replace = replace,
194205 lines = lines,
195206 clear = clear,
196207 show = show,

neovim/tests/bugabinga/pivi/editor/diff_spec.lua

Added
new file mode 100644

+168 / −0 text lines

1---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch, redundant-parameter
2local diff = require 'bugabinga.pivi.diff'
3local entry = require 'bugabinga.pivi.entry'
4local follow = require 'bugabinga.pivi.follow'
5local transcript = require 'bugabinga.pivi.transcript'
6local fake = dofile 'tests/helpers/pivi_fake.lua'
7
8local temp_file = function( lines )
9 local path = vim.fs.normalize( vim.fn.tempname() .. '.lua' )
10 vim.fn.writefile( lines, path )
11 return path
12end
14-- A change as the edit tool formats it: every changed line carries its number.
15local CHANGE = table.concat( {
16 ' 1 one',
17 '-2 two',
18 '+2 TWO',
19 ' 3 three',
20}, '\n' )
22local recorded = function( bufnr, path, change )
23 local id = entry.open( bufnr, 'tool', {
24 tool = 'edit',
25 args = { path = path, },
26 result = { details = { diff = change, firstChangedLine = 2, }, },
27 } )
28 entry.line( bufnr, id, 'edit ' .. vim.fs.basename( path ) )
29 for _, line in ipairs( vim.split( change, '\n', { plain = true, } ) ) do
30 entry.line( bufnr, id, line )
31 end
32 entry.close( bufnr, id )
33 return id
34end
36describe( 'pivi diff', function()
37 local bufnr, win
39 before_each( function()
40 bufnr = transcript.ensure 'comparing'
41 transcript.clear( bufnr )
42 win = transcript.show( bufnr )
43 vim.api.nvim_set_current_win( win )
44 end )
46 after_each( function()
47 diff.close()
48 follow.reset()
49 transcript.forget_all()
50 fake.close_extra_windows()
51 vim.cmd 'silent! %bwipeout!'
52 end )
54 describe( 'reading a reported change', function()
55 it( 'separates what was added from what was removed', function()
56 local removed, added = diff.parse( CHANGE )
58 assert.same( { { line = 2, text = 'two', }, }, removed )
59 assert.same( { { line = 2, text = 'TWO', }, }, added )
60 end )
62 it( 'ignores context lines', function()
63 local removed, added = diff.parse ' 1 untouched'
64 assert.same( {}, removed )
65 assert.same( {}, added )
66 end )
68 it( 'rebuilds the content that existed before the change', function()
69 local original, faithful = diff.before( { 'one', 'TWO', 'three', }, CHANGE )
71 assert.same( { 'one', 'two', 'three', }, original )
72 assert.is_true( faithful )
73 end )
75 it( 'rebuilds a change that only added lines', function()
76 local original = diff.before( { 'one', 'two', }, '+2 two' )
77 assert.same( { 'one', }, original )
78 end )
80 it( 'rebuilds a change that only removed lines', function()
81 local original = diff.before( { 'one', }, '-2 two' )
82 assert.same( { 'one', 'two', }, original )
83 end )
85 it( 'says so when the content no longer matches the change', function()
86 local _, faithful = diff.before( { 'one', 'something else', 'three', }, CHANGE )
87 assert.is_false( faithful )
88 end )
89 end )
91 describe( 'comparing', function()
92 it( 'opens the change as an editor comparison', function()
93 local path = temp_file { 'one', 'TWO', 'three', }
94 local id = recorded( bufnr, path, CHANGE )
95 local first = select( 1, entry.range( bufnr, id ) )
97 local changed, original, faithful = diff.open( bufnr, first )
99 assert.is_number( changed )
100 assert.is_number( original )
101 assert.is_true( faithful )
103 assert.is_true( vim.wo[changed].diff )
104 assert.is_true( vim.wo[original].diff )
105 assert.same( { 'one', 'two', 'three', }, vim.api.nvim_buf_get_lines( vim.api.nvim_win_get_buf( original ), 0, -1, false ) )
106 end )
108 it( 'keeps the working window and leaves the transcript untouched', function()
109 local path = temp_file { 'one', 'TWO', 'three', }
110 local id = recorded( bufnr, path, CHANGE )
111 local first = select( 1, entry.range( bufnr, id ) )
112 local before_text = transcript.lines( bufnr )
114 diff.open( bufnr, first )
116 assert.equal( win, vim.api.nvim_get_current_win() )
117 assert.same( before_text, transcript.lines( bufnr ) )
118 end )
120 it( 'states that the file has moved on', function()
121 local path = temp_file { 'one', 'something else', 'three', }
122 local id = recorded( bufnr, path, CHANGE )
123 local first = select( 1, entry.range( bufnr, id ) )
125 local _, original, faithful = diff.open( bufnr, first )
127 assert.is_false( faithful )
128 assert.is_true( vim.api.nvim_buf_get_name( vim.api.nvim_win_get_buf( original ) ):find( 'moved on', 1, true ) ~= nil )
129 end )
131 it( 'compares nothing for an entry that reports no change', function()
132 local id = entry.open( bufnr, 'tool', { tool = 'read', args = { path = temp_file { 'one', }, }, } )
133 entry.line( bufnr, id, 'read a.lua' )
134 entry.close( bufnr, id )
136 assert.is_nil( diff.open( bufnr, select( 1, entry.range( bufnr, id ) ) ) )
137 end )
139 it( 'compares nothing outside a tool entry', function()
140 local id = entry.open( bufnr, 'answer' )
141 entry.line( bufnr, id, 'just words' )
142 entry.close( bufnr, id )
144 assert.is_nil( diff.open( bufnr, select( 1, entry.range( bufnr, id ) ) ) )
145 end )
147 it( 'can be left again', function()
148 local path = temp_file { 'one', 'TWO', 'three', }
149 local id = recorded( bufnr, path, CHANGE )
150 local _, original = diff.open( bufnr, select( 1, entry.range( bufnr, id ) ) )
152 diff.close()
154 assert.is_false( vim.api.nvim_win_is_valid( original ) )
155 assert.equal( win, vim.api.nvim_get_current_win() )
156 end )
158 it( 'binds comparison in its own buffers only', function()
159 local bound = {}
160 for _, mapping in ipairs( vim.api.nvim_buf_get_keymap( bufnr, 'n' ) ) do
161 bound[mapping.lhs] = mapping.desc or ''
162 end
164 assert.is_string( bound.gD )
165 assert.is_true( bound.gD:find( 'pivi', 1, true ) ~= nil )
166 end )
167 end )
168end )

neovim/tests/bugabinga/pivi/editor/navigate_spec.lua

Modified

+76 / −0 text lines

6060 assert.equal( '/elsewhere/a.lua', located.path )
6161 end )
63 it( 'reaches the first changed line of an edit', function()
64 local located = navigate.location_of {
65 kind = 'tool',
66 meta = {
67 tool = 'edit',
68 args = { path = 'a.lua', },
69 result = { details = { diff = '-7 old\n+7 new', firstChangedLine = 7, }, },
70 },
71 }
73 assert.equal( 7, located.line )
74 end )
76 it( 'prefers the reported change over an argument line', function()
77 local located = navigate.location_of {
78 kind = 'tool',
79 meta = {
80 tool = 'edit',
81 args = { path = 'a.lua', line = 1, },
82 result = { details = { firstChangedLine = 12, }, },
83 },
84 }
86 assert.equal( 12, located.line )
87 end )
89 it( 'keeps the argument line when no change was reported', function()
90 local located = navigate.location_of {
91 kind = 'tool',
92 meta = { tool = 'read', args = { path = 'a.lua', line = 4, }, },
93 }
95 assert.equal( 4, located.line )
96 end )
98 it( 'lands on an edit at the line it changed', function()
99 local path = temp_file { 'one', 'two', 'three', 'four', 'five', }
100 block( bufnr, 'tool', {
101 tool = 'edit',
102 args = { path = path, },
103 result = { details = { diff = '-4 four\n+4 FOUR', firstChangedLine = 4, }, },
104 }, { 'edit', '-4 four', '+4 FOUR', } )
106 local listed = entry.list( bufnr )
107 local target = navigate.locate( bufnr, listed[#listed].first )
109 assert.is_number( target )
110 assert.equal( 4, vim.api.nvim_win_get_cursor( target )[1] )
111 end )
113 it( 'reaches the full output of a truncated result', function()
114 local located = navigate.location_of {
115 kind = 'tool',
116 meta = {
117 tool = 'bash',
118 args = { command = 'ls -R', },
119 result = { details = { truncation = { truncated = true, }, fullOutputPath = '/tmp/pi-bash-abc.log', }, },
120 },
121 }
123 assert.equal( '/tmp/pi-bash-abc.log', located.path )
124 end )
126 it( 'prefers what a tool acted on over where its output spilled', function()
127 local located = navigate.location_of {
128 kind = 'tool',
129 meta = {
130 tool = 'read',
131 args = { path = '/work/a.lua', },
132 result = { details = { fullOutputPath = '/tmp/spill.log', }, },
133 },
134 }
136 assert.equal( '/work/a.lua', located.path )
137 end )
63139 it( 'reports no place for an entry that names none', function()
64140 assert.is_nil( navigate.location_of { kind = 'answer', meta = {}, } )
65141 assert.is_nil( navigate.location_of( nil ) )

neovim/tests/bugabinga/pivi/editor/render_spec.lua

Modified

+87 / −0 text lines

22local render = require 'bugabinga.pivi.render'
33local entry = require 'bugabinga.pivi.entry'
44local transcript = require 'bugabinga.pivi.transcript'
5local tool = require 'bugabinga.pivi.tool'
56local fake = dofile 'tests/helpers/pivi_fake.lua'
78describe( 'pivi render', function()
8788 assert.is_true( #render.marks( bufnr ) > 0 )
8889 end )
91 it( 'shows a reported change with added and removed lines distinguished', function()
92 local id = entry.open( bufnr, 'tool', {
93 tool = 'edit',
94 args = { path = 'a.lua', },
95 result = { details = { diff = ' 1 keep\n-2 old\n+2 new\n', }, },
96 } )
97 for _, text in ipairs { 'edit a.lua', ' 1 keep', '-2 old', '+2 new', } do
98 entry.line( bufnr, id, text )
99 end
100 entry.close( bufnr, id )
102 local before = transcript.lines( bufnr )
103 render.decorate( bufnr, id )
105 local groups = {}
106 for _, mark in ipairs( render.marks( bufnr ) ) do
107 local details = mark[4] or {}
108 if details.line_hl_group then groups[mark[2] + 1] = details.line_hl_group end
109 end
111 local first = select( 1, entry.range( bufnr, id ) )
112 assert.equal( 'Comment', groups[first] )
113 assert.equal( 'Comment', groups[first + 1] )
114 assert.equal( 'DiffDelete', groups[first + 2] )
115 assert.equal( 'DiffAdd', groups[first + 3] )
117 -- The change is decoration over reported text, so the text is untouched.
118 assert.same( before, transcript.lines( bufnr ) )
119 end )
121 it( 'leaves a tool that reported no change entirely dimmed', function()
122 local id = entry.open( bufnr, 'tool', { tool = 'read', args = { path = 'a.lua', }, } )
123 for _, text in ipairs { 'read a.lua', '+ not a diff', } do
124 entry.line( bufnr, id, text )
125 end
126 entry.close( bufnr, id )
128 render.decorate( bufnr, id )
130 for _, mark in ipairs( render.marks( bufnr ) ) do
131 assert.is_not.equal( 'DiffAdd', ( mark[4] or {} ).line_hl_group )
132 end
133 end )
135 it( 'presents tool output in the language it came from', function()
136 local id = entry.open( bufnr, 'tool', {
137 tool = 'read',
138 args = { path = '/work/greet.lua', },
139 cwd = '/work',
140 result = { content = { { type = 'text', text = 'local value = 1', }, }, },
141 } )
142 entry.line( bufnr, id, 'read greet.lua' )
143 entry.line( bufnr, id, 'local value = 1' )
144 entry.close( bufnr, id )
146 local before = transcript.lines( bufnr )
147 render.decorate( bufnr, id )
149 local groups = {}
150 for _, mark in ipairs( render.marks( bufnr ) ) do
151 local group = ( mark[4] or {} ).hl_group
152 if group then groups[group] = true end
153 end
155 assert.is_true( groups['@keyword.lua'] or groups['@variable.lua'] or false,
156 'no lua highlight was applied: ' .. vim.inspect( vim.tbl_keys( groups ) ) )
157 assert.same( before, transcript.lines( bufnr ) )
158 end )
160 it( 'leaves output alone when no language can be claimed', function()
161 for _, meta in ipairs {
162 { tool = 'bash', args = { command = 'ls', }, },
163 { tool = 'read', args = { path = '/work/notes.unknownext', }, },
164 { tool = 'read', args = {}, },
165 { tool = 'edit', args = { path = '/work/a.lua', }, result = { details = { diff = '+1 x', }, }, },
166 } do
167 assert.is_nil( tool.language( meta ) )
168 end
170 assert.equal( 'lua', tool.language {
171 tool = 'read',
172 args = { path = '/work/a.lua', },
173 result = { content = {}, },
174 } )
175 end )
90177 it( 'decorates each kind with its own framing', function()
91178 for kind in pairs( entry.kinds ) do
92179 assert.is_table( render.frames[kind] )

neovim/tests/bugabinga/pivi/session_spec.lua

Modified

+158 / −0 text lines

433433 assert.same( {}, commands_of( channel, 'prompt' ) )
434434 end )
436 it( 'states how a tool ended beside what it acted on', function()
437 local channel = fake.new()
438 local current = create( channel )
439 local win = transcript.show( current.buffer )
441 channel.frame {
442 type = 'tool_execution_start',
443 toolCallId = 'c1',
444 toolName = 'edit',
445 args = { path = 'greet.lua', },
446 }
447 channel.frame {
448 type = 'tool_execution_end',
449 toolCallId = 'c1',
450 toolName = 'edit',
451 isError = false,
452 result = {
453 content = { { type = 'text', text = 'Successfully replaced 1 block(s) in greet.lua.', }, },
454 details = { diff = ' 1 keep\n-2 old\n+2 new\n', firstChangedLine = 2, },
455 },
456 }
457 channel.flush()
459 local item = entry.list( current.buffer )[1]
460 local lines = transcript.lines( current.buffer )
462 -- The outcome is decoration, never buffer text.
463 assert.equal( 'edit greet.lua', lines[item.first] )
465 local outcomes = {}
466 for _, mark in ipairs( render.marks( current.buffer ) ) do
467 local virt = ( mark[4] or {} ).virt_text
468 if virt then table.insert( outcomes, virt[1][1] ) end
469 end
470 assert.is_true( vim.iter( outcomes ):any( function( text ) return text:find( '+1 -1', 1, true ) ~= nil end ) )
472 -- And it survives collapsing.
473 local collapsed = vim.api.nvim_win_call( win, function()
474 vim.v.foldstart = item.first
475 vim.v.foldend = item.last
476 return fold.text()
477 end )
479 assert.is_true( collapsed:find( 'greet.lua', 1, true ) ~= nil )
480 assert.is_true( collapsed:find( '+1 -1', 1, true ) ~= nil )
481 end )
483 it( 'shows the output of a running tool as it arrives', function()
484 local channel = fake.new()
485 local current = create( channel )
487 channel.frame {
488 type = 'tool_execution_start',
489 toolCallId = 'c1',
490 toolName = 'bash',
491 args = { command = 'count', },
492 }
493 channel.flush()
495 local opened = entry.list( current.buffer )[1]
496 assert.equal( opened.first, opened.last )
498 channel.frame {
499 type = 'tool_execution_update',
500 toolCallId = 'c1',
501 toolName = 'bash',
502 partialResult = { content = { { type = 'text', text = 'one', }, }, },
503 }
504 channel.flush()
506 local growing = entry.list( current.buffer )[1]
507 assert.is_true( vim.list_contains( transcript.lines( current.buffer ), 'one' ) )
508 assert.equal( opened.first, growing.first )
509 assert.equal( growing.first + 1, growing.last )
511 channel.frame {
512 type = 'tool_execution_update',
513 toolCallId = 'c1',
514 toolName = 'bash',
515 partialResult = { content = { { type = 'text', text = 'one\ntwo\nthree', }, }, },
516 }
517 channel.flush()
519 local grown = entry.list( current.buffer )[1]
520 local lines = transcript.lines( current.buffer )
522 -- The tail was rewritten rather than appended twice.
523 assert.equal( opened.first, grown.first )
524 assert.equal( grown.first + 3, grown.last )
525 assert.same(
526 { 'bash count', 'one', 'two', 'three', },
527 vim.list_slice( lines, grown.first, grown.last )
528 )
530 channel.frame {
531 type = 'tool_execution_end',
532 toolCallId = 'c1',
533 toolName = 'bash',
534 isError = false,
535 result = { content = { { type = 'text', text = 'one\ntwo\nthree\ndone', }, }, },
536 }
537 channel.flush()
539 local finished = entry.list( current.buffer )[1]
540 assert.same(
541 { 'bash count', 'one', 'two', 'three', 'done', },
542 vim.list_slice( transcript.lines( current.buffer ), finished.first, finished.last )
543 )
544 end )
546 it( 'keeps later entries intact while a tool streams', function()
547 local channel = fake.new()
548 local current = create( channel )
550 current.submit( 'do it', { capture = false, } )
551 channel.frame { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'bash', args = { command = 'go', }, }
552 for _, text in ipairs { 'a', 'a\nb', 'a\nb\nc', } do
553 channel.frame {
554 type = 'tool_execution_update',
555 toolCallId = 'c1',
556 toolName = 'bash',
557 partialResult = { content = { { type = 'text', text = text, }, }, },
558 }
559 end
560 channel.flush()
562 local listed = entry.list( current.buffer )
563 local prompt = listed[1]
565 assert.equal( 'prompt', prompt.kind )
566 assert.equal( 'do it', transcript.lines( current.buffer )[prompt.first] )
567 assert.is_true( listed[2].first > prompt.last )
568 end )
570 it( 'says nothing about a tool that reported nothing', function()
571 local channel = fake.new()
572 local current = create( channel )
574 channel.frame {
575 type = 'tool_execution_start',
576 toolCallId = 'c1',
577 toolName = 'write',
578 args = { path = 'new.lua', },
579 }
580 channel.frame {
581 type = 'tool_execution_end',
582 toolCallId = 'c1',
583 toolName = 'write',
584 isError = false,
585 result = { content = { { type = 'text', text = 'wrote new.lua', }, }, },
586 }
587 channel.flush()
589 local item = entry.list( current.buffer )[1]
590 assert.is_nil( require( 'bugabinga.pivi.tool' ).outcome( item.meta ) )
591 assert.equal( 'write new.lua', transcript.lines( current.buffer )[item.first] )
592 end )
436594 it( 'records a rejected submission as its own entry', function()
437595 local channel = fake.new()
438596 local current = create( channel )

neovim/tests/bugabinga/pivi/tool_spec.lua

Added
new file mode 100644

+194 / −0 text lines

1---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch, redundant-parameter
2local tool = require 'bugabinga.pivi.tool'
3
4-- Shapes recorded from the installed Pi implementation: edit always reports a
5-- change, bash reports truncation and a full output path, the search tools
6-- report the limit they hit, and write reports nothing.
7local EDIT_DIFF = table.concat( {
8 ' 1 local function greet(name)',
9 '-2 return name',
10 '+2 return "hello " .. name',
11 '+3 -- added',
12 ' 4 end',
13}, '\n' )
15describe( 'pivi tool', function()
16 describe( 'subject', function()
17 it( 'names a path relative to the session directory', function()
18 assert.equal( 'lua/deep/file.lua', tool.subject {
19 tool = 'edit',
20 args = { path = '/work/lua/deep/file.lua', },
21 cwd = '/work',
22 } )
23 end )
25 it( 'falls back to the basename of a foreign path', function()
26 assert.equal( 'file.lua', tool.subject {
27 tool = 'read',
28 args = { path = '/elsewhere/file.lua', },
29 cwd = '/work',
30 } )
31 end )
33 it( 'names a command, a pattern, a tag or a title', function()
34 assert.equal( 'ls -la', tool.subject { args = { command = 'ls -la', }, } )
35 assert.equal( 'needle', tool.subject { args = { pattern = 'needle', }, } )
36 assert.equal( 'quickfix', tool.subject { args = { tag = 'quickfix', }, } )
37 assert.equal( 'review', tool.subject { args = { title = 'review', }, } )
38 end )
40 it( 'collapses whitespace and bounds the length', function()
41 local long = tool.subject { args = { command = string.rep( 'x', 200 ), }, }
42 assert.is_true( #long <= tool.max_subject + 2 )
44 assert.equal( 'a b c', tool.subject { args = { command = 'a b\tc', }, } )
45 end )
47 it( 'names nothing when the arguments name nothing', function()
48 assert.is_nil( tool.subject { tool = 'nvim_state', args = {}, } )
49 assert.is_nil( tool.subject( nil ) )
50 end )
51 end )
53 describe( 'outcome', function()
54 it( 'counts what an edit added and removed', function()
55 assert.equal( '+2 -1', tool.outcome {
56 tool = 'edit',
57 result = { details = { diff = EDIT_DIFF, }, },
58 } )
59 end )
61 it( 'reports a truncated result', function()
62 assert.equal( 'truncated', tool.outcome {
63 tool = 'bash',
64 result = { details = { truncation = { truncated = true, }, fullOutputPath = '/tmp/out.log', }, },
65 } )
66 end )
68 it( 'reports the limit a search tool hit', function()
69 assert.equal( 'match limit', tool.outcome {
70 tool = 'grep',
71 result = { details = { matchLimitReached = 100, }, },
72 } )
73 assert.equal( 'result limit', tool.outcome {
74 tool = 'find',
75 result = { details = { resultLimitReached = 100, }, },
76 } )
77 assert.equal( 'entry limit', tool.outcome {
78 tool = 'ls',
79 result = { details = { entryLimitReached = 500, }, },
80 } )
81 end )
83 it( 'reports a failure whatever the tool reported', function()
84 assert.equal( 'failed', tool.outcome { tool = 'bash', failed = true, } )
85 assert.equal( 'truncated failed', tool.outcome {
86 tool = 'bash',
87 failed = true,
88 result = { details = { truncation = { truncated = true, }, }, },
89 } )
90 end )
92 it( 'reports nothing for a tool that reported nothing', function()
93 assert.is_nil( tool.outcome { tool = 'write', result = { content = {}, }, } )
94 assert.is_nil( tool.outcome { tool = 'read', result = { content = {}, details = nil, }, } )
95 assert.is_nil( tool.outcome( nil ) )
96 end )
98 it( 'ignores a truncation that did not happen', function()
99 assert.is_nil( tool.outcome {
100 tool = 'read',
101 result = { details = { truncation = { truncated = false, }, }, },
102 } )
103 end )
104 end )
106 describe( 'the change an edit reported', function()
107 it( 'keeps the change as the tool formatted it', function()
108 local change = tool.diff { tool = 'edit', result = { details = { diff = EDIT_DIFF .. '\n\n', }, }, }
110 assert.equal( EDIT_DIFF, change )
111 end )
113 it( 'reports no change when none was reported', function()
114 assert.is_nil( tool.diff { tool = 'write', result = { content = {}, }, } )
115 assert.is_nil( tool.diff { tool = 'edit', result = { details = { diff = '', }, }, } )
116 end )
118 it( 'distinguishes added from removed lines', function()
119 assert.equal( 'DiffAdd', tool.diff_highlight '+2 return "hello"' )
120 assert.equal( 'DiffDelete', tool.diff_highlight '-2 return name' )
121 assert.is_nil( tool.diff_highlight ' 1 local function greet(name)' )
122 assert.is_nil( tool.diff_highlight( nil ) )
123 end )
125 it( 'shows the change rather than a sentence about it', function()
126 local shown = tool.body {
127 tool = 'edit',
128 result = {
129 content = { { type = 'text', text = 'Successfully replaced 1 block(s) in a.lua.', }, },
130 details = { diff = EDIT_DIFF, },
131 },
132 }
134 assert.same( vim.split( EDIT_DIFF, '\n', { plain = true, } ), shown )
135 end )
137 it( 'shows what a tool produced when it reported no change', function()
138 assert.same( { 'alpha', 'beta', }, tool.body {
139 tool = 'read',
140 result = { content = { { type = 'text', text = 'alpha\nbeta\n', }, }, },
141 } )
142 end )
144 it( 'shows a failure when a tool produced nothing at all', function()
145 assert.same( { 'failed', }, tool.body { tool = 'bash', failed = true, result = { content = {}, }, } )
146 assert.same( {}, tool.body { tool = 'write', result = { content = {}, }, } )
147 end )
148 end )
150 describe( 'truncation', function()
151 it( 'knows a result was kept only in part', function()
152 assert.is_true( tool.truncated {
153 tool = 'bash',
154 result = { details = { truncation = { truncated = true, }, }, },
155 } )
156 assert.is_false( tool.truncated {
157 tool = 'bash',
158 result = { details = { truncation = { truncated = false, }, }, },
159 } )
160 assert.is_false( tool.truncated { tool = 'write', result = { content = {}, }, } )
161 end )
163 it( 'knows where the full output still lives', function()
164 assert.equal( '/tmp/pi-bash-abc.log', tool.full_output {
165 tool = 'bash',
166 result = { details = { truncation = { truncated = true, }, fullOutputPath = '/tmp/pi-bash-abc.log', }, },
167 } )
168 assert.is_nil( tool.full_output { tool = 'read', result = { details = { truncation = {}, }, }, } )
169 end )
170 end )
172 describe( 'lines', function()
173 it( 'opens an entry with the tool and what it acted on', function()
174 assert.equal( 'edit a.lua', tool.headline { tool = 'edit', args = { path = 'a.lua', }, } )
175 assert.equal( 'nvim_state', tool.headline { tool = 'nvim_state', args = {}, } )
176 end )
178 it( 'states subject and outcome together for a collapsed entry', function()
179 local collapsed = tool.summary {
180 tool = 'edit',
181 args = { path = 'a.lua', },
182 result = { details = { diff = EDIT_DIFF, }, },
183 }
185 assert.is_true( collapsed:find( 'edit', 1, true ) ~= nil )
186 assert.is_true( collapsed:find( 'a.lua', 1, true ) ~= nil )
187 assert.is_true( collapsed:find( '+2 -1', 1, true ) ~= nil )
188 end )
190 it( 'degrades to the subject alone when nothing was reported', function()
191 assert.equal( 'write a.lua', tool.summary { tool = 'write', args = { path = 'a.lua', }, } )
192 end )
193 end )
194end )