-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexecutor_test.go
More file actions
1935 lines (1665 loc) · 54.1 KB
/
executor_test.go
File metadata and controls
1935 lines (1665 loc) · 54.1 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
import (
"context"
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/bborn/workflow/internal/config"
"github.com/bborn/workflow/internal/db"
)
func TestNeedsInputDetection(t *testing.T) {
tests := []struct {
name string
lines []string
wantMsg string
wantNeed bool
}{
{
name: "simple NEEDS_INPUT",
lines: []string{"NEEDS_INPUT: What should be the database name?"},
wantMsg: "What should be the database name?",
wantNeed: true,
},
{
name: "NEEDS_INPUT in middle of output",
lines: []string{"Processing...", "NEEDS_INPUT: Please clarify the requirements", "More output"},
wantMsg: "Please clarify the requirements",
wantNeed: true,
},
{
name: "TASK_COMPLETE",
lines: []string{"Done", "TASK_COMPLETE"},
wantMsg: "",
wantNeed: false,
},
{
name: "no markers",
lines: []string{"Some output", "More output"},
wantMsg: "",
wantNeed: false,
},
{
name: "NEEDS_INPUT with extra whitespace",
lines: []string{"NEEDS_INPUT: What's the API key? "},
wantMsg: "What's the API key?",
wantNeed: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotMsg, gotNeed := detectNeedsInput(tt.lines)
if gotNeed != tt.wantNeed {
t.Errorf("detectNeedsInput() needsInput = %v, want %v", gotNeed, tt.wantNeed)
}
if gotMsg != tt.wantMsg {
t.Errorf("detectNeedsInput() message = %q, want %q", gotMsg, tt.wantMsg)
}
})
}
}
// detectNeedsInput is a helper function that mirrors the detection logic in runCrush
func detectNeedsInput(lines []string) (string, bool) {
var needsInputMsg string
var foundComplete bool
for _, line := range lines {
if strings.Contains(line, "TASK_COMPLETE") {
foundComplete = true
}
if strings.Contains(line, "NEEDS_INPUT:") {
if idx := strings.Index(line, "NEEDS_INPUT:"); idx >= 0 {
needsInputMsg = strings.TrimSpace(line[idx+len("NEEDS_INPUT:"):])
}
}
}
if foundComplete {
return "", false
}
if needsInputMsg != "" {
return needsInputMsg, true
}
return "", false
}
func TestInterrupt(t *testing.T) {
// Create temp database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
// Create the test project first
if err := database.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
exec := New(database, cfg)
// Create a test task
task := &db.Task{
Title: "Test task",
Status: db.StatusProcessing,
Project: "test",
}
if err := database.CreateTask(task); err != nil {
t.Fatal(err)
}
// Mark as running
exec.mu.Lock()
exec.runningTasks[task.ID] = true
ctx, cancel := context.WithCancel(context.Background())
exec.cancelFuncs[task.ID] = cancel
exec.mu.Unlock()
// Test IsRunning
if !exec.IsRunning(task.ID) {
t.Error("expected task to be running")
}
// Test Interrupt
result := exec.Interrupt(task.ID)
if !result {
t.Error("expected interrupt to return true")
}
// Wait a bit for context to be cancelled
time.Sleep(10 * time.Millisecond)
// Verify context was cancelled
select {
case <-ctx.Done():
// Expected
default:
t.Error("expected context to be cancelled")
}
// Verify status was updated
updatedTask, err := database.GetTask(task.ID)
if err != nil {
t.Fatal(err)
}
if updatedTask.Status != db.StatusBacklog {
t.Errorf("expected status %q, got %q", db.StatusBacklog, updatedTask.Status)
}
}
func TestRunningTasks(t *testing.T) {
// Create temp database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
cfg := &config.Config{}
exec := New(database, cfg)
// No running tasks initially
if len(exec.RunningTasks()) != 0 {
t.Error("expected no running tasks")
}
// Add some running tasks
exec.mu.Lock()
exec.runningTasks[1] = true
exec.runningTasks[2] = true
exec.mu.Unlock()
// Should have 2 running tasks
running := exec.RunningTasks()
if len(running) != 2 {
t.Errorf("expected 2 running tasks, got %d", len(running))
}
}
func TestAttachmentsInPrompt(t *testing.T) {
// Create temp database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
// Create the test project first
if err := database.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
exec := New(database, cfg)
// Create a test task
task := &db.Task{
Title: "Test task with attachments",
Status: db.StatusQueued,
Type: db.TypeCode,
Project: "test",
}
if err := database.CreateTask(task); err != nil {
t.Fatal(err)
}
// Add attachments
_, err = database.AddAttachment(task.ID, "notes.txt", "text/plain", []byte("test notes content"))
if err != nil {
t.Fatal(err)
}
_, err = database.AddAttachment(task.ID, "data.json", "application/json", []byte(`{"key":"value"}`))
if err != nil {
t.Fatal(err)
}
t.Run("prepareAttachments creates files in .claude/attachments", func(t *testing.T) {
// Create a temporary worktree directory
worktreePath := t.TempDir()
paths, cleanup := exec.prepareAttachments(task.ID, worktreePath)
defer cleanup()
if len(paths) != 2 {
t.Errorf("expected 2 attachment paths, got %d", len(paths))
}
// Verify files exist and are in the .claude/attachments directory
for _, path := range paths {
if _, err := os.Stat(path); os.IsNotExist(err) {
t.Errorf("attachment file does not exist: %s", path)
}
// Verify path is inside .claude/attachments/
expectedPrefix := filepath.Join(worktreePath, ".claude", "attachments")
if !strings.HasPrefix(path, expectedPrefix) {
t.Errorf("attachment path %s should be inside %s", path, expectedPrefix)
}
}
})
t.Run("getAttachmentsSection uses Read tool with relative paths", func(t *testing.T) {
worktreePath := "/worktree"
paths := []string{"/worktree/.claude/attachments/notes.txt", "/worktree/.claude/attachments/data.json"}
section := exec.getAttachmentsSection(task.ID, paths, worktreePath)
if !strings.Contains(section, "## Attachments") {
t.Error("section should contain Attachments header")
}
if !strings.Contains(section, "Read tool") {
t.Error("section should mention Read tool (not View tool)")
}
if strings.Contains(section, "View tool") {
t.Error("section should NOT mention View tool")
}
// Paths should be relative, not absolute
if !strings.Contains(section, ".claude/attachments/notes.txt") {
t.Error("section should contain relative file path")
}
if strings.Contains(section, "/worktree/.claude/attachments/notes.txt") {
t.Error("section should NOT contain absolute file path")
}
})
t.Run("buildPrompt includes attachments section", func(t *testing.T) {
worktreePath := t.TempDir()
// Set task's WorktreePath so buildPrompt can convert to relative paths
task.WorktreePath = worktreePath
paths, cleanup := exec.prepareAttachments(task.ID, worktreePath)
defer cleanup()
prompt := exec.buildPrompt(task, paths)
if !strings.Contains(prompt, "## Attachments") {
t.Error("prompt should include attachments section")
}
if !strings.Contains(prompt, "Read tool") {
t.Error("prompt should mention Read tool")
}
// Verify paths are relative in the prompt
if !strings.Contains(prompt, ".claude/attachments/") {
t.Error("prompt should contain relative attachment paths")
}
})
t.Run("retry feedback includes attachments when present", func(t *testing.T) {
worktreePath := t.TempDir()
paths, cleanup := exec.prepareAttachments(task.ID, worktreePath)
defer cleanup()
// Simulate what happens during retry: attachment section is appended to feedback
retryFeedback := "Please fix the bug"
feedbackWithAttachments := retryFeedback
if len(paths) > 0 {
feedbackWithAttachments = retryFeedback + "\n" + exec.getAttachmentsSection(task.ID, paths, worktreePath)
}
// Verify attachments are included in the retry feedback
if !strings.Contains(feedbackWithAttachments, "## Attachments") {
t.Error("retry feedback should include attachments section")
}
if !strings.Contains(feedbackWithAttachments, "Read tool") {
t.Error("retry feedback should mention Read tool")
}
if !strings.Contains(feedbackWithAttachments, "Please fix the bug") {
t.Error("retry feedback should still contain original feedback")
}
// Verify paths are relative
if !strings.Contains(feedbackWithAttachments, ".claude/attachments/") {
t.Error("retry feedback should contain relative attachment paths")
}
})
}
func TestFindClaudeSessionID(t *testing.T) {
// Create a temporary directory structure mimicking Claude's session storage
home, err := os.UserHomeDir()
if err != nil {
t.Skip("Could not get home directory")
}
// Create a unique test directory
testWorkDir := "/tmp/test-claude-session-" + time.Now().Format("20060102150405")
// Match Claude's escaping: replace / with -, replace . with -, keep leading -
escapedPath := strings.ReplaceAll(testWorkDir, "/", "-")
escapedPath = strings.ReplaceAll(escapedPath, ".", "-")
projectDir := home + "/.claude/projects/" + escapedPath
// Create the project directory
if err := os.MkdirAll(projectDir, 0755); err != nil {
t.Fatalf("Could not create project directory: %v", err)
}
defer os.RemoveAll(projectDir)
t.Run("no session files", func(t *testing.T) {
result := FindClaudeSessionID(testWorkDir)
if result != "" {
t.Errorf("expected empty string, got %q", result)
}
})
t.Run("finds most recent session", func(t *testing.T) {
// Create some session files with different timestamps
session1 := projectDir + "/abc12345-1234-5678-abcd-123456789abc.jsonl"
session2 := projectDir + "/def67890-1234-5678-abcd-123456789def.jsonl"
// Create first session (older)
if err := os.WriteFile(session1, []byte(`{"test":"data"}`), 0644); err != nil {
t.Fatalf("Could not create session file: %v", err)
}
time.Sleep(10 * time.Millisecond)
// Create second session (newer)
if err := os.WriteFile(session2, []byte(`{"test":"data2"}`), 0644); err != nil {
t.Fatalf("Could not create session file: %v", err)
}
result := FindClaudeSessionID(testWorkDir)
if result != "def67890-1234-5678-abcd-123456789def" {
t.Errorf("expected most recent session, got %q", result)
}
// Clean up
os.Remove(session1)
os.Remove(session2)
})
t.Run("ignores agent files", func(t *testing.T) {
// Create an agent file and a regular session file
agentFile := projectDir + "/agent-abc12345-1234-5678-abcd-123456789abc.jsonl"
sessionFile := projectDir + "/xyz99999-1234-5678-abcd-123456789xyz.jsonl"
if err := os.WriteFile(agentFile, []byte(`{"agent":"data"}`), 0644); err != nil {
t.Fatalf("Could not create agent file: %v", err)
}
if err := os.WriteFile(sessionFile, []byte(`{"session":"data"}`), 0644); err != nil {
t.Fatalf("Could not create session file: %v", err)
}
result := FindClaudeSessionID(testWorkDir)
if result != "xyz99999-1234-5678-abcd-123456789xyz" {
t.Errorf("expected regular session, got %q (should ignore agent files)", result)
}
// Clean up
os.Remove(agentFile)
os.Remove(sessionFile)
})
}
func TestRenameClaudeSession(t *testing.T) {
t.Run("returns nil for non-existent workdir", func(t *testing.T) {
// Test with a workdir that doesn't have any Claude sessions
err := RenameClaudeSession("/tmp/non-existent-workdir-12345", "New Name", "")
if err != nil {
t.Errorf("expected nil error for non-existent session, got: %v", err)
}
})
// Note: We can't easily test the actual rename without mocking the claude CLI
// The function will return an error if claude isn't installed or if the session
// doesn't exist, but we handle that gracefully
}
func TestConversationHistory(t *testing.T) {
t.Run("no history for fresh task", func(t *testing.T) {
// Create fresh database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
// Create the test project
if err := database.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
exec := New(database, cfg)
// Create a test task
task := &db.Task{
Title: "Test task",
Status: db.StatusBacklog,
Type: db.TypeCode,
Project: "test",
}
if err := database.CreateTask(task); err != nil {
t.Fatal(err)
}
prompt := exec.buildPrompt(task, nil)
if strings.Contains(prompt, "Previous Conversation") {
t.Error("fresh task should not have conversation history")
}
})
t.Run("history after retry with feedback", func(t *testing.T) {
// Create fresh database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
// Create the test project
if err := database.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
exec := New(database, cfg)
// Create a test task
task := &db.Task{
Title: "Test task",
Status: db.StatusBacklog,
Type: db.TypeCode,
Project: "test",
}
if err := database.CreateTask(task); err != nil {
t.Fatal(err)
}
// Simulate a first run with a question
database.AppendTaskLog(task.ID, "system", "Starting task #1: Test task")
database.AppendTaskLog(task.ID, "output", "Looking at the code...")
database.AppendTaskLog(task.ID, "question", "What database name should I use?")
database.AppendTaskLog(task.ID, "system", "Task needs input - use 'r' to retry with your answer")
// Simulate retry with feedback
database.RetryTask(task.ID, "Use 'myapp_production' as the database name")
prompt := exec.buildPrompt(task, nil)
if !strings.Contains(prompt, "Previous Conversation") {
t.Error("retry should include conversation history")
}
if !strings.Contains(prompt, "What database name should I use?") {
t.Error("retry should include the original question")
}
if !strings.Contains(prompt, "myapp_production") {
t.Error("retry should include user's feedback")
}
})
t.Run("multiple continuations", func(t *testing.T) {
// Create fresh database for this subtest
tmpFile2, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile2.Name())
tmpFile2.Close()
database2, err := db.Open(tmpFile2.Name())
if err != nil {
t.Fatal(err)
}
defer database2.Close()
// Create the test project
if err := database2.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg2 := &config.Config{}
exec2 := New(database2, cfg2)
// Create a test task
task2 := &db.Task{
Title: "Test task 2",
Status: db.StatusBacklog,
Type: db.TypeCode,
Project: "test",
}
if err := database2.CreateTask(task2); err != nil {
t.Fatal(err)
}
// First run
database2.AppendTaskLog(task2.ID, "question", "First question?")
database2.AppendTaskLog(task2.ID, "system", "--- Continuation ---")
database2.AppendTaskLog(task2.ID, "text", "Feedback: First answer")
// Second run
database2.AppendTaskLog(task2.ID, "question", "Second question?")
database2.AppendTaskLog(task2.ID, "system", "--- Continuation ---")
database2.AppendTaskLog(task2.ID, "text", "Feedback: Second answer")
prompt := exec2.buildPrompt(task2, nil)
if !strings.Contains(prompt, "First question?") {
t.Errorf("should include first question\nPrompt: %s", prompt)
}
if !strings.Contains(prompt, "First answer") {
t.Errorf("should include first answer\nPrompt: %s", prompt)
}
if !strings.Contains(prompt, "Second question?") {
t.Errorf("should include second question\nPrompt: %s", prompt)
}
if !strings.Contains(prompt, "Second answer") {
t.Errorf("should include second answer\nPrompt: %s", prompt)
}
})
}
func TestBuildPromptIncludesTaskMetadata(t *testing.T) {
t.Run("includes branch and PR info", func(t *testing.T) {
// Create fresh database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
// Create the test project
if err := database.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
exec := New(database, cfg)
task := &db.Task{
Title: "Fix bug",
Body: "Fix the authentication bug",
Project: "test",
BranchName: "fix/auth-bug-123",
PRURL: "https://github.com/org/repo/pull/456",
PRNumber: 456,
Tags: "bugfix,auth",
}
if err := database.CreateTask(task); err != nil {
t.Fatal(err)
}
prompt := exec.buildPrompt(task, nil)
if !strings.Contains(prompt, "Branch: fix/auth-bug-123") {
t.Error("prompt should include branch name")
}
if !strings.Contains(prompt, "https://github.com/org/repo/pull/456") {
t.Error("prompt should include PR URL")
}
if !strings.Contains(prompt, "Tags: bugfix,auth") {
t.Error("prompt should include tags")
}
})
t.Run("handles task without metadata", func(t *testing.T) {
// Create fresh database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
// Create the test project
if err := database.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
exec := New(database, cfg)
task := &db.Task{
Title: "Simple task",
Body: "Do something simple",
Project: "test",
}
if err := database.CreateTask(task); err != nil {
t.Fatal(err)
}
prompt := exec.buildPrompt(task, nil)
// Should not have empty "Task Details" section
if strings.Contains(prompt, "## Task Details\n\n\n") {
t.Error("prompt should not include empty task details section")
}
})
t.Run("shows PR number when URL is empty", func(t *testing.T) {
// Create fresh database for this subtest
tmpFile2, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile2.Name())
tmpFile2.Close()
database2, err := db.Open(tmpFile2.Name())
if err != nil {
t.Fatal(err)
}
defer database2.Close()
// Create the test project
if err := database2.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg2 := &config.Config{}
exec2 := New(database2, cfg2)
task := &db.Task{
Title: "PR task",
Body: "Work on PR",
Project: "test",
PRNumber: 789,
}
if err := database2.CreateTask(task); err != nil {
t.Fatal(err)
}
prompt := exec2.buildPrompt(task, nil)
if !strings.Contains(prompt, "PR #789") {
t.Error("prompt should include PR number")
}
})
}
func TestCleanupClaudeSessions(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil {
t.Skip("Could not get home directory")
}
defaultDir := filepath.Join(home, ".claude")
t.Run("returns nil for empty worktree path", func(t *testing.T) {
err := CleanupClaudeSessions("", defaultDir)
if err != nil {
t.Errorf("expected nil error for empty path, got: %v", err)
}
})
t.Run("returns nil for non-existent session directory", func(t *testing.T) {
err := CleanupClaudeSessions("/tmp/non-existent-worktree-12345", defaultDir)
if err != nil {
t.Errorf("expected nil error for non-existent directory, got: %v", err)
}
})
t.Run("removes existing session directory", func(t *testing.T) {
// Create a unique test worktree path
testWorkDir := "/tmp/test-cleanup-sessions-" + time.Now().Format("20060102150405")
// Match Claude's escaping: replace / with -, replace . with -, keep leading -
escapedPath := strings.ReplaceAll(testWorkDir, "/", "-")
escapedPath = strings.ReplaceAll(escapedPath, ".", "-")
projectDir := home + "/.claude/projects/" + escapedPath
// Create the project directory with some session files
if err := os.MkdirAll(projectDir, 0755); err != nil {
t.Fatalf("Could not create project directory: %v", err)
}
// Create some session files
session1 := projectDir + "/abc12345-1234-5678-abcd-123456789abc.jsonl"
session2 := projectDir + "/def67890-1234-5678-abcd-123456789def.jsonl"
agentFile := projectDir + "/agent-xyz99999.jsonl"
if err := os.WriteFile(session1, []byte(`{"test":"data"}`), 0644); err != nil {
t.Fatalf("Could not create session file: %v", err)
}
if err := os.WriteFile(session2, []byte(`{"test":"data2"}`), 0644); err != nil {
t.Fatalf("Could not create session file: %v", err)
}
if err := os.WriteFile(agentFile, []byte(`{"agent":"data"}`), 0644); err != nil {
t.Fatalf("Could not create agent file: %v", err)
}
// Verify files exist
if _, err := os.Stat(projectDir); os.IsNotExist(err) {
t.Fatal("Project directory should exist before cleanup")
}
// Run cleanup
err := CleanupClaudeSessions(testWorkDir, defaultDir)
if err != nil {
t.Errorf("CleanupClaudeSessions failed: %v", err)
}
// Verify directory was removed
if _, err := os.Stat(projectDir); !os.IsNotExist(err) {
t.Error("Project directory should not exist after cleanup")
// Clean up manually if test failed
os.RemoveAll(projectDir)
}
})
}
func TestIsValidWorktreePath(t *testing.T) {
tests := []struct {
name string
path string
wantValid bool
}{
{
name: "valid worktree path",
path: "/Users/bruno/Projects/myproject/.task-worktrees/123-task-slug",
wantValid: true,
},
{
name: "valid worktree path with nested dirs",
path: "/Users/bruno/Projects/myproject/.task-worktrees/456-another-task/subdir",
wantValid: true,
},
{
name: "main project directory - not valid",
path: "/Users/bruno/Projects/myproject",
wantValid: false,
},
{
name: "project subdirectory - not valid",
path: "/Users/bruno/Projects/myproject/src",
wantValid: false,
},
{
name: "root directory - not valid",
path: "/",
wantValid: false,
},
{
name: "home directory - not valid",
path: "/Users/bruno",
wantValid: false,
},
{
name: "tmp directory - not valid",
path: "/tmp",
wantValid: false,
},
{
name: ".task-worktrees directory itself - not valid (needs subdirectory)",
path: "/Users/bruno/Projects/myproject/.task-worktrees",
wantValid: false,
},
{
name: "empty path - not valid",
path: "",
wantValid: false,
},
{
name: "relative path with .task-worktrees",
path: "project/.task-worktrees/123-task",
wantValid: true,
},
{
name: "path containing task-worktrees without dot - not valid",
path: "/Users/bruno/Projects/task-worktrees/123-task",
wantValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isValidWorktreePath(tt.path)
if got != tt.wantValid {
t.Errorf("isValidWorktreePath(%q) = %v, want %v", tt.path, got, tt.wantValid)
}
})
}
}
func TestIsValidWorktreePathWithRealDirectory(t *testing.T) {
// Create a real temporary directory structure to test with
tmpDir, err := os.MkdirTemp("", "test-worktree-validation-*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
// Create the .task-worktrees structure
worktreesDir := tmpDir + "/.task-worktrees"
taskDir := worktreesDir + "/123-test-task"
if err := os.MkdirAll(taskDir, 0755); err != nil {
t.Fatal(err)
}
t.Run("real worktree directory is valid", func(t *testing.T) {
if !isValidWorktreePath(taskDir) {
t.Errorf("isValidWorktreePath(%q) should return true for real worktree directory", taskDir)
}
})
t.Run("real project directory is not valid", func(t *testing.T) {
if isValidWorktreePath(tmpDir) {
t.Errorf("isValidWorktreePath(%q) should return false for project directory", tmpDir)
}
})
t.Run("worktrees parent directory is not valid", func(t *testing.T) {
// The .task-worktrees directory itself shouldn't be valid
// (we need to be inside a specific task worktree)
if isValidWorktreePath(worktreesDir) {
t.Errorf("isValidWorktreePath(%q) should return false for worktrees parent directory", worktreesDir)
}
})
}
func TestIsValidWorkDir(t *testing.T) {
// Create a real temporary directory structure
tmpDir, err := os.MkdirTemp("", "test-workdir-validation-*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
// Create the .task-worktrees structure
worktreesDir := tmpDir + "/.task-worktrees"
taskDir := worktreesDir + "/123-test-task"
if err := os.MkdirAll(taskDir, 0755); err != nil {
t.Fatal(err)
}
t.Run("worktree path is valid regardless of allowedProjectDir", func(t *testing.T) {
if !isValidWorkDir(taskDir, "") {
t.Errorf("isValidWorkDir(%q, \"\") should return true for worktree directory", taskDir)
}
if !isValidWorkDir(taskDir, "/some/other/path") {
t.Errorf("isValidWorkDir(%q, other) should return true for worktree directory", taskDir)
}
})
t.Run("project directory is valid when it matches allowedProjectDir", func(t *testing.T) {
if !isValidWorkDir(tmpDir, tmpDir) {
t.Errorf("isValidWorkDir(%q, %q) should return true when paths match", tmpDir, tmpDir)
}
})
t.Run("project directory is rejected when allowedProjectDir differs", func(t *testing.T) {
if isValidWorkDir(tmpDir, "/some/other/path") {
t.Errorf("isValidWorkDir(%q, other) should return false when paths don't match", tmpDir)
}
})
t.Run("arbitrary directory is rejected without allowedProjectDir", func(t *testing.T) {
if isValidWorkDir(tmpDir, "") {
t.Errorf("isValidWorkDir(%q, \"\") should return false for non-worktree path with empty allowed", tmpDir)
}
})
t.Run("empty path is not valid", func(t *testing.T) {
if isValidWorkDir("", tmpDir) {
t.Error("isValidWorkDir('', ...) should return false")
}
})
t.Run("non-existent path is not valid even if allowed", func(t *testing.T) {
nonExistent := "/nonexistent/path/xyz"
if isValidWorkDir(nonExistent, nonExistent) {
t.Error("isValidWorkDir should return false for non-existent path")
}
})
}
func TestDoneTaskCleanupTimeout(t *testing.T) {
// Verify the cleanup timeout constant is set correctly
if DoneTaskCleanupTimeout != 30*time.Minute {
t.Errorf("DoneTaskCleanupTimeout = %v, want 30 minutes", DoneTaskCleanupTimeout)
}
}
func TestCleanupInactiveDoneTasksFiltering(t *testing.T) {
// Create temp database
tmpFile, err := os.CreateTemp("", "test-*.db")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
tmpFile.Close()
database, err := db.Open(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
defer database.Close()
// Create the test project first
if err := database.CreateProject(&db.Project{Name: "test", Path: "/tmp/test"}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
exec := New(database, cfg)
now := time.Now()
t.Run("skips tasks without CompletedAt", func(t *testing.T) {
task := &db.Task{
Title: "Task without CompletedAt",
Status: db.StatusDone,
Project: "test",
}
if err := database.CreateTask(task); err != nil {
t.Fatal(err)
}
// This should not panic or error - it should just skip the task
exec.cleanupInactiveDoneTasks()
})