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
|
package executor
import (
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/thepeterstone/claudomator/internal/storage"
)
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)
// sandboxCloneSource intentionally filters to local-FS remotes (so
// `git clone <src>` doesn't go over the network). Use a local path
// for origin to verify the fallback semantics.
originURL := t.TempDir()
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, slog.Default())
if err != nil {
t.Fatalf("setupSandbox: %v", err)
}
t.Cleanup(func() { os.RemoveAll(sandbox) })
// Force sandbox to master if it cloned as main
exec.Command("git", gitSafe("-C", sandbox, "checkout", "master")...).Run()
// Debug sandbox
logOut, _ := exec.Command("git", "-C", sandbox, "log", "-1").CombinedOutput()
fmt.Printf("DEBUG: sandbox log: %s\n", string(logOut))
// 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, slog.Default())
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_AutocommitsChanges(t *testing.T) {
// Create a bare repo as origin so push succeeds.
bare := t.TempDir()
if out, err := exec.Command("git", "init", "--bare", "-b", "main", bare).CombinedOutput(); err != nil {
t.Fatalf("git init bare: %v\n%s", err, out)
}
// Create a sandbox directly.
sandbox := t.TempDir()
initGitRepo(t, sandbox)
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "remote", "add", "origin", bare).CombinedOutput(); err != nil {
t.Fatalf("git remote add: %v\n%s", err, out)
}
// Initial push to establish origin/main
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "push", "origin", "main").CombinedOutput(); err != nil {
t.Fatalf("git push initial: %v\n%s", err, out)
}
// Capture startHEAD
headOut, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "rev-parse", "HEAD").Output()
if err != nil {
t.Fatalf("rev-parse HEAD: %v", err)
}
startHEAD := strings.TrimSpace(string(headOut))
// Leave an uncommitted file in the sandbox.
if err := os.WriteFile(filepath.Join(sandbox, "dirty.txt"), []byte("autocommit me"), 0644); err != nil {
t.Fatal(err)
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
execRecord := &storage.Execution{}
err = teardownSandbox("", sandbox, startHEAD, logger, execRecord)
if err != nil {
t.Fatalf("expected autocommit to succeed, got error: %v", err)
}
// Sandbox should be removed after successful autocommit and push.
if _, statErr := os.Stat(sandbox); !os.IsNotExist(statErr) {
t.Error("sandbox should have been removed after successful autocommit and push")
}
// Verify the commit exists in the bare repo.
out, err := exec.Command("git", "-C", bare, "log", "-1", "--pretty=%B").Output()
if err != nil {
t.Fatalf("git log in bare repo: %v", err)
}
if !strings.Contains(string(out), "chore: autocommit uncommitted changes") {
t.Errorf("expected autocommit message in log, got: %q", string(out))
}
// Verify the commit was captured in execRecord.
if len(execRecord.Commits) == 0 {
t.Error("expected at least one commit in execRecord")
} else if !strings.Contains(execRecord.Commits[0].Message, "chore: autocommit uncommitted changes") {
t.Errorf("unexpected commit message: %q", execRecord.Commits[0].Message)
}
}
func TestTeardownSandbox_BuildFailure_BlocksAutocommit(t *testing.T) {
bare := t.TempDir()
if out, err := exec.Command("git", "init", "--bare", "-b", "main", bare).CombinedOutput(); err != nil {
t.Fatalf("git init bare: %v\n%s", err, out)
}
sandbox := t.TempDir()
initGitRepo(t, sandbox)
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "remote", "add", "origin", bare).CombinedOutput(); err != nil {
t.Fatalf("git remote add: %v\n%s", err, out)
}
// Capture startHEAD
headOut, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "rev-parse", "HEAD").Output()
if err != nil {
t.Fatalf("rev-parse HEAD: %v", err)
}
startHEAD := strings.TrimSpace(string(headOut))
// Leave an uncommitted file.
if err := os.WriteFile(filepath.Join(sandbox, "dirty.txt"), []byte("dirty"), 0644); err != nil {
t.Fatal(err)
}
// Add a failing Makefile.
makefile := "build:\n\t@echo 'build failed'\n\texit 1\n"
if err := os.WriteFile(filepath.Join(sandbox, "Makefile"), []byte(makefile), 0644); err != nil {
t.Fatal(err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
execRecord := &storage.Execution{}
err = teardownSandbox("", sandbox, startHEAD, logger, execRecord)
if err == nil {
t.Error("expected teardown to fail due to build failure, but it succeeded")
} else if !strings.Contains(err.Error(), "build failed before autocommit") {
t.Errorf("expected build failure error message, got: %v", err)
}
// Sandbox should NOT be removed if teardown failed.
if _, statErr := os.Stat(sandbox); os.IsNotExist(statErr) {
t.Error("sandbox should have been preserved after build failure")
}
// Verify no new commit in bare repo.
out, err := exec.Command("git", "-C", bare, "log", "HEAD").CombinedOutput()
if strings.Contains(string(out), "chore: autocommit uncommitted changes") {
t.Error("autocommit should not have been pushed after build failure")
}
}
func TestTeardownSandbox_BuildSuccess_ProceedsToAutocommit(t *testing.T) {
bare := t.TempDir()
if out, err := exec.Command("git", "init", "--bare", "-b", "main", bare).CombinedOutput(); err != nil {
t.Fatalf("git init bare: %v\n%s", err, out)
}
sandbox := t.TempDir()
initGitRepo(t, sandbox)
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "remote", "add", "origin", bare).CombinedOutput(); err != nil {
t.Fatalf("git remote add: %v\n%s", err, out)
}
// Capture startHEAD
headOut, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "rev-parse", "HEAD").Output()
if err != nil {
t.Fatalf("rev-parse HEAD: %v", err)
}
startHEAD := strings.TrimSpace(string(headOut))
// Leave an uncommitted file.
if err := os.WriteFile(filepath.Join(sandbox, "dirty.txt"), []byte("dirty"), 0644); err != nil {
t.Fatal(err)
}
// Add a successful Makefile.
makefile := "build:\n\t@echo 'build succeeded'\n"
if err := os.WriteFile(filepath.Join(sandbox, "Makefile"), []byte(makefile), 0644); err != nil {
t.Fatal(err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
execRecord := &storage.Execution{}
err = teardownSandbox("", sandbox, startHEAD, logger, execRecord)
if err != nil {
t.Fatalf("expected teardown to succeed after build success, got error: %v", err)
}
// Sandbox should be removed after success.
if _, statErr := os.Stat(sandbox); !os.IsNotExist(statErr) {
t.Error("sandbox should have been removed after successful build and autocommit")
}
// Verify new commit in bare repo.
out, err := exec.Command("git", "-C", bare, "log", "-1", "--pretty=%B").Output()
if err != nil {
t.Fatalf("git log in bare repo: %v", err)
}
if !strings.Contains(string(out), "chore: autocommit uncommitted changes") {
t.Errorf("expected autocommit message in log, got: %q", string(out))
}
}
func TestTeardownSandbox_CapturesExplicitCommits(t *testing.T) {
bare := t.TempDir()
if out, err := exec.Command("git", "init", "--bare", "-b", "main", bare).CombinedOutput(); err != nil {
t.Fatalf("git init bare: %v\n%s", err, out)
}
sandbox := t.TempDir()
initGitRepo(t, sandbox)
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "remote", "add", "origin", bare).CombinedOutput(); err != nil {
t.Fatalf("git remote add: %v\n%s", err, out)
}
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "push", "origin", "main").CombinedOutput(); err != nil {
t.Fatalf("git push initial: %v\n%s", err, out)
}
headOut, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "rev-parse", "HEAD").Output()
if err != nil {
t.Fatalf("rev-parse HEAD: %v", err)
}
startHEAD := strings.TrimSpace(string(headOut))
// Simulate Claude explicitly committing changes.
if err := os.WriteFile(filepath.Join(sandbox, "work.txt"), []byte("done"), 0644); err != nil {
t.Fatal(err)
}
for _, args := range [][]string{
{"-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "add", "-A"},
{"-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", sandbox, "commit", "-m", "feat: implement the feature"},
} {
if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
execRecord := &storage.Execution{}
if err := teardownSandbox("", sandbox, startHEAD, logger, execRecord); err != nil {
t.Fatalf("teardownSandbox: %v", err)
}
if len(execRecord.Commits) == 0 {
t.Fatal("expected commits to be captured in execRecord")
}
if !strings.Contains(execRecord.Commits[0].Message, "feat: implement the feature") {
t.Errorf("unexpected commit message: %q", execRecord.Commits[0].Message)
}
if execRecord.Commits[0].Hash == "" {
t.Error("commit hash should not be empty")
}
}
func TestTeardownSandbox_CleanSandboxWithNoNewCommits_RemovesSandbox(t *testing.T) {
src := t.TempDir()
initGitRepo(t, src)
sandbox, err := setupSandbox(src, slog.Default())
if err != nil {
t.Fatalf("setupSandbox: %v", err)
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
execRecord := &storage.Execution{}
headOut, _ := exec.Command("git", "-C", sandbox, "rev-parse", "HEAD").Output()
startHEAD := strings.TrimSpace(string(headOut))
// Sandbox has no new commits beyond origin; teardown should succeed and remove it.
if err := teardownSandbox(src, sandbox, startHEAD, logger, execRecord); 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)
}
}
func TestTailFile_MissingFile_ReturnsEmpty(t *testing.T) {
got := tailFile("/nonexistent/path/file.log", 10)
if got != "" {
t.Errorf("want empty string for missing file, got %q", got)
}
}
func initGitRepo(t *testing.T, dir string) {
t.Helper()
cmds := [][]string{
{"git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", dir, "init", "-b", "main"},
{"git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", dir, "config", "user.email", "test@test"},
{"git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", dir, "config", "user.name", "test"},
}
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)
}
}
if err := os.WriteFile(filepath.Join(dir, "init.txt"), []byte("init"), 0644); err != nil {
t.Fatal(err)
}
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", dir, "add", ".").CombinedOutput(); err != nil {
t.Fatalf("git add: %v\n%s", err, out)
}
if out, err := exec.Command("git", "-c", "safe.directory=*", "-c", "commit.gpgsign=false", "-C", dir, "commit", "-m", "init").CombinedOutput(); err != nil {
t.Fatalf("git commit: %v\n%s", err, out)
}
}
|