| 1 | //go:build e2e |
| 2 | |
| 3 | package e2e |
| 4 | |
| 5 | import ( |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os/exec" |
| 9 | "regexp" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "the-valley/flow/internal/event" |
| 15 | "the-valley/flow/internal/report" |
| 16 | "the-valley/flow/internal/run" |
| 17 | ) |
| 18 | |
| 19 | // TestEventsSayWhereAgentTimeGoes launches a run whose agent runs go test and |
| 20 | // opens PR 12, then a CI fix on that PR as the pipeline launches one (--pr 12 |
| 21 | // --reason ci-fix), and lets both finalize. Every event of both runs carries |
| 22 | // the repo-qualified keys, the head SHA and the dispatch reason; each run's |
| 23 | // phases and the test run in its stream are events, in order; and klaus |
| 24 | // report time sums the two runs as one change with a ci-fix follow-up. |
| 25 | func TestEventsSayWhereAgentTimeGoes(t *testing.T) { |
| 26 | t.Parallel() |
| 27 | h := NewHarness(t) |
| 28 | h.WriteStub("gh", reviewerGHStub(h, false)) |
| 29 | h.git(h.RepoDir, "push", "-q", "origin", "main:refs/heads/fix-branch") |
| 30 | h.UseGitHubOrigin() |
| 31 | const prURL = "https://github.com/acme/widget/pull/12" |
| 32 | h.WriteDefaultClaudeOutput(`{"type":"system","subtype":"init","model":"claude-e2e"} |
| 33 | {"type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"go test ./..."}}]}} |
| 34 | {"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","is_error":false,"content":"ok"}]}} |
| 35 | {"type":"assistant","message":{"content":[{"type":"text","text":"Opened PR: ` + prURL + `"}]}} |
| 36 | {"type":"result","subtype":"success","total_cost_usd":0.25,"duration_ms":4242,"session_id":"11111111-2222-4333-8444-555555555555"} |
| 37 | `) |
| 38 | |
| 39 | first, _ := h.launchRun("# Add a health check\n\nAdd a /healthz endpoint.") |
| 40 | h.WaitForClaudeStart(30 * time.Second) |
| 41 | first = h.finishRun(first.ID) |
| 42 | if first.PRURL == nil || *first.PRURL != prURL || first.DispatchReason != event.DispatchLaunch || first.RepoKey != "acme/widget" { |
| 43 | t.Fatalf("first run: PR %v, reason %q, repo key %q; want %s, launch, acme/widget", first.PRURL, first.DispatchReason, first.RepoKey, prURL) |
| 44 | } |
| 45 | |
| 46 | h.resetWorker() |
| 47 | fix, _ := h.launchRun("--pr", "12", "--reason", "ci-fix", "CI is failing on PR #12.") |
| 48 | h.WaitForClaudeStart(30 * time.Second) |
| 49 | fix = h.finishRun(fix.ID) |
| 50 | if fix.ChangeID != first.ChangeID || fix.DispatchReason != event.DispatchCIFix { |
| 51 | t.Fatalf("fix run: change %q, reason %q; want %q, ci-fix", fix.ChangeID, fix.DispatchReason, first.ChangeID) |
| 52 | } |
| 53 | |
| 54 | sha := regexp.MustCompile(`^[0-9a-f]{40}$`) |
| 55 | wantSequence := "agent:started phase:completed/setup phase:started/agent check:started check:completed " + |
| 56 | "phase:completed/agent phase:started/finalize agent:completed agent:pr-created phase:completed/finalize" |
| 57 | for _, tc := range []struct { |
| 58 | id, reason string |
| 59 | keys []string // the key each event carries, in order: the change until the run knows its PR |
| 60 | }{ |
| 61 | {first.ID, "launch", []string{"acme/widget@" + first.ChangeID, "acme/widget#12"}}, |
| 62 | {fix.ID, "ci-fix", []string{"acme/widget#12"}}, |
| 63 | } { |
| 64 | evts := h.runEvents(tc.id) |
| 65 | var seq []string |
| 66 | for _, e := range evts { |
| 67 | s := e.Type |
| 68 | if p, ok := e.Data["phase"].(string); ok { |
| 69 | s += "/" + p |
| 70 | } |
| 71 | seq = append(seq, s) |
| 72 | } |
| 73 | if got := strings.Join(seq, " "); got != wantSequence { |
| 74 | t.Errorf("run %s events:\n %s\nwant:\n %s", tc.id, got, wantSequence) |
| 75 | } |
| 76 | keyAt := 0 |
| 77 | for _, e := range evts { |
| 78 | d := e.Data |
| 79 | if d["repo_key"] != "acme/widget" || d["change_id"] != first.ChangeID || d["dispatch_reason"] != tc.reason { |
| 80 | t.Errorf("run %s %s: repo_key %v, change_id %v, dispatch_reason %v", tc.id, e.Type, d["repo_key"], d["change_id"], d["dispatch_reason"]) |
| 81 | } |
| 82 | if head, _ := d["head_sha"].(string); !sha.MatchString(head) { |
| 83 | t.Errorf("run %s %s: head_sha %v", tc.id, e.Type, d["head_sha"]) |
| 84 | } |
| 85 | if d["key"] != tc.keys[keyAt] && keyAt+1 < len(tc.keys) && d["key"] == tc.keys[keyAt+1] { |
| 86 | keyAt++ |
| 87 | } |
| 88 | if d["key"] != tc.keys[keyAt] { |
| 89 | t.Errorf("run %s %s: key %v, want %s", tc.id, e.Type, d["key"], tc.keys[keyAt]) |
| 90 | } |
| 91 | if e.Type == event.PhaseCompleted || e.Type == event.CheckCompleted { |
| 92 | if ms, ok := d["duration_ms"].(float64); !ok || ms < 0 { |
| 93 | t.Errorf("run %s %s: duration_ms %v", tc.id, e.Type, d["duration_ms"]) |
| 94 | } |
| 95 | } |
| 96 | if e.Type == event.CheckCompleted && (d["kind"] != "test" || d["command"] != "go test ./..." || d["success"] != true) { |
| 97 | t.Errorf("run %s check:completed %+v", tc.id, d) |
| 98 | } |
| 99 | } |
| 100 | if keyAt != len(tc.keys)-1 { |
| 101 | t.Errorf("run %s: its events never carried key %s", tc.id, tc.keys[len(tc.keys)-1]) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | res := h.RunKlaus("report", "time", "--current", "--json") |
| 106 | if res.ExitCode != 0 { |
| 107 | t.Fatalf("report time exited %d: %s", res.ExitCode, res.Stderr) |
| 108 | } |
| 109 | var rep report.Report |
| 110 | if err := json.Unmarshal([]byte(res.Stdout), &rep); err != nil { |
| 111 | t.Fatalf("report JSON: %v\n%s", err, res.Stdout) |
| 112 | } |
| 113 | o := rep.Overall |
| 114 | if o.Runs != 2 || o.Changes != 1 || o.FollowUps != 1 || o.FollowUpReasons["ci-fix"] != 1 || |
| 115 | o.Reasons["launch"] != 1 || o.Reasons["ci-fix"] != 1 || o.Unfinished != 0 || o.Untimed != 0 { |
| 116 | t.Errorf("report overall %+v", o) |
| 117 | } |
| 118 | if c := o.Checks["test"]; c == nil || c.Count != 2 || c.Failed != 0 { |
| 119 | t.Errorf("report test checks %+v", c) |
| 120 | } |
| 121 | if o.AgentMS <= 0 || o.CostRuns != 2 || fmt.Sprintf("%.2f", o.CostUSD) != "0.50" { |
| 122 | t.Errorf("report agent %dms, cost $%v over %d runs", o.AgentMS, o.CostUSD, o.CostRuns) |
| 123 | } |
| 124 | if len(rep.Repos) != 1 || rep.Repos[0].Repo != "acme/widget" || len(rep.Changes) != 1 || rep.Changes[0].Key != "acme/widget#12" { |
| 125 | t.Errorf("report repos %+v, changes %+v", rep.Repos, rep.Changes) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | // TestStreamChecksOutlastUnsavedState runs the real _format-stream as an |
| 130 | // agent's pane does (KLAUS_RUN_ID set) on a stream that runs go test and |
| 131 | // ends before launch has saved the run's state, as a fast agent's can. For |
| 132 | // one run launch saves the state soon after, and its check events carry the |
| 133 | // run's fields; for the other it never does, and its check events still land |
| 134 | // in the session's event log under the run's ID, where klaus report time |
| 135 | // counts them. |
| 136 | func TestStreamChecksOutlastUnsavedState(t *testing.T) { |
| 137 | t.Parallel() |
| 138 | h := NewHarness(t) |
| 139 | const agentStream = `{"type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"go test ./..."}}]}} |
| 140 | {"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","is_error":false,"content":"ok"}]}} |
| 141 | ` |
| 142 | formatStream := func(id string) *exec.Cmd { |
| 143 | cmd := exec.Command(klausBinary, "_format-stream") |
| 144 | cmd.Dir = h.RepoDir |
| 145 | cmd.Env = append(h.env(), "KLAUS_RUN_ID="+id) |
| 146 | cmd.Stdin = strings.NewReader(agentStream) |
| 147 | if err := cmd.Start(); err != nil { |
| 148 | t.Fatalf("starting _format-stream: %v", err) |
| 149 | } |
| 150 | return cmd |
| 151 | } |
| 152 | |
| 153 | const savedLate, neverSaved = "20261021-0100-5a7ed1a7", "20261021-0100-0e7e5a7e" |
| 154 | late, never := formatStream(savedLate), formatStream(neverSaved) |
| 155 | time.Sleep(500 * time.Millisecond) // both streams have ended by now |
| 156 | h.SeedState(&run.State{ |
| 157 | ID: savedLate, |
| 158 | CreatedAt: time.Now().Format(time.RFC3339), |
| 159 | RepoKey: "acme/widget", |
| 160 | ChangeID: "Ifeedface", |
| 161 | DispatchReason: event.DispatchLaunch, |
| 162 | }) |
| 163 | for _, cmd := range []*exec.Cmd{late, never} { |
| 164 | if err := cmd.Wait(); err != nil { |
| 165 | t.Fatalf("_format-stream: %v", err) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | for _, tc := range []struct { |
| 170 | id string |
| 171 | repoKey interface{} // nil: the run's state never existed |
| 172 | }{ |
| 173 | {savedLate, "acme/widget"}, |
| 174 | {neverSaved, nil}, |
| 175 | } { |
| 176 | evts := h.runEvents(tc.id) |
| 177 | var types []string |
| 178 | for _, e := range evts { |
| 179 | types = append(types, e.Type) |
| 180 | if e.Data["kind"] != event.CheckTest || e.Data["command"] != "go test ./..." || e.Data["repo_key"] != tc.repoKey { |
| 181 | t.Errorf("run %s %s: %+v", tc.id, e.Type, e.Data) |
| 182 | } |
| 183 | if e.Type == event.CheckCompleted && e.Data["success"] != true { |
| 184 | t.Errorf("run %s check:completed: success %v", tc.id, e.Data["success"]) |
| 185 | } |
| 186 | } |
| 187 | if got, want := strings.Join(types, " "), "check:started check:completed"; got != want { |
| 188 | t.Errorf("run %s events: %q, want %q", tc.id, got, want) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | res := h.RunKlaus("report", "time", "--current", "--json") |
| 193 | if res.ExitCode != 0 { |
| 194 | t.Fatalf("report time exited %d: %s", res.ExitCode, res.Stderr) |
| 195 | } |
| 196 | var rep report.Report |
| 197 | if err := json.Unmarshal([]byte(res.Stdout), &rep); err != nil { |
| 198 | t.Fatalf("report JSON: %v\n%s", err, res.Stdout) |
| 199 | } |
| 200 | if c := rep.Overall.Checks["test"]; c == nil || c.Count != 2 || c.Failed != 0 { |
| 201 | t.Errorf("report test checks %+v", c) |
| 202 | } |
| 203 | } |