| 1 | //go:build e2e |
| 2 | |
| 3 | package e2e |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "the-valley/flow/internal/git" |
| 18 | "the-valley/flow/internal/run" |
| 19 | ) |
| 20 | |
| 21 | // sessionLimitOutput is what the fake claude prints for a run that stops at |
| 22 | // the usage limit: a success result saying so, which finalize salvages as |
| 23 | // session_limit. |
| 24 | const sessionLimitOutput = `{"type":"result","subtype":"success","result":"You've hit your session limit · resets 4:20pm","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n" |
| 25 | |
| 26 | // pushToGitHubOrigin is pushWork for a repo whose origin is on GitHub |
| 27 | // (UseGitHubOrigin): git reaches it through the ssh stub, on the harness's |
| 28 | // PATH. |
| 29 | func (h *Harness) pushToGitHubOrigin(st *run.State, file, subject string) string { |
| 30 | h.t.Helper() |
| 31 | if err := os.WriteFile(filepath.Join(st.Worktree, file), []byte(subject+"\n"), 0o644); err != nil { |
| 32 | h.t.Fatal(err) |
| 33 | } |
| 34 | h.git(st.Worktree, "add", "-A") |
| 35 | h.git(st.Worktree, "commit", "-qm", subject) |
| 36 | cmd := exec.Command("git", "push", "-q", "-u", "origin", "HEAD") |
| 37 | cmd.Dir = st.Worktree |
| 38 | cmd.Env = append(os.Environ(), "PATH="+h.BinDir+":"+os.Getenv("PATH"), "HOME="+h.Home, |
| 39 | "GIT_CONFIG_GLOBAL="+filepath.Join(h.Home, ".gitconfig"), "GIT_CONFIG_NOSYSTEM=1") |
| 40 | if out, err := cmd.CombinedOutput(); err != nil { |
| 41 | h.t.Fatalf("git push: %v: %s", err, out) |
| 42 | } |
| 43 | return h.GitOutput(st.Worktree, "rev-parse", "HEAD") |
| 44 | } |
| 45 | |
| 46 | // stubGitHubPRs makes gh answer the REST query for the PRs whose head is a |
| 47 | // branch of acme/widget: prs maps a branch to the URL of the PR it heads, |
| 48 | // or to "down" for a query that fails; any other branch heads none. Every |
| 49 | // other gh call answers nothing, as the default stub does. |
| 50 | func (h *Harness) stubGitHubPRs(prs map[string]string) { |
| 51 | h.t.Helper() |
| 52 | var cases strings.Builder |
| 53 | for branch, pr := range prs { |
| 54 | head := url.QueryEscape("acme:" + branch) |
| 55 | if pr == "down" { |
| 56 | fmt.Fprintf(&cases, " *head=%s) echo 'HTTP 502: Bad Gateway' >&2; exit 1 ;;\n", head) |
| 57 | } else { |
| 58 | fmt.Fprintf(&cases, " *head=%s) echo '[{\"html_url\":\"%s\"}]' ;;\n", head, pr) |
| 59 | } |
| 60 | } |
| 61 | h.WriteStub("gh", fmt.Sprintf(`#!/usr/bin/env bash |
| 62 | dir=%q |
| 63 | { printf 'gh'; for a in "$@"; do printf ' %%q' "$a"; done; printf '\n'; } >> "$dir/gh.argv" |
| 64 | if [ "$1" = api ]; then |
| 65 | case "$2" in |
| 66 | %s repos/*/pulls\?*) echo '[]' ;; |
| 67 | esac |
| 68 | fi |
| 69 | exit 0 |
| 70 | `, h.E2EDir, cases.String())) |
| 71 | } |
| 72 | |
| 73 | // seedSalvaged seeds a finished run of change, in acme/widget, that stopped |
| 74 | // at the usage limit: finalize pushed branch at sha and marked it as |
| 75 | // needing attention. |
| 76 | func (h *Harness) seedSalvaged(id, branch, sha, change string) *run.State { |
| 77 | h.t.Helper() |
| 78 | clone, cost := h.RepoDir, 0.5 |
| 79 | st := &run.State{ |
| 80 | ID: id, Type: "launch", Prompt: "stopped at the limit", TargetRepo: strPtrE2E("acme/widget"), CloneDir: &clone, |
| 81 | Branch: branch, PushedBranch: &branch, PushedSHA: &sha, ChangeID: change, CostUSD: &cost, |
| 82 | NeedsAttention: strPtrE2E("session_limit; branch " + branch + " preserved (pushed)"), |
| 83 | CreatedAt: time.Now().Add(-time.Hour).Format(time.RFC3339), |
| 84 | } |
| 85 | h.SeedState(st) |
| 86 | return st |
| 87 | } |
| 88 | |
| 89 | // originBranches lists the branches on the sandbox's origin. |
| 90 | func (h *Harness) originBranches() []string { |
| 91 | h.t.Helper() |
| 92 | return strings.Fields(h.GitOutput(h.OriginDir, "for-each-ref", "--format=%(refname:short)", "refs/heads")) |
| 93 | } |
| 94 | |
| 95 | // TestResumeFromContinuesPushedBranch replays the incident of 2026-10-20 |
| 96 | // with real launches, in a repo whose origin is on GitHub. A run stops at |
| 97 | // the usage limit before opening its PR: finalize salvages its unfinished |
| 98 | // work, pushes the branch and marks the run as needing attention. A |
| 99 | // --resume-from follow-up continues that branch with the same change ID and |
| 100 | // is told to push fast-forward and open the PR from it; no other branch |
| 101 | // appears on origin. Once the follow-up opens the PR, klaus status shows the |
| 102 | // salvaged run superseded and names its change by the PR. |
| 103 | func TestResumeFromContinuesPushedBranch(t *testing.T) { |
| 104 | t.Parallel() |
| 105 | h := NewHarness(t) |
| 106 | h.UseGitHubOrigin() |
| 107 | h.stubGitHubPRs(nil) |
| 108 | h.recordConversation() |
| 109 | h.WriteDefaultClaudeOutput(sessionLimitOutput) |
| 110 | |
| 111 | first, _ := h.launchRun("add a health check endpoint") |
| 112 | h.WaitForClaudeStart(30 * time.Second) |
| 113 | h.pushToGitHubOrigin(first, "health.go", "Add a health check") |
| 114 | if err := os.WriteFile(filepath.Join(first.Worktree, "health_test.go"), []byte("cut off\n"), 0o644); err != nil { |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | first = h.finishRun(first.ID) |
| 118 | if first.NeedsAttention == nil || !strings.Contains(*first.NeedsAttention, "session_limit") || first.PRURL != nil { |
| 119 | t.Fatalf("the first run should be salvaged at the session limit, without a PR: attention %v, PR %v", first.NeedsAttention, first.PRURL) |
| 120 | } |
| 121 | if first.PushedBranch == nil || *first.PushedBranch != first.Branch || first.PushedSHA == nil { |
| 122 | t.Fatalf("finalize should record the salvaged branch on origin: %v at %v", first.PushedBranch, first.PushedSHA) |
| 123 | } |
| 124 | salvaged := *first.PushedSHA |
| 125 | if got := h.GitOutput(h.OriginDir, "show", salvaged+":health_test.go"); got != "cut off" { |
| 126 | t.Fatalf("origin's %s should hold the salvaged work, got %q", first.Branch, got) |
| 127 | } |
| 128 | |
| 129 | // The follow-up opens PR #4242 (defaultClaudeOutput). It is later by its |
| 130 | // creation time too. |
| 131 | waitNextSecond() |
| 132 | h.resetWorker() |
| 133 | h.WriteDefaultClaudeOutput(defaultClaudeOutput) |
| 134 | follow, res := h.launchRun("--resume-from", first.ID, "carry on") |
| 135 | h.WaitForClaudeStart(30 * time.Second) |
| 136 | for _, want := range []string{ |
| 137 | "Launching agent " + follow.ID + " (continuing change " + first.ChangeID + ")...", |
| 138 | "branch: " + first.Branch + "\n", |
| 139 | "resume: continuing the branch run " + first.ID + " pushed\n", |
| 140 | "change: " + first.ChangeID + " ", |
| 141 | "takes on: the work of " + first.ID + ", which needed attention\n", |
| 142 | "replay: resuming conversation from run " + first.ID + " (--resume-from)", |
| 143 | } { |
| 144 | if !strings.Contains(res.Stdout, want) { |
| 145 | t.Errorf("launch output missing %q:\n%s", want, res.Stdout) |
| 146 | } |
| 147 | } |
| 148 | if follow.Branch != first.Branch || follow.ChangeID != first.ChangeID || follow.DispatchReason != "resume" || |
| 149 | strings.Join(follow.TookOver, ",") != first.ID { |
| 150 | t.Errorf("follow-up on branch %q, change %q, reason %q, taking on %v; want %q, %q, resume, %s", |
| 151 | follow.Branch, follow.ChangeID, follow.DispatchReason, follow.TookOver, first.Branch, first.ChangeID, first.ID) |
| 152 | } |
| 153 | if calls := h.GHArgv(); !strings.Contains(calls, "gh api repos/acme/widget/pulls\\?state=all") { |
| 154 | t.Errorf("launch should ask GitHub for the branch's PRs before continuing it:\n%s", calls) |
| 155 | } |
| 156 | if head := h.GitOutput(follow.Worktree, "rev-parse", "HEAD"); head != salvaged { |
| 157 | t.Errorf("follow-up worktree at %s, want the salvaged head %s", head, salvaged) |
| 158 | } |
| 159 | if got, want := h.originBranches(), []string{first.Branch, "main"}; strings.Join(got, " ") != strings.Join(want, " ") { |
| 160 | t.Errorf("origin's branches = %v, want %v: no sibling branch", got, want) |
| 161 | } |
| 162 | if sys := h.WorkerSystemPrompt(); !strings.Contains(sys, "You are continuing an existing change, "+first.ChangeID+". This worktree is on its branch, "+first.Branch) || |
| 163 | !strings.Contains(sys, "push fast-forward to the same branch and open the PR from it") { |
| 164 | t.Errorf("worker prompt should say it continues the branch and opens the PR from it:\n%s", sys) |
| 165 | } |
| 166 | |
| 167 | // It pushes fast-forward and opens the PR. |
| 168 | v2 := h.pushToGitHubOrigin(follow, "health_test.go", "Test the health check") |
| 169 | h.git(h.OriginDir, "merge-base", "--is-ancestor", salvaged, v2) |
| 170 | follow = h.finishRun(follow.ID) |
| 171 | if follow.PRURL == nil || !strings.HasSuffix(*follow.PRURL, "/pull/4242") || follow.NeedsAttention != nil { |
| 172 | t.Fatalf("the follow-up should open PR #4242: PR %v, attention %v", follow.PRURL, follow.NeedsAttention) |
| 173 | } |
| 174 | |
| 175 | res = h.RunKlaus("status") |
| 176 | if res.ExitCode != 0 { |
| 177 | t.Fatalf("status exited %d; stderr: %s", res.ExitCode, res.Stderr) |
| 178 | } |
| 179 | if got := statusOf(t, res.Stdout, first.ID); got != "superseded" { |
| 180 | t.Errorf("the salvaged run's status = %q, want superseded\n%s", got, res.Stdout) |
| 181 | } |
| 182 | for _, id := range []string{first.ID, follow.ID} { |
| 183 | if got := changeColumn(t, res.Stdout, id); got != "#4242" { |
| 184 | t.Errorf("%s: CHANGE %q, want the change's PR #4242", id, got) |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | // TestResumeFromFallsBackToNewBranch: a --resume-from run gets a new branch, |
| 190 | // with the resumed run's change ID, and says why on its resume: line, when |
| 191 | // that run's branch is gone from origin, has diverged from its push, or its |
| 192 | // change went on in a PR. A run that pushed nothing gets a new branch |
| 193 | // without a word. |
| 194 | func TestResumeFromFallsBackToNewBranch(t *testing.T) { |
| 195 | t.Parallel() |
| 196 | h := NewHarness(t) |
| 197 | h.RegisterProject("acme/widget", h.RepoDir) |
| 198 | h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n") |
| 199 | ago := func(m int) string { return time.Now().Add(-time.Duration(m) * time.Minute).Format(time.RFC3339) } |
| 200 | clone := h.RepoDir |
| 201 | salvaged := func(id, branch, sha string, change byte) *run.State { |
| 202 | st := &run.State{ |
| 203 | ID: id, Type: "launch", Prompt: "stopped at the limit", TargetRepo: strPtrE2E("acme/widget"), CloneDir: &clone, |
| 204 | Branch: branch, PushedBranch: &branch, PushedSHA: &sha, ChangeID: strings.Repeat(string(change), 32), |
| 205 | NeedsAttention: strPtrE2E("session_limit; branch " + branch + " preserved (pushed)"), CreatedAt: ago(60), |
| 206 | } |
| 207 | h.SeedState(st) |
| 208 | return st |
| 209 | } |
| 210 | |
| 211 | gone := salvaged("20261020-1200-00000001", "agent/gone", strings.Repeat("1", 40), 'n') |
| 212 | diverged := salvaged("20261020-1200-00000002", "agent/diverged", h.pushBranch("agent/elsewhere", "e.txt"), 'o') |
| 213 | h.pushBranch("agent/diverged", "d.txt") |
| 214 | inPR := salvaged("20261020-1200-00000003", "agent/in-pr", h.pushBranch("agent/in-pr", "p.txt"), 'p') |
| 215 | h.SeedState(&run.State{ |
| 216 | ID: "20261020-1200-00000004", Type: "launch", Prompt: "opened the PR", TargetRepo: strPtrE2E("acme/widget"), |
| 217 | Branch: "agent/in-pr-r", ChangeID: inPR.ChangeID, PRURL: strPtrE2E("https://github.com/acme/widget/pull/335"), CreatedAt: ago(30), |
| 218 | }) |
| 219 | unpushed := &run.State{ |
| 220 | ID: "20261020-1200-00000005", Type: "launch", Prompt: "pushed nothing", TargetRepo: strPtrE2E("acme/widget"), |
| 221 | Branch: "agent/unpushed", ChangeID: strings.Repeat("u", 32), CreatedAt: ago(60), |
| 222 | } |
| 223 | h.SeedState(unpushed) |
| 224 | |
| 225 | for _, tc := range []struct { |
| 226 | prior *run.State |
| 227 | note string |
| 228 | }{ |
| 229 | {gone, "run " + gone.ID + "'s branch agent/gone is gone from origin"}, |
| 230 | {diverged, "origin's agent/diverged has diverged from run " + diverged.ID + "'s push " + (*diverged.PushedSHA)[:7]}, |
| 231 | {inPR, "its change went on in PR #335 (run 20261020-1200-00000004); --pr continues that branch"}, |
| 232 | {unpushed, ""}, |
| 233 | } { |
| 234 | t.Run(tc.prior.Branch, func(t *testing.T) { |
| 235 | h.resetWorker() |
| 236 | st, res := h.launchRun("--repo", "widget", "--resume-from", tc.prior.ID, "carry on") |
| 237 | h.WaitForClaudeStart(30 * time.Second) |
| 238 | if tc.note != "" && !strings.Contains(res.Stdout, "resume: new branch: "+tc.note+"\n") { |
| 239 | t.Errorf("launch output should say why the branch is new, %q:\n%s", tc.note, res.Stdout) |
| 240 | } |
| 241 | if tc.note == "" && strings.Contains(res.Stdout, "resume:") { |
| 242 | t.Errorf("a run that pushed nothing needs no resume: line:\n%s", res.Stdout) |
| 243 | } |
| 244 | if st.Branch == tc.prior.Branch || !strings.HasSuffix(st.Branch, runIDTail(st.ID)) || st.ChangeID != tc.prior.ChangeID { |
| 245 | t.Errorf("follow-up on branch %q, change %q; want a new branch and change %q", st.Branch, st.ChangeID, tc.prior.ChangeID) |
| 246 | } |
| 247 | if strings.Contains(res.Stdout, "(continuing change") { |
| 248 | t.Errorf("a new branch continues no change's branch:\n%s", res.Stdout) |
| 249 | } |
| 250 | h.finishRun(st.ID) |
| 251 | }) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // TestSupersededAttentionFoldsIntoPR runs the real dashboard, klaus status |
| 256 | // and klaus notifications over constructed run states: |
| 257 | // |
| 258 | // - a run salvaged at the usage limit and a run of its change that |
| 259 | // recorded taking its work on (TookOver) and opened PR #334: one row, |
| 260 | // without ATTN, and the salvaged run superseded; |
| 261 | // - the incident of 2026-10-20 as it happened: the successor recreated |
| 262 | // the work on a -r branch and recorded no handoff, and its PR #335 |
| 263 | // merged; the salvaged run still needs attention, on #335's row; |
| 264 | // - a salvaged run whose successor took its work on and then failed, |
| 265 | // its clock running behind so it reads as created first: the salvaged |
| 266 | // run is superseded and the attention is the successor's; |
| 267 | // - mixed delivery: PR #336 merged, then a run of its change pushed a |
| 268 | // branch without a PR, which waits on its own SUBMIT row; |
| 269 | // - a salvaged run nothing followed, which reads ATTN. |
| 270 | func TestSupersededAttentionFoldsIntoPR(t *testing.T) { |
| 271 | t.Parallel() |
| 272 | h := NewHarness(t) |
| 273 | h.WriteStub("gh", fmt.Sprintf(`#!/usr/bin/env bash |
| 274 | dir=%q |
| 275 | echo "$*" >> "$dir/gh.argv" |
| 276 | %s |
| 277 | ref="${@: -1}" |
| 278 | case "$*" in |
| 279 | *"--json state "*) case "${ref##*/}" in 334) echo OPEN ;; *) echo MERGED ;; esac ;; |
| 280 | "pr checks"*) printf 'build\tpending\t0\thttps://ci.invalid/1\n' ;; |
| 281 | *"--json mergeable "*) echo MERGEABLE ;; |
| 282 | esac |
| 283 | exit 0 |
| 284 | `, h.E2EDir, ghGraphQLAnswer(map[int]string{334: "OPEN", 335: "MERGED", 336: "MERGED"}, "PENDING"))) |
| 285 | ago := func(m int) string { return time.Now().Add(-time.Duration(m) * time.Minute).Format(time.RFC3339) } |
| 286 | cost := 3.5 |
| 287 | salvaged := func(id, branch, change string) *run.State { |
| 288 | st := &run.State{ |
| 289 | ID: id, Type: "launch", Prompt: "stopped at the limit: " + branch, TargetRepo: strPtrE2E("klaus"), |
| 290 | Branch: branch, PushedBranch: &branch, PushedSHA: strPtrE2E(strings.Repeat("a", 40)), ChangeID: change, |
| 291 | NeedsAttention: strPtrE2E("session_limit; branch " + branch + " preserved (pushed)"), CostUSD: &cost, CreatedAt: ago(50), |
| 292 | } |
| 293 | h.SeedState(st) |
| 294 | return st |
| 295 | } |
| 296 | opened := func(id string, prior *run.State, pr int, branch string, tookOver bool) *run.State { |
| 297 | st := &run.State{ |
| 298 | ID: id, Type: "launch", Prompt: "resume after the usage limit", TargetRepo: strPtrE2E("klaus"), |
| 299 | Branch: branch, ChangeID: prior.ChangeID, CostUSD: &cost, CreatedAt: ago(20), |
| 300 | PRURL: strPtrE2E(fmt.Sprintf("https://github.com/maintainer/klaus/pull/%d", pr)), OriginalRunID: &prior.ID, |
| 301 | } |
| 302 | if tookOver { |
| 303 | st.TookOver = []string{prior.ID} |
| 304 | } |
| 305 | h.SeedState(st) |
| 306 | return st |
| 307 | } |
| 308 | handedOff := salvaged("20261021-2300-0a0a0a0a", "continued-on-its-branch-0a0a0a0a", "kkkklllllmmmmmnnnnnooooopppppqqq") |
| 309 | openedA := opened("20261021-2310-0b0b0b0b", handedOff, 334, handedOff.Branch, true) |
| 310 | incident := salvaged("20261020-1217-9a50467d", "events-say-where-agent-time-goes-and-a-9a50467d", "ymzrntpopqlxywsukrvmqwsunnoqylvv") |
| 311 | openedB := opened("20261021-0050-24e5aa1e", incident, 335, incident.Branch+"-r", false) |
| 312 | failedFrom := salvaged("20261021-2320-0c0c0c0c", "taken-on-then-failed-0c0c0c0c", "rrrrsssssstttttuuuuuvvvvvwwwwwxx") |
| 313 | failed := &run.State{ |
| 314 | ID: "20261021-2330-0d0d0d0d", Type: "launch", Prompt: "took it on and crashed", TargetRepo: strPtrE2E("klaus"), |
| 315 | Branch: failedFrom.Branch, ChangeID: failedFrom.ChangeID, TookOver: []string{failedFrom.ID}, CostUSD: &cost, |
| 316 | FailureReason: strPtrE2E("error_during_execution"), CreatedAt: ago(90), // its clock ran behind |
| 317 | } |
| 318 | h.SeedState(failed) |
| 319 | mergedPR := &run.State{ |
| 320 | ID: "20261021-2340-0e0e0e0e", Type: "launch", Prompt: "opened 336", TargetRepo: strPtrE2E("klaus"), Branch: "mixed", |
| 321 | ChangeID: "xxxxyyyyyzzzzzkkkkklllllmmmmmnnn", CostUSD: &cost, CreatedAt: ago(40), |
| 322 | PRURL: strPtrE2E("https://github.com/maintainer/klaus/pull/336"), |
| 323 | } |
| 324 | h.SeedState(mergedPR) |
| 325 | pushedBranch, clone := "mixed-pushed", h.RepoDir |
| 326 | pushedSHA := h.pushBranch(pushedBranch, "mixed.txt") |
| 327 | pushedAfter := &run.State{ |
| 328 | ID: "20261021-2350-0f0f0f0f", Type: "launch", Prompt: "pushed after 336 merged", TargetRepo: strPtrE2E("klaus"), |
| 329 | Branch: pushedBranch, PushedBranch: &pushedBranch, PushedSHA: &pushedSHA, ChangeID: mergedPR.ChangeID, |
| 330 | CloneDir: &clone, CostUSD: &cost, CreatedAt: ago(10), |
| 331 | } |
| 332 | h.SeedState(pushedAfter) |
| 333 | lone := salvaged("20261020-1300-01010101", "nobody-followed-up-01010101", "qqqqrrrrssssttttuuuuvvvvwwwwxxxx") |
| 334 | |
| 335 | events := "" |
| 336 | for _, st := range []*run.State{handedOff, incident, failedFrom, failed, lone} { |
| 337 | line, err := json.Marshal(map[string]any{"timestamp": st.CreatedAt, "run_id": st.ID, "type": "agent:needs-attention", |
| 338 | "data": map[string]any{"id": st.ID, "branch": st.Branch, "reason": "session_limit"}}) |
| 339 | if err != nil { |
| 340 | t.Fatal(err) |
| 341 | } |
| 342 | events += string(line) + "\n" |
| 343 | } |
| 344 | if err := os.WriteFile(filepath.Join(filepath.Dir(h.RunsDir()), "events.jsonl"), []byte(events), 0o644); err != nil { |
| 345 | t.Fatal(err) |
| 346 | } |
| 347 | |
| 348 | _, screen := h.startDashboard(170) |
| 349 | s := screen("#334", "#335", "#336", "SUBMIT", "4 yours", "1 pipeline", "1 done") |
| 350 | rowsOf := func(sub string) []string { |
| 351 | var rows []string |
| 352 | for _, line := range strings.Split(s, "\n") { |
| 353 | if strings.Contains(line, sub) { |
| 354 | rows = append(rows, line) |
| 355 | } |
| 356 | } |
| 357 | return rows |
| 358 | } |
| 359 | if rows := rowsOf("#334 "); len(rows) != 1 || strings.Contains(rows[0], "ATTN") { |
| 360 | t.Errorf("#334 should be one row, without ATTN: %q\n%s", rows, s) |
| 361 | } |
| 362 | if rows := rowsOf("#335 "); len(rows) != 1 || !strings.Contains(rows[0], "MERGED") || !strings.Contains(rows[0], "ATTN") { |
| 363 | t.Errorf("#335 should be one row, MERGED with ATTN: its successor recorded no handoff: %q\n%s", rows, s) |
| 364 | } |
| 365 | if rows := rowsOf("#336 "); len(rows) != 1 || !strings.Contains(rows[0], "MERGED") || strings.Contains(rows[0], "SUBMIT") { |
| 366 | t.Errorf("#336 should be one MERGED row: %q\n%s", rows, s) |
| 367 | } |
| 368 | if line := lineContaining(s, mergedPR.ChangeID[:8]); !strings.Contains(line, "SUBMIT") || !strings.Contains(line, "pushed after 336 merged") { |
| 369 | t.Errorf("the push after #336 merged should wait on its change's own row: %q\n%s", line, s) |
| 370 | } |
| 371 | for _, st := range []*run.State{failedFrom, lone} { |
| 372 | if line := lineContaining(s, st.ChangeID[:8]); !strings.Contains(line, "ATTN") { |
| 373 | t.Errorf("change %s should read ATTN: %q\n%s", st.ChangeID[:8], line, s) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | res := h.RunKlaus("status") |
| 378 | if res.ExitCode != 0 { |
| 379 | t.Fatalf("status exited %d; stderr: %s", res.ExitCode, res.Stderr) |
| 380 | } |
| 381 | for _, tc := range []struct { |
| 382 | st *run.State |
| 383 | status, change string |
| 384 | }{ |
| 385 | {handedOff, "superseded", "#334"}, |
| 386 | {openedA, "pr-created", "#334"}, |
| 387 | {incident, "needs-attention", "#335"}, |
| 388 | {openedB, "merged", "#335"}, |
| 389 | {failedFrom, "superseded", failedFrom.ChangeID[:8]}, |
| 390 | {failed, "needs-attention", failedFrom.ChangeID[:8]}, |
| 391 | {mergedPR, "merged", "#336"}, |
| 392 | {pushedAfter, "awaiting-integration", "#336"}, |
| 393 | {lone, "needs-attention", lone.ChangeID[:8]}, |
| 394 | } { |
| 395 | if got := statusOf(t, res.Stdout, tc.st.ID); got != tc.status { |
| 396 | t.Errorf("%s: status %q, want %q", tc.st.ID, got, tc.status) |
| 397 | } |
| 398 | if got := changeColumn(t, res.Stdout, tc.st.ID); got != tc.change { |
| 399 | t.Errorf("%s: CHANGE %q, want %q", tc.st.ID, got, tc.change) |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | res = h.RunKlaus("notifications", "--all") |
| 404 | if res.ExitCode != 0 { |
| 405 | t.Fatalf("notifications exited %d; stderr: %s", res.ExitCode, res.Stderr) |
| 406 | } |
| 407 | want := "3 agent(s) need attention:\n 9a50467d — session_limit\n 0d0d0d0d — session_limit\n 01010101 — session_limit\n" |
| 408 | if !strings.Contains(res.Stdout, want) { |
| 409 | t.Errorf("notifications should list the runs still needing attention, %q:\n%s", want, res.Stdout) |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | // lineContaining returns the first line of s that contains sub. |
| 414 | func lineContaining(s, sub string) string { |
| 415 | for _, line := range strings.Split(s, "\n") { |
| 416 | if strings.Contains(line, sub) { |
| 417 | return line |
| 418 | } |
| 419 | } |
| 420 | return "" |
| 421 | } |
| 422 | |
| 423 | // TestResumeFromContinuesValleyChange: in a repo that delivers to a valley, |
| 424 | // a --resume-from follow-up of a run whose push the valley holds as its |
| 425 | // change's active version continues that branch as --change does: it |
| 426 | // returns the change to draft, pushes fast-forward, and finalize marks the |
| 427 | // new head ready on the same branch. Once the valley's active version is on |
| 428 | // another branch, a --resume-from of the first run gets a new branch and |
| 429 | // says the change moved on. |
| 430 | func TestResumeFromContinuesValleyChange(t *testing.T) { |
| 431 | t.Parallel() |
| 432 | h := NewHarness(t) |
| 433 | h.RegisterProject("acme/widget", h.RepoDir) |
| 434 | h.installValleyStub() |
| 435 | h.joinValley() |
| 436 | if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.has-unready"), nil, 0o644); err != nil { |
| 437 | t.Fatal(err) |
| 438 | } |
| 439 | h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n") |
| 440 | |
| 441 | first, _ := h.launchRun("add a health check endpoint") |
| 442 | h.WaitForClaudeStart(30 * time.Second) |
| 443 | v1 := h.pushWork(first, "health.go", "Add a health check") |
| 444 | first = h.finishRun(first.ID) |
| 445 | if first.Valley == nil || first.Valley.Handle != "nxvp" { |
| 446 | t.Fatalf("finalize should mark the first run's push ready: %+v", first.Valley) |
| 447 | } |
| 448 | writeListing := func(branch, head string) { |
| 449 | v := version(1, head, "Add a health check", "not-landed") |
| 450 | v["branch"] = branch |
| 451 | h.writeValleyChanges(map[string]any{ |
| 452 | "schema": "valley-changes/v1", |
| 453 | "host": "valley-host", |
| 454 | "repos": []any{map[string]any{"repo": "widget", "url": "git@valley-host:widget.git", "error": nil, "branches": []any{}, |
| 455 | "changes": []any{change(first, "ready", 1, v)}}}, |
| 456 | }) |
| 457 | } |
| 458 | writeListing(first.Branch, v1) |
| 459 | |
| 460 | h.resetWorker() |
| 461 | follow, res := h.launchRun("--repo", "widget", "--resume-from", first.ID, "tidy the health check") |
| 462 | h.WaitForClaudeStart(30 * time.Second) |
| 463 | for _, want := range []string{ |
| 464 | "Launching agent " + follow.ID + " (continuing change nxvp)...", |
| 465 | "branch: " + first.Branch + "\n", |
| 466 | "resume: continuing the branch run " + first.ID + " pushed\n", |
| 467 | "valley: widget nxvp is a draft until the agent pushes", |
| 468 | } { |
| 469 | if !strings.Contains(res.Stdout, want) { |
| 470 | t.Errorf("launch output missing %q:\n%s", want, res.Stdout) |
| 471 | } |
| 472 | } |
| 473 | if follow.Branch != first.Branch || follow.ChangeID != first.ChangeID || follow.ChangeRepo != "widget" { |
| 474 | t.Errorf("follow-up on branch %q, change %q in %q; want %q, %q in widget", |
| 475 | follow.Branch, follow.ChangeID, follow.ChangeRepo, first.Branch, first.ChangeID) |
| 476 | } |
| 477 | worktree := follow.Worktree |
| 478 | v2 := h.pushWork(follow, "health_test.go", "Test the health check") |
| 479 | follow = h.finishRun(follow.ID) |
| 480 | ready := worktree + ": ready --change " + first.ChangeID + " --head " + v2 + " " + first.Branch |
| 481 | if calls := h.valleyCalls("ready"); len(calls) != 2 || calls[1] != ready { |
| 482 | t.Errorf("valley ready calls = %q, want the second to be %q", calls, ready) |
| 483 | } |
| 484 | |
| 485 | // The change's active version moves to another branch. |
| 486 | h.resetWorker() |
| 487 | writeListing("readied-elsewhere", h.pushBranch("readied-elsewhere", "cache.txt")) |
| 488 | other, res := h.launchRun("--repo", "widget", "--resume-from", first.ID, "try again") |
| 489 | h.WaitForClaudeStart(30 * time.Second) |
| 490 | if want := "resume: new branch: change nxvp moved on to branch readied-elsewhere; --change continues it there\n"; !strings.Contains(res.Stdout, want) { |
| 491 | t.Errorf("launch output missing %q:\n%s", want, res.Stdout) |
| 492 | } |
| 493 | if other.Branch == first.Branch || other.ChangeID != first.ChangeID { |
| 494 | t.Errorf("run on branch %q, change %q; want a new branch and change %q", other.Branch, other.ChangeID, first.ChangeID) |
| 495 | } |
| 496 | h.finishRun(other.ID) |
| 497 | } |
| 498 | |
| 499 | // TestResumeFromFailedSuccessorCarriesAttention: with real launches in a |
| 500 | // repo without PRs, a run stops at the usage limit and a --resume-from run |
| 501 | // continues its branch, recording that it took the work on. The follow-up |
| 502 | // stops at the limit too, and finalize salvages it on the same branch. The |
| 503 | // attention moves to the follow-up: klaus status shows the first run |
| 504 | // superseded and the follow-up needing attention, the dashboard shows the |
| 505 | // change's one row ATTN, and notifications lists only the follow-up. |
| 506 | func TestResumeFromFailedSuccessorCarriesAttention(t *testing.T) { |
| 507 | t.Parallel() |
| 508 | h := NewHarness(t) |
| 509 | h.WriteDefaultClaudeOutput(sessionLimitOutput) |
| 510 | |
| 511 | first, _ := h.launchRun("add a health check endpoint") |
| 512 | h.WaitForClaudeStart(30 * time.Second) |
| 513 | h.pushWork(first, "health.go", "Add a health check") |
| 514 | first = h.finishRun(first.ID) |
| 515 | if first.NeedsAttention == nil || first.PushedSHA == nil { |
| 516 | t.Fatalf("the first run should be salvaged with its branch pushed: %+v", first) |
| 517 | } |
| 518 | |
| 519 | h.resetWorker() |
| 520 | follow, res := h.launchRun("--resume-from", first.ID, "carry on") |
| 521 | h.WaitForClaudeStart(30 * time.Second) |
| 522 | if follow.Branch != first.Branch || strings.Join(follow.TookOver, ",") != first.ID { |
| 523 | t.Fatalf("the follow-up should continue %s, taking on %s: branch %q, took over %v\n%s", |
| 524 | first.Branch, first.ID, follow.Branch, follow.TookOver, res.Stdout) |
| 525 | } |
| 526 | if err := os.WriteFile(filepath.Join(follow.Worktree, "health_test.go"), []byte("cut off again\n"), 0o644); err != nil { |
| 527 | t.Fatal(err) |
| 528 | } |
| 529 | follow = h.finishRun(follow.ID) |
| 530 | if follow.NeedsAttention == nil || !strings.Contains(*follow.NeedsAttention, "session_limit") { |
| 531 | t.Fatalf("the follow-up should be salvaged at the limit too: %v", follow.NeedsAttention) |
| 532 | } |
| 533 | h.git(h.OriginDir, "merge-base", "--is-ancestor", *first.PushedSHA, first.Branch) |
| 534 | |
| 535 | res = h.RunKlaus("status") |
| 536 | if res.ExitCode != 0 { |
| 537 | t.Fatalf("status exited %d; stderr: %s", res.ExitCode, res.Stderr) |
| 538 | } |
| 539 | if got := statusOf(t, res.Stdout, first.ID); got != "superseded" { |
| 540 | t.Errorf("the first run's status = %q, want superseded\n%s", got, res.Stdout) |
| 541 | } |
| 542 | if got := statusOf(t, res.Stdout, follow.ID); got != "needs-attention" { |
| 543 | t.Errorf("the follow-up's status = %q, want needs-attention: the attention is its now\n%s", got, res.Stdout) |
| 544 | } |
| 545 | |
| 546 | _, screen := h.startDashboard(170) |
| 547 | s := screen("ATTN", "1 yours") |
| 548 | if strings.Count(s, "ATTN") != 1 { |
| 549 | t.Errorf("the change should be one ATTN row:\n%s", s) |
| 550 | } |
| 551 | |
| 552 | res = h.RunKlaus("notifications", "--all") |
| 553 | if !strings.Contains(res.Stdout, "1 agent(s) need attention:\n "+runIDTail(follow.ID)+" — session_limit\n") { |
| 554 | t.Errorf("notifications should list only the follow-up:\n%s", res.Stdout) |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | // TestResumeFromChecksBranchOwnership: before a --resume-from run continues |
| 559 | // its run's branch on its own, launch checks the branch is still that |
| 560 | // change's. It gets a new branch, and says why, when GitHub has a PR whose |
| 561 | // head is the branch, when GitHub can't be asked, when a run of another |
| 562 | // change worked on the branch, when origin's tip carries another change's |
| 563 | // Change-Id, and when the run is in another owner's repo of the same name. |
| 564 | // A branch that passes every check is continued, though a run in another |
| 565 | // owner's repo of the same name used the same branch name. |
| 566 | func TestResumeFromChecksBranchOwnership(t *testing.T) { |
| 567 | t.Parallel() |
| 568 | h := NewHarness(t) |
| 569 | h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n") |
| 570 | other := strings.Repeat("z", 32) |
| 571 | push := map[string]string{} |
| 572 | for _, b := range []string{"agent/has-pr", "agent/gh-down", "agent/shared", "agent/bobs", "agent/clean"} { |
| 573 | push[b] = h.pushBranch(b, strings.ReplaceAll(b, "/", "-")+".txt") |
| 574 | } |
| 575 | // origin's tip carries another change's commit. |
| 576 | h.git(h.RepoDir, "checkout", "-q", "-b", "agent/foreign-tip", "origin/main") |
| 577 | if err := os.WriteFile(filepath.Join(h.RepoDir, "foreign.txt"), []byte("x\n"), 0o644); err != nil { |
| 578 | t.Fatal(err) |
| 579 | } |
| 580 | h.git(h.RepoDir, "add", "foreign.txt") |
| 581 | h.git(h.RepoDir, "commit", "-qm", "ours", "-m", "Change-Id: "+strings.Repeat("y", 32)) |
| 582 | h.git(h.RepoDir, "push", "-q", "origin", "agent/foreign-tip") |
| 583 | push["agent/foreign-tip"] = h.GitOutput(h.RepoDir, "rev-parse", "HEAD") |
| 584 | h.git(h.RepoDir, "checkout", "-q", "main") |
| 585 | h.git(h.RepoDir, "branch", "-q", "-D", "agent/foreign-tip") |
| 586 | |
| 587 | h.UseGitHubOrigin() |
| 588 | h.stubGitHubPRs(map[string]string{"agent/has-pr": "https://github.com/acme/widget/pull/77", "agent/gh-down": "down"}) |
| 589 | h.SeedState(&run.State{ID: "20261021-2200-00000009", Type: "launch", Prompt: "another change", TargetRepo: strPtrE2E("acme/widget"), |
| 590 | Branch: "agent/shared", ChangeID: other, CostUSD: strPtrFloat(0.5), CreatedAt: time.Now().Add(-2 * time.Hour).Format(time.RFC3339)}) |
| 591 | // The same branch name in another owner's widget is no claim on ours. |
| 592 | h.SeedState(&run.State{ID: "20261021-2200-00000008", Type: "launch", Prompt: "bob's change", TargetRepo: strPtrE2E("bob/widget"), |
| 593 | RepoKey: "bob/widget", Branch: "agent/clean", ChangeID: other, CostUSD: strPtrFloat(0.5), |
| 594 | CreatedAt: time.Now().Add(-2 * time.Hour).Format(time.RFC3339)}) |
| 595 | bobs := h.seedSalvaged("20261021-2200-00000005", "agent/bobs", push["agent/bobs"], strings.Repeat("o", 32)) |
| 596 | bobs.TargetRepo, bobs.RepoKey = strPtrE2E("bob/widget"), "bob/widget" |
| 597 | h.SeedState(bobs) |
| 598 | |
| 599 | for i, tc := range []struct { |
| 600 | branch, note string |
| 601 | }{ |
| 602 | {"agent/has-pr", "branch agent/has-pr has PR #77 on GitHub; --pr continues it"}, |
| 603 | {"agent/gh-down", "couldn't ask GitHub whether branch agent/gh-down has a PR: "}, |
| 604 | {"agent/shared", "branch agent/shared is also run 20261021-2200-00000009's, of another change"}, |
| 605 | {"agent/foreign-tip", "origin's agent/foreign-tip ends in a commit of another change, " + strings.Repeat("y", 32)}, |
| 606 | {"agent/bobs", "run 20261021-2200-00000005 is in bob's widget, not acme/widget"}, |
| 607 | {"agent/clean", ""}, |
| 608 | } { |
| 609 | t.Run(tc.branch, func(t *testing.T) { |
| 610 | prior := bobs |
| 611 | if tc.branch != "agent/bobs" { |
| 612 | prior = h.seedSalvaged(fmt.Sprintf("20261021-2200-0000001%d", i), tc.branch, push[tc.branch], strings.Repeat(string(rune('k'+i)), 32)) |
| 613 | } |
| 614 | h.resetWorker() |
| 615 | st, res := h.launchRun("--resume-from", prior.ID, "carry on") |
| 616 | h.WaitForClaudeStart(30 * time.Second) |
| 617 | if tc.note == "" { |
| 618 | if st.Branch != tc.branch || !strings.Contains(res.Stdout, "resume: continuing the branch run "+prior.ID+" pushed\n") { |
| 619 | t.Errorf("a branch that passes every check should be continued: on %q\n%s", st.Branch, res.Stdout) |
| 620 | } |
| 621 | } else { |
| 622 | if !strings.Contains(res.Stdout, "resume: new branch: "+tc.note) { |
| 623 | t.Errorf("launch output should say %q:\n%s", tc.note, res.Stdout) |
| 624 | } |
| 625 | if st.Branch == tc.branch || len(st.TookOver) != 0 { |
| 626 | t.Errorf("follow-up on %q, taking on %v; want a new branch, taking nothing on", st.Branch, st.TookOver) |
| 627 | } |
| 628 | } |
| 629 | h.finishRun(st.ID) |
| 630 | }) |
| 631 | } |
| 632 | if tip := h.GitOutput(h.OriginDir, "rev-parse", "refs/heads/agent/has-pr"); tip != push["agent/has-pr"] { |
| 633 | t.Errorf("a branch launch didn't continue should be untouched: %s, want %s", tip, push["agent/has-pr"]) |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | func strPtrFloat(f float64) *float64 { return &f } |
| 638 | |
| 639 | // gitBarrier holds one klaus process at a git call of the test's choosing, |
| 640 | // to force an interleaving: the git on the harness's PATH is a wrapper |
| 641 | // that runs the real one, and in a process started with the barrier's env |
| 642 | // (pause) it stops at the nth call whose arguments match a glob until the |
| 643 | // test releases it. Other processes run git straight through. |
| 644 | type gitBarrier struct { |
| 645 | t *testing.T |
| 646 | dir string |
| 647 | } |
| 648 | |
| 649 | // gitBarrier installs the wrapper and returns a new barrier. |
| 650 | func (h *Harness) gitBarrier() *gitBarrier { |
| 651 | h.t.Helper() |
| 652 | real, err := exec.LookPath("git") |
| 653 | if err != nil { |
| 654 | h.t.Fatal(err) |
| 655 | } |
| 656 | h.WriteStub("git", fmt.Sprintf(`#!/usr/bin/env bash |
| 657 | real=%q |
| 658 | pause() { |
| 659 | local dir=$E2E_GIT_BARRIER n |
| 660 | n=$(( $(cat "$dir/count" 2>/dev/null || echo 0) + 1 )) |
| 661 | echo "$n" > "$dir/count" |
| 662 | [ "$n" = "$E2E_GIT_PAUSE_NTH" ] || return 0 |
| 663 | : > "$dir/paused" |
| 664 | # klaus gives a local git call 30s. |
| 665 | for _ in $(seq 1 500); do [ -f "$dir/release" ] && return 0; sleep 0.05; done |
| 666 | } |
| 667 | if [ -n "$E2E_GIT_BARRIER" ] && [[ "$*" == $E2E_GIT_PAUSE ]]; then |
| 668 | if [ "$E2E_GIT_PAUSE_AFTER" = 1 ]; then |
| 669 | "$real" "$@"; rc=$?; pause; exit $rc |
| 670 | fi |
| 671 | pause |
| 672 | fi |
| 673 | exec "$real" "$@" |
| 674 | `, real)) |
| 675 | dir, err := os.MkdirTemp(h.E2EDir, "git-barrier-") |
| 676 | if err != nil { |
| 677 | h.t.Fatal(err) |
| 678 | } |
| 679 | return &gitBarrier{t: h.t, dir: dir} |
| 680 | } |
| 681 | |
| 682 | // pause is the environment that holds a process at the nth git call whose |
| 683 | // arguments ("$*") match glob, before the real git runs or, with after, |
| 684 | // once it has. |
| 685 | func (b *gitBarrier) pause(glob string, nth int, after bool) []string { |
| 686 | env := []string{"E2E_GIT_BARRIER=" + b.dir, "E2E_GIT_PAUSE=" + glob, fmt.Sprintf("E2E_GIT_PAUSE_NTH=%d", nth)} |
| 687 | if after { |
| 688 | env = append(env, "E2E_GIT_PAUSE_AFTER=1") |
| 689 | } |
| 690 | return env |
| 691 | } |
| 692 | |
| 693 | // waitPaused waits until p is held at the barrier, failing the test if p |
| 694 | // exits first. |
| 695 | func (b *gitBarrier) waitPaused(p *klausProcess) { |
| 696 | b.t.Helper() |
| 697 | p.waitFor(func() bool { |
| 698 | _, err := os.Stat(filepath.Join(b.dir, "paused")) |
| 699 | return err == nil |
| 700 | }, "to reach the git barrier") |
| 701 | } |
| 702 | |
| 703 | // release lets the held process go on. |
| 704 | func (b *gitBarrier) release() { |
| 705 | b.t.Helper() |
| 706 | if err := os.WriteFile(filepath.Join(b.dir, "release"), nil, 0o644); err != nil { |
| 707 | b.t.Fatal(err) |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | // klausProcess is a klaus invocation running in the background, writing |
| 712 | // its output to files. |
| 713 | type klausProcess struct { |
| 714 | t *testing.T |
| 715 | cmd *exec.Cmd |
| 716 | stdout, stderr string |
| 717 | done chan struct{} |
| 718 | err error |
| 719 | } |
| 720 | |
| 721 | // startKlaus starts the real klaus binary as RunKlaus runs it, with extra |
| 722 | // environment, and doesn't wait for it. |
| 723 | func (h *Harness) startKlaus(env []string, args ...string) *klausProcess { |
| 724 | h.t.Helper() |
| 725 | dir, err := os.MkdirTemp(h.E2EDir, "klaus-") |
| 726 | if err != nil { |
| 727 | h.t.Fatal(err) |
| 728 | } |
| 729 | p := &klausProcess{t: h.t, stdout: filepath.Join(dir, "stdout"), stderr: filepath.Join(dir, "stderr"), done: make(chan struct{})} |
| 730 | out, err := os.Create(p.stdout) |
| 731 | if err != nil { |
| 732 | h.t.Fatal(err) |
| 733 | } |
| 734 | errf, err := os.Create(p.stderr) |
| 735 | if err != nil { |
| 736 | h.t.Fatal(err) |
| 737 | } |
| 738 | p.cmd = exec.Command(klausBinary, args...) |
| 739 | p.cmd.Dir, p.cmd.Env, p.cmd.Stdout, p.cmd.Stderr = h.RepoDir, append(h.env(), env...), out, errf |
| 740 | if err := p.cmd.Start(); err != nil { |
| 741 | h.t.Fatalf("starting klaus %v: %v", args, err) |
| 742 | } |
| 743 | go func() { |
| 744 | p.err = p.cmd.Wait() |
| 745 | out.Close() |
| 746 | errf.Close() |
| 747 | close(p.done) |
| 748 | }() |
| 749 | h.t.Cleanup(func() { |
| 750 | p.cmd.Process.Kill() |
| 751 | <-p.done |
| 752 | }) |
| 753 | return p |
| 754 | } |
| 755 | |
| 756 | // output is what p has written to stdout and stderr so far. |
| 757 | func (p *klausProcess) output() (string, string) { |
| 758 | out, _ := os.ReadFile(p.stdout) |
| 759 | errOut, _ := os.ReadFile(p.stderr) |
| 760 | return string(out), string(errOut) |
| 761 | } |
| 762 | |
| 763 | // waitFor waits up to 30s until cond holds, failing the test if p exits |
| 764 | // first; what names what it waits for p to do. |
| 765 | func (p *klausProcess) waitFor(cond func() bool, what string) { |
| 766 | p.t.Helper() |
| 767 | deadline := time.Now().Add(30 * time.Second) |
| 768 | for !cond() { |
| 769 | select { |
| 770 | case <-p.done: |
| 771 | if cond() { |
| 772 | return |
| 773 | } |
| 774 | stdout, stderr := p.output() |
| 775 | p.t.Fatalf("klaus %v exited before %s\nstdout:\n%s\nstderr:\n%s", p.cmd.Args[1:], what, stdout, stderr) |
| 776 | case <-time.After(50 * time.Millisecond): |
| 777 | } |
| 778 | if time.Now().After(deadline) { |
| 779 | p.t.Fatalf("klaus %v didn't %s within 30s", p.cmd.Args[1:], what) |
| 780 | } |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | // wait waits for p to exit and returns its outcome. |
| 785 | func (p *klausProcess) wait() RunResult { |
| 786 | p.t.Helper() |
| 787 | <-p.done |
| 788 | stdout, stderr := p.output() |
| 789 | res := RunResult{Stdout: stdout, Stderr: stderr} |
| 790 | if ee, ok := p.err.(*exec.ExitError); ok { |
| 791 | res.ExitCode = ee.ExitCode() |
| 792 | } else if p.err != nil { |
| 793 | p.t.Fatalf("running klaus %v: %v", p.cmd.Args[1:], p.err) |
| 794 | } |
| 795 | return res |
| 796 | } |
| 797 | |
| 798 | // TestContinuingNeverTouchesOtherWork: a --resume-from run that would |
| 799 | // continue its run's branch refuses, as --change and --pr do, and leaves |
| 800 | // the work where it is, when the branch is checked out in a worktree with |
| 801 | // uncommitted changes, when the local branch has commits origin lacks, when |
| 802 | // a finished run's clean worktree still has it checked out, and, even with |
| 803 | // --force-takeover, when a worktree no run registered has it. Of two such |
| 804 | // launches on one branch, the second checks while the first is between its |
| 805 | // own check and its run's registration, its worktree created and work |
| 806 | // under way in it (held there by a git barrier): the second waits for the |
| 807 | // first to register, then refuses, naming it, and the first's worktree |
| 808 | // keeps its uncommitted work. |
| 809 | func TestContinuingNeverTouchesOtherWork(t *testing.T) { |
| 810 | t.Parallel() |
| 811 | h := NewHarness(t) |
| 812 | h.RegisterProject("acme/widget", h.RepoDir) |
| 813 | h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n") |
| 814 | cost := 0.5 |
| 815 | // worktree checks branch out at a new path outside the repo. |
| 816 | worktree := func(branch string) string { |
| 817 | path := filepath.Join(t.TempDir(), "wt") |
| 818 | h.git(h.RepoDir, "worktree", "add", "-q", "-B", branch, path, "origin/"+branch) |
| 819 | return path |
| 820 | } |
| 821 | prior := func(i int, branch string) *run.State { |
| 822 | return h.seedSalvaged(fmt.Sprintf("20261021-2200-0000002%d", i), branch, h.pushBranch(branch, fmt.Sprintf("f%d.txt", i)), |
| 823 | strings.Repeat(string(rune('k'+i)), 32)) |
| 824 | } |
| 825 | |
| 826 | dirty := prior(0, "agent/dirty") |
| 827 | dirtyWT := worktree("agent/dirty") |
| 828 | if err := os.WriteFile(filepath.Join(dirtyWT, "notes.txt"), []byte("half done\n"), 0o644); err != nil { |
| 829 | t.Fatal(err) |
| 830 | } |
| 831 | h.SeedState(&run.State{ID: "20261021-2200-00000030", Type: "launch", Prompt: "an earlier attempt", TargetRepo: strPtrE2E("acme/widget"), |
| 832 | Branch: "agent/dirty", ChangeID: dirty.ChangeID, Worktree: dirtyWT, CostUSD: &cost, CreatedAt: dirty.CreatedAt}) |
| 833 | |
| 834 | unpushed := prior(1, "agent/unpushed") |
| 835 | scratch := worktree("agent/unpushed") |
| 836 | h.git(scratch, "commit", "-q", "--allow-empty", "-m", "local only") |
| 837 | h.git(h.RepoDir, "worktree", "remove", scratch) |
| 838 | |
| 839 | occupied := prior(2, "agent/occupied") |
| 840 | occupiedWT := worktree("agent/occupied") |
| 841 | h.SeedState(&run.State{ID: "20261021-2200-00000032", Type: "launch", Prompt: "an earlier attempt", TargetRepo: strPtrE2E("acme/widget"), |
| 842 | Branch: "agent/occupied", ChangeID: occupied.ChangeID, Worktree: occupiedWT, CostUSD: &cost, CreatedAt: occupied.CreatedAt}) |
| 843 | |
| 844 | foreign := prior(3, "agent/foreign") |
| 845 | foreignWT := worktree("agent/foreign") |
| 846 | |
| 847 | for _, tc := range []struct { |
| 848 | name string |
| 849 | prior *run.State |
| 850 | force bool |
| 851 | want string |
| 852 | keep string |
| 853 | }{ |
| 854 | {"dirty worktree", dirty, false, "--resume-from: branch agent/dirty is checked out in run 20261021-2200-00000030's worktree " + dirtyWT + " (with uncommitted changes); klaus never removes a worktree, even with --force-takeover: save that work, then clean that run up (klaus cleanup 20261021-2200-00000030, with --force while its agent runs) and launch again", filepath.Join(dirtyWT, "notes.txt")}, |
| 855 | {"unpushed commits", unpushed, false, `--resume-from: creating worktree: local branch "agent/unpushed" has 1 commit(s) not on origin/agent/unpushed`, ""}, |
| 856 | {"a finished run's worktree", occupied, false, "--resume-from: branch agent/occupied is checked out in run 20261021-2200-00000032's worktree " + occupiedWT + "; klaus never removes a worktree, even with --force-takeover: clean that run up first (klaus cleanup 20261021-2200-00000032, with --force while its agent runs) and launch again", occupiedWT}, |
| 857 | {"a worktree no run registered", foreign, true, "--resume-from: branch agent/foreign is checked out in " + foreignWT + ", which no klaus run registered; klaus never removes it", foreignWT}, |
| 858 | } { |
| 859 | t.Run(tc.name, func(t *testing.T) { |
| 860 | args := []string{"launch", "--repo", "widget", "--resume-from", tc.prior.ID} |
| 861 | if tc.force { |
| 862 | args = append(args, "--force-takeover") |
| 863 | } |
| 864 | res := h.RunKlaus(append(args, "carry on")...) |
| 865 | if res.ExitCode == 0 { |
| 866 | t.Fatalf("launch should refuse\nstdout:\n%s", res.Stdout) |
| 867 | } |
| 868 | if !strings.Contains(res.Stderr, tc.want) { |
| 869 | t.Errorf("stderr should say %q:\n%s", tc.want, res.Stderr) |
| 870 | } |
| 871 | if tc.keep != "" { |
| 872 | if _, err := os.Stat(tc.keep); err != nil { |
| 873 | t.Errorf("%s should be untouched: %v", tc.keep, err) |
| 874 | } |
| 875 | } |
| 876 | }) |
| 877 | } |
| 878 | if got := h.GitOutput(h.RepoDir, "rev-list", "--count", "origin/agent/unpushed..agent/unpushed"); got != "1" { |
| 879 | t.Errorf("the unpushed commit should still be on the local branch: %s ahead", got) |
| 880 | } |
| 881 | |
| 882 | // Two launches on one branch: the first holds once its worktree |
| 883 | // exists, before its run is registered, and work starts in it; the |
| 884 | // second launches then. |
| 885 | contested := prior(4, "agent/contested") |
| 886 | before := len(h.RunIDs()) |
| 887 | barrier := h.gitBarrier() |
| 888 | first := h.startKlaus(barrier.pause("worktree add -B agent/contested *", 1, true), |
| 889 | "launch", "--repo", "widget", "--resume-from", contested.ID, "attempt 1") |
| 890 | barrier.waitPaused(first) |
| 891 | firstWT := git.BranchWorktree(context.Background(), h.RepoDir, "agent/contested") |
| 892 | if firstWT == "" { |
| 893 | t.Fatal("the first launch's worktree should have agent/contested checked out") |
| 894 | } |
| 895 | notes := filepath.Join(firstWT, "notes.txt") |
| 896 | if err := os.WriteFile(notes, []byte("half done\n"), 0o644); err != nil { |
| 897 | t.Fatal(err) |
| 898 | } |
| 899 | second := h.startKlaus(nil, "launch", "--repo", "widget", "--resume-from", contested.ID, "attempt 2") |
| 900 | second.waitFor(func() bool { |
| 901 | _, stderr := second.output() |
| 902 | return strings.Contains(stderr, "waiting for another launch continuing a branch in ") |
| 903 | }, "wait for the first launch") |
| 904 | barrier.release() |
| 905 | won, lost := first.wait(), second.wait() |
| 906 | if won.ExitCode != 0 || lost.ExitCode == 0 { |
| 907 | t.Fatalf("the first launch should start and the second refuse: exits %d and %d\nfirst:\n%s%s\nsecond:\n%s%s", |
| 908 | won.ExitCode, lost.ExitCode, won.Stdout, won.Stderr, lost.Stdout, lost.Stderr) |
| 909 | } |
| 910 | if ids := h.RunIDs(); len(ids) != before+1 { |
| 911 | t.Fatalf("one run should be recorded: %d new", len(ids)-before) |
| 912 | } |
| 913 | var winner *run.State |
| 914 | for _, id := range h.RunIDs() { |
| 915 | if st, _ := h.ReadState(id); st != nil && st.Branch == "agent/contested" && st.TmuxPane != nil { |
| 916 | winner = st |
| 917 | } |
| 918 | } |
| 919 | if winner == nil || winner.Worktree != firstWT { |
| 920 | t.Fatalf("the first launch's run should continue agent/contested in %s: %+v\n%s", firstWT, winner, won.Stdout) |
| 921 | } |
| 922 | if want := "--resume-from: run " + winner.ID + " is still working on"; !strings.Contains(lost.Stderr, want) { |
| 923 | t.Errorf("the second launch should refuse, naming %s: %q\n%s", winner.ID, want, lost.Stderr) |
| 924 | } |
| 925 | h.WaitForClaudeStart(30 * time.Second) |
| 926 | if data, err := os.ReadFile(notes); err != nil || string(data) != "half done\n" { |
| 927 | t.Errorf("the first run's uncommitted work should be intact: %q, %v", data, err) |
| 928 | } |
| 929 | if got := h.GitOutput(firstWT, "status", "--porcelain"); got != "?? notes.txt" { |
| 930 | t.Errorf("the first run's worktree should hold its work and nothing else: %q", got) |
| 931 | } |
| 932 | if got := h.GitOutput(firstWT, "rev-parse", "--abbrev-ref", "HEAD"); got != "agent/contested" { |
| 933 | t.Errorf("the first run's worktree should still be on agent/contested: %s", got) |
| 934 | } |
| 935 | os.Remove(notes) // so finalize has nothing to salvage |
| 936 | h.finishRun(winner.ID) |
| 937 | } |
| 938 | |
| 939 | // TestForcedTakeoverNeverRemovesAWorktree: --force-takeover refuses while |
| 940 | // a worktree has the branch checked out, with uncommitted work in it, and |
| 941 | // leaves it as it was: a finished run's worktree, and an ordinary checkout |
| 942 | // recreated at a run's registered path after that run's worktree was |
| 943 | // removed, which no check of the path could tell from the run's. The |
| 944 | // refusal names the run and the work, and no run is recorded. |
| 945 | func TestForcedTakeoverNeverRemovesAWorktree(t *testing.T) { |
| 946 | t.Parallel() |
| 947 | h := NewHarness(t) |
| 948 | h.RegisterProject("acme/widget", h.RepoDir) |
| 949 | cost := 0.5 |
| 950 | for i, tc := range []struct { |
| 951 | name string |
| 952 | recreate bool // the run's worktree is removed, and a checkout made at its path |
| 953 | }{ |
| 954 | {"a finished run's worktree", false}, |
| 955 | {"a checkout recreated at a run's path", true}, |
| 956 | } { |
| 957 | t.Run(tc.name, func(t *testing.T) { |
| 958 | branch := fmt.Sprintf("agent/forced-%d", i) |
| 959 | salvaged := h.seedSalvaged(fmt.Sprintf("20261021-2200-0000004%d", i), branch, h.pushBranch(branch, fmt.Sprintf("forced%d.txt", i)), |
| 960 | strings.Repeat(string(rune('k'+i)), 32)) |
| 961 | runWT := filepath.Join(t.TempDir(), "wt") |
| 962 | h.git(h.RepoDir, "worktree", "add", "-q", "-B", branch, runWT, "origin/"+branch) |
| 963 | holder := fmt.Sprintf("20261021-2200-0000005%d", i) |
| 964 | h.SeedState(&run.State{ID: holder, Type: "launch", Prompt: "an earlier attempt", TargetRepo: strPtrE2E("acme/widget"), |
| 965 | Branch: branch, ChangeID: salvaged.ChangeID, Worktree: runWT, CostUSD: &cost, CreatedAt: salvaged.CreatedAt}) |
| 966 | if tc.recreate { |
| 967 | h.git(h.RepoDir, "worktree", "remove", runWT) |
| 968 | h.git(h.RepoDir, "worktree", "add", "-q", runWT, branch) |
| 969 | } |
| 970 | notes := filepath.Join(runWT, "notes.txt") |
| 971 | if err := os.WriteFile(notes, []byte("half done\n"), 0o644); err != nil { |
| 972 | t.Fatal(err) |
| 973 | } |
| 974 | before := len(h.RunIDs()) |
| 975 | |
| 976 | res := h.RunKlaus("launch", "--repo", "widget", "--resume-from", salvaged.ID, "--force-takeover", "take it over") |
| 977 | if res.ExitCode == 0 { |
| 978 | t.Fatalf("launch should refuse\nstdout:\n%s", res.Stdout) |
| 979 | } |
| 980 | want := "--resume-from: branch " + branch + " is checked out in run " + holder + "'s worktree " + runWT + |
| 981 | " (with uncommitted changes); klaus never removes a worktree, even with --force-takeover: save that work, then clean that run up (klaus cleanup " + holder |
| 982 | if !strings.Contains(res.Stderr, want) { |
| 983 | t.Errorf("stderr should say %q:\n%s", want, res.Stderr) |
| 984 | } |
| 985 | if data, err := os.ReadFile(notes); err != nil || string(data) != "half done\n" { |
| 986 | t.Errorf("the uncommitted work should be intact: %q, %v", data, err) |
| 987 | } |
| 988 | if got := h.GitOutput(runWT, "status", "--porcelain"); got != "?? notes.txt" { |
| 989 | t.Errorf("the worktree should hold its work and nothing else: %q", got) |
| 990 | } |
| 991 | if got := h.GitOutput(runWT, "rev-parse", "--abbrev-ref", "HEAD"); got != branch { |
| 992 | t.Errorf("the worktree should still be on %s: %s", branch, got) |
| 993 | } |
| 994 | if ids := h.RunIDs(); len(ids) != before { |
| 995 | t.Errorf("a refused launch should record no run: %d new", len(ids)-before) |
| 996 | } |
| 997 | }) |
| 998 | } |
| 999 | } |