gunk-dev/the-valley

transitions.go

sourcec14b0e68e9c3main's published tip history
34.5 KiB
1package pipeline
2
3import (
4 "fmt"
5 "strings"
6 "time"
7
8 "the-valley/flow/internal/event"
9 ghutil "the-valley/flow/internal/github"
10 "the-valley/flow/internal/review"
11 "the-valley/flow/internal/run"
12)
13
14// transition defines a single state-machine rule. Guards are evaluated
15// top-to-bottom; the first matching transition fires. An Apply function
16// mutates pipeline state and returns any actions/descriptors.
17type transition struct {
18 Name string
19 Guard func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) bool
20 Apply func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor)
21}
22
23// transitions is the ordered list of pipeline rules. First match wins.
24var transitions = []transition{
25 // ── Terminal: merged PRs must not be re-processed ───────────────────
26 {
27 Name: "terminal/merged",
28 Guard: inStage(StageMerged),
29 Apply: func(_ *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
30 return nil, nil
31 },
32 },
33
34 // ── A failed dispatch waits, stalled, for new inputs ────────────────
35 {
36 Name: "dispatch-failed/await-new-inputs",
37 Guard: dispatchFailedOnTheseInputs,
38 Apply: func(_ *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
39 return nil, nil
40 },
41 },
42
43 // ── Budget-paused (handled before CI rules so the dashboard surfaces
44 // the pause regardless of CI state) ────────────────────────────────
45
46 {
47 Name: "budget-paused/await-decision",
48 Guard: allOf(
49 isBudgetPausedDraft,
50 agentNotRunning,
51 ),
52 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
53 if ps.Stage != StageBudgetPaused {
54 c.emitEvent(ps.PRNumber, event.AgentPaused, map[string]interface{}{
55 "pr_number": ps.PRNumber,
56 "pr_url": status.PRURL,
57 "reason": "budget_exhausted",
58 })
59 }
60 ps.Stage = StageBudgetPaused
61 return nil, nil
62 },
63 },
64 {
65 Name: "budget-paused/noop-while-agent-running",
66 Guard: isBudgetPausedDraft,
67 Apply: func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
68 // An agent is running against the paused PR (klaus launch --pr).
69 // Hold the budget_paused stage until the agent's _finalize
70 // clears the label.
71 if ps.Stage != StageBudgetPaused {
72 ps.Stage = StageBudgetPaused
73 }
74 return nil, nil
75 },
76 },
77
78 // ── CI failing ──────────────────────────────────────────────────────
79
80 {
81 Name: "ci-failing/circuit-breaker-already-stalled",
82 Guard: allOf(
83 ciFailing,
84 fixAttemptsExhausted,
85 agentNotRunning,
86 inStage(StageStalled),
87 ),
88 Apply: func(_ *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
89 return nil, nil
90 },
91 },
92 {
93 Name: "ci-failing/circuit-breaker-trip",
94 Guard: allOf(
95 ciFailing,
96 fixAttemptsExhausted,
97 agentNotRunning,
98 ),
99 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
100 c.stall(ps, status.PRURL, fmt.Sprintf("%d CI fix attempts failed", ps.FixAttempts))
101 c.logger.Warn("fix agent circuit breaker tripped",
102 "pr", ps.PRNumber,
103 "attempts", ps.FixAttempts,
104 )
105 return []Action{{
106 Type: "error",
107 Detail: fmt.Sprintf("PR #%s: %d fix attempts failed, stopping", ps.PRNumber, ps.FixAttempts),
108 }}, nil
109 },
110 },
111 {
112 Name: "ci-failing/dispatch-fix-agent",
113 Guard: allOf(
114 ciFailing,
115 notInStageWhileRunning(StageCIFailed),
116 agentNotRunning,
117 cooldownExpired,
118 ),
119 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
120 // Count a failed fix attempt when a previous agent finished but CI is still failing.
121 if ps.Stage == StageCIFailed && ps.LastAgentID != "" {
122 ps.FixAttempts++
123 }
124
125 // Re-check circuit breaker after incrementing.
126 if ps.FixAttempts >= maxFixAttempts {
127 c.stall(ps, status.PRURL, fmt.Sprintf("%d CI fix attempts failed", ps.FixAttempts))
128 c.logger.Warn("fix agent circuit breaker tripped",
129 "pr", ps.PRNumber,
130 "attempts", ps.FixAttempts,
131 )
132 return []Action{{
133 Type: "error",
134 Detail: fmt.Sprintf("PR #%s: %d fix attempts failed, stopping", ps.PRNumber, ps.FixAttempts),
135 }}, nil
136 }
137
138 var descs []ActionDescriptor
139 descs = append(descs, ActionDescriptor{
140 Type: ActionCleanupWorktrees,
141 PRNumber: ps.PRNumber,
142 RunStates: runStates,
143 })
144
145 prompt := fmt.Sprintf(
146 "CI is failing on PR #%s. Diagnose the failures and push fixes. Check `gh pr checks %s` for details and `gh run view <run-id> --log-failed` for error output.",
147 ps.PRNumber, ps.PRNumber,
148 )
149 ps.pendingLaunchDetail = fmt.Sprintf("CI fix agent for PR #%s", ps.PRNumber)
150 descs = append(descs, ActionDescriptor{
151 Type: ActionLaunchAgent,
152 PRNumber: ps.PRNumber,
153 Repo: status.TargetRepo,
154 Prompt: prompt,
155 ResumeFrom: ps.LastAgentID,
156 Reason: event.DispatchCIFix,
157 })
158
159 ps.Stage = StageCIFailed
160 c.emitEvent(ps.PRNumber, event.AgentCIFailed, map[string]interface{}{
161 "pr_number": ps.PRNumber,
162 "pr_url": status.PRURL,
163 })
164 return nil, descs
165 },
166 },
167 {
168 Name: "ci-failing/update-stage",
169 Guard: allOf(
170 ciFailing,
171 notInStageWhileRunning(StageCIFailed),
172 ),
173 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
174 if ps.Stage != StageCIFailed {
175 c.emitEvent(ps.PRNumber, event.AgentCIFailed, map[string]interface{}{
176 "pr_number": ps.PRNumber,
177 "pr_url": status.PRURL,
178 })
179 }
180 ps.Stage = StageCIFailed
181 return nil, nil
182 },
183 },
184 {
185 Name: "ci-failing/noop-already-handling",
186 Guard: ciFailing,
187 Apply: func(_ *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
188 return nil, nil
189 },
190 },
191
192 // ── CI passing + conflicts → rebase ─────────────────────────────────
193
194 {
195 Name: "ci-passing/rebase-circuit-breaker-already-stalled",
196 Guard: allOf(
197 ciPassing,
198 hasConflicts,
199 rebaseAttemptsExhausted,
200 agentNotRunning,
201 inStage(StageStalled),
202 ),
203 Apply: func(_ *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
204 return nil, nil
205 },
206 },
207 {
208 Name: "ci-passing/conflicts-dispatch-rebase",
209 Guard: allOf(
210 ciPassing,
211 hasConflicts,
212 agentNotRunning,
213 cooldownExpired,
214 ),
215 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
216 emitCIPassedIfNeeded(c, ps, status)
217
218 // CI is now passing — any prior CI-fix attempts no longer count against
219 // the rebase agent's budget. RebaseAttempts is tracked separately.
220 ps.FixAttempts = 0
221
222 // Count a failed rebase attempt when a previous agent finished but conflicts persist.
223 if ps.Stage == StageNeedsRebase && ps.LastAgentID != "" {
224 ps.RebaseAttempts++
225 }
226
227 // Re-check rebase circuit breaker after incrementing.
228 if ps.RebaseAttempts >= maxFixAttempts {
229 c.stall(ps, status.PRURL, fmt.Sprintf("%d rebase attempts failed", ps.RebaseAttempts))
230 c.logger.Warn("rebase agent circuit breaker tripped",
231 "pr", ps.PRNumber,
232 "attempts", ps.RebaseAttempts,
233 )
234 return []Action{{
235 Type: "error",
236 Detail: fmt.Sprintf("PR #%s: %d rebase attempts failed, stopping", ps.PRNumber, ps.RebaseAttempts),
237 }}, nil
238 }
239
240 var descs []ActionDescriptor
241 descs = append(descs, ActionDescriptor{
242 Type: ActionCleanupWorktrees,
243 PRNumber: ps.PRNumber,
244 RunStates: runStates,
245 })
246 prompt := fmt.Sprintf(
247 "PR #%s has merge conflicts with the base branch. Rebase onto main, resolve all conflicts, and push. Run tests after resolving.",
248 ps.PRNumber,
249 )
250 ps.Stage = StageNeedsRebase
251 ps.pendingLaunchDetail = fmt.Sprintf("Rebase agent for PR #%s", ps.PRNumber)
252 descs = append(descs, ActionDescriptor{
253 Type: ActionLaunchAgent,
254 PRNumber: ps.PRNumber,
255 Repo: status.TargetRepo,
256 Prompt: prompt,
257 ResumeFrom: ps.LastAgentID,
258 Reason: event.DispatchConflictFix,
259 })
260 return nil, descs
261 },
262 },
263 {
264 Name: "ci-passing/conflicts-wait",
265 Guard: allOf(
266 ciPassing,
267 hasConflicts,
268 ),
269 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
270 emitCIPassedIfNeeded(c, ps, status)
271 // Move stage out of CI-failed/pending stages so emitCIPassedIfNeeded
272 // doesn't fire on every poll while the rebase dispatch is gated on
273 // cooldown or an in-flight agent. Preserve Stalled so the circuit
274 // breaker remains observable.
275 if ps.Stage != StageStalled && ps.Stage != StageNeedsRebase {
276 ps.Stage = StageNeedsRebase
277 }
278 return nil, nil
279 },
280 },
281
282 // ── CI passing + approved + no conflicts → merge ────────────────────
283
284 {
285 Name: "ci-passing/approved-merge-exhausted",
286 Guard: allOf(
287 ciPassing,
288 isApproved,
289 noConflicts,
290 autoMergeEnabled,
291 mergeBudgetExhausted,
292 ),
293 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
294 approvedBookkeeping(c, ps, status, runStates)
295 // stall() is edge-triggered, so the poll that spends the last
296 // attempt emits pipeline:stalled once and later polls are silent.
297 if status.BehindBy > 0 {
298 c.stall(ps, status.PRURL, fmt.Sprintf("branch update failed after %d attempts", ps.BranchUpdateAttempts))
299 } else {
300 c.stall(ps, status.PRURL, fmt.Sprintf("auto-merge failed after %d attempts", ps.MergeAttempts))
301 }
302 return nil, nil
303 },
304 },
305 {
306 Name: "ci-passing/approved-behind-update-branch",
307 Guard: allOf(
308 ciPassing,
309 isApproved,
310 noConflicts,
311 autoMergeEnabled,
312 isBehind,
313 mergeBackoffExpired,
314 ),
315 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
316 approvedBookkeeping(c, ps, status, runStates)
317
318 // The PR is mergeable but its head lacks commits from the base
319 // branch, which an up-to-date-branch protection rule rejects.
320 // Update the branch first; the merge happens on a later poll once
321 // BehindBy is back to 0 and CI has re-run.
322 ps.BranchUpdateAttempts++
323 ps.LastMergeAttemptAt = time.Now()
324 c.logger.Info("updating behind PR branch before auto-merge",
325 "pr", ps.PRNumber,
326 "behind", status.BehindBy,
327 "attempt", ps.BranchUpdateAttempts,
328 )
329 return nil, []ActionDescriptor{{
330 Type: ActionUpdateBranch,
331 PRNumber: ps.PRNumber,
332 Repo: dispatchRepo(c, status),
333 }}
334 },
335 },
336 {
337 Name: "ci-passing/approved-auto-merge",
338 Guard: allOf(
339 ciPassing,
340 isApproved,
341 noConflicts,
342 autoMergeEnabled,
343 notBehind,
344 mergeBackoffExpired,
345 ),
346 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
347 approvedBookkeeping(c, ps, status, runStates)
348
349 ps.MergeAttempts++
350 ps.LastMergeAttemptAt = time.Now()
351 ps.Stage = StageMerging
352 return nil, []ActionDescriptor{{
353 Type: ActionMergePR,
354 PRNumber: ps.PRNumber,
355 Repo: dispatchRepo(c, status),
356 PRNumbers: []string{ps.PRNumber},
357 }}
358 },
359 },
360 // Also the resting state for an approved PR waiting out the auto-merge
361 // backoff between attempts.
362 {
363 Name: "ci-passing/approved-no-auto-merge",
364 Guard: allOf(
365 ciPassing,
366 isApproved,
367 ),
368 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
369 approvedBookkeeping(c, ps, status, runStates)
370 return nil, nil
371 },
372 },
373
374 // ── CI passing + changes requested ──────────────────────────────────
375
376 {
377 Name: "ci-passing/changes-requested-dispatch",
378 Guard: allOf(
379 ciPassing,
380 changesRequested,
381 agentNotRunning,
382 cooldownExpired,
383 ),
384 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
385 ps.FixAttempts = 0
386 ps.RebaseAttempts = 0
387 emitCIPassedIfNeeded(c, ps, status)
388
389 var descs []ActionDescriptor
390 descs = append(descs, ActionDescriptor{
391 Type: ActionCleanupWorktrees,
392 PRNumber: ps.PRNumber,
393 RunStates: runStates,
394 })
395 descs = append(descs, ActionDescriptor{
396 Type: ActionSnapshotThreads,
397 PRNumber: ps.PRNumber,
398 Repo: dispatchRepo(c, status),
399 })
400
401 prompt := reviewFixPrompt(
402 fmt.Sprintf("PR #%s in %s has changes requested by reviewers.", ps.PRNumber, status.TargetRepo),
403 ps.PRNumber,
404 )
405 ps.pendingLaunchDetail = fmt.Sprintf("Review fix agent for PR #%s", ps.PRNumber)
406 ps.Stage = StageReviewPending
407 descs = append(descs, ActionDescriptor{
408 Type: ActionLaunchAgent,
409 PRNumber: ps.PRNumber,
410 Repo: status.TargetRepo,
411 Prompt: prompt,
412 ResumeFrom: ps.LastAgentID,
413 Reason: event.DispatchReviewFix,
414 })
415 return nil, descs
416 },
417 },
418 {
419 Name: "ci-passing/changes-requested-wait",
420 Guard: allOf(
421 ciPassing,
422 changesRequested,
423 ),
424 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
425 ps.FixAttempts = 0
426 ps.RebaseAttempts = 0
427 emitCIPassedIfNeeded(c, ps, status)
428 return nil, nil
429 },
430 },
431
432 // ── CI passing + trusted comments ───────────────────────────────────
433
434 {
435 Name: "ci-passing/trusted-comments-circuit-breaker-already-stalled",
436 Guard: allOf(
437 ciPassing,
438 hasTrustedComments,
439 reviewFixAttemptsExhausted,
440 agentNotRunning,
441 inStage(StageStalled),
442 ),
443 Apply: func(_ *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
444 return nil, nil
445 },
446 },
447 {
448 Name: "ci-passing/trusted-comments-circuit-breaker-trip",
449 Guard: allOf(
450 ciPassing,
451 hasTrustedComments,
452 reviewFixAttemptsExhausted,
453 agentNotRunning,
454 ),
455 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
456 c.stall(ps, status.PRURL, fmt.Sprintf("%d review fix attempts failed", ps.ReviewFixAttempts))
457 c.logger.Warn("review fix agent circuit breaker tripped",
458 "pr", ps.PRNumber,
459 "attempts", ps.ReviewFixAttempts,
460 )
461 return []Action{{
462 Type: "error",
463 Detail: fmt.Sprintf("PR #%s: %d review fix attempts failed, stopping", ps.PRNumber, ps.ReviewFixAttempts),
464 }}, nil
465 },
466 },
467 {
468 Name: "ci-passing/trusted-comments-dispatch",
469 Guard: allOf(
470 ciPassing,
471 hasTrustedComments,
472 agentNotRunning,
473 cooldownExpired,
474 ),
475 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
476 ps.FixAttempts = 0
477 ps.RebaseAttempts = 0
478 emitCIPassedIfNeeded(c, ps, status)
479
480 // Count a failed attempt when a previous review-fix agent finished
481 // but the trusted comments are still unaddressed (no new commit
482 // advanced the watermark).
483 if ps.Stage == StageReviewPending && ps.LastAgentID != "" {
484 ps.ReviewFixAttempts++
485 }
486
487 // Re-check circuit breaker after incrementing.
488 if ps.ReviewFixAttempts >= maxFixAttempts {
489 c.stall(ps, status.PRURL, fmt.Sprintf("%d review fix attempts failed", ps.ReviewFixAttempts))
490 c.logger.Warn("review fix agent circuit breaker tripped",
491 "pr", ps.PRNumber,
492 "attempts", ps.ReviewFixAttempts,
493 )
494 return []Action{{
495 Type: "error",
496 Detail: fmt.Sprintf("PR #%s: %d review fix attempts failed, stopping", ps.PRNumber, ps.ReviewFixAttempts),
497 }}, nil
498 }
499
500 var descs []ActionDescriptor
501 descs = append(descs, ActionDescriptor{
502 Type: ActionSnapshotThreads,
503 PRNumber: ps.PRNumber,
504 Repo: dispatchRepo(c, status),
505 })
506
507 prompt := reviewFixPrompt(
508 fmt.Sprintf("PR #%s in %s has review comments from a trusted reviewer that need to be addressed.", ps.PRNumber, status.TargetRepo),
509 ps.PRNumber,
510 )
511 ps.pendingLaunchDetail = fmt.Sprintf("Review fix agent for PR #%s (trusted reviewer)", ps.PRNumber)
512 ps.Stage = StageReviewPending
513 descs = append(descs, ActionDescriptor{
514 Type: ActionLaunchAgent,
515 PRNumber: ps.PRNumber,
516 Repo: status.TargetRepo,
517 Prompt: prompt,
518 ResumeFrom: ps.LastAgentID,
519 Reason: event.DispatchReviewCommentFix,
520 })
521 return nil, descs
522 },
523 },
524 {
525 Name: "ci-passing/trusted-comments-wait",
526 Guard: allOf(
527 ciPassing,
528 hasTrustedComments,
529 ),
530 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
531 ps.FixAttempts = 0
532 ps.RebaseAttempts = 0
533 // Emit CI-passed only when arriving from a CI stage. Unlike
534 // emitCIPassedIfNeeded, StageReviewPending is excluded because this
535 // transition holds that stage across polls while the dispatch above
536 // is gated on cooldown or an in-flight agent — the hold is what lets
537 // the dispatch's attempt counter recognize a re-dispatch (the
538 // awaiting-review transition below would otherwise reset the stage
539 // to ci_passed and emit a spurious awaiting-approval event).
540 if ps.Stage == StageCIFailed || ps.Stage == StageCIPending {
541 c.emitEvent(ps.PRNumber, event.AgentCIPassed, map[string]interface{}{
542 "pr_number": ps.PRNumber,
543 "pr_url": status.PRURL,
544 })
545 ps.Stage = StageCIPassed
546 }
547 return nil, nil
548 },
549 },
550
551 // ── CI passing + awaiting review ────────────────────────────────────
552
553 {
554 Name: "ci-passing/awaiting-review",
555 Guard: allOf(
556 ciPassing,
557 notInStages(StageApproved, StageMerging),
558 agentNotRunning,
559 ),
560 Apply: func(c *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
561 ps.FixAttempts = 0
562 ps.RebaseAttempts = 0
563 // Reaching here means no trusted comments are pending (the
564 // trusted-comments transitions above match first otherwise), so
565 // any prior review-fix attempts were addressed.
566 ps.ReviewFixAttempts = 0
567 emitCIPassedIfNeeded(c, ps, status)
568 if ps.Stage != StageCIPassed {
569 c.emitEvent(ps.PRNumber, event.PRAwaitingApproval, map[string]interface{}{
570 "pr_number": ps.PRNumber,
571 "pr_url": status.PRURL,
572 })
573 }
574 ps.Stage = StageCIPassed
575 return nil, nil
576 },
577 },
578
579 // CI passing catch-all (agent running, or already approved/merging with no action needed).
580 {
581 Name: "ci-passing/noop",
582 Guard: ciPassing,
583 Apply: func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
584 ps.FixAttempts = 0
585 ps.RebaseAttempts = 0
586 // No trusted comments pending here (the trusted-comments-wait
587 // transition matches first otherwise).
588 ps.ReviewFixAttempts = 0
589 return nil, nil
590 },
591 },
592
593 // ── CI pending / unknown ────────────────────────────────────────────
594
595 {
596 Name: "ci-pending/reset-from-failed",
597 Guard: allOf(
598 ciPendingOrUnknown,
599 inStages(StageCIFailed, StageStalled),
600 ),
601 Apply: func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
602 ps.FixAttempts = 0
603 ps.RebaseAttempts = 0
604 ps.ReviewFixAttempts = 0
605 if ps.Stage == StageStalled {
606 ps.Stage = StageCIPending
607 }
608 return nil, nil
609 },
610 },
611 {
612 Name: "ci-pending/init",
613 Guard: allOf(
614 ciPendingOrUnknown,
615 inStages("", StageStalled),
616 ),
617 Apply: func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
618 ps.Stage = StageCIPending
619 return nil, nil
620 },
621 },
622 {
623 Name: "ci-pending/noop",
624 Guard: ciPendingOrUnknown,
625 Apply: func(_ *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) ([]Action, []ActionDescriptor) {
626 return nil, nil
627 },
628 },
629}
630
631// ── Guard functions ─────────────────────────────────────────────────────
632
633type guardFunc = func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) bool
634
635// allOf combines multiple guards with logical AND.
636func allOf(guards ...guardFunc) guardFunc {
637 return func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) bool {
638 for _, g := range guards {
639 if !g(c, ps, status, runStates) {
640 return false
641 }
642 }
643 return true
644 }
645}
646
647// CI status guards.
648
649func ciFailing(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
650 return status.CI == "failing"
651}
652
653func ciPassing(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
654 return status.CI == "passing"
655}
656
657func ciPendingOrUnknown(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
658 return status.CI != "failing" && status.CI != "passing"
659}
660
661// Agent status guards.
662
663// agentNotRunning gates dispatch on there being no active agent for this PR.
664// It checks both the controller's last-dispatched agent (ps.AgentRunning) and
665// any pr-fix run in runStates that matches the PR — the latter catches
666// coordinator-launched runs (`klaus launch --pr`) that the controller did not
667// dispatch itself, preventing the pipeline from racing them with a competing
668// fix agent.
669func agentNotRunning(c *Controller, ps *PRPipelineState, _ *PRStatus, runStates []*run.State) bool {
670 if ps.AgentRunning {
671 return false
672 }
673 return !c.anyPRFixRunning(ps.PRNumber, runStates)
674}
675
676func cooldownExpired(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
677 return time.Since(ps.LastDispatchAt) > dispatchCooldown
678}
679
680// dispatchFailedOnTheseInputs holds a PR whose last dispatch failed while its
681// inputs stay as they were (HandleGHStatus clears the failure once they change).
682func dispatchFailedOnTheseInputs(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
683 return ps.FailedDispatch != nil
684}
685
686// Fix attempt guards.
687
688func fixAttemptsExhausted(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
689 return ps.FixAttempts >= maxFixAttempts
690}
691
692func rebaseAttemptsExhausted(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
693 return ps.RebaseAttempts >= maxFixAttempts
694}
695
696func reviewFixAttemptsExhausted(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
697 return ps.ReviewFixAttempts >= maxFixAttempts
698}
699
700// Auto-merge attempt guards.
701
702// mergeBudgetExhausted reports whether the attempt budget for the step the PR
703// currently needs — a base-branch update while it is behind, otherwise the
704// merge itself — is spent.
705func mergeBudgetExhausted(_ *Controller, ps *PRPipelineState, status *PRStatus, _ []*run.State) bool {
706 if status.BehindBy > 0 {
707 return ps.BranchUpdateAttempts >= maxMergeAttempts
708 }
709 return ps.MergeAttempts >= maxMergeAttempts
710}
711
712// mergeBackoffExpired gates auto-merge retries so a merge that cannot succeed
713// in the PR's current state is re-attempted once per backoff window instead of
714// on every GH poll.
715func mergeBackoffExpired(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
716 return ps.LastMergeAttemptAt.IsZero() || time.Since(ps.LastMergeAttemptAt) > mergeRetryBackoff
717}
718
719// Stage guards.
720
721func inStage(s Stage) guardFunc {
722 return func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
723 return ps.Stage == s
724 }
725}
726
727func inStages(stages ...Stage) guardFunc {
728 return func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
729 for _, s := range stages {
730 if ps.Stage == s {
731 return true
732 }
733 }
734 return false
735 }
736}
737
738func notInStages(stages ...Stage) guardFunc {
739 return func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
740 for _, s := range stages {
741 if ps.Stage == s {
742 return false
743 }
744 }
745 return true
746 }
747}
748
749// notInStageWhileRunning returns true unless the PR is already in the given
750// stage AND the agent is currently running (meaning we're already handling it).
751func notInStageWhileRunning(s Stage) guardFunc {
752 return func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
753 return !(ps.Stage == s && ps.AgentRunning)
754 }
755}
756
757// Review decision guards.
758
759func isApproved(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) bool {
760 cr := strings.EqualFold(status.ReviewDecision, "CHANGES_REQUESTED")
761 return strings.EqualFold(status.ReviewDecision, "APPROVED") ||
762 (!cr && c.hasKlausApproval(ps.PRNumber, runStates))
763}
764
765func changesRequested(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
766 return strings.EqualFold(status.ReviewDecision, "CHANGES_REQUESTED")
767}
768
769func hasTrustedComments(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
770 return status.HasNewTrustedComments
771}
772
773// Label guards.
774
775// isBudgetPausedDraft reports whether the PR carries either spelling of the
776// budget-paused label. We treat the label as the canonical paused-state signal:
777// it persists across restarts and survives the worktree being cleaned up.
778// Whether the PR is currently draft or ready-for-review doesn't change the
779// signal; the label IS the signal.
780func isBudgetPausedDraft(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
781 for _, label := range status.Labels {
782 if event.IsBudgetPausedLabel(label) {
783 return true
784 }
785 }
786 return false
787}
788
789// Conflict guards.
790
791func hasConflicts(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
792 return status.Conflicts == "yes"
793}
794
795func noConflicts(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
796 return status.Conflicts != "yes"
797}
798
799// Base-freshness guards. A PR can be conflict-free yet still behind its base
800// branch; branch protection rules that require an up-to-date branch reject a
801// merge in that state.
802
803func isBehind(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
804 return status.BehindBy > 0
805}
806
807func notBehind(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool {
808 return status.BehindBy <= 0
809}
810
811// Controller config guards.
812
813func autoMergeEnabled(c *Controller, _ *PRPipelineState, _ *PRStatus, _ []*run.State) bool {
814 return c.autoMergeOnApproval
815}
816
817// ── Shared helpers used by Apply functions ──────────────────────────────
818
819// emitCIPassedIfNeeded emits the CI-passed event when transitioning from
820// stages where CI was not previously known to be passing. StageNeedsRebase is
821// excluded so that polls during an in-flight rebase don't re-emit the event.
822func emitCIPassedIfNeeded(c *Controller, ps *PRPipelineState, status *PRStatus) {
823 if ps.Stage == StageCIFailed || ps.Stage == StageCIPending || ps.Stage == StageReviewPending {
824 c.emitEvent(ps.PRNumber, event.AgentCIPassed, map[string]interface{}{
825 "pr_number": ps.PRNumber,
826 "pr_url": status.PRURL,
827 })
828 }
829}
830
831// dispatchRepo returns the owner/repo slug to attach to ActionDescriptors whose
832// handlers treat Repo as a real GitHub slug (ActionSnapshotThreads, ActionMergePR).
833// It derives the slug from status.PRURL (always a full GitHub PR URL) because
834// status.TargetRepo holds the canonical project SHORT name (e.g. "klaus") for
835// registered projects, which is NOT a valid owner/repo slug. If the URL can't be
836// parsed it falls back to status.TargetRepo to preserve prior behavior.
837//
838// Note: ActionLaunchAgent intentionally does NOT use this — its handler runs the
839// value through normalizeTargetRepo, which expects the short name.
840func dispatchRepo(c *Controller, status *PRStatus) string {
841 if slug := ghutil.OwnerRepoFromPRURL(status.PRURL); slug != "" {
842 return slug
843 }
844 c.logger.Warn("could not derive owner/repo from PR URL; falling back to TargetRepo",
845 "pr", status.PRURL,
846 "target_repo", status.TargetRepo,
847 )
848 return status.TargetRepo
849}
850
851// AgentReplyMarker is embedded in every reply a review-fix agent posts. Agents
852// run gh as the operator, who is often a trusted reviewer, so the comment
853// author can't distinguish an agent's reply from real feedback; review
854// detection skips comments carrying either spelling of this marker. It is an
855// HTML comment so it doesn't render on GitHub.
856const (
857 AgentReplyMarker = "<!-- klaus-agent-reply -->"
858 FlowAgentReplyMarker = "<!-- flow-agent-reply -->"
859)
860
861// IsAgentReply reports whether body carries either spelling of the agent-reply
862// marker.
863func IsAgentReply(body string) bool {
864 return strings.Contains(body, AgentReplyMarker) || strings.Contains(body, FlowAgentReplyMarker)
865}
866
867// CrossReviewMarker opens the hidden line in a posted cross-review body. Such
868// a review counts as trusted when posted by the operator's gh account.
869const (
870 CrossReviewMarker = review.CrossReviewMarker
871 FlowCrossReviewMarker = review.FlowCrossReviewMarker
872)
873
874// HasCrossReviewMarker reports whether body carries either spelling of the
875// cross-review marker.
876func HasCrossReviewMarker(body string) bool {
877 return review.HasCrossReviewMarker(body)
878}
879
880// FixCommand and ActionableMarker are the two ways a PR author opts a PR
881// conversation comment in as review feedback. The operator and fix agents post
882// through the same account, so author conversation comments are ignored by
883// review detection unless the first non-blank line is FixCommand (or
884// FlowFixCommand) or a line consists of ActionableMarker (or
885// FlowActionableMarker) alone. Comments from trusted reviewers other than the
886// PR author need neither.
887const (
888 FixCommand = "/klaus fix"
889 FlowFixCommand = "/flow fix"
890 ActionableMarker = "<!-- klaus-actionable -->"
891 FlowActionableMarker = "<!-- flow-actionable -->"
892)
893
894// IsActionableMarker reports whether line is either spelling of the actionable
895// marker.
896func IsActionableMarker(line string) bool {
897 return line == ActionableMarker || line == FlowActionableMarker
898}
899
900// HasFixCommand reports whether line starts with either spelling of the fix
901// directive, standing alone or followed by whitespace.
902func HasFixCommand(line string) bool {
903 for _, cmd := range []string{FixCommand, FlowFixCommand} {
904 if rest, ok := strings.CutPrefix(line, cmd); ok && (rest == "" || rest[0] == ' ' || rest[0] == '\t') {
905 return true
906 }
907 }
908 return false
909}
910
911// reviewFixPrompt builds the prompt sent to a review-fix agent. The leadIn is
912// the situation-specific opening sentence (e.g. "PR #X has changes requested
913// by reviewers."); the rest of the body is shared so both the changes-requested
914// and trusted-comments dispatch paths produce identical instructions to the agent.
915//
916// The "(that you haven't already replied to)" qualifier matters because a fix
917// agent may be re-dispatched (e.g. after CI fails on its first push). Without
918// it the agent may post duplicate replies on threads it already answered.
919func reviewFixPrompt(leadIn, prNumber string) string {
920 // The API paths use the literal {owner}/{repo} placeholder, which gh expands
921 // from the worktree's git remote at runtime. We must NOT substitute the
922 // dispatch repo here: PRStatus.TargetRepo is the canonical project short name
923 // (e.g. "klaus") for registered projects, not an owner/repo slug, so it would
924 // produce a 404 path like repos/klaus/pulls/267/comments. The fix agent always
925 // runs inside the PR's worktree, so {owner}/{repo} resolves correctly.
926 return fmt.Sprintf(
927 "%s "+
928 "Review comments come in two kinds; fetch both:\n"+
929 " inline review comments: gh api repos/{owner}/{repo}/pulls/%s/comments\n"+
930 " PR conversation comments: gh api repos/{owner}/{repo}/issues/%s/comments\n"+
931 "Ignore comments whose body contains %s or %s — those are earlier agent replies.\n"+
932 "Conversation comments from the PR author are feedback only if their first line is %s or %s, or a line is exactly %s or %s; ignore the author's other conversation comments.\n"+
933 "Address each comment in the code, then push your fixes.\n"+
934 "After pushing, reply to EACH review comment that you haven't already replied to with a concise (1-2 sentence) explanation of what you changed. "+
935 "If a comment was intentionally not addressed, reply explaining why it was discounted.\n"+
936 "End every reply body with the line %s so flow doesn't mistake your reply for new review feedback. Never start a reply with %s or %s or copy a %s or %s line into it; link to the original comment instead of quoting such lines.\n"+
937 "Use this exact command to reply to an inline comment, substituting the comment id and your explanation:\n"+
938 " gh api repos/{owner}/{repo}/pulls/%s/comments/{commentId}/replies -f body='<explanation> %s'\n"+
939 "A conversation comment has no reply thread; reply with a new PR comment that quotes or links the original:\n"+
940 " gh pr comment %s --body '<quote or link to the original> <explanation> %s'",
941 leadIn, prNumber, prNumber, AgentReplyMarker, FlowAgentReplyMarker,
942 FixCommand, FlowFixCommand, ActionableMarker, FlowActionableMarker,
943 AgentReplyMarker, FixCommand, FlowFixCommand, ActionableMarker, FlowActionableMarker,
944 prNumber, AgentReplyMarker, prNumber, AgentReplyMarker,
945 )
946}
947
948// approvedBookkeeping is the shared prelude for every transition that observes
949// an approved PR: reset the agent-attempt budgets that approval invalidates,
950// emit the CI-passed and approval edges, and mirror the approval into run state.
951func approvedBookkeeping(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) {
952 ps.FixAttempts = 0
953 ps.RebaseAttempts = 0
954 ps.ReviewFixAttempts = 0
955 emitCIPassedIfNeeded(c, ps, status)
956 setApprovedIfNeeded(c, ps, status)
957 c.markRunStatesApproved(ps.PRNumber, runStates)
958}
959
960// setApprovedIfNeeded emits pr:approved the first time the PR is seen
961// approved and moves the PR into StageApproved.
962//
963// The emission is keyed off the ledger rather than the stage, because the
964// stage is not a reliable edge signal: a failed auto-merge moves an approved
965// PR out of StageApproved and the next poll moves it back, which would
966// re-emit pr:approved on every poll for as long as the merge keeps failing.
967// The ledger also outlives a restart and a PR dropping out of tracking, so
968// the event fires once per PR, even when an approval is dismissed and
969// granted again.
970//
971// StageStalled is preserved so a tripped circuit breaker stays observable.
972func setApprovedIfNeeded(c *Controller, ps *PRPipelineState, status *PRStatus) {
973 if c.recordTransition(ledgerKey(ps.PRNumber, status.PRURL), markApproved) {
974 c.emitEvent(ps.PRNumber, event.PRApproved, map[string]interface{}{
975 "pr_number": ps.PRNumber,
976 "pr_url": status.PRURL,
977 })
978 }
979 if ps.Stage != StageMerging && ps.Stage != StageNeedsRebase && ps.Stage != StageStalled {
980 ps.Stage = StageApproved
981 }
982}