repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(neovim): deliver pivi native pi integration

09f22af20584addf574d8c5366be4cb18bdbc3fa

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

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (43)

neovim/init.lua

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

neovim/justfile

Modified
25 25 test path="tests":
26 26 timeit { nvim --headless --noplugin -u tests/minimal_init.lua -c "PlenaryBustedDirectory {{ path }} {minimal_init = 'tests/minimal_init.lua'}" +q }
28 +# drive a live neovim over rpc and assert interactive behaviour
29 +drive:
30 + nvim --headless --clean -l tests/drive/run.lua
32 +# run the pi contract tests against a real `pi --mode rpc` child
33 +test-contract:
34 + with-env { PIVI_CONTRACT: "1" } { nvim --headless --noplugin -u tests/minimal_init.lua -c "PlenaryBustedDirectory tests/contract {minimal_init = 'tests/minimal_init.lua'}" +q }
28 36 # run manual tests
29 37 test-manual:
30 38 nvim -c "set rtp^=." -c "luafile tests/manual/input.lua"

neovim/lua/bugabinga/pivi/AGENTS.md

Added
new file mode 100644
1 +# pivi — testing rules
3 +pivi drives an external Pi process over JSONL RPC and mutates live buffers.
4 +Both properties break the usual "require the module, assert side effects" pattern.
5 +Follow these rules; they are load-bearing, not style.
7 +Spec: `.system/specs/NL-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md`.
8 +Research (Pi 0.85.1 / nvim 0.12 API facts): `.system/research/NL-RESEARCH-KZYYEFY_-pi-and-neovim-capabilities-for-pivi/index.md`.
10 +## Test layers
12 +| Layer | Scope | Where | Runs |
13 +| --- | --- | --- | --- |
14 +| L1 pure | framing, delta assembly, status reducer, partial-arg parser, snapshots | `tests/bugabinga/pivi/*_spec.lua` | every `just test` |
15 +| L2 fake transport | `pivi.rpc` fed scripted frames | `tests/bugabinga/pivi/rpc_spec.lua` | every `just test` |
16 +| L3 editor effects | real buffers, extmarks, undo, qf/loclist, windows | `tests/bugabinga/pivi/editor/*_spec.lua` | every `just test` |
17 +| L4 driven nvim | interactive/async behavior in a live nvim | `tests/drive/*.lua` | on demand |
18 +| L5 Pi contract | real `pi --mode rpc` assumptions | `tests/contract/*_spec.lua` | opt-in only |
19 +| L6 rendering | actual TUI pixels/layout | WezTerm pane capture | rare, manual |
21 +Most pivi code belongs in L1. If a bug can only be caught in L4+, the logic is in the wrong place.
23 +## Rules
25 +1. **Keep the core pure.** Parsing, assembly, and state transitions are `fn(state, frame) -> state, effects`. No `vim.api` inside them.
26 +2. **Inject the spawner.** `pivi.rpc` takes a `spawn` function; tests pass a fake. Never `rawset(vim, 'system', ...)` for pivi tests — pivi holds a long-lived process, and global monkeypatching leaks across specs.
27 +3. **Frame tests must include hostile input:** records split at arbitrary byte boundaries, trailing `\r`, `U+2028`/`U+2029` inside JSON strings, interleaved responses and events, unknown event types, stderr noise, child exit mid-stream.
28 +4. **Chunk-split fuzz is mandatory** for the decoder: replay one golden transcript under many random split points and assert an identical frame sequence.
29 +5. **Never sleep.** Use `vim.wait(ms, predicate)` or an RPC roundtrip as a flush barrier. A bare `vim.wait(200)` in a committed test is a bug.
30 +6. **Assert data, not screens,** except in L6.
31 +7. **Prove scheduling discipline.** Editor-facing callbacks assert `not vim.in_fast_event()`; RPC output callbacks run in fast contexts and must defer.
32 +8. **Ghost text must be provably inert:** feed incomplete tool arguments, assert `b:changedtick` is unchanged.
33 +9. **Undo coherence is a test, not a hope:** apply an edit, press `u` once, assert full revert; force the undo-join refusal path and assert the edit survives.
34 +10. **Namespace isolation is a test:** agent diagnostics/extmarks in pivi's own namespace, LSP namespaces untouched.
35 +11. **Clean up in `after_each`:** delete created buffers, clear namespaces, stop fake/real children, `package.loaded['bugabinga.pivi.*'] = nil`.
36 +12. **Consumers degrade:** at least one spec asserts a statusline/consumer works with pivi never loaded, and that status evaluation performs no RPC.
37 +13. **Fixtures come from reality.** Golden JSONL under `tests/fixtures/pivi/` is recorded from a real `pi --mode rpc` run, never hand-written from memory.
38 + Recorded so far: `rpc-no-llm.jsonl` (responses, no model call) and `rpc-provider-error.jsonl` (a real failed run).
39 + No streaming text or tool-call fixture exists yet: every configured provider refused a completion when these specs were written.
40 + Until one is recorded, delta-shaped events are constructed inside the spec that needs them, from Pi's documented `message_update` protocol, and the spec says so.
41 +14. **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.
43 +## Commands
45 +```
46 +just test
47 +just test tests/bugabinga/pivi
48 +just drive
49 +just test-contract
50 +```
52 +`just drive` starts its own headless server, connects with
53 +`vim.fn.sockconnect('tcp', address, { rpc = true })`, and drives it with
54 +`vim.rpcrequest(channel, 'nvim_exec_lua' | 'nvim_input' | 'nvim_get_mode', ...)`.
55 +Requests are synchronous, so scenarios need no sleeps.
56 +Add scenarios to `tests/drive/run.lua`.
58 +## Gotchas
60 +- 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.
61 +- `nvim --server ... --remote-expr` / `--remote-send` is unusable on win32 here: it spawns a TUI and swallows stdout. Use socket RPC.
62 +- A headless server has no UI, so `screenstring()` and friends are meaningless. Grid truth requires a real UI client or a WezTerm capture.
63 +- Overriding a built-in Pi tool requires matching its exact result and `details` shape; prefer injecting operations over reimplementing the tool, and assert the shape in a contract test.
64 +- A plain `prompt` while Pi is streaming is rejected; every submission path must choose steering or follow-up explicitly and a test must cover the rejection.
65 +- `:Pi help` must spawn its own session-less run; assert the working session's history, queue, and status are untouched.
67 +## Module conventions
69 +Follow `neovim/AGENTS.md`: no `local M = {}`, snake_case files, `*_spec.lua` mirroring source paths.
70 +Test-visible entry points use the `_G.BugabingaPivi` global; library submodules do not.

neovim/lua/bugabinga/pivi/activity.lua

Added
new file mode 100644
1 +local publish = require 'bugabinga.pivi.publish'
3 +local TRAIL_NAMESPACE = 'pivi-trail'
4 +local GHOST_NAMESPACE = 'pivi-ghost'
5 +local DIAGNOSTIC_NAMESPACE = 'pivi-diagnostic'
6 +local SIGN_GROUP = 'pivi'
8 +local namespaces = {}
10 +local namespace = function( name )
11 + if not namespaces[name] then
12 + namespaces[name] = vim.api.nvim_create_namespace( name )
13 + end
14 + return namespaces[name]
15 +end
17 +local diagnostic_namespace = function() return namespace( DIAGNOSTIC_NAMESPACE ) end
19 +local trail = {}
21 +--- Marks changed lines so the agent's work stays navigable.
22 +--- Marks live in pivi's own namespace and never touch diagnostic or
23 +--- language server namespaces.
24 +local mark_edit = function( bufnr, ranges )
25 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
26 + local ns = namespace( TRAIL_NAMESPACE )
27 + for _, range in ipairs( ranges or {} ) do
28 + local first = math.max( 0, range.first )
29 + local last = math.max( first + 1, range.last )
30 + local count = vim.api.nvim_buf_line_count( bufnr )
31 + for line = first, math.min( last, count ) - 1 do
32 + pcall( vim.api.nvim_buf_set_extmark, bufnr, ns, line, 0, {
33 + line_hl_group = 'DiffChange',
34 + sign_text = '│',
35 + sign_hl_group = 'DiffChange',
36 + priority = 90,
37 + } )
38 + end
39 + table.insert( trail, { buffer = bufnr, first = first + 1, last = math.min( last, count ), } )
40 + end
41 + publish.activity { kind = 'edit', buffer = bufnr, ranges = ranges, }
42 +end
44 +local marks = function( bufnr )
45 + if not vim.api.nvim_buf_is_valid( bufnr ) then return {} end
46 + return vim.api.nvim_buf_get_extmarks( bufnr, namespace( TRAIL_NAMESPACE ), 0, -1, {} )
47 +end
49 +local clear_trail = function( bufnr )
50 + if bufnr and vim.api.nvim_buf_is_valid( bufnr ) then
51 + vim.api.nvim_buf_clear_namespace( bufnr, namespace( TRAIL_NAMESPACE ), 0, -1 )
52 + end
53 + trail = {}
54 +end
56 +local trail_entries = function() return vim.deepcopy( trail ) end
58 +--- Shows streaming edit intent without touching buffer contents.
59 +local ghost = function( bufnr, line, text )
60 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
61 + if type( text ) ~= 'string' or text == '' then return end
62 + local ns = namespace( GHOST_NAMESPACE )
63 + local count = vim.api.nvim_buf_line_count( bufnr )
64 + local target = math.min( math.max( 0, line ), math.max( 0, count - 1 ) )
65 + vim.api.nvim_buf_clear_namespace( bufnr, ns, 0, -1 )
66 + local chunks = {}
67 + for _, piece in ipairs( vim.split( text, '\n', { plain = true, } ) ) do
68 + table.insert( chunks, { { piece, 'Comment', }, } )
69 + end
70 + pcall( vim.api.nvim_buf_set_extmark, bufnr, ns, target, 0, {
71 + virt_lines = chunks,
72 + virt_lines_above = false,
73 + priority = 100,
74 + } )
75 +end
77 +local ghost_marks = function( bufnr )
78 + if not vim.api.nvim_buf_is_valid( bufnr ) then return {} end
79 + return vim.api.nvim_buf_get_extmarks( bufnr, namespace( GHOST_NAMESPACE ), 0, -1, {} )
80 +end
82 +local ghost_clear = function( bufnr )
83 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
84 + vim.api.nvim_buf_clear_namespace( bufnr, namespace( GHOST_NAMESPACE ), 0, -1 )
85 +end
87 +local to_quickfix_item = function( item )
88 + return {
89 + filename = item.path,
90 + bufnr = item.path and nil or item.buffer,
91 + lnum = item.line or 1,
92 + col = ( item.column or 0 ) + 1,
93 + text = item.text or '',
94 + type = item.severity == 'error' and 'E' or item.severity == 'warning' and 'W' or 'I',
95 + }
96 +end
98 +--- Cross-file findings use the quickfix list.
99 +local findings = function( items, title )
100 + local entries = vim.tbl_map( to_quickfix_item, items or {} )
101 + vim.fn.setqflist( {}, ' ', { title = title or 'pivi', items = entries, } )
102 + publish.activity { kind = 'findings', count = #entries, }
103 + return entries
104 +end
106 +--- Window associated findings use the location list.
107 +local window_findings = function( win, items, title )
108 + local entries = vim.tbl_map( to_quickfix_item, items or {} )
109 + vim.fn.setloclist( win or 0, {}, ' ', { title = title or 'pivi', items = entries, } )
110 + return entries
111 +end
113 +local severity_of = function( value )
114 + if value == 'error' then return vim.diagnostic.severity.ERROR end
115 + if value == 'warning' then return vim.diagnostic.severity.WARN end
116 + if value == 'hint' then return vim.diagnostic.severity.HINT end
117 + return vim.diagnostic.severity.INFO
118 +end
120 +--- Agent diagnostics stay distinguishable from compiler and language server output.
121 +local diagnose = function( bufnr, items )
122 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
123 + local diagnostics = {}
124 + for _, item in ipairs( items or {} ) do
125 + table.insert( diagnostics, {
126 + lnum = math.max( 0, ( item.line or 1 ) - 1 ),
127 + col = item.column or 0,
128 + message = item.text or '',
129 + severity = severity_of( item.severity ),
130 + source = 'pi',
131 + } )
132 + end
133 + vim.diagnostic.set( diagnostic_namespace(), bufnr, diagnostics )
134 +end
136 +local diagnostics = function( bufnr )
137 + return vim.diagnostic.get( bufnr, { namespace = diagnostic_namespace(), } )
138 +end
140 +local clear_diagnostics = function( bufnr )
141 + vim.diagnostic.reset( diagnostic_namespace(), bufnr )
142 +end
144 +local clear_all = function( bufnr )
145 + ghost_clear( bufnr )
146 + clear_trail( bufnr )
147 + clear_diagnostics( bufnr )
148 +end
150 +return {
151 + sign_group = SIGN_GROUP,
152 + namespace = namespace,
153 + trail_namespace = TRAIL_NAMESPACE,
154 + ghost_namespace = GHOST_NAMESPACE,
155 + diagnostic_namespace = diagnostic_namespace,
156 + mark_edit = mark_edit,
157 + marks = marks,
158 + trail = trail_entries,
159 + clear_trail = clear_trail,
160 + ghost = ghost,
161 + ghost_marks = ghost_marks,
162 + ghost_clear = ghost_clear,
163 + findings = findings,
164 + window_findings = window_findings,
165 + diagnose = diagnose,
166 + diagnostics = diagnostics,
167 + clear_diagnostics = clear_diagnostics,
168 + clear_all = clear_all,

neovim/lua/bugabinga/pivi/assemble.lua

Added
new file mode 100644
1 +local TEXT = 'text'
2 +local THINKING = 'thinking'
3 +local TOOL_CALL = 'toolcall'
5 +local new = function()
6 + return {
7 + parts = {},
8 + order = {},
9 + complete = false,
10 + }
11 +end
13 +local part_at = function( state, index, kind )
14 + local part = state.parts[index]
15 + if not part then
16 + part = { kind = kind, index = index, text = '', }
17 + state.parts[index] = part
18 + table.insert( state.order, index )
19 + table.sort( state.order )
20 + end
21 + return part
22 +end
24 +local ordered_parts = function( state )
25 + local parts = {}
26 + for _, index in ipairs( state.order ) do
27 + table.insert( parts, state.parts[index] )
28 + end
29 + return parts
30 +end
32 +local from_message = function( message )
33 + local state = new()
34 + local content = message and message.content
35 + if type( content ) ~= 'table' then return state end
36 + for offset, block in ipairs( content ) do
37 + local index = offset - 1
38 + if block.type == TEXT then
39 + local part = part_at( state, index, TEXT )
40 + part.text = block.text or ''
41 + elseif block.type == THINKING then
42 + local part = part_at( state, index, THINKING )
43 + part.text = block.thinking or ''
44 + elseif block.type == 'toolCall' then
45 + local part = part_at( state, index, TOOL_CALL )
46 + part.id = block.id
47 + part.name = block.name
48 + part.arguments = block.arguments
49 + part.complete = true
50 + end
51 + end
52 + state.complete = true
53 + return state
54 +end
56 +--- Applies one streaming delta to the assembled message state.
57 +--- `message_end` is authoritative and replaces everything accumulated so far.
58 +--- @param state table assembled state
59 +--- @param event table one RPC event
60 +--- @return table state the updated assembled state
61 +local apply = function( state, event )
62 + if type( event ) ~= 'table' then return state end
64 + if event.type == 'message_start' then
65 + if event.message and event.message.role ~= 'assistant' then return state end
66 + return new()
67 + end
69 + if event.type == 'message_end' then
70 + if event.message and event.message.role ~= 'assistant' then return state end
71 + return from_message( event.message )
72 + end
74 + if event.type ~= 'message_update' then return state end
76 + local delta = event.assistantMessageEvent
77 + if type( delta ) ~= 'table' then return state end
79 + local index = delta.contentIndex or 0
81 + if delta.type == 'text_start' then
82 + part_at( state, index, TEXT )
83 + elseif delta.type == 'text_delta' then
84 + local part = part_at( state, index, TEXT )
85 + part.text = part.text .. ( delta.delta or '' )
86 + elseif delta.type == 'text_end' then
87 + local part = part_at( state, index, TEXT )
88 + if delta.content then part.text = delta.content end
89 + elseif delta.type == 'thinking_start' then
90 + part_at( state, index, THINKING )
91 + elseif delta.type == 'thinking_delta' then
92 + local part = part_at( state, index, THINKING )
93 + part.text = part.text .. ( delta.delta or '' )
94 + elseif delta.type == 'thinking_end' then
95 + local part = part_at( state, index, THINKING )
96 + if delta.content then part.text = delta.content end
97 + elseif delta.type == 'toolcall_start' then
98 + local part = part_at( state, index, TOOL_CALL )
99 + part.id = delta.id
100 + part.name = delta.toolName
101 + elseif delta.type == 'toolcall_delta' then
102 + local part = part_at( state, index, TOOL_CALL )
103 + part.text = part.text .. ( delta.delta or '' )
104 + elseif delta.type == 'toolcall_end' then
105 + local part = part_at( state, index, TOOL_CALL )
106 + local call = delta.toolCall
107 + if call then
108 + part.id = call.id or part.id
109 + part.name = call.name or part.name
110 + part.arguments = call.arguments
111 + end
112 + part.complete = true
113 + end
115 + return state
116 +end
118 +--- @return string text visible assistant text, thinking excluded
119 +local text = function( state )
120 + local pieces = {}
121 + for _, part in ipairs( ordered_parts( state ) ) do
122 + if part.kind == TEXT then table.insert( pieces, part.text ) end
123 + end
124 + return table.concat( pieces )
125 +end
127 +--- @return string thinking accumulated reasoning text
128 +local thinking = function( state )
129 + local pieces = {}
130 + for _, part in ipairs( ordered_parts( state ) ) do
131 + if part.kind == THINKING then table.insert( pieces, part.text ) end
132 + end
133 + return table.concat( pieces )
134 +end
136 +--- @return table[] calls tool calls in content order
137 +local tool_calls = function( state )
138 + local calls = {}
139 + for _, part in ipairs( ordered_parts( state ) ) do
140 + if part.kind == TOOL_CALL then
141 + table.insert( calls, {
142 + index = part.index,
143 + id = part.id,
144 + name = part.name,
145 + arguments = part.arguments,
146 + arguments_text = part.text,
147 + complete = part.complete == true,
148 + } )
149 + end
150 + end
151 + return calls
152 +end
154 +return {
155 + new = new,
156 + apply = apply,
157 + text = text,
158 + thinking = thinking,
159 + tool_calls = tool_calls,

neovim/lua/bugabinga/pivi/bridge.lua

Added
new file mode 100644
1 +local edit = require 'bugabinga.pivi.edit'
2 +local context = require 'bugabinga.pivi.context'
3 +local activity = require 'bugabinga.pivi.activity'
5 +local failure = function( message )
6 + return { ok = false, error = tostring( message ), }
7 +end
9 +local ensure_buffer = function( path )
10 + local bufnr = edit.buffer_for( path )
11 + if bufnr then return bufnr, true end
12 + return nil, false
13 +end
15 +local actions = {}
17 +--- Loaded buffers, including unsaved content, win over disk.
18 +actions.read = function( request )
19 + if type( request.path ) ~= 'string' then return failure 'path is required' end
20 + local content, source = edit.read( request.path )
21 + if content == nil then return failure( 'cannot read ' .. request.path ) end
22 + return { ok = true, content = content, source = source, }
23 +end
25 +actions.write = function( request )
26 + if type( request.path ) ~= 'string' then return failure 'path is required' end
27 + if type( request.content ) ~= 'string' then return failure 'content is required' end
29 + local bufnr = ensure_buffer( request.path )
30 + if not bufnr then
31 + local ok, problem = pcall( vim.fn.writefile, vim.split( request.content, '\n', { plain = true, } ), request.path )
32 + if not ok then return failure( problem ) end
33 + return { ok = true, source = 'disk', }
34 + end
36 + local applied, joined = edit.apply( bufnr, { {
37 + first = 0,
38 + last = -1,
39 + lines = vim.split( request.content, '\n', { plain = true, } ),
40 + }, } )
41 + if not applied then return failure 'buffer write failed' end
42 + local persisted = edit.persist( bufnr )
43 + return { ok = true, source = 'buffer', joined = joined, persisted = persisted, }
44 +end
46 +actions.edit = function( request )
47 + if type( request.path ) ~= 'string' then return failure 'path is required' end
48 + if type( request.old_text ) ~= 'string' then return failure 'old_text is required' end
49 + if type( request.new_text ) ~= 'string' then return failure 'new_text is required' end
51 + local bufnr = ensure_buffer( request.path )
52 + if not bufnr then
53 + local content = edit.read( request.path )
54 + if content == nil then return failure( 'cannot read ' .. request.path ) end
55 + local first = content:find( request.old_text, 1, true )
56 + if not first then return failure 'old_text not found' end
57 + local replaced = content:sub( 1, first - 1 ) .. request.new_text .. content:sub( first + #request.old_text )
58 + local ok, problem = pcall( vim.fn.writefile, vim.split( replaced, '\n', { plain = true, } ), request.path )
59 + if not ok then return failure( problem ) end
60 + return { ok = true, source = 'disk', }
61 + end
63 + local applied, problem = edit.replace( bufnr, request.old_text, request.new_text )
64 + if not applied then return failure( problem ) end
65 + local persisted = edit.persist( bufnr )
66 + return { ok = true, source = 'buffer', joined = problem, persisted = persisted, }
67 +end
69 +actions.state = function()
70 + return { ok = true, state = context.editor(), }
71 +end
73 +actions.lua = function( request )
74 + if type( request.code ) ~= 'string' then return failure 'code is required' end
75 + local chunk, problem = loadstring( request.code, 'pivi' )
76 + if not chunk then return failure( problem ) end
77 + local ok, result = pcall( chunk )
78 + if not ok then return failure( result ) end
79 + return { ok = true, result = vim.inspect( result ), }
80 +end
82 +actions.findings = function( request )
83 + local entries = activity.findings( request.items, request.title )
84 + return { ok = true, count = #entries, }
85 +end
87 +actions.diagnostics = function( request )
88 + if type( request.path ) ~= 'string' then return failure 'path is required' end
89 + local bufnr = ensure_buffer( request.path )
90 + if not bufnr then return failure 'file is not loaded in a buffer' end
91 + activity.diagnose( bufnr, request.items )
92 + return { ok = true, count = #( request.items or {} ), }
93 +end
95 +--- Single entry point used by the companion Pi extension.
96 +--- @param request table action plus action specific fields
97 +local handle = function( request )
98 + if type( request ) ~= 'table' then return failure 'request must be a table' end
99 + local action = actions[request.action]
100 + if not action then return failure( 'unknown action: ' .. tostring( request.action ) ) end
101 + local ok, result = pcall( action, request )
102 + if not ok then return failure( result ) end
103 + return result
104 +end
106 +return {
107 + handle = handle,
108 + actions = actions,

neovim/lua/bugabinga/pivi/command.lua

Added
new file mode 100644
1 +local session = require 'bugabinga.pivi.session'
2 +local help = require 'bugabinga.pivi.help'
3 +local transcript = require 'bugabinga.pivi.transcript'
4 +local context = require 'bugabinga.pivi.context'
5 +local follow = require 'bugabinga.pivi.follow'
6 +local publish = require 'bugabinga.pivi.publish'
8 +local INPUT_FILETYPE = 'pivi-input'
10 +local notify = function( message, level )
11 + vim.notify( 'pivi: ' .. message, level or vim.log.levels.INFO )
12 +end
14 +local require_session = function()
15 + local current = session.active()
16 + if current then return current end
17 + return session.create {}
18 +end
20 +--- Decides whether `/` opens slash-command entry.
21 +--- Only a pivi input buffer with the cursor on the first character qualifies.
22 +--- @param bufnr number
23 +--- @param col number zero based cursor column
24 +local slash_opens_commands = function( bufnr, col )
25 + if not vim.api.nvim_buf_is_valid( bufnr ) then return false end
26 + if vim.bo[bufnr].filetype ~= INPUT_FILETYPE then return false end
27 + return col == 0
28 +end
30 +local fetch_commands = function( current, callback )
31 + current.request( { type = 'get_commands', }, function( response )
32 + local commands = {}
33 + if response.success and response.data then
34 + for _, entry in ipairs( response.data.commands or {} ) do
35 + table.insert( commands, entry )
36 + end
37 + end
38 + current.commands = commands
39 + if callback then callback( commands ) end
40 + end )
41 +end
43 +local run_slash_command = function( current, name, arguments )
44 + local message = '/' .. name
45 + if arguments and arguments ~= '' then message = message .. ' ' .. arguments end
46 + local accepted, rejection = current.submit( message, { capture = false, } )
47 + if not accepted then notify( rejection, vim.log.levels.WARN ) end
48 +end
50 +local pick_slash_command = function( current, on_pick )
51 + fetch_commands( current, function( commands )
52 + if #commands == 0 then
53 + notify( 'no pi commands available', vim.log.levels.WARN )
54 + return
55 + end
56 + vim.ui.select( commands, {
57 + prompt = 'pi command',
58 + format_item = function( entry )
59 + return '/' .. entry.name .. ( entry.description and ( ' ' .. entry.description ) or '' )
60 + end,
61 + }, function( choice )
62 + if not choice then return end
63 + on_pick( choice )
64 + end )
65 + end )
66 +end
68 +--- Opens a modifiable prompt buffer bound to a session.
69 +local open_prompt = function( current )
70 + local bufnr = vim.api.nvim_create_buf( false, true )
71 + vim.bo[bufnr].buftype = 'nofile'
72 + vim.bo[bufnr].bufhidden = 'wipe'
73 + vim.bo[bufnr].filetype = INPUT_FILETYPE
74 + vim.b[bufnr].pivi_session = current.name
76 + vim.keymap.set( { 'n', 'i', }, '/', function()
77 + local col = vim.api.nvim_win_get_cursor( 0 )[2]
78 + if not slash_opens_commands( bufnr, col ) then return '/' end
79 + vim.schedule( function()
80 + pick_slash_command( current, function( choice )
81 + run_slash_command( current, choice.name, nil )
82 + end )
83 + end )
84 + return ''
85 + end, { buffer = bufnr, expr = true, desc = 'pivi slash command entry', } )
87 + vim.keymap.set( { 'n', 'i', }, '<c-s>', function()
88 + local lines = vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
89 + local text = vim.trim( table.concat( lines, '\n' ) )
90 + if text == '' then return end
91 + local accepted, rejection = current.submit( text, { capture = false, } )
92 + if not accepted then
93 + notify( rejection, vim.log.levels.WARN )
94 + return
95 + end
96 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { '', } )
97 + end, { buffer = bufnr, desc = 'pivi submit prompt', } )
99 + if pcall( vim.cmd.split ) then
100 + local win = vim.api.nvim_get_current_win()
101 + vim.api.nvim_win_set_buf( win, bufnr )
102 + pcall( vim.api.nvim_win_set_height, win, 6 )
103 + end
104 + return bufnr
105 +end
107 +local submit_text = function( text, options )
108 + local current = require_session()
109 + local accepted, rejection = current.submit( text, options )
110 + if not accepted then
111 + notify( rejection, vim.log.levels.WARN )
112 + return false
113 + end
114 + transcript.show( current.buffer )
115 + return true
116 +end
118 +local subcommands = {}
120 +subcommands.ask = function( arguments, modifiers )
121 + if arguments == '' then
122 + notify( 'ask needs a question', vim.log.levels.WARN )
123 + return
124 + end
125 + local options = {}
126 + if modifiers and modifiers.range and modifiers.range > 0 then
127 + options.snapshot = context.snapshot { range = {
128 + kind = 'range',
129 + first = { modifiers.line1, 0, },
130 + last = { modifiers.line2, 0, },
131 + }, }
132 + end
133 + submit_text( arguments, options )
134 +end
136 +subcommands.steer = function( arguments )
137 + submit_text( arguments, { delivery = 'steer', } )
138 +end
140 +subcommands['follow-up'] = function( arguments )
141 + submit_text( arguments, { delivery = 'follow_up', } )
142 +end
144 +subcommands.help = function( arguments )
145 + if arguments == '' then
146 + notify( 'help needs a question', vim.log.levels.WARN )
147 + return
148 + end
149 + help.ask( arguments )
150 +end
152 +subcommands.command = function( arguments )
153 + local current = require_session()
154 + local name, rest = arguments:match '^(%S+)%s*(.*)$'
155 + if name then
156 + run_slash_command( current, name, rest )
157 + transcript.show( current.buffer )
158 + return
159 + end
160 + pick_slash_command( current, function( choice )
161 + run_slash_command( current, choice.name, nil )
162 + transcript.show( current.buffer )
163 + end )
164 +end
166 +subcommands.start = function( arguments )
167 + local created = session.create { name = arguments ~= '' and arguments or nil, }
168 + publish.set_active( created.name )
169 + transcript.show( created.buffer )
170 + notify( 'session ' .. created.name )
171 +end
173 +subcommands.stop = function( arguments )
174 + local target = arguments ~= '' and session.get( arguments ) or session.active()
175 + if not target then
176 + notify( 'no session', vim.log.levels.WARN )
177 + return
178 + end
179 + target.stop()
180 + notify( 'stopped ' .. target.name )
181 +end
183 +subcommands.sessions = function()
184 + local names = session.list()
185 + if #names == 0 then
186 + notify( 'no sessions', vim.log.levels.WARN )
187 + return
188 + end
189 + vim.ui.select( names, { prompt = 'pi session', }, function( choice )
190 + if not choice then return end
191 + session.set_active( choice )
192 + local chosen = session.get( choice )
193 + if chosen then transcript.show( chosen.buffer ) end
194 + end )
195 +end
197 +subcommands.show = function()
198 + local current = session.active()
199 + if not current then
200 + notify( 'no session', vim.log.levels.WARN )
201 + return
202 + end
203 + transcript.show( current.buffer )
204 +end
206 +subcommands.prompt = function()
207 + open_prompt( require_session() )
208 +end
210 +subcommands.abort = function()
211 + local current = session.active()
212 + if not current then
213 + notify( 'no session', vim.log.levels.WARN )
214 + return
215 + end
216 + current.abort()
217 +end
219 +subcommands.queue = function()
220 + local current = session.active()
221 + if not current then
222 + notify( 'no session', vim.log.levels.WARN )
223 + return
224 + end
225 + local queue = current.status.queue or {}
226 + local entries = {}
227 + for _, item in ipairs( queue.steering or {} ) do table.insert( entries, 'steer: ' .. item ) end
228 + for _, item in ipairs( queue.follow_up or {} ) do table.insert( entries, 'follow-up: ' .. item ) end
229 + if #entries == 0 then
230 + notify 'queue is empty'
231 + return
232 + end
233 + notify( table.concat( entries, '\n' ) )
234 +end
236 +subcommands.clear = function()
237 + local current = session.active()
238 + if not current then
239 + notify( 'no session', vim.log.levels.WARN )
240 + return
241 + end
242 + current.clear_queue( function() notify 'queue cleared' end )
243 +end
245 +subcommands.follow = function( arguments )
246 + follow.toggle( arguments ~= '' and arguments or nil )
247 + notify( 'follow ' .. ( follow.mode() or 'off' ) )
248 +end
250 +local names = function()
251 + local list = {}
252 + for key in pairs( subcommands ) do table.insert( list, key ) end
253 + table.sort( list )
254 + return list
255 +end
257 +local dispatch = function( options )
258 + local input = options.args or ''
259 + local name, rest = input:match '^(%S+)%s*(.*)$'
260 + if not name then
261 + subcommands.show()
262 + return
263 + end
264 + local handler = subcommands[name]
265 + if not handler then
266 + notify( 'unknown subcommand: ' .. name, vim.log.levels.ERROR )
267 + return
268 + end
269 + handler( rest or '', options )
270 +end
272 +local setup = function()
273 + vim.api.nvim_create_user_command( 'Pi', dispatch, {
274 + nargs = '*',
275 + range = true,
276 + desc = 'pivi native Pi integration',
277 + complete = function( lead, line )
278 + local before = line:match '^%s*Pi%s+(%S*)$'
279 + if before == nil then return {} end
280 + return vim.tbl_filter( function( candidate )
281 + return candidate:sub( 1, #lead ) == lead
282 + end, names() )
283 + end,
284 + } )
286 + vim.keymap.set( 'n', '<Plug>(pivi-show)', function() subcommands.show() end, { desc = 'pivi show transcript', } )
287 + vim.keymap.set( 'n', '<Plug>(pivi-prompt)', function() subcommands.prompt() end, { desc = 'pivi open prompt', } )
288 + vim.keymap.set( 'n', '<Plug>(pivi-abort)', function() subcommands.abort() end, { desc = 'pivi abort run', } )
289 + vim.keymap.set( 'n', '<Plug>(pivi-follow)', function() subcommands.follow '' end, { desc = 'pivi toggle follow', } )
290 +end
292 +return {
293 + input_filetype = INPUT_FILETYPE,
294 + setup = setup,
295 + dispatch = dispatch,
296 + subcommands = subcommands,
297 + names = names,
298 + slash_opens_commands = slash_opens_commands,
299 + open_prompt = open_prompt,

neovim/lua/bugabinga/pivi/context.lua

Added
new file mode 100644
1 +local SURROUNDING_LINES = 40
3 +local freeze = function( value )
4 + if type( value ) ~= 'table' then return value end
5 + return setmetatable( {}, {
6 + __index = value,
7 + __newindex = function() error 'pivi context snapshots are immutable' end,
8 + __len = function() return #value end,
9 + __pairs = function() return pairs( value ) end,
10 + } )
11 +end
13 +local function deep_freeze( value )
14 + if type( value ) ~= 'table' then return value end
15 + local frozen = {}
16 + for key, item in pairs( value ) do
17 + frozen[key] = deep_freeze( item )
18 + end
19 + return freeze( frozen )
20 +end
22 +--- Resolves the current or last visual selection into a line and column range.
23 +local selection_range = function()
24 + local mode = vim.api.nvim_get_mode().mode
25 + local visual = mode:sub( 1, 1 ) == 'v' or mode:sub( 1, 1 ) == 'V' or mode:sub( 1, 1 ) == '\22'
26 + local start_position = vim.fn.getpos( visual and 'v' or "'<" )
27 + local end_position = vim.fn.getpos( visual and '.' or "'>" )
28 + if start_position[2] == 0 or end_position[2] == 0 then return nil end
29 + local first = { start_position[2], start_position[3] - 1, }
30 + local last = { end_position[2], end_position[3] - 1, }
31 + if first[1] > last[1] or ( first[1] == last[1] and first[2] > last[2] ) then
32 + first, last = last, first
33 + end
34 + return {
35 + kind = visual and mode or 'mark',
36 + first = first,
37 + last = last,
38 + }
39 +end
41 +local text_between = function( bufnr, range )
42 + local lines = vim.api.nvim_buf_get_lines( bufnr, range.first[1] - 1, range.last[1], false )
43 + return table.concat( lines, '\n' )
44 +end
46 +--- Captures an immutable snapshot of the submission's originating editor state.
47 +--- @param source table? bufnr and window override
48 +local snapshot = function( source )
49 + source = source or {}
50 + local bufnr = source.bufnr or vim.api.nvim_get_current_buf()
51 + if not vim.api.nvim_buf_is_valid( bufnr ) then return nil end
52 + if vim.bo[bufnr].buftype ~= '' and vim.bo[bufnr].buftype ~= 'acwrite' then return nil end
54 + local win = source.win or vim.api.nvim_get_current_win()
55 + local cursor = { 1, 0, }
56 + if vim.api.nvim_win_is_valid( win ) and vim.api.nvim_win_get_buf( win ) == bufnr then
57 + cursor = vim.api.nvim_win_get_cursor( win )
58 + end
60 + local total = vim.api.nvim_buf_line_count( bufnr )
61 + local first = math.max( 1, cursor[1] - math.floor( SURROUNDING_LINES / 2 ) )
62 + local last = math.min( total, first + SURROUNDING_LINES - 1 )
63 + local surrounding = table.concat( vim.api.nvim_buf_get_lines( bufnr, first - 1, last, false ), '\n' )
65 + local range = source.range
66 + local selected
67 + if range then selected = text_between( bufnr, range ) end
69 + return deep_freeze {
70 + buffer = bufnr,
71 + path = vim.api.nvim_buf_get_name( bufnr ),
72 + filetype = vim.bo[bufnr].filetype,
73 + revision = vim.api.nvim_buf_get_changedtick( bufnr ),
74 + modified = vim.bo[bufnr].modified,
75 + line_count = total,
76 + cursor = { cursor[1], cursor[2], },
77 + range = range,
78 + selection_kind = range and range.kind or nil,
79 + selected_text = selected,
80 + surrounding = surrounding,
81 + surrounding_first_line = first,
82 + surrounding_last_line = last,
83 + }
84 +end
86 +--- Renders a snapshot as a stable prompt preamble.
87 +local render = function( shot )
88 + if not shot then return '' end
89 + local lines = { '<editor-context>', }
90 + table.insert( lines, 'path: ' .. ( shot.path ~= '' and shot.path or '[No Name]' ) )
91 + table.insert( lines, 'revision: ' .. tostring( shot.revision ) )
92 + table.insert( lines, 'cursor: ' .. tostring( shot.cursor[1] ) .. ':' .. tostring( shot.cursor[2] ) )
93 + if shot.modified then table.insert( lines, 'unsaved: true' ) end
94 + if shot.selected_text then
95 + table.insert( lines, 'selection (' .. tostring( shot.selection_kind ) .. '):' )
96 + table.insert( lines, shot.selected_text )
97 + else
98 + table.insert( lines, 'around cursor (lines ' ..
99 + tostring( shot.surrounding_first_line ) .. '-' .. tostring( shot.surrounding_last_line ) .. '):' )
100 + table.insert( lines, shot.surrounding )
101 + end
102 + table.insert( lines, '</editor-context>' )
103 + table.insert( lines, '' )
104 + return table.concat( lines, '\n' )
105 +end
107 +--- Ambient core editor state, fetched on demand rather than attached to every prompt.
108 +local editor = function()
109 + local buffers = {}
110 + for _, bufnr in ipairs( vim.api.nvim_list_bufs() ) do
111 + if vim.api.nvim_buf_is_loaded( bufnr ) then
112 + table.insert( buffers, {
113 + buffer = bufnr,
114 + path = vim.api.nvim_buf_get_name( bufnr ),
115 + filetype = vim.bo[bufnr].filetype,
116 + modified = vim.bo[bufnr].modified,
117 + line_count = vim.api.nvim_buf_line_count( bufnr ),
118 + revision = vim.api.nvim_buf_get_changedtick( bufnr ),
119 + } )
120 + end
121 + end
123 + local windows = {}
124 + for _, win in ipairs( vim.api.nvim_list_wins() ) do
125 + table.insert( windows, {
126 + window = win,
127 + buffer = vim.api.nvim_win_get_buf( win ),
128 + cursor = vim.api.nvim_win_get_cursor( win ),
129 + tabpage = vim.api.nvim_win_get_tabpage( win ),
130 + } )
131 + end
133 + return {
134 + cwd = vim.uv.cwd(),
135 + mode = vim.api.nvim_get_mode().mode,
136 + current_buffer = vim.api.nvim_get_current_buf(),
137 + current_window = vim.api.nvim_get_current_win(),
138 + buffers = buffers,
139 + windows = windows,
141 +end
143 +return {
144 + snapshot = snapshot,
145 + render = render,
146 + editor = editor,
147 + selection_range = selection_range,

neovim/lua/bugabinga/pivi/dialog.lua

Added
new file mode 100644
1 +local publish = require 'bugabinga.pivi.publish'
3 +local NOTIFY_LEVELS = {
4 + info = vim.log.levels.INFO,
5 + warning = vim.log.levels.WARN,
6 + error = vim.log.levels.ERROR,
7 +}
9 +local widgets = {}
10 +local statuses = {}
12 +local value_response = function( id, value )
13 + if value == nil then
14 + return { type = 'extension_ui_response', id = id, cancelled = true, }
15 + end
16 + return { type = 'extension_ui_response', id = id, value = value, }
17 +end
19 +--- Maps one extension UI request to a native Neovim surface.
20 +--- Dialog methods answer with the request's own identifier; fire and forget
21 +--- methods answer with nothing.
22 +--- @param request table the `extension_ui_request` frame
23 +--- @param respond fun(response: table) sends an `extension_ui_response`
24 +--- @return boolean handled
25 +local handle = function( request, respond )
26 + if type( request ) ~= 'table' or request.type ~= 'extension_ui_request' then return false end
27 + local method = request.method
29 + if method == 'select' then
30 + vim.ui.select( request.options or {}, { prompt = request.title, }, function( choice )
31 + respond( value_response( request.id, choice ) )
32 + end )
33 + return true
34 + end
36 + if method == 'confirm' then
37 + local message = request.message and ( request.title .. '\n' .. request.message ) or request.title
38 + vim.ui.select( { 'yes', 'no', }, { prompt = message, }, function( choice )
39 + if choice == nil then
40 + respond { type = 'extension_ui_response', id = request.id, cancelled = true, }
41 + return
42 + end
43 + respond { type = 'extension_ui_response', id = request.id, confirmed = choice == 'yes', }
44 + end )
45 + return true
46 + end
48 + if method == 'input' then
49 + vim.ui.input( { prompt = request.title, default = request.placeholder, }, function( value )
50 + respond( value_response( request.id, value ) )
51 + end )
52 + return true
53 + end
55 + if method == 'editor' then
56 + vim.ui.input( { prompt = request.title, default = request.prefill, }, function( value )
57 + respond( value_response( request.id, value ) )
58 + end )
59 + return true
60 + end
62 + if method == 'notify' then
63 + vim.notify( request.message or '', NOTIFY_LEVELS[request.notifyType] or vim.log.levels.INFO )
64 + return true
65 + end
67 + if method == 'setStatus' then
68 + statuses[request.statusKey] = request.statusText
69 + publish.activity { kind = 'status', key = request.statusKey, text = request.statusText, }
70 + return true
71 + end
73 + if method == 'setWidget' then
74 + widgets[request.widgetKey] = request.widgetLines
75 + publish.activity { kind = 'widget', key = request.widgetKey, lines = request.widgetLines, }
76 + return true
77 + end
79 + if method == 'setTitle' then
80 + pcall( function() vim.o.titlestring = request.title or '' end )
81 + return true
82 + end
84 + if method == 'set_editor_text' then
85 + publish.activity { kind = 'editor_text', text = request.text, }
86 + return true
87 + end
89 + return false
90 +end
92 +local status_entries = function() return vim.deepcopy( statuses ) end
94 +local widget_entries = function() return vim.deepcopy( widgets ) end
96 +local reset = function()
97 + widgets = {}
98 + statuses = {}
99 +end
101 +return {
102 + handle = handle,
103 + statuses = status_entries,
104 + widgets = widget_entries,
105 + reset = reset,

neovim/lua/bugabinga/pivi/edit.lua

Added
new file mode 100644
1 +local activity = require 'bugabinga.pivi.activity'
3 +local is_file_buffer = function( bufnr )
4 + return vim.api.nvim_buf_is_valid( bufnr )
5 + and vim.bo[bufnr].buftype == ''
6 + and vim.api.nvim_buf_get_name( bufnr ) ~= ''
7 +end
9 +--- Finds the loaded buffer for a path, if any.
10 +local buffer_for = function( path )
11 + local wanted = vim.fs.normalize( vim.fn.fnamemodify( path, ':p' ) )
12 + for _, bufnr in ipairs( vim.api.nvim_list_bufs() ) do
13 + if vim.api.nvim_buf_is_loaded( bufnr ) then
14 + local name = vim.api.nvim_buf_get_name( bufnr )
15 + if name ~= '' and vim.fs.normalize( name ) == wanted then return bufnr end
16 + end
17 + end
18 + return nil
19 +end
21 +--- Reads authoritative content: the loaded buffer wins over disk.
22 +local read = function( path )
23 + local bufnr = buffer_for( path )
24 + if bufnr then
25 + return table.concat( vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ), '\n' ), 'buffer'
26 + end
27 + local ok, lines = pcall( vim.fn.readfile, path )
28 + if not ok then return nil, 'missing' end
29 + return table.concat( lines, '\n' ), 'disk'
30 +end
32 +--- Writes a loaded buffer to disk so later filesystem readers observe agent edits.
33 +--- pivi starts no filesystem watcher; visibility is part of the edit itself.
34 +local persist = function( bufnr )
35 + if not is_file_buffer( bufnr ) then return false end
36 + if not vim.bo[bufnr].modified then return true end
37 + local ok = pcall( vim.api.nvim_buf_call, bufnr, function()
38 + vim.cmd 'silent! noautocmd write'
39 + end )
40 + return ok and not vim.bo[bufnr].modified
41 +end
43 +--- Applies line replacements as one coherent undoable change.
44 +--- Replacements are zero based, end exclusive, and are applied bottom up.
45 +--- When Neovim refuses to join undo blocks the edit still lands.
46 +--- @return boolean applied
47 +--- @return boolean joined whether the change stayed a single undo block
48 +local apply = function( bufnr, replacements )
49 + vim.validate( 'bufnr', bufnr, 'number' )
50 + vim.validate( 'replacements', replacements, 'table' )
51 + if not vim.api.nvim_buf_is_valid( bufnr ) then return false, false end
53 + local ordered = vim.deepcopy( replacements )
54 + table.sort( ordered, function( left, right ) return left.first > right.first end )
56 + local joined = true
57 + local touched = {}
59 + for index, replacement in ipairs( ordered ) do
60 + if index > 1 then
61 + local ok = pcall( vim.api.nvim_buf_call, bufnr, function() vim.cmd.undojoin() end )
62 + if not ok then joined = false end
63 + end
64 + vim.api.nvim_buf_set_lines(
65 + bufnr,
66 + replacement.first,
67 + replacement.last,
68 + false,
69 + replacement.lines
70 + )
71 + table.insert( touched, {
72 + first = replacement.first,
73 + last = replacement.first + #replacement.lines,
74 + } )
75 + end
77 + activity.mark_edit( bufnr, touched )
78 + return true, joined
79 +end
81 +local find_text = function( content, needle )
82 + local first = content:find( needle, 1, true )
83 + if not first then return nil end
84 + local second = content:find( needle, first + 1, true )
85 + if second then return nil, 'text is not unique' end
86 + return first
87 +end
89 +--- Replaces one unique text occurrence in a loaded buffer.
90 +local replace = function( bufnr, old_text, new_text )
91 + vim.validate( 'old_text', old_text, 'string' )
92 + vim.validate( 'new_text', new_text, 'string' )
93 + if not vim.api.nvim_buf_is_valid( bufnr ) then return false, 'invalid buffer' end
95 + local lines = vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
96 + 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
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
104 + local applied, joined = apply( bufnr, { {
105 + first = 0,
106 + last = -1,
107 + lines = vim.split( replaced, '\n', { plain = true, } ),
108 + }, } )
110 + if applied then
111 + activity.mark_edit( bufnr, { { first = before - 1, last = after, }, } )
112 + end
113 + return applied, joined
114 +end
116 +return {
117 + buffer_for = buffer_for,
118 + is_file_buffer = is_file_buffer,
119 + read = read,
120 + persist = persist,
121 + apply = apply,
122 + replace = replace,

neovim/lua/bugabinga/pivi/extension/client.lua

Added
new file mode 100644
1 +-- Throwaway client used by the companion Pi extension.
2 +-- Usage: nvim --headless --clean -l client.lua <address> <request.json> <response.json>
4 +local address = arg[1]
5 +local request_path = arg[2]
6 +local response_path = arg[3]
8 +local write_response = function( value )
9 + vim.fn.writefile( { vim.json.encode( value ), }, response_path )
10 +end
12 +if not address or not request_path or not response_path then
13 + write_response { ok = false, error = 'client needs address, request path, and response path', }
14 + return
15 +end
17 +local ok, request = pcall( function()
18 + return vim.json.decode( table.concat( vim.fn.readfile( request_path ), '\n' ) )
19 +end )
21 +if not ok then
22 + write_response { ok = false, error = 'unreadable request: ' .. tostring( request ), }
23 + return
24 +end
26 +local kind = address:match '^[%w%.%-]+:%d+$' and 'tcp' or 'pipe'
28 +local connected, channel = pcall( vim.fn.sockconnect, kind, address, { rpc = true, } )
29 +if not connected or channel == 0 then
30 + write_response { ok = false, error = 'cannot reach neovim at ' .. address, }
31 + return
32 +end
34 +local answered, result = pcall(
35 + vim.rpcrequest,
36 + channel,
37 + 'nvim_exec_lua',
38 + 'return require("bugabinga.pivi.bridge").handle(...)',
39 + { request, }
42 +pcall( vim.fn.chanclose, channel )
44 +if not answered then
45 + write_response { ok = false, error = tostring( result ), }
46 + return
47 +end
49 +write_response( result )

neovim/lua/bugabinga/pivi/extension/index.ts

Added
new file mode 100644
1 +/**
2 + * pivi companion extension.
3 + *
4 + * Loaded additively when pivi starts Pi, alongside the user's normal Pi configuration.
5 + * It makes loaded Neovim buffers authoritative for built-in file tools by injecting
6 + * operations, so result and detail shapes stay exactly those of the built-in tools.
7 + * It also exposes the live editor: core state and unrestricted Lua execution.
8 + */
10 +import {
11 + createEditTool,
12 + createReadTool,
13 + createWriteTool,
14 + type EditOperations,
15 + type ExtensionAPI,
16 + type ReadOperations,
17 + type WriteOperations,
18 +} from "@earendil-works/pi-coding-agent";
19 +import { spawn } from "child_process";
20 +import { mkdtempSync, readFileSync, writeFileSync } from "fs";
21 +import { readFile, writeFile } from "fs/promises";
22 +import { tmpdir } from "os";
23 +import { dirname, join, resolve } from "path";
24 +import { fileURLToPath } from "url";
25 +import { Type } from "typebox";
27 +type BridgeResponse = {
28 + ok: boolean;
29 + error?: string;
30 + content?: string;
31 + source?: string;
32 + state?: unknown;
33 + result?: string;
34 + count?: number;
35 + persisted?: boolean;
36 + joined?: boolean;
37 +};
39 +const here = dirname(fileURLToPath(import.meta.url));
41 +const address = () => process.env.PIVI_NVIM_ADDRESS ?? "";
42 +const nvimExecutable = () => process.env.PIVI_NVIM_EXE ?? "nvim";
43 +const clientScript = () => process.env.PIVI_NVIM_CLIENT ?? join(here, "client.lua");
45 +/**
46 + * Talks to the Neovim instance that started this Pi process.
47 + * A throwaway headless Neovim performs the msgpack RPC call, so no protocol
48 + * implementation is duplicated here.
49 + */
50 +async function bridge(request: Record<string, unknown>): Promise<BridgeResponse> {
51 + const target = address();
52 + if (!target) return { ok: false, error: "no neovim address" };
54 + const directory = mkdtempSync(join(tmpdir(), "pivi-"));
55 + const requestPath = join(directory, "request.json");
56 + const responsePath = join(directory, "response.json");
57 + writeFileSync(requestPath, JSON.stringify(request), "utf8");
59 + const code = await new Promise<number>((done) => {
60 + const child = spawn(
61 + nvimExecutable(),
62 + ["--headless", "--clean", "-l", clientScript(), target, requestPath, responsePath],
63 + { stdio: "ignore" },
64 + );
65 + child.on("error", () => done(1));
66 + child.on("close", (status) => done(status ?? 1));
67 + });
69 + if (code !== 0) return { ok: false, error: "neovim client failed" };
71 + try {
72 + return JSON.parse(readFileSync(responsePath, "utf8")) as BridgeResponse;
73 + } catch (failure) {
74 + return { ok: false, error: String(failure) };
75 + }
78 +function bufferOperations(cwd: string): ReadOperations & WriteOperations & EditOperations {
79 + const absolute = (path: string) => resolve(cwd, path);
81 + return {
82 + readFile: async (path: string) => {
83 + const answer = await bridge({ action: "read", path: absolute(path) });
84 + if (answer.ok && answer.source === "buffer" && typeof answer.content === "string") {
85 + return Buffer.from(answer.content, "utf8");
86 + }
87 + return readFile(absolute(path));
88 + },
89 + access: async (path: string) => {
90 + const answer = await bridge({ action: "read", path: absolute(path) });
91 + if (answer.ok) return;
92 + await readFile(absolute(path));
93 + },
94 + writeFile: async (path: string, content: string) => {
95 + const answer = await bridge({ action: "write", path: absolute(path), content });
96 + if (answer.ok && answer.source === "buffer") return;
97 + await writeFile(absolute(path), content, "utf8");
98 + },
99 + };
102 +export default function (pi: ExtensionAPI) {
103 + const cwd = process.cwd();
104 + const operations = bufferOperations(cwd);
106 + const read = createReadTool(cwd, { operations });
107 + const write = createWriteTool(cwd, { operations });
108 + const edit = createEditTool(cwd, { operations });
110 + pi.registerTool({ ...read });
111 + pi.registerTool({ ...write });
112 + pi.registerTool({ ...edit });
114 + pi.registerTool({
115 + name: "nvim_state",
116 + label: "Neovim state",
117 + description:
118 + "Read live core Neovim state: working directory, mode, current buffer and window, loaded buffers with unsaved status, and window layout.",
119 + promptSnippet: "Inspect the live Neovim editor state",
120 + promptGuidelines: [
121 + "Use nvim_state when the answer depends on what the user currently has open, selected, or unsaved.",
122 + ],
123 + parameters: Type.Object({}),
124 + async execute() {
125 + const answer = await bridge({ action: "state" });
126 + if (!answer.ok) {
127 + return {
128 + content: [{ type: "text" as const, text: `Neovim unavailable: ${answer.error}` }],
129 + details: { error: true },
130 + };
132 + return {
133 + content: [{ type: "text" as const, text: JSON.stringify(answer.state, null, 2) }],
134 + details: { state: answer.state },
135 + };
136 + },
137 + });
139 + pi.registerTool({
140 + name: "nvim_lua",
141 + label: "Neovim Lua",
142 + description:
143 + "Execute arbitrary Lua inside the running Neovim instance and return the inspected result. Full editor access: buffers, selections, windows, tabs, marks, jumps, changes, lists, diagnostics, and commands.",
144 + promptSnippet: "Run Lua inside the running Neovim instance",
145 + promptGuidelines: [
146 + "Use nvim_lua for editor operations that no other tool covers, and prefer returning a value over printing.",
147 + ],
148 + parameters: Type.Object({
149 + code: Type.String({ description: "Lua chunk; return a value to receive it" }),
150 + }),
151 + async execute(_id, params: { code: string }) {
152 + const answer = await bridge({ action: "lua", code: params.code });
153 + if (!answer.ok) {
154 + return {
155 + content: [{ type: "text" as const, text: `Lua failed: ${answer.error}` }],
156 + details: { error: true },
157 + };
159 + return {
160 + content: [{ type: "text" as const, text: answer.result ?? "nil" }],
161 + details: { ok: true },
162 + };
163 + },
164 + });
166 + pi.registerTool({
167 + name: "nvim_findings",
168 + label: "Neovim findings",
169 + description:
170 + "Publish cross-file findings to the Neovim quickfix list so the user can navigate them with normal motions.",
171 + promptSnippet: "Publish findings to the Neovim quickfix list",
172 + promptGuidelines: ["Use nvim_findings when reporting several file locations the user should visit."],
173 + parameters: Type.Object({
174 + title: Type.Optional(Type.String()),
175 + items: Type.Array(
176 + Type.Object({
177 + path: Type.String(),
178 + line: Type.Optional(Type.Number()),
179 + column: Type.Optional(Type.Number()),
180 + text: Type.Optional(Type.String()),
181 + severity: Type.Optional(Type.String()),
182 + }),
183 + ),
184 + }),
185 + async execute(_id, params: { title?: string; items: unknown[] }) {
186 + const answer = await bridge({ action: "findings", title: params.title, items: params.items });
187 + if (!answer.ok) {
188 + return {
189 + content: [{ type: "text" as const, text: `Findings failed: ${answer.error}` }],
190 + details: { error: true },
191 + };
193 + return {
194 + content: [{ type: "text" as const, text: `Published ${answer.count} findings to the quickfix list.` }],
195 + details: { count: answer.count },
196 + };
197 + },
198 + });

neovim/lua/bugabinga/pivi/follow.lua

Added
new file mode 100644
1 +local MODES = { window = true, tab = true, current = true, }
3 +local state = {
4 + mode = nil,
5 + window = nil,
6 + tabpage = nil,
7 + origin = nil,
8 +}
10 +local mode = function() return state.mode end
12 +local set = function( value )
13 + if value == nil or value == 'off' then
14 + state.mode = nil
15 + return nil
16 + end
17 + if not MODES[value] then return state.mode end
18 + state.mode = value
19 + return state.mode
20 +end
22 +local toggle = function( value )
23 + if state.mode then return set( nil ) end
24 + return set( value or 'window' )
25 +end
27 +local remember_origin = function()
28 + local win = vim.api.nvim_get_current_win()
29 + state.origin = {
30 + window = win,
31 + buffer = vim.api.nvim_win_get_buf( win ),
32 + cursor = vim.api.nvim_win_get_cursor( win ),
33 + }
34 +end
36 +--- @return integer? window
37 +local ensure_window = function()
38 + if state.window and vim.api.nvim_win_is_valid( state.window ) then return state.window end
39 + local current = vim.api.nvim_get_current_win()
40 + if not pcall( vim.cmd.vsplit ) then return current end
41 + state.window = vim.api.nvim_get_current_win()
42 + vim.api.nvim_set_current_win( current )
43 + return state.window
44 +end
46 +--- @return integer? window
47 +local ensure_tab = function()
48 + if state.tabpage and vim.api.nvim_tabpage_is_valid( state.tabpage ) then
49 + local wins = vim.api.nvim_tabpage_list_wins( state.tabpage )
50 + if #wins > 0 then return wins[1] end
51 + end
52 + local current = vim.api.nvim_get_current_win()
53 + if not pcall( vim.cmd.tabnew ) then return current end
54 + state.tabpage = vim.api.nvim_get_current_tabpage()
55 + local win = vim.api.nvim_get_current_win()
56 + vim.api.nvim_set_current_win( current )
57 + return win
58 +end
60 +local resolve_buffer = function( location )
61 + if location.buffer and vim.api.nvim_buf_is_valid( location.buffer ) then return location.buffer end
62 + if not location.path or location.path == '' then return nil end
63 + return vim.fn.bufadd( location.path )
64 +end
66 +--- Follows a located agent event.
67 +--- Following is passive: it never steals the user's working window and
68 +--- never pollutes the jumplist.
69 +local to = function( location )
70 + if not state.mode then return nil end
71 + if type( location ) ~= 'table' then return nil end
73 + local bufnr = resolve_buffer( location )
74 + if not bufnr then return nil end
75 + vim.fn.bufload( bufnr )
77 + if not state.origin then remember_origin() end
79 + local target
80 + if state.mode == 'current' then
81 + target = vim.api.nvim_get_current_win()
82 + elseif state.mode == 'tab' then
83 + target = ensure_tab()
84 + else
85 + target = ensure_window()
86 + end
88 + if target == nil or not vim.api.nvim_win_is_valid( target ) then return nil end
90 + local previous = vim.api.nvim_get_current_win()
91 + vim.api.nvim_win_set_buf( target, bufnr )
92 + local count = vim.api.nvim_buf_line_count( bufnr )
93 + local line = math.min( math.max( 1, location.line or 1 ), count )
94 + pcall( vim.api.nvim_win_set_cursor, target, { line, location.column or 0, } )
95 + if state.mode ~= 'current' and vim.api.nvim_win_is_valid( previous ) then
96 + vim.api.nvim_set_current_win( previous )
97 + end
98 + return target
99 +end
101 +--- Returns to the location held before following began.
102 +local back = function()
103 + local origin = state.origin
104 + state.origin = nil
105 + if not origin then return false end
106 + if not vim.api.nvim_win_is_valid( origin.window ) then return false end
107 + vim.api.nvim_set_current_win( origin.window )
108 + if vim.api.nvim_buf_is_valid( origin.buffer ) then
109 + vim.api.nvim_win_set_buf( origin.window, origin.buffer )
110 + pcall( vim.api.nvim_win_set_cursor, origin.window, origin.cursor )
111 + end
112 + return true
113 +end
115 +local reset = function()
116 + if state.window and vim.api.nvim_win_is_valid( state.window ) then
117 + pcall( vim.api.nvim_win_close, state.window, true )
118 + end
119 + if state.tabpage and vim.api.nvim_tabpage_is_valid( state.tabpage ) then
120 + for _, win in ipairs( vim.api.nvim_tabpage_list_wins( state.tabpage ) ) do
121 + pcall( vim.api.nvim_win_close, win, true )
122 + end
123 + end
124 + state.mode = nil
125 + state.window = nil
126 + state.tabpage = nil
127 + state.origin = nil
128 +end
130 +local window = function() return state.window end
132 +return {
133 + modes = MODES,
134 + mode = mode,
135 + set = set,
136 + toggle = toggle,
137 + to = to,
138 + back = back,
139 + reset = reset,
140 + window = window,

neovim/lua/bugabinga/pivi/help.lua

Added
new file mode 100644
1 +local rpc = require 'bugabinga.pivi.rpc'
2 +local transcript = require 'bugabinga.pivi.transcript'
4 +local BUFFER_NAME = 'help'
6 +local ORIENTATION = table.concat( {
7 + 'You answer one short question about Neovim or about pivi, the native Neovim integration for Pi.',
8 + 'pivi runs Pi as a JSONL RPC child process and presents sessions, edits, and findings through native Neovim surfaces.',
9 + 'Answer directly and briefly. Do not modify files.',
10 +}, ' ' )
12 +local executable = function()
13 + return vim.g.pivi_executable or 'pi'
14 +end
16 +local build_command = function( options )
17 + local command = {
18 + executable(), '--mode', 'rpc',
19 + '--no-session',
20 + '--no-tools',
21 + '--append-system-prompt', ORIENTATION,
22 + }
23 + if options.model then
24 + table.insert( command, '--model' )
25 + table.insert( command, options.model )
26 + end
27 + for _, argument in ipairs( options.arguments or {} ) do
28 + table.insert( command, argument )
29 + end
30 + return command
31 +end
33 +--- Answers a question in an independent ephemeral run.
34 +--- It owns its own process, buffer, and lifetime, so no working session's
35 +--- history, queue, or status is touched.
36 +--- @param question string
37 +--- @param options table? model, arguments, spawn, on_done
38 +local ask = function( question, options )
39 + vim.validate( 'question', question, 'string' )
40 + options = options or {}
42 + local bufnr = transcript.ensure( BUFFER_NAME )
43 + transcript.clear( bufnr )
44 + transcript.line( bufnr, '? ' .. question )
45 + transcript.line( bufnr, '' )
47 + local run = { buffer = bufnr, done = false, answer = '', }
49 + run.client = rpc.start {
50 + command = build_command( options ),
51 + cwd = options.cwd or vim.uv.cwd(),
52 + spawn = options.spawn,
53 + on_event = function( event )
54 + if event.type == 'message_update' then
55 + local delta = event.assistantMessageEvent or {}
56 + if delta.type == 'text_delta' then
57 + run.answer = run.answer .. ( delta.delta or '' )
58 + transcript.append( bufnr, delta.delta or '' )
59 + end
60 + elseif event.type == 'message_end' and event.message and event.message.errorMessage then
61 + transcript.line( bufnr, '! ' .. tostring( event.message.errorMessage ) )
62 + elseif event.type == 'agent_settled' then
63 + run.done = true
64 + run.client.stop()
65 + if options.on_done then options.on_done( run ) end
66 + end
67 + end,
68 + on_exit = function()
69 + run.done = true
70 + end,
71 + }
73 + run.client.request( { type = 'prompt', message = question, }, function( response )
74 + if response.success then return end
75 + transcript.line( bufnr, '! ' .. tostring( response.error or 'help run rejected' ) )
76 + run.done = true
77 + run.client.stop()
78 + if options.on_done then options.on_done( run ) end
79 + end )
81 + transcript.show( bufnr )
82 + return run
83 +end
85 +return {
86 + buffer_name = BUFFER_NAME,
87 + orientation = ORIENTATION,
88 + build_command = build_command,
89 + ask = ask,

neovim/lua/bugabinga/pivi/init.lua

Added
new file mode 100644
1 +local session = require 'bugabinga.pivi.session'
2 +local help = require 'bugabinga.pivi.help'
3 +local command = require 'bugabinga.pivi.command'
4 +local status = require 'bugabinga.pivi.status'
5 +local publish = require 'bugabinga.pivi.publish'
6 +local transcript = require 'bugabinga.pivi.transcript'
7 +local activity = require 'bugabinga.pivi.activity'
8 +local edit = require 'bugabinga.pivi.edit'
9 +local follow = require 'bugabinga.pivi.follow'
10 +local dialog = require 'bugabinga.pivi.dialog'
11 +local context = require 'bugabinga.pivi.context'
12 +local bridge = require 'bugabinga.pivi.bridge'
14 +--- Reads cached status only. Safe to call from a statusline.
15 +local summary = function( name ) return publish.summary( name ) end
17 +local reset = function()
18 + session.stop_all()
19 + follow.reset()
20 + dialog.reset()
21 + transcript.forget_all()
22 + publish.reset()
23 +end
25 +_G.BugabingaPivi = {
26 + session = session,
27 + help = help,
28 + command = command,
29 + status = status,
30 + publish = publish,
31 + transcript = transcript,
32 + activity = activity,
33 + edit = edit,
34 + follow = follow,
35 + dialog = dialog,
36 + context = context,
37 + bridge = bridge,
38 + summary = summary,
39 + reset = reset,
42 +command.setup()
44 +return _G.BugabingaPivi

neovim/lua/bugabinga/pivi/jsonl.lua

Added
new file mode 100644
1 +local LF = '\n'
3 +local strip_carriage_return = function( record )
4 + if record:sub( -1 ) == '\r' then return record:sub( 1, -2 ) end
5 + return record
6 +end
8 +--- Creates a strict JSONL record splitter.
9 +--- Records are delimited by LF only. A trailing CR is stripped.
10 +--- Unicode line separators inside JSON strings never split a record.
11 +local new_splitter = function()
12 + local pending = ''
14 + --- @param chunk string? bytes received from the child process
15 + --- @return string[] records complete records contained in the chunk
16 + local feed = function( chunk )
17 + local records = {}
18 + if chunk == nil or chunk == '' then return records end
20 + pending = pending .. chunk
22 + while true do
23 + local index = pending:find( LF, 1, true )
24 + if not index then break end
25 + local record = strip_carriage_return( pending:sub( 1, index - 1 ) )
26 + pending = pending:sub( index + 1 )
27 + if record ~= '' then table.insert( records, record ) end
28 + end
30 + return records
31 + end
33 + --- @return string[] records the unterminated remainder, if any
34 + local finish = function()
35 + local remainder = strip_carriage_return( pending )
36 + pending = ''
37 + if remainder == '' then return {} end
38 + return { remainder, }
39 + end
41 + local buffered = function() return pending end
43 + return {
44 + feed = feed,
45 + finish = finish,
46 + buffered = buffered,
47 + }
48 +end
50 +--- @param record string one complete JSONL record
51 +--- @return table? value decoded object, or nil when the record is not a JSON object
52 +--- @return string? error decode failure description
53 +local parse = function( record )
54 + local ok, value = pcall( vim.json.decode, record, { luanil = { object = true, array = true, }, } )
55 + if not ok then return nil, tostring( value ) end
56 + if type( value ) ~= 'table' then return nil, 'record is not a JSON object' end
57 + return value, nil
58 +end
60 +return {
61 + splitter = new_splitter,
62 + parse = parse,

neovim/lua/bugabinga/pivi/partial.lua

Added
new file mode 100644
1 +local ESCAPES = {
2 + n = '\n',
3 + t = '\t',
4 + r = '\r',
5 + b = '\b',
6 + f = '\f',
7 + ['"'] = '"',
8 + ['\\'] = '\\',
9 + ['/'] = '/',
12 +local read_string = function( text, start )
13 + local pieces = {}
14 + local index = start
15 + local length = #text
16 + while index <= length do
17 + local char = text:sub( index, index )
18 + if char == '"' then
19 + return table.concat( pieces ), index + 1, true
20 + elseif char == '\\' then
21 + local escape = text:sub( index + 1, index + 1 )
22 + if escape == '' then break end
23 + if escape == 'u' then
24 + local code = text:sub( index + 2, index + 5 )
25 + if #code < 4 then break end
26 + local number = tonumber( code, 16 )
27 + if number then table.insert( pieces, vim.fn.nr2char( number ) ) end
28 + index = index + 6
29 + else
30 + table.insert( pieces, ESCAPES[escape] or escape )
31 + index = index + 2
32 + end
33 + else
34 + table.insert( pieces, char )
35 + index = index + 1
36 + end
37 + end
38 + return table.concat( pieces ), length + 1, false
39 +end
41 +--- Tolerantly reads string valued fields out of streaming tool arguments.
42 +--- The result is presentation only: an incomplete value never describes a
43 +--- validated edit, so callers must not mutate a buffer from it.
44 +--- @param text string accumulated argument bytes, possibly truncated mid token
45 +--- @return table result complete flag, decoded value when parseable, and partial fields
46 +local parse = function( text )
47 + if type( text ) ~= 'string' or text == '' then
48 + return { complete = false, value = nil, fields = {}, }
49 + end
51 + local ok, value = pcall( vim.json.decode, text, { luanil = { object = true, array = true, }, } )
52 + if ok and type( value ) == 'table' then
53 + local fields = {}
54 + for key, item in pairs( value ) do
55 + if type( item ) == 'string' then fields[key] = item end
56 + end
57 + return { complete = true, value = value, fields = fields, }
58 + end
60 + local fields = {}
61 + local index = 1
62 + local length = #text
63 + while index <= length do
64 + local key_start = text:find( '"', index, true )
65 + if not key_start then break end
66 + local key, after_key, closed = read_string( text, key_start + 1 )
67 + if not closed then break end
68 + local separator = text:find( '^%s*:%s*', after_key )
69 + if separator then
70 + local _, value_start = text:find( '^%s*:%s*', after_key )
71 + local first = text:sub( value_start + 1, value_start + 1 )
72 + if first == '"' then
73 + local item, after_value = read_string( text, value_start + 2 )
74 + fields[key] = item
75 + index = after_value
76 + else
77 + index = value_start + 1
78 + end
79 + else
80 + index = after_key
81 + end
82 + end
84 + return { complete = false, value = nil, fields = fields, }
85 +end
87 +--- Describes streaming edit intent for ghost presentation.
88 +local intent = function( tool_name, arguments_text )
89 + local result = parse( arguments_text )
90 + local fields = result.fields
91 + local path = fields.path or fields.file_path or fields.filePath
92 + local body = fields.new_text or fields.newText or fields.content or fields.text
93 + return {
94 + complete = result.complete,
95 + tool = tool_name,
96 + path = path,
97 + text = body,
98 + value = result.value,
99 + }
100 +end
102 +return {
103 + parse = parse,
104 + intent = intent,

neovim/lua/bugabinga/pivi/publish.lua

Added
new file mode 100644
1 +local status = require 'bugabinga.pivi.status'
3 +local VARIABLE = 'pivi'
4 +local EVENT = 'User'
5 +local STATUS_PATTERN = 'PiviStatus'
6 +local ACTIVITY_PATTERN = 'PiviActivity'
8 +local read = function()
9 + local value = vim.g[VARIABLE]
10 + if type( value ) ~= 'table' then return { active = nil, sessions = {}, } end
11 + value.sessions = value.sessions or {}
12 + return value
13 +end
15 +local write = function( value ) vim.g[VARIABLE] = value end
17 +local emit = function( pattern, data )
18 + pcall( vim.api.nvim_exec_autocmds, EVENT, { pattern = pattern, data = data, modeline = false, } )
19 +end
21 +--- Caches one session's semantic status and announces the change.
22 +--- Consumers read the cached variable; they never perform RPC.
23 +local session_status = function( name, state )
24 + vim.validate( 'name', name, 'string' )
25 + vim.validate( 'state', state, 'table' )
27 + local value = read()
28 + value.sessions[name] = {
29 + name = name,
30 + connection = state.connection,
31 + run = state.run,
32 + tool = state.tool,
33 + queue = state.queue,
34 + compacting = state.compacting,
35 + retry = state.retry,
36 + error = state.error,
37 + model = state.model,
38 + thinking = state.thinking,
39 + session = state.session,
40 + context = state.context,
41 + summary = status.summary( state ),
42 + }
43 + value.active = value.active or name
44 + write( value )
45 + emit( STATUS_PATTERN, { session = name, status = value.sessions[name], } )
46 +end
48 +local set_active = function( name )
49 + local value = read()
50 + value.active = name
51 + write( value )
52 + emit( STATUS_PATTERN, { session = name, status = value.sessions[name], } )
53 +end
55 +local remove = function( name )
56 + local value = read()
57 + value.sessions[name] = nil
58 + if value.active == name then
59 + value.active = next( value.sessions )
60 + end
61 + write( value )
62 + emit( STATUS_PATTERN, { session = name, status = nil, } )
63 +end
65 +local activity = function( payload )
66 + emit( ACTIVITY_PATTERN, payload )
67 +end
69 +--- Cached statusline text. Safe when pivi never started.
70 +local summary = function( name )
71 + local value = read()
72 + local key = name or value.active
73 + if not key then return '' end
74 + local entry = value.sessions[key]
75 + if not entry then return '' end
76 + return entry.summary or ''
77 +end
79 +local reset = function()
80 + write( { active = nil, sessions = {}, } )
81 +end
83 +return {
84 + variable = VARIABLE,
85 + status_pattern = STATUS_PATTERN,
86 + activity_pattern = ACTIVITY_PATTERN,
87 + read = read,
88 + session_status = session_status,
89 + set_active = set_active,
90 + remove = remove,
91 + activity = activity,
92 + summary = summary,
93 + reset = reset,

neovim/lua/bugabinga/pivi/rpc.lua

Added
new file mode 100644
1 +local jsonl = require 'bugabinga.pivi.jsonl'
3 +local next_request_id = 0
5 +local new_request_id = function()
6 + next_request_id = next_request_id + 1
7 + return 'pivi-' .. tostring( next_request_id )
8 +end
10 +local default_spawn = function( command, options )
11 + return vim.system( command, {
12 + cwd = options.cwd,
13 + env = options.env,
14 + stdin = true,
15 + text = true,
16 + stdout = options.stdout,
17 + stderr = options.stderr,
18 + }, options.on_exit )
19 +end
21 +--- Starts a Pi RPC child process.
22 +--- Output arrives in fast contexts, so every handler call is deferred through the main loop.
23 +--- @param options table command, cwd, spawn, on_event, on_response, on_stderr, on_exit, on_decode_error
24 +local start = function( options )
25 + vim.validate( 'options', options, 'table' )
26 + vim.validate( 'options.command', options.command, 'table' )
28 + local spawn = options.spawn or default_spawn
29 + local splitter = jsonl.splitter()
30 + local pending = {}
31 + local state = { running = true, exit_code = nil, }
33 + local failures = {}
35 + --- Handler failures never escape into the main loop, where a late error
36 + --- would raise a message prompt instead of failing a request.
37 + local guard = function( handler, ... )
38 + if not handler then return end
39 + local ok, failure = pcall( handler, ... )
40 + if not ok then table.insert( failures, tostring( failure ) ) end
41 + end
43 + local dispatch = function( records )
44 + if vim.in_fast_event() then
45 + table.insert( failures, 'dispatch ran in a fast event context' )
46 + return
47 + end
48 + for _, record in ipairs( records ) do
49 + local frame, decode_error = jsonl.parse( record )
50 + if not frame then
51 + guard( options.on_decode_error, record, decode_error )
52 + elseif frame.type == 'response' then
53 + local callback = frame.id and pending[frame.id]
54 + if callback then
55 + pending[frame.id] = nil
56 + guard( callback, frame )
57 + end
58 + guard( options.on_response, frame )
59 + else
60 + guard( options.on_event, frame )
61 + end
62 + end
63 + end
65 + local on_stdout = function( _, data )
66 + local records = splitter.feed( data )
67 + if #records == 0 then return end
68 + vim.schedule( function() dispatch( records ) end )
69 + end
71 + local on_stderr = function( _, data )
72 + if data == nil or data == '' then return end
73 + if not options.on_stderr then return end
74 + vim.schedule( function() guard( options.on_stderr, data ) end )
75 + end
77 + local on_exit = function( result )
78 + local trailing = splitter.finish()
79 + vim.schedule( function()
80 + state.running = false
81 + state.exit_code = result and result.code
82 + if #trailing > 0 then dispatch( trailing ) end
83 + for id, callback in pairs( pending ) do
84 + pending[id] = nil
85 + guard( callback, {
86 + id = id,
87 + type = 'response',
88 + success = false,
89 + error = 'pi process exited before responding',
90 + } )
91 + end
92 + guard( options.on_exit, state.exit_code )
93 + end )
94 + end
96 + local handle = spawn( options.command, {
97 + cwd = options.cwd,
98 + env = options.env,
99 + stdout = on_stdout,
100 + stderr = on_stderr,
101 + on_exit = on_exit,
102 + } )
104 + local send = function( command )
105 + if not state.running then return false, 'pi process is not running' end
106 + local ok, encoded = pcall( vim.json.encode, command )
107 + if not ok then return false, tostring( encoded ) end
108 + handle:write( encoded .. '\n' )
109 + return true, nil
110 + end
112 + --- Sends a command and correlates its response by id.
113 + local request = function( command, callback )
114 + local payload = vim.deepcopy( command )
115 + payload.id = payload.id or new_request_id()
116 + if callback then pending[payload.id] = callback end
117 + local ok, failure = send( payload )
118 + if not ok then
119 + pending[payload.id] = nil
120 + if callback then
121 + callback( { id = payload.id, type = 'response', success = false, error = failure, } )
122 + end
123 + end
124 + return payload.id
125 + end
127 + local notify = function( command ) return send( command ) end
129 + local stop = function()
130 + if not state.running then return end
131 + pcall( function() handle:write( nil ) end )
132 + pcall( function() handle:kill( 'sigterm' ) end )
133 + end
135 + local is_running = function() return state.running end
137 + return {
138 + request = request,
139 + notify = notify,
140 + stop = stop,
141 + is_running = is_running,
142 + handle = handle,
143 + failures = function() return vim.deepcopy( failures ) end,
145 +end
147 +return {
148 + start = start,

neovim/lua/bugabinga/pivi/session.lua

Added
new file mode 100644
1 +local rpc = require 'bugabinga.pivi.rpc'
2 +local status = require 'bugabinga.pivi.status'
3 +local publish = require 'bugabinga.pivi.publish'
4 +local transcript = require 'bugabinga.pivi.transcript'
5 +local assemble = require 'bugabinga.pivi.assemble'
6 +local context = require 'bugabinga.pivi.context'
7 +local dialog = require 'bugabinga.pivi.dialog'
8 +local partial = require 'bugabinga.pivi.partial'
9 +local activity = require 'bugabinga.pivi.activity'
10 +local follow = require 'bugabinga.pivi.follow'
11 +local edit = require 'bugabinga.pivi.edit'
13 +local registry = {}
14 +local counter = 0
16 +local executable = function()
17 + return vim.g.pivi_executable or 'pi'
18 +end
20 +local runtime_file = function( relative )
21 + local found = vim.api.nvim_get_runtime_file( relative, false )[1]
22 + if found then return vim.fs.normalize( found ) end
23 + return nil
24 +end
26 +local extension_path = function()
27 + return runtime_file 'lua/bugabinga/pivi/extension/index.ts'
28 +end
30 +--- Environment the companion extension needs to reach this Neovim instance.
31 +local bridge_environment = function()
32 + local address = vim.v.servername
33 + if address == nil or address == '' then return nil end
34 + return {
35 + PIVI_NVIM_ADDRESS = address,
36 + PIVI_NVIM_EXE = vim.v.progpath,
37 + PIVI_NVIM_CLIENT = runtime_file 'lua/bugabinga/pivi/extension/client.lua',
38 + }
39 +end
41 +local build_command = function( options )
42 + options = options or {}
43 + local command = { executable(), '--mode', 'rpc', }
44 + local extension = options.extension ~= false and extension_path() or nil
45 + if extension then
46 + table.insert( command, '-e' )
47 + table.insert( command, extension )
48 + end
49 + if options.model then
50 + table.insert( command, '--model' )
51 + table.insert( command, options.model )
52 + end
53 + if options.session then
54 + table.insert( command, '--session' )
55 + table.insert( command, options.session )
56 + end
57 + if options.name then
58 + table.insert( command, '--name' )
59 + table.insert( command, options.name )
60 + end
61 + for _, argument in ipairs( options.arguments or {} ) do
62 + table.insert( command, argument )
63 + end
64 + return command
65 +end
67 +local unique_name = function( cwd )
68 + counter = counter + 1
69 + local base = vim.fs.basename( cwd or vim.uv.cwd() or 'pi' )
70 + local name = base
71 + while registry[name] do
72 + name = base .. '-' .. tostring( counter )
73 + counter = counter + 1
74 + end
75 + return name
76 +end
78 +local render_event = function( self, event )
79 + local bufnr = self.buffer
81 + if event.type == 'message_start' and event.message and event.message.role == 'assistant' then
82 + transcript.line( bufnr, '' )
83 + transcript.line( bufnr, '# pi' )
84 + elseif event.type == 'message_update' then
85 + local delta = event.assistantMessageEvent or {}
86 + if delta.type == 'text_delta' then
87 + transcript.append( bufnr, delta.delta or '' )
88 + end
89 + elseif event.type == 'tool_execution_start' then
90 + transcript.line( bufnr, '' )
91 + transcript.line( bufnr, ' · ' .. tostring( event.toolName ) )
92 + elseif event.type == 'agent_settled' then
93 + transcript.line( bufnr, '' )
94 + elseif event.type == 'message_end' and event.message and event.message.errorMessage then
95 + transcript.line( bufnr, '' )
96 + transcript.line( bufnr, ' ! ' .. tostring( event.message.errorMessage ) )
97 + end
98 +end
100 +local publish_status = function( self )
101 + publish.session_status( self.name, self.status )
102 +end
104 +local located = function( arguments )
105 + if type( arguments ) ~= 'table' then return nil end
106 + local path = arguments.path or arguments.file_path or arguments.filePath
107 + if type( path ) ~= 'string' or path == '' then return nil end
108 + return { path = path, line = arguments.line or arguments.lnum, }
109 +end
111 +--- Renders streaming edit intent as inert ghost text.
112 +--- Nothing here mutates a buffer: complete arguments are required for that.
113 +local ghost_intent = function( self, call )
114 + local intent = partial.intent( call.name, call.arguments_text )
115 + if not intent.path or not intent.text then return end
116 + local bufnr = edit.buffer_for( intent.path )
117 + if not bufnr then return end
118 + self.ghost_buffer = bufnr
119 + activity.ghost( bufnr, 0, intent.text )
120 +end
122 +local clear_ghost = function( self )
123 + if self.ghost_buffer then
124 + activity.ghost_clear( self.ghost_buffer )
125 + self.ghost_buffer = nil
126 + end
127 +end
129 +local handle_event = function( self, event )
130 + if event.type == 'extension_ui_request' then
131 + dialog.handle( event, function( response ) self.client.notify( response ) end )
132 + return
133 + end
135 + self.status = status.reduce( self.status, event )
136 + self.message = assemble.apply( self.message, event )
138 + if event.type == 'message_update' then
139 + local delta = event.assistantMessageEvent or {}
140 + if delta.type == 'toolcall_delta' then
141 + for _, call in ipairs( assemble.tool_calls( self.message ) ) do
142 + if not call.complete then ghost_intent( self, call ) end
143 + end
144 + elseif delta.type == 'toolcall_end' then
145 + clear_ghost( self )
146 + end
147 + elseif event.type == 'tool_execution_start' then
148 + clear_ghost( self )
149 + local location = located( event.args )
150 + if location then follow.to( location ) end
151 + elseif event.type == 'agent_settled' then
152 + clear_ghost( self )
153 + end
155 + render_event( self, event )
156 + for _, listener in ipairs( self.listeners ) do
157 + pcall( listener, event, self )
158 + end
159 + publish_status( self )
160 +end
162 +--- Creates a session and starts its Pi process.
163 +--- @param options table? name, cwd, model, session, arguments, spawn
164 +local new = function( options )
165 + options = options or {}
166 + local cwd = options.cwd or vim.uv.cwd()
167 + local name = options.name or unique_name( cwd )
169 + local self = {
170 + name = name,
171 + cwd = cwd,
172 + status = status.initial(),
173 + message = assemble.new(),
174 + listeners = {},
175 + buffer = transcript.ensure( name ),
178 + self.client = rpc.start {
179 + command = build_command {
180 + model = options.model,
181 + session = options.session,
182 + name = options.name,
183 + arguments = options.arguments,
184 + extension = options.extension,
185 + },
186 + cwd = cwd,
187 + env = options.env or bridge_environment(),
188 + spawn = options.spawn,
189 + on_event = function( event ) handle_event( self, event ) end,
190 + on_stderr = function( data ) self.last_stderr = data end,
191 + on_exit = function( code )
192 + self.status = status.stopped( self.status, code )
193 + publish_status( self )
194 + end,
197 + self.status.connection = 'running'
198 + publish_status( self )
200 + registry[name] = self
201 + return self
202 +end
204 +local get = function( name ) return registry[name] end
206 +local list = function()
207 + local names = {}
208 + for key in pairs( registry ) do table.insert( names, key ) end
209 + table.sort( names )
210 + return names
211 +end
213 +local active = function()
214 + local value = publish.read()
215 + if value.active and registry[value.active] then return registry[value.active] end
216 + local names = list()
217 + if #names == 0 then return nil end
218 + return registry[names[1]]
219 +end
221 +local set_active = function( name )
222 + if not registry[name] then return false end
223 + publish.set_active( name )
224 + return true
225 +end
227 +--- Submits text to the session.
228 +--- A submission during an active run must choose its delivery explicitly;
229 +--- rejection is returned, never silently swallowed.
230 +--- @return boolean accepted
231 +--- @return string? rejection
232 +local submit = function( self, text, options )
233 + options = options or {}
234 + vim.validate( 'text', text, 'string' )
236 + if not self.client.is_running() then
237 + return false, 'pi process is not running'
238 + end
240 + local busy = status.is_busy( self.status )
241 + local delivery = options.delivery
243 + if busy and not delivery then
244 + return false, 'pi is running: choose steer or follow_up delivery'
245 + end
247 + if delivery and delivery ~= 'steer' and delivery ~= 'follow_up' then
248 + return false, 'unknown delivery: ' .. tostring( delivery )
249 + end
251 + local snapshot = options.snapshot
252 + if snapshot == nil and options.capture ~= false then
253 + snapshot = context.snapshot( options.source )
254 + end
256 + local message = text
257 + if snapshot then
258 + message = context.render( snapshot ) .. text
259 + end
261 + transcript.line( self.buffer, '' )
262 + transcript.line( self.buffer, '> ' .. text )
264 + local command
265 + if delivery == 'steer' then
266 + command = { type = 'steer', message = message, }
267 + elseif delivery == 'follow_up' then
268 + command = { type = 'follow_up', message = message, }
269 + else
270 + command = { type = 'prompt', message = message, }
271 + end
273 + table.insert( self.submissions, { text = text, delivery = delivery, snapshot = snapshot, } )
275 + self.client.request( command, function( response )
276 + if response.success then return end
277 + transcript.line( self.buffer, ' ! ' .. tostring( response.error or 'submission rejected' ) )
278 + self.status = vim.tbl_extend( 'force', self.status, { error = response.error, } )
279 + publish_status( self )
280 + end )
282 + return true, nil
283 +end
285 +local request = function( self, command, callback )
286 + return self.client.request( command, callback )
287 +end
289 +local abort = function( self, callback )
290 + return self.client.request( { type = 'abort', }, callback )
291 +end
293 +local clear_queue = function( self, callback )
294 + return self.client.request( { type = 'clear_queue', }, function( response )
295 + if response.success and response.data then
296 + self.status = status.reduce( self.status, {
297 + type = 'queue_update',
298 + steering = {},
299 + followUp = {},
300 + } )
301 + publish_status( self )
302 + end
303 + if callback then callback( response ) end
304 + end )
305 +end
307 +local refresh = function( self, callback )
308 + return self.client.request( { type = 'get_state', }, function( response )
309 + if response.success then
310 + self.status = status.reduce_state( self.status, response.data )
311 + publish_status( self )
312 + end
313 + if callback then callback( response ) end
314 + end )
315 +end
317 +local stop = function( self )
318 + self.client.stop()
319 + registry[self.name] = nil
320 + publish.remove( self.name )
321 +end
323 +local on = function( self, listener )
324 + table.insert( self.listeners, listener )
325 + return function()
326 + for index, candidate in ipairs( self.listeners ) do
327 + if candidate == listener then
328 + table.remove( self.listeners, index )
329 + return
330 + end
331 + end
332 + end
333 +end
335 +local stop_all = function()
336 + for _, name in ipairs( list() ) do
337 + local live = registry[name]
338 + if live then stop( live ) end
339 + end
340 +end
342 +local wrap = function( self )
343 + self.submissions = self.submissions or {}
344 + self.submit = function( text, options ) return submit( self, text, options ) end
345 + self.request = function( command, callback ) return request( self, command, callback ) end
346 + self.abort = function( callback ) return abort( self, callback ) end
347 + self.clear_queue = function( callback ) return clear_queue( self, callback ) end
348 + self.refresh = function( callback ) return refresh( self, callback ) end
349 + self.stop = function() return stop( self ) end
350 + self.on = function( listener ) return on( self, listener ) end
351 + return self
352 +end
354 +local create = function( options ) return wrap( new( options ) ) end
356 +return {
357 + create = create,
358 + get = get,
359 + list = list,
360 + active = active,
361 + set_active = set_active,
362 + stop_all = stop_all,
363 + build_command = build_command,

neovim/lua/bugabinga/pivi/status.lua

Added
new file mode 100644
1 +local copy = function( state )
2 + local next_state = vim.deepcopy( state )
3 + return next_state
4 +end
6 +local initial = function()
7 + return {
8 + connection = 'starting',
9 + run = 'idle',
10 + tool = nil,
11 + queue = { steering = {}, follow_up = {}, },
12 + compacting = false,
13 + retry = nil,
14 + error = nil,
15 + model = nil,
16 + thinking = nil,
17 + session = nil,
18 + context = nil,
19 + exit_code = nil,
20 + }
21 +end
23 +--- Folds one RPC event into cached semantic status.
24 +--- Pure: no editor state is read or written here.
25 +--- @param state table current status
26 +--- @param event table one RPC event
27 +--- @return table state the next status
28 +local reduce = function( state, event )
29 + if type( event ) ~= 'table' or type( event.type ) ~= 'string' then return state end
30 + local next_state = copy( state )
31 + local kind = event.type
33 + if kind == 'agent_start' then
34 + next_state.connection = 'running'
35 + next_state.run = 'running'
36 + next_state.error = nil
37 + elseif kind == 'agent_end' then
38 + next_state.run = event.willRetry and 'retrying' or 'running'
39 + elseif kind == 'agent_settled' then
40 + next_state.run = 'idle'
41 + next_state.tool = nil
42 + next_state.retry = nil
43 + elseif kind == 'tool_execution_start' then
44 + next_state.run = 'running'
45 + next_state.tool = { id = event.toolCallId, name = event.toolName, }
46 + elseif kind == 'tool_execution_end' then
47 + if next_state.tool and next_state.tool.id == event.toolCallId then next_state.tool = nil end
48 + elseif kind == 'queue_update' then
49 + next_state.queue = {
50 + steering = event.steering or {},
51 + follow_up = event.followUp or {},
52 + }
53 + elseif kind == 'compaction_start' then
54 + next_state.compacting = true
55 + elseif kind == 'compaction_end' then
56 + next_state.compacting = false
57 + if event.errorMessage then next_state.error = event.errorMessage end
58 + elseif kind == 'auto_retry_start' then
59 + next_state.run = 'retrying'
60 + next_state.retry = { attempt = event.attempt, max = event.maxAttempts, delay = event.delayMs, }
61 + next_state.error = event.errorMessage
62 + elseif kind == 'auto_retry_end' then
63 + next_state.retry = nil
64 + if event.success then
65 + next_state.run = 'running'
66 + next_state.error = nil
67 + else
68 + next_state.run = 'idle'
69 + next_state.error = event.finalError
70 + end
71 + elseif kind == 'extension_error' then
72 + next_state.error = event.error
73 + elseif kind == 'message_end' then
74 + local message = event.message
75 + if message and message.errorMessage then next_state.error = message.errorMessage end
76 + end
78 + return next_state
79 +end
81 +--- Folds a `get_state` response payload into cached status.
82 +local reduce_state = function( state, data )
83 + if type( data ) ~= 'table' then return state end
84 + local next_state = copy( state )
85 + next_state.connection = 'running'
86 + next_state.model = data.model and data.model.id or next_state.model
87 + next_state.thinking = data.thinkingLevel or next_state.thinking
88 + next_state.session = {
89 + id = data.sessionId,
90 + name = data.sessionName,
91 + file = data.sessionFile,
92 + messages = data.messageCount,
93 + }
94 + if data.isStreaming ~= nil and next_state.run == 'idle' and data.isStreaming then
95 + next_state.run = 'running'
96 + end
97 + next_state.compacting = data.isCompacting == true
98 + return next_state
99 +end
101 +--- Folds a `get_session_stats` response payload into cached status.
102 +local reduce_stats = function( state, data )
103 + if type( data ) ~= 'table' then return state end
104 + local next_state = copy( state )
105 + local usage = data.contextUsage
106 + if usage then
107 + next_state.context = {
108 + tokens = usage.tokens,
109 + window = usage.contextWindow,
110 + percent = usage.percent,
112 + end
113 + next_state.cost = data.cost
114 + return next_state
115 +end
117 +local stopped = function( state, exit_code )
118 + local next_state = copy( state )
119 + next_state.connection = 'stopped'
120 + next_state.run = 'idle'
121 + next_state.tool = nil
122 + next_state.exit_code = exit_code
123 + return next_state
124 +end
126 +local is_busy = function( state )
127 + return state.run == 'running' or state.run == 'retrying' or state.compacting == true
128 +end
130 +local pending_count = function( state )
131 + return #( state.queue.steering or {} ) + #( state.queue.follow_up or {} )
132 +end
134 +--- Short human summary suitable for a statusline.
135 +local summary = function( state )
136 + if state.connection == 'stopped' then return 'pi:off' end
137 + if state.run == 'retrying' then return 'pi:retry' end
138 + if state.error then return 'pi:error' end
139 + if state.compacting then return 'pi:compacting' end
140 + if state.tool then return 'pi:' .. tostring( state.tool.name ) end
141 + if state.run == 'running' then return 'pi:run' end
142 + local pending = pending_count( state )
143 + if pending > 0 then return 'pi:idle+' .. tostring( pending ) end
144 + return 'pi:idle'
145 +end
147 +return {
148 + initial = initial,
149 + reduce = reduce,
150 + reduce_state = reduce_state,
151 + reduce_stats = reduce_stats,
152 + stopped = stopped,
153 + is_busy = is_busy,
154 + pending_count = pending_count,
155 + summary = summary,

neovim/lua/bugabinga/pivi/transcript.lua

Added
new file mode 100644
1 +local FILETYPE = 'pivi'
3 +local buffers = {}
5 +local configure = function( bufnr, name )
6 + vim.bo[bufnr].buftype = 'nofile'
7 + vim.bo[bufnr].bufhidden = 'hide'
8 + vim.bo[bufnr].swapfile = false
9 + vim.bo[bufnr].filetype = FILETYPE
10 + vim.bo[bufnr].modifiable = false
11 + pcall( vim.api.nvim_buf_set_name, bufnr, 'pivi://' .. name )
12 +end
14 +--- Returns the transcript buffer for a name, creating it when missing.
15 +local ensure = function( name )
16 + vim.validate( 'name', name, 'string' )
17 + local bufnr = buffers[name]
18 + if bufnr and vim.api.nvim_buf_is_valid( bufnr ) then return bufnr end
19 + bufnr = vim.api.nvim_create_buf( false, true )
20 + configure( bufnr, name )
21 + buffers[name] = bufnr
22 + return bufnr
23 +end
25 +local writable = function( bufnr, action )
26 + vim.bo[bufnr].modifiable = true
27 + local ok, failure = pcall( action )
28 + vim.bo[bufnr].modifiable = false
29 + if not ok then error( failure ) end
30 +end
32 +local follow_windows = function( bufnr )
33 + local last = vim.api.nvim_buf_line_count( bufnr )
34 + for _, win in ipairs( vim.api.nvim_list_wins() ) do
35 + if vim.api.nvim_win_get_buf( win ) == bufnr then
36 + pcall( vim.api.nvim_win_set_cursor, win, { last, 0, } )
37 + end
38 + end
39 +end
41 +--- Appends raw text, continuing the final line when it does not start with a newline.
42 +local append = function( bufnr, text )
43 + vim.validate( 'bufnr', bufnr, 'number' )
44 + vim.validate( 'text', text, 'string' )
45 + if text == '' then return end
46 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
48 + local chunks = vim.split( text, '\n', { plain = true, } )
49 + writable( bufnr, function()
50 + local count = vim.api.nvim_buf_line_count( bufnr )
51 + local last = vim.api.nvim_buf_get_lines( bufnr, count - 1, count, false )[1] or ''
52 + local lines = { last .. chunks[1], }
53 + for offset = 2, #chunks do
54 + table.insert( lines, chunks[offset] )
55 + end
56 + vim.api.nvim_buf_set_lines( bufnr, count - 1, count, false, lines )
57 + end )
58 + follow_windows( bufnr )
59 +end
61 +--- Appends complete lines.
62 +local line = function( bufnr, text )
63 + vim.validate( 'bufnr', bufnr, 'number' )
64 + vim.validate( 'text', text, 'string' )
65 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
66 + append( bufnr, text .. '\n' )
67 +end
69 +local lines = function( bufnr )
70 + if not vim.api.nvim_buf_is_valid( bufnr ) then return {} end
71 + return vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
72 +end
74 +local clear = function( bufnr )
75 + if not vim.api.nvim_buf_is_valid( bufnr ) then return end
76 + writable( bufnr, function()
77 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { '', } )
78 + end )
79 +end
81 +--- Shows the transcript buffer without stealing the current window.
82 +local show = function( bufnr )
83 + if not vim.api.nvim_buf_is_valid( bufnr ) then return nil end
84 + for _, win in ipairs( vim.api.nvim_list_wins() ) do
85 + if vim.api.nvim_win_get_buf( win ) == bufnr then return win end
86 + end
87 + local current = vim.api.nvim_get_current_win()
88 + local split = pcall( vim.cmd.vsplit )
89 + if not split then return nil end
90 + local win = vim.api.nvim_get_current_win()
91 + 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
95 + vim.api.nvim_set_current_win( current )
96 + return win
97 +end
99 +local forget = function( name )
100 + local bufnr = buffers[name]
101 + buffers[name] = nil
102 + if bufnr and vim.api.nvim_buf_is_valid( bufnr ) then
103 + pcall( vim.api.nvim_buf_delete, bufnr, { force = true, } )
104 + end
105 +end
107 +local forget_all = function()
108 + for name in pairs( buffers ) do
109 + forget( name )
110 + end
111 +end
113 +return {
114 + filetype = FILETYPE,
115 + ensure = ensure,
116 + append = append,
117 + line = line,
118 + lines = lines,
119 + clear = clear,
120 + show = show,
121 + forget = forget,
122 + forget_all = forget_all,

neovim/tests/bugabinga/pivi/assemble_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local assemble = require 'bugabinga.pivi.assemble'
4 +-- Delta shapes follow Pi's documented `message_update` protocol.
5 +-- No recorded streaming fixture exists because every configured provider
6 +-- refused a live completion while these specs were written.
7 +local delta = function( value )
8 + return { type = 'message_update', assistantMessageEvent = value, }
9 +end
11 +local feed = function( events )
12 + local state = assemble.new()
13 + for _, event in ipairs( events ) do
14 + state = assemble.apply( state, event )
15 + end
16 + return state
17 +end
19 +describe( 'pivi assemble', function()
20 + it( 'concatenates text deltas by content index', function()
21 + local state = feed {
22 + { type = 'message_start', message = { role = 'assistant', }, },
23 + delta { type = 'text_start', contentIndex = 0, },
24 + delta { type = 'text_delta', contentIndex = 0, delta = 'Hello', },
25 + delta { type = 'text_delta', contentIndex = 0, delta = ' world', },
26 + }
27 + assert.equal( 'Hello world', assemble.text( state ) )
28 + end )
30 + it( 'keeps interleaved content blocks in index order', function()
31 + local state = feed {
32 + delta { type = 'text_delta', contentIndex = 2, delta = 'second', },
33 + delta { type = 'text_delta', contentIndex = 0, delta = 'first ', },
34 + }
35 + assert.equal( 'first second', assemble.text( state ) )
36 + end )
38 + it( 'separates thinking from visible text', function()
39 + local state = feed {
40 + delta { type = 'thinking_delta', contentIndex = 0, delta = 'pondering', },
41 + delta { type = 'text_delta', contentIndex = 1, delta = 'answer', },
42 + }
43 + assert.equal( 'answer', assemble.text( state ) )
44 + assert.equal( 'pondering', assemble.thinking( state ) )
45 + end )
47 + it( 'buffers tool call arguments and marks completion', function()
48 + local state = feed {
49 + delta { type = 'toolcall_start', contentIndex = 0, id = 'call_1', toolName = 'edit', },
50 + delta { type = 'toolcall_delta', contentIndex = 0, delta = '{"path":"a.lua"', },
51 + }
53 + local streaming = assemble.tool_calls( state )[1]
54 + assert.equal( 'call_1', streaming.id )
55 + assert.equal( 'edit', streaming.name )
56 + assert.equal( '{"path":"a.lua"', streaming.arguments_text )
57 + assert.is_false( streaming.complete )
59 + state = assemble.apply( state, delta {
60 + type = 'toolcall_end',
61 + contentIndex = 0,
62 + toolCall = { id = 'call_1', name = 'edit', arguments = { path = 'a.lua', }, },
63 + } )
65 + local finished = assemble.tool_calls( state )[1]
66 + assert.is_true( finished.complete )
67 + assert.equal( 'a.lua', finished.arguments.path )
68 + end )
70 + it( 'treats message_end as authoritative over accumulated deltas', function()
71 + local state = feed {
72 + delta { type = 'text_delta', contentIndex = 0, delta = 'partial junk', },
73 + {
74 + type = 'message_end',
75 + message = {
76 + role = 'assistant',
77 + content = { { type = 'text', text = 'final answer', }, },
78 + },
79 + },
80 + }
81 + assert.equal( 'final answer', assemble.text( state ) )
82 + assert.is_true( state.complete )
83 + end )
85 + it( 'resets on a new assistant message and ignores user messages', function()
86 + local state = feed {
87 + delta { type = 'text_delta', contentIndex = 0, delta = 'old', },
88 + { type = 'message_start', message = { role = 'user', }, },
89 + }
90 + assert.equal( 'old', assemble.text( state ) )
92 + state = assemble.apply( state, { type = 'message_start', message = { role = 'assistant', }, } )
93 + assert.equal( '', assemble.text( state ) )
94 + end )
96 + it( 'ignores unknown events and malformed deltas', function()
97 + local state = feed {
98 + { type = 'totally_unknown_event', },
99 + { type = 'message_update', },
100 + delta { type = 'nonsense', contentIndex = 0, },
101 + 'not a table',
103 + assert.equal( '', assemble.text( state ) )
104 + end )
105 +end )

neovim/tests/bugabinga/pivi/bridge_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local bridge = require 'bugabinga.pivi.bridge'
3 +local activity = require 'bugabinga.pivi.activity'
5 +local temp_file = function( lines )
6 + local path = vim.fs.normalize( vim.fn.tempname() .. '.txt' )
7 + vim.fn.writefile( lines, path )
8 + return path
9 +end
11 +local open = function( path )
12 + vim.cmd( 'edit! ' .. vim.fn.fnameescape( path ) )
13 + return vim.api.nvim_get_current_buf()
14 +end
16 +describe( 'pivi bridge', function()
17 + after_each( function()
18 + vim.cmd 'silent! %bwipeout!'
19 + activity.clear_trail()
20 + vim.fn.setqflist( {}, 'r' )
21 + end )
23 + it( 'rejects an unknown action', function()
24 + local answer = bridge.handle { action = 'levitate', }
25 + assert.is_false( answer.ok )
26 + assert.is_string( answer.error )
27 + end )
29 + it( 'rejects a malformed request', function()
30 + assert.is_false( bridge.handle( 'nonsense' ).ok )
31 + end )
33 + it( 'reads unsaved buffer content instead of disk content', function()
34 + local path = temp_file { 'on disk', }
35 + local bufnr = open( path )
36 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { 'unsaved', } )
38 + local answer = bridge.handle { action = 'read', path = path, }
40 + assert.is_true( answer.ok )
41 + assert.equal( 'buffer', answer.source )
42 + assert.equal( 'unsaved', answer.content )
43 + end )
45 + it( 'reads from disk when no buffer holds the file', function()
46 + local path = temp_file { 'from disk', }
47 + local answer = bridge.handle { action = 'read', path = path, }
48 + assert.equal( 'disk', answer.source )
49 + assert.equal( 'from disk', answer.content )
50 + end )
52 + it( 'reports a missing file', function()
53 + local answer = bridge.handle { action = 'read', path = vim.fn.tempname() .. '.absent', }
54 + assert.is_false( answer.ok )
55 + end )
57 + it( 'writes through the loaded buffer and makes it visible on disk', function()
58 + local path = temp_file { 'before', }
59 + local bufnr = open( path )
61 + local answer = bridge.handle { action = 'write', path = path, content = 'after', }
63 + assert.is_true( answer.ok )
64 + assert.equal( 'buffer', answer.source )
65 + assert.is_true( answer.persisted )
66 + assert.same( { 'after', }, vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ) )
67 + assert.same( { 'after', }, vim.fn.readfile( path ) )
68 + end )
70 + it( 'writes straight to disk when no buffer holds the file', function()
71 + local path = temp_file { 'before', }
72 + local answer = bridge.handle { action = 'write', path = path, content = 'after', }
73 + assert.equal( 'disk', answer.source )
74 + assert.same( { 'after', }, vim.fn.readfile( path ) )
75 + end )
77 + it( 'edits a loaded buffer and keeps the change undoable', function()
78 + local path = temp_file { 'local value = 1', 'return value', }
79 + local bufnr = open( path )
80 + local before = vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
82 + local answer = bridge.handle {
83 + action = 'edit',
84 + path = path,
85 + old_text = 'local value = 1',
86 + new_text = 'local value = 2',
87 + }
89 + assert.is_true( answer.ok )
90 + assert.equal( 'buffer', answer.source )
91 + assert.same( { 'local value = 2', 'return value', }, vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ) )
93 + vim.api.nvim_buf_call( bufnr, function() vim.cmd 'silent undo' end )
94 + assert.same( before, vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ) )
95 + end )
97 + it( 'edits a file that is not loaded', function()
98 + local path = temp_file { 'alpha', }
99 + local answer = bridge.handle { action = 'edit', path = path, old_text = 'alpha', new_text = 'omega', }
100 + assert.equal( 'disk', answer.source )
101 + assert.same( { 'omega', }, vim.fn.readfile( path ) )
102 + end )
104 + it( 'refuses an edit whose text is absent', function()
105 + local path = temp_file { 'alpha', }
106 + open( path )
107 + local answer = bridge.handle { action = 'edit', path = path, old_text = 'missing', new_text = 'x', }
108 + assert.is_false( answer.ok )
109 + end )
111 + it( 'reports live editor state', function()
112 + local path = temp_file { 'ambient', }
113 + local bufnr = open( path )
115 + local answer = bridge.handle { action = 'state', }
117 + assert.is_true( answer.ok )
118 + assert.equal( bufnr, answer.state.current_buffer )
119 + assert.is_true( #answer.state.windows > 0 )
120 + end )
122 + it( 'executes arbitrary lua and returns the inspected result', function()
123 + local answer = bridge.handle { action = 'lua', code = 'return 1 + 1', }
124 + assert.is_true( answer.ok )
125 + assert.equal( '2', answer.result )
126 + end )
128 + it( 'reports a lua failure instead of throwing', function()
129 + assert.is_false( bridge.handle( { action = 'lua', code = 'error("boom")', } ).ok )
130 + assert.is_false( bridge.handle( { action = 'lua', code = 'this is not lua', } ).ok )
131 + end )
133 + it( 'publishes findings to the quickfix list', function()
134 + local answer = bridge.handle {
135 + action = 'findings',
136 + title = 'review',
137 + items = { { path = 'a.lua', line = 2, text = 'look here', }, },
139 + assert.is_true( answer.ok )
140 + assert.equal( 1, #vim.fn.getqflist() )
141 + end )
143 + it( 'publishes diagnostics for a loaded buffer only', function()
144 + local path = temp_file { 'one', 'two', }
145 + local bufnr = open( path )
147 + local answer = bridge.handle {
148 + action = 'diagnostics',
149 + path = path,
150 + items = { { line = 2, text = 'suspicious', severity = 'warning', }, },
153 + assert.is_true( answer.ok )
154 + assert.equal( 1, #activity.diagnostics( bufnr ) )
156 + assert.is_false( bridge.handle( {
157 + action = 'diagnostics',
158 + path = vim.fn.tempname() .. '.absent',
159 + items = {},
160 + } ).ok )
162 + activity.clear_diagnostics( bufnr )
163 + end )
164 +end )

neovim/tests/bugabinga/pivi/command_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local command = require 'bugabinga.pivi.command'
3 +local session = require 'bugabinga.pivi.session'
4 +local transcript = require 'bugabinga.pivi.transcript'
5 +local publish = require 'bugabinga.pivi.publish'
6 +local fake = dofile 'tests/helpers/pivi_fake.lua'
8 +local notices
10 +describe( 'pivi command', function()
11 + local original_notify, original_select
13 + before_each( function()
14 + notices = {}
15 + original_notify = vim.notify
16 + original_select = vim.ui.select
17 + vim.notify = function( message, level ) table.insert( notices, { message, level, } ) end
18 + end )
20 + after_each( function()
21 + fake.drain()
22 + vim.notify = original_notify
23 + vim.ui.select = original_select
24 + session.stop_all()
25 + transcript.forget_all()
26 + publish.reset()
27 + fake.close_extra_windows()
28 + vim.cmd 'silent! %bwipeout!'
29 + pcall( vim.api.nvim_del_user_command, 'Pi' )
30 + end )
32 + describe( 'slash entry', function()
33 + it( 'opens only at the first character of a pivi input buffer', function()
34 + local bufnr = vim.api.nvim_create_buf( false, true )
35 + vim.bo[bufnr].filetype = command.input_filetype
37 + assert.is_true( command.slash_opens_commands( bufnr, 0 ) )
38 + assert.is_false( command.slash_opens_commands( bufnr, 1 ) )
39 + assert.is_false( command.slash_opens_commands( bufnr, 7 ) )
40 + end )
42 + it( 'never opens in an ordinary buffer', function()
43 + vim.cmd 'enew'
44 + local bufnr = vim.api.nvim_get_current_buf()
45 + assert.is_false( command.slash_opens_commands( bufnr, 0 ) )
46 + end )
48 + it( 'never opens in an invalid buffer', function()
49 + local bufnr = vim.api.nvim_create_buf( false, true )
50 + vim.api.nvim_buf_delete( bufnr, { force = true, } )
51 + assert.is_false( command.slash_opens_commands( bufnr, 0 ) )
52 + end )
54 + it( 'keeps ordinary search behavior away from the first character', function()
55 + local channel = fake.new()
56 + local current = session.create { spawn = channel.spawn, name = 'spec', extension = false, env = {}, }
57 + local bufnr = command.open_prompt( current )
59 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { 'hello', } )
60 + vim.api.nvim_win_set_cursor( 0, { 1, 3, } )
62 + local mapping
63 + for _, entry in ipairs( vim.api.nvim_buf_get_keymap( bufnr, 'n' ) ) do
64 + if entry.lhs == '/' then mapping = entry end
65 + end
67 + assert.is_table( mapping )
68 + assert.equal( '/', mapping.callback() )
69 + end )
70 + end )
72 + describe( 'dispatch', function()
73 + it( 'registers the user command and its subcommand completion', function()
74 + command.setup()
75 + assert.is_table( vim.api.nvim_get_commands( {} ).Pi )
77 + local names = command.names()
78 + assert.is_true( vim.list_contains( names, 'ask' ) )
79 + assert.is_true( vim.list_contains( names, 'help' ) )
80 + assert.is_true( vim.list_contains( names, 'command' ) )
81 + end )
83 + it( 'reports an unknown subcommand', function()
84 + command.dispatch { args = 'levitate', }
85 + assert.equal( 1, #notices )
86 + assert.equal( vim.log.levels.ERROR, notices[1][2] )
87 + end )
89 + it( 'refuses an empty question', function()
90 + command.dispatch { args = 'help', }
91 + assert.equal( vim.log.levels.WARN, notices[1][2] )
92 + end )
94 + it( 'reports that nothing is running when no session exists', function()
95 + command.dispatch { args = 'abort', }
96 + assert.equal( vim.log.levels.WARN, notices[1][2] )
97 + end )
98 + end )
100 + describe( 'slash commands', function()
101 + it( 'runs a named pi command through the session', function()
102 + local channel = fake.new()
103 + session.create { spawn = channel.spawn, name = 'spec', extension = false, env = {}, }
105 + command.subcommands.command 'compact focus on edits'
107 + local prompts = {}
108 + for _, entry in ipairs( channel.commands ) do
109 + if entry.type == 'prompt' then table.insert( prompts, entry ) end
110 + end
111 + assert.equal( 1, #prompts )
112 + assert.equal( '/compact focus on edits', prompts[1].message )
113 + end )
115 + it( 'offers only the commands pi reports for this session', function()
116 + local channel = fake.new()
117 + local current = session.create { spawn = channel.spawn, name = 'spec', extension = false, env = {}, }
119 + local offered
120 + vim.ui.select = function( items, _, on_choice )
121 + offered = items
122 + on_choice( items[1] )
123 + end
125 + command.subcommands.command ''
127 + local request
128 + for _, entry in ipairs( channel.commands ) do
129 + if entry.type == 'get_commands' then request = entry end
130 + end
131 + assert.is_table( request )
133 + channel.frame {
134 + id = request.id,
135 + type = 'response',
136 + command = 'get_commands',
137 + success = true,
138 + data = { commands = {
139 + { name = 'compact', description = 'Compact context', source = 'extension', },
140 + { name = 'skill:wiki', description = 'Wiki skill', source = 'skill', },
141 + }, },
144 + assert.is_true( channel.settle( function() return offered ~= nil end ) )
145 + assert.equal( 2, #offered )
146 + assert.equal( 'compact', offered[1].name )
147 + assert.equal( 2, #current.commands )
148 + end )
150 + it( 'reports when pi offers no commands', function()
151 + local channel = fake.new()
152 + session.create { spawn = channel.spawn, name = 'spec', extension = false, env = {}, }
154 + command.subcommands.command ''
156 + local request
157 + for _, entry in ipairs( channel.commands ) do
158 + if entry.type == 'get_commands' then request = entry end
159 + end
160 + channel.frame {
161 + id = request.id,
162 + type = 'response',
163 + command = 'get_commands',
164 + success = true,
165 + data = { commands = {}, },
168 + assert.is_true( channel.settle( function() return #notices > 0 end ) )
169 + assert.equal( vim.log.levels.WARN, notices[#notices][2] )
170 + end )
171 + end )
173 + describe( 'follow', function()
174 + it( 'toggles follow mode and reports it', function()
175 + command.subcommands.follow ''
176 + assert.is_true( notices[1][1]:find( 'window', 1, true ) ~= nil )
177 + command.subcommands.follow ''
178 + assert.is_true( notices[2][1]:find( 'off', 1, true ) ~= nil )
179 + end )
180 + end )
181 +end )

neovim/tests/bugabinga/pivi/context_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local context = require 'bugabinga.pivi.context'
4 +local scratch = function( lines )
5 + vim.cmd 'enew'
6 + local bufnr = vim.api.nvim_get_current_buf()
7 + vim.api.nvim_buf_set_name( bufnr, vim.fn.tempname() .. '.lua' )
8 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, lines )
9 + return bufnr
10 +end
12 +describe( 'pivi context', function()
13 + after_each( function()
14 + vim.cmd 'silent! %bwipeout!'
15 + end )
17 + it( 'captures buffer identity, revision, and cursor', function()
18 + local bufnr = scratch { 'one', 'two', 'three', }
19 + vim.api.nvim_win_set_cursor( 0, { 2, 1, } )
21 + local shot = context.snapshot()
23 + assert.equal( bufnr, shot.buffer )
24 + assert.equal( vim.api.nvim_buf_get_changedtick( bufnr ), shot.revision )
25 + assert.equal( 2, shot.cursor[1] )
26 + assert.equal( 1, shot.cursor[2] )
27 + assert.equal( 3, shot.line_count )
28 + end )
30 + it( 'captures unsaved content', function()
31 + local bufnr = scratch { 'unsaved line', }
32 + local shot = context.snapshot()
34 + assert.is_true( shot.modified )
35 + assert.is_true( shot.surrounding:find( 'unsaved line', 1, true ) ~= nil )
36 + end )
38 + it( 'refuses mutation of a snapshot', function()
39 + scratch { 'a', }
40 + local shot = context.snapshot()
41 + assert.has_error( function() shot.path = 'elsewhere' end )
42 + assert.has_error( function() shot.cursor[1] = 99 end )
43 + end )
45 + it( 'keeps its own values when the buffer changes later', function()
46 + local bufnr = scratch { 'before', }
47 + local shot = context.snapshot()
48 + local revision = shot.revision
50 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { 'after', 'more', } )
52 + assert.equal( revision, shot.revision )
53 + assert.equal( 1, shot.line_count )
54 + assert.is_true( shot.surrounding:find( 'before', 1, true ) ~= nil )
55 + assert.is_nil( shot.surrounding:find( 'after', 1, true ) )
56 + end )
58 + it( 'captures a selected range and its text', function()
59 + scratch { 'one', 'two', 'three', }
60 + local shot = context.snapshot { range = { kind = 'V', first = { 1, 0, }, last = { 2, 0, }, }, }
62 + assert.equal( 'V', shot.selection_kind )
63 + assert.equal( 'one\ntwo', shot.selected_text )
64 + end )
66 + it( 'renders a stable prompt preamble', function()
67 + scratch { 'one', 'two', }
68 + local rendered = context.render( context.snapshot() )
70 + assert.is_true( rendered:find( '<editor-context>', 1, true ) == 1 )
71 + assert.is_true( rendered:find( 'revision:', 1, true ) ~= nil )
72 + assert.is_true( rendered:find( '</editor-context>', 1, true ) ~= nil )
73 + end )
75 + it( 'renders nothing without a snapshot', function()
76 + assert.equal( '', context.render( nil ) )
77 + end )
79 + it( 'skips buffers that are not editable files', function()
80 + local bufnr = vim.api.nvim_create_buf( false, true )
81 + vim.bo[bufnr].buftype = 'nofile'
82 + assert.is_nil( context.snapshot { bufnr = bufnr, } )
83 + end )
85 + it( 'reports ambient editor state on demand', function()
86 + local bufnr = scratch { 'ambient', }
87 + local state = context.editor()
89 + assert.equal( bufnr, state.current_buffer )
90 + assert.is_string( state.mode )
91 + assert.is_true( #state.buffers > 0 )
92 + assert.is_true( #state.windows > 0 )
94 + local found = false
95 + for _, entry in ipairs( state.buffers ) do
96 + if entry.buffer == bufnr then
97 + found = true
98 + assert.is_true( entry.modified )
99 + end
100 + end
101 + assert.is_true( found )
102 + end )
103 +end )

neovim/tests/bugabinga/pivi/dialog_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local dialog = require 'bugabinga.pivi.dialog'
4 +describe( 'pivi dialog', function()
5 + local original_select, original_input, original_notify
7 + before_each( function()
8 + original_select = vim.ui.select
9 + original_input = vim.ui.input
10 + original_notify = vim.notify
11 + end )
13 + after_each( function()
14 + vim.ui.select = original_select
15 + vim.ui.input = original_input
16 + vim.notify = original_notify
17 + dialog.reset()
18 + end )
20 + local collect = function()
21 + local answers = {}
22 + return answers, function( response ) table.insert( answers, response ) end
23 + end
25 + it( 'ignores frames that are not extension ui requests', function()
26 + local _, respond = collect()
27 + assert.is_false( dialog.handle( { type = 'agent_start', }, respond ) )
28 + end )
30 + it( 'answers a selection with the request identifier', function()
31 + local offered
32 + vim.ui.select = function( items, _, on_choice )
33 + offered = items
34 + on_choice( items[2] )
35 + end
37 + local answers, respond = collect()
38 + local handled = dialog.handle( {
39 + type = 'extension_ui_request',
40 + id = 'uuid-1',
41 + method = 'select',
42 + title = 'Allow dangerous command?',
43 + options = { 'Allow', 'Block', },
44 + }, respond )
46 + assert.is_true( handled )
47 + assert.same( { 'Allow', 'Block', }, offered )
48 + assert.equal( 'extension_ui_response', answers[1].type )
49 + assert.equal( 'uuid-1', answers[1].id )
50 + assert.equal( 'Block', answers[1].value )
51 + end )
53 + it( 'answers a dismissed dialog as cancelled', function()
54 + vim.ui.select = function( _, _, on_choice ) on_choice( nil ) end
56 + local answers, respond = collect()
57 + dialog.handle( {
58 + type = 'extension_ui_request',
59 + id = 'uuid-2',
60 + method = 'select',
61 + title = 'pick',
62 + options = { 'a', },
63 + }, respond )
65 + assert.is_true( answers[1].cancelled )
66 + assert.is_nil( answers[1].value )
67 + end )
69 + it( 'answers a confirmation with a boolean', function()
70 + vim.ui.select = function( _, _, on_choice ) on_choice 'yes' end
72 + local answers, respond = collect()
73 + dialog.handle( {
74 + type = 'extension_ui_request',
75 + id = 'uuid-3',
76 + method = 'confirm',
77 + title = 'Clear session?',
78 + message = 'All messages will be lost.',
79 + }, respond )
81 + assert.is_true( answers[1].confirmed )
82 + assert.equal( 'uuid-3', answers[1].id )
83 + end )
85 + it( 'answers text input and editor requests', function()
86 + vim.ui.input = function( options, on_confirm ) on_confirm( ( options.default or '' ) .. '!' ) end
88 + local answers, respond = collect()
89 + dialog.handle( {
90 + type = 'extension_ui_request',
91 + id = 'uuid-4',
92 + method = 'input',
93 + title = 'Enter a value',
94 + placeholder = 'seed',
95 + }, respond )
96 + dialog.handle( {
97 + type = 'extension_ui_request',
98 + id = 'uuid-5',
99 + method = 'editor',
100 + title = 'Edit text',
101 + prefill = 'draft',
102 + }, respond )
104 + assert.equal( 'seed!', answers[1].value )
105 + assert.equal( 'uuid-4', answers[1].id )
106 + assert.equal( 'draft!', answers[2].value )
107 + assert.equal( 'uuid-5', answers[2].id )
108 + end )
110 + it( 'shows a notification without answering', function()
111 + local seen = {}
112 + vim.notify = function( message, level ) table.insert( seen, { message, level, } ) end
114 + local answers, respond = collect()
115 + local handled = dialog.handle( {
116 + type = 'extension_ui_request',
117 + id = 'uuid-6',
118 + method = 'notify',
119 + message = 'Command blocked by user',
120 + notifyType = 'warning',
121 + }, respond )
123 + assert.is_true( handled )
124 + assert.equal( 0, #answers )
125 + assert.equal( 'Command blocked by user', seen[1][1] )
126 + assert.equal( vim.log.levels.WARN, seen[1][2] )
127 + end )
129 + it( 'keeps status and widget entries without answering', function()
130 + local answers, respond = collect()
132 + dialog.handle( {
133 + type = 'extension_ui_request',
134 + id = 'uuid-7',
135 + method = 'setStatus',
136 + statusKey = 'ext',
137 + statusText = 'Turn 3 running...',
138 + }, respond )
139 + dialog.handle( {
140 + type = 'extension_ui_request',
141 + id = 'uuid-8',
142 + method = 'setWidget',
143 + widgetKey = 'ext',
144 + widgetLines = { 'line one', 'line two', },
145 + }, respond )
147 + assert.equal( 0, #answers )
148 + assert.equal( 'Turn 3 running...', dialog.statuses().ext )
149 + assert.same( { 'line one', 'line two', }, dialog.widgets().ext )
151 + dialog.handle( {
152 + type = 'extension_ui_request',
153 + id = 'uuid-9',
154 + method = 'setStatus',
155 + statusKey = 'ext',
156 + }, respond )
157 + assert.is_nil( dialog.statuses().ext )
158 + end )
160 + it( 'reports an unsupported method as unhandled', function()
161 + local _, respond = collect()
162 + assert.is_false( dialog.handle( {
163 + type = 'extension_ui_request',
164 + id = 'uuid-10',
165 + method = 'custom',
166 + }, respond ) )
167 + end )
168 +end )

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

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local activity = require 'bugabinga.pivi.activity'
4 +local scratch = function( lines )
5 + vim.cmd 'enew'
6 + local bufnr = vim.api.nvim_get_current_buf()
7 + vim.api.nvim_buf_set_name( bufnr, vim.fn.tempname() .. '.lua' )
8 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, lines )
9 + return bufnr
10 +end
12 +describe( 'pivi activity', function()
13 + after_each( function()
14 + vim.cmd 'silent! %bwipeout!'
15 + activity.clear_trail()
16 + vim.fn.setqflist( {}, 'r' )
17 + end )
19 + it( 'marks changed lines in its own namespace', function()
20 + local bufnr = scratch { 'one', 'two', 'three', }
21 + activity.mark_edit( bufnr, { { first = 0, last = 2, }, } )
23 + assert.equal( 2, #activity.marks( bufnr ) )
24 + assert.same( { { buffer = bufnr, first = 1, last = 2, }, }, activity.trail() )
25 + end )
27 + it( 'leaves foreign extmark namespaces untouched', function()
28 + local bufnr = scratch { 'one', 'two', }
29 + local foreign = vim.api.nvim_create_namespace 'some-language-server'
30 + vim.api.nvim_buf_set_extmark( bufnr, foreign, 0, 0, {} )
32 + activity.mark_edit( bufnr, { { first = 0, last = 1, }, } )
33 + activity.clear_trail( bufnr )
35 + assert.equal( 1, #vim.api.nvim_buf_get_extmarks( bufnr, foreign, 0, -1, {} ) )
36 + assert.equal( 0, #activity.marks( bufnr ) )
37 + end )
39 + it( 'renders ghost text without mutating the buffer', function()
40 + local bufnr = scratch { 'one', 'two', }
41 + local revision = vim.api.nvim_buf_get_changedtick( bufnr )
42 + local before = vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
44 + activity.ghost( bufnr, 0, 'proposed\nchange' )
46 + assert.equal( 1, #activity.ghost_marks( bufnr ) )
47 + assert.equal( revision, vim.api.nvim_buf_get_changedtick( bufnr ) )
48 + assert.same( before, vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ) )
49 + end )
51 + it( 'replaces earlier ghost text and clears on demand', function()
52 + local bufnr = scratch { 'one', }
53 + activity.ghost( bufnr, 0, 'first' )
54 + activity.ghost( bufnr, 0, 'second' )
55 + assert.equal( 1, #activity.ghost_marks( bufnr ) )
57 + activity.ghost_clear( bufnr )
58 + assert.equal( 0, #activity.ghost_marks( bufnr ) )
59 + end )
61 + it( 'ignores empty ghost text', function()
62 + local bufnr = scratch { 'one', }
63 + activity.ghost( bufnr, 0, '' )
64 + assert.equal( 0, #activity.ghost_marks( bufnr ) )
65 + end )
67 + it( 'publishes cross file findings to the quickfix list', function()
68 + local entries = activity.findings( {
69 + { path = 'a.lua', line = 3, column = 2, text = 'first', severity = 'error', },
70 + { path = 'b.lua', line = 1, text = 'second', },
71 + }, 'review' )
73 + assert.equal( 2, #entries )
74 + local list = vim.fn.getqflist()
75 + assert.equal( 2, #list )
76 + assert.equal( 3, list[1].lnum )
77 + assert.equal( 'first', list[1].text )
78 + assert.equal( 'review', vim.fn.getqflist( { title = 0, } ).title )
79 + end )
81 + it( 'publishes window findings to the location list', function()
82 + activity.window_findings( 0, { { path = 'a.lua', line = 2, text = 'local', }, }, 'local review' )
83 + local list = vim.fn.getloclist( 0 )
84 + assert.equal( 1, #list )
85 + assert.equal( 2, list[1].lnum )
86 + end )
88 + it( 'keeps agent diagnostics distinguishable from other producers', function()
89 + local bufnr = scratch { 'one', 'two', }
90 + local foreign = vim.api.nvim_create_namespace 'pretend-language-server'
91 + vim.diagnostic.set( foreign, bufnr, { {
92 + lnum = 0,
93 + col = 0,
94 + message = 'from the language server',
95 + severity = vim.diagnostic.severity.ERROR,
96 + }, } )
98 + activity.diagnose( bufnr, { { line = 2, text = 'from the agent', severity = 'warning', }, } )
100 + local mine = activity.diagnostics( bufnr )
101 + assert.equal( 1, #mine )
102 + assert.equal( 'from the agent', mine[1].message )
103 + assert.equal( 'pi', mine[1].source )
104 + assert.equal( 1, mine[1].lnum )
106 + assert.equal( 2, #vim.diagnostic.get( bufnr ) )
108 + activity.clear_diagnostics( bufnr )
109 + assert.equal( 0, #activity.diagnostics( bufnr ) )
110 + assert.equal( 1, #vim.diagnostic.get( bufnr ) )
111 + end )
113 + it( 'ignores invalid buffers', function()
114 + local bufnr = vim.api.nvim_create_buf( false, true )
115 + vim.api.nvim_buf_delete( bufnr, { force = true, } )
117 + activity.mark_edit( bufnr, { { first = 0, last = 1, }, } )
118 + activity.ghost( bufnr, 0, 'text' )
119 + activity.diagnose( bufnr, { { line = 1, text = 'x', }, } )
121 + assert.same( {}, activity.marks( bufnr ) )
122 + end )
123 +end )

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

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local edit = require 'bugabinga.pivi.edit'
3 +local activity = require 'bugabinga.pivi.activity'
5 +local temp_file = function( lines )
6 + local path = vim.fs.normalize( vim.fn.tempname() .. '.txt' )
7 + vim.fn.writefile( lines, path )
8 + return path
9 +end
11 +local open = function( path )
12 + vim.cmd( 'edit! ' .. vim.fn.fnameescape( path ) )
13 + return vim.api.nvim_get_current_buf()
14 +end
16 +local lines_of = function( bufnr )
17 + return vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
18 +end
20 +describe( 'pivi edit', function()
21 + after_each( function()
22 + vim.cmd 'silent! %bwipeout!'
23 + activity.clear_trail()
24 + end )
26 + it( 'finds the loaded buffer for a path', function()
27 + local path = temp_file { 'one', }
28 + local bufnr = open( path )
29 + assert.equal( bufnr, edit.buffer_for( path ) )
30 + assert.is_nil( edit.buffer_for( path .. '.absent' ) )
31 + end )
33 + it( 'prefers unsaved buffer content over disk content', function()
34 + local path = temp_file { 'on disk', }
35 + local bufnr = open( path )
36 + vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { 'in buffer', } )
38 + local content, source = edit.read( path )
39 + assert.equal( 'in buffer', content )
40 + assert.equal( 'buffer', source )
41 + assert.same( { 'on disk', }, vim.fn.readfile( path ) )
42 + end )
44 + it( 'falls back to disk when no buffer is loaded', function()
45 + local path = temp_file { 'only on disk', }
46 + local content, source = edit.read( path )
47 + assert.equal( 'only on disk', content )
48 + assert.equal( 'disk', source )
49 + end )
51 + it( 'lands an edit in the loaded buffer without a reload', function()
52 + local path = temp_file { 'alpha', 'beta', 'gamma', }
53 + local bufnr = open( path )
55 + local applied = edit.apply( bufnr, { { first = 1, last = 2, lines = { 'BETA', }, }, } )
57 + assert.is_true( applied )
58 + assert.same( { 'alpha', 'BETA', 'gamma', }, lines_of( bufnr ) )
59 + assert.is_true( vim.bo[bufnr].modified )
60 + end )
62 + it( 'keeps a multi part edit inside one undo block', function()
63 + local path = temp_file { 'one', 'two', 'three', 'four', }
64 + local bufnr = open( path )
65 + local before = lines_of( bufnr )
67 + local applied, joined = edit.apply( bufnr, {
68 + { first = 0, last = 1, lines = { 'ONE', }, },
69 + { first = 3, last = 4, lines = { 'FOUR', }, },
70 + } )
72 + assert.is_true( applied )
73 + assert.is_true( joined )
74 + assert.same( { 'ONE', 'two', 'three', 'FOUR', }, lines_of( bufnr ) )
76 + vim.api.nvim_buf_call( bufnr, function() vim.cmd 'silent undo' end )
77 + assert.same( before, lines_of( bufnr ) )
78 + end )
80 + it( 'still applies the edit when neovim refuses to join undo blocks', function()
81 + local path = temp_file { 'one', 'two', 'three', }
82 + local bufnr = open( path )
84 + vim.api.nvim_buf_set_lines( bufnr, 0, 1, false, { 'scratch', } )
85 + vim.api.nvim_buf_call( bufnr, function() vim.cmd 'silent undo' end )
87 + local applied = edit.apply( bufnr, {
88 + { first = 0, last = 1, lines = { 'ONE', }, },
89 + { first = 2, last = 3, lines = { 'THREE', }, },
90 + } )
92 + assert.is_true( applied )
93 + assert.same( { 'ONE', 'two', 'THREE', }, lines_of( bufnr ) )
94 + end )
96 + it( 'marks every changed line with a navigable trail', function()
97 + local path = temp_file { 'one', 'two', 'three', }
98 + local bufnr = open( path )
100 + edit.apply( bufnr, { { first = 1, last = 2, lines = { 'TWO', }, }, } )
102 + assert.is_true( #activity.marks( bufnr ) > 0 )
103 + assert.is_true( #activity.trail() > 0 )
104 + end )
106 + it( 'replaces one unique occurrence', function()
107 + local path = temp_file { 'local value = 1', 'return value', }
108 + local bufnr = open( path )
110 + local applied = edit.replace( bufnr, 'local value = 1', 'local value = 2' )
112 + assert.is_true( applied )
113 + assert.same( { 'local value = 2', 'return value', }, lines_of( bufnr ) )
114 + end )
116 + it( 'refuses an ambiguous replacement', function()
117 + local path = temp_file { 'same', 'same', }
118 + local bufnr = open( path )
120 + local applied, failure = edit.replace( bufnr, 'same', 'other' )
122 + assert.is_false( applied )
123 + assert.equal( 'text is not unique', failure )
124 + assert.same( { 'same', 'same', }, lines_of( bufnr ) )
125 + end )
127 + it( 'refuses a replacement whose text is absent', function()
128 + local path = temp_file { 'one', }
129 + local bufnr = open( path )
130 + local applied, failure = edit.replace( bufnr, 'missing', 'other' )
131 + assert.is_false( applied )
132 + assert.equal( 'text not found', failure )
133 + end )
135 + it( 'makes an agent edit visible to later filesystem readers', function()
136 + local path = temp_file { 'before', }
137 + local bufnr = open( path )
139 + edit.apply( bufnr, { { first = 0, last = 1, lines = { 'after', }, }, } )
140 + assert.same( { 'before', }, vim.fn.readfile( path ) )
142 + assert.is_true( edit.persist( bufnr ) )
143 + assert.same( { 'after', }, vim.fn.readfile( path ) )
144 + assert.is_false( vim.bo[bufnr].modified )
145 + end )
147 + it( 'never persists a scratch buffer', function()
148 + local bufnr = vim.api.nvim_create_buf( false, true )
149 + assert.is_false( edit.persist( bufnr ) )
150 + end )
151 +end )

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

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local follow = require 'bugabinga.pivi.follow'
3 +local fake = dofile 'tests/helpers/pivi_fake.lua'
5 +local temp_file = function( lines )
6 + local path = vim.fs.normalize( vim.fn.tempname() .. '.txt' )
7 + vim.fn.writefile( lines, path )
8 + return path
9 +end
11 +describe( 'pivi follow', function()
12 + after_each( function()
13 + follow.reset()
14 + fake.close_extra_windows()
15 + vim.cmd 'silent! %bwipeout!'
16 + end )
18 + it( 'is disabled until the user selects a mode', function()
19 + assert.is_nil( follow.mode() )
20 + assert.is_nil( follow.to { path = temp_file { 'one', }, line = 1, } )
21 + end )
23 + it( 'toggles on and off', function()
24 + assert.equal( 'window', follow.toggle() )
25 + assert.is_nil( follow.toggle() )
26 + assert.equal( 'tab', follow.toggle 'tab' )
27 + end )
29 + it( 'refuses an unknown mode', function()
30 + follow.set 'window'
31 + assert.equal( 'window', follow.set 'sideways' )
32 + end )
34 + it( 'follows into a dedicated window without taking the working window', function()
35 + local working = vim.api.nvim_get_current_win()
36 + local path = temp_file { 'one', 'two', 'three', }
37 + follow.set 'window'
39 + local target = follow.to { path = path, line = 3, }
41 + assert.is_number( target )
42 + assert.is_not.equal( working, target )
43 + assert.equal( working, vim.api.nvim_get_current_win() )
44 + assert.equal( 3, vim.api.nvim_win_get_cursor( target )[1] )
45 + end )
47 + it( 'reuses its dedicated window for later locations', function()
48 + follow.set 'window'
49 + local first = follow.to { path = temp_file { 'a', }, line = 1, }
50 + local second = follow.to { path = temp_file { 'b', 'c', }, line = 2, }
51 + assert.equal( first, second )
52 + end )
54 + it( 'clamps a location beyond the end of the file', function()
55 + follow.set 'window'
56 + local target = follow.to { path = temp_file { 'only', }, line = 99, }
57 + assert.equal( 1, vim.api.nvim_win_get_cursor( target )[1] )
58 + end )
60 + it( 'follows in the current window when asked', function()
61 + follow.set 'current'
62 + local working = vim.api.nvim_get_current_win()
63 + local target = follow.to { path = temp_file { 'one', 'two', }, line = 2, }
64 + assert.equal( working, target )
65 + end )
67 + it( 'returns to the location held before following began', function()
68 + local path = temp_file { 'alpha', 'beta', 'gamma', }
69 + vim.cmd( 'edit! ' .. vim.fn.fnameescape( path ) )
70 + local working = vim.api.nvim_get_current_win()
71 + local buffer = vim.api.nvim_get_current_buf()
72 + vim.api.nvim_win_set_cursor( working, { 2, 0, } )
74 + follow.set 'window'
75 + follow.to { path = temp_file { 'elsewhere', }, line = 1, }
77 + assert.is_true( follow.back() )
78 + assert.equal( working, vim.api.nvim_get_current_win() )
79 + assert.equal( buffer, vim.api.nvim_get_current_buf() )
80 + assert.equal( 2, vim.api.nvim_win_get_cursor( working )[1] )
81 + end )
83 + it( 'reports nothing to return to when following never happened', function()
84 + assert.is_false( follow.back() )
85 + end )
86 +end )

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

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local publish = require 'bugabinga.pivi.publish'
3 +local status = require 'bugabinga.pivi.status'
5 +describe( 'pivi publish', function()
6 + after_each( function()
7 + publish.reset()
8 + end )
10 + it( 'reports nothing when pivi never published anything', function()
11 + vim.g[publish.variable] = nil
12 + assert.equal( '', publish.summary() )
13 + assert.same( {}, publish.read().sessions )
14 + end )
16 + it( 'caches one session status in a native variable', function()
17 + local state = status.reduce( status.initial(), { type = 'agent_start', } )
18 + publish.session_status( 'work', state )
20 + local cached = publish.read()
21 + assert.equal( 'work', cached.active )
22 + assert.equal( 'running', cached.sessions.work.run )
23 + assert.equal( 'pi:run', cached.sessions.work.summary )
24 + end )
26 + it( 'announces a change through a semantic user event', function()
27 + local seen = {}
28 + local group = vim.api.nvim_create_augroup( 'pivi_publish_spec', { clear = true, } )
29 + vim.api.nvim_create_autocmd( 'User', {
30 + group = group,
31 + pattern = publish.status_pattern,
32 + callback = function( event ) table.insert( seen, event.data ) end,
33 + } )
35 + publish.session_status( 'work', status.initial() )
37 + assert.equal( 1, #seen )
38 + assert.equal( 'work', seen[1].session )
39 + assert.equal( 'pi:idle', seen[1].status.summary )
41 + vim.api.nvim_del_augroup_by_id( group )
42 + end )
44 + it( 'lets a consumer read cached status without any process', function()
45 + publish.session_status( 'work', status.reduce( status.initial(), {
46 + type = 'tool_execution_start',
47 + toolCallId = 'c1',
48 + toolName = 'grep',
49 + } ) )
51 + local statusline = function() return publish.summary 'work' end
53 + assert.equal( 'pi:grep', statusline() )
54 + assert.equal( 'pi:grep', statusline() )
55 + end )
57 + it( 'degrades to an empty statusline for an unknown session', function()
58 + publish.session_status( 'work', status.initial() )
59 + assert.equal( '', publish.summary 'absent' )
60 + end )
62 + it( 'moves the active session and forgets a removed one', function()
63 + publish.session_status( 'one', status.initial() )
64 + publish.session_status( 'two', status.initial() )
65 + assert.equal( 'one', publish.read().active )
67 + publish.set_active 'two'
68 + assert.equal( 'two', publish.read().active )
70 + publish.remove 'two'
71 + assert.equal( 'one', publish.read().active )
72 + assert.is_nil( publish.read().sessions.two )
73 + end )
75 + it( 'announces activity separately from status', function()
76 + local seen = {}
77 + local group = vim.api.nvim_create_augroup( 'pivi_publish_activity_spec', { clear = true, } )
78 + vim.api.nvim_create_autocmd( 'User', {
79 + group = group,
80 + pattern = publish.activity_pattern,
81 + callback = function( event ) table.insert( seen, event.data ) end,
82 + } )
84 + publish.activity { kind = 'findings', count = 2, }
86 + assert.equal( 1, #seen )
87 + assert.equal( 'findings', seen[1].kind )
89 + vim.api.nvim_del_augroup_by_id( group )
90 + end )
91 +end )

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

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local transcript = require 'bugabinga.pivi.transcript'
4 +describe( 'pivi transcript', function()
5 + after_each( function()
6 + transcript.forget_all()
7 + end )
9 + it( 'creates one scratch buffer per name and reuses it', function()
10 + local first = transcript.ensure 'work'
11 + local again = transcript.ensure 'work'
12 + local other = transcript.ensure 'other'
14 + assert.equal( first, again )
15 + assert.is_not.equal( first, other )
16 + assert.equal( 'nofile', vim.bo[first].buftype )
17 + assert.equal( transcript.filetype, vim.bo[first].filetype )
18 + end )
20 + it( 'keeps the buffer unmodifiable between writes', function()
21 + local bufnr = transcript.ensure 'work'
22 + transcript.line( bufnr, 'hello' )
23 + assert.is_false( vim.bo[bufnr].modifiable )
24 + end )
26 + it( 'continues the final line when a chunk has no newline', function()
27 + local bufnr = transcript.ensure 'work'
28 + transcript.append( bufnr, 'Hel' )
29 + transcript.append( bufnr, 'lo ' )
30 + transcript.append( bufnr, 'world' )
31 + assert.same( { 'Hello world', }, transcript.lines( bufnr ) )
32 + end )
34 + it( 'breaks lines on embedded newlines', function()
35 + local bufnr = transcript.ensure 'work'
36 + transcript.append( bufnr, 'one\ntwo\nthree' )
37 + assert.same( { 'one', 'two', 'three', }, transcript.lines( bufnr ) )
38 + end )
40 + it( 'appends complete lines', function()
41 + local bufnr = transcript.ensure 'work'
42 + transcript.line( bufnr, 'first' )
43 + transcript.line( bufnr, 'second' )
44 + assert.same( { 'first', 'second', '', }, transcript.lines( bufnr ) )
45 + end )
47 + it( 'shows the transcript without stealing the current window', function()
48 + local before = vim.api.nvim_get_current_win()
49 + local bufnr = transcript.ensure 'work'
50 + local win = transcript.show( bufnr )
52 + assert.is_number( win )
53 + assert.is_not.equal( before, win )
54 + assert.equal( before, vim.api.nvim_get_current_win() )
55 + assert.equal( bufnr, vim.api.nvim_win_get_buf( win ) )
57 + assert.equal( win, transcript.show( bufnr ) )
58 + vim.api.nvim_win_close( win, true )
59 + end )
61 + it( 'forgets and deletes a transcript buffer', function()
62 + local bufnr = transcript.ensure 'work'
63 + transcript.forget 'work'
64 + assert.is_false( vim.api.nvim_buf_is_valid( bufnr ) )
65 + assert.is_not.equal( bufnr, transcript.ensure 'work' )
66 + end )
67 +end )

neovim/tests/bugabinga/pivi/help_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local help = require 'bugabinga.pivi.help'
3 +local session = require 'bugabinga.pivi.session'
4 +local transcript = require 'bugabinga.pivi.transcript'
5 +local publish = require 'bugabinga.pivi.publish'
6 +local fake = dofile 'tests/helpers/pivi_fake.lua'
8 +describe( 'pivi help', function()
9 + after_each( function()
10 + fake.drain()
11 + session.stop_all()
12 + transcript.forget_all()
13 + publish.reset()
14 + fake.close_extra_windows()
15 + end )
17 + it( 'runs without persisting a session and without tools', function()
18 + local channel = fake.new()
19 + help.ask( 'what is a quickfix list', { spawn = channel.spawn, } )
21 + assert.is_true( vim.list_contains( channel.command, '--no-session' ) )
22 + assert.is_true( vim.list_contains( channel.command, '--no-tools' ) )
23 + assert.is_true( vim.list_contains( channel.command, '--append-system-prompt' ) )
24 + end )
26 + it( 'streams the answer into its own buffer', function()
27 + local channel = fake.new()
28 + local run = help.ask( 'how do I open the quickfix list', { spawn = channel.spawn, } )
30 + channel.frame {
31 + type = 'message_update',
32 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = 'use :copen', },
33 + }
35 + assert.is_true( channel.settle( function() return run.answer == 'use :copen' end ) )
36 + assert.is_true( vim.list_contains( transcript.lines( run.buffer ), 'use :copen' ) )
37 + end )
39 + it( 'ends its own process once the answer settles', function()
40 + local channel = fake.new()
41 + local finished
42 + local run = help.ask( 'anything', { spawn = channel.spawn, on_done = function( value ) finished = value end, } )
44 + channel.frame { type = 'agent_settled', }
46 + assert.is_true( channel.settle( function() return finished ~= nil end ) )
47 + assert.is_true( run.done )
48 + assert.is_true( channel.killed )
49 + end )
51 + it( 'answers while a working session runs, leaving it untouched', function()
52 + local work = fake.new()
53 + local working = session.create {
54 + spawn = work.spawn,
55 + name = 'work',
56 + extension = false,
57 + env = {},
58 + }
59 + working.submit( 'long task', { capture = false, } )
60 + work.frame { type = 'agent_start', }
61 + assert.is_true( work.settle( function() return working.status.run == 'running' end ) )
63 + local transcript_before = vim.deepcopy( transcript.lines( working.buffer ) )
64 + local commands_before = #work.commands
65 + local status_before = vim.deepcopy( working.status )
67 + local channel = fake.new()
68 + local run = help.ask( 'what does :checktime do', { spawn = channel.spawn, } )
69 + channel.frame {
70 + type = 'message_update',
71 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = 'it reloads changed files', },
72 + }
73 + assert.is_true( channel.settle( function() return run.answer ~= '' end ) )
75 + assert.is_not.equal( run.buffer, working.buffer )
76 + assert.same( transcript_before, transcript.lines( working.buffer ) )
77 + assert.equal( commands_before, #work.commands )
78 + assert.same( status_before.queue, working.status.queue )
79 + assert.equal( status_before.run, working.status.run )
80 + end )
82 + it( 'reports its own failure without disturbing a working session', function()
83 + local work = fake.new()
84 + local working = session.create { spawn = work.spawn, name = 'work', extension = false, env = {}, }
86 + local channel = fake.new()
87 + local run = help.ask( 'anything', { spawn = channel.spawn, } )
88 + local id = channel.commands[1].id
89 + channel.frame { id = id, type = 'response', command = 'prompt', success = false, error = 'help unavailable', }
91 + assert.is_true( channel.settle( function() return run.done end ) )
92 + assert.is_true( vim.list_contains( transcript.lines( run.buffer ), '! help unavailable' ) )
93 + assert.equal( 'running', working.status.connection )
94 + assert.is_nil( working.status.error )
95 + end )
96 +end )

neovim/tests/bugabinga/pivi/jsonl_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local jsonl = require 'bugabinga.pivi.jsonl'
4 +local FIXTURES = {
5 + 'tests/fixtures/pivi/rpc-no-llm.jsonl',
6 + 'tests/fixtures/pivi/rpc-provider-error.jsonl',
7 +}
9 +local read_fixture = function( path )
10 + return table.concat( vim.fn.readfile( path ), '\n' ) .. '\n'
11 +end
13 +describe( 'pivi jsonl', function()
14 + it( 'splits records on line feed only', function()
15 + local splitter = jsonl.splitter()
16 + local records = splitter.feed '{"a":1}\n{"b":2}\n'
17 + assert.same( { '{"a":1}', '{"b":2}', }, records )
18 + end )
20 + it( 'strips a trailing carriage return', function()
21 + local splitter = jsonl.splitter()
22 + local records = splitter.feed '{"a":1}\r\n'
23 + assert.same( { '{"a":1}', }, records )
24 + end )
26 + it( 'never splits on unicode line separators inside strings', function()
27 + local splitter = jsonl.splitter()
28 + local payload = '{"text":"before\u{2028}after\u{2029}end"}'
29 + local records = splitter.feed( payload .. '\n' )
30 + assert.equal( 1, #records )
31 + local value = jsonl.parse( records[1] )
32 + assert.equal( 'before\u{2028}after\u{2029}end', value.text )
33 + end )
35 + it( 'buffers an unterminated record until its line feed arrives', function()
36 + local splitter = jsonl.splitter()
37 + assert.same( {}, splitter.feed '{"a"' )
38 + assert.same( {}, splitter.feed ':1}' )
39 + assert.same( { '{"a":1}', }, splitter.feed '\n' )
40 + assert.equal( '', splitter.buffered() )
41 + end )
43 + it( 'returns the unterminated remainder on finish', function()
44 + local splitter = jsonl.splitter()
45 + splitter.feed '{"a":1}'
46 + assert.same( { '{"a":1}', }, splitter.finish() )
47 + assert.same( {}, splitter.finish() )
48 + end )
50 + it( 'ignores empty records and nil chunks', function()
51 + local splitter = jsonl.splitter()
52 + assert.same( {}, splitter.feed( nil ) )
53 + assert.same( { '{"a":1}', }, splitter.feed '\n\n{"a":1}\n' )
54 + end )
56 + it( 'reports a decode failure instead of throwing', function()
57 + local value, failure = jsonl.parse 'not json'
58 + assert.is_nil( value )
59 + assert.is_string( failure )
60 + end )
62 + it( 'rejects records that are not JSON objects', function()
63 + local value, failure = jsonl.parse '42'
64 + assert.is_nil( value )
65 + assert.equal( 'record is not a JSON object', failure )
66 + end )
68 + for _, fixture in ipairs( FIXTURES ) do
69 + it( 'recovers the same records under random chunk boundaries: ' .. fixture, function()
70 + local payload = read_fixture( fixture )
72 + local whole = jsonl.splitter()
73 + local expected = whole.feed( payload )
74 + assert.is_true( #expected > 0 )
76 + math.randomseed( 42 )
77 + for _ = 1, 40 do
78 + local splitter = jsonl.splitter()
79 + local records = {}
80 + local index = 1
81 + while index <= #payload do
82 + local size = math.random( 1, 97 )
83 + local chunk = payload:sub( index, index + size - 1 )
84 + index = index + size
85 + for _, record in ipairs( splitter.feed( chunk ) ) do
86 + table.insert( records, record )
87 + end
88 + end
89 + for _, record in ipairs( splitter.finish() ) do
90 + table.insert( records, record )
91 + end
92 + assert.same( expected, records )
93 + end
94 + end )
95 + end
97 + it( 'parses every record of a recorded pi run', function()
98 + local splitter = jsonl.splitter()
99 + for _, record in ipairs( splitter.feed( read_fixture( FIXTURES[1] ) ) ) do
100 + local value, failure = jsonl.parse( record )
101 + assert.is_nil( failure )
102 + assert.equal( 'response', value.type )
103 + end
104 + end )
105 +end )

neovim/tests/bugabinga/pivi/partial_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local partial = require 'bugabinga.pivi.partial'
4 +describe( 'pivi partial', function()
5 + it( 'reports completion for valid arguments', function()
6 + local result = partial.parse '{"path":"a.lua","new_text":"local x = 1"}'
7 + assert.is_true( result.complete )
8 + assert.equal( 'a.lua', result.value.path )
9 + end )
11 + it( 'recovers fields from a truncated object without throwing', function()
12 + local result = partial.parse '{"path":"a.lua","new_text":"local x ='
13 + assert.is_false( result.complete )
14 + assert.is_nil( result.value )
15 + assert.equal( 'a.lua', result.fields.path )
16 + assert.equal( 'local x =', result.fields.new_text )
17 + end )
19 + it( 'decodes escapes inside a truncated string', function()
20 + local result = partial.parse '{"new_text":"line one\\nline \\"two\\"'
21 + assert.equal( 'line one\nline "two"', result.fields.new_text )
22 + end )
24 + it( 'survives every prefix of a complete argument object', function()
25 + local complete = '{"path":"src/main.lua","old_text":"a","new_text":"b"}'
26 + for length = 1, #complete do
27 + local result = partial.parse( complete:sub( 1, length ) )
28 + assert.is_table( result.fields )
29 + end
30 + end )
32 + it( 'returns nothing for empty or non string input', function()
33 + assert.is_false( partial.parse( '' ).complete )
34 + assert.is_false( partial.parse( nil ).complete )
35 + end )
37 + it( 'describes streaming edit intent', function()
38 + local intent = partial.intent( 'edit', '{"path":"a.lua","new_text":"half' )
39 + assert.is_false( intent.complete )
40 + assert.equal( 'edit', intent.tool )
41 + assert.equal( 'a.lua', intent.path )
42 + assert.equal( 'half', intent.text )
43 + end )
45 + it( 'describes complete edit intent', function()
46 + local intent = partial.intent( 'write', '{"path":"a.lua","content":"done"}' )
47 + assert.is_true( intent.complete )
48 + assert.equal( 'done', intent.text )
49 + end )
50 +end )

neovim/tests/bugabinga/pivi/rpc_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local rpc = require 'bugabinga.pivi.rpc'
3 +local fake = dofile 'tests/helpers/pivi_fake.lua'
5 +local start = function( channel, options )
6 + options = options or {}
7 + options.command = { 'pi', '--mode', 'rpc', }
8 + options.spawn = channel.spawn
9 + return rpc.start( options )
10 +end
12 +describe( 'pivi rpc', function()
13 + it( 'spawns with the given command and working directory', function()
14 + local channel = fake.new()
15 + start( channel, { cwd = '/tmp', } )
16 + assert.same( { 'pi', '--mode', 'rpc', }, channel.command )
17 + assert.equal( '/tmp', channel.options.cwd )
18 + end )
20 + it( 'writes commands as single line JSONL records', function()
21 + local channel = fake.new()
22 + local client = start( channel )
23 + client.notify { type = 'abort', }
24 + assert.equal( '{"type":"abort"}\n', channel.writes[1] )
25 + end )
27 + it( 'correlates a response with its request id', function()
28 + local channel = fake.new()
29 + local client = start( channel )
30 + local answer
31 + local id = client.request( { type = 'get_state', }, function( response ) answer = response end )
33 + channel.frame { id = 'other', type = 'response', command = 'get_state', success = true, }
34 + channel.frame { id = id, type = 'response', command = 'get_state', success = true, data = { messageCount = 3, }, }
36 + assert.is_true( channel.settle( function() return answer ~= nil end ) )
37 + assert.equal( id, answer.id )
38 + assert.equal( 3, answer.data.messageCount )
39 + end )
41 + it( 'never delivers a frame from a fast event context', function()
42 + local channel = fake.new()
43 + local contexts = {}
44 + start( channel, {
45 + on_event = function() table.insert( contexts, vim.in_fast_event() ) end,
46 + } )
48 + channel.frame { type = 'agent_start', }
49 + assert.is_true( channel.settle( function() return #contexts == 1 end ) )
50 + assert.is_false( contexts[1] )
51 + end )
53 + it( 'delivers interleaved events and responses in arrival order', function()
54 + local channel = fake.new()
55 + local seen = {}
56 + local client = start( channel, {
57 + on_event = function( event ) table.insert( seen, event.type ) end,
58 + } )
59 + client.request( { type = 'prompt', message = 'hi', }, function() table.insert( seen, 'response' ) end )
61 + local id = channel.commands[1].id
62 + channel.emit(
63 + vim.json.encode { id = id, type = 'response', command = 'prompt', success = true, } .. '\n' ..
64 + vim.json.encode { type = 'agent_start', } .. '\n' ..
65 + vim.json.encode { type = 'agent_settled', } .. '\n'
66 + )
68 + assert.is_true( channel.settle( function() return #seen == 3 end ) )
69 + assert.same( { 'response', 'agent_start', 'agent_settled', }, seen )
70 + end )
72 + it( 'reassembles frames split at arbitrary byte boundaries', function()
73 + local channel = fake.new()
74 + local events = {}
75 + start( channel, { on_event = function( event ) table.insert( events, event ) end, } )
77 + local payload = vim.json.encode { type = 'message_update', assistantMessageEvent = { type = 'text_delta', delta = 'hello', }, } .. '\n'
78 + for index = 1, #payload do
79 + channel.emit( payload:sub( index, index ) )
80 + end
82 + assert.is_true( channel.settle( function() return #events == 1 end ) )
83 + assert.equal( 'hello', events[1].assistantMessageEvent.delta )
84 + end )
86 + it( 'reports an undecodable record instead of crashing', function()
87 + local channel = fake.new()
88 + local failures = {}
89 + start( channel, {
90 + on_decode_error = function( record ) table.insert( failures, record ) end,
91 + } )
93 + channel.emit 'this is not json\n'
94 + assert.is_true( channel.settle( function() return #failures == 1 end ) )
95 + assert.equal( 'this is not json', failures[1] )
96 + end )
98 + it( 'keeps standard error separate from protocol output', function()
99 + local channel = fake.new()
100 + local events, noise = {}, {}
101 + start( channel, {
102 + on_event = function( event ) table.insert( events, event ) end,
103 + on_stderr = function( data ) table.insert( noise, data ) end,
104 + } )
106 + channel.stderr_emit 'warning: something\n'
107 + assert.is_true( channel.settle( function() return #noise == 1 end ) )
108 + assert.equal( 0, #events )
109 + end )
111 + it( 'flushes a trailing record and fails pending requests when the child exits', function()
112 + local channel = fake.new()
113 + local events, answers, exits = {}, {}, {}
114 + local client = start( channel, {
115 + on_event = function( event ) table.insert( events, event ) end,
116 + on_exit = function( code ) table.insert( exits, code ) end,
117 + } )
119 + client.request( { type = 'get_state', }, function( response ) table.insert( answers, response ) end )
120 + channel.emit( vim.json.encode { type = 'agent_settled', } )
121 + channel.close( 2 )
123 + assert.is_true( channel.settle( function() return #exits == 1 end ) )
124 + assert.equal( 2, exits[1] )
125 + assert.equal( 1, #events )
126 + assert.equal( 1, #answers )
127 + assert.is_false( answers[1].success )
128 + assert.is_false( client.is_running() )
129 + end )
131 + it( 'rejects a request sent after the child exited', function()
132 + local channel = fake.new()
133 + local client = start( channel )
134 + channel.close( 0 )
135 + assert.is_true( channel.settle( function() return not client.is_running() end ) )
137 + local answer
138 + client.request( { type = 'prompt', message = 'late', }, function( response ) answer = response end )
139 + assert.is_false( answer.success )
140 + assert.is_string( answer.error )
141 + end )
143 + it( 'closes stdin and terminates the child on stop', function()
144 + local channel = fake.new()
145 + local client = start( channel )
146 + client.stop()
147 + assert.is_true( channel.stdin_closed )
148 + assert.is_true( channel.killed )
149 + end )
150 +end )

neovim/tests/bugabinga/pivi/session_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch
2 +local session = require 'bugabinga.pivi.session'
3 +local publish = require 'bugabinga.pivi.publish'
4 +local transcript = require 'bugabinga.pivi.transcript'
5 +local activity = require 'bugabinga.pivi.activity'
6 +local follow = require 'bugabinga.pivi.follow'
7 +local fake = dofile 'tests/helpers/pivi_fake.lua'
9 +local create = function( channel, options )
10 + options = options or {}
11 + options.spawn = channel.spawn
12 + options.name = options.name or 'spec'
13 + options.extension = false
14 + options.env = {}
15 + return session.create( options )
16 +end
18 +local commands_of = function( channel, kind )
19 + local found = {}
20 + for _, command in ipairs( channel.commands ) do
21 + if command.type == kind then table.insert( found, command ) end
22 + end
23 + return found
24 +end
26 +describe( 'pivi session', function()
27 + after_each( function()
28 + fake.drain()
29 + session.stop_all()
30 + transcript.forget_all()
31 + publish.reset()
32 + follow.reset()
33 + activity.clear_trail()
34 + fake.close_extra_windows()
35 + vim.cmd 'silent! %bwipeout!'
36 + end )
38 + local temp_buffer = function( lines )
39 + local path = vim.fs.normalize( vim.fn.tempname() .. '.txt' )
40 + vim.fn.writefile( lines, path )
41 + vim.cmd( 'edit! ' .. vim.fn.fnameescape( path ) )
42 + return vim.api.nvim_get_current_buf(), path
43 + end
45 + it( 'starts pi in rpc mode inside the session working directory', function()
46 + local channel = fake.new()
47 + local current = create( channel, { cwd = vim.uv.cwd(), } )
49 + assert.same( { 'pi', '--mode', 'rpc', '--name', 'spec', }, channel.command )
50 + assert.equal( vim.uv.cwd(), channel.options.cwd )
51 + assert.equal( 'spec', current.name )
52 + assert.same( { 'spec', }, session.list() )
53 + end )
55 + it( 'sends an idle submission as a plain prompt', function()
56 + local channel = fake.new()
57 + local current = create( channel )
59 + local accepted, rejection = current.submit( 'do the thing', { capture = false, } )
61 + assert.is_true( accepted )
62 + assert.is_nil( rejection )
63 + local prompts = commands_of( channel, 'prompt' )
64 + assert.equal( 1, #prompts )
65 + assert.equal( 'do the thing', prompts[1].message )
66 + end )
68 + it( 'rejects a submission during a run instead of silently dropping it', function()
69 + local channel = fake.new()
70 + local current = create( channel )
71 + channel.frame { type = 'agent_start', }
72 + assert.is_true( channel.settle( function() return current.status.run == 'running' end ) )
74 + local accepted, rejection = current.submit( 'late thought', { capture = false, } )
76 + assert.is_false( accepted )
77 + assert.is_string( rejection )
78 + assert.equal( 0, #commands_of( channel, 'prompt' ) )
79 + end )
81 + it( 'accepts an explicit steering delivery during a run', function()
82 + local channel = fake.new()
83 + local current = create( channel )
84 + channel.frame { type = 'agent_start', }
85 + assert.is_true( channel.settle( function() return current.status.run == 'running' end ) )
87 + local accepted = current.submit( 'focus on errors', { capture = false, delivery = 'steer', } )
89 + assert.is_true( accepted )
90 + local steers = commands_of( channel, 'steer' )
91 + assert.equal( 1, #steers )
92 + assert.equal( 'focus on errors', steers[1].message )
93 + end )
95 + it( 'accepts an explicit follow-up delivery during a run', function()
96 + local channel = fake.new()
97 + local current = create( channel )
98 + channel.frame { type = 'agent_start', }
99 + assert.is_true( channel.settle( function() return current.status.run == 'running' end ) )
101 + assert.is_true( current.submit( 'then summarize', { capture = false, delivery = 'follow_up', } ) )
102 + assert.equal( 1, #commands_of( channel, 'follow_up' ) )
103 + end )
105 + it( 'refuses an unknown delivery', function()
106 + local channel = fake.new()
107 + local current = create( channel )
108 + local accepted, rejection = current.submit( 'x', { capture = false, delivery = 'shout', } )
109 + assert.is_false( accepted )
110 + assert.is_string( rejection )
111 + end )
113 + it( 'streams assistant text into the transcript buffer', function()
114 + local channel = fake.new()
115 + local current = create( channel )
117 + channel.frame { type = 'message_start', message = { role = 'assistant', }, }
118 + channel.frame {
119 + type = 'message_update',
120 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = 'hello ', },
122 + channel.frame {
123 + type = 'message_update',
124 + assistantMessageEvent = { type = 'text_delta', contentIndex = 0, delta = 'editor', },
127 + assert.is_true( channel.settle( function()
128 + return vim.list_contains( transcript.lines( current.buffer ), 'hello editor' )
129 + end ) )
130 + end )
132 + it( 'surfaces a rejected submission in the transcript', function()
133 + local channel = fake.new()
134 + local current = create( channel )
135 + current.submit( 'do it', { capture = false, } )
137 + local id = commands_of( channel, 'prompt' )[1].id
138 + channel.frame { id = id, type = 'response', command = 'prompt', success = false, error = 'nope', }
140 + assert.is_true( channel.settle( function()
141 + for _, line in ipairs( transcript.lines( current.buffer ) ) do
142 + if line:find( 'nope', 1, true ) then return true end
143 + end
144 + return false
145 + end ) )
146 + end )
148 + it( 'publishes cached status through a variable and a user event', function()
149 + local channel = fake.new()
150 + local current = create( channel )
152 + local seen = {}
153 + local group = vim.api.nvim_create_augroup( 'pivi_session_spec', { clear = true, } )
154 + vim.api.nvim_create_autocmd( 'User', {
155 + group = group,
156 + pattern = publish.status_pattern,
157 + callback = function( event ) table.insert( seen, event.data ) end,
158 + } )
160 + channel.frame { type = 'agent_start', }
161 + assert.is_true( channel.settle( function() return #seen > 0 end ) )
163 + assert.equal( 'spec', seen[#seen].session )
164 + assert.equal( 'pi:run', publish.summary 'spec' )
165 + assert.equal( 'running', publish.read().sessions.spec.run )
167 + vim.api.nvim_del_augroup_by_id( group )
168 + end )
170 + it( 'marks the session stopped when the child exits', function()
171 + local channel = fake.new()
172 + local current = create( channel )
173 + channel.close( 0 )
175 + assert.is_true( channel.settle( function() return current.status.connection == 'stopped' end ) )
176 + assert.equal( 'pi:off', require( 'bugabinga.pivi.status' ).summary( current.status ) )
177 + end )
179 + it( 'removes a stopped session from the registry and the published state', function()
180 + local channel = fake.new()
181 + local current = create( channel )
182 + current.stop()
184 + assert.same( {}, session.list() )
185 + assert.is_nil( publish.read().sessions.spec )
186 + assert.is_true( channel.killed )
187 + end )
189 + it( 'shows streaming edit intent without touching the buffer', function()
190 + local bufnr, path = temp_buffer { 'local value = 1', }
191 + local revision = vim.api.nvim_buf_get_changedtick( bufnr )
192 + local before = vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
194 + local channel = fake.new()
195 + create( channel )
197 + channel.frame {
198 + type = 'message_update',
199 + assistantMessageEvent = { type = 'toolcall_start', contentIndex = 0, id = 'c1', toolName = 'edit', },
201 + channel.frame {
202 + type = 'message_update',
203 + assistantMessageEvent = {
204 + type = 'toolcall_delta',
205 + contentIndex = 0,
206 + delta = '{"path":"' .. path:gsub( '\\', '\\\\' ) .. '","new_text":"local value = 2',
207 + },
210 + assert.is_true( channel.settle( function() return #activity.ghost_marks( bufnr ) > 0 end ) )
211 + assert.equal( revision, vim.api.nvim_buf_get_changedtick( bufnr ) )
212 + assert.same( before, vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ) )
214 + channel.frame {
215 + type = 'message_update',
216 + assistantMessageEvent = {
217 + type = 'toolcall_end',
218 + contentIndex = 0,
219 + toolCall = { id = 'c1', name = 'edit', arguments = { path = path, new_text = 'local value = 2', }, },
220 + },
223 + assert.is_true( channel.settle( function() return #activity.ghost_marks( bufnr ) == 0 end ) )
224 + assert.same( before, vim.api.nvim_buf_get_lines( bufnr, 0, -1, false ) )
225 + end )
227 + it( 'follows a located tool call when following is enabled', function()
228 + local _, path = temp_buffer { 'one', 'two', 'three', }
229 + local working = vim.api.nvim_get_current_win()
230 + follow.set 'window'
232 + local channel = fake.new()
233 + create( channel )
234 + channel.frame {
235 + type = 'tool_execution_start',
236 + toolCallId = 'c1',
237 + toolName = 'read',
238 + args = { path = path, line = 3, },
241 + assert.is_true( channel.settle( function() return follow.window() ~= nil end ) )
242 + assert.equal( working, vim.api.nvim_get_current_win() )
243 + assert.equal( 3, vim.api.nvim_win_get_cursor( follow.window() )[1] )
244 + end )
246 + it( 'answers an extension dialog with a matching identifier', function()
247 + local original = vim.ui.select
248 + vim.ui.select = function( items, _, on_choice ) on_choice( items[1] ) end
250 + local channel = fake.new()
251 + create( channel )
252 + channel.frame {
253 + type = 'extension_ui_request',
254 + id = 'uuid-1',
255 + method = 'select',
256 + title = 'Allow?',
257 + options = { 'Allow', 'Block', },
260 + assert.is_true( channel.settle( function()
261 + for _, entry in ipairs( channel.commands ) do
262 + if entry.type == 'extension_ui_response' then return true end
263 + end
264 + return false
265 + end ) )
267 + local answer
268 + for _, entry in ipairs( channel.commands ) do
269 + if entry.type == 'extension_ui_response' then answer = entry end
270 + end
271 + assert.equal( 'uuid-1', answer.id )
272 + assert.equal( 'Allow', answer.value )
274 + vim.ui.select = original
275 + end )
277 + it( 'keeps several sessions with distinct names', function()
278 + local first = create( fake.new(), { name = 'one', } )
279 + local second = create( fake.new(), { name = 'two', } )
281 + assert.same( { 'one', 'two', }, session.list() )
282 + assert.is_not.equal( first.buffer, second.buffer )
284 + session.set_active 'two'
285 + assert.equal( 'two', session.active().name )
286 + end )
287 +end )

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 status = require 'bugabinga.pivi.status'
4 +local fold = function( events )
5 + local state = status.initial()
6 + for _, event in ipairs( events ) do
7 + state = status.reduce( state, event )
8 + end
9 + return state
10 +end
12 +describe( 'pivi status', function()
13 + it( 'starts idle and disconnected from any run', function()
14 + local state = status.initial()
15 + assert.equal( 'idle', state.run )
16 + assert.is_false( status.is_busy( state ) )
17 + assert.equal( 'pi:idle', status.summary( state ) )
18 + end )
20 + it( 'never mutates the state it folds', function()
21 + local before = status.initial()
22 + local after = status.reduce( before, { type = 'agent_start', } )
23 + assert.equal( 'idle', before.run )
24 + assert.equal( 'running', after.run )
25 + end )
27 + it( 'tracks a run from start to settlement', function()
28 + local state = fold {
29 + { type = 'agent_start', },
30 + { type = 'tool_execution_start', toolCallId = 'c1', toolName = 'bash', },
31 + }
32 + assert.is_true( status.is_busy( state ) )
33 + assert.equal( 'bash', state.tool.name )
34 + assert.equal( 'pi:bash', status.summary( state ) )
36 + state = status.reduce( state, { type = 'tool_execution_end', toolCallId = 'c1', } )
37 + assert.is_nil( state.tool )
39 + state = status.reduce( state, { type = 'agent_settled', } )
40 + assert.equal( 'idle', state.run )
41 + assert.is_false( status.is_busy( state ) )
42 + end )
44 + it( 'stays busy between agent_end and agent_settled', function()
45 + local state = fold {
46 + { type = 'agent_start', },
47 + { type = 'agent_end', willRetry = false, },
48 + }
49 + assert.is_true( status.is_busy( state ) )
50 + end )
52 + it( 'reports queued steering and follow-up messages', function()
53 + local state = fold {
54 + { type = 'queue_update', steering = { 'focus on errors', }, followUp = { 'summarize', }, },
55 + }
56 + assert.equal( 2, status.pending_count( state ) )
57 + assert.equal( 'pi:idle+2', status.summary( state ) )
58 + end )
60 + it( 'tracks retry and clears it on success', function()
61 + local state = fold {
62 + { type = 'auto_retry_start', attempt = 1, maxAttempts = 3, delayMs = 2000, errorMessage = 'overloaded', },
63 + }
64 + assert.equal( 'retrying', state.run )
65 + assert.equal( 'pi:retry', status.summary( state ) )
67 + state = status.reduce( state, { type = 'auto_retry_end', success = true, attempt = 2, } )
68 + assert.equal( 'running', state.run )
69 + assert.is_nil( state.error )
70 + end )
72 + it( 'keeps the final error when retry gives up', function()
73 + local state = fold {
74 + { type = 'auto_retry_start', attempt = 3, maxAttempts = 3, },
75 + { type = 'auto_retry_end', success = false, attempt = 3, finalError = '529 overloaded', },
76 + }
77 + assert.equal( 'idle', state.run )
78 + assert.equal( '529 overloaded', state.error )
79 + assert.equal( 'pi:error', status.summary( state ) )
80 + end )
82 + it( 'tracks compaction', function()
83 + local state = fold { { type = 'compaction_start', reason = 'threshold', }, }
84 + assert.is_true( state.compacting )
85 + assert.equal( 'pi:compacting', status.summary( state ) )
87 + state = status.reduce( state, { type = 'compaction_end', reason = 'threshold', } )
88 + assert.is_false( state.compacting )
89 + end )
91 + it( 'surfaces a provider error reported on a finished message', function()
92 + local lines = vim.fn.readfile 'tests/fixtures/pivi/rpc-provider-error.jsonl'
93 + local recorded = vim.json.decode( lines[7] )
94 + local state = status.reduce( status.initial(), recorded )
95 + assert.is_string( state.error )
96 + assert.equal( 'pi:error', status.summary( state ) )
97 + end )
99 + it( 'folds a get_state payload without contacting pi', function()
100 + local lines = vim.fn.readfile 'tests/fixtures/pivi/rpc-no-llm.jsonl'
101 + local recorded = vim.json.decode( lines[1] )
102 + local state = status.reduce_state( status.initial(), recorded.data )
103 + assert.equal( 'running', state.connection )
104 + assert.is_string( state.model )
105 + assert.is_string( state.thinking )
106 + end )
108 + it( 'reports a stopped process', function()
109 + local state = status.stopped( status.initial(), 1 )
110 + assert.equal( 'stopped', state.connection )
111 + assert.equal( 1, state.exit_code )
112 + assert.equal( 'pi:off', status.summary( state ) )
113 + end )
115 + it( 'ignores malformed events', function()
116 + local state = status.reduce( status.initial(), 'nonsense' )
117 + assert.equal( 'idle', state.run )
118 + end )
119 +end )

neovim/tests/contract/pi_rpc_spec.lua

Added
new file mode 100644
1 +---@diagnostic disable: need-check-nil, undefined-field
2 +-- Guards the Pi assumptions pivi is built on.
3 +-- These run a real `pi --mode rpc` child, so they are opt in:
4 +-- PIVI_CONTRACT=1 just test tests/contract
5 +-- They make no model call, so they cost nothing beyond process startup.
7 +local jsonl = require 'bugabinga.pivi.jsonl'
8 +local rpc = require 'bugabinga.pivi.rpc'
10 +local enabled = vim.env.PIVI_CONTRACT == '1' and vim.fn.executable 'pi' == 1
12 +local ask = function( commands, predicate )
13 + local frames = {}
14 + local client = rpc.start {
15 + command = { 'pi', '--mode', 'rpc', '--no-session', '--no-extensions', },
16 + cwd = vim.uv.cwd(),
17 + on_event = function( frame ) table.insert( frames, frame ) end,
18 + on_response = function( frame ) table.insert( frames, frame ) end,
19 + }
20 + for _, command in ipairs( commands ) do
21 + client.request( command )
22 + end
23 + vim.wait( 60000, function() return predicate( frames ) end, 50 )
24 + client.stop()
25 + return frames
26 +end
28 +local response_for = function( frames, name )
29 + for _, frame in ipairs( frames ) do
30 + if frame.type == 'response' and frame.command == name then return frame end
31 + end
32 + return nil
33 +end
35 +describe( 'pi rpc contract', function()
36 + if not enabled then
37 + it( 'is skipped without PIVI_CONTRACT=1 and pi on PATH', function()
38 + assert.is_true( true )
39 + end )
40 + return
41 + end
43 + it( 'answers get_state with the fields pivi caches', function()
44 + local frames = ask( { { type = 'get_state', }, }, function( seen )
45 + return response_for( seen, 'get_state' ) ~= nil
46 + end )
48 + local answer = response_for( frames, 'get_state' )
49 + assert.is_true( answer.success )
50 + assert.is_boolean( answer.data.isStreaming )
51 + assert.is_boolean( answer.data.isCompacting )
52 + assert.is_string( answer.data.thinkingLevel )
53 + end )
55 + it( 'lists only commands a non interactive client can invoke', function()
56 + local frames = ask( { { type = 'get_commands', }, }, function( seen )
57 + return response_for( seen, 'get_commands' ) ~= nil
58 + end )
60 + local answer = response_for( frames, 'get_commands' )
61 + assert.is_true( answer.success )
62 + for _, entry in ipairs( answer.data.commands ) do
63 + assert.is_string( entry.name )
64 + assert.is_true( entry.source == 'extension' or entry.source == 'prompt' or entry.source == 'skill' )
65 + assert.is_not.equal( 'settings', entry.name )
66 + assert.is_not.equal( 'hotkeys', entry.name )
67 + end
68 + end )
70 + it( 'reports a failed command instead of closing the channel', function()
71 + local frames = ask( {
72 + { type = 'set_model', provider = 'nope', modelId = 'nope', },
73 + { type = 'get_available_thinking_levels', },
74 + }, function( seen )
75 + return response_for( seen, 'get_available_thinking_levels' ) ~= nil
76 + end )
78 + local failed = response_for( frames, 'set_model' )
79 + assert.is_false( failed.success )
80 + assert.is_string( failed.error )
81 + assert.is_true( response_for( frames, 'get_available_thinking_levels' ).success )
82 + end )
84 + it( 'frames every record as strict line feed delimited JSON', function()
85 + local frames = ask( { { type = 'get_state', }, }, function( seen )
86 + return response_for( seen, 'get_state' ) ~= nil
87 + end )
88 + assert.is_true( #frames > 0 )
89 + for _, frame in ipairs( frames ) do
90 + local encoded = vim.json.encode( frame )
91 + assert.is_nil( encoded:find( '\n', 1, true ) )
92 + assert.is_table( jsonl.parse( encoded ) )
93 + end
94 + end )
95 +end )

neovim/tests/drive/run.lua

Added
new file mode 100644
1 +---@diagnostic disable: need-check-nil, undefined-field, param-type-mismatch, assign-type-mismatch
2 +-- Drives a live Neovim over RPC and asserts pivi's interactive behavior.
3 +-- Run with: just drive
4 +--
5 +-- The server is a real Neovim with the real configuration runtime path, so
6 +-- keymaps, user commands, autocommands, and buffer state behave as they do
7 +-- for a person. Requests are synchronous, so no scenario sleeps.
9 +local ADDRESS = '127.0.0.1:' .. tostring( 6800 + math.random( 1, 180 ) )
11 +local server = vim.system( {
12 + vim.v.progpath,
13 + '--headless',
14 + '--noplugin',
15 + '-u', 'tests/minimal_init.lua',
16 + '--listen', ADDRESS,
17 +}, { stdout = false, stderr = false, } )
19 +local channel
20 +local connected = vim.wait( 20000, function()
21 + local ok, value = pcall( vim.fn.sockconnect, 'tcp', ADDRESS, { rpc = true, } )
22 + if ok and value ~= 0 then
23 + channel = value
24 + return true
25 + end
26 + return false
27 +end, 100 )
29 +if not connected then
30 + io.stderr:write( 'cannot reach the driven neovim at ' .. ADDRESS .. '\n' )
31 + server:kill 'sigterm'
32 + os.exit( 1 )
33 +end
35 +local remote = function( code, arguments )
36 + return vim.rpcrequest( channel, 'nvim_exec_lua', code, arguments or {} )
37 +end
39 +local failures = {}
41 +local scenario = function( name, body )
42 + local ok, failure = pcall( body )
43 + if ok then
44 + print( 'ok ' .. name )
45 + else
46 + failures[#failures + 1] = name
47 + print( 'FAIL ' .. name .. ': ' .. tostring( failure ) )
48 + end
49 +end
51 +local expect = function( condition, message )
52 + if not condition then error( message or 'expectation failed', 2 ) end
53 +end
55 +remote [[
56 + local command = require 'bugabinga.pivi.command'
57 + command.setup()
58 + _G.DRIVE = { picked = false }
59 + vim.ui.select = function( items, _, on_choice )
60 + _G.DRIVE.picked = true
61 + on_choice( nil )
62 + end
63 + return true
64 +]]
66 +scenario( 'the Pi user command exists with subcommand completion', function()
67 + local names = remote [[
68 + return vim.fn.getcompletion('Pi ', 'cmdline')
69 + ]]
70 + expect( vim.list_contains( names, 'ask' ), 'ask is missing from completion' )
71 + expect( vim.list_contains( names, 'help' ), 'help is missing from completion' )
72 +end )
74 +scenario( 'an unknown subcommand is reported rather than executed', function()
75 + local message = remote [[
76 + local seen
77 + local original = vim.notify
78 + vim.notify = function(text) seen = text end
79 + vim.cmd 'Pi levitate'
80 + vim.notify = original
81 + return seen
82 + ]]
83 + expect( type( message ) == 'string', 'no message was shown' )
84 + expect( message:find( 'levitate', 1, true ) ~= nil, 'the message does not name the subcommand' )
85 +end )
87 +scenario( 'slash opens command entry only on the first character', function()
88 + local result = remote [[
89 + local session = require 'bugabinga.pivi.session'
90 + local command = require 'bugabinga.pivi.command'
91 + local current = setmetatable({ name = 'drive' }, { __index = function() return function() end end })
92 + local bufnr = command.open_prompt(current)
93 + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { 'hello' })
94 + return {
95 + first = command.slash_opens_commands(bufnr, 0),
96 + later = command.slash_opens_commands(bufnr, 3),
97 + filetype = vim.bo[bufnr].filetype,
98 + }
99 + ]]
100 + expect( result.first == true, 'slash does not open at the first character' )
101 + expect( result.later == false, 'slash wrongly opens later in the line' )
102 + expect( result.filetype == 'pivi-input', 'the prompt buffer has the wrong filetype' )
103 +end )
105 +scenario( 'typing slash later in the line still searches', function()
106 + local typed = remote [[
107 + vim.cmd 'normal! ggdG'
108 + vim.api.nvim_buf_set_lines(0, 0, -1, false, { 'alpha beta' })
109 + vim.api.nvim_win_set_cursor(0, { 1, 4 })
110 + _G.DRIVE.picked = false
111 + local mapping
112 + for _, entry in ipairs(vim.api.nvim_buf_get_keymap(0, 'n')) do
113 + if entry.lhs == '/' then mapping = entry end
114 + end
115 + return { produced = mapping.callback(), picked = _G.DRIVE.picked }
116 + ]]
117 + expect( typed.produced == '/', 'slash was swallowed away from the first character' )
118 + expect( typed.picked == false, 'the command picker opened away from the first character' )
119 +end )
121 +scenario( 'status consumers read cached state without any pi process', function()
122 + local summary = remote [[
123 + local publish = require 'bugabinga.pivi.publish'
124 + local status = require 'bugabinga.pivi.status'
125 + publish.reset()
126 + local empty = publish.summary()
127 + publish.session_status('drive', status.reduce(status.initial(), { type = 'agent_start' }))
128 + return { empty = empty, running = publish.summary('drive') }
129 + ]]
130 + expect( summary.empty == '', 'an unpublished statusline is not empty' )
131 + expect( summary.running == 'pi:run', 'the cached statusline is wrong: ' .. tostring( summary.running ) )
132 +end )
134 +pcall( vim.fn.chanclose, channel )
135 +server:kill 'sigterm'
137 +if #failures > 0 then
138 + print( tostring( #failures ) .. ' scenario(s) failed' )
139 + os.exit( 1 )
140 +end
142 +print 'all drive scenarios passed'

neovim/tests/fixtures/pivi/rpc-no-llm.jsonl

Added
new file mode 100644
1 +{"id":"r1","type":"response","command":"get_state","success":true,"data":{"model":{"id":"gpt-5.6-luna","name":"GPT-5.6 Luna","api":"openai-codex-responses","provider":"openai-codex","baseUrl":"https://chatgpt.com/backend-api","reasoning":true,"input":["text","image"],"cost":{"input":0.2,"output":1.2,"cacheRead":0.02,"cacheWrite":0.25,"tiers":[{"inputTokensAbove":272000,"input":0.4,"output":1.8,"cacheRead":0.04,"cacheWrite":0.5}]},"contextWindow":272000,"maxTokens":128000,"thinkingLevelMap":{"xhigh":"xhigh","max":"max","minimal":"low"},"compat":{"supportsOpenAIGrammarTools":true,"supportsAdditionalTools":true,"supportsToolSearch":true,"supportsMidConvoSystemMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionId":"01a0b043-dba0-73a4-86aa-32b0ee6934f1","autoCompactionEnabled":true,"messageCount":0,"pendingMessageCount":0}}
2 +{"id":"r2","type":"response","command":"get_commands","success":true,"data":{"commands":[{"name":"llama","description":"Manage llama.cpp router models","source":"extension","sourceInfo":{"path":"<inline:llama.cpp>","source":"inline","scope":"temporary","origin":"top-level"}},{"name":"brainstorm","description":"Brainstorm ideas","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\brainstorm.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"ci","description":"Commit current changes","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\ci.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"desloppy","description":"Find ugliest slop in code and fix it","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\desloppy.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"fix","description":"Fix bug with systematic debugging","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\fix.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"grill","description":"A relentless interview to sharpen a plan or design","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\grill.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"handoff","description":"Compact current conversation into a handoff document","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\handoff.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"live-browser-test","description":"Live-test a browser UI with Chrome CDP or Firefox BiDi","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\live-browser-test.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"live-terminal-test","description":"Live-test an interactive CLI/TUI in observable terminal/tmux","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\live-terminal-test.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"note-taker","description":"Collect rapid note snippets, then compile them in my voice","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\note-taker.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"optimize","description":"Benchmark and optimize code","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\optimize.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"pr","description":"Review, checkout, test, and prepare PR merge for git/jj repos","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\pr.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"refactor","description":"Refactor code safely","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\refactor.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"sensei","description":"Stateful teaching workspace for learning a skill or concept","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\sensei.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"tech-review","description":"Run the ISP technology-review workflow from evidence to team decision","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\tech-review.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"wtf","description":"Agent behavior feedback — surprise, confusion, or annoyance","source":"prompt","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\prompts\\wtf.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:skills","description":"fake skill","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\AGENTS.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:archlinux","description":"Use for Arch Linux system help: configuring the OS, pacman/package management, upgrades, maintenance, AUR/PKGBUILD/makepkg, boot/service/package/software troubleshooting. Not Raspberry Pi or generic Linux unless Arch-specific.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\archlinux\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:ascii-boxes","description":"Draw proper Unicode boxes/tables. Use when output needs aligned terminal boxes, table borders, nested frames, box-drawing chars.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\ascii-boxes\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:chrome-cdp","description":"Inspect, debug, or interact with a page the user has open in local Chrome via Chrome DevTools Protocol. Use only when the user explicitly asks to use their live Chrome/browser/page/session.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\chrome-cdp\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:coding-guidelines","description":"Use before designing, implementing, debugging, testing, or reviewing code.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\coding-guidelines\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:d2","description":"D2 (Declarative Diagramming) language reference — syntax for shapes, connections, containers, styling, SQL tables, sequence diagrams, UML classes. Load when working with D2 diagram code.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\d2\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:desloppy","description":"Use when the user asks to desloppy, clean up, simplify, refactor, or review a specific file, directory, diff, or code scope for messy/sloppy code, code smells, technical debt, duplication, complexity, or overengineering.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\desloppy\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:experimentation","description":"Use for throwaway code or artifacts investigating a technical question. Not normal implementation, permanent tests, or artifact-free research.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\experimentation\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:file-upload","description":"Upload and publicly share human-facing artifacts such as HTML plans, specs, reviews, mockups, videos, screenshots, PDFs, audio, and asciinema recordings. Use only when the user asks to upload, publish, or share a file.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\file-upload\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:firefox-bidi","description":"Inspect, debug, or interact with a local Firefox page via WebDriver BiDi. Use when the user asks to use Firefox/browser/page/session state, including launching a managed Firefox if needed.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\firefox-bidi\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:git-commit","description":"Commit selected changes in a Git repository. Use when asked to commit, record, or split current work without pushing.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\git\\git-commit\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:git-fast-forward","description":"Fast-forward a Git target branch to the current branch and push it without creating a merge commit. Use for direct linear branch integration.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\git\\git-fast-forward\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:git-review","description":"Prepare and inspect a pinned Git branch, commit range, or pair of refs without changing source. Use when a read-only workflow needs a trustworthy Git revision comparison.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\git\\git-review\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:git-sync","description":"Synchronize a Git branch by fetching, rebasing onto its target, testing, and optionally pushing when publication was requested. Use for pull, sync, rebase-and-push, or branch publication requests.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\git\\git-sync\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:github-cli","description":"Access GitHub issues, pull requests, releases, comments, Actions, and repository metadata through the gh CLI. Use when local VCS data is insufficient.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\github\\github-cli\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:github-pr-create","description":"Create or update a GitHub pull request and drive it to review-ready completion. Use when asked to make, open, prepare, publish, or finish a GitHub PR.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\github\\github-pr-create\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:github-pr-merge","description":"Validate, merge, and clean up a GitHub pull request. Use when asked to merge, accept, or integrate a GitHub PR.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\github\\github-pr-merge\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:github-pr-review","description":"Review a GitHub pull request against pinned base and head commits. Use for local PR review, readiness assessment, or drafting and publishing GitHub review feedback.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\github\\github-pr-review\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:google-workspace","description":"Access Google Workspace APIs (Drive, Docs, Calendar, Gmail, Sheets, Slides, Chat, People) via local helper scripts without MCP. Handles OAuth login and direct API calls.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\google-workspace\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:grilling","description":"Interview the user relentlessly about a plan or design. Use when the user wants to stress-test a plan before building, or uses any 'grill' trigger phrases.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\grilling\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:ims-process-review","description":"Use for Confluence IMS/ISO process reviews and Document Owner maintenance. Triggers: IMS, ISO-Prozess, ims-dokument, Prozessprüfung, Prozessreport, Prüfung, Freigabe.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\ims-process-review\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:jj-bookmark-move","description":"Move a Jujutsu target bookmark forward to the current change and push it. Use for direct linear integration without a merge commit.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\jj\\jj-bookmark-move\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:jj-commit","description":"Commit the current Jujutsu change. Use when asked to commit or record work in a jj repository without pushing.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\jj\\jj-commit\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:jj-review","description":"Prepare and inspect pinned Jujutsu revisions, bookmarks, or a change range without modifying source. Use when a read-only workflow needs a trustworthy jj comparison.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\jj\\jj-review\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:jj-sync","description":"Synchronize a Jujutsu change stack by fetching, rebasing onto its target, testing, and optionally pushing when publication was requested. Use for pull, sync, rebase-and-push, or bookmark publication requests.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\jj\\jj-sync\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:linux","description":"Use when diagnosing Linux system issues, asking about host state, systemd/journal logs, services, boot/session problems, permissions, devices, networking, or when a task may need root escalation.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\linux\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:linux-console","description":"Use for real Linux kernel virtual console work: tty1/tty2, /dev/ttyN, Ctrl+Alt+F1 VTs, TERM=linux, getty, vconsole.conf, setfont, loadkeys, setterm, console_codes, fbcon. Not for terminal emulators, /dev/pts ptys, tmux, X11, or Wayland.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\linux-console\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:linux-userland","description":"Use when editing or diagnosing Linux user-owned configuration, XDG paths, shell environment, PATH issues, dotfiles, user systemd units, desktop/session config, caches, state dirs, or app config under HOME.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\linux-userland\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:merge-plan","description":"Use when planning or performing a pull, sync, merge, or rebase with upstream, especially in dirty repositories with conflicts, submodules, or worktrees.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\merge-plan\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:mise","description":"Use when editing Mise config or diagnosing config discovery, activation, shims, trust, installs, or backends. Not for running documented repository tasks.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\mise\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:nerdfont-icons","description":"Resolve Nerd Font nf-* names to verified code points, glyphs, and dev-language escapes. Use when matching Nerd Font icons to hex/Unicode/JS/CSS/HTML/etc.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\nerdfont-icons\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:nushell","description":"Use when writing, debugging, or modernizing Nu code/config, editing .nu files, or translating shell commands to Nushell. Not generic Bash or terminal work.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\nushell\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:pastel","description":"Use for choosing, analyzing, or converting colors, palettes, contrast, and colorblind simulation.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\pastel\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:pi-sessions","description":"Use when locating, inspecting, comparing, or mining saved Pi sessions: session names/IDs, history, transcripts, compaction, errors, aborts, tool timelines, or repeated workflow friction. Not for driving a live Pi terminal.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\pi-sessions\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:presenterm","description":"Use for presentations, slides, or Markdown talks with presenterm.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\presenterm\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:progressive-disclosure","description":"Use when the user asks to remember, add a rule, keep in mind, always/never do something, make sure future agents know something, or otherwise persist guidance/memory.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\progressive-disclosure\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:security","description":"Use for authorized defensive review of first-party product source and configuration, confirming suspected security defects with local regression tests, or privately reporting confirmed defects to authorized maintainers.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\security\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:speak-as-oliver","description":"Write outward-facing text as Oliver (bugabinga), in his voice. Trigger for drafts \"as me\", \"in my voice\", \"on my behalf\", or text he will publish under his name.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\speak-as-oliver\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:terminal-harness","description":"Use when driving or observing an interactive terminal program, including CLIs, TUIs, nested agents, long-running jobs, and terminal E2E tests.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\terminal-harness\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:wiki","description":"Use for research, web/repo sources, persistent knowledge in ~/Notes/Wiki, ingesting URLs/files/text, session lessons, recall, synthesis, and wiki maintenance. Not permission to save every lookup.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\wiki\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:win32-drive","description":"Use for inspecting, driving, or debugging Windows desktop GUIs, including cursor and pointer issues.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\win32-drive\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:windows-filename-guidance","description":"Use for Windows filename rules and failures involving reserved DOS device names such as NUL, invalid or trailing characters, inaccessible cross-platform names, long paths, or files that Windows cannot inspect, rename, or delete normally.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\windows-filename-guidance\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:writing-skills","description":"Use when creating, reviewing, refactoring, or packaging agent skills: SKILL.md files, skill descriptions, references, scripts, assets, discovery, activation, and validation.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\writing-skills\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:x230","description":"Lenovo ThinkPad X230/X230i hardware facts. Use only for explicit ThinkPad X230/X230i hardware questions: ports, devices, storage, display, battery, docking, IDs. Exclude X230 Tablet and unrelated X230 names.","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.pi\\agent\\skills\\x230\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.pi\\agent"}},{"name":"skill:twg","description":"Use TWG whenever Atlassian or company context would help: Jira workitems and issues; Confluence pages and PRDs; Bitbucket PRs; project or goal status and launch readiness; owners, SMEs, approvers, or escalation; personal, org, or leadership work rollups and out-of-office catch-ups; dependency maps; code search, repository, or PR discovery; incidents, on-call, or reliability; and deep internal research across connected sources, docs, work, and people.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-agentic-search","description":"Use with root `twg` for deep iterative enterprise/company knowledge search and internal research with Rovo Search across connected apps/connectors including Confluence, Jira, Drive, Slack, Bitbucket, and GitHub.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-agentic-search\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-bench-lite","description":"Run a lightweight single-prompt A/B comparison of free Atlassian/local MCP context vs TWG CLI graph context using paired read-only agent sessions.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-bench-lite\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-confluence","description":"Use with root `twg` for Confluence content, spaces, hierarchy, authoring, editing, comments, versions, permissions, exports, and CQL. Applies Confluence semantics and safe write rules.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-confluence\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-context-discovery","description":"Use with root `twg` for deep context, dependency maps, related entities, project-to-repo discovery, OOO catch-ups, and \"catch me up\" requests around a concrete anchor.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-context-discovery\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-engineering-work","description":"Use with root `twg` for code search, repositories using an API/package, implementation and reverse-dependency discovery, PR status and reviews, repo contributors, hot areas, and issue-to-PR lookups.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-engineering-work\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-jira","description":"Use with root `twg` for Jira workitems, similar issue discovery, duplicate detection, projects, boards, sprints, fields, transitions, comments, links, and administration. Applies Jira semantics and safe mutation rules.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-jira\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-jira-resolve-merged-work","description":"Clean up stale or unresolved Jira workitems. Dry-run single items, lists, boards, sprints, epics, or projects by matching Jira keys/titles to merged PRs, repos, Rovo/search-code hits, and assignee activity.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-jira-resolve-merged-work\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-operational-health","description":"Use with the root `twg` skill for on-call handoffs, incident response and investigation, post-incident reviews, reliability reviews, Assets refresh, capacity views, meeting summaries, and operational risk readouts.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-operational-health\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-responsibility-routing","description":"Use with root `twg` to route owners, subject-matter experts, maintainers, reviewers, approvers, decision authorities, Heads of Engineering, or escalation paths for a topic, area, ask, project, service, or component.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-responsibility-routing\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-space-creation","description":"Create, design, bootstrap, or clone a whole Confluence space for any domain from a brief, existing space, repository evidence, or another source. Use for space creation or structure adaptation, not individual edits.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-space-creation\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}},{"name":"skill:twg-status-rollups","description":"Use with root `twg` for status rollups, personal work summaries, and decision-readiness or go/no-go briefs. Routes to `pr-tree`, `org-tree`, `work-tree`, or `workitem-tree`.\n","source":"skill","sourceInfo":{"path":"C:\\Users\\okr\\.agents\\skills\\twg-status-rollups\\SKILL.md","source":"auto","scope":"user","origin":"top-level","baseDir":"C:\\Users\\okr\\.agents"}}]}}
3 +{"id":"r3","type":"response","command":"set_model","success":false,"error":"Model not found: nope/nope"}
4 +{"id":"r4","type":"response","command":"get_available_thinking_levels","success":true,"data":{"levels":["off","minimal","low","medium","high","xhigh","max"]}}

neovim/tests/fixtures/pivi/rpc-provider-error.jsonl

Added
new file mode 100644
1 +{"id":"p1","type":"response","command":"prompt","success":true}
2 +{"type":"agent_start"}
3 +{"type":"turn_start"}
4 +{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"Reply with exactly: OK"}],"timestamp":1789663650948}}
5 +{"type":"message_end","message":{"role":"user","content":[{"type":"text","text":"Reply with exactly: OK"}],"timestamp":1789663650948}}
6 +{"type":"message_start","message":{"role":"assistant","content":[],"api":"openai-codex-responses","provider":"openai-codex","model":"gpt-5.6-luna","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","timestamp":1789663650964,"errorMessage":"Codex error: The usage limit has been reached"}}
7 +{"type":"message_end","message":{"role":"assistant","content":[],"api":"openai-codex-responses","provider":"openai-codex","model":"gpt-5.6-luna","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","timestamp":1789663650964,"errorMessage":"Codex error: The usage limit has been reached"}}
8 +{"type":"turn_end","message":{"role":"assistant","content":[],"api":"openai-codex-responses","provider":"openai-codex","model":"gpt-5.6-luna","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","timestamp":1789663650964,"errorMessage":"Codex error: The usage limit has been reached"},"toolResults":[]}
9 +{"type":"agent_end","messages":[{"role":"user","content":[{"type":"text","text":"Reply with exactly: OK"}],"timestamp":1789663650948},{"role":"assistant","content":[],"api":"openai-codex-responses","provider":"openai-codex","model":"gpt-5.6-luna","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","timestamp":1789663650964,"errorMessage":"Codex error: The usage limit has been reached"}],"willRetry":false}
10 +{"type":"agent_settled"}

neovim/tests/helpers/pivi_fake.lua

Added
new file mode 100644
1 +--- Fake Pi child process for pivi specs.
2 +--- Never patches globals: pivi takes its spawner as an argument.
3 +local new = function()
4 + local channel = {
5 + writes = {},
6 + killed = false,
7 + commands = {},
8 + }
10 + channel.spawn = function( command, options )
11 + channel.command = command
12 + channel.options = options
13 + channel.stdout = options.stdout
14 + channel.stderr = options.stderr
15 + channel.on_exit = options.on_exit
16 + return {
17 + write = function( _, data )
18 + if data == nil then
19 + channel.stdin_closed = true
20 + return
21 + end
22 + table.insert( channel.writes, data )
23 + for _, record in ipairs( vim.split( data, '\n', { plain = true, } ) ) do
24 + if record ~= '' then
25 + local ok, value = pcall( vim.json.decode, record )
26 + if ok then table.insert( channel.commands, value ) end
27 + end
28 + end
29 + end,
30 + kill = function() channel.killed = true end,
31 + }
32 + end
34 + --- Emits raw bytes on the child's stdout.
35 + channel.emit = function( text ) channel.stdout( nil, text ) end
37 + --- Emits one frame as a complete JSONL record.
38 + channel.frame = function( value ) channel.emit( vim.json.encode( value ) .. '\n' ) end
40 + channel.stderr_emit = function( text ) channel.stderr( nil, text ) end
42 + channel.close = function( code ) channel.on_exit { code = code or 0, } end
44 + --- Waits for a predicate without sleeping blindly.
45 + channel.settle = function( predicate )
46 + return vim.wait( 2000, predicate, 5 )
47 + end
49 + --- Waits until every scheduled callback so far has run.
50 + channel.flush = function()
51 + local done = false
52 + vim.schedule( function() done = true end )
53 + vim.wait( 2000, function() return done end, 1 )
54 + end
56 + return channel
57 +end
59 +--- Runs the event loop briefly so callbacks scheduled by a finished test
60 +--- cannot surface after its stubs and buffers are gone.
61 +local drain = function( milliseconds )
62 + vim.wait( milliseconds or 60, function() return false end, 5 )
63 +end
65 +--- Closes every window except the first so repeated splits cannot exhaust space.
66 +local close_extra_windows = function()
67 + local wins = vim.api.nvim_tabpage_list_wins( 0 )
68 + for index = 2, #wins do
69 + pcall( vim.api.nvim_win_close, wins[index], true )
70 + end
71 + for _, tabpage in ipairs( vim.api.nvim_list_tabpages() ) do
72 + if tabpage ~= vim.api.nvim_get_current_tabpage() then
73 + pcall( vim.api.nvim_win_close, vim.api.nvim_tabpage_list_wins( tabpage )[1], true )
74 + end
75 + end
76 +end
78 +return { new = new, drain = drain, close_extra_windows = close_extra_windows, }