gunk-dev/the-valley

pipeline_test.go

source601b054bc28emain's published tip history
90.0 KiB
1package pipeline
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11 "time"
12
13 "the-valley/flow/internal/event"
14 "the-valley/flow/internal/run"
15)
16
17// testTmuxDeps returns TmuxDeps where all panes "exist" and are alive (not dead, idle).
18func testTmuxDeps() run.TmuxDeps {
19 return run.TmuxDeps{
20 PaneExists: func(string) bool { return true },
21 PaneIsDead: func(string) bool { return false },
22 PaneIsIdle: func(string) bool { return true },
23 }
24}
25
26func newTestController(t *testing.T) (*Controller, string) {
27 t.Helper()
28 dir := t.TempDir()
29 return controllerIn(t, dir), dir
30}
31
32// controllerIn builds a controller on the session in dir, as the dashboard
33// does: events and the transition ledger live in the session directory. A
34// second call on the same dir stands in for a dashboard restart.
35func controllerIn(t *testing.T, dir string) *Controller {
36 t.Helper()
37 baseDir := filepath.Join(dir, "session")
38 if err := os.MkdirAll(baseDir, 0o755); err != nil {
39 t.Fatal(err)
40 }
41 eventLog := event.NewLog(baseDir)
42 logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
43
44 stateDir := filepath.Join(dir, "klaus")
45 store := run.NewGitDirStore(stateDir)
46
47 c := New(store, eventLog, logger)
48 c.SetTmuxDeps(testTmuxDeps())
49 ledger, err := LoadLedger(filepath.Join(baseDir, LedgerFile))
50 if err != nil {
51 t.Fatal(err)
52 }
53 c.SetLedger(ledger)
54 return c
55}
56
57func TestStateTransition_CIPendingToFailed(t *testing.T) {
58 c, _ := newTestController(t)
59
60 var launchedPR string
61 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
62 launchedPR = prNumber
63 return "agent-001", nil
64 })
65
66 statuses := map[string]*PRStatus{
67 "42": {PRNumber: "42", PRURL: "https://github.com/owner/repo/pull/42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
68 }
69
70 actions := c.HandleGHStatus(context.Background(), statuses, nil)
71
72 if launchedPR != "42" {
73 t.Errorf("expected agent launched for PR #42, got %q", launchedPR)
74 }
75 if len(actions) != 1 || actions[0].Type != "launch" {
76 t.Errorf("expected 1 launch action, got %v", actions)
77 }
78
79 states := c.PipelineStates()
80 if states["42"].Stage != StageCIFailed {
81 t.Errorf("expected stage ci_failed, got %s", states["42"].Stage)
82 }
83 if states["42"].PRURL != "https://github.com/owner/repo/pull/42" {
84 t.Errorf("state should record the PR it tracks, got %q", states["42"].PRURL)
85 }
86}
87
88func TestStateTransition_CIFailedToPassedToApproved(t *testing.T) {
89 c, _ := newTestController(t)
90 c.SetAutoMergeOnApproval(true)
91
92 launchCount := 0
93 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
94 launchCount++
95 return "agent-001", nil
96 })
97 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
98 return nil
99 })
100
101 // Step 1: CI failing -> dispatches agent
102 statuses := map[string]*PRStatus{
103 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
104 }
105 c.HandleGHStatus(context.Background(), statuses, nil)
106
107 if c.PipelineStates()["42"].Stage != StageCIFailed {
108 t.Fatalf("expected ci_failed, got %s", c.PipelineStates()["42"].Stage)
109 }
110
111 // Step 2: CI passes (no review yet)
112 statuses["42"] = &PRStatus{PRNumber: "42", State: "OPEN", CI: "passing", TargetRepo: "owner/repo"}
113 c.HandleGHStatus(context.Background(), statuses, nil)
114
115 if c.PipelineStates()["42"].Stage != StageCIPassed {
116 t.Fatalf("expected ci_passed, got %s", c.PipelineStates()["42"].Stage)
117 }
118
119 // Step 3: Approved -> auto-merge
120 statuses["42"] = &PRStatus{
121 PRNumber: "42", State: "OPEN", CI: "passing",
122 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
123 }
124 actions := c.HandleGHStatus(context.Background(), statuses, nil)
125
126 // Should have merged
127 hasMerge := false
128 for _, a := range actions {
129 if a.Type == "merge" {
130 hasMerge = true
131 }
132 }
133 if !hasMerge {
134 t.Error("expected merge action after approval")
135 }
136}
137
138func TestNoDuplicateAgentDispatch(t *testing.T) {
139 c, _ := newTestController(t)
140
141 launchCount := 0
142 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
143 launchCount++
144 return "agent-001", nil
145 })
146
147 statuses := map[string]*PRStatus{
148 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
149 }
150
151 // First call should dispatch.
152 c.HandleGHStatus(context.Background(), statuses, nil)
153 if launchCount != 1 {
154 t.Fatalf("expected 1 launch, got %d", launchCount)
155 }
156
157 // Simulate agent still running.
158 runStates := []*run.State{
159 {ID: "agent-001", TmuxPane: strPtr("%1")}, // running: has pane, no cost/duration
160 }
161 c.HandleGHStatus(context.Background(), statuses, runStates)
162 if launchCount != 1 {
163 t.Errorf("expected no duplicate launch, got %d total", launchCount)
164 }
165}
166
167func TestAgentReDispatchAfterCompletion(t *testing.T) {
168 c, _ := newTestController(t)
169
170 launchCount := 0
171 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
172 launchCount++
173 return "agent-002", nil
174 })
175
176 statuses := map[string]*PRStatus{
177 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
178 }
179
180 // First dispatch.
181 c.HandleGHStatus(context.Background(), statuses, nil)
182 if launchCount != 1 {
183 t.Fatalf("expected 1 launch, got %d", launchCount)
184 }
185
186 // Agent completed (finalized with cost).
187 cost := 1.0
188 runStates := []*run.State{
189 {ID: "agent-002", TmuxPane: strPtr("%1"), CostUSD: &cost},
190 }
191
192 // Expire the dispatch cooldown so re-dispatch is allowed.
193 c.mu.Lock()
194 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
195 c.mu.Unlock()
196
197 // CI still failing -> should re-dispatch.
198 c.HandleGHStatus(context.Background(), statuses, runStates)
199 if launchCount != 2 {
200 t.Errorf("expected re-dispatch after agent completed, got %d total", launchCount)
201 }
202}
203
204func TestReviewCommentsDispatchAgent(t *testing.T) {
205 c, _ := newTestController(t)
206
207 var launchedPrompt string
208 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
209 launchedPrompt = prompt
210 return "agent-review", nil
211 })
212
213 statuses := map[string]*PRStatus{
214 "42": {
215 PRNumber: "42", State: "OPEN", CI: "passing",
216 ReviewDecision: "CHANGES_REQUESTED", TargetRepo: "owner/repo",
217 },
218 }
219
220 actions := c.HandleGHStatus(context.Background(), statuses, nil)
221
222 if launchedPrompt == "" {
223 t.Error("expected agent dispatch for review comments")
224 }
225 if len(actions) != 1 || actions[0].Type != "launch" {
226 t.Errorf("expected 1 launch action, got %v", actions)
227 }
228
229 states := c.PipelineStates()
230 if states["42"].Stage != StageReviewPending {
231 t.Errorf("expected stage review_pending, got %s", states["42"].Stage)
232 }
233}
234
235func TestReviewFixPromptsInstructAgentToReplyToComments(t *testing.T) {
236 cases := []struct {
237 name string
238 status *PRStatus
239 wantLeadIn string
240 }{
241 {
242 name: "changes-requested",
243 status: &PRStatus{
244 PRNumber: "42", State: "OPEN", CI: "passing",
245 ReviewDecision: "CHANGES_REQUESTED", TargetRepo: "owner/repo",
246 },
247 wantLeadIn: "changes requested by reviewers",
248 },
249 {
250 name: "trusted-comments",
251 status: &PRStatus{
252 PRNumber: "42", State: "OPEN", CI: "passing",
253 HasNewTrustedComments: true, TargetRepo: "owner/repo",
254 },
255 wantLeadIn: "trusted reviewer",
256 },
257 }
258
259 prompts := make(map[string]string, len(cases))
260 for _, tc := range cases {
261 t.Run(tc.name, func(t *testing.T) {
262 c, _ := newTestController(t)
263
264 var launchedPrompt string
265 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
266 launchedPrompt = prompt
267 return "agent-x", nil
268 })
269
270 c.HandleGHStatus(context.Background(), map[string]*PRStatus{"42": tc.status}, nil)
271
272 if launchedPrompt == "" {
273 t.Fatal("expected agent dispatch")
274 }
275 // Path-specific lead-in.
276 if !strings.Contains(launchedPrompt, tc.wantLeadIn) {
277 t.Errorf("prompt missing lead-in %q: %q", tc.wantLeadIn, launchedPrompt)
278 }
279 // Must instruct fetching the comments using the literal
280 // {owner}/{repo} placeholder, which gh expands from the worktree's
281 // git remote. It must NOT substitute TargetRepo, which is a project
282 // short name and would yield a 404 path (issue #269).
283 if !strings.Contains(launchedPrompt, "gh api repos/{owner}/{repo}/pulls/42/comments") {
284 t.Errorf("prompt missing placeholder fetch instruction: %q", launchedPrompt)
285 }
286 if strings.Contains(launchedPrompt, "repos/"+tc.status.TargetRepo+"/pulls") {
287 t.Errorf("prompt substitutes TargetRepo into API path (404 risk): %q", launchedPrompt)
288 }
289 // Must also cover PR conversation comments, which live in the
290 // issues API and are replied to with a new PR comment.
291 if !strings.Contains(launchedPrompt, "gh api repos/{owner}/{repo}/issues/42/comments") {
292 t.Errorf("prompt missing conversation comment fetch instruction: %q", launchedPrompt)
293 }
294 if !strings.Contains(launchedPrompt, "gh pr comment 42 --body") {
295 t.Errorf("prompt missing conversation comment reply command: %q", launchedPrompt)
296 }
297 // Replies must carry the marker review detection uses to skip them.
298 if !strings.Contains(launchedPrompt, AgentReplyMarker) {
299 t.Errorf("prompt missing agent reply marker: %q", launchedPrompt)
300 }
301 // Must instruct replying to each comment.
302 if !strings.Contains(launchedPrompt, "reply to EACH") {
303 t.Errorf("prompt missing reply-to-each instruction: %q", launchedPrompt)
304 }
305 // Must guard against duplicate replies on re-dispatch.
306 if !strings.Contains(launchedPrompt, "haven't already replied to") {
307 t.Errorf("prompt missing duplicate-reply guard: %q", launchedPrompt)
308 }
309 // Must include the exact replies endpoint format.
310 if !strings.Contains(launchedPrompt, "/comments/{commentId}/replies") {
311 t.Errorf("prompt missing replies command format: %q", launchedPrompt)
312 }
313 // Must mention discounted comments.
314 if !strings.Contains(launchedPrompt, "discounted") {
315 t.Errorf("prompt missing discounted-comment guidance: %q", launchedPrompt)
316 }
317 prompts[tc.name] = launchedPrompt
318 })
319 }
320
321 // The shared body (everything from "Review comments come in two kinds" onward)
322 // must be identical across both dispatch paths so reviewers see consistent
323 // instructions regardless of which transition fired.
324 bodyOf := func(p string) string {
325 i := strings.Index(p, "Review comments come in two kinds")
326 if i < 0 {
327 t.Fatalf("prompt has no shared body: %q", p)
328 }
329 return p[i:]
330 }
331 if bodyOf(prompts["changes-requested"]) != bodyOf(prompts["trusted-comments"]) {
332 t.Errorf("shared prompt body differs across dispatch paths:\nchanges-requested: %q\ntrusted-comments: %q",
333 bodyOf(prompts["changes-requested"]), bodyOf(prompts["trusted-comments"]))
334 }
335}
336
337func TestMergedPRCleanedUp(t *testing.T) {
338 c, _ := newTestController(t)
339 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
340 return "agent-001", nil
341 })
342
343 // Start with a CI failing PR.
344 statuses := map[string]*PRStatus{
345 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
346 }
347 c.HandleGHStatus(context.Background(), statuses, nil)
348
349 if len(c.PipelineStates()) != 1 {
350 t.Fatal("expected 1 tracked PR")
351 }
352
353 // PR gets merged externally.
354 statuses["42"] = &PRStatus{PRNumber: "42", State: "MERGED"}
355 c.HandleGHStatus(context.Background(), statuses, nil)
356
357 if len(c.PipelineStates()) != 0 {
358 t.Error("expected merged PR to be cleaned up from tracking")
359 }
360}
361
362func TestClosedPRCleanedUp(t *testing.T) {
363 c, _ := newTestController(t)
364
365 // Manually seed state.
366 c.mu.Lock()
367 c.prStates["99"] = &PRPipelineState{PRNumber: "99", Stage: StageCIPassed}
368 c.mu.Unlock()
369
370 statuses := map[string]*PRStatus{
371 "99": {PRNumber: "99", State: "CLOSED"},
372 }
373 c.HandleGHStatus(context.Background(), statuses, nil)
374
375 if len(c.PipelineStates()) != 0 {
376 t.Error("expected closed PR to be cleaned up from tracking")
377 }
378}
379
380func TestAutoMergeBlockedByConflicts(t *testing.T) {
381 c, _ := newTestController(t)
382
383 mergeCount := 0
384 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
385 mergeCount++
386 return nil
387 })
388
389 var launchedPrompt string
390 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
391 launchedPrompt = prompt
392 return "agent-rebase", nil
393 })
394
395 statuses := map[string]*PRStatus{
396 "42": {
397 PRNumber: "42", State: "OPEN", CI: "passing",
398 ReviewDecision: "APPROVED", Conflicts: "yes", TargetRepo: "owner/repo",
399 },
400 }
401
402 actions := c.HandleGHStatus(context.Background(), statuses, nil)
403
404 if mergeCount != 0 {
405 t.Error("should not merge when conflicts exist")
406 }
407
408 if launchedPrompt == "" {
409 t.Error("expected rebase agent dispatch when conflicts detected")
410 }
411 if !strings.Contains(launchedPrompt, "merge conflicts") {
412 t.Errorf("expected rebase prompt, got %q", launchedPrompt)
413 }
414
415 hasLaunch := false
416 for _, a := range actions {
417 if a.Type == "launch" && strings.Contains(a.Detail, "Rebase") {
418 hasLaunch = true
419 }
420 }
421 if !hasLaunch {
422 t.Errorf("expected rebase launch action, got %v", actions)
423 }
424
425 states := c.PipelineStates()
426 if states["42"].Stage != StageNeedsRebase {
427 t.Errorf("expected stage needs_rebase, got %s", states["42"].Stage)
428 }
429}
430
431func TestStageLabelCoverage(t *testing.T) {
432 tests := []struct {
433 stage Stage
434 want string
435 }{
436 {StageCIPending, "CI pending"},
437 {StageCIFailed, "CI failed, fix running"},
438 {StageCIPassed, "CI passed, reviewing"},
439 {StageReviewPending, "review fix running"},
440 {StageApproved, "approved, ready"},
441 {StageNeedsRebase, "rebasing"},
442 {StageMerging, "merging"},
443 {StageMerged, "merged"},
444 {StageStalled, "stalled"},
445 {Stage("unknown"), "unknown"},
446 }
447 for _, tt := range tests {
448 got := StageLabel(tt.stage)
449 if got != tt.want {
450 t.Errorf("StageLabel(%q) = %q, want %q", tt.stage, got, tt.want)
451 }
452 }
453}
454
455func TestExtractAgentID(t *testing.T) {
456 tests := []struct {
457 input string
458 want string
459 }{
460 {"Launching agent 20260401-1500-abc1...\n worktree: ...", "20260401-1500-abc1"},
461 {"Launching agent abc123 (PR #42 fix)...", "abc123"},
462 {"no match here", ""},
463 {"", ""},
464 }
465 for _, tt := range tests {
466 got := extractAgentID(tt.input)
467 if got != tt.want {
468 t.Errorf("extractAgentID(%q) = %q, want %q", tt.input, got, tt.want)
469 }
470 }
471}
472
473func TestTruncateError(t *testing.T) {
474 tests := []struct {
475 input string
476 maxLen int
477 want string
478 }{
479 {"short error", 50, "short error"},
480 {"line one\nline two\nline three", 50, "line one"},
481 {"some error\n\nUsage:\n klaus launch [flags]", 50, "some error"},
482 {"before Usage: after", 50, "before"},
483 {strings.Repeat("x", 200), 50, strings.Repeat("x", 49) + "…"},
484 {"", 50, ""},
485 }
486 for _, tt := range tests {
487 got := truncateError(tt.input, tt.maxLen)
488 if got != tt.want {
489 t.Errorf("truncateError(%q, %d) = %q, want %q", tt.input, tt.maxLen, got, tt.want)
490 }
491 }
492}
493
494// TestFailedDispatchWaitsForNewInputs: a launch that fails stalls the PR
495// and reports it once; polls on the same inputs, however late, don't launch
496// again, and a change to any input does.
497func TestFailedDispatchWaitsForNewInputs(t *testing.T) {
498 base := PRStatus{PRNumber: "42", PRURL: "https://github.com/owner/repo/pull/42", State: "OPEN", CI: "failing", HeadSHA: "aaa", TargetRepo: "owner/repo"}
499 for _, tt := range []struct {
500 name string
501 change func(*PRStatus)
502 }{
503 {"head", func(s *PRStatus) { s.HeadSHA = "bbb" }},
504 {"ci", func(s *PRStatus) { s.CI, s.Conflicts = "passing", "yes" }},
505 {"review", func(s *PRStatus) { s.ReviewDecision = "CHANGES_REQUESTED" }},
506 {"trusted comments", func(s *PRStatus) { s.HasNewTrustedComments = true }},
507 {"more trusted comments", func(s *PRStatus) { s.TrustedFeedbackAt = time.Now() }},
508 } {
509 t.Run(tt.name, func(t *testing.T) {
510 c, dir := newTestController(t)
511 launches := 0
512 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
513 launches++
514 return "", fmt.Errorf("worktree has an unpushed commit")
515 })
516 poll := func(s PRStatus) []Action {
517 return c.HandleGHStatus(context.Background(), map[string]*PRStatus{"42": &s}, nil)
518 }
519
520 actions := poll(base)
521 if launches != 1 || len(actions) != 1 || actions[0].Type != "error" || !strings.Contains(actions[0].Error, "unpushed commit") {
522 t.Fatalf("first poll: %d launches, actions %+v; want 1 launch and its error", launches, actions)
523 }
524 for i := 0; i < 5; i++ {
525 c.mu.Lock()
526 c.prStates["42"].LastDispatchAt = time.Now().Add(-time.Hour)
527 c.mu.Unlock()
528 poll(base)
529 }
530 if launches != 1 {
531 t.Errorf("same inputs: %d launches, want 1", launches)
532 }
533 if got := c.PipelineStates()["42"].Stage; got != StageStalled {
534 t.Errorf("stage on the same inputs = %s, want stalled", got)
535 }
536 evts := readEvents(t, dir)
537 if got := countEvents(evts, event.PipelineStalled); got != 1 {
538 t.Fatalf("pipeline:stalled events = %d, want 1", got)
539 }
540 for _, e := range evts {
541 if e.Type == event.PipelineStalled && !strings.Contains(fmt.Sprint(e.Data["reason"]), "unpushed commit") {
542 t.Errorf("stalled event doesn't carry the error: %v", e.Data)
543 }
544 }
545
546 next := base
547 tt.change(&next)
548 poll(next)
549 if launches != 2 {
550 t.Errorf("after the %s changed: %d launches, want 2", tt.name, launches)
551 }
552 })
553 }
554}
555
556func TestWorktreeCleanupBeforeDispatch(t *testing.T) {
557 c, _ := newTestController(t)
558
559 // Create a temp dir to act as the stale worktree.
560 staleDir := t.TempDir()
561
562 var cleanedUpID string
563 // Override launchAgent to track that cleanup happened before launch.
564 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
565 // By the time launch is called, the stale worktree should have
566 // had cleanup attempted. We can't easily verify the cleanup command
567 // ran (it would fail since the run ID doesn't exist in store), but
568 // we can verify the controller attempted it by checking the worktree
569 // dir was passed. For this test, just succeed.
570 return "agent-new", nil
571 })
572
573 // Provide a run state for a completed agent that has a worktree on disk.
574 cost := 1.0
575 staleRun := &run.State{
576 ID: "agent-stale",
577 PR: strPtr("42"),
578 Worktree: staleDir,
579 TmuxPane: strPtr("%99"), // pane exists but run is finalized
580 CostUSD: &cost, // finalized -> not running
581 }
582
583 statuses := map[string]*PRStatus{
584 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
585 }
586
587 actions := c.HandleGHStatus(context.Background(), statuses, []*run.State{staleRun})
588
589 // Should have dispatched a new agent.
590 if len(actions) == 0 || actions[0].Type != "launch" {
591 t.Errorf("expected launch action, got %v", actions)
592 }
593
594 _ = cleanedUpID // cleanup runs best-effort via exec
595}
596
597func TestTrustedCommentDispatch(t *testing.T) {
598 c, _ := newTestController(t)
599
600 var launchedPrompt string
601 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
602 launchedPrompt = prompt
603 return "agent-trusted", nil
604 })
605
606 statuses := map[string]*PRStatus{
607 "42": {
608 PRNumber: "42",
609 State: "OPEN",
610 CI: "passing",
611 ReviewDecision: "", // empty — not CHANGES_REQUESTED
612 HasNewTrustedComments: true,
613 TargetRepo: "owner/repo",
614 },
615 }
616
617 actions := c.HandleGHStatus(context.Background(), statuses, nil)
618
619 if launchedPrompt == "" {
620 t.Error("expected agent dispatch for trusted reviewer comments")
621 }
622 if len(actions) != 1 || actions[0].Type != "launch" {
623 t.Errorf("expected 1 launch action, got %v", actions)
624 }
625
626 states := c.PipelineStates()
627 if states["42"].Stage != StageReviewPending {
628 t.Errorf("expected stage review_pending, got %s", states["42"].Stage)
629 }
630}
631
632func TestNoDispatchWithoutTrustedComments(t *testing.T) {
633 c, _ := newTestController(t)
634
635 launchCount := 0
636 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
637 launchCount++
638 return "agent-001", nil
639 })
640
641 statuses := map[string]*PRStatus{
642 "42": {
643 PRNumber: "42",
644 State: "OPEN",
645 CI: "passing",
646 ReviewDecision: "",
647 HasNewTrustedComments: false,
648 TargetRepo: "owner/repo",
649 },
650 }
651
652 c.HandleGHStatus(context.Background(), statuses, nil)
653
654 if launchCount != 0 {
655 t.Errorf("expected no agent dispatch without trusted comments, got %d launches", launchCount)
656 }
657
658 states := c.PipelineStates()
659 if states["42"].Stage != StageCIPassed {
660 t.Errorf("expected stage ci_passed, got %s", states["42"].Stage)
661 }
662}
663
664func TestNoDoubleDispatchOnTrustedComments(t *testing.T) {
665 c, _ := newTestController(t)
666
667 launchCount := 0
668 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
669 launchCount++
670 return "agent-trusted", nil
671 })
672
673 statuses := map[string]*PRStatus{
674 "42": {
675 PRNumber: "42",
676 State: "OPEN",
677 CI: "passing",
678 ReviewDecision: "",
679 HasNewTrustedComments: true,
680 TargetRepo: "owner/repo",
681 },
682 }
683
684 // First call dispatches.
685 c.HandleGHStatus(context.Background(), statuses, nil)
686 if launchCount != 1 {
687 t.Fatalf("expected 1 launch, got %d", launchCount)
688 }
689
690 // Simulate agent still running.
691 runStates := []*run.State{
692 {ID: "agent-trusted", TmuxPane: strPtr("%1")},
693 }
694 c.HandleGHStatus(context.Background(), statuses, runStates)
695 if launchCount != 1 {
696 t.Errorf("expected no duplicate launch while agent running, got %d total", launchCount)
697 }
698}
699
700func TestNeedsRebaseTransitionsToMergeAfterConflictsResolved(t *testing.T) {
701 c, _ := newTestController(t)
702 c.SetAutoMergeOnApproval(true)
703
704 launchCount := 0
705 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
706 launchCount++
707 return fmt.Sprintf("agent-%03d", launchCount), nil
708 })
709 mergeCount := 0
710 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
711 mergeCount++
712 return nil
713 })
714
715 // Step 1: Approved with conflicts → dispatches rebase agent.
716 statuses := map[string]*PRStatus{
717 "42": {
718 PRNumber: "42", State: "OPEN", CI: "passing",
719 ReviewDecision: "APPROVED", Conflicts: "yes", TargetRepo: "owner/repo",
720 },
721 }
722 c.HandleGHStatus(context.Background(), statuses, nil)
723
724 if c.PipelineStates()["42"].Stage != StageNeedsRebase {
725 t.Fatalf("expected needs_rebase, got %s", c.PipelineStates()["42"].Stage)
726 }
727 if launchCount != 1 {
728 t.Fatalf("expected 1 launch, got %d", launchCount)
729 }
730
731 // Step 2: Rebase agent completes, CI passes, conflicts resolved → should merge.
732 cost := 1.0
733 runStates := []*run.State{
734 {ID: "agent-001", TmuxPane: strPtr("%1"), CostUSD: &cost}, // completed
735 }
736 statuses["42"] = &PRStatus{
737 PRNumber: "42", State: "OPEN", CI: "passing",
738 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
739 }
740 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
741
742 hasMerge := false
743 for _, a := range actions {
744 if a.Type == "merge" {
745 hasMerge = true
746 }
747 }
748 if !hasMerge {
749 t.Error("expected merge after rebase resolved conflicts")
750 }
751 if mergeCount != 1 {
752 t.Errorf("expected 1 merge call, got %d", mergeCount)
753 }
754}
755
756func TestNeedsRebaseTransitionsToCIFailedIfCIFails(t *testing.T) {
757 c, _ := newTestController(t)
758
759 launchCount := 0
760 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
761 launchCount++
762 return fmt.Sprintf("agent-%03d", launchCount), nil
763 })
764
765 // Step 1: Approved with conflicts → rebase agent dispatched.
766 statuses := map[string]*PRStatus{
767 "42": {
768 PRNumber: "42", State: "OPEN", CI: "passing",
769 ReviewDecision: "APPROVED", Conflicts: "yes", TargetRepo: "owner/repo",
770 },
771 }
772 c.HandleGHStatus(context.Background(), statuses, nil)
773
774 if c.PipelineStates()["42"].Stage != StageNeedsRebase {
775 t.Fatalf("expected needs_rebase, got %s", c.PipelineStates()["42"].Stage)
776 }
777
778 // Expire the dispatch cooldown so the CI fix agent can be dispatched.
779 c.mu.Lock()
780 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
781 c.mu.Unlock()
782
783 // Step 2: Rebase agent completes but CI fails.
784 cost := 1.0
785 runStates := []*run.State{
786 {ID: "agent-001", TmuxPane: strPtr("%1"), CostUSD: &cost},
787 }
788 statuses["42"] = &PRStatus{
789 PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo",
790 }
791 c.HandleGHStatus(context.Background(), statuses, runStates)
792
793 state := c.PipelineStates()["42"]
794 if state.Stage != StageCIFailed {
795 t.Errorf("expected ci_failed after rebase + CI failure, got %s", state.Stage)
796 }
797 // Should have dispatched a CI fix agent (launch 2).
798 if launchCount != 2 {
799 t.Errorf("expected 2 launches (rebase + CI fix), got %d", launchCount)
800 }
801}
802
803func TestNeedsRebaseNoDoubleDispatch(t *testing.T) {
804 c, _ := newTestController(t)
805
806 launchCount := 0
807 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
808 launchCount++
809 return "agent-rebase", nil
810 })
811
812 statuses := map[string]*PRStatus{
813 "42": {
814 PRNumber: "42", State: "OPEN", CI: "passing",
815 ReviewDecision: "APPROVED", Conflicts: "yes", TargetRepo: "owner/repo",
816 },
817 }
818
819 // First call dispatches rebase agent.
820 c.HandleGHStatus(context.Background(), statuses, nil)
821 if launchCount != 1 {
822 t.Fatalf("expected 1 launch, got %d", launchCount)
823 }
824
825 // Agent still running — should not re-dispatch.
826 runStates := []*run.State{
827 {ID: "agent-rebase", TmuxPane: strPtr("%1")},
828 }
829 c.HandleGHStatus(context.Background(), statuses, runStates)
830 if launchCount != 1 {
831 t.Errorf("expected no duplicate rebase dispatch, got %d total", launchCount)
832 }
833}
834
835func TestUnapprovedConflictsDispatchesRebase(t *testing.T) {
836 c, _ := newTestController(t)
837
838 mergeCount := 0
839 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
840 mergeCount++
841 return nil
842 })
843
844 var launchedPrompt string
845 launchCount := 0
846 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
847 launchedPrompt = prompt
848 launchCount++
849 return "agent-rebase", nil
850 })
851
852 // CI passing, no review decision, no klaus internal approval, but conflicts present.
853 statuses := map[string]*PRStatus{
854 "42": {
855 PRNumber: "42", State: "OPEN", CI: "passing",
856 ReviewDecision: "", Conflicts: "yes", TargetRepo: "owner/repo",
857 },
858 }
859
860 actions := c.HandleGHStatus(context.Background(), statuses, nil)
861
862 if mergeCount != 0 {
863 t.Error("should not merge when conflicts exist")
864 }
865 if launchCount != 1 {
866 t.Errorf("expected 1 rebase agent launch for unapproved PR with conflicts, got %d", launchCount)
867 }
868 if !strings.Contains(launchedPrompt, "merge conflicts") {
869 t.Errorf("expected rebase prompt, got %q", launchedPrompt)
870 }
871
872 hasLaunch := false
873 for _, a := range actions {
874 if a.Type == "launch" && strings.Contains(a.Detail, "Rebase") {
875 hasLaunch = true
876 }
877 }
878 if !hasLaunch {
879 t.Errorf("expected rebase launch action, got %v", actions)
880 }
881
882 state := c.PipelineStates()["42"]
883 if state.Stage != StageNeedsRebase {
884 t.Errorf("expected stage needs_rebase, got %s", state.Stage)
885 }
886 // Approval-related side effects must not have run.
887 if state.Stage == StageApproved {
888 t.Error("rebase dispatch should not transition unapproved PR to approved stage")
889 }
890}
891
892func TestRebaseCircuitBreaker(t *testing.T) {
893 c, _ := newTestController(t)
894
895 launchCount := 0
896 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
897 launchCount++
898 return fmt.Sprintf("agent-%03d", launchCount), nil
899 })
900
901 statuses := map[string]*PRStatus{
902 "42": {
903 PRNumber: "42", State: "OPEN", CI: "passing",
904 ReviewDecision: "", Conflicts: "yes", TargetRepo: "owner/repo",
905 },
906 }
907
908 // Dispatch 1: initial rebase agent.
909 c.HandleGHStatus(context.Background(), statuses, nil)
910 if launchCount != 1 {
911 t.Fatalf("expected 1 launch, got %d", launchCount)
912 }
913
914 for attempt := 2; attempt <= 3; attempt++ {
915 // Simulate agent completion (finalized with cost) without resolving conflicts.
916 cost := 1.0
917 runStates := []*run.State{
918 {ID: fmt.Sprintf("agent-%03d", attempt-1), TmuxPane: strPtr("%1"), CostUSD: &cost},
919 }
920
921 // Expire the dispatch cooldown.
922 c.mu.Lock()
923 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
924 c.mu.Unlock()
925
926 // Conflicts still present -> should re-dispatch rebase.
927 c.HandleGHStatus(context.Background(), statuses, runStates)
928 if launchCount != attempt {
929 t.Fatalf("attempt %d: expected %d launches, got %d", attempt, attempt, launchCount)
930 }
931 }
932
933 // Three rebase agents have been dispatched. Simulate agent 3 completing.
934 cost := 1.0
935 runStates := []*run.State{
936 {ID: "agent-003", TmuxPane: strPtr("%1"), CostUSD: &cost},
937 }
938 c.mu.Lock()
939 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
940 c.mu.Unlock()
941
942 // Conflicts persist -> circuit breaker trips; no 4th dispatch.
943 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
944 if launchCount != 3 {
945 t.Errorf("expected circuit breaker to stop at 3 launches, got %d", launchCount)
946 }
947
948 hasError := false
949 for _, a := range actions {
950 if a.Type == "error" && strings.Contains(a.Detail, "rebase attempts failed") {
951 hasError = true
952 }
953 }
954 if !hasError {
955 t.Errorf("expected error action from rebase circuit breaker, got %v", actions)
956 }
957
958 if c.PipelineStates()["42"].Stage != StageStalled {
959 t.Errorf("expected stalled stage, got %s", c.PipelineStates()["42"].Stage)
960 }
961
962 // Subsequent poll while still stalled and conflicts present must not re-dispatch
963 // or emit duplicate stall errors.
964 c.mu.Lock()
965 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
966 c.mu.Unlock()
967 actions = c.HandleGHStatus(context.Background(), statuses, runStates)
968 if launchCount != 3 {
969 t.Errorf("expected no further dispatches after stall, got %d", launchCount)
970 }
971 for _, a := range actions {
972 if a.Type == "error" {
973 t.Errorf("expected no duplicate error after stall, got %v", actions)
974 }
975 }
976}
977
978// TestStalledFromCIRecoversWithConflicts verifies that a PR which exhausted
979// its CI fix-attempt budget and went to StageStalled is not blocked from
980// dispatching a rebase agent once CI starts passing — the rebase counter is
981// tracked separately so the rebase agent gets its own budget.
982func TestStalledFromCIRecoversWithConflicts(t *testing.T) {
983 c, _ := newTestController(t)
984
985 launchCount := 0
986 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
987 launchCount++
988 return fmt.Sprintf("agent-%03d", launchCount), nil
989 })
990
991 // Manually put the PR in StageStalled with FixAttempts maxed out, simulating
992 // having exhausted CI fix attempts before CI started passing.
993 c.mu.Lock()
994 c.prStates["42"] = &PRPipelineState{
995 PRNumber: "42",
996 Stage: StageStalled,
997 FixAttempts: maxFixAttempts,
998 LastAgentID: "agent-old",
999 }
1000 c.mu.Unlock()
1001
1002 // CI now passes but conflicts have appeared.
1003 statuses := map[string]*PRStatus{
1004 "42": {
1005 PRNumber: "42", State: "OPEN", CI: "passing",
1006 ReviewDecision: "", Conflicts: "yes", TargetRepo: "owner/repo",
1007 },
1008 }
1009 actions := c.HandleGHStatus(context.Background(), statuses, nil)
1010
1011 if launchCount != 1 {
1012 t.Errorf("expected rebase agent to dispatch with fresh budget, got %d launches", launchCount)
1013 }
1014 for _, a := range actions {
1015 if a.Type == "error" {
1016 t.Errorf("did not expect circuit-breaker error on first rebase attempt, got %v", actions)
1017 }
1018 }
1019 state := c.PipelineStates()["42"]
1020 if state.Stage != StageNeedsRebase {
1021 t.Errorf("expected stage needs_rebase after recovery, got %s", state.Stage)
1022 }
1023 if state.FixAttempts != 0 {
1024 t.Errorf("expected FixAttempts reset to 0, got %d", state.FixAttempts)
1025 }
1026 if state.RebaseAttempts != 0 {
1027 t.Errorf("expected RebaseAttempts to start at 0, got %d", state.RebaseAttempts)
1028 }
1029}
1030
1031// TestRebaseDispatchDoesNotConsumeCIFixBudget verifies a PR with prior CI
1032// fix attempts gets a full rebase budget once CI passes.
1033func TestRebaseDispatchDoesNotConsumeCIFixBudget(t *testing.T) {
1034 c, _ := newTestController(t)
1035
1036 launchCount := 0
1037 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1038 launchCount++
1039 return fmt.Sprintf("agent-%03d", launchCount), nil
1040 })
1041
1042 // Two prior CI fix attempts that didn't resolve CI yet.
1043 c.mu.Lock()
1044 c.prStates["42"] = &PRPipelineState{
1045 PRNumber: "42",
1046 Stage: StageCIFailed,
1047 FixAttempts: 2,
1048 LastAgentID: "agent-old",
1049 }
1050 c.mu.Unlock()
1051
1052 statuses := map[string]*PRStatus{
1053 "42": {
1054 PRNumber: "42", State: "OPEN", CI: "passing",
1055 ReviewDecision: "", Conflicts: "yes", TargetRepo: "owner/repo",
1056 },
1057 }
1058
1059 // First rebase dispatch: should fire and reset FixAttempts.
1060 c.HandleGHStatus(context.Background(), statuses, nil)
1061 if launchCount != 1 {
1062 t.Fatalf("expected first rebase dispatch, got %d launches", launchCount)
1063 }
1064 state := c.PipelineStates()["42"]
1065 if state.FixAttempts != 0 {
1066 t.Errorf("expected FixAttempts reset to 0 once CI passes, got %d", state.FixAttempts)
1067 }
1068 if state.RebaseAttempts != 0 {
1069 t.Errorf("expected RebaseAttempts at 0 after first dispatch, got %d", state.RebaseAttempts)
1070 }
1071
1072 // Two more cycles should still dispatch rebase agents (full rebase budget).
1073 for attempt := 2; attempt <= 3; attempt++ {
1074 cost := 1.0
1075 runStates := []*run.State{
1076 {ID: fmt.Sprintf("agent-%03d", attempt-1), TmuxPane: strPtr("%1"), CostUSD: &cost},
1077 }
1078 c.mu.Lock()
1079 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1080 c.mu.Unlock()
1081 c.HandleGHStatus(context.Background(), statuses, runStates)
1082 if launchCount != attempt {
1083 t.Fatalf("attempt %d: expected %d total launches, got %d", attempt, attempt, launchCount)
1084 }
1085 }
1086}
1087
1088// TestConflictsWaitDoesNotSpamCIPassedEvent verifies that polling repeatedly
1089// while a rebase is in flight (conflicts still present) does not re-emit the
1090// AgentCIPassed event on every poll.
1091func TestConflictsWaitDoesNotSpamCIPassedEvent(t *testing.T) {
1092 c, baseDir := newTestController(t)
1093 eventLog := event.NewLog(filepath.Join(baseDir, "session"))
1094
1095 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1096 return "agent-rebase", nil
1097 })
1098
1099 // Seed the PR in StageCIPending so the first poll's transition emits
1100 // AgentCIPassed exactly once when CI is found passing.
1101 c.mu.Lock()
1102 c.prStates["42"] = &PRPipelineState{
1103 PRNumber: "42",
1104 Stage: StageCIPending,
1105 }
1106 c.mu.Unlock()
1107
1108 statuses := map[string]*PRStatus{
1109 "42": {
1110 PRNumber: "42", State: "OPEN", CI: "passing",
1111 ReviewDecision: "", Conflicts: "yes", TargetRepo: "owner/repo",
1112 },
1113 }
1114
1115 // Initial poll dispatches rebase agent and emits AgentCIPassed once.
1116 c.HandleGHStatus(context.Background(), statuses, nil)
1117
1118 // Subsequent polls hit conflicts-wait (agent still running — unfinalized
1119 // run with a live pane is treated as running). Each must not re-emit
1120 // AgentCIPassed.
1121 runStates := []*run.State{
1122 {ID: "agent-rebase", TmuxPane: strPtr("%1")},
1123 }
1124 for i := 0; i < 5; i++ {
1125 c.HandleGHStatus(context.Background(), statuses, runStates)
1126 }
1127
1128 events, err := eventLog.Read()
1129 if err != nil {
1130 t.Fatalf("reading event log: %v", err)
1131 }
1132 ciPassedCount := 0
1133 for _, e := range events {
1134 if e.Type == event.AgentCIPassed {
1135 ciPassedCount++
1136 }
1137 }
1138 if ciPassedCount != 1 {
1139 t.Errorf("expected exactly 1 AgentCIPassed event, got %d (events: %v)", ciPassedCount, events)
1140 }
1141}
1142
1143func TestApprovedNoConflictsMerges(t *testing.T) {
1144 c, _ := newTestController(t)
1145 c.SetAutoMergeOnApproval(true)
1146
1147 launchCount := 0
1148 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1149 launchCount++
1150 return "agent-001", nil
1151 })
1152 mergeCount := 0
1153 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
1154 mergeCount++
1155 return nil
1156 })
1157
1158 statuses := map[string]*PRStatus{
1159 "42": {
1160 PRNumber: "42", State: "OPEN", CI: "passing",
1161 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
1162 },
1163 }
1164
1165 actions := c.HandleGHStatus(context.Background(), statuses, nil)
1166
1167 if launchCount != 0 {
1168 t.Errorf("expected no agent launch for conflict-free merge, got %d", launchCount)
1169 }
1170 if mergeCount != 1 {
1171 t.Errorf("expected 1 merge, got %d", mergeCount)
1172 }
1173
1174 hasMerge := false
1175 for _, a := range actions {
1176 if a.Type == "merge" {
1177 hasMerge = true
1178 }
1179 }
1180 if !hasMerge {
1181 t.Error("expected merge action")
1182 }
1183}
1184
1185func TestApprovedNoAutoMergeWhenDisabled(t *testing.T) {
1186 c, _ := newTestController(t)
1187 // autoMergeOnApproval defaults to false — do not set it
1188
1189 mergeCount := 0
1190 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
1191 mergeCount++
1192 return nil
1193 })
1194
1195 statuses := map[string]*PRStatus{
1196 "42": {
1197 PRNumber: "42", State: "OPEN", CI: "passing",
1198 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
1199 },
1200 }
1201
1202 actions := c.HandleGHStatus(context.Background(), statuses, nil)
1203
1204 if mergeCount != 0 {
1205 t.Errorf("expected no merge when auto_merge_on_approval is disabled, got %d", mergeCount)
1206 }
1207 for _, a := range actions {
1208 if a.Type == "merge" {
1209 t.Error("unexpected merge action when auto_merge_on_approval is disabled")
1210 }
1211 }
1212}
1213
1214func TestReviewThreadsResolvedAfterAgentCompletion(t *testing.T) {
1215 c, _ := newTestController(t)
1216
1217 // Track which threads were resolved.
1218 var resolvedThreads []string
1219 c.SetSnapshotThreads(func(repo, prNumber string) ([]string, error) {
1220 return []string{"RT_aaa", "RT_bbb"}, nil
1221 })
1222 c.SetResolveThread(func(threadID string) error {
1223 resolvedThreads = append(resolvedThreads, threadID)
1224 return nil
1225 })
1226 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1227 return "agent-fix", nil
1228 })
1229
1230 // Step 1: CHANGES_REQUESTED → dispatches fix agent, snapshots threads.
1231 statuses := map[string]*PRStatus{
1232 "42": {
1233 PRNumber: "42", State: "OPEN", CI: "passing",
1234 ReviewDecision: "CHANGES_REQUESTED", TargetRepo: "owner/repo",
1235 },
1236 }
1237 c.HandleGHStatus(context.Background(), statuses, nil)
1238
1239 state := c.PipelineStates()["42"]
1240 if len(state.PendingResolveThreadIDs) != 2 {
1241 t.Fatalf("expected 2 pending threads, got %d", len(state.PendingResolveThreadIDs))
1242 }
1243
1244 // Step 2: Agent completes (finalized with cost).
1245 cost := 1.0
1246 runStates := []*run.State{
1247 {ID: "agent-fix", TmuxPane: strPtr("%1"), CostUSD: &cost},
1248 }
1249 // CI now passing, review approved → the threads should be resolved.
1250 statuses["42"] = &PRStatus{
1251 PRNumber: "42", State: "OPEN", CI: "passing",
1252 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
1253 }
1254 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
1255 return nil
1256 })
1257 c.HandleGHStatus(context.Background(), statuses, runStates)
1258
1259 if len(resolvedThreads) != 2 {
1260 t.Errorf("expected 2 threads resolved, got %d: %v", len(resolvedThreads), resolvedThreads)
1261 }
1262 if resolvedThreads[0] != "RT_aaa" || resolvedThreads[1] != "RT_bbb" {
1263 t.Errorf("unexpected resolved threads: %v", resolvedThreads)
1264 }
1265
1266 // Pending threads should be cleared after resolution.
1267 state = c.PipelineStates()["42"]
1268 if state != nil && len(state.PendingResolveThreadIDs) != 0 {
1269 t.Errorf("expected pending threads cleared, got %d", len(state.PendingResolveThreadIDs))
1270 }
1271}
1272
1273// TestSnapshotThreadsUsesOwnerRepoSlugFromPRURL guards against issue where
1274// ActionSnapshotThreads was given PRStatus.TargetRepo, which is a canonical
1275// project short name (e.g. "klaus") for registered projects, not an owner/repo
1276// slug. defaultSnapshotThreads splits the value on "/" and would fail, silently
1277// breaking thread resolution. The descriptor must instead carry the owner/repo
1278// slug extracted from PRURL.
1279func TestSnapshotThreadsUsesOwnerRepoSlugFromPRURL(t *testing.T) {
1280 for _, tc := range []struct {
1281 name string
1282 reviewDecision string
1283 trusted bool
1284 }{
1285 {"changes-requested", "CHANGES_REQUESTED", false},
1286 {"trusted-comments", "", true},
1287 } {
1288 t.Run(tc.name, func(t *testing.T) {
1289 c, _ := newTestController(t)
1290
1291 var gotRepo string
1292 c.SetSnapshotThreads(func(repo, prNumber string) ([]string, error) {
1293 gotRepo = repo
1294 return nil, nil
1295 })
1296 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1297 return "agent-fix", nil
1298 })
1299
1300 statuses := map[string]*PRStatus{
1301 "42": {
1302 PRNumber: "42",
1303 State: "OPEN",
1304 CI: "passing",
1305 ReviewDecision: tc.reviewDecision,
1306 HasNewTrustedComments: tc.trusted,
1307 // TargetRepo is a project short name, NOT an owner/repo slug.
1308 TargetRepo: "klaus",
1309 PRURL: "https://github.com/maintainer/klaus/pull/42",
1310 },
1311 }
1312 c.HandleGHStatus(context.Background(), statuses, nil)
1313
1314 if gotRepo != "maintainer/klaus" {
1315 t.Errorf("snapshotThreads got repo %q, want owner/repo slug from PRURL %q", gotRepo, "maintainer/klaus")
1316 }
1317 if strings.Count(gotRepo, "/") != 1 {
1318 t.Errorf("snapshot repo %q is not a valid owner/repo slug (need exactly one '/')", gotRepo)
1319 }
1320 })
1321 }
1322}
1323
1324// TestDispatchRepoDerivesSlugFromPRURL covers the slug-extraction helper used to
1325// attach a real owner/repo to descriptors whose handlers treat Repo as a GitHub
1326// slug. status.TargetRepo may be a bare project short name (e.g. "klaus"), so the
1327// slug must come from the PR URL, falling back to TargetRepo only when the URL is
1328// unparseable. The parsing itself lives in github.OwnerRepoFromPRURL (the single
1329// source of truth, unit-tested in internal/github).
1330func TestDispatchRepoDerivesSlugFromPRURL(t *testing.T) {
1331 c, _ := newTestController(t)
1332 for _, tt := range []struct {
1333 name string
1334 status *PRStatus
1335 want string
1336 }{
1337 {"valid URL overrides bare short name", &PRStatus{PRURL: "https://github.com/maintainer/klaus/pull/270", TargetRepo: "klaus"}, "maintainer/klaus"},
1338 {"trailing slash", &PRStatus{PRURL: "https://github.com/maintainer/klaus/", TargetRepo: "klaus"}, "maintainer/klaus"},
1339 {"malformed URL falls back to TargetRepo", &PRStatus{PRURL: "not-a-url", TargetRepo: "owner/repo"}, "owner/repo"},
1340 {"empty URL falls back to TargetRepo", &PRStatus{PRURL: "", TargetRepo: "owner/repo"}, "owner/repo"},
1341 } {
1342 t.Run(tt.name, func(t *testing.T) {
1343 if got := dispatchRepo(c, tt.status); got != tt.want {
1344 t.Errorf("dispatchRepo() = %q, want %q", got, tt.want)
1345 }
1346 })
1347 }
1348}
1349
1350// TestMergeDescriptorUsesOwnerRepoSlug locks the audit fix: the ActionMergePR
1351// descriptor must carry the owner/repo slug derived from the PR URL, not the bare
1352// project short name in TargetRepo.
1353func TestMergeDescriptorUsesOwnerRepoSlug(t *testing.T) {
1354 c, _ := newTestController(t)
1355 c.SetAutoMergeOnApproval(true)
1356
1357 var mergeRepo string
1358 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
1359 mergeRepo = repo
1360 return nil
1361 })
1362
1363 statuses := map[string]*PRStatus{
1364 "270": {
1365 PRNumber: "270", State: "OPEN", CI: "passing",
1366 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "klaus",
1367 PRURL: "https://github.com/maintainer/klaus/pull/270",
1368 },
1369 }
1370
1371 c.HandleGHStatus(context.Background(), statuses, nil)
1372
1373 if mergeRepo != "maintainer/klaus" {
1374 t.Errorf("merge repo = %q, want maintainer/klaus", mergeRepo)
1375 }
1376}
1377
1378func TestReviewThreadResolutionFailureDoesNotBlock(t *testing.T) {
1379 c, _ := newTestController(t)
1380 c.SetAutoMergeOnApproval(true)
1381
1382 resolveCount := 0
1383 c.SetSnapshotThreads(func(repo, prNumber string) ([]string, error) {
1384 return []string{"RT_ok", "RT_fail", "RT_ok2"}, nil
1385 })
1386 c.SetResolveThread(func(threadID string) error {
1387 resolveCount++
1388 if threadID == "RT_fail" {
1389 return fmt.Errorf("permission denied")
1390 }
1391 return nil
1392 })
1393 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1394 return "agent-fix", nil
1395 })
1396 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
1397 return nil
1398 })
1399
1400 // Dispatch fix agent.
1401 statuses := map[string]*PRStatus{
1402 "42": {
1403 PRNumber: "42", State: "OPEN", CI: "passing",
1404 ReviewDecision: "CHANGES_REQUESTED", TargetRepo: "owner/repo",
1405 },
1406 }
1407 c.HandleGHStatus(context.Background(), statuses, nil)
1408
1409 // Agent completes.
1410 cost := 1.0
1411 runStates := []*run.State{
1412 {ID: "agent-fix", TmuxPane: strPtr("%1"), CostUSD: &cost},
1413 }
1414 statuses["42"] = &PRStatus{
1415 PRNumber: "42", State: "OPEN", CI: "passing",
1416 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
1417 }
1418 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
1419
1420 // All 3 threads should have been attempted.
1421 if resolveCount != 3 {
1422 t.Errorf("expected 3 resolve attempts, got %d", resolveCount)
1423 }
1424
1425 // Pipeline should continue (merge action present).
1426 hasMerge := false
1427 for _, a := range actions {
1428 if a.Type == "merge" {
1429 hasMerge = true
1430 }
1431 }
1432 if !hasMerge {
1433 t.Error("expected merge action despite resolution failure")
1434 }
1435}
1436
1437func TestTrustedCommentSnapshotsThreads(t *testing.T) {
1438 c, _ := newTestController(t)
1439
1440 var snapshotCalled bool
1441 c.SetSnapshotThreads(func(repo, prNumber string) ([]string, error) {
1442 snapshotCalled = true
1443 return []string{"RT_trusted"}, nil
1444 })
1445 c.SetResolveThread(func(threadID string) error {
1446 return nil
1447 })
1448 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1449 return "agent-trusted", nil
1450 })
1451
1452 statuses := map[string]*PRStatus{
1453 "42": {
1454 PRNumber: "42",
1455 State: "OPEN",
1456 CI: "passing",
1457 ReviewDecision: "",
1458 HasNewTrustedComments: true,
1459 TargetRepo: "owner/repo",
1460 },
1461 }
1462
1463 c.HandleGHStatus(context.Background(), statuses, nil)
1464
1465 if !snapshotCalled {
1466 t.Error("expected thread snapshot for trusted reviewer comment dispatch")
1467 }
1468
1469 state := c.PipelineStates()["42"]
1470 if len(state.PendingResolveThreadIDs) != 1 || state.PendingResolveThreadIDs[0] != "RT_trusted" {
1471 t.Errorf("expected 1 pending thread RT_trusted, got %v", state.PendingResolveThreadIDs)
1472 }
1473}
1474
1475func TestNoThreadResolutionWhileAgentRunning(t *testing.T) {
1476 c, _ := newTestController(t)
1477
1478 resolveCount := 0
1479 c.SetSnapshotThreads(func(repo, prNumber string) ([]string, error) {
1480 return []string{"RT_aaa"}, nil
1481 })
1482 c.SetResolveThread(func(threadID string) error {
1483 resolveCount++
1484 return nil
1485 })
1486 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1487 return "agent-fix", nil
1488 })
1489
1490 // Dispatch fix agent.
1491 statuses := map[string]*PRStatus{
1492 "42": {
1493 PRNumber: "42", State: "OPEN", CI: "passing",
1494 ReviewDecision: "CHANGES_REQUESTED", TargetRepo: "owner/repo",
1495 },
1496 }
1497 c.HandleGHStatus(context.Background(), statuses, nil)
1498
1499 // Agent still running.
1500 runStates := []*run.State{
1501 {ID: "agent-fix", TmuxPane: strPtr("%1")}, // running: no cost/duration
1502 }
1503 c.HandleGHStatus(context.Background(), statuses, runStates)
1504
1505 if resolveCount != 0 {
1506 t.Errorf("expected no thread resolution while agent running, got %d", resolveCount)
1507 }
1508}
1509
1510func TestDispatchCooldownPreventsRapidRedispatch(t *testing.T) {
1511 t.Run("CI failing", func(t *testing.T) {
1512 c, _ := newTestController(t)
1513
1514 launchCount := 0
1515 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1516 launchCount++
1517 return fmt.Sprintf("agent-%03d", launchCount), nil
1518 })
1519
1520 statuses := map[string]*PRStatus{
1521 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
1522 }
1523
1524 // First poll dispatches agent.
1525 c.HandleGHStatus(context.Background(), statuses, nil)
1526 if launchCount != 1 {
1527 t.Fatalf("expected 1 launch, got %d", launchCount)
1528 }
1529
1530 // Agent completes immediately.
1531 cost := 1.0
1532 runStates := []*run.State{
1533 {ID: "agent-001", TmuxPane: strPtr("%1"), CostUSD: &cost},
1534 }
1535
1536 // Second poll within cooldown — should NOT re-dispatch.
1537 c.HandleGHStatus(context.Background(), statuses, runStates)
1538 if launchCount != 1 {
1539 t.Errorf("expected cooldown to prevent re-dispatch, got %d launches", launchCount)
1540 }
1541
1542 // Simulate cooldown expiry.
1543 c.mu.Lock()
1544 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1545 c.mu.Unlock()
1546
1547 // Third poll after cooldown — should dispatch.
1548 c.HandleGHStatus(context.Background(), statuses, runStates)
1549 if launchCount != 2 {
1550 t.Errorf("expected dispatch after cooldown, got %d launches", launchCount)
1551 }
1552 })
1553
1554 t.Run("CHANGES_REQUESTED", func(t *testing.T) {
1555 c, _ := newTestController(t)
1556
1557 launchCount := 0
1558 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1559 launchCount++
1560 return fmt.Sprintf("agent-%03d", launchCount), nil
1561 })
1562
1563 statuses := map[string]*PRStatus{
1564 "42": {
1565 PRNumber: "42", State: "OPEN", CI: "passing",
1566 ReviewDecision: "CHANGES_REQUESTED", TargetRepo: "owner/repo",
1567 },
1568 }
1569
1570 // First poll dispatches.
1571 c.HandleGHStatus(context.Background(), statuses, nil)
1572 if launchCount != 1 {
1573 t.Fatalf("expected 1 launch, got %d", launchCount)
1574 }
1575
1576 // Agent completes.
1577 cost := 1.0
1578 runStates := []*run.State{
1579 {ID: "agent-001", TmuxPane: strPtr("%1"), CostUSD: &cost},
1580 }
1581
1582 // Second poll within cooldown — blocked.
1583 c.HandleGHStatus(context.Background(), statuses, runStates)
1584 if launchCount != 1 {
1585 t.Errorf("expected cooldown to prevent re-dispatch, got %d launches", launchCount)
1586 }
1587
1588 // Expire cooldown.
1589 c.mu.Lock()
1590 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1591 c.mu.Unlock()
1592
1593 // Third poll — allowed.
1594 c.HandleGHStatus(context.Background(), statuses, runStates)
1595 if launchCount != 2 {
1596 t.Errorf("expected dispatch after cooldown, got %d launches", launchCount)
1597 }
1598 })
1599
1600 t.Run("trusted comments", func(t *testing.T) {
1601 c, _ := newTestController(t)
1602
1603 launchCount := 0
1604 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1605 launchCount++
1606 return fmt.Sprintf("agent-%03d", launchCount), nil
1607 })
1608
1609 statuses := map[string]*PRStatus{
1610 "42": {
1611 PRNumber: "42",
1612 State: "OPEN",
1613 CI: "passing",
1614 ReviewDecision: "",
1615 HasNewTrustedComments: true,
1616 TargetRepo: "owner/repo",
1617 },
1618 }
1619
1620 // First poll dispatches.
1621 c.HandleGHStatus(context.Background(), statuses, nil)
1622 if launchCount != 1 {
1623 t.Fatalf("expected 1 launch, got %d", launchCount)
1624 }
1625
1626 // Agent completes.
1627 cost := 1.0
1628 runStates := []*run.State{
1629 {ID: "agent-001", TmuxPane: strPtr("%1"), CostUSD: &cost},
1630 }
1631
1632 // Second poll within cooldown — blocked.
1633 c.HandleGHStatus(context.Background(), statuses, runStates)
1634 if launchCount != 1 {
1635 t.Errorf("expected cooldown to prevent re-dispatch, got %d launches", launchCount)
1636 }
1637
1638 // Expire cooldown.
1639 c.mu.Lock()
1640 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1641 c.mu.Unlock()
1642
1643 // Third poll — allowed.
1644 c.HandleGHStatus(context.Background(), statuses, runStates)
1645 if launchCount != 2 {
1646 t.Errorf("expected dispatch after cooldown, got %d launches", launchCount)
1647 }
1648 })
1649}
1650
1651func TestCIFixAgentResumesFromLastAgent(t *testing.T) {
1652 c, _ := newTestController(t)
1653
1654 var capturedResume string
1655 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1656 capturedResume = resumeFrom
1657 return "agent-fix", nil
1658 })
1659
1660 // Seed pipeline state with a previous agent ID.
1661 c.mu.Lock()
1662 c.prStates["42"] = &PRPipelineState{
1663 PRNumber: "42",
1664 Stage: StageCIFailed,
1665 LastAgentID: "agent-original",
1666 }
1667 c.mu.Unlock()
1668
1669 statuses := map[string]*PRStatus{
1670 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
1671 }
1672
1673 c.HandleGHStatus(context.Background(), statuses, nil)
1674
1675 if capturedResume != "agent-original" {
1676 t.Errorf("expected resumeFrom=%q, got %q", "agent-original", capturedResume)
1677 }
1678}
1679
1680func TestReviewFixAgentResumesFromLastAgent(t *testing.T) {
1681 c, _ := newTestController(t)
1682
1683 var capturedResume string
1684 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1685 capturedResume = resumeFrom
1686 return "agent-review-fix", nil
1687 })
1688
1689 c.mu.Lock()
1690 c.prStates["10"] = &PRPipelineState{
1691 PRNumber: "10",
1692 Stage: StageCIPassed,
1693 LastAgentID: "agent-prev",
1694 }
1695 c.mu.Unlock()
1696
1697 statuses := map[string]*PRStatus{
1698 "10": {
1699 PRNumber: "10", State: "OPEN", CI: "passing",
1700 ReviewDecision: "CHANGES_REQUESTED", TargetRepo: "owner/repo",
1701 },
1702 }
1703
1704 c.HandleGHStatus(context.Background(), statuses, nil)
1705
1706 if capturedResume != "agent-prev" {
1707 t.Errorf("expected resumeFrom=%q, got %q", "agent-prev", capturedResume)
1708 }
1709}
1710
1711func TestFirstAgentDispatchHasEmptyResume(t *testing.T) {
1712 c, _ := newTestController(t)
1713
1714 var capturedResume string
1715 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1716 capturedResume = resumeFrom
1717 return "agent-first", nil
1718 })
1719
1720 statuses := map[string]*PRStatus{
1721 "7": {PRNumber: "7", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
1722 }
1723
1724 c.HandleGHStatus(context.Background(), statuses, nil)
1725
1726 if capturedResume != "" {
1727 t.Errorf("expected empty resumeFrom for first dispatch, got %q", capturedResume)
1728 }
1729}
1730
1731func TestFixAgentCircuitBreaker(t *testing.T) {
1732 c, _ := newTestController(t)
1733
1734 launchCount := 0
1735 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1736 launchCount++
1737 return fmt.Sprintf("agent-%03d", launchCount), nil
1738 })
1739
1740 statuses := map[string]*PRStatus{
1741 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
1742 }
1743
1744 // Dispatch 1: initial fix agent.
1745 c.HandleGHStatus(context.Background(), statuses, nil)
1746 if launchCount != 1 {
1747 t.Fatalf("expected 1 launch, got %d", launchCount)
1748 }
1749
1750 for attempt := 2; attempt <= 3; attempt++ {
1751 // Simulate agent completion (finalized with cost).
1752 cost := 1.0
1753 runStates := []*run.State{
1754 {ID: fmt.Sprintf("agent-%03d", attempt-1), TmuxPane: strPtr("%1"), CostUSD: &cost},
1755 }
1756
1757 // Expire the dispatch cooldown.
1758 c.mu.Lock()
1759 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1760 c.mu.Unlock()
1761
1762 // CI still failing -> should re-dispatch.
1763 c.HandleGHStatus(context.Background(), statuses, runStates)
1764 if launchCount != attempt {
1765 t.Fatalf("attempt %d: expected %d launches, got %d", attempt, attempt, launchCount)
1766 }
1767 }
1768
1769 // Now we've dispatched 3 agents. Simulate agent 3 completing.
1770 cost := 1.0
1771 runStates := []*run.State{
1772 {ID: "agent-003", TmuxPane: strPtr("%1"), CostUSD: &cost},
1773 }
1774
1775 c.mu.Lock()
1776 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1777 c.mu.Unlock()
1778
1779 // CI still failing -> circuit breaker should trip; no 4th dispatch.
1780 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
1781 if launchCount != 3 {
1782 t.Errorf("expected circuit breaker to stop at 3 launches, got %d", launchCount)
1783 }
1784
1785 // Should have an error action.
1786 hasError := false
1787 for _, a := range actions {
1788 if a.Type == "error" && strings.Contains(a.Detail, "fix attempts failed") {
1789 hasError = true
1790 }
1791 }
1792 if !hasError {
1793 t.Error("expected error action from circuit breaker, got:", actions)
1794 }
1795
1796 // Stage should be stalled.
1797 states := c.PipelineStates()
1798 if states["42"].Stage != StageStalled {
1799 t.Errorf("expected stalled stage, got %s", states["42"].Stage)
1800 }
1801}
1802
1803func TestFixAgentCircuitBreakerResetOnCIPass(t *testing.T) {
1804 c, _ := newTestController(t)
1805
1806 launchCount := 0
1807 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1808 launchCount++
1809 return fmt.Sprintf("agent-%03d", launchCount), nil
1810 })
1811
1812 statuses := map[string]*PRStatus{
1813 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
1814 }
1815
1816 // Dispatch 2 fix agents (below the limit).
1817 c.HandleGHStatus(context.Background(), statuses, nil)
1818 cost := 1.0
1819 runStates := []*run.State{
1820 {ID: "agent-001", TmuxPane: strPtr("%1"), CostUSD: &cost},
1821 }
1822 c.mu.Lock()
1823 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1824 c.mu.Unlock()
1825 c.HandleGHStatus(context.Background(), statuses, runStates)
1826
1827 if launchCount != 2 {
1828 t.Fatalf("expected 2 launches, got %d", launchCount)
1829 }
1830
1831 // CI passes — should reset FixAttempts.
1832 statuses["42"] = &PRStatus{PRNumber: "42", State: "OPEN", CI: "passing", TargetRepo: "owner/repo"}
1833 c.HandleGHStatus(context.Background(), statuses, nil)
1834
1835 states := c.PipelineStates()
1836 if states["42"].FixAttempts != 0 {
1837 t.Errorf("expected FixAttempts reset to 0 after CI pass, got %d", states["42"].FixAttempts)
1838 }
1839}
1840
1841func TestFixAgentCircuitBreakerResetOnNewPush(t *testing.T) {
1842 c, _ := newTestController(t)
1843
1844 launchCount := 0
1845 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1846 launchCount++
1847 return fmt.Sprintf("agent-%03d", launchCount), nil
1848 })
1849
1850 statuses := map[string]*PRStatus{
1851 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
1852 }
1853
1854 // Dispatch 3 fix agents to trip the circuit breaker.
1855 c.HandleGHStatus(context.Background(), statuses, nil)
1856 for i := 2; i <= 3; i++ {
1857 cost := 1.0
1858 runStates := []*run.State{
1859 {ID: fmt.Sprintf("agent-%03d", i-1), TmuxPane: strPtr("%1"), CostUSD: &cost},
1860 }
1861 c.mu.Lock()
1862 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1863 c.mu.Unlock()
1864 c.HandleGHStatus(context.Background(), statuses, runStates)
1865 }
1866
1867 // Trip the breaker.
1868 cost := 1.0
1869 runStates := []*run.State{
1870 {ID: "agent-003", TmuxPane: strPtr("%1"), CostUSD: &cost},
1871 }
1872 c.mu.Lock()
1873 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
1874 c.mu.Unlock()
1875 c.HandleGHStatus(context.Background(), statuses, runStates)
1876
1877 if c.PipelineStates()["42"].Stage != StageStalled {
1878 t.Fatalf("expected stalled, got %s", c.PipelineStates()["42"].Stage)
1879 }
1880
1881 // Simulate new push: CI goes to pending.
1882 statuses["42"] = &PRStatus{PRNumber: "42", State: "OPEN", CI: "pending", TargetRepo: "owner/repo"}
1883 c.HandleGHStatus(context.Background(), statuses, nil)
1884
1885 states := c.PipelineStates()
1886 if states["42"].FixAttempts != 0 {
1887 t.Errorf("expected FixAttempts reset to 0 after new push (CI pending), got %d", states["42"].FixAttempts)
1888 }
1889 if states["42"].Stage != StageCIPending {
1890 t.Errorf("expected stage to reset to ci_pending after new push, got %s", states["42"].Stage)
1891 }
1892
1893 // CI fails again — should be able to dispatch again.
1894 statuses["42"] = &PRStatus{PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"}
1895 c.HandleGHStatus(context.Background(), statuses, nil)
1896
1897 if launchCount != 4 {
1898 t.Errorf("expected 4th launch after circuit breaker reset, got %d", launchCount)
1899 }
1900}
1901
1902func TestKlausApprovalTriggersAutoMerge(t *testing.T) {
1903 c, _ := newTestController(t)
1904 c.SetAutoMergeOnApproval(true)
1905
1906 launchCount := 0
1907 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1908 launchCount++
1909 return "agent-001", nil
1910 })
1911 mergeCount := 0
1912 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
1913 mergeCount++
1914 return nil
1915 })
1916
1917 // CI passing, no GitHub review, but klaus internal approval is set.
1918 statuses := map[string]*PRStatus{
1919 "42": {
1920 PRNumber: "42", State: "OPEN", CI: "passing",
1921 ReviewDecision: "", Conflicts: "none", TargetRepo: "owner/repo",
1922 },
1923 }
1924
1925 approved := true
1926 pr := "42"
1927 runStates := []*run.State{
1928 {ID: "run-001", PR: &pr, Approved: &approved},
1929 }
1930
1931 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
1932
1933 if launchCount != 0 {
1934 t.Errorf("expected no agent launch, got %d", launchCount)
1935 }
1936 if mergeCount != 1 {
1937 t.Errorf("expected 1 merge from klaus approval, got %d", mergeCount)
1938 }
1939
1940 hasMerge := false
1941 for _, a := range actions {
1942 if a.Type == "merge" {
1943 hasMerge = true
1944 }
1945 }
1946 if !hasMerge {
1947 t.Error("expected merge action from klaus internal approval")
1948 }
1949}
1950
1951func TestChangesRequestedOverridesKlausApproval(t *testing.T) {
1952 c, _ := newTestController(t)
1953 c.SetAutoMergeOnApproval(true)
1954
1955 mergeCount := 0
1956 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
1957 mergeCount++
1958 return nil
1959 })
1960
1961 launchCount := 0
1962 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
1963 launchCount++
1964 return "agent-fix", nil
1965 })
1966
1967 // CI passing, CHANGES_REQUESTED on GitHub, but klaus internal approval is set.
1968 statuses := map[string]*PRStatus{
1969 "42": {
1970 PRNumber: "42", State: "OPEN", CI: "passing",
1971 ReviewDecision: "CHANGES_REQUESTED", Conflicts: "none", TargetRepo: "owner/repo",
1972 },
1973 }
1974
1975 approved := true
1976 pr := "42"
1977 runStates := []*run.State{
1978 {ID: "run-001", PR: &pr, Approved: &approved},
1979 }
1980
1981 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
1982
1983 if mergeCount != 0 {
1984 t.Errorf("expected no merge when CHANGES_REQUESTED, got %d merges", mergeCount)
1985 }
1986 if launchCount != 1 {
1987 t.Errorf("expected fix agent dispatch for CHANGES_REQUESTED, got %d launches", launchCount)
1988 }
1989
1990 hasLaunch := false
1991 for _, a := range actions {
1992 if a.Type == "launch" {
1993 hasLaunch = true
1994 }
1995 }
1996 if !hasLaunch {
1997 t.Error("expected launch action for review fix agent")
1998 }
1999}
2000
2001func TestRunStateMatchesPR(t *testing.T) {
2002 pr := "42"
2003 tests := []struct {
2004 name string
2005 state *run.State
2006 want bool
2007 }{
2008 {"match by PR field", &run.State{PR: &pr}, true},
2009 {"match by PRURL", &run.State{PRURL: strPtr("https://github.com/o/r/pull/42")}, true},
2010 {"match by PRURL with trailing slash", &run.State{PRURL: strPtr("https://github.com/o/r/pull/42/")}, true},
2011 {"no match different PR", &run.State{PRURL: strPtr("https://github.com/o/r/pull/421")}, false},
2012 {"no match nil fields", &run.State{}, false},
2013 }
2014 for _, tt := range tests {
2015 t.Run(tt.name, func(t *testing.T) {
2016 got := runStateMatchesPR(tt.state, "42")
2017 if got != tt.want {
2018 t.Errorf("runStateMatchesPR() = %v, want %v", got, tt.want)
2019 }
2020 })
2021 }
2022}
2023
2024func TestKlausApprovalWithConflictsDispatchesRebase(t *testing.T) {
2025 c, _ := newTestController(t)
2026
2027 mergeCount := 0
2028 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
2029 mergeCount++
2030 return nil
2031 })
2032
2033 var launchedPrompt string
2034 launchCount := 0
2035 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2036 launchedPrompt = prompt
2037 launchCount++
2038 return "agent-rebase", nil
2039 })
2040
2041 // CI passing, no GitHub review decision, but klaus internal approval is set.
2042 statuses := map[string]*PRStatus{
2043 "42": {
2044 PRNumber: "42", State: "OPEN", CI: "passing",
2045 ReviewDecision: "", Conflicts: "yes", TargetRepo: "owner/repo",
2046 },
2047 }
2048
2049 approved := true
2050 pr := "42"
2051 runStates := []*run.State{
2052 {ID: "run-001", PR: &pr, Approved: &approved},
2053 }
2054
2055 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
2056
2057 if mergeCount != 0 {
2058 t.Error("should not merge when conflicts exist")
2059 }
2060
2061 if launchCount != 1 {
2062 t.Errorf("expected 1 rebase agent launch, got %d", launchCount)
2063 }
2064 if launchedPrompt == "" {
2065 t.Error("expected rebase agent dispatch for klaus-approved PR with conflicts")
2066 }
2067 if !strings.Contains(launchedPrompt, "merge conflicts") {
2068 t.Errorf("expected rebase prompt, got %q", launchedPrompt)
2069 }
2070
2071 hasLaunch := false
2072 for _, a := range actions {
2073 if a.Type == "launch" && strings.Contains(a.Detail, "Rebase") {
2074 hasLaunch = true
2075 }
2076 }
2077 if !hasLaunch {
2078 t.Errorf("expected rebase launch action, got %v", actions)
2079 }
2080
2081 states := c.PipelineStates()
2082 if states["42"].Stage != StageNeedsRebase {
2083 t.Errorf("expected stage needs_rebase, got %s", states["42"].Stage)
2084 }
2085}
2086
2087func TestIsRunning_DeadPane(t *testing.T) {
2088 c, _ := newTestController(t)
2089 pane := "dead-pane"
2090
2091 // Pane does not exist (agent crashed without finalizing).
2092 c.SetTmuxDeps(run.TmuxDeps{
2093 PaneExists: func(string) bool { return false },
2094 PaneIsDead: func(string) bool { return true },
2095 PaneIsIdle: func(string) bool { return false },
2096 })
2097
2098 s := &run.State{TmuxPane: &pane}
2099 if c.isRunning(s) {
2100 t.Error("expected isRunning=false when pane does not exist")
2101 }
2102
2103 // Pane exists and is alive (agent still running).
2104 c.SetTmuxDeps(run.TmuxDeps{
2105 PaneExists: func(string) bool { return true },
2106 PaneIsDead: func(string) bool { return false },
2107 PaneIsIdle: func(string) bool { return false },
2108 })
2109
2110 if !c.isRunning(s) {
2111 t.Error("expected isRunning=true when pane exists and is alive")
2112 }
2113
2114 // No tmux pane at all.
2115 s2 := &run.State{}
2116 if c.isRunning(s2) {
2117 t.Error("expected isRunning=false when TmuxPane is nil")
2118 }
2119}
2120
2121func TestMergedStageIsTerminal(t *testing.T) {
2122 c, _ := newTestController(t)
2123 c.SetAutoMergeOnApproval(true)
2124
2125 launchCount := 0
2126 mergeCount := 0
2127 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2128 launchCount++
2129 return "agent-001", nil
2130 })
2131 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
2132 mergeCount++
2133 return nil
2134 })
2135
2136 // Seed a PR directly in StageMerged (simulates post-merge state).
2137 c.mu.Lock()
2138 c.prStates["38"] = &PRPipelineState{
2139 PRNumber: "38",
2140 Stage: StageMerged,
2141 SeenCommentIDs: make(map[int64]bool),
2142 }
2143 c.mu.Unlock()
2144
2145 // Even with CI passing and approved status, merged should not transition.
2146 statuses := map[string]*PRStatus{
2147 "38": {
2148 PRNumber: "38", State: "OPEN", CI: "passing",
2149 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
2150 },
2151 }
2152
2153 c.HandleGHStatus(context.Background(), statuses, nil)
2154
2155 state := c.PipelineStates()["38"]
2156 if state.Stage != StageMerged {
2157 t.Errorf("expected merged to remain terminal, got stage %s", state.Stage)
2158 }
2159 if launchCount != 0 {
2160 t.Errorf("expected no agent launch for merged PR, got %d", launchCount)
2161 }
2162 if mergeCount != 0 {
2163 t.Errorf("expected no merge attempt for merged PR, got %d", mergeCount)
2164 }
2165}
2166
2167func TestSessionResumeSeedsFromGitHubStatus(t *testing.T) {
2168 c, _ := newTestController(t)
2169
2170 launchCount := 0
2171 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2172 launchCount++
2173 return "agent-001", nil
2174 })
2175
2176 // Simulate session resume: prStates is empty, but PR is already passing CI.
2177 statuses := map[string]*PRStatus{
2178 "50": {PRNumber: "50", State: "OPEN", CI: "passing", TargetRepo: "owner/repo"},
2179 }
2180
2181 c.HandleGHStatus(context.Background(), statuses, nil)
2182
2183 state := c.PipelineStates()["50"]
2184 if state == nil {
2185 t.Fatal("expected PR 50 to be tracked")
2186 }
2187 // A passing PR on session resume should seed as ci_passed, not ci_pending.
2188 if state.Stage != StageCIPassed {
2189 t.Errorf("expected ci_passed on resume with passing CI, got %s", state.Stage)
2190 }
2191 // Should not have dispatched any agent (CI is passing, no review issues).
2192 if launchCount != 0 {
2193 t.Errorf("expected no agent launch for passing PR on resume, got %d", launchCount)
2194 }
2195}
2196
2197func TestSessionResumeFailingCISeedsCorrectly(t *testing.T) {
2198 c, _ := newTestController(t)
2199
2200 launchCount := 0
2201 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2202 launchCount++
2203 return "agent-fix", nil
2204 })
2205
2206 // Session resume with a failing CI PR.
2207 statuses := map[string]*PRStatus{
2208 "51": {PRNumber: "51", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
2209 }
2210
2211 c.HandleGHStatus(context.Background(), statuses, nil)
2212
2213 state := c.PipelineStates()["51"]
2214 if state == nil {
2215 t.Fatal("expected PR 51 to be tracked")
2216 }
2217 if state.Stage != StageCIFailed {
2218 t.Errorf("expected ci_failed after handling failing CI, got %s", state.Stage)
2219 }
2220 if launchCount != 1 {
2221 t.Errorf("expected 1 agent launch for failing CI, got %d", launchCount)
2222 }
2223}
2224
2225// TestCoordinatorLaunchedPRFixSuppresses verifies the controller does NOT
2226// dispatch a competing fix agent when a coordinator-launched pr-fix run
2227// (e.g. from `klaus launch --pr 42 ...`) is already active on the same PR.
2228// This is the real-world incident on flux PR #66, where intermediate commits
2229// during a multi-step refactor failed CI, the pipeline dispatched its own
2230// fix agent, and the two agents revert-warred.
2231func TestCoordinatorLaunchedPRFixSuppresses(t *testing.T) {
2232 c, _ := newTestController(t)
2233
2234 launchCount := 0
2235 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2236 launchCount++
2237 return "pipeline-agent", nil
2238 })
2239
2240 // Coordinator-launched pr-fix run: Type set, running pane, PRURL matches PR 42.
2241 // Note: the pipeline never recorded it in ps.LastAgentID.
2242 runStates := []*run.State{
2243 {
2244 ID: "coord-fix-001",
2245 Type: "pr-fix",
2246 PRURL: strPtr("https://github.com/owner/repo/pull/42"),
2247 TmuxPane: strPtr("%7"),
2248 },
2249 }
2250
2251 statuses := map[string]*PRStatus{
2252 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
2253 }
2254
2255 c.HandleGHStatus(context.Background(), statuses, runStates)
2256
2257 if launchCount != 0 {
2258 t.Errorf("expected pipeline to suppress dispatch while coordinator pr-fix run is active, got %d launches", launchCount)
2259 }
2260}
2261
2262// TestCoordinatorLaunchedPRFixSuppressesViaPRField covers the case where the
2263// coordinator-launched run has its PR field populated (rather than PRURL).
2264// Both forms should trigger the guard.
2265func TestCoordinatorLaunchedPRFixSuppressesViaPRField(t *testing.T) {
2266 c, _ := newTestController(t)
2267
2268 launchCount := 0
2269 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2270 launchCount++
2271 return "pipeline-agent", nil
2272 })
2273
2274 runStates := []*run.State{
2275 {
2276 ID: "coord-fix-002",
2277 Type: "pr-fix",
2278 PR: strPtr("42"),
2279 TmuxPane: strPtr("%8"),
2280 },
2281 }
2282
2283 statuses := map[string]*PRStatus{
2284 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
2285 }
2286
2287 c.HandleGHStatus(context.Background(), statuses, runStates)
2288
2289 if launchCount != 0 {
2290 t.Errorf("expected suppression via PR field match, got %d launches", launchCount)
2291 }
2292}
2293
2294// TestCoordinatorLaunchedPRFixFinishedAllowsDispatch verifies that once the
2295// coordinator-launched pr-fix run completes (finalized, pane idle), the
2296// pipeline is free to dispatch its own fix agent on a CI failure.
2297func TestCoordinatorLaunchedPRFixFinishedAllowsDispatch(t *testing.T) {
2298 c, _ := newTestController(t)
2299
2300 launchCount := 0
2301 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2302 launchCount++
2303 return "pipeline-agent", nil
2304 })
2305
2306 // Coordinator run is finalized (CostUSD set) — IsAgentRunning treats this
2307 // as not running when the pane is idle (testTmuxDeps reports PaneIsIdle=true).
2308 cost := 0.42
2309 runStates := []*run.State{
2310 {
2311 ID: "coord-fix-001",
2312 Type: "pr-fix",
2313 PRURL: strPtr("https://github.com/owner/repo/pull/42"),
2314 TmuxPane: strPtr("%7"),
2315 CostUSD: &cost,
2316 },
2317 }
2318
2319 statuses := map[string]*PRStatus{
2320 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
2321 }
2322
2323 c.HandleGHStatus(context.Background(), statuses, runStates)
2324
2325 if launchCount != 1 {
2326 t.Errorf("expected dispatch after coordinator pr-fix run finished, got %d launches", launchCount)
2327 }
2328}
2329
2330// TestCoordinatorLaunchedNonPRFixDoesNotSuppress ensures only pr-fix runs trip
2331// the guard — other run types on the same PR shouldn't block the pipeline.
2332func TestCoordinatorLaunchedNonPRFixDoesNotSuppress(t *testing.T) {
2333 c, _ := newTestController(t)
2334
2335 launchCount := 0
2336 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2337 launchCount++
2338 return "pipeline-agent", nil
2339 })
2340
2341 runStates := []*run.State{
2342 {
2343 ID: "coord-other",
2344 Type: "session", // not a pr-fix
2345 PR: strPtr("42"),
2346 TmuxPane: strPtr("%9"),
2347 },
2348 }
2349
2350 statuses := map[string]*PRStatus{
2351 "42": {PRNumber: "42", State: "OPEN", CI: "failing", TargetRepo: "owner/repo"},
2352 }
2353
2354 c.HandleGHStatus(context.Background(), statuses, runStates)
2355
2356 if launchCount != 1 {
2357 t.Errorf("expected dispatch when only non-pr-fix runs are active, got %d launches", launchCount)
2358 }
2359}
2360
2361func strPtr(s string) *string {
2362 return &s
2363}
2364
2365func TestBudgetPausedLabelDrivesStage(t *testing.T) {
2366 c, _ := newTestController(t)
2367
2368 launchCount := 0
2369 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2370 launchCount++
2371 return "agent-x", nil
2372 })
2373
2374 // PR has the klaus:budget-paused label. Even though CI is failing, the
2375 // pause transition should win and no fix-agent should be dispatched.
2376 statuses := map[string]*PRStatus{
2377 "42": {
2378 PRNumber: "42",
2379 State: "OPEN",
2380 CI: "failing",
2381 TargetRepo: "owner/repo",
2382 Labels: []string{"klaus:budget-paused"},
2383 },
2384 }
2385
2386 actions := c.HandleGHStatus(context.Background(), statuses, nil)
2387
2388 if launchCount != 0 {
2389 t.Errorf("expected no agent dispatch for paused PR, got %d launches", launchCount)
2390 }
2391 if len(actions) != 0 {
2392 t.Errorf("expected no actions for paused PR, got %v", actions)
2393 }
2394 if got := c.PipelineStates()["42"].Stage; got != StageBudgetPaused {
2395 t.Errorf("expected stage budget_paused, got %s", got)
2396 }
2397}
2398
2399func TestBudgetPausedTransitionsToCIFailedOnceLabelCleared(t *testing.T) {
2400 c, _ := newTestController(t)
2401 launchCount := 0
2402 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2403 launchCount++
2404 return "agent-fix", nil
2405 })
2406
2407 // Step 1: paused.
2408 statuses := map[string]*PRStatus{
2409 "42": {
2410 PRNumber: "42",
2411 State: "OPEN",
2412 CI: "failing",
2413 TargetRepo: "owner/repo",
2414 Labels: []string{"klaus:budget-paused"},
2415 },
2416 }
2417 c.HandleGHStatus(context.Background(), statuses, nil)
2418 if c.PipelineStates()["42"].Stage != StageBudgetPaused {
2419 t.Fatalf("setup: expected budget_paused, got %s", c.PipelineStates()["42"].Stage)
2420 }
2421
2422 // Step 2: label cleared → pipeline should resume normal handling
2423 // (dispatch a fix agent for failing CI).
2424 statuses["42"] = &PRStatus{
2425 PRNumber: "42",
2426 State: "OPEN",
2427 CI: "failing",
2428 TargetRepo: "owner/repo",
2429 Labels: nil,
2430 }
2431 c.HandleGHStatus(context.Background(), statuses, nil)
2432
2433 if launchCount != 1 {
2434 t.Errorf("expected fix agent dispatch after label clear, got %d launches", launchCount)
2435 }
2436 if got := c.PipelineStates()["42"].Stage; got != StageCIFailed {
2437 t.Errorf("expected stage ci_failed after label clear, got %s", got)
2438 }
2439}
2440
2441func TestBudgetPausedEmitsEventOnTransition(t *testing.T) {
2442 c, _ := newTestController(t)
2443 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2444 return "agent-x", nil
2445 })
2446
2447 statuses := map[string]*PRStatus{
2448 "42": {
2449 PRNumber: "42",
2450 State: "OPEN",
2451 CI: "passing",
2452 TargetRepo: "owner/repo",
2453 Labels: []string{"klaus:budget-paused"},
2454 },
2455 }
2456 c.HandleGHStatus(context.Background(), statuses, nil)
2457
2458 // Idempotent: calling again should not double-emit (we just verify the
2459 // stage stays the same — events.jsonl assertion is more fragile to set
2460 // up in this test harness, so we rely on the stage as the proxy).
2461 c.HandleGHStatus(context.Background(), statuses, nil)
2462
2463 if got := c.PipelineStates()["42"].Stage; got != StageBudgetPaused {
2464 t.Errorf("expected stage budget_paused, got %s", got)
2465 }
2466}
2467
2468func TestStageLabelBudgetPaused(t *testing.T) {
2469 if got := StageLabel(StageBudgetPaused); got != "budget paused, awaiting decision" {
2470 t.Errorf("StageLabel(budget_paused) = %q", got)
2471 }
2472}
2473
2474// TestTrustedCommentsCircuitBreaker reproduces the production redispatch loop
2475// (2026-07-06): a trusted review that never reads as addressed — the fix
2476// agent pushes no commit, so HasNewTrustedComments never clears — must stop
2477// dispatching after maxFixAttempts agents instead of looping forever.
2478func TestTrustedCommentsCircuitBreaker(t *testing.T) {
2479 c, _ := newTestController(t)
2480
2481 launchCount := 0
2482 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2483 launchCount++
2484 return fmt.Sprintf("agent-%03d", launchCount), nil
2485 })
2486 c.SetSnapshotThreads(func(repo, prNumber string) ([]string, error) {
2487 return nil, nil
2488 })
2489
2490 statuses := map[string]*PRStatus{
2491 "42": {
2492 PRNumber: "42",
2493 State: "OPEN",
2494 CI: "passing",
2495 ReviewDecision: "",
2496 HasNewTrustedComments: true,
2497 TargetRepo: "owner/repo",
2498 PRURL: "https://github.com/owner/repo/pull/42",
2499 },
2500 }
2501
2502 // Dispatch 1: initial review-fix agent.
2503 c.HandleGHStatus(context.Background(), statuses, nil)
2504 if launchCount != 1 {
2505 t.Fatalf("expected 1 launch, got %d", launchCount)
2506 }
2507
2508 cost := 1.0
2509 for attempt := 2; attempt <= 3; attempt++ {
2510 // Previous agent completed without pushing: comments still unaddressed.
2511 runStates := []*run.State{
2512 {ID: fmt.Sprintf("agent-%03d", attempt-1), TmuxPane: strPtr("%1"), CostUSD: &cost},
2513 }
2514
2515 // Poll while the dispatch cooldown is still active: must hold
2516 // review_pending (not fall back to awaiting-review, which would hide
2517 // the completed attempt from the counter) and must not dispatch.
2518 c.HandleGHStatus(context.Background(), statuses, runStates)
2519 if launchCount != attempt-1 {
2520 t.Fatalf("attempt %d: dispatched during cooldown, got %d launches", attempt, launchCount)
2521 }
2522 if st := c.PipelineStates()["42"].Stage; st != StageReviewPending {
2523 t.Fatalf("attempt %d: expected review_pending while cooling down, got %s", attempt, st)
2524 }
2525
2526 // Expire the cooldown; comments still unaddressed -> redispatch.
2527 c.mu.Lock()
2528 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
2529 c.mu.Unlock()
2530 c.HandleGHStatus(context.Background(), statuses, runStates)
2531 if launchCount != attempt {
2532 t.Fatalf("attempt %d: expected %d launches, got %d", attempt, attempt, launchCount)
2533 }
2534 }
2535
2536 // Agent 3 completes without pushing; the breaker must trip: no 4th dispatch.
2537 runStates := []*run.State{
2538 {ID: "agent-003", TmuxPane: strPtr("%1"), CostUSD: &cost},
2539 }
2540 c.mu.Lock()
2541 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
2542 c.mu.Unlock()
2543 actions := c.HandleGHStatus(context.Background(), statuses, runStates)
2544
2545 if launchCount != 3 {
2546 t.Errorf("expected circuit breaker to stop at 3 launches, got %d", launchCount)
2547 }
2548 hasError := false
2549 for _, a := range actions {
2550 if a.Type == "error" && strings.Contains(a.Detail, "review fix attempts failed") {
2551 hasError = true
2552 }
2553 }
2554 if !hasError {
2555 t.Error("expected error action from review fix circuit breaker, got:", actions)
2556 }
2557 if st := c.PipelineStates()["42"].Stage; st != StageStalled {
2558 t.Errorf("expected stalled stage, got %s", st)
2559 }
2560
2561 // Subsequent polls stay stalled silently: no dispatch, no repeated error.
2562 c.mu.Lock()
2563 c.prStates["42"].LastDispatchAt = time.Now().Add(-61 * time.Second)
2564 c.mu.Unlock()
2565 actions = c.HandleGHStatus(context.Background(), statuses, runStates)
2566 if launchCount != 3 {
2567 t.Errorf("expected no dispatch while stalled, got %d launches", launchCount)
2568 }
2569 if len(actions) != 0 {
2570 t.Errorf("expected no actions while stalled, got %v", actions)
2571 }
2572}
2573
2574// TestTrustedCommentsBreakerResetsWhenAddressed verifies the breaker is not a
2575// dead end: once the comments read as addressed (a new push advanced the
2576// watermark), the attempt budget resets and a later trusted review can
2577// dispatch again.
2578func TestTrustedCommentsBreakerResetsWhenAddressed(t *testing.T) {
2579 c, _ := newTestController(t)
2580
2581 launchCount := 0
2582 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2583 launchCount++
2584 return fmt.Sprintf("agent-%03d", launchCount), nil
2585 })
2586 c.SetSnapshotThreads(func(repo, prNumber string) ([]string, error) {
2587 return nil, nil
2588 })
2589
2590 // Seed a PR stalled by the review-fix breaker.
2591 c.mu.Lock()
2592 c.prStates["42"] = &PRPipelineState{
2593 PRNumber: "42",
2594 Stage: StageStalled,
2595 ReviewFixAttempts: maxFixAttempts,
2596 SeenCommentIDs: make(map[int64]bool),
2597 }
2598 c.mu.Unlock()
2599
2600 // Comments addressed -> awaiting review, counter reset.
2601 statuses := map[string]*PRStatus{
2602 "42": {
2603 PRNumber: "42", State: "OPEN", CI: "passing",
2604 HasNewTrustedComments: false, TargetRepo: "owner/repo",
2605 },
2606 }
2607 c.HandleGHStatus(context.Background(), statuses, nil)
2608
2609 state := c.PipelineStates()["42"]
2610 if state.ReviewFixAttempts != 0 {
2611 t.Errorf("expected ReviewFixAttempts reset to 0 once comments are addressed, got %d", state.ReviewFixAttempts)
2612 }
2613 if launchCount != 0 {
2614 t.Fatalf("expected no launch while comments are addressed, got %d", launchCount)
2615 }
2616
2617 // A fresh trusted review with inline comments dispatches again.
2618 statuses["42"].HasNewTrustedComments = true
2619 c.HandleGHStatus(context.Background(), statuses, nil)
2620 if launchCount != 1 {
2621 t.Errorf("expected dispatch after breaker reset, got %d launches", launchCount)
2622 }
2623}
2624
2625// ── Auto-merge retry loop (issue #292) ──────────────────────────────────
2626
2627// readEvents returns every event the controller emitted to its event log.
2628// newTestController roots the log at <dir>/session.
2629func readEvents(t *testing.T, dir string) []event.Event {
2630 t.Helper()
2631 evts, err := event.NewLog(filepath.Join(dir, "session")).Read()
2632 if err != nil {
2633 t.Fatalf("reading event log: %v", err)
2634 }
2635 return evts
2636}
2637
2638func countEvents(evts []event.Event, typ string) int {
2639 n := 0
2640 for _, e := range evts {
2641 if e.Type == typ {
2642 n++
2643 }
2644 }
2645 return n
2646}
2647
2648// expireMergeBackoff rewinds the last auto-merge attempt so the next poll is
2649// past the retry window, standing in for waiting out mergeRetryBackoff.
2650func expireMergeBackoff(c *Controller, prNumber string) {
2651 c.mu.Lock()
2652 defer c.mu.Unlock()
2653 if ps := c.prStates[prNumber]; ps != nil {
2654 ps.LastMergeAttemptAt = time.Now().Add(-2 * mergeRetryBackoff)
2655 }
2656}
2657
2658// TestApprovedBehindPRDoesNotFloodApprovedEvents reproduces site #734
2659// (2026-08-22): an approved, CI-green, conflict-free PR that is behind its
2660// base branch used to re-emit pr:approved on every ~3s poll, flooding
2661// `klaus watch`. The event must be emitted once per approval edge.
2662func TestApprovedBehindPRDoesNotFloodApprovedEvents(t *testing.T) {
2663 c, dir := newTestController(t)
2664 c.SetAutoMergeOnApproval(true)
2665
2666 updateCount := 0
2667 c.SetUpdateBranch(func(ctx context.Context, repo, prNumber string) error {
2668 updateCount++
2669 return nil
2670 })
2671 mergeCount := 0
2672 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
2673 mergeCount++
2674 return nil
2675 })
2676
2677 // Behind by 1: mergeable, but an up-to-date-branch protection rule
2678 // rejects the merge until the branch is updated.
2679 statuses := map[string]*PRStatus{
2680 "734": {
2681 PRNumber: "734", State: "OPEN", CI: "passing",
2682 ReviewDecision: "APPROVED", Conflicts: "none", BehindBy: 1,
2683 TargetRepo: "owner/repo",
2684 },
2685 }
2686
2687 for i := 0; i < 20; i++ {
2688 c.HandleGHStatus(context.Background(), statuses, nil)
2689 }
2690
2691 if got := countEvents(readEvents(t, dir), event.PRApproved); got != 1 {
2692 t.Errorf("expected exactly 1 pr:approved event across 20 polls, got %d", got)
2693 }
2694 if updateCount != 1 {
2695 t.Errorf("expected 1 branch update (backoff gates the rest), got %d", updateCount)
2696 }
2697 if mergeCount != 0 {
2698 t.Errorf("expected no merge attempt while the PR is behind, got %d", mergeCount)
2699 }
2700}
2701
2702// TestBehindPRUpdatesBranchThenMerges covers the happy path for a behind PR:
2703// update the branch, and once GitHub reports it caught up, merge it.
2704func TestBehindPRUpdatesBranchThenMerges(t *testing.T) {
2705 c, _ := newTestController(t)
2706 c.SetAutoMergeOnApproval(true)
2707
2708 var updatedPR, updatedRepo string
2709 c.SetUpdateBranch(func(ctx context.Context, repo, prNumber string) error {
2710 updatedPR, updatedRepo = prNumber, repo
2711 return nil
2712 })
2713 mergeCount := 0
2714 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
2715 mergeCount++
2716 return nil
2717 })
2718
2719 status := &PRStatus{
2720 PRNumber: "734", State: "OPEN", CI: "passing",
2721 ReviewDecision: "APPROVED", Conflicts: "none", BehindBy: 1,
2722 TargetRepo: "owner/repo",
2723 }
2724 statuses := map[string]*PRStatus{"734": status}
2725
2726 actions := c.HandleGHStatus(context.Background(), statuses, nil)
2727
2728 if updatedPR != "734" || updatedRepo != "owner/repo" {
2729 t.Errorf("expected branch update for PR #734 in owner/repo, got %q in %q", updatedPR, updatedRepo)
2730 }
2731 if mergeCount != 0 {
2732 t.Fatalf("expected no merge on the poll that updates the branch, got %d", mergeCount)
2733 }
2734 hasUpdate := false
2735 for _, a := range actions {
2736 if a.Type == "update-branch" {
2737 hasUpdate = true
2738 }
2739 }
2740 if !hasUpdate {
2741 t.Errorf("expected an update-branch action, got %v", actions)
2742 }
2743
2744 // GitHub now reports the branch caught up; the merge lands on a later poll.
2745 status.BehindBy = 0
2746 expireMergeBackoff(c, "734")
2747 c.HandleGHStatus(context.Background(), statuses, nil)
2748
2749 if mergeCount != 1 {
2750 t.Errorf("expected 1 merge once the PR is no longer behind, got %d", mergeCount)
2751 }
2752 if got := c.PipelineStates()["734"].Stage; got != StageMerged {
2753 t.Errorf("expected stage merged, got %s", got)
2754 }
2755}
2756
2757// TestFailingMergeBacksOffThenStalls is the other half of #292: a merge that
2758// can never succeed must not be retried on every poll, and must stall loudly
2759// once the attempt budget is spent instead of looping forever.
2760func TestFailingMergeBacksOffThenStalls(t *testing.T) {
2761 c, dir := newTestController(t)
2762 c.SetAutoMergeOnApproval(true)
2763
2764 mergeCount := 0
2765 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
2766 mergeCount++
2767 return fmt.Errorf("Pull request is not mergeable")
2768 })
2769
2770 statuses := map[string]*PRStatus{
2771 "734": {
2772 PRNumber: "734", State: "OPEN", CI: "passing",
2773 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
2774 },
2775 }
2776
2777 // First attempt, then a burst of polls inside the backoff window.
2778 for i := 0; i < 10; i++ {
2779 c.HandleGHStatus(context.Background(), statuses, nil)
2780 }
2781 if mergeCount != 1 {
2782 t.Fatalf("expected the backoff to hold the retry count at 1, got %d", mergeCount)
2783 }
2784 if got := c.PipelineStates()["734"].Stage; got != StageApproved {
2785 t.Errorf("expected a failed merge to fall back to approved, got %s", got)
2786 }
2787
2788 // Wait out the backoff for each remaining attempt in the budget.
2789 for i := 0; i < maxMergeAttempts-1; i++ {
2790 expireMergeBackoff(c, "734")
2791 c.HandleGHStatus(context.Background(), statuses, nil)
2792 }
2793 if mergeCount != maxMergeAttempts {
2794 t.Fatalf("expected %d merge attempts, got %d", maxMergeAttempts, mergeCount)
2795 }
2796 if got := c.PipelineStates()["734"].Stage; got != StageStalled {
2797 t.Fatalf("expected stage stalled after the budget is spent, got %s", got)
2798 }
2799
2800 // Budget spent: further polls neither retry nor re-notify.
2801 for i := 0; i < 10; i++ {
2802 expireMergeBackoff(c, "734")
2803 c.HandleGHStatus(context.Background(), statuses, nil)
2804 }
2805 if mergeCount != maxMergeAttempts {
2806 t.Errorf("expected no merge attempts past the budget, got %d", mergeCount)
2807 }
2808
2809 evts := readEvents(t, dir)
2810 if got := countEvents(evts, event.PipelineStalled); got != 1 {
2811 t.Errorf("expected exactly 1 pipeline:stalled event, got %d", got)
2812 }
2813 if got := countEvents(evts, event.PRApproved); got != 1 {
2814 t.Errorf("expected exactly 1 pr:approved event, got %d", got)
2815 }
2816 for _, e := range evts {
2817 if e.Type != event.PipelineStalled {
2818 continue
2819 }
2820 if reason, _ := e.Data["reason"].(string); !strings.Contains(reason, "auto-merge failed") {
2821 t.Errorf("expected a stall reason naming auto-merge, got %q", reason)
2822 }
2823 }
2824}
2825
2826// TestFailingBranchUpdateStalls covers the same circuit breaker on the
2827// behind-PR path: a branch update that keeps failing must stall rather than
2828// retry forever.
2829func TestFailingBranchUpdateStalls(t *testing.T) {
2830 c, dir := newTestController(t)
2831 c.SetAutoMergeOnApproval(true)
2832
2833 updateCount := 0
2834 c.SetUpdateBranch(func(ctx context.Context, repo, prNumber string) error {
2835 updateCount++
2836 return fmt.Errorf("merge conflict between base and head")
2837 })
2838
2839 statuses := map[string]*PRStatus{
2840 "734": {
2841 PRNumber: "734", State: "OPEN", CI: "passing",
2842 ReviewDecision: "APPROVED", Conflicts: "none", BehindBy: 1,
2843 TargetRepo: "owner/repo",
2844 },
2845 }
2846
2847 for i := 0; i < maxMergeAttempts+5; i++ {
2848 expireMergeBackoff(c, "734")
2849 c.HandleGHStatus(context.Background(), statuses, nil)
2850 }
2851
2852 if updateCount != maxMergeAttempts {
2853 t.Errorf("expected %d branch update attempts, got %d", maxMergeAttempts, updateCount)
2854 }
2855 if got := c.PipelineStates()["734"].Stage; got != StageStalled {
2856 t.Errorf("expected stage stalled, got %s", got)
2857 }
2858 if got := countEvents(readEvents(t, dir), event.PipelineStalled); got != 1 {
2859 t.Errorf("expected exactly 1 pipeline:stalled event, got %d", got)
2860 }
2861}
2862
2863// TestReApprovalResetsMergeBudgetWithoutReEmitting: losing and regaining
2864// approval gives auto-merge a fresh attempt budget, but pr:approved is
2865// reported once per PR, so it doesn't fire again.
2866func TestReApprovalResetsMergeBudgetWithoutReEmitting(t *testing.T) {
2867 c, dir := newTestController(t)
2868 c.SetAutoMergeOnApproval(true)
2869
2870 mergeCount := 0
2871 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
2872 mergeCount++
2873 return fmt.Errorf("Pull request is not mergeable")
2874 })
2875 c.SetLaunchAgent(func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
2876 return "agent-001", nil
2877 })
2878
2879 status := &PRStatus{
2880 PRNumber: "734", State: "OPEN", CI: "passing",
2881 ReviewDecision: "APPROVED", Conflicts: "none", TargetRepo: "owner/repo",
2882 }
2883 statuses := map[string]*PRStatus{"734": status}
2884
2885 c.HandleGHStatus(context.Background(), statuses, nil)
2886 if mergeCount != 1 {
2887 t.Fatalf("expected 1 merge attempt, got %d", mergeCount)
2888 }
2889
2890 // Approval is dismissed by a new push, then re-granted.
2891 status.ReviewDecision = "REVIEW_REQUIRED"
2892 c.HandleGHStatus(context.Background(), statuses, nil)
2893 status.ReviewDecision = "APPROVED"
2894 c.HandleGHStatus(context.Background(), statuses, nil)
2895
2896 if mergeCount != 2 {
2897 t.Errorf("expected re-approval to reset the merge budget and retry immediately, got %d attempts", mergeCount)
2898 }
2899 if got := countEvents(readEvents(t, dir), event.PRApproved); got != 1 {
2900 t.Errorf("expected 1 pr:approved event (once per PR), got %d", got)
2901 }
2902}
2903
2904// TestBranchUpdateDoesNotSpendMergeBudget keeps catching up with a moving base
2905// branch from eating the auto-merge retry budget — a PR behind a busy base
2906// must still get its full set of merge attempts once it is caught up.
2907func TestBranchUpdateDoesNotSpendMergeBudget(t *testing.T) {
2908 c, _ := newTestController(t)
2909 c.SetAutoMergeOnApproval(true)
2910
2911 updateCount := 0
2912 c.SetUpdateBranch(func(ctx context.Context, repo, prNumber string) error {
2913 updateCount++
2914 return nil
2915 })
2916 mergeCount := 0
2917 c.SetMergePRs(func(ctx context.Context, repo string, prNumbers []string) error {
2918 mergeCount++
2919 return fmt.Errorf("Pull request is not mergeable")
2920 })
2921
2922 status := &PRStatus{
2923 PRNumber: "734", State: "OPEN", CI: "passing",
2924 ReviewDecision: "APPROVED", Conflicts: "none", BehindBy: 1,
2925 TargetRepo: "owner/repo",
2926 }
2927 statuses := map[string]*PRStatus{"734": status}
2928
2929 // The base branch moves twice while CI re-runs.
2930 for i := 0; i < 2; i++ {
2931 expireMergeBackoff(c, "734")
2932 c.HandleGHStatus(context.Background(), statuses, nil)
2933 }
2934 if updateCount != 2 {
2935 t.Fatalf("expected 2 branch updates, got %d", updateCount)
2936 }
2937
2938 // Caught up: the merge budget is untouched, so all attempts are available.
2939 status.BehindBy = 0
2940 for i := 0; i < maxMergeAttempts+2; i++ {
2941 expireMergeBackoff(c, "734")
2942 c.HandleGHStatus(context.Background(), statuses, nil)
2943 }
2944 if mergeCount != maxMergeAttempts {
2945 t.Errorf("expected %d merge attempts after catching up, got %d", maxMergeAttempts, mergeCount)
2946 }
2947 if got := c.PipelineStates()["734"].Stage; got != StageStalled {
2948 t.Errorf("expected stage stalled once the merge budget is spent, got %s", got)
2949 }
2950}