| 1 | package pipeline |
| 2 | |
| 3 | import ( |
| 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. |
| 17 | type 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. |
| 24 | var 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 | |
| 633 | type guardFunc = func(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) bool |
| 634 | |
| 635 | // allOf combines multiple guards with logical AND. |
| 636 | func 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 | |
| 649 | func ciFailing(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool { |
| 650 | return status.CI == "failing" |
| 651 | } |
| 652 | |
| 653 | func ciPassing(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool { |
| 654 | return status.CI == "passing" |
| 655 | } |
| 656 | |
| 657 | func 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. |
| 669 | func 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 | |
| 676 | func 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). |
| 682 | func dispatchFailedOnTheseInputs(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool { |
| 683 | return ps.FailedDispatch != nil |
| 684 | } |
| 685 | |
| 686 | // Fix attempt guards. |
| 687 | |
| 688 | func fixAttemptsExhausted(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool { |
| 689 | return ps.FixAttempts >= maxFixAttempts |
| 690 | } |
| 691 | |
| 692 | func rebaseAttemptsExhausted(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool { |
| 693 | return ps.RebaseAttempts >= maxFixAttempts |
| 694 | } |
| 695 | |
| 696 | func 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. |
| 705 | func 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. |
| 715 | func mergeBackoffExpired(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool { |
| 716 | return ps.LastMergeAttemptAt.IsZero() || time.Since(ps.LastMergeAttemptAt) > mergeRetryBackoff |
| 717 | } |
| 718 | |
| 719 | // Stage guards. |
| 720 | |
| 721 | func inStage(s Stage) guardFunc { |
| 722 | return func(_ *Controller, ps *PRPipelineState, _ *PRStatus, _ []*run.State) bool { |
| 723 | return ps.Stage == s |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | func 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 | |
| 738 | func 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). |
| 751 | func 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 | |
| 759 | func 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 | |
| 765 | func changesRequested(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool { |
| 766 | return strings.EqualFold(status.ReviewDecision, "CHANGES_REQUESTED") |
| 767 | } |
| 768 | |
| 769 | func 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 the klaus:budget-paused |
| 776 | // label. We treat the label as the canonical paused-state signal: it persists |
| 777 | // across klaus restarts and survives the worktree being cleaned up. Whether |
| 778 | // the PR is currently draft or ready-for-review doesn't change the signal; |
| 779 | // the label IS the signal. |
| 780 | func isBudgetPausedDraft(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool { |
| 781 | for _, label := range status.Labels { |
| 782 | if label == event.BudgetPausedLabel { |
| 783 | return true |
| 784 | } |
| 785 | } |
| 786 | return false |
| 787 | } |
| 788 | |
| 789 | // Conflict guards. |
| 790 | |
| 791 | func hasConflicts(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool { |
| 792 | return status.Conflicts == "yes" |
| 793 | } |
| 794 | |
| 795 | func 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 | |
| 803 | func isBehind(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool { |
| 804 | return status.BehindBy > 0 |
| 805 | } |
| 806 | |
| 807 | func notBehind(_ *Controller, _ *PRPipelineState, status *PRStatus, _ []*run.State) bool { |
| 808 | return status.BehindBy <= 0 |
| 809 | } |
| 810 | |
| 811 | // Controller config guards. |
| 812 | |
| 813 | func 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. |
| 822 | func 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. |
| 840 | func 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 this marker. It is an HTML comment so it |
| 855 | // doesn't render on GitHub. |
| 856 | const AgentReplyMarker = "<!-- klaus-agent-reply -->" |
| 857 | |
| 858 | // CrossReviewMarker opens the hidden line in a `klaus review --post` review body. Such a review counts as trusted when posted by the operator's gh account. |
| 859 | const CrossReviewMarker = review.CrossReviewMarker |
| 860 | |
| 861 | // FixCommand and ActionableMarker are the two ways a PR author opts a PR |
| 862 | // conversation comment in as review feedback. The operator and fix agents post |
| 863 | // through the same account, so author conversation comments are ignored by |
| 864 | // review detection unless the first non-blank line is FixCommand or a line |
| 865 | // consists of ActionableMarker alone. Comments from trusted reviewers other |
| 866 | // than the PR author need neither. |
| 867 | const ( |
| 868 | FixCommand = "/klaus fix" |
| 869 | ActionableMarker = "<!-- klaus-actionable -->" |
| 870 | ) |
| 871 | |
| 872 | // reviewFixPrompt builds the prompt sent to a review-fix agent. The leadIn is |
| 873 | // the situation-specific opening sentence (e.g. "PR #X has changes requested |
| 874 | // by reviewers."); the rest of the body is shared so both the changes-requested |
| 875 | // and trusted-comments dispatch paths produce identical instructions to the agent. |
| 876 | // |
| 877 | // The "(that you haven't already replied to)" qualifier matters because a fix |
| 878 | // agent may be re-dispatched (e.g. after CI fails on its first push). Without |
| 879 | // it the agent may post duplicate replies on threads it already answered. |
| 880 | func reviewFixPrompt(leadIn, prNumber string) string { |
| 881 | // The API paths use the literal {owner}/{repo} placeholder, which gh expands |
| 882 | // from the worktree's git remote at runtime. We must NOT substitute the |
| 883 | // dispatch repo here: PRStatus.TargetRepo is the canonical project short name |
| 884 | // (e.g. "klaus") for registered projects, not an owner/repo slug, so it would |
| 885 | // produce a 404 path like repos/klaus/pulls/267/comments. The fix agent always |
| 886 | // runs inside the PR's worktree, so {owner}/{repo} resolves correctly. |
| 887 | return fmt.Sprintf( |
| 888 | "%s "+ |
| 889 | "Review comments come in two kinds; fetch both:\n"+ |
| 890 | " inline review comments: gh api repos/{owner}/{repo}/pulls/%s/comments\n"+ |
| 891 | " PR conversation comments: gh api repos/{owner}/{repo}/issues/%s/comments\n"+ |
| 892 | "Ignore comments whose body contains %s — those are earlier agent replies.\n"+ |
| 893 | "Conversation comments from the PR author are feedback only if their first line is %s or a line is exactly %s; ignore the author's other conversation comments.\n"+ |
| 894 | "Address each comment in the code, then push your fixes.\n"+ |
| 895 | "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. "+ |
| 896 | "If a comment was intentionally not addressed, reply explaining why it was discounted.\n"+ |
| 897 | "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 copy a %s line into it; link to the original comment instead of quoting such lines.\n"+ |
| 898 | "Use this exact command to reply to an inline comment, substituting the comment id and your explanation:\n"+ |
| 899 | " gh api repos/{owner}/{repo}/pulls/%s/comments/{commentId}/replies -f body='<explanation> %s'\n"+ |
| 900 | "A conversation comment has no reply thread; reply with a new PR comment that quotes or links the original:\n"+ |
| 901 | " gh pr comment %s --body '<quote or link to the original> <explanation> %s'", |
| 902 | leadIn, prNumber, prNumber, AgentReplyMarker, FixCommand, ActionableMarker, |
| 903 | AgentReplyMarker, FixCommand, ActionableMarker, |
| 904 | prNumber, AgentReplyMarker, prNumber, AgentReplyMarker, |
| 905 | ) |
| 906 | } |
| 907 | |
| 908 | // approvedBookkeeping is the shared prelude for every transition that observes |
| 909 | // an approved PR: reset the agent-attempt budgets that approval invalidates, |
| 910 | // emit the CI-passed and approval edges, and mirror the approval into run state. |
| 911 | func approvedBookkeeping(c *Controller, ps *PRPipelineState, status *PRStatus, runStates []*run.State) { |
| 912 | ps.FixAttempts = 0 |
| 913 | ps.RebaseAttempts = 0 |
| 914 | ps.ReviewFixAttempts = 0 |
| 915 | emitCIPassedIfNeeded(c, ps, status) |
| 916 | setApprovedIfNeeded(c, ps, status) |
| 917 | c.markRunStatesApproved(ps.PRNumber, runStates) |
| 918 | } |
| 919 | |
| 920 | // setApprovedIfNeeded emits pr:approved the first time the PR is seen |
| 921 | // approved and moves the PR into StageApproved. |
| 922 | // |
| 923 | // The emission is keyed off the ledger rather than the stage, because the |
| 924 | // stage is not a reliable edge signal: a failed auto-merge moves an approved |
| 925 | // PR out of StageApproved and the next poll moves it back, which would |
| 926 | // re-emit pr:approved on every poll for as long as the merge keeps failing. |
| 927 | // The ledger also outlives a restart and a PR dropping out of tracking, so |
| 928 | // the event fires once per PR, even when an approval is dismissed and |
| 929 | // granted again. |
| 930 | // |
| 931 | // StageStalled is preserved so a tripped circuit breaker stays observable. |
| 932 | func setApprovedIfNeeded(c *Controller, ps *PRPipelineState, status *PRStatus) { |
| 933 | if c.recordTransition(ledgerKey(ps.PRNumber, status.PRURL), markApproved) { |
| 934 | c.emitEvent(ps.PRNumber, event.PRApproved, map[string]interface{}{ |
| 935 | "pr_number": ps.PRNumber, |
| 936 | "pr_url": status.PRURL, |
| 937 | }) |
| 938 | } |
| 939 | if ps.Stage != StageMerging && ps.Stage != StageNeedsRebase && ps.Stage != StageStalled { |
| 940 | ps.Stage = StageApproved |
| 941 | } |
| 942 | } |