From 46d4bf9c3761e5e23218901c0df23212e6f73c46 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 17 Nov 2026 12:13:47 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=90=9B=20Activity=20monitor:=20one=20?= =?UTF-8?q?rule=20for=20the=20human-gate=20pill=20and=20its=20verbs;=20nam?= =?UTF-8?q?e=20the=20real=20blocker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The gate pill lit 'Needs human · review' from the cached reviewer verdict for the head while its verbs acted only on a PR the hive had parked on a person, so a PR whose sign-off a person had already approved kept offering Approve / Request changes / Let hive decide and every click answered 'nothing to act on' (hivecommons/hive#18667). - stage_tracker_gate.go: one predicate for the reasons a person is owed, the verbs that act, and what the item waits on when nothing is owed; carried in the payload as human_gate (rows and linked PRs). - tracker-gate-truth.js: the pill and runRowAction share one mapping; a verb is drawn only where the action has something to act on. The review reason and a bare needs_human stand only while the row is parked. - Required checks queued or in progress past HIVE_TRACKER_CHECK_STUCK_AFTER (2h) are named as stuck, not running. - A stale click says what the item is waiting on and re-reads the tracker. Fixes #18769 Signed-off-by: Andy Anderson --- changelog.d/fixed-18769-tracker-gate-truth.md | 1 + src/docs/api-reference/dashboard-misc.md | 21 +- .../dashboard-sections/activity-monitor.md | 21 +- src/docs/env-vars.md | 1 + src/pkg/dashboard/stage_tracker.go | 6 + src/pkg/dashboard/stage_tracker_activity.go | 29 +- src/pkg/dashboard/stage_tracker_build.go | 1 + src/pkg/dashboard/stage_tracker_ci_stuck.go | 81 ++++ src/pkg/dashboard/stage_tracker_gate.go | 361 ++++++++++++++++++ src/pkg/dashboard/stage_tracker_gate_test.go | 232 +++++++++++ .../stage_tracker_gate_truth.test.js | 127 ++++++ .../stage_tracker_row_actions_test.go | 1 + .../static-src/js/tracker-actions.js | 4 +- .../static-src/js/tracker-gate-truth.js | 109 ++++++ .../static-src/js/tracker-human-gate.js | 18 +- .../static-src/js/tracker-row-layout.js | 4 +- .../static-src/js/tracker-row-render.js | 4 +- .../static-src/js/tracker-row-strip.js | 5 +- src/pkg/dashboard/static-src/manifest.txt | 1 + src/pkg/dashboard/static/index.html | 144 ++++++- src/pkg/dashboard/testdata/gate_states.json | 108 ++++++ 21 files changed, 1246 insertions(+), 33 deletions(-) create mode 100644 changelog.d/fixed-18769-tracker-gate-truth.md create mode 100644 src/pkg/dashboard/stage_tracker_ci_stuck.go create mode 100644 src/pkg/dashboard/stage_tracker_gate.go create mode 100644 src/pkg/dashboard/stage_tracker_gate_test.go create mode 100644 src/pkg/dashboard/stage_tracker_gate_truth.test.js create mode 100644 src/pkg/dashboard/static-src/js/tracker-gate-truth.js create mode 100644 src/pkg/dashboard/testdata/gate_states.json diff --git a/changelog.d/fixed-18769-tracker-gate-truth.md b/changelog.d/fixed-18769-tracker-gate-truth.md new file mode 100644 index 0000000000..07c33ec8c1 --- /dev/null +++ b/changelog.d/fixed-18769-tracker-gate-truth.md @@ -0,0 +1 @@ +- Activity monitor: a row no longer offers **Approve**, **Request changes…** or **Let hive decide** when no decision is pending. The gate pill and its verbs now read one rule (the payload's new `human_gate`), so a PR whose reviewer sign-off a person already approved shows *Approved by @login · waiting on …* naming the real blocker instead of *Needs human · review*; triage and author-owned rows keep their own lead instead of a decision pill; a hold or sentinel pill on an unparked row keeps only its own answer. Required checks queued or in progress past `HIVE_TRACKER_CHECK_STUCK_AFTER` (default `2h`) read **stuck** and are named, not shown as running, and a verb clicked from a stale view says what the item is waiting on and refreshes the row ([#18769](https://github.com/hivecommons/hive/issues/18769)). diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 227d764263..b912a1e4eb 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -5,12 +5,29 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f `GET /api/stage-tracker` adds independent PR `ci_activity`, `review_activity` and `code_activity` observations, also copied to `linked_prs[]`. Each is -`{head, state, caption, detail?, actor?, source, observed_at?, since?, blocker?, url?, active?, checks_passed?, checks_total?, checks_failed?, checks_failing?, checks_pending?, perspectives_done?, perspectives_total?, perspectives?}`. +`{head, state, caption, detail?, actor?, source, observed_at?, since?, blocker?, url?, active?, checks_passed?, checks_total?, checks_failed?, checks_failing?, checks_pending?, checks_stuck?, stuck_since?, perspectives_done?, perspectives_total?, perspectives?}`. These are display evidence, **not merge authorization**. An absent timestamp means unknown freshness; a different head invalidates the observation. `detail?` is the longer, plain-language sentence behind caption. `checks_failing?` and `checks_pending?` are string lists of check names; `perspectives?` list -per-perspective verdicts on the head. CI is classified against the resolved +per-perspective verdicts on the head. `checks_stuck?` names the pending checks +that have been queued or in progress longer than `HIVE_TRACKER_CHECK_STUCK_AFTER` +(default `2h`) and `stuck_since?` is when the oldest of them started: such a +check is not running in any useful sense, and when every pending check is stuck +the caption reads `CI stuck · …` and `active` is false. + +Every open issue and PR row (and each `linked_prs[]` entry that mirrors a listed +PR) also carries `human_gate`: `{reasons, actions, answered?, answered_by?, waiting_on?}`. +`reasons` are the things a person is owed right now (`review`, `decision`, +`sentinel`, `hold`; empty when nothing is); `actions` are the gate verbs that +would act on the row (`decide:approve`, `gate:request-changes`, `decide:delegate`, +`gate:decide`, `gate:confirm-sentinel`, `release`) — a verb absent from the list +has nothing to act on and is never drawn. `answered` is true when the reviewer +asked for a person's sign-off on this head and the hive no longer parks the PR +on it, with `answered_by` the approver when the lane recorded one. `waiting_on` +is `{kind, text, checks?}` on a PR with no reasons: what it actually waits on +(`conflict`, `author`, `fixing`, `checks-failing`, `checks-stuck`, +`checks-missing`, `ci-running`, `review-pending`, `merge-queue`). CI is classified against the resolved required set when branch protection is known, otherwise against every check run observed on the head (checks_total == 0 means no count could be made). Review assignment comes from dispatch, current work additionally requires its actual diff --git a/src/docs/dashboard-sections/activity-monitor.md b/src/docs/dashboard-sections/activity-monitor.md index 916e0b6435..dc4db7b00c 100644 --- a/src/docs/dashboard-sections/activity-monitor.md +++ b/src/docs/dashboard-sections/activity-monitor.md @@ -252,13 +252,30 @@ Every row a person must settle carries exactly **one** control for it ([#17470]( | Reason | Set by | Verbs | What gets posted | |---|---|---|---| -| `review` | the review verdict requires a human on this head (`review_activity.state: human_decision`) | **Approve** · **Request changes…** · **Let hive decide** | Approve posts `/lgtm` + `/approve` on the current head (`…/items/{n}/decision`, `approve`); Request changes opens a modal whose text is posted as `/hive decision ` (`decision: direction`), the author agent pushes a new head; Let hive decide records a `/hive decision` under the hive's policy. | -| `decision` | `stage/085-needs-decision` on a PR, `045` on an issue, or a `needs-decision` / `needs-human` modifier | **Decide…** · **Approve as-is** (PR rows; *Approve* when stacked with `review`) · **Let hive decide** | Decide opens a modal with the question pre-filled; the answer is posted as `/hive decision `; Approve as-is is the GitHub approval of the head as it stands; Let hive decide as above. An issue with no PR offers Decide… and Let hive decide only. | +| `review` | the review verdict requires a human on this head (`review_activity.state: human_decision`) **and** the hive parks the PR on it (085 / `needs-decision` / ready for human merge) | **Approve** · **Request changes…** · **Let hive decide** | Approve posts `/lgtm` + `/approve` on the current head (`…/items/{n}/decision`, `approve`); Request changes opens a modal whose text is posted as `/hive decision ` (`decision: direction`), the author agent pushes a new head; Let hive decide records a `/hive decision` under the hive's policy. | +| `decision` | `stage/085-needs-decision` on a PR, `045` on an issue, or a `needs-decision` / `needs-human` modifier; `needs_human` alone only on a parked row | **Decide…** · **Approve as-is** (PR rows; *Approve* when stacked with `review`) · **Let hive decide** | Decide opens a modal with the question pre-filled; the answer is posted as `/hive decision `; Approve as-is is the GitHub approval of the head as it stands; Let hive decide as above. An issue with no PR offers Decide… and Let hive decide only. | | `sentinel` | the `sentinel-alert` label or blocking findings on this head (`sentinel_alert`, not the trusted-author notice) | **Confirm safe** · **Let hive decide** | Confirm safe comments `` with the person's words and removes the sentinel label (`POST …/items/{n}/sentinel-confirm`, audited `repo_item_sentinel_confirm`); Let hive decide never clears the alert. | | `hold` | a `hold` / `do-not-merge*` label (`hold`, `modifiers: hold`) | **Release hold** · **Let hive decide** | Release hold removes the label (`POST …/items/{n}/hold`, `{"held": false}`); Let hive decide as above. | Every verb runs `runRowAction` — the row menu's own path: the in-app confirm or prompt modal (never a native dialog), the result toast saying what was posted, the acting row — and the pill reads **settling…** (dashed outline, verbs disabled) until the next snapshot re-renders the row. A verb the viewer cannot run is greyed with the reason, never hidden. The review verdict's own question is not a second reason: a `requires_human` verdict on a 085 PR reads `review` alone; `review, sentinel` when the sentinel also flags it. +**The pill and its verbs read one rule** ([#18769](https://github.com/hivecommons/hive/issues/18769)). A row once showed *Needs human · review* with **Approve**, **Request changes…** and **Let hive decide** while the click answered *nothing to act on — #18667 is not waiting on that decision*: the pill read the cached reviewer verdict for the head, the action read whether the hive had parked the PR on a person, and a verdict never changes for a head, so the pill outlived the approval that answered it. Now both come from the same predicate, stated by the server per row as `human_gate` (`reasons`, `actions`, `answered`, `waiting_on`) and applied by the page to the rows it draws: + +| Row state | Pill | Verbs offered | +|---|---|---| +| Parked at 085 on the reviewer's sign-off question | **Needs human · review** | Approve · Request changes… · Let hive decide | +| Parked at 085 / 045, or wearing `needs-decision` | **Needs human · decision** | Decide… · Approve as-is (PR rows) · Let hive decide | +| `needs-human` label on a PR the hive has not parked | **Needs human · decision** | Decide… only | +| Sentinel alert on a PR that is not parked | **Needs human · sentinel** | Confirm safe only | +| Hold on a PR that is not parked | **Needs human · hold** | Release hold only | +| Ready for human merge (090) with a sentinel alert or hold | reasons stacked as before | every verb of those reasons | +| Sign-off question answered — a person approved the head, the PR left 085 | no gate pill; a passive **Approved by @login · waiting on …** pill (*No decision pending · waiting on …* when the lane recorded no approver) | none | +| Triage needed, or a human author's turn (`needs_human` with no park) | no gate pill; the row's lead (**Accept triage**, **Adopt**) | the lead only | + +**Let hive decide**, **Approve** and **Approve as-is** are drawn only where the action has a decision to act on (a parked PR, an issue's one parked PR, an issue parked at 045, or an issue with several open PRs for *Let hive decide*); a hold or sentinel pill on a row that is not parked keeps only its own answer. The reviewer's `requires_human` verdict lights `review` only while the hive parks the PR on it; afterwards the Review track reads *signed off* (*no sign-off pending* when the lane recorded no approver), never *needs owner sign-off*. + +When no decision is pending the row names what it actually waits on (`human_gate.waiting_on`), the first that applies: a merge conflict with the base; the author's turn; required checks failing (named); required checks **stuck** (named); required checks not reported (named); CI running (*n/m*); the review re-run on the new head; the merge queue. A required check that has been queued or in progress longer than `HIVE_TRACKER_CHECK_STUCK_AFTER` (default two hours — well past the slowest pipeline) is **stuck**, not running: the CI track reads *CI 67/69 · 'PR Type', 'PR Issue' stuck* (*13 running · 2 stuck (…)* while other checks still move), its hover says nothing finishes a stuck check on its own, and when every pending check is stuck the track stops pulsing. A verb clicked from a stale view — the row re-rendered between the paint and the click — answers *nothing to act on — #N is waiting on required checks stuck: PR Type, PR Issue* and the tracker re-reads the server at once so the row drops the verb. + A **secondary row of a shared PR** — an issue drawn under another listed issue's row because one PR closes both ([#17333](https://github.com/hivecommons/hive/issues/17333)) — never renders a gate pill or an amber chevron of its own; its *decision pending on #N* chip is a link that scrolls to and focuses the row that carries the gate. #### Unauthorized pill diff --git a/src/docs/env-vars.md b/src/docs/env-vars.md index 49a0f8724c..efbc0ebeb2 100644 --- a/src/docs/env-vars.md +++ b/src/docs/env-vars.md @@ -49,6 +49,7 @@ behavior. [Maintenance limitations](#keeping-this-reference-current) still apply | `HIVE_CONFIG` | No | `/etc/hive/hive.yaml` | Default config path used before the `--config` flag is parsed; an explicit `--config` outranks it, so `entrypoint.sh` also appends `--config "$HIVE_CONFIG"` to the launch argv when it is set ([#4973](https://github.com/hivecommons/hive/issues/4973)). The dashboard also uses it when reporting config provenance — which is why the two must not disagree. | | `HIVE_MODE` | No | spoke/dashboard mode | Set to `hub` to run the hub server instead of the spoke dashboard. | | `HIVE_HUB_PORT` | No | `3001` | Hub listen port when `HIVE_MODE=hub`. | +| `HIVE_TRACKER_CHECK_STUCK_AFTER` | No | `2h` | Go duration a required check may stay queued or in progress before the activity monitor calls it **stuck** instead of running (`ci_activity.checks_stuck`, the `CI stuck · …` caption and the *waiting on required checks stuck* blocker). Read on every tracker build; an unparsable or non-positive value falls back to the default. | | `HIVE_SINGLETON_LOCK` | No | `/var/run/hive-metrics/hive.singleton.lock` when available, otherwise OS temp dir | Overrides the process singleton lock path. Set exactly `off` only for local development where duplicate processes are intentional. | | `HIVE_GITHUB_TOKEN` | Required unless GitHub App auth is configured | none | Main PAT fallback for `github.token`; also used by fleet/stat fallback paths and some deployment manifests. Missing PAT scopes surface as request-time 403s — see [Required PAT scopes](github-app-setup.md#personal-access-token-pat-scopes). | | `GH_APP_KEY_FILE` | No | configured `github.key_file`, then `/data/gh-app-key.pem` or `/secrets/gh-app-key.pem` in provisioned paths | GitHub App private-key file fallback. | diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 3d2d1418e8..3b97811d1e 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -471,6 +471,10 @@ type StageTrackerItem struct { // 095 / 100): state, what holds it, whether hive's merge sweep is on // it now, the next pass and the soak countdown (hivecommons/hive#15073). MergeGate *StageTrackerMergeGate `json:"merge_gate,omitempty"` + // HumanGate is the row's live human-gate state: the reasons a person is + // owed something now, the verbs that would act, and what the item + // waits on when nothing is owed (stage_tracker_gate.go). + HumanGate *StageTrackerHumanGate `json:"human_gate,omitempty"` // Soak is the soak clock while the lane holds this head for the soak // window, at 060/080/095: when it started, when it ends, the window // and the head it was measured on. The SPA counts it down in place. @@ -813,6 +817,8 @@ type StageTrackerLinkedPR struct { SoakRemainingSeconds int64 `json:"soak_remaining_seconds,omitempty"` MergeGate *StageTrackerMergeGate `json:"merge_gate,omitempty"` MergeTrain *StageTrackerMergeTrain `json:"merge_train,omitempty"` + // HumanGate mirrors the nested PR's own row gate (stage_tracker_gate.go). + HumanGate *StageTrackerHumanGate `json:"human_gate,omitempty"` // LeftTrain mirrors the nested PR's own row field so the sub-row's // hover can say it left its train while under repair. LeftTrain *StageTrackerLeftTrain `json:"left_train,omitempty"` diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 5bb980b41a..56b96e6e87 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -44,6 +44,12 @@ type StageTrackerActivity struct { // (running, queued, or not reported), so the chevron can name the last // one or two the head waits on (hivecommons/hive#16630). ChecksPending []string `json:"checks_pending,omitempty"` + // ChecksStuck names the pending checks that have been queued or in + // progress longer than trackerCheckStuckAfter: they are not running in + // any useful sense and will not finish on their own + // (hivecommons/hive#18769). StuckSince is when the oldest one started. + ChecksStuck []string `json:"checks_stuck,omitempty"` + StuckSince *time.Time `json:"stuck_since,omitempty"` // Perspective counts on the current head for the Review track: Total is // the swarm's expected set for this PR (configured perspectives plus any // extra one dispatched or reported for the head), Done the ones with a @@ -88,8 +94,8 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA out.Source += "+github-commit-statuses" } if !a.RequiredKnown || a.RequiredSource == "" || len(a.RequiredChecks) == 0 || len(a.Required) == 0 { - stageTrackerCountHeadChecks(out, a) - out.Active = out.State == "running" + stageTrackerCountHeadChecks(out, a, now) + out.Active = out.State == "running" && !stageTrackerAllChecksStuck(out) return out } type requiredObservation struct { @@ -124,8 +130,8 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA } } if !found { - stageTrackerCountHeadChecks(out, a) - out.Active = out.State == "running" + stageTrackerCountHeadChecks(out, a, now) + out.Active = out.State == "running" && !stageTrackerAllChecksStuck(out) return out } } @@ -142,6 +148,8 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA // Required checks with no run at all, or only a pending commit status: // on a Prow repository, a presubmit that never ran or has not finished. presubmitWaiting := map[string]bool{} + // Per required-check name: when its queued or running observation began. + pendingSince := map[string]time.Time{} // Required checks with no run on the head while commit statuses were // not read: unknown rather than missing, with the no-run caption. noRunUnread := map[string]bool{} @@ -189,6 +197,9 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA if state != "passing" && state != "failing" && state != "skipped" { settled[name] = false } + if (state == "running" || state == "queued") && check.Since != nil { + pendingSince[name] = *check.Since + } // A red required check leads, then missing/unknown, then running/queued. rank := map[string]int{"passing": 0, "queued": 1, "running": 2, "skipped": 3, "unknown": 4, "missing": 5, "failing": 6} if previous, seen := perName[name]; !seen || rank[state] >= rank[previous] { @@ -328,6 +339,7 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA // age rides ObservedAt for the tooltip, never a dimmer state // (hivecommons/hive#16643). out.Active = out.State == "running" || out.State == "queued" + stageTrackerMarkStuckChecks(out, pendingSince, now) stageTrackerAttachTide(out, full, presubmitWaiting) return out } @@ -419,7 +431,7 @@ func pluralVerb(n int, one, many string) string { // when any name is red, running while names still lack a final result, // and unknown — "no check results observed" — only when the head has no // check run at all. -func stageTrackerCountHeadChecks(out *StageTrackerActivity, a *github.PRCIActivity) { +func stageTrackerCountHeadChecks(out *StageTrackerActivity, a *github.PRCIActivity, now time.Time) { type tally struct { passing, failing bool since time.Time @@ -449,6 +461,7 @@ func stageTrackerCountHeadChecks(out *StageTrackerActivity, a *github.PRCIActivi } } out.ChecksTotal = len(order) + pendingSince := map[string]time.Time{} for _, name := range order { t := byName[name] switch { @@ -459,8 +472,14 @@ func stageTrackerCountHeadChecks(out *StageTrackerActivity, a *github.PRCIActivi out.ChecksPassed++ default: out.ChecksPending = append(out.ChecksPending, name) + if !t.since.IsZero() { + pendingSince[name] = t.since + } } } + // The caller sets Active from the state on return; a head whose every + // pending check is stuck reports no motion there. + defer func() { stageTrackerMarkStuckChecks(out, pendingSince, now) }() if out.ChecksTotal == 0 { return } diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index a305256d06..b7f626f710 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -599,6 +599,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto stageTrackerMarkClosedBy(resp.Items, s.mergedLedger().ClosedBy) stageTrackerResolveActors(resp.Items) stageTrackerResolveHumanAttention(resp.Items) + stageTrackerResolveHumanGates(resp.Items, now) sort.SliceStable(resp.Items, stageTrackerLess(resp.Items)) return resp } diff --git a/src/pkg/dashboard/stage_tracker_ci_stuck.go b/src/pkg/dashboard/stage_tracker_ci_stuck.go new file mode 100644 index 0000000000..31cafcb5af --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_ci_stuck.go @@ -0,0 +1,81 @@ +package dashboard + +import ( + "fmt" + "os" + "strings" + "time" +) + +// A required check that has been queued or in progress far longer than a +// check run normally takes is stuck, not running: its reporter died or +// could not write the result (hivecommons/hive#18764 left `PR Type` and +// `PR Issue` in progress for hours), and nothing finishes it without a +// re-run. The CI track names such checks instead of presenting them as +// motion (hivecommons/hive#18769). + +// trackerCheckStuckAfterEnv overrides trackerCheckStuckAfterDefault with a +// Go duration ("45m", "3h"). +const trackerCheckStuckAfterEnv = "HIVE_TRACKER_CHECK_STUCK_AFTER" + +// trackerCheckStuckAfterDefault is how long a required check may stay +// queued or in progress before the tracker calls it stuck. It sits well +// past the slowest pipeline the fleet runs, so a long image build is never +// called stuck. +const trackerCheckStuckAfterDefault = 2 * time.Hour + +// trackerCheckStuckAfter resolves the stuck threshold. +func trackerCheckStuckAfter() time.Duration { + if raw := strings.TrimSpace(os.Getenv(trackerCheckStuckAfterEnv)); raw != "" { + if d, err := time.ParseDuration(raw); err == nil && d > 0 { + return d + } + } + return trackerCheckStuckAfterDefault +} + +// stageTrackerMarkStuckChecks names the pending checks whose queued or +// running observation began more than the stuck threshold ago and, when +// every check the head still waits on is one of them, says so in the +// caption: the head is not running, it is stuck. pendingSince maps a +// pending check to when that observation began. +func stageTrackerMarkStuckChecks(out *StageTrackerActivity, pendingSince map[string]time.Time, now time.Time) { + if out == nil || (out.State != "running" && out.State != "queued") || len(pendingSince) == 0 { + return + } + after := trackerCheckStuckAfter() + for _, name := range out.ChecksPending { + since, ok := pendingSince[name] + if !ok || since.IsZero() || now.Sub(since) <= after { + continue + } + out.ChecksStuck = append(out.ChecksStuck, name) + if out.StuckSince == nil || since.Before(*out.StuckSince) { + at := since + out.StuckSince = &at + } + } + if len(out.ChecksStuck) == 0 { + return + } + names := make([]string, 0, len(out.ChecksStuck)) + for _, name := range out.ChecksStuck { + names = append(names, stageTrackerCheckName(name)) + } + span := stageTrackerHumanGateSpan(now.Sub(*out.StuckSince)) + out.Detail = strings.TrimSpace(out.Detail + fmt.Sprintf(" Stuck: %s %s been queued or in progress for %s, far longer than a check normally runs. Nothing finishes a stuck check on its own: re-run it, or fix whatever reports its result.", + strings.Join(names, ", "), pluralVerb(len(names), "has", "have"), span)) + if len(out.ChecksStuck) < len(out.ChecksPending) { + out.Caption += fmt.Sprintf(" · %d stuck", len(out.ChecksStuck)) + return + } + // Every check the head waits on is stuck: no motion to show. + out.Caption = "CI stuck · " + strings.Join(names, ", ") + " in progress " + span + out.Active = false +} + +// stageTrackerAllChecksStuck reports a head whose every pending check is +// stuck: nothing on it is in motion. +func stageTrackerAllChecksStuck(a *StageTrackerActivity) bool { + return a != nil && len(a.ChecksStuck) > 0 && len(a.ChecksStuck) >= len(a.ChecksPending) +} diff --git a/src/pkg/dashboard/stage_tracker_gate.go b/src/pkg/dashboard/stage_tracker_gate.go new file mode 100644 index 0000000000..2b167dab17 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_gate.go @@ -0,0 +1,361 @@ +package dashboard + +import ( + "fmt" + "slices" + "strconv" + "strings" + "time" +) + +// The human gate's one source of truth (hivecommons/hive#18769). +// +// A tracker row used to derive its "Needs human · review" pill from the +// cached reviewer verdict for the head (review_activity.state == +// human_decision) while the verbs on that pill acted only on a PR the hive +// had actually parked on a person. A verdict never changes for a head, so +// once a person approved it the pill stayed and every verb answered +// "nothing to act on" (hivecommons/hive#18667). stageTrackerHumanGateFor is the +// single predicate now: it names the reasons a person is owed something +// right now, the verbs that would act, and — when nothing is owed — what +// the item is actually waiting on. The payload carries it as `human_gate`; the +// SPA's pill and its action precondition both read the same rule +// (tracker-gate-truth.js mirrors it for rows the page synthesizes, and +// testdata/gate_states.json pins the two implementations to one table). + +// Gate reason keys, in the order they stand on the pill. +const ( + gateReasonReview = "review" + gateReasonDecision = "decision" + gateReasonSentinel = "sentinel" + gateReasonHold = "hold" +) + +// Gate verbs that are not decision actions (the decide:* ids live in +// stage_tracker_decision.go). +const ( + gateActionRequestChanges = "gate:request-changes" + gateActionDecide = "gate:decide" + gateActionConfirmSentinel = "gate:confirm-sentinel" +) + +// What an item with no pending decision waits on. +const ( + gateWaitConflict = "conflict" + gateWaitAuthor = "author" + gateWaitFixing = "fixing" + gateWaitChecksFailing = "checks-failing" + gateWaitChecksStuck = "checks-stuck" + gateWaitChecksMissing = "checks-missing" + gateWaitCIRunning = "ci-running" + gateWaitReview = "review-pending" + gateWaitMergeQueue = "merge-queue" +) + +// stageTrackerHumanGateDelegateAllMin mirrors the SPA's +// STAGE_TRACKER_DELEGATE_ALL_MIN: an issue row with this many open PRs +// delegates all of them. +const stageTrackerHumanGateDelegateAllMin = 2 + +// stageTrackerHumanGateTerminal mirrors the SPA's STAGE_TRACKER_TERMINAL: a row +// at or past it is merged or closed. +const stageTrackerHumanGateTerminal = 110 + +// stageTrackerHumanGateShortSHA is how many characters of a head the waiting +// text prints. +const stageTrackerHumanGateShortSHA = 7 + +// stageTrackerHumanGateOrder is the canonical reason order. +var stageTrackerHumanGateOrder = []string{gateReasonReview, gateReasonDecision, gateReasonSentinel, gateReasonHold} + +// stageTrackerHumanGateVerbs maps a reason to its verbs (the SPA's +// STAGE_TRACKER_GATE_VERBS). +var stageTrackerHumanGateVerbs = map[string][]string{ + gateReasonReview: {decisionActionApprove, gateActionRequestChanges, decisionActionDelegate}, + gateReasonDecision: {gateActionDecide, decisionActionApprove, decisionActionDelegate}, + gateReasonSentinel: {gateActionConfirmSentinel, decisionActionDelegate}, + gateReasonHold: {decisionActionRelease, decisionActionDelegate}, +} + +// stageTrackerHumanGatePROnly are the verbs that need a head to act on. +var stageTrackerHumanGatePROnly = []string{decisionActionApprove, gateActionRequestChanges} + +// stageTrackerHumanGateAuthorDCO are the reasons that make needs_human the +// author's move rather than a decision (hivecommons/hive#17789). +var stageTrackerHumanGateAuthorDCO = []string{"dco-missing", "hive-signoff-attribution"} + +// StageTrackerHumanGate is the live human-gate state of one tracker row. +type StageTrackerHumanGate struct { + // Reasons a person is owed something right now, in pill order; empty + // when nothing is. + Reasons []string `json:"reasons"` + // Actions are the verbs that would act on the item now. A verb absent + // here answers "nothing to act on" and is never drawn. + Actions []string `json:"actions"` + // Answered is true when the reviewer asked for a person's sign-off on + // this head and the hive no longer parks the PR on it; AnsweredBy is + // the approver when the lane recorded one. + Answered bool `json:"answered,omitempty"` + AnsweredBy string `json:"answered_by,omitempty"` + // WaitingOn names what the item actually waits on when no decision is + // pending. + WaitingOn *StageTrackerHumanGateWait `json:"waiting_on,omitempty"` +} + +// StageTrackerHumanGateWait is the real blocker of a row nobody owes a decision on. +type StageTrackerHumanGateWait struct { + // Kind is one of the gateWait* constants. + Kind string `json:"kind"` + // Text is the sentence the row and the stale-click toast print. + Text string `json:"text"` + // Checks names the required checks behind a checks-* kind. + Checks []string `json:"checks,omitempty"` +} + +// stageTrackerHumanGateInert reports rows that never carry a gate: closed, +// superseded, adopted, merged or draft. +func stageTrackerHumanGateInert(it StageTrackerItem) bool { + if it.Superseded != nil || it.SupersededBy > 0 || it.AdoptedBy > 0 || it.Stage >= stageTrackerHumanGateTerminal { + return true + } + return slices.Contains(it.Modifiers, "merged") || slices.Contains(it.Modifiers, modDraft) +} + +// stageTrackerHumanGatePRParked mirrors the SPA's stageTrackerPRParked: the PR +// is parked on a person (045 / 085, the needs-decision pill, superseded, or +// ready for a human merge). +func stageTrackerHumanGatePRParked(stage int, modifiers []string, superseded, manualMerge bool, humanMergeReason string) bool { + return superseded || slices.Contains(modifiers, modNeedsDecision) || + stage == trackerNumberIssueDecision || stage == trackerNumberNeedsDecision || + manualMerge || strings.TrimSpace(humanMergeReason) != "" +} + +// stageTrackerHumanGateOpenLinkedPR reports a nested PR that is still in play. +func stageTrackerHumanGateOpenLinkedPR(lp StageTrackerLinkedPR) bool { + return lp.State != "closed" && lp.SupersededBy == 0 && lp.AdoptedBy == 0 && + lp.Stage < stageTrackerHumanGateTerminal && !slices.Contains(lp.Modifiers, "merged") +} + +// stageTrackerHumanGateDecisionTarget mirrors the SPA's +// stageTrackerDecisionTarget: whether a decide:* action on the row has an +// item to act on. A PR decides itself when parked; an issue decides its one +// parked nested PR, else itself when parked at 045. +func stageTrackerHumanGateDecisionTarget(it StageTrackerItem) bool { + if it.Kind == "pr" { + return stageTrackerHumanGatePRParked(it.Stage, it.Modifiers, it.Superseded != nil, it.ManualMerge, it.HumanMergeReason) + } + parked := 0 + for _, lp := range it.LinkedPRs { + if stageTrackerHumanGatePRParked(lp.Stage, lp.Modifiers, false, lp.ManualMerge, lp.HumanMergeReason) && stageTrackerHumanGateOpenLinkedPR(lp) { + parked++ + } + } + if parked > 0 { + return parked == 1 + } + if it.Mirrored { + return false + } + return slices.Contains(it.Modifiers, modNeedsDecision) || it.Stage == trackerNumberIssueDecision +} + +// stageTrackerHumanGateAccepts is the action precondition: whether verb would +// act on the row. It is the rule the SPA's runRowAction applies before it +// posts anything, so a verb this refuses is never offered. +func stageTrackerHumanGateAccepts(it StageTrackerItem, verb string) bool { + switch { + case verb == decisionActionDelegate: + if stageTrackerHumanGateDecisionTarget(it) { + return true + } + open := 0 + for _, lp := range it.LinkedPRs { + if stageTrackerHumanGateOpenLinkedPR(lp) { + open++ + } + } + return it.Kind != "pr" && open >= stageTrackerHumanGateDelegateAllMin + case strings.HasPrefix(verb, "decide:"): + return stageTrackerHumanGateDecisionTarget(it) + } + return true +} + +// stageTrackerHumanGateOnHead reports an activity recorded for the row's head. +func stageTrackerHumanGateOnHead(a *StageTrackerActivity, head string) bool { + return a != nil && (a.Head == "" || head == "" || strings.EqualFold(a.Head, head)) +} + +// stageTrackerHumanGateReasons derives the reasons a person is owed on the row. +func stageTrackerHumanGateReasons(it StageTrackerItem) []string { + if stageTrackerHumanGateInert(it) { + return nil + } + pr := it.Kind == "pr" + target := stageTrackerHumanGateDecisionTarget(it) + var out []string + // A requires_human verdict is a live ask only while the hive parks the + // PR on it. Off the park the person has answered (or the head is not + // there yet): the verdict for the head stays as it was recorded. + review := pr && stageTrackerHumanGateOnHead(it.ReviewActivity, it.Head) && it.ReviewActivity.State == "human_decision" && target + if review { + out = append(out, gateReasonReview) + } + decisionStage := it.Stage == trackerNumberNeedsDecision || (!pr && it.Stage == trackerNumberIssueDecision) + labelled := decisionStage || slices.Contains(it.Modifiers, modNeedsDecision) || slices.Contains(it.Modifiers, modNeedsHuman) + // needs_human alone (triage needed, a human author's turn, ready for + // human merge) is a decision only where a decision can be recorded. + bare := stageTrackerNeedsHuman(it) && !slices.Contains(stageTrackerHumanGateAuthorDCO, strings.TrimSpace(it.Reason)) && target + blocked := it.Blocker != nil && strings.TrimSpace(it.Blocker.Short) != "" + if (labelled || bare) && strings.TrimSpace(it.UnauthorizedStep) == "" && !blocked && !review { + out = append(out, gateReasonDecision) + } + if it.SentinelAlert && !it.SentinelNotice { + out = append(out, gateReasonSentinel) + } + if it.Hold != nil || slices.Contains(it.Modifiers, modHold) { + out = append(out, gateReasonHold) + } + return out +} + +// stageTrackerHumanGateActions is the union of the reasons' verbs, in reason +// order, de-duplicated, keeping only what the action precondition accepts. +func stageTrackerHumanGateActions(it StageTrackerItem, reasons []string) []string { + out := []string{} + for _, key := range stageTrackerHumanGateOrder { + if !slices.Contains(reasons, key) { + continue + } + for _, verb := range stageTrackerHumanGateVerbs[key] { + if slices.Contains(out, verb) || (it.Kind != "pr" && slices.Contains(stageTrackerHumanGatePROnly, verb)) || !stageTrackerHumanGateAccepts(it, verb) { + continue + } + out = append(out, verb) + } + } + return out +} + +// stageTrackerHumanGateFor is the gate of one row: nil for a row that never +// carries one. +func stageTrackerHumanGateFor(it StageTrackerItem, now time.Time) *StageTrackerHumanGate { + if (it.Kind != "pr" && it.Kind != "issue") || stageTrackerHumanGateInert(it) { + return nil + } + reasons := stageTrackerHumanGateReasons(it) + g := &StageTrackerHumanGate{Reasons: append([]string{}, reasons...), Actions: stageTrackerHumanGateActions(it, reasons)} + if it.Kind != "pr" { + return g + } + if stageTrackerHumanGateOnHead(it.ReviewActivity, it.Head) && it.ReviewActivity.State == "human_decision" && !slices.Contains(reasons, gateReasonReview) { + g.Answered, g.AnsweredBy = true, strings.TrimPrefix(strings.TrimSpace(it.HumanApprover), "@") + } + if len(reasons) == 0 { + g.WaitingOn = stageTrackerHumanGateWaitingOn(it, now) + } + return g +} + +// stageTrackerHumanGateWaitingOn names what a PR nobody owes a decision on is +// waiting for, the first that applies: a conflict, its author, required +// checks (red, stuck, unreported, running), the review of this head, the +// merge queue. +func stageTrackerHumanGateWaitingOn(it StageTrackerItem, now time.Time) *StageTrackerHumanGateWait { + if slices.Contains(it.Modifiers, modNeedsRebase) || (it.MergeTrain != nil && it.MergeTrain.State == MergeGateStateRebaseExhausted) { + base := strings.TrimSpace(it.BaseRef) + if base == "" { + base = "its base branch" + } + return &StageTrackerHumanGateWait{Kind: gateWaitConflict, Text: "blocked by a merge conflict with " + base} + } + switch it.Stage { + case trackerNumberNeedsAuthor, trackerNumberReturned: + who := strings.TrimPrefix(strings.TrimSpace(it.Author), "@") + if who == "" { + return &StageTrackerHumanGateWait{Kind: gateWaitAuthor, Text: "the author's turn"} + } + return &StageTrackerHumanGateWait{Kind: gateWaitAuthor, Text: "the author's turn (@" + who + ")"} + case trackerNumberFixing: + return &StageTrackerHumanGateWait{Kind: gateWaitFixing, Text: "the hive fixing this head"} + } + if ci := it.CIActivity; stageTrackerHumanGateOnHead(ci, it.Head) { + tally := "" + if ci.ChecksTotal > 0 { + tally = fmt.Sprintf(" (%d/%d)", ci.ChecksPassed, ci.ChecksTotal) + } + switch { + case len(ci.ChecksFailing) > 0 && ci.State == "failing": + return &StageTrackerHumanGateWait{Kind: gateWaitChecksFailing, Checks: ci.ChecksFailing, Text: "required checks failing: " + strings.Join(ci.ChecksFailing, ", ")} + case len(ci.ChecksStuck) > 0: + text := "required checks stuck: " + strings.Join(ci.ChecksStuck, ", ") + if ci.StuckSince != nil && now.After(*ci.StuckSince) { + text += " (in progress " + stageTrackerHumanGateSpan(now.Sub(*ci.StuckSince)) + ", far longer than a normal run)" + } + if len(ci.ChecksPending) > len(ci.ChecksStuck) { + text += " · CI running" + tally + } + return &StageTrackerHumanGateWait{Kind: gateWaitChecksStuck, Checks: ci.ChecksStuck, Text: text} + case ci.State == "missing" && len(ci.ChecksPending) > 0: + return &StageTrackerHumanGateWait{Kind: gateWaitChecksMissing, Checks: ci.ChecksPending, Text: "required checks not reported: " + strings.Join(ci.ChecksPending, ", ")} + case ci.State == "running" || ci.State == "queued": + return &StageTrackerHumanGateWait{Kind: gateWaitCIRunning, Checks: ci.ChecksPending, Text: "CI running" + tally} + } + } + if rv := it.ReviewActivity; stageTrackerHumanGateOnHead(rv, it.Head) { + switch rv.State { + case "approved", "human_decision": + case "changes_requested": + return &StageTrackerHumanGateWait{Kind: gateWaitAuthor, Text: "the author's turn: review findings on this head"} + default: + head := strings.TrimSpace(it.Head) + if len(head) > stageTrackerHumanGateShortSHA { + head = head[:stageTrackerHumanGateShortSHA] + } + if head == "" { + return &StageTrackerHumanGateWait{Kind: gateWaitReview, Text: "the review of the current head"} + } + return &StageTrackerHumanGateWait{Kind: gateWaitReview, Text: "the review re-run on head " + head} + } + } + if it.Stage >= trackerNumberAwaitingMerge || it.MergeGate != nil || it.MergeTrain != nil { + text := "the merge queue" + if mg := it.MergeGate; mg != nil && strings.TrimSpace(mg.Reason) != "" { + text += " (" + strings.TrimSpace(mg.Reason) + ")" + } + return &StageTrackerHumanGateWait{Kind: gateWaitMergeQueue, Text: text} + } + return nil +} + +// stageTrackerHumanGateSpan prints a wait as whole hours or minutes. +func stageTrackerHumanGateSpan(d time.Duration) string { + if d >= time.Hour { + return strconv.Itoa(int(d/time.Hour)) + "h" + } + return strconv.Itoa(int(d/time.Minute)) + "m" +} + +// stageTrackerResolveHumanGates sets every row's gate and mirrors a listed PR's +// gate onto the links that draw it. It runs after the decision, actor and +// human-attention projections so it reads the finished row. +func stageTrackerResolveHumanGates(items []StageTrackerItem, now time.Time) { + prs := map[string]*StageTrackerItem{} + for i := range items { + it := &items[i] + it.HumanGate = stageTrackerHumanGateFor(*it, now) + if it.Kind == "pr" { + prs[it.Repo+"#"+strconv.Itoa(it.Number)] = it + } + } + for i := range items { + it := &items[i] + for j := range it.LinkedPRs { + lp := &it.LinkedPRs[j] + lp.HumanGate = nil + if pr := prs[it.Repo+"#"+strconv.Itoa(lp.Number)]; pr != nil && pr.Head == lp.Head && stageTrackerHumanGateOpenLinkedPR(*lp) { + lp.HumanGate = pr.HumanGate + } + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_gate_test.go b/src/pkg/dashboard/stage_tracker_gate_test.go new file mode 100644 index 0000000000..a1b07da9ed --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_gate_test.go @@ -0,0 +1,232 @@ +package dashboard + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// gateStateCase is one row of testdata/gate_states.json: a tracker item as +// the payload carries it and what its human gate must show. +type gateStateCase struct { + Name string `json:"name"` + Item StageTrackerItem `json:"item"` + Want struct { + Reasons []string `json:"reasons"` + Actions []string `json:"actions"` + Answered bool `json:"answered"` + AnsweredBy string `json:"answered_by"` + Wait string `json:"wait"` + Inert bool `json:"inert"` + } `json:"want"` +} + +func loadGateStateCases(t *testing.T) []gateStateCase { + t.Helper() + raw, err := os.ReadFile(filepath.Join("testdata", "gate_states.json")) + if err != nil { + t.Fatalf("reading the gate table: %v", err) + } + var table struct { + Cases []gateStateCase `json:"cases"` + } + if err := json.Unmarshal(raw, &table); err != nil { + t.Fatalf("parsing the gate table: %v", err) + } + if len(table.Cases) == 0 { + t.Fatal("the gate table is empty") + } + return table.Cases +} + +// TestStageTrackerHumanGateTable runs the shared gate table through the +// server rule (hivecommons/hive#18769): the reasons on the pill, the verbs +// offered and the blocker named when no decision is pending. The invariant +// the bug broke is asserted on every row: a verb is offered if and only if +// the action precondition accepts it, so no state offers a button that +// answers "nothing to act on". +func TestStageTrackerHumanGateTable(t *testing.T) { + now := time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC) + for _, tc := range loadGateStateCases(t) { + t.Run(tc.Name, func(t *testing.T) { + g := stageTrackerHumanGateFor(tc.Item, now) + if tc.Want.Inert { + if g != nil { + t.Fatalf("an inert row carries a gate: %+v", g) + } + return + } + if g == nil { + t.Fatal("no gate computed") + } + if !slices.Equal(g.Reasons, tc.Want.Reasons) { + t.Errorf("reasons = %v, want %v", g.Reasons, tc.Want.Reasons) + } + if !slices.Equal(g.Actions, tc.Want.Actions) { + t.Errorf("actions = %v, want %v", g.Actions, tc.Want.Actions) + } + if g.Answered != tc.Want.Answered || g.AnsweredBy != tc.Want.AnsweredBy { + t.Errorf("answered = %v by %q, want %v by %q", g.Answered, g.AnsweredBy, tc.Want.Answered, tc.Want.AnsweredBy) + } + wait := "" + if g.WaitingOn != nil { + wait = g.WaitingOn.Kind + if strings.TrimSpace(g.WaitingOn.Text) == "" { + t.Errorf("waiting_on %q has no text", wait) + } + } + if wait != tc.Want.Wait { + t.Errorf("waiting on %q, want %q (%+v)", wait, tc.Want.Wait, g.WaitingOn) + } + // Offered ⇔ accepted, over every verb any reason could offer. + for _, key := range stageTrackerHumanGateOrder { + for _, verb := range stageTrackerHumanGateVerbs[key] { + offered := slices.Contains(g.Actions, verb) + if offered && !stageTrackerHumanGateAccepts(tc.Item, verb) { + t.Errorf("%s is offered but the action refuses it", verb) + } + if offered && !slices.Contains(g.Reasons, key) { + continue + } + if !offered && slices.Contains(g.Reasons, key) && stageTrackerHumanGateAccepts(tc.Item, verb) && + (tc.Item.Kind == "pr" || !slices.Contains(stageTrackerHumanGatePROnly, verb)) { + t.Errorf("%s would act on a %s gate but is not offered", verb, key) + } + } + } + if len(g.Reasons) > 0 && len(g.Actions) == 0 { + t.Errorf("a gate with reasons %v offers no verb", g.Reasons) + } + if len(g.Reasons) > 0 && g.WaitingOn != nil { + t.Errorf("a row with a pending decision also names a blocker: %+v", g.WaitingOn) + } + }) + } +} + +// TestStageTrackerHumanGate18667 is the reported row end to end: a person +// approved the head the reviewer asked about, so the PR left 085 and waits +// on required checks, two of which have sat in progress for hours. The CI +// track must name them as stuck rather than running, and the gate must +// offer no decision verb and name them as the blocker. +func TestStageTrackerHumanGate18667(t *testing.T) { + now := time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC) + started := now.Add(-3 * time.Hour) + recent := now.Add(-4 * time.Minute) + const head = "ac459c3c3" + pr := github.PullRequest{HeadSHA: head, CIActivity: &github.PRCIActivity{ + Head: head, Source: "github-check-runs", ObservedAt: &now, RequiredKnown: true, StatusesKnown: true, RequiredSource: "protection", + Required: []string{"build", "PR Type", "PR Issue"}, + RequiredChecks: []github.PRRequiredCheck{{Name: "build", AppKnown: true}, {Name: "PR Type", AppKnown: true}, {Name: "PR Issue", AppKnown: true}}, + Checks: []github.PRActivityCheck{ + {Name: "build", State: "completed", Conclusion: "success", Since: &recent}, + {Name: "PR Type", State: "in_progress", Since: &started}, + {Name: "PR Issue", State: "in_progress", Since: &started}, + }, + }} + ci := stageTrackerCIActivity(pr, now) + if !slices.Equal(ci.ChecksStuck, []string{"PR Type", "PR Issue"}) || ci.StuckSince == nil || !ci.StuckSince.Equal(started) { + t.Fatalf("stuck checks = %v since %v, want PR Type and PR Issue since %v", ci.ChecksStuck, ci.StuckSince, started) + } + if ci.Active || !strings.HasPrefix(ci.Caption, "CI stuck · ") || !strings.Contains(ci.Caption, "'PR Type'") || !strings.Contains(ci.Caption, "'PR Issue'") { + t.Errorf("a head whose only pending checks are stuck must not read as running: active=%v caption=%q", ci.Active, ci.Caption) + } + if !strings.Contains(ci.Detail, "far longer than a check normally runs") { + t.Errorf("detail does not explain the stuck checks: %q", ci.Detail) + } + + it := StageTrackerItem{Repo: "hivecommons/hive", Number: 18667, Kind: "pr", Stage: trackerNumberReviewed, Head: head, BaseRef: "v6", + HumanApprover: "clubanderson", Reason: "verdict-requires-human:human-approved@clubanderson", CIActivity: ci, + ReviewActivity: &StageTrackerActivity{Head: head, State: "human_decision", Caption: "Review findings · needs owner sign-off"}} + g := stageTrackerHumanGateFor(it, now) + if g == nil || len(g.Reasons) != 0 || len(g.Actions) != 0 { + t.Fatalf("an answered sign-off still shows a gate: %+v", g) + } + if !g.Answered || g.AnsweredBy != "clubanderson" { + t.Errorf("answered = %v by %q, want the approver named", g.Answered, g.AnsweredBy) + } + if g.WaitingOn == nil || g.WaitingOn.Kind != gateWaitChecksStuck || !slices.Equal(g.WaitingOn.Checks, []string{"PR Type", "PR Issue"}) { + t.Fatalf("blocker = %+v, want the two stuck required checks", g.WaitingOn) + } + if want := "required checks stuck: PR Type, PR Issue (in progress 3h, far longer than a normal run)"; g.WaitingOn.Text != want { + t.Errorf("blocker text = %q, want %q", g.WaitingOn.Text, want) + } + for _, verb := range []string{decisionActionApprove, decisionActionDelegate} { + if stageTrackerHumanGateAccepts(it, verb) { + t.Errorf("%s is accepted on a PR no decision is pending on", verb) + } + } + + // The same head before the approval: parked at 085, the ask is live. + parked := it + parked.Stage, parked.HumanApprover, parked.Reason = trackerNumberNeedsDecision, "", "" + g = stageTrackerHumanGateFor(parked, now) + if g == nil || !slices.Equal(g.Reasons, []string{gateReasonReview}) || !slices.Equal(g.Actions, []string{decisionActionApprove, gateActionRequestChanges, decisionActionDelegate}) || g.Answered || g.WaitingOn != nil { + t.Errorf("the parked head must carry the review gate and its verbs: %+v", g) + } +} + +// TestStageTrackerStuckChecksThreshold: a check within the threshold is +// running; past it, stuck; a head with a stuck check beside real motion +// stays active and counts the stuck one; the threshold is configurable. +func TestStageTrackerStuckChecksThreshold(t *testing.T) { + now := time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC) + activity := func(since map[string]time.Duration) *StageTrackerActivity { + out := &StageTrackerActivity{State: "running", Caption: "CI running · 2 checks pending", Active: true} + pending := map[string]time.Time{} + for name, ago := range since { + out.ChecksPending = append(out.ChecksPending, name) + pending[name] = now.Add(-ago) + } + slices.Sort(out.ChecksPending) + stageTrackerMarkStuckChecks(out, pending, now) + return out + } + if a := activity(map[string]time.Duration{"build": trackerCheckStuckAfterDefault - time.Minute}); len(a.ChecksStuck) != 0 || !a.Active { + t.Errorf("a check inside the threshold was called stuck: %+v", a) + } + a := activity(map[string]time.Duration{"build": time.Minute, "PR Type": trackerCheckStuckAfterDefault + time.Minute}) + if !slices.Equal(a.ChecksStuck, []string{"PR Type"}) || !a.Active || !strings.HasSuffix(a.Caption, " · 1 stuck") { + t.Errorf("one stuck check beside a running one: %+v", a) + } + t.Setenv(trackerCheckStuckAfterEnv, "10m") + if a := activity(map[string]time.Duration{"build": 11 * time.Minute}); !slices.Equal(a.ChecksStuck, []string{"build"}) || a.Active { + t.Errorf("%s=10m did not lower the threshold: %+v", trackerCheckStuckAfterEnv, a) + } + t.Setenv(trackerCheckStuckAfterEnv, "nonsense") + if got := trackerCheckStuckAfter(); got != trackerCheckStuckAfterDefault { + t.Errorf("an unparsable threshold must fall back to the default, got %v", got) + } +} + +// TestStageTrackerResolveHumanGates: every row gets its gate and a nested +// PR link mirrors the listed PR's, so the issue row that draws the PR +// shows the same state. +func TestStageTrackerResolveHumanGates(t *testing.T) { + now := time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC) + items := []StageTrackerItem{ + {Repo: "acme/api", Number: 2, Kind: "pr", Stage: trackerNumberNeedsDecision, Head: "abc"}, + {Repo: "acme/api", Number: 1, Kind: "issue", Stage: trackerNumberCoveredByPR, Mirrored: true, + LinkedPRs: []StageTrackerLinkedPR{{Number: 2, Head: "abc", Stage: trackerNumberNeedsDecision}, {Number: 3, Head: "old", State: "closed"}}}, + } + stageTrackerResolveHumanGates(items, now) + if items[0].HumanGate == nil || !slices.Equal(items[0].HumanGate.Reasons, []string{gateReasonDecision}) { + t.Fatalf("PR gate = %+v", items[0].HumanGate) + } + if items[1].LinkedPRs[0].HumanGate != items[0].HumanGate { + t.Errorf("the link does not mirror its PR's gate: %+v", items[1].LinkedPRs[0].HumanGate) + } + if items[1].LinkedPRs[1].HumanGate != nil { + t.Errorf("a closed link carries a gate: %+v", items[1].LinkedPRs[1].HumanGate) + } + // The issue row decides its one parked PR: delegate is accepted there. + if !stageTrackerHumanGateAccepts(items[1], decisionActionDelegate) { + t.Error("an issue with one parked nested PR must accept Let hive decide") + } +} diff --git a/src/pkg/dashboard/stage_tracker_gate_truth.test.js b/src/pkg/dashboard/stage_tracker_gate_truth.test.js new file mode 100644 index 0000000000..049a9f858e --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_gate_truth.test.js @@ -0,0 +1,127 @@ +// The human gate's one source of truth (hivecommons/hive#18769). A row +// showed "Needs human · review" with Approve / Request changes… / Let hive +// decide while the click answered "nothing to act on — #18667 is not +// waiting on that decision": the pill read the cached reviewer verdict, the +// action read the live park. This runs the shipped pill renderer and the +// shipped action mapping over testdata/gate_states.json — the table the +// server rule (stage_tracker_gate_test.go) runs too — and proves that every +// verb a row draws is one the action accepts, and that a row nobody owes a +// decision on names what it waits on instead. +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); +const table = JSON.parse(fs.readFileSync(path.join(__dirname, 'testdata', 'gate_states.json'), 'utf8')); + +function pick(re, what) { + const m = html.match(re); + assert.ok(m, what + ' not found in index.html'); + return m[0]; +} +const fn = (name, args) => pick(new RegExp('function ' + name + '\\(' + args + '\\) \\{[\\s\\S]*?\\n \\}\\n'), name); +const line = name => pick(new RegExp('const ' + name + ' = [^\\n]*\\n'), name); + +const src = [ + 'var toasts = []; var fetched = 0; var _stageTrackerEtag = "e"; var _stageTrackerSig = "s"; var _stageTracker = null;', + 'function showToast(msg, type) { toasts.push(type + ":" + msg); }', + 'function fetchStageTracker() { fetched++; }', + 'function esc(s) { return String(s == null ? "" : s).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); }', + line('STAGE_TRACKER_TERMINAL'), + line('STAGE_TRACKER_DECISION_STAGES'), + line('STAGE_TRACKER_DELEGATE_ALL_MIN'), + pick(/function stageTrackerRefOf\(item\) \{[^\n]*\n/, 'stageTrackerRefOf'), + pick(/function stageTrackerItemKey\(it\) \{[^\n]*\n/, 'stageTrackerItemKey'), + fn('stageTrackerLinkedPRItem', 'issue, lp'), + fn('stageTrackerLinkedPROpen', 'lp, issue'), + fn('stageTrackerNestedOpenPRs', 'issue'), + fn('stageTrackerPRParked', 'it'), + fn('stageTrackerParkedNestedPRs', 'item'), + fn('stageTrackerDecisionTarget', 'item'), + fn('stageTrackerDelegateTargets', 'item'), + 'function stageTrackerActionLabel(id) { return id === "decide:delegate" ? "Let hive decide" : id; }', + fn('stageTrackerNothingToActOn', 'id, rows'), + // The two modules under test, as shipped. + fs.readFileSync(path.join(__dirname, 'static-src/js/tracker-human-gate.js'), 'utf8'), + fs.readFileSync(path.join(__dirname, 'static-src/js/tracker-gate-truth.js'), 'utf8'), + `return { reasons: stageTrackerHumanGateReasons, gateHtml: stageTrackerHumanGateHtml, waitingHtml: stageTrackerGateWaitingHtml, waitText: stageTrackerGateWaitText, + targets: stageTrackerGateTargets, accepts: stageTrackerGateAccepts, answered: stageTrackerGateAnswered, stuckWord: stageTrackerStuckChecksWord, + nothing: stageTrackerNothingToActOn, VERBS: STAGE_TRACKER_GATE_VERBS, toasts, fetched: () => fetched, sig: () => _stageTrackerSig + _stageTrackerEtag };`, +].join('\n'); +const api = new Function(src)(); + +const reasonsOf = h => ((/data-ham-gate-reasons="([^"]*)"/.exec(h) || [])[1] || '').split(' ').filter(Boolean); +const verbsOf = h => Array.from(h.matchAll(/data-ham-act="([^"]*)"/g)).map(m => m[1]).filter((v, i, a) => a.indexOf(v) === i); + +// The shipped bundle carries the module, and the action runs the mapping +// the pill filters on — one function, not two copies. +test('the pill and the action share one mapping', () => { + assert.ok(html.includes('function stageTrackerGateAccepts(item, id)'), 'tracker-gate-truth.js is in the bundle'); + assert.ok(html.includes('items.map(it => stageTrackerGateTargets(it, id))'), 'runRowAction maps its decide targets through stageTrackerGateTargets'); + assert.ok(html.includes('stageTrackerGateAccepts(item, v.id)'), 'the pill draws only the verbs stageTrackerGateAccepts allows'); +}); + +for (const tc of table.cases) { + test('gate table: ' + tc.name, () => { + const item = tc.item; + const row = api.gateHtml(item, item, Date.now()); + assert.deepStrictEqual(reasonsOf(row), tc.want.reasons, 'reasons on the pill: ' + row); + assert.deepStrictEqual(verbsOf(row), tc.want.actions, 'verbs on the pill: ' + row); + assert.strictEqual(!!row, tc.want.reasons.length > 0, 'a pill renders exactly when a person is owed something'); + // Offered ⇔ accepted: each drawn decide verb has something to act on, + // and each verb the reasons would list but the pill left out has not. + for (const id of verbsOf(row)) { + if (id.indexOf('decide:') === 0) assert.ok(api.targets(item, id).length > 0, id + ' is drawn but runRowAction would find nothing to act on'); + } + for (const key of tc.want.reasons) { + for (const id of api.VERBS[key]) { + if (verbsOf(row).indexOf(id) >= 0 || (item.kind !== 'pr' && (id === 'decide:approve' || id === 'gate:request-changes'))) continue; + assert.strictEqual(api.accepts(item, id), false, id + ' would act but the pill does not offer it'); + } + } + assert.strictEqual(api.answered(item), tc.want.answered, 'answered sign-off'); + }); +} + +test('hive#18667: approved head, stuck required checks — no decision buttons, the blocker named', () => { + const tc = table.cases[0]; + // The row as the server sends it: the payload names the blocker. + const item = Object.assign({}, tc.item, { human_gate: { reasons: [], actions: [], answered: true, answered_by: 'clubanderson', + waiting_on: { kind: 'checks-stuck', checks: ['PR Type', 'PR Issue'], text: 'required checks stuck: PR Type, PR Issue (in progress 3h, far longer than a normal run) · CI running (54/69)' } } }); + assert.strictEqual(api.gateHtml(item, item, Date.now()), '', 'no gate pill: nobody is asked to decide'); + const pill = api.waitingHtml(item); + assert.ok(pill.includes('class="ham-badge ham-gate-waiting"') && pill.includes('data-ham-gate-waiting="checks-stuck"'), pill); + assert.ok(pill.includes('>Approved by @clubanderson · waiting on required checks stuck: PR Type, PR Issue · CI running (54/69)<'), 'the pill names the approver and the stuck checks: ' + pill); + assert.ok(!/data-ham-act=/.test(pill) && !/