repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

fix(neovim): make pivi work and read well in a live editor

9ed1bbf873490660153da7a8f3e10a5d271c27a2

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

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (23)

neovim/init.lua

Modified
83 83 defer 'bugabinga.inlay'
84 84 defer 'bugabinga.d2'
85 85 defer 'bugabinga.pivi'
86 +defer 'bugabinga.pivi_status'
87 88 -- Plugins handle deferred loading via puk.
88 89 -- No need to use `defer(...)`

neovim/lua/bugabinga/pivi/AGENTS.md

Modified
60 60 Never answer a Neovim documentation question from model memory in this codebase: `nvim_help` resolves against the running version's runtime path, including plugin docs.
61 61 Help is read-only by construction; keep mutating tools out of its allowlist.
63 -16. **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.
63 +16. **Edits stay proportional.** Never rewrite a whole buffer for a local change: `edit.replace` rewrites only the spanned lines and `edit.set_content` diffs first.
64 + A whole-buffer replacement marks every line as agent work, destroys marks and folds, and makes the trail useless.
65 + Assert the trail covers only the changed lines.
67 +17. **The trail belongs to the agent until the user edits.** `activity.touch` records the agent-owned revision; a later foreign change clears the trail.
68 + Anything the agent's own operation triggers, including a write, must call `touch` again, or an unrelated plugin reacting to the write wipes the trail.
69 + A revision recorded before the operation finishes is not enough; re-record after the event loop settles.
71 +18. **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.
65 73 ## Commands
84 92 Requests are synchronous, so scenarios need no sleeps.
85 93 Add scenarios to `tests/drive/run.lua`.
95 +## Presentation
97 +pivi decorates only its own windows and publishes state for everyone else.
99 +| Surface | Rule |
100 +| --- | --- |
101 +| Transcript and prompt windows | window-local `winbar` carries the session name; the prompt also names its submit key |
102 +| Progress | `transcript.set_state` shows the running tool in pivi's own winbar |
103 +| Statusline | `lua/bugabinga/pivi_status.lua` is a consumer: it reads `vim.g.pivi` and never requires pivi, so it degrades when pivi is absent |
104 +| Headings | write `## pi` only when real text arrives, so a tool-only turn leaves no empty heading |
105 +| Leading blank lines | models open with them; strip them before the first visible character |
106 +| Rejections | name the command the user should type, not the internal state |
87 108 ## Gotchas
110 +- Resolve the Pi executable to a real path before spawning. On Windows the launcher is a `.CMD` shim, a bare `pi` reaches the spawner as `ENOENT`, and a Neovim started from a desktop launcher has a smaller `PATH` than a shell. A failed spawn must be reported, never raised as a traceback in the editor.
111 +- End a Pi child by closing its input and only killing it after a grace period. On Windows the launcher is a shim, so an immediate kill orphans the runtime behind it and those orphans keep later test runs from exiting. Contract tests share one child per command line and shut it down explicitly.
112 +- Plenary discovers spec files by spawning `pwsh` with a 5 second timeout. Under load that fails with `E5108` and no tests run at all. Run the file directly when that happens; an empty summary is a harness failure, not a pass.
89 113 - Never pipe a Plenary run into `tail`, `grep`, or `head`. Plenary spawns child Neovim processes that inherit stdout, so the pipe stays open and the shell appears to hang long after the tests finished. Redirect to a file and read the file.
90 114 - A `vim.wait` predicate that already holds when the wait begins asserts nothing. `run == 'idle'` is true before the first frame is ever dispatched; wait for an observed event instead, or use the fake's `flush` barrier.
91 115 - Real extension traffic dominates a recorded run: a recorded stream is mostly `setStatus` and `setWidget`, and the extensions clear their own entries on shutdown, so end-of-run status maps are empty by design.

neovim/lua/bugabinga/pivi/activity.lua

Modified
17 17 local diagnostic_namespace = function() return namespace( DIAGNOSTIC_NAMESPACE ) end
19 19 local trail = {}
20 +local revisions = {}
21 +local groups = {}
23 +local clear_trail
25 +local unwatch = function( bufnr )
26 + revisions[bufnr] = nil
27 + if groups[bufnr] then
28 + pcall( vim.api.nvim_del_augroup_by_id, groups[bufnr] )
29 + groups[bufnr] = nil
30 + end
31 +end
33 +--- Records the current revision as agent-owned.
34 +--- Whatever the edit triggers in the same loop iteration, such as a formatter
35 +--- on write, still belongs to the agent's operation rather than to the user.
36 +local touch = function( bufnr )
37 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
38 + revisions[bufnr] = vim.api.nvim_buf_get_changedtick( bufnr )
39 + vim.schedule( function()
40 + if revisions[bufnr] and vim.api.nvim_buf_is_valid( bufnr ) then
41 + revisions[bufnr] = vim.api.nvim_buf_get_changedtick( bufnr )
42 + end
43 + end )
44 +end
46 +--- Clears a buffer's trail as soon as the user changes that buffer themselves.
47 +--- Agent edits record their own revision, so only a foreign change clears it.
48 +local watch = function( bufnr )
49 + touch( bufnr )
50 + if groups[bufnr] then return end
52 + groups[bufnr] = vim.api.nvim_create_augroup( 'pivi_trail_' .. tostring( bufnr ), { clear = true, } )
54 + vim.api.nvim_create_autocmd( { 'TextChanged', 'TextChangedI', }, {
55 + group = groups[bufnr],
56 + buffer = bufnr,
57 + desc = 'Clear the pivi edit trail once the user changes the buffer.',
58 + callback = function()
59 + if not vim.api.nvim_buf_is_valid( bufnr ) then
60 + unwatch( bufnr )
61 + return true
62 + end
63 + if vim.api.nvim_buf_get_changedtick( bufnr ) == revisions[bufnr] then return end
64 + clear_trail( bufnr )
65 + return true
66 + end,
67 + } )
68 +end
21 70 --- Marks changed lines so the agent's work stays navigable.
22 71 --- Marks live in pivi's own namespace and never touch diagnostic or
39 88 table.insert( trail, { buffer = bufnr, first = first + 1, last = math.min( last, count ), } )
90 + watch( bufnr )
41 91 publish.activity { kind = 'edit', buffer = bufnr, ranges = ranges, }
46 96 return vim.api.nvim_buf_get_extmarks( bufnr, namespace( TRAIL_NAMESPACE ), 0, -1, {} )
49 -local clear_trail = function( bufnr )
99 +clear_trail = function( bufnr )
50 100 if bufnr and vim.api.nvim_buf_is_valid( bufnr ) then
51 101 vim.api.nvim_buf_clear_namespace( bufnr, namespace( TRAIL_NAMESPACE ), 0, -1 )
103 + if bufnr then
104 + unwatch( bufnr )
105 + else
106 + for buffer in pairs( groups ) do unwatch( buffer ) end
107 + end
53 108 trail = {}
150 205 return {
151 206 sign_group = SIGN_GROUP,
152 207 namespace = namespace,
208 + touch = touch,
153 209 trail_namespace = TRAIL_NAMESPACE,
154 210 ghost_namespace = GHOST_NAMESPACE,
155 211 diagnostic_namespace = diagnostic_namespace,

neovim/lua/bugabinga/pivi/bridge.lua

Modified
34 34 return { ok = true, source = 'disk', }
37 - local applied, joined = edit.apply( bufnr, { {
38 - first = 0,
39 - last = -1,
40 - lines = vim.split( request.content, '\n', { plain = true, } ),
41 - }, } )
37 + local applied, joined = edit.set_content( bufnr, request.content )
42 38 if not applied then return failure 'buffer write failed' end
43 39 local persisted = edit.persist( bufnr )
44 40 return { ok = true, source = 'buffer', joined = joined, persisted = persisted, }

neovim/lua/bugabinga/pivi/command.lua

Modified
4 4 local session = require 'bugabinga.pivi.session'
5 5 local help = require 'bugabinga.pivi.help'
6 6 local transcript = require 'bugabinga.pivi.transcript'
7 7 local context = require 'bugabinga.pivi.context'
8 8 local follow = require 'bugabinga.pivi.follow'
9 9 local publish = require 'bugabinga.pivi.publish'
10 +local runtime = require 'bugabinga.pivi.runtime'
11 12 local INPUT_FILETYPE = 'pivi-input'
11 12 vim.notify( 'pivi: ' .. message, level or vim.log.levels.INFO )
15 +--- Returns the active session, starting one when none exists.
16 +--- A missing or unusable Pi is reported, never raised.
14 17 local require_session = function()
15 18 local current = session.active()
16 19 if current then return current end
17 - return session.create {}
21 + local available, failure = runtime.executable()
22 + if not available then
23 + notify( failure, vim.log.levels.ERROR )
24 + return nil
25 + end
27 + local ok, created = pcall( session.create, {} )
28 + if not ok then
29 + notify( 'cannot start pi: ' .. tostring( created ), vim.log.levels.ERROR )
30 + return nil
31 + end
33 + local started = created.client.failure()
34 + if started then
35 + notify( 'cannot start pi: ' .. started, vim.log.levels.ERROR )
36 + created.stop()
37 + return nil
38 + end
40 + return created
20 43 --- Decides whether `/` opens slash-command entry.
72 95 vim.bo[bufnr].bufhidden = 'wipe'
73 96 vim.bo[bufnr].filetype = INPUT_FILETYPE
74 97 vim.b[bufnr].pivi_session = current.name
98 + pcall( vim.api.nvim_buf_set_name, bufnr, 'pivi://' .. current.name .. '/prompt' )
76 100 vim.keymap.set( { 'n', 'i', }, '/', function()
77 101 local col = vim.api.nvim_win_get_cursor( 0 )[2]
79 103 vim.schedule( function()
80 104 pick_slash_command( current, function( choice )
81 105 run_slash_command( current, choice.name, nil )
106 + transcript.show( current.buffer )
84 109 return ''
94 119 return
96 121 vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { '', } )
122 + -- A submission the user cannot read the answer to is a dead end.
123 + transcript.show( current.buffer )
97 124 end, { buffer = bufnr, desc = 'pivi submit prompt', } )
99 126 if pcall( vim.cmd.split ) then
100 127 local win = vim.api.nvim_get_current_win()
101 128 vim.api.nvim_win_set_buf( win, bufnr )
102 129 pcall( vim.api.nvim_win_set_height, win, 6 )
130 + transcript.decorate( win, current.name )
131 + vim.wo[win].winbar = '%#Title#π ' .. current.name ..
132 + '%* %#Comment#<c-s> send / commands%*'
133 + vim.cmd.startinsert()
104 135 return bufnr
107 138 local submit_text = function( text, options )
108 139 local current = require_session()
140 + if not current then return false end
109 142 local accepted, rejection = current.submit( text, options )
110 143 if not accepted then
111 144 notify( rejection, vim.log.levels.WARN )
152 185 subcommands.command = function( arguments )
153 186 local current = require_session()
187 + if not current then return end
154 189 local name, rest = arguments:match '^(%S+)%s*(.*)$'
155 190 if name then
156 191 run_slash_command( current, name, rest )
166 201 subcommands.start = function( arguments )
202 + local available, failure = runtime.executable()
203 + if not available then
204 + notify( failure, vim.log.levels.ERROR )
205 + return
206 + end
167 208 local created = session.create { name = arguments ~= '' and arguments or nil, }
168 209 publish.set_active( created.name )
169 210 transcript.show( created.buffer )
206 247 subcommands.prompt = function()
207 - open_prompt( require_session() )
248 + local current = require_session()
249 + if not current then return end
250 + open_prompt( current )
210 253 subcommands.abort = function()

neovim/lua/bugabinga/pivi/edit.lua

Modified
37 37 local ok = pcall( vim.api.nvim_buf_call, bufnr, function()
38 38 vim.cmd 'silent! noautocmd write'
39 39 end )
40 + -- Writing stays part of the agent's operation, so the trail survives it.
41 + activity.touch( bufnr )
40 42 return ok and not vim.bo[bufnr].modified
78 80 return true, joined
83 +--- Brings a buffer to the given content by rewriting only what differs.
84 +--- A whole-buffer replacement would mark every line as agent work and destroy
85 +--- marks and folds for an edit that touched one line.
86 +local set_content = function( bufnr, content )
87 + vim.validate( 'content', content, 'string' )
88 + if not vim.api.nvim_buf_is_valid( bufnr ) then return false, false end
90 + local target = vim.split( content, '\n', { plain = true, } )
91 + local current = table.concat( vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ), '\n' )
92 + if current == content then return true, true end
94 + local whole = { { first = 0, last = -1, lines = target, }, }
96 + local ok, hunks = pcall( vim.text.diff, current .. '\n', content .. '\n', { result_type = 'indices', } )
97 + if not ok or type( hunks ) ~= 'table' or #hunks == 0 then
98 + return apply( bufnr, whole )
99 + end
101 + local replacements = {}
102 + for _, hunk in ipairs( hunks ) do
103 + local start_a, count_a, start_b, count_b = hunk[1], hunk[2], hunk[3], hunk[4]
104 + local first = count_a > 0 and start_a - 1 or start_a
105 + local lines = {}
106 + for index = start_b, start_b + count_b - 1 do
107 + table.insert( lines, target[index] )
108 + end
109 + table.insert( replacements, { first = first, last = first + count_a, lines = lines, } )
110 + end
112 + return apply( bufnr, replacements )
113 +end
81 115 local find_text = function( content, needle )
82 116 local first = content:find( needle, 1, true )
83 117 if not first then return nil end
89 123 --- Replaces one unique text occurrence in a loaded buffer.
124 +--- Only the lines the replacement actually spans are rewritten, so undo,
125 +--- marks, folds, and the activity trail stay proportional to the change.
90 126 local replace = function( bufnr, old_text, new_text )
91 127 vim.validate( 'old_text', old_text, 'string' )
92 128 vim.validate( 'new_text', new_text, 'string' )
95 131 local lines = vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
96 132 local content = table.concat( lines, '\n' )
97 - local first, failure = find_text( content, old_text )
98 - if not first then return false, failure or 'text not found' end
133 + local found, failure = find_text( content, old_text )
134 + if not found then return false, failure or 'text not found' end
100 - local replaced = content:sub( 1, first - 1 ) .. new_text .. content:sub( first + #old_text )
101 - local before = #vim.split( content:sub( 1, first - 1 ), '\n', { plain = true, } )
102 - local after = before + #vim.split( new_text, '\n', { plain = true, } ) - 1
136 + local first = #vim.split( content:sub( 1, found - 1 ), '\n', { plain = true, } )
137 + local last = first + #vim.split( old_text, '\n', { plain = true, } ) - 1
104 - local applied, joined = apply( bufnr, { {
105 - first = 0,
106 - last = -1,
139 + local region = table.concat( vim.list_slice( lines, first, last ), '\n' )
140 + local offset = region:find( old_text, 1, true )
141 + if not offset then return false, 'text not found' end
143 + local replaced = region:sub( 1, offset - 1 ) .. new_text .. region:sub( offset + #old_text )
145 + return apply( bufnr, { {
146 + first = first - 1,
147 + last = last,
107 148 lines = vim.split( replaced, '\n', { plain = true, } ),
108 149 }, } )
110 - if applied then
111 - activity.mark_edit( bufnr, { { first = before - 1, last = after, }, } )
112 - end
113 - return applied, joined
116 152 return {
119 155 read = read,
120 156 persist = persist,
121 157 apply = apply,
158 + set_content = set_content,
122 159 replace = replace,

neovim/lua/bugabinga/pivi/help.lua

Modified
15 15 'Answer directly and briefly, and change nothing.',
16 16 }, ' ' )
18 -local executable = function()
19 - return vim.g.pivi_executable or 'pi'
20 -end
22 18 local build_command = function( options )
23 19 options = options or {}
24 20 local command = {
25 - executable(), '--mode', 'rpc',
21 + options.executable or runtime.executable() or 'pi', '--mode', 'rpc',
26 22 '--no-session',
27 23 '--tools', TOOLS,
28 24 '--append-system-prompt', ORIENTATION,
40 36 table.insert( command, skill )
43 - if options.model then
39 + local chosen = options.model or vim.g.pivi_help_model or vim.g.pivi_model
40 + if chosen then
44 41 table.insert( command, '--model' )
45 - table.insert( command, options.model )
42 + table.insert( command, chosen )
43 + end
45 + local thinking = options.thinking or vim.g.pivi_thinking
46 + if thinking then
47 + table.insert( command, '--thinking' )
48 + table.insert( command, thinking )
47 50 for _, argument in ipairs( options.arguments or {} ) do
48 51 table.insert( command, argument )
73 76 transcript.line( bufnr, '? ' .. question )
74 77 transcript.line( bufnr, '' )
76 - local run = { buffer = bufnr, done = false, answer = '', }
79 + local run = { buffer = bufnr, done = false, answer = '', answering = false, }
81 + -- The window must exist before its state can be shown.
82 + transcript.show( bufnr )
84 + local state = function( text ) transcript.set_state( bufnr, BUFFER_NAME, text ) end
85 + state 'thinking'
78 87 run.client = rpc.start {
79 88 command = build_command( options ),
83 92 on_event = function( event )
84 93 if event.type == 'message_update' then
85 94 local delta = event.assistantMessageEvent or {}
86 - if delta.type == 'text_delta' then
87 - run.answer = run.answer .. ( delta.delta or '' )
88 - transcript.append( bufnr, delta.delta or '' )
95 + if delta.type == 'text_delta' and ( delta.delta or '' ) ~= '' then
96 + local text = delta.delta
97 + if not run.answering then
98 + text = text:gsub( '^%s*\n', '' )
99 + if text ~= '' then
100 + run.answering = true
101 + state 'answering'
102 + transcript.line( bufnr, '' )
103 + end
104 + end
105 + if text ~= '' then
106 + run.answer = run.answer .. text
107 + transcript.append( bufnr, text )
108 + end
90 110 elseif event.type == 'tool_execution_start' then
111 + run.answering = false
112 + local subject = type( event.args ) == 'table' and ( event.args.tag or event.args.path or event.args.pattern ) or nil
113 + local described = tostring( event.toolName )
114 + if type( subject ) == 'string' and subject ~= '' then described = described .. ' ' .. subject end
115 + state( described )
91 116 transcript.line( bufnr, '' )
92 - transcript.line( bufnr, ' · ' .. tostring( event.toolName ) )
117 + transcript.line( bufnr, ' ▸ ' .. described )
93 118 elseif event.type == 'message_end' and event.message and event.message.errorMessage then
94 - transcript.line( bufnr, '! ' .. tostring( event.message.errorMessage ) )
119 + transcript.line( bufnr, '' )
120 + transcript.line( bufnr, ' ! ' .. tostring( event.message.errorMessage ) )
95 121 elseif event.type == 'agent_settled' then
96 122 run.done = true
123 + state( nil )
97 124 run.client.stop()
98 125 if options.on_done then options.on_done( run ) end
101 128 on_exit = function()
102 129 run.done = true
130 + state( nil )
106 134 run.client.request( { type = 'prompt', message = compose( question, options ), }, function( response )
107 135 if response.success then return end
108 - transcript.line( bufnr, '! ' .. tostring( response.error or 'help run rejected' ) )
136 + transcript.line( bufnr, ' ! ' .. tostring( response.error or 'help run rejected' ) )
109 137 run.done = true
138 + state( nil )
110 139 run.client.stop()
111 140 if options.on_done then options.on_done( run ) end
114 - transcript.show( bufnr )
115 143 return run

neovim/lua/bugabinga/pivi/init.lua

Modified
46 46 command.setup()
48 +vim.api.nvim_create_autocmd( 'VimLeavePre', {
49 + group = vim.api.nvim_create_augroup( 'pivi_shutdown', { clear = true, } ),
50 + desc = 'End every Pi process when Neovim exits.',
51 + callback = function() pcall( session.stop_all ) end,
52 +} )
48 54 return _G.BugabingaPivi

neovim/lua/bugabinga/pivi/rpc.lua

Modified
93 93 end )
96 - local handle = spawn( options.command, {
96 + -- A missing or unusable executable is an ordinary reported failure, never a
97 + -- traceback in the user's editor.
98 + local started, spawned = pcall( spawn, options.command, {
97 99 cwd = options.cwd,
98 100 env = options.env,
99 101 stdout = on_stdout,
101 103 on_exit = on_exit,
106 + local handle = started and spawned or nil
108 + if not handle then
109 + state.running = false
110 + state.failure = tostring( spawned )
111 + table.insert( failures, state.failure )
112 + vim.schedule( function() guard( options.on_exit, nil ) end )
113 + end
104 115 local send = function( command )
105 - if not state.running then return false, 'pi process is not running' end
116 + if not state.running or not handle then
117 + return false, state.failure or 'pi process is not running'
118 + end
106 119 local ok, encoded = pcall( vim.json.encode, command )
107 120 if not ok then return false, tostring( encoded ) end
108 121 handle:write( encoded .. '\n' )
127 140 local notify = function( command ) return send( command ) end
142 + local GRACE_MS = 2000
144 + --- Ends the child by closing its input first.
145 + --- Pi exits on its own when stdin closes; killing immediately would orphan
146 + --- the runtime behind a launcher shim, which keeps processes alive forever.
129 147 local stop = function()
130 - if not state.running then return end
148 + if not state.running or not handle then return end
131 150 pcall( function() handle:write( nil ) end )
132 - pcall( function() handle:kill( 'sigterm' ) end )
152 + local timer = vim.uv.new_timer()
153 + if not timer then
154 + pcall( function() handle:kill( 'sigterm' ) end )
155 + return
156 + end
158 + timer:start( GRACE_MS, 0, vim.schedule_wrap( function()
159 + timer:stop()
160 + timer:close()
161 + if state.running then pcall( function() handle:kill( 'sigterm' ) end ) end
162 + end ) )
135 165 local is_running = function() return state.running end
139 169 notify = notify,
140 170 stop = stop,
141 171 is_running = is_running,
172 + failure = function() return state.failure end,
142 173 handle = handle,
143 174 failures = function() return vim.deepcopy( failures ) end,

neovim/lua/bugabinga/pivi/runtime.lua

Modified
20 20 return runtime_file 'lua/bugabinga/pivi/skills/pivi/SKILL.md'
23 +--- Directories a global npm install commonly uses.
24 +--- A Neovim started from a desktop launcher inherits a smaller PATH than a
25 +--- shell does, so PATH alone is not a reliable way to find Pi.
26 +local install_directories = function()
27 + local home = vim.fs.normalize( vim.uv.os_homedir() or '' )
28 + local directories = {}
30 + -- Built without holes: a nil entry would end iteration early.
31 + local add = function( directory )
32 + if directory and directory ~= '' then
33 + table.insert( directories, vim.fs.normalize( directory ) )
34 + end
35 + end
37 + add( vim.env.PIVI_PI_DIR )
38 + add( vim.env.NPM_CONFIG_PREFIX )
39 + if vim.env.NPM_CONFIG_PREFIX then add( vim.env.NPM_CONFIG_PREFIX .. '/bin' ) end
40 + add( home .. '/.local/share/npm' )
41 + add( home .. '/.local/bin' )
42 + add( home .. '/AppData/Roaming/npm' )
43 + add( home .. '/.npm-global/bin' )
44 + add( home .. '/.bun/bin' )
45 + add '/usr/local/bin'
46 + add '/opt/homebrew/bin'
48 + return directories
49 +end
51 +local names = function()
52 + if vim.fn.has 'win32' == 1 then return { 'pi.cmd', 'pi.exe', 'pi.bat', 'pi', } end
53 + return { 'pi', }
54 +end
56 +local probe = function( candidate )
57 + if candidate == nil or candidate == '' then return nil end
58 + if vim.fn.executable( candidate ) == 1 then
59 + local resolved = vim.fn.exepath( candidate )
60 + return vim.fs.normalize( resolved ~= '' and resolved or candidate )
61 + end
62 + local stat = vim.uv.fs_stat( candidate )
63 + if stat and stat.type == 'file' then return vim.fs.normalize( candidate ) end
64 + return nil
65 +end
67 +--- Resolves the Pi executable to a real path.
68 +--- A bare name is not enough: on Windows the launcher is a `.CMD` shim, and an
69 +--- unresolved name reaches the process spawner as a missing file.
70 +--- @return string? path
71 +--- @return string? failure
72 +local executable = function()
73 + local configured = vim.g.pivi_executable
74 + if configured then
75 + local found = probe( configured )
76 + if found then return found end
77 + return nil, 'pi executable not found: ' .. tostring( configured )
78 + end
80 + for _, name in ipairs( names() ) do
81 + local found = probe( name )
82 + if found then return found end
83 + end
85 + for _, directory in ipairs( install_directories() ) do
86 + if directory and directory ~= '' then
87 + for _, name in ipairs( names() ) do
88 + local found = probe( vim.fs.normalize( directory .. '/' .. name ) )
89 + if found then return found end
90 + end
91 + end
92 + end
94 + return nil, 'pi not found on PATH or in the usual install directories; set vim.g.pivi_executable'
95 +end
23 97 --- Environment the companion extension needs to reach this Neovim instance.
24 98 local bridge_environment = function()
25 99 local address = vim.v.servername
34 108 return {
35 109 file = runtime_file,
110 + install_directories = install_directories,
111 + executable = executable,
36 112 extension_path = extension_path,
37 113 client_path = client_path,
38 114 skill_path = skill_path,

neovim/lua/bugabinga/pivi/session.lua

Modified
14 14 local registry = {}
15 15 local counter = 0
17 -local executable = function()
18 - return vim.g.pivi_executable or 'pi'
17 +local model = function( requested )
18 + return requested or vim.g.pivi_model
21 21 local build_command = function( options )
22 22 options = options or {}
23 - local command = { executable(), '--mode', 'rpc', }
23 + local command = { options.executable or runtime.executable() or 'pi', '--mode', 'rpc', }
25 25 local extension = options.extension ~= false and runtime.extension_path() or nil
26 26 if extension then
33 33 table.insert( command, '--skill' )
34 34 table.insert( command, skill )
36 - if options.model then
36 + local chosen = model( options.model )
37 + if chosen then
37 38 table.insert( command, '--model' )
38 - table.insert( command, options.model )
39 + table.insert( command, chosen )
40 + end
42 + local thinking = options.thinking or vim.g.pivi_thinking
43 + if thinking then
44 + table.insert( command, '--thinking' )
45 + table.insert( command, thinking )
40 47 if options.session then
41 48 table.insert( command, '--session' )
62 69 return name
72 +local relative = function( self, path )
73 + if type( path ) ~= 'string' or path == '' then return nil end
74 + local root = self.cwd and vim.fs.normalize( self.cwd ) or nil
75 + local full = vim.fs.normalize( path )
76 + if root and full:sub( 1, #root + 1 ) == root .. '/' then return full:sub( #root + 2 ) end
77 + return vim.fs.basename( full )
78 +end
80 +--- Describes a tool call the way a reader wants to scan it.
81 +local describe_tool = function( self, name, arguments )
82 + local subject = type( arguments ) == 'table'
83 + and ( arguments.path or arguments.file_path or arguments.filePath
84 + or arguments.command or arguments.pattern or arguments.tag or arguments.title )
85 + or nil
87 + if type( subject ) ~= 'string' or subject == '' then return tostring( name ) end
88 + if subject:find( '[/\\]' ) then subject = relative( self, subject ) or subject end
90 + subject = subject:gsub( '%s+', ' ' )
91 + if #subject > 60 then subject = subject:sub( 1, 59 ) .. '…' end
92 + return tostring( name ) .. ' ' .. subject
93 +end
95 +--- Writes the assistant heading only once real text arrives, so a turn that
96 +--- only calls tools never leaves an empty heading behind.
97 +local open_answer = function( self )
98 + if self.answering then return end
99 + self.answering = true
100 + transcript.line( self.buffer, '' )
101 + transcript.line( self.buffer, '## pi' )
102 +end
65 104 local render_event = function( self, event )
66 105 local bufnr = self.buffer
68 107 if event.type == 'message_start' and event.message and event.message.role == 'assistant' then
69 - transcript.line( bufnr, '' )
70 - transcript.line( bufnr, '# pi' )
108 + self.answering = false
71 109 elseif event.type == 'message_update' then
72 110 local delta = event.assistantMessageEvent or {}
73 - if delta.type == 'text_delta' then
74 - transcript.append( bufnr, delta.delta or '' )
111 + if delta.type == 'text_delta' and ( delta.delta or '' ) ~= '' then
112 + local text = delta.delta
113 + -- Models often open with blank lines; the heading already separates turns.
114 + if not self.answering then text = text:gsub( '^%s*\n', '' ) end
115 + if text ~= '' then
116 + open_answer( self )
117 + transcript.append( bufnr, text )
118 + end
76 120 elseif event.type == 'tool_execution_start' then
121 + self.answering = false
77 122 transcript.line( bufnr, '' )
78 - transcript.line( bufnr, ' · ' .. tostring( event.toolName ) )
123 + transcript.line( bufnr, ' ▸ ' .. describe_tool( self, event.toolName, event.args ) )
124 + elseif event.type == 'tool_execution_end' and event.isError then
125 + transcript.line( bufnr, ' failed' )
79 126 elseif event.type == 'agent_settled' then
127 + self.answering = false
80 128 transcript.line( bufnr, '' )
81 129 elseif event.type == 'message_end' and event.message and event.message.errorMessage then
130 + self.answering = false
82 131 transcript.line( bufnr, '' )
83 132 transcript.line( bufnr, ' ! ' .. tostring( event.message.errorMessage ) )
170 219 arguments = options.arguments,
171 220 extension = options.extension,
172 221 skill = options.skill,
222 + thinking = options.thinking,
223 + executable = options.executable,
174 225 cwd = cwd,
175 226 env = options.env or runtime.bridge_environment(),
229 280 local delivery = options.delivery
231 282 if busy and not delivery then
232 - return false, 'pi is running: choose steer or follow_up delivery'
283 + return false, 'pi is running; use :Pi steer <text>, :Pi follow-up <text>, or :Pi abort'
235 286 if delivery and delivery ~= 'steer' and delivery ~= 'follow_up' then
236 - return false, 'unknown delivery: ' .. tostring( delivery )
287 + return false, 'unknown delivery "' .. tostring( delivery ) .. '"; use steer or follow_up'
239 290 local snapshot = options.snapshot
246 297 message = context.render( snapshot ) .. text
300 + self.answering = false
249 301 transcript.line( self.buffer, '' )
250 - transcript.line( self.buffer, '> ' .. text )
302 + for _, line in ipairs( vim.split( text, '\n', { plain = true, } ) ) do
303 + transcript.line( self.buffer, '> ' .. line )
304 + end
252 306 local command
253 307 if delivery == 'steer' then

neovim/lua/bugabinga/pivi/transcript.lua

Modified
78 78 end )
81 +--- Window-local identity for a pivi window.
82 +--- Only pivi's own windows are decorated; user-owned windows are untouched.
83 +local decorate = function( win, name )
84 + vim.wo[win].number = false
85 + vim.wo[win].relativenumber = false
86 + vim.wo[win].signcolumn = 'no'
87 + vim.wo[win].foldcolumn = '0'
88 + vim.wo[win].cursorline = false
89 + vim.wo[win].wrap = true
90 + vim.wo[win].linebreak = true
91 + vim.wo[win].breakindent = true
92 + vim.wo[win].list = false
93 + vim.wo[win].spell = false
94 + vim.wo[win].winbar = '%#Title#π ' .. name .. '%*'
95 +end
97 +--- Shows what a pivi window is doing right now, in its own winbar.
98 +local set_state = function( bufnr, name, state )
99 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
100 + local text = '%#Title#π ' .. name .. '%*'
101 + if state and state ~= '' then text = text .. ' %#Comment#' .. state .. '%*' end
102 + for _, win in ipairs( vim.api.nvim_list_wins() ) do
103 + if vim.api.nvim_win_get_buf( win ) == bufnr then vim.wo[win].winbar = text end
104 + end
105 +end
107 +local name_of = function( bufnr )
108 + for name, candidate in pairs( buffers ) do
109 + if candidate == bufnr then return name end
110 + end
111 + return 'pi'
112 +end
81 114 --- Shows the transcript buffer without stealing the current window.
82 115 local show = function( bufnr )
83 116 if not vim.api.nvim_buf_is_valid( bufnr ) then return nil end
89 122 if not split then return nil end
90 123 local win = vim.api.nvim_get_current_win()
91 124 vim.api.nvim_win_set_buf( win, bufnr )
92 - vim.wo[win].number = false
93 - vim.wo[win].relativenumber = false
94 - vim.wo[win].wrap = true
125 + decorate( win, name_of( bufnr ) )
95 126 vim.api.nvim_set_current_win( current )
96 127 return win
113 144 return {
114 145 filetype = FILETYPE,
115 146 ensure = ensure,
147 + decorate = decorate,
148 + set_state = set_state,
116 149 append = append,
117 150 line = line,
118 151 lines = lines,

neovim/lua/bugabinga/pivi_status.lua

Added
new file mode 100644
1 +--- Statusline consumer for pivi.
2 +--- It reads the published cache only and never requires pivi, so the
3 +--- statusline keeps working when pivi is absent, unloaded, or broken.
4 +local statusline = require 'bugabinga.statusline'
5 +local auto = require 'std.auto'
7 +local SPINNER = { '⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏', }
8 +local INTERVAL = 90
10 +local state = {
11 + frame = 1,
12 + timer = nil,
15 +local sessions = function()
16 + local value = vim.g.pivi
17 + if type( value ) ~= 'table' then return nil, {} end
18 + return value.active, value.sessions or {}
19 +end
21 +local busy = function( entry )
22 + return entry ~= nil
23 + and entry.connection ~= 'stopped'
24 + and ( entry.run == 'running' or entry.run == 'retrying' or entry.compacting == true )
25 +end
27 +local pending = function( entry )
28 + if not entry or type( entry.queue ) ~= 'table' then return 0 end
29 + return #( entry.queue.steering or {} ) + #( entry.queue.follow_up or {} )
30 +end
32 +local label = function( entry )
33 + if entry.error then return '%#ErrorMsg#π ' .. ( entry.tool and entry.tool.name or 'error' ) .. '%*' end
34 + if entry.compacting then return '%#WarningMsg#π compacting%*' end
35 + if entry.run == 'retrying' then return '%#WarningMsg#π retry%*' end
36 + if entry.tool then return '%#DiffChange#π ' .. tostring( entry.tool.name ) .. '%*' end
37 + if entry.run == 'running' then return '%#DiffChange#π thinking%*' end
38 + return 'π'
39 +end
41 +local stop_spinner = function()
42 + if not state.timer then return end
43 + state.timer:stop()
44 + state.timer:close()
45 + state.timer = nil
46 +end
48 +local start_spinner = function()
49 + if state.timer then return end
50 + state.timer = vim.uv.new_timer()
51 + state.timer:start( INTERVAL, INTERVAL, vim.schedule_wrap( function()
52 + state.frame = state.frame % #SPINNER + 1
53 + vim.cmd.redrawstatus()
54 + end ) )
55 +end
57 +--- Cached only: evaluating the statusline never talks to Pi.
58 +local component = function()
59 + local active, all = sessions()
60 + if not active then return '' end
62 + local entry = all[active]
63 + if not entry then return '' end
65 + local pieces = { label( entry ), }
66 + if busy( entry ) then table.insert( pieces, 1, SPINNER[state.frame] ) end
68 + local waiting = pending( entry )
69 + if waiting > 0 then table.insert( pieces, '+' .. tostring( waiting ) ) end
71 + return table.concat( pieces, ' ' )
72 +end
74 +statusline.register( component )
76 +auto 'pivi_statusline' {
77 + events = 'User',
78 + pattern = 'PiviStatus',
79 + description = 'Animate the pivi statusline while a run is active.',
80 + command = function()
81 + local active, all = sessions()
82 + local entry = active and all[active] or nil
83 + if busy( entry ) then
84 + start_spinner()
85 + else
86 + stop_spinner()
87 + end
88 + vim.cmd.redrawstatus()
89 + end,
92 +auto 'pivi_activity' {
93 + events = 'User',
94 + pattern = 'PiviActivity',
95 + description = 'Announce agent findings that landed in a native list.',
96 + command = function( event )
97 + local data = event.data
98 + if type( data ) ~= 'table' or data.kind ~= 'findings' then return end
99 + local count = tonumber( data.count ) or 0
100 + if count == 0 then return end
101 + vim.notify(
102 + ( 'π %d finding%s in the quickfix list' ):format( count, count == 1 and '' or 's' ),
103 + vim.log.levels.INFO
105 + end,
108 +_G.BugabingaPiviStatus = {
109 + component = component,
110 + busy = busy,
111 + pending = pending,
112 + label = label,
115 +return _G.BugabingaPiviStatus

neovim/tests/bugabinga/pivi/command_spec.lua

Modified
39 39 assert.is_false( command.slash_opens_commands( bufnr, 7 ) )
40 40 end )
42 + it( 'gives the prompt window an identity and its submit hint', function()
43 + local channel = fake.new()
44 + local current = session.create { spawn = channel.spawn, name = 'spec', extension = false, skill = false, env = {}, }
45 + local bufnr = command.open_prompt( current )
46 + local win = vim.fn.bufwinid( bufnr )
48 + assert.is_true( win > 0 )
49 + assert.is_true( vim.wo[win].winbar:find( 'spec', 1, true ) ~= nil )
50 + assert.is_true( vim.wo[win].winbar:find( 'c-s', 1, true ) ~= nil )
51 + assert.is_true( vim.api.nvim_buf_get_name( bufnr ):find( 'pivi://', 1, true ) ~= nil )
52 + assert.equal( 'spec', vim.b[bufnr].pivi_session )
54 + vim.cmd.stopinsert()
55 + end )
57 + it( 'shows the transcript after a prompt submission', function()
58 + local channel = fake.new()
59 + local current = session.create { spawn = channel.spawn, name = 'spec', extension = false, skill = false, env = {}, }
60 + local bufnr = command.open_prompt( current )
61 + vim.cmd.stopinsert()
63 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { 'do the thing', } )
65 + local mapping
66 + for _, entry in ipairs( vim.api.nvim_buf_get_keymap( bufnr, 'n' ) ) do
67 + if entry.lhs == '<C-S>' then mapping = entry end
68 + end
69 + assert.is_table( mapping )
71 + mapping.callback()
73 + assert.is_true( vim.fn.bufwinid( current.buffer ) > 0 )
74 + assert.same( { '', }, vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ) )
75 + end )
42 77 it( 'never opens in an ordinary buffer', function()
43 78 vim.cmd 'enew'
44 79 local bufnr = vim.api.nvim_get_current_buf()

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

Modified
36 36 assert.equal( 0, #activity.marks( bufnr ) )
37 37 end )
39 + it( 'keeps the trail across further agent edits', function()
40 + local bufnr = scratch { 'one', 'two', 'three', }
42 + activity.mark_edit( bufnr, { { first = 0, last = 1, }, } )
43 + activity.mark_edit( bufnr, { { first = 2, last = 3, }, } )
44 + vim.api.nvim_exec_autocmds( 'TextChanged', { buffer = bufnr, } )
46 + assert.equal( 2, #activity.marks( bufnr ) )
47 + end )
49 + it( 'clears the trail once the user changes the buffer', function()
50 + local bufnr = scratch { 'one', 'two', }
52 + activity.mark_edit( bufnr, { { first = 0, last = 1, }, } )
53 + assert.equal( 1, #activity.marks( bufnr ) )
55 + vim.api.nvim_buf_set_lines( bufnr, 0, 1, false, { 'edited by hand', } )
56 + vim.api.nvim_exec_autocmds( 'TextChanged', { buffer = bufnr, } )
58 + assert.equal( 0, #activity.marks( bufnr ) )
59 + assert.same( {}, activity.trail() )
60 + end )
39 62 it( 'renders ghost text without mutating the buffer', function()
40 63 local bufnr = scratch { 'one', 'two', }
41 64 local revision = vim.api.nvim_buf_get_changedtick( bufnr )

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

Modified
113 113 assert.same( { 'local value = 2', 'return value', }, lines_of( bufnr ) )
116 + it( 'marks only the lines a replacement actually touched', function()
117 + local path = temp_file { 'one', 'two', 'three', 'four', 'five', }
118 + local bufnr = open( path )
120 + edit.replace( bufnr, 'three', 'THREE' )
122 + assert.same( { { buffer = bufnr, first = 3, last = 3, }, }, activity.trail() )
123 + assert.equal( 1, #activity.marks( bufnr ) )
124 + end )
126 + it( 'keeps a replacement undoable as one change', function()
127 + local path = temp_file { 'one', 'two', 'three', }
128 + local bufnr = open( path )
129 + local before = lines_of( bufnr )
131 + edit.replace( bufnr, 'two', 'TWO' )
132 + vim.api.nvim_buf_call( bufnr, function() vim.cmd 'silent undo' end )
134 + assert.same( before, lines_of( bufnr ) )
135 + end )
137 + it( 'rewrites only what differs when setting whole content', function()
138 + local path = temp_file { 'one', 'two', 'three', 'four', 'five', }
139 + local bufnr = open( path )
141 + local applied = edit.set_content( bufnr, 'one\ntwo\nTHREE\nfour\nfive' )
143 + assert.is_true( applied )
144 + assert.same( { 'one', 'two', 'THREE', 'four', 'five', }, lines_of( bufnr ) )
145 + assert.is_true( #activity.marks( bufnr ) < 5 )
146 + end )
148 + it( 'reports identical content as already applied without marking it', function()
149 + local path = temp_file { 'one', 'two', }
150 + local bufnr = open( path )
152 + assert.is_true( edit.set_content( bufnr, 'one\ntwo' ) )
153 + assert.equal( 0, #activity.marks( bufnr ) )
154 + assert.is_false( vim.bo[bufnr].modified )
155 + end )
157 + it( 'sets content that grows and shrinks the buffer', function()
158 + local path = temp_file { 'one', 'two', }
159 + local bufnr = open( path )
161 + assert.is_true( edit.set_content( bufnr, 'one\ninserted\ntwo\ntail' ) )
162 + assert.same( { 'one', 'inserted', 'two', 'tail', }, lines_of( bufnr ) )
164 + assert.is_true( edit.set_content( bufnr, 'only' ) )
165 + assert.same( { 'only', }, lines_of( bufnr ) )
166 + end )
116 168 it( 'refuses an ambiguous replacement', function()
117 169 local path = temp_file { 'same', 'same', }
118 170 local bufnr = open( path )

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

Modified
58 58 vim.api.nvim_win_close( win, true )
59 59 end )
61 + it( 'gives its own window an identity without touching other windows', function()
62 + local working = vim.api.nvim_get_current_win()
63 + local before = vim.wo[working].winbar
65 + local bufnr = transcript.ensure 'work'
66 + local win = transcript.show( bufnr )
68 + assert.is_true( vim.wo[win].winbar:find( 'work', 1, true ) ~= nil )
69 + assert.is_true( vim.wo[win].wrap )
70 + assert.is_false( vim.wo[win].number )
71 + assert.equal( before, vim.wo[working].winbar )
73 + vim.api.nvim_win_close( win, true )
74 + end )
61 76 it( 'forgets and deletes a transcript buffer', function()
62 77 local bufnr = transcript.ensure 'work'
63 78 transcript.forget 'work'

neovim/tests/bugabinga/pivi/help_spec.lua

Modified
60 60 assert.is_true( sent:find( 'why does this look wrong', 1, true ) ~= nil )
61 61 end )
63 + it( 'shows what it is doing in its own window', function()
64 + local channel = fake.new()
65 + local run = help.ask( 'a question', { spawn = channel.spawn, } )
66 + local win = transcript.show( run.buffer )
68 + transcript.set_state( run.buffer, help.buffer_name, 'thinking' )
69 + assert.is_true( vim.wo[win].winbar:find( 'thinking', 1, true ) ~= nil )
71 + channel.frame {
72 + type = 'tool_execution_start',
73 + toolCallId = 'c1',
74 + toolName = 'nvim_help',
75 + args = { tag = 'quickfix', },
76 + }
77 + channel.flush()
79 + assert.is_true( vim.wo[win].winbar:find( 'quickfix', 1, true ) ~= nil )
80 + assert.is_true( vim.list_contains( transcript.lines( run.buffer ), ' ▸ nvim_help quickfix' ) )
82 + channel.frame { type = 'agent_settled', }
83 + channel.flush()
85 + assert.is_nil( vim.wo[win].winbar:find( 'quickfix', 1, true ) )
86 + assert.is_true( vim.wo[win].winbar:find( help.buffer_name, 1, true ) ~= nil )
87 + end )
89 + it( 'drops the blank lines a model opens with', function()
90 + local channel = fake.new()
91 + local run = help.ask( 'a question', { spawn = channel.spawn, } )
93 + channel.frame {
94 + type = 'message_update',
95 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = '\n\nUse :cnext.', },
96 + }
97 + channel.flush()
99 + assert.equal( 'Use :cnext.', run.answer )
100 + end )
63 102 it( 'can ask without any view', function()
64 103 local channel = fake.new()
65 104 help.ask( 'plain question', { spawn = channel.spawn, view = false, } )
100 139 assert.is_true( channel.settle( function() return finished ~= nil end ) )
101 140 assert.is_true( run.done )
102 - assert.is_true( channel.killed )
141 + -- The child is ended by closing its input, not by an immediate kill.
142 + assert.is_true( channel.stdin_closed )
105 145 it( 'answers while a working session runs, leaving it untouched', function()
144 184 channel.frame { id = id, type = 'response', command = 'prompt', success = false, error = 'help unavailable', }
146 186 assert.is_true( channel.settle( function() return run.done end ) )
147 - assert.is_true( vim.list_contains( transcript.lines( run.buffer ), '! help unavailable' ) )
187 + assert.is_true( vim.list_contains( transcript.lines( run.buffer ), ' ! help unavailable' ) )
148 188 assert.equal( 'running', working.status.connection )
149 189 assert.is_nil( working.status.error )

neovim/tests/bugabinga/pivi/rpc_spec.lua

Modified
140 140 assert.is_string( answer.error )
143 - it( 'closes stdin and terminates the child on stop', function()
143 + it( 'reports an unspawnable executable instead of raising', function()
144 + local exited = false
145 + local client = rpc.start {
146 + command = { 'definitely-not-a-real-program', },
147 + spawn = function() error 'ENOENT: no such file or directory' end,
148 + -- A process that never started reports no exit code.
149 + on_exit = function( code )
150 + exited = true
151 + assert.is_nil( code )
152 + end,
155 + assert.is_false( client.is_running() )
156 + assert.is_true( client.failure():find( 'ENOENT', 1, true ) ~= nil )
158 + local answer
159 + client.request( { type = 'prompt', message = 'hi', }, function( response ) answer = response end )
160 + assert.is_false( answer.success )
162 + -- Stopping a process that never started must be harmless.
163 + client.stop()
165 + assert.is_true( vim.wait( 2000, function() return exited end, 5 ) )
166 + end )
168 + it( 'closes stdin first so the child can exit on its own', function()
144 169 local channel = fake.new()
145 170 local client = start( channel )
146 172 client.stop()
147 174 assert.is_true( channel.stdin_closed )
148 - assert.is_true( channel.killed )
175 + -- Killing straight away would orphan the runtime behind a launcher shim.
176 + assert.is_false( channel.killed )
178 + channel.close( 0 )
179 + assert.is_true( channel.settle( function() return not client.is_running() end ) )
181 + vim.wait( 2500, function() return channel.killed end, 20 )
182 + assert.is_false( channel.killed )
183 + end )
185 + it( 'terminates a child that ignores a closed input', function()
186 + local channel = fake.new()
187 + local client = start( channel )
189 + client.stop()
191 + assert.is_true( vim.wait( 5000, function() return channel.killed end, 20 ) )

neovim/tests/bugabinga/pivi/runtime_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local runtime = require 'bugabinga.pivi.runtime'
4 +describe( 'pivi runtime', function()
5 + local original
7 + before_each( function()
8 + original = vim.g.pivi_executable
9 + end )
11 + after_each( function()
12 + vim.g.pivi_executable = original
13 + end )
15 + it( 'finds the assets pivi ships', function()
16 + assert.is_true( runtime.extension_path():find( 'index.ts', 1, true ) ~= nil )
17 + assert.is_true( runtime.client_path():find( 'client.lua', 1, true ) ~= nil )
18 + assert.is_true( runtime.skill_path():find( 'SKILL.md', 1, true ) ~= nil )
19 + end )
21 + it( 'lists install directories without holes', function()
22 + local directories = runtime.install_directories()
23 + assert.is_true( #directories > 0 )
25 + local counted = 0
26 + for _ in pairs( directories ) do counted = counted + 1 end
28 + -- A nil entry would end ipairs at the first index and hide every later directory.
29 + assert.equal( #directories, counted )
31 + for _, directory in ipairs( directories ) do
32 + assert.is_nil( directory:find( '\\', 1, true ) )
33 + end
34 + end )
36 + it( 'resolves pi to a path that can actually be spawned', function()
37 + vim.g.pivi_executable = nil
38 + local resolved, failure = runtime.executable()
40 + assert.is_nil( failure )
41 + assert.is_string( resolved )
42 + assert.is_true( resolved:lower():find( 'pi', 1, true ) ~= nil )
44 + local stat = vim.uv.fs_stat( resolved )
45 + assert.is_true( stat ~= nil or vim.fn.executable( resolved ) == 1 )
46 + end )
48 + it( 'reports a configured executable that does not exist', function()
49 + vim.g.pivi_executable = vim.fn.tempname() .. '-absent'
50 + local resolved, failure = runtime.executable()
52 + assert.is_nil( resolved )
53 + assert.is_true( failure:find( 'not found', 1, true ) ~= nil )
54 + end )
56 + it( 'accepts a configured executable that exists', function()
57 + local path = vim.fn.tempname() .. '.txt'
58 + vim.fn.writefile( { 'not really pi', }, path )
59 + vim.g.pivi_executable = path
61 + assert.equal( vim.fs.normalize( path ), runtime.executable() )
62 + end )
63 +end )

neovim/tests/bugabinga/pivi/session_spec.lua

Modified
14 14 options.name = options.name or 'spec'
15 15 options.extension = false
16 16 options.skill = false
17 + options.executable = options.executable or 'pi'
17 18 options.env = {}
18 19 return session.create( options )
66 67 assert.same( { 'spec', }, session.list() )
67 68 end )
69 - it( 'never strips the user\'s own pi configuration', function()
70 + it( 'resolves the pi executable to a real path', function()
70 71 local built = session.build_command {}
72 + local resolved = built[1]
74 + assert.is_true( resolved:lower():find( 'pi', 1, true ) ~= nil )
75 + -- A bare name would reach the spawner unresolved and fail on Windows.
76 + assert.equal( 1, vim.fn.executable( resolved ) )
77 + end )
79 + it( 'never strips the user\'s own pi configuration', function()
80 + local built = session.build_command { executable = 'pi', }
71 81 for _, flag in ipairs( STRIPPING_FLAGS ) do
72 82 assert.is_false( vim.list_contains( built, flag ) )
75 85 end )
77 87 it( 'adds only its companion extension and its skill to the user\'s pi', function()
78 - local plain = session.build_command { extension = false, skill = false, }
88 + local plain = session.build_command { extension = false, skill = false, executable = 'pi', }
79 89 assert.same( { 'pi', '--mode', 'rpc', }, plain )
81 - local built = session.build_command {}
91 + local built = session.build_command { executable = 'pi', }
82 92 for index = 4, #built, 2 do
83 93 local flag = built[index]
84 94 assert.is_true( flag == '-e' or flag == '--skill' )
170 180 end ) )
183 + it( 'writes no heading for a turn that only calls tools', function()
184 + local channel = fake.new()
185 + local current = create( channel )
187 + channel.frame { type = 'message_start', message = { role = 'assistant', }, }
188 + channel.frame { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'read', args = { path = 'greet.lua', }, }
189 + channel.frame { type = 'tool_execution_end', toolCallId = 'c1', toolName = 'read', isError = false, }
190 + channel.flush()
192 + local rendered = table.concat( transcript.lines( current.buffer ), '\n' )
193 + assert.is_nil( rendered:find( '## pi', 1, true ) )
194 + assert.is_true( rendered:find( 'read', 1, true ) ~= nil )
195 + end )
197 + it( 'writes one heading once real text arrives', function()
198 + local channel = fake.new()
199 + local current = create( channel )
201 + channel.frame { type = 'message_start', message = { role = 'assistant', }, }
202 + for _, piece in ipairs { 'all ', 'done', } do
203 + channel.frame {
204 + type = 'message_update',
205 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = piece, },
207 + end
208 + channel.flush()
210 + local lines = transcript.lines( current.buffer )
211 + local headings = 0
212 + for _, line in ipairs( lines ) do
213 + if line == '## pi' then headings = headings + 1 end
214 + end
216 + assert.equal( 1, headings )
217 + assert.is_true( vim.list_contains( lines, 'all done' ) )
218 + end )
220 + it( 'drops the blank lines a model opens with', function()
221 + local channel = fake.new()
222 + local current = create( channel )
224 + channel.frame { type = 'message_start', message = { role = 'assistant', }, }
225 + channel.frame {
226 + type = 'message_update',
227 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = '\n\nDone.', },
229 + channel.flush()
231 + local lines = transcript.lines( current.buffer )
232 + local heading
233 + for index, line in ipairs( lines ) do
234 + if line == '## pi' then heading = index end
235 + end
237 + assert.is_number( heading )
238 + assert.equal( 'Done.', lines[heading + 1] )
239 + end )
241 + it( 'ignores an empty text delta', function()
242 + local channel = fake.new()
243 + local current = create( channel )
245 + channel.frame { type = 'message_start', message = { role = 'assistant', }, }
246 + channel.frame {
247 + type = 'message_update',
248 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = '', },
250 + channel.flush()
252 + assert.is_nil(
253 + table.concat( transcript.lines( current.buffer ), '\n' ):find( '## pi', 1, true )
255 + end )
257 + it( 'names what a tool acts on, relative to the session directory', function()
258 + local channel = fake.new()
259 + local current = create( channel, { cwd = vim.uv.cwd(), } )
261 + channel.frame {
262 + type = 'tool_execution_start',
263 + toolCallId = 'c1',
264 + toolName = 'edit',
265 + args = { path = vim.fs.normalize( vim.uv.cwd() .. '/lua/deep/file.lua' ), },
267 + channel.flush()
269 + local rendered = table.concat( transcript.lines( current.buffer ), '\n' )
270 + assert.is_true( rendered:find( 'lua/deep/file.lua', 1, true ) ~= nil )
271 + assert.is_nil( rendered:find( vim.uv.cwd(), 1, true ) )
272 + end )
274 + it( 'marks a failed tool call', function()
275 + local channel = fake.new()
276 + local current = create( channel )
278 + channel.frame { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'read', args = {}, }
279 + channel.frame { type = 'tool_execution_end', toolCallId = 'c1', toolName = 'read', isError = true, }
280 + channel.flush()
282 + assert.is_true( vim.list_contains( transcript.lines( current.buffer ), ' failed' ) )
283 + end )
285 + it( 'quotes a multi-line submission line by line', function()
286 + local channel = fake.new()
287 + local current = create( channel )
289 + current.submit( 'first\nsecond', { capture = false, } )
291 + local lines = transcript.lines( current.buffer )
292 + assert.is_true( vim.list_contains( lines, '> first' ) )
293 + assert.is_true( vim.list_contains( lines, '> second' ) )
294 + end )
173 296 it( 'surfaces a rejected submission in the transcript', function()
174 297 local channel = fake.new()
175 298 local current = create( channel )
225 348 assert.same( {}, session.list() )
226 349 assert.is_nil( publish.read().sessions.spec )
227 - assert.is_true( channel.killed )
350 + assert.is_true( channel.stdin_closed )
230 353 it( 'shows streaming edit intent without touching the buffer', function()
339 462 for _, frame in ipairs( fixture.frames 'rpc-tool-stream.jsonl' ) do
340 463 if frame.type == 'message_end' and frame.message and frame.message.role == 'assistant' then
341 464 for _, block in ipairs( frame.message.content or {} ) do
342 - if block.type == 'text' and block.text ~= '' then
343 - answered = answered or rendered:find( block.text:sub( 1, 12 ), 1, true ) ~= nil
465 + -- The transcript drops the blank lines a model opens with.
466 + local text = vim.trim( block.text or '' )
467 + if text ~= '' then
468 + answered = answered or rendered:find( text:sub( 1, 12 ), 1, true ) ~= nil

neovim/tests/bugabinga/pivi_status_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local statusline = require 'bugabinga.statusline'
3 +local publisher = require 'bugabinga.pivi.publish'
4 +local consumer = require 'bugabinga.pivi_status'
6 +local publish = function( value ) vim.g.pivi = value end
8 +local session = function( fields )
9 + return vim.tbl_extend( 'force', {
10 + name = 'work',
11 + connection = 'running',
12 + run = 'idle',
13 + queue = { steering = {}, follow_up = {}, },
14 + compacting = false,
15 + summary = 'pi:idle',
16 + }, fields or {} )
17 +end
19 +describe( 'pivi statusline consumer', function()
20 + after_each( function()
21 + vim.g.pivi = nil
22 + end )
24 + it( 'shows nothing when pivi never published anything', function()
25 + vim.g.pivi = nil
26 + assert.equal( '', consumer.component() )
27 + end )
29 + it( 'shows nothing for an unknown active session', function()
30 + publish { active = 'absent', sessions = {}, }
31 + assert.equal( '', consumer.component() )
32 + end )
34 + it( 'shows a quiet marker while idle', function()
35 + publish { active = 'work', sessions = { work = session(), }, }
36 + assert.equal( 'π', consumer.component() )
37 + end )
39 + it( 'animates and names the running tool', function()
40 + publish { active = 'work', sessions = {
41 + work = session { run = 'running', tool = { id = 'c1', name = 'edit', }, },
42 + }, }
44 + local shown = consumer.component()
45 + assert.is_true( shown:find( 'edit', 1, true ) ~= nil )
46 + assert.is_true( #shown > #'π edit' )
47 + end )
49 + it( 'reports thinking, retry, compaction, and error distinctly', function()
50 + local seen = {}
51 + for _, fields in ipairs {
52 + { run = 'running', },
53 + { run = 'retrying', },
54 + { compacting = true, },
55 + { error = 'boom', },
56 + } do
57 + publish { active = 'work', sessions = { work = session( fields ), }, }
58 + table.insert( seen, consumer.component() )
59 + end
61 + assert.is_true( seen[1]:find( 'thinking', 1, true ) ~= nil )
62 + assert.is_true( seen[2]:find( 'retry', 1, true ) ~= nil )
63 + assert.is_true( seen[3]:find( 'compacting', 1, true ) ~= nil )
64 + assert.is_true( seen[4]:find( 'error', 1, true ) ~= nil )
65 + end )
67 + it( 'counts queued submissions', function()
68 + publish { active = 'work', sessions = {
69 + work = session { queue = { steering = { 'a', }, follow_up = { 'b', 'c', }, }, },
70 + }, }
72 + assert.is_true( consumer.component():find( '+3', 1, true ) ~= nil )
73 + end )
75 + it( 'never treats a stopped session as busy', function()
76 + assert.is_false( consumer.busy( session { connection = 'stopped', run = 'running', } ) )
77 + end )
79 + it( 'announces findings that reached the quickfix list', function()
80 + local seen = {}
81 + local original = vim.notify
82 + vim.notify = function( message ) table.insert( seen, message ) end
84 + publisher.activity { kind = 'findings', count = 3, }
85 + publisher.activity { kind = 'findings', count = 0, }
86 + publisher.activity { kind = 'edit', }
88 + vim.notify = original
90 + assert.equal( 1, #seen )
91 + assert.is_true( seen[1]:find( '3 findings', 1, true ) ~= nil )
92 + end )
94 + it( 'is registered with the statusline and evaluates without pivi loaded', function()
95 + package.loaded['bugabinga.pivi'] = nil
96 + vim.g.pivi = nil
98 + local rendered = statusline.plugins_component()
100 + assert.is_string( rendered )
101 + assert.is_nil( package.loaded['bugabinga.pivi'] )
102 + end )
103 +end )

neovim/tests/contract/pi_rpc_spec.lua

Modified
15 15 local enabled = vim.env.PIVI_CONTRACT == '1' and vim.fn.executable 'pi' == 1
17 -local ask = function( commands, predicate, command_line )
18 - local frames = {}
19 - local client = rpc.start {
20 - command = command_line or { 'pi', '--mode', 'rpc', '--no-session', },
17 +-- Starting Pi with the user's full configuration is the expensive part, so one
18 +-- child per command line serves every question asked of it.
19 +local children = {}
21 +local child_for = function( label, command_line )
22 + if children[label] then return children[label] end
24 + local child = { frames = {}, }
25 + child.client = rpc.start {
26 + command = command_line,
21 27 cwd = vim.uv.cwd(),
22 - on_event = function( frame ) table.insert( frames, frame ) end,
23 - on_response = function( frame ) table.insert( frames, frame ) end,
28 + on_event = function( frame ) table.insert( child.frames, frame ) end,
29 + on_response = function( frame ) table.insert( child.frames, frame ) end,
31 + children[label] = child
32 + return child
33 +end
35 +local ask = function( commands, predicate, command_line )
36 + local child = child_for(
37 + command_line and 'help' or 'default',
38 + command_line or { 'pi', '--mode', 'rpc', '--no-session', }
39 + )
41 + local first = #child.frames + 1
25 42 for _, command in ipairs( commands ) do
26 - client.request( command )
43 + child.client.request( command )
28 - vim.wait( 60000, function() return predicate( frames ) end, 50 )
29 - client.stop()
30 - return frames
46 + local since = function()
47 + return vim.list_slice( child.frames, first, #child.frames )
48 + end
50 + vim.wait( 120000, function() return predicate( since() ) end, 50 )
51 + return since()
52 +end
54 +local shutdown = function()
55 + for _, child in pairs( children ) do
56 + child.client.stop()
57 + -- A child that outlives the run keeps the whole suite from exiting.
58 + vim.wait( 15000, function() return not child.client.is_running() end, 50 )
59 + end
60 + children = {}
33 63 local response_for = function( frames, name )
125 155 assert.is_string( runtime.skill_path() )
158 + after_each( function()
159 + -- Every question must be answerable by an already running child.
160 + for _, child in pairs( children ) do
161 + assert.is_true( child.client.is_running() )
162 + end
163 + end )
128 165 it( 'frames every record as strict line feed delimited JSON', function()
129 166 local frames = ask( { { type = 'get_state', }, }, function( seen )
130 167 return response_for( seen, 'get_state' ) ~= nil
136 173 assert.is_table( jsonl.parse( encoded ) )
177 + it( 'ends every child it started', function()
178 + shutdown()
179 + assert.same( {}, children )
180 + end )