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
|
package executor
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/google/uuid"
"github.com/thepeterstone/claudomator/internal/llm"
"github.com/thepeterstone/claudomator/internal/provider/openaicompat"
"github.com/thepeterstone/claudomator/internal/storage"
"github.com/thepeterstone/claudomator/internal/story"
"github.com/thepeterstone/claudomator/internal/task"
)
// TestNativeRunner_Run_ChangestatsParseable confirms that a git diff --stat
// summary line embedded in the model's assistant text (the only way such a
// line can reach stdout.log — tool results themselves are never logged) is
// still recoverable by task.ParseChangestatFromFile via the new
// NativeRunner/agentloop path, exactly as it was via the old LocalRunner
// (neither runner logs raw tool output; both only log assistant text +
// result lines, so this has always depended on the model itself echoing the
// diff stat in its reply).
func TestNativeRunner_Run_ChangestatsParseable(t *testing.T) {
srv := fakeChatServer(t, []fakeTurn{
{content: "## Summary\nCommitted the fix.\n2 files changed, 30 insertions(+), 4 deletions(-)", promptTok: 3, outTok: 7},
})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec, newStoreChannel(&fakeChannelStore{}, tt.ID)); err != nil {
t.Fatalf("Run: %v", err)
}
stdoutPath := filepath.Join(r.ExecLogDir(exec.ID), "stdout.log")
cs := task.ParseChangestatFromFile(stdoutPath)
if cs == nil {
t.Fatalf("ParseChangestatFromFile found nothing in %s", stdoutPath)
}
if cs.FilesChanged != 2 || cs.LinesAdded != 30 || cs.LinesRemoved != 4 {
t.Errorf("changestats: got %+v, want {2 30 4}", cs)
}
}
// This file exercises NativeRunner — the provider.Provider/agentloop.Loop
// based successor to the former LocalRunner — via a fake OpenAI-compatible
// HTTP server, using the same fake-server test pattern LocalRunner's tests
// used (fakeChatServer/fakeTurn/toolCall below), so it verifies behavioral
// equivalence: same stdout.log stream-json shape, same summary/changestats
// extraction, same tool-loop semantics.
// fakeTurn is one canned chat-completion response the fake server returns.
type fakeTurn struct {
content string
toolCalls []llm.ToolCall
promptTok int
outTok int
}
// fakeChatServer replies to /chat/completions with the supplied turns in order,
// one per request (non-streaming JSON), so a tool-use loop can be driven
// deterministically. Requests beyond the list repeat the final turn.
func fakeChatServer(t *testing.T, turns []fakeTurn) *httptest.Server {
t.Helper()
var mu sync.Mutex
idx := 0
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
turn := turns[idx]
if idx < len(turns)-1 {
idx++
}
mu.Unlock()
msg := map[string]any{"role": "assistant", "content": turn.content}
if len(turn.toolCalls) > 0 {
msg["tool_calls"] = turn.toolCalls
}
resp := map[string]any{
"model": "fake",
"choices": []map[string]any{{"message": msg, "finish_reason": "stop"}},
"usage": map[string]int{"prompt_tokens": turn.promptTok, "completion_tokens": turn.outTok},
}
_ = json.NewEncoder(w).Encode(resp)
}))
}
func toolCall(id, name, args string) llm.ToolCall {
return llm.ToolCall{ID: id, Type: "function", Function: llm.ToolCallFunction{Name: name, Arguments: args}}
}
func newLocalRunner(t *testing.T, srv *httptest.Server) *NativeRunner {
t.Helper()
client := &llm.Client{Endpoint: srv.URL + "/v1", Model: "fake"}
return &NativeRunner{
Provider: openaicompat.New(client),
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
LogDir: t.TempDir(),
}
}
func localTask() *task.Task {
return &task.Task{
ID: "task-1",
Name: "test",
Agent: task.AgentConfig{
Type: "local",
Model: "fake",
Instructions: "Do a thing.",
SkipPlanning: true, // keep the preamble out of these assertions
},
}
}
func TestNativeRunner_Run_WritesStreamJSON(t *testing.T) {
srv := fakeChatServer(t, []fakeTurn{{content: "## Summary\nAll good.", promptTok: 11, outTok: 22}})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec, newStoreChannel(&fakeChannelStore{}, tt.ID)); err != nil {
t.Fatalf("Run: %v", err)
}
if exec.CostUSD != 0 {
t.Errorf("CostUSD should be 0 for native runner, got %v", exec.CostUSD)
}
if exec.TokensIn != 11 || exec.TokensOut != 22 {
t.Errorf("tokens: want 11/22 got %d/%d", exec.TokensIn, exec.TokensOut)
}
stdoutPath := filepath.Join(r.ExecLogDir(exec.ID), "stdout.log")
data, err := os.ReadFile(stdoutPath)
if err != nil {
t.Fatalf("read stdout: %v", err)
}
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
// One assistant envelope + one result line.
if len(lines) != 2 {
t.Fatalf("expected 2 lines (assistant + result), got %d:\n%s", len(lines), data)
}
var env struct {
Type string `json:"type"`
}
if err := json.Unmarshal([]byte(lines[0]), &env); err != nil || env.Type != "assistant" {
t.Fatalf("line 0 should be an assistant envelope: %v: %s", err, lines[0])
}
if summary := extractSummary(stdoutPath); !strings.Contains(summary, "All good.") {
t.Errorf("extractSummary should find 'All good.', got %q", summary)
}
}
func TestNativeRunner_Run_ToolLoop_ReportSummaryAndSpawn(t *testing.T) {
// Turn 1: model spawns a subtask. Turn 2: reports summary. Turn 3: finishes.
srv := fakeChatServer(t, []fakeTurn{
{toolCalls: []llm.ToolCall{toolCall("c1", "spawn_subtask", `{"name":"sub A","instructions":"do sub"}`)}, promptTok: 5, outTok: 3},
{toolCalls: []llm.ToolCall{toolCall("c2", "report_summary", `{"summary":"all done"}`)}, promptTok: 4, outTok: 2},
{content: "finished", promptTok: 2, outTok: 1},
})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
store := &fakeChannelStore{}
ch := newStoreChannel(store, tt.ID)
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec, ch); err != nil {
t.Fatalf("Run: %v", err)
}
if len(store.createdTasks) != 1 || store.createdTasks[0].Name != "sub A" {
t.Errorf("expected one spawned subtask 'sub A', got %+v", store.createdTasks)
}
if store.createdTasks[0].ParentTaskID != tt.ID {
t.Errorf("subtask parent: want %q, got %q", tt.ID, store.createdTasks[0].ParentTaskID)
}
if sum, ok := ch.ReportedSummary(); !ok || sum != "all done" {
t.Errorf("expected reported summary 'all done', got %q (set=%v)", sum, ok)
}
// Tokens accumulate across all three turns.
if exec.TokensIn != 11 || exec.TokensOut != 6 {
t.Errorf("tokens should accumulate: want 11/6, got %d/%d", exec.TokensIn, exec.TokensOut)
}
}
// TestNativeRunner_Run_ToolLoop_SpawnSubtask_RolePassthrough is an
// end-to-end-ish test (fake LLM server, real agentloop.Loop/tools.go
// dispatch, real storeChannel) proving a spawn_subtask tool call carrying a
// "role" argument reaches SubtaskSpec.Role correctly through
// internal/agentloop/tools.go's dispatchTool, and from there through
// storeChannel.SpawnSubtask into the created child task's Agent.Role.
func TestNativeRunner_Run_ToolLoop_SpawnSubtask_RolePassthrough(t *testing.T) {
srv := fakeChatServer(t, []fakeTurn{
{toolCalls: []llm.ToolCall{toolCall("c1", "spawn_subtask", `{"name":"eval","instructions":"evaluate","role":"evaluator_quality"}`)}},
{content: "finished"},
})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
store := &fakeChannelStore{}
ch := newStoreChannel(store, tt.ID)
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec, ch); err != nil {
t.Fatalf("Run: %v", err)
}
if len(store.createdTasks) != 1 {
t.Fatalf("expected 1 spawned subtask, got %d", len(store.createdTasks))
}
child := store.createdTasks[0]
if child.Agent.Role != "evaluator_quality" {
t.Errorf("Agent.Role: want evaluator_quality, got %q", child.Agent.Role)
}
if child.Agent.Type != "" {
t.Errorf("Agent.Type: want empty for role-typed subtask, got %q", child.Agent.Type)
}
if child.Agent.Instructions != "evaluate" {
t.Errorf("Agent.Instructions: want evaluate, got %q", child.Agent.Instructions)
}
}
// TestNativeRunner_Run_ToolLoop_ProposeEpic is an end-to-end-ish test (fake
// LLM server, real agentloop.Loop/tools.go dispatch, real storeChannel)
// proving a propose_epic tool call reaches AgentChannel.ProposeEpic
// correctly through internal/agentloop/tools.go's dispatchTool, and from
// there through storeChannel.ProposeEpic into a created epic with the given
// stories grouped under it — mirroring the spawn_subtask role-passthrough
// coverage above (Phase 6) for this phase's new tool (Phase 7c).
func TestNativeRunner_Run_ToolLoop_ProposeEpic(t *testing.T) {
srv := fakeChatServer(t, []fakeTurn{
{toolCalls: []llm.ToolCall{toolCall("c1", "propose_epic", `{"name":"Checkout revamp","description":"relaunch","story_ids":["story-1","story-2"]}`)}},
{content: "finished"},
})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
store := &fakeChannelStore{
stories: map[string]*story.Story{
"story-1": {ID: "story-1", Name: "s1"},
"story-2": {ID: "story-2", Name: "s2"},
},
}
ch := newStoreChannel(store, tt.ID)
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec, ch); err != nil {
t.Fatalf("Run: %v", err)
}
if len(store.epics) != 1 {
t.Fatalf("expected 1 created epic, got %d", len(store.epics))
}
var epicID string
for id, e := range store.epics {
epicID = id
if e.Name != "Checkout revamp" || e.Description != "relaunch" {
t.Errorf("epic fields not propagated: %+v", e)
}
}
if store.stories["story-1"].EpicID != epicID || store.stories["story-2"].EpicID != epicID {
t.Errorf("stories not grouped under the proposed epic: %+v / %+v", store.stories["story-1"], store.stories["story-2"])
}
}
// TestNativeRunner_Run_ToolLoop_ProposeRoleConfig is an end-to-end-ish test
// (fake LLM server, real agentloop.Loop/tools.go dispatch, real
// storeChannel) proving a propose_role_config tool call reaches
// AgentChannel.ProposeRoleConfig correctly through
// internal/agentloop/tools.go's dispatchTool, and from there through
// storeChannel.ProposeRoleConfig into a new draft role_configs row —
// mirroring the propose_epic coverage above (Phase 7c) for this phase's
// (Phase 8) new tool.
func TestNativeRunner_Run_ToolLoop_ProposeRoleConfig(t *testing.T) {
srv := fakeChatServer(t, []fakeTurn{
{toolCalls: []llm.ToolCall{toolCall("c1", "propose_role_config", `{"role":"builder","system_prompt":"Be more careful.","escalation_ladder":[{"candidates":[{"provider":"anthropic","model":"claude-sonnet-4-6"}],"max_retries":1}]}`)}},
{content: "finished"},
})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
store := &fakeChannelStore{}
ch := newStoreChannel(store, tt.ID)
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec, ch); err != nil {
t.Fatalf("Run: %v", err)
}
rows := store.roleConfigs["builder"]
if len(rows) != 1 {
t.Fatalf("expected 1 created role_configs row, got %d", len(rows))
}
row := rows[0]
if row.Status != "draft" {
t.Errorf("expected status draft, got %q", row.Status)
}
var decoded struct {
Role string `json:"role"`
SystemPrompt string `json:"system_prompt"`
EscalationLadder []struct {
Candidates []struct {
Provider string `json:"provider"`
Model string `json:"model"`
} `json:"candidates"`
MaxRetries int `json:"max_retries"`
} `json:"escalation_ladder"`
}
if err := json.Unmarshal([]byte(row.ConfigJSON), &decoded); err != nil {
t.Fatalf("unmarshal config_json: %v", err)
}
if decoded.Role != "builder" || decoded.SystemPrompt != "Be more careful." {
t.Errorf("config fields not propagated: %+v", decoded)
}
if len(decoded.EscalationLadder) != 1 || len(decoded.EscalationLadder[0].Candidates) != 1 ||
decoded.EscalationLadder[0].Candidates[0].Provider != "anthropic" {
t.Errorf("escalation_ladder not propagated: %+v", decoded.EscalationLadder)
}
if len(store.createdEvents) != 1 || store.createdEvents[0].TaskID != tt.ID {
t.Errorf("expected 1 role_config_proposed event attached to the calling task, got %+v", store.createdEvents)
}
}
func TestNativeRunner_Run_RecordProgress(t *testing.T) {
srv := fakeChatServer(t, []fakeTurn{
{toolCalls: []llm.ToolCall{toolCall("c1", "record_progress", `{"message":"halfway there"}`)}},
{content: "done"},
})
defer srv.Close()
store := &fakeChannelStore{}
tt := localTask()
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := newLocalRunner(t, srv).Run(context.Background(), tt, exec, newStoreChannel(store, tt.ID)); err != nil {
t.Fatalf("Run: %v", err)
}
if len(store.createdEvents) != 1 {
t.Fatalf("expected 1 progress event, got %d", len(store.createdEvents))
}
if !strings.Contains(string(store.createdEvents[0].Payload), "halfway there") {
t.Errorf("progress event payload: %s", store.createdEvents[0].Payload)
}
}
func TestNativeRunner_Run_AskUser_Blocks(t *testing.T) {
srv := fakeChatServer(t, []fakeTurn{
{toolCalls: []llm.ToolCall{toolCall("c1", "ask_user", `{"question":"which branch?"}`)}},
{content: "should not be reached"},
})
defer srv.Close()
tt := localTask()
exec := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
err := newLocalRunner(t, srv).Run(context.Background(), tt, exec, newStoreChannel(&fakeChannelStore{}, tt.ID))
var be *BlockedError
if !errors.As(err, &be) {
t.Fatalf("expected *BlockedError, got %v", err)
}
if !strings.Contains(be.QuestionJSON, "which branch?") {
t.Errorf("BlockedError question: %q", be.QuestionJSON)
}
}
func TestNativeRunner_Run_NoProvider_Errors(t *testing.T) {
r := &NativeRunner{LogDir: t.TempDir()}
tt := &task.Task{ID: "x", Agent: task.AgentConfig{Instructions: "hi"}}
exec := &storage.Execution{ID: "exec-x"}
err := r.Run(context.Background(), tt, exec, newStoreChannel(nil, tt.ID))
if err == nil || !strings.Contains(err.Error(), "no provider configured") {
t.Errorf("expected 'no provider configured' error, got %v", err)
}
}
func TestNativeRunner_Run_EmptyInstructions_Errors(t *testing.T) {
r := &NativeRunner{
Provider: openaicompat.New(&llm.Client{Endpoint: "http://unused", Model: "x"}),
LogDir: t.TempDir(),
}
tt := &task.Task{ID: "x", Agent: task.AgentConfig{}}
exec := &storage.Execution{ID: "exec-x"}
err := r.Run(context.Background(), tt, exec, newStoreChannel(nil, tt.ID))
if err == nil || !strings.Contains(err.Error(), "empty instructions") {
t.Errorf("expected empty-instructions error, got %v", err)
}
}
func TestNativeRunner_ExecLogDir(t *testing.T) {
r := &NativeRunner{LogDir: "/tmp/logs"}
if got := r.ExecLogDir("abc"); got != "/tmp/logs/abc" {
t.Errorf("ExecLogDir: got %q", got)
}
r.LogDir = ""
if got := r.ExecLogDir("abc"); got != "" {
t.Errorf("ExecLogDir empty LogDir: got %q", got)
}
}
// TestNativeRunner_Run_ProjectDir_SandboxToolsAndPush drives a task with
// Agent.ProjectDir set through write_file/read_file/glob/run_bash tool calls
// against a real HostSandbox (git clone into a temp dir), confirming the
// verbatim-ported sandbox.HostSandbox behavior end-to-end: tool dispatch
// hits the real filesystem/shell, a commit made via run_bash is pushed back
// to the origin repo on a clean finish, and the sandbox temp dir is removed
// afterward — exactly the git-clone/push/cleanup sequence LocalRunner used
// to run inline. No prior test (LocalRunner's included) exercised this path;
// it's new coverage for logic that was previously only exercised manually.
func TestNativeRunner_Run_ProjectDir_SandboxToolsAndPush(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
// Bare origin repo so `git push origin HEAD` from the sandbox clone
// doesn't hit receive.denyCurrentBranch.
origin := t.TempDir()
run := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com",
"GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com",
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
run(origin, "init", "--bare", "-b", "main")
// Seed the bare repo with an initial commit (an empty bare repo has no
// HEAD, so LocalRunner's plain `git clone <remote> <dir>` needs something
// to check out).
seed := t.TempDir()
run(seed, "init", "-b", "main")
run(seed, "remote", "add", "origin", origin)
if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o644); err != nil {
t.Fatal(err)
}
run(seed, "add", "-A")
run(seed, "commit", "-m", "seed")
run(seed, "push", "origin", "main")
srv := fakeChatServer(t, []fakeTurn{
{toolCalls: []llm.ToolCall{toolCall("c1", "write_file", `{"path":"hello.txt","content":"hello world"}`)}},
{toolCalls: []llm.ToolCall{toolCall("c2", "read_file", `{"path":"hello.txt"}`)}},
{toolCalls: []llm.ToolCall{toolCall("c3", "glob", `{"pattern":"*.txt"}`)}},
{toolCalls: []llm.ToolCall{toolCall("c4", "run_bash", `{"command":"git add -A && git -c user.name=test -c user.email=test@example.com commit -m 'add hello'"}`)}},
{content: "## Summary\nAdded hello.txt and committed."},
})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
tt.Agent.ProjectDir = origin
exec_ := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec_, newStoreChannel(&fakeChannelStore{}, tt.ID)); err != nil {
t.Fatalf("Run: %v", err)
}
if exec_.SandboxDir != "" {
t.Errorf("expected SandboxDir cleared after clean finish, got %q", exec_.SandboxDir)
}
// Verify the commit actually landed on origin.
logCmd := exec.Command("git", "-C", origin, "log", "--oneline", "main")
out, err := logCmd.CombinedOutput()
if err != nil {
t.Fatalf("git log on origin: %v\n%s", err, out)
}
if !strings.Contains(string(out), "add hello") {
t.Errorf("expected pushed commit 'add hello' in origin log, got:\n%s", out)
}
}
// TestNativeRunner_Run_GuardrailRejection_IsNonFatal confirms the Phase 3
// guardrail wiring end-to-end: NativeRunner now always wraps its sandbox in
// sandbox.Guarded (see NativeRunner.newBaseSandbox), so a denylisted
// run_bash command and a write to a protected path both get rejected
// without aborting the run — the model sees the rejection reason as
// ordinary tool content (via the sandbox.RejectionError handling added to
// agentloop.dispatchTool) and the loop continues to a normal finish,
// exactly like a failed shell command would (non-zero exit code, not a
// crashed execution).
func TestNativeRunner_Run_GuardrailRejection_IsNonFatal(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
origin := t.TempDir()
run := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com",
"GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com",
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
run(origin, "init", "--bare", "-b", "main")
seed := t.TempDir()
run(seed, "init", "-b", "main")
run(seed, "remote", "add", "origin", origin)
if err := os.WriteFile(filepath.Join(seed, "README.md"), []byte("seed\n"), 0o644); err != nil {
t.Fatal(err)
}
run(seed, "add", "-A")
run(seed, "commit", "-m", "seed")
run(seed, "push", "origin", "main")
srv := fakeChatServer(t, []fakeTurn{
// Turn 1: model tries something denylisted via run_bash.
{toolCalls: []llm.ToolCall{toolCall("c1", "run_bash", `{"command":"rm -rf /"}`)}},
// Turn 2: model tries to write a protected path.
{toolCalls: []llm.ToolCall{toolCall("c2", "write_file", `{"path":".env","content":"SECRET=1"}`)}},
// Turn 3: model recovers and does ordinary, allowed work.
{toolCalls: []llm.ToolCall{toolCall("c3", "write_file", `{"path":"hello.txt","content":"hello world"}`)}},
{toolCalls: []llm.ToolCall{toolCall("c4", "run_bash", `{"command":"git add -A && git -c user.name=test -c user.email=test@example.com commit -m 'add hello'"}`)}},
{content: "## Summary\nAdded hello.txt and committed."},
})
defer srv.Close()
r := newLocalRunner(t, srv)
tt := localTask()
tt.Agent.ProjectDir = origin
exec_ := &storage.Execution{ID: uuid.New().String(), TaskID: tt.ID}
if err := r.Run(context.Background(), tt, exec_, newStoreChannel(&fakeChannelStore{}, tt.ID)); err != nil {
t.Fatalf("Run should complete successfully despite rejected tool calls: %v", err)
}
// The commit from turn 4 should still have landed and been pushed —
// proof the run continued normally after both rejections.
logCmd := exec.Command("git", "-C", origin, "log", "--oneline", "main")
out, err := logCmd.CombinedOutput()
if err != nil {
t.Fatalf("git log on origin: %v\n%s", err, out)
}
if !strings.Contains(string(out), "add hello") {
t.Errorf("expected pushed commit 'add hello' in origin log, got:\n%s", out)
}
// And .env must never have been written into the sandbox — the write
// was rejected before it ever reached the wrapped Sandbox.
if _, err := os.Stat(filepath.Join(origin, ".env")); err == nil {
t.Error(".env should not exist in origin (write was rejected, nothing to push)")
}
}
|