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
|
package executor
import (
"context"
"errors"
"io"
"log/slog"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/thepeterstone/claudomator/internal/storage"
"github.com/thepeterstone/claudomator/internal/task"
)
func TestClaudeRunner_BuildArgs_BasicTask(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "fix the bug",
Model: "sonnet",
SkipPlanning: true,
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
argMap := make(map[string]bool)
for _, a := range args {
argMap[a] = true
}
for _, want := range []string{"-p", "fix the bug", "--output-format", "stream-json", "--verbose", "--model", "sonnet"} {
if !argMap[want] {
t.Errorf("missing arg %q in %v", want, args)
}
}
}
func TestClaudeRunner_BuildArgs_FullConfig(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "implement feature",
Model: "opus",
MaxBudgetUSD: 5.0,
PermissionMode: "bypassPermissions",
SystemPromptAppend: "Follow TDD",
AllowedTools: []string{"Bash", "Edit"},
DisallowedTools: []string{"Write"},
ContextFiles: []string{"/src"},
AdditionalArgs: []string{"--verbose"},
SkipPlanning: true,
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
// Check key args are present.
argMap := make(map[string]bool)
for _, a := range args {
argMap[a] = true
}
requiredArgs := []string{
"-p", "implement feature", "--output-format", "stream-json",
"--model", "opus", "--max-budget-usd", "5.00",
"--permission-mode", "bypassPermissions",
"--append-system-prompt", "Follow TDD",
"--allowedTools", "Bash", "Edit",
"--disallowedTools", "Write",
"--add-dir", "/src",
"--verbose",
}
for _, req := range requiredArgs {
if !argMap[req] {
t.Errorf("missing arg %q in %v", req, args)
}
}
}
func TestClaudeRunner_BuildArgs_DefaultsToBypassPermissions(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "do work",
SkipPlanning: true,
// PermissionMode intentionally not set
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
found := false
for i, a := range args {
if a == "--permission-mode" && i+1 < len(args) && args[i+1] == "bypassPermissions" {
found = true
}
}
if !found {
t.Errorf("expected --permission-mode bypassPermissions when PermissionMode is empty, args: %v", args)
}
}
func TestClaudeRunner_BuildArgs_RespectsExplicitPermissionMode(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "do work",
PermissionMode: "default",
SkipPlanning: true,
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
for i, a := range args {
if a == "--permission-mode" && i+1 < len(args) {
if args[i+1] != "default" {
t.Errorf("expected --permission-mode default, got %q", args[i+1])
}
return
}
}
t.Errorf("--permission-mode flag not found in args: %v", args)
}
func TestClaudeRunner_BuildArgs_AlwaysIncludesVerbose(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "do something",
SkipPlanning: true,
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
found := false
for _, a := range args {
if a == "--verbose" {
found = true
break
}
}
if !found {
t.Errorf("--verbose missing from args: %v", args)
}
}
func TestClaudeRunner_BuildArgs_PreamblePrepended(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "fix the bug",
SkipPlanning: false,
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
// The -p value should start with the preamble and end with the original instructions.
if len(args) < 2 || args[0] != "-p" {
t.Fatalf("expected -p as first arg, got: %v", args)
}
if !strings.HasPrefix(args[1], planningPreamble) {
t.Errorf("instructions should start with planning preamble")
}
if !strings.HasSuffix(args[1], "fix the bug") {
t.Errorf("instructions should end with original instructions")
}
}
func TestClaudeRunner_BuildArgs_PreambleAddsBash(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "do work",
AllowedTools: []string{"Read"},
SkipPlanning: false,
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
// Bash should be appended to allowed tools.
foundBash := false
for i, a := range args {
if a == "--allowedTools" && i+1 < len(args) && args[i+1] == "Bash" {
foundBash = true
}
}
if !foundBash {
t.Errorf("Bash should be added to --allowedTools when preamble is active: %v", args)
}
}
func TestClaudeRunner_BuildArgs_PreambleBashNotDuplicated(t *testing.T) {
r := &ClaudeRunner{}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "do work",
AllowedTools: []string{"Bash", "Read"},
SkipPlanning: false,
},
}
args := r.buildArgs(tk, &storage.Execution{ID: "test-exec"}, "/tmp/q.json")
// Count Bash occurrences in --allowedTools values.
bashCount := 0
for i, a := range args {
if a == "--allowedTools" && i+1 < len(args) && args[i+1] == "Bash" {
bashCount++
}
}
if bashCount != 1 {
t.Errorf("Bash should appear exactly once in --allowedTools, got %d: %v", bashCount, args)
}
}
// TestClaudeRunner_Run_ResumeSetsSessionIDFromResumeSession verifies that when a
// resume execution is itself blocked again, the stored SessionID is the original
// resumed session, not the new execution's own UUID. Without this, a second
// block-and-resume cycle passes the wrong --resume session ID and fails.
func TestClaudeRunner_Run_ResumeSetsSessionIDFromResumeSession(t *testing.T) {
logDir := t.TempDir()
r := &ClaudeRunner{
BinaryPath: "true", // exits 0, no output
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
LogDir: logDir,
}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "continue",
SkipPlanning: true,
},
}
exec := &storage.Execution{
ID: "resume-exec-uuid",
TaskID: "task-1",
ResumeSessionID: "original-session-uuid",
ResumeAnswer: "yes",
}
// Run completes successfully (binary is "true").
_ = r.Run(context.Background(), tk, exec)
// SessionID must be the original session (ResumeSessionID), not the new
// exec's own ID. If it were exec.ID, a second blocked-then-resumed cycle
// would use the wrong --resume argument and fail.
if exec.SessionID != "original-session-uuid" {
t.Errorf("SessionID after resume Run: want %q, got %q", "original-session-uuid", exec.SessionID)
}
}
func TestClaudeRunner_Run_InaccessibleWorkingDir_ReturnsError(t *testing.T) {
r := &ClaudeRunner{
BinaryPath: "true", // would succeed if it ran
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
LogDir: t.TempDir(),
}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
ProjectDir: "/nonexistent/path/does/not/exist",
SkipPlanning: true,
},
}
exec := &storage.Execution{ID: "test-exec"}
err := r.Run(context.Background(), tk, exec)
if err == nil {
t.Fatal("expected error for inaccessible working_dir, got nil")
}
if !strings.Contains(err.Error(), "project_dir") {
t.Errorf("expected 'project_dir' in error, got: %v", err)
}
}
func TestClaudeRunner_BinaryPath_Default(t *testing.T) {
r := &ClaudeRunner{}
if r.binaryPath() != "claude" {
t.Errorf("want 'claude', got %q", r.binaryPath())
}
}
func TestClaudeRunner_BinaryPath_Custom(t *testing.T) {
r := &ClaudeRunner{BinaryPath: "/usr/local/bin/claude"}
if r.binaryPath() != "/usr/local/bin/claude" {
t.Errorf("want custom path, got %q", r.binaryPath())
}
}
// TestExecOnce_NoGoroutineLeak_OnNaturalExit verifies that execOnce does not
// leave behind any goroutines when the subprocess exits normally (no context
// cancellation). Both the pgid-kill goroutine and the parseStream goroutine
// must have exited before execOnce returns.
func TestExecOnce_NoGoroutineLeak_OnNaturalExit(t *testing.T) {
logDir := t.TempDir()
r := &ClaudeRunner{
BinaryPath: "true", // exits immediately with status 0, produces no output
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
LogDir: logDir,
}
e := &storage.Execution{
ID: "goroutine-leak-test",
TaskID: "task-id",
StdoutPath: filepath.Join(logDir, "stdout.log"),
StderrPath: filepath.Join(logDir, "stderr.log"),
ArtifactDir: logDir,
}
// Let any goroutines from test infrastructure settle before sampling.
runtime.Gosched()
baseline := runtime.NumGoroutine()
if err := r.execOnce(context.Background(), []string{}, "", e); err != nil {
t.Fatalf("execOnce failed: %v", err)
}
// Give the scheduler a moment to let any leaked goroutines actually exit.
// In correct code the goroutines exit before execOnce returns, so this is
// just a safety buffer for the scheduler.
time.Sleep(10 * time.Millisecond)
runtime.Gosched()
after := runtime.NumGoroutine()
if after > baseline {
t.Errorf("goroutine leak: %d goroutines before execOnce, %d after (leaked %d)",
baseline, after, after-baseline)
}
}
// initGitRepo creates a git repo in dir with one commit so it is clonable.
func initGitRepo(t *testing.T, dir string) {
t.Helper()
cmds := [][]string{
{"git", "-C", dir, "init"},
{"git", "-C", dir, "config", "user.email", "test@test"},
{"git", "-C", dir, "config", "user.name", "test"},
{"git", "-C", dir, "commit", "--allow-empty", "-m", "init"},
}
for _, args := range cmds {
if out, err := exec.Command(args[0], args[1:]...).CombinedOutput(); err != nil {
t.Fatalf("%v: %v\n%s", args, err, out)
}
}
}
func TestSandboxCloneSource_PrefersLocalRemote(t *testing.T) {
dir := t.TempDir()
initGitRepo(t, dir)
// Add a "local" remote pointing to a bare repo.
bare := t.TempDir()
exec.Command("git", "init", "--bare", bare).Run()
exec.Command("git", "-C", dir, "remote", "add", "local", bare).Run()
exec.Command("git", "-C", dir, "remote", "add", "origin", "https://example.com/repo").Run()
got := sandboxCloneSource(dir)
if got != bare {
t.Errorf("expected bare repo path %q, got %q", bare, got)
}
}
func TestSandboxCloneSource_FallsBackToOrigin(t *testing.T) {
dir := t.TempDir()
initGitRepo(t, dir)
originURL := "https://example.com/origin-repo"
exec.Command("git", "-C", dir, "remote", "add", "origin", originURL).Run()
got := sandboxCloneSource(dir)
if got != originURL {
t.Errorf("expected origin URL %q, got %q", originURL, got)
}
}
func TestSandboxCloneSource_FallsBackToProjectDir(t *testing.T) {
dir := t.TempDir()
initGitRepo(t, dir)
// No remotes configured.
got := sandboxCloneSource(dir)
if got != dir {
t.Errorf("expected projectDir %q (no remotes), got %q", dir, got)
}
}
func TestSetupSandbox_ClonesGitRepo(t *testing.T) {
src := t.TempDir()
initGitRepo(t, src)
sandbox, err := setupSandbox(src)
if err != nil {
t.Fatalf("setupSandbox: %v", err)
}
t.Cleanup(func() { os.RemoveAll(sandbox) })
// Verify sandbox is a git repo with at least one commit.
out, err := exec.Command("git", "-C", sandbox, "log", "--oneline").Output()
if err != nil {
t.Fatalf("git log in sandbox: %v", err)
}
if len(strings.TrimSpace(string(out))) == 0 {
t.Error("expected at least one commit in sandbox, got empty log")
}
}
func TestSetupSandbox_InitialisesNonGitDir(t *testing.T) {
// A plain directory (not a git repo) should be initialised then cloned.
src := t.TempDir()
sandbox, err := setupSandbox(src)
if err != nil {
t.Fatalf("setupSandbox on plain dir: %v", err)
}
t.Cleanup(func() { os.RemoveAll(sandbox) })
if _, err := os.Stat(filepath.Join(sandbox, ".git")); err != nil {
t.Errorf("sandbox should be a git repo: %v", err)
}
}
func TestTeardownSandbox_UncommittedChanges_ReturnsError(t *testing.T) {
src := t.TempDir()
initGitRepo(t, src)
sandbox, err := setupSandbox(src)
if err != nil {
t.Fatalf("setupSandbox: %v", err)
}
t.Cleanup(func() { os.RemoveAll(sandbox) })
// Leave an uncommitted file in the sandbox.
if err := os.WriteFile(filepath.Join(sandbox, "dirty.txt"), []byte("oops"), 0644); err != nil {
t.Fatal(err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
err = teardownSandbox(src, sandbox, logger)
if err == nil {
t.Fatal("expected error for uncommitted changes, got nil")
}
if !strings.Contains(err.Error(), "uncommitted changes") {
t.Errorf("expected 'uncommitted changes' in error, got: %v", err)
}
// Sandbox should be preserved (not removed) on error.
if _, statErr := os.Stat(sandbox); os.IsNotExist(statErr) {
t.Error("sandbox was removed despite error; should be preserved for debugging")
}
}
func TestTeardownSandbox_CleanSandboxWithNoNewCommits_RemovesSandbox(t *testing.T) {
src := t.TempDir()
initGitRepo(t, src)
sandbox, err := setupSandbox(src)
if err != nil {
t.Fatalf("setupSandbox: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
// Sandbox has no new commits beyond origin; teardown should succeed and remove it.
if err := teardownSandbox(src, sandbox, logger); err != nil {
t.Fatalf("teardownSandbox: %v", err)
}
if _, statErr := os.Stat(sandbox); !os.IsNotExist(statErr) {
t.Error("sandbox should have been removed after clean teardown")
os.RemoveAll(sandbox)
}
}
// TestBlockedError_IncludesSandboxDir verifies that when a task is blocked in a
// sandbox, the BlockedError carries the sandbox path so the resume execution can
// run in the same directory (where Claude's session files are stored).
func TestBlockedError_IncludesSandboxDir(t *testing.T) {
src := t.TempDir()
initGitRepo(t, src)
logDir := t.TempDir()
// Use a script that writes question.json to the env-var path and exits 0
// (simulating a blocked agent that asks a question before exiting).
scriptPath := filepath.Join(t.TempDir(), "fake-claude.sh")
if err := os.WriteFile(scriptPath, []byte(`#!/bin/sh
if [ -n "$CLAUDOMATOR_QUESTION_FILE" ]; then
printf '{"text":"Should I continue?"}' > "$CLAUDOMATOR_QUESTION_FILE"
fi
`), 0755); err != nil {
t.Fatalf("write script: %v", err)
}
r := &ClaudeRunner{
BinaryPath: scriptPath,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
LogDir: logDir,
}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
Instructions: "do something",
ProjectDir: src,
SkipPlanning: true,
},
}
exec := &storage.Execution{ID: "blocked-exec-uuid", TaskID: "task-1"}
err := r.Run(context.Background(), tk, exec)
var blocked *BlockedError
if !errors.As(err, &blocked) {
t.Fatalf("expected BlockedError, got: %v", err)
}
if blocked.SandboxDir == "" {
t.Error("BlockedError.SandboxDir should be set when task runs in a sandbox")
}
// Sandbox should still exist (preserved for resume).
if _, statErr := os.Stat(blocked.SandboxDir); os.IsNotExist(statErr) {
t.Error("sandbox directory should be preserved when blocked")
} else {
os.RemoveAll(blocked.SandboxDir) // cleanup
}
}
// TestClaudeRunner_Run_ResumeUsesStoredSandboxDir verifies that when a resume
// execution has SandboxDir set, the runner uses that directory (not project_dir)
// as the working directory, so Claude finds its session files there.
func TestClaudeRunner_Run_ResumeUsesStoredSandboxDir(t *testing.T) {
logDir := t.TempDir()
sandboxDir := t.TempDir()
cwdFile := filepath.Join(logDir, "cwd.txt")
// Use a script that writes its working directory to a file in logDir (stable path).
scriptPath := filepath.Join(t.TempDir(), "fake-claude.sh")
script := "#!/bin/sh\nprintf '%s' \"$PWD\" > " + cwdFile + "\n"
if err := os.WriteFile(scriptPath, []byte(script), 0755); err != nil {
t.Fatalf("write script: %v", err)
}
r := &ClaudeRunner{
BinaryPath: scriptPath,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
LogDir: logDir,
}
tk := &task.Task{
Agent: task.AgentConfig{
Type: "claude",
ProjectDir: sandboxDir, // must exist; resume overrides it with SandboxDir anyway
SkipPlanning: true,
},
}
exec := &storage.Execution{
ID: "resume-exec-uuid",
TaskID: "task-1",
ResumeSessionID: "original-session",
ResumeAnswer: "yes",
SandboxDir: sandboxDir,
}
_ = r.Run(context.Background(), tk, exec)
got, err := os.ReadFile(cwdFile)
if err != nil {
t.Fatalf("cwd file not written: %v", err)
}
// The runner should have executed claude in sandboxDir, not in project_dir.
if string(got) != sandboxDir {
t.Errorf("resume working dir: want %q, got %q", sandboxDir, string(got))
}
}
func TestIsCompletionReport(t *testing.T) {
tests := []struct {
name string
json string
expected bool
}{
{
name: "real question with options",
json: `{"text": "Should I proceed with implementation?", "options": ["Yes", "No"]}`,
expected: false,
},
{
name: "real question no options",
json: `{"text": "Which approach do you prefer?"}`,
expected: false,
},
{
name: "completion report no options no question mark",
json: `{"text": "All tests pass. Implementation complete. Summary written to CLAUDOMATOR_SUMMARY_FILE."}`,
expected: true,
},
{
name: "completion report with empty options",
json: `{"text": "Feature implemented and committed.", "options": []}`,
expected: true,
},
{
name: "invalid json treated as not a report",
json: `not json`,
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isCompletionReport(tt.json)
if got != tt.expected {
t.Errorf("isCompletionReport(%q) = %v, want %v", tt.json, got, tt.expected)
}
})
}
}
func TestGitSafe_PrependsSafeDirectory(t *testing.T) {
got := gitSafe("-C", "/some/path", "status")
want := []string{"-c", "safe.directory=*", "-C", "/some/path", "status"}
if len(got) != len(want) {
t.Fatalf("gitSafe() = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("gitSafe()[%d] = %q, want %q", i, got[i], want[i])
}
}
}
|