-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexecutor.go
More file actions
5310 lines (4510 loc) · 179 KB
/
executor.go
File metadata and controls
5310 lines (4510 loc) · 179 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
// Package executor runs Claude Code tasks in the background.
package executor
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unicode"
"github.com/charmbracelet/log"
"github.com/bborn/workflow/internal/config"
"github.com/bborn/workflow/internal/db"
"github.com/bborn/workflow/internal/events"
"github.com/bborn/workflow/internal/github"
"github.com/bborn/workflow/internal/hooks"
)
// TaskEvent represents a change to a task.
type TaskEvent struct {
Type string // "created", "updated", "deleted", "status_changed"
Task *db.Task // The task (may be nil for deleted)
TaskID int64 // Always set
}
// Executor manages background task execution.
type Executor struct {
db *db.DB
config *config.Config
logger *log.Logger
hooks *hooks.Runner
events *events.Emitter
prCache *github.PRCache
// Executor factory for pluggable backends
executorFactory *ExecutorFactory
mu sync.RWMutex
runningTasks map[int64]bool // tracks which tasks are currently executing
cancelFuncs map[int64]context.CancelFunc // cancel functions for running tasks
running bool
stopCh chan struct{}
// Suspended task tracking
suspendedTasks map[int64]time.Time // taskID -> time when suspended
// Subscribers for real-time log updates (per-task)
subsMu sync.RWMutex
subs map[int64][]chan *db.TaskLog
// Subscribers for task events (global)
taskSubsMu sync.RWMutex
taskSubs []chan TaskEvent
// Wakeup channel to trigger immediate task processing (non-blocking send)
wakeupCh chan struct{}
// Silent mode suppresses log output (for TUI embedding)
silent bool
executorSlug string
executorName string
}
// DefaultSuspendIdleTimeout is the default time a blocked task must be idle before being suspended.
const DefaultSuspendIdleTimeout = 6 * time.Hour
// DoneTaskCleanupTimeout is how long after a task is marked done before its Claude process is killed.
// This gives users time to review output or retry the task before the process is cleaned up.
const DoneTaskCleanupTimeout = 30 * time.Minute
// DefaultWorktreeCleanupMaxAge is the default time after completion before a done/archived
// task's worktree is automatically archived and removed to reclaim disk space.
const DefaultWorktreeCleanupMaxAge = 7 * 24 * time.Hour // 7 days
const (
defaultExecutorSlug = "claude"
defaultExecutorName = "Claude"
)
var executorEnvKeys = []string{"TASK_EXECUTOR", "WORKFLOW_EXECUTOR", "TASKYOU_EXECUTOR", "WORKTREE_EXECUTOR"}
// detectExecutorIdentity determines the current executor based on environment variables.
// It falls back to the default Claude executor when no overrides are provided.
func detectExecutorIdentity() (slug, display string) {
for _, key := range executorEnvKeys {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
slug = strings.ToLower(value)
return slug, formatExecutorDisplayName(slug, value)
}
}
return defaultExecutorSlug, defaultExecutorName
}
func formatExecutorDisplayName(slug, raw string) string {
switch slug {
case "codex":
return "Codex"
case "claude":
return defaultExecutorName
case "gemini":
return "Gemini"
case "pi":
return "Pi"
}
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return defaultExecutorName
}
lower := strings.ToLower(trimmed)
if trimmed == lower {
runes := []rune(lower)
if len(runes) == 0 {
return defaultExecutorName
}
runes[0] = unicode.ToUpper(runes[0])
return string(runes)
}
return trimmed
}
// DefaultExecutorName returns the fallback executor display name.
func DefaultExecutorName() string {
return defaultExecutorName
}
// New creates a new executor.
func New(database *db.DB, cfg *config.Config) *Executor {
slug, display := detectExecutorIdentity()
eventsEmitter := events.New(hooks.DefaultHooksDir())
e := &Executor{
db: database,
config: cfg,
logger: log.NewWithOptions(io.Discard, log.Options{Prefix: "executor"}),
hooks: hooks.NewSilent(hooks.DefaultHooksDir()),
events: eventsEmitter,
prCache: github.NewPRCache(),
executorFactory: NewExecutorFactory(),
stopCh: make(chan struct{}),
wakeupCh: make(chan struct{}, 1),
subs: make(map[int64][]chan *db.TaskLog),
taskSubs: make([]chan TaskEvent, 0),
runningTasks: make(map[int64]bool),
cancelFuncs: make(map[int64]context.CancelFunc),
suspendedTasks: make(map[int64]time.Time),
silent: true,
executorSlug: slug,
executorName: display,
}
// Register the events emitter with the database for event emission
database.SetEventEmitter(eventsEmitter)
// Register available executors
e.executorFactory.Register(NewClaudeExecutor(e))
e.executorFactory.Register(NewCodexExecutor(e))
e.executorFactory.Register(NewGeminiExecutor(e))
e.executorFactory.Register(NewOpenClawExecutor(e))
e.executorFactory.Register(NewOpenCodeExecutor(e))
e.executorFactory.Register(NewPiExecutor(e))
return e
}
// NewWithLogging creates an executor that logs to stderr (for daemon mode).
func NewWithLogging(database *db.DB, cfg *config.Config, w io.Writer) *Executor {
slug, display := detectExecutorIdentity()
eventsEmitter := events.New(hooks.DefaultHooksDir())
e := &Executor{
db: database,
config: cfg,
logger: log.NewWithOptions(w, log.Options{Prefix: "executor"}),
hooks: hooks.New(hooks.DefaultHooksDir()),
events: eventsEmitter,
prCache: github.NewPRCache(),
executorFactory: NewExecutorFactory(),
stopCh: make(chan struct{}),
wakeupCh: make(chan struct{}, 1),
subs: make(map[int64][]chan *db.TaskLog),
taskSubs: make([]chan TaskEvent, 0),
runningTasks: make(map[int64]bool),
cancelFuncs: make(map[int64]context.CancelFunc),
suspendedTasks: make(map[int64]time.Time),
silent: false,
executorSlug: slug,
executorName: display,
}
// Register the events emitter with the database for event emission
database.SetEventEmitter(eventsEmitter)
// Register available executors
e.executorFactory.Register(NewClaudeExecutor(e))
e.executorFactory.Register(NewCodexExecutor(e))
e.executorFactory.Register(NewGeminiExecutor(e))
e.executorFactory.Register(NewOpenClawExecutor(e))
e.executorFactory.Register(NewOpenCodeExecutor(e))
e.executorFactory.Register(NewPiExecutor(e))
return e
}
// DisplayName returns the configured executor display name.
func (e *Executor) DisplayName() string {
if e == nil || e.executorName == "" {
return defaultExecutorName
}
return e.executorName
}
// ExecutorSlug returns the normalized identifier for the executor (e.g., "codex").
func (e *Executor) ExecutorSlug() string {
if e == nil || e.executorSlug == "" {
return defaultExecutorSlug
}
return e.executorSlug
}
// Start begins the background worker.
func (e *Executor) Start(ctx context.Context) {
e.mu.Lock()
if e.running {
e.mu.Unlock()
return
}
e.running = true
e.mu.Unlock()
// Recover stale tmux references on startup (handles crash recovery)
e.recoverStaleTmuxRefs()
// Run stale worktree cleanup on startup (and then periodically in worker loop)
go e.cleanupStaleWorktrees()
e.logger.Info("Background executor started")
go e.worker(ctx)
}
// recoverStaleTmuxRefs clears stale daemon_session and tmux_window_id references
// from tasks after a daemon restart or crash. This is called automatically on startup.
func (e *Executor) recoverStaleTmuxRefs() {
// Step 1: Find all active daemon sessions
activeSessions := make(map[string]bool)
sessionsOut, err := exec.Command("tmux", "list-sessions", "-F", "#{session_name}").Output()
if err == nil {
for _, session := range strings.Split(strings.TrimSpace(string(sessionsOut)), "\n") {
if strings.HasPrefix(session, "task-daemon-") {
activeSessions[session] = true
}
}
}
// Step 2: Find all valid window IDs across all daemon sessions
validWindowIDs := make(map[string]bool)
for session := range activeSessions {
windowsOut, err := exec.Command("tmux", "list-windows", "-t", session, "-F", "#{window_id}").Output()
if err == nil {
for _, windowID := range strings.Split(strings.TrimSpace(string(windowsOut)), "\n") {
if windowID != "" {
validWindowIDs[windowID] = true
}
}
}
}
// Step 3: Clear stale references in database
staleDaemon, staleWindow, err := e.db.RecoverStaleTmuxRefs(activeSessions, validWindowIDs)
if err != nil {
e.logger.Error("Failed to recover stale tmux refs", "error", err)
return
}
if staleDaemon > 0 || staleWindow > 0 {
e.logger.Info("Recovered stale tmux references",
"daemon_sessions", staleDaemon,
"window_ids", staleWindow,
)
}
}
// Stop stops the background worker.
func (e *Executor) Stop() {
e.mu.Lock()
if !e.running {
e.mu.Unlock()
return
}
e.running = false
close(e.stopCh)
e.mu.Unlock()
e.logger.Info("Background executor stopped")
}
// RunningTasks returns the IDs of currently processing tasks.
func (e *Executor) RunningTasks() []int64 {
e.mu.RLock()
defer e.mu.RUnlock()
ids := make([]int64, 0, len(e.runningTasks))
for id := range e.runningTasks {
ids = append(ids, id)
}
return ids
}
// IsRunning checks if a specific task is currently executing.
func (e *Executor) IsRunning(taskID int64) bool {
e.mu.RLock()
defer e.mu.RUnlock()
return e.runningTasks[taskID]
}
// Interrupt cancels a running task.
// If running in this process, cancels directly. Also marks in DB for cross-process interrupt.
func (e *Executor) Interrupt(taskID int64) bool {
// Get task before interrupting
task, _ := e.db.GetTask(taskID)
// Mark as backlog in database (for cross-process communication)
e.updateStatus(taskID, db.StatusBacklog)
e.logLine(taskID, "system", "Task interrupted by user")
// Emit interrupt event
if task != nil {
e.events.EmitTaskFailed(task, "interrupted")
}
// If running locally, cancel the context
e.mu.RLock()
cancel, ok := e.cancelFuncs[taskID]
e.mu.RUnlock()
if ok {
cancel()
}
return true
}
// SuspendTask suspends a task's Claude process using SIGTSTP (same as Ctrl+Z) to save memory.
// Returns true if successfully suspended.
func (e *Executor) SuspendTask(taskID int64) bool {
pid := e.getClaudePID(taskID)
if pid == 0 {
return false
}
// Send SIGTSTP to suspend the process (same as Ctrl+Z, allows Claude to handle gracefully)
proc, err := os.FindProcess(pid)
if err != nil {
e.logger.Debug("Failed to find process", "pid", pid, "error", err)
return false
}
if err := sendSIGTSTP(proc); err != nil {
e.logger.Debug("Failed to suspend process", "pid", pid, "error", err)
return false
}
e.mu.Lock()
e.suspendedTasks[taskID] = time.Now()
e.mu.Unlock()
e.logger.Info("Suspended Claude process", "task", taskID, "pid", pid)
e.logLine(taskID, "system", "Claude suspended (idle timeout)")
return true
}
// ResumeTask resumes a suspended task's Claude process using SIGCONT.
// Returns true if successfully resumed.
func (e *Executor) ResumeTask(taskID int64) bool {
e.mu.RLock()
_, isSuspended := e.suspendedTasks[taskID]
e.mu.RUnlock()
if !isSuspended {
return false
}
pid := e.getClaudePID(taskID)
if pid == 0 {
// Process gone, clean up suspended state
e.mu.Lock()
delete(e.suspendedTasks, taskID)
e.mu.Unlock()
return false
}
// Send SIGCONT to resume the process
proc, err := os.FindProcess(pid)
if err != nil {
e.mu.Lock()
delete(e.suspendedTasks, taskID)
e.mu.Unlock()
return false
}
if err := sendSIGCONT(proc); err != nil {
e.logger.Debug("Failed to resume process", "pid", pid, "error", err)
return false
}
e.mu.Lock()
delete(e.suspendedTasks, taskID)
e.mu.Unlock()
e.logger.Info("Resumed Claude process", "task", taskID, "pid", pid)
e.logLine(taskID, "system", "Claude resumed")
return true
}
// IsSuspended checks if a task is currently suspended.
func (e *Executor) IsSuspended(taskID int64) bool {
e.mu.RLock()
defer e.mu.RUnlock()
_, suspended := e.suspendedTasks[taskID]
return suspended
}
// findPanesForWindow parses tmux list-panes output and returns PIDs for panes
// in windows matching the given name exactly. The input format is one line per pane:
//
// "session:window:pane pid"
//
// e.g. "task-daemon-123:task-5:0 12345"
func findPanesForWindow(tmuxOutput, windowName string) []int {
var pids []int
for _, line := range strings.Split(tmuxOutput, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Parse "session:window:pane pid"
parts := strings.Fields(line)
if len(parts) != 2 {
continue
}
target := parts[0]
pidStr := parts[1]
// Parse target format: "session:window:pane" and match window name exactly
targetParts := strings.SplitN(target, ":", 3)
if len(targetParts) < 2 {
continue
}
if targetParts[1] != windowName {
continue
}
pid, err := strconv.Atoi(pidStr)
if err != nil {
continue
}
pids = append(pids, pid)
}
return pids
}
// getClaudePID finds the PID of the Claude process for a task.
// It first checks the stored daemon session, then searches all sessions for the task window.
func (e *Executor) getClaudePID(taskID int64) int {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
windowName := TmuxWindowName(taskID)
// Search all tmux sessions for a window with this task's name
out, err := exec.CommandContext(ctx, "tmux", "list-panes", "-a", "-F", "#{session_name}:#{window_name}:#{pane_index} #{pane_pid}").Output()
if err != nil {
return 0
}
for _, pid := range findPanesForWindow(string(out), windowName) {
// Check if this is a Claude process or has Claude as child
cmdOut, _ := exec.CommandContext(ctx, "ps", "-p", strconv.Itoa(pid), "-o", "comm=").Output()
if strings.Contains(string(cmdOut), "claude") {
return pid
}
// Check for claude child process
childOut, err := exec.CommandContext(ctx, "pgrep", "-P", strconv.Itoa(pid), "claude").Output()
if err == nil && len(childOut) > 0 {
childPid, err := strconv.Atoi(strings.TrimSpace(string(childOut)))
if err == nil {
return childPid
}
}
}
return 0
}
// GetClaudePIDFromPane returns the Claude PID for a specific tmux pane.
// This is used by the UI when it knows the exact pane ID.
func GetClaudePIDFromPane(paneID string) int {
if paneID == "" {
return 0
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Get the PID of the process in this pane
out, err := exec.CommandContext(ctx, "tmux", "display-message", "-t", paneID, "-p", "#{pane_pid}").Output()
if err != nil {
return 0
}
pid, err := strconv.Atoi(strings.TrimSpace(string(out)))
if err != nil {
return 0
}
// Check if this is Claude
cmdOut, _ := exec.CommandContext(ctx, "ps", "-p", strconv.Itoa(pid), "-o", "comm=").Output()
if strings.Contains(string(cmdOut), "claude") {
return pid
}
// Check for claude child
childOut, err := exec.CommandContext(ctx, "pgrep", "-P", strconv.Itoa(pid), "claude").Output()
if err == nil && len(childOut) > 0 {
childPid, err := strconv.Atoi(strings.TrimSpace(string(childOut)))
if err == nil {
return childPid
}
}
return pid // Return the pane PID as fallback
}
// KillClaudeProcess terminates the Claude process for a task to free up memory.
// This is called when a task is completed, closed, or deleted.
// Exported for use by the UI when deleting tasks.
func (e *Executor) KillClaudeProcess(taskID int64) bool {
pid := e.getClaudePID(taskID)
if pid == 0 {
return false
}
// Send SIGTERM for graceful shutdown
proc, err := os.FindProcess(pid)
if err != nil {
e.logger.Debug("Failed to find Claude process", "pid", pid, "error", err)
return false
}
if err := proc.Signal(syscall.SIGTERM); err != nil {
e.logger.Debug("Failed to terminate Claude process", "pid", pid, "error", err)
return false
}
e.logger.Info("Terminated Claude process", "task", taskID, "pid", pid)
// Clean up suspended task tracking if present
e.mu.Lock()
delete(e.suspendedTasks, taskID)
e.mu.Unlock()
return true
}
// IsClaudeRunning checks if a Claude process is running for a task.
func (e *Executor) IsClaudeRunning(taskID int64) bool {
return e.getClaudePID(taskID) != 0
}
// Subscribe to log updates for a task.
func (e *Executor) Subscribe(taskID int64) chan *db.TaskLog {
ch := make(chan *db.TaskLog, 100)
e.subsMu.Lock()
e.subs[taskID] = append(e.subs[taskID], ch)
e.subsMu.Unlock()
return ch
}
// Unsubscribe from log updates.
func (e *Executor) Unsubscribe(taskID int64, ch chan *db.TaskLog) {
e.subsMu.Lock()
defer e.subsMu.Unlock()
subs := e.subs[taskID]
for i, sub := range subs {
if sub == ch {
e.subs[taskID] = append(subs[:i], subs[i+1:]...)
close(ch)
break
}
}
}
func (e *Executor) broadcast(taskID int64, log *db.TaskLog) {
e.subsMu.RLock()
defer e.subsMu.RUnlock()
for _, ch := range e.subs[taskID] {
select {
case ch <- log:
default:
// Channel full, skip
}
}
}
// SubscribeTaskEvents subscribes to task change events (status changes, etc.).
func (e *Executor) SubscribeTaskEvents() chan TaskEvent {
ch := make(chan TaskEvent, 100)
e.taskSubsMu.Lock()
e.taskSubs = append(e.taskSubs, ch)
e.taskSubsMu.Unlock()
return ch
}
// UnsubscribeTaskEvents unsubscribes from task events.
func (e *Executor) UnsubscribeTaskEvents(ch chan TaskEvent) {
e.taskSubsMu.Lock()
defer e.taskSubsMu.Unlock()
for i, sub := range e.taskSubs {
if sub == ch {
e.taskSubs = append(e.taskSubs[:i], e.taskSubs[i+1:]...)
close(ch)
break
}
}
}
// broadcastTaskEvent sends a task event to all subscribers.
func (e *Executor) broadcastTaskEvent(event TaskEvent) {
e.taskSubsMu.RLock()
defer e.taskSubsMu.RUnlock()
for _, ch := range e.taskSubs {
select {
case ch <- event:
default:
// Channel full, skip
}
}
}
// NotifyTaskChange notifies subscribers of a task change (for use by UI/other components).
// If the task is newly queued, it also triggers immediate processing so the executor
// starts without waiting for the next poll cycle.
func (e *Executor) NotifyTaskChange(eventType string, task *db.Task) {
event := TaskEvent{
Type: eventType,
Task: task,
TaskID: task.ID,
}
e.broadcastTaskEvent(event)
// Trigger immediate processing when a task becomes queued
if task.Status == db.StatusQueued {
e.TriggerProcessing()
}
}
// TriggerProcessing wakes up the worker loop to process queued tasks immediately.
// This is a non-blocking operation; if a wakeup is already pending, the call is a no-op.
func (e *Executor) TriggerProcessing() {
select {
case e.wakeupCh <- struct{}{}:
default:
// Already has a pending wakeup, no need to send another
}
}
// updateStatus updates task status in DB and broadcasts the change.
func (e *Executor) updateStatus(taskID int64, status string) error {
// Get old status for event
oldTask, _ := e.db.GetTask(taskID)
oldStatus := ""
if oldTask != nil {
oldStatus = oldTask.Status
}
if err := e.db.UpdateTaskStatus(taskID, status); err != nil {
return err
}
// Fetch updated task and broadcast
task, err := e.db.GetTask(taskID)
if err == nil && task != nil {
e.broadcastTaskEvent(TaskEvent{
Type: "status_changed",
Task: task,
TaskID: taskID,
})
// Emit events based on status
switch status {
case db.StatusQueued, db.StatusProcessing:
e.events.EmitTaskStarted(task)
case db.StatusBlocked:
e.events.EmitTaskBlocked(task, "Task needs input")
case db.StatusDone:
e.events.EmitTaskCompleted(task)
default:
if oldStatus != "" && oldStatus != status {
e.events.EmitTaskUpdated(task, map[string]interface{}{
"old_status": oldStatus,
"new_status": status,
})
}
}
}
return nil
}
func (e *Executor) worker(ctx context.Context) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
// Check for idle blocked tasks to suspend every 60 seconds (30 ticks)
// Check for due scheduled tasks every 10 seconds (5 ticks)
// Check for inactive done tasks to cleanup every 5 minutes (150 ticks)
// Check for stale worktrees to archive every 1 hour (1800 ticks)
tickCount := 0
const suspendCheckInterval = 30
const doneCleanupInterval = 150 // 5 minutes at 2 second ticks
const staleWorktreeInterval = 1800 // 1 hour at 2 second ticks
for {
select {
case <-ctx.Done():
return
case <-e.stopCh:
return
case <-e.wakeupCh:
// Immediate wakeup: a task was just enqueued, process it now
e.processNextTask(ctx)
case <-ticker.C:
e.processNextTask(ctx)
tickCount++
// Periodically check for idle blocked tasks to suspend
if tickCount%suspendCheckInterval == 0 {
e.suspendIdleBlockedTasks()
}
// Periodically cleanup Claude processes for inactive done tasks
if tickCount%doneCleanupInterval == 0 {
e.cleanupInactiveDoneTasks()
}
// Periodically archive and remove stale worktrees to reclaim disk space
if tickCount%staleWorktreeInterval == 0 {
e.cleanupStaleWorktrees()
}
}
}
}
// suspendIdleBlockedTasks finds blocked tasks that have been idle and suspends their Claude processes.
func (e *Executor) suspendIdleBlockedTasks() {
tasks, err := e.db.ListTasks(db.ListTasksOptions{Status: db.StatusBlocked, Limit: 100})
if err != nil {
return
}
for _, task := range tasks {
// Skip if already suspended
e.mu.RLock()
_, alreadySuspended := e.suspendedTasks[task.ID]
e.mu.RUnlock()
if alreadySuspended {
continue
}
// Check if task has been blocked for long enough
// Use UpdatedAt as proxy for when it became blocked
if task.UpdatedAt.Time.IsZero() {
continue
}
idleDuration := time.Since(task.UpdatedAt.Time)
if idleDuration >= e.getSuspendIdleTimeout() {
// Check if there's actually a Claude process to suspend
pid := e.getClaudePID(task.ID)
if pid > 0 {
e.logger.Info("Suspending idle blocked task", "task", task.ID, "idle", idleDuration.Round(time.Second))
e.SuspendTask(task.ID)
}
}
}
}
// cleanupInactiveDoneTasks kills Claude processes for done tasks that have been inactive
// for longer than DoneTaskCleanupTimeout. This frees up memory from orphaned processes.
func (e *Executor) cleanupInactiveDoneTasks() {
tasks, err := e.db.ListTasks(db.ListTasksOptions{
Status: db.StatusDone,
IncludeClosed: true,
Limit: 100,
})
if err != nil {
e.logger.Debug("Failed to list done tasks for cleanup", "error", err)
return
}
for _, task := range tasks {
// Skip if not completed or completed recently
if task.CompletedAt == nil {
continue
}
doneDuration := time.Since(task.CompletedAt.Time)
if doneDuration < DoneTaskCleanupTimeout {
continue
}
// Check if there's a Claude process to kill
pid := e.getClaudePID(task.ID)
if pid == 0 {
continue
}
// Kill the Claude process
e.logger.Info("Cleaning up inactive done task", "task", task.ID, "done_for", doneDuration.Round(time.Minute))
e.KillClaudeProcess(task.ID)
// Also kill the tmux window to fully clean up
windowName := TmuxWindowName(task.ID)
killAllWindowsByNameAllSessions(windowName)
e.logLine(task.ID, "system", "Claude process cleaned up (inactive done task)")
}
}
// cleanupStaleWorktrees archives and removes worktrees for done/archived tasks
// that have been completed longer than the configured max age. This reclaims disk
// space from the .task-worktrees directory which can grow very large over time.
func (e *Executor) cleanupStaleWorktrees() {
maxAge := e.getWorktreeCleanupMaxAge()
if maxAge <= 0 {
return // Disabled
}
tasks, err := e.db.GetStaleWorktreeTasks(maxAge)
if err != nil {
e.logger.Debug("Failed to list stale worktree tasks", "error", err)
return
}
for _, task := range tasks {
// Skip tasks that are currently running
e.mu.RLock()
running := e.runningTasks[task.ID]
e.mu.RUnlock()
if running {
continue
}
// Skip non-worktree projects - they share the project directory and should not be archived
if !e.config.ProjectUsesWorktrees(task.Project) {
e.db.ClearTaskWorktreePath(task.ID)
continue
}
// Skip if worktree path doesn't exist on disk (already cleaned up)
if _, err := os.Stat(task.WorktreePath); os.IsNotExist(err) {
// Path gone, just clear the DB reference
e.db.ClearTaskWorktreePath(task.ID)
continue
}
age := time.Since(task.CompletedAt.Time)
e.logger.Info("Archiving stale worktree",
"task", task.ID,
"project", task.Project,
"age", age.Round(time.Hour),
)
// Archive the worktree (preserves changes in git refs) then remove it
if err := e.ArchiveWorktree(task); err != nil {
e.logger.Warn("Failed to archive stale worktree",
"task", task.ID,
"error", err,
)
continue
}
e.logLine(task.ID, "system",
fmt.Sprintf("Worktree auto-archived after %s (use 'unarchive' to restore)", age.Round(time.Hour)))
}
}
// getWorktreeCleanupMaxAge returns the configured max age before stale worktrees are cleaned up.
// Returns 0 to disable automatic cleanup.
func (e *Executor) getWorktreeCleanupMaxAge() time.Duration {
if val, err := e.db.GetSetting(config.SettingWorktreeCleanupMaxAge); err == nil && val != "" {
if val == "0" || val == "disabled" {
return 0
}
if duration, err := time.ParseDuration(val); err == nil {
return duration
}
}
return DefaultWorktreeCleanupMaxAge
}
// CleanupStaleWorktreesManual runs stale worktree cleanup on demand and returns
// the list of tasks that were cleaned up. If dryRun is true, no changes are made.
func (e *Executor) CleanupStaleWorktreesManual(maxAge time.Duration, dryRun bool) ([]*db.Task, error) {
tasks, err := e.db.GetStaleWorktreeTasks(maxAge)
if err != nil {
return nil, fmt.Errorf("list stale worktree tasks: %w", err)
}
if dryRun {
return tasks, nil
}
var cleaned []*db.Task
for _, task := range tasks {
// Skip non-worktree projects
if !e.config.ProjectUsesWorktrees(task.Project) {
e.db.ClearTaskWorktreePath(task.ID)
cleaned = append(cleaned, task)
continue
}
// Skip if worktree path doesn't exist on disk
if _, err := os.Stat(task.WorktreePath); os.IsNotExist(err) {
e.db.ClearTaskWorktreePath(task.ID)
cleaned = append(cleaned, task)
continue
}
if err := e.ArchiveWorktree(task); err != nil {
e.logger.Warn("Failed to archive stale worktree",
"task", task.ID,
"error", err,
)
continue
}
cleaned = append(cleaned, task)
}
// Also run git worktree prune on all project directories to clean up stale git refs
e.pruneAllProjectWorktrees()
return cleaned, nil
}
// pruneAllProjectWorktrees runs `git worktree prune` on all configured project directories
// to clean up stale internal git worktree references.
func (e *Executor) pruneAllProjectWorktrees() {
projects, err := e.db.ListProjects()
if err != nil {
return
}
for _, p := range projects {
// Skip non-worktree projects - no git worktrees to prune
if !p.UsesWorktrees() {
continue
}
dir := e.config.GetProjectDir(p.Name)
if dir == "" {
continue
}
cmd := exec.Command("git", "worktree", "prune")
cmd.Dir = dir
cmd.Run() // Ignore errors
}
}
func (e *Executor) processNextTask(ctx context.Context) {
// Get all queued tasks
tasks, err := e.db.GetQueuedTasks()
if err != nil {
e.logger.Error("Failed to get queued tasks", "error", err)
return
}
for _, task := range tasks {
// Atomically check-and-set to prevent race where two ticks
// both see the task as not-running and spawn duplicate goroutines
e.mu.Lock()
if e.runningTasks[task.ID] {
e.mu.Unlock()
continue
}
e.runningTasks[task.ID] = true
e.mu.Unlock()