gunk-dev/the-valley

launch_test.go

source672eff5ffaecmain's published tip history
17.0 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11 "time"
12
13 "the-valley/flow/internal/cmd"
14 "the-valley/flow/internal/config"
15 "the-valley/flow/internal/run"
16)
17
18// TestLaunchLifecycle is the headline scenario. With a fake claude, a real git
19// worktree, and a fake gh, it drives `klaus launch` end-to-end and asserts the
20// full lifecycle:
21//
22// (a) a real pane is created in the isolated tmux server with the agent title,
23// (b) run state is written with a branch, worktree, and pane,
24// (c) the fake claude was invoked with the expected args,
25// (d) after the agent completes, _finalize populates cost/duration/PR URL from
26// the stub's emitted stream-json, and
27// (e) the worktree is removed and the pane is killed.
28//
29// The origin is on GitHub (UseGitHubOrigin), so the run delivers by PR and
30// takes the PR URL its log names.
31func TestLaunchLifecycle(t *testing.T) {
32 t.Parallel()
33 h := NewHarness(t)
34 h.UseGitHubOrigin()
35
36 const prompt = "add a health check endpoint"
37 res := h.RunKlaus("launch", prompt)
38 if res.ExitCode != 0 {
39 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
40 }
41
42 // Exactly one run should have been recorded.
43 ids := h.RunIDs()
44 if len(ids) != 1 {
45 t.Fatalf("expected 1 run, got %d: %v", len(ids), ids)
46 }
47 runID := ids[0]
48
49 // (b) State is written with branch/worktree/pane while the agent runs.
50 st, err := h.ReadState(runID)
51 if err != nil {
52 t.Fatalf("reading state: %v", err)
53 }
54 if st.Branch == "" {
55 t.Error("state has empty Branch")
56 }
57 if st.Worktree == "" {
58 t.Error("state has empty Worktree")
59 }
60 if st.TmuxPane == nil || *st.TmuxPane == "" {
61 t.Fatal("state has no TmuxPane")
62 }
63 pane := *st.TmuxPane
64
65 // The worktree should actually exist on disk during the run.
66 if _, err := os.Stat(st.Worktree); err != nil {
67 t.Errorf("worktree should exist during run: %v", err)
68 }
69
70 // Wait until the fake claude is actually running in the pane before we
71 // assert on the live pane (the stub blocks until released).
72 h.WaitForClaudeStart(30 * time.Second)
73
74 // (a) The pane exists in the isolated server with the expected title.
75 if !h.PaneExists(pane) {
76 t.Fatalf("expected pane %s to exist; panes: %v", pane, h.ListPanes())
77 }
78 wantTitle := cmd.FormatPaneTitle(runID, "", prompt)
79 if got := h.PaneTitle(pane); got != wantTitle {
80 t.Errorf("pane title = %q, want %q", got, wantTitle)
81 }
82
83 // (c) claude was invoked with the expected args, and the prompt on stdin.
84 argv := h.ClaudeArgv()
85 for _, want := range []string{"-p", "--output-format", "stream-json", "--max-budget-usd", "--append-system-prompt-file"} {
86 if !strings.Contains(argv, want) {
87 t.Errorf("claude argv missing %q\n--- argv ---\n%s", want, argv)
88 }
89 }
90 if strings.Contains(argv, prompt) {
91 t.Errorf("prompt should not be in argv\n--- argv ---\n%s", argv)
92 }
93 if got := h.ClaudeStdin(); got != prompt {
94 t.Errorf("claude stdin = %q, want the prompt %q", got, prompt)
95 }
96 // With neither flag nor config set, the claude command must not carry
97 // --model/--effort at all — claude's own resolution applies unchanged.
98 for _, absent := range []string{"--model", "--effort"} {
99 if strings.Contains(argv, absent) {
100 t.Errorf("claude argv should not carry %q when unset\n--- argv ---\n%s", absent, argv)
101 }
102 }
103
104 // Let the agent finish; the pipeline runs _format-stream then _finalize.
105 h.ReleaseClaude()
106
107 // (d) _finalize populates cost/duration/PR URL from the emitted log.
108 final := h.WaitForState(runID, func(s *run.State) bool {
109 return s.CostUSD != nil && s.TmuxPane == nil
110 }, 30*time.Second)
111
112 if final.CostUSD == nil || *final.CostUSD != 0.1234 {
113 t.Errorf("CostUSD = %v, want 0.1234", final.CostUSD)
114 }
115 if final.DurationMS == nil || *final.DurationMS != 4242 {
116 t.Errorf("DurationMS = %v, want 4242", final.DurationMS)
117 }
118 if final.Delivery != run.DeliveryPR {
119 t.Errorf("Delivery = %q, want %q", final.Delivery, run.DeliveryPR)
120 }
121 if final.PRURL == nil || *final.PRURL != "https://github.com/acme/widget/pull/4242" {
122 t.Errorf("PRURL = %v, want the PR URL from the stub log", final.PRURL)
123 }
124
125 // (e) The worktree is removed and the pane is killed.
126 if final.Worktree != "" {
127 t.Errorf("Worktree should be cleared after cleanup, got %q", final.Worktree)
128 }
129 if _, err := os.Stat(st.Worktree); !os.IsNotExist(err) {
130 t.Errorf("worktree dir should be removed, stat err: %v", err)
131 }
132 waitPaneGone(t, h, pane, 30*time.Second)
133}
134
135// waitPaneGone polls until the pane disappears from the isolated server.
136func waitPaneGone(t *testing.T, h *Harness, pane string, timeout time.Duration) {
137 t.Helper()
138 deadline := time.Now().Add(timeout)
139 for time.Now().Before(deadline) {
140 if !h.PaneExists(pane) {
141 return
142 }
143 time.Sleep(100 * time.Millisecond)
144 }
145 t.Errorf("pane %s still alive after %s; panes: %v", pane, timeout, h.ListPanes())
146}
147
148// TestLaunchPromptFile covers the failure --prompt-file exists to prevent: a
149// prompt full of backticks passed as a shell argument is mangled by the shell
150// (in zsh, backticks inside double quotes are command substitution) long before
151// klaus sees it. Read from a file, the prompt must reach run state — and the
152// agent — byte for byte.
153func TestLaunchPromptFile(t *testing.T) {
154 t.Parallel()
155 h := NewHarness(t)
156
157 const prompt = "Fix `ValidateToken()` in internal/auth/verify.go:87 —\n" +
158 "it uses `Before()` where it should use `After()`.\n" +
159 "Do not touch $HOME handling; run `go test ./...` before pushing.\n"
160 promptPath := filepath.Join(h.E2EDir, "prompt.md")
161 if err := os.WriteFile(promptPath, []byte(prompt), 0o644); err != nil {
162 t.Fatalf("writing prompt file: %v", err)
163 }
164
165 res := h.RunKlaus("launch", "--prompt-file", promptPath, "--budget", "7.50")
166 if res.ExitCode != 0 {
167 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
168 }
169
170 ids := h.RunIDs()
171 if len(ids) != 1 {
172 t.Fatalf("expected 1 run, got %d: %v", len(ids), ids)
173 }
174 runID := ids[0]
175
176 st, err := h.ReadState(runID)
177 if err != nil {
178 t.Fatalf("reading state: %v", err)
179 }
180 if st.Prompt != prompt {
181 t.Errorf("state prompt does not match the file byte for byte:\n got: %q\nwant: %q", st.Prompt, prompt)
182 }
183 // Everything else downstream behaves as it does for a positional prompt.
184 if st.Budget == nil || *st.Budget != "7.50" {
185 t.Errorf("Budget = %v, want 7.50", st.Budget)
186 }
187 if st.Branch == "" || st.Worktree == "" || st.TmuxPane == nil {
188 t.Errorf("state incomplete: branch=%q worktree=%q pane=%v", st.Branch, st.Worktree, st.TmuxPane)
189 }
190
191 // The agent is actually briefed with the full text, backticks intact.
192 h.WaitForClaudeStart(30 * time.Second)
193 if got := h.ClaudeStdin(); got != prompt {
194 t.Errorf("claude stdin does not match the file prompt:\n got: %q\nwant: %q", got, prompt)
195 }
196
197 h.ReleaseClaude()
198 h.WaitForState(runID, func(s *run.State) bool { return s.TmuxPane == nil }, 30*time.Second)
199}
200
201// TestLaunchModelEffort covers per-launch model/effort selection: config
202// defaults apply when a flag is unset, a flag overrides the config default,
203// the values reach the claude argv, and the run state records what the run
204// executed under.
205func TestLaunchModelEffort(t *testing.T) {
206 t.Parallel()
207 h := NewHarness(t)
208
209 // Config sets defaults for both; the launch overrides only --effort.
210 h.AmendRepoConfig(map[string]any{
211 "default_agent_model": "claude-config-model",
212 "default_agent_effort": "high",
213 })
214
215 res := h.RunKlaus("launch", "add retries to the fetcher", "--effort", "low")
216 if res.ExitCode != 0 {
217 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
218 }
219
220 ids := h.RunIDs()
221 if len(ids) != 1 {
222 t.Fatalf("expected 1 run, got %d: %v", len(ids), ids)
223 }
224
225 h.WaitForClaudeStart(30 * time.Second)
226 argv := h.ClaudeArgv()
227 // Config default applies for the model; the flag wins for effort.
228 if !strings.Contains(argv, "--model\nclaude-config-model\n") {
229 t.Errorf("claude argv missing config-default model\n--- argv ---\n%s", argv)
230 }
231 if !strings.Contains(argv, "--effort\nlow\n") {
232 t.Errorf("claude argv missing flag-override effort\n--- argv ---\n%s", argv)
233 }
234 if strings.Contains(argv, "--effort\nhigh\n") {
235 t.Errorf("config effort should be overridden by the flag\n--- argv ---\n%s", argv)
236 }
237
238 // Run state records what the run executed under.
239 st, err := h.ReadState(ids[0])
240 if err != nil {
241 t.Fatalf("reading state: %v", err)
242 }
243 if st.Model == nil || *st.Model != "claude-config-model" {
244 t.Errorf("state Model = %v, want claude-config-model", st.Model)
245 }
246 if st.Effort == nil || *st.Effort != "low" {
247 t.Errorf("state Effort = %v, want low", st.Effort)
248 }
249
250 h.ReleaseClaude()
251 h.WaitForState(ids[0], func(s *run.State) bool { return s.TmuxPane == nil }, 30*time.Second)
252}
253
254// TestLaunchInvalidEffort asserts an effort outside the claude CLI's set is
255// rejected up front: non-zero exit, an error naming the valid values, and no
256// run recorded.
257func TestLaunchInvalidEffort(t *testing.T) {
258 t.Parallel()
259 h := NewHarness(t)
260
261 res := h.RunKlaus("launch", "do the thing", "--effort", "turbo")
262 if res.ExitCode == 0 {
263 t.Fatalf("launch with invalid effort exited 0\nstdout:\n%s", res.Stdout)
264 }
265 for _, want := range []string{"turbo", "low", "medium", "high", "xhigh", "max"} {
266 if !strings.Contains(res.Stderr, want) {
267 t.Errorf("stderr should mention %q, got:\n%s", want, res.Stderr)
268 }
269 }
270 if ids := h.RunIDs(); len(ids) != 0 {
271 t.Errorf("no run should have been recorded, got %v", ids)
272 }
273}
274
275// TestLaunchPromptSourceErrors asserts the prompt source is unambiguous: both
276// sources or neither is a clear error and no agent is launched.
277func TestLaunchPromptSourceErrors(t *testing.T) {
278 t.Parallel()
279 h := NewHarness(t)
280
281 promptPath := filepath.Join(h.E2EDir, "prompt.md")
282 if err := os.WriteFile(promptPath, []byte("do the thing\n"), 0o644); err != nil {
283 t.Fatalf("writing prompt file: %v", err)
284 }
285
286 cases := []struct {
287 name string
288 args []string
289 }{
290 {"both sources", []string{"launch", "do the thing", "--prompt-file", promptPath}},
291 {"no source", []string{"launch"}},
292 {"missing file", []string{"launch", "--prompt-file", filepath.Join(h.E2EDir, "nope.md")}},
293 }
294 for _, tc := range cases {
295 t.Run(tc.name, func(t *testing.T) {
296 res := h.RunKlaus(tc.args...)
297 if res.ExitCode == 0 {
298 t.Fatalf("launch %v exited 0, want a failure\nstdout:\n%s", tc.args, res.Stdout)
299 }
300 if !strings.Contains(res.Stderr, "prompt") {
301 t.Errorf("stderr should name the problem, got:\n%s", res.Stderr)
302 }
303 })
304 }
305
306 if ids := h.RunIDs(); len(ids) != 0 {
307 t.Errorf("no run should have been recorded, got %v", ids)
308 }
309}
310
311// TestLaunchLongPromptOverStdin is the regression test for issue #308: a brief
312// well past tmux's ~16KB command limit launches through the real tmux path,
313// reaches the worker byte for byte on stdin, and stays on disk as the audit copy.
314func TestLaunchLongPromptOverStdin(t *testing.T) {
315 for _, kind := range []string{"claude", "codex"} {
316 t.Run(kind, func(t *testing.T) {
317 t.Parallel()
318 h := NewHarness(t)
319 h.WriteStub(kind, h.claudeStubScript())
320
321 line := "Fix `ValidateToken()`; don't touch $(rm -rf ~) or ${HOME} or #{pane_id} — keep \"quotes\" and 'these'.\n"
322 prompt := strings.Repeat(line, 40*1024/len(line)+1)
323 promptPath := filepath.Join(h.E2EDir, "brief.md")
324 if err := os.WriteFile(promptPath, []byte(prompt), 0o644); err != nil {
325 t.Fatal(err)
326 }
327
328 res := h.RunKlaus("launch", "--backend", kind, "--prompt-file", promptPath)
329 if res.ExitCode != 0 {
330 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%.2000s", res.ExitCode, res.Stdout, res.Stderr)
331 }
332 ids := h.RunIDs()
333 if len(ids) != 1 {
334 t.Fatalf("expected 1 run, got %v", ids)
335 }
336 runID := ids[0]
337 st, err := h.ReadState(runID)
338 if err != nil || st.TmuxPane == nil {
339 t.Fatalf("state: %+v, %v", st, err)
340 }
341
342 h.WaitForClaudeStart(30 * time.Second)
343 if got := h.ClaudeStdin(); got != prompt {
344 t.Fatalf("worker stdin is %d bytes, want the %d-byte prompt verbatim", len(got), len(prompt))
345 }
346 if argv := h.ClaudeArgv(); strings.Contains(argv, "ValidateToken") {
347 t.Fatalf("prompt leaked into argv:\n%.500s", argv)
348 }
349
350 saved := filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "prompts", runID+".md")
351 info, err := os.Stat(saved)
352 if err != nil || info.Mode().Perm() != 0o600 {
353 t.Fatalf("prompt file %s: %v, %v", saved, info, err)
354 }
355
356 releaseBackendWorkers(t, h)
357 if data, err := os.ReadFile(saved); err != nil || string(data) != prompt {
358 t.Fatalf("audit copy of the prompt not kept after the run: %v", err)
359 }
360 })
361 }
362}
363
364// TestLaunchSizeGuard: when an inline part (here the worker system prompt,
365// which Codex takes as an argument) would push the pane command past tmux's
366// limit, launch fails up front with the sizes, before creating a worktree.
367// Claude reads the same system prompt from a file and launches fine.
368func TestLaunchSizeGuard(t *testing.T) {
369 t.Parallel()
370 h := NewHarness(t)
371 sysPrompt := strings.Repeat("Follow the house rules.\n", 13000/24+1)
372 if err := os.WriteFile(filepath.Join(h.RepoDir, ".klaus", "prompt.md"), []byte(sysPrompt), 0o644); err != nil {
373 t.Fatal(err)
374 }
375
376 res := h.RunKlaus("launch", "--backend", "codex", "small task")
377 if res.ExitCode == 0 {
378 t.Fatalf("launch should fail the size guard\nstdout:\n%s", res.Stdout)
379 }
380 delivery, err := config.RenderDelivery(config.PromptVars{DirectPush: true})
381 if err != nil {
382 t.Fatal(err)
383 }
384 wantSize := fmt.Sprintf("the worker system prompt is %d bytes", len(config.WithWorkerRules(strings.TrimRight(sysPrompt, "\n")+"\n\n"+delivery)))
385 for _, want := range []string{"over the 12000-byte limit", wantSize} {
386 if !strings.Contains(res.Stderr, want) {
387 t.Errorf("stderr missing %q:\n%s", want, res.Stderr)
388 }
389 }
390 if strings.Contains(res.Stderr, "cleaning up worktree") || strings.Contains(res.Stdout, "worktree:") {
391 t.Errorf("guard fired after the worktree was created:\n%s%s", res.Stdout, res.Stderr)
392 }
393 if entries, _ := os.ReadDir(filepath.Join(filepath.Dir(h.RepoDir), "worktrees")); len(entries) != 0 {
394 t.Errorf("worktree base should be empty, has %d entries", len(entries))
395 }
396 if ids := h.RunIDs(); len(ids) != 0 {
397 t.Errorf("no run should have been recorded, got %v", ids)
398 }
399
400 res = h.RunKlaus("launch", "small task")
401 if res.ExitCode != 0 {
402 t.Fatalf("claude launch exited %d\nstdout:\n%s\nstderr:\n%.2000s", res.ExitCode, res.Stdout, res.Stderr)
403 }
404 h.WaitForClaudeStart(30 * time.Second)
405 argv := strings.Split(h.ClaudeArgv(), "\n")
406 var sysFile string
407 for i, a := range argv {
408 if a == "--append-system-prompt-file" && i+1 < len(argv) {
409 sysFile = argv[i+1]
410 }
411 }
412 if data, err := os.ReadFile(sysFile); err != nil || !strings.Contains(string(data), sysPrompt) {
413 t.Fatalf("system prompt file %q not written: %v", sysFile, err)
414 }
415 h.ReleaseClaude()
416 h.WaitForState(h.RunIDs()[0], func(s *run.State) bool { return s.TmuxPane == nil && s.Worktree == "" }, 30*time.Second)
417}
418
419// TestLaunchDeliveryFollowsOrigin: launch reads the repo's origin to pick the
420// worker's delivery, and records it on the run. The harness origin is a local
421// bare repo, like a valley remote with no GitHub PRs, so the agent is told to
422// push its branch and report; a github.com origin keeps the PR workflow. The
423// GitHub case serves the github.com URL from the same bare repo
424// (UseGitHubOrigin), so launch's real fetch works offline.
425func TestLaunchDeliveryFollowsOrigin(t *testing.T) {
426 t.Parallel()
427 for _, tc := range []struct {
428 name string
429 github bool
430 wantPrompt []string
431 noPrompt []string
432 }{
433 {
434 name: "direct-push origin",
435 wantPrompt: []string{"Do not create a PR", "head SHA", "the operator reviews from your final report"},
436 noPrompt: []string{"Create a PR.", "--reviewer"},
437 },
438 {
439 name: "github origin",
440 github: true,
441 wantPrompt: []string{"6. Create a PR.", "Use --reviewer"},
442 noPrompt: []string{"Do not create a PR", "head SHA"},
443 },
444 } {
445 t.Run(tc.name, func(t *testing.T) {
446 t.Parallel()
447 h := NewHarness(t)
448 if tc.github {
449 h.UseGitHubOrigin()
450 }
451
452 res := h.RunKlaus("launch", "tidy the README")
453 if res.ExitCode != 0 {
454 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
455 }
456 if got := strings.Contains(res.Stdout, "delivery: push branch, no PR"); got == tc.github {
457 t.Errorf("delivery line printed = %v, want %v\nstdout:\n%s", got, !tc.github, res.Stdout)
458 }
459
460 h.WaitForClaudeStart(30 * time.Second)
461 sysPrompt := h.WorkerSystemPrompt()
462 for _, want := range append(tc.wantPrompt, "`git push -u origin HEAD`", "Never commit directly to the default branch") {
463 if !strings.Contains(sysPrompt, want) {
464 t.Errorf("system prompt missing %q:\n%s", want, sysPrompt)
465 }
466 }
467 for _, absent := range tc.noPrompt {
468 if strings.Contains(sysPrompt, absent) {
469 t.Errorf("system prompt should not contain %q:\n%s", absent, sysPrompt)
470 }
471 }
472
473 h.ReleaseClaude()
474 st := h.WaitForState(h.RunIDs()[0], func(s *run.State) bool { return s.TmuxPane == nil && s.Worktree == "" }, 30*time.Second)
475 // Launch records the delivery, which finalize then honours.
476 want := run.DeliveryPush
477 if tc.github {
478 want = run.DeliveryPR
479 }
480 if st.Delivery != want {
481 t.Errorf("recorded delivery = %q, want %q", st.Delivery, want)
482 }
483 })
484 }
485}