gunk-dev/the-valley

status.go

source30e24c82839bmain's published tip history
24.6 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "the-valley/flow/internal/review"
7 "io"
8 "os"
9 "strings"
10 "time"
11
12 gh "the-valley/flow/internal/github"
13 "the-valley/flow/internal/integration"
14 "the-valley/flow/internal/jobs"
15 "the-valley/flow/internal/restack"
16 "the-valley/flow/internal/run"
17 "the-valley/flow/internal/tmux"
18 "github.com/spf13/cobra"
19)
20
21var statusCmd = &cobra.Command{
22 Use: "status",
23 Short: "Show all runs and their current state",
24 Long: `Shows all runs in the session and their current state.
25
26STATUS is one of: running (the agent's pane is still running it, judged as
27the dashboard judges it: a dead pane, or an idle one once the run finished,
28isn't running), needs-attention (finalize salvaged its work, it failed
29after taking on the work of runs that needed attention, or the files its
30clone shares across worktrees, its git config, info/attributes or hooks,
31changed while it ran: a line below the table names them, and that holds
32whatever became of its work), superseded (it
33needed attention, but a run of its change, the same change ID in the same
34repo, took its pushed work on and is running or finished: that run
35recorded it, as launch does for a --pr, --change or --resume-from run
36continuing a branch that holds the work, and finalize does when the head a
37run left on origin contains it; that run carries the attention from then
38on, and shows needs-attention itself if it ended needing attention or
39failing; neither status nor the dashboard counts the superseded run as
40needing attention), pr-created, merged, closed,
41no-access (GitHub won't show the PR with the current credentials), exited,
42and, for runs that finished by pushing a branch without a PR:
43
44 awaiting-integration the branch is on origin and hasn't landed
45 integrated its work is on origin's default branch, by ancestry
46 or by an equal patch-id, or the valley says its
47 change landed
48 branch-gone the branch was deleted from origin without landing
49
50and, for a branch finalize recorded as a version of its change on a valley
51(ready, or a draft when ready_at_finalize is off), where the valley's record
52says the change stands:
53
54 awaiting-review a draft finalize left for review, as it does when
55 ready_at_finalize is off; approve refuses it until
56 'valley flow ready' marks it ready once its review passes
57 awaiting-approval ready and waiting for you to approve it
58 approved approved: the integrator hasn't decided, or judged it
59 stale only because its checks are still running (CI
60 shows them). Nothing to do
61 uncertain a request was consumed or failed with no landing
62 evidence: look at it
63 checks-failed stale, and the version's checks failed
64 conflicting stale, and the change's current restack report
65 says a rebase conflicted
66 stale, rejected, the integrator's decision on the request (stale
67 failed with passed checks, or on a valley that lists
68 none, is for you to look at)
69 withdrawn the change was withdrawn
70 older-version the change has a newer version, made by the
71 valley's restacker or a later run, and hasn't
72 landed; the run's row says nothing of whether the
73 change is done
74 draft returned to draft ('valley unready'), as launch
75 does when a follow-up run continues the change;
76 approve refuses it until a head is ready again.
77 A draft reads draft even when its landing is
78 uncertain; only landing evidence comes first
79
80A run that isn't running and isn't done shows working while another run of
81its change (the same change ID in the same repo) is running: a follow-up
82(--pr, --resume-from or a pipeline fix) is still pushing to it, so there is
83nothing to approve yet.
84
85A valley change added with valley flow track shows where the valley's listing
86says its active version stands, by the statuses above (awaiting-approval,
87approved, integrated, draft, withdrawn and so on), with its title as the
88prompt; it reads tracking while the valley can't be asked. A tracked PR
89reads tracking until GitHub says it is merged or closed.
90
91CHANGE names the change a run belongs to: its PR's number (#319), else the
92number of its change's PR (the PR of the newest run of the change that has
93one), else its valley change's handle, else the first 8 characters of its
94change ID, so runs of one change share it, running or not. The handle is the valley
95listing's, else (when the valley can't be asked) the one a run of the
96change recorded when finalize marked it ready or launch returned it to
97draft. A valley run shows its change's title as the
98prompt.
99
100Integration is checked with one "valley changes --all --json" when a valley
101is involved, and otherwise against each run's clone (one ls-remote and fetch
102per repo). If the valley can't be asked, its runs are checked against their
103clones. If the check can't complete, the run stays awaiting-integration (or
104awaiting-approval, or awaiting-review). A deleted branch alone never settles a valley change: it
105stays awaiting-approval rather than branch-gone.
106
107A valley's host runs a ready change's required checks. CI reads where they
108stand on the change's active version, as it reads a PR's CI: pending,
109failing or passing, and a list after the table names each change's failed
110checks. CI reads - while the change isn't ready, or the valley lists no
111checks (one from before it listed them). The checks don't change the
112status: a ready change reads awaiting-approval whatever they say, since you
113may approve it before they finish, and it lands once both hold. The
114dashboard dispatches a run to fix a failed head of a change flow owns (see
115valley flow failed-checks).
116
117A valley's restacker rebases ready changes onto main after each landing,
118and reports a rebase that conflicts. For a change flow owns (its record's
119owner is the repo's valley.principal), CONFLICTS reads restack while the
120conflict stands, and a list after the table says where each stands: a
121resolution run due, dispatched (attempt n of 3), being launched (flow
122hasn't yet seen the run start), waiting out the cooldown, a run already
123working on the change, stopped after 3 runs, not dispatched (and why: the
124change couldn't be returned to draft, or the launch failed, perhaps after
125starting its worker), or left alone (the conflict is in a change below it,
126or the change sits on other changes). valley flow restack-conflicts, which the
127dashboard runs, does the dispatching; status only reads.
128
129A line after them sums the session's cost, counting the runs valley flow cleanup
130removed.
131
132After the runs, a jobs table lists the session's consults, reviews, and running
133prose passes (see valley flow jobs): every one running, and consults and reviews that
134finished in the last 3 hours, with how long each has run or took. Finished prose
135passes in the last 3 hours are counted on a single summary line under the table
136(total and failed). Both are left out when there are none.`,
137 RunE: func(cmd *cobra.Command, args []string) error {
138 store, err := sessionStore()
139 if err != nil {
140 return err
141 }
142 if err := printRuns(cmd.Context(), store); err != nil {
143 return err
144 }
145 printRecentJobs(os.Stdout, store, time.Now())
146 return nil
147 },
148}
149
150// printRecentJobs prints, after a blank line, the jobs table of the
151// session's running jobs and recent consults and reviews, followed by a
152// single summary line of finished prose passes in recentJobs; nothing when
153// there are none.
154func printRecentJobs(w io.Writer, store run.StateStore, now time.Time) {
155 hds, ok := store.(*run.HomeDirStore)
156 if !ok {
157 return
158 }
159 list, err := jobs.NewStore(hds.BaseDir()).List()
160 if err != nil {
161 fmt.Fprintf(os.Stderr, "warning: reading jobs: %v\n", err)
162 return
163 }
164 listed, prose := partitionJobs(jobs.Recent(list, now, recentJobs))
165 if len(listed) == 0 && prose.total == 0 {
166 return
167 }
168 fmt.Fprintln(w)
169 if len(listed) > 0 {
170 printJobsTable(w, listed, now)
171 }
172 if prose.total > 0 {
173 fmt.Fprintf(w, "%s (finished in the last 3h; valley flow jobs --kind prose)\n", prose)
174 }
175}
176
177// printRuns prints the runs table and the session's spend, or says there
178// are no runs.
179func printRuns(ctx context.Context, store run.StateStore) error {
180 states, err := store.List()
181 if err != nil {
182 return err
183 }
184 cleared := sessionCleared(store, states)
185 if len(states) == 0 && cleared.Runs == 0 {
186 fmt.Println("No runs found.")
187 return nil
188 }
189 if len(states) > 0 {
190 if _, err := runStatuses(ctx, store, states, os.Stdout, nil); err != nil {
191 return err
192 }
193 }
194 fmt.Fprintln(os.Stdout)
195 fmt.Fprintf(os.Stdout, "Session cost: $%.2f", computeTotalCost(states)+cleared.CostUSD)
196 if cleared.Runs > 0 {
197 fmt.Fprintf(os.Stdout, " ($%.2f of it by %d runs cleanup removed)", cleared.CostUSD, cleared.Runs)
198 }
199 fmt.Fprintln(os.Stdout)
200 return nil
201}
202
203// sessionCleared sums the runs cleanup removed from the session; zero when
204// store isn't a session directory or the ledger can't be read.
205func sessionCleared(store run.StateStore, live []*run.State) run.Cleared {
206 c, err := clearedOf(store, live)
207 if err != nil {
208 fmt.Fprintf(os.Stderr, "warning: reading cleared runs: %v\n", err)
209 }
210 return c
211}
212
213// clearedOf sums the runs cleanup removed from store's session, other than
214// those in live; zero when store isn't a session directory.
215func clearedOf(store run.StateStore, live []*run.State) (run.Cleared, error) {
216 hds, ok := store.(*run.HomeDirStore)
217 if !ok {
218 return run.Cleared{}, nil
219 }
220 return run.ReadCleared(hds.BaseDir(), live)
221}
222
223// runStanding returns where each run of states stands, by index, as klaus
224// status shows it, and the integration check it read.
225func runStanding(ctx context.Context, store run.StateStore, states []*run.State) ([]string, integration.Report, error) {
226 var report integration.Report
227 statuses, err := runStatuses(ctx, store, states, io.Discard, &report)
228 return statuses, report, err
229}
230
231// runStatuses writes the runs table for states to out and returns where
232// each run stands, by index into states, as the table shows it. A non-nil
233// checked receives the integration check it read.
234func runStatuses(ctx context.Context, store run.StateStore, states []*run.State, out io.Writer, checked *integration.Report) ([]string, error) {
235 tmuxClient := tmux.NewExecClient()
236 ghClient := gh.NewGHCLIClient("")
237
238 fmt.Fprintf(out, "%-22s %-10s %-26s %-8s %-6s %-20s %-15s %-8s %-10s %-10s %-8s %-10s %s\n",
239 "RUN ID", "STATUS", "MODEL", "COST", "ISSUE", "REPO", "HOST", "CHANGE", "CI", "CONFLICTS", "BEHIND", "MERGE", "PROMPT")
240 fmt.Fprintf(out, "%-22s %-10s %-26s %-8s %-6s %-20s %-15s %-8s %-10s %-10s %-8s %-10s %s\n",
241 "------", "------", "-----", "----", "-----", "----", "----", "------", "--", "---------", "------", "-----", "------")
242
243 statuses := make([]string, len(states))
244 running := make(map[string]bool)
245 for i, s := range states {
246 if err := ctx.Err(); err != nil {
247 return nil, err
248 }
249 statuses[i] = determineStatus(ctx, s, tmuxClient)
250 running[s.ID] = statuses[i] == "running"
251 }
252 // A run whose work a later run took on hands its attention to that run.
253 superseded := supersededRuns(states, func(s *run.State) bool { return running[s.ID] })
254 var pushed []*run.State
255 for i, s := range states {
256 if statuses[i] == "needs-attention" && superseded[s.ID] && !s.SharedGitChanged() {
257 statuses[i] = "superseded"
258 }
259 if statuses[i] == "awaiting-integration" || integration.TracksChange(s) {
260 pushed = append(pushed, s)
261 }
262 }
263 // Where pushed branches stand: one valley listing for the runs a
264 // valley knows and the tracked valley changes, one check per repo
265 // against each run's own clone for the rest.
266 report := integration.NewValleyChecker(nil).Check(ctx, pushed)
267 if checked != nil {
268 *checked = report
269 }
270 if note := integration.ValleyNote(report.ValleyErr); note != "" {
271 fmt.Fprintln(os.Stderr, note)
272 }
273 handles := changeHandles(states, report.Changes)
274 prs := changePRs(states)
275 // The restack conflicts on changes klaus owns, and what klaus did
276 // about them; reading them changes nothing.
277 var restackList []restack.View
278 var err error
279 if hds, ok := store.(*run.HomeDirStore); ok && (report.Listing != nil || !report.Asked) {
280 if restackList, err = restackPass(ctx, hds, report.Listing, false); err != nil {
281 fmt.Fprintf(os.Stderr, "warning: reading restack conflicts: %v\n", err)
282 }
283 }
284 restacks := restackViews(restackList)
285
286 // The changes some run is still running on: any other run of one
287 // that isn't done is working.
288 changeOf := changeKeys(states)
289 busy := make(map[integration.ChangeKey]bool)
290 for i, s := range states {
291 if k, ok := changeOf(s); ok && statuses[i] == "running" {
292 busy[k] = true
293 }
294 }
295
296 for i, s := range states {
297 if err := ctx.Err(); err != nil {
298 return nil, err
299 }
300 status := statuses[i]
301 prompt := truncate(s.Prompt, 40)
302 var change *integration.Change
303 if status == "awaiting-integration" {
304 res := report.Runs[s.ID]
305 change = res.Change
306 if change == nil {
307 change = integration.RecordedChange(s)
308 }
309 status = pushedStatus(res.Verdict, change != nil)
310 if change != nil && awaitsReview(s, res.Verdict) {
311 status = "awaiting-review"
312 }
313 if change != nil && change.Title != "" {
314 prompt = truncate(change.Title, 40)
315 }
316 }
317 // A tracked valley change stands where the valley's listing says
318 // its active version does; tracking while the valley can't be
319 // asked.
320 if integration.TracksChange(s) && !s.SharedGitChanged() {
321 if view := report.Changes[valleyKey(s)]; view.Change != nil {
322 status = pushedStatus(view.Verdict, true)
323 if view.Change.Title != "" {
324 prompt = truncate(view.Change.Title, 40)
325 }
326 }
327 }
328 cost := formatCost(s)
329 issue := "-"
330 if s.Issue != nil {
331 issue = *s.Issue
332 }
333 repo := "-"
334 if s.TargetRepo != nil {
335 repo = truncate(*s.TargetRepo, 20)
336 }
337 host := "-"
338 if s.Host != nil {
339 host = *s.Host
340 }
341 ci, conflicts, behind, merge := "-", "-", "-", "-"
342 if prRef := extractPRRef(s); prRef != "" {
343 prState := ghClient.GetState(ctx, prRef)
344 switch prState {
345 case "MERGED":
346 status = prSettled(status, s, "merged")
347 merge = "merged"
348 case "CLOSED":
349 status = prSettled(status, s, "closed")
350 case gh.StateNoAccess:
351 // GitHub won't show this PR to us: nothing else to ask.
352 status = prSettled(status, s, "no-access")
353 default:
354 ci = ghClient.GetCI(ctx, prRef)
355 conflicts = ghClient.GetConflicts(ctx, prRef)
356 behindBy := ghClient.GetCommitsBehind(ctx, prRef)
357 if behindBy > 0 {
358 behind = fmt.Sprintf("%d", behindBy)
359 }
360 merge = computeMergeStatus(ci, conflicts, ghClient.GetReviewDecision(ctx, prRef), behindBy)
361 }
362 }
363
364 if s.ChangeID != "" && ci == "-" {
365 if view := report.Changes[valleyKey(s)]; view.Change != nil {
366 if c := checksCI(view.Change.Checks); c != "" {
367 ci = c
368 }
369 }
370 }
371
372 if _, ok := restacks[valleyKey(s)]; ok && s.ChangeID != "" && conflicts == "-" {
373 conflicts = "restack"
374 }
375
376 if k, ok := changeOf(s); ok && busy[k] && live(status) && !s.SharedGitChanged() {
377 status = "working"
378 }
379
380 statuses[i] = status
381 fmt.Fprintf(out, "%-22s %-10s %-26s %-8s %-6s %-20s %-15s %-8s %-10s %-10s %-8s %-10s %s\n",
382 s.ID, status, runBackendName(s), cost, issue, repo, host, changeLabel(s, changeOf, prs, handles), ci, conflicts, behind, merge, prompt)
383 }
384
385 // A run that changed the files its clone shares across worktrees
386 // says which, for the operator to check before git runs there again.
387 first := true
388 for _, s := range states {
389 if !s.SharedGitChanged() {
390 continue
391 }
392 if first {
393 fmt.Fprintln(out)
394 first = false
395 }
396 fmt.Fprintf(out, "%s changed its clone's shared git files while it ran: %s (in %s); check them before running git in that clone\n",
397 s.ID, strings.Join(s.SharedGit.Changed, ", "), s.SharedGit.Dir)
398 }
399
400 if failing := failingChecks(states, report.Changes); len(failing) > 0 {
401 fmt.Fprintln(out)
402 fmt.Fprintln(out, "Failed valley checks:")
403 for _, f := range failing {
404 fmt.Fprintf(out, " %s\n", f)
405 }
406 }
407
408 if len(restackList) > 0 {
409 fmt.Fprintln(out)
410 fmt.Fprintln(out, "Restack conflicts on changes flow owns:")
411 for _, v := range restackList {
412 fmt.Fprintf(out, " %s\n", v)
413 }
414 }
415
416 return statuses, nil
417}
418
419// prSettled is the status of run s, status so far, once GitHub says its PR
420// is settled (merged, closed or out of reach): settled, unless the run
421// still needs attention it took on with other runs' work (TookOver), which
422// its PR's fate settles nothing about, as on the dashboard.
423func prSettled(status string, s *run.State, settled string) string {
424 if status == "needs-attention" && (len(s.TookOver) > 0 || s.SharedGitChanged()) {
425 return status
426 }
427 return settled
428}
429
430func determineStatus(ctx context.Context, s *run.State, tc tmux.Client) string {
431 if s.Type == "session" {
432 if _, err := os.Stat(s.Worktree); err == nil {
433 return "active"
434 }
435 return "ended"
436 }
437
438 if s.Type == "track" {
439 if s.MergedAt != nil {
440 return "merged"
441 }
442 return "tracking"
443 }
444
445 // Running as the dashboard decides it: a pane that exists isn't enough
446 // when its command is dead, or, once the run finalized, idle.
447 if s.IsAgentRunningWith(run.TmuxDepsFor(ctx, tc)) {
448 return "running"
449 }
450
451 // The attention a run took on with other runs' work (TookOver) outlasts
452 // its PR's merge, as on the dashboard, and so does a change to the
453 // clone's shared git files.
454 if needsAttention(s) && len(s.TookOver) > 0 || s.SharedGitChanged() {
455 return "needs-attention"
456 }
457 if s.MergedAt != nil {
458 return "merged"
459 }
460 if needsAttention(s) {
461 return "needs-attention"
462 }
463 if s.PRURL != nil {
464 return "pr-created"
465 }
466 if s.PushedSHA != nil {
467 // Direct-push finish: the branch on origin waits for the operator.
468 // The status command refines this with an integration check.
469 return "awaiting-integration"
470 }
471 return "exited"
472}
473
474// live reports whether a status leaves something to do for a run that isn't
475// running: salvaged work, an open PR, or a pushed branch that hasn't landed,
476// gone, or been withdrawn or gained a newer version.
477func live(status string) bool {
478 switch status {
479 case "needs-attention", "pr-created", "awaiting-integration", "awaiting-review", "awaiting-approval",
480 "approved", "checks-failed", "conflicting", "uncertain", "stale", "rejected", "failed", "draft":
481 return true
482 }
483 return false
484}
485
486// pushedStatus is the status of a run awaiting integration once an
487// integration check has looked at it; valley says a valley knows the run's
488// change. An unknown verdict (no clone, origin unreachable) keeps it
489// awaiting.
490func pushedStatus(v integration.Verdict, valley bool) string {
491 switch v {
492 case integration.Integrated, integration.IntegratedContent:
493 return "integrated"
494 case integration.Gone:
495 return "branch-gone"
496 case integration.Ready:
497 return "awaiting-approval"
498 case integration.Unknown, integration.Awaiting:
499 if valley {
500 return "awaiting-approval"
501 }
502 return "awaiting-integration"
503 case integration.Superseded:
504 // The change has a newer version, the restacker's or a later
505 // run's; the change itself may still wait for approval.
506 return "older-version"
507 }
508 // approved, checks-failed, conflicting, uncertain, stale, rejected,
509 // failed, withdrawn, draft
510 return v.String()
511}
512
513// awaitsReview reports whether a valley change's version, which run s
514// pushed and a check says v of, awaits review rather than approval:
515// finalize left it a draft (ready_at_finalize off), klaus ready hasn't
516// marked it ready since, and the valley says it is still a draft, or can't
517// be asked. A draft whose review passed is marked ready with klaus ready.
518func awaitsReview(s *run.State, v integration.Verdict) bool {
519 if s == nil || s.Valley == nil || !s.Valley.Draft {
520 return false
521 }
522 return v == integration.Draft || v == integration.Unknown || v == integration.Awaiting
523}
524
525func formatCost(s *run.State) string {
526 if s.CostUSD != nil {
527 return fmt.Sprintf("$%.2f", *s.CostUSD)
528 }
529 if s.Budget != nil {
530 return fmt.Sprintf("<$%s", *s.Budget)
531 }
532 return "-"
533}
534
535// changeLabel names the change a run belongs to, for the CHANGE column: its
536// PR's number (#319), else its change's PR's (changePRs), else its valley
537// change's handle (changeHandles), else the first 8 characters of its
538// change ID, as the dashboard names a PR's or a change's row; "-" for a run
539// with none of them.
540func changeLabel(s *run.State, changeOf func(*run.State) (integration.ChangeKey, bool), prs, handles map[integration.ChangeKey]string) string {
541 k, _ := changeOf(s)
542 switch {
543 case s.PRURL != nil:
544 return formatPR(s)
545 case prs[k] != "":
546 return prs[k]
547 case handles[k] != "":
548 return handles[k]
549 case s.ChangeID != "":
550 return s.ChangeID[:min(8, len(s.ChangeID))]
551 }
552 return "-"
553}
554
555// changePRs names each change some run with a PR belongs to by that PR's
556// number, the newest such run's, as the dashboard puts the change's runs
557// without a PR on that PR's row.
558func changePRs(states []*run.State) map[integration.ChangeKey]string {
559 changeOf := changeKeys(states)
560 out := make(map[integration.ChangeKey]string)
561 by := make(map[integration.ChangeKey]*run.State) // the run whose PR names each change
562 for _, s := range states {
563 k, ok := changeOf(s)
564 if !ok || s.PRURL == nil || by[k] != nil && createdBefore(s, by[k]) {
565 continue
566 }
567 out[k], by[k] = formatPR(s), s
568 }
569 return out
570}
571
572// changeHandles names each valley change some run belongs to, so every run
573// on it, running or not, shows the same handle: the valley's listing's, which
574// is current (a handle lengthens when another change comes to share its
575// prefix); else, when the valley can't be asked or doesn't list the change,
576// the handle the latest run to record one got from finalize's ready or
577// launch's unready.
578func changeHandles(states []*run.State, listed map[integration.ChangeKey]integration.Result) map[integration.ChangeKey]string {
579 changeOf := changeKeys(states)
580 out := make(map[integration.ChangeKey]string)
581 by := make(map[integration.ChangeKey]*run.State) // the run whose record names each unlisted change
582 for _, s := range states {
583 k, ok := changeOf(s)
584 if !ok {
585 continue
586 }
587 if c := listed[valleyKey(s)].Change; c != nil {
588 out[k] = c.Handle
589 continue
590 }
591 h := recordedHandle(s)
592 if h == "" || by[k] != nil && createdBefore(s, by[k]) {
593 continue
594 }
595 out[k], by[k] = h, s
596 }
597 return out
598}
599
600// recordedHandle is the handle a run recorded for its change: from
601// finalize's ready, else from launch's unready; "" when neither got one.
602func recordedHandle(s *run.State) string {
603 if s.Valley != nil && s.Valley.Handle != "" {
604 return s.Valley.Handle
605 }
606 return s.UnreadyHandle()
607}
608
609func formatPR(s *run.State) string {
610 if s.PRURL == nil {
611 return "-"
612 }
613 url := *s.PRURL
614 // Extract PR number from URL
615 for i := len(url) - 1; i >= 0; i-- {
616 if url[i] == '/' {
617 return "#" + url[i+1:]
618 }
619 }
620 return url
621}
622
623// extractPRNumber returns the PR number (e.g. "18") from a run state, or "".
624func extractPRNumber(s *run.State) string {
625 if s.PRURL == nil {
626 return ""
627 }
628 url := *s.PRURL
629 for i := len(url) - 1; i >= 0; i-- {
630 if url[i] == '/' {
631 return url[i+1:]
632 }
633 }
634 return ""
635}
636
637// extractPRRef returns the full PR URL from a run state (for use with gh CLI),
638// or "" if no PRURL is set. Using the full URL ensures gh can find the PR
639// regardless of the current working directory.
640func extractPRRef(s *run.State) string {
641 if s.PRURL == nil {
642 return ""
643 }
644 return *s.PRURL
645}
646
647// computeMergeStatus determines overall merge readiness. behind is the base-ahead
648// commit count; a would-be-ready-but-behind PR reads "behind N" (rebased at merge)
649// so it is never shown as a clean "ready".
650func computeMergeStatus(ci, conflicts, reviewDecision string, behind int) string {
651 if conflicts == "yes" {
652 return "blocked"
653 }
654 if ci == "failing" {
655 return "blocked"
656 }
657 if strings.EqualFold(reviewDecision, "CHANGES_REQUESTED") {
658 return "blocked"
659 }
660 if ci == "pending" || reviewDecision == "unknown" {
661 return "pending"
662 }
663 if ci == "passing" && conflicts == "none" && (strings.EqualFold(reviewDecision, "APPROVED") || reviewDecision == "") {
664 if behind > 0 {
665 return fmt.Sprintf("behind %d", behind)
666 }
667 return "ready"
668 }
669 return "pending"
670}
671
672func truncate(s string, max int) string {
673 if len(s) <= max {
674 return s
675 }
676 return s[:max] + "..."
677}
678
679func init() {
680 rootCmd.AddCommand(statusCmd)
681}
682
683func runBackendName(s *run.State) string {
684 if s.Type == "track" {
685 return "-"
686 }
687 return runBackendModel(s)
688}
689
690// runBackendModel is a run's backend and model: the model the worker
691// reported, else the one launched with, else "(default model)".
692func runBackendModel(s *run.State) string {
693 b := s.Backend
694 if b == "" {
695 b = "claude"
696 }
697 model := s.ResolvedModel
698 if model == "" && s.Model != nil {
699 model = *s.Model
700 }
701 return review.BackendModel(b, model)
702}