gunk-dev/the-valley

change_test.go

sourceccb7354855a5main's published tip history
18.9 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/run"
14)
15
16// changeSession is the Claude session the fake claude reports for every run.
17const changeSession = "11111111-2222-4333-8444-555555555555"
18
19// recordConversation makes the fake claude also write its conversation where
20// claude keeps it, ~/.claude/projects/<cwd, '/' and '.' as '-'>/<session>.jsonl,
21// so finalize stores it on the data ref for a later launch to replay.
22func (h *Harness) recordConversation() {
23 h.t.Helper()
24 h.WriteStub("claude", strings.Replace(h.claudeStubScript(), `cat "$dir/claude.output.jsonl"`,
25 `conv="$HOME/.claude/projects/$(printf '%s' "$PWD" | tr '/.' '--')"
26mkdir -p "$conv"
27printf '{"type":"user","sessionId":"`+changeSession+`","cwd":"%s","message":{"role":"user","content":"go"}}\n' "$PWD" > "$conv/`+changeSession+`.jsonl"
28cat "$dir/claude.output.jsonl"`, 1))
29}
30
31// resetWorker readies the fake worker for another launch, whatever its
32// backend: the claude, codex and agy stubs are all claudeStubScript, sharing
33// its files, so each blocks until released again and the record of the last
34// run is gone.
35func (h *Harness) resetWorker() {
36 for _, f := range []string{"claude.release", "claude.started", "claude.argv"} {
37 os.Remove(filepath.Join(h.E2EDir, f))
38 }
39}
40
41// launchRun runs klaus launch with args and returns the new run's state and
42// the launch's output, failing the test unless launch succeeds.
43func (h *Harness) launchRun(args ...string) (*run.State, RunResult) {
44 h.t.Helper()
45 known := make(map[string]bool)
46 for _, id := range h.RunIDs() {
47 known[id] = true
48 }
49 res := h.RunKlaus(append([]string{"launch"}, args...)...)
50 if res.ExitCode != 0 {
51 h.t.Fatalf("launch %v exited %d\nstdout:\n%s\nstderr:\n%s", args, res.ExitCode, res.Stdout, res.Stderr)
52 }
53 for _, id := range h.RunIDs() {
54 if !known[id] {
55 st, err := h.ReadState(id)
56 if err != nil {
57 h.t.Fatal(err)
58 }
59 return st, res
60 }
61 }
62 h.t.Fatalf("launch %v recorded no run\nstdout:\n%s", args, res.Stdout)
63 return nil, res
64}
65
66// pushWork commits a file in a run's worktree and pushes it as the worker
67// prompt says, `git push -u origin HEAD`, returning the pushed head.
68func (h *Harness) pushWork(st *run.State, file, subject string) string {
69 h.t.Helper()
70 if err := os.WriteFile(filepath.Join(st.Worktree, file), []byte(subject+"\n"), 0o644); err != nil {
71 h.t.Fatal(err)
72 }
73 h.git(st.Worktree, "add", "-A")
74 h.git(st.Worktree, "commit", "-qm", subject)
75 h.git(st.Worktree, "push", "-q", "-u", "origin", "HEAD")
76 return h.GitOutput(st.Worktree, "rev-parse", "HEAD")
77}
78
79// finishRun lets the fake worker end and waits for finalize to clean up, so
80// the test's temp dirs aren't removed under its push.
81func (h *Harness) finishRun(id string) *run.State {
82 h.t.Helper()
83 h.ReleaseClaude()
84 return h.WaitForState(id, func(s *run.State) bool {
85 return s.DurationMS != nil && s.TmuxPane == nil && s.Worktree == ""
86 }, 60*time.Second)
87}
88
89// TestChangeContinuesAChange drives three real launches on one valley
90// change, against a fake valley that can unready. The first run pushes v1
91// and finalize marks it ready and stores its conversation. A --change
92// <run-id> follow-up runs on the first run's branch at v1 with its change
93// ID, returns the change to draft, replays the first run's conversation, is
94// told it continues the change and to keep its head message true to the
95// whole change, and shares the change's dashboard row; it pushes to the same
96// branch and finalize readies the new head there. A --change <handle> --no-replay run resolves the handle through the
97// recorded runs, starts at the follow-up's head, and starts fresh. The
98// follow-ups target the repo by the name the valley gives it, widget: the
99// sandbox's own name is its origin's path.
100func TestChangeContinuesAChange(t *testing.T) {
101 t.Parallel()
102 h := NewHarness(t)
103 h.RegisterProject("acme/widget", h.RepoDir)
104 h.installValleyStub()
105 h.joinValley()
106 if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.has-unready"), nil, 0o644); err != nil {
107 t.Fatal(err)
108 }
109 h.recordConversation()
110 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n")
111
112 first, _ := h.launchRun("add a health check endpoint")
113 h.WaitForClaudeStart(30 * time.Second)
114 v1 := h.pushWork(first, "health.go", "Add a health check")
115 first = h.finishRun(first.ID)
116 if first.Valley == nil || first.Valley.Handle != "nxvp" || first.PushedSHA == nil || *first.PushedSHA != v1 {
117 t.Fatalf("the first run should have pushed v1 and marked it ready: valley %+v, pushed %v", first.Valley, first.PushedSHA)
118 }
119
120 // --change <run-id>.
121 h.resetWorker()
122 follow, res := h.launchRun("--repo", "widget", "--change", first.ID, "tidy the health check")
123 h.WaitForClaudeStart(30 * time.Second)
124 for _, want := range []string{
125 "Launching agent " + follow.ID + " (continuing change nxvp)...",
126 "branch: " + first.Branch + "\n",
127 "change: " + first.ChangeID + " (inherited from change nxvp)",
128 "valley: widget nxvp is a draft until the agent pushes",
129 "replay: resuming conversation from run " + first.ID,
130 } {
131 if !strings.Contains(res.Stdout, want) {
132 t.Errorf("launch output missing %q:\n%s", want, res.Stdout)
133 }
134 }
135 if follow.Branch != first.Branch || follow.ChangeID != first.ChangeID || follow.ChangeRepo != "widget" {
136 t.Errorf("follow-up on branch %q, change %q in %q; want %q, %q in widget",
137 follow.Branch, follow.ChangeID, follow.ChangeRepo, first.Branch, first.ChangeID)
138 }
139 if follow.OriginalRunID == nil || *follow.OriginalRunID != first.ID {
140 t.Errorf("follow-up should record the run it replays, %s: %v", first.ID, follow.OriginalRunID)
141 }
142 if follow.Unready == nil || *follow.Unready != (run.Unready{ChangeID: first.ChangeID, Repo: "widget", Handle: "nxvp"}) {
143 t.Errorf("follow-up unready = %+v, want the change back to draft", follow.Unready)
144 }
145 if _, err := os.Stat(filepath.Join(h.E2EDir, "valley.unready-late")); err == nil {
146 t.Error("valley unready ran after the agent started")
147 }
148 if head := h.GitOutput(follow.Worktree, "rev-parse", "HEAD"); head != v1 {
149 t.Errorf("follow-up worktree at %s, want v1 %s", head, v1)
150 }
151 if argv := h.ClaudeArgv(); !strings.Contains(argv, "--resume\n"+changeSession+"\n") {
152 t.Errorf("claude should resume the first run's conversation:\n%s", argv)
153 }
154 want := "You are continuing an existing change, nxvp. This worktree is on its branch, " + first.Branch + ", which already holds the earlier work."
155 if sys := h.WorkerSystemPrompt(); !strings.Contains(sys, want) || !strings.Contains(sys, "keep the head message accurate for the whole change") {
156 t.Errorf("worker prompt should say it continues the change on its branch:\n%s", sys)
157 }
158
159 // The follow-up runs on the change's row, as a fix agent runs on its PR's.
160 _, screen := h.startDashboard(170)
161 running := "agent:" + follow.ID[len(follow.ID)-4:] + " running"
162 s := screen("1 agents", running)
163 if row := rowOf(t, s, "nxvp"); !strings.Contains(row, running) {
164 t.Errorf("the follow-up should run on the change's row: %q\n%s", row, s)
165 }
166 if strings.Contains(s, "tidy the health check") {
167 t.Errorf("the follow-up should have no row of its own:\n%s", s)
168 }
169
170 // It pushes fast-forward to the change's branch; finalize readies the new head there.
171 worktree := follow.Worktree
172 v2 := h.pushWork(follow, "health_test.go", "Test the health check")
173 if tip := h.GitOutput(h.OriginDir, "rev-parse", "refs/heads/"+first.Branch); tip != v2 {
174 t.Errorf("origin's %s at %s, want the follow-up's %s", first.Branch, tip, v2)
175 }
176 h.git(h.OriginDir, "merge-base", "--is-ancestor", v1, v2)
177 follow = h.finishRun(follow.ID)
178 if follow.PushedBranch == nil || *follow.PushedBranch != first.Branch || follow.PushedSHA == nil || *follow.PushedSHA != v2 {
179 t.Errorf("follow-up pushed %v at %v, want %s at %s", follow.PushedBranch, follow.PushedSHA, first.Branch, v2)
180 }
181 ready := worktree + ": ready --change " + first.ChangeID + " --head " + v2 + " " + first.Branch
182 if calls := h.valleyCalls("ready"); len(calls) != 2 || calls[1] != ready {
183 t.Errorf("valley ready calls = %q, want the second to be %q", calls, ready)
184 }
185
186 // --change <handle> --no-replay.
187 h.resetWorker()
188 third, res := h.launchRun("--repo", "widget", "--change", "nxvp", "--no-replay", "rename the endpoint")
189 h.WaitForClaudeStart(30 * time.Second)
190 for _, want := range []string{
191 "change: " + first.ChangeID + " (inherited from change nxvp)",
192 "replay: fresh agent (--no-replay)",
193 } {
194 if !strings.Contains(res.Stdout, want) {
195 t.Errorf("launch output missing %q:\n%s", want, res.Stdout)
196 }
197 }
198 if third.Branch != first.Branch || third.ChangeID != first.ChangeID {
199 t.Errorf("third run on branch %q, change %q; want %q, %q", third.Branch, third.ChangeID, first.Branch, first.ChangeID)
200 }
201 if head := h.GitOutput(third.Worktree, "rev-parse", "HEAD"); head != v2 {
202 t.Errorf("third run's worktree at %s, want the follow-up's %s", head, v2)
203 }
204 if argv := h.ClaudeArgv(); strings.Contains(argv, "--resume") {
205 t.Errorf("--no-replay should start a fresh agent:\n%s", argv)
206 }
207 h.finishRun(third.ID)
208}
209
210// TestChangeResolvesThroughValley launches --change with a handle no run
211// records: the change was marked ready from another machine, so `valley
212// changes --json` names it, its active version's branch and head.
213func TestChangeResolvesThroughValley(t *testing.T) {
214 t.Parallel()
215 h := NewHarness(t)
216 h.installValleyStub()
217 h.joinValley()
218 sha := h.pushBranch("readied-elsewhere", "cache.txt")
219 changeID := "lmno" + strings.Repeat("k", 28)
220 v := version(1, sha, "Tune the cache", "not-landed")
221 v["branch"] = "readied-elsewhere"
222 h.writeValleyChanges(map[string]any{
223 "schema": "valley-changes/v1",
224 "host": "valley-host",
225 "repos": []any{map[string]any{"repo": "widget", "url": "git@valley-host:widget.git", "error": nil, "branches": []any{},
226 "changes": []any{map[string]any{"change_id": changeID, "handle": "lmno", "target": "main", "owner": "operator",
227 "state": "ready", "record": strings.Repeat("0", 40), "seq": 1, "active": 1,
228 "versions": []any{v}, "includes": []string{}}}}},
229 })
230 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n")
231
232 st, res := h.launchRun("--change", "lmno", "tune the cache further")
233 for _, want := range []string{
234 "branch: readied-elsewhere\n",
235 "change: " + changeID + " (inherited from change lmno)",
236 "replay: fresh agent (no prior run recorded for this change)",
237 } {
238 if !strings.Contains(res.Stdout, want) {
239 t.Errorf("launch output missing %q:\n%s", want, res.Stdout)
240 }
241 }
242 if st.ChangeID != changeID || st.ChangeRepo != "widget" {
243 t.Errorf("run's change %q in %q, want %q in widget", st.ChangeID, st.ChangeRepo, changeID)
244 }
245 if head := h.GitOutput(st.Worktree, "rev-parse", "HEAD"); head != sha {
246 t.Errorf("worktree at %s, want the active version's head %s", head, sha)
247 }
248 if calls := h.valleyCalls("changes"); len(calls) != 1 || !strings.HasSuffix(calls[0], ": changes --json") {
249 t.Errorf("valley changes calls = %q, want one for the current repo", calls)
250 }
251 h.WaitForClaudeStart(30 * time.Second)
252 h.finishRun(st.ID)
253}
254
255// TestChangeRefErrors launches --change against recorded runs where it must
256// refuse before any worktree exists: with --pr, with a handle that names two
257// changes, and for a change whose branch is gone from origin.
258func TestChangeRefErrors(t *testing.T) {
259 t.Parallel()
260 h := NewHarness(t)
261 // Launched as --repo widget, the runs' repo.
262 h.RegisterProject("acme/widget", h.RepoDir)
263 ago := func(m int) time.Time { return time.Now().Add(-time.Duration(m) * time.Minute) }
264 a := h.valleyRun("20261013-0900-0001", "add a health check", "nxvp", "Add a health check", 1,
265 h.pushBranch("agent/20261013-0900-0001", "a.txt"), ago(20))
266 b := h.valleyRun("20261013-0900-0002", "port the health check", "nxvq", "Port the health check", 1,
267 h.pushBranch("agent/20261013-0900-0002", "b.txt"), ago(10))
268 gone := h.valleyRun("20261013-0900-0003", "drop the shim", "rstu", "Drop the shim", 1, strings.Repeat("3", 40), ago(5))
269
270 for _, tc := range []struct {
271 name string
272 args []string
273 want []string
274 }{
275 {"with --pr", []string{"--pr", "7", "--change", "nxvp"}, []string{"--pr and --change are mutually exclusive"}},
276 {"an ambiguous handle", []string{"--change", "nxv"}, []string{`"nxv" names 2 changes in widget`,
277 a.ChangeID + " (nxvp), latest run " + a.ID + ": Add a health check",
278 b.ChangeID + " (nxvq), latest run " + b.ID + ": Port the health check"}},
279 {"a branch gone from origin", []string{"--change", gone.ID}, []string{
280 "change rstu's branch agent/20261013-0900-0003 is not on origin (last known head " + strings.Repeat("3", 40) + ")"}},
281 } {
282 t.Run(tc.name, func(t *testing.T) {
283 res := h.RunKlaus(append([]string{"launch", "--repo", "widget"}, append(tc.args, "continue")...)...)
284 if res.ExitCode == 0 {
285 t.Fatalf("launch should fail\nstdout:\n%s", res.Stdout)
286 }
287 for _, want := range tc.want {
288 if !strings.Contains(res.Stderr, want) {
289 t.Errorf("stderr missing %q:\n%s", want, res.Stderr)
290 }
291 }
292 })
293 }
294 if ids := h.RunIDs(); len(ids) != 3 {
295 t.Errorf("refused launches should record no run: %v", ids)
296 }
297 if entries, _ := os.ReadDir(filepath.Join(filepath.Dir(h.RepoDir), "worktrees")); len(entries) != 0 {
298 t.Errorf("refused launches should leave no worktree: %v", entries)
299 }
300}
301
302// TestContinuingYieldsToALiveRun: while a --change follow-up is still
303// running, another --change launch on the change and a --pr launch on its
304// branch refuse, naming it, and leave its uncommitted work alone. So does
305// --force-takeover, which never removes the worktree the live run has the
306// branch checked out in. Once the operator cleans that run up (klaus
307// cleanup --force), a --change launch continues the branch.
308func TestContinuingYieldsToALiveRun(t *testing.T) {
309 t.Parallel()
310 h := NewHarness(t)
311 h.RegisterProject("acme/widget", h.RepoDir)
312 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n")
313
314 first, _ := h.launchRun("--repo", "widget", "add a health check endpoint")
315 h.WaitForClaudeStart(30 * time.Second)
316 v1 := h.pushWork(first, "health.go", "Add a health check")
317 first = h.finishRun(first.ID)
318
319 h.resetWorker()
320 live, _ := h.launchRun("--repo", "widget", "--change", first.ID, "tidy the health check")
321 h.WaitForClaudeStart(30 * time.Second)
322 notes := filepath.Join(live.Worktree, "notes.txt")
323 if err := os.WriteFile(notes, []byte("half done\n"), 0o644); err != nil {
324 t.Fatal(err)
325 }
326 // gh answers for PR #4242, whose head is the change's branch.
327 h.WriteStub("gh", fmt.Sprintf(`#!/usr/bin/env bash
328case "$*" in
329 *headRefName*) echo %q ;;
330 *"--json url"*) echo https://github.com/acme/widget/pull/4242 ;;
331esac
332exit 0
333`, first.Branch))
334
335 for _, tc := range []struct {
336 name string
337 args []string
338 want string
339 }{
340 {"--change", []string{"--change", first.ID}, "--change: run " + live.ID + " is still working on change " + first.ChangeID},
341 {"--pr", []string{"--pr", "4242"}, "--pr: run " + live.ID + " is still working on branch " + first.Branch},
342 } {
343 t.Run(tc.name, func(t *testing.T) {
344 res := h.RunKlaus(append(append([]string{"launch", "--repo", "widget"}, tc.args...), "take it over")...)
345 if res.ExitCode == 0 {
346 t.Fatalf("launch should refuse\nstdout:\n%s", res.Stdout)
347 }
348 for _, want := range []string{tc.want, "klaus cleanup --force " + live.ID, "--force-takeover launches past it, but never removes a worktree"} {
349 if !strings.Contains(res.Stderr, want) {
350 t.Errorf("stderr missing %q:\n%s", want, res.Stderr)
351 }
352 }
353 })
354 }
355 if ids := h.RunIDs(); len(ids) != 2 {
356 t.Errorf("refused launches should record no run: %v", ids)
357 }
358 if _, err := os.Stat(notes); err != nil {
359 t.Errorf("the live run's uncommitted work should be untouched: %v", err)
360 }
361
362 res := h.RunKlaus("launch", "--repo", "widget", "--change", first.ID, "--force-takeover", "take it over")
363 want := "--change: branch " + first.Branch + " is checked out in run " + live.ID + "'s worktree " + live.Worktree +
364 " (with uncommitted changes); klaus never removes a worktree, even with --force-takeover: save that work, then clean that run up (klaus cleanup " + live.ID + ", with --force while its agent runs) and launch again"
365 if res.ExitCode == 0 || !strings.Contains(res.Stderr, want) {
366 t.Fatalf("--force-takeover should refuse, saying %q: exit %d\nstdout:\n%s\nstderr:\n%s", want, res.ExitCode, res.Stdout, res.Stderr)
367 }
368 if data, err := os.ReadFile(notes); err != nil || string(data) != "half done\n" {
369 t.Errorf("the live run's uncommitted work should be untouched: %q, %v", data, err)
370 }
371 if ids := h.RunIDs(); len(ids) != 2 {
372 t.Errorf("a refused takeover should record no run: %v", ids)
373 }
374
375 if res := h.RunKlaus("cleanup", "--force", live.ID); res.ExitCode != 0 {
376 t.Fatalf("klaus cleanup --force %s exited %d\n%s%s", live.ID, res.ExitCode, res.Stdout, res.Stderr)
377 }
378 h.resetWorker()
379 takeover, res := h.launchRun("--repo", "widget", "--change", first.ID, "take it over")
380 h.WaitForClaudeStart(30 * time.Second)
381 if !strings.Contains(res.Stdout, "branch: "+first.Branch+"\n") || takeover.ChangeID != first.ChangeID {
382 t.Errorf("takeover on branch %q, change %q; want %q, %q\n%s", takeover.Branch, takeover.ChangeID, first.Branch, first.ChangeID, res.Stdout)
383 }
384 if head := h.GitOutput(takeover.Worktree, "rev-parse", "HEAD"); head != v1 {
385 t.Errorf("takeover worktree at %s, want origin's %s", head, v1)
386 }
387 h.finishRun(takeover.ID)
388}
389
390// TestChangeResumeFromUnresumableStartsFresh: --change A --resume-from B,
391// where B's transcript is gone, starts a fresh agent on A's branch and says
392// so, rather than replaying A's stored conversation.
393func TestChangeResumeFromUnresumableStartsFresh(t *testing.T) {
394 t.Parallel()
395 h := NewHarness(t)
396 h.recordConversation()
397 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n")
398
399 a, _ := h.launchRun("add a health check endpoint")
400 h.WaitForClaudeStart(30 * time.Second)
401 h.pushWork(a, "health.go", "Add a health check")
402 a = h.finishRun(a.ID)
403
404 gone := filepath.Join(h.E2EDir, "gone.jsonl")
405 b := &run.State{ID: "20261013-0900-0b0b0b0b", Type: "launch", Prompt: "an earlier attempt", TargetRepo: a.TargetRepo,
406 Branch: "agent/20261013-0900-0b0b0b0b", LogFile: &gone, CreatedAt: time.Now().Add(-time.Hour).Format(time.RFC3339)}
407 h.SeedState(b)
408
409 h.resetWorker()
410 c, res := h.launchRun("--change", a.ID, "--resume-from", b.ID, "carry on")
411 h.WaitForClaudeStart(30 * time.Second)
412 if want := "replay: fresh agent (--resume-from " + b.ID + ": its conversation can't be resumed)"; !strings.Contains(res.Stdout, want) {
413 t.Errorf("launch output missing %q:\n%s", want, res.Stdout)
414 }
415 if argv := h.ClaudeArgv(); strings.Contains(argv, "--resume") {
416 t.Errorf("an unresumable --resume-from should start a fresh agent, not replay %s:\n%s", a.ID, argv)
417 }
418 if c.Branch != a.Branch || c.ChangeID != a.ChangeID {
419 t.Errorf("run on branch %q, change %q; want A's %q, %q", c.Branch, c.ChangeID, a.Branch, a.ChangeID)
420 }
421 h.finishRun(c.ID)
422}