-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
5486 lines (4853 loc) · 166 KB
/
main.go
File metadata and controls
5486 lines (4853 loc) · 166 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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// task is the local CLI for managing tasks.
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
osexec "os/exec"
"os/signal"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
"github.com/spf13/cobra"
"github.com/bborn/workflow/internal/autocomplete"
"github.com/bborn/workflow/internal/config"
"github.com/bborn/workflow/internal/db"
"github.com/bborn/workflow/internal/executor"
"github.com/bborn/workflow/internal/github"
"github.com/bborn/workflow/internal/mcp"
"github.com/bborn/workflow/internal/ui"
)
var (
version = "dev"
// Styles for CLI output
successStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#10B981"))
errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#EF4444"))
dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#6B7280"))
boldStyle = lipgloss.NewStyle().Bold(true)
)
// getSessionID returns a unique session identifier for this instance.
// Uses PID to ensure each task instance gets its own tmux sessions.
func getSessionID() string {
// Check if SESSION_ID is already set (for child processes)
if sid := os.Getenv("WORKTREE_SESSION_ID"); sid != "" {
return sid
}
// Generate new session ID based on PID
return fmt.Sprintf("%d", os.Getpid())
}
// getUISessionName returns the task-ui session name for this instance.
func getUISessionName() string {
return fmt.Sprintf("task-ui-%s", getSessionID())
}
// getDaemonSessionName returns the task-daemon session name for this instance.
func getDaemonSessionName() string {
return fmt.Sprintf("task-daemon-%s", getSessionID())
}
func main() {
var dangerous bool
rootCmd := &cobra.Command{
Use: "ty",
Short: "Task queue manager",
Long: "A beautiful terminal UI for managing your task queue.",
Version: version,
Run: func(cmd *cobra.Command, args []string) {
// TUI requires tmux for split-pane Claude interaction
if os.Getenv("TMUX") == "" {
if err := execInTmux(); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
return
}
debugStatePath, _ := cmd.Flags().GetString("debug-state-file")
// Run locally
if err := runLocal(dangerous, debugStatePath); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
},
}
rootCmd.SetVersionTemplate(`{{.Version}}
`)
rootCmd.PersistentFlags().BoolVar(&dangerous, "dangerous", false, "Run Claude with --dangerously-skip-permissions (for sandboxed environments)")
rootCmd.PersistentFlags().String("debug-state-file", "", "Path to write debug state JSON on update")
// Debug subcommand
debugCmd := &cobra.Command{
Use: "debug",
Short: "Debugging tools",
}
rootCmd.AddCommand(debugCmd)
// Debug state subcommand
debugStateCmd := &cobra.Command{
Use: "state",
Short: "Dump application state (Model) as JSON",
Long: `Dump the application state (Model) as structured JSON.
This is useful for debugging and for AI agents to verify UI logic.
Examples:
ty debug state
ty debug state --keys "Down,Down,Enter" # Simulate key presses
ty debug state --keys "n,test task,Enter" # Simulate creating a task`,
Run: func(cmd *cobra.Command, args []string) {
keys, _ := cmd.Flags().GetString("keys")
dbPath := db.DefaultPath()
database, err := db.Open(dbPath)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
defer database.Close()
cwd, _ := os.Getwd()
exec := executor.New(database, config.New(database))
model := ui.NewAppModel(database, exec, cwd, version)
// Load tasks synchronously to ensure model is populated
tasks, err := database.ListTasks(db.ListTasksOptions{
IncludeClosed: true,
Limit: 1000,
})
if err == nil {
model.SetTasks(tasks)
// Also update window size to something reasonable
model.Update(tea.WindowSizeMsg{Width: 120, Height: 40})
}
// Simulate key presses if provided
if keys != "" {
keyEvents := parseKeyEvents(keys)
for _, msg := range keyEvents {
model.Update(msg)
}
}
// Generate and print state
state := model.GenerateDebugState()
data, _ := json.MarshalIndent(state, "", " ")
fmt.Println(string(data))
},
}
debugStateCmd.Flags().String("keys", "", "Comma-separated list of keys to simulate (e.g., 'Down,Enter,n')")
debugCmd.AddCommand(debugStateCmd)
// Daemon subcommand - runs executor in background
daemonCmd := &cobra.Command{
Use: "daemon",
Short: "Run the task executor daemon",
Long: "Runs the background executor that processes queued tasks.",
Run: func(cmd *cobra.Command, args []string) {
// Set dangerous mode env var if flag is enabled
// This is checked by executors when spawning Claude sessions
if dangerous {
os.Setenv("WORKTREE_DANGEROUS_MODE", "1")
}
if err := runDaemon(); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
},
}
// Daemon stop subcommand
daemonStopCmd := &cobra.Command{
Use: "stop",
Short: "Stop the daemon",
Run: func(cmd *cobra.Command, args []string) {
if err := stopDaemon(); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
fmt.Println(successStyle.Render("Daemon stopped"))
},
}
daemonCmd.AddCommand(daemonStopCmd)
// Daemon restart subcommand
daemonRestartCmd := &cobra.Command{
Use: "restart",
Short: "Restart the daemon",
Run: func(cmd *cobra.Command, args []string) {
// Stop if running (ignore errors - might not be running)
stopDaemon()
// Small delay to ensure clean shutdown
time.Sleep(100 * time.Millisecond)
// Use --dangerous flag (persistent from root cmd), falling back to env var
restartDangerous := dangerous || os.Getenv("WORKTREE_DANGEROUS_MODE") == "1"
if err := ensureDaemonRunning(restartDangerous); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
fmt.Println(successStyle.Render("Daemon restarted"))
},
}
daemonCmd.AddCommand(daemonRestartCmd)
// Daemon status subcommand
daemonStatusCmd := &cobra.Command{
Use: "status",
Short: "Check daemon status",
Run: func(cmd *cobra.Command, args []string) {
pidFile := getPidFilePath()
modeFile := pidFile + ".mode"
if pid, err := readPidFile(pidFile); err == nil && processExists(pid) {
mode := "safe"
if m, err := os.ReadFile(modeFile); err == nil {
mode = string(m)
}
fmt.Println(successStyle.Render(fmt.Sprintf("Daemon running (pid %d, %s mode)", pid, mode)))
} else {
fmt.Println(dimStyle.Render("Daemon not running"))
}
},
}
daemonCmd.AddCommand(daemonStatusCmd)
rootCmd.AddCommand(daemonCmd)
// Restart subcommand - restart daemon and TUI (preserves agent sessions by default)
var hardRestart bool
restartCmd := &cobra.Command{
Use: "restart",
Short: "Restart the daemon and TUI (preserves agent sessions)",
Long: `Restarts the daemon and TUI while preserving running agent sessions.
Use --hard to kill all tmux sessions for a complete reset.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(dimStyle.Render("Stopping daemon..."))
stopDaemon()
if hardRestart {
fmt.Println(dimStyle.Render("Killing tmux sessions..."))
// Kill all task-daemon-* and task-ui-* sessions
out, _ := osexec.Command("tmux", "list-sessions", "-F", "#{session_name}").Output()
for _, session := range strings.Split(string(out), "\n") {
session = strings.TrimSpace(session)
if strings.HasPrefix(session, "task-daemon-") || strings.HasPrefix(session, "task-ui-") {
osexec.Command("tmux", "kill-session", "-t", session).Run()
}
}
} else {
// Soft restart: only kill the task-ui session, preserve task-daemon sessions with agent windows
fmt.Println(dimStyle.Render("Preserving agent sessions..."))
out, _ := osexec.Command("tmux", "list-sessions", "-F", "#{session_name}").Output()
for _, session := range strings.Split(string(out), "\n") {
session = strings.TrimSpace(session)
// Only kill task-ui sessions, keep task-daemon sessions with Claude windows
if strings.HasPrefix(session, "task-ui-") {
osexec.Command("tmux", "kill-session", "-t", session).Run()
}
}
}
fmt.Println(successStyle.Render("Restarting..."))
time.Sleep(200 * time.Millisecond)
// Re-exec task command
executable, err := os.Executable()
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
syscall.Exec(executable, []string{executable}, os.Environ())
},
}
restartCmd.Flags().BoolVar(&hardRestart, "hard", false, "Kill all tmux sessions (full reset)")
rootCmd.AddCommand(restartCmd)
// Recover subcommand - fix stale references after crash
recoverCmd := &cobra.Command{
Use: "recover",
Short: "Fix stale tmux references after a crash",
Long: `Clears stale daemon_session and tmux_window_id references from tasks.
Use this after your computer crashes or the daemon dies unexpectedly.
Tasks will automatically reconnect to their agent sessions when viewed.`,
Run: func(cmd *cobra.Command, args []string) {
dryRun, _ := cmd.Flags().GetBool("dry-run")
recoverStaleTmuxRefs(dryRun)
},
}
recoverCmd.Flags().Bool("dry-run", false, "Show what would be cleaned up without making changes")
rootCmd.AddCommand(recoverCmd)
// Logs subcommand - tail claude session logs
logsCmd := &cobra.Command{
Use: "logs",
Short: "Tail claude session logs for debugging",
Long: "Streams all claude session logs across all projects in real-time.",
Run: func(cmd *cobra.Command, args []string) {
if err := tailClaudeLogs(); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
},
}
rootCmd.AddCommand(logsCmd)
// Claude hook subcommand - handles Claude Code hook callbacks (internal use)
claudeHookCmd := &cobra.Command{
Use: "claude-hook",
Short: "Handle Claude Code hook callbacks",
Hidden: true, // Internal use only
Run: func(cmd *cobra.Command, args []string) {
hookEvent, _ := cmd.Flags().GetString("event")
if err := handleClaudeHook(hookEvent); err != nil {
// Don't print errors - hooks should be silent
os.Exit(1)
}
},
}
claudeHookCmd.Flags().String("event", "", "Hook event type (Notification, Stop, etc.)")
rootCmd.AddCommand(claudeHookCmd)
// MCP server subcommand - runs the workflow MCP server for a task (internal use)
mcpServerCmd := &cobra.Command{
Use: "mcp-server",
Short: "Run the workflow MCP server for a task",
Hidden: true, // Internal use only - invoked by Claude Code via .mcp.json
Run: func(cmd *cobra.Command, args []string) {
taskID, _ := cmd.Flags().GetInt64("task-id")
if taskID == 0 {
// Also check WORKTREE_TASK_ID environment variable
if taskIDStr := os.Getenv("WORKTREE_TASK_ID"); taskIDStr != "" {
fmt.Sscanf(taskIDStr, "%d", &taskID)
}
}
if taskID == 0 {
fmt.Fprintln(os.Stderr, "task-id is required (via --task-id flag or WORKTREE_TASK_ID env)")
os.Exit(1)
}
if err := runMCPServer(taskID); err != nil {
fmt.Fprintln(os.Stderr, "MCP server error:", err)
os.Exit(1)
}
},
}
mcpServerCmd.Flags().Int64("task-id", 0, "Task ID for the MCP server")
rootCmd.AddCommand(mcpServerCmd)
// Sessions subcommand - manage running agent sessions (supports all executors)
sessionsCmd := &cobra.Command{
Use: "sessions",
Short: "Manage running agent tmux sessions",
Run: func(cmd *cobra.Command, args []string) {
listSessions()
},
}
sessionsListCmd := &cobra.Command{
Use: "list",
Short: "List running agent sessions",
Run: func(cmd *cobra.Command, args []string) {
listSessions()
},
}
sessionsCmd.AddCommand(sessionsListCmd)
sessionsCleanupCmd := &cobra.Command{
Use: "cleanup",
Short: "Kill orphaned agent processes not tied to active task windows",
Run: func(cmd *cobra.Command, args []string) {
force, _ := cmd.Flags().GetBool("force")
cleanupOrphanedSessions(force)
},
}
sessionsCleanupCmd.Flags().BoolP("force", "f", false, "Use SIGKILL instead of SIGTERM to force kill processes")
sessionsCmd.AddCommand(sessionsCleanupCmd)
rootCmd.AddCommand(sessionsCmd)
// Alias: claudes -> sessions (for backwards compatibility)
claudesCmd := &cobra.Command{
Use: "claudes",
Short: "Alias for 'sessions' (deprecated, use 'sessions' instead)",
Hidden: true, // Hide from help but still works
Run: func(cmd *cobra.Command, args []string) {
listSessions()
},
}
rootCmd.AddCommand(claudesCmd)
// Delete subcommand - delete a task, kill its agent session, and remove worktree
deleteCmd := &cobra.Command{
Use: "delete <task-id>",
Short: "Delete a task, kill its agent session, and remove its worktree",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var taskID int64
if _, err := fmt.Sscanf(args[0], "%d", &taskID); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Invalid task ID: "+args[0]))
os.Exit(1)
}
// Get task info for confirmation
dbPath := db.DefaultPath()
database, err := db.Open(dbPath)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
task, err := database.GetTask(taskID)
database.Close()
if err != nil || task == nil {
fmt.Fprintln(os.Stderr, errorStyle.Render(fmt.Sprintf("Task #%d not found", taskID)))
os.Exit(1)
}
// Confirm unless --force flag is set
force, _ := cmd.Flags().GetBool("force")
if !force {
fmt.Printf("Delete task #%d: %s? [y/N] ", taskID, task.Title)
reader := bufio.NewReader(os.Stdin)
response, _ := reader.ReadString('\n')
response = strings.TrimSpace(strings.ToLower(response))
if response != "y" && response != "yes" {
fmt.Println("Cancelled")
return
}
}
if err := deleteTask(taskID); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
fmt.Println(successStyle.Render(fmt.Sprintf("Deleted task #%d", taskID)))
},
}
deleteCmd.Flags().BoolP("force", "f", false, "Skip confirmation prompt")
rootCmd.AddCommand(deleteCmd)
// Create subcommand - create a new task from command line
createCmd := &cobra.Command{
Use: "create [title]",
Short: "Create a new task",
Long: `Create a new task from the command line.
Title is optional if --body is provided; AI will generate a title from the body.
Examples:
task create "Fix login bug"
task create "Add dark mode" --type code --project myapp
task create "Write documentation" --body "Document the API endpoints" --execute
task create "Refactor auth" --executor codex # Use Codex instead of Claude
task create "Urgent bug" --tags "bug,urgent" --pinned # Tagged and pinned task
task create --body "The login button is broken on mobile devices" # AI generates title
task create "QA: PR #2526" --branch fix/ui-overflow --project myapp # Checkout existing branch`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var title string
if len(args) > 0 {
title = args[0]
}
body, _ := cmd.Flags().GetString("body")
body = unescapeNewlines(body) // Convert literal \n to actual newlines
taskType, _ := cmd.Flags().GetString("type")
project, _ := cmd.Flags().GetString("project")
taskExecutor, _ := cmd.Flags().GetString("executor")
execute, _ := cmd.Flags().GetBool("execute")
tags, _ := cmd.Flags().GetString("tags")
pinned, _ := cmd.Flags().GetBool("pinned")
branch, _ := cmd.Flags().GetString("branch")
outputJSON, _ := cmd.Flags().GetBool("json")
// Validate that either title or body is provided
if strings.TrimSpace(title) == "" && strings.TrimSpace(body) == "" {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: either title or --body must be provided"))
os.Exit(1)
}
// Set defaults
if taskType == "" {
taskType = db.TypeCode
}
// Open database
dbPath := db.DefaultPath()
database, err := db.Open(dbPath)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
defer database.Close()
// Validate task type against database types
if taskType == "" {
taskType = db.TypeCode // Default to code if not specified
}
taskTypes, _ := database.ListTaskTypes()
validType := false
var typeNames []string
for _, t := range taskTypes {
typeNames = append(typeNames, t.Name)
if t.Name == taskType {
validType = true
}
}
if !validType {
if len(typeNames) > 0 {
fmt.Fprintln(os.Stderr, errorStyle.Render("Invalid type. Must be one of: "+strings.Join(typeNames, ", ")))
} else {
fmt.Fprintln(os.Stderr, errorStyle.Render("Invalid type. Must be: code, writing, or thinking"))
}
os.Exit(1)
}
// Validate executor if provided
validExecutors := []string{db.ExecutorClaude, db.ExecutorCodex, db.ExecutorGemini, db.ExecutorPi, db.ExecutorOpenCode, db.ExecutorOpenClaw, db.ExecutorVibe}
if taskExecutor != "" {
validExecutor := false
for _, e := range validExecutors {
if e == taskExecutor {
validExecutor = true
break
}
}
if !validExecutor {
fmt.Fprintln(os.Stderr, errorStyle.Render("Invalid executor. Must be one of: "+strings.Join(validExecutors, ", ")))
os.Exit(1)
}
}
// If project not specified, try to detect from cwd
if project == "" {
if cwd, err := os.Getwd(); err == nil {
if p, err := database.GetProjectByPath(cwd); err == nil && p != nil {
project = p.Name
}
}
}
// Generate title from body if title is empty
if strings.TrimSpace(title) == "" && strings.TrimSpace(body) != "" {
var apiKey string
apiKey, _ = database.GetSetting("anthropic_api_key")
svc := autocomplete.NewService(apiKey)
if svc.IsAvailable() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if generatedTitle, genErr := svc.GenerateTitle(ctx, body, project); genErr == nil && generatedTitle != "" {
title = generatedTitle
if !outputJSON {
fmt.Println(dimStyle.Render("Generated title: " + title))
}
}
cancel()
}
// Fallback if generation failed
if strings.TrimSpace(title) == "" {
firstLine := strings.Split(strings.TrimSpace(body), "\n")[0]
if len(firstLine) > 50 {
firstLine = firstLine[:50] + "..."
}
title = firstLine
}
}
// Set initial status
status := db.StatusBacklog
if execute {
status = db.StatusQueued
}
// Create the task
task := &db.Task{
Title: title,
Body: body,
Status: status,
Type: taskType,
Project: project,
Executor: taskExecutor,
Tags: tags,
Pinned: pinned,
SourceBranch: branch,
}
if err := database.CreateTask(task); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
if outputJSON {
output := map[string]interface{}{
"id": task.ID,
"title": task.Title,
"status": task.Status,
"type": task.Type,
"project": task.Project,
"executor": task.Executor,
}
if task.SourceBranch != "" {
output["source_branch"] = task.SourceBranch
}
jsonBytes, _ := json.Marshal(output)
fmt.Println(string(jsonBytes))
} else {
msg := fmt.Sprintf("Created task #%d: %s", task.ID, task.Title)
if branch != "" {
msg += fmt.Sprintf(" (branch: %s)", branch)
}
if execute {
msg += " (queued for execution)"
}
fmt.Println(successStyle.Render(msg))
}
},
}
createCmd.Flags().String("body", "", "Task body/description (if no title, AI generates from body)")
createCmd.Flags().StringP("type", "t", "", "Task type: code, writing, thinking (default: code)")
createCmd.Flags().StringP("project", "p", "", "Project name (auto-detected from cwd if not specified)")
createCmd.Flags().StringP("executor", "e", "", "Task executor: claude, codex, gemini, pi, opencode, openclaw, vibe (default: claude)")
createCmd.Flags().BoolP("execute", "x", false, "Queue task for immediate execution")
createCmd.Flags().String("tags", "", "Task tags (comma-separated)")
createCmd.Flags().Bool("pinned", false, "Pin the task to the top of its column")
createCmd.Flags().StringP("branch", "b", "", "Existing branch to checkout for worktree (e.g., fix/ui-overflow)")
createCmd.Flags().Bool("json", false, "Output in JSON format")
rootCmd.AddCommand(createCmd)
// List subcommand - list tasks
listCmd := &cobra.Command{
Use: "list",
Short: "List tasks",
Long: `List tasks with optional filtering.
Examples:
task list
task list --status queued
task list --project myapp
task list --pr # Show PR/CI status
task list --all --json`,
Run: func(cmd *cobra.Command, args []string) {
status, _ := cmd.Flags().GetString("status")
project, _ := cmd.Flags().GetString("project")
taskType, _ := cmd.Flags().GetString("type")
all, _ := cmd.Flags().GetBool("all")
limit, _ := cmd.Flags().GetInt("limit")
outputJSON, _ := cmd.Flags().GetBool("json")
showPR, _ := cmd.Flags().GetBool("pr")
// Open database
dbPath := db.DefaultPath()
database, err := db.Open(dbPath)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
defer database.Close()
opts := db.ListTasksOptions{
Status: status,
Project: project,
Type: taskType,
Limit: limit,
IncludeClosed: all,
}
tasks, err := database.ListTasks(opts)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
// Fetch PR info if requested
var prCache *github.PRCache
var cfg *config.Config
prInfoMap := make(map[int64]*github.PRInfo)
if showPR {
prCache = github.NewPRCache()
cfg = config.New(database)
for _, t := range tasks {
if t.BranchName != "" {
repoDir := t.WorktreePath
if repoDir == "" {
repoDir = cfg.GetProjectDir(t.Project)
}
if prInfo := prCache.GetPRForBranch(repoDir, t.BranchName); prInfo != nil {
prInfoMap[t.ID] = prInfo
}
}
}
}
if outputJSON {
var output []map[string]interface{}
for _, t := range tasks {
item := map[string]interface{}{
"id": t.ID,
"title": t.Title,
"status": t.Status,
"type": t.Type,
"project": t.Project,
"created_at": t.CreatedAt.Time.Format(time.RFC3339),
}
// Add PR info to JSON output if available
if prInfo, ok := prInfoMap[t.ID]; ok {
item["pr"] = map[string]interface{}{
"number": prInfo.Number,
"url": prInfo.URL,
"state": string(prInfo.State),
"check_state": string(prInfo.CheckState),
"description": prInfo.StatusDescription(),
}
}
output = append(output, item)
}
jsonBytes, _ := json.Marshal(output)
fmt.Println(string(jsonBytes))
} else {
if len(tasks) == 0 {
fmt.Println(dimStyle.Render("No tasks found"))
return
}
// Define status colors
statusStyle := func(status string) lipgloss.Style {
switch status {
case db.StatusQueued:
return lipgloss.NewStyle().Foreground(lipgloss.Color("#F59E0B"))
case db.StatusProcessing:
return lipgloss.NewStyle().Foreground(lipgloss.Color("#3B82F6"))
case db.StatusBlocked:
return lipgloss.NewStyle().Foreground(lipgloss.Color("#EF4444"))
case db.StatusDone:
return lipgloss.NewStyle().Foreground(lipgloss.Color("#10B981"))
default:
return lipgloss.NewStyle().Foreground(lipgloss.Color("#6B7280"))
}
}
// PR status styling
prStatusStyle := func(prInfo *github.PRInfo) string {
if prInfo == nil {
return ""
}
var icon, desc string
var color lipgloss.Color
switch prInfo.State {
case github.PRStateMerged:
icon, desc, color = "M", "merged", lipgloss.Color("#C678DD")
case github.PRStateClosed:
icon, desc, color = "X", "closed", lipgloss.Color("#EF4444")
case github.PRStateDraft:
icon, desc, color = "D", "draft", lipgloss.Color("#6B7280")
case github.PRStateOpen:
switch prInfo.CheckState {
case github.CheckStatePassing:
if prInfo.Mergeable == "MERGEABLE" {
icon, desc, color = "R", "ready", lipgloss.Color("#10B981")
} else if prInfo.Mergeable == "CONFLICTING" {
icon, desc, color = "C", "conflicts", lipgloss.Color("#EF4444")
} else {
icon, desc, color = "P", "passing", lipgloss.Color("#10B981")
}
case github.CheckStateFailing:
icon, desc, color = "F", "failing", lipgloss.Color("#EF4444")
case github.CheckStatePending:
icon, desc, color = "W", "running", lipgloss.Color("#F59E0B")
default:
icon, desc, color = "O", "open", lipgloss.Color("#10B981")
}
}
badge := lipgloss.NewStyle().
Foreground(lipgloss.Color("#FFFFFF")).
Background(color).
Bold(true).
Render(icon)
descStyled := lipgloss.NewStyle().Foreground(color).Render(desc)
return fmt.Sprintf(" %s %s", badge, descStyled)
}
for _, t := range tasks {
id := dimStyle.Render(fmt.Sprintf("#%-4d", t.ID))
status := statusStyle(t.Status).Render(fmt.Sprintf("%-10s", t.Status))
project := ""
if t.Project != "" {
project = dimStyle.Render(fmt.Sprintf("[%s] ", t.Project))
}
// Schedule indicator
prStatus := ""
if showPR {
prStatus = prStatusStyle(prInfoMap[t.ID])
}
fmt.Printf("%s %s %s%s%s\n", id, status, project, t.Title, prStatus)
}
}
},
}
listCmd.Flags().StringP("status", "s", "", "Filter by status: backlog, queued, processing, blocked, done")
listCmd.Flags().StringP("project", "p", "", "Filter by project")
listCmd.Flags().StringP("type", "t", "", "Filter by type: code, writing, thinking")
listCmd.Flags().BoolP("all", "a", false, "Include completed tasks")
listCmd.Flags().IntP("limit", "n", 50, "Maximum number of tasks to return")
listCmd.Flags().Bool("json", false, "Output in JSON format")
listCmd.Flags().Bool("pr", false, "Show PR/CI status (requires network)")
rootCmd.AddCommand(listCmd)
boardCmd := &cobra.Command{
Use: "board",
Short: "Show the Kanban board in the CLI",
Long: `Print the same Backlog / Queued / In Progress / Blocked / Done view
that the TUI shows, either as formatted text or JSON for automation.`,
Run: func(cmd *cobra.Command, args []string) {
outputJSON, _ := cmd.Flags().GetBool("json")
limit, _ := cmd.Flags().GetInt("limit")
if limit <= 0 {
limit = 5
}
dbPath := db.DefaultPath()
database, err := db.Open(dbPath)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
defer database.Close()
tasks, err := database.ListTasks(db.ListTasksOptions{IncludeClosed: true, Limit: 500})
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
snapshot := buildBoardSnapshot(tasks, limit)
if outputJSON {
data, _ := json.MarshalIndent(snapshot, "", " ")
fmt.Println(string(data))
return
}
fmt.Println(boldStyle.Render("Kanban Snapshot"))
fmt.Println(strings.Repeat("─", 50))
for _, column := range snapshot.Columns {
fmt.Printf("%s (%d)\n", column.Label, column.Count)
if column.Count == 0 {
fmt.Println(" (empty)")
fmt.Println()
continue
}
for _, task := range column.Tasks {
line := fmt.Sprintf("- #%d %s", task.ID, task.Title)
if task.Project != "" {
line += fmt.Sprintf(" [%s]", task.Project)
}
if task.Type != "" {
line += fmt.Sprintf(" (%s)", task.Type)
}
if task.Pinned {
line += " 📌"
}
if task.AgeHint != "" {
line += fmt.Sprintf(" • %s", task.AgeHint)
}
fmt.Println(" " + line)
}
if column.Count > len(column.Tasks) {
fmt.Printf(" … +%d more\n", column.Count-len(column.Tasks))
}
fmt.Println()
}
},
}
boardCmd.Flags().Bool("json", false, "Output board snapshot as JSON")
boardCmd.Flags().Int("limit", 5, "Maximum entries to show per column")
rootCmd.AddCommand(boardCmd)
// Tail subcommand - live updating task view grouped by project and status
tailCmd := &cobra.Command{
Use: "tail",
Short: "Live view of tasks organized by project and status",
Long: `Show a continuously updating view of all active tasks,
grouped by project and then by status. Refreshes automatically.
Press Ctrl+C to stop.`,
Run: func(cmd *cobra.Command, args []string) {
interval, _ := cmd.Flags().GetDuration("interval")
showDone, _ := cmd.Flags().GetBool("done")
dbPath := db.DefaultPath()
database, err := db.Open(dbPath)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
defer database.Close()
p := tea.NewProgram(
tailModel{
db: database,
interval: interval,
showDone: showDone,
},
tea.WithAltScreen(),
)
if _, err := p.Run(); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
},
}
tailCmd.Flags().Duration("interval", 2*time.Second, "Refresh interval (e.g. 1s, 500ms)")
tailCmd.Flags().Bool("done", false, "Include completed tasks")
rootCmd.AddCommand(tailCmd)
// Show subcommand - show task details
showCmd := &cobra.Command{
Use: "show <task-id>",
Short: "Show task details",
Long: `Show detailed information about a task.
Examples:
task show 42
task show 42 --json
task show 42 --logs`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var taskID int64
if _, err := fmt.Sscanf(args[0], "%d", &taskID); err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Invalid task ID: "+args[0]))
os.Exit(1)
}
outputJSON, _ := cmd.Flags().GetBool("json")
showLogs, _ := cmd.Flags().GetBool("logs")
// Open database
dbPath := db.DefaultPath()
database, err := db.Open(dbPath)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
defer database.Close()
task, err := database.GetTask(taskID)
if err != nil {
fmt.Fprintln(os.Stderr, errorStyle.Render("Error: "+err.Error()))
os.Exit(1)
}
if task == nil {
fmt.Fprintln(os.Stderr, errorStyle.Render(fmt.Sprintf("Task #%d not found", taskID)))
os.Exit(1)
}
// Fetch PR info if task has a branch
var prInfo *github.PRInfo
if task.BranchName != "" {
cfg := config.New(database)
repoDir := task.WorktreePath
if repoDir == "" {
repoDir = cfg.GetProjectDir(task.Project)
}
prCache := github.NewPRCache()
prInfo = prCache.GetPRForBranch(repoDir, task.BranchName)
}
if outputJSON {
output := map[string]interface{}{
"id": task.ID,
"title": task.Title,
"body": task.Body,
"status": task.Status,
"type": task.Type,
"project": task.Project,
"executor": task.Executor,
"worktree": task.WorktreePath,
"branch": task.BranchName,
"claude_pane_id": task.ClaudePaneID,
"shell_pane_id": task.ShellPaneID,
"summary": task.Summary,
"created_at": task.CreatedAt.Time.Format(time.RFC3339),
"updated_at": task.UpdatedAt.Time.Format(time.RFC3339),
}
if task.StartedAt != nil {
output["started_at"] = task.StartedAt.Time.Format(time.RFC3339)
}
if task.CompletedAt != nil {
output["completed_at"] = task.CompletedAt.Time.Format(time.RFC3339)
}
// Add PR info to JSON output
if prInfo != nil {
output["pr"] = map[string]interface{}{