-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.lua
More file actions
628 lines (560 loc) · 19.6 KB
/
Copy pathinit.lua
File metadata and controls
628 lines (560 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
local config = require("openspec.config")
local context = require("openspec.context")
local discovery = require("openspec.discovery")
local health = require("openspec.health")
local html = require("openspec.html")
local tasks = require("openspec.tasks")
local ui = require("openspec.ui")
local implement = require("openspec.implement")
local registry = require("openspec.registry")
local util = require("openspec.util")
local worktree = require("openspec.worktree")
local M = {}
local function maybe_redirect(change)
local wt_cfg = config.get().implement and config.get().implement.worktree or {}
if wt_cfg.redirect == false then
return change
end
local binding = worktree.binding(change.root, change.name, wt_cfg)
if not binding then
return change
end
if util.normalize_path(change.root) == util.normalize_path(binding.path) then
return change
end
local redirected = vim.tbl_extend("force", {}, change)
redirected.origin_root = change.root
redirected.origin_path = change.path
redirected.origin_tasks_path = change.tasks_path
redirected.root = util.normalize_path(binding.path)
redirected.path = util.normalize_path(util.join_path(binding.path, "openspec", "changes", change.name))
redirected.tasks_path = util.normalize_path(binding.tasks_path)
redirected.worktree = {
path = binding.path,
branch = binding.branch,
}
return redirected
end
local function deliver_change(callback, change)
callback(maybe_redirect(change))
end
local function select_change(callback, opts)
opts = opts or {}
local buffer_path = vim.api.nvim_buf_get_name(0)
local root = discovery.find_root(buffer_path)
if not root then
root = discovery.find_root(vim.fn.getcwd())
end
if not root then
util.notify("No openspec/changes directory found from the current buffer or cwd.", vim.log.levels.WARN)
return
end
local current_change = discovery.change_from_current_buffer(root)
if current_change and not opts.always_select then
deliver_change(callback, current_change)
return
end
local changes = discovery.scan_active_changes(root)
if #changes == 0 then
util.notify("No active OpenSpec changes with tasks.md were found.", vim.log.levels.WARN)
return
end
if #changes == 1 and not opts.always_select then
deliver_change(callback, changes[1])
return
end
vim.ui.select(changes, {
prompt = opts.prompt or "OpenSpec change",
format_item = function(item)
if current_change and item.name == current_change.name then
return item.name .. " (current)"
end
return item.name
end,
}, function(choice)
if choice then
deliver_change(callback, choice)
end
end)
end
local function with_parsed_change(callback, opts)
select_change(function(change)
local parsed, err = tasks.parse_change(change)
if not parsed then
util.notify(err, vim.log.levels.ERROR)
return
end
callback(change, parsed)
end, opts)
end
local function line_arg(params)
if not params or not params.fargs or not params.fargs[1] then
return nil
end
local lnum = tonumber(params.fargs[1])
if not lnum then
util.notify("Task line must be a number.", vim.log.levels.ERROR)
return false
end
return lnum
end
local function show_health(change, parsed, state, opts)
opts = opts or {}
local win = ui.open_workspace(change, parsed, state)
ui.set_findings_quickfix(state, { open = opts.open_quickfix })
if win and vim.api.nvim_win_is_valid(win) then
vim.api.nvim_set_current_win(win)
end
end
function M.summary()
if ui.close_summary() then
return
end
with_parsed_change(function(change, parsed)
ui.open_summary(change, parsed)
end, { always_select = true, prompt = "OpenSpec summary change" })
end
function M.html()
with_parsed_change(function(change, parsed)
html.open(change, parsed)
end)
end
function M.archive_search(params)
local query = ""
if params and params.fargs and #params.fargs > 0 then
query = table.concat(params.fargs, " ")
end
if ui.close_archive_search() then
ui.close_archive_detail()
return
end
local buffer_path = vim.api.nvim_buf_get_name(0)
local root = discovery.find_root(buffer_path)
if not root then
root = discovery.find_root(vim.fn.getcwd())
end
if not root then
util.notify("No openspec/changes directory found from the current buffer or cwd.", vim.log.levels.WARN)
return
end
local changes = discovery.scan_archived_changes(root)
ui.open_archive_search(changes, query)
end
function M.workspace()
with_parsed_change(function(change, parsed)
local state = health.evaluate(change, parsed, {})
show_health(change, parsed, state)
end)
end
local function update_task_status(change, lnum, status)
local current = util.normalize_path(vim.api.nvim_buf_get_name(0))
if M.is_change_tasks_buffer(change, current) then
return tasks.update_buffer_status(0, lnum, status)
end
return tasks.update_file_status(change.tasks_path, lnum, status)
end
function M.is_change_tasks_buffer(change, path)
local current = util.normalize_path(path or vim.api.nvim_buf_get_name(0))
return current ~= ""
and (current == util.normalize_path(change.tasks_path)
or current == util.normalize_path(change.origin_tasks_path or ""))
end
local function select_task(parsed, lnum)
if not lnum then
return parsed.next_task
end
lnum = tonumber(lnum)
if not lnum then
return nil
end
for _, task in ipairs(parsed.tasks) do
if task.lnum == lnum then
return task
end
end
return nil
end
local function refresh_parsed_change(change, fallback)
local current = util.normalize_path(vim.api.nvim_buf_get_name(0))
if M.is_change_tasks_buffer(change, current) then
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
return tasks._parse_lines(lines, change.tasks_path, change.name), nil
end
local refreshed, err = tasks.parse_change(change)
if not refreshed then
return fallback, err
end
return refreshed, nil
end
local function is_complete_instructions(payload)
if not payload then
return false
end
local progress = payload.progress
if progress and tonumber(progress.remaining) == 0 then
return true
end
if payload.isComplete or payload.complete then
return true
end
local state = payload.state or payload.status
return state == "complete" or state == "done" or state == "all_done"
end
local function is_change_complete(state)
local cli_state = state and state.cli or {}
return is_complete_instructions(cli_state.instructions)
end
local function guard_completed_implement(change, state, selected_task)
if selected_task and selected_task.status == "done" then
util.notify(
"Selected task is already done for "
.. change.name
.. ". Move to a pending task, or run from a non-task line for whole-change implementation.",
vim.log.levels.WARN
)
return true
end
if selected_task and selected_task.status == "skipped" then
util.notify(
"Selected task is skipped for " .. change.name .. ". Update the task status before implementing it.",
vim.log.levels.WARN
)
return true
end
if not selected_task and is_change_complete(state) then
util.notify(
"Implementation is already complete for " .. change.name .. ". Run /opsx:verify " .. change.name .. " before archive.",
vim.log.levels.WARN
)
return true
end
return false
end
function M.task_start(params)
local lnum = line_arg(params)
if lnum == false then
return
end
with_parsed_change(function(change, parsed)
local task = select_task(parsed, lnum)
if not task then
task = parsed.next_task
end
if not task then
util.notify("No todo or WIP task is available.", vim.log.levels.ERROR)
return
end
local result, err = update_task_status(change, task.lnum, "wip")
if not result then
util.notify(err, vim.log.levels.ERROR)
return
end
local refreshed, parse_err = refresh_parsed_change(change, parsed)
if parse_err then
util.notify(parse_err, vim.log.levels.WARN)
end
local selected_task = select_task(refreshed, result.lnum) or {
lnum = result.lnum,
path = change.tasks_path,
section = task.section,
status = "wip",
text = task.text,
}
local state = health.evaluate(change, refreshed, { task = selected_task })
show_health(change, refreshed, state, { open_quickfix = true })
util.notify("Task line " .. result.lnum .. " started as WIP.")
end)
end
function M.context(params)
local lnum = line_arg(params)
if lnum == false then
return
end
with_parsed_change(function(change, parsed)
local selected_task = select_task(parsed, lnum)
local state = health.evaluate(change, parsed, { task = selected_task })
if not selected_task then
util.notify("Context generation is best with a selected task or next todo/WIP task.", vim.log.levels.WARN)
end
context.open(change, parsed, state)
end)
end
function M.implement(params)
if not params.fargs or #params.fargs == 0 then
util.notify("Usage: :OpenSpecImplement {provider} [profile=<name>] [model=<model>] [effort=<effort>] [layout=<layout>] [goal=<off|auto|copy>]", vim.log.levels.ERROR)
return
end
local args, args_err = implement.parse_args(params.fargs)
if not args then
util.notify(args_err, vim.log.levels.ERROR)
return
end
local settings, settings_err = implement.resolve_settings(args)
if not settings then
util.notify(settings_err, vim.log.levels.ERROR)
return
end
local valid, valid_err = implement.validate_settings(settings, {})
if not valid then
util.notify(valid_err, vim.log.levels.ERROR)
return
end
with_parsed_change(function(change, parsed)
local current = util.normalize_path(vim.api.nvim_buf_get_name(0))
local selected_task = nil
if M.is_change_tasks_buffer(change, current) then
selected_task = select_task(parsed, vim.fn.line("."))
end
local wt_resolution = nil
local wt_cfg = config.get().implement and config.get().implement.worktree or {}
if settings.worktree ~= "off" then
wt_resolution = worktree.resolve(change.name, settings.worktree, vim.tbl_extend("force", wt_cfg, {
repo_root = change.origin_root or change.root,
}))
if #(wt_resolution.blockers or {}) > 0 then
util.notify("Worktree launch blocked: " .. table.concat(wt_resolution.blockers, "\n"), vim.log.levels.ERROR)
return
end
end
local layout = implement.resolve_layout(settings.layout, implement._tmux_layout(), config.get().implement)
if wt_resolution and layout == "external" then
local template = config.get().implement and config.get().implement.external and config.get().implement.external.command_template
if template and not template:find("{cwd}", 1, true) then
table.insert(wt_resolution.warnings, "external command template does not include {cwd}; the external terminal may ignore the worktree directory")
end
end
local state = health.evaluate(change, parsed, { task = selected_task, fallback_to_next_task = false })
state.worktree_resolution = wt_resolution
if guard_completed_implement(change, state, selected_task) then
return
end
local existing = registry.get(change.name)
if existing then
local proceed = vim.fn.confirm("An OpenSpecImplement session is already registered for " .. change.name .. ". Launch another one?", "&Launch\n&Cancel", 2, "Question") == 1
if not proceed then
util.notify("OpenSpecImplement launch cancelled.")
return
end
end
if wt_resolution and (wt_resolution.action == "create" or wt_resolution.action == "reuse-branch") then
state.git = vim.tbl_extend("force", state.git or {}, wt_resolution.git or {})
state.git.branch = wt_resolution.branch
state.git.worktree = wt_resolution.path
state.git.dirty = {}
end
local lines = context.lines(change, parsed, state)
implement.start(change.name, selected_task, lines, params.fargs, {
args = args,
settings = settings,
settings_validated = true,
layout = layout,
cwd = wt_resolution and wt_resolution.path or vim.fn.getcwd(),
worktree = wt_resolution,
worktree_config = wt_cfg,
})
end)
end
function M.current()
with_parsed_change(function(change, parsed)
local state = health.evaluate(change, parsed, {})
local lines = {
"Current change: " .. change.name,
"Branch: " .. (state.git and state.git.branch or "(unknown)"),
"Worktree: " .. (state.git and state.git.worktree or "(unknown)"),
"Local changes: " .. tostring(#(state.git and state.git.dirty or {})),
"CLI: " .. (state.cli and state.cli.cliAvailable and "available" or "missing"),
"Next recommendation: " .. ((state.recommendations[1] and state.recommendations[1].command) or "none"),
}
vim.notify(table.concat(lines, "\n"), vim.log.levels.INFO, { title = "OpenSpec" })
end)
end
local task_statuses = { "done", "todo", "wip", "skipped" }
local function complete_task_status(arg_lead, cmdline)
if cmdline:match("^%s*OpenSpecTaskStatus%s+%S+%s+") then
return {}
end
local matches = {}
for _, status in ipairs(task_statuses) do
if status:sub(1, #arg_lead) == arg_lead then
table.insert(matches, status)
end
end
return matches
end
function M.task_status(params)
local status = params.fargs[1]
local lnum = params.fargs[2]
if not status then
util.notify("Usage: :OpenSpecTaskStatus {done|todo|wip|skipped} [line]", vim.log.levels.ERROR)
return
end
if #params.fargs > 2 then
util.notify("Usage: :OpenSpecTaskStatus {done|todo|wip|skipped} [line]", vim.log.levels.ERROR)
return
end
if lnum and not tonumber(lnum) then
util.notify("Task line must be a number.", vim.log.levels.ERROR)
return
end
local current = util.normalize_path(vim.api.nvim_buf_get_name(0))
local root = discovery.find_root(current)
local current_change = root and discovery.change_from_current_buffer(root) or nil
if current_change then
local binding = worktree.binding(root, current_change.name, config.get().implement and config.get().implement.worktree or {})
if binding and current == current_change.tasks_path then
local proceed = vim.fn.confirm(
"This change has a live worktree binding. Write status to the origin tasks.md anyway?",
"&Write\n&Cancel",
2,
"Question"
) == 1
if not proceed then
util.notify("Task status update cancelled.")
return
end
end
end
local result, err = tasks.update_current_task_status(status, lnum)
if not result then
util.notify(err, vim.log.levels.ERROR)
return
end
local suffix = result.changed and "" or " (unchanged)"
util.notify("Task line " .. result.lnum .. " set to " .. tasks.status_label(status) .. suffix)
end
function M.worktree(params)
local action = params.fargs[1]
local change_name = params.fargs[2]
local root = discovery.find_root(vim.api.nvim_buf_get_name(0)) or discovery.find_root(vim.fn.getcwd())
if not root then
util.notify("No openspec/changes directory found from the current buffer or cwd.", vim.log.levels.WARN)
return
end
if action == "list" then
local items, err = worktree.list(root, config.get().implement and config.get().implement.worktree or {})
if not items then
util.notify(err, vim.log.levels.ERROR)
return
end
local lines = { "OpenSpec worktrees" }
local sessions = {}
for _, session in ipairs(registry.list()) do
sessions[session.branch or ""] = session
end
for _, item in ipairs(items) do
local session = sessions[item.branch or ""]
local suffix = ""
if session then
local handle = session.pane_id or session.job_id or session.layout or "session"
suffix = string.format(" session:%s/%s %s", session.provider or "provider", session.model or "model", tostring(handle))
end
table.insert(lines, string.format("%s %s%s", item.branch or "(detached)", item.path, suffix))
end
if #items == 0 then
table.insert(lines, "No OpenSpec worktrees found.")
end
vim.notify(table.concat(lines, "\n"), vim.log.levels.INFO, { title = "OpenSpec" })
return
end
if action == "remove" then
if not change_name then
util.notify("Usage: :OpenSpecWorktree remove {change}", vim.log.levels.ERROR)
return
end
local binding, bind_err = worktree.binding(root, change_name, config.get().implement and config.get().implement.worktree or {})
if not binding then
util.notify(bind_err, vim.log.levels.ERROR)
return
end
local proceed = vim.fn.confirm("Remove worktree " .. binding.path .. "?", "&Remove\n&Cancel", 2, "Question") == 1
if not proceed then
util.notify("Worktree removal cancelled.")
return
end
local ok, err = worktree.remove(root, change_name, config.get().implement and config.get().implement.worktree or {})
if not ok then
util.notify(err, vim.log.levels.ERROR)
return
end
util.notify("Removed worktree for " .. change_name .. ".")
return
end
util.notify("Usage: :OpenSpecWorktree {list|remove} [change]", vim.log.levels.ERROR)
end
local function create_commands()
vim.api.nvim_create_user_command("OpenSpecTasksSummary", M.summary, { force = true })
vim.api.nvim_create_user_command("OpenSpecTasksHtml", M.html, { force = true })
vim.api.nvim_create_user_command("OpenSpecWorkspace", M.workspace, {
desc = "Open the OpenSpec workspace state",
force = true,
})
vim.api.nvim_create_user_command("OpenSpecTaskStart", M.task_start, {
desc = "Start the selected task as WIP",
force = true,
nargs = "?",
})
vim.api.nvim_create_user_command("OpenSpecContext", M.context, {
desc = "Open an upstream action context pack",
force = true,
nargs = "?",
})
vim.api.nvim_create_user_command("OpenSpecImplement", M.implement, {
desc = "Launch a provider implementation session with resolved model settings",
force = true,
nargs = "+",
})
vim.api.nvim_create_user_command("OpenSpecArchiveSearch", M.archive_search, {
desc = "Open an archive search view for archived OpenSpec changes",
force = true,
nargs = "?",
})
vim.api.nvim_create_user_command("OpenSpecCurrent", M.current, {
desc = "Report current OpenSpec change health",
force = true,
nargs = "?",
})
vim.api.nvim_create_user_command("OpenSpecTaskStatus", M.task_status, {
complete = complete_task_status,
desc = "Set the checkbox status for the current OpenSpec task line",
force = true,
nargs = "+",
})
vim.api.nvim_create_user_command("OpenSpecWorktree", M.worktree, {
complete = function(arg_lead, cmdline)
if cmdline:match("^%s*OpenSpecWorktree%s+%S+%s+") then
return {}
end
local values = {}
for _, item in ipairs({ "list", "remove" }) do
if item:sub(1, #arg_lead) == arg_lead then
table.insert(values, item)
end
end
return values
end,
desc = "List or remove OpenSpec worktrees",
force = true,
nargs = "+",
})
end
local function create_keymaps()
local mappings = config.get().mappings
vim.keymap.set("n", mappings.summary, M.summary, { desc = "OpenSpec: Task summary" })
vim.keymap.set("n", mappings.html, M.html, { desc = "OpenSpec: HTML change report" })
vim.keymap.set("n", mappings.workspace, M.workspace, { desc = "OpenSpec: Workspace cockpit" })
vim.keymap.set("n", mappings.archive, M.archive_search, { desc = "OpenSpec: Archive search" })
end
function M.setup(opts)
config.setup(opts)
local options = config.get()
if options.commands then
create_commands()
end
if options.keymaps then
create_keymaps()
end
end
M.discovery = discovery
M.health = health
M.tasks = tasks
return M