gunk-dev/the-valley

status.go

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