| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "the-valley/flow/internal/event" |
| 13 | "the-valley/flow/internal/report" |
| 14 | ) |
| 15 | |
| 16 | // reportFixture writes two sessions' event logs under home and returns the |
| 17 | // second session's ID. Times are relative to now, so --since windows hold. |
| 18 | // |
| 19 | // Session A, new events: run r1 opens acme/widget PR 7 on change c1 (setup |
| 20 | // 30s, agent 1h with a test and a failing _pre-review, finalize 20s, $2.50); |
| 21 | // the pipeline's ci-fix run r2 starts 2h after r1 ends (setup 10s, agent |
| 22 | // 30m, finalize 10s, $1); the pipeline approves PR 7 29m40s after r2 ends. |
| 23 | // A review of PR 7 and two consults, one in acme/widget's checkout. Run r6 |
| 24 | // is 10 days old. |
| 25 | // |
| 26 | // Session B: old runs r3 and r4 on PR 9, events without repo_key, change_id, |
| 27 | // dispatch_reason or phases (an hour of agent time, then 30m 9h later), and |
| 28 | // a docs-timer run r5 on a valley that hasn't finished. |
| 29 | func reportFixture(t *testing.T, home string) string { |
| 30 | t.Helper() |
| 31 | now := time.Now().UTC().Truncate(time.Second) |
| 32 | at := func(d time.Duration) time.Time { return now.Add(-d) } |
| 33 | type ev struct { |
| 34 | at time.Time |
| 35 | run string |
| 36 | typ string |
| 37 | data map[string]interface{} |
| 38 | } |
| 39 | nano := func(t time.Time) string { return t.Format(time.RFC3339Nano) } |
| 40 | phase := func(run, name string, start time.Time, d time.Duration, extra map[string]interface{}) ev { |
| 41 | data := map[string]interface{}{"phase": name, "started_at": nano(start), "ended_at": nano(start.Add(d)), "duration_ms": d.Milliseconds()} |
| 42 | for k, v := range extra { |
| 43 | data[k] = v |
| 44 | } |
| 45 | return ev{start.Add(d), run, event.PhaseCompleted, data} |
| 46 | } |
| 47 | keys := func(reason, repo, change, pr string, extra map[string]interface{}) map[string]interface{} { |
| 48 | data := map[string]interface{}{"dispatch_reason": reason, "repo_key": repo, "change_id": change} |
| 49 | if pr != "" { |
| 50 | data["pr_number"], data["key"] = pr, repo+"#"+pr |
| 51 | } else { |
| 52 | data["key"] = repo + "@" + change |
| 53 | } |
| 54 | for k, v := range extra { |
| 55 | data[k] = v |
| 56 | } |
| 57 | return data |
| 58 | } |
| 59 | |
| 60 | r1Setup := at(50 * time.Hour) |
| 61 | r1Agent := r1Setup.Add(30 * time.Second) |
| 62 | r1End := r1Agent.Add(time.Hour) |
| 63 | r2Setup := r1End.Add(20 * time.Second).Add(2 * time.Hour) |
| 64 | r2Agent := r2Setup.Add(10 * time.Second) |
| 65 | r2End := r2Agent.Add(30 * time.Minute) |
| 66 | r6Setup := at(240 * time.Hour) |
| 67 | r5Setup := at(2 * time.Hour) |
| 68 | |
| 69 | sessionA := []ev{ |
| 70 | phase("r6", event.PhaseSetup, r6Setup, 5*time.Second, keys("launch", "acme/old", "c6", "", nil)), |
| 71 | {r6Setup.Add(5 * time.Second), "r6", event.AgentStarted, keys("launch", "acme/old", "c6", "", nil)}, |
| 72 | phase("r6", event.PhaseAgent, r6Setup.Add(5*time.Second), time.Hour, keys("launch", "acme/old", "c6", "", nil)), |
| 73 | |
| 74 | phase("r1", event.PhaseSetup, r1Setup, 30*time.Second, keys("launch", "acme/widget", "c1", "", nil)), |
| 75 | {r1Agent, "r1", event.AgentStarted, keys("launch", "acme/widget", "c1", "", map[string]interface{}{"target_repo": "widget"})}, |
| 76 | {r1Agent.Add(10 * time.Minute), "r1", event.CheckCompleted, keys("launch", "acme/widget", "c1", "", map[string]interface{}{"kind": "test", "duration_ms": 60000, "success": true})}, |
| 77 | {r1Agent.Add(50 * time.Minute), "r1", event.CheckCompleted, keys("launch", "acme/widget", "c1", "", map[string]interface{}{"kind": "pre-review", "duration_ms": 90000, "success": false})}, |
| 78 | phase("r1", event.PhaseAgent, r1Agent, time.Hour, keys("launch", "acme/widget", "c1", "7", map[string]interface{}{"cost_usd": 2.5})), |
| 79 | {r1End, "r1", event.AgentCompleted, keys("launch", "acme/widget", "c1", "7", map[string]interface{}{"cost_usd": 2.5})}, |
| 80 | {r1End, "r1", event.AgentPRCreated, keys("launch", "acme/widget", "c1", "7", map[string]interface{}{"pr_url": "https://github.com/acme/widget/pull/7"})}, |
| 81 | phase("r1", event.PhaseFinalize, r1End, 20*time.Second, keys("launch", "acme/widget", "c1", "7", nil)), |
| 82 | {r1End.Add(time.Hour), "7", event.AgentCIFailed, map[string]interface{}{"pr_number": "7", "pr_url": "https://github.com/acme/widget/pull/7"}}, |
| 83 | {at(48 * time.Hour), "consult-1", event.ConsultCompleted, map[string]interface{}{"repo_key": "acme/widget", "duration_ms": 60000, "success": true}}, |
| 84 | {at(47 * time.Hour), "consult-2", event.ConsultCompleted, map[string]interface{}{"duration_ms": 30000, "success": true}}, |
| 85 | |
| 86 | phase("r2", event.PhaseSetup, r2Setup, 10*time.Second, keys("ci-fix", "acme/widget", "c1", "7", nil)), |
| 87 | {r2Agent, "r2", event.AgentStarted, keys("ci-fix", "acme/widget", "c1", "7", nil)}, |
| 88 | phase("r2", event.PhaseAgent, r2Agent, 30*time.Minute, keys("ci-fix", "acme/widget", "c1", "7", map[string]interface{}{"cost_usd": 1.0})), |
| 89 | {r2End, "r2", event.AgentCompleted, keys("ci-fix", "acme/widget", "c1", "7", map[string]interface{}{"cost_usd": 1.0})}, |
| 90 | phase("r2", event.PhaseFinalize, r2End, 10*time.Second, keys("ci-fix", "acme/widget", "c1", "7", nil)), |
| 91 | {r2End.Add(10 * time.Second).Add(29*time.Minute + 40*time.Second), "7", event.PRApproved, map[string]interface{}{"pr_number": "7", "pr_url": "https://github.com/acme/widget/pull/7"}}, |
| 92 | {at(46 * time.Hour), "review-1", event.ReviewCompleted, map[string]interface{}{"repo": "acme/widget", "pr_number": "7", "duration_ms": 120000, "success": true}}, |
| 93 | } |
| 94 | sessionB := []ev{ |
| 95 | {at(30 * time.Hour), "r3", event.AgentStarted, map[string]interface{}{"id": "r3", "prompt": "fix the parser", "target_repo": "widget"}}, |
| 96 | {at(29 * time.Hour), "r3", event.AgentCompleted, map[string]interface{}{"id": "r3", "cost_usd": 0.5, "duration_ms": 3500000}}, |
| 97 | {at(29 * time.Hour), "r3", event.AgentPRCreated, map[string]interface{}{"id": "r3", "pr_url": "https://github.com/acme/widget/pull/9", "pr_number": "9"}}, |
| 98 | {at(20 * time.Hour), "r4", event.AgentStarted, map[string]interface{}{"id": "r4", "prompt": "address the review", "target_repo": "widget"}}, |
| 99 | {at(19*time.Hour + 30*time.Minute), "r4", event.AgentCompleted, map[string]interface{}{"id": "r4", "cost_usd": 0.25}}, |
| 100 | {at(19*time.Hour + 30*time.Minute), "r4", event.AgentPRCreated, map[string]interface{}{"id": "r4", "pr_url": "https://github.com/acme/widget/pull/9", "pr_number": "9"}}, |
| 101 | phase("r5", event.PhaseSetup, r5Setup, 5*time.Second, keys("docs-timer", "valley:gadget", "c5", "", nil)), |
| 102 | {r5Setup.Add(5 * time.Second), "r5", event.AgentStarted, keys("docs-timer", "valley:gadget", "c5", "", nil)}, |
| 103 | {r5Setup.Add(5 * time.Second), "r5", event.PhaseStarted, keys("docs-timer", "valley:gadget", "c5", "", map[string]interface{}{"phase": "agent"})}, |
| 104 | } |
| 105 | |
| 106 | write := func(session string, evts []ev) { |
| 107 | dir := filepath.Join(home, ".klaus", "sessions", session) |
| 108 | log := event.NewLog(dir) |
| 109 | for _, e := range evts { |
| 110 | if err := log.Emit(event.Event{Timestamp: e.at.Format(time.RFC3339), RunID: e.run, Type: e.typ, Data: e.data}); err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | write("session-20261018-0900-aaaa", sessionA) |
| 116 | write("session-20261019-0900-bbbb", sessionB) |
| 117 | return "session-20261019-0900-bbbb" |
| 118 | } |
| 119 | |
| 120 | func runReport(t *testing.T, bin, home, session string, args ...string) string { |
| 121 | t.Helper() |
| 122 | c := exec.Command(bin, append([]string{"report", "time"}, args...)...) |
| 123 | c.Env = append(os.Environ(), "HOME="+home, sessionIDEnv+"="+session) |
| 124 | out, err := c.CombinedOutput() |
| 125 | if err != nil { |
| 126 | t.Fatalf("klaus report time %v: %v\n%s", args, err, out) |
| 127 | } |
| 128 | return string(out) |
| 129 | } |
| 130 | |
| 131 | func reportJSON(t *testing.T, bin, home, session string, args ...string) report.Report { |
| 132 | t.Helper() |
| 133 | out := runReport(t, bin, home, session, append(args, "--json")...) |
| 134 | var rep report.Report |
| 135 | if err := json.Unmarshal([]byte(out), &rep); err != nil { |
| 136 | t.Fatalf("report JSON: %v\n%s", err, out) |
| 137 | } |
| 138 | return rep |
| 139 | } |
| 140 | |
| 141 | // TestReportTimeSumsEventLogs runs the real klaus report time over the |
| 142 | // fixture's two sessions. |
| 143 | func TestReportTimeSumsEventLogs(t *testing.T) { |
| 144 | bin := klausBinary(t) |
| 145 | home := t.TempDir() |
| 146 | current := reportFixture(t, home) |
| 147 | |
| 148 | t.Run("a week of every session", func(t *testing.T) { |
| 149 | rep := reportJSON(t, bin, home, current) |
| 150 | o := rep.Overall |
| 151 | if rep.Sessions != 2 || o.Runs != 5 || o.Unfinished != 1 || o.Untimed != 2 { |
| 152 | t.Errorf("sessions %d, runs %d, unfinished %d, untimed %d; want 2, 5 (r6 is older), 1 (r5), 2 (r3, r4)", rep.Sessions, o.Runs, o.Unfinished, o.Untimed) |
| 153 | } |
| 154 | wantReasons := map[string]int{"launch": 1, "ci-fix": 1, "unknown": 2, "docs-timer": 1} |
| 155 | if !sameCounts(o.Reasons, wantReasons) { |
| 156 | t.Errorf("reasons %v, want %v", o.Reasons, wantReasons) |
| 157 | } |
| 158 | // r3 and r4 have no phases: agent:started to their last event. |
| 159 | if o.SetupMS != 45000 || o.AgentMS != (3*time.Hour).Milliseconds() || o.FinalizeMS != 30000 { |
| 160 | t.Errorf("setup %d, agent %d, finalize %d; want 45000, %d, 30000", o.SetupMS, o.AgentMS, (3 * time.Hour).Milliseconds(), o.FinalizeMS) |
| 161 | } |
| 162 | if c := o.Checks["test"]; c == nil || c.Count != 1 || c.MS != 60000 || c.Failed != 0 { |
| 163 | t.Errorf("test checks %+v", c) |
| 164 | } |
| 165 | if c := o.Checks["pre-review"]; c == nil || c.Count != 1 || c.MS != 90000 || c.Failed != 1 { |
| 166 | t.Errorf("pre-review checks %+v", c) |
| 167 | } |
| 168 | // r2 follows r1 on change c1, r4 follows r3 on PR 9; r5's docs-timer |
| 169 | // run starts its change. |
| 170 | if o.Changes != 3 || o.FollowUps != 2 || !sameCounts(o.FollowUpReasons, map[string]int{"ci-fix": 1, "unknown": 1}) { |
| 171 | t.Errorf("changes %d, follow-ups %d %v; want 3, 2 {ci-fix, unknown}", o.Changes, o.FollowUps, o.FollowUpReasons) |
| 172 | } |
| 173 | wantWait := (2*time.Hour + 9*time.Hour).Milliseconds() |
| 174 | if o.WaitMS != wantWait { |
| 175 | t.Errorf("wait between runs %d, want %d", o.WaitMS, wantWait) |
| 176 | } |
| 177 | if o.Approvals != 1 || o.ApprovalWaitMS != (29*time.Minute+40*time.Second).Milliseconds() { |
| 178 | t.Errorf("approvals %d after %dms; want 1 after 29m40s", o.Approvals, o.ApprovalWaitMS) |
| 179 | } |
| 180 | if o.Consults != 2 || o.ConsultMS != 90000 || o.Reviews != 1 || o.ReviewMS != 120000 { |
| 181 | t.Errorf("consults %d %dms, reviews %d %dms", o.Consults, o.ConsultMS, o.Reviews, o.ReviewMS) |
| 182 | } |
| 183 | if o.CostRuns != 4 || o.CostUSD != 4.25 { |
| 184 | t.Errorf("cost $%v over %d runs, want $4.25 over 4", o.CostUSD, o.CostRuns) |
| 185 | } |
| 186 | |
| 187 | repos := map[string]report.Totals{} |
| 188 | for _, r := range rep.Repos { |
| 189 | repos[r.Repo] = r |
| 190 | } |
| 191 | // r3 and r4 named their repo "widget" until their PR said acme/widget. |
| 192 | if w := repos["acme/widget"]; w.Runs != 4 || w.Consults != 1 || w.Reviews != 1 || w.FollowUps != 2 || w.Approvals != 1 { |
| 193 | t.Errorf("acme/widget %+v", w) |
| 194 | } |
| 195 | if g := repos["valley:gadget"]; g.Runs != 1 || g.Unfinished != 1 || g.Reasons["docs-timer"] != 1 { |
| 196 | t.Errorf("valley:gadget %+v", g) |
| 197 | } |
| 198 | if len(rep.Repos) != 2 { |
| 199 | t.Errorf("repos %v, want acme/widget and valley:gadget", repos) |
| 200 | } |
| 201 | |
| 202 | changes := map[string]report.Change{} |
| 203 | for _, c := range rep.Changes { |
| 204 | changes[c.Key] = c |
| 205 | } |
| 206 | c1 := changes["acme/widget#7"] |
| 207 | if c1.Runs != 2 || len(c1.FollowUps) != 1 || c1.FollowUps[0].RunID != "r2" || c1.FollowUps[0].Reason != "ci-fix" || |
| 208 | c1.FollowUps[0].WaitMS != (2*time.Hour).Milliseconds() { |
| 209 | t.Errorf("change acme/widget#7 %+v", c1) |
| 210 | } |
| 211 | if c := changes["acme/widget#9"]; c.Runs != 2 || len(c.FollowUps) != 1 || c.FollowUps[0].Reason != "unknown" { |
| 212 | t.Errorf("change acme/widget#9 %+v", c) |
| 213 | } |
| 214 | if c := changes["valley:gadget@c5"]; c.Runs != 1 || len(c.FollowUps) != 0 { |
| 215 | t.Errorf("change valley:gadget@c5 %+v", c) |
| 216 | } |
| 217 | }) |
| 218 | |
| 219 | t.Run("all time", func(t *testing.T) { |
| 220 | rep := reportJSON(t, bin, home, current, "--since", "0") |
| 221 | if rep.Overall.Runs != 6 || rep.Since != "" { |
| 222 | t.Errorf("runs %d since %q, want 6 (r6 too) since all time", rep.Overall.Runs, rep.Since) |
| 223 | } |
| 224 | }) |
| 225 | |
| 226 | t.Run("one repo", func(t *testing.T) { |
| 227 | rep := reportJSON(t, bin, home, current, "--repo", "widget") |
| 228 | o := rep.Overall |
| 229 | if o.Runs != 4 || o.Consults != 1 || o.Reviews != 1 || len(rep.Repos) != 1 || rep.Repos[0].Repo != "acme/widget" { |
| 230 | t.Errorf("--repo widget: runs %d, consults %d, reviews %d, repos %+v", o.Runs, o.Consults, o.Reviews, rep.Repos) |
| 231 | } |
| 232 | }) |
| 233 | |
| 234 | t.Run("the current session", func(t *testing.T) { |
| 235 | rep := reportJSON(t, bin, home, current, "--current") |
| 236 | if rep.Sessions != 1 || rep.Overall.Runs != 3 || rep.Overall.Consults != 0 { |
| 237 | t.Errorf("--current: sessions %d, runs %d, consults %d; want 1, 3, 0", rep.Sessions, rep.Overall.Runs, rep.Overall.Consults) |
| 238 | } |
| 239 | }) |
| 240 | |
| 241 | t.Run("table", func(t *testing.T) { |
| 242 | out := runReport(t, bin, home, current) |
| 243 | for _, want := range []string{ |
| 244 | "REPO", "acme/widget", "valley:gadget", "TOTAL", |
| 245 | "DISPATCH REASON", "docs-timer", "ci-fix", |
| 246 | "CHECK", "pre-review", |
| 247 | "acme/widget#7", "acme/widget#9", |
| 248 | "Cost is known for 4 of 5 runs.", "2 run(s) predate phase events", "1 run(s) have not finished.", |
| 249 | } { |
| 250 | if !strings.Contains(out, want) { |
| 251 | t.Errorf("table missing %q:\n%s", want, out) |
| 252 | } |
| 253 | } |
| 254 | }) |
| 255 | |
| 256 | t.Run("bad --since", func(t *testing.T) { |
| 257 | c := exec.Command(bin, "report", "time", "--since", "a week") |
| 258 | c.Env = append(os.Environ(), "HOME="+home) |
| 259 | out, err := c.CombinedOutput() |
| 260 | if err == nil || !strings.Contains(string(out), "use a duration such as 7d") { |
| 261 | t.Errorf("--since 'a week' should fail naming the forms: %v\n%s", err, out) |
| 262 | } |
| 263 | }) |
| 264 | } |
| 265 | |
| 266 | func sameCounts(got, want map[string]int) bool { |
| 267 | if len(got) != len(want) { |
| 268 | return false |
| 269 | } |
| 270 | for k, v := range want { |
| 271 | if got[k] != v { |
| 272 | return false |
| 273 | } |
| 274 | } |
| 275 | return true |
| 276 | } |