gunk-dev/the-valley

pipeline.go

source68d12192bbd3main's published tip history
28.1 KiB
1package pipeline
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "os"
8 "os/exec"
9 "strconv"
10 "strings"
11 "sync"
12 "time"
13
14 "the-valley/flow/internal/event"
15 ghutil "the-valley/flow/internal/github"
16 "the-valley/flow/internal/run"
17)
18
19// Stage represents the pipeline stage for a PR.
20type Stage string
21
22const (
23 StageCIPending Stage = "ci_pending"
24 StageCIFailed Stage = "ci_failed"
25 StageCIPassed Stage = "ci_passed"
26 StageReviewPending Stage = "review_pending"
27 StageApproved Stage = "approved"
28 StageNeedsRebase Stage = "needs_rebase"
29 StageMerging Stage = "merging"
30 StageMerged Stage = "merged"
31 StageStalled Stage = "stalled"
32 StageBudgetPaused Stage = "budget_paused"
33)
34
35// PRStatus holds the GitHub-fetched status for a single PR, passed from the dashboard.
36type PRStatus struct {
37 PRNumber string
38 PRURL string
39 State string // OPEN, MERGED, CLOSED, or UNKNOWN when GitHub couldn't be asked
40 CI string // passing, failing, pending, unknown
41 Conflicts string // yes, none, unknown
42 BehindBy int // commits base has that head lacks; >0 = stale-but-mergeable
43 ReviewDecision string // APPROVED, CHANGES_REQUESTED, etc.
44 TargetRepo string // canonical project short name (e.g. "klaus") for registered projects, else an owner/repo slug; NOT guaranteed to be a GitHub owner/repo slug — do not use in gh api paths
45 HasNewTrustedComments bool // unaddressed comments from trusted reviewers
46 Labels []string // GitHub label names; klaus uses "klaus:budget-paused" as a pause signal
47 HeadSHA string
48 TrustedFeedbackAt time.Time // when trusted reviewers last left feedback; new feedback moves it
49}
50
51// DispatchInputs are what a PR's dispatch decision reads from GitHub. A
52// dispatch that failed isn't tried again until they change.
53type DispatchInputs struct {
54 HeadSHA string
55 CI string
56 ReviewDecision string
57 TrustedComments bool
58 TrustedFeedback time.Time
59}
60
61func dispatchInputs(s *PRStatus) DispatchInputs {
62 return DispatchInputs{HeadSHA: s.HeadSHA, CI: s.CI, ReviewDecision: s.ReviewDecision, TrustedComments: s.HasNewTrustedComments, TrustedFeedback: s.TrustedFeedbackAt}
63}
64
65// PRPipelineState tracks per-PR pipeline state.
66type PRPipelineState struct {
67 PRNumber string
68 PRURL string // the PR this state tracks; the number alone is ambiguous across repos
69 Stage Stage
70 LastAgentID string // run ID of last dispatched agent
71 AgentRunning bool // whether the dispatched agent is still active
72 SeenCommentIDs map[int64]bool
73 PendingResolveThreadIDs []string // GraphQL thread IDs to resolve after agent completes
74 FailedDispatch *DispatchInputs // the inputs the last dispatch failed on; nil once they change
75 LastDispatchAt time.Time // when the last agent was dispatched (cooldown guard)
76 FixAttempts int // number of CI-fix agents dispatched that completed without fixing CI
77 RebaseAttempts int // number of rebase agents dispatched that completed without resolving conflicts
78 ReviewFixAttempts int // number of review-fix agents dispatched that completed without addressing trusted comments
79 MergeAttempts int // number of auto-merge attempts made since approval
80 BranchUpdateAttempts int // number of base-branch updates attempted since approval
81 LastMergeAttemptAt time.Time // when the last merge or branch-update attempt was made (backoff guard)
82
83 pendingLaunchDetail string // transient: detail text for pending launch action
84}
85
86// Action describes a side-effect the controller wants the dashboard to perform.
87type Action struct {
88 Type string // "launch", "merge", or "error"
89 Detail string // human-readable description
90 Error string // non-empty if action represents a failure
91}
92
93// ActionType enumerates the kinds of side-effects evaluate() can request.
94type ActionType int
95
96const (
97 ActionLaunchAgent ActionType = iota
98 ActionMergePR
99 ActionCleanupWorktrees
100 ActionSnapshotThreads
101 ActionUpdateBranch
102)
103
104// ActionDescriptor is a pure data description of a side-effect to perform.
105// evaluate() returns these instead of executing I/O directly.
106type ActionDescriptor struct {
107 Type ActionType
108 PRNumber string
109 Repo string
110 Prompt string
111 ResumeFrom string
112 Reason string // why an agent is launched: an event.Dispatch* reason, for klaus launch --reason
113 PRNumbers []string // for merge
114 RunStates []*run.State // for worktree cleanup
115}
116
117// Controller manages the PR pipeline lifecycle.
118type Controller struct {
119 store run.StateStore
120 eventLog *event.Log
121 logger *slog.Logger
122 prStates map[string]*PRPipelineState // keyed by PR number
123 ledger *Ledger // the PR transitions already seen and reported
124 mu sync.Mutex
125
126 autoMergeOnApproval bool // whether to auto-merge approved PRs
127
128 tmuxDeps run.TmuxDeps // tmux operations for checking pane state
129
130 // Injectable runners for testing.
131 launchAgent func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error)
132 mergePRs func(ctx context.Context, repo string, prNumbers []string) error
133 updateBranch func(ctx context.Context, repo, prNumber string) error
134 snapshotThreads func(repo, prNumber string) ([]string, error)
135 resolveThread func(threadID string) error
136}
137
138// New creates a new pipeline controller.
139func New(store run.StateStore, eventLog *event.Log, logger *slog.Logger) *Controller {
140 c := &Controller{
141 store: store,
142 eventLog: eventLog,
143 logger: logger,
144 prStates: make(map[string]*PRPipelineState),
145 ledger: NewLedger(),
146 tmuxDeps: run.DefaultTmuxDeps(),
147 }
148 c.launchAgent = c.defaultLaunchAgent
149 c.mergePRs = c.defaultMergePRs
150 c.updateBranch = c.defaultUpdateBranch
151 c.snapshotThreads = c.defaultSnapshotThreads
152 c.resolveThread = func(threadID string) error {
153 return ghutil.NewGHCLIClient("").ResolveReviewThread(context.TODO(), threadID)
154 }
155 return c
156}
157
158// SetTmuxDeps overrides the tmux dependencies used for pane state checks.
159func (c *Controller) SetTmuxDeps(td run.TmuxDeps) {
160 c.tmuxDeps = td
161}
162
163// SetLedger replaces the in-memory ledger, typically with one loaded from
164// the session directory so a restarted dashboard doesn't report a PR
165// transition again.
166func (c *Controller) SetLedger(l *Ledger) {
167 c.mu.Lock()
168 defer c.mu.Unlock()
169 c.ledger = l
170}
171
172// SetAutoMergeOnApproval controls whether approved PRs are automatically merged.
173func (c *Controller) SetAutoMergeOnApproval(enabled bool) {
174 c.mu.Lock()
175 defer c.mu.Unlock()
176 c.autoMergeOnApproval = enabled
177}
178
179// SetLaunchAgent overrides the agent launcher (for testing).
180func (c *Controller) SetLaunchAgent(fn func(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error)) {
181 c.mu.Lock()
182 defer c.mu.Unlock()
183 c.launchAgent = fn
184}
185
186// SetMergePRs overrides the merge runner (for testing).
187func (c *Controller) SetMergePRs(fn func(ctx context.Context, repo string, prNumbers []string) error) {
188 c.mu.Lock()
189 defer c.mu.Unlock()
190 c.mergePRs = fn
191}
192
193// SetUpdateBranch overrides the branch-update runner (for testing).
194func (c *Controller) SetUpdateBranch(fn func(ctx context.Context, repo, prNumber string) error) {
195 c.mu.Lock()
196 defer c.mu.Unlock()
197 c.updateBranch = fn
198}
199
200// SetSnapshotThreads overrides thread snapshot fetching (for testing).
201func (c *Controller) SetSnapshotThreads(fn func(repo, prNumber string) ([]string, error)) {
202 c.mu.Lock()
203 defer c.mu.Unlock()
204 c.snapshotThreads = fn
205}
206
207// SetResolveThread overrides thread resolution (for testing).
208func (c *Controller) SetResolveThread(fn func(threadID string) error) {
209 c.mu.Lock()
210 defer c.mu.Unlock()
211 c.resolveThread = fn
212}
213
214// HandleGHStatus is called by the dashboard on each GH poll with fresh PR statuses.
215// It evaluates pipeline transitions and returns any actions taken.
216//
217// The method holds the mutex only while computing what to do (evaluate), then
218// releases it to execute I/O (agent launches, merges, worktree cleanup), and
219// re-acquires to update state with results. This prevents blocking dashboard
220// rendering during slow exec calls.
221func (c *Controller) HandleGHStatus(ctx context.Context, statuses map[string]*PRStatus, runStates []*run.State) []Action {
222 // Phase 1: Hold lock, compute descriptors and collect immediate actions.
223 c.mu.Lock()
224
225 var actions []Action
226 var descriptors []ActionDescriptor
227 // Track which PRs need thread resolution (agent just completed).
228 var threadResolvePRs []*PRPipelineState
229
230 // Build a set of running agent run IDs from current run states.
231 runningAgents := make(map[string]bool)
232 for _, s := range runStates {
233 if c.isRunning(s) {
234 runningAgents[s.ID] = true
235 }
236 }
237
238 for prNum, status := range statuses {
239 key := ledgerKey(prNum, status.PRURL)
240 switch status.State {
241 case "OPEN":
242 c.recordTransition(key, markSeenOpen)
243 case "MERGED":
244 // A merge is reported once, and only for a PR klaus saw open:
245 // one already merged when klaus first sees it is history.
246 if c.recordTransition(key, markMerged) && c.ledger.has(key, markSeenOpen) {
247 c.emitEvent(prNum, event.PRMerged, map[string]interface{}{
248 "pr_number": prNum,
249 "pr_url": status.PRURL,
250 })
251 }
252 delete(c.prStates, prNum)
253 continue
254 case "CLOSED":
255 c.recordTransition(key, markClosed)
256 delete(c.prStates, prNum)
257 continue
258 default:
259 // GitHub couldn't be asked (UNKNOWN: a timeout, rate limit or
260 // network failure). That says nothing about the PR, so leave it
261 // as it was. Taking it for open once tracked long-merged PRs
262 // afresh, re-approved them, tried to merge them, and reported
263 // them merged again when the next poll got through.
264 continue
265 }
266
267 ps := c.getOrCreateState(prNum, status)
268 ps.PRURL = status.PRURL
269
270 // Update agent running status.
271 wasRunning := ps.AgentRunning
272 if ps.LastAgentID != "" {
273 ps.AgentRunning = runningAgents[ps.LastAgentID]
274 }
275
276 // Mark PRs that need thread resolution (agent just completed).
277 if wasRunning && !ps.AgentRunning && len(ps.PendingResolveThreadIDs) > 0 {
278 threadResolvePRs = append(threadResolvePRs, ps)
279 }
280
281 // Approval-edge bookkeeping: once the PR is no longer approved, the
282 // next approval gives auto-merge a fresh attempt budget. pr:approved
283 // itself is reported once per PR, through the ledger.
284 if !isApproved(c, ps, status, runStates) {
285 ps.MergeAttempts = 0
286 ps.BranchUpdateAttempts = 0
287 ps.LastMergeAttemptAt = time.Time{}
288 }
289
290 // A dispatch that failed waits for its inputs to change; once they
291 // have, the PR is evaluated afresh.
292 if ps.FailedDispatch != nil && *ps.FailedDispatch != dispatchInputs(status) {
293 ps.FailedDispatch = nil
294 }
295
296 prevStage := ps.Stage
297 evalActions, evalDescs := c.evaluate(ps, status, runStates)
298 actions = append(actions, evalActions...)
299 descriptors = append(descriptors, evalDescs...)
300
301 if ps.Stage != prevStage {
302 c.logger.Info("pipeline transition",
303 "pr", prNum,
304 "from", string(prevStage),
305 "to", string(ps.Stage),
306 )
307 }
308 }
309
310 c.mu.Unlock()
311
312 // Phase 2: Execute I/O without holding the lock.
313
314 // Resolve pending review threads for agents that just completed.
315 for _, ps := range threadResolvePRs {
316 c.resolvePendingThreads(ps)
317 }
318
319 // Execute descriptors and collect results to apply under the lock.
320 type launchResult struct {
321 prNumber string
322 agentID string
323 err error
324 }
325 type mergeResult struct {
326 prNumber string
327 repo string
328 err error
329 }
330 type updateResult struct {
331 prNumber string
332 err error
333 }
334 var launchResults []launchResult
335 var mergeResults []mergeResult
336 var updateResults []updateResult
337
338 for _, desc := range descriptors {
339 switch desc.Type {
340 case ActionCleanupWorktrees:
341 c.cleanupStaleWorktrees(desc.PRNumber, desc.RunStates)
342
343 case ActionSnapshotThreads:
344 c.mu.Lock()
345 ps := c.prStates[desc.PRNumber]
346 c.mu.Unlock()
347 if ps != nil {
348 c.snapshotUnresolvedThreads(ps, desc.Repo)
349 }
350
351 case ActionLaunchAgent:
352 agentID, err := c.launchAgent(ctx, desc.PRNumber, desc.Repo, desc.Prompt, desc.ResumeFrom, desc.Reason)
353 launchResults = append(launchResults, launchResult{
354 prNumber: desc.PRNumber,
355 agentID: agentID,
356 err: err,
357 })
358
359 case ActionMergePR:
360 err := c.mergePRs(ctx, desc.Repo, desc.PRNumbers)
361 mergeResults = append(mergeResults, mergeResult{
362 prNumber: desc.PRNumber,
363 repo: desc.Repo,
364 err: err,
365 })
366
367 case ActionUpdateBranch:
368 err := c.updateBranch(ctx, desc.Repo, desc.PRNumber)
369 updateResults = append(updateResults, updateResult{
370 prNumber: desc.PRNumber,
371 err: err,
372 })
373 }
374 }
375
376 // Phase 3: Re-acquire lock to apply results.
377 c.mu.Lock()
378 defer c.mu.Unlock()
379
380 for _, lr := range launchResults {
381 ps := c.prStates[lr.prNumber]
382 if ps == nil {
383 continue
384 }
385 if lr.err != nil {
386 // Retrying on the same inputs fails the same way, so the PR stalls
387 // until they change, and the coordinator hears of it once.
388 c.logger.Error("failed to dispatch agent", "pr", lr.prNumber, "err", lr.err)
389 in := dispatchInputs(statuses[lr.prNumber])
390 ps.FailedDispatch = &in
391 msg := truncateError(lr.err.Error(), 120)
392 c.stall(ps, ps.PRURL, "dispatch failed: "+msg)
393 actions = append(actions, Action{Type: "error", Detail: fmt.Sprintf("PR #%s: dispatch failed", lr.prNumber), Error: msg})
394 } else {
395 ps.LastAgentID = lr.agentID
396 ps.AgentRunning = true
397 ps.LastDispatchAt = time.Now()
398 actions = append(actions, Action{Type: "launch", Detail: ps.pendingLaunchDetail})
399 ps.pendingLaunchDetail = ""
400 }
401 }
402
403 for _, ur := range updateResults {
404 ps := c.prStates[ur.prNumber]
405 if ps == nil {
406 continue
407 }
408 if ur.err != nil {
409 c.logger.Error("branch update failed", "pr", ur.prNumber, "err", ur.err)
410 c.stallIfExhausted(ps, ps.BranchUpdateAttempts, fmt.Sprintf("branch update failed after %d attempts", ps.BranchUpdateAttempts))
411 actions = append(actions, Action{Type: "error", Detail: fmt.Sprintf("PR #%s: branch update failed", ur.prNumber), Error: truncateError(ur.err.Error(), 120)})
412 } else {
413 actions = append(actions, Action{Type: "update-branch", Detail: fmt.Sprintf("Updated PR #%s from base branch", ur.prNumber)})
414 }
415 }
416
417 for _, mr := range mergeResults {
418 ps := c.prStates[mr.prNumber]
419 if ps == nil {
420 continue
421 }
422 if mr.err != nil {
423 c.logger.Error("auto-merge failed", "pr", mr.prNumber, "err", mr.err)
424 // Drop back to approved so the next poll re-evaluates instead of
425 // re-entering merging immediately; the backoff and attempt budget
426 // on the auto-merge transition gate the retry.
427 ps.Stage = StageApproved
428 c.stallIfExhausted(ps, ps.MergeAttempts, fmt.Sprintf("auto-merge failed after %d attempts", ps.MergeAttempts))
429 actions = append(actions, Action{Type: "error", Detail: fmt.Sprintf("PR #%s: auto-merge failed", mr.prNumber), Error: truncateError(mr.err.Error(), 120)})
430 } else {
431 ps.Stage = StageMerged
432 if c.recordTransition(ledgerKey(mr.prNumber, ps.PRURL), markMerged) {
433 c.emitEvent(mr.prNumber, event.PRMerged, map[string]interface{}{
434 "pr_number": mr.prNumber,
435 "pr_url": ps.PRURL,
436 })
437 }
438 actions = append(actions, Action{Type: "merge", Detail: fmt.Sprintf("Merged PR #%s", mr.prNumber)})
439 }
440 }
441
442 return actions
443}
444
445// PipelineStates returns a snapshot of current pipeline states (for dashboard rendering).
446func (c *Controller) PipelineStates() map[string]*PRPipelineState {
447 c.mu.Lock()
448 defer c.mu.Unlock()
449 out := make(map[string]*PRPipelineState, len(c.prStates))
450 for k, v := range c.prStates {
451 cp := *v
452 out[k] = &cp
453 }
454 return out
455}
456
457func (c *Controller) getOrCreateState(prNum string, status *PRStatus) *PRPipelineState {
458 ps, ok := c.prStates[prNum]
459 if !ok {
460 // Seed initial stage from current GitHub status so that session
461 // resume doesn't force already-progressed PRs back to ci_pending.
462 stage := seedStageFromStatus(status)
463 ps = &PRPipelineState{
464 PRNumber: prNum,
465 Stage: stage,
466 SeenCommentIDs: make(map[int64]bool),
467 }
468 c.prStates[prNum] = ps
469 }
470 return ps
471}
472
473// seedStageFromStatus returns an appropriate initial pipeline stage based on
474// the PR's current GitHub status. Merged/closed PRs are filtered out before
475// this function is called, so only open-PR statuses are handled here.
476func seedStageFromStatus(status *PRStatus) Stage {
477 switch {
478 case status.CI == "passing":
479 return StageCIPassed
480 case status.CI == "failing":
481 return StageCIFailed
482 default:
483 return StageCIPending
484 }
485}
486
487// maxFixAttempts is the maximum number of fix agents dispatched for a single PR
488// before the pipeline gives up. Reset when the branch is updated or CI passes.
489const maxFixAttempts = 3
490
491// dispatchCooldown is the minimum time between agent dispatches for the same PR.
492const dispatchCooldown = 60 * time.Second
493
494// maxMergeAttempts bounds how many auto-merge attempts — and, separately, how
495// many base-branch updates — the controller makes for a single approval before
496// stalling the PR. A PR that can never reach a mergeable state stalls loudly
497// instead of retrying forever. The budgets are separate so a PR that is merely
498// behind a fast-moving base doesn't spend its merge attempts catching up.
499const maxMergeAttempts = 3
500
501// mergeRetryBackoff is the minimum time between auto-merge attempts for the
502// same PR. Without it the dashboard's ~3s GH poll would retry a failing merge
503// on every tick.
504const mergeRetryBackoff = 60 * time.Second
505
506// evaluate checks the current GH status and determines transitions + action
507// descriptors. It performs NO I/O — all side-effects are described as
508// ActionDescriptor values for the caller to execute outside the lock.
509//
510// The method iterates over the transition table defined in transitions.go.
511// The first transition whose Guard matches is applied; subsequent transitions
512// are skipped. This makes the state machine explicit and testable.
513func (c *Controller) evaluate(ps *PRPipelineState, status *PRStatus, runStates []*run.State) ([]Action, []ActionDescriptor) {
514 for _, t := range transitions {
515 if t.Guard(c, ps, status, runStates) {
516 return t.Apply(c, ps, status, runStates)
517 }
518 }
519 return nil, nil
520}
521
522// Settled returns MERGED or CLOSED for a PR the ledger has seen so, else "".
523// The dashboard doesn't ask GitHub about such a PR again, so a closed PR
524// that is reopened stays closed to klaus.
525func (c *Controller) Settled(prURL string) string {
526 switch {
527 case c.ledger.has(prURL, markMerged):
528 return "MERGED"
529 case c.ledger.has(prURL, markClosed):
530 return "CLOSED"
531 }
532 return ""
533}
534
535// stall moves a PR into StageStalled and emits pipeline:stalled on the
536// transition edge. Re-entering an already-stalled state is a no-op, so a
537// coordinator watching `klaus watch` gets exactly one notification per stall
538// rather than one per poll.
539func (c *Controller) stall(ps *PRPipelineState, prURL, reason string) {
540 if ps.Stage == StageStalled {
541 return
542 }
543 ps.Stage = StageStalled
544 data := map[string]interface{}{
545 "pr_number": ps.PRNumber,
546 "reason": reason,
547 }
548 if prURL != "" {
549 data["pr_url"] = prURL
550 }
551 c.emitEvent(ps.PRNumber, event.PipelineStalled, data)
552}
553
554// stallIfExhausted stalls the PR once the given attempt budget is spent. Below
555// the budget the PR stays approved and is retried after the backoff window.
556func (c *Controller) stallIfExhausted(ps *PRPipelineState, attempts int, reason string) {
557 if attempts < maxMergeAttempts {
558 return
559 }
560 c.logger.Warn("auto-merge circuit breaker tripped",
561 "pr", ps.PRNumber,
562 "attempts", attempts,
563 )
564 c.stall(ps, "", reason)
565}
566
567// cleanupStaleWorktrees removes worktrees from completed runs that match the given PR number.
568// This prevents "worktree already exists" errors when re-dispatching agents.
569func (c *Controller) cleanupStaleWorktrees(prNumber string, runStates []*run.State) {
570 for _, s := range runStates {
571 if s.PR == nil || *s.PR != prNumber {
572 continue
573 }
574 if c.isRunning(s) {
575 continue
576 }
577 if s.Worktree == "" {
578 continue
579 }
580 // Check if the worktree directory still exists on disk.
581 if _, err := os.Stat(s.Worktree); err != nil {
582 continue
583 }
584 // Run klaus cleanup for this stale run.
585 c.logger.Info("cleaning up stale worktree before dispatch",
586 "pr", prNumber,
587 "run", s.ID,
588 "worktree", s.Worktree,
589 )
590 cmd := exec.Command("klaus", "cleanup", s.ID)
591 if out, err := cmd.CombinedOutput(); err != nil {
592 c.logger.Error("stale worktree cleanup failed",
593 "run", s.ID,
594 "err", err,
595 "output", string(out),
596 )
597 }
598 }
599}
600
601// markRunStatesApproved sets Approved=true on run states matching the given PR number
602// that are not already approved, and persists the change via the store.
603func (c *Controller) markRunStatesApproved(prNumber string, runStates []*run.State) {
604 now := time.Now().UTC().Format(time.RFC3339)
605 for _, s := range runStates {
606 if !runStateMatchesPR(s, prNumber) {
607 continue
608 }
609 if s.Approved != nil && *s.Approved {
610 continue
611 }
612 approved := true
613 s.Approved = &approved
614 s.ApprovedAt = &now
615 if c.store != nil {
616 if err := c.store.Save(s); err != nil {
617 c.logger.Error("failed to persist GitHub approval to run state",
618 "pr", prNumber, "run", s.ID, "err", err)
619 }
620 }
621 }
622}
623
624// runStateMatchesPR reports whether the run state is associated with the given PR number.
625func runStateMatchesPR(s *run.State, prNumber string) bool {
626 if s.PR != nil && *s.PR == prNumber {
627 return true
628 }
629 if s.PRURL != nil && strings.HasSuffix(strings.TrimRight(*s.PRURL, "/"), "/"+prNumber) {
630 return true
631 }
632 return false
633}
634
635// hasKlausApproval returns true if any run state for the given PR has been
636// approved via `klaus approve`.
637func (c *Controller) hasKlausApproval(prNumber string, runStates []*run.State) bool {
638 for _, s := range runStates {
639 if !runStateMatchesPR(s, prNumber) {
640 continue
641 }
642 if s.Approved != nil && *s.Approved {
643 return true
644 }
645 }
646 return false
647}
648
649// recordTransition records a PR's transition in the ledger and reports
650// whether it is new, that is, whether its event should be emitted.
651func (c *Controller) recordTransition(key string, m ledgerMark) bool {
652 first, err := c.ledger.record(key, m)
653 if err != nil {
654 c.logger.Error("failed to persist PR transition", "pr", key, "err", err)
655 }
656 return first
657}
658
659// emitEvent emits a PR's event. The run ID is the PR number; a PR URL in
660// data adds the repo-qualified keys run events carry: repo_key (owner/repo)
661// and key (owner/repo#<pr>).
662func (c *Controller) emitEvent(prNumber, eventType string, data map[string]interface{}) {
663 if c.eventLog == nil {
664 return
665 }
666 if prURL, _ := data["pr_url"].(string); prURL != "" {
667 if repo := ghutil.OwnerRepoFromPRURL(prURL); repo != "" {
668 data["repo_key"] = repo
669 data["key"] = repo + "#" + prNumber
670 }
671 }
672 evt := event.New(prNumber, eventType, data)
673 if err := c.eventLog.Emit(evt); err != nil {
674 c.logger.Error("failed to emit event", "type", eventType, "pr", prNumber, "err", err)
675 }
676}
677
678func (c *Controller) defaultLaunchAgent(ctx context.Context, prNumber, repo, prompt, resumeFrom, reason string) (string, error) {
679 args := []string{"launch", "--pr", prNumber}
680 if repo != "" {
681 args = append(args, "--repo", repo)
682 }
683 if resumeFrom != "" {
684 args = append(args, "--resume-from", resumeFrom)
685 }
686 if reason != "" {
687 args = append(args, "--reason", reason)
688 }
689 args = append(args, prompt)
690 cmd := exec.CommandContext(ctx, "klaus", args...)
691 out, err := cmd.CombinedOutput()
692 if err != nil {
693 return "", fmt.Errorf("klaus launch: %w: %s", err, string(out))
694 }
695 // Extract run ID from output (first line typically: "Launching agent <id>...")
696 // Best-effort extraction.
697 output := string(out)
698 if id := extractAgentID(output); id != "" {
699 return id, nil
700 }
701 return "unknown", nil
702}
703
704func (c *Controller) defaultMergePRs(ctx context.Context, repo string, prNumbers []string) error {
705 args := []string{"merge", "--yes"}
706 if repo != "" {
707 args = append(args, "--repo", repo)
708 }
709 args = append(args, prNumbers...)
710 cmd := exec.CommandContext(ctx, "klaus", args...)
711 out, err := cmd.CombinedOutput()
712 if err != nil {
713 return fmt.Errorf("klaus merge: %w: %s", err, string(out))
714 }
715 return nil
716}
717
718func (c *Controller) defaultUpdateBranch(ctx context.Context, repo, prNumber string) error {
719 return ghutil.NewGHCLIClient(repo).UpdateBranch(ctx, prNumber)
720}
721
722// extractAgentID attempts to pull the run ID from "Launching agent <id>..." output.
723func extractAgentID(output string) string {
724 for _, line := range strings.Split(output, "\n") {
725 if strings.HasPrefix(line, "Launching agent ") {
726 parts := strings.Fields(line)
727 if len(parts) >= 3 {
728 return strings.TrimSuffix(parts[2], "...")
729 }
730 }
731 }
732 return ""
733}
734
735// isRunning checks if a run is still active (has tmux pane, not finalized).
736func (c *Controller) isRunning(s *run.State) bool {
737 return s.IsAgentRunningWith(c.tmuxDeps)
738}
739
740// anyPRFixRunning returns true if any pr-fix run is currently active on the
741// given PR, regardless of whether the controller itself dispatched it. This
742// detects coordinator-launched pr-fix runs (`klaus launch --pr <num>`) that
743// the controller has no record of, so it can avoid racing with them while
744// they are pushing incremental commits.
745func (c *Controller) anyPRFixRunning(prNumber string, runStates []*run.State) bool {
746 for _, s := range runStates {
747 if s == nil || s.Type != "pr-fix" {
748 continue
749 }
750 if !runStateMatchesPR(s, prNumber) {
751 continue
752 }
753 if c.isRunning(s) {
754 return true
755 }
756 }
757 return false
758}
759
760// truncateError returns a short, single-line version of an error message.
761// It strips cobra "Usage:" help text and truncates to maxLen.
762func truncateError(s string, maxLen int) string {
763 // Strip everything from "Usage:" onward (cobra help text).
764 if idx := strings.Index(s, "Usage:"); idx > 0 {
765 s = strings.TrimSpace(s[:idx])
766 }
767 // Take only the first line.
768 if idx := strings.IndexByte(s, '\n'); idx >= 0 {
769 s = s[:idx]
770 }
771 s = strings.TrimSpace(s)
772 if len(s) > maxLen {
773 return s[:maxLen-1] + "…"
774 }
775 return s
776}
777
778// snapshotUnresolvedThreads fetches and stores unresolved review thread IDs
779// so they can be resolved after the fix agent completes.
780func (c *Controller) snapshotUnresolvedThreads(ps *PRPipelineState, repo string) {
781 threadIDs, err := c.snapshotThreads(repo, ps.PRNumber)
782 if err != nil {
783 c.logger.Warn("failed to snapshot review threads", "pr", ps.PRNumber, "err", err)
784 ps.PendingResolveThreadIDs = nil
785 return
786 }
787 ps.PendingResolveThreadIDs = threadIDs
788 if len(threadIDs) > 0 {
789 c.logger.Info("snapshotted unresolved review threads",
790 "pr", ps.PRNumber,
791 "count", len(threadIDs),
792 )
793 }
794}
795
796// resolvePendingThreads resolves all pending review threads for a PR.
797func (c *Controller) resolvePendingThreads(ps *PRPipelineState) {
798 resolved := 0
799 for _, threadID := range ps.PendingResolveThreadIDs {
800 if err := c.resolveThread(threadID); err != nil {
801 c.logger.Warn("failed to resolve review thread",
802 "pr", ps.PRNumber,
803 "thread", threadID,
804 "err", err,
805 )
806 continue
807 }
808 resolved++
809 }
810 if resolved > 0 {
811 c.logger.Info("resolved review threads after agent completion",
812 "pr", ps.PRNumber,
813 "resolved", resolved,
814 "total", len(ps.PendingResolveThreadIDs),
815 )
816 }
817 ps.PendingResolveThreadIDs = nil
818}
819
820// defaultSnapshotThreads fetches unresolved review thread IDs from GitHub.
821func (c *Controller) defaultSnapshotThreads(repo, prNumber string) ([]string, error) {
822 parts := strings.SplitN(repo, "/", 2)
823 if len(parts) != 2 {
824 return nil, fmt.Errorf("invalid repo format: %s", repo)
825 }
826 prNum, err := strconv.Atoi(prNumber)
827 if err != nil {
828 return nil, fmt.Errorf("invalid PR number: %s", prNumber)
829 }
830 threads, err := ghutil.NewGHCLIClient("").FetchReviewThreads(context.TODO(), parts[0], parts[1], prNum)
831 if err != nil {
832 return nil, err
833 }
834 var ids []string
835 for _, t := range threads {
836 if !t.IsResolved {
837 ids = append(ids, t.ID)
838 }
839 }
840 return ids, nil
841}
842
843// StageLabel returns a human-readable label for dashboard display.
844func StageLabel(stage Stage) string {
845 switch stage {
846 case StageCIPending:
847 return "CI pending"
848 case StageCIFailed:
849 return "CI failed, fix running"
850 case StageCIPassed:
851 return "CI passed, reviewing"
852 case StageReviewPending:
853 return "review fix running"
854 case StageApproved:
855 return "approved, ready"
856 case StageNeedsRebase:
857 return "rebasing"
858 case StageMerging:
859 return "merging"
860 case StageMerged:
861 return "merged"
862 case StageStalled:
863 return "stalled"
864 case StageBudgetPaused:
865 return "budget paused, awaiting decision"
866 default:
867 return string(stage)
868 }
869}