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
1 change: 1 addition & 0 deletions changelog.d/changed-signoff-unauthorized-upsert.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `hive:signoff-attribution` and `hive:unauthorized` notes are now one comment per PR (per blocked step for `unauthorized`), edited in place with a capped update history / attempt count when a new head hits the same block, instead of a fresh copy per push (hivecommons/hive#17066).
2 changes: 1 addition & 1 deletion src/docs/labels-and-control-signals/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,7 @@ Same exempt behavior as `do-not-merge`; wins over required-label admission. Defa

**Applies to:** PRs (issues when a step on one is blocked). **Kind:** Human-gated hold.

The hive's GitHub App was refused (`403 Resource not accessible by integration`) on an API call the lane needs to advance, so only a person can take the next step. First wired call site: approving held `action_required` workflow runs for a registry-trusted author needs `actions: write`, which an operator may decline to grant ([#14589](https://github.com/hivecommons/hive/issues/14589)). The lane reports `unauthorized:<step>` (`unauthorized:approve-workflow-runs`), the stage engine parks the PR at 085, one `<!-- hive:unauthorized head=<sha> step=<step> -->` comment names the missing permission, the exact human step (**Approve and run** on the checks banner or Actions tab, with the run ids) and the alternative of granting the permission, and the hive logs `lane unauthorized` once per head at INFO instead of a WARN per tick.
The hive's GitHub App was refused (`403 Resource not accessible by integration`) on an API call the lane needs to advance, so only a person can take the next step. First wired call site: approving held `action_required` workflow runs for a registry-trusted author needs `actions: write`, which an operator may decline to grant ([#14589](https://github.com/hivecommons/hive/issues/14589)). The lane reports `unauthorized:<step>` (`unauthorized:approve-workflow-runs`), the stage engine parks the PR at 085, one `<!-- hive:unauthorized step=<step> -->` comment per PR and step names the missing permission, the exact human step (**Approve and run** on the checks banner or Actions tab, with the run ids) and the alternative of granting the permission β€” a further head hitting the same block edits that comment with an attempt count and the heads it covers instead of posting again ([#17066](https://github.com/hivecommons/hive/issues/17066)) β€” and the hive logs `lane unauthorized` once per head at INFO instead of a WARN per tick.

The activity monitor draws a muted `unauthorized` pill (counted under Needs attention) whose tooltip repeats the permission and the step, and the 085 cell reads **Awaiting human: approve workflow runs**.

Expand Down
5 changes: 4 additions & 1 deletion src/docs/labels-and-control-signals/stage-labels.md
Original file line number Diff line number Diff line change
Expand Up @@ -573,9 +573,12 @@ lands on a non-App-authored branch (`review.fix_human_prs` does not authorize
one and the hive must not forge the author's `Signed-off-by`), so the PR
goes back to its author by kind under `hive-signoff-attribution`: `071` for
a human, `072` for a contributor agent β€” never `070`, where nothing can act. The human
gets one comment per head (`<!-- hive:signoff-attribution head=… -->`) with
gets one comment per PR (`<!-- hive:signoff-attribution -->`) with
the exact fix (`git commit --amend --reset-author -s && git push
--force-with-lease`, or the `git rebase --exec` form for several commits);
a new head rewrites that comment in place and appends an `updated …` line
(history capped at five) instead of posting another copy
([#17066](https://github.com/hivecommons/hive/issues/17066));
the contributor agent's regular 072 nudge carries the same ask. An adoption cannot
fix it by rewriting (the hive may not touch the contributor's authorship,
and a supersede would carry the same head), and the hive's own in-place fix
Expand Down
194 changes: 188 additions & 6 deletions src/pkg/github/automerge/automerge_contributor_held_runs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"fmt"
"net/http"
"net/url"
"reflect"
"slices"
"strings"
"testing"
Expand Down Expand Up @@ -265,7 +266,7 @@ func TestContributorLaneHeadRepoFallsBackToBase(t *testing.T) {
// reports.
func TestContributorLaneUnauthorizedWhenApproveForbidden(t *testing.T) {
wantReason := unauthorizedReasonPrefix + unauthorizedStepApproveWorkflowRuns
wantMarker := unauthorizedMarker("sha7", unauthorizedStepApproveWorkflowRuns)
wantMarker := unauthorizedMarker(unauthorizedStepApproveWorkflowRuns)
for _, tc := range []struct {
name string
// labelled pre-seeds hive:unauthorized and the marker comment on
Expand All @@ -288,7 +289,7 @@ func TestContributorLaneUnauthorizedWhenApproveForbidden(t *testing.T) {
fx.prComments = []map[string]any{{
"id": 5,
"user": map[string]string{"login": testHiveAppBotLogin},
"body": unauthorizedComment("sha7", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, "do it"),
"body": unauthorizedComment("sha7", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, "do it", unauthorizedAttempts{Count: 1, Heads: []string{"sha7"}}),
}}
}
api := newContributorLaneAPI(t, &fx)
Expand Down Expand Up @@ -432,21 +433,202 @@ func TestIsResourceNotAccessible(t *testing.T) {
}

func TestUnauthorizedCommentAndMarker(t *testing.T) {
marker := unauthorizedMarker("E3E9F5CABCDEF1234567", unauthorizedStepApproveWorkflowRuns)
if marker != "<!-- hive:unauthorized head=e3e9f5cabcdef1234567 step=approve-workflow-runs -->" {
marker := unauthorizedMarker(unauthorizedStepApproveWorkflowRuns)
if marker != "<!-- hive:unauthorized step=approve-workflow-runs -->" {
t.Fatalf("marker = %q", marker)
}
action := approveWorkflowRunsHumanAction("acme", "widget", "CI / Mutation (advisory)", []int64{40459320512, 40459320537})
body := unauthorizedComment("e3e9f5cabcdef1234567", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, action)
for _, want := range []string{marker, "`actions: write`", "approve workflow runs", "e3e9f5cabcdef", "Approve and run", "40459320512, 40459320537", "CI / Mutation (advisory)", "Actions tab of acme/widget"} {
first := unauthorizedAttempts{Count: 1, Heads: []string{"e3e9f5cabcdef1234567"}}
body := unauthorizedComment("E3E9F5CABCDEF1234567", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, action, first)
for _, want := range []string{marker, "`actions: write`", "approve workflow runs", "e3e9f5cabcdef", "Approve and run", "40459320512, 40459320537", "CI / Mutation (advisory)", "Actions tab of acme/widget", first.record()} {
if !strings.Contains(body, want) {
t.Fatalf("comment lacks %q:\n%s", want, body)
}
}
if !strings.HasPrefix(body, marker+"\n") {
t.Fatalf("comment must start with the marker line:\n%s", body)
}
if strings.Contains(body, "Attempt ") {
t.Fatalf("first attempt must not count itself:\n%s", body)
}
if got := parseUnauthorizedAttempts(body); !reflect.DeepEqual(got, first) {
t.Fatalf("parse(first) = %+v, want %+v", got, first)
}
second := unauthorizedComment("ffff", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, action, first.next("FFFF"))
if !strings.Contains(second, "<sub>Attempt 2: the same block hit heads `e3e9f5cabcde`, `ffff`.</sub>") || !strings.Contains(second, "for head `ffff`") {
t.Fatalf("second attempt:\n%s", second)
}
if got := unauthorizedReason(unauthorizedStepApproveWorkflowRuns); got != "unauthorized:approve-workflow-runs" {
t.Fatalf("reason = %q", got)
}
}

func TestParseUnauthorizedAttempts(t *testing.T) {
step := unauthorizedStepRerunSharedCI
for _, tc := range []struct {
name string
body string
want unauthorizedAttempts
match bool
}{
{
name: "current form with record",
body: unauthorizedMarker(step) + "\ntext\n" + unauthorizedAttempts{Count: 3, Heads: []string{"aaa", "bbb"}}.record() + "\n",
want: unauthorizedAttempts{Count: 3, Heads: []string{"aaa", "bbb"}},
match: true,
},
{
name: "legacy per-head marker counts as one attempt on that head",
body: unauthorizedLegacyMarker("D61D907", step) + "\nThe hive's GitHub App lacks `actions: write`…",
want: unauthorizedAttempts{Count: 1, Heads: []string{"d61d907"}},
match: true,
},
{
name: "current marker without record is one unknown attempt",
body: unauthorizedMarker(step) + "\ntext",
want: unauthorizedAttempts{Count: 1},
match: true,
},
{
name: "malformed count falls back to one",
body: unauthorizedMarker(step) + "\n" + unauthorizedAttemptsPrefix + "x heads=aaa" + unauthorizedAttemptsSuffix,
want: unauthorizedAttempts{Count: 1, Heads: []string{"aaa"}},
match: true,
},
{
name: "other step does not match",
body: unauthorizedMarker(unauthorizedStepApproveWorkflowRuns) + "\ntext",
want: unauthorizedAttempts{Count: 1},
match: false,
},
{
name: "legacy other step does not match",
body: unauthorizedLegacyMarker("aaa", unauthorizedStepApproveWorkflowRuns) + "\ntext",
want: unauthorizedAttempts{Count: 1, Heads: []string{"aaa"}},
match: false,
},
} {
t.Run(tc.name, func(t *testing.T) {
if got := isUnauthorizedCommentFor(step)(tc.body); got != tc.match {
t.Fatalf("match = %v, want %v", got, tc.match)
}
if got := parseUnauthorizedAttempts(tc.body); !reflect.DeepEqual(got, tc.want) {
t.Fatalf("parse = %+v, want %+v", got, tc.want)
}
})
}
}

func TestUnauthorizedAttemptsNextCapsHeads(t *testing.T) {
a := unauthorizedAttempts{Count: 1, Heads: []string{"h1"}}
for i := 2; i <= 8; i++ {
a = a.next(fmt.Sprintf("H%d", i))
}
if a.Count != 8 || !reflect.DeepEqual(a.Heads, []string{"h4", "h5", "h6", "h7", "h8"}) {
t.Fatalf("after 8 attempts: %+v", a)
}
if !a.covers("H8") || a.covers("h1") {
t.Fatalf("covers: %+v", a)
}
}

// TestCommentUnauthorizedUpsertsPerStep pins hivecommons/hive#17066: the
// hive:unauthorized note is one comment per PR and step. The same head is
// a no-op, a new head edits the note with the attempt count, a legacy
// per-head note is adopted rather than joined, and a different step gets
// its own note.
func TestCommentUnauthorizedUpsertsPerStep(t *testing.T) {
step := unauthorizedStepRerunSharedCI
for _, tc := range []struct {
name string
existing []map[string]any
heads []string
wantPosts int
wantEdits int
wantAttempt int
wantLast string
}{
{
name: "same head twice posts once",
heads: []string{"aaa", "aaa"},
wantPosts: 1,
wantEdits: 0,
wantAttempt: 1,
},
{
name: "three heads post once and edit twice",
heads: []string{"aaa", "bbb", "ccc"},
wantPosts: 1,
wantEdits: 2,
wantAttempt: 3,
wantLast: "<sub>Attempt 3: the same block hit heads `aaa`, `bbb`, `ccc`.</sub>",
},
{
name: "legacy per-head note is adopted in place",
existing: []map[string]any{{
"id": 5,
"user": map[string]string{"login": testHiveAppBotLogin},
"body": unauthorizedLegacyMarker("aaa", step) + "\nold text",
}},
heads: []string{"aaa", "bbb"},
wantPosts: 0,
wantEdits: 1,
wantAttempt: 2,
wantLast: "<sub>Attempt 2: the same block hit heads `aaa`, `bbb`.</sub>",
},
{
name: "a stranger's marker is not edited",
existing: []map[string]any{{
"id": 5,
"user": map[string]string{"login": "mallory"},
"body": unauthorizedMarker(step) + "\nforged",
}},
heads: []string{"aaa"},
wantPosts: 1,
wantEdits: 0,
wantAttempt: 1,
},
} {
t.Run(tc.name, func(t *testing.T) {
fx := validContributorFixture()
fx.prComments = tc.existing
api := newContributorLaneAPI(t, &fx)
defer api.Close()
clock := &contributorLaneClock{at: time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC)}
engine := newContributorLaneEngine(api.URL, defaultContributorLanePolicy(), clock, Options{})
for _, head := range tc.heads {
if err := engine.commentUnauthorized(context.Background(), "acme", "widget", 7, head, step, unauthorizedPermissionActionsWrite, "do it"); err != nil {
t.Fatalf("head %s: %v", head, err)
}
}
if fx.comments != tc.wantPosts || len(fx.commentEdits) != tc.wantEdits {
t.Fatalf("posts = %d edits = %d, want %d/%d\nedits: %q", fx.comments, len(fx.commentEdits), tc.wantPosts, tc.wantEdits, fx.commentEdits)
}
var notes []string
for _, c := range fx.prComments {
if body, _ := c["body"].(string); isUnauthorizedCommentFor(step)(body) && c["user"].(map[string]string)["login"] == testHiveAppBotLogin {
notes = append(notes, body)
}
}
if len(notes) != 1 {
t.Fatalf("own notes for step = %d, want 1: %q", len(notes), notes)
}
if got := parseUnauthorizedAttempts(notes[0]); got.Count != tc.wantAttempt {
t.Fatalf("attempts = %+v, want count %d", got, tc.wantAttempt)
}
if tc.wantLast != "" && !strings.Contains(notes[0], tc.wantLast) {
t.Fatalf("note lacks %q:\n%s", tc.wantLast, notes[0])
}
if !strings.HasPrefix(notes[0], unauthorizedMarker(step)+"\n") {
t.Fatalf("note not under the current marker:\n%s", notes[0])
}
// A different step is its own note.
if err := engine.commentUnauthorized(context.Background(), "acme", "widget", 7, "aaa", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, "click"); err != nil {
t.Fatal(err)
}
if fx.comments != tc.wantPosts+1 {
t.Fatalf("other step did not post its own note: posts = %d", fx.comments)
}
})
}
}
16 changes: 16 additions & 0 deletions src/pkg/github/automerge/automerge_contributor_lane_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ type contributorLaneFixture struct {
updates int
lastComment string
allComments []string
// commentEdits records the bodies written by PATCH /issues/comments/ID,
// which also rewrites the matching prComments entry.
commentEdits []string
// checkCompletedAt, when set, is the completed_at the check-runs
// endpoint reports for sha7 (RFC 3339); empty omits the field.
checkCompletedAt string
Expand Down Expand Up @@ -446,6 +449,19 @@ func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.S
"body": payload.Body,
})
json.NewEncoder(w).Encode(map[string]any{"id": 1000 + fx.comments})
case r.Method == http.MethodPatch && strings.HasPrefix(r.URL.Path, "/repos/acme/widget/issues/comments/"):
id, _ := strconv.ParseInt(strings.TrimPrefix(r.URL.Path, "/repos/acme/widget/issues/comments/"), 10, 64)
var payload struct {
Body string `json:"body"`
}
_ = json.NewDecoder(r.Body).Decode(&payload)
for _, c := range fx.prComments {
if cid, ok := c["id"]; ok && fmt.Sprint(cid) == strconv.FormatInt(id, 10) {
c["body"] = payload.Body
}
}
fx.commentEdits = append(fx.commentEdits, payload.Body)
json.NewEncoder(w).Encode(map[string]any{"id": id, "body": payload.Body})
case r.Method == http.MethodGet && otherPRCommentsNumber(r.URL.Path) > 0:
comments := fx.otherPRComments[otherPRCommentsNumber(r.URL.Path)]
if comments == nil {
Expand Down
44 changes: 0 additions & 44 deletions src/pkg/github/automerge/automerge_contributor_nudge.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,50 +342,6 @@ func (c *Engine) resolveNudge(ctx context.Context, rec stagelabels.Record, had b
c.contributorNudge.Resolve(ctx, obs.Owner, obs.Repo, obs.Number)
}

// SignoffAttributionMarkerPrefix opens the one comment a human author gets
// when their head is held for hive-signoff-attribution; the head keeps it
// idempotent per push.
const SignoffAttributionMarkerPrefix = "<!-- hive:signoff-attribution"

// SignoffAttributionComment renders the author-facing comment for a human
// PR parked at 071 on LaneReasonHiveSignoffAttribution: who owes the fix,
// why no agent can do it, and the exact commands.
func SignoffAttributionComment(n ContributorNudge, stage stagelabels.Stage) string {
var b strings.Builder
fmt.Fprintf(&b, "%s head=%s -->\n", SignoffAttributionMarkerPrefix, n.HeadSHA)
fmt.Fprintf(&b, "@%s this PR is back in your court (`%s`). ", n.Author, stage.Label())
b.WriteString("Its commits are signed off as the hive App rather than as you, so a squash merge would misattribute them and the sign-off attribution check stays red. No hive agent can rewrite a contributor's commits β€” the fix is yours:\n\n")
for _, a := range n.ReviewAsks {
fmt.Fprintf(&b, "- %s\n", a)
}
b.WriteString("\nOnce the new head lands, CI and the review swarm re-run automatically and the PR returns to the normal path.\n")
return b.String()
}

// nudgeSignoffAttribution posts SignoffAttributionComment once per head for
// a non-clanker author (a clanker gets the regular 072 nudge, which carries
// the same ask). It returns the number of comments posted.
func (c *Engine) nudgeSignoffAttribution(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, now time.Time) (int, error) {
rec, ok := store.Get(key)
if !ok || obs.Author == "" || obs.HeadSHA == "" || rec.NudgeHead == obs.HeadSHA {
return 0, nil
}
_, asks, _ := nudgeDiagnosis(obs.Reason, obs.Detail)
n := ContributorNudge{
Owner: obs.Owner, Repo: obs.Repo, Display: obs.Display, Number: obs.Number,
HeadSHA: obs.HeadSHA, Title: obs.Title, URL: obs.URL, Author: obs.Author, OpenedAt: obs.OpenedAt,
Reason: obs.Reason, ReviewAsks: asks, Nudge: 1,
}
body := SignoffAttributionComment(n, fixingStage(obs))
if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil {
c.warn("stage labels: sign-off attribution comment failed", "repo", obs.Display, "pr", obs.Number, "error", err)
return 0, err
}
store.MarkNudged(key, obs.HeadSHA, 1, false, now)
c.info("stage labels: author told to re-sign the head", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "squash_unsafe_hive", obs.Detail.DCOSquashUnsafeHive)
return 1, nil
}

// TrustedHuman071MarkerPrefix opens the one comment a trusted human author
// gets when their PR enters stage 071 (hivecommons/hive#13636); the head keeps
// it idempotent per push.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (c *Engine) workflowFenceReleased(ctx context.Context, displayRepo, owner,
if !ok {
return "", false
}
if hasCommentWithPrefix(comments, unauthorizedMarker(headSHA, unauthorizedStepMergeWorkflowPath)) {
if unauthorizedCommentCoversHead(comments, unauthorizedStepMergeWorkflowPath, headSHA) {
// A previous process already learnt the App cannot merge this head;
// re-arm the in-memory mark so the reason flips without another
// merge attempt.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ func TestContributorLaneWorkflowFenceMergeUnauthorizedFallback(t *testing.T) {
fx.prComments = []map[string]any{{
"id": 5,
"user": map[string]string{"login": testHiveAppBotLogin},
"body": unauthorizedComment("sha7", unauthorizedStepMergeWorkflowPath, unauthorizedPermissionWorkflowsWrite, "click"),
"body": unauthorizedComment("sha7", unauthorizedStepMergeWorkflowPath, unauthorizedPermissionWorkflowsWrite, "click", unauthorizedAttempts{Count: 1, Heads: []string{"sha7"}}),
}}
}
api := newContributorLaneAPI(t, &fx)
Expand Down Expand Up @@ -522,7 +522,7 @@ func TestContributorLaneWorkflowFenceMergeUnauthorizedFallback(t *testing.T) {
if !slices.Contains(fx.labels, unauthorizedLabel) {
t.Fatalf("labels = %v, want %q", fx.labels, unauthorizedLabel)
}
marker := unauthorizedMarker("sha7", unauthorizedStepMergeWorkflowPath)
marker := unauthorizedMarker(unauthorizedStepMergeWorkflowPath)
unauthorizedComments := 0
for _, body := range fx.allComments {
if strings.HasPrefix(body, marker) {
Expand Down
Loading
Loading