From c2cd3669c5231a4a82263953e9da5709428e5aed Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 18:46:28 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20an=20owner?= =?UTF-8?q?'s=20Approve=20admits=20the=20untrusted-author=20PR=20head=20?= =?UTF-8?q?=E2=80=94=20no=20adoption,=20merge=20as-is;=20DCO=20warned=20be?= =?UTF-8?q?fore=20acting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An owner/maintainer Approve (approve, queue-merge or merge-now) on a contributor-lane PR is now a trust override for that head: the stage record carries admitted_by: operator-approval:, the contributor lane admits the author for that head (contributor-lane:operator-approval) and merges as-is after checks and soak, and the adoption engine refuses to adopt or supersede while the admission stands (adopt_blocked_by: operator-admission) unless the person explicitly asks for it. A /hive decision approve by a trusted merger is the same admission, derived from the recorded approval and written back. When the head cannot merge as-is (commits without a Signed-off-by) the 090 popover and both Approve confirms say so before acting and offer "Re-author as hive PR" as a separate decision (re-author), which queues adoption with its own note and never merges. Fixes #15136 Signed-off-by: Andrew Anderson --- ...fixed-owner-approve-admits-untrusted-pr.md | 1 + src/docs/dashboard-sections.md | 2 +- src/docs/operator-reference.md | 27 +++- src/pkg/dashboard/api_repo_item_decision.go | 84 ++++++++++-- .../api_repo_item_decision_admission_test.go | 128 ++++++++++++++++++ .../dashboard/api_repo_item_decision_test.go | 6 + src/pkg/dashboard/operator_actions.go | 5 + src/pkg/dashboard/operator_actions_test.go | 1 + src/pkg/dashboard/stage_tracker.go | 30 +++- src/pkg/dashboard/stage_tracker_adoption.go | 2 + src/pkg/dashboard/stage_tracker_decision.go | 75 +++++++++- .../dashboard/stage_tracker_decision_test.go | 61 +++++++++ .../stage_tracker_row_actions_test.go | 73 ++++++++++ src/pkg/dashboard/static/index.html | 25 +++- .../automerge/automerge_contributor_adopt.go | 3 + .../automerge/automerge_contributor_lane.go | 16 +++ .../automerge_contributor_lane_test.go | 9 ++ .../automerge/automerge_operator_admission.go | 73 ++++++++++ .../automerge_operator_admission_test.go | 107 +++++++++++++++ src/pkg/stageengine/prstage/reasons.go | 3 + src/pkg/stagelabels/admission_test.go | 59 ++++++++ src/pkg/stagelabels/store.go | 67 +++++++++ 22 files changed, 837 insertions(+), 20 deletions(-) create mode 100644 changelog.d/fixed-owner-approve-admits-untrusted-pr.md create mode 100644 src/pkg/dashboard/api_repo_item_decision_admission_test.go create mode 100644 src/pkg/github/automerge/automerge_operator_admission.go create mode 100644 src/pkg/github/automerge/automerge_operator_admission_test.go create mode 100644 src/pkg/stagelabels/admission_test.go diff --git a/changelog.d/fixed-owner-approve-admits-untrusted-pr.md b/changelog.d/fixed-owner-approve-admits-untrusted-pr.md new file mode 100644 index 0000000000..26b8bdc2ae --- /dev/null +++ b/changelog.d/fixed-owner-approve-admits-untrusted-pr.md @@ -0,0 +1 @@ +- Activity Monitor: an owner's Approve (either variant) on an untrusted-author PR is now a trust override for that head — the stage record carries `admitted_by: operator-approval:`, the contributor lane merges the head as-is after checks and soak, and the adoption engine refuses to adopt or supersede it while the admission stands (before, the approval was reduced to a comment and the claim-tier rule adopt-superseded the PR). When the head cannot merge as-is (commits without a Signed-off-by) the popover and both Approve confirms say so before acting and offer "Re-author as hive PR" as a separate choice. Fixes #15136 (#15156). diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 3a9a41f8f0..c40fbfa67d 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -739,7 +739,7 @@ The glyph is drawn for **every** row on the gate, so two rows in the same 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 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. **Either Approve is the trust override for that head** ([#15136](https://github.com/hivecommons/hive/issues/15136); owner, 2026-10-29: "I approved these and then they went to adopted…"): the stage record gets `admitted_by: operator-approval:`, the contributor lane merges the head as-is after checks and soak, and the adoption engine refuses to adopt or supersede it while the admission stands (the row reads *not adopted: a maintainer approved this head; the hive merges it as-is*; the 090 tooltip and popover say *Approved by @you as the owner decision…* and the second Approve greys out). When the record's commit check found commits without a `Signed-off-by`, the popover's blocker line and both Approve confirms say so **before** acting (*2 of 3 commits have no Signed-off-by, so a required DCO check refuses the merge*) and a third lead action appears, **Re-author as hive PR** — the explicit, separate choice: the hive re-homes the commits on a signed-off hive branch and opens a superseding PR; nothing is merged as-is. It is greyed with the reason on a person's PR. Renderer test: `TestStageTrackerReauthorAndApprovalCaveats`. | | 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.) | diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 8449f7b800..926bb672de 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -472,7 +472,32 @@ verified owner or an authorized user with the `merger` role: | `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 +**Approve is the trust override for that head +([#15136](https://github.com/hivecommons/hive/issues/15136)).** Before, an +owner's Approve on an untrusted-author PR was reduced to the `/lgtm` + +`/approve` comments and the contributor lane's claim-tier rule then +adopt-superseded the PR the owner had just approved. Now every Approve +variant — `approve`, `queue-merge`, `merge-now` — writes +`admitted_by: operator-approval:` (with `admitted_head`, +`admitted_at`) on the PR's stage record before touching GitHub, and the +response and audit detail carry `admitted_by`. While that admission stands +for the head: the contributor lane admits the author for that head +(`contributor-lane:operator-approval`; the merge comment names who +admitted it), **no adoption or supersede is permitted** — a due adoption +records `adopt_blocked_by: operator-admission` and the row reads *not +adopted: a maintainer approved this head; the hive merges it as-is* — and +the hive merges as-is after checks and soak (or at once for `merge-now`). +A new push drops the admission and the row asks again. A +`/hive decision approve` comment by a trusted merger is the same admission; +the engine derives it from the recorded approval and writes it back. An +explicit **Adopt** / **Re-author** from the dashboard is the person choosing +re-authoring and is not refused. + +| Decision | What it does | Audit / ledger | +|---|---|---| +| `re-author` — *Re-author as hive PR* | Offered as its own lead action on a 090 PR whose head cannot merge as-is — the stage record's commit check counted commits without a `Signed-off-by` (`dco_unsigned` / `dco_total` on the row). The popover and both Approve confirms say so **before** acting (*2 of 3 commits have no Signed-off-by, so a required DCO check refuses the merge*); approving never re-authors by itself. Re-author posts its own note and the `adoption/supersede` request label; the hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR. Disabled with the reason on a person's PR (the hive does not re-author a human's PR — ask them to `git commit -s --amend`). | `repo_item_decision_adopt` with `decision=re-author`; `last_operator_action.action: re-author`; toast *adopted*. | + +Neither merge action 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 diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index 87789c0802..211fbf91ef 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -8,11 +8,13 @@ import ( "net/http" "strconv" "strings" + "time" "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" + "github.com/hivecommons/hive/pkg/stagelabels" ) // Activity-monitor row decisions (hivecommons/hive#13479 follow-up). The @@ -67,6 +69,12 @@ const ( // tick once CI is green (soak and the self-merge ban still apply). repoItemDecisionMergeNow = "merge-now" repoItemDecisionQueueMerge = "queue-merge" + // re-author is the operator's explicit choice, offered on a 090 PR + // whose head cannot merge as-is (unsigned commits → DCO), to have the + // hive re-home the commits on a hive-owned branch and open a + // superseding PR (hivecommons/hive#15136). It queues the same adoption + // the Adopt decision does; it is never implied by an Approve. + repoItemDecisionReauthor = "re-author" repoItemDecisionMaxBody = 16 << 10 repoItemDecisionMaxComment = 4000 @@ -156,6 +164,29 @@ type repoItemDecisionResponse struct { Result *RowActionResult `json:"result,omitempty"` // Head is the PR head an approve / direction was recorded against. Head string `json:"head,omitempty"` + // AdmittedBy is the trust override an Approve (either variant) wrote + // on the stage record for Head — "operator-approval:" — so the + // contributor lane merges the head as-is and the adoption engine + // leaves the PR alone (hivecommons/hive#15136). + AdmittedBy string `json:"admitted_by,omitempty"` +} + +// admitPullRequestHead records user's Approve as the trust override for +// head on the stage record (hivecommons/hive#15136) and returns the +// admitted_by value written ("" when there is no record to write to — +// the lane then derives the same admission from the recorded approval). +func (s *Server) admitPullRequestHead(repoFull string, number int, head, user string) string { + by := stagelabels.OperatorApprovalAdmission(user) + if strings.TrimSpace(head) == "" || by == "" { + return "" + } + store := s.stageStoreOrShared() + key := stagelabels.Key(repoFull, number) + store.NoteAdmission(key, head, by, time.Now()) + if rec, ok := store.Get(key); ok && rec.Admission(head) == by { + return by + } + return "" } // repoItemDecisionResult reads a recorded human decision into the shared @@ -200,6 +231,10 @@ 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 repoItemDecisionReauthor: + out.Action = rowActionAdopted + out.Outcome = "Re-authoring queued: `" + label + "` applied." + out.Next = "The hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR on its next cycle; this PR is closed when that one merges. Nothing is merged as-is." case repoItemDecisionMergeNow: out.Action = rowActionMerged out.Outcome = "Merged into `" + label + "` now via hive's identity, attributed to you." @@ -347,16 +382,20 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) s.audit.LogRecord(user, auditRepoItemDecisionClose, auditDetail("repo", repoFull, "number", numStr, "type", itemType, "reason", verb, "superseded_by", supersededBy), "", repoFull, number) jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "closed", Label: label, Result: repoItemDecisionResult(repoFull, number, itemType, decision, comment, supersededBy, label, nil)}) - case repoItemDecisionAdopt: + case repoItemDecisionAdopt, repoItemDecisionReauthor: if itemType != "pr" { - jsonError(w, "adopt applies to pull requests", http.StatusBadRequest) + jsonError(w, decision+" applies to pull requests", http.StatusBadRequest) return } if !s.stageAdoptionEnabled() { jsonError(w, "adoption requires governor.labels.stage.adoption to be enabled on this hive", http.StatusConflict) return } - if err := gh.CreateIssueComment(ctx, repoFull, number, renderRepoItemDecisionAdoptComment(user, comment)); err != nil { + note := renderRepoItemDecisionAdoptComment(user, comment) + if decision == repoItemDecisionReauthor { + note = renderRepoItemDecisionReauthorComment(user, comment) + } + if err := gh.CreateIssueComment(ctx, repoFull, number, note); err != nil { jsonError(w, "posting adoption note: "+err.Error(), http.StatusBadGateway) return } @@ -368,7 +407,7 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) jsonError(w, "queuing adoption: "+err.Error(), http.StatusBadGateway) return } - s.audit.LogRecord(user, auditRepoItemDecisionAdopt, auditDetail("repo", repoFull, "number", numStr, "type", itemType, "label", delegatedecision.LabelAdoptSupersede), "", repoFull, number) + s.audit.LogRecord(user, auditRepoItemDecisionAdopt, auditDetail("repo", repoFull, "number", numStr, "type", itemType, "label", delegatedecision.LabelAdoptSupersede, "decision", decision), "", 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: @@ -382,7 +421,7 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) } s.handlePullRequestMergeDecision(ctx, w, repoFull, number, user, decision, comment) default: - jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix, adopt, merge-now or queue-merge", http.StatusBadRequest) + jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix, adopt, re-author, merge-now or queue-merge", http.StatusBadRequest) } } @@ -428,15 +467,19 @@ func (s *Server) handlePullRequestMergeDecision(ctx context.Context, w http.Resp if base == "" { base = "the base branch" } + // Either variant is the person's trust override for this head: written + // before the GitHub call so the adoption engine cannot take the PR over + // between the approval landing and the merge (hivecommons/hive#15136). + admitted := s.admitPullRequestHead(repoFull, number, state.HeadSHA, user) 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.audit.LogRecord(user, auditRepoItemDecisionQueue, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", state.HeadSHA, "author", author, "label", label, "admitted_by", admitted), "", repoFull, number) s.invalidateStageTrackerForWebhook() - jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "queued-for-merge", Label: label, Head: state.HeadSHA, + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "queued-for-merge", Label: label, Head: state.HeadSHA, AdmittedBy: admitted, Result: repoItemDecisionResult(repoFull, number, "pr", decision, comment, "", label, nil)}) return } @@ -455,9 +498,9 @@ func (s *Server) handlePullRequestMergeDecision(ctx context.Context, w http.Resp 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.audit.LogRecord(user, auditRepoItemDecisionMerge, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", state.HeadSHA, "author", author, "base", state.BaseRef, "sha", res.SHA, "admitted_by", admitted), "", repoFull, number) s.invalidateStageTrackerForWebhook() - jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "merged", Head: state.HeadSHA, + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "merged", Head: state.HeadSHA, AdmittedBy: admitted, Result: repoItemDecisionResult(repoFull, number, "pr", decision, comment, "", base, nil)}) } @@ -491,6 +534,17 @@ func renderRepoItemDecisionAdoptComment(user, comment string) string { return body } +// renderRepoItemDecisionReauthorComment is the attributed note a +// Re-author decision leaves on the PR before the adoption request label is +// applied (hivecommons/hive#15136). +func renderRepoItemDecisionReauthorComment(user, comment string) string { + body := fmt.Sprintf("%s by=%s -->\n@%s asked the hive to re-author this pull request as a hive PR: its head cannot merge as-is (commits without a Signed-off-by), so the hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR; this one is closed when that merges. The author's commits are preserved and attributed.", repoItemDecisionAdoptMarker, user, user) + if c := strings.TrimSpace(comment); c != "" { + body += "\n\n> " + strings.ReplaceAll(c, "\n", "\n> ") + } + return body +} + // handlePullRequestDecision answers approve / direction on a pull request. func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseWriter, repoFull string, number int, user, decision, comment string) { gh := s.deps.GHClient @@ -533,14 +587,22 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW return } action, status := auditRepoItemDecisionApprove, "approval-commented" + admitted := "" if decision == repoItemDecisionDirection { action, status = auditRepoItemDecisionDirection, "direction-recorded" + } else { + // The person's Approve is the trust override for this head: the + // contributor lane merges it as-is and the adoption engine leaves + // it alone while the admission stands (hivecommons/hive#15136). + if admitted = s.admitPullRequestHead(repoFull, number, head, user); admitted != "" { + released = append(released, "admitted") + } } - s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", head, "decision", comment, "released", strings.Join(released, ","), "stage", stage), "", repoFull, number) + s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", head, "decision", comment, "released", strings.Join(released, ","), "stage", stage, "admitted_by", admitted), "", repoFull, number) // The row's park was just answered: serve the re-derived stage on the // next tracker read instead of the cached 085. s.invalidateStageTrackerForWebhook() - jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status, Released: released, Stage: stage, Head: head, + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status, Released: released, Stage: stage, Head: head, AdmittedBy: admitted, Result: repoItemDecisionResult(repoFull, number, "pr", decision, comment, "", "", released)}) } diff --git a/src/pkg/dashboard/api_repo_item_decision_admission_test.go b/src/pkg/dashboard/api_repo_item_decision_admission_test.go new file mode 100644 index 0000000000..236f79e5e1 --- /dev/null +++ b/src/pkg/dashboard/api_repo_item_decision_admission_test.go @@ -0,0 +1,128 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +const admissionTestHead = "feedfacefeedfacefeedfacefeedfacefeedface" + +// seedAdmissionRecord gives PR #8 the stage record the engine would have +// written, so the dashboard's Approve has somewhere to note the admission. +func seedAdmissionRecord(t *testing.T, srv *Server, stage stagelabels.Stage) *stagelabels.Store { + t.Helper() + now := time.Date(2026, 11, 2, 18, 0, 0, 0, time.UTC) + store := stagelabels.NewStore("", func() time.Time { return now }) + srv.stageStore = store + store.Observe(stagelabels.Key("testorg/testrepo", 8), stage, "contributor-lane:untrusted-author") + return store +} + +// An owner's Approve — either variant — on an untrusted-author PR is a trust +// override for that head (hivecommons/hive#15136): the stage record carries +// admitted_by: operator-approval:, the response and audit say so, +// and the contributor lane reads it (no adoption, merge as-is). +func TestRepoItemDecisionApproveAdmitsTheHead(t *testing.T) { + for _, tc := range []struct { + name, body, role, status, audit string + }{ + {name: "approve", body: `{"decision":"approve","type":"pr"}`, role: "", status: "approval-commented", audit: auditRepoItemDecisionApprove}, + {name: "queue-merge", body: `{"decision":"queue-merge","type":"pr"}`, role: "merger", status: "queued-for-merge", audit: auditRepoItemDecisionQueue}, + {name: "merge-now", body: `{"decision":"merge-now","type":"pr"}`, role: "merger", status: "merged", audit: auditRepoItemDecisionMerge}, + } { + t.Run(tc.name, func(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/090-ready-for-human-merge"}} + srv := newRepoItemDecisionServer(t, mock) + store := seedAdmissionRecord(t, srv, stagelabels.ReadyForHumanMerge) + + w := postRepoItemDecisionAs(t, srv, 8, "writer", tc.role, tc.body) + if w.Code != http.StatusOK { + t.Fatalf("%s: code=%d body=%s", tc.name, w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Status != tc.status || resp.AdmittedBy != "operator-approval:writer" { + t.Fatalf("response = %+v", resp) + } + rec, ok := store.Get(stagelabels.Key("testorg/testrepo", 8)) + if !ok || rec.Admission(admissionTestHead) != "operator-approval:writer" || rec.AdmittedAt.IsZero() { + t.Fatalf("record = %+v", rec) + } + if rec.Admission("0000000000000000000000000000000000000000") != "" { + t.Fatalf("admission must be per head: %+v", rec) + } + if tc.name == "approve" && !strings.Contains(strings.Join(resp.Released, ","), "admitted") { + t.Fatalf("approve must report the admission: %+v", resp.Released) + } + details := decisionAuditDetails(srv) + if len(details) == 0 || !strings.Contains(details[0], "admitted_by=operator-approval:writer") { + t.Fatalf("audit must carry admitted_by: %v", details) + } + }) + } +} + +// Without a stage record there is nothing to note on: the Approve still +// lands, and the response says no admission was written. +func TestRepoItemDecisionApproveWithoutRecordAdmitsNothing(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true} + srv := newRepoItemDecisionServer(t, mock) + srv.stageStore = stagelabels.NewStore("", time.Now) + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"approve","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("approve: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.AdmittedBy != "" || strings.Contains(strings.Join(resp.Released, ","), "admitted") { + t.Fatalf("admission without a record: %+v", resp) + } +} + +// Re-author is the explicit, separate choice when the head cannot merge +// as-is: it queues adoption with its own note and never merges. +func TestRepoItemDecisionReauthorQueuesAdoptionWithItsOwnNote(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/090-ready-for-human-merge"}} + srv := newRepoItemDecisionServer(t, mock) + if w := postRepoItemDecision(t, srv, 7, "writer", `{"decision":"re-author","type":"issue"}`); w.Code != http.StatusBadRequest { + t.Fatalf("issue re-author: code=%d body=%s", w.Code, w.Body.String()) + } + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"re-author","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("re-author: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Decision != "re-author" || resp.Status != "adoption-queued" || resp.Label != delegatedecision.LabelAdoptSupersede || resp.AdmittedBy != "" { + t.Fatalf("resp = %+v", resp) + } + if resp.Result == nil || resp.Result.Action != rowActionAdopted || !strings.Contains(resp.Result.Outcome, "Re-authoring") { + t.Fatalf("result = %+v", resp.Result) + } + if len(mock.merges) != 0 || strings.Join(mock.added, ",") != delegatedecision.LabelAdoptSupersede { + t.Fatalf("re-author must only queue adoption: merges=%v added=%v", mock.merges, mock.added) + } + if len(mock.comments) != 1 || !strings.Contains(mock.comments[0], "re-author this pull request as a hive PR") || !strings.Contains(mock.comments[0], "Signed-off-by") { + t.Fatalf("comments = %v", mock.comments) + } + if acts := decisionAuditActions(srv); len(acts) == 0 || acts[0] != auditRepoItemDecisionAdopt { + t.Fatalf("audit = %v", acts) + } + if details := decisionAuditDetails(srv); len(details) == 0 || !strings.Contains(details[0], "decision=re-author") { + t.Fatalf("audit detail = %v", details) + } +} + +func decisionAuditDetails(srv *Server) []string { + var out []string + for _, e := range srv.GetAudit().Recent(20) { + out = append(out, e.Detail) + } + return out +} diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index 980e4df1ef..8d4b3d8b2b 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -10,9 +10,11 @@ import ( "strings" "sync" "testing" + "time" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stagelabels" ) // repoItemDecisionMock is the slice of GitHub the decision endpoint touches: @@ -348,6 +350,10 @@ func TestRepoItemDecisionApprovePRPostsLgtmAndApproveComments(t *testing.T) { func TestRepoItemDecisionApprovePRReleasesThePark(t *testing.T) { mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/085-needs-decision", "needs-human", "sentinel-alert", "role/trusted"}} srv := newRepoItemDecisionServer(t, mock) + // Own store: with no stage record there is no head admission to + // report (hivecommons/hive#15136), whatever other tests left in the + // process-wide store. + srv.stageStore = stagelabels.NewStore("", time.Now) srv.stageTrackerCacheMu.Lock() gen := srv.stageTrackerGen srv.stageTrackerCacheMu.Unlock() diff --git a/src/pkg/dashboard/operator_actions.go b/src/pkg/dashboard/operator_actions.go index 1921f3a173..712d03bb77 100644 --- a/src/pkg/dashboard/operator_actions.go +++ b/src/pkg/dashboard/operator_actions.go @@ -44,6 +44,9 @@ const ( // App, or queued for the hive's merge sweep. operatorActionMergeNow = "merge-now" operatorActionQueueMerge = "queue-merge" + // The operator's explicit re-authoring of a head that cannot merge + // as-is (hivecommons/hive#15136). + operatorActionReauthor = "re-author" // Stored outcomes: what the endpoint answered when the action was // submitted. `pending` is a delegated decision still running; the job's @@ -278,6 +281,8 @@ func operatorActionFromBody(endpoint string, body []byte) (operatorActionRequest out.Action = operatorActionMergeNow case repoItemDecisionQueueMerge: out.Action = operatorActionQueueMerge + case repoItemDecisionReauthor: + out.Action = operatorActionReauthor default: return out, false } diff --git a/src/pkg/dashboard/operator_actions_test.go b/src/pkg/dashboard/operator_actions_test.go index f01cabe938..2089429077 100644 --- a/src/pkg/dashboard/operator_actions_test.go +++ b/src/pkg/dashboard/operator_actions_test.go @@ -61,6 +61,7 @@ func TestOperatorActionFromBody(t *testing.T) { {"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":"re-author"}`, operatorActionRequest{Action: operatorActionReauthor}, 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/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index bd3dc39c3b..54b110c194 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -365,6 +365,19 @@ type StageTrackerItem struct { // leaving the owner to ask why (hivecommons/hive#14658). HumanMergeReason string `json:"human_merge_reason,omitempty"` HumanMergeReasonText string `json:"human_merge_reason_text,omitempty"` + // AdmittedBy is the person's trust override standing on the current + // head ("operator-approval:", hivecommons/hive#15136): their + // Approve admitted the head to the contributor lane, which merges it + // as-is after checks and soak, and the adoption engine leaves the PR + // alone while it stands. Empty when nobody admitted this head. + AdmittedBy string `json:"admitted_by,omitempty"` + // DCOUnsigned / DCOTotal are the stage record's commit check for the + // current head (0/0 when not cached): how many of the PR's commits lack + // a Signed-off-by. The 090 decision reads them to say, before anyone + // presses Approve, that merging as-is would fail DCO and to offer + // re-authoring as a separate choice (hivecommons/hive#15136). + DCOUnsigned int `json:"dco_unsigned,omitempty"` + DCOTotal int `json:"dco_total,omitempty"` // UnauthorizedStep is set when the item wears hive:unauthorized: the // step the hive's GitHub App is not permitted to take, in words // ("approve workflow runs"), from the `unauthorized:` stage @@ -512,7 +525,13 @@ type StageTrackerLinkedPR struct { ManualMerge bool `json:"manual_merge,omitempty"` HumanMergeReason string `json:"human_merge_reason,omitempty"` HumanMergeReasonText string `json:"human_merge_reason_text,omitempty"` - Head string `json:"head,omitempty"` + // AdmittedBy / DCOUnsigned / DCOTotal mirror the nested PR's trust + // override and commit check (#15136) so the sub-row's confirmations + // carry the same caveats. + AdmittedBy string `json:"admitted_by,omitempty"` + DCOUnsigned int `json:"dco_unsigned,omitempty"` + DCOTotal int `json:"dco_total,omitempty"` + Head string `json:"head,omitempty"` // DecisionNeeded mirrors the nested PR's own row field so the issue's // sub-row can open the same "Needs human" popover. DecisionNeeded *StageTrackerDecision `json:"decision_needed,omitempty"` @@ -1741,6 +1760,10 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.AdoptedBy = rec.AdoptedBy it.AdoptedByState = stageTrackerAdoptedByState(rec) it.SoakRemainingSeconds = int64(stageTrackerSoakRemaining(rec, now) / time.Second) + it.AdmittedBy = rec.Admission(it.Head) + if total, unsigned, ok := rec.DCOFor(it.Head); ok { + it.DCOTotal, it.DCOUnsigned = total, unsigned + } } it.Hold = stageTrackerHoldFrom(rec, hasRec, labels) it.Stage = stage.Number() @@ -1796,6 +1819,10 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.HumanMergeReasonText = "Untrusted author: " + why + ". Until then a maintainer merges — Approve & merge as maintainer, or Approve — let hive merge, from the row's ⋯ menu." } } + // A person already took the trust call for this head (#15136). + if login := stagelabels.AdmissionLogin(it.AdmittedBy); login != "" { + it.HumanMergeReasonText = "Approved by @" + login + " as the owner decision (" + it.AdmittedBy + "): the hive merges this head as-is on its next pass once CI is green and the head has soaked, and does not adopt or re-author it. " + it.HumanMergeReasonText + } } if slices.Contains(it.Modifiers, modUnauthorized) || slices.Contains(it.DeferredModifiers, modUnauthorized) { it.UnauthorizedStep, it.Unauthorized = stageTrackerUnauthorized(it.Reason) @@ -2703,6 +2730,7 @@ func stageTrackerResolveLinkedPRs(items []StageTrackerItem) { lp.Presence = pr.Presence lp.HumanApprover, lp.ManualMerge = pr.HumanApprover, pr.ManualMerge lp.HumanMergeReason, lp.HumanMergeReasonText = pr.HumanMergeReason, pr.HumanMergeReasonText + lp.AdmittedBy, lp.DCOUnsigned, lp.DCOTotal = pr.AdmittedBy, pr.DCOUnsigned, pr.DCOTotal lp.BaseRef = pr.BaseRef lp.DecisionNeeded = pr.DecisionNeeded lp.SoakRemainingSeconds, lp.MergeGate = pr.SoakRemainingSeconds, pr.MergeGate diff --git a/src/pkg/dashboard/stage_tracker_adoption.go b/src/pkg/dashboard/stage_tracker_adoption.go index 5f012117d0..44a8582150 100644 --- a/src/pkg/dashboard/stage_tracker_adoption.go +++ b/src/pkg/dashboard/stage_tracker_adoption.go @@ -158,6 +158,8 @@ func stageTrackerAdoptionText(author string, a StageTrackerAdoption, now time.Ti text += " — adopt?" case a.BlockedBy == stagelabels.AdoptBlockedAuthorMaintainer: text += " — not adopted: maintainer_policy is never" + case a.BlockedBy == stagelabels.AdoptBlockedOperatorAdmission: + text += " — not adopted: a maintainer approved this head; the hive merges it as-is" case a.BlockedBy != "": text += " — not adopted: " + a.BlockedBy } diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index 07f47e061b..4085b6a6c4 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -1,6 +1,7 @@ package dashboard import ( + "fmt" "slices" "strconv" "strings" @@ -75,6 +76,7 @@ const ( decisionActionCloseWontfix = "decide:close-wontfix" decisionActionMergeNow = "decide:merge-now" decisionActionQueueMerge = "decide:queue-merge" + decisionActionReauthor = "decide:re-author" decisionActionAcceptTriage = "accept-triage" decisionActionHold = "hold" decisionActionRelease = "release" @@ -257,13 +259,31 @@ func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision if approver != "" { d.Blocker = "Approved by @" + approver + "; the hive still never merges this unattended. A maintainer merges: here, or on GitHub." } + admitter := stagelabels.AdmissionLogin(it.AdmittedBy) + if admitter != "" { + // A person already took the trust call for this head (#15136): + // the lane merges it as-is; nothing is adopted or re-authored. + d.Question = "@" + admitter + " approved this head as the owner decision; the hive's merge sweep merges " + ref + " as-is once CI is green and the head has soaked, and will not adopt or re-author it. Merge it now instead, or send it back?" + d.Blocker = "Admitted by @" + admitter + " (" + it.AdmittedBy + "). The hive merges this head on its next pass; a new push drops the admission and asks again." + } + dco := decisionDCOBlocker(it) + if dco != "" { + d.Blocker += " " + dco + } 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" + queue.Consequence = "records your approval as the trust override for this head; the hive's merge sweep merges " + ref + " as-is on its next pass once CI is green and the head has soaked, and does not adopt it" + if admitter != "" && !held { + queue.Enabled, queue.ReasonIfDisabled = false, "@"+admitter+" already approved this head; the hive merges it on its next pass" + } + if dco != "" { + mergeNow.Consequence += "; " + decisionDCOConsequence(it) + queue.Consequence += "; " + decisionDCOConsequence(it) + } 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, "") @@ -271,10 +291,61 @@ func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision 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)} + d.Options = []StageTrackerDecisionOption{mergeNow, queue} + if dco != "" { + d.Options = append(d.Options, decisionReauthorOption(it, ref, held)) + } + d.Options = append(d.Options, delegate, direction, closeSup, closeWontfix, decisionHoldOption(held)) return d } +// decisionDCOBlocker says, before anyone presses Approve, that the head +// cannot merge as-is where DCO is required: the stage record's commit check +// found commits without a Signed-off-by (hivecommons/hive#15136). "" when +// the check is not cached for this head or every commit is signed. +func decisionDCOBlocker(it StageTrackerItem) string { + if it.DCOUnsigned <= 0 { + return "" + } + return fmt.Sprintf("Merging as-is may not be possible: %d of %s no Signed-off-by, so a required DCO check refuses the merge. Re-author as hive PR is the separate choice for that; an Approve never re-authors by itself.", + it.DCOUnsigned, pluralCommitsHave(it.DCOTotal)) +} + +// decisionDCOConsequence is the short DCO caveat under the merge options. +func decisionDCOConsequence(it StageTrackerItem) string { + return fmt.Sprintf("%d of %s no Signed-off-by, so GitHub refuses the merge where DCO is required", it.DCOUnsigned, pluralCommitsHave(it.DCOTotal)) +} + +// pluralCommitsHave renders "3 commits have" / "1 commit has" for the DCO +// sentences; a total the record does not know reads "its commits have". +func pluralCommitsHave(total int) string { + switch { + case total == 1: + return "1 commit has" + case total > 1: + return strconv.Itoa(total) + " commits have" + } + return "its commits have" +} + +// decisionReauthorOption is the operator's explicit "re-author as hive PR" +// choice (hivecommons/hive#15136): the hive re-homes the commits on a +// hive-owned, signed-off branch and opens a superseding PR. A person's PR +// is never re-authored by the hive, so for a human author the option is +// shown disabled with the step that does unblock it. +func decisionReauthorOption(it StageTrackerItem, ref string, held bool) StageTrackerDecisionOption { + o := decisionOption(decisionActionReauthor, "Re-author as hive PR", !held && it.AuthorKind != authorKindHuman, "Release the hold first") + if it.AuthorKind == authorKindHuman { + who := "the author" + if it.Author != "" { + who = "@" + it.Author + } + o.ReasonIfDisabled = "The hive does not re-author a person's PR; ask " + who + " to sign off (git commit -s --amend, then push), or merge on GitHub if DCO is not required there" + } + o.Consequence = "the hive re-homes " + ref + "'s commits on a hive-owned, signed-off branch and opens a superseding PR; " + ref + " is closed when that one merges; nothing is merged as-is" + return o +} + // 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 diff --git a/src/pkg/dashboard/stage_tracker_decision_test.go b/src/pkg/dashboard/stage_tracker_decision_test.go index be7b171eee..b7b1970f07 100644 --- a/src/pkg/dashboard/stage_tracker_decision_test.go +++ b/src/pkg/dashboard/stage_tracker_decision_test.go @@ -312,6 +312,67 @@ func TestStageTrackerDecisionForHumanMerge(t *testing.T) { } decisionOptionByAction(t, d, decisionActionRelease) }) + + // hivecommons/hive#15136: the popover warns about DCO BEFORE anyone + // presses Approve and offers re-authoring as its own choice; once a + // person approved, the row says who admitted the head and the second + // Approve is no longer offered. + t.Run("unsigned commits warn before acting and offer re-author", func(t *testing.T) { + agent := it + agent.Author, agent.AuthorKind, agent.DCOUnsigned, agent.DCOTotal = "hive[bot]", "hive", 2, 3 + d := stageTrackerDecisionNeeded(agent, nil, "") + if !strings.Contains(d.Blocker, "2 of 3 commits have no Signed-off-by") || !strings.Contains(d.Blocker, "Re-author as hive PR is the separate choice") { + t.Fatalf("blocker lacks the DCO warning: %q", d.Blocker) + } + if got := []string{d.Options[0].Action, d.Options[1].Action, d.Options[2].Action}; got[2] != decisionActionReauthor || got[0] != decisionActionMergeNow || got[1] != decisionActionQueueMerge { + t.Fatalf("options = %v, want merge-now, queue-merge, re-author", got) + } + for _, a := range []string{decisionActionMergeNow, decisionActionQueueMerge} { + if o := decisionOptionByAction(t, d, a); !o.Enabled || !strings.Contains(o.Consequence, "no Signed-off-by") { + t.Errorf("%s must stay available with the DCO caveat: %+v", a, o) + } + } + re := d.Options[2] + if !re.Enabled || re.Label != "Re-author as hive PR" || !strings.Contains(re.Consequence, "nothing is merged as-is") { + t.Fatalf("re-author = %+v", re) + } + human := it + human.DCOUnsigned, human.DCOTotal = 1, 1 + d = stageTrackerDecisionNeeded(human, nil, "") + if o := decisionOptionByAction(t, d, decisionActionReauthor); o.Enabled || !strings.Contains(o.ReasonIfDisabled, "@Karibhou to sign off") { + t.Fatalf("re-author on a person's PR = %+v", o) + } + if d := stageTrackerDecisionNeeded(it, nil, ""); decisionHasAction(d, decisionActionReauthor) { + t.Fatalf("re-author offered without unsigned commits: %+v", d.Options) + } + }) + + t.Run("admitted head names the approver and drops the second approve", func(t *testing.T) { + admitted := it + admitted.AdmittedBy = stagelabels.OperatorApprovalAdmission("octo") + d := stageTrackerDecisionNeeded(admitted, nil, "") + if !strings.Contains(d.Blocker, "Admitted by @octo (operator-approval:octo)") { + t.Fatalf("blocker = %q", d.Blocker) + } + if o := decisionOptionByAction(t, d, decisionActionQueueMerge); o.Enabled || !strings.Contains(o.ReasonIfDisabled, "@octo already approved") { + t.Fatalf("queue-merge after admission = %+v", o) + } + if o := decisionOptionByAction(t, d, decisionActionMergeNow); !o.Enabled { + t.Fatalf("merge-now must stay available: %+v", o) + } + }) +} + +func decisionHasAction(d *StageTrackerDecision, action string) bool { + if d == nil { + return false + } + for _, o := range d.Options { + if o.Action == action { + return true + } + } + return false } // TestStageTrackerNeedsHumanStatesCarryAnAction: every state diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 76a1215d6b..8a23a35a30 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -763,6 +763,7 @@ func stageTrackerConfirmOptOutJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerAskConfig"), jsFunc(t, html, "stageTrackerAsk"), jsFunc(t, html, "stageTrackerDelegateConfirm"), + jsFunc(t, html, "stageTrackerDCOCaveat"), jsFunc(t, html, "stageTrackerActionPayload"), `const store = {}; global.localStorage = { getItem: k => (k in store ? store[k] : null), setItem: (k, v) => { store[k] = String(v); }, removeItem: k => { delete store[k]; } }; global.window = { _hiveUser: 'clubanderson' }; @@ -1185,3 +1186,75 @@ const pr85 = { repo: 'o/r', kind: 'pr', number: 4, url: 'u', stage: 85, modifier assert.strictEqual(stageTrackerDecisionOptions(pr85, merger)[0].id, 'decide:delegate'); `) } + +// hivecommons/hive#15136: an owner's Approve is the trust override for the +// head, and the row must say so BEFORE acting. A 090 PR whose stage record +// counted unsigned commits gets the DCO caveat in both Approve confirms +// and a separate "Re-author as hive PR" lead action with its own confirm; +// the request, caption and ledger id are wired; a signed head says nothing +// about DCO. +func TestStageTrackerReauthorAndApprovalCaveats(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+stageTrackerConfirmOptOutJS(t, html)+jsConstLine(t, html, "STAGE_TRACKER_ACTED_OPTION_ID")+` +const ids = as => as.map(a => a.id); +const merger = { user: true, canHold: true, canHuman: true }; +const 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; 2 of 3 commits have no Signed-off-by, so GitHub refuses the merge where DCO is required' }, + { action: 'decide:queue-merge', label: 'Approve — let hive merge', enabled: true, consequence: 'records your approval as the trust override for this head; the hive\'s merge sweep merges #317 as-is on its next pass once CI is green and the head has soaked, and does not adopt it' }, + { action: 'decide:re-author', label: 'Re-author as hive PR', enabled: true, consequence: 'the hive re-homes #317\'s commits on a hive-owned, signed-off branch and opens a superseding PR; #317 is closed when that one merges; nothing is merged as-is' }, + { 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-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, url: 'https://github.com/hivecommons/hotshot/pull/317', author: 'hive[bot]', author_kind: 'hive', base_ref: 'main', + stage: 90, modifiers: [], human_merge_reason: 'untrusted-author', dco_unsigned: 2, dco_total: 3, decision_needed: { question: 'q', options } }; +const issue316 = { repo: 'hivecommons/hotshot', kind: 'issue', number: 316, url: 'u', stage: 90, mirrored: true, modifiers: [], + linked_prs: [{ number: 317, url: pr317.url, author: 'hive[bot]', author_kind: 'hive', base_ref: 'main', stage: 90, modifiers: [], human_merge_reason: 'untrusted-author', dco_unsigned: 2, dco_total: 3, decision_needed: { question: 'q', options } }] }; + +// The re-author choice leads right after the two Approve answers, on the +// PR sub-row and on the issue row over it. +let as = stageTrackerRowActions(pr317, merger); +assert.deepStrictEqual(ids(as).slice(0, 4), ['decide:merge-now', 'decide:queue-merge', 'decide:re-author', 'decide'], ids(as)); +assert.strictEqual(as[2].label, 'Re-author as hive PR'); +assert.ok(as[2].enabled && as[2].lead); +assert.ok(as[2].hint.includes('nothing is merged as-is')); +as = stageTrackerRowActions(issue316, merger); +assert.deepStrictEqual(ids(as).slice(0, 3), ['decide:merge-now', 'decide:queue-merge', 'decide:re-author'], ids(as)); +assert.strictEqual(as[2].target.number, 317); +const menu = stageTrackerMenuHtml(as, 'hivecommons/hotshot#316'); +assert.ok(menu.indexOf('data-ham-act="decide:re-author"') > 0 && menu.indexOf('data-ham-act="decide:re-author"') < menu.indexOf('data-ham-act="hold"')); +// Wiring: request body, acting caption, ledger id, label. +assert.deepStrictEqual(stageTrackerActionRequest(pr317, 'decide:re-author', {}).body, { decision: 're-author', comment: '', type: 'pr' }); +assert.strictEqual(STAGE_TRACKER_ACTION_LABELS['decide:re-author'], 'Re-author as hive PR'); +assert.strictEqual(STAGE_TRACKER_ACTING_CAPTIONS['decide:re-author'], 'Queuing re-authoring…'); +assert.strictEqual(STAGE_TRACKER_ACTED_OPTION_ID['re-author'], 'decide:re-author'); +// The DCO caveat, in plain words, only when the record counted unsigned commits. +assert.ok(stageTrackerDCOCaveat([pr317]).includes('2 of 3 commits on this head lack a Signed-off-by'), stageTrackerDCOCaveat([pr317])); +assert.ok(stageTrackerDCOCaveat([pr317]).includes('"Re-author as hive PR" is the separate choice')); +assert.strictEqual(stageTrackerDCOCaveat([{ ...pr317, dco_unsigned: 0 }]), ''); +assert.strictEqual(stageTrackerDCOCaveat([]), ''); +(async () => { + // Both Approve confirms warn BEFORE acting and say what approval means. + await stageTrackerActionPayload([pr317], 'decide:merge-now'); + assert.strictEqual(dialogs[0].cfg.title, 'Approve & merge as maintainer'); + assert.ok(dialogs[0].cfg.message.includes('lack a Signed-off-by'), dialogs[0].cfg.message); + await stageTrackerActionPayload([pr317], 'decide:queue-merge'); + assert.strictEqual(dialogs[1].cfg.title, 'Approve — let hive merge'); + assert.ok(dialogs[1].cfg.message.includes('trust override for this head'), dialogs[1].cfg.message); + assert.ok(dialogs[1].cfg.message.includes('will not adopt or re-author it'), dialogs[1].cfg.message); + assert.ok(dialogs[1].cfg.message.includes('lack a Signed-off-by'), dialogs[1].cfg.message); + // Re-author has its own confirm, danger-styled, with the don't-ask box. + assert.deepStrictEqual(await stageTrackerActionPayload([pr317], 'decide:re-author'), {}); + assert.strictEqual(dialogs[2].cfg.title, 'Re-author as hive PR'); + assert.ok(dialogs[2].cfg.danger); + assert.ok(dialogs[2].cfg.message.includes('superseding PR') && dialogs[2].cfg.message.includes('Nothing is merged as-is'), dialogs[2].cfg.message); + assert.deepStrictEqual(dialogs[2].cfg.check, { label: "Don't ask again for this action" }); + dialogAnswer = false; + assert.strictEqual(await stageTrackerActionPayload([pr317], 'decide:re-author'), null, 'cancel acts on nothing'); + // A signed head: no DCO sentence in the Approve confirm. + dialogAnswer = true; dialogs.length = 0; + await stageTrackerActionPayload([{ ...pr317, dco_unsigned: 0 }], 'decide:merge-now'); + assert.ok(!dialogs[0].cfg.message.includes('Signed-off-by'), dialogs[0].cfg.message); +})().catch(e => { console.error(e); process.exit(1); }); +`) +} diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 177247fec6..9a4a7e928e 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -15159,7 +15159,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', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge' }; + 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', 're-author': 'decide:re-author' }; // 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. @@ -16980,11 +16980,24 @@

All labels

if (e) return detail ? e.detail : e.plain; return s.replace(/^[a-z-]+:/, '').replace(/[-_]+/g, ' ').trim(); } + // Pure: the DCO caveat the merge confirmations print BEFORE acting + // when the stage record counted unsigned commits on the head (#15136): + // merging as-is then fails where DCO is required; re-authoring is the + // separate choice. + function stageTrackerDCOCaveat(items) { + const rows = (Array.isArray(items) ? items : [items]).filter(it => it && Number(it.dco_unsigned) > 0); + if (!rows.length) return ''; + const it = rows[0]; + const total = Number(it.dco_total) || 0; + const of = total > 0 ? ' of ' + total + ' commit' + (total === 1 ? '' : 's') : ' commit' + (Number(it.dco_unsigned) === 1 ? '' : 's'); + return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by, so GitHub refuses the merge where DCO is required. "Re-author as hive PR" is the separate choice for that; approving never re-authors by itself.'; + } const STAGE_TRACKER_ACTION_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', + 'decide:re-author': 'Re-author as hive PR', 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', }; @@ -18054,10 +18067,14 @@

All labels

} 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; + 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.' + stageTrackerDCOCaveat(items), 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; + return (await stageTrackerAsk(id, 'confirm', { title: 'Approve — let hive merge', message: preface + 'Record your approval on ' + refs + ' as the owner decision, as ' + who + '? This is the trust override for this head: hive\'s merge sweep merges it as-is on the next tick once CI is green, respecting soak, and will not adopt or re-author it. The dashboard merges nothing itself.' + stageTrackerDCOCaveat(items), confirmLabel: 'Approve' })) ? {} : null; + case 'decide:re-author': { + const caveat = stageTrackerDCOCaveat(items); + return (await stageTrackerAsk(id, 'confirm', { title: 'Re-author as hive PR', message: preface + 'Have the hive re-author ' + refs + ' as ' + who + '?' + (caveat || ' Its head cannot merge as-is.') + ' The hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR; this one is closed when that merges. Nothing is merged as-is, and the author\'s commits stay attributed.', confirmLabel: 'Re-author', danger: true })) ? {} : 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; @@ -18086,7 +18103,7 @@

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…', + 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Queuing for merge…', 'decide:re-author': 'Queuing re-authoring…', }; const STAGE_TRACKER_ACTION_WORDS = { adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index 1fadf0380e..46bcff48e1 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -599,6 +599,9 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor c.info("stage labels: adoption due but blocked by label", "repo", obs.Display, "pr", obs.Number, "label", l) return 0, nil } + if c.adoptionRefusedByAdmission(store, key, obs, requested, now) { + return 0, nil + } if held, deferred := c.maintainerHoldsAdoption(ctx, obs, policy, requested, now); held || deferred { if held && !deferred { // Recorded so the activity monitor says why (hivecommons/hive#14524): diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 3ef3443014..ae980a8ee6 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -529,6 +529,9 @@ type contributorClaimMatch struct { // PR: the head SHA the stage store records as adopted/pushed by the // hive, which the lane verified equals the PR head it is evaluating. AdoptedHead string + // OperatorLogin is set when a person's Approve admitted the head + // (hivecommons/hive#15136, operatorAdmission). + OperatorLogin string // ObservedTier is the raw tier the lane saw for the author (registry // profile or this hive's claim marker), admitted or not. It feeds the // author/* stage label; admission itself still goes through Reason. @@ -616,6 +619,9 @@ func (c *Engine) admitContributor(ctx context.Context, owner, repo string, pr *g if headSHA := pr.GetHead().GetSHA(); c.adoptedHeadOwnedByHive(owner, repo, pr.GetNumber(), headSHA) { return contributorClaimMatch{AdoptedHead: headSHA, ObservedTier: c.observedRegistryTier(author)}, nil } + if login := c.operatorAdmission(owner, repo, pr.GetNumber(), pr.GetHead().GetSHA()); login != "" { + return contributorClaimMatch{OperatorLogin: login, ObservedTier: c.observedRegistryTier(author)}, nil + } if tier := c.admittedRegistryTier(author, policy); tier != "" { return contributorClaimMatch{RegistryTier: tier, ObservedTier: tier}, nil } @@ -1229,6 +1235,9 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own if claim.admittedByAdoption() { c.info("contributor-lane admitted", "repo", displayRepo, "pr", number, "author", author, "reason", contributorLaneReasonAdoptedByHive, "adopted_head", claim.AdoptedHead) } + if claim.admittedByOperator() { + c.info("contributor-lane admitted", "repo", displayRepo, "pr", number, "author", author, "reason", contributorLaneReasonOperatorApproval, "admitted_by", claim.OperatorLogin, "head", headSHA) + } if claim.admittedByRegistry() { c.info("contributor-lane admitted", "repo", displayRepo, "pr", number, "author", author, "reason", contributorLaneReasonRegistryTrusted, "registry_tier", claim.RegistryTier) } @@ -1430,6 +1439,9 @@ func contributorLaneAdmitPath(claim contributorClaimMatch) string { if claim.admittedByAdoption() { return contributorLaneReasonAdoptedByHive } + if claim.admittedByOperator() { + return contributorLaneReasonOperatorApproval + } if claim.admittedByRegistry() { return contributorLaneReasonRegistryTrusted } @@ -1455,6 +1467,10 @@ func contributorLaneMergeComment(author string, claim contributorClaimMatch, soa return fmt.Sprintf("Merged by hive contributor-lane auto-merge: CI green for ≥%dm, %s, head `%s` adopted by the hive (`%s`) with @%s's commits — merged under the hive's own authority.", int(soak.Minutes()), verdictText, shortSHA(claim.AdoptedHead), stagelabels.AdoptedByHive.Label(), login) } + if claim.admittedByOperator() { + return fmt.Sprintf("Merged by hive contributor-lane auto-merge: CI green for ≥%dm, %s, @%s approved this head as the owner decision (`admitted_by: %s`) — merged as-is on that approval.", + int(soak.Minutes()), verdictText, claim.OperatorLogin, stagelabels.OperatorApprovalAdmission(claim.OperatorLogin)) + } if claim.admittedByRegistry() { return fmt.Sprintf("Merged by hive contributor-lane auto-merge: CI green for ≥%dm, %s, @%s holds the %s tier in this hive's contributor registry.", int(soak.Minutes()), verdictText, login, claim.RegistryTier) diff --git a/src/pkg/github/automerge/automerge_contributor_lane_test.go b/src/pkg/github/automerge/automerge_contributor_lane_test.go index acb409bf08..06805777aa 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane_test.go +++ b/src/pkg/github/automerge/automerge_contributor_lane_test.go @@ -1281,6 +1281,15 @@ func TestContributorLaneAdmitPathAndRegistryTierHelpers(t *testing.T) { if got := contributorLaneAdmitPath(contributorClaimMatch{Issue: 42}); got != "claim" { t.Fatalf("admit path = %q, want claim", got) } + // A person's Approve outranks the registry tier for that head (#15136) + // and the merge comment names who admitted it. + operator := contributorClaimMatch{OperatorLogin: "octo", RegistryTier: "trusted"} + if got := contributorLaneAdmitPath(operator); got != contributorLaneReasonOperatorApproval || contributorLaneReasonOperatorApproval != "contributor-lane:operator-approval" { + t.Fatalf("operator admit path = %q", got) + } + if c := contributorLaneMergeComment("mallory", operator, 30*time.Minute, ContributorLaneVerdict{}); !strings.Contains(c, "@octo") || !strings.Contains(c, "operator-approval:octo") { + t.Fatalf("operator merge comment = %q", c) + } if contributorLaneReasonRegistryTrusted != "contributor-lane:registry-trusted" { t.Fatalf("admit reason = %q", contributorLaneReasonRegistryTrusted) } diff --git a/src/pkg/github/automerge/automerge_operator_admission.go b/src/pkg/github/automerge/automerge_operator_admission.go new file mode 100644 index 0000000000..3fd36d2b94 --- /dev/null +++ b/src/pkg/github/automerge/automerge_operator_admission.go @@ -0,0 +1,73 @@ +package automerge + +import ( + "strings" + "time" + + "github.com/hivecommons/hive/pkg/stageengine/prstage" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// contributorLaneReasonOperatorApproval is the admit reason logged when a +// person's Approve admitted the head (hivecommons/hive#15136): an owner or +// trusted merger pressed Approve on the dashboard (or typed `/hive decision +// approve`) on a PR whose author no registry tier or claim marker vouches +// for. Their approval is a trust override for exactly that head: the lane +// merges it as-is after checks and soak, and the adoption engine leaves +// the PR alone while the admission stands. +const contributorLaneReasonOperatorApproval = prstage.ContributorLaneReasonOperatorApproval + +// operatorAdmission reports the person whose approval admits head on +// owner/repo#number, or "" when nobody did. Two sources agree on one +// answer: the stage record's admitted_by (the dashboard writes it when the +// Approve lands) and a recorded human approval for the head by a trusted +// merger (`/hive decision approve`, or a dashboard Approve that landed +// before the record existed). The second source is written back to the +// record so the activity monitor shows the admission. +func (c *Engine) operatorAdmission(owner, repo string, number int, head string) string { + head = strings.TrimSpace(head) + if c == nil || head == "" { + return "" + } + key := stageKey(owner, repo, number) + store := c.stageStoreOrShared() + if rec, ok := store.Get(key); ok { + if by := rec.Admission(head); by != "" { + if login := stagelabels.AdmissionLogin(by); login != "" { + return login + } + } + } + login, ok := c.recordedHumanApprovalForHead(owner, repo, number, head) + if !ok { + return "" + } + if trusted, configured := c.isTrustedMerger(login); !configured || !trusted { + return "" + } + store.NoteAdmission(key, head, stagelabels.OperatorApprovalAdmission(login), c.now()) + return login +} + +// admittedByOperator reports whether a person's approval admitted the head. +func (m contributorClaimMatch) admittedByOperator() bool { + return m.OperatorLogin != "" +} + +// adoptionRefusedByAdmission is the adoption engine's answer when the head +// about to be adopted carries a person's admission (hivecommons/hive#15136): +// the PR is theirs to merge as-is, so the hive records why it stood down +// and does not take it over. An explicit Adopt request from the dashboard +// is the same person choosing re-authoring, so it is not refused. +func (c *Engine) adoptionRefusedByAdmission(store *stagelabels.Store, key string, obs stageObservation, requested bool, now time.Time) bool { + if requested { + return false + } + login := c.operatorAdmission(obs.Owner, obs.Repo, obs.Number, obs.HeadSHA) + if login == "" { + return false + } + store.NoteAdoptionBlocked(key, obs.HeadSHA, stagelabels.AdoptBlockedOperatorAdmission, now) + c.info("stage labels: adoption due but a person admitted this head; not adopting", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "admitted_by", stagelabels.OperatorApprovalAdmission(login)) + return true +} diff --git a/src/pkg/github/automerge/automerge_operator_admission_test.go b/src/pkg/github/automerge/automerge_operator_admission_test.go new file mode 100644 index 0000000000..a3414f1be1 --- /dev/null +++ b/src/pkg/github/automerge/automerge_operator_admission_test.go @@ -0,0 +1,107 @@ +package automerge + +import ( + "testing" + "time" + + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// An owner's Approve on an untrusted-author PR is a trust override for that +// head (hivecommons/hive#15136): the dashboard writes admitted_by on the +// stage record, and a due adoption stands down instead of superseding the +// PR the person just approved. The row shows why (operator-admission); an +// explicit Adopt request from the same dashboard is the person choosing +// re-authoring and goes ahead. +func TestOperatorAdmissionRefusesAdoption(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, adoptPolicy()) + defer done() + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + store := h.e.stageStoreOrShared() + if !store.NoteAdmission(key, "aaa", stagelabels.OperatorApprovalAdmission("octo"), h.clock.now()) { + t.Fatalf("NoteAdmission refused a known key") + } + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + h.api.reset() + h.clock.advance(5 * time.Hour) + h.observe(adoptPR(7, "aaa", labels...), "check-failing:unit") + rec, _ := store.Get(key) + if len(h.adopt.pulls) != 0 || len(adoptionComments(h.api)) != 0 || rec.AdoptedHead != "" { + t.Fatalf("adopted an operator-admitted head: pulls=%d comments=%v rec=%+v", len(h.adopt.pulls), h.api.comments, rec) + } + if got := rec.AdoptionBlocked("aaa"); got != stagelabels.AdoptBlockedOperatorAdmission { + t.Fatalf("blocked reason = %q, want %q (%+v)", got, stagelabels.AdoptBlockedOperatorAdmission, rec) + } + if got := rec.Admission("aaa"); got != "operator-approval:octo" { + t.Fatalf("admission = %q", got) + } + if rec.Admission("bbb") != "" { + t.Fatalf("admission leaked to another head: %+v", rec) + } + // The person explicitly asks for re-authoring: not refused. + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", append(labels, delegatedecision.LabelAdoptSupersede)...), "check-failing:unit") + if rec, _ = store.Get(key); rec.AdoptedHead != "aaa" { + t.Fatalf("explicit Adopt request refused by admission: %+v", rec) + } +} + +// Without the dashboard's record, a `/hive decision approve` by a trusted +// merger is the same admission: the engine derives it from the recorded +// human approval and writes it back so the row shows it. An approval by +// someone the merger authorizer does not trust admits nothing. +func TestOperatorAdmissionDerivedFromHumanApproval(t *testing.T) { + for _, tc := range []struct { + name string + actor string + trusted bool + want string + }{ + {name: "trusted merger approves", actor: "Octo", trusted: true, want: "octo"}, + {name: "untrusted approver", actor: "mallory", trusted: false, want: ""}, + } { + t.Run(tc.name, func(t *testing.T) { + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, adoptPolicy()) + defer done() + h.e.humanChangeRequests = review.NewHumanChangeRequests("") + h.e.SetMergerAuthorizer(func(login string) bool { return tc.trusted }) + if err := h.e.humanChangeRequests.Record(review.HumanChangeRequest{Repo: "acme/widget", Number: 7, HeadSHA: "aaa", Actor: tc.actor, Kind: review.HumanChangeRequestKindApprove, SourceID: 1}); err != nil { + t.Fatal(err) + } + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + if got := h.e.operatorAdmission("acme", "widget", 7, "aaa"); got != tc.want { + t.Fatalf("operatorAdmission = %q, want %q", got, tc.want) + } + rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) + wantRec := "" + if tc.want != "" { + wantRec = stagelabels.OperatorApprovalAdmission(tc.want) + } + if rec.Admission("aaa") != wantRec { + t.Fatalf("record admission = %q, want %q", rec.Admission("aaa"), wantRec) + } + }) + } +} + +// Nothing admitted: a nil engine and an unknown head both answer "" and +// the adoption refusal is a no-op. +func TestOperatorAdmissionAbsent(t *testing.T) { + var nilEngine *Engine + if got := nilEngine.operatorAdmission("acme", "widget", 7, "aaa"); got != "" { + t.Fatalf("nil engine admitted %q", got) + } + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, adoptPolicy()) + defer done() + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + if got := h.e.operatorAdmission("acme", "widget", 7, "aaa"); got != "" { + t.Fatalf("admitted without approval: %q", got) + } + if got := h.e.operatorAdmission("acme", "widget", 7, ""); got != "" { + t.Fatalf("empty head admitted: %q", got) + } +} diff --git a/src/pkg/stageengine/prstage/reasons.go b/src/pkg/stageengine/prstage/reasons.go index 74b8a37a78..b5555f4ba6 100644 --- a/src/pkg/stageengine/prstage/reasons.go +++ b/src/pkg/stageengine/prstage/reasons.go @@ -38,6 +38,9 @@ const ( ContributorLaneReasonClaimUnverified = "contributor-lane:claim-unverified" ContributorLaneReasonFilesEvidence = "contributor-lane:files-evidence" ContributorLaneReasonNoAppBotLogin = "contributor-lane:no-app-bot-login" + // ContributorLaneReasonOperatorApproval is the admit reason when a + // person's Approve admitted the head (hivecommons/hive#15136). + ContributorLaneReasonOperatorApproval = "contributor-lane:operator-approval" ContributorLaneReasonNoAuthor = "contributor-lane:no-author" ContributorLaneReasonNoClaim = "contributor-lane:no-claim" ContributorLaneReasonNoLinkedIssue = "contributor-lane:no-linked-issue" diff --git a/src/pkg/stagelabels/admission_test.go b/src/pkg/stagelabels/admission_test.go new file mode 100644 index 0000000000..bec6eb4cbc --- /dev/null +++ b/src/pkg/stagelabels/admission_test.go @@ -0,0 +1,59 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +// A person's Approve admits one head (hivecommons/hive#15136): noted on an +// existing record only, read back per head, and the login recoverable from +// the admitted_by value. +func TestStoreAdmission(t *testing.T) { + now := time.Date(2026, 11, 2, 18, 0, 0, 0, time.UTC) + st := NewStore(filepath.Join(t.TempDir(), "s.json"), func() time.Time { return now }) + key := Key("hivecommons/hotshot", 317) + + if got := OperatorApprovalAdmission(" @Octo "); got != "operator-approval:octo" { + t.Fatalf("OperatorApprovalAdmission = %q", got) + } + if OperatorApprovalAdmission("") != "" || AdmissionLogin("") != "" || AdmissionLogin("registry:trusted") != "" { + t.Fatal("empty/foreign admission values must not yield a login") + } + if got := AdmissionLogin("operator-approval:octo"); got != "octo" { + t.Fatalf("AdmissionLogin = %q", got) + } + + // Unknown key, empty head or empty by: no-op. + if st.NoteAdmission(key, "aaa", "operator-approval:octo", now) { + t.Fatal("note on unknown key reported a change") + } + if _, ok := st.Get(key); ok { + t.Fatal("note created a record") + } + st.Observe(key, ReadyForHumanMerge, "contributor-lane:untrusted-author") + if st.NoteAdmission(key, "", "operator-approval:octo", now) || st.NoteAdmission(key, "aaa", "", now) { + t.Fatal("empty note reported a change") + } + + if !st.NoteAdmission(key, "aaa", "operator-approval:octo", now) { + t.Fatal("first note must report a change") + } + r, _ := st.Get(key) + if r.Admission("aaa") != "operator-approval:octo" || !r.AdmittedAt.Equal(now) { + t.Fatalf("admission: %+v", r) + } + if r.Admission("bbb") != "" || r.Admission("") != "" { + t.Fatal("admission leaked to another head") + } + // Same note again: unchanged. A new head replaces it. + if st.NoteAdmission(key, "aaa", "operator-approval:octo", now.Add(time.Hour)) { + t.Fatal("identical note reported a change") + } + if !st.NoteAdmission(key, "bbb", "operator-approval:mallory", now.Add(time.Hour)) { + t.Fatal("new head must report a change") + } + if r, _ = st.Get(key); r.Admission("aaa") != "" || r.Admission("bbb") != "operator-approval:mallory" { + t.Fatalf("replacement: %+v", r) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 636af91db3..b529d44b11 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -203,6 +203,16 @@ type Record struct { AdoptBlockedHead string `json:"adopt_blocked_head,omitempty"` AdoptBlockedBy string `json:"adopt_blocked_by,omitempty"` AdoptBlockedAt time.Time `json:"adopt_blocked_at,omitempty"` + // AdmittedHead / AdmittedBy / AdmittedAt record a person's trust + // override for one head (hivecommons/hive#15136): an owner or trusted + // merger approved the PR from the dashboard (or `/hive decision + // approve`), so for THAT head the contributor lane treats the author + // as trusted and the adoption engine does not take the PR over. + // AdmittedBy is "operator-approval:". A new head drops it: + // the person approved what they read, not what came after. + AdmittedHead string `json:"admitted_head,omitempty"` + AdmittedBy string `json:"admitted_by,omitempty"` + AdmittedAt time.Time `json:"admitted_at,omitempty"` // DCORepairHead is the in-place-adopted head whose unsigned hive // commits the hive last rewrote with its sign-off on the contributor // branch (hivecommons/hive#14666); one attempt per head. @@ -1206,6 +1216,63 @@ func (r Record) AdoptionBlocked(head string) string { return r.AdoptBlockedBy } +// AdoptBlockedOperatorAdmission is the AdoptBlockedBy reason for a due +// adoption the engine refused because a person admitted the head +// (Record.Admission): their approval said "merge this as-is", so the hive +// does not take the PR over (hivecommons/hive#15136). +const AdoptBlockedOperatorAdmission = "operator-admission" + +// AdmittedByOperatorApprovalPrefix prefixes AdmittedBy when the admission +// came from a person's Approve: "operator-approval:octocat". +const AdmittedByOperatorApprovalPrefix = "operator-approval:" + +// OperatorApprovalAdmission is the AdmittedBy value for login's Approve. +func OperatorApprovalAdmission(login string) string { + login = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(login), "@")) + if login == "" { + return "" + } + return AdmittedByOperatorApprovalPrefix + login +} + +// AdmissionLogin returns the person behind an AdmittedBy value ("" when it +// is not an operator approval). +func AdmissionLogin(admittedBy string) string { + if !strings.HasPrefix(admittedBy, AdmittedByOperatorApprovalPrefix) { + return "" + } + return strings.TrimPrefix(admittedBy, AdmittedByOperatorApprovalPrefix) +} + +// NoteAdmission records that `by` admitted head on an existing record +// (hivecommons/hive#15136). It returns true when the record changed. +func (s *Store) NoteAdmission(key, head, by string, now time.Time) bool { + head, by = strings.TrimSpace(head), strings.TrimSpace(by) + if head == "" || by == "" { + return false + } + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || (r.AdmittedHead == head && r.AdmittedBy == by) { + return false + } + r.AdmittedHead, r.AdmittedBy, r.AdmittedAt = head, by, now + s.items[key] = r + s.dirty = true + return true +} + +// Admission reports who admitted head ("" when nobody did, or the admission +// is for another head). +func (r Record) Admission(head string) string { + head = strings.TrimSpace(head) + if head == "" || r.AdmittedHead != head { + return "" + } + return r.AdmittedBy +} + // NoteAdoptReason records why the current adoption happened (the marker's // reason=) on an existing record. func (s *Store) NoteAdoptReason(key, reason string) {