diff --git a/changelog.d/fixed-18889-no-decision-on-midflight-head.md b/changelog.d/fixed-18889-no-decision-on-midflight-head.md new file mode 100644 index 0000000000..5e11f8001d --- /dev/null +++ b/changelog.d/fixed-18889-no-decision-on-midflight-head.md @@ -0,0 +1 @@ +- Stop offering Decide…, Approve as-is and Let hive decide on a PR whose CI is running or whose review is incomplete on its current head (#18889): the verbs stay on the row, disabled, with the reason (`mid_flight`: *CI running 2/5*, *review queued on abc1234*), and a park from an earlier head no longer counts after a push; `Let hive decide — all N PRs` skips the PRs still in flight; the server answers `no-effect` before any decider runs and the policy's `default-release` / `small-low-risk` now require CI that is not pending; and the row says why a PR with no linked issue is parked (`contributor-lane:no-linked-issue`) instead of a bare *decision*. diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index d4eee421f7..c2f3dde99d 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -39,6 +39,18 @@ filters or routing. Consumers must not turn either display field into a gate. The monitor renders CI and Review concurrently on one shared PR row; see [Reading the tracks](../streaming-the-activity-monitor.md#reading-the-tracks). +Every open PR row (and each `linked_prs[]` entry) whose CURRENT head is still being +checked also carries `mid_flight`: `{kind, text, head?, park?}`, `kind` one of +`ci-running`, `review-in-progress`, `head-moved` (the CI / review on file belong to +an earlier head). While it is set the decision options that rest on the head +(`decide:delegate`, `decide:approve`, `decide:direction`) arrive in +`decision_needed.options` with `enabled: false` and the reason, the SPA draws +*Decide…*, *Approve as-is* and *Let hive decide* disabled, and +`POST …/decide-delegated` answers `no-effect` (rule `mid-flight`, nothing +written, `force` does not lift it). `park` is the plain reason the hive parked the +PR when a person was asked for a decision. The field is absent on a PR whose CI and +review are settled. + | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](../audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:63` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 2855731db5..5777595c83 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -21,7 +21,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/notes` | Signed-in GitHub user (or verified owner) | Maintainer notes — the private per-item notes maintainers leave each other on Activity Monitor rows ([#maintainer-notes](../operator-reference.md#maintainer-notes)). `?repo=owner/name&number=N` lists one item's live notes oldest first; with no query, every live note in the hive (the SPA's count badges). `{notes: [{id, repo, number, author, text, created_at}]}`. Never read from or written to GitHub. | `pkg/dashboard/api.go:336`, `pkg/dashboard/api_maintainer_notes.go` | | `POST` | `/api/notes` | Owner or repo write/maintain/admin, signed-in GitHub user | Append a maintainer note. Body `{repo, number, text}` — `text` is plain text up to 2000 characters; the author is the dashboard session's GitHub login, never a body field. `401` signed out, `403` without write on the repo, `400` for an empty/oversized note or a bad item. `201 {ok, note}`; appended to `/data/maintainer-notes.jsonl`, audited as `maintainer_note_add`, and broadcast as the `maintainer-notes` SSE event `{seq, repo, number, count, action}` so other maintainers' browsers refresh the row. | `pkg/dashboard/api.go:337`, `pkg/dashboard/api_maintainer_notes.go` | | `DELETE` | `/api/notes/{id}` | The note's author, or a verified owner | Tombstone a maintainer note (append-only store: a `deleted_at` record, never a rewrite). `404` unknown or already deleted, `403` for anyone else. `{ok, note}`; audited as `maintainer_note_delete`, broadcast as `maintainer-notes`. | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_maintainer_notes.go` | -| `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | +| `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085), and never decides a PR whose CI is running or whose review is incomplete on the current head — it answers `no-effect` (rule `mid-flight`, nothing written; fails closed, "review state not yet loaded", when the PR's review state cannot be read from the tracker; per PR in the `prs` fan-out, where the PR is skipped and counted as such), and the policy itself never releases (`default-release`, `small-low-risk`) a head whose checks are pending (rule `ci-pending`). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:341`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:342` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:343` | diff --git a/src/docs/dashboard-sections/activity-monitor.md b/src/docs/dashboard-sections/activity-monitor.md index 2a8f0d6132..3b894c5c07 100644 --- a/src/docs/dashboard-sections/activity-monitor.md +++ b/src/docs/dashboard-sections/activity-monitor.md @@ -276,6 +276,10 @@ Every verb runs `runRowAction` — the row menu's own path: the in-app confirm o 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. +**No decision on a head that is still being checked** ([#18889](https://github.com/hivecommons/hive/issues/18889)). A decision is a call on the head as it stands, so while the **current** head's CI is running (queued, running, or required checks not yet reported), its review is queued or in progress, or the CI / review on file belong to an earlier head (a push restarted both), the row carries `mid_flight` (`{kind, text, head, park?}`; `kind` is `ci-running`, `review-in-progress` or `head-moved`). Then **Decide…**, **Approve as-is**, **Let hive decide** and *Give direction…* stay on the pill and the menu but are **disabled with the reason** (*Waiting on CI running 2/5: the decision opens when CI and review finish on the current head*), and the pill says it in words (*waiting on CI running 2/5*). A park recorded for an earlier head does not count: the old park's pill stays, nothing on it is live until the new head has been checked. *Release hold*, *Confirm safe* and the close options are unaffected (a person may always close a PR). Checks stuck far past a normal run do not hold the row (they will not finish on their own, and the person may have to act). `park` is, when a person was asked for a decision, the plain reason the hive parked the PR (*it links no issue, so the hive cannot tell which claim it fulfils and does not trust its author yet*), so the row says why it is parked at all instead of a bare *decision*. + +**Why a PR with no linked issue reads "Needs human · decision".** `needs-decision` on a PR has three sources: the 085 stage itself (the lane parked it; its reason is the lane reason, e.g. `contributor-lane:no-linked-issue`, a trust-family reason for a contributor PR whose claim the hive cannot match to an issue); the `pr-needs-decision` label; and, for a 085 PR whose chevron is its real stage (CI / Review) because its head is not merge-ready yet, the pill the tracker adds back so the ask stays visible (`stageTrackerApplyPersonActsOnPRPill`, [#17453](https://github.com/hivecommons/hive/issues/17453)). None of them looks at the Prow label path: a repo without Prow gets the same park. The ask is real, but it cannot be answered until CI and review finish, which is what `mid_flight` now says on the row. + 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 @@ -746,7 +750,7 @@ The item leaves 085/045 and proceeds without the owner. The action is audited as Permission is the same as **Hold**: owner, or a signed-in user with repository write access. The recorded decision names the requesting user as the person who delegated it. -**Multiple PRs.** An issue with two or more open nested PRs offers **Let hive decide — all N PRs**. It never silently chooses one ([#15009](https://github.com/hivecommons/hive/issues/15009)). Each PR has its own job and result toast; the issue toast summarizes them. For example: “Decided each of the 2 nested pull requests: #15017 approved (small low risk); #15020 no change (already decided).” The next-step summary can read “2 sent · 1 decided · 1 no-op. Each PR's own toast says what happens next.” The aggregate fails only if every PR failed. With one nested PR or none, the issue's own decision path is unchanged. +**Multiple PRs.** An issue with two or more open nested PRs offers **Let hive decide — all N PRs**. It never silently chooses one ([#15009](https://github.com/hivecommons/hive/issues/15009)). Each PR has its own job and result toast; the issue toast summarizes them. For example: “Decided each of the 2 nested pull requests: #15017 approved (small low risk); #15020 no change (already decided).” The next-step summary can read “2 sent · 1 decided · 1 no-op. Each PR's own toast says what happens next.” A PR whose CI is running or whose review is incomplete on its current head is skipped, not decided ([#18889](https://github.com/hivecommons/hive/issues/18889)): it gets its own `no-effect` result (rule `mid-flight`, nothing written) and the issue toast words it “#15020 skipped (CI running 1/4)” and adds “· 1 skipped (CI or review still running)” to the summary; the button itself says “skips N still running”, and is disabled with the reasons when every PR is in flight. The aggregate fails only if every PR failed. With one nested PR or none, the issue's own decision path is unchanged. **Request/response reference.** @@ -780,7 +784,7 @@ The rules live in one place — `src/pkg/delegatedecision/policy.go` (`PolicyTex | a hive-filed proposal **without** such evidence | `proposal-not-now` (verdict `not-now`) | Declined for now: a comment saying "no incident or recurrence justifies the cost yet; re-propose with evidence", then closed as not planned (the established declined-proposal path). Never applied to a person's proposal (those keep `default-approve`), never to the hive's own policy (`hive-policy` stays recommend-only). | | a change to the hive's own policy (for example an RFC to hold unacknowledged hive-filed proposals) | `hive-policy` (recommend-only) | Unchanged in shape, but the recommendation is a real sentence in the owner's terms — "approve `` as proposed — proposals nobody has acknowledged should not be actionable; make it default-on for the lanes it names rather than opt-in; owner to confirm" — never "no special rule applies". | -Each decision names the rule that fired (`dedupe`, `owner-only`, `flaky-test`, `ci-ratchet`, `design-proposal`, `review-backlog`, `selfreport-operator-action`, `proposal-approve-evidence`, `proposal-not-now`, `default-approve`, `prefer-contributor`, `contributor-offline`, `sentinel-trusted`, `small-low-risk`, `reporter-trust`, `fix-then-merge`, `default-release`, `hive-policy`, `sentinel-untrusted`, `rail-hold`, `one-pr-per-issue`) in the comment and in the job's `decision.rule`. +Each decision names the rule that fired (`dedupe`, `owner-only`, `flaky-test`, `ci-ratchet`, `design-proposal`, `review-backlog`, `selfreport-operator-action`, `proposal-approve-evidence`, `proposal-not-now`, `default-approve`, `prefer-contributor`, `contributor-offline`, `sentinel-trusted`, `small-low-risk`, `reporter-trust`, `fix-then-merge`, `default-release`, `hive-policy`, `sentinel-untrusted`, `rail-hold`, `one-pr-per-issue`, `ci-pending`, `mid-flight`) in the comment and in the job's `decision.rule`. **Safety rails** (`ApplyRails`, applied after the policy and before anything is written): the delegate never merges a PR — it only records the approval the auto-merge engine already acts on per repository settings (a merger/owner requester's approval is written as the queue line the sweep parses; anyone else's as `/lgtm` + `/approve` comments attributed to them); it does not touch an item wearing `hold` (refused, nothing written — release the hold first if you want it decided); it never grants org membership, secrets or permissions (those items get `needs-owner` + `hold` and the one owner-action comment, and keep their park); and a question that is a policy or scope change to the hive itself (settings, governance docs, security posture — the `governance` label or those words in the park reason) is left parked: the delegate posts "hive recommends: …; owner to confirm" and keeps 085. @@ -844,7 +848,7 @@ See [operator-reference.md](../operator-reference.md). #### What this release decides mechanically -The decider is rules-first: the cases above that are mechanically decidable (dedupe, owner-only, flaky, CI ratchet, design proposal, review backlog, contributor-offline, sentinel-trusted, small-low-risk, reporter-trust, hive-policy) are decided from the item itself; anything else falls to the reversible default (approve direction on an issue; release a green hive PR; ask for the fix first when the head is red or conflicting). Competing-PR comparisons and adopt-supersede requests are implemented. The same safety rails still decide whether the proposed action can run. +The decider is rules-first: the cases above that are mechanically decidable (dedupe, owner-only, flaky, CI ratchet, design proposal, review backlog, contributor-offline, sentinel-trusted, small-low-risk, reporter-trust, hive-policy) are decided from the item itself; anything else falls to the reversible default (approve direction on an issue; release a green hive PR; ask for the fix first when the head is red or conflicting; write nothing while its checks are still pending — rule `ci-pending`, so `default-release` and `small-low-risk` need a green head, not merely one without failures). Competing-PR comparisons and adopt-supersede requests are implemented. The same safety rails still decide whether the proposed action can run. #### LLM step for the non-mechanical cases diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index e98c1d8c7e..7e7ed8550c 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -454,6 +454,8 @@ func delegatedItemWord(it delegatedDecisionItem) string { return "failed — " + it.Error case it.Result != nil && it.Result.Action == rowActionNoop: return "no change (already decided)" + case it.Result != nil && it.Result.Action == rowActionNoEffect && it.Result.Rule == delegatedecision.RuleMidFlight: + return "skipped (" + strings.TrimSuffix(strings.TrimPrefix(it.Result.Outcome, "Not decided: "), ".") + ")" case it.Result != nil: word := it.Result.Action if it.Result.Rule != "" { @@ -469,12 +471,14 @@ func delegatedItemWord(it delegatedDecisionItem) string { // untrusted)". Each PR's own result carries its outcome and next step. func delegatedPerPRResult(repoFull string, number int, items []delegatedDecisionItem) RowActionResult { parts := make([]string, 0, len(items)) - decided, noop, failed := 0, 0, 0 + decided, noop, failed, waiting := 0, 0, 0, 0 for _, it := range items { parts = append(parts, "#"+strconv.Itoa(it.Number)+" "+delegatedItemWord(it)) switch { case it.Error != "": failed++ + case it.Result != nil && it.Result.Action == rowActionNoEffect && it.Result.Rule == delegatedecision.RuleMidFlight: + waiting++ case it.Result != nil && it.Result.Action == rowActionNoop: noop++ default: @@ -484,6 +488,9 @@ func delegatedPerPRResult(repoFull string, number int, items []delegatedDecision out := RowActionResult{Action: rowActionDecidedEach, Target: rowActionTarget(repoFull, rowActionTargetIssue, number)} out.Outcome = fmt.Sprintf("Decided each of the %d nested pull requests: %s.", len(items), strings.Join(parts, "; ")) out.Next = fmt.Sprintf("%d sent · %d decided · %d no-op", len(items), decided, noop) + if waiting > 0 { + out.Next += fmt.Sprintf(" · %d skipped (CI or review still running)", waiting) + } if failed > 0 { out.Next += fmt.Sprintf(" · %d failed", failed) } @@ -498,6 +505,13 @@ func (s *Server) decideDelegatedOne(ctx context.Context, repoFull string, number s.audit.LogRecord(user, auditRepoItemDecisionDelegated+"_failed", auditDetail("repo", repoFull, "number", strconv.Itoa(number), "error", err.Error()), "", repoFull, number) return delegatedOutcome{Err: err} } + // A head whose CI is still running or whose review is unfinished is not + // decided on (hivecommons/hive#18889): an approval here would be an + // approval of a head nobody has finished checking. Force does not lift + // it — "re-run" repeats a decision, it does not make a head ready. + if mf := s.delegatedMidFlight(repoFull, number, in); mf != nil { + return s.delegatedMidFlightOutcome(repoFull, number, itemType, user, mf) + } // Consult the applied native decision BEFORE invoking any paid decider. // A posted AI verdict alone is not proof of durable application. if in.Kind == delegatedecision.KindPR && !req.Force { diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_midflight.go b/src/pkg/dashboard/api_repo_item_decide_delegated_midflight.go new file mode 100644 index 0000000000..67d590ac11 --- /dev/null +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_midflight.go @@ -0,0 +1,94 @@ +package dashboard + +import ( + "strconv" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/delegatedecision" +) + +// delegatedMidFlight is the server-side twin of the row's `mid_flight` +// (hivecommons/hive#18889): what the PR's CURRENT head still waits on before +// a delegated decision means anything. CI comes from the live read the +// gather just made (Input.CIPending); the review track and any activity +// recorded for an earlier head come from the last tracker body, measured +// against the live head — a push since that body was served reads as a head +// whose review has not run. nil when nothing is outstanding, and for an item +// that is not a PR. +func (s *Server) delegatedMidFlight(repoFull string, number int, in delegatedecision.Input) *StageTrackerMidFlight { + if in.Kind != delegatedecision.KindPR { + return nil + } + it, ok := s.stageTrackerCachedPR(repoFull, number) + if !ok { + it, ok = s.stageTrackerBuiltPR(repoFull, number) + } + if !ok { + // The review track of this PR cannot be read: fail closed. An + // approval must never rest on a head whose review state is unknown + // (a restart before the first tracker poll, a PR the enumeration + // has not listed yet). + return &StageTrackerMidFlight{Kind: midFlightKindReview, Head: strings.TrimSpace(in.HeadSHA), Text: "review state not yet loaded"} + } + it.Kind, it.Repo, it.Number = "pr", repoFull, number + if head := strings.TrimSpace(in.HeadSHA); head != "" { + it.Head = head + } + // The gather's own read of the head's checks outranks the cached CI + // track: it is newer, and it is the one the policy decides on. + switch { + case in.CIPending: + it.CIActivity = &StageTrackerActivity{Head: it.Head, State: "running"} + default: + it.CIActivity = nil + } + return stageTrackerMidFlightFor(it) +} + +// stageTrackerBuiltPR finds a PR row by building the tracker from the status +// snapshot, for when no tracker body has been served yet. +func (s *Server) stageTrackerBuiltPR(repoFull string, number int) (StageTrackerItem, bool) { + s.statusMu.RLock() + status := s.status + s.statusMu.RUnlock() + if status == nil { + return StageTrackerItem{}, false + } + for _, it := range s.buildStageTracker(status, s.stageStoreOrShared(), time.Now().UTC()).Items { + if it.Kind == "pr" && it.Number == number && strings.EqualFold(it.Repo, repoFull) { + return it, true + } + } + return StageTrackerItem{}, false +} + +// delegatedMidFlightOutcome answers a delegated decision on a mid-flight PR: +// no decider runs, nothing is written, the park stays. +func (s *Server) delegatedMidFlightOutcome(repoFull string, number int, itemType, user string, mf *StageTrackerMidFlight) delegatedOutcome { + head := shortHead(mf.Head) + d := delegatedecision.Decision{ + Verdict: delegatedecision.VerdictRefused, Rule: delegatedecision.RuleMidFlight, KeepsPark: true, + Text: "wait on #" + strconv.Itoa(number) + ": " + mf.Text, + Rationale: mf.Text + "; a decision now would rest on a head nobody has finished checking", + } + res := RowActionResult{ + Action: rowActionNoEffect, + Target: rowActionTarget(repoFull, rowActionTargetPR, number), + Rule: delegatedecision.RuleMidFlight, + Why: "mid-flight:" + mf.Kind, + Outcome: "Not decided: " + mf.Text + ".", + Next: "Nothing was written. Decide again once CI and review finish" + stageTrackerMidFlightOn(head) + "; the row offers the decision again by itself.", + } + s.audit.LogRecord(user, auditRepoItemDecisionDelegated, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", itemType, + "verdict", string(d.Verdict), "rule", d.Rule, "actions", "", "noop", "no-effect:mid-flight:"+mf.Kind, "policy", delegatedecision.PolicyName, "decision", d.Text), "", repoFull, number) + return delegatedOutcome{Decision: &d, Notes: []string{"mid-flight (" + mf.Text + "); nothing written"}, Result: &res} +} + +// stageTrackerMidFlightOn is " on <sha>" for a known head, "" otherwise. +func stageTrackerMidFlightOn(head string) string { + if head == "" { + return "" + } + return " on " + head +} diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_midflight_test.go b/src/pkg/dashboard/api_repo_item_decide_delegated_midflight_test.go new file mode 100644 index 0000000000..eefcc9ab7a --- /dev/null +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_midflight_test.go @@ -0,0 +1,160 @@ +package dashboard + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/delegatedecision" +) + +// seedTrackerPR plants a PR row in the last served tracker body, the way +// delegatedMidFlight reads the review track. +func seedTrackerPR(t *testing.T, srv *Server, number int, item map[string]any) { + t.Helper() + item["repo"], item["kind"], item["number"] = "testorg/testrepo", "pr", number + srv.stageTrackerCacheMu.Lock() + defer srv.stageTrackerCacheMu.Unlock() + var cur struct { + Items []map[string]any `json:"items"` + } + _ = json.Unmarshal(srv.stageTrackerCache.body, &cur) + items := []map[string]any{item} + for _, other := range cur.Items { + if n, _ := other["number"].(float64); int(n) != number { + items = append(items, other) + } + } + body, err := json.Marshal(map[string]any{"items": items}) + if err != nil { + t.Fatal(err) + } + srv.stageTrackerCache.body = body +} + +// seedSettledTrackerPRs serves tracker rows whose review is approved and CI +// passing, with no head recorded so they match any head. +func seedSettledTrackerPRs(srv *Server, numbers ...int) { + items := make([]map[string]any, 0, len(numbers)) + for _, n := range numbers { + items = append(items, map[string]any{"repo": "testorg/testrepo", "kind": "pr", "number": n, "stage": 85, + "review_activity": map[string]any{"state": "approved"}, "ci_activity": map[string]any{"state": "passing"}}) + } + body, _ := json.Marshal(map[string]any{"items": items}) + srv.stageTrackerCacheMu.Lock() + srv.stageTrackerCache.body = body + srv.stageTrackerCacheMu.Unlock() +} + +const midFlightHead = "feedfacefeedfacefeedfacefeedfacefeedface" + +func assertMidFlightNoEffect(t *testing.T, mock *repoItemDecisionMock, job delegatedDecisionJob, wantText string) { + t.Helper() + if job.Status != delegatedJobStatusDone || job.Decision == nil || job.Result == nil { + t.Fatalf("job = %+v", job) + } + if job.Decision.Verdict != delegatedecision.VerdictRefused || job.Decision.Rule != delegatedecision.RuleMidFlight || !job.Decision.KeepsPark { + t.Fatalf("decision = %+v", job.Decision) + } + if job.Result.Action != rowActionNoEffect || job.Result.Rule != delegatedecision.RuleMidFlight || !strings.Contains(job.Result.Outcome, wantText) { + t.Fatalf("result = %+v, want no-effect mentioning %q", job.Result, wantText) + } + if len(mock.comments) != 0 || len(mock.reviews) != 0 || len(mock.edits) != 0 || len(mock.merges) != 0 { + t.Fatalf("a mid-flight PR was written to: comments=%v reviews=%v edits=%v merges=%v", mock.comments, mock.reviews, mock.edits, mock.merges) + } +} + +// hivecommons/hive#18889: "Let hive decide" on a PR whose CI is still +// running used to run the policy, which has no CI guard (CIRed() is false +// while checks are pending) and recorded an approval of a head nobody had +// finished checking. +func TestDelegatedDecisionPendingCIIsNoEffect(t *testing.T) { + for _, force := range []string{"", `,"force":true`} { + mock := &repoItemDecisionMock{prMergeState: "unstable", prCIRunning: true} + srv := newDelegatedServer(t, mock) + w := postDelegated(t, srv, 8, "writer", `{"type":"pr"`+force+`}`, nil) + assertMidFlightNoEffect(t, mock, decodeDelegatedJob(t, w), "CI running") + } +} + +// A review that is queued (or being worked) on the current head is not a +// head the delegate may approve either, whatever the checks say. +func TestDelegatedDecisionQueuedReviewIsNoEffect(t *testing.T) { + for _, state := range []string{"unassigned", "assigned", "reviewing", "adjudicating"} { + t.Run(state, func(t *testing.T) { + mock := &repoItemDecisionMock{} + srv := newDelegatedServer(t, mock) + seedTrackerPR(t, srv, 8, map[string]any{"head": midFlightHead, "stage": 85, + "review_activity": map[string]any{"head": midFlightHead, "state": state, "perspectives_done": 0, "perspectives_total": 5}}) + w := postDelegated(t, srv, 8, "writer", `{"type":"pr"}`, nil) + assertMidFlightNoEffect(t, mock, decodeDelegatedJob(t, w), "review") + }) + } +} + +// A park (and its review) recorded for an earlier head does not count: the +// push since restarted both tracks. +func TestDelegatedDecisionStaleParkAfterPushIsNoEffect(t *testing.T) { + mock := &repoItemDecisionMock{} + srv := newDelegatedServer(t, mock) + seedTrackerPR(t, srv, 8, map[string]any{"head": "0ldhead0ldhead0ldhead0ldhead0ldhead0ldh", "stage": 85, "modifiers": []string{"needs-decision"}, + "review_activity": map[string]any{"head": "0ldhead0ldhead0ldhead0ldhead0ldhead0ldh", "state": "human_decision"}}) + w := postDelegated(t, srv, 8, "writer", `{"type":"pr"}`, nil) + assertMidFlightNoEffect(t, mock, decodeDelegatedJob(t, w), "not yet run") +} + +// Settled CI and review on the current head: the delegate decides as before. +func TestDelegatedDecisionSettledHeadStillDecides(t *testing.T) { + mock := &repoItemDecisionMock{} + srv := newDelegatedServer(t, mock) + seedTrackerPR(t, srv, 8, map[string]any{"head": midFlightHead, "stage": 85, + "review_activity": map[string]any{"head": midFlightHead, "state": "approved"}, + "ci_activity": map[string]any{"head": midFlightHead, "state": "passing"}}) + w := postDelegated(t, srv, 8, "writer", `{"type":"pr"}`, nil) + job := decodeDelegatedJob(t, w) + if job.Decision == nil || job.Decision.Verdict != delegatedecision.VerdictApprove { + t.Fatalf("job = %+v", job) + } +} + +// "Let hive decide — all N PRs" with PRs in flight: each one in flight is +// skipped with its own no-effect result, and the summary counts it. +func TestDelegatedDecisionAllPRsSkipsMidFlight(t *testing.T) { + mock := &repoItemDecisionMock{issueLabels: []string{"bug"}} + srv := newDelegatedServer(t, mock) + // #8 reviews on the current head; #9 is settled, but the tracker row is + // keyed per PR, so seed #8 only and let #9 decide. + seedTrackerPR(t, srv, 8, map[string]any{"head": midFlightHead, "stage": 85, + "review_activity": map[string]any{"head": midFlightHead, "state": "unassigned"}}) + w := postDelegated(t, srv, 7, "writer", `{"type":"issue","prs":[8,9]}`, nil) + job := decodeDelegatedJob(t, w) + if len(job.Items) != 2 { + t.Fatalf("items = %+v", job.Items) + } + skipped, decided := job.Items[0], job.Items[1] + if skipped.Number != 8 || skipped.Result == nil || skipped.Result.Action != rowActionNoEffect || skipped.Result.Rule != delegatedecision.RuleMidFlight { + t.Fatalf("#8 = %+v, want skipped as no-effect", skipped) + } + if decided.Number != 9 || decided.Decision == nil || decided.Decision.Verdict != delegatedecision.VerdictApprove { + t.Fatalf("#9 = %+v, want decided", decided) + } + if job.Result == nil || !strings.Contains(job.Result.Outcome, "#8 skipped") || !strings.Contains(job.Result.Next, "1 skipped") { + t.Fatalf("summary = %+v", job.Result) + } + all := strings.Join(mock.comments, "\n") + if strings.Contains(all, "approve #8") || !strings.Contains(all, "approve #9") { + t.Fatalf("only the settled PR is decided: %v", mock.comments) + } +} + +// A PR whose review state cannot be read at all (no tracker body served, the +// PR not in a built tracker) is not decided on: the guard fails closed. +func TestDelegatedDecisionUnreadableReviewStateFailsClosed(t *testing.T) { + mock := &repoItemDecisionMock{} + srv := newDelegatedServer(t, mock) + srv.stageTrackerCacheMu.Lock() + srv.stageTrackerCache.body = nil + srv.stageTrackerCacheMu.Unlock() + w := postDelegated(t, srv, 8, "writer", `{"type":"pr"}`, nil) + assertMidFlightNoEffect(t, mock, decodeDelegatedJob(t, w), "review state not yet loaded") +} diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_test.go b/src/pkg/dashboard/api_repo_item_decide_delegated_test.go index fbd1d94675..6cccf92765 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_test.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_test.go @@ -24,6 +24,10 @@ func newDelegatedServer(t *testing.T, mock *repoItemDecisionMock) *Server { srv := newRepoItemDecisionServer(t, mock) // PR decisions fail closed without an enumeration snapshot. srv.status = &StatusPayload{} + // The mid-flight guard fails closed on a PR whose review state it cannot + // read (hivecommons/hive#18889): serve the tracker rows of PRs #8 and #9 + // as settled, head-less so they match whatever head a test's mock reports. + seedSettledTrackerPRs(srv, 8, 9) return srv } diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index 1afe7755c2..1577afd5fb 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -47,6 +47,9 @@ type repoItemDecisionMock struct { // prTidePending is hivecommons/hive#15722's head: every check green, // only the tide merge-metadata context pending (GitHub: "unstable"). prTidePending bool + // prCIRunning is hivecommons/hive#18889's head: a real check still + // running with none failed (GitHub: "unstable"/"blocked", status pending). + prCIRunning bool // priorComments are the comment bodies GET /comments lists (a prior // delegated decision makes a repeat click a no-op). priorComments []string @@ -201,6 +204,8 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { _, _ = io.WriteString(w, `{"state":"failure","statuses":[{"context":"ci/test","state":"failure"}]}`) case m.prNoCI: _, _ = io.WriteString(w, `{"state":"pending","statuses":[]}`) + case m.prCIRunning: + _, _ = io.WriteString(w, `{"state":"pending","statuses":[{"context":"ci/test","state":"pending"}]}`) case m.prTidePending: _, _ = io.WriteString(w, `{"state":"pending","statuses":[{"context":"ci/test","state":"success"},{"context":"tide","state":"pending"}]}`) default: diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 3b97811d1e..98c74e8613 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -475,6 +475,11 @@ type StageTrackerItem struct { // 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"` + // MidFlight is what a PR's CURRENT head still waits on (CI running, + // review queued or in progress, or activity on file for an earlier + // head): while set, no decision is offered on the row and the server's + // delegated decision answers no-effect (stage_tracker_midflight.go). + MidFlight *StageTrackerMidFlight `json:"mid_flight,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. @@ -819,6 +824,8 @@ type StageTrackerLinkedPR struct { 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"` + // MidFlight mirrors the nested PR's own row field (stage_tracker_midflight.go). + MidFlight *StageTrackerMidFlight `json:"mid_flight,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_decision_lanes.go b/src/pkg/dashboard/stage_tracker_decision_lanes.go index e994922330..cfca7955aa 100644 --- a/src/pkg/dashboard/stage_tracker_decision_lanes.go +++ b/src/pkg/dashboard/stage_tracker_decision_lanes.go @@ -237,6 +237,8 @@ func decisionPlainReason(base string) string { return "GitHub requires a review the hive cannot give" case stageengineprstage.AutoMergeReasonMergeRefusedMethod: return "GitHub refused the hive's merge method" + case stageengineprstage.ContributorLaneReasonNoLinkedIssue: + return "it links no issue, so the hive cannot tell which claim it fulfils and does not trust its author yet" } // The shared decision glossary (pkg/delegatedecision) covers the // reasons the lane shares with the delegate — changes requested, @@ -248,5 +250,9 @@ func decisionPlainReason(base string) string { if text := humanizeStageReason(base); text != "" { return text } - return "the hive parked it" + return decisionPlainReasonFallback } + +// decisionPlainReasonFallback is what decisionPlainReason says of a lane +// reason it has no words for. +const decisionPlainReasonFallback = "the hive parked it" diff --git a/src/pkg/dashboard/stage_tracker_gate.go b/src/pkg/dashboard/stage_tracker_gate.go index 2b167dab17..aabc620e71 100644 --- a/src/pkg/dashboard/stage_tracker_gate.go +++ b/src/pkg/dashboard/stage_tracker_gate.go @@ -340,6 +340,7 @@ func stageTrackerHumanGateSpan(d time.Duration) string { // 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) { + stageTrackerResolveMidFlight(items) prs := map[string]*StageTrackerItem{} for i := range items { it := &items[i] diff --git a/src/pkg/dashboard/stage_tracker_gate_truth.test.js b/src/pkg/dashboard/stage_tracker_gate_truth.test.js index 049a9f858e..874ded9b33 100644 --- a/src/pkg/dashboard/stage_tracker_gate_truth.test.js +++ b/src/pkg/dashboard/stage_tracker_gate_truth.test.js @@ -125,3 +125,41 @@ test('a verb clicked in a stale view says what the item is waiting on and refres api.nothing('decide:delegate', [{ repo: 'acme/api', number: 9, kind: 'issue', stage: 15 }]); assert.deepStrictEqual(api.toasts, ['warning:Let hive decide: nothing to act on — acme/api#9 is not waiting on that decision']); }); + +// hivecommons/hive#18889: the pill still names what parked the row, but the +// verbs that decide on the head are disabled, with the reason, while the +// CURRENT head's CI or review is still running — and the pill says so in +// words ("waiting on CI running 2/5"), not only in a hover. +test('hive#18889: mid-flight head — decision verbs disabled with the reason, release stays live', () => { + const parked = { repo: 'acme/api', number: 5, kind: 'pr', stage: 85, head: 'aaa1111', author_kind: 'hive', modifiers: ['needs-decision'], needs_human: true, + reason: 'contributor-lane:no-linked-issue' }; + const disabledOf = h => Array.from(h.matchAll(/data-ham-act="([^"]*)"([^>]*)>/g)).filter(m => /aria-disabled="true"/.test(m[2])).map(m => m[1]); + + // Settled head: nothing disabled, no wait chip. + const settled = api.gateHtml(parked, parked, Date.now()); + assert.deepStrictEqual(disabledOf(settled), []); + assert.ok(!settled.includes('ham-gate-wait'), settled); + + // CI running on the current head. + const ci = Object.assign({}, parked, { mid_flight: { kind: 'ci-running', text: 'CI running 2/5', head: 'aaa1111', park: 'it links no issue' } }); + const row = api.gateHtml(ci, ci, Date.now()); + assert.deepStrictEqual(reasonsOf(row), ['decision'], 'the pill still says what parked it'); + assert.deepStrictEqual(verbsOf(row), ['gate:decide', 'decide:approve', 'decide:delegate']); + assert.deepStrictEqual(disabledOf(row), ['gate:decide', 'decide:approve', 'decide:delegate'], 'Decide…, Approve as-is and Let hive decide are all disabled'); + assert.ok(row.includes('class="ham-gate-wait"') && row.includes('>waiting on CI running 2/5<'), 'the reason is visible on the pill: ' + row); + assert.ok(row.includes('parked because it links no issue'), 'the real park reason rides the hover: ' + row); + assert.ok(row.includes('title="Waiting on CI running 2/5: the decision opens when CI and review finish on the current head'), row); + + // Review queued on the current head, and a push that left the old park behind. + for (const text of ['review queued on aaa1111 (0/5)', 'CI and review not yet run on aaa1111']) { + const it = Object.assign({}, parked, { mid_flight: { kind: 'x', text, head: 'aaa1111' } }); + const h = api.gateHtml(it, it, Date.now()); + assert.deepStrictEqual(disabledOf(h), ['gate:decide', 'decide:approve', 'decide:delegate'], text); + assert.ok(h.includes('>waiting on ' + text + '<'), h); + } + + // A hold is a person's to release whatever the head is doing. + const held = Object.assign({}, ci, { modifiers: ['needs-decision', 'hold'], hold: { by: 'octocat' } }); + const heldRow = api.gateHtml(held, held, Date.now()); + assert.ok(verbsOf(heldRow).includes('release') && !disabledOf(heldRow).includes('release'), heldRow); +}); diff --git a/src/pkg/dashboard/stage_tracker_midflight.go b/src/pkg/dashboard/stage_tracker_midflight.go new file mode 100644 index 0000000000..8ee7839865 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_midflight.go @@ -0,0 +1,221 @@ +package dashboard + +import ( + "fmt" + "slices" + "strconv" + "strings" +) + +// Mid-flight PRs (hivecommons/hive#18889). +// +// A decision on a PR (Decide…, Approve as-is, Let hive decide) is a call on +// the head as it stands. While the CURRENT head's CI is still running, or +// its review has not finished, the call is premature: the verdict the person +// would be deciding against does not exist yet, and an approval recorded now +// is an approval of a head nobody has looked at. The row therefore carries +// `mid_flight`, the one fact the SPA's guards and the server's delegated +// decision both read: what the current head still waits on. A park recorded +// for an EARLIER head does not count either — a push restarts both tracks, +// so a CI or review activity measured on another head says the current one +// has not been evaluated yet. + +// Mid-flight kinds. +const ( + midFlightKindCI = "ci-running" + midFlightKindReview = "review-in-progress" + midFlightKindHead = "head-moved" +) + +// StageTrackerMidFlight is what the PR's current head still waits on before +// a decision is meaningful. nil on a PR whose CI and review are settled. +type StageTrackerMidFlight struct { + // Kind is one of the midFlightKind* constants (the first that applies: + // a moved head, then CI, then review). + Kind string `json:"kind"` + // Text is the reason the row prints on the disabled verbs: "CI running + // 2/5", "review queued on abc1234 (0/5)". + Text string `json:"text"` + // Head is the current head the wait is about. + Head string `json:"head,omitempty"` + // Park is, when a person was asked for a decision on this PR, the plain + // reason the hive asked, so the row says why it is parked at all + // instead of a bare "decision". + Park string `json:"park,omitempty"` +} + +// stageTrackerReviewInFlightStates are the review activity states of a head +// whose review has been requested and has not produced its verdict: +// queued (unassigned / assigned) or being worked (reviewing / adjudicating). +var stageTrackerReviewInFlightStates = map[string]string{ + "unassigned": "queued", + "assigned": "queued", + "reviewing": "in progress", + "adjudicating": "in progress", +} + +// stageTrackerMidFlightFor derives the mid-flight state of a PR row from its +// CI and review activity on the CURRENT head. Rows that are not open PRs, +// and PRs whose CI and review are settled, answer nil. Checks that have run +// far longer than a normal run (stuck) do not make a PR mid-flight: they +// will not finish on their own, and the person may have to act. +func stageTrackerMidFlightFor(it StageTrackerItem) *StageTrackerMidFlight { + if it.Kind != "pr" || stageTrackerHumanGateInert(it) { + return nil + } + head := shortHead(it.Head) + out := &StageTrackerMidFlight{Head: strings.TrimSpace(it.Head)} + ci, rv := it.CIActivity, it.ReviewActivity + var waits []string + var moved []string + if ci != nil && !stageTrackerHumanGateOnHead(ci, it.Head) { + moved = append(moved, "CI") + } + if rv != nil && !stageTrackerHumanGateOnHead(rv, it.Head) { + moved = append(moved, "review") + } + if len(moved) > 0 { + // The activity on file is for an earlier head: a push restarted + // the tracks, and whatever parked the PR parked the old head. + out.Kind = midFlightKindHead + on := "" + if head != "" { + on = " on " + head + } + waits = append(waits, strings.Join(moved, " and ")+" not yet run"+on) + } + if ci != nil && stageTrackerHumanGateOnHead(ci, it.Head) && stageTrackerCIMidFlight(ci) { + tally := "" + if ci.ChecksTotal > 0 { + tally = fmt.Sprintf(" %d/%d", ci.ChecksPassed, ci.ChecksTotal) + } + if out.Kind == "" { + out.Kind = midFlightKindCI + } + waits = append(waits, "CI running"+tally) + } + if rv != nil && stageTrackerHumanGateOnHead(rv, it.Head) { + if word, ok := stageTrackerReviewInFlightStates[rv.State]; ok { + tally := "" + if rv.PerspectivesTotal > 0 { + tally = fmt.Sprintf(" (%d/%d)", rv.PerspectivesDone, rv.PerspectivesTotal) + } + on := "" + if head != "" { + on = " on " + head + } + if out.Kind == "" { + out.Kind = midFlightKindReview + } + waits = append(waits, "review "+word+on+tally) + } + } + if len(waits) == 0 { + return nil + } + out.Text = strings.Join(waits, " · ") + if stageTrackerHumanGatePRParked(it.Stage, it.Modifiers, it.Superseded != nil, it.ManualMerge, it.HumanMergeReason) { + out.Park = stageTrackerMidFlightPark(it) + } + return out +} + +// stageTrackerCIMidFlight reports a CI activity that still has checks to +// report on its head: running, queued, or required checks not yet reported +// — unless every pending check is stuck. +func stageTrackerCIMidFlight(ci *StageTrackerActivity) bool { + if ci == nil { + return false + } + if len(ci.ChecksStuck) > 0 && len(ci.ChecksPending) <= len(ci.ChecksStuck) { + return false + } + switch ci.State { + case "running", "queued": + return true + case "missing": + return len(ci.ChecksPending) > 0 + } + return false +} + +// stageTrackerMidFlightPark is the plain-words reason the hive parked the PR +// for a person: the lane reason's own words, "" when the row names none. +func stageTrackerMidFlightPark(it StageTrackerItem) string { + base := strings.TrimSpace(it.Reason) + if base == "" { + return "" + } + if plain := decisionPlainReason(base); plain != "" && plain != decisionPlainReasonFallback { + return plain + } + return "" +} + +// stageTrackerResolveMidFlight sets every PR row's mid_flight and each +// nested PR's, from the same tracks (a nested PR carries its own CI and +// review activity). It runs before the human gates so the gate and the +// verbs read the finished field. +func stageTrackerResolveMidFlight(items []StageTrackerItem) { + // A nested PR carries no lane reason of its own; when the PR is listed + // as a row, its park reason is the row's. + parks := map[string]string{} + for i := range items { + it := &items[i] + it.MidFlight = stageTrackerMidFlightFor(*it) + stageTrackerMidFlightGuardOptions(it.DecisionNeeded, it.MidFlight) + if it.Kind == "pr" && it.MidFlight != nil && it.MidFlight.Park != "" { + parks[strings.ToLower(it.Repo)+"#"+strconv.Itoa(it.Number)] = it.MidFlight.Park + } + } + for i := range items { + it := &items[i] + for j := range it.LinkedPRs { + lp := &it.LinkedPRs[j] + lp.MidFlight = nil + if !stageTrackerHumanGateOpenLinkedPR(*lp) { + continue + } + lp.MidFlight = stageTrackerMidFlightFor(StageTrackerItem{ + Repo: it.Repo, Number: lp.Number, Kind: "pr", Stage: lp.Stage, Head: lp.Head, + Modifiers: lp.Modifiers, ManualMerge: lp.ManualMerge, HumanMergeReason: lp.HumanMergeReason, + CIActivity: lp.CIActivity, ReviewActivity: lp.ReviewActivity, + }) + if lp.MidFlight != nil && lp.MidFlight.Park == "" { + lp.MidFlight.Park = parks[strings.ToLower(it.Repo)+"#"+strconv.Itoa(lp.Number)] + } + stageTrackerMidFlightGuardOptions(lp.DecisionNeeded, lp.MidFlight) + } + } +} + +// stageTrackerMidFlightVerbs are the decision options that rest on the head +// being checked: the delegate, the approval and the answer to the park's +// question. Closing, holding and the rest stay as they were — a person may +// close a PR whose CI is still running. +var stageTrackerMidFlightVerbs = []string{decisionActionDelegate, decisionActionApprove, decisionActionDirection} + +// stageTrackerMidFlightWhy is the reason printed on a disabled verb. +func stageTrackerMidFlightWhy(mf *StageTrackerMidFlight) string { + why := "Waiting on " + mf.Text + ": the decision opens when CI and review finish on the current head" + if mf.Park != "" { + why += " (parked because " + mf.Park + ")" + } + return why +} + +// stageTrackerMidFlightGuardOptions disables, in place, the options of a +// decision that rest on the head being checked while the PR is mid-flight, +// with the reason, so every surface that draws the server's options (the +// popover, the lead actions, the pill) shows them disabled instead of +// offering a decision on a head nobody has finished checking. +func stageTrackerMidFlightGuardOptions(d *StageTrackerDecision, mf *StageTrackerMidFlight) { + if d == nil || mf == nil { + return + } + for i := range d.Options { + if o := &d.Options[i]; slices.Contains(stageTrackerMidFlightVerbs, o.Action) { + o.Enabled, o.ReasonIfDisabled = false, stageTrackerMidFlightWhy(mf) + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_midflight_test.go b/src/pkg/dashboard/stage_tracker_midflight_test.go new file mode 100644 index 0000000000..04de40156d --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_midflight_test.go @@ -0,0 +1,168 @@ +package dashboard + +import ( + "strings" + "testing" +) + +const midFlightTestHead = "abc1234def5678" + +func midFlightPR(mods ...func(*StageTrackerItem)) StageTrackerItem { + it := StageTrackerItem{Repo: "acme/api", Number: 7, Kind: "pr", Stage: 85, Head: midFlightTestHead, Modifiers: []string{modNeedsDecision}, + Reason: "contributor-lane:no-linked-issue"} + for _, m := range mods { + m(&it) + } + return it +} + +// hivecommons/hive#18889: a PR is mid-flight while the CURRENT head's CI +// runs or its review is queued or unfinished, or while the CI / review on +// file belong to an earlier head. +func TestStageTrackerMidFlightFor(t *testing.T) { + ciRunning := &StageTrackerActivity{Head: midFlightTestHead, State: "running", ChecksPassed: 2, ChecksTotal: 5, ChecksPending: []string{"a", "b", "c"}} + cases := []struct { + name string + item StageTrackerItem + wantKind string + wantText string + }{ + {"CI running on the current head", midFlightPR(func(it *StageTrackerItem) { it.CIActivity = ciRunning }), midFlightKindCI, "CI running 2/5"}, + {"CI queued, no tally", midFlightPR(func(it *StageTrackerItem) { + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "queued"} + }), midFlightKindCI, "CI running"}, + {"required checks not reported", midFlightPR(func(it *StageTrackerItem) { + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "missing", ChecksPending: []string{"build"}} + }), midFlightKindCI, "CI running"}, + {"review queued", midFlightPR(func(it *StageTrackerItem) { + it.ReviewActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "unassigned", PerspectivesDone: 0, PerspectivesTotal: 5} + }), midFlightKindReview, "review queued on abc1234 (0/5)"}, + {"review being worked", midFlightPR(func(it *StageTrackerItem) { + it.ReviewActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "reviewing", PerspectivesDone: 2, PerspectivesTotal: 5} + }), midFlightKindReview, "review in progress on abc1234 (2/5)"}, + {"CI and review both", midFlightPR(func(it *StageTrackerItem) { + it.CIActivity = ciRunning + it.ReviewActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "assigned"} + }), midFlightKindCI, "CI running 2/5 · review queued on abc1234"}, + {"stale park: the review on file is for an earlier head", midFlightPR(func(it *StageTrackerItem) { + it.ReviewActivity = &StageTrackerActivity{Head: "0ld0ld0ld0ld", State: "human_decision"} + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "passing"} + }), midFlightKindHead, "review not yet run on abc1234"}, + {"stale park: CI and review both on file for an earlier head", midFlightPR(func(it *StageTrackerItem) { + it.ReviewActivity = &StageTrackerActivity{Head: "0ld0ld0ld0ld", State: "approved"} + it.CIActivity = &StageTrackerActivity{Head: "0ld0ld0ld0ld", State: "passing"} + }), midFlightKindHead, "CI and review not yet run on abc1234"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mf := stageTrackerMidFlightFor(tc.item) + if mf == nil { + t.Fatalf("want mid-flight %q, got nil", tc.wantText) + } + if mf.Kind != tc.wantKind || !strings.Contains(mf.Text, tc.wantText) { + t.Fatalf("mid-flight = %+v, want kind %s text containing %q", mf, tc.wantKind, tc.wantText) + } + if mf.Head != midFlightTestHead { + t.Fatalf("head = %q", mf.Head) + } + if mf.Park != "it links no issue, so the hive cannot tell which claim it fulfils and does not trust its author yet" { + t.Fatalf("a parked PR names why it was parked: %q", mf.Park) + } + }) + } +} + +func TestStageTrackerMidFlightSettledAndInert(t *testing.T) { + settled := []StageTrackerItem{ + midFlightPR(), + midFlightPR(func(it *StageTrackerItem) { + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "passing"} + it.ReviewActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "approved"} + }), + midFlightPR(func(it *StageTrackerItem) { + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "failing", ChecksFailing: []string{"build"}} + it.ReviewActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "changes_requested"} + }), + midFlightPR(func(it *StageTrackerItem) { + it.ReviewActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "human_decision"} + }), + // Checks that have run far past a normal run will not finish on + // their own: the person may have to act, so the row is not held. + midFlightPR(func(it *StageTrackerItem) { + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "running", ChecksPending: []string{"a"}, ChecksStuck: []string{"a"}} + }), + // No review swarm at all: nothing to wait for. + midFlightPR(func(it *StageTrackerItem) { + it.ReviewActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "unknown"} + }), + // An issue is not a PR. + {Repo: "acme/api", Number: 1, Kind: "issue", Stage: 45, CIActivity: &StageTrackerActivity{State: "running"}}, + // A merged PR has no decision to hold back. + midFlightPR(func(it *StageTrackerItem) { + it.Modifiers = []string{"merged"} + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "running"} + }), + } + for i, it := range settled { + if mf := stageTrackerMidFlightFor(it); mf != nil { + t.Errorf("case %d: settled row reads mid-flight: %+v", i, mf) + } + } +} + +// The unparked PR still reads mid-flight (delegate-all offers it), but names +// no park reason. +func TestStageTrackerMidFlightUnparkedNamesNoPark(t *testing.T) { + it := midFlightPR(func(it *StageTrackerItem) { + it.Stage, it.Modifiers, it.Reason = 60, nil, "" + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "running"} + }) + mf := stageTrackerMidFlightFor(it) + if mf == nil || mf.Park != "" { + t.Fatalf("mid-flight = %+v", mf) + } +} + +// The resolver sets the field on every row, mirrors it onto nested PRs from +// their own tracks, and disables the options that rest on the head being +// checked — on the row's decision and on its nested PRs' — with the reason. +func TestStageTrackerResolveMidFlightGuardsDecisionOptions(t *testing.T) { + pr := midFlightPR(func(it *StageTrackerItem) { + it.CIActivity = &StageTrackerActivity{Head: midFlightTestHead, State: "running", ChecksPassed: 2, ChecksTotal: 5} + it.DecisionNeeded = decisionForPR(*it, nil, "sentinel", false) + }) + issue := StageTrackerItem{Repo: "acme/api", Number: 5, Kind: "issue", Stage: 50, LinkedPRs: []StageTrackerLinkedPR{{ + Number: 7, Stage: 85, Head: midFlightTestHead, Modifiers: []string{modNeedsDecision}, + CIActivity: pr.CIActivity, DecisionNeeded: decisionForPR(pr, nil, "sentinel", false)}, + {Number: 8, Stage: 60, Head: "fff", CIActivity: &StageTrackerActivity{Head: "fff", State: "passing"}}}} + items := []StageTrackerItem{pr, issue} + stageTrackerResolveMidFlight(items) + + if items[0].MidFlight == nil || items[0].MidFlight.Text != "CI running 2/5" { + t.Fatalf("row mid_flight = %+v", items[0].MidFlight) + } + if lp := items[1].LinkedPRs[0]; lp.MidFlight == nil || lp.MidFlight.Text != "CI running 2/5" { + t.Fatalf("nested #7 mid_flight = %+v", lp.MidFlight) + } + if items[1].LinkedPRs[1].MidFlight != nil { + t.Fatalf("nested #8 has a green head: %+v", items[1].LinkedPRs[1].MidFlight) + } + for _, d := range []*StageTrackerDecision{items[0].DecisionNeeded, items[1].LinkedPRs[0].DecisionNeeded} { + guarded := map[string]bool{} + for _, o := range d.Options { + if o.Action == decisionActionDelegate || o.Action == decisionActionApprove || o.Action == decisionActionDirection { + guarded[o.Action] = true + if o.Enabled || !strings.Contains(o.ReasonIfDisabled, "CI running 2/5") { + t.Errorf("%s should be disabled with the reason: %+v", o.Action, o) + } + continue + } + if !o.Enabled && o.Action == decisionActionCloseWontfix { + t.Errorf("closing stays available while CI runs: %+v", o) + } + } + if len(guarded) != 3 { + t.Errorf("options guarded = %v", guarded) + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index ef2dc633ba..6389f33936 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -65,6 +65,10 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerDelegateTargets"), jsFunc(t, html, "stageTrackerGateTargets"), jsFunc(t, html, "stageTrackerServerDelegate"), + jsConstLine(t, html, "STAGE_TRACKER_MIDFLIGHT_VERBS"), + jsFunc(t, html, "stageTrackerMidFlightOf"), + jsFunc(t, html, "stageTrackerMidFlightWhy"), + jsFunc(t, html, "stageTrackerMidFlightApply"), jsFunc(t, html, "stageTrackerDecideOptions"), jsFunc(t, html, "stageTrackerSupersederOptions"), jsFunc(t, html, "stageTrackerSupersederDefault"), @@ -2123,3 +2127,84 @@ _stageTracker = { items: [issue, ownHold, twoPRs] }; })().catch(e => { console.error(e); process.exit(1); }); `) } + +// TestStageTrackerMidFlightGuardsDecisions: Decide / Approve / Let hive decide +// are not offered while the CURRENT head's CI is running or its review is +// queued or unfinished (hivecommons/hive#18889). They stay on the menu, +// disabled, with the reason; a park from an earlier head does not count; and +// "Let hive decide — all N PRs" skips (or, when every PR is in flight, +// disables for) the PRs still running. +func TestStageTrackerMidFlightGuardsDecisions(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+` +const ctx = { user: true, canHold: true, canHuman: true }; +const byId = (opts, id) => opts.find(o => o.id === id); +const GUARDED = ['decide:delegate', 'decide:approve', 'decide:direction']; +const parked = extra => Object.assign({ repo: 'o/r', kind: 'pr', number: 4, url: 'u', stage: 85, head: 'abc1234def', modifiers: ['needs-decision'], reason: 'contributor-lane:no-linked-issue' }, extra || {}); + +// Settled head: every option is live. +for (const o of stageTrackerDecideOptions(parked(), ctx)) assert.strictEqual(o.enabled, true, o.id + ' is offered on a settled head'); + +// Pending CI on the current head. +const ci = parked({ mid_flight: { kind: 'ci-running', text: 'CI running 2/5', head: 'abc1234def', park: 'it links no issue' } }); +const ciOpts = stageTrackerDecideOptions(ci, ctx); +for (const id of GUARDED) { + const o = byId(ciOpts, id); + assert.strictEqual(o.enabled, false, id + ' is disabled while CI runs'); + assert.ok(o.why.includes('CI running 2/5'), id + ' says why: ' + o.why); + assert.ok(o.why.includes('it links no issue'), id + ' names what parked the PR: ' + o.why); +} +// What a person may still do: close it. +assert.strictEqual(byId(ciOpts, 'decide:close-wontfix').enabled, true); +assert.strictEqual(byId(ciOpts, 'decide:close-superseded').enabled, true); + +// Review queued on the current head (hivecommons/hive#18868: "Review 0/5 · queued"). +const rv = parked({ mid_flight: { kind: 'review-in-progress', text: 'review queued on abc1234 (0/5)', head: 'abc1234def' } }); +assert.ok(byId(stageTrackerDecideOptions(rv, ctx), 'decide:delegate').why.includes('review queued on abc1234 (0/5)')); +assert.strictEqual(byId(stageTrackerDecideOptions(rv, ctx), 'decide:approve').enabled, false); + +// A park recorded for an earlier head: the push restarted both tracks, so +// the old park (its needs-decision pill and 085 stage) does not enable anything. +const stale = parked({ stage: 85, modifiers: ['needs-decision'], mid_flight: { kind: 'head-moved', text: 'CI and review not yet run on abc1234', head: 'abc1234def' } }); +for (const id of GUARDED) assert.strictEqual(byId(stageTrackerDecideOptions(stale, ctx), id).enabled, false, id + ' on a stale park'); + +// A server option that was already disabled keeps its own reason when the +// head is settled (no mid_flight), and an unset mid_flight changes nothing. +assert.strictEqual(stageTrackerMidFlightOf({ mid_flight: { text: '' } }), null); +assert.strictEqual(stageTrackerMidFlightWhy(parked()), ''); + +// Issue row: its one parked nested PR is decided through that PR, so the +// nested PR's mid_flight disables the issue row's options too. +const issue = { repo: 'o/r', kind: 'issue', number: 5, url: 'u', stage: 50, modifiers: [], linked_prs: [Object.assign({ number: 4, state: 'open', stage: 85, head: 'abc1234def', modifiers: ['needs-decision'] }, { mid_flight: ci.mid_flight })] }; +const target = stageTrackerDecisionTarget(issue); +assert.strictEqual(target.number, 4); +assert.strictEqual(byId(stageTrackerDecideOptions(target, ctx), 'decide:delegate').enabled, false); + +// Delegate-all: skip what is in flight, disable when everything is. +const fly = n => ({ number: n, state: 'open', stage: 60, head: 'h' + n, modifiers: [], mid_flight: { kind: 'ci-running', text: 'CI running 1/4', head: 'h' + n } }); +const calm = n => ({ number: n, state: 'open', stage: 85, head: 'h' + n, modifiers: ['needs-decision'] }); +const rowOf = linked => ({ repo: 'o/r', kind: 'issue', number: 5, url: 'u', stage: 50, modifiers: [], linked_prs: linked }); +const allOf = row => stageTrackerRowActions(row, ctx).find(a => a.id === 'decide:delegate-all'); +const none = allOf(rowOf([calm(11), calm(12)])); +assert.strictEqual(none.enabled, true); assert.strictEqual(none.hint, 'per PR'); +const some = allOf(rowOf([calm(11), fly(12)])); +assert.strictEqual(some.enabled, true, 'one settled PR is still decided'); +assert.ok(some.hint.includes('skips 1 still running'), some.hint); +assert.deepStrictEqual(some.prs, [11, 12], 'the request names every PR; the server skips the one in flight'); +const every = allOf(rowOf([fly(11), fly(12)])); +assert.strictEqual(every.enabled, false); +assert.ok(every.why.includes('#11 CI running 1/4') && every.why.includes('#12 CI running 1/4'), every.why); + +// The click that beat the repaint is answered, not sent. +const calls = []; const toasts = []; +global.fetch = async (url, init) => { calls.push(url); return { ok: true, status: 200, json: async () => ({}) }; }; +global.showToast = (msg, type) => { toasts.push(type + ':' + msg); return null; }; +(async () => { + await runRowAction('decide:delegate', [ci]); + await runRowAction('decide:approve', [ci]); + await runRowAction('decide:delegate-all', [rowOf([fly(11), fly(12)])]); + assert.deepStrictEqual(calls, [], 'nothing is sent for a PR whose CI is running'); + assert.ok(toasts.length === 3 && toasts[0].includes('not yet') && toasts[0].includes('CI running 2/5'), toasts.join(' | ')); +})().catch(e => { console.error(e); process.exit(1); }); +`) +} diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 10d3247c1e..c5aa7b8380 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -1014,6 +1014,7 @@ .ham-human-gate .ham-gate-more[aria-expanded="true"] { background: color-mix(in srgb, var(--amber) 22%, transparent); } .ham-human-gate.ham-gate-settling { opacity: 0.75; border-style: dashed; } .ham-human-gate.ham-gate-settling > .ham-gate-status { color: var(--cue-work); } + .ham-human-gate > .ham-gate-wait { display: inline-flex; align-items: center; min-width: 0; padding: 0 var(--sp-2); color: var(--muted); font-size: var(--fs-xs); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .ham-gate-menu[hidden] { display: none; } /* The passive "decision pending on #N" chip is a link to the primary row. */ .ham-decision-pending[data-ham-scroll-to] { text-decoration: underline dotted; text-underline-offset: var(--sp-1); } diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index 686651a28f..d826c009b3 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -289,7 +289,8 @@ out.push({ id: 'decide:close-superseded', label: 'Close as superseded by…', enabled, why, danger: true }); out.push({ id: 'decide:close-wontfix', label: "Won't fix…", enabled, why, danger: true }); out.push({ id: 'decide:direction', label: 'Give direction…', enabled, why }); - return out; + // A head whose CI or review is still running is not decided on yet. + return typeof stageTrackerMidFlightApply === 'function' ? stageTrackerMidFlightApply(out, item) : out; } out.push({ id: 'decide:approve', label: 'Approve direction', enabled, why }); out.push({ id: 'decide:direction', label: 'Send back to the hive…', enabled, why }); @@ -453,7 +454,14 @@ const nested = stageTrackerNestedOpenPRs(item); if (nested.length >= STAGE_TRACKER_DELEGATE_ALL_MIN) { const can = write && !!ctx.user; - out.push({ id: 'decide:delegate-all', label: 'Let hive decide — all ' + nested.length + ' PRs', hint: 'per PR', enabled: can, why: can ? '' : STAGE_TRACKER_WHY_WRITE, prs: nested.map(p => p.number) }); + // PRs whose CI or review is still running on the current head are + // skipped by the fan-out (the server answers each one no-effect); + // when every PR is mid-flight the action is disabled with the reason + // (hivecommons/hive#18889). + const flying = typeof stageTrackerMidFlightOf === 'function' ? nested.filter(stageTrackerMidFlightOf) : []; + const allFlying = flying.length === nested.length; + const flightWhy = allFlying ? 'Every PR is still waiting: ' + flying.map(p => '#' + p.number + ' ' + stageTrackerMidFlightOf(p).text).join('; ') : ''; + out.push({ id: 'decide:delegate-all', label: 'Let hive decide — all ' + nested.length + ' PRs', hint: flying.length && !allFlying ? 'per PR · skips ' + flying.length + ' still running' : 'per PR', enabled: can && !allFlying, why: !can ? STAGE_TRACKER_WHY_WRITE : flightWhy, prs: nested.map(p => p.number) }); } // The row asks the human for something (decision_needed on the item // or its one asking nested PR): the server's answers lead the menu, @@ -2706,6 +2714,11 @@ } else if (id === 'decide:delegate-all') { // The issue row itself is the request; the server fans out per PR. items = items.filter(it => stageTrackerNestedOpenPRs(it).length >= STAGE_TRACKER_DELEGATE_ALL_MIN); + // Every PR still mid-flight: nothing to send (the menu disables it). + if (typeof stageTrackerMidFlightOf === 'function' && items.length && items.every(it => stageTrackerNestedOpenPRs(it).every(stageTrackerMidFlightOf))) { + showToast('Let hive decide — all PRs: not yet, CI or review is still running on each', 'info'); + return { toasts: [], pending: [] }; + } } else if (id === 'decide:adopt-now' || stageTrackerActionBase(id) === 'decide:reroute') { // Adopt now / Reroute act on the PR waiting on its contributor (072 / 071). items = items.map(stageTrackerTakeoverTarget).filter(Boolean); @@ -2753,6 +2766,18 @@ items = [].concat(...items.map(it => stageTrackerGateTargets(it, id))) .filter(t => t && !seen[stageTrackerItemKey(t)] && (seen[stageTrackerItemKey(t)] = true)); if (!items.length) { stageTrackerNothingToActOn(id, rows); return { toasts: [], pending: [] }; } + // A decision on a head whose CI or review is still running is not + // sent (hivecommons/hive#18889): the menu draws it disabled, and a + // click that beat the repaint is answered with the reason. + if (typeof stageTrackerMidFlightApply === 'function' && STAGE_TRACKER_MIDFLIGHT_VERBS.indexOf(id) >= 0) { + const ready = items.filter(t => !stageTrackerMidFlightOf(t)); + if (ready.length < items.length) { + const held = items.filter(t => stageTrackerMidFlightOf(t)); + showToast(stageTrackerActionLabel(id) + ': not yet — ' + held.map(t => stageTrackerRefOf(t) + ' ' + stageTrackerMidFlightWhy(t)).join('; '), 'info'); + if (!ready.length) return { toasts: [], pending: [] }; + items = ready; + } + } } const payload = await stageTrackerActionPayload(items, id, rows); if (payload == null) return { toasts: [], pending: [], cancelled: true }; diff --git a/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js b/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js index 7122f06d10..2fb88d2fde 100644 --- a/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js +++ b/src/pkg/dashboard/static-src/js/tracker-filter-fetch.js @@ -65,6 +65,8 @@ "adoption-undone": {"kind": "reason", "plain": "the hive's copy was closed without merging and the adoption was undone", "detail": "The hive opened its copy, but the copy was closed without merging and a fresh one could not be opened, so the adoption was undone and the PR is back in its normal flow. Re-run the decision to adopt it again, or act on GitHub."}, "adoption/supersede": {"kind": "action", "plain": "close this PR and open a fresh hive-authored PR with the same commits", "detail": "Supersede means the hive closes this PR and opens a fresh hive-authored PR carrying the same commits and sign-off, then finishes it itself."}, "advisory-in-progress": {"kind": "rule", "plain": "a hive advisory the hive is still working; nothing to decide", "detail": "The issue is a hive advisory whose items are still being worked: the sweep ticks each as it closes or merges and closes the advisory when all are resolved. Nothing is written and nobody is parked on it."}, + "ci-pending": {"kind": "rule", "plain": "CI is still running on this branch; nothing to decide yet", "detail": "The pull request's checks have not finished and none has failed, so there is no fix to ask for and no green head to approve. The hive writes nothing and leaves it parked; decide again once the checks finish."}, + "mid-flight": {"kind": "rule", "plain": "checks or review are still running on this branch's current head; nothing decided", "detail": "CI is running, or the review of the current head is queued or unfinished, so a decision now would rest on a head nobody has finished checking. The hive writes nothing; decide once CI and review finish on that head."}, "advisory-resolved": {"kind": "rule", "plain": "a hive advisory whose items are all resolved; closed as completed", "detail": "The issue is a hive advisory (a dedupe checklist or triage note) and every item it lists is closed or merged, so nothing is left to read; the hive closes it as completed."}, "already-fixed": {"kind": "rule", "plain": "the issue was already fixed by a merged PR; closed as superseded", "detail": "The issue this PR fixes is already closed and a merged PR closed it (or a merged PR declares it supersedes this one), so nothing is left to deliver. The hive closes the PR as superseded with a note naming the merging PR; it never adopts it."}, "approve": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge queue merges it once every check passes.", "issue_plain": "approved to proceed — an agent may claim it", "issue_detail": "The hive approved the direction; the issue leaves Needs decision and an agent may claim it. Nothing is merged."}, diff --git a/src/pkg/dashboard/static-src/js/tracker-gate-truth.js b/src/pkg/dashboard/static-src/js/tracker-gate-truth.js index 6236ab85f7..b0c6e16a2a 100644 --- a/src/pkg/dashboard/static-src/js/tracker-gate-truth.js +++ b/src/pkg/dashboard/static-src/js/tracker-gate-truth.js @@ -22,6 +22,36 @@ const STAGE_TRACKER_GATE_NO_DECISION = 'No decision pending'; const STAGE_TRACKER_GATE_APPROVED_BY = 'Approved by @'; const STAGE_TRACKER_GATE_STALE = ' is not waiting on that decision'; + /* ---- Mid-flight PRs (hivecommons/hive#18889) -------------------------- + A decision is a call on the head as it stands. While the CURRENT + head's CI is running, its review is queued or unfinished, or the CI / + review on file belong to an earlier head (a push restarted both), the + call is premature. The server states it per row as `mid_flight` + ({kind, text, head, park}); the verbs that rest on the head being + checked are drawn disabled with the reason instead of offered. A park + recorded for an earlier head does not count. */ + const STAGE_TRACKER_MIDFLIGHT_VERBS = ['decide:delegate', 'decide:approve', 'decide:direction', 'gate:decide']; + // Pure: the server's mid_flight on the row, null when the head is settled. + function stageTrackerMidFlightOf(item) { + const m = item && item.mid_flight; + return m && typeof m === 'object' && String(m.text || '').trim() ? m : null; + } + // Pure: the reason a decision on the row is not offered yet, '' when it is. + function stageTrackerMidFlightWhy(item) { + const m = stageTrackerMidFlightOf(item); + if (!m) return ''; + const park = String(m.park || '').trim(); + return 'Waiting on ' + String(m.text).trim() + ': the decision opens when CI and review finish on the current head' + (park ? ' (parked because ' + park + ')' : ''); + } + // Pure: disables, in place, the options that rest on the head being + // checked while the row is mid-flight; the options come back unchanged + // otherwise. + function stageTrackerMidFlightApply(options, item) { + const why = stageTrackerMidFlightWhy(item); + if (!why) return options; + (options || []).forEach(o => { if (o && STAGE_TRACKER_MIDFLIGHT_VERBS.indexOf(o.id) >= 0) { o.enabled = false; o.why = why; } }); + return options; + } // Pure: the server's gate for the row (`human_gate`), null when absent. function stageTrackerServerGate(item) { const g = item && item.human_gate; diff --git a/src/pkg/dashboard/static-src/js/tracker-human-gate.js b/src/pkg/dashboard/static-src/js/tracker-human-gate.js index 8a07da972e..84859dca03 100644 --- a/src/pkg/dashboard/static-src/js/tracker-human-gate.js +++ b/src/pkg/dashboard/static-src/js/tracker-human-gate.js @@ -158,6 +158,10 @@ // row's own lead actions (server-judged delegate, approve) are trusted // first; the rest follow the hold permission the endpoints share. function stageTrackerHumanGateVerbState(id, item, ctx, leads) { + // A head whose CI or review is still running is not decided on yet + // (hivecommons/hive#18889): the verb stays, disabled, with the reason. + const flight = typeof stageTrackerMidFlightOf === 'function' && STAGE_TRACKER_MIDFLIGHT_VERBS.indexOf(id) >= 0 && stageTrackerMidFlightOf(item) ? stageTrackerMidFlightWhy(item) : ''; + if (flight) return { enabled: false, why: flight }; const lead = (leads || []).find(a => a && a.id === id); if (lead) return { enabled: lead.enabled !== false, why: lead.enabled === false ? String(lead.why || '') : '' }; return typeof stageTrackerActionAllowed === 'function' ? stageTrackerActionAllowed(id, ctx) : { enabled: true, why: '' }; @@ -232,7 +236,13 @@ // stamped into the wrap the first time the … opens. const more = moreVerbs.length ? `<span class="ham-gate-more-wrap"><button type="button" class="ham-lead-act ham-gate-act ham-gate-more" data-ham-gate-more aria-haspopup="menu" aria-expanded="false" aria-label="More ways to settle this gate" title="${esc(moreVerbs.map(v => v.label).join(' · '))}">…</button><template class="ham-gate-menu-tpl"><div class="ham-menu ham-gate-menu" role="menu" aria-label="More ways to settle this gate" hidden>${moreVerbs.map(v => stageTrackerHumanGateVerbHtml(item, v, stageTrackerHumanGateVerbState(v.id, shown, ctx, leads), true)).join('')}</div></template></span>` : ''; const key = typeof stageTrackerItemKey === 'function' ? stageTrackerItemKey(item) : ''; - return `<span class="ham-human-gate" data-ham-gate="${esc(key)}" data-ham-gate-reasons="${esc(reasons.map(r => r.key).join(' '))}" role="group" aria-label="${esc(text)}">${status}${acts}${more}</span>`; + // The real reason the verbs are not live yet: the head's CI or review + // is still running (hivecommons/hive#18889). The pill still names what + // parked the row; this says why nothing can be decided on it now. + const flightWhy = typeof stageTrackerMidFlightWhy === 'function' ? stageTrackerMidFlightWhy(shown) : ''; + const flightWord = flightWhy ? String(stageTrackerMidFlightOf(shown).text).trim() : ''; + const wait = flightWhy ? `<span class="ham-gate-wait" data-ham-gate-wait="${esc(String(stageTrackerMidFlightOf(shown).kind || ''))}" title="${esc(flightWhy)}" role="status">waiting on ${esc(flightWord)}</span>` : ''; + return `<span class="ham-human-gate" data-ham-gate="${esc(key)}" data-ham-gate-reasons="${esc(reasons.map(r => r.key).join(' '))}" role="group" aria-label="${esc(text + (flightWord ? ' — waiting on ' + flightWord : ''))}">${status}${wait}${acts}${more}</span>`; } // The pill's optimistic state after one of its verbs ran: the status // reads "settling…" until the next snapshot re-renders the row. diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 4a59b0c634..937918557e 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -76,7 +76,7 @@ human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, - decided: lp.decided || null, human_gate: lp.human_gate || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; + decided: lp.decided || null, human_gate: lp.human_gate || null, mid_flight: lp.mid_flight || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; } // Pure: whether a linked PR is still open (not merged / closed / // superseded). With `issue`, an adopted original whose hive copy is diff --git a/src/pkg/dashboard/static-src/js/tracker-row-render.js b/src/pkg/dashboard/static-src/js/tracker-row-render.js index 2e60588d6a..4e75e250b6 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -138,7 +138,7 @@ shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, human_gate: lp.human_gate || null }); + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, human_gate: lp.human_gate || null, mid_flight: lp.mid_flight || null }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed // and nothing lit; one sub-row per PR carries the live chevron. diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 14aea7df3f..f7ed0966f0 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -2369,6 +2369,7 @@ .ham-human-gate .ham-gate-more[aria-expanded="true"] { background: color-mix(in srgb, var(--amber) 22%, transparent); } .ham-human-gate.ham-gate-settling { opacity: 0.75; border-style: dashed; } .ham-human-gate.ham-gate-settling > .ham-gate-status { color: var(--cue-work); } + .ham-human-gate > .ham-gate-wait { display: inline-flex; align-items: center; min-width: 0; padding: 0 var(--sp-2); color: var(--muted); font-size: var(--fs-xs); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .ham-gate-menu[hidden] { display: none; } /* The passive "decision pending on #N" chip is a link to the primary row. */ .ham-decision-pending[data-ham-scroll-to] { text-decoration: underline dotted; text-underline-offset: var(--sp-1); } @@ -21516,7 +21517,7 @@ <h3 class="faq-group-title">Where to get help</h3> human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, - decided: lp.decided || null, human_gate: lp.human_gate || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; + decided: lp.decided || null, human_gate: lp.human_gate || null, mid_flight: lp.mid_flight || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; } // Pure: whether a linked PR is still open (not merged / closed / // superseded). With `issue`, an adopted original whose hive copy is @@ -22013,7 +22014,7 @@ <h3 class="faq-group-title">Where to get help</h3> shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, human_gate: lp.human_gate || null }); + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null, human_gate: lp.human_gate || null, mid_flight: lp.mid_flight || null }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed // and nothing lit; one sub-row per PR carries the live chevron. @@ -24968,6 +24969,8 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> "adoption-undone": {"kind": "reason", "plain": "the hive's copy was closed without merging and the adoption was undone", "detail": "The hive opened its copy, but the copy was closed without merging and a fresh one could not be opened, so the adoption was undone and the PR is back in its normal flow. Re-run the decision to adopt it again, or act on GitHub."}, "adoption/supersede": {"kind": "action", "plain": "close this PR and open a fresh hive-authored PR with the same commits", "detail": "Supersede means the hive closes this PR and opens a fresh hive-authored PR carrying the same commits and sign-off, then finishes it itself."}, "advisory-in-progress": {"kind": "rule", "plain": "a hive advisory the hive is still working; nothing to decide", "detail": "The issue is a hive advisory whose items are still being worked: the sweep ticks each as it closes or merges and closes the advisory when all are resolved. Nothing is written and nobody is parked on it."}, + "ci-pending": {"kind": "rule", "plain": "CI is still running on this branch; nothing to decide yet", "detail": "The pull request's checks have not finished and none has failed, so there is no fix to ask for and no green head to approve. The hive writes nothing and leaves it parked; decide again once the checks finish."}, + "mid-flight": {"kind": "rule", "plain": "checks or review are still running on this branch's current head; nothing decided", "detail": "CI is running, or the review of the current head is queued or unfinished, so a decision now would rest on a head nobody has finished checking. The hive writes nothing; decide once CI and review finish on that head."}, "advisory-resolved": {"kind": "rule", "plain": "a hive advisory whose items are all resolved; closed as completed", "detail": "The issue is a hive advisory (a dedupe checklist or triage note) and every item it lists is closed or merged, so nothing is left to read; the hive closes it as completed."}, "already-fixed": {"kind": "rule", "plain": "the issue was already fixed by a merged PR; closed as superseded", "detail": "The issue this PR fixes is already closed and a merged PR closed it (or a merged PR declares it supersedes this one), so nothing is left to deliver. The hive closes the PR as superseded with a note naming the merging PR; it never adopts it."}, "approve": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge queue merges it once every check passes.", "issue_plain": "approved to proceed — an agent may claim it", "issue_detail": "The hive approved the direction; the issue leaves Needs decision and an agent may claim it. Nothing is merged."}, @@ -25359,7 +25362,8 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> out.push({ id: 'decide:close-superseded', label: 'Close as superseded by…', enabled, why, danger: true }); out.push({ id: 'decide:close-wontfix', label: "Won't fix…", enabled, why, danger: true }); out.push({ id: 'decide:direction', label: 'Give direction…', enabled, why }); - return out; + // A head whose CI or review is still running is not decided on yet. + return typeof stageTrackerMidFlightApply === 'function' ? stageTrackerMidFlightApply(out, item) : out; } out.push({ id: 'decide:approve', label: 'Approve direction', enabled, why }); out.push({ id: 'decide:direction', label: 'Send back to the hive…', enabled, why }); @@ -25523,7 +25527,14 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const nested = stageTrackerNestedOpenPRs(item); if (nested.length >= STAGE_TRACKER_DELEGATE_ALL_MIN) { const can = write && !!ctx.user; - out.push({ id: 'decide:delegate-all', label: 'Let hive decide — all ' + nested.length + ' PRs', hint: 'per PR', enabled: can, why: can ? '' : STAGE_TRACKER_WHY_WRITE, prs: nested.map(p => p.number) }); + // PRs whose CI or review is still running on the current head are + // skipped by the fan-out (the server answers each one no-effect); + // when every PR is mid-flight the action is disabled with the reason + // (hivecommons/hive#18889). + const flying = typeof stageTrackerMidFlightOf === 'function' ? nested.filter(stageTrackerMidFlightOf) : []; + const allFlying = flying.length === nested.length; + const flightWhy = allFlying ? 'Every PR is still waiting: ' + flying.map(p => '#' + p.number + ' ' + stageTrackerMidFlightOf(p).text).join('; ') : ''; + out.push({ id: 'decide:delegate-all', label: 'Let hive decide — all ' + nested.length + ' PRs', hint: flying.length && !allFlying ? 'per PR · skips ' + flying.length + ' still running' : 'per PR', enabled: can && !allFlying, why: !can ? STAGE_TRACKER_WHY_WRITE : flightWhy, prs: nested.map(p => p.number) }); } // The row asks the human for something (decision_needed on the item // or its one asking nested PR): the server's answers lead the menu, @@ -27776,6 +27787,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } else if (id === 'decide:delegate-all') { // The issue row itself is the request; the server fans out per PR. items = items.filter(it => stageTrackerNestedOpenPRs(it).length >= STAGE_TRACKER_DELEGATE_ALL_MIN); + // Every PR still mid-flight: nothing to send (the menu disables it). + if (typeof stageTrackerMidFlightOf === 'function' && items.length && items.every(it => stageTrackerNestedOpenPRs(it).every(stageTrackerMidFlightOf))) { + showToast('Let hive decide — all PRs: not yet, CI or review is still running on each', 'info'); + return { toasts: [], pending: [] }; + } } else if (id === 'decide:adopt-now' || stageTrackerActionBase(id) === 'decide:reroute') { // Adopt now / Reroute act on the PR waiting on its contributor (072 / 071). items = items.map(stageTrackerTakeoverTarget).filter(Boolean); @@ -27823,6 +27839,18 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> items = [].concat(...items.map(it => stageTrackerGateTargets(it, id))) .filter(t => t && !seen[stageTrackerItemKey(t)] && (seen[stageTrackerItemKey(t)] = true)); if (!items.length) { stageTrackerNothingToActOn(id, rows); return { toasts: [], pending: [] }; } + // A decision on a head whose CI or review is still running is not + // sent (hivecommons/hive#18889): the menu draws it disabled, and a + // click that beat the repaint is answered with the reason. + if (typeof stageTrackerMidFlightApply === 'function' && STAGE_TRACKER_MIDFLIGHT_VERBS.indexOf(id) >= 0) { + const ready = items.filter(t => !stageTrackerMidFlightOf(t)); + if (ready.length < items.length) { + const held = items.filter(t => stageTrackerMidFlightOf(t)); + showToast(stageTrackerActionLabel(id) + ': not yet — ' + held.map(t => stageTrackerRefOf(t) + ' ' + stageTrackerMidFlightWhy(t)).join('; '), 'info'); + if (!ready.length) return { toasts: [], pending: [] }; + items = ready; + } + } } const payload = await stageTrackerActionPayload(items, id, rows); if (payload == null) return { toasts: [], pending: [], cancelled: true }; @@ -28125,6 +28153,10 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> // row's own lead actions (server-judged delegate, approve) are trusted // first; the rest follow the hold permission the endpoints share. function stageTrackerHumanGateVerbState(id, item, ctx, leads) { + // A head whose CI or review is still running is not decided on yet + // (hivecommons/hive#18889): the verb stays, disabled, with the reason. + const flight = typeof stageTrackerMidFlightOf === 'function' && STAGE_TRACKER_MIDFLIGHT_VERBS.indexOf(id) >= 0 && stageTrackerMidFlightOf(item) ? stageTrackerMidFlightWhy(item) : ''; + if (flight) return { enabled: false, why: flight }; const lead = (leads || []).find(a => a && a.id === id); if (lead) return { enabled: lead.enabled !== false, why: lead.enabled === false ? String(lead.why || '') : '' }; return typeof stageTrackerActionAllowed === 'function' ? stageTrackerActionAllowed(id, ctx) : { enabled: true, why: '' }; @@ -28199,7 +28231,13 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> // stamped into the wrap the first time the … opens. const more = moreVerbs.length ? `<span class="ham-gate-more-wrap"><button type="button" class="ham-lead-act ham-gate-act ham-gate-more" data-ham-gate-more aria-haspopup="menu" aria-expanded="false" aria-label="More ways to settle this gate" title="${esc(moreVerbs.map(v => v.label).join(' · '))}">…</button><template class="ham-gate-menu-tpl"><div class="ham-menu ham-gate-menu" role="menu" aria-label="More ways to settle this gate" hidden>${moreVerbs.map(v => stageTrackerHumanGateVerbHtml(item, v, stageTrackerHumanGateVerbState(v.id, shown, ctx, leads), true)).join('')}</div></template></span>` : ''; const key = typeof stageTrackerItemKey === 'function' ? stageTrackerItemKey(item) : ''; - return `<span class="ham-human-gate" data-ham-gate="${esc(key)}" data-ham-gate-reasons="${esc(reasons.map(r => r.key).join(' '))}" role="group" aria-label="${esc(text)}">${status}${acts}${more}</span>`; + // The real reason the verbs are not live yet: the head's CI or review + // is still running (hivecommons/hive#18889). The pill still names what + // parked the row; this says why nothing can be decided on it now. + const flightWhy = typeof stageTrackerMidFlightWhy === 'function' ? stageTrackerMidFlightWhy(shown) : ''; + const flightWord = flightWhy ? String(stageTrackerMidFlightOf(shown).text).trim() : ''; + const wait = flightWhy ? `<span class="ham-gate-wait" data-ham-gate-wait="${esc(String(stageTrackerMidFlightOf(shown).kind || ''))}" title="${esc(flightWhy)}" role="status">waiting on ${esc(flightWord)}</span>` : ''; + return `<span class="ham-human-gate" data-ham-gate="${esc(key)}" data-ham-gate-reasons="${esc(reasons.map(r => r.key).join(' '))}" role="group" aria-label="${esc(text + (flightWord ? ' — waiting on ' + flightWord : ''))}">${status}${wait}${acts}${more}</span>`; } // The pill's optimistic state after one of its verbs ran: the status // reads "settling…" until the next snapshot re-renders the row. @@ -28253,6 +28291,36 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const STAGE_TRACKER_GATE_NO_DECISION = 'No decision pending'; const STAGE_TRACKER_GATE_APPROVED_BY = 'Approved by @'; const STAGE_TRACKER_GATE_STALE = ' is not waiting on that decision'; + /* ---- Mid-flight PRs (hivecommons/hive#18889) -------------------------- + A decision is a call on the head as it stands. While the CURRENT + head's CI is running, its review is queued or unfinished, or the CI / + review on file belong to an earlier head (a push restarted both), the + call is premature. The server states it per row as `mid_flight` + ({kind, text, head, park}); the verbs that rest on the head being + checked are drawn disabled with the reason instead of offered. A park + recorded for an earlier head does not count. */ + const STAGE_TRACKER_MIDFLIGHT_VERBS = ['decide:delegate', 'decide:approve', 'decide:direction', 'gate:decide']; + // Pure: the server's mid_flight on the row, null when the head is settled. + function stageTrackerMidFlightOf(item) { + const m = item && item.mid_flight; + return m && typeof m === 'object' && String(m.text || '').trim() ? m : null; + } + // Pure: the reason a decision on the row is not offered yet, '' when it is. + function stageTrackerMidFlightWhy(item) { + const m = stageTrackerMidFlightOf(item); + if (!m) return ''; + const park = String(m.park || '').trim(); + return 'Waiting on ' + String(m.text).trim() + ': the decision opens when CI and review finish on the current head' + (park ? ' (parked because ' + park + ')' : ''); + } + // Pure: disables, in place, the options that rest on the head being + // checked while the row is mid-flight; the options come back unchanged + // otherwise. + function stageTrackerMidFlightApply(options, item) { + const why = stageTrackerMidFlightWhy(item); + if (!why) return options; + (options || []).forEach(o => { if (o && STAGE_TRACKER_MIDFLIGHT_VERBS.indexOf(o.id) >= 0) { o.enabled = false; o.why = why; } }); + return options; + } // Pure: the server's gate for the row (`human_gate`), null when absent. function stageTrackerServerGate(item) { const g = item && item.human_gate; diff --git a/src/pkg/delegatedecision/ci_pending_test.go b/src/pkg/delegatedecision/ci_pending_test.go new file mode 100644 index 0000000000..179e7a8cbe --- /dev/null +++ b/src/pkg/delegatedecision/ci_pending_test.go @@ -0,0 +1,42 @@ +package delegatedecision + +import "testing" + +// hivecommons/hive#18889: CIRed() is false while checks are merely pending, +// so a PR whose checks had not finished fell through every rung to the two +// "green head" approvals. Pending CI now answers a refusal that writes +// nothing and keeps the park. +func TestDecidePRPendingCINeverReleases(t *testing.T) { + cases := []struct { + name string + in Input + }{ + {"default release", Input{Kind: KindPR, Number: 7, Title: "Add filter", ContributorOnline: true, CIPending: true}}, + {"hive authored", Input{Kind: KindPR, Number: 7, Title: "Add filter", HiveAuthored: true, ContributorOnline: true, CIPending: true}}, + {"small low risk", Input{Kind: KindPR, Number: 7, Title: "Pin the CI image", ContributorOnline: true, CIPending: true, Small: true, LowRiskPaths: true}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + d := Decide(tc.in) + if d.Verdict != VerdictRefused || d.Rule != RuleCIPending || !d.KeepsPark || len(d.Actions) != 0 { + t.Fatalf("pending CI must refuse and write nothing: verdict %s rule %s keeps_park %v actions %+v", d.Verdict, d.Rule, d.KeepsPark, d.Actions) + } + if d.Rule == "default-release" || d.Rule == "small-low-risk" { + t.Fatalf("released a head whose CI is running: %+v", d) + } + }) + } + // The same heads, green, are released as before. + for _, in := range []Input{ + {Kind: KindPR, Number: 7, Title: "Add filter", ContributorOnline: true, CIGreen: true}, + {Kind: KindPR, Number: 7, Title: "Pin the CI image", ContributorOnline: true, CIGreen: true, Small: true, LowRiskPaths: true}, + } { + if d := Decide(in); d.Verdict != VerdictApprove { + t.Fatalf("green head: verdict %s rule %s", d.Verdict, d.Rule) + } + } + // A head with a real problem is still handled by its own rule, pending or not. + if d := Decide(Input{Kind: KindPR, Number: 7, Title: "Add filter", ContributorOnline: true, CIPending: true, Conflicting: true}); d.Rule == RuleCIPending || d.Verdict == VerdictApprove { + t.Fatalf("conflicting head must be directed, not waited on or released: rule %s verdict %s", d.Rule, d.Verdict) + } +} diff --git a/src/pkg/delegatedecision/decision_glossary.go b/src/pkg/delegatedecision/decision_glossary.go index c907653c6c..f1fa1ff4be 100644 --- a/src/pkg/delegatedecision/decision_glossary.go +++ b/src/pkg/delegatedecision/decision_glossary.go @@ -145,6 +145,10 @@ var glossary = []GlossaryEntry{ Detail: "The issue is a hive advisory (a dedupe checklist or triage note) and every item it lists is closed or merged, so nothing is left to read; the hive closes it as completed."}, {Slug: RuleAdvisoryInProgress, Kind: GlossaryRule, Plain: "a hive advisory the hive is still working; nothing to decide", Detail: "The issue is a hive advisory whose items are still being worked: the sweep ticks each as it closes or merges and closes the advisory when all are resolved. Nothing is written and nobody is parked on it."}, + {Slug: RuleCIPending, Kind: GlossaryRule, Plain: "CI is still running on this branch; nothing to decide yet", + Detail: "The pull request's checks have not finished and none has failed, so there is no fix to ask for and no green head to approve. The hive writes nothing and leaves it parked; decide again once the checks finish."}, + {Slug: RuleMidFlight, Kind: GlossaryRule, Plain: "checks or review are still running on this branch's current head; nothing decided", + Detail: "CI is running, or the review of the current head is queued or unfinished, so a decision now would rest on a head nobody has finished checking. The hive writes nothing; decide once CI and review finish on that head."}, {Slug: "default-approve", Kind: GlossaryRule, Plain: "no special rule applies; the hive took its own recommendation", Detail: "No owner rule singles this issue out, so the hive went with its own recommendation — the reversible choice that keeps work moving."}, {Slug: "default-release", Kind: GlossaryRule, Plain: "no special rule applies; a green branch is approved", diff --git a/src/pkg/delegatedecision/policy.go b/src/pkg/delegatedecision/policy.go index 0fee26304c..e785ef3fe7 100644 --- a/src/pkg/delegatedecision/policy.go +++ b/src/pkg/delegatedecision/policy.go @@ -152,6 +152,18 @@ const ( RuleAdvisoryInProgress = "advisory-in-progress" ) +// Mid-flight rule names (hivecommons/hive#18889): a head whose checks have +// not finished is not a head the delegate may release. +const ( + // RuleCIPending: the PR's checks are still running with none failed, so + // no fix is owed and no approval is earned; the delegate writes nothing. + RuleCIPending = "ci-pending" + // RuleMidFlight: the dashboard's server-side guard — CI is running or + // the review is incomplete on the current head — answered before any + // decider ran. + RuleMidFlight = "mid-flight" +) + // AdvisoryChecklist is the progress of a hive advisory's checklist: how // many of its items are resolved. Total 0 is an advisory without items. type AdvisoryChecklist struct { @@ -600,6 +612,17 @@ func operatorActionDecision(sr SelfReport, remedy string) Decision { } } +// ciPendingDecision declines to release a PR whose checks are still +// running: nothing is written and the PR stays parked until they finish. +func ciPendingDecision(ref string) Decision { + return Decision{ + Verdict: VerdictRefused, Rule: RuleCIPending, + Text: "wait on " + ref + ": CI is still running on the current head", + Rationale: "CI is still running on the current head, so there is nothing yet to approve; decide again once the checks finish", + KeepsPark: true, + } +} + // notNowDecision declines a hive-filed proposal that shows neither an // incident nor a recurrence: the reason is posted and the issue is closed // as not planned, the way a declined proposal leaves the tracker. @@ -752,6 +775,13 @@ func decidePR(in Input) Decision { Actions: []Action{decisionComment(text)}, } } + // CIRed is false while checks are merely pending, so fixList above names + // nothing for a head still running its checks; without this the two + // approvals below ("green head") fired on a head that was not green + // (hivecommons/hive#18889). + if in.CIPending { + return ciPendingDecision(ref) + } if in.IsSmall() || in.LowRiskPaths { return releasePR("small-low-risk", "approve "+ref+": small, necessary, low-risk change on a green head", "small low-risk changes (CI pins, read-only RBAC, warning text, workflow hygiene) are approved once checked") }