Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- A recorded operator decision (dashboard Approve, `/hive decision …`) now follows a hive-authored PR onto the head the hive's own `require_current_base` refresh produced — a merge of the base by the App that leaves the PR's diff identical — so the reviewer route reads `decision_answered=true` instead of re-parking the PR at `stage/085-needs-decision`, and the review gate and hold guard accept the carried approval. Any other head change still supersedes the decision ([#15751](https://github.com/hivecommons/hive/issues/15751)).
103 changes: 103 additions & 0 deletions src/cmd/hive/hold_guard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -78,6 +79,15 @@ type holdGuardServer struct {
// (#14534: proving the merged parent of a hygiene merge is a base commit).
baseContains map[string]bool
compareCalls int

// commitBySHA serves GET /repos/{o}/{r}/commits/{sha}, pulls serves
// GET /repos/{o}/{r}/pulls/{n} and compareResult overrides the compare
// payload for "base...head" (#15649: the decision carry proves a head
// is the hive's own base refresh before accepting an approval on the
// previous head). Unknown SHAs and PRs are 404s.
commitBySHA map[string]map[string]any
pulls map[int]map[string]any
compareResult map[string]map[string]any
}

func (s *holdGuardServer) handler(t *testing.T) http.Handler {
Expand All @@ -89,12 +99,31 @@ func (s *holdGuardServer) handler(t *testing.T) http.Handler {
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/compare/"):
s.compareCalls++
spec := r.URL.Path[strings.Index(r.URL.Path, "/compare/")+len("/compare/"):]
if payload, ok := s.compareResult[spec]; ok {
_ = json.NewEncoder(w).Encode(payload)
return
}
_, head, _ := strings.Cut(spec, "...")
status := "diverged"
if s.baseContains[head] {
status = "behind"
}
_ = json.NewEncoder(w).Encode(map[string]any{"status": status})
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/commits/") && !strings.Contains(r.URL.Path, "/pulls/"):
sha := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]
commit, ok := s.commitBySHA[sha]
if !ok {
http.NotFound(w, r)
return
}
_ = json.NewEncoder(w).Encode(commit)
case r.Method == http.MethodGet && holdGuardPullPath.MatchString(r.URL.Path):
pr, ok := s.pulls[pathPRNumber(t, r.URL.Path)]
if !ok {
http.NotFound(w, r)
return
}
_ = json.NewEncoder(w).Encode(pr)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/commits"):
if s.failCommits {
http.Error(w, `{"message":"boom"}`, http.StatusInternalServerError)
Expand Down Expand Up @@ -190,6 +219,9 @@ func (s *holdGuardServer) handler(t *testing.T) http.Handler {
})
}

// holdGuardPullPath matches GET /repos/{o}/{r}/pulls/{n} and nothing under it.
var holdGuardPullPath = regexp.MustCompile(`/pulls/\d+$`)

func pathPRNumber(t *testing.T, path string) int {
t.Helper()
parts := strings.Split(path, "/")
Expand Down Expand Up @@ -1074,6 +1106,77 @@ func TestEnforceHoldGuardOperatorApprovalOnCurrentHeadAcceptsHiveLift(t *testing
}
}

// hivecommons/hive#15649: the operator approved the PR on head c1 and the
// hive's require_current_base gate then merged the base into the branch —
// a merge commit by the App that left the PR's diff untouched. That head
// change is the hive's own doing, so the approval follows the PR onto m1
// and the guard accepts the head. A merge by a person, or a refresh that
// changed the diff, is drift as before.
func TestEnforceHoldGuardOperatorApprovalCarriesOverHiveBaseRefresh(t *testing.T) {
files := func(blob string) []map[string]any {
return []map[string]any{{"filename": "deploy/monitoring.yaml", "status": "modified", "sha": blob, "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ " + blob}}
}
for _, tc := range []struct {
name, mergeAuthor, newBlob string
carried bool
}{
{name: "pure base refresh by the App", mergeAuthor: "kubestellar-hive[bot]", newBlob: "blob1", carried: true},
{name: "base merged by a person", mergeAuthor: "odttlnt", newBlob: "blob1"},
{name: "refresh that changed the diff", mergeAuthor: "kubestellar-hive[bot]", newBlob: "blob9"},
} {
t.Run(tc.name, func(t *testing.T) {
store := newTestHoldGuardStore(t)
decisions := swapHoldGuardHumanChangeRequests(t)
recordHoldGuardDecision(t, decisions, "c1", "clubanderson", review.HumanChangeRequestKindApprove)
fake := &holdGuardServer{commits: map[int][]map[string]any{
7: {ghCommit("c1", "odttlnt", "deploy: monitoring"), ghCommit("m1", tc.mergeAuthor, "Merge branch 'main' into deploy")},
}}
fake.timeline = map[int][]map[string]any{
7: gateLiftTimeline("sentinel-alert", "kubestellar-hive[bot]", "Bot", "2026-10-22T18:19:00Z"),
}
fake.pulls = map[int]map[string]any{7: {"number": 7, "head": map[string]any{"sha": "m1"}, "base": map[string]any{"ref": "main"}}}
fake.commitBySHA = map[string]map[string]any{"m1": {
"sha": "m1", "author": map[string]any{"login": tc.mergeAuthor}, "committer": map[string]any{"login": "web-flow"},
"parents": []map[string]any{{"sha": "c1"}, {"sha": "b1"}},
}}
fake.compareResult = map[string]map[string]any{
"main...c1": {"status": "ahead", "merge_base_commit": map[string]any{"sha": "b0"}, "files": files("blob1")},
"main...m1": {"status": "ahead", "merge_base_commit": map[string]any{"sha": "b1"}, "files": files(tc.newBlob)},
}
client := newHoldGuardClient(t, fake)
client.SetAppBotLogin("kubestellar-hive[bot]")
cfg := escalationTestConfig()
cfg.Dashboard.AuthorizedUsers = []string{"clubanderson:owner"}
store.Snapshot("acme/widgets", 7, "c1", []holdguard.Commit{{SHA: "c1", Author: "odttlnt"}})

got := enforceHoldGuard(context.Background(), cfg, client, client,
actionableWith(github.PullRequest{Repo: "widgets", Number: 7, Author: "odttlnt", HeadSHA: "m1"}), discardLogger())
if got["widgets/7"] == tc.carried {
t.Fatalf("re-review-gated=%v, want %v", got["widgets/7"], !tc.carried)
}
if tc.carried {
if len(fake.comments) != 0 || len(fake.labels) != 0 {
t.Fatalf("comments=%v labels=%v, want no drift comment and no re-hold", fake.comments, fake.labels)
}
if _, ok := store.Recorded("acme/widgets", 7); ok {
t.Fatal("snapshot must clear once the carried approval covers the head")
}
carried, ok := decisions.For("acme/widgets", 7, "m1")
if !ok || !carried.IsApproval() || carried.CarriedFromHead != "c1" || carried.Actor != "clubanderson" {
t.Fatalf("carried decision = %+v ok=%v", carried, ok)
}
return
}
if len(fake.labels) != 1 || fake.labels[0] != holdguard.ReHoldLabel {
t.Fatalf("labels=%v, want re-hold", fake.labels)
}
if _, ok := decisions.For("acme/widgets", 7, "c1"); !ok {
t.Fatal("the approval must stay on the head the person actually approved")
}
})
}
}

// The approval must name the head on the branch now: one recorded on the
// pre-push head, or by someone outside the merger tier, is not a review of
// the current tree and the drift path stands.
Expand Down
11 changes: 7 additions & 4 deletions src/cmd/hive/main_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,11 @@ var holdGuardHumanChangeRequests = func() review.HumanChangeRequestStore {
// the person reviewed the tree on the branch now, which the gate-lift
// timeline cannot show when the hive removed the label for them. Fails
// closed: no record, a change request, an unknown or untrusted actor, or an
// empty head never cover the head.
func holdGuardOperatorApproval(cfg *config.Config, repo string, number int, headSHA string) (string, bool) {
// empty head never cover the head. The one head change that does not
// supersede the record is the hive's own base refresh — a merge of the base
// branch by the App that leaves the PR's diff as the person saw it — which
// carries the approval onto the new head first (hivecommons/hive#15649).
func holdGuardOperatorApproval(ctx context.Context, cfg *config.Config, ghClient *github.Client, repo string, number int, headSHA string) (string, bool) {
headSHA = strings.TrimSpace(headSHA)
if cfg == nil || headSHA == "" {
return "", false
Expand All @@ -62,7 +65,7 @@ func holdGuardOperatorApproval(cfg *config.Config, repo string, number int, head
if store == nil {
return "", false
}
req, ok := store.For(repo, number, headSHA)
req, ok := ghClient.RecordedDecisionFor(ctx, store, repo, number, headSHA)
if !ok || !req.IsApproval() || !strings.EqualFold(strings.TrimSpace(req.HeadSHA), headSHA) {
return "", false
}
Expand Down Expand Up @@ -201,7 +204,7 @@ func enforceHoldGuard(
// gate label on their behalf, so the timeline below shows a hive
// lift that can never cover the head. The head-keyed approval by a
// trusted merger is the review the guard asks for: accept it.
if login, ok := holdGuardOperatorApproval(cfg, repo, pr.Number, pr.HeadSHA); ok {
if login, ok := holdGuardOperatorApproval(ctx, cfg, ghClient, repo, pr.Number, pr.HeadSHA); ok {
store.Clear(repo, pr.Number)
logger.Info("hold guard: current head approved by a trusted merger through the hive's decision record; head accepted",
"repo", repo, "pr", pr.Number,
Expand Down
21 changes: 21 additions & 0 deletions src/docs/hive-merge.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,27 @@ takes effect without a restart.
outcome becomes `human-approved` and the merge proceeds.
- **off**: no evaluation.

**A decision is head-scoped — except across the hive's own base refresh.**
A recorded operator decision (dashboard Approve, `/hive decision …`, a
hand-applied return label) names the exact head the person saw; a new head
is a new tree nobody has decided on, so the record is superseded and the
reviewer's `decision_requested` question stands again. The one head change
that does not supersede it is the hive's own `require_current_base` refresh:
a merge commit authored by the App whose parents are the decided head and a
commit on the base branch, and whose three-dot diff against the base is
file-for-file (name, status, blob, line counts, patch) identical to the
decided head's. Before any gate reads the new head — the reviewer-verdict
stage route, the automerge review gate, operator admission and the hold
guard — the decision is re-recorded on it with `carried_from_head` naming
the original, and one INFO line `decision carried over base refresh` is
logged; the reviewer route then reads `decision_answered=true` instead of
parking the PR at `stage/085-needs-decision` a second time
([#15751](https://github.com/hivecommons/hive/issues/15751), seen on #15649). A content push,
a merge by anyone but the App, a rebase, a refresh whose diff differs, and
GitHub review approvals (which are never moved between heads) all keep the
record where it was. The answer for a (PR, head) pair is memoised, so the
check costs one commit read and two compares per new head.

Each evaluation writes one audit line, action `review_evaluated`, detail
`lane=<self-merge|trusted-bot|trusted-author> would_hold=<bool> reason=<code> enforce=<bool> head=<sha>`,
plus `human_approver=<login> overrode=<swarm outcome>` when a human's
Expand Down
4 changes: 2 additions & 2 deletions src/pkg/github/automerge/automerge_contributor_adopt.go
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,7 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor
}
if forced {
c.info("stage labels: operator forced adoption; maintainer policy, admission and presence bypassed", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "by", forcedBy, "online", presence.Online, "policy", policy.maintainerPolicy())
} else if c.adoptionRefusedByAdmission(store, key, obs, requested, now) {
} else if c.adoptionRefusedByAdmission(ctx, store, key, obs, requested, now) {
return 0, nil
} else if held, deferred := c.maintainerHoldsAdoption(ctx, obs, policy, requested, now); held || deferred {
if held && !deferred {
Expand Down Expand Up @@ -830,7 +830,7 @@ func (c *Engine) supersedeAdoptedPR(ctx context.Context, store *stagelabels.Stor
rec.AdoptReason = reason
// A person's approval of this head travels to the copy
// (hivecommons/hive#15136 follow-up): adopting is not un-approving.
admittedBy := c.operatorAdmission(owner, repo, number, obs.HeadSHA)
admittedBy := c.operatorAdmission(ctx, owner, repo, number, obs.HeadSHA)
if stored, ok := store.Get(key); ok && stored.AdoptDiffFence != "" {
// A second takeover (dco-rehome, signoff-rehome, in-place-stalled)
// carries the fence the first adoption recorded.
Expand Down
2 changes: 1 addition & 1 deletion src/pkg/github/automerge/automerge_contributor_lane.go
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,7 @@ 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 != "" {
if login := c.operatorAdmission(ctx, owner, repo, pr.GetNumber(), pr.GetHead().GetSHA()); login != "" {
return contributorClaimMatch{OperatorLogin: login, ObservedTier: c.observedRegistryTier(author)}, nil
}
if tier := c.admittedRegistryTier(author, policy); tier != "" {
Expand Down
3 changes: 2 additions & 1 deletion src/pkg/github/automerge/automerge_decision_answered_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package automerge

import (
"context"
"testing"

"github.com/hivecommons/hive/pkg/review"
Expand Down Expand Up @@ -39,7 +40,7 @@ func TestFoldRecordedDecisionAnswersVerdictRoute(t *testing.T) {
{Lane: stageLaneSelf, Owner: "hivecommons", Repo: "hive", Number: 14628, HeadSHA: tc.head, Labels: tc.labels, Reason: contributorLaneReasonNoVerdict, Detail: stageDetail{VerdictKnown: true, Verdict: asked}},
{Lane: stageLaneContributor, Owner: "hivecommons", Repo: "hive", Number: 14628, HeadSHA: tc.head, Labels: tc.labels, Reason: contributorLaneReasonAppAuthored, Detail: stageDetail{VerdictKnown: true, Verdict: asked}},
}
c.foldRecordedDecision(list)
c.foldRecordedDecision(context.Background(), list)
got, _, obs := resolveStage(list)
if got.Stage != tc.wantStage || got.Reason != tc.wantReason {
t.Fatalf("stage=%s reason=%q (lane %s), want %s %q", got.Stage, got.Reason, obs.Lane, tc.wantStage, tc.wantReason)
Expand Down
52 changes: 52 additions & 0 deletions src/pkg/github/automerge/automerge_decision_carry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package automerge

import (
"context"
"strings"

hgithub "github.com/hivecommons/hive/pkg/github"
"github.com/hivecommons/hive/pkg/review"
)

// decisionCarrier is the engine's carrier of recorded operator decisions
// over the hive's own base refresh (hivecommons/hive#15649). nil when the
// engine has no REST client or App identity to verify the refresh with: a
// decision then stands only on the head it was recorded on, as before.
func (c *Engine) decisionCarrier() *hgithub.DecisionCarrier {
if c == nil || c.humanChangeRequests == nil || c.gh == nil || c.transport == nil {
return nil
}
app := strings.TrimSpace(c.transport.AppBotLogin())
if app == "" {
return nil
}
return &hgithub.DecisionCarrier{
Store: c.humanChangeRequests, API: c.gh.Repositories, AppBotLogin: app, Logger: c.logger, Checker: &c.baseRefresh,
ResolveBase: func(ctx context.Context, owner, repo string, number int) (string, error) {
pr, _, err := c.gh.PullRequests.Get(hgithub.WithRESTCaller(ctx, "hive:decision_base_refresh"), owner, repo, number)
if err != nil {
return "", err
}
return pr.GetBase().GetRef(), nil
},
}
}

// recordedDecisionFor is review.DecisionAnswerFor for head on
// owner/repo#number, carrying the PR's newest decision onto head first when
// head is nothing but the hive's base refresh of the head it was recorded
// on. baseRef may be "" when the caller does not know it.
func (c *Engine) recordedDecisionFor(ctx context.Context, owner, repo string, number int, baseRef, head string) (review.HumanChangeRequest, bool) {
if c == nil || c.humanChangeRequests == nil {
return review.HumanChangeRequest{}, false
}
fullRepo := owner + "/" + repo
if req, ok := review.DecisionAnswerFor(c.humanChangeRequests, fullRepo, number, head); ok {
return req, true
}
carrier := c.decisionCarrier()
if carrier == nil {
return review.HumanChangeRequest{}, false
}
return carrier.Carry(ctx, owner, repo, number, baseRef, head)
}
Loading
Loading