From 1c3f32d62e077ac742abb1b6f2fc70f0f00a9a6a Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:59:53 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=8C=B1=20automerge:=20upsert=20signof?= =?UTF-8?q?f-attribution=20and=20unauthorized=20comments=20instead=20of=20?= =?UTF-8?q?reposting=20per=20head?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hive:signoff-attribution becomes one comment per PR under a stable marker, rewritten in place on a new head with an 'updated …' history capped at five lines. hive:unauthorized becomes one comment per PR and blocked step; a new head hitting the same block edits it with an attempt count and the heads it covers. Legacy per-head comments are adopted and upgraded in place. workflowFenceReleased reads head coverage from the upserted note. Fixes #17066 Signed-off-by: Andrew Anderson --- .../changed-signoff-unauthorized-upsert.md | 1 + .../labels-and-control-signals/reference.md | 2 +- .../stage-labels.md | 5 +- .../automerge_contributor_held_runs_test.go | 194 +++++++++++++++++- .../automerge_contributor_lane_test.go | 16 ++ .../automerge/automerge_contributor_nudge.go | 44 ---- ...automerge_contributor_workflow_approval.go | 2 +- ...erge_contributor_workflow_approval_test.go | 4 +- .../automerge/automerge_marker_upsert.go | 123 +++++++++++ .../automerge_signoff_attribution.go | 126 ++++++++++++ .../automerge_signoff_attribution_test.go | 177 ++++++++++++++++ .../automerge/automerge_stage_labels.go | 3 +- .../automerge/automerge_stage_labels_test.go | 2 +- .../automerge/automerge_unauthorized.go | 169 +++++++++++++-- 14 files changed, 793 insertions(+), 75 deletions(-) create mode 100644 changelog.d/changed-signoff-unauthorized-upsert.md create mode 100644 src/pkg/github/automerge/automerge_marker_upsert.go create mode 100644 src/pkg/github/automerge/automerge_signoff_attribution.go create mode 100644 src/pkg/github/automerge/automerge_signoff_attribution_test.go diff --git a/changelog.d/changed-signoff-unauthorized-upsert.md b/changelog.d/changed-signoff-unauthorized-upsert.md new file mode 100644 index 0000000000..acd6485d95 --- /dev/null +++ b/changelog.d/changed-signoff-unauthorized-upsert.md @@ -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). diff --git a/src/docs/labels-and-control-signals/reference.md b/src/docs/labels-and-control-signals/reference.md index bff63274c7..fb920febef 100644 --- a/src/docs/labels-and-control-signals/reference.md +++ b/src/docs/labels-and-control-signals/reference.md @@ -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:` (`unauthorized:approve-workflow-runs`), the stage engine parks the PR at 085, one `` 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:` (`unauthorized:approve-workflow-runs`), the stage engine parks the PR at 085, one `` 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**. diff --git a/src/docs/labels-and-control-signals/stage-labels.md b/src/docs/labels-and-control-signals/stage-labels.md index 54052572a9..92c16796a0 100644 --- a/src/docs/labels-and-control-signals/stage-labels.md +++ b/src/docs/labels-and-control-signals/stage-labels.md @@ -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 (``) with +gets one comment per PR (``) 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 diff --git a/src/pkg/github/automerge/automerge_contributor_held_runs_test.go b/src/pkg/github/automerge/automerge_contributor_held_runs_test.go index b31434424e..8eaeb9ffd6 100644 --- a/src/pkg/github/automerge/automerge_contributor_held_runs_test.go +++ b/src/pkg/github/automerge/automerge_contributor_held_runs_test.go @@ -11,6 +11,7 @@ import ( "fmt" "net/http" "net/url" + "reflect" "slices" "strings" "testing" @@ -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 @@ -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) @@ -432,13 +433,14 @@ func TestIsResourceNotAccessible(t *testing.T) { } func TestUnauthorizedCommentAndMarker(t *testing.T) { - marker := unauthorizedMarker("E3E9F5CABCDEF1234567", unauthorizedStepApproveWorkflowRuns) - if marker != "" { + marker := unauthorizedMarker(unauthorizedStepApproveWorkflowRuns) + if marker != "" { 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) } @@ -446,7 +448,187 @@ func TestUnauthorizedCommentAndMarker(t *testing.T) { 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, "Attempt 2: the same block hit heads `e3e9f5cabcde`, `ffff`.") || !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: "Attempt 3: the same block hit heads `aaa`, `bbb`, `ccc`.", + }, + { + 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: "Attempt 2: the same block hit heads `aaa`, `bbb`.", + }, + { + 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) + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_lane_test.go b/src/pkg/github/automerge/automerge_contributor_lane_test.go index f012261d7b..c60ed61224 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane_test.go +++ b/src/pkg/github/automerge/automerge_contributor_lane_test.go @@ -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 @@ -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 { diff --git a/src/pkg/github/automerge/automerge_contributor_nudge.go b/src/pkg/github/automerge/automerge_contributor_nudge.go index a4e132fbd6..ed1ee58f43 100644 --- a/src/pkg/github/automerge/automerge_contributor_nudge.go +++ b/src/pkg/github/automerge/automerge_contributor_nudge.go @@ -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 = "\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. diff --git a/src/pkg/github/automerge/automerge_contributor_workflow_approval.go b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go index 9d4697fa4c..53cd13f3d8 100644 --- a/src/pkg/github/automerge/automerge_contributor_workflow_approval.go +++ b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go @@ -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. diff --git a/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go b/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go index 3c661e4c21..e21fd93000 100644 --- a/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go +++ b/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go @@ -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) @@ -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) { diff --git a/src/pkg/github/automerge/automerge_marker_upsert.go b/src/pkg/github/automerge/automerge_marker_upsert.go new file mode 100644 index 0000000000..494b200e0d --- /dev/null +++ b/src/pkg/github/automerge/automerge_marker_upsert.go @@ -0,0 +1,123 @@ +package automerge + +// One marker comment per PR, edited in place (hivecommons/hive#17066). +// +// Several lane notes used to key their marker on the head SHA so a new push +// got a fresh copy: on a long-lived PR with many pushes that meant eight +// `hive:signoff-attribution` and five `hive:unauthorized` comments saying +// the same thing (hivecommons/hive#16524). The claim ledger +// (hivecommons/hive#16433) showed the quieter shape: find the hive's own +// comment carrying the marker and rewrite it, which notifies nobody, and +// keep a short, capped "updated" history inside the comment so a reader +// who saw the earlier wording knows what changed. + +import ( + "context" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" +) + +const ( + // markerHistoryCap bounds the "updated" lines kept inside an upserted + // comment: the five most recent, oldest dropped first. + markerHistoryCap = 5 + // markerHistoryHeading opens the history block; every line after it + // that starts with markerHistoryBullet is one history entry. + markerHistoryHeading = "Updates (newest last):" + markerHistoryBullet = "- " + // markerHistoryTimeLayout is the timestamp a history line carries. + markerHistoryTimeLayout = "2006-01-02 15:04 UTC" +) + +// findOwnMarkerComment returns the most recent comment on owner/repo#number +// that match accepts and that one of the hive's own accounts wrote, or nil +// when none exists. Only the hive's App login counts as its own: anyone can +// type a marker, and the hive must never edit a stranger's comment. When +// the hive cannot name its App login, any author is accepted — the same +// fallback the sentinel's marker reads use. +func (c *Engine) findOwnMarkerComment(ctx context.Context, owner, repo string, number int, match func(body string) bool) (*gh.IssueComment, error) { + if c == nil || c.gh == nil || match == nil { + return nil, nil + } + comments, err := c.listIssueComments(ctx, owner, repo, number) + if err != nil { + return nil, err + } + app := "" + if c.transport != nil { + app = normalizeBotLogin(c.transport.AppBotLogin()) + } + var found *gh.IssueComment + for _, cm := range comments { + if cm == nil || !match(cm.GetBody()) { + continue + } + if app != "" && normalizeBotLogin(cm.GetUser().GetLogin()) != app { + continue + } + found = cm + } + return found, nil +} + +// editMarkerComment rewrites the hive's own comment id with body. An edit +// notifies nobody, which is the point. +func (c *Engine) editMarkerComment(ctx context.Context, owner, repo string, id int64, body string) error { + _, _, err := c.gh.Issues.EditComment(ctx, owner, repo, id, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated + return err +} + +// splitMarkerHistory separates an upserted comment body into the part +// before the history block and the history lines themselves (without the +// bullet). A body with no history block returns itself and nil. +func splitMarkerHistory(body string) (core string, history []string) { + idx := strings.Index(body, markerHistoryHeading) + if idx < 0 { + return strings.TrimRight(body, "\n"), nil + } + core = strings.TrimRight(body[:idx], "\n") + for _, line := range strings.Split(body[idx+len(markerHistoryHeading):], "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, markerHistoryBullet) { + history = append(history, strings.TrimPrefix(line, markerHistoryBullet)) + } + } + return core, history +} + +// appendMarkerHistory adds line to history, dropping the oldest entries so +// at most markerHistoryCap remain. +func appendMarkerHistory(history []string, line string) []string { + history = append(history, line) + if len(history) > markerHistoryCap { + history = history[len(history)-markerHistoryCap:] + } + return history +} + +// markerHistoryLine renders one history entry: the time, then what changed. +func markerHistoryLine(at time.Time, change string) string { + return "updated " + at.UTC().Format(markerHistoryTimeLayout) + ": " + change +} + +// renderMarkerHistory appends the history block to core; no history means +// core alone. +func renderMarkerHistory(core string, history []string) string { + core = strings.TrimRight(core, "\n") + "\n" + if len(history) == 0 { + return core + } + var b strings.Builder + b.WriteString(core) + b.WriteString("\n") + b.WriteString(markerHistoryHeading) + b.WriteString("\n") + for _, h := range history { + b.WriteString(markerHistoryBullet) + b.WriteString(h) + b.WriteString("\n") + } + return b.String() +} diff --git a/src/pkg/github/automerge/automerge_signoff_attribution.go b/src/pkg/github/automerge/automerge_signoff_attribution.go new file mode 100644 index 0000000000..81bc33ad5c --- /dev/null +++ b/src/pkg/github/automerge/automerge_signoff_attribution.go @@ -0,0 +1,126 @@ +package automerge + +// The sign-off attribution note, one per PR (hivecommons/hive#17066). +// +// A human whose head is held for hive-signoff-attribution gets told once +// with the exact commands. The note used to carry the head in its marker +// so every push re-posted it; now the PR carries one note that a new head +// rewrites in place, with a short capped history of what changed. + +import ( + "context" + "fmt" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// SignoffAttributionMarkerPrefix opens the one comment a human author gets +// when their head is held for hive-signoff-attribution. Comments from +// before hivecommons/hive#17066 carry ` head=` after it; the upsert +// adopts the latest of those and rewrites it under SignoffAttributionMarker. +const SignoffAttributionMarkerPrefix = "" + +// isSignoffAttributionComment reports whether body is a sign-off +// attribution note, in either the current or the per-head legacy form. +func isSignoffAttributionComment(body string) bool { + return strings.HasPrefix(body, SignoffAttributionMarkerPrefix) +} + +// 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. history is the capped +// list of earlier rewrites (nil on first post). +func SignoffAttributionComment(n ContributorNudge, stage stagelabels.Stage, history []string) string { + return renderMarkerHistory(signoffAttributionCore(n, stage), history) +} + +// signoffAttributionCore is the comment without its history block: the +// part whose change triggers a rewrite. +func signoffAttributionCore(n ContributorNudge, stage stagelabels.Stage) string { + var b strings.Builder + b.WriteString(SignoffAttributionMarker) + b.WriteString("\n") + 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) + } + fmt.Fprintf(&b, "\nOnce the new head lands, CI and the review swarm re-run automatically and the PR returns to the normal path. Current head: `%s`.\n", shortSHA(n.HeadSHA)) + return b.String() +} + +// signoffAttributionChange is the history line for a rewrite on a new head. +func signoffAttributionChange(headSHA string, hiveSigned int) string { + if hiveSigned <= 0 { + hiveSigned = 1 + } + plural := "s" + if hiveSigned == 1 { + plural = "" + } + return fmt.Sprintf("head `%s`, %d commit%s signed off as the hive App", shortSHA(headSHA), hiveSigned, plural) +} + +// nudgeSignoffAttribution tells a non-clanker author once per PR that the +// head needs re-signing (a clanker gets the regular 072 nudge, which +// carries the same ask). The first head posts the comment; a later head +// rewrites it in place and appends one history line. It returns the number +// of comments posted (an edit counts zero). +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, + } + stage := fixingStage(obs) + existing, err := c.findOwnMarkerComment(ctx, obs.Owner, obs.Repo, obs.Number, isSignoffAttributionComment) + if err != nil { + // A list failure reads as "none": the note is posted rather than lost. + c.warn("stage labels: could not list comments for the sign-off attribution upsert", "repo", obs.Display, "pr", obs.Number, "error", err) + } + if existing != nil { + body, changed := signoffAttributionRewrite(existing.GetBody(), n, stage, obs.Detail.DCOSquashUnsafeHive, now) + if changed { + if err := c.editMarkerComment(ctx, obs.Owner, obs.Repo, existing.GetID(), body); err != nil { + c.warn("stage labels: sign-off attribution comment edit failed", "repo", obs.Display, "pr", obs.Number, "error", err) + return 0, err + } + c.info("stage labels: sign-off attribution note updated in place", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "squash_unsafe_hive", obs.Detail.DCOSquashUnsafeHive) + } + store.MarkNudged(key, obs.HeadSHA, 1, false, now) + return 0, nil + } + body := SignoffAttributionComment(n, stage, nil) + 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 +} + +// signoffAttributionRewrite is the body that replaces previous for the +// observation n (hiveSigned commits carry the App's sign-off), and whether +// it differs. The history gains one line only when the core text (asks, +// head) changed; an identical ask on the same head leaves the comment alone. +func signoffAttributionRewrite(previous string, n ContributorNudge, stage stagelabels.Stage, hiveSigned int, now time.Time) (string, bool) { + prevCore, history := splitMarkerHistory(previous) + core := signoffAttributionCore(n, stage) + if strings.TrimRight(core, "\n") == prevCore { + return previous, false + } + history = appendMarkerHistory(history, markerHistoryLine(now, signoffAttributionChange(n.HeadSHA, hiveSigned))) + return renderMarkerHistory(core, history), true +} diff --git a/src/pkg/github/automerge/automerge_signoff_attribution_test.go b/src/pkg/github/automerge/automerge_signoff_attribution_test.go new file mode 100644 index 0000000000..f0c45d4c2c --- /dev/null +++ b/src/pkg/github/automerge/automerge_signoff_attribution_test.go @@ -0,0 +1,177 @@ +package automerge + +// One sign-off attribution note per PR (hivecommons/hive#17066). + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +func TestMarkerHistoryRoundTrip(t *testing.T) { + at := time.Date(2026, 11, 4, 12, 4, 0, 0, time.UTC) + for _, tc := range []struct { + name string + body string + wantCore string + wantHist []string + }{ + {name: "no history", body: "\nbody\n", wantCore: "\nbody"}, + { + name: "two lines", + body: renderMarkerHistory("\nbody", []string{"updated a", "updated b"}), + wantCore: "\nbody", + wantHist: []string{"updated a", "updated b"}, + }, + { + name: "stray text after the heading is ignored", + body: "\nbody\n\n" + markerHistoryHeading + "\nnot a bullet\n- kept\n", + wantCore: "\nbody", + wantHist: []string{"kept"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + core, hist := splitMarkerHistory(tc.body) + if core != tc.wantCore || strings.Join(hist, "|") != strings.Join(tc.wantHist, "|") { + t.Fatalf("split = %q / %q, want %q / %q", core, hist, tc.wantCore, tc.wantHist) + } + }) + } + var hist []string + for i := 1; i <= markerHistoryCap+2; i++ { + hist = appendMarkerHistory(hist, markerHistoryLine(at.Add(time.Duration(i)*time.Minute), fmt.Sprintf("change %d", i))) + } + if len(hist) != markerHistoryCap || hist[0] != "updated 2026-11-04 12:07 UTC: change 3" || hist[markerHistoryCap-1] != "updated 2026-11-04 12:11 UTC: change 7" { + t.Fatalf("capped history = %q", hist) + } +} + +func TestSignoffAttributionRewrite(t *testing.T) { + now := time.Date(2026, 11, 4, 12, 4, 59, 0, time.UTC) + stage := stagelabels.NeedsAuthor + nudge := func(head string, hiveSigned int) ContributorNudge { + _, asks, _ := nudgeDiagnosis(stagelabels.LaneReasonHiveSignoffAttribution, stageDetail{DCOTotal: hiveSigned, DCOSquashUnsafeHive: hiveSigned}) + return ContributorNudge{Author: "clubanderson", HeadSHA: head, ReviewAsks: asks} + } + first := SignoffAttributionComment(nudge("eb40422ae63967eb7363a3f866e73121c58f2c1b", 8), stage, nil) + legacy := strings.Replace(first, SignoffAttributionMarker, SignoffAttributionMarkerPrefix+" head=eb40422ae63967eb7363a3f866e73121c58f2c1b -->", 1) + fiveDeep := first + for i := 1; i <= 5; i++ { + fiveDeep, _ = signoffAttributionRewrite(fiveDeep, nudge(fmt.Sprintf("%040d", i), 8), stage, 8, now.Add(time.Duration(i)*time.Minute)) + } + for _, tc := range []struct { + name string + previous string + head string + hiveSigned int + wantChanged bool + wantLines int + wantLast string + }{ + {name: "same head and asks leave the note alone", previous: first, head: "eb40422ae63967eb7363a3f866e73121c58f2c1b", hiveSigned: 8}, + { + name: "new head rewrites and records one line", previous: first, head: "2940830726b72f08dff5a1ef6a37bff871b4a7d5", hiveSigned: 20, + wantChanged: true, wantLines: 1, wantLast: "updated 2026-11-04 12:04 UTC: head `2940830726b7`, 20 commits signed off as the hive App", + }, + { + name: "legacy per-head note is adopted under the stable marker", previous: legacy, head: "2940830726b72f08dff5a1ef6a37bff871b4a7d5", hiveSigned: 1, + wantChanged: true, wantLines: 1, wantLast: "updated 2026-11-04 12:04 UTC: head `2940830726b7`, 1 commit signed off as the hive App", + }, + { + name: "history stays capped at five", previous: fiveDeep, head: "dc8ccef2b084b5860f317dacc5037071d78bc1b6", hiveSigned: 30, + wantChanged: true, wantLines: markerHistoryCap, wantLast: "updated 2026-11-04 12:04 UTC: head `dc8ccef2b084`, 30 commits signed off as the hive App", + }, + } { + t.Run(tc.name, func(t *testing.T) { + body, changed := signoffAttributionRewrite(tc.previous, nudge(tc.head, tc.hiveSigned), stage, tc.hiveSigned, now) + if changed != tc.wantChanged { + t.Fatalf("changed = %v, want %v\n%s", changed, tc.wantChanged, body) + } + if !changed { + if body != tc.previous { + t.Fatalf("unchanged rewrite altered the body:\n%s", body) + } + return + } + if !strings.HasPrefix(body, SignoffAttributionMarker+"\n") || strings.Contains(body, " head=") { + t.Fatalf("body not under the stable marker:\n%s", body) + } + if !strings.Contains(body, "Current head: `"+shortSHA(tc.head)+"`.") { + t.Fatalf("body does not name the current head:\n%s", body) + } + _, hist := splitMarkerHistory(body) + if len(hist) != tc.wantLines || hist[len(hist)-1] != tc.wantLast { + t.Fatalf("history = %q, want %d lines ending %q", hist, tc.wantLines, tc.wantLast) + } + if again, changedAgain := signoffAttributionRewrite(body, nudge(tc.head, tc.hiveSigned), stage, tc.hiveSigned, now.Add(time.Hour)); changedAgain || again != body { + t.Fatalf("second pass on the same head rewrote again:\n%s", again) + } + }) + } +} + +// TestApplyStageLabelsSignoffAttributionUpsertsAcrossHeads pins the +// hivecommons/hive#16524 shape: eight pushes used to mean eight notes. Now +// the first head posts, each later head edits the same comment, and a +// repeat sweep on an already-noted head writes nothing. +func TestApplyStageLabelsSignoffAttributionUpsertsAcrossHeads(t *testing.T) { + hiveCommit := stageCommitFixture{ + message: "Add OWNERS file\n\nSigned-off-by: Andy Anderson <280983584+hivecommons-hive[bot]@users.noreply.github.com>", + authorLogin: testHiveAppBotLogin, + authorName: "Andy Anderson", + authorEmail: "280983584+hivecommons-hive[bot]@users.noreply.github.com", + } + api := &stageAPI{labels: map[string]string{}, statefulComments: true, commitDetails: map[int][]stageCommitFixture{16524: {hiveCommit}}} + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 11, 4, 3, 1, 0, 0, time.UTC)} + e, _, store := newStageEngine(t, srv.URL, clock) + e.stageLabelPolicy = func() StageLabelPolicy { return StageLabelPolicy{Enabled: true, ContributorNudge: true} } + + sweep := func(head string, labels ...string) { + t.Helper() + pr := stagePR(16524, labels...) + pr.Head.SHA = gh.Ptr(head) + pr.User = &gh.User{Login: gh.Ptr("clubanderson")} + e.recordStage(stageLaneTrusted, "acme/widget", "acme", "widget", pr, autoMergeReasonReviewGatePrefix+ReviewGateOutcomeAwaiting, false, nil) + e.noteStageRole("acme", "widget", 16524, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(context.Background()); err != nil { + t.Fatal(err) + } + rec, ok := store.Get(stageKey("acme", "widget", 16524)) + if !ok || rec.Reason != stagelabels.LaneReasonHiveSignoffAttribution || rec.NudgeHead != head { + t.Fatalf("head %s: record %+v ok=%v", head, rec, ok) + } + } + held := []string{"role/trusted", "author/human", stagelabels.DCOLabel, "stage/071-needs-author"} + + sweep("eb40422", "role/trusted") + if len(api.comments) != 1 || len(api.commentEdits) != 0 { + t.Fatalf("first head: comments %q edits %q", api.comments, api.commentEdits) + } + for i, head := range []string{"d61d907", "2940830", "7879a51"} { + clock.at = clock.at.Add(10 * time.Minute) + sweep(head, held...) + if len(api.comments) != 1 || len(api.commentEdits) != i+1 { + t.Fatalf("head %s: comments %q edits %q", head, api.comments, api.commentEdits) + } + last := api.commentEdits[i] + if !strings.HasPrefix(last, SignoffAttributionMarker+"\n") || !strings.Contains(last, "Current head: `"+head+"`.") { + t.Fatalf("head %s: edit not the upserted note:\n%s", head, last) + } + if _, hist := splitMarkerHistory(last); len(hist) != i+1 || !strings.Contains(hist[i], "head `"+head+"`, 1 commit signed off as the hive App") { + t.Fatalf("head %s: history %q", head, hist) + } + } + // Same head, next sweep: nothing is written. + clock.at = clock.at.Add(10 * time.Minute) + sweep("7879a51", held...) + if len(api.comments) != 1 || len(api.commentEdits) != 3 { + t.Fatalf("repeat sweep wrote: comments %q edits %q", api.comments, api.commentEdits) + } +} diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 13eef2c7fb..6ef7008b8b 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -1431,7 +1431,8 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) } } else if obs.Reason == stagelabels.LaneReasonHiveSignoffAttribution { // A person owns the fix and nothing else will tell them: - // one comment per head with the exact commands. + // one comment per PR with the exact commands, rewritten + // in place on a new head (hivecommons/hive#17066). n, err := c.nudgeSignoffAttribution(ctx, store, key, obs, now) result.Comments += n if err != nil && firstErr == nil { diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index b0f8ed9ac8..fd2736be1c 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -2247,7 +2247,7 @@ func TestApplyStageLabelsHiveBotSignoffOnHumanHeadNeedsAuthorWithInstructions(t if len(api.comments) != 1 { t.Fatalf("comments %q", api.comments) } - for _, want := range []string{SignoffAttributionMarkerPrefix + " head=sha -->", "@clubanderson", "`stage/071-needs-author`", "git commit --amend --reset-author -s && git push --force-with-lease", "git config user.email"} { + for _, want := range []string{SignoffAttributionMarker + "\n", "Current head: `sha`.", "@clubanderson", "`stage/071-needs-author`", "git commit --amend --reset-author -s && git push --force-with-lease", "git config user.email"} { if !strings.Contains(api.comments[0], want) { t.Fatalf("comment lacks %q:\n%s", want, api.comments[0]) } diff --git a/src/pkg/github/automerge/automerge_unauthorized.go b/src/pkg/github/automerge/automerge_unauthorized.go index 6313cc1451..a872bf1ff8 100644 --- a/src/pkg/github/automerge/automerge_unauthorized.go +++ b/src/pkg/github/automerge/automerge_unauthorized.go @@ -9,7 +9,7 @@ package automerge // sits at its previous reason (`required-check-missing:`) looking like // CI is merely slow while the sweep WARNs every tick. The owner's decision is // to say so plainly instead of widening the App: the lane marks the PR -// `unauthorized` — label hive:unauthorized, one comment per head naming the +// `unauthorized` — label hive:unauthorized, one comment per step naming the // missing permission and the exact human step, reason `unauthorized:` // so the stage engine parks it at 085 and the tracker's pill column shows // the word — and clears all of it in the same tick the step stops being @@ -23,6 +23,7 @@ import ( "fmt" "net/http" "net/url" + "slices" "strconv" "strings" @@ -41,9 +42,9 @@ const ( // label on first use so it does not appear in GitHub's random colour. unauthorizedLabelColor = "6e7781" unauthorizedLabelDescription = "The hive's GitHub App lacks the permission for the next step; a maintainer must take it (see the hive:unauthorized comment)" - // unauthorizedMarkerPrefix tags the one comment per head; the marker - // carries the head and the step so a new push, or a different blocked - // step, gets a fresh note while the same head never gets two. + // unauthorizedMarkerPrefix tags the one comment per (PR, step); a + // different blocked step gets its own note while a new push rewrites + // the existing one with the attempt count. unauthorizedMarkerPrefix = "" +} + +// unauthorizedLegacyMarker is the per-head first line comments carried +// before hivecommons/hive#17066; the upsert adopts the latest one. +func unauthorizedLegacyMarker(headSHA, step string) string { return unauthorizedMarkerPrefix + " head=" + strings.ToLower(headSHA) + " step=" + step + " -->" } +// unauthorizedAttemptsPrefix / unauthorizedAttemptsSuffix frame the hidden +// line that records the attempt count and the heads the note covers: +// +// +const ( + unauthorizedAttemptsPrefix = "" + // unauthorizedHeadsCap bounds the heads the note remembers; the + // attempt count keeps growing past it. + unauthorizedHeadsCap = markerHistoryCap +) + +// unauthorizedAttempts is the state an existing note carries. +type unauthorizedAttempts struct { + Count int + Heads []string +} + +// isUnauthorizedCommentFor reports whether body is the hive:unauthorized +// note for step, in either the current or the per-head legacy form. +func isUnauthorizedCommentFor(step string) func(body string) bool { + marker := unauthorizedMarker(step) + suffix := " step=" + step + " -->" + return func(body string) bool { + first, _, _ := strings.Cut(body, "\n") + if first == marker { + return true + } + return strings.HasPrefix(first, unauthorizedMarkerPrefix+" head=") && strings.HasSuffix(first, suffix) + } +} + +// parseUnauthorizedAttempts reads the attempt state from an existing note. +// A legacy per-head note counts as one attempt on the head its marker +// names; a note with no record counts as one attempt on no known head. +func parseUnauthorizedAttempts(body string) unauthorizedAttempts { + for _, line := range strings.Split(body, "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, unauthorizedAttemptsPrefix) || !strings.HasSuffix(line, unauthorizedAttemptsSuffix) { + continue + } + fields := strings.Fields(strings.TrimSuffix(strings.TrimPrefix(line, unauthorizedAttemptsPrefix), unauthorizedAttemptsSuffix)) + if len(fields) == 0 { + break + } + n, err := strconv.Atoi(fields[0]) + if err != nil || n < 1 { + n = 1 + } + out := unauthorizedAttempts{Count: n} + for _, f := range fields[1:] { + if heads, ok := strings.CutPrefix(f, "heads="); ok { + for _, h := range strings.Split(heads, ",") { + if h = strings.ToLower(strings.TrimSpace(h)); h != "" { + out.Heads = append(out.Heads, h) + } + } + } + } + return out + } + first, _, _ := strings.Cut(body, "\n") + if rest, ok := strings.CutPrefix(first, unauthorizedMarkerPrefix+" head="); ok { + head, _, _ := strings.Cut(rest, " ") + if head != "" { + return unauthorizedAttempts{Count: 1, Heads: []string{strings.ToLower(head)}} + } + } + return unauthorizedAttempts{Count: 1} +} + +// covers reports whether the note already names headSHA. +func (a unauthorizedAttempts) covers(headSHA string) bool { + return slices.Contains(a.Heads, strings.ToLower(headSHA)) +} + +// next is the state after one more attempt on headSHA: the count grows and +// the head joins the remembered set (oldest dropped past the cap). +func (a unauthorizedAttempts) next(headSHA string) unauthorizedAttempts { + heads := append(slices.Clone(a.Heads), strings.ToLower(headSHA)) + if len(heads) > unauthorizedHeadsCap { + heads = heads[len(heads)-unauthorizedHeadsCap:] + } + return unauthorizedAttempts{Count: a.Count + 1, Heads: heads} +} + +// record renders the hidden attempt line. +func (a unauthorizedAttempts) record() string { + return unauthorizedAttemptsPrefix + strconv.Itoa(a.Count) + " heads=" + strings.Join(a.Heads, ",") + unauthorizedAttemptsSuffix +} + // unauthorizedComment is the comment body: the marker, then the permission -// the App lacks, the step it therefore cannot take, and what a person does. -func unauthorizedComment(headSHA, step, permission, humanAction string) string { - return fmt.Sprintf("%s\nThe hive's GitHub App lacks `%s`, so it cannot %s for head `%s`. %s Hive will resume automatically once the step is done; this label and note clear themselves.", - unauthorizedMarker(headSHA, step), permission, strings.ReplaceAll(step, "-", " "), shortSHA(headSHA), strings.TrimSpace(humanAction)) +// the App lacks, the step it therefore cannot take and what a person does, +// then the attempt record. A first attempt shows no count; later ones say +// how many heads have hit the same block. +func unauthorizedComment(headSHA, step, permission, humanAction string, attempts unauthorizedAttempts) string { + var b strings.Builder + fmt.Fprintf(&b, "%s\nThe hive's GitHub App lacks `%s`, so it cannot %s for head `%s`. %s Hive will resume automatically once the step is done; this label and note clear themselves.", + unauthorizedMarker(step), permission, strings.ReplaceAll(step, "-", " "), shortSHA(headSHA), strings.TrimSpace(humanAction)) + if attempts.Count > 1 { + short := make([]string, 0, len(attempts.Heads)) + for _, h := range attempts.Heads { + short = append(short, "`"+shortSHA(h)+"`") + } + fmt.Fprintf(&b, "\n\nAttempt %d: the same block hit heads %s.", attempts.Count, strings.Join(short, ", ")) + } + b.WriteString("\n") + b.WriteString(attempts.record()) + b.WriteString("\n") + return b.String() } -// commentUnauthorized posts the note once per (head, step): an existing -// marker on the PR, or a prior effects claim, suppresses it. +// unauthorizedCommentCoversHead reports whether comments carry the hive's +// note for step naming headSHA: a previous process already learnt the App +// cannot take the step on this head. +func unauthorizedCommentCoversHead(comments []*gh.IssueComment, step, headSHA string) bool { + match := isUnauthorizedCommentFor(step) + for _, comment := range comments { + if comment == nil || !match(comment.GetBody()) { + continue + } + if parseUnauthorizedAttempts(comment.GetBody()).covers(headSHA) { + return true + } + } + return false +} + +// commentUnauthorized keeps one note per (PR, step): a note already naming +// this head is left alone; a note for an earlier head is rewritten in place +// with the attempt count; no note posts one through the effects claim. func (c *Engine) commentUnauthorized(ctx context.Context, owner, repo string, number int, headSHA, step, permission, humanAction string) error { - comments, err := c.listIssueComments(ctx, owner, repo, number) + existing, err := c.findOwnMarkerComment(ctx, owner, repo, number, isUnauthorizedCommentFor(step)) if err != nil { return err } - marker := unauthorizedMarker(headSHA, step) - for _, comment := range comments { - if comment != nil && strings.HasPrefix(comment.GetBody(), marker) { + if existing != nil { + attempts := parseUnauthorizedAttempts(existing.GetBody()) + if attempts.covers(headSHA) { return nil } + return c.editMarkerComment(ctx, owner, repo, existing.GetID(), unauthorizedComment(headSHA, step, permission, humanAction, attempts.next(headSHA))) } - body := unauthorizedComment(headSHA, step, permission, humanAction) + marker := unauthorizedMarker(step) + body := unauthorizedComment(headSHA, step, permission, humanAction, unauthorizedAttempts{Count: 1, Heads: []string{strings.ToLower(headSHA)}}) _, err = effects.Execute(ctx, c.mutation, effects.Claim{ Repo: owner + "/" + repo, Kind: effects.KindIssueComment, From e1a967d4dde14e253aec021fdd5136c6d64961d2 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 14:10:34 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=8C=B1=20automerge:=20fix=20capped-hi?= =?UTF-8?q?story=20test=20heads;=20move=20nudge=20raw-write=20baseline=20l?= =?UTF-8?q?ine=20to=20the=20signoff=20file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sign-off attribution CreateComment moved files unchanged (2→1 in the nudge file, 1 in automerge_signoff_attribution.go); the test heads used %040d, whose 12-char short SHA was identical for every head. Signed-off-by: Andrew Anderson --- .../github/automerge/automerge_signoff_attribution_test.go | 4 ++-- src/pkg/writeback/testdata/direct-writes-baseline.txt | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/pkg/github/automerge/automerge_signoff_attribution_test.go b/src/pkg/github/automerge/automerge_signoff_attribution_test.go index f0c45d4c2c..d667527d1e 100644 --- a/src/pkg/github/automerge/automerge_signoff_attribution_test.go +++ b/src/pkg/github/automerge/automerge_signoff_attribution_test.go @@ -61,8 +61,8 @@ func TestSignoffAttributionRewrite(t *testing.T) { first := SignoffAttributionComment(nudge("eb40422ae63967eb7363a3f866e73121c58f2c1b", 8), stage, nil) legacy := strings.Replace(first, SignoffAttributionMarker, SignoffAttributionMarkerPrefix+" head=eb40422ae63967eb7363a3f866e73121c58f2c1b -->", 1) fiveDeep := first - for i := 1; i <= 5; i++ { - fiveDeep, _ = signoffAttributionRewrite(fiveDeep, nudge(fmt.Sprintf("%040d", i), 8), stage, 8, now.Add(time.Duration(i)*time.Minute)) + for i := 1; i <= markerHistoryCap; i++ { + fiveDeep, _ = signoffAttributionRewrite(fiveDeep, nudge(strings.Repeat(fmt.Sprint(i), 40), 8), stage, 8, now.Add(time.Duration(i)*time.Minute)) } for _, tc := range []struct { name string diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index 7b66f292e9..201a0d5521 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -9,11 +9,12 @@ raw pkg/github/automerge/automerge_bot_takeover.go 2 raw pkg/github/automerge/automerge_contributor_adopt.go 15 raw pkg/github/automerge/automerge_contributor_held_runs.go 1 raw pkg/github/automerge/automerge_contributor_lane.go 3 -raw pkg/github/automerge/automerge_contributor_nudge.go 2 +raw pkg/github/automerge/automerge_contributor_nudge.go 1 raw pkg/github/automerge/automerge_contributor_workflow_approval.go 1 raw pkg/github/automerge/automerge_held_runs.go 3 raw pkg/github/automerge/automerge_merge_commit.go 1 raw pkg/github/automerge/automerge_merge_forward.go 1 +raw pkg/github/automerge/automerge_signoff_attribution.go 1 raw pkg/github/automerge/automerge_stage_human.go 1 raw pkg/github/automerge/automerge_stage_labels.go 3 raw pkg/github/automerge/automerge_sweep_queued.go 3