-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathmain.go
More file actions
632 lines (574 loc) · 20.2 KB
/
Copy pathmain.go
File metadata and controls
632 lines (574 loc) · 20.2 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
629
630
631
632
package main
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/minicodemonkey/chief/internal/agent"
"github.com/minicodemonkey/chief/internal/cmd"
"github.com/minicodemonkey/chief/internal/config"
"github.com/minicodemonkey/chief/internal/git"
"github.com/minicodemonkey/chief/internal/loop"
"github.com/minicodemonkey/chief/internal/prd"
"github.com/minicodemonkey/chief/internal/tui"
)
// Version is set at build time via ldflags
var Version = "dev"
// TUIOptions holds the parsed command-line options for the TUI
type TUIOptions struct {
PRDPath string
MaxIterations int
Verbose bool
Merge bool
Force bool
NoRetry bool
Agent string // --agent claude|codex|opencode|cursor
AgentPath string // --agent-path
}
func main() {
// Handle subcommands first
if len(os.Args) > 1 {
switch os.Args[1] {
case "new":
runNew()
return
case "edit":
runEdit()
return
case "status":
runStatus()
return
case "list":
runList()
return
case "help":
printHelp()
return
case "--help", "-h":
printHelp()
return
case "--version", "-v":
fmt.Printf("chief version %s\n", Version)
return
case "update":
runUpdate()
return
case "wiggum":
printWiggum()
return
}
}
// Non-blocking version check on startup (for interactive TUI sessions)
cmd.CheckVersionOnStartup(Version)
// Parse flags for TUI mode
opts := parseTUIFlags()
// Handle special flags that were parsed
if opts == nil {
// Already handled (--help or --version)
return
}
// Run the TUI
runTUIWithOptions(opts)
}
// findAvailablePRD looks for any available PRD in .chief/prds/
// Returns the path to the first PRD found, or empty string if none exist.
func findAvailablePRD() string {
prdsDir := ".chief/prds"
entries, err := os.ReadDir(prdsDir)
if err != nil {
return ""
}
for _, entry := range entries {
if entry.IsDir() {
prdPath := filepath.Join(prdsDir, entry.Name(), "prd.md")
if _, err := os.Stat(prdPath); err == nil {
return prdPath
}
}
}
return ""
}
// listAvailablePRDs returns all PRD names in .chief/prds/
func listAvailablePRDs() []string {
prdsDir := ".chief/prds"
entries, err := os.ReadDir(prdsDir)
if err != nil {
return nil
}
var names []string
for _, entry := range entries {
if entry.IsDir() {
prdPath := filepath.Join(prdsDir, entry.Name(), "prd.md")
if _, err := os.Stat(prdPath); err == nil {
names = append(names, entry.Name())
}
}
}
return names
}
// parseAgentFlags extracts --agent and --agent-path from args[startIdx:],
// returning the agent name, agent path, remaining args (with agent flags removed),
// and the updated index offsets. It exits on missing values.
func parseAgentFlags(args []string, startIdx int) (agentName, agentPath string, remaining []string) {
for i := startIdx; i < len(args); i++ {
arg := args[i]
switch {
case arg == "--agent":
if i+1 < len(args) {
i++
agentName = args[i]
} else {
fmt.Fprintf(os.Stderr, "Error: --agent requires a value (claude, codex, opencode, cursor or gemini)\n")
os.Exit(1)
}
case strings.HasPrefix(arg, "--agent="):
agentName = strings.TrimPrefix(arg, "--agent=")
case arg == "--agent-path":
if i+1 < len(args) {
i++
agentPath = args[i]
} else {
fmt.Fprintf(os.Stderr, "Error: --agent-path requires a value\n")
os.Exit(1)
}
case strings.HasPrefix(arg, "--agent-path="):
agentPath = strings.TrimPrefix(arg, "--agent-path=")
default:
remaining = append(remaining, arg)
}
}
return
}
// parseTUIFlags parses command-line flags for TUI mode
func parseTUIFlags() *TUIOptions {
opts := &TUIOptions{
PRDPath: "", // Will be resolved later
MaxIterations: 0, // 0 signals dynamic calculation (remaining stories + 5)
Verbose: false,
Merge: false,
Force: false,
NoRetry: false,
}
// Pre-extract agent flags so they don't interfere with positional arg parsing
opts.Agent, opts.AgentPath, _ = parseAgentFlags(os.Args, 1)
for i := 1; i < len(os.Args); i++ {
arg := os.Args[i]
switch {
case arg == "--help" || arg == "-h":
printHelp()
return nil
case arg == "--version" || arg == "-v":
fmt.Printf("chief version %s\n", Version)
return nil
case arg == "--verbose":
opts.Verbose = true
case arg == "--merge":
opts.Merge = true
case arg == "--force":
opts.Force = true
case arg == "--no-retry":
opts.NoRetry = true
case arg == "--agent" || arg == "--agent-path":
i++ // skip value (already parsed by parseAgentFlags)
case strings.HasPrefix(arg, "--agent=") || strings.HasPrefix(arg, "--agent-path="):
// already parsed by parseAgentFlags
case arg == "--max-iterations" || arg == "-n":
// Next argument should be the number
if i+1 < len(os.Args) {
i++
n, err := strconv.Atoi(os.Args[i])
if err != nil {
fmt.Fprintf(os.Stderr, "Error: invalid value for %s: %s\n", arg, os.Args[i])
os.Exit(1)
}
if n < 1 {
fmt.Fprintf(os.Stderr, "Error: --max-iterations must be at least 1\n")
os.Exit(1)
}
opts.MaxIterations = n
} else {
fmt.Fprintf(os.Stderr, "Error: %s requires a value\n", arg)
os.Exit(1)
}
case strings.HasPrefix(arg, "--max-iterations="):
val := strings.TrimPrefix(arg, "--max-iterations=")
n, err := strconv.Atoi(val)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: invalid value for --max-iterations: %s\n", val)
os.Exit(1)
}
if n < 1 {
fmt.Fprintf(os.Stderr, "Error: --max-iterations must be at least 1\n")
os.Exit(1)
}
opts.MaxIterations = n
case strings.HasPrefix(arg, "-n="):
val := strings.TrimPrefix(arg, "-n=")
n, err := strconv.Atoi(val)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: invalid value for -n: %s\n", val)
os.Exit(1)
}
if n < 1 {
fmt.Fprintf(os.Stderr, "Error: -n must be at least 1\n")
os.Exit(1)
}
opts.MaxIterations = n
case strings.HasPrefix(arg, "-"):
// Unknown flag
fmt.Fprintf(os.Stderr, "Error: unknown flag: %s\n", arg)
fmt.Fprintf(os.Stderr, "Run 'chief --help' for usage.\n")
os.Exit(1)
default:
// Positional argument: PRD name or path
if strings.HasSuffix(arg, ".md") || strings.HasSuffix(arg, ".json") || strings.HasSuffix(arg, "/") {
opts.PRDPath = arg
} else {
// Treat as PRD name
opts.PRDPath = fmt.Sprintf(".chief/prds/%s/prd.md", arg)
}
}
}
return opts
}
func runNew() {
opts := cmd.NewOptions{}
// Parse arguments: chief new [name] [context...] [--agent X] [--agent-path X]
flagAgent, flagPath, positional := parseAgentFlags(os.Args, 2)
// Filter out remaining flags, keep only positional args
var args []string
for _, a := range positional {
if !strings.HasPrefix(a, "-") {
args = append(args, a)
}
}
if len(args) > 0 {
opts.Name = args[0]
}
if len(args) > 1 {
opts.Context = strings.Join(args[1:], " ")
}
opts.Provider = resolveProvider(flagAgent, flagPath)
if err := cmd.RunNew(opts); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func runEdit() {
opts := cmd.EditOptions{}
// Parse arguments: chief edit [name] [--agent X] [--agent-path X]
flagAgent, flagPath, remaining := parseAgentFlags(os.Args, 2)
for _, arg := range remaining {
if opts.Name == "" && !strings.HasPrefix(arg, "-") {
opts.Name = arg
}
}
opts.Provider = resolveProvider(flagAgent, flagPath)
if err := cmd.RunEdit(opts); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func runStatus() {
opts := cmd.StatusOptions{}
// Parse arguments: chief status [name]
if len(os.Args) > 2 && !strings.HasPrefix(os.Args[2], "-") {
opts.Name = os.Args[2]
}
if err := cmd.RunStatus(opts); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func runUpdate() {
if err := cmd.RunUpdate(cmd.UpdateOptions{
Version: Version,
}); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func runList() {
opts := cmd.ListOptions{}
if err := cmd.RunList(opts); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// resolveProvider loads config and resolves the agent provider, exiting on error.
func resolveProvider(flagAgent, flagPath string) loop.Provider {
cwd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
cfg, err := config.Load(cwd)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to load .chief/config.yaml: %v\n", err)
os.Exit(1)
}
provider, err := agent.Resolve(flagAgent, flagPath, cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if err := agent.CheckInstalled(provider); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
return provider
}
func runTUIWithOptions(opts *TUIOptions) {
provider := resolveProvider(opts.Agent, opts.AgentPath)
prdPath := opts.PRDPath
// If no PRD specified, try to find one
if prdPath == "" {
// Try "main" first
mainPath := ".chief/prds/main/prd.md"
if _, err := os.Stat(mainPath); err == nil {
prdPath = mainPath
} else {
// Look for any available PRD
prdPath = findAvailablePRD()
}
// If still no PRD found, run first-time setup
if prdPath == "" {
cwd, _ := os.Getwd()
showGitignore := git.IsGitRepo(cwd) && !git.IsChiefIgnored(cwd)
// Run the first-time setup TUI
result, err := tui.RunFirstTimeSetup(cwd, showGitignore)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if result.Cancelled {
return
}
// Save config from setup
cfg := config.Default()
cfg.OnComplete.Push = result.PushOnComplete
cfg.OnComplete.CreatePR = result.CreatePROnComplete
if err := config.Save(cwd, cfg); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to save config: %v\n", err)
}
// Create the PRD
newOpts := cmd.NewOptions{
Name: result.PRDName,
Provider: provider,
}
if err := cmd.RunNew(newOpts); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Restart TUI with the new PRD
opts.PRDPath = fmt.Sprintf(".chief/prds/%s/prd.md", result.PRDName)
runTUIWithOptions(opts)
return
}
}
prdDir := filepath.Dir(prdPath)
// Auto-migrate: if prd.json exists alongside prd.md, migrate status
jsonPath := filepath.Join(prdDir, "prd.json")
if _, err := os.Stat(jsonPath); err == nil {
fmt.Println("Migrating status from prd.json to prd.md...")
if err := prd.MigrateFromJSON(prdDir); err != nil {
fmt.Printf("Warning: migration failed: %v\n", err)
} else {
fmt.Println("Migration complete (prd.json renamed to prd.json.bak).")
}
}
app, err := tui.NewAppWithOptions(prdPath, opts.MaxIterations, provider)
if err != nil {
// Check if this is a missing PRD file error
if os.IsNotExist(err) || strings.Contains(err.Error(), "no such file") {
fmt.Printf("PRD not found: %s\n", prdPath)
fmt.Println()
// Show available PRDs if any exist
available := listAvailablePRDs()
if len(available) > 0 {
fmt.Println("Available PRDs:")
for _, name := range available {
fmt.Printf(" chief %s\n", name)
}
fmt.Println()
}
fmt.Println("Or create a new one:")
fmt.Println(" chief new # Create default PRD")
fmt.Println(" chief new <name> # Create named PRD")
} else {
fmt.Printf("Error: %v\n", err)
}
os.Exit(1)
}
// Set verbose mode if requested
if opts.Verbose {
app.SetVerbose(true)
}
// Disable retry if requested
if opts.NoRetry {
app.DisableRetry()
}
p := tea.NewProgram(app, tea.WithAltScreen())
model, err := p.Run()
if err != nil {
fmt.Printf("Error running program: %v\n", err)
os.Exit(1)
}
// Check for post-exit actions
if finalApp, ok := model.(tui.App); ok {
switch finalApp.PostExitAction {
case tui.PostExitInit:
// Run new command then restart TUI
newOpts := cmd.NewOptions{
Name: finalApp.PostExitPRD,
Provider: provider,
}
if err := cmd.RunNew(newOpts); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Restart TUI with the new PRD
opts.PRDPath = fmt.Sprintf(".chief/prds/%s/prd.md", finalApp.PostExitPRD)
runTUIWithOptions(opts)
case tui.PostExitEdit:
// Run edit command then restart TUI
editOpts := cmd.EditOptions{
Name: finalApp.PostExitPRD,
Provider: provider,
}
if err := cmd.RunEdit(editOpts); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Restart TUI with the edited PRD
opts.PRDPath = fmt.Sprintf(".chief/prds/%s/prd.md", finalApp.PostExitPRD)
runTUIWithOptions(opts)
}
}
}
func printHelp() {
fmt.Println(`Chief - Autonomous PRD Agent
Usage:
chief [options] [<name>|<path/to/prd.md>]
chief <command> [arguments]
Commands:
new [name] [context] Create a new PRD interactively
edit [name] [options] Edit an existing PRD interactively
status [name] Show progress for a PRD (default: main)
list List all PRDs with progress
update Update Chief to the latest version
help Show this help message
Global Options:
--agent <provider> Agent CLI to use: claude (default), codex, opencode, cursor, or gemini
--agent-path <path> Custom path to agent CLI binary
--max-iterations N, -n N Set maximum iterations (default: dynamic)
--no-retry Disable auto-retry on agent crashes
--verbose Show raw agent output in log
--merge Auto-merge progress on conversion conflicts
--force Auto-overwrite on conversion conflicts
--help, -h Show this help message
--version, -v Show version number
Edit Options:
--merge Auto-merge progress on conversion conflicts
--force Auto-overwrite on conversion conflicts
Positional Arguments:
<name> PRD name (loads .chief/prds/<name>/prd.md)
<path/to/prd.md> Direct path to a prd.md file
Examples:
chief Launch TUI with default PRD (.chief/prds/main/)
chief auth Launch TUI with named PRD (.chief/prds/auth/)
chief ./my-prd.md Launch TUI with specific PRD file
chief -n 20 Launch with 20 max iterations
chief --max-iterations=5 auth
Launch auth PRD with 5 max iterations
chief --verbose Launch with raw agent output visible
chief --agent codex Use Codex CLI instead of Claude
chief --agent cursor Use Cursor CLI as agent
chief new Create PRD in .chief/prds/main/
chief new auth Create PRD in .chief/prds/auth/
chief new auth "JWT authentication for REST API"
Create PRD with context hint
chief edit Edit PRD in .chief/prds/main/
chief edit auth Edit PRD in .chief/prds/auth/
chief edit auth --merge Edit and auto-merge progress
chief status Show progress for default PRD
chief status auth Show progress for auth PRD
chief list List all PRDs with progress
chief --version Show version number`)
}
func printWiggum() {
// ANSI color codes
blue := "\033[34m"
yellow := "\033[33m"
reset := "\033[0m"
art := blue + `
-=
+%#- :=#%#**%-
##+**************#%*-::::=*-
:##***********************+***#
:@#********%#%#******************#*
:##*****%+-:::-%%%%%##************#:
:#%###%%-:::+#*******##%%%*******#%*:
-+%**#%%@@%%%%%%%%%#****#%##*##%%=
-@@%%%%%%%%%%%%%%@*#%%#*##:::
+%%%%%%%%%%%%%%@#+--=#--=#@+:
-@@@@@%@@@@#%#=-=**--+*-----=#:
` + yellow + ` :* *- - :#-:*=-----=#:
%::%@- *: *@# +::=*--#=:-%:
#- =+**##- =*:::#*#-++:*:
#+:-::+--%***-::::::::-*##
:+#:+=:-==-*:::::::::::::::-%
*=::::::::::::::-=*##*:::::::-+
*-::::::::-=+**+-+%%%%+:::::--+
:*%##**==++%%%######%:::::--%-
:-=#--%####%%%%@@+:::::--%=
` + blue + ` -#%%%%#-` + yellow + ` *:::+%%##%%#%%*:::::::-*#%-
:##++++=+++%:` + yellow + ` :@%*:::::::::::::::-=##*%%*%=
:%++++@%#+=++#` + yellow + ` %%%=--:::::---=+%%****%##@%#%%*:
-%=-:-%%%*=+++##` + yellow + ` :*@%***@%%%###*********%%#%********%-
*#+==**%++++++#*-` + yellow + ` :*%@*+*%*%%%%@*********%%**##****%=--#%*#
*%#%-:+*++++*%#=#-` + yellow + ` :%#%#*+***#@%%%@%#%%%@%#*****%****%::::::##%-
:*::::*-%@%@#=*%-` + yellow + ` :%*#%+*******%%%@#*************%****%-::::::**%=
+==%*+-----+%` + yellow + ` %#*%#********#@%%@********%*%***#%**+*%-:::::*#*%:
*=::----##**%:` + yellow + `+%#*@**********@%%%%*+***%-::::::#*%#****%#:::-%***%-
#-:+@#***+*@%` + yellow + `**#%**********%%%#%%*****%::::::-#**%***************%
=%*****+%%+**` + yellow + `@#%***********@%#%%#******%:::::%****@*********+****##
` + blue + ` %*#%@#*+++**#%` + yellow + `************%%%%%#********###*******@**************%:
=#**++***+**@` + yellow + `************%%%%#%%*******************%*************##
%*++******@#` + yellow + `************@%%#%%@*******************#@*************@:
#***+***%#*` + yellow + `************@%%%%%@#*******************#%*************+
+#***##%**` + yellow + `************@%%%%%%%********************%************%
:######**` + yellow + `*+**********%%%%%%%%*********************%************%
:+%@#**` + yellow + `*******+*****#%@@%#******+***************#@*****+*****%:
` + blue + ` @*********************************************##*+**+*****#+
=%%%%%@@@%%#**************************##%%@@@%%%@**********##
=%%#%%%%%%%%%%%%%----====%%%%%%%%%%%%%%%%#%%#%%%%%******#%#*%
:@@%%#%%%%%%%%%%#::::::::*%%%%%%%%%%%%%%%%%%#%%%@@#%%%##***#%
%*##%%@@@@%%%%%::::::::#%%%%%%%@@@@@@%%####****##****#%#==#
:%*********************************************#%#*+=-----*-
:%************************************+********@:::::----=+
##**********+******************+************##::-::=--#-%
=%******************+*+*********************%:=-*:++:#-%
*#*****************************************@*#:*:*=:*+=
%*********#%#**************************+*% -#+%**=:
**************#%%%%###*******************#
=#***************% #****************#
:@***+**********## *****************#
%**************#= =#+******+*******#
=#*************%: :@***************#
:#****+********# #***************#
:#************** =#**************#
:%************%- :%*************##
#***********## %*************%=
-%@@@%######%@@+ =%#***#*#%@@%#@:
:%%%%%%%%%%%%%%%%# +@%%%%%%%%%%%%%%*
+@%%%%%%%%%%%%%%%%+ :%%%%%%%%%%%%%%##@+
#%%%%%%%%%%%@%@%@* :@%%%%%%%%%%%%@%%@*
` + reset + `
"Bake 'em away, toys!"
- Chief Wiggum
`
fmt.Print(art)
}