gunk-dev/the-valley

pause_test.go

sourced9f7bacd171bmain's published tip history
14.5 KiB
1package cmd
2
3import (
4 "context"
5 "encoding/json"
6 "os"
7 "path/filepath"
8 "strings"
9 "testing"
10
11 "the-valley/flow/internal/draft"
12 "the-valley/flow/internal/event"
13 "the-valley/flow/internal/run"
14)
15
16// fakeRunner records gh/git calls and lets a test stub gh responses by
17// matching substrings in the joined args. git calls are forwarded to the
18// real git binary so worktree manipulation actually happens โ€” that's the
19// whole point of these tests (validate the WIP commit + push reach the
20// filesystem).
21type fakeRunner struct {
22 realGit draft.ExecRunner
23 ghCalls [][]string
24 ghStubs []ghStub
25}
26
27type ghStub struct {
28 match []string
29 out string
30 err error
31}
32
33func (f *fakeRunner) Git(ctx context.Context, workdir string, args ...string) (string, error) {
34 return f.realGit.Git(ctx, workdir, args...)
35}
36
37func (f *fakeRunner) GH(_ context.Context, _ string, args ...string) (string, error) {
38 cp := append([]string(nil), args...)
39 f.ghCalls = append(f.ghCalls, cp)
40 joined := strings.Join(args, " ")
41 for _, s := range f.ghStubs {
42 all := true
43 for _, m := range s.match {
44 if !strings.Contains(joined, m) {
45 all = false
46 break
47 }
48 }
49 if all {
50 return s.out, s.err
51 }
52 }
53 return "", nil
54}
55
56func (f *fakeRunner) findCall(parts ...string) []string {
57 for _, c := range f.ghCalls {
58 all := true
59 for _, p := range parts {
60 found := false
61 for _, a := range c {
62 if a == p {
63 found = true
64 break
65 }
66 }
67 if !found {
68 all = false
69 break
70 }
71 }
72 if all {
73 return c
74 }
75 }
76 return nil
77}
78
79// setupBareRemote creates a bare repo to act as origin, an initial clone, a
80// worktree with one dirty file, and returns the paths.
81func setupBareRemote(t *testing.T) (origin, repo, worktree, branch string) {
82 t.Helper()
83 root := t.TempDir()
84
85 origin = filepath.Join(root, "origin.git")
86 runGitCmd(t, root, "init", "--bare", origin)
87
88 repo = filepath.Join(root, "repo")
89 runGitCmd(t, root, "clone", origin, repo)
90 runGitCmd(t, repo, "config", "user.email", "test@test")
91 runGitCmd(t, repo, "config", "user.name", "test")
92
93 // Seed initial commit on main.
94 if err := os.WriteFile(filepath.Join(repo, "README.md"), []byte("# repo\n"), 0644); err != nil {
95 t.Fatal(err)
96 }
97 runGitCmd(t, repo, "add", "README.md")
98 runGitCmd(t, repo, "commit", "-m", "init")
99 runGitCmd(t, repo, "branch", "-M", "main")
100 runGitCmd(t, repo, "push", "-u", "origin", "main")
101
102 branch = "agent/test-pause"
103 worktree = filepath.Join(root, "wt")
104 runGitCmd(t, repo, "worktree", "add", worktree, "-b", branch)
105 runGitCmd(t, worktree, "config", "user.email", "test@test")
106 runGitCmd(t, worktree, "config", "user.name", "test")
107
108 // Add a dirty file (uncommitted) to simulate work-in-progress.
109 if err := os.WriteFile(filepath.Join(worktree, "wip.txt"), []byte("partial work\n"), 0644); err != nil {
110 t.Fatal(err)
111 }
112
113 return origin, repo, worktree, branch
114}
115
116func TestBudgetPauseFlow_EndToEnd(t *testing.T) {
117 _, _, worktree, branch := setupBareRemote(t)
118
119 r := &fakeRunner{}
120 // gh pr list returns nothing โ†’ triggers create.
121 r.ghStubs = append(r.ghStubs,
122 ghStub{match: []string{"pr", "list", "--head"}, out: "", err: nil},
123 ghStub{match: []string{"pr", "create", "--draft"}, out: "https://github.com/owner/repo/pull/777\n", err: nil},
124 )
125
126 in := draft.PauseInput{
127 RunID: "20260529-1729-zzzz",
128 Worktree: worktree,
129 Branch: branch,
130 Repo: "owner/repo",
131 Prompt: "fix the auth bug",
132 CostUSD: 4.98,
133 BudgetUSD: 5.00,
134 }
135 out, err := draft.HandleBudgetPause(context.Background(), r, in)
136 if err != nil {
137 t.Fatalf("HandleBudgetPause: %v", err)
138 }
139
140 if !out.CommittedWIP {
141 t.Error("expected CommittedWIP=true (worktree had dirty file)")
142 }
143 if !out.CreatedNewPR {
144 t.Error("expected CreatedNewPR=true (no existing PR)")
145 }
146 if out.PRNumber != "777" {
147 t.Errorf("expected PRNumber=777, got %q", out.PRNumber)
148 }
149
150 // Verify the WIP commit landed: git log on the branch must show a
151 // commit referencing the run ID.
152 logOut, err := r.realGit.Git(context.Background(), worktree, "log", "-1", "--format=%s")
153 if err != nil {
154 t.Fatalf("git log: %v", err)
155 }
156 if !strings.Contains(logOut, "WIP from klaus run 20260529-1729-zzzz") {
157 t.Errorf("expected WIP commit message, got %q", strings.TrimSpace(logOut))
158 }
159
160 // Verify the branch was pushed to origin.
161 listOut, err := r.realGit.Git(context.Background(), worktree, "ls-remote", "origin", branch)
162 if err != nil {
163 t.Fatalf("ls-remote: %v", err)
164 }
165 if strings.TrimSpace(listOut) == "" {
166 t.Error("expected branch pushed to origin, got empty ls-remote")
167 }
168
169 // Verify gh was driven through the pause sequence.
170 if r.findCall("label", "create", "klaus:budget-paused") == nil {
171 t.Error("expected gh label create call")
172 }
173 if r.findCall("pr", "create", "--draft", "--head", branch) == nil {
174 t.Error("expected gh pr create --draft call")
175 }
176 if r.findCall("pr", "edit", "777", "--add-label") == nil {
177 t.Error("expected gh pr edit --add-label call")
178 }
179 if c := r.findCall("pr", "comment", "777"); c == nil {
180 t.Error("expected gh pr comment call")
181 } else {
182 joined := strings.Join(c, " ")
183 if !strings.Contains(joined, "$4.98") || !strings.Contains(joined, "$5.00") {
184 t.Errorf("expected comment body with cost/budget, got %q", joined)
185 }
186 }
187}
188
189func TestBudgetPauseFlow_ReusesExistingPR(t *testing.T) {
190 _, _, worktree, branch := setupBareRemote(t)
191
192 r := &fakeRunner{}
193 r.ghStubs = append(r.ghStubs,
194 // lookup existing PR returns number+url
195 ghStub{match: []string{"pr", "view", "55", "--repo", "owner/repo", "--json"}, out: "55\nhttps://github.com/owner/repo/pull/55\n"},
196 )
197
198 in := draft.PauseInput{
199 RunID: "20260529-1729-aaaa",
200 Worktree: worktree,
201 Branch: branch,
202 Repo: "owner/repo",
203 Prompt: "second attempt",
204 CostUSD: 4.95,
205 BudgetUSD: 5.00,
206 ExistingPR: "55",
207 }
208 out, err := draft.HandleBudgetPause(context.Background(), r, in)
209 if err != nil {
210 t.Fatalf("HandleBudgetPause: %v", err)
211 }
212
213 if out.CreatedNewPR {
214 t.Error("expected to reuse PR #55, not create a new one")
215 }
216 if out.PRNumber != "55" {
217 t.Errorf("expected PR #55, got %q", out.PRNumber)
218 }
219 // Should not have called pr create.
220 if c := r.findCall("pr", "create"); c != nil {
221 t.Errorf("expected no gh pr create, got %v", c)
222 }
223 // Should still apply label and comment.
224 if r.findCall("pr", "edit", "55", "--add-label") == nil {
225 t.Error("expected label apply on existing PR")
226 }
227 if r.findCall("pr", "comment", "55") == nil {
228 t.Error("expected PR comment on existing PR")
229 }
230}
231
232func TestIsBudgetExhausted(t *testing.T) {
233 cost := 4.95
234 budget5 := "5.00"
235 budget10 := "10.00"
236 tests := []struct {
237 name string
238 state *run.State
239 subtype string
240 want bool
241 }{
242 {
243 name: "95 percent with non-success subtype",
244 state: &run.State{CostUSD: &cost, Budget: &budget5},
245 subtype: "",
246 want: true,
247 },
248 {
249 name: "95 percent but success subtype",
250 state: &run.State{CostUSD: &cost, Budget: &budget5},
251 subtype: "success",
252 want: false,
253 },
254 {
255 name: "below 95 percent",
256 state: &run.State{CostUSD: &cost, Budget: &budget10},
257 subtype: "",
258 want: false,
259 },
260 {
261 name: "no budget",
262 state: &run.State{CostUSD: &cost},
263 subtype: "",
264 want: false,
265 },
266 {
267 name: "no cost",
268 state: &run.State{Budget: &budget5},
269 subtype: "",
270 want: false,
271 },
272 }
273 for _, tt := range tests {
274 t.Run(tt.name, func(t *testing.T) {
275 got := isBudgetExhausted(tt.state, tt.subtype)
276 if got != tt.want {
277 t.Errorf("isBudgetExhausted = %v, want %v", got, tt.want)
278 }
279 })
280 }
281}
282
283// TestFinalizeBudgetPauseEmitsEvents drives the full _finalize budget-pause
284// path end-to-end: a dirty worktree + a result-event-less log + cost near
285// the cap โ†’ expects the WIP commit, the gh pause calls, agent:paused +
286// agent:pr-created events in events.jsonl, and the worktree removed.
287func TestFinalizeBudgetPauseEmitsEvents(t *testing.T) {
288 _, repo, worktree, branch := setupBareRemote(t)
289
290 sessionID := "20260529-1729-test-session"
291 // Set up the HomeDirStore at a temp KLAUS sessions dir.
292 homeDir := t.TempDir()
293 t.Setenv("HOME", homeDir)
294 t.Setenv(sessionIDEnv, sessionID)
295 store, err := run.NewHomeDirStore(sessionID)
296 if err != nil {
297 t.Fatalf("NewHomeDirStore: %v", err)
298 }
299 if err := store.EnsureDirs(); err != nil {
300 t.Fatalf("EnsureDirs: %v", err)
301 }
302
303 // Build a fake log file with cost near budget cap, no success subtype.
304 runID := "20260529-1729-runxx"
305 logFile := filepath.Join(store.LogDir(), runID+".jsonl")
306 logContent := `{"type":"system","subtype":"init","model":"claude-sonnet-4-5"}
307{"type":"assistant","message":{"content":[{"type":"text","text":"working..."}]}}
308{"type":"result","subtype":"error_max_turns","is_error":true,"total_cost_usd":4.95,"duration_ms":30000}
309{"type":"klaus_exit","exit_code":1}
310`
311 if err := os.WriteFile(logFile, []byte(logContent), 0644); err != nil {
312 t.Fatalf("writing log: %v", err)
313 }
314
315 budget := "5.00"
316 targetRepo := "owner/repo"
317 state := &run.State{
318 ID: runID,
319 Prompt: "fix the auth bug in handler",
320 Branch: branch,
321 Worktree: worktree,
322 CreatedAt: "2026-05-29T17:00:00Z",
323 LogFile: &logFile,
324 Budget: &budget,
325 TargetRepo: &targetRepo,
326 CloneDir: &repo,
327 }
328 if err := store.Save(state); err != nil {
329 t.Fatalf("saving state: %v", err)
330 }
331
332 // Inject the fake gh runner; keep real git.
333 r := &fakeRunner{}
334 r.ghStubs = []ghStub{
335 {match: []string{"pr", "list", "--head"}, out: ""},
336 {match: []string{"pr", "create", "--draft"}, out: "https://github.com/owner/repo/pull/123\n"},
337 }
338 prev := budgetPauseRunner
339 budgetPauseRunner = r
340 defer func() { budgetPauseRunner = prev }()
341
342 // Run _finalize.
343 finalizeCmd.SetContext(context.Background())
344 if err := finalizeCmd.RunE(finalizeCmd, []string{runID}); err != nil {
345 t.Fatalf("_finalize: %v", err)
346 }
347
348 // Assert: gh pause calls were issued.
349 if r.findCall("pr", "create", "--draft") == nil {
350 t.Error("expected gh pr create --draft (no prior PR was set on state)")
351 }
352 if r.findCall("pr", "edit", "123", "--add-label") == nil {
353 t.Error("expected gh label apply on PR 123")
354 }
355 if r.findCall("pr", "comment", "123") == nil {
356 t.Error("expected gh pr comment on PR 123")
357 }
358
359 // Assert: events log contains agent:paused.
360 evtFile := filepath.Join(store.BaseDir(), "events.jsonl")
361 data, err := os.ReadFile(evtFile)
362 if err != nil {
363 t.Fatalf("reading events.jsonl: %v", err)
364 }
365 pausedFound := false
366 prCreatedFound := false
367 completedFound := false
368 for _, line := range strings.Split(string(data), "\n") {
369 if line == "" {
370 continue
371 }
372 var ev struct {
373 RunID string `json:"run_id"`
374 Type string `json:"type"`
375 Data map[string]interface{} `json:"data"`
376 }
377 if err := json.Unmarshal([]byte(line), &ev); err != nil {
378 continue
379 }
380 if ev.Type == event.AgentPaused && ev.RunID == runID {
381 pausedFound = true
382 if got, _ := ev.Data["pr_number"].(string); got != "123" {
383 t.Errorf("agent:paused pr_number = %q, want 123", got)
384 }
385 }
386 if ev.Type == event.AgentPRCreated && ev.RunID == runID {
387 prCreatedFound = true
388 }
389 if ev.Type == event.AgentCompleted && ev.RunID == runID {
390 completedFound = true
391 }
392 }
393 if !pausedFound {
394 t.Error("expected agent:paused event in events.jsonl")
395 }
396 if !prCreatedFound {
397 t.Error("expected agent:pr-created event in events.jsonl (PR was discovered)")
398 }
399 if completedFound {
400 t.Error("agent:completed should be suppressed when the run is paused")
401 }
402
403 // Assert: worktree was cleaned up by _finalize's cleanupWorktree step.
404 if _, err := os.Stat(worktree); !os.IsNotExist(err) {
405 t.Errorf("expected worktree removed after _finalize, stat err = %v", err)
406 }
407
408 // Assert: the WIP commit was pushed to origin.
409 pushed, err := r.realGit.Git(context.Background(), repo, "ls-remote", "origin", branch)
410 if err != nil {
411 t.Fatalf("ls-remote: %v", err)
412 }
413 if strings.TrimSpace(pushed) == "" {
414 t.Error("expected branch pushed to origin, got empty ls-remote")
415 }
416}
417
418// TestFinalizeClearsBudgetPausedLabel verifies that a normal-completion
419// _finalize against a PR that carries the budget-paused label removes the
420// label and emits agent:resumed.
421func TestFinalizeClearsBudgetPausedLabel(t *testing.T) {
422 _, repo, worktree, branch := setupBareRemote(t)
423
424 sessionID := "20260529-1729-clear-session"
425 homeDir := t.TempDir()
426 t.Setenv("HOME", homeDir)
427 t.Setenv(sessionIDEnv, sessionID)
428 store, err := run.NewHomeDirStore(sessionID)
429 if err != nil {
430 t.Fatalf("NewHomeDirStore: %v", err)
431 }
432 if err := store.EnsureDirs(); err != nil {
433 t.Fatalf("EnsureDirs: %v", err)
434 }
435
436 // Log: success subtype, cost well below cap.
437 runID := "20260529-1729-runzz"
438 logFile := filepath.Join(store.LogDir(), runID+".jsonl")
439 logContent := `{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":10000}
440`
441 if err := os.WriteFile(logFile, []byte(logContent), 0644); err != nil {
442 t.Fatalf("writing log: %v", err)
443 }
444
445 prNum := "200"
446 prURL := "https://github.com/owner/repo/pull/200"
447 budget := "5.00"
448 targetRepo := "owner/repo"
449 state := &run.State{
450 ID: runID,
451 Prompt: "finish what the paused agent started",
452 PR: &prNum,
453 PRURL: &prURL,
454 Branch: branch,
455 Worktree: worktree,
456 CreatedAt: "2026-05-29T17:00:00Z",
457 LogFile: &logFile,
458 Budget: &budget,
459 TargetRepo: &targetRepo,
460 CloneDir: &repo,
461 Type: "pr-fix",
462 }
463 if err := store.Save(state); err != nil {
464 t.Fatalf("saving state: %v", err)
465 }
466
467 // gh stubs: HasBudgetPausedLabel returns the label, ClearBudgetPausedLabel succeeds.
468 r := &fakeRunner{}
469 r.ghStubs = []ghStub{
470 {match: []string{"pr", "view", "200", "--repo", "owner/repo", "--json", "labels"}, out: "klaus:budget-paused\n"},
471 {match: []string{"pr", "edit", "200", "--repo", "owner/repo", "--remove-label"}, out: ""},
472 }
473 prev := budgetPauseRunner
474 budgetPauseRunner = r
475 defer func() { budgetPauseRunner = prev }()
476
477 finalizeCmd.SetContext(context.Background())
478 if err := finalizeCmd.RunE(finalizeCmd, []string{runID}); err != nil {
479 t.Fatalf("_finalize: %v", err)
480 }
481
482 if r.findCall("pr", "edit", "200", "--remove-label") == nil {
483 t.Error("expected gh pr edit --remove-label on follow-up finalize")
484 }
485
486 // Assert agent:resumed emitted, agent:completed also emitted.
487 evtFile := filepath.Join(store.BaseDir(), "events.jsonl")
488 data, _ := os.ReadFile(evtFile)
489 if !strings.Contains(string(data), event.AgentResumed) {
490 t.Error("expected agent:resumed event")
491 }
492 if !strings.Contains(string(data), event.AgentCompleted) {
493 t.Error("expected agent:completed event on normal finalize")
494 }
495 // Verify we did NOT trigger the budget-pause flow this time.
496 if r.findCall("pr", "create", "--draft") != nil {
497 t.Error("should not run pause flow on a successful completion")
498 }
499}