gunk-dev/the-valley

change_test.go

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