| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "log/slog" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "time" |
| 10 | |
| 11 | tea "github.com/charmbracelet/bubbletea" |
| 12 | "github.com/fsnotify/fsnotify" |
| 13 | "the-valley/flow/internal/config" |
| 14 | "the-valley/flow/internal/event" |
| 15 | "the-valley/flow/internal/integration" |
| 16 | "the-valley/flow/internal/pipeline" |
| 17 | "the-valley/flow/internal/restack" |
| 18 | "the-valley/flow/internal/run" |
| 19 | "the-valley/flow/internal/webhook" |
| 20 | ) |
| 21 | |
| 22 | // Messages for the bubbletea event loop. |
| 23 | |
| 24 | type statesLoadedMsg struct { |
| 25 | states []*run.State |
| 26 | cleared run.Cleared // the runs cleanup removed |
| 27 | clock *stateClock // the session's events, dating REVIEW rows |
| 28 | } |
| 29 | |
| 30 | type ghStatusMsg struct { |
| 31 | statuses map[string]*prStatus // keyed by PR URL |
| 32 | // rateLimitedUntil is when GitHub lets polling resume; zero when it |
| 33 | // isn't rate-limited. |
| 34 | rateLimitedUntil time.Time |
| 35 | } |
| 36 | |
| 37 | // integrationTickMsg starts an integration check of pushed runs, unless a |
| 38 | // later check re-armed the timer: seq is the arming it came from. |
| 39 | type integrationTickMsg struct{ seq int } |
| 40 | |
| 41 | // integrationMsg carries the results of an integration check, by run ID. |
| 42 | type integrationMsg struct { |
| 43 | results map[string]integration.Result |
| 44 | changes map[integration.ChangeKey]integration.Result |
| 45 | // restacks is where each restack conflict on a change klaus owns |
| 46 | // stands after the check's restack pass; nil when none ran. |
| 47 | restacks map[integration.ChangeKey]restack.View |
| 48 | // valleyErr is why the check couldn't ask the valley; "" when it could. |
| 49 | valleyErr string |
| 50 | } |
| 51 | |
| 52 | type fsEventMsg struct{} |
| 53 | |
| 54 | type tickMsg struct{} |
| 55 | |
| 56 | // reconcileTickMsg fires the slow reconcile heartbeat in webhook-only mode. |
| 57 | type reconcileTickMsg struct{} |
| 58 | |
| 59 | type sandboxStatusMsg struct { |
| 60 | hosts map[string]bool // host -> reachable |
| 61 | } |
| 62 | |
| 63 | type pipelineActionMsg struct { |
| 64 | actions []pipeline.Action |
| 65 | } |
| 66 | |
| 67 | type errMsg struct { |
| 68 | err error |
| 69 | } |
| 70 | |
| 71 | // errHintMsg carries a transient, non-fatal hint to surface in the dashboard |
| 72 | // (via the recentErrors strip) without triggering the fatal error screen that |
| 73 | // errMsg does. Used by best-effort background actions like opening a browser. |
| 74 | type errHintMsg struct { |
| 75 | msg string |
| 76 | } |
| 77 | |
| 78 | type webhookMsg struct { |
| 79 | event webhook.Event |
| 80 | } |
| 81 | |
| 82 | // webhookClosedMsg signals that the webhook event channel was closed, so live |
| 83 | // webhook consumption has stopped. Surfaced as a non-fatal error in the TUI. |
| 84 | type webhookClosedMsg struct{} |
| 85 | |
| 86 | // internalEventMsg delivers a klaus-emitted event (e.g. PRApprovalChanged |
| 87 | // from `klaus approve`) into the dashboard's Update loop. Internal events |
| 88 | // are treated as invalidation signals — the dashboard reacts by re-fetching |
| 89 | // PR status, mirroring how it reacts to a real GitHub webhook. |
| 90 | type internalEventMsg struct { |
| 91 | event event.Event |
| 92 | } |
| 93 | |
| 94 | type trustedCommentsMsg struct { |
| 95 | prURL string |
| 96 | hasNewTrustedComments bool |
| 97 | } |
| 98 | |
| 99 | // prStatus holds the GitHub-fetched status for a single PR. |
| 100 | type prStatus struct { |
| 101 | PRNumber string |
| 102 | State string // OPEN, MERGED, CLOSED or NOACCESS (gh.StateNoAccess) |
| 103 | Draft bool |
| 104 | HeadSHA string |
| 105 | CI string // passing, failing, pending, unknown |
| 106 | Conflicts string // yes, none, unknown |
| 107 | BehindBy int // commits base has that head lacks; >0 = stale-but-mergeable |
| 108 | ReviewDecision string // APPROVED, CHANGES_REQUESTED, etc. |
| 109 | HasNewTrustedComments bool // unaddressed comments from trusted reviewers |
| 110 | TrustedFeedbackAt time.Time // when trusted reviewers last left feedback |
| 111 | Labels []string // applied PR labels (used to surface klaus:budget-paused) |
| 112 | } |
| 113 | |
| 114 | // Commands for the bubbletea event loop. |
| 115 | |
| 116 | func loadStatesCmd(store run.StateStore) tea.Cmd { |
| 117 | return func() tea.Msg { |
| 118 | states, err := store.List() |
| 119 | if err != nil { |
| 120 | return errMsg{err: err} |
| 121 | } |
| 122 | cleared, _ := clearedOf(store, states) |
| 123 | return statesLoadedMsg{states: states, cleared: cleared, clock: loadClock(store)} |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // noAccessRecheck is how long a PR the agent can't read goes without being |
| 128 | // queried again, so a fixed credential recovers on its own without the |
| 129 | // dashboard asking GitHub about it on every poll. |
| 130 | const noAccessRecheck = 30 * time.Minute |
| 131 | |
| 132 | // fetchGHStatusCmd fetches the GitHub status of every PR the states refer |
| 133 | // to, keyed by PR URL so equal PR numbers in different repos don't collide. |
| 134 | // PRs last found unreadable less than noAccessRecheck ago are skipped; their |
| 135 | // NOACCESS status stays in place. A PR the pipeline's ledger has seen merged |
| 136 | // or closed isn't asked about again, even after a restart; its status comes |
| 137 | // from the ledger. |
| 138 | func (m dashboardModel) fetchGHStatusCmd(states []*run.State) tea.Cmd { |
| 139 | skip := make(map[string]bool) |
| 140 | now := time.Now() |
| 141 | for url, at := range m.noAccessAt { |
| 142 | if now.Sub(at) < noAccessRecheck { |
| 143 | skip[url] = true |
| 144 | } |
| 145 | } |
| 146 | settled := func(string) string { return "" } |
| 147 | if m.pipelineCtrl != nil { |
| 148 | settled = m.pipelineCtrl.Settled |
| 149 | } |
| 150 | return fetchGHStatusCmd(m.ghPoller, settled, states, skip) |
| 151 | } |
| 152 | |
| 153 | func fetchGHStatusCmd(p *ghPoller, settled func(prURL string) string, states []*run.State, skip map[string]bool) tea.Cmd { |
| 154 | var prs []trackedPR |
| 155 | done := make(map[string]*prStatus) |
| 156 | seen := make(map[string]bool) |
| 157 | for _, s := range states { |
| 158 | url := extractPRRef(s) |
| 159 | if url == "" || skip[url] || seen[url] { |
| 160 | continue |
| 161 | } |
| 162 | seen[url] = true |
| 163 | if state := settled(url); state != "" { |
| 164 | done[url] = &prStatus{PRNumber: extractPRNumber(s), State: state} |
| 165 | continue |
| 166 | } |
| 167 | prs = append(prs, trackedPR{url: url, number: extractPRNumber(s)}) |
| 168 | } |
| 169 | return func() tea.Msg { |
| 170 | statuses, until := p.poll(context.TODO(), prs) |
| 171 | for url, ps := range done { |
| 172 | statuses[url] = ps |
| 173 | } |
| 174 | return ghStatusMsg{statuses: statuses, rateLimitedUntil: until} |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | // integrationInterval is how often the dashboard checks whether pushed runs |
| 179 | // have landed. It is independent of GitHub polling. Where a valley host's |
| 180 | // telemetry can be followed, a check also starts as soon as the host reports |
| 181 | // a decision or new evidence (valleyWaker), and the interval is the fallback. |
| 182 | const integrationInterval = time.Minute |
| 183 | |
| 184 | // integrationTimeout bounds one integration check. |
| 185 | const integrationTimeout = 5 * time.Minute |
| 186 | |
| 187 | // checkIntegrationCmd checks, in the background, the runs that are waiting |
| 188 | // for their pushed branch to be integrated, and the tracked valley changes. |
| 189 | // With a ValleyChecker that is at most one `valley changes` for all of them. Then, with a store, it settles |
| 190 | // the knots of runs whose change the check found landed (settleKnots). |
| 191 | // With a change ledger and a session directory, it emits the transitions |
| 192 | // the valley's listing shows for those runs' changes (reportChangeTransitions). |
| 193 | // With restacks and a session directory, it then runs a restack pass, as |
| 194 | // klaus restack-conflicts does, dispatching resolution runs for the restack |
| 195 | // conflicts on changes klaus owns: on the check's valley listing, or, when |
| 196 | // the check asked no valley, listing each repo itself; a valley the check |
| 197 | // couldn't ask isn't asked again. With a listing it then runs a checks |
| 198 | // pass, as klaus failed-checks does, dispatching fix runs for the failed |
| 199 | // checks of ready changes klaus owns. The next |
| 200 | // check starts only once this one is done, so no two settle a knot, or |
| 201 | // dispatch, at once. |
| 202 | func checkIntegrationCmd(checker integration.Checker, states []*run.State, store run.StateStore, ledger *pipeline.ChangeLedger, restacks bool) tea.Cmd { |
| 203 | if checker == nil { |
| 204 | return nil |
| 205 | } |
| 206 | var pushed []*run.State |
| 207 | for _, s := range states { |
| 208 | if awaitsIntegration(s) || integration.TracksChange(s) { |
| 209 | cp := *s // the check runs off the Update goroutine |
| 210 | pushed = append(pushed, &cp) |
| 211 | } |
| 212 | } |
| 213 | return func() tea.Msg { |
| 214 | ctx, cancel := context.WithTimeout(context.Background(), integrationTimeout) |
| 215 | defer cancel() |
| 216 | rep := checker.Check(ctx, pushed) |
| 217 | if store != nil { |
| 218 | settleKnots(ctx, store, pushed, rep.Runs, rep.Changes) |
| 219 | } |
| 220 | hds, ok := store.(*run.HomeDirStore) |
| 221 | if ok && ledger != nil && rep.Listing != nil { |
| 222 | reportChangeTransitions(hds, ledger, pushed, rep.Listing) |
| 223 | } |
| 224 | msg := integrationMsg{results: rep.Runs, changes: rep.Changes, valleyErr: rep.ValleyErr} |
| 225 | if ok && restacks && (rep.Listing != nil || !rep.Asked) { |
| 226 | views, err := restackPass(ctx, hds, rep.Listing, true) |
| 227 | if err != nil { |
| 228 | slog.Warn("restack pass failed", "err", err) |
| 229 | } |
| 230 | msg.restacks = restackViews(views) |
| 231 | } |
| 232 | if ok && restacks && rep.Listing != nil { |
| 233 | if _, err := checksPass(ctx, hds, rep.Listing, true); err != nil { |
| 234 | slog.Warn("checks pass failed", "err", err) |
| 235 | } |
| 236 | } |
| 237 | return msg |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | // startIntegrationCheck starts an integration check of the model's runs. The |
| 242 | // model notes it runs until its integrationMsg arrives, so a wake meanwhile |
| 243 | // asks for one more check after it rather than one beside it. |
| 244 | func (m dashboardModel) startIntegrationCheck() (dashboardModel, tea.Cmd) { |
| 245 | cmd := checkIntegrationCmd(m.checker, m.states, m.store, m.changeLedger, m.restackOn) |
| 246 | m.checking = cmd != nil |
| 247 | return m, cmd |
| 248 | } |
| 249 | |
| 250 | // keepValleyViews returns a check's results, except where the valley placed |
| 251 | // a run before and git judged it now (the valley couldn't be asked, or |
| 252 | // couldn't read the repo): unless git found it landed, the run keeps the |
| 253 | // valley's last view, marked Outdated. A valley outage then leaves an |
| 254 | // uncertain or rejected change where it was instead of showing it as ready |
| 255 | // to approve, or as done because its branch went away. |
| 256 | func keepValleyViews(prev, next map[string]integration.Result) map[string]integration.Result { |
| 257 | for id, r := range next { |
| 258 | if old, ok := prev[id]; ok && old.Change != nil && r.Change == nil && !r.Verdict.Landed() { |
| 259 | old.Outdated = true |
| 260 | next[id] = old |
| 261 | } |
| 262 | } |
| 263 | return next |
| 264 | } |
| 265 | |
| 266 | // keepChangeViews does for the valley's views of changes what keepValleyViews |
| 267 | // does for runs': a change the latest check has no view of (the valley |
| 268 | // couldn't be asked, or couldn't read its repo) keeps its last view, marked |
| 269 | // Outdated. |
| 270 | func keepChangeViews(prev, next map[integration.ChangeKey]integration.Result) map[integration.ChangeKey]integration.Result { |
| 271 | if next == nil { |
| 272 | next = make(map[integration.ChangeKey]integration.Result) |
| 273 | } |
| 274 | for k, old := range prev { |
| 275 | if _, ok := next[k]; !ok { |
| 276 | old.Outdated = true |
| 277 | next[k] = old |
| 278 | } |
| 279 | } |
| 280 | return next |
| 281 | } |
| 282 | |
| 283 | func integrationTickAfterCmd(seq int) tea.Cmd { |
| 284 | return tea.Tick(integrationInterval, func(time.Time) tea.Msg { |
| 285 | return integrationTickMsg{seq: seq} |
| 286 | }) |
| 287 | } |
| 288 | |
| 289 | func waitForWebhookCmd(ch <-chan webhook.Event) tea.Cmd { |
| 290 | if ch == nil { |
| 291 | return nil |
| 292 | } |
| 293 | return func() tea.Msg { |
| 294 | ev, ok := <-ch |
| 295 | if !ok { |
| 296 | // The webhook channel was closed. Re-reading it would return |
| 297 | // immediately forever (a busy-loop), so we do NOT re-arm. |
| 298 | // Surface a visible (non-fatal) error instead of going silently |
| 299 | // dark — in webhook-only mode this would otherwise permanently |
| 300 | // kill all reconcile triggers except the slow heartbeat (see |
| 301 | // issue #271). |
| 302 | return webhookClosedMsg{} |
| 303 | } |
| 304 | return webhookMsg{event: ev} |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | func waitForInternalEventCmd(ch <-chan event.Event) tea.Cmd { |
| 309 | if ch == nil { |
| 310 | return nil |
| 311 | } |
| 312 | return func() tea.Msg { |
| 313 | ev, ok := <-ch |
| 314 | if !ok { |
| 315 | return nil |
| 316 | } |
| 317 | return internalEventMsg{event: ev} |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | // shouldInvalidate reports whether an event type should trigger a refetch |
| 322 | // of GitHub PR status. Most klaus events (agent:started, pr:merged, …) are |
| 323 | // pure notifications and either reflect state the dashboard already learned |
| 324 | // from the pipeline FSM, or are observational. Only events that signal an |
| 325 | // external precondition change need an active invalidation. |
| 326 | func shouldInvalidate(eventType string) bool { |
| 327 | switch eventType { |
| 328 | case event.PRApprovalChanged: |
| 329 | return true |
| 330 | } |
| 331 | return false |
| 332 | } |
| 333 | |
| 334 | // internalEventPRNumber returns the PR number associated with an event, |
| 335 | // or empty if none. The event Data is map[string]interface{}; JSON decodes |
| 336 | // numbers as float64, but events constructed in-process may carry int / |
| 337 | // int64, so all common numeric forms are tolerated. |
| 338 | func internalEventPRNumber(ev event.Event) string { |
| 339 | if ev.Data == nil { |
| 340 | return "" |
| 341 | } |
| 342 | switch v := ev.Data["pr_number"].(type) { |
| 343 | case string: |
| 344 | return v |
| 345 | case int: |
| 346 | return fmt.Sprintf("%d", v) |
| 347 | case int64: |
| 348 | return fmt.Sprintf("%d", v) |
| 349 | case float64: |
| 350 | if v == float64(int64(v)) { |
| 351 | return fmt.Sprintf("%d", int64(v)) |
| 352 | } |
| 353 | } |
| 354 | return "" |
| 355 | } |
| 356 | |
| 357 | func tickCmd() tea.Cmd { |
| 358 | return func() tea.Msg { |
| 359 | return tickMsg{} |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | func tickAfterCmd() tea.Cmd { |
| 364 | return tea.Tick(30*time.Second, func(time.Time) tea.Msg { |
| 365 | return tickMsg{} |
| 366 | }) |
| 367 | } |
| 368 | |
| 369 | // defaultReconcileInterval is the slow reconcile heartbeat interval used in |
| 370 | // webhook-only mode when no override is configured. |
| 371 | const defaultReconcileInterval = 5 * time.Minute |
| 372 | |
| 373 | // shouldScheduleReconcile reports whether the slow reconcile heartbeat should |
| 374 | // run. It runs only in webhook mode when polling is NOT active: poll mode |
| 375 | // already re-fetches every 30s (tickMsg), so the heartbeat would be redundant. |
| 376 | // A non-positive interval disables the heartbeat entirely. |
| 377 | func shouldScheduleReconcile(useWebhook, pollEnabled bool, interval time.Duration) bool { |
| 378 | return useWebhook && !pollEnabled && interval > 0 |
| 379 | } |
| 380 | |
| 381 | // reconcileInterval resolves the heartbeat interval from config. A zero value |
| 382 | // means "use the default"; a negative value disables the heartbeat. |
| 383 | func reconcileInterval(cfg *config.WebhookConfig) time.Duration { |
| 384 | if cfg == nil || cfg.ReconcileIntervalSeconds == 0 { |
| 385 | return defaultReconcileInterval |
| 386 | } |
| 387 | if cfg.ReconcileIntervalSeconds < 0 { |
| 388 | return 0 // disabled |
| 389 | } |
| 390 | return time.Duration(cfg.ReconcileIntervalSeconds) * time.Second |
| 391 | } |
| 392 | |
| 393 | func reconcileTickAfterCmd(interval time.Duration) tea.Cmd { |
| 394 | // Defensive guard: tea.Tick fires immediately for a non-positive duration, |
| 395 | // so re-arming with interval <= 0 (the disabled-heartbeat sentinel) would |
| 396 | // spin an infinite loop of reconcileTickMsg messages and peg the CPU. |
| 397 | // Returning nil cleanly disables the heartbeat (bubbletea ignores nil cmds). |
| 398 | if interval <= 0 { |
| 399 | return nil |
| 400 | } |
| 401 | return tea.Tick(interval, func(time.Time) tea.Msg { |
| 402 | return reconcileTickMsg{} |
| 403 | }) |
| 404 | } |
| 405 | |
| 406 | // startWatcherCmd watches the run state directory and, when jobsDir is set, |
| 407 | // the job records. |
| 408 | func startWatcherCmd(store run.StateStore, jobsDir string) tea.Cmd { |
| 409 | return func() tea.Msg { |
| 410 | stateDir := store.StateDir() |
| 411 | // Ensure the directory exists before watching |
| 412 | os.MkdirAll(stateDir, 0o755) |
| 413 | |
| 414 | w, err := fsnotify.NewWatcher() |
| 415 | if err != nil { |
| 416 | return errMsg{err: fmt.Errorf("creating file watcher: %w", err)} |
| 417 | } |
| 418 | if err := w.Add(stateDir); err != nil { |
| 419 | w.Close() |
| 420 | return errMsg{err: fmt.Errorf("watching state dir: %w", err)} |
| 421 | } |
| 422 | if jobsDir != "" { |
| 423 | os.MkdirAll(jobsDir, 0o700) |
| 424 | if err := w.Add(jobsDir); err != nil { |
| 425 | w.Close() |
| 426 | return errMsg{err: fmt.Errorf("watching jobs dir: %w", err)} |
| 427 | } |
| 428 | } |
| 429 | return w |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // watchFSCmd waits for a record to change: a job's in jobsDir (jobsFSMsg), |
| 434 | // else a run's (fsEventMsg). |
| 435 | func watchFSCmd(w *fsnotify.Watcher, jobsDir string) tea.Cmd { |
| 436 | return func() tea.Msg { |
| 437 | for { |
| 438 | select { |
| 439 | case event, ok := <-w.Events: |
| 440 | if !ok { |
| 441 | return nil |
| 442 | } |
| 443 | if filepath.Ext(event.Name) != ".json" { |
| 444 | continue |
| 445 | } |
| 446 | if jobsDir != "" && filepath.Dir(event.Name) == filepath.Clean(jobsDir) { |
| 447 | return jobsFSMsg{} |
| 448 | } |
| 449 | return fsEventMsg{} |
| 450 | case _, ok := <-w.Errors: |
| 451 | if !ok { |
| 452 | return nil |
| 453 | } |
| 454 | // Ignore watcher errors and keep watching |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | func checkSandboxCmd(states []*run.State) tea.Cmd { |
| 461 | return func() tea.Msg { |
| 462 | hosts := make(map[string]bool) |
| 463 | for _, s := range states { |
| 464 | if s.Host != nil && *s.Host != "" { |
| 465 | if _, ok := hosts[*s.Host]; !ok { |
| 466 | hosts[*s.Host] = CheckSandboxReachable(*s.Host) |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | if len(hosts) == 0 { |
| 471 | return nil |
| 472 | } |
| 473 | return sandboxStatusMsg{hosts: hosts} |
| 474 | } |
| 475 | } |