gunk-dev/the-valley

pipeline_test.go

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