diff --git a/changelog.d/fixed-ready-for-human-merge-actions.md b/changelog.d/fixed-ready-for-human-merge-actions.md new file mode 100644 index 0000000000..493cc89758 --- /dev/null +++ b/changelog.d/fixed-ready-for-human-merge-actions.md @@ -0,0 +1 @@ +- Activity Monitor: a PR at *Ready for human merge* now offers **Approve & merge as maintainer** and **Approve — let hive merge** at the top of its ⋯ menu and needs-human popover (new `merge-now` / `queue-merge` decisions, merger/owner only, confirm + toast + decision badge), every needs-human state carries at least one matching action with a consequence line plus *Let hive decide* (on a 090 PR the hive answers at once in plain words why it won't merge, with the merge buttons), and the *untrusted author* pill explains why in plain words and how to trust the author (#15078). diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 70a3a90d91..ea4eb9ab27 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -725,6 +725,22 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p The glyph is drawn for **every** row on the gate, so two rows in the same state always look the same; the ⬡ / 🤖 / 👤 icon *after* the word is whose move it is (`STAGE_TRACKER_ACTOR`), unchanged. The *working* spin (an agent on the item right now) stays a separate cue and now also carries its sentence as tooltip and `aria-label` (*Working now: reviewer reviewed it · 2m ago*). `next_sweep_at` comes from the automerge lanes' sweep clock (`automerge.SweepSnapshot()` — the next periodic floor pass, 5 min event-driven or the legacy 10 s tick); webhook-named passes run sooner, which the tooltip says. `last_sweep_at` is the stage record's `last_seen` (when a lane last evaluated the PR). +**Every ask has its action (the lead entries).** Owner, on hotshot#317 at *Ready for human merge · untrusted author* (2026-10-29): "this claims it needs human merge but there is no option to take that action" ([#15078](https://github.com/hivecommons/hive/issues/15078)). Whenever a row — an issue row whose one nested PR is parked, or a PR sub-row — is in a state that asks a person for something, the ⋯ menu **leads** with the matching action(s), taken straight from the payload's `decision_needed.options`, each with its consequence as the hint; the generic entries (*Decide…*, *Hold*, *Re-evaluate now*, *Mark needs-human…*, *Open on GitHub*, *Copy link*) follow under a separator, and the needs-human popover shows the same options with the consequence under each button (`ham-decision-consequences`). A Go table test (`TestStageTrackerNeedsHumanStatesCarryAnAction`) keeps every state `stageTrackerNeedsHuman` flags on a non-empty options list with at least one enabled action (or a disabled one whose `reason_if_disabled` is plain words), and renderer tests (`TestStageTrackerRowActionsLeadWithDecisionOptions`, `TestStageTrackerIssueRowWithNested090PRCarriesAllThree` — the issue row over its one nested 090 PR carries Approve & merge, Approve — let hive merge and Let hive decide) keep the menu leading with them. *Let hive decide* is on every needs-human state: where the hive cannot act it says so in plain words through the no-effect toast instead of silently recording a decision. State by state: + +| State the pill shows | Lead actions in ⋯ and in the popover (consequence) | +|---|---| +| PR at 090 *Ready for human merge* (untrusted author, workflow files, manual-merge path, branch protection…) | **Approve & merge as maintainer** (merges #N into *base* now via hive's identity, attributed to you — a comment on the PR names you, the audit log records `repo_item_decision_merge`, `source: dashboard`) · **Approve — let hive merge** (records your approval as the owner decision — an APPROVE review and the automerge label; the hive's merge sweep merges it on its next pass once CI is green and the head has soaked) · Give direction (hive-authored PRs only) · Close as superseded · Close as won't fix · Hold. Both merge actions need the merger or owner role and confirm first (with *Don't ask again*); the toast reads *merged* / *queued for merge*; the badge records `merge-now` / `queue-merge`. **Let hive decide** is here too (third): on a 090 PR it never runs the policy — the hive answers at once through the no-effect toast, *I can't merge this: author @Karibhou is untrusted on hotshot — …*, with *Approve & merge as maintainer · Approve — let hive merge* as buttons and the 👥 Contributors fix in the next line. | +| PR at 085 *Needs human decision* | Let hive decide · Approve · Give direction · Close as superseded · Close as won't fix · Hold (unchanged). | +| Issue at 045 *Needs decision* (direction) | Let hive decide · Give direction · Approve direction · Send back to the hive · Hold (unchanged). | +| Human-authored PR at 071 *Needs author* / 072 *Returned to contributor* | Let hive decide · Close as superseded · Close as won't fix · Hold — the hive never rewrites a person's PR, so the choice is wait or close. (A hive-authored PR there carries *Adopt now* when adoption applies.) | +| `needs-human` label set by a person or the hive (any stage) | **Resolve — lift needs-human** (removes the label; on a PR also leaves the hive's /lgtm + /approve, on an issue a `/hive approve`) · Let hive decide · Hold. | +| `hive:unauthorized` | **Re-evaluate now** (re-reads GitHub; the hive resumes and clears the label once you did the step on GitHub) · Let hive decide · Hold · Mark needs-human. | +| 015 *Triage needed* | Accept triage · Let hive decide · Hold · Mark needs-human. | +| Hold set by an operator | **Release hold** leads; the state's own options stay listed but disabled with *Release the hold first*. | +| Any other stage the hive leaves to a person | Re-evaluate now · Let hive decide · Hold · Mark needs-human, with the question naming the stage. | + +**"Untrusted author", in plain words.** The 090 pill's tooltip now says *why* and *what would make it trusted*, per reason code. For the common `contributor-lane:author-association` (hotshot#317): *Untrusted author: @login is not a collaborator of this repository on GitHub (no owner, member or collaborator association) and holds no trusted or merger tier in this hive's contributor registry, so the hive will not merge their PR unattended. To trust them: give them the trusted or merger tier under 👥 Contributors (`auto_merge.contributor_lane.require_tiers`), or add them as a collaborator of the repository on GitHub. Until then a maintainer merges — Approve & merge as maintainer, or Approve — let hive merge, from the row's ⋯ menu.* The other trust reasons (`untrusted-author-role` → merger role under ⚙ Security / `dashboard.authorized_users`; `author-permission-missing` → `auto_merge.trusted_authors.require_github_permission`; `fork-non-member`; the claim-tier / no-claim / unverified-claim family → the 👥 Contributors tier) each get their own sentence. The hive App's own PRs are never "untrusted" — the lane only names a human author; the same text is the popover's question. + **Cue tokens.** The three cues of the legend above (state pill, working spin, decision badge) share one `tracker-cues` CSS block on `.ham-row`: `--cue-state` (what the row waits on — the pill and this popover), `--cue-work` (the hive is working right now — the chevron spin), `--cue-decision` (what people and the hive decided — the ✓ badge). Nothing else blinks; motion stays in the 150–300 ms range. ### Let hive decide diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index c022cb91ee..8c7dd318c5 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -456,6 +456,28 @@ from **Settings → Features → Auto-merge**. The dashboard writes the same owner-only `/api/config/auto-merge` overlay as the other auto-merge controls, so hosted spoke changes survive restarts without editing `hive.yaml`. +**When a lane leaves the merge to a person (`stage/090-ready-for-human-merge`).** +A PR no lane vouches for — an untrusted author (`contributor-lane:author-association`, +`untrusted-author-role`, `author-permission-missing`, `fork-non-member`, the +claim-tier family), workflow files, a manual-merge path — parks at 090 with a +*Ready for human merge* pill whose tooltip names the reason and the fix in plain +words (the config key and where in ⚙ / 👥 it is set). The Activity Monitor's ⋯ +menu and needs-human popover lead with the two actions that do what the pill +asks ([#15078](https://github.com/hivecommons/hive/issues/15078)), both +`POST /api/repos/{owner}/{repo}/items/{n}/decision` and both limited to a +verified owner or an authorized user with the `merger` role: + +| Decision | What it does | Audit / ledger | +|---|---|---| +| `merge-now` — *Approve & merge as maintainer* | Comments on the PR that @you merged it from the dashboard, then merges it at once through the hive's GitHub App (`MergePRVia`, audit path `dashboard`). Refused when the PR is merged or closed, or when you are its author. | `repo_item_decision_merge`; `last_operator_action.action: merge-now`; toast *merged*. | +| `queue-merge` — *Approve — let hive merge* | Leaves an `APPROVED` review in your name with a note, adds the automerge label, and leaves the merge to the App self-merge sweep, which merges on its next pass once CI is green and the head has soaked. Refused on your own PR. | `repo_item_decision_queue_merge`; `last_operator_action.action: queue-merge`; toast *queued for merge*. | + +Neither widens who the lanes trust: to stop a contributor's PRs parking at 090 +give them the `trusted` / `merger` tier under 👥 Contributors +(`auto_merge.contributor_lane.require_tiers`), add them as a repository +collaborator, or list them under `dashboard.authorized_users` with the +`merger` role. + Actionable merge failures surface as dashboard system alerts, deduplicated by repo+reason and cleared by the next successful merge in that repo. Alerts name the operator action: grant/install the App with Contents and Pull requests write, diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index ce2cf1d838..0849a80d2c 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "net/http" + "slices" "sort" "strconv" "strings" @@ -472,6 +473,12 @@ 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 PR at 090 Ready for human merge is one the hive's lanes already + // declined to merge: no policy run changes that, so answer at once in + // plain words with the actions that do (hivecommons/hive#15078). + if out, ok := s.delegatedHumanMergeOutcome(repoFull, number, itemType, user, mergerRole, in, req); ok { + return out + } d, deciderNotes := s.decideDelegated(ctx, in) // An adoption whose copy was closed unmerged (hivecommons/hive#15052) // overrides the policy: the recorded decision no longer stands, so the @@ -559,6 +566,7 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb in.Labels = append(in.Labels, l.GetName()) } author := strings.TrimSpace(issue.GetUser().GetLogin()) + in.Author = author in.HiveAuthored = client.IsHiveAuthorLogin(author) in.TrustedAuthor = in.HiveAuthored if issue.IsPullRequest() || itemType == "pr" { @@ -567,7 +575,13 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb if err != nil { return in, fmt.Errorf("reading PR %s#%d: %w", repoFull, number, err) } + for _, l := range pr.Labels { + if name := l.GetName(); name != "" && !slices.Contains(in.Labels, name) { + in.Labels = append(in.Labels, name) + } + } author = strings.TrimSpace(pr.GetUser().GetLogin()) + in.Author = author in.HiveAuthored = client.IsHiveAuthorLogin(author) in.TrustedAuthor = in.HiveAuthored if err := s.gatherDelegatedPRContext(ctx, repoFull, pr, &in); err != nil { 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 27a707d77c..f8b66d8940 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_test.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_test.go @@ -594,3 +594,56 @@ func TestDelegatedStuckWhyReadsTheLane(t *testing.T) { } } } + +// "Let hive decide" on a PR at 090 Ready for human merge answers at once +// (hivecommons/hive#15078): no policy run, no comment, a no-effect result +// that says in plain words why the hive will not merge it and carries the +// merge answers as buttons — enabled for a merger, greyed for a writer. +func TestDelegatedDecisionReadyForHumanMergeAnswersWithMergeOptions(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/090-ready-for-human-merge", "role/newcomer"}} + srv := newDelegatedServer(t, mock) + body := `{"type":"pr","reason":"contributor-lane:author-association","caption":"Ready for human merge · untrusted author"}` + w := postDelegated(t, srv, 8, "writer", body, map[string]string{"X-Hive-Role": "merger"}) + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + job := decodeDelegatedJob(t, w) + if job.Status != delegatedJobStatusDone || job.Result == nil || job.Result.Action != rowActionNoEffect { + t.Fatalf("job = %+v", job) + } + res := job.Result + t.Logf("outcome: %s\nnext: %s\nwhy: %s", res.Outcome, res.Next, res.Why) + for _, want := range []string{"I can't merge this: author @someone is untrusted on testrepo", "not a collaborator", "trusted or merger tier", "👥 Contributors"} { + if !strings.Contains(res.Outcome, want) { + t.Errorf("outcome %q missing %q", res.Outcome, want) + } + } + if res.Why != delegatedecision.GlossaryHumanMerge || res.Rule != delegatedHumanMergeRule { + t.Errorf("why=%q rule=%q", res.Why, res.Rule) + } + if !strings.Contains(res.Next, "Approve & merge as maintainer · Approve — let hive merge") || !strings.Contains(res.Next, "promote the author to trusted") { + t.Errorf("next = %q", res.Next) + } + if len(res.Options) < 2 || res.Options[0].Action != decisionActionMergeNow || !res.Options[0].Enabled || res.Options[1].Action != decisionActionQueueMerge || !res.Options[1].Enabled { + t.Fatalf("options = %+v", res.Options) + } + for _, o := range res.Options { + if o.Action == decisionActionDirection && (o.Enabled || o.ReasonIfDisabled == "") { + t.Errorf("direction on a human PR must be disabled with a reason: %+v", o) + } + } + if len(mock.comments) != 0 || len(mock.edits) != 0 || len(mock.reviews) != 0 || len(mock.merges) != 0 { + t.Fatalf("nothing may be written: comments=%v edits=%v reviews=%v merges=%v", mock.comments, mock.edits, mock.reviews, mock.merges) + } + + // A writer without the merger role gets the same answer with the merge + // buttons greyed and the reason in plain words. + w = postDelegated(t, srv, 8, "writer", body, nil) + job = decodeDelegatedJob(t, w) + if job.Result == nil || len(job.Result.Options) < 2 { + t.Fatalf("job = %+v", job) + } + if o := job.Result.Options[0]; o.Enabled || o.ReasonIfDisabled != decisionWhyMergerRole { + t.Errorf("merge-now for a writer = %+v", o) + } +} diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index 880a81f19b..87789c0802 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" + "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/delegatedecision" ghpkg "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/review" @@ -59,6 +60,13 @@ const ( repoItemDecisionCloseSuperseded = "close-superseded" repoItemDecisionCloseWontFix = "close-wontfix" repoItemDecisionAdopt = "adopt" + // Merge-gate answers on a PR parked at stage/090-ready-for-human-merge + // (hivecommons/hive#15078). merge-now merges through the hive's App at + // once, attributed to the operator; queue-merge records the operator's + // approval for the hive's auto-merge sweep, which merges it on the next + // tick once CI is green (soak and the self-merge ban still apply). + repoItemDecisionMergeNow = "merge-now" + repoItemDecisionQueueMerge = "queue-merge" repoItemDecisionMaxBody = 16 << 10 repoItemDecisionMaxComment = 4000 @@ -67,6 +75,8 @@ const ( auditRepoItemDecisionDirection = "repo_item_decision_direction" auditRepoItemDecisionClose = "repo_item_decision_close" auditRepoItemDecisionAdopt = "repo_item_decision_adopt" + auditRepoItemDecisionMerge = "repo_item_decision_merge" + auditRepoItemDecisionQueue = "repo_item_decision_queue_merge" // repoItemDecisionAdoptMarker opens the attributed note an Adopt // decision leaves on the PR. @@ -190,6 +200,14 @@ func repoItemDecisionResult(repoFull string, number int, itemType, decision, com out.Action = rowActionAdopted out.Outcome = "Adoption queued: `" + label + "` applied." out.Next = "The hive opens its own PR carrying the author's commits and sign-off on its next cycle; the original is closed as superseded." + case repoItemDecisionMergeNow: + out.Action = rowActionMerged + out.Outcome = "Merged into `" + label + "` now via hive's identity, attributed to you." + out.Next = "Nothing further to do; the row leaves the tracker on its next refresh." + case repoItemDecisionQueueMerge: + out.Action = rowActionQueued + out.Outcome = "Your approval is recorded; `" + label + "` applied." + out.Next = "Hive's merge sweep merges it on the next tick once CI is green, respecting soak; the dashboard merges nothing itself." } return out } @@ -353,9 +371,114 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) s.audit.LogRecord(user, auditRepoItemDecisionAdopt, auditDetail("repo", repoFull, "number", numStr, "type", itemType, "label", delegatedecision.LabelAdoptSupersede), "", repoFull, number) jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "adoption-queued", Label: delegatedecision.LabelAdoptSupersede, Result: repoItemDecisionResult(repoFull, number, itemType, decision, comment, "", delegatedecision.LabelAdoptSupersede, nil)}) + case repoItemDecisionMergeNow, repoItemDecisionQueueMerge: + if itemType != "pr" { + jsonError(w, decision+" applies to pull requests", http.StatusBadRequest) + return + } + if !repoItemMergeDecisionAllowed(r) { + jsonError(w, "merger or owner access required to merge or queue a pull request", http.StatusForbidden) + return + } + s.handlePullRequestMergeDecision(ctx, w, repoFull, number, user, decision, comment) default: - jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix or adopt", http.StatusBadRequest) + jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix, adopt, merge-now or queue-merge", http.StatusBadRequest) + } +} + +// repoItemMergeDecisionAllowed is the merge bar on top of the repo-hold bar: +// a verified owner or a merger (the same bar as POST .../queue-automerge), +// since both merge decisions end with a commit on the base branch. +func repoItemMergeDecisionAllowed(r *http.Request) bool { + role := r.Header.Get("X-Hive-Role") + if isOwnerRole(role) { + return r.Header.Get(ownerRoleVerifiedHeader) == "true" + } + return config.RoleAtLeast(role, config.RoleMerger) +} + +// handlePullRequestMergeDecision answers merge-now / queue-merge on a PR the +// merge gate parked for a person (stage/090-ready-for-human-merge). +func (s *Server) handlePullRequestMergeDecision(ctx context.Context, w http.ResponseWriter, repoFull string, number int, user, decision, comment string) { + gh := s.deps.GHClient + numStr := strconv.Itoa(number) + state, err := gh.GetPRState(ctx, repoFull, number) + if err != nil { + jsonError(w, "reading the pull request: "+err.Error(), http.StatusBadGateway) + return + } + if !state.MergedAt.IsZero() { + jsonError(w, "pull request is already merged", http.StatusConflict) + return + } + if !strings.EqualFold(state.State, "open") { + jsonError(w, "pull request is already closed", http.StatusConflict) + return + } + author, err := gh.GetPRAuthor(ctx, repoFull, number) + if err != nil { + jsonError(w, "reading the pull request author: "+err.Error(), http.StatusBadGateway) + return + } + if strings.EqualFold(author, user) { + jsonError(w, "you opened this pull request; another maintainer has to merge it", http.StatusForbidden) + return + } + base := state.BaseRef + if base == "" { + base = "the base branch" + } + if decision == repoItemDecisionQueueMerge { + if err := gh.QueuePRAutoMergeWithNote(ctx, repoFull, number, user, renderRepoItemDecisionQueueNote(user, comment)); err != nil { + jsonError(w, err.Error(), http.StatusBadGateway) + return + } + label := gh.AutoMergeLabel() + s.audit.LogRecord(user, auditRepoItemDecisionQueue, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", state.HeadSHA, "author", author, "label", label), "", repoFull, number) + s.invalidateStageTrackerForWebhook() + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "queued-for-merge", Label: label, Head: state.HeadSHA, + Result: repoItemDecisionResult(repoFull, number, "pr", decision, comment, "", label, nil)}) + return + } + if err := gh.CreateIssueComment(ctx, repoFull, number, renderRepoItemDecisionMergeComment(user, comment)); err != nil { + jsonError(w, "posting merge note: "+err.Error(), http.StatusBadGateway) + return + } + // The head the operator saw is the head that merges: a push in between + // makes GitHub refuse (409) rather than merge code nobody looked at. + res, err := gh.MergePRVia(ctx, repoFull, number, "", state.HeadSHA, ghpkg.PRAuditPathDashboard) + if err != nil { + jsonError(w, err.Error(), http.StatusBadGateway) + return + } + if !res.Merged { + jsonError(w, "GitHub did not merge the pull request: "+strings.TrimSpace(res.Message), http.StatusConflict) + return + } + s.audit.LogRecord(user, auditRepoItemDecisionMerge, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", state.HeadSHA, "author", author, "base", state.BaseRef, "sha", res.SHA), "", repoFull, number) + s.invalidateStageTrackerForWebhook() + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "merged", Head: state.HeadSHA, + Result: repoItemDecisionResult(repoFull, number, "pr", decision, comment, "", base, nil)}) +} + +// renderRepoItemDecisionMergeComment is the attributed note left on the PR +// before the hive's App merges it for the operator. +func renderRepoItemDecisionMergeComment(user, comment string) string { + body := fmt.Sprintf("Merged as maintainer by @%s from the Hive dashboard: the merge gate parked this pull request for a human because its author is not a trusted merger on this repository.", strings.TrimSpace(user)) + if c := strings.TrimSpace(comment); c != "" { + body += "\n\n> " + strings.ReplaceAll(c, "\n", "\n> ") + } + return body +} + +// renderRepoItemDecisionQueueNote is the note appended to the App's approval +// review when the operator lets the hive merge. +func renderRepoItemDecisionQueueNote(user, comment string) string { + note := fmt.Sprintf("Approved from the Hive dashboard by @%s as the owner decision on a Ready-for-human-merge pull request; the hive's merge sweep merges it on green CI.", strings.TrimSpace(user)) + if c := strings.TrimSpace(comment); c != "" { + note += "\n\n> " + strings.ReplaceAll(c, "\n", "\n> ") } + return note } // renderRepoItemDecisionAdoptComment is the attributed note an Adopt diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index 2d4cba6eb6..980e4df1ef 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -42,6 +42,10 @@ type repoItemDecisionMock struct { // an adoption marker on #8 may name (hivecommons/hive#15052); "" is 404. supersederState string supersederMerged bool + // merges records PUT /pulls/8/merge bodies; reviews the POST /reviews + // bodies (merge-now / queue-merge, hivecommons/hive#15078). + merges []map[string]any + reviews []map[string]any } func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { @@ -52,8 +56,10 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { w.Header().Set("Content-Type", "application/json") path := r.URL.Path switch { - case r.Method == http.MethodGet && strings.HasSuffix(path, "/collaborators/writer/permission"): + case r.Method == http.MethodGet && (strings.HasSuffix(path, "/collaborators/writer/permission") || strings.HasSuffix(path, "/collaborators/someone/permission")): _, _ = io.WriteString(w, `{"permission":"write"}`) + case r.Method == http.MethodPost && strings.Contains(path, "/statuses/"): + _, _ = io.WriteString(w, `{}`) case r.Method == http.MethodGet && strings.HasSuffix(path, "/collaborators/reader/permission"): _, _ = io.WriteString(w, `{"permission":"read"}`) case r.Method == http.MethodGet && strings.HasSuffix(path, "/issues/7"): @@ -93,7 +99,19 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { for _, label := range m.prLabels { prLabels = append(prLabels, map[string]string{"name": label}) } - _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "labels": prLabels, "user": author, "mergeable": true, "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}}) + _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "labels": prLabels, "user": author, "mergeable": true, "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}, "base": map[string]any{"ref": "main"}}) + case r.Method == http.MethodPut && strings.HasSuffix(path, "/pulls/8/merge"): + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + m.merges = append(m.merges, body) + _, _ = io.WriteString(w, `{"sha":"0ddba11","merged":true,"message":"Pull Request successfully merged"}`) + case r.Method == http.MethodGet && strings.HasSuffix(path, "/pulls/8/reviews"): + _, _ = io.WriteString(w, `[]`) + case r.Method == http.MethodPost && strings.HasSuffix(path, "/pulls/8/reviews"): + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + m.reviews = append(m.reviews, body) + _, _ = io.WriteString(w, `{"id":1,"state":"APPROVED"}`) case r.Method == http.MethodGet && strings.HasSuffix(path, "/commits/feedfacefeedfacefeedfacefeedfacefeedface/status"): switch { case m.prRedCI: @@ -434,3 +452,104 @@ func TestParseRepoItemSupersededBy(t *testing.T) { } } } + +func postRepoItemDecisionAs(t *testing.T, srv *Server, number int, user, role, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/api/repos/testorg/testrepo/items/"+strconv.Itoa(number)+"/decision", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Hive-User", user) + req.Header.Set("X-Hive-Role", role) + w := httptest.NewRecorder() + srv.mux.ServeHTTP(w, req) + return w +} + +// TestRepoItemDecisionMergeNowMergesAsMaintainer: "Approve & merge as +// maintainer" on a Ready-for-human-merge PR leaves an attributed note, then +// merges through the hive's App against the head the operator saw, audits +// it on the dashboard path and answers the shared result (merged) +// (hivecommons/hive#15078). +func TestRepoItemDecisionMergeNowMergesAsMaintainer(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/090-ready-for-human-merge"}} + srv := newRepoItemDecisionServer(t, mock) + + w := postRepoItemDecisionAs(t, srv, 8, "writer", "merger", `{"decision":"merge-now","type":"pr","comment":"release notes look right"}`) + if w.Code != http.StatusOK { + t.Fatalf("merge-now: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Status != "merged" || resp.Head != "feedfacefeedfacefeedfacefeedfacefeedface" { + t.Fatalf("response = %+v", resp) + } + if resp.Result == nil || resp.Result.Action != rowActionMerged || !strings.Contains(resp.Result.Outcome, "`main`") || !strings.Contains(resp.Result.Outcome, "attributed to you") { + t.Fatalf("result = %+v", resp.Result) + } + if len(mock.merges) != 1 || mock.merges[0]["sha"] != "feedfacefeedfacefeedfacefeedfacefeedface" { + t.Fatalf("merge must pin the head the operator saw: %v", mock.merges) + } + if len(mock.comments) != 1 || !strings.Contains(mock.comments[0], "Merged as maintainer by @writer") || !strings.Contains(mock.comments[0], "> release notes look right") { + t.Fatalf("comments = %q", mock.comments) + } + if actions := decisionAuditActions(srv); len(actions) == 0 || actions[0] != auditRepoItemDecisionMerge { + t.Fatalf("audit = %v", actions) + } +} + +// TestRepoItemDecisionQueueMergeApprovesForTheSweep: "Approve — let hive +// merge" posts the App's approval naming the operator as the queuer and +// applies the auto-merge label; the dashboard merges nothing. +func TestRepoItemDecisionQueueMergeApprovesForTheSweep(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/090-ready-for-human-merge"}} + srv := newRepoItemDecisionServer(t, mock) + + w := postRepoItemDecisionAs(t, srv, 8, "writer", "merger", `{"decision":"queue-merge","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("queue-merge: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Status != "queued-for-merge" || resp.Label != srv.deps.GHClient.AutoMergeLabel() { + t.Fatalf("response = %+v", resp) + } + if resp.Result == nil || resp.Result.Action != rowActionQueued || !strings.Contains(resp.Result.Next, "merge sweep") { + t.Fatalf("result = %+v", resp.Result) + } + if len(mock.merges) != 0 { + t.Fatalf("queue-merge must not merge: %v", mock.merges) + } + if len(mock.reviews) != 1 || mock.reviews[0]["event"] != "APPROVE" || !strings.HasPrefix(mock.reviews[0]["body"].(string), "Approved by @writer for Hive auto-merge on green CI.") { + t.Fatalf("reviews = %v", mock.reviews) + } + if !strings.Contains(mock.reviews[0]["body"].(string), "Approved from the Hive dashboard by @writer") { + t.Fatalf("approval must carry the dashboard note: %v", mock.reviews[0]["body"]) + } + if len(mock.added) != 1 || mock.added[0] != srv.deps.GHClient.AutoMergeLabel() { + t.Fatalf("labels added = %v", mock.added) + } + if actions := decisionAuditActions(srv); len(actions) == 0 || actions[0] != auditRepoItemDecisionQueue { + t.Fatalf("audit = %v", actions) + } +} + +// TestRepoItemDecisionMergeDecisionsGuard: both merge answers need the +// merger or owner role on top of write access, apply to PRs only, and +// refuse the operator's own PR. +func TestRepoItemDecisionMergeDecisionsGuard(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true} + srv := newRepoItemDecisionServer(t, mock) + for _, decision := range []string{"merge-now", "queue-merge"} { + if w := postRepoItemDecisionAs(t, srv, 8, "writer", "write", `{"decision":"`+decision+`","type":"pr"}`); w.Code != http.StatusForbidden { + t.Errorf("%s as a plain writer: code=%d body=%s", decision, w.Code, w.Body.String()) + } + if w := postRepoItemDecisionAs(t, srv, 7, "writer", "merger", `{"decision":"`+decision+`","type":"issue"}`); w.Code != http.StatusBadRequest { + t.Errorf("%s on an issue: code=%d body=%s", decision, w.Code, w.Body.String()) + } + if w := postRepoItemDecisionAs(t, srv, 8, "someone", "merger", `{"decision":"`+decision+`","type":"pr"}`); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "you opened this pull request") { + t.Errorf("%s on one's own PR: code=%d body=%s", decision, w.Code, w.Body.String()) + } + } + if len(mock.merges)+len(mock.reviews) != 0 { + t.Fatalf("guards must stop before GitHub writes: merges=%v reviews=%v", mock.merges, mock.reviews) + } +} diff --git a/src/pkg/dashboard/delegated_decision_human_merge.go b/src/pkg/dashboard/delegated_decision_human_merge.go new file mode 100644 index 0000000000..2f3be62aaa --- /dev/null +++ b/src/pkg/dashboard/delegated_decision_human_merge.go @@ -0,0 +1,107 @@ +package dashboard + +import ( + "slices" + "strconv" + "strings" + + "github.com/hivecommons/hive/pkg/delegatedecision" + stageengineprstage "github.com/hivecommons/hive/pkg/stageengine/prstage" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// "Let hive decide" on a PR at stage/090 Ready for human merge +// (hivecommons/hive#15078). +// +// The lanes already decided this one: nothing about the PR is wrong, the +// hive simply will not vouch for its author (not a collaborator, no +// trusted / merger tier, a fork from outside the organization, …). Running +// the owner-delegate policy would only record an approval the merge gate +// then ignores, and the operator would learn that thirty minutes later +// through the stalled-decision path. So the hive answers at once, in the +// same no-effect shape the SPA already renders: why it cannot merge this +// itself, and the buttons that do — Approve & merge as maintainer, Approve +// — let hive merge — plus how to trust the author next time. + +// delegatedHumanMergeRule is the rule slug on the answer; it resolves in +// the glossary to the plain words the toast head shows. +const delegatedHumanMergeRule = delegatedecision.GlossaryHumanMerge + +// delegatedHumanMergeReason picks the 090 lane reason the row showed, from +// the request's reason / caption or the gathered reasons; "" when none. +func delegatedHumanMergeReason(in delegatedecision.Input, req delegatedDecisionRequest) string { + candidates := append([]string{req.Reason, req.Caption}, in.Reasons...) + for _, c := range candidates { + if c = strings.TrimSpace(c); c != "" && stageengineprstage.HumanMergeReason(c) != "" { + return c + } + } + return "" +} + +// delegatedHumanMergeOptions are the answer's buttons: the two merge +// actions (merger / owner only), then send back (hive-authored PRs only: +// a direction has no agent to carry it on a person's PR) and close. +func delegatedHumanMergeOptions(in delegatedecision.Input, number int, mergerRole bool) []StageTrackerDecisionOption { + ref := "#" + strconv.Itoa(number) + mergeNow := decisionOption(decisionActionMergeNow, "Approve & merge as maintainer", mergerRole, decisionWhyMergerRole) + mergeNow.Consequence = "merges " + ref + " now via hive's identity, attributed to you" + queue := decisionOption(decisionActionQueueMerge, "Approve — let hive merge", mergerRole, decisionWhyMergerRole) + queue.Consequence = "records your approval; the hive's merge sweep merges " + ref + " on its next pass once CI is green and the head has soaked" + direction := decisionOption(decisionActionDirection, "Send back for a new commit", in.HiveAuthored, "The hive did not open this PR, so it cannot carry a direction to its author; leave a changes-requested review on GitHub") + closeSup := decisionOption(decisionActionCloseSuperseded, "Close as superseded", true, "") + return []StageTrackerDecisionOption{mergeNow, queue, direction, closeSup} +} + +// decisionWhyMergerRole is the plain reason a merge button is greyed. +const decisionWhyMergerRole = "merger role required" + +// delegatedHumanMergeOutcome answers "Let hive decide" on a PR wearing the +// 090 label without running the policy. ok=false for anything else. +func (s *Server) delegatedHumanMergeOutcome(repoFull string, number int, itemType, user string, mergerRole bool, in delegatedecision.Input, req delegatedDecisionRequest) (delegatedOutcome, bool) { + if in.Kind != delegatedecision.KindPR || !slices.Contains(in.Labels, stagelabels.ReadyForHumanMerge.Label()) { + return delegatedOutcome{}, false + } + reason := delegatedHumanMergeReason(in, req) + base, _ := stagelabels.HumanApprovedReason(reason) + base = strings.TrimSpace(base) + code := stageengineprstage.HumanMergeReason(reason) + if code == "" { + code = delegatedHumanMergeRule + } + why := stageTrackerUntrustedAuthorWhy(base, in.Author) + if why == "" { + why = decisionPlainReason(base) + if base == "" || why == base { + why = "the hive's merge rules leave this PR to a person" + } + } + who := "its author" + if a := strings.TrimSpace(in.Author); a != "" { + who = "author @" + a + } + _, repoName, _ := strings.Cut(repoFull, "/") + if repoName == "" { + repoName = repoFull + } + options := delegatedHumanMergeOptions(in, number, mergerRole) + d := delegatedecision.Decision{ + Verdict: delegatedecision.VerdictRecommendOnly, + Rule: delegatedHumanMergeRule, + Text: "I can't merge this: " + who + " is untrusted on " + repoName + ".", + Rationale: why, + KeepsPark: true, + } + res := RowActionResult{ + Action: rowActionNoEffect, + Target: rowActionTarget(repoFull, rowActionTargetPR, number), + Rule: delegatedHumanMergeRule, + Why: delegatedecision.GlossaryHumanMerge, + Options: options, + Outcome: "I can't merge this: " + who + " is untrusted on " + repoName + " — " + why + ".", + Next: "A maintainer merges it. Options: " + strings.Join(optionLabels(options), " · ") + ". To let the hive merge their PRs next time, promote the author to trusted under 👥 Contributors.", + } + s.audit.LogRecord(user, auditRepoItemDecisionDelegated, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", itemType, + "verdict", string(d.Verdict), "rule", d.Rule, "actions", "", "noop", "human-merge:"+code, "policy", delegatedecision.PolicyName, "decision", d.Text), "", repoFull, number) + return delegatedOutcome{Decision: &d, Notes: []string{"ready for human merge (" + code + "); nothing written"}, Result: &res}, true +} diff --git a/src/pkg/dashboard/operator_actions.go b/src/pkg/dashboard/operator_actions.go index 33cd290edb..96a3426462 100644 --- a/src/pkg/dashboard/operator_actions.go +++ b/src/pkg/dashboard/operator_actions.go @@ -39,6 +39,11 @@ const ( operatorActionRelease = "release" operatorActionAcceptTriage = "accept-triage" operatorActionMarkNeedsHuman = "mark-needs-human" + // Merge-gate answers on a 090 Ready-for-human-merge PR + // (hivecommons/hive#15078): merged by the operator through the hive's + // App, or queued for the hive's merge sweep. + operatorActionMergeNow = "merge-now" + operatorActionQueueMerge = "queue-merge" // Stored outcomes: what the endpoint answered when the action was // submitted. `pending` is a delegated decision still running; the job's @@ -269,6 +274,10 @@ func operatorActionFromBody(endpoint string, body []byte) (operatorActionRequest out.Target = strings.TrimSpace(raw.SupersededBy) case repoItemDecisionCloseWontFix: out.Action = operatorActionWontFix + case repoItemDecisionMergeNow: + out.Action = operatorActionMergeNow + case repoItemDecisionQueueMerge: + out.Action = operatorActionQueueMerge default: return out, false } diff --git a/src/pkg/dashboard/operator_actions_test.go b/src/pkg/dashboard/operator_actions_test.go index 42d31e3da6..cb6018bec4 100644 --- a/src/pkg/dashboard/operator_actions_test.go +++ b/src/pkg/dashboard/operator_actions_test.go @@ -59,6 +59,8 @@ func TestOperatorActionFromBody(t *testing.T) { {"decision", `{"decision":"direction","comment":" ship B "}`, operatorActionRequest{Action: operatorActionGiveDirection, Note: "ship B"}, true}, {"decision", `{"decision":"close-superseded","superseded_by":"#41"}`, operatorActionRequest{Action: operatorActionCloseSuperseded, Target: "#41"}, true}, {"decision", `{"decision":"close-wontfix"}`, operatorActionRequest{Action: operatorActionWontFix}, true}, + {"decision", `{"decision":"merge-now","head":"abc"}`, operatorActionRequest{Action: operatorActionMergeNow, Head: "abc"}, true}, + {"decision", `{"decision":"queue-merge"}`, operatorActionRequest{Action: operatorActionQueueMerge}, true}, {"decision", `{"decision":"bogus"}`, operatorActionRequest{}, false}, {"decide-delegated", ``, operatorActionRequest{Action: operatorActionLetHiveDecide}, true}, {"hold", `{"held":true}`, operatorActionRequest{Action: operatorActionHold}, true}, diff --git a/src/pkg/dashboard/row_action_result.go b/src/pkg/dashboard/row_action_result.go index b1380557ad..f01ad2d7ea 100644 --- a/src/pkg/dashboard/row_action_result.go +++ b/src/pkg/dashboard/row_action_result.go @@ -53,6 +53,8 @@ const ( rowActionRescanned = "rescanned" rowActionTriaged = "triage-accepted" rowActionNeedsHuman = "needs-human" + rowActionMerged = "merged" + rowActionQueued = "queued-for-merge" rowActionNoop = "noop-already-applied" // rowActionDecidedEach is an issue job that decided each nested PR on // its own; the per-PR results ride delegatedDecisionJob.Items. diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 32863dd114..aacfcf69eb 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -1301,6 +1301,48 @@ func stageTrackerHumanMergeReason(reason string) (code, word, tip string) { return stageengineprstage.HumanMergeReasonPolicy, "policy", "The merge lane will not merge this unattended (lane reason `" + strings.TrimSpace(base) + "`); a maintainer merges by hand" } +// Where an operator makes an author trusted, in the words the ⚙ and 👥 +// sections use, for the untrusted-author tooltip. +const ( + stageTrackerTrustFixTier = "give them the trusted or merger tier under 👥 Contributors (auto_merge.contributor_lane.require_tiers)" + stageTrackerTrustFixRole = "add them under Authorized users on ⚙ Security with the merger role (dashboard.authorized_users, auto_merge.trusted_authors.require_role)" + stageTrackerTrustFixCollab = "add them as a collaborator of the repository on GitHub" +) + +// stageTrackerUntrustedAuthorWhy says, in plain words, why the hive will +// not vouch for the PR's author under a trust-family 090 reason and what +// would make them trusted — the config key and where in the dashboard it +// is set (hivecommons/hive#15078). "" for any other reason. +func stageTrackerUntrustedAuthorWhy(base, author string) string { + who := "the author" + if a := strings.TrimSpace(author); a != "" { + who = "@" + a + } + switch strings.ToLower(strings.TrimSpace(base)) { + case stageengineprstage.ContributorLaneReasonAuthorAssociation: + return who + " is not a collaborator of this repository on GitHub (no owner, member or collaborator association) and holds no trusted or merger tier in this hive's contributor registry, so the hive will not merge their PR unattended. To trust them: " + stageTrackerTrustFixTier + ", or " + stageTrackerTrustFixCollab + case "untrusted-author-role": + return who + " does not hold the merger role under this hive's Authorized users, so the trusted-authors merge lane does not vouch for them. To trust them: " + stageTrackerTrustFixRole + case "author-permission-missing": + return "GitHub reports no push, maintain or admin permission for " + who + " on this repository, which the trusted-authors lane requires (auto_merge.trusted_authors.require_github_permission). To trust them: grant them write access on GitHub, or turn that check off" + case "fork-non-member": + return "this PR comes from a fork and " + who + " is not a member of the organization, so the hive will not merge it unattended. To trust them: " + stageTrackerTrustFixCollab + case "untrusted-merger": + return "the person who queued this PR for auto-merge does not hold the merger role under this hive's Authorized users (dashboard.authorized_users). A merger or owner queues or merges it" + case stageengineprstage.ContributorLaneReasonClaimTier: + return who + "'s contributor tier is below the tiers the contributor lane merges for (auto_merge.contributor_lane.require_tiers, default trusted and merger). To trust them: " + stageTrackerTrustFixTier + case stageengineprstage.ContributorLaneReasonNoClaim, stageengineprstage.ContributorLaneReasonNoLinkedIssue: + return "no hive claim links this PR to an issue the hive handed out, and " + who + " holds no trusted or merger tier in the contributor registry, so no lane vouches for it. To trust them: " + stageTrackerTrustFixTier + case stageengineprstage.ContributorLaneReasonClaimUnverified: + return who + "'s GitHub login is not verified against their contributor profile, so the contributor lane cannot vouch for them. They verify it on the hub (Contributors → Verify GitHub), or " + stageTrackerTrustFixTier + case stageengineprstage.ContributorLaneReasonClaimAuthor: + return "the hive's claim on the linked issue names a different contributor than " + who + ", so the contributor lane does not vouch for this PR. A maintainer merges, or " + stageTrackerTrustFixTier + case stageengineprstage.ContributorLaneReasonClaimOtherHive: + return "the linked issue is claimed by another hive, so this hive's contributor lane does not vouch for " + who + ". The owning hive merges it, or a maintainer merges here" + } + return "" +} + // trackerSoakRemainingRE pulls the time left out of the lane's // `contributor-lane:soaking(remaining=12m0s)` reason. var trackerSoakRemainingRE = regexp.MustCompile(`remaining=([0-9hms.]+)`) @@ -1704,6 +1746,13 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.ManualMerge = stageTrackerManualMergeReason(base) if stage == stagelabels.ReadyForHumanMerge { it.HumanMergeReason, _, it.HumanMergeReasonText = stageTrackerHumanMergeReason(it.Reason) + // An untrusted author gets the specific why-and-how-to-fix + // instead of the generic trust sentence (hivecommons/hive#15078). + if it.HumanMergeReason == stageengineprstage.HumanMergeReasonUntrustedAuthor { + if why := stageTrackerUntrustedAuthorWhy(base, it.Author); why != "" { + it.HumanMergeReasonText = "Untrusted author: " + why + ". Until then a maintainer merges — Approve & merge as maintainer, or Approve — let hive merge, from the row's ⋯ menu." + } + } } if slices.Contains(it.Modifiers, modUnauthorized) || slices.Contains(it.DeferredModifiers, modUnauthorized) { it.UnauthorizedStep, it.Unauthorized = stageTrackerUnauthorized(it.Reason) diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index f2ad92bc7c..7157c37fcb 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -58,6 +58,11 @@ type StageTrackerDecisionOption struct { Label string `json:"label"` Enabled bool `json:"enabled"` ReasonIfDisabled string `json:"reason_if_disabled,omitempty"` + // Consequence says, in one clause, what happens when the action is + // taken ("merges #317 into main now via hive's identity, attributed to + // you"); the ⋯ menu and the popover print it under the label + // (hivecommons/hive#15078). + Consequence string `json:"consequence,omitempty"` } // Action ids shared with the SPA's row context menu @@ -68,10 +73,13 @@ const ( decisionActionDirection = "decide:direction" decisionActionCloseSuperseded = "decide:close-superseded" decisionActionCloseWontfix = "decide:close-wontfix" + decisionActionMergeNow = "decide:merge-now" + decisionActionQueueMerge = "decide:queue-merge" decisionActionAcceptTriage = "accept-triage" decisionActionHold = "hold" decisionActionRelease = "release" decisionActionNeedsHuman = "needs-human" + decisionActionRetry = "retry" ) // Who asked, in the plain words the popover prints (owner, 2026-10-28: @@ -141,6 +149,8 @@ func stageTrackerDecisionNeededAt(it StageTrackerItem, verdict *review.Aggregate switch { case it.Kind == "pr" && (it.Stage == stagelabels.NeedsDecision.Number() || slices.Contains(it.Modifiers, modNeedsDecision)): return decisionForPR(it, verdict, sentinelLabel, held) + case it.Kind == "pr" && it.Stage == stagelabels.ReadyForHumanMerge.Number(): + return decisionForHumanMerge(it, held) case it.Kind == "issue" && it.Mirrored: // The issue rides its covering PR; the PR's own row (nested under // the issue) carries the decision. @@ -151,12 +161,177 @@ func stageTrackerDecisionNeededAt(it StageTrackerItem, verdict *review.Aggregate return decisionForTriage(it, held) case slices.Contains(it.Modifiers, modNeedsHuman): return decisionForNeedsHuman(it, held) + case slices.Contains(it.Modifiers, modUnauthorized): + return decisionForUnauthorized(it, held) case it.Kind == "pr" && it.Adoption != nil && it.Adoption.Action == decisionActionAdopt: return decisionForAdoption(it, held, now) + case it.Kind == "pr" && it.AuthorKind == authorKindHuman && slices.Contains(stageTrackerNeedsHumanAuthorStages, it.Stage): + return decisionForWaitingOnAuthor(it, held) + case stageTrackerNeedsHuman(it) || (held && stageTrackerNeedsHuman(stageTrackerWithoutHold(it))): + // Flagged for a person by a stage/kind pairing none of the cases + // above knows (an issue wearing a PR stage label by hand, a PR at + // a triage stage): still never a pill without an action. + return decisionForParked(it, held) } return nil } +// stageTrackerWithoutHold is the item as it reads with the hold pill off, +// so a held row still derives the decision its underlying state asks for. +func stageTrackerWithoutHold(it StageTrackerItem) StageTrackerItem { + it.Modifiers = slices.DeleteFunc(slices.Clone(it.Modifiers), func(m string) bool { return m == modHold }) + return it +} + +// decisionDelegateOption is "Let hive decide" for a state the hive would +// not otherwise decide: the delegate answers in plain words why it won't +// act itself and lists the person's options (hivecommons/hive#15078). +func decisionDelegateOption(held bool, consequence string) StageTrackerDecisionOption { + o := decisionOption(decisionActionDelegate, "Let hive decide", !held, decisionWhyHeld) + o.Consequence = consequence + return o +} + +// decisionForParked is the fallback for any needs-human state without a +// dedicated decision: say what the row is parked on and offer the generic +// moves — look again, hold, flag for a person (hivecommons/hive#15078). +func decisionForParked(it StageTrackerItem, held bool) *StageTrackerDecision { + what := "issue" + if it.Kind == "pr" { + what = "PR" + } + stage := strings.TrimSpace(it.StageLabel) + if stage == "" { + stage = "stage " + strconv.Itoa(it.Stage) + } + d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByLane, BlockerReason: strings.TrimSpace(it.Reason)} + d.Question = "This " + what + " sits at " + stage + ", a stage the hive leaves to a person" + if clause := decisionPlainReason(strings.TrimSpace(it.Reason)); strings.TrimSpace(it.Reason) != "" { + d.Question += " (" + clause + ")" + } + d.Question += ". Act on it on GitHub, then re-evaluate so the hive picks it up." + d.Blocker = "The hive makes no move here until a person does." + if held { + d.Blocker += " " + decisionHeldBlocker(it.Hold) + } + retry := decisionOption(decisionActionRetry, "Re-evaluate now", true, "") + retry.Consequence = "re-reads GitHub and re-derives the stage" + d.Options = []StageTrackerDecisionOption{retry, decisionDelegateOption(held, "the hive says in plain words what it can and cannot do here"), decisionHoldOption(held)} + if !slices.Contains(it.Modifiers, modNeedsHuman) { + d.Options = append(d.Options, decisionOption(decisionActionNeedsHuman, "Mark needs-human", true, "")) + } + return d +} + +// decisionForHumanMerge: a PR parked at 090 Ready for human merge — the +// hive's lanes will not merge it unattended (untrusted author, workflow +// files, manual-merge path, branch protection, …), so the person is asked +// to merge. The lead options do exactly that (hivecommons/hive#15078): +// "Approve & merge as maintainer" merges now through the hive's GitHub +// App, attributed to the operator; "Approve — let hive merge" queues the +// PR for the hive's merge sweep, which merges it on its next pass once CI +// is green and the head has soaked. Both need the merger or owner role; +// the SPA greys them out for anyone else. +func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision { + base, approver := stagelabels.HumanApprovedReason(it.Reason) + base = strings.TrimSpace(base) + _, word, _ := stageTrackerHumanMergeReason(it.Reason) + d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByLane, BlockerReason: base} + if word == "" { + word = "policy" + } + ref := "#" + strconv.Itoa(it.Number) + into := strings.TrimSpace(it.BaseRef) + if into == "" { + into = "its base branch" + } + why := stageTrackerUntrustedAuthorWhy(base, it.Author) + if why == "" { + why = decisionPlainReason(base) + if strings.TrimSpace(base) == "" { + why = "the hive's merge rules leave this one to a person" + } + } + d.Question = "This PR is ready to merge, but the hive will not merge it by itself (" + word + "): " + why + ". Merge it now, let the hive merge it, or send it back?" + d.Blocker = "The hive never merges this unattended. A maintainer merges: here, or on GitHub." + if approver != "" { + d.Blocker = "Approved by @" + approver + "; the hive still never merges this unattended. A maintainer merges: here, or on GitHub." + } + if held { + d.Blocker += " " + decisionHeldBlocker(it.Hold) + } + mergeNow := decisionOption(decisionActionMergeNow, "Approve & merge as maintainer", !held, "Release the hold first") + mergeNow.Consequence = "merges " + ref + " into " + into + " now via hive's identity, attributed to you" + queue := decisionOption(decisionActionQueueMerge, "Approve — let hive merge", !held, "Release the hold first") + queue.Consequence = "records your approval; the hive's merge sweep merges " + ref + " on its next pass once CI is green and the head has soaked" + direction := decisionOption(decisionActionDirection, "Give direction", it.AuthorKind != authorKindHuman, "The hive did not open this PR, so it cannot carry a direction to its author; leave a changes-requested review on GitHub") + direction.Consequence = "asks the author agent for a new head instead of merging" + closeSup := decisionOption(decisionActionCloseSuperseded, "Close as superseded", true, "") + closeSup.Consequence = "closes " + ref + " unmerged, naming the PR that replaces it" + closeWontfix := decisionOption(decisionActionCloseWontfix, "Close as won't fix", true, "") + closeWontfix.Consequence = "closes " + ref + " unmerged" + delegate := decisionDelegateOption(held, "the hive answers at once why it will not merge this itself and lists these options; it never merges it") + d.Options = []StageTrackerDecisionOption{mergeNow, queue, delegate, direction, closeSup, closeWontfix, decisionHoldOption(held)} + return d +} + +// decisionForUnauthorized: a row wearing hive:unauthorized outside 085 — +// the hive's GitHub App lacks the permission for its next step, so a +// person takes that step on GitHub (approve the held workflow runs, merge +// the workflow-file PR, …) and then asks the hive to look again. +func decisionForUnauthorized(it StageTrackerItem, held bool) *StageTrackerDecision { + d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByApp, BlockerReason: strings.TrimSpace(it.Reason)} + step := strings.TrimSpace(it.UnauthorizedStep) + if step == "" { + _, tip := stageTrackerUnauthorized(it.Reason) + d.Question = "The hive's GitHub App lacks a permission for the next step. " + tip + } else { + d.Question = "The hive's GitHub App may not " + unauthorizedStepWords(step) + " here. Do that step on GitHub, then re-evaluate so the hive picks it up." + } + d.Blocker = strings.TrimSpace(it.Unauthorized) + if d.Blocker == "" { + d.Blocker = decisionWhyNoPermission + "." + } + if held { + d.Blocker += " " + decisionHeldBlocker(it.Hold) + } + retry := decisionOption(decisionActionRetry, "Re-evaluate now", true, "") + retry.Consequence = "re-reads GitHub; the hive resumes and clears the label once the step is done" + d.Options = []StageTrackerDecisionOption{retry, decisionDelegateOption(held, "the hive says in plain words which step it may not take and what would let it"), decisionHoldOption(held)} + if !slices.Contains(it.Modifiers, modNeedsHuman) { + d.Options = append(d.Options, decisionOption(decisionActionNeedsHuman, "Mark needs-human", true, "")) + } + return d +} + +// decisionForWaitingOnAuthor: a human-authored PR at 071 Needs author / +// 072 Returned to contributor — the hive waits for its author to push. +// The hive never adopts a human's PR, so the person's choices are to wait, +// hold, or close it (hivecommons/hive#15078). +func decisionForWaitingOnAuthor(it StageTrackerItem, held bool) *StageTrackerDecision { + who := "its author" + if a := strings.TrimSpace(it.Author); a != "" { + who = "@" + a + } + ref := "#" + strconv.Itoa(it.Number) + d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByLane, BlockerReason: strings.TrimSpace(it.Reason)} + what := "a new commit" + if clause := decisionPlainReason(strings.TrimSpace(it.Reason)); strings.TrimSpace(it.Reason) != "" && clause != "the hive parked it" { + what = "a new commit (" + clause + ")" + } + d.Question = "This PR waits on " + who + " for " + what + ". The hive never rewrites a person's PR. Wait for them, or close it?" + d.Blocker = "Nothing for the hive to do until " + who + " pushes." + if held { + d.Blocker += " " + decisionHeldBlocker(it.Hold) + } + closeSup := decisionOption(decisionActionCloseSuperseded, "Close as superseded", true, "") + closeSup.Consequence = "closes " + ref + " unmerged, naming the PR that replaces it" + closeWontfix := decisionOption(decisionActionCloseWontfix, "Close as won't fix", true, "") + closeWontfix.Consequence = "closes " + ref + " unmerged" + d.Options = []StageTrackerDecisionOption{decisionDelegateOption(held, "the hive weighs waiting against closing and says so in plain words; it never rewrites the PR"), closeSup, closeWontfix, decisionHoldOption(held)} + return d +} + // decisionForAdoption: a nudged 072 PR whose author maintains the // repository, held for an owner under // governor.labels.stage.adoption.maintainer_policy: ask @@ -465,6 +640,7 @@ func decisionForTriage(it StageTrackerItem, held bool) *StageTrackerDecision { } d.Options = []StageTrackerDecisionOption{ decisionOption(decisionActionAcceptTriage, "Accept triage", true, ""), + decisionDelegateOption(held, "the hive triages it as the owner's delegate: accepts it, or says in plain words why not"), decisionHoldOption(held), } if !slices.Contains(it.Modifiers, modNeedsHuman) { @@ -479,12 +655,21 @@ func decisionForNeedsHuman(it StageTrackerItem, held bool) *StageTrackerDecision if it.Kind == "pr" { what = "PR" } - d.Question = "This " + what + " is marked needs-human: automated fixes ran out, or a person flagged it. Review it on GitHub and remove the label when the hive may continue." + d.Question = "This " + what + " is marked needs-human: automated fixes ran out, or a person flagged it. Review it, then resolve it here (lifts the label) or remove the label on GitHub when the hive may continue." d.Blocker = "The hive does nothing with a needs-human item until a person removes the label." if held { d.Blocker += " " + decisionHeldBlocker(it.Hold) } - d.Options = []StageTrackerDecisionOption{decisionHoldOption(held)} + // The matching action for the ask (hivecommons/hive#15078): Approve + // lifts needs-human — on a PR it also posts /lgtm + /approve as the + // operator, on an issue it records /hive approve and un-parks it. + resolve := decisionOption(decisionActionApprove, "Resolve — lift needs-human", !held, "Release the hold first") + if it.Kind == "pr" { + resolve.Consequence = "lifts needs-human and posts /lgtm + /approve as you; the merge gate takes it from there" + } else { + resolve.Consequence = "lifts needs-human and records /hive approve as you; the hive carries on" + } + d.Options = []StageTrackerDecisionOption{resolve, decisionDelegateOption(held, "the hive reviews it as the owner's delegate and either lifts needs-human or says in plain words why it kept it"), decisionHoldOption(held)} return d } diff --git a/src/pkg/dashboard/stage_tracker_decision_popover_test.go b/src/pkg/dashboard/stage_tracker_decision_popover_test.go index c6afe0f660..c256474da9 100644 --- a/src/pkg/dashboard/stage_tracker_decision_popover_test.go +++ b/src/pkg/dashboard/stage_tracker_decision_popover_test.go @@ -19,7 +19,6 @@ func stageTrackerDecisionPopPreamble(t *testing.T, html string) string { jsConstLine(t, html, "STAGE_TRACKER_DECISION_LEAVE_MS"), "var _stageTrackerDecisionPop = null;", jsFunc(t, html, "agentNowAgo"), - jsFunc(t, html, "stageTrackerDecisionOf"), jsFunc(t, html, "stageTrackerDecisionTriggerHtml"), jsFunc(t, html, "stageTrackerDecisionOptions"), jsFunc(t, html, "stageTrackerDecisionPopHtml"), diff --git a/src/pkg/dashboard/stage_tracker_decision_test.go b/src/pkg/dashboard/stage_tracker_decision_test.go index e36f4bf845..be7b171eee 100644 --- a/src/pkg/dashboard/stage_tracker_decision_test.go +++ b/src/pkg/dashboard/stage_tracker_decision_test.go @@ -1,6 +1,8 @@ package dashboard import ( + "slices" + "strconv" "strings" "testing" "time" @@ -210,7 +212,7 @@ func TestStageTrackerDecisionNeeded(t *testing.T) { if !strings.Contains(d.Question, "This PR is marked needs-human") { t.Fatalf("question = %q", d.Question) } - if len(d.Options) != 1 || d.Options[0].Action != decisionActionHold { + if len(d.Options) != 3 || d.Options[0].Action != decisionActionApprove || !d.Options[0].Enabled || d.Options[0].Consequence == "" || d.Options[1].Action != decisionActionDelegate || d.Options[2].Action != decisionActionHold { t.Fatalf("options = %+v", d.Options) } }) @@ -247,3 +249,144 @@ func TestStageTrackerVerdictLookup(t *testing.T) { t.Fatal("nil artifact matched") } } + +// TestStageTrackerDecisionForHumanMerge: a PR at 090 Ready for human merge +// asks the person to merge, so the decision leads with the two ways to do +// that — merge now as maintainer, or approve and let the hive's sweep merge +// — each with its consequence, then direction / close / hold +// (hivecommons/hive#15078: hotshot#317 had no such action). +func TestStageTrackerDecisionForHumanMerge(t *testing.T) { + since := time.Date(2026, 10, 28, 15, 0, 0, 0, time.UTC) + it := StageTrackerItem{Repo: "hivecommons/hotshot", Number: 317, Kind: "pr", Author: "Karibhou", AuthorKind: authorKindHuman, BaseRef: "main", + Stage: stagelabels.ReadyForHumanMerge.Number(), StageSince: &since, Reason: stageengineprstage.ContributorLaneReasonAuthorAssociation} + d := stageTrackerDecisionNeeded(it, nil, "") + if d == nil || d.AskedBy != decisionAskedByLane { + t.Fatalf("decision = %+v", d) + } + if got := []string{d.Options[0].Action, d.Options[1].Action}; got[0] != decisionActionMergeNow || got[1] != decisionActionQueueMerge { + t.Fatalf("lead options = %v, want merge-now then queue-merge", got) + } + merge := d.Options[0] + if !merge.Enabled || merge.Label != "Approve & merge as maintainer" || merge.Consequence != "merges #317 into main now via hive's identity, attributed to you" { + t.Fatalf("merge-now = %+v", merge) + } + queue := d.Options[1] + if !queue.Enabled || queue.Label != "Approve — let hive merge" || !strings.Contains(queue.Consequence, "merge sweep merges #317") || !strings.Contains(queue.Consequence, "soaked") { + t.Fatalf("queue-merge = %+v", queue) + } + for _, want := range []string{"untrusted author", "@Karibhou is not a collaborator", "👥 Contributors", "auto_merge.contributor_lane.require_tiers"} { + if !strings.Contains(d.Question, want) { + t.Errorf("question lacks %q: %q", want, d.Question) + } + } + dir := decisionOptionByAction(t, d, decisionActionDirection) + if dir.Enabled || !strings.Contains(dir.ReasonIfDisabled, "did not open this PR") { + t.Fatalf("direction on a human PR = %+v", dir) + } + for _, want := range []string{decisionActionCloseSuperseded, decisionActionCloseWontfix, decisionActionHold} { + if o := decisionOptionByAction(t, d, want); !o.Enabled { + t.Errorf("%s should be enabled: %+v", want, o) + } + } + + t.Run("hive-authored PR may take direction", func(t *testing.T) { + agent := it + agent.Author, agent.AuthorKind, agent.Reason = "hive[bot]", "hive", "contributor-lane:workflow-files" + d := stageTrackerDecisionNeeded(agent, nil, "") + if d == nil || !decisionOptionByAction(t, d, decisionActionDirection).Enabled { + t.Fatalf("decision = %+v", d) + } + if d.Options[0].Action != decisionActionMergeNow { + t.Fatalf("merge-now must lead: %+v", d.Options) + } + }) + + t.Run("held row disables the merges with the reason", func(t *testing.T) { + held := it + held.Modifiers = []string{modHold} + d := stageTrackerDecisionNeeded(held, nil, "") + for _, a := range []string{decisionActionMergeNow, decisionActionQueueMerge} { + if o := decisionOptionByAction(t, d, a); o.Enabled || o.ReasonIfDisabled != "Release the hold first" { + t.Errorf("%s on a held row = %+v", a, o) + } + } + decisionOptionByAction(t, d, decisionActionRelease) + }) +} + +// TestStageTrackerNeedsHumanStatesCarryAnAction: every state +// stageTrackerNeedsHuman flags — the stages, the author stages on a human +// PR and the modifiers — yields a decision_needed whose options are +// non-empty and hold at least one enabled action, or a disabled one whose +// reason_if_disabled is plain words. A pill that asks for a person with no +// matching action is the bug this guards (hivecommons/hive#15078). +func TestStageTrackerNeedsHumanStatesCarryAnAction(t *testing.T) { + since := time.Date(2026, 10, 28, 15, 0, 0, 0, time.UTC) + type tc struct { + name string + it StageTrackerItem + } + var cases []tc + for _, stage := range stageTrackerNeedsHumanStages { + for _, kind := range []string{"issue", "pr"} { + it := StageTrackerItem{Repo: "o/r", Number: 1, Kind: kind, Stage: stage, StageSince: &since} + if kind == "pr" { + it.Author, it.AuthorKind, it.BaseRef = "someone", authorKindHuman, "main" + if stage == stagelabels.ReadyForHumanMerge.Number() { + it.Reason = stageengineprstage.ContributorLaneReasonAuthorAssociation + } + } + cases = append(cases, tc{"stage " + strconv.Itoa(stage) + " " + kind, it}) + } + } + for _, stage := range stageTrackerNeedsHumanAuthorStages { + cases = append(cases, tc{"author stage " + strconv.Itoa(stage) + " human pr", StageTrackerItem{Repo: "o/r", Number: 2, Kind: "pr", Author: "someone", AuthorKind: authorKindHuman, Stage: stage, StageSince: &since, Reason: "changes-requested"}}) + } + for _, mod := range stageTrackerNeedsHumanMods { + for _, kind := range []string{"issue", "pr"} { + it := StageTrackerItem{Repo: "o/r", Number: 3, Kind: kind, Stage: 60, StageSince: &since, Modifiers: []string{mod}} + if mod == modUnauthorized { + it.Reason = "unauthorized:approve-workflow-runs" + } + cases = append(cases, tc{"modifier " + mod + " " + kind, it}) + } + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if !stageTrackerNeedsHuman(c.it) { + t.Fatalf("fixture is not flagged needs-human: %+v", c.it) + } + d := stageTrackerDecisionNeeded(c.it, nil, "hive:sentinel-alert") + if d == nil { + t.Fatalf("no decision_needed for a needs-human row: %+v", c.it) + } + if strings.TrimSpace(d.Question) == "" { + t.Fatal("decision has no question") + } + if len(d.Options) == 0 { + t.Fatalf("decision_needed.options is empty: %+v", d) + } + enabled := false + for _, o := range d.Options { + if o.Action == "" || o.Label == "" { + t.Errorf("option without action/label: %+v", o) + } + if o.Enabled { + enabled = true + continue + } + if r := strings.TrimSpace(o.ReasonIfDisabled); r == "" || strings.Contains(r, ":") && !strings.Contains(r, " ") { + t.Errorf("disabled option %q lacks a plain-words reason: %+v", o.Action, o) + } + } + if !enabled { + t.Errorf("no enabled action among %+v", d.Options) + } + // "Let hive decide" is on every needs-human state: where the + // hive cannot act it answers in plain words why, with options. + if !slices.ContainsFunc(d.Options, func(o StageTrackerDecisionOption) bool { return o.Action == decisionActionDelegate }) { + t.Errorf("no Let hive decide among %+v", d.Options) + } + }) + } +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 264c0f9bcb..389dc9a1a9 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -31,6 +31,8 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsConstLine(t, html, "STAGE_TRACKER_DELEGATE_POLL_MS"), jsConstLine(t, html, "STAGE_TRACKER_DELEGATE_POLL_MAX"), jsConstLine(t, html, "STAGE_TRACKER_DELEGATE_ALL_MIN"), + jsConstLine(t, html, "STAGE_TRACKER_MERGE_ACTIONS"), + jsConstLine(t, html, "STAGE_TRACKER_GENERIC_ACTIONS"), jsConstLine(t, html, "STAGE_TRACKER_TERMINAL"), "var _stageTrackerSel = new Set(); var _stageTrackerSelAnchor = ''; var _stageTrackerMenu = null; var _stageTracker = null; var _statusSeqFloor = 0; var _stageTrackerEtag = 'e'; var _stageTrackerSig = 's';", jsFunc(t, html, "esc"), @@ -58,6 +60,9 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerSupersederValid"), jsFunc(t, html, "stageTrackerTriageNeeded"), jsFunc(t, html, "stageTrackerTriageAccepted"), + jsFunc(t, html, "stageTrackerDecisionOf"), + jsFunc(t, html, "stageTrackerActionAllowed"), + jsFunc(t, html, "stageTrackerLeadActions"), jsFunc(t, html, "stageTrackerRowActions"), jsFunc(t, html, "stageTrackerFlatActions"), jsFunc(t, html, "stageTrackerSelectionActions"), @@ -970,3 +975,149 @@ assert.ok(!acting('o/r/issue#7'), 'a no-op or an error clears at once'); })().catch(e => { console.error(e); process.exit(1); }); `) } + +// TestStageTrackerRowActionsLeadWithDecisionOptions: a row the hive parked +// for a person carries the matching actions at the top of its ⋯ menu, each +// with the server's consequence line, on the issue row (one nested asking +// PR) and on the PR sub-row alike (hivecommons/hive#15078: hotshot#317 at +// 090 "Ready for human merge · untrusted author" offered only Hold / +// Re-evaluate / Mark needs-human / Open / Copy). The merge actions need the +// merger role; a server-disabled option keeps its plain-words reason; the +// options the Decide… submenu already offers are not repeated. +func TestStageTrackerRowActionsLeadWithDecisionOptions(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+` +const ids = as => as.map(a => a.id); +const merger = { user: true, canHold: true, canHuman: true }; +const writer = { user: true, canHold: true, canHuman: false }; +const decision090 = { question: 'This PR is ready to merge, but the hive will not merge it by itself (untrusted author): @Karibhou is not a collaborator…', blocker: 'The hive never merges this unattended.', asked_by: 'the merge lane', since: '2026-10-28T12:00:00Z', + options: [ + { action: 'decide:merge-now', label: 'Approve & merge as maintainer', enabled: true, consequence: 'merges #317 into main now via hive\'s identity, attributed to you' }, + { action: 'decide:queue-merge', label: 'Approve — let hive merge', enabled: true, consequence: 'records your approval; the hive\'s merge sweep merges #317 on its next pass once CI is green and the head has soaked' }, + { action: 'decide:delegate', label: 'Let hive decide', enabled: true, consequence: 'the hive answers at once why it will not merge this itself and lists these options; it never merges it' }, + { action: 'decide:direction', label: 'Give direction', enabled: false, reason_if_disabled: 'The hive did not open this PR, so it cannot carry a direction to its author; leave a changes-requested review on GitHub' }, + { action: 'decide:close-superseded', label: 'Close as superseded', enabled: true, consequence: 'closes #317 unmerged, naming the PR that replaces it' }, + { action: 'decide:close-wontfix', label: "Close as won't fix", enabled: true, consequence: 'closes #317 unmerged' }, + { action: 'hold', label: 'Hold', enabled: true }, + ] }; +const pr317 = { repo: 'hivecommons/hotshot', kind: 'pr', number: 317, title: 'docs: prepare v0.2.0 release notes', url: 'https://github.com/hivecommons/hotshot/pull/317', author: 'Karibhou', author_kind: 'human', base_ref: 'main', + stage: 90, modifiers: [], human_merge_reason: 'untrusted-author', decision_needed: decision090 }; +const issue316 = { repo: 'hivecommons/hotshot', kind: 'issue', number: 316, title: 'Release v0.2.0', url: 'https://github.com/hivecommons/hotshot/issues/316', stage: 90, mirrored: true, modifiers: [], + linked_prs: [{ number: 317, title: pr317.title, url: pr317.url, author: 'Karibhou', author_kind: 'human', base_ref: 'main', stage: 90, modifiers: [], human_merge_reason: 'untrusted-author', decision_needed: decision090 }] }; + +// The PR sub-row: the two merge answers lead, then Decide… with the rest, +// then the generic items. +let as = stageTrackerRowActions(pr317, merger); +assert.deepStrictEqual(ids(as), ['decide:merge-now', 'decide:queue-merge', 'decide', 'hold', 'retry', 'needs-human', 'open', 'copy']); +assert.strictEqual(as[0].label, 'Approve & merge as maintainer'); +assert.strictEqual(as[0].hint, 'merges #317 into main now via hive\'s identity, attributed to you', 'the consequence rides as the hint'); +assert.ok(as[0].enabled && as[1].enabled, 'a merger may merge or queue'); +assert.ok(as[0].lead && as[1].lead); +assert.strictEqual(as[2].sep, true, 'the Decide… group is separated from the lead answers'); +assert.deepStrictEqual(ids(as[2].submenu), ['decide:delegate', 'decide:approve', 'decide:close-superseded', 'decide:close-wontfix', 'decide:direction'], 'options the submenu already offers are not repeated at the top'); +// The menu markup lists the lead answers above everything else, with the +// consequence under the label. +const menu = stageTrackerMenuHtml(as, 'hivecommons/hotshot#317'); +const at = s => menu.indexOf(s); +assert.ok(at('data-ham-act="decide:merge-now"') > 0 && at('data-ham-act="decide:merge-now"') < at('data-ham-act="decide:queue-merge"')); +assert.ok(at('data-ham-act="decide:queue-merge"') < at('data-ham-act="decide"'), 'merge answers above Decide…'); +assert.ok(at('data-ham-act="decide"') < at('data-ham-act="hold"') && at('data-ham-act="hold"') < at('data-ham-act="open"'), 'generic items last'); +assert.ok(menu.includes('merges #317 into main now via hive's identity, attributed to you') || menu.includes('merges #317 into main now via hive\'s identity, attributed to you'), 'consequence line rendered: ' + menu); + +// A writer without the merger role sees the merge answers, greyed with the +// role reason — never silently missing. +as = stageTrackerRowActions(pr317, writer); +assert.deepStrictEqual(ids(as).slice(0, 2), ['decide:merge-now', 'decide:queue-merge']); +assert.strictEqual(as[0].enabled, false); assert.strictEqual(as[0].why, STAGE_TRACKER_WHY_ROLE); +assert.strictEqual(as[1].enabled, false); assert.strictEqual(as[1].why, STAGE_TRACKER_WHY_ROLE); + +// The issue row over its one asking PR: the same lead answers, acting on +// PR #317 (runRowAction resolves the decision target to the PR). +as = stageTrackerRowActions(issue316, merger); +assert.deepStrictEqual(ids(as), ['decide:merge-now', 'decide:queue-merge', 'decide', 'hold', 'retry', 'needs-human', 'open', 'copy']); +assert.strictEqual(as[0].target.number, 317); assert.strictEqual(as[0].target.kind, 'pr'); +assert.strictEqual(as[2].label, 'Decide PR #317…'); +assert.strictEqual(stageTrackerDecisionTarget(issue316).number, 317, 'a human-merge reason parks the PR for the issue row'); +const req = stageTrackerActionRequest(stageTrackerDecisionTarget(issue316), 'decide:merge-now', {}); +assert.strictEqual(req.url, '/api/repos/hivecommons/hotshot/items/317/decision'); +assert.deepStrictEqual(req.body, { decision: 'merge-now', comment: '', type: 'pr' }); +assert.deepStrictEqual(stageTrackerActionRequest(pr317, 'decide:queue-merge', {}).body, { decision: 'queue-merge', comment: '', type: 'pr' }); +assert.strictEqual(STAGE_TRACKER_ACTING_CAPTIONS['decide:merge-now'], 'Merging…'); +assert.strictEqual(STAGE_TRACKER_ACTION_WORDS.merged, 'merged'); +assert.strictEqual(STAGE_TRACKER_ACTION_WORDS['queued-for-merge'], 'queued for merge'); + +// A human-authored PR waiting on its author (072): no Decide… submenu, so +// the server's close answers lead, with their consequences. +const waiting = { repo: 'o/r', kind: 'pr', number: 9, url: 'u', author: 'someone', author_kind: 'human', stage: 72, modifiers: [], + decision_needed: { question: 'This PR waits on @someone for a new commit.', options: [ + { action: 'decide:close-superseded', label: 'Close as superseded', enabled: true, consequence: 'closes #9 unmerged, naming the PR that replaces it' }, + { action: 'decide:close-wontfix', label: "Close as won't fix", enabled: true, consequence: 'closes #9 unmerged' }, + { action: 'hold', label: 'Hold', enabled: true } ] } }; +as = stageTrackerRowActions(waiting, writer); +assert.deepStrictEqual(ids(as), ['decide:close-superseded', 'decide:close-wontfix', 'hold', 'retry', 'needs-human', 'open', 'copy']); +assert.ok(as[0].danger && as[1].danger); +assert.strictEqual(as[0].hint, 'closes #9 unmerged, naming the PR that replaces it'); + +// A server-disabled lead keeps the server's plain-words reason. +const refused = { ...pr317, decision_needed: { ...decision090, options: [{ action: 'decide:merge-now', label: 'Approve & merge as maintainer', enabled: false, reason_if_disabled: 'Release the hold first' }] } }; +as = stageTrackerRowActions(refused, merger); +assert.strictEqual(as[0].id, 'decide:merge-now'); assert.strictEqual(as[0].enabled, false); assert.strictEqual(as[0].why, 'Release the hold first'); + +// Generic options the server names (hold / needs-human / retry) are never +// doubled; a 085 PR's menu is unchanged. +const pr85 = { repo: 'o/r', kind: 'pr', number: 4, url: 'u', stage: 85, modifiers: ['needs-decision'], + decision_needed: { question: 'q', options: [{ action: 'decide:delegate', label: 'Let hive decide', enabled: true }, { action: 'decide:approve', label: 'Approve', enabled: true }, { action: 'hold', label: 'Hold', enabled: true }, { action: 'needs-human', label: 'Mark needs-human', enabled: true }] } }; +assert.deepStrictEqual(ids(stageTrackerRowActions(pr85, merger)), ['decide', 'hold', 'retry', 'needs-human', 'open', 'copy']); +`) +} + +// The live case (hivecommons/hive#15078, operator screenshot 2026-10-28): +// hotshot#316 with its one nested PR #317 at 090. The ISSUE row's ⋯ menu +// must carry all three — Approve & merge as maintainer, Approve — let hive +// merge, Let hive decide — and the popover the same, merge answers first. +func TestStageTrackerIssueRowWithNested090PRCarriesAllThree(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerDecisionPopPreamble(t, html)+` +const ids = as => as.map(a => a.id); +const merger = { user: true, canHold: true, canHuman: true }; +const decision090 = { question: 'This PR is ready to merge, but the hive will not merge it by itself (untrusted author).', blocker: 'The hive never merges this unattended.', asked_by: 'the merge lane', since: '2026-10-28T12:00:00Z', + options: [ + { action: 'decide:merge-now', label: 'Approve & merge as maintainer', enabled: true, consequence: 'merges #317 into main now via hive\'s identity, attributed to you' }, + { action: 'decide:queue-merge', label: 'Approve — let hive merge', enabled: true, consequence: 'records your approval; the hive\'s merge sweep merges #317 on its next pass' }, + { action: 'decide:delegate', label: 'Let hive decide', enabled: true, consequence: 'the hive answers at once why it will not merge this itself and lists these options; it never merges it' }, + { action: 'decide:close-superseded', label: 'Close as superseded', enabled: true, consequence: 'closes #317 unmerged, naming the PR that replaces it' }, + { action: 'decide:close-wontfix', label: "Close as won't fix", enabled: true, consequence: 'closes #317 unmerged' }, + { action: 'hold', label: 'Hold', enabled: true }, + ] }; +const lp317 = { number: 317, title: 'docs: prepare v0.2.0 release notes', url: 'https://github.com/hivecommons/hotshot/pull/317', author: 'Karibhou', author_kind: 'human', base_ref: 'main', stage: 90, modifiers: [], human_merge_reason: 'untrusted-author', decision_needed: decision090 }; +const issue316 = { repo: 'hivecommons/hotshot', kind: 'issue', number: 316, title: 'Release v0.2.0', url: 'https://github.com/hivecommons/hotshot/issues/316', stage: 90, mirrored: true, modifiers: [], linked_prs: [lp317] }; + +const as = stageTrackerRowActions(issue316, merger); +const flat = stageTrackerFlatActions(as); +assert.deepStrictEqual(ids(as).slice(0, 3), ['decide:merge-now', 'decide:queue-merge', 'decide'], 'issue row leads with the two merge answers: ' + ids(as)); +assert.ok(flat['decide:merge-now'] && flat['decide:merge-now'].enabled, 'Approve & merge as maintainer present and enabled'); +assert.ok(flat['decide:queue-merge'] && flat['decide:queue-merge'].enabled, 'Approve — let hive merge present and enabled'); +assert.ok(flat['decide:delegate'] && flat['decide:delegate'].enabled, 'Let hive decide present (in Decide PR #317…) and enabled'); +assert.strictEqual(as[2].label, 'Decide PR #317…'); +assert.strictEqual(as[2].submenu[0].id, 'decide:delegate', 'Let hive decide leads the Decide… group'); +for (const id of ['decide:merge-now', 'decide:queue-merge']) assert.strictEqual(flat[id].target.number, 317, id + ' acts on PR #317'); +const menu = stageTrackerMenuHtml(as, 'hivecommons/hotshot#316'); +for (const id of ['decide:merge-now', 'decide:queue-merge', 'decide:delegate']) assert.ok(menu.includes('data-ham-act="' + id + '"'), id + ' rendered in the issue-row menu'); +assert.ok(menu.indexOf('data-ham-act="decide:merge-now"') < menu.indexOf('data-ham-act="hold"'), 'merge answers above the generic items'); + +// The needs-human popover on the issue row resolves to PR #317 and lists +// the same three, merge answers first, Let hive decide right after. +const dec = stageTrackerDecisionOf(issue316); +assert.strictEqual(dec.item.number, 317); +const pop = stageTrackerDecisionOptions(dec.item, merger); +assert.deepStrictEqual(ids(pop).slice(0, 3), ['decide:merge-now', 'decide:queue-merge', 'decide:delegate'], 'popover order: ' + ids(pop)); +assert.ok(pop[0].enabled && pop[1].enabled && pop[2].enabled); +const html = stageTrackerDecisionPopHtml(dec.item, pop, Date.now(), ''); +for (const id of ['decide:merge-now', 'decide:queue-merge', 'decide:delegate']) assert.ok(html.includes('data-ham-act="' + id + '"'), id + ' rendered in the popover'); + +// A 085 popover still leads with Let hive decide. +const pr85 = { repo: 'o/r', kind: 'pr', number: 4, url: 'u', stage: 85, modifiers: ['needs-decision'], + decision_needed: { question: 'q', options: [{ action: 'decide:approve', label: 'Approve', enabled: true }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; +assert.strictEqual(stageTrackerDecisionOptions(pr85, merger)[0].id, 'decide:delegate'); +`) +} diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 2548676deb..43bed748cd 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1696,6 +1696,9 @@ .ham-decision-act.ham-menu-danger { color: var(--red); } .ham-decision-act[aria-disabled="true"] { color: var(--text-faint); border-style: dashed; cursor: default; opacity: 0.6; } .ham-decision-act[aria-disabled="true"]:hover { background: transparent; border-color: var(--line-subtle); } + .ham-decision-consequences { margin: 0 0 var(--sp-1); padding-left: var(--sp-4); font-size: var(--fs-xs); color: var(--text-muted); } + .ham-decision-consequences li { margin: 0; overflow-wrap: anywhere; } + .ham-decision-consequences b { font-weight: var(--fw-semibold); color: var(--text); } .ham-selbar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin: 0 0 var(--sp-2); padding: var(--sp-2) var(--sp-3); border: var(--line-width) solid color-mix(in srgb, var(--accent) 45%, var(--line-subtle)); border-radius: var(--r-sm); background: color-mix(in srgb, var(--accent) 8%, var(--panel)); font-size: var(--fs-xs); } .ham-selbar[hidden] { display: none; } .ham-selbar .ham-sel-count { font-weight: var(--fw-semibold); color: var(--text); margin-right: var(--sp-2); } @@ -14825,6 +14828,7 @@

Where to get help

const STAGE_TRACKER_ACTED_LABELS = { approve: 'Approve', 'give-direction': 'Give direction', 'close-superseded': 'Close as superseded', wontfix: "Close as won't-fix", 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', + 'merge-now': 'Approve & merge as maintainer', 'queue-merge': 'Approve — let hive merge', }; const STAGE_TRACKER_ACTED_STATES = ['waiting', 'addressed', 'stuck', 'pending', 'failed']; const STAGE_TRACKER_ACTED_FILTERS = ['any', 'awaiting', 'acted', 'stuck']; @@ -14908,7 +14912,7 @@

Where to get help

} // Row-menu action id each ledger action was submitted under, so the // option the owner just took is not offered back to them. - const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'accept-triage': 'accept-triage', hold: 'hold' }; + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge' }; // Pure: what the owner can still do when their action changed nothing // (no-op) or the item has not moved (stuck): the enabled options from // the row's decision_needed payload, minus the one just taken. @@ -15043,7 +15047,7 @@

Where to get help

const open = Array.isArray(issue.linked_prs) ? issue.linked_prs.filter(x => x && x.number !== lp.number && stageTrackerLinkedPROpen(x)) : []; return { repo: issue.repo, number: lp.number, kind: 'pr', title: lp.title || '', url: lp.url || '', author: lp.author || '', author_kind: lp.author_kind || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', - 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 || '', head: lp.head || '', decision_needed: lp.decision_needed || 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 || '', head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, adoption: lp.adoption || null, superseded: !!lp.superseded, 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 }; } @@ -16595,6 +16599,7 @@

All labels

"approve": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge gate merges it once every check passes."}, "approve-review": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge gate merges it once every check passes."}, "approved": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge gate merges it once every check passes."}, + "author-association": {"kind": "reason", "plain": "no merge lane vouches for this PR's author; a maintainer merges", "detail": "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve & merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors."}, "author-online": {"kind": "reason", "plain": "the author's hive is connected, so hive won't take the PR over", "detail": "Adoption is for authors whose hive has gone offline; this author's hive is connected, so the hive leaves the PR with them."}, "behind": {"kind": "reason", "plain": "the branch is behind the base branch", "detail": "The branch is behind the base branch and must be updated before it can merge."}, "changes-requested": {"kind": "reason", "plain": "a reviewer asked for changes; a new commit is needed", "detail": "A reviewer asked for changes on this branch. Approving cannot override that: only a new commit, or a maintainer merging by hand, moves it."}, @@ -16610,6 +16615,7 @@

All labels

"comment-decision": {"kind": "action", "plain": "recorded the decision on GitHub", "detail": "The hive posted the decision as a `/hive decision` comment, the way a maintainer would."}, "conflict": {"kind": "reason", "plain": "the branch conflicts with the base branch", "detail": "The branch has merge conflicts with the base branch; it needs a rebase before anything can merge."}, "conflicting": {"kind": "reason", "plain": "the branch conflicts with the base branch", "detail": "The branch has merge conflicts with the base branch; it needs a rebase before anything can merge."}, + "contributor-lane:author-association": {"kind": "reason", "plain": "no merge lane vouches for this PR's author; a maintainer merges", "detail": "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve & merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors."}, "contributor-lane:changes-requested": {"kind": "reason", "plain": "a reviewer asked for changes; a new commit is needed", "detail": "A reviewer asked for changes on this branch. Approving cannot override that: only a new commit, or a maintainer merging by hand, moves it."}, "contributor-lane:sentinel-blocked": {"kind": "reason", "plain": "security-sensitive files changed; a maintainer must approve", "detail": "Security-sensitive files changed. The hive never merges until a maintainer reviews and removes the sentinel label."}, "contributor-offline": {"kind": "rule", "plain": "the author's hive hasn't been connected since the nudge", "detail": "The PR's author has been offline since the hive nudged them, so the hive takes the work over instead of waiting."}, @@ -16628,6 +16634,7 @@

All labels

"hive-policy": {"kind": "rule", "plain": "this changes the hive's own rules", "detail": "This changes the hive's own settings, governance or security posture; the hive only recommends and the owner confirms."}, "hold": {"kind": "reason", "plain": "on hold; the hive does nothing until it is released", "detail": "The item is on hold. The hive does nothing with it until a person releases the hold."}, "human-changes-requested": {"kind": "reason", "plain": "a reviewer asked for changes; a new commit is needed", "detail": "A reviewer asked for changes on this branch. Approving cannot override that: only a new commit, or a maintainer merging by hand, moves it."}, + "human-merge": {"kind": "reason", "plain": "no merge lane vouches for this PR's author; a maintainer merges", "detail": "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve & merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors."}, "label:needs-human": {"kind": "reason", "plain": "marked needs-human; a person must remove the label", "detail": "The item is marked needs-human: automated fixes ran out or a person flagged it. The hive waits until the label is removed."}, "labels-add": {"kind": "action", "plain": "added labels", "detail": "The hive added labels to the item."}, "labels-remove": {"kind": "action", "plain": "removed labels", "detail": "The hive removed labels from the item."}, @@ -16643,6 +16650,7 @@

All labels

"prefer-contributor": {"kind": "rule", "plain": "a contributor's PR and a hive PR do the same work", "detail": "A contributor's PR and a hive-authored PR cover the same work; the hive prefers the contributor's when it is mergeable and current."}, "quarantine-flaky": {"kind": "action", "plain": "quarantined the flaky test", "detail": "The flaky test is quarantined with a retry and a deflake task is filed."}, "rail-hold": {"kind": "rule", "plain": "the item is on hold", "detail": "The item carries the hold label; the hive never acts on a held item until a person releases the hold."}, + "ready-for-human-merge": {"kind": "reason", "plain": "no merge lane vouches for this PR's author; a maintainer merges", "detail": "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve & merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors."}, "recommend-only": {"kind": "action", "plain": "recommended only; a person confirms", "detail": "The hive only recommended; the item stays parked until a person confirms."}, "recommended": {"kind": "action", "plain": "recommended only; a person confirms", "detail": "The hive only recommended; the item stays parked until a person confirms."}, "red": {"kind": "reason", "plain": "CI is failing on this branch", "detail": "Required checks are failing on this branch; nothing merges until they are green."}, @@ -16663,6 +16671,7 @@

All labels

"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."}, "supersede-now": {"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."}, "superseded": {"kind": "action", "plain": "closed because another PR carries the work", "detail": "Closed because another PR carries the same work; the author is credited there."}, + "untrusted-author": {"kind": "reason", "plain": "no merge lane vouches for this PR's author; a maintainer merges", "detail": "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve & merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors."}, }; // Pure: plain words for a glossary slug ("supersede" → "close this PR and // open a fresh hive-authored PR with the same commits"). Strips a lane @@ -16682,9 +16691,17 @@

All labels

'decide:delegate': 'Let hive decide', 'decide:delegate-all': 'Let hive decide — all PRs', 'decide:delegate:rerun': 'Re-run decision', 'decide:approve': 'Approve', 'decide:direction': 'Give direction', 'decide:close-superseded': 'Close as superseded by', 'decide:close-wontfix': "Close as won't-fix", 'decide:adopt': 'Adopt (hive takes over)', + 'decide:merge-now': 'Approve & merge as maintainer', 'decide:queue-merge': 'Approve — let hive merge', hold: 'Hold', release: 'Release hold', retry: 'Re-evaluate now', 'accept-triage': 'Accept triage', 'needs-human': 'Mark needs-human', open: 'Open on GitHub', copy: 'Copy link', }; + // Actions that end with a commit on the base branch (merge now, or an + // approval the hive's sweep merges on): merger or owner only, like + // POST .../queue-automerge. + const STAGE_TRACKER_MERGE_ACTIONS = ['decide:merge-now', 'decide:queue-merge']; + // Generic items every row has; a server-named decision option with one + // of these ids is not repeated at the top of the menu. + const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:adopt']; // Accept triage shows on an issue the chevron calls "Triage needed": // stage 015, or the needs-triage pill on a pre-claim stage (010 / 017 / // 045). A needs-triage left on a claimed or covered issue is reported @@ -16893,6 +16910,34 @@

All labels

} return next; } + // Pure: whether this viewer may run a decision option: write access, + // and the merger/owner role for anything that merges. + function stageTrackerActionAllowed(id, ctx) { + ctx = ctx || {}; + if (STAGE_TRACKER_MERGE_ACTIONS.indexOf(id) >= 0) return ctx.canHuman ? { enabled: true, why: '' } : { enabled: false, why: STAGE_TRACKER_WHY_ROLE }; + const can = ctx.canHold !== false && !!ctx.user; + return { enabled: can, why: can ? '' : STAGE_TRACKER_WHY_WRITE }; + } + // Pure: the row's lead actions — the server's decision_needed.options + // (the item's own, else its one asking nested PR's) that neither the + // generic items every row has nor the Decide… submenu (`taken`) already + // offer, in the server's order, each carrying its consequence as the + // hint. Enabled only when the server and this viewer's permissions + // agree; otherwise disabled with the reason. + function stageTrackerLeadActions(item, ctx, taken) { + const dec = typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const d = dec && dec.item && dec.item.decision_needed; + const server = d && Array.isArray(d.options) ? d.options : []; + const out = []; + for (const o of server) { + if (!o || !o.action || STAGE_TRACKER_GENERIC_ACTIONS.indexOf(o.action) >= 0 || o.action.indexOf('decide:') !== 0 || (taken && taken[o.action])) continue; + const allowed = stageTrackerActionAllowed(o.action, ctx); + const enabled = !!o.enabled && allowed.enabled; + const why = enabled ? '' : (o.enabled ? allowed.why : (o.reason_if_disabled || 'Not available on this row')); + out.push({ id: o.action, label: o.label || STAGE_TRACKER_ACTION_LABELS[o.action] || o.action, hint: o.consequence || '', enabled, why, danger: /^decide:close-/.test(o.action), lead: true, target: dec.item }); + } + return out; + } // Pure: the actions that apply to one row in its current state. function stageTrackerRowActions(item, ctx) { ctx = ctx || {}; @@ -16905,10 +16950,20 @@

All labels

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) }); } + // 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, + // each with its consequence, so the pill's ask always has its action + // right here (hivecommons/hive#15078: "Ready for human merge" with no + // way to merge). const target = stageTrackerDecisionTarget(item); + const submenu = target ? stageTrackerDecideOptions(target, ctx) : []; + const taken = {}; + for (const o of submenu) taken[o.id] = true; + const lead = stageTrackerLeadActions(item, ctx, taken); + for (const a of lead) out.push(a); if (target) { const on = target === item ? '' : ' PR #' + (Number(target.number) || 0); - out.push({ id: 'decide', label: 'Decide' + on + '…', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, submenu: stageTrackerDecideOptions(target, ctx), target }); + out.push({ id: 'decide', label: 'Decide' + on + '…', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, submenu, target, sep: lead.length > 0 }); } // A nudged contributor PR the engine would adopt but for the owner's // say-so (maintainer_policy: ask) offers Adopt (hivecommons/hive#14524). @@ -16964,7 +17019,7 @@

All labels

function stageTrackerMenuItemHtml(a) { const dis = a.enabled ? '' : ` aria-disabled="true" title="${esc(a.why || '')}"`; if (a.submenu) { - return ``; + return `${a.sep ? '' : ''}`; } return `${a.sep ? '' : ''}`; } @@ -17158,10 +17213,12 @@

All labels

const c = flat[o.action]; const enabled = !!o.enabled && !!(c && c.enabled); const why = enabled ? '' : (o.reason_if_disabled || (c ? c.why : 'Not available on this row') || ''); - return { id: o.action, label: o.label || STAGE_TRACKER_ACTION_LABELS[o.action] || o.action, enabled, why, danger: !!(c && c.danger) || /^decide:close-/.test(o.action) }; + return { id: o.action, label: o.label || STAGE_TRACKER_ACTION_LABELS[o.action] || o.action, enabled, why, consequence: o.consequence || '', danger: !!(c && c.danger) || /^decide:close-/.test(o.action) }; }); + // "Let hive decide" leads — except where the server's first option + // is the merge the pill asks for (090: hivecommons/hive#15078). const lead = out.findIndex(o => o.id === 'decide:delegate'); - if (lead > 0) out.unshift(out.splice(lead, 1)[0]); + if (lead > 0 && STAGE_TRACKER_MERGE_ACTIONS.indexOf(out[0].id) < 0) out.unshift(out.splice(lead, 1)[0]); return out; } // Pure: the popover markup. @@ -17170,13 +17227,17 @@

All labels

const ref = stageTrackerRefOf(item); const sinceMs = Date.parse(d.since || item.stage_since || ''); const meta = ['Asked by ' + (d.asked_by || 'the hive'), sinceMs ? agentNowAgo(nowMs - sinceMs) : ''].filter(Boolean).join(' · '); - const buttons = options.map(o => ``).join(''); + const buttons = options.map(o => ``).join(''); + // Each option's consequence in plain words, so the choice is made + // knowing what happens next (hivecommons/hive#15078). + const consequences = options.filter(o => o.consequence).map(o => `
  • ${esc(o.label)} — ${esc(o.consequence)}
  • `).join(''); // Order (owner): WHAT it is waiting on → WHAT you can do → WHO asked, when. return ``; @@ -17684,6 +17745,12 @@

    All labels

    const v = await stageTrackerAsk(id, 'prompt', { title: stageTrackerActionLabel(id), label: 'Comment for ' + refs + ' (optional)', placeholder: 'Why this is closed', confirmLabel: 'Close' }); return v == null ? null : { comment: v }; } + case 'decide:merge-now': { + const base = items.map(it => it.base_ref || '').filter(Boolean)[0] || 'its base branch'; + return (await stageTrackerAsk(id, 'confirm', { title: 'Approve & merge as maintainer', message: preface + 'Merge ' + refs + ' into ' + base + ' now via hive\'s identity, attributed to ' + who + '? The merge gate parked it for a human because its author is not a trusted merger on this repo; this is you taking that call. The head you see is the head that merges — a push in between makes GitHub refuse.', confirmLabel: 'Approve & merge', danger: true })) ? {} : null; + } + case 'decide:queue-merge': + return (await stageTrackerAsk(id, 'confirm', { title: 'Approve — let hive merge', message: preface + 'Record your approval on ' + refs + ' as the owner decision, as ' + who + '? Hive\'s merge sweep merges it on the next tick once CI is green, respecting soak; the dashboard merges nothing itself.', confirmLabel: 'Approve' })) ? {} : null; case 'decide:adopt': { const why = items.map(it => stageTrackerAdoptionTip(it)).filter(Boolean).join('\n'); return (await hiveConfirm({ title: 'Adopt pull request' + (items.length > 1 ? 's' : ''), message: (why ? why + '\n\n' : '') + 'Have the hive adopt ' + refs + ' as ' + who + '? The author\'s commits and sign-off are kept; the hive rebases and fixes CI (in place when GitHub allows, else on a superseding hive PR that closes this one when it merges). Recorded as your decision on the PR.', confirmLabel: 'Adopt' })) ? {} : null; @@ -17712,9 +17779,11 @@

    All labels

    const STAGE_TRACKER_ACTING_CAPTIONS = { 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'decide:delegate': 'Hive is deciding…', 'decide:delegate-all': 'Hive is deciding each PR…', 'decide:delegate:rerun': 'Hive is deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', + 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Queuing for merge…', }; const STAGE_TRACKER_ACTION_WORDS = { adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', + merged: 'merged', 'queued-for-merge': 'queued for merge', held: 'held', released: 'hold released', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', [STAGE_TRACKER_ACTION_NOOP]: 'no change', [STAGE_TRACKER_ACTION_NO_EFFECT]: "decided, but it hasn't taken effect", }; diff --git a/src/pkg/delegatedecision/decision_glossary.go b/src/pkg/delegatedecision/decision_glossary.go index 0c006680c1..87cd1f402e 100644 --- a/src/pkg/delegatedecision/decision_glossary.go +++ b/src/pkg/delegatedecision/decision_glossary.go @@ -67,6 +67,7 @@ const ( GlossaryNoNewCommit = "no-new-commit" GlossarySelfDecision = "self-decision-read-as-changes" GlossaryEffectUnknown = "effect-unknown" + GlossaryHumanMerge = "human-merge" // 090: no lane vouches for the author (hivecommons/hive#15078) glossaryFallbackUnknown = "the hive did not say why" ) @@ -173,6 +174,9 @@ var glossary = []GlossaryEntry{ Detail: "The hive decided to close it, but it is still open; the close call did not land."}, {Slug: GlossaryNoNewCommit, Kind: GlossaryReason, Plain: "no new commit has been pushed", Detail: "The hive gave direction, but no new commit has been pushed yet."}, + {Slug: GlossaryHumanMerge, Kind: GlossaryReason, Plain: "no merge lane vouches for this PR's author; a maintainer merges", + Detail: "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve & merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors.", + Aliases: []string{"untrusted-author", "ready-for-human-merge", "contributor-lane:author-association", "author-association"}}, {Slug: GlossaryNoEffect, Kind: GlossaryReason, Plain: "the decision hasn't taken effect", Detail: "The hive recorded this decision, but what it was supposed to cause has not happened within the expected time."}, {Slug: GlossaryEffectUnknown, Kind: GlossaryReason, Plain: glossaryFallbackUnknown, diff --git a/src/pkg/delegatedecision/policy.go b/src/pkg/delegatedecision/policy.go index f24665e444..9adcda71bd 100644 --- a/src/pkg/delegatedecision/policy.go +++ b/src/pkg/delegatedecision/policy.go @@ -154,6 +154,8 @@ type Input struct { // question, when one was recorded. Reasons []string Question string + // Author is the PR's / issue's GitHub login, for plain-words answers. + Author string // HiveAuthored: the hive opened the PR / filed the issue. HiveAuthored bool // TrustedAuthor: the author is the hive or holds write on the repo. diff --git a/src/pkg/github/attribution.go b/src/pkg/github/attribution.go index a8b8d95ec0..5b29679115 100644 --- a/src/pkg/github/attribution.go +++ b/src/pkg/github/attribution.go @@ -143,6 +143,11 @@ const ( // Merge) carried out through MergePRVia, so forge-driven merges are not // counted as relay merges. PRAuditPathForge = "forge" + // PRAuditPathDashboard marks a merge an operator asked for from the + // dashboard's activity monitor ("Approve & merge as maintainer" on a + // Ready-for-human-merge row, hivecommons/hive#15078): the hive's App + // performs it, the audit line names the person. + PRAuditPathDashboard = "dashboard" ) // System "agent" names recorded for creations no single coding agent diff --git a/src/pkg/github/pr_audit_path_test.go b/src/pkg/github/pr_audit_path_test.go index 9ed73cce17..28f83383df 100644 --- a/src/pkg/github/pr_audit_path_test.go +++ b/src/pkg/github/pr_audit_path_test.go @@ -99,7 +99,7 @@ func TestMergePRViaAuditsCallerPath(t *testing.T) { } func TestRecordPRMergedAuditCarriesPath(t *testing.T) { - for _, path := range []string{PRAuditPathSweep, PRAuditPathQueue, PRAuditPathRelay, PRAuditPathForge} { + for _, path := range []string{PRAuditPathSweep, PRAuditPathQueue, PRAuditPathRelay, PRAuditPathForge, PRAuditPathDashboard} { t.Run(path, func(t *testing.T) { c := &Client{} var trail []prAuditRec