diff --git a/src/changelog.d/added-merge-issue-author-credit.md b/src/changelog.d/added-merge-issue-author-credit.md new file mode 100644 index 0000000000..ffcea66106 --- /dev/null +++ b/src/changelog.d/added-merge-issue-author-credit.md @@ -0,0 +1 @@ +- Every hive-performed merge (self-authored, trusted-author, contributor-lane and queue sweeps, `hive-merge` relay) now credits the human authors of the issues the PR closes: `Co-authored-by: ` trailers are appended to the squash (or merge) commit message, so a reporter whose issue an external clanker fixed shows on the contributor graph the way hive-opened PRs already did. Bots, the PR author and logins the branch already credits are skipped; branch commit bodies and `Signed-off-by` lines are preserved ahead of the trailers; the logins are recorded as `issue_authors=` on the merge audit entry and in review-evidence `merge.issue_authors`. One cached `GET /issues/{n}` per newly referenced issue. Switch: `auto_merge.credit_issue_authors` (default on) (#14581). diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 895ae88a87..47f1210d50 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -10274,6 +10274,9 @@ func installReviewRelaySettings(client *github.Client, cfg *config.Config, logge client.SetReviewEvidence(func(repo string) github.ReviewEvidenceSettings { return reviewEvidenceSettings(cfg, repo) }) + // hivecommons/hive#14581: issue-author credit on every merge path, read + // live so a reload of auto_merge.credit_issue_authors applies. + client.SetCreditIssueAuthors(func(string) bool { return cfg.AutoMerge.CreditIssueAuthorsEnabled() }) // hivecommons/hive#13241: an issue a person reopens after its closing PR // merged is a change failure on that PR's evidence record, from both the // issues.reopened webhook and the enumeration reopen check. diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index af4d382946..6b2beb20da 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -557,6 +557,38 @@ unattended (for example `mrbobbytables`): A claim keeps the tier the contributor held when it was taken, so grant the tier before the issue is leased. +### Issue-author credit at merge time + +Every merge the hive performs — the self-authored, trusted-author, +contributor-lane and queue sweeps as well as `hive-merge` relay requests — +credits the humans who opened the issues the PR closes. The merge reads the +closing references the PR already carries (`Fixes|Closes|Resolves #N` in the +body) and resolves each referenced issue's author with at most one +`GET /issues/{n}` per newly seen issue, cached for the life of the process +(attributed as `hive:merge_credit` in the API-quota ledger). Bots and Apps +(`type=Bot`, `[bot]`/`-bot` suffixes, `github-actions*`), the PR author +themself, and issues that are really PRs are skipped; the remaining logins are +de-duplicated and appended as `Co-authored-by: +` trailers to the squash commit message. A +`merge-method/merge` PR gets the trailer on the merge commit instead; a rebase +merge has no commit to carry it and is left alone. + +`Co-authored-by` is the trailer GitHub counts toward the contributor graph, so +a reporter whose issue was fixed by someone else's clanker shows up on the +repository's contributors page rather than only in the issue timeline. It is +purely additive: the branch's own commit subjects, bodies and `Signed-off-by` +lines are reproduced unchanged ahead of the new trailers, so the squash +sign-off gate and `check-squash-signoff-attribution.sh` see exactly what they +saw before plus the credit. This is the single mechanism: a hive-opened PR +already carries the trailer on its commits (`issue-coauthor.sh`, +`hive-open-pr`), and the merge recognises an existing trailer for the same +login (by noreply address or login) and does not add a duplicate. The credited +logins are recorded on the merge audit entry (`issue_authors=`) and in the PR's +review-evidence `merge.issue_authors`, so dashboards and DIBS statistics can +report them. If the branch's commits cannot be read at merge time, the hive +falls back to GitHub's default message rather than risk dropping a sign-off. +Switch it off with `auto_merge.credit_issue_authors: false` (#14581). + ### Stage labels Every sweep cycle also writes the hive-owned `stage/NNN-*` label for each PR diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 9f494b9ee1..647344df07 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -427,6 +427,7 @@ advanced into the merge path. | `auto_merge.require_current_base` | unset (off) | Repo list (`owner/repo`) whose App self-merge, trusted-author and contributor lanes only merge a head that contains the current base tip. A green head tested against an older base is updated with GitHub update-branch (a merge commit; no author commit is rewritten) and merges once CI is green on the new head, so a semantic conflict with work merged since turns that PR red instead of breaking the base (#13634). Costs one compare call per merge candidate. | | `auto_merge.merge_forward_trusted_human` | unset (off) | Repo list (`owner/repo`) where a `role/trusted` + `author/human` PR on a same-repo branch that GitHub reports as conflicting (`dirty`) gets the base merged into its head as one App-authored, signed-off merge commit via the GitHub merges API (no human commit is rewritten), then merges once CI is green on the new head. A real conflict pushes nothing and posts one `` note naming the files both sides changed. Fork heads are never written. Attempted once per head (#13636). | | `auto_merge.squash_only` | unset (no repo) | Repo list (`owner/repo`) whose branch policy forbids merge commits. Elsewhere, a `role/trusted` PR whose head mixes the contributor's commits with App-linked, App-signed ones (the hive's own in-place adoption fixes), every commit self-signed, is labelled `merge-method/merge` and merged with a merge commit instead of parking at `stage/085` as `adoption-stalled:hive-signoff-attribution`; a listed repo keeps squash-only policy and re-homes an in-place adoption to an App-authored superseder instead (#13975). | +| `auto_merge.credit_issue_authors` | `true` | Append `Co-authored-by: ` for the human authors of the issues a PR closes (`Fixes|Closes|Resolves #N`) to the squash (or merge) commit message on every hive-performed merge, so reporters land on the contributor graph when an external clanker fixed their issue. Bots, the PR author and logins already credited on the branch are skipped; the logins are recorded as `issue_authors=` on the merge audit entry and in review evidence. One cached `GET /issues/{n}` per newly referenced issue. `false` leaves GitHub's default squash message untouched (#14581). | | `auto_merge.bot_takeover.enabled` | `true` | When `github-actions[bot]` is in `auto_merge.trusted_bot_authors`, re-author its same-repo PRs whose required `pull_request` checks can never run (the bot opened them with a workflow `GITHUB_TOKEN`). After the head is older than both `min_head_age` and 30 minutes with no `pull_request` run, the App pushes the same change as one signed-off commit to `hive/takeover-`, opens a PR with the original title/body plus `Supersedes #`, comments `Superseded by #N` on the bot PR and closes it. One attempt per bot head SHA. See [hive-merge.md](hive-merge.md#github-actionsbot-pr-takeover). | | `auto_merge.trusted_authors.enabled` | `false` | Enables the opt-in human-authored PR tier: Hive may merge a green PR only when the author already holds the required hive role and, by default, GitHub push/maintain/admin permission on that repo. | | `auto_merge.trusted_authors.repos` | empty = all watched repos | Optional repo allow-list for the trusted-author tier. The dashboard renders this as a watched-repo multi-select; selecting nothing preserves the all-repos default. | diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 004f74c68f..d0ba3eea72 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:4662-4676`, descending `AgeMinutes`). + (`RankActionableIssues`, `src/pkg/github/client.go:4676-4686`, descending `AgeMinutes`). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index ac6c2ea530..32486a529b 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -7661,6 +7661,22 @@ type AutoMergeConfig struct { // squash-only repo the lane keeps the squash convention and the PR goes // back to its author (or, adopted, to stage/085 naming this policy). SquashOnly []string `yaml:"squash_only,omitempty" json:"squash_only,omitempty"` + // CreditIssueAuthors puts `Co-authored-by: ` on the commit + // the hive's merge lands for every human who opened an issue the PR + // closes (`Fixes|Closes|Resolves #N`), minus the PR author, skipping + // bots, and never duplicating a trailer the branch already carries + // (hivecommons/hive#14581). The credit is additive — the PR author + // still authors the squash, every Signed-off-by is kept — and reaches + // the PRs external clankers open, which bypass the hive's own + // open-time attribution. nil/unset means ON; `credit_issue_authors: + // false` sends the merge with GitHub's default message as before. + CreditIssueAuthors *bool `yaml:"credit_issue_authors,omitempty" json:"credit_issue_authors,omitempty"` +} + +// CreditIssueAuthorsEnabled reports the auto_merge.credit_issue_authors +// switch; unset is on. +func (a AutoMergeConfig) CreditIssueAuthorsEnabled() bool { + return a.CreditIssueAuthors == nil || *a.CreditIssueAuthors } // AutoMergeRepoConfig carries per-repository auto-merge overrides. diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 536a284075..b9a31d2d45 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -139,6 +139,7 @@ agents..variables..type # TODO #11854 agents..variables..url # TODO #11854 agents..variables..value # TODO #11854 agents.github_api_hourly_cap # TODO #11854 +auto_merge.credit_issue_authors # merge-time Co-authored-by credit (#14581); yaml-only auto_merge.allow_unprotected_base[] # TODO #11854 auto_merge.human_merge_paths. # TODO #11854 auto_merge.merge_forward_trusted_human[] # TODO #11854 diff --git a/src/pkg/evidence/evidence.go b/src/pkg/evidence/evidence.go index 284d749a13..5dd35b87bb 100644 --- a/src/pkg/evidence/evidence.go +++ b/src/pkg/evidence/evidence.go @@ -187,6 +187,10 @@ type MergeEvent struct { At time.Time `json:"at"` SHA string `json:"sha"` OpenedAt time.Time `json:"opened_at,omitzero"` + // IssueAuthors are the human authors of the issues the PR closed whom + // the merge credited (hivecommons/hive#14581): the Co-authored-by the + // hive put on the landing commit, or that the branch already carried. + IssueAuthors []string `json:"issue_authors,omitempty"` } // Shadow records what shadow-mode gates would have done for the head SHA. diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 1ba2fcf169..c830945d50 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -1317,13 +1317,11 @@ func (c *Engine) trySweepContributorLanePR(ctx context.Context, displayRepo, own return AutoMergeSweepEvent{}, refused, nil } + mergeMessage, mergeOpts := c.mergeOptions(ctx, owner, repo, eval.pr, headSHA, method) var mergeResult *gh.PullRequestMergeResult mergeOut, err := c.executeMergeEffect(ctx, mergeClaim, owner, repo, number, func(ctx context.Context) (effects.Result, error) { var apiErr error - mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, "", &gh.PullRequestOptions{ - SHA: headSHA, - MergeMethod: method, - }) + mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, mergeMessage, mergeOpts) if apiErr != nil { return effects.Result{}, mergeAPIErrorNotApplied(apiErr) } diff --git a/src/pkg/github/automerge/automerge_contributor_lane_test.go b/src/pkg/github/automerge/automerge_contributor_lane_test.go index 2b433a4693..65d4eec226 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane_test.go +++ b/src/pkg/github/automerge/automerge_contributor_lane_test.go @@ -106,6 +106,20 @@ type contributorLaneFixture struct { // approveStatus, when set, is the status every approve returns. approvedRuns []int64 approveStatus int + // issueAuthor is who GET issues/42 reports as the linked issue's + // author (hivecommons/hive#14581); empty serves the PR author, so the + // merge credits nobody and sends GitHub's default message. + issueAuthor string + issueAuthorID int64 + issueAuthorType string + issueStatus int + issueGets int + // commitMessages are the branch commits GET pulls/7/commits serves; + // nil serves one signed commit. + commitMessages []string + commitLists int + // mergeBody is the JSON body of the last PUT pulls/7/merge. + mergeBody map[string]any } func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.Server { @@ -219,6 +233,35 @@ func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.S sha = fx.recheckHeadSHA } json.NewEncoder(w).Encode(pull(sha)) + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/issues/42": + fx.issueGets++ + if fx.issueStatus != 0 { + http.Error(w, "issue error", fx.issueStatus) + return + } + issueAuthor := fx.issueAuthor + if issueAuthor == "" { + issueAuthor = author + } + userType := fx.issueAuthorType + if userType == "" { + userType = "User" + } + json.NewEncoder(w).Encode(map[string]any{ + "number": 42, "state": "open", + "user": map[string]any{"login": issueAuthor, "id": fx.issueAuthorID, "type": userType}, + }) + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7/commits": + fx.commitLists++ + msgs := fx.commitMessages + if msgs == nil { + msgs = []string{"Fix the widget\n\nSigned-off-by: " + author + " <" + author + "@example.com>"} + } + commits := make([]map[string]any, 0, len(msgs)) + for i, msg := range msgs { + commits = append(commits, map[string]any{"sha": fmt.Sprintf("c%d", i), "commit": map[string]any{"message": msg}, "parents": []map[string]any{{"sha": "p"}}}) + } + json.NewEncoder(w).Encode(commits) case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/issues/42/comments": if fx.issueCommentsSt != 0 { http.Error(w, "comments error", fx.issueCommentsSt) @@ -258,6 +301,8 @@ func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.S json.NewEncoder(w).Encode(map[string]any{"sha": "sha7", "committer": map[string]string{"name": "c", "date": fx.headCommittedAt}}) case r.Method == http.MethodPut && r.URL.Path == "/repos/acme/widget/pulls/7/merge": fx.merges++ + fx.mergeBody = map[string]any{} + _ = json.NewDecoder(r.Body).Decode(&fx.mergeBody) if fx.mergeStatus != 0 { w.WriteHeader(fx.mergeStatus) msg := fx.mergeMessage diff --git a/src/pkg/github/automerge/automerge_merge_credit.go b/src/pkg/github/automerge/automerge_merge_credit.go new file mode 100644 index 0000000000..ad1b057519 --- /dev/null +++ b/src/pkg/github/automerge/automerge_merge_credit.go @@ -0,0 +1,38 @@ +package automerge + +import ( + "context" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" +) + +// Issue-author credit on the sweep's merges (hivecommons/hive#14581): every +// lane builds its merge request through mergeOptions, which asks the +// transport's MergeCreditor for the Co-authored-by trailers naming the human +// authors of the issues the PR closes and stashes the decision so the +// pr_merged audit and the evidence merge event can name them. A transport +// without a creditor (test stubs, no API client) merges exactly as before. + +type mergeCreditTransport interface { + MergeCreditor() *hgithub.MergeCreditor + NoteMergeCredit(repo string, number int, credit hgithub.MergeCredit) +} + +// mergeOptions returns the commit message and options for merging pr's +// head at headSHA with method. The message is "" (GitHub's default) unless +// the repo credits issue authors and the PR has one to credit. +func (c *Engine) mergeOptions(ctx context.Context, owner, repo string, pr *gh.PullRequest, headSHA, method string) (string, *gh.PullRequestOptions) { + opts := &gh.PullRequestOptions{SHA: headSHA, MergeMethod: method} + mt, ok := c.transport.(mergeCreditTransport) + if !ok || pr == nil { + return "", opts + } + creditor := mt.MergeCreditor() + if !creditor.Enabled(owner + "/" + repo) { + return "", opts + } + credit := creditor.Prepare(ctx, owner, repo, pr, method) + mt.NoteMergeCredit(owner+"/"+repo, pr.GetNumber(), credit) + return credit.CommitMessage, opts +} diff --git a/src/pkg/github/automerge/automerge_merge_credit_test.go b/src/pkg/github/automerge/automerge_merge_credit_test.go new file mode 100644 index 0000000000..b26eaa6238 --- /dev/null +++ b/src/pkg/github/automerge/automerge_merge_credit_test.go @@ -0,0 +1,135 @@ +package automerge + +// Issue-author credit at merge time (hivecommons/hive#14581): the sweep's +// merge request carries `Co-authored-by: ` for the humans who +// opened the issues the PR closes, the branch's own trailers are kept, a +// trailer the branch already carries is not duplicated, and the switch +// turns the whole thing off. + +import ( + "context" + "strings" + "testing" + "time" + + hgithub "github.com/hivecommons/hive/pkg/github" +) + +func TestContributorLaneMergeCreditsIssueAuthor(t *testing.T) { + fx := validContributorFixture() + fx.issueAuthor, fx.issueAuthorID = "Danathar", 12345 + fx.commitMessages = []string{ + "Fix the widget\n\nSigned-off-by: " + contributorLaneTestAuthor + " <" + contributorLaneTestAuthor + "@example.com>", + "Address review\n\nSigned-off-by: " + contributorLaneTestAuthor + " <" + contributorLaneTestAuthor + "@example.com>", + } + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + clock := &contributorLaneClock{at: time.Date(2026, 10, 15, 13, 0, 0, 0, time.UTC)} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock)}) + if _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy); err != nil || reason != "" { + t.Fatalf("reason=%q err=%v, want merge", reason, err) + } + if fx.merges != 1 { + t.Fatalf("merges = %d, want 1", fx.merges) + } + got, _ := fx.mergeBody["commit_message"].(string) + want := "* Fix the widget\n\nSigned-off-by: " + contributorLaneTestAuthor + " <" + contributorLaneTestAuthor + "@example.com>\n\n" + + "* Address review\n\nSigned-off-by: " + contributorLaneTestAuthor + " <" + contributorLaneTestAuthor + "@example.com>\n\n" + + "Co-authored-by: Danathar <12345+Danathar@users.noreply.github.com>" + if got != want { + t.Fatalf("squash commit_message =\n%s\nwant\n%s", got, want) + } + if fx.mergeBody["merge_method"] != "squash" || fx.mergeBody["sha"] != "sha7" { + t.Fatalf("merge request lost its method/sha: %+v", fx.mergeBody) + } + if strings.Count(got, "Signed-off-by:") != 2 { + t.Fatalf("branch sign-offs not preserved:\n%s", got) + } + if fx.issueGets != 1 || fx.commitLists != 1 { + t.Fatalf("issue GETs = %d, commit lists = %d; want one each", fx.issueGets, fx.commitLists) + } +} + +func TestContributorLaneMergeCreditOff(t *testing.T) { + fx := validContributorFixture() + fx.issueAuthor, fx.issueAuthorID = "Danathar", 12345 + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + clock := &contributorLaneClock{at: time.Date(2026, 10, 15, 13, 0, 0, 0, time.UTC)} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock)}) + engine.transport.(*hgithub.Client).SetCreditIssueAuthors(func(string) bool { return false }) + if _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy); err != nil || reason != "" { + t.Fatalf("reason=%q err=%v, want merge", reason, err) + } + if _, has := fx.mergeBody["commit_message"]; has || fx.merges != 1 { + t.Fatalf("credit off: merge body %+v (merges %d), want GitHub's default message", fx.mergeBody, fx.merges) + } + if fx.issueGets != 0 || fx.commitLists != 0 { + t.Fatalf("credit off still read issue (%d) / commits (%d)", fx.issueGets, fx.commitLists) + } +} + +// A PR author who filed their own issue is not their own co-author, and the +// merge then sends no message at all (no commit read either). +func TestContributorLaneMergeCreditSkipsSelf(t *testing.T) { + fx := validContributorFixture() + fx.issueAuthor = contributorLaneTestAuthor + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + clock := &contributorLaneClock{at: time.Date(2026, 10, 15, 13, 0, 0, 0, time.UTC)} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock)}) + if _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy); err != nil || reason != "" { + t.Fatalf("reason=%q err=%v, want merge", reason, err) + } + if _, has := fx.mergeBody["commit_message"]; has || fx.commitLists != 0 { + t.Fatalf("self-filed issue: merge body %+v (commit lists %d)", fx.mergeBody, fx.commitLists) + } +} + +// The self-authored lane: a hive-opened PR already carries the trailer from +// issue-coauthor.sh, so the merge adds nothing; a hive PR whose branch lacks +// it gains it. +func TestSelfAuthoredSweepMergeCredit(t *testing.T) { + for _, tc := range []struct { + name string + commits []string + want string + }{ + { + name: "branch already credits the issue author", + commits: []string{"Fix\n\nSigned-off-by: hive[bot] \nCo-authored-by: Dana Thar <12345+Danathar@users.noreply.github.com>"}, + }, + { + name: "branch lacks the trailer", + commits: []string{"Fix\n\nSigned-off-by: hive[bot] "}, + want: "Signed-off-by: hive[bot] \n\nCo-authored-by: Danathar <12345+Danathar@users.noreply.github.com>", + }, + } { + t.Run(tc.name, func(t *testing.T) { + merges := 0 + var mergeBody map[string]any + fx := selfSweepFixture{ + body: testIntentLinkedBody, + mergeApplied: true, + mergeCalls: &merges, + issueAuthor: "Danathar", + issueAuthorID: 12345, + commitMessages: tc.commits, + mergeBody: &mergeBody, + } + api := newSelfSweepGuardAPI(t, fx) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + if _, reason, err := c.trySweepSelfAuthoredPR(context.Background(), "acme/widget", "acme", "widget", 7, true); err != nil || reason != "" { + t.Fatalf("trySweepSelfAuthoredPR = (reason %q, err %v), want merge", reason, err) + } + got, _ := mergeBody["commit_message"].(string) + if merges != 1 || got != tc.want { + t.Fatalf("merges = %d, commit_message = %q, want %q", merges, got, tc.want) + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 31a79f0c1b..bad9269684 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -1787,13 +1787,11 @@ func (c *Engine) trySweepSelfAuthoredPR(ctx context.Context, displayRepo, owner, return AutoMergeSweepEvent{}, refused, nil } + mergeMessage, mergeOpts := c.mergeOptions(ctx, owner, repo, current, evaluatedHeadSHA, method) var mergeResult *gh.PullRequestMergeResult mergeOut, err := c.executeMergeEffect(ctx, mergeClaim, owner, repo, number, func(ctx context.Context) (effects.Result, error) { var apiErr error - mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, "", &gh.PullRequestOptions{ - SHA: evaluatedHeadSHA, - MergeMethod: method, - }) + mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, mergeMessage, mergeOpts) if apiErr != nil { return effects.Result{}, mergeAPIErrorNotApplied(apiErr) } @@ -2184,13 +2182,11 @@ func (c *Engine) trySweepTrustedAuthorPR(ctx context.Context, displayRepo, owner return AutoMergeSweepEvent{}, refused, nil } + mergeMessage, mergeOpts := c.mergeOptions(ctx, owner, repo, current, headSHA, method) var mergeResult *gh.PullRequestMergeResult mergeOut, err := c.executeMergeEffect(ctx, mergeClaim, owner, repo, number, func(ctx context.Context) (effects.Result, error) { var apiErr error - mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, "", &gh.PullRequestOptions{ - SHA: headSHA, - MergeMethod: method, - }) + mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, mergeMessage, mergeOpts) if apiErr != nil { return effects.Result{}, mergeAPIErrorNotApplied(apiErr) } @@ -2532,13 +2528,11 @@ func (c *Engine) trySweepQueuedPR(ctx context.Context, displayRepo, owner, repo return AutoMergeSweepEvent{}, refused, nil } + mergeMessage, mergeOpts := c.mergeOptions(ctx, owner, repo, pr, headSHA, method) var mergeResult *gh.PullRequestMergeResult mergeOut, err := c.executeMergeEffect(ctx, mergeClaim, owner, repo, number, func(ctx context.Context) (effects.Result, error) { var apiErr error - mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, "", &gh.PullRequestOptions{ - SHA: headSHA, - MergeMethod: method, - }) + mergeResult, _, apiErr = c.gh.PullRequests.Merge(ctx, owner, repo, number, mergeMessage, mergeOpts) if apiErr != nil { return effects.Result{}, mergeAPIErrorNotApplied(apiErr) } diff --git a/src/pkg/github/automerge/automerge_sweep_guards_test.go b/src/pkg/github/automerge/automerge_sweep_guards_test.go index 23efaed3e2..670c4f36ac 100644 --- a/src/pkg/github/automerge/automerge_sweep_guards_test.go +++ b/src/pkg/github/automerge/automerge_sweep_guards_test.go @@ -10,9 +10,11 @@ package automerge import ( "context" "encoding/json" + "fmt" hgithub "github.com/hivecommons/hive/pkg/github" "net/http" "net/http/httptest" + "strings" "testing" gh "github.com/google/go-github/v72/github" @@ -45,6 +47,14 @@ type selfSweepFixture struct { mergeCalls *int // incremented on every PUT .../merge // reviews is the PR review list; nil serves an empty list. reviews []map[string]any + // Issue-author credit (hivecommons/hive#14581): issueAuthor is who the + // linked issue's GET reports as its author (default: a bot, so the + // merge credits nobody); commitMessages are the branch commits served + // for the squash body; mergeBody receives the last merge request body. + issueAuthor string + issueAuthorID int64 + commitMessages []string + mergeBody *map[string]any } func newSelfSweepGuardAPI(t *testing.T, fx selfSweepFixture) *httptest.Server { @@ -137,10 +147,26 @@ func newSelfSweepGuardAPI(t *testing.T, fx selfSweepFixture) *httptest.Server { runs = append(runs, map[string]string{"name": "build", "status": "completed", "conclusion": "success"}) } json.NewEncoder(w).Encode(map[string]any{"total_count": len(runs), "check_runs": runs}) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/acme/widget/issues/") && !strings.Contains(strings.TrimPrefix(r.URL.Path, "/repos/acme/widget/issues/"), "/"): + user := map[string]any{"login": "linker[bot]", "id": 1, "type": "Bot"} + if fx.issueAuthor != "" { + user = map[string]any{"login": fx.issueAuthor, "id": fx.issueAuthorID, "type": "User"} + } + json.NewEncoder(w).Encode(map[string]any{"number": 12, "state": "open", "user": user}) + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7/commits": + commits := make([]map[string]any, 0, len(fx.commitMessages)) + for i, msg := range fx.commitMessages { + commits = append(commits, map[string]any{"sha": fmt.Sprintf("c%d", i), "commit": map[string]any{"message": msg}, "parents": []map[string]any{{"sha": "p"}}}) + } + json.NewEncoder(w).Encode(commits) case r.Method == http.MethodPut && r.URL.Path == "/repos/acme/widget/pulls/7/merge": if fx.mergeCalls != nil { *fx.mergeCalls++ } + if fx.mergeBody != nil { + *fx.mergeBody = map[string]any{} + _ = json.NewDecoder(r.Body).Decode(fx.mergeBody) + } if fx.mergeHTTPCode != 0 { w.WriteHeader(fx.mergeHTTPCode) return diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 5d6b08db8f..00f99b9180 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -186,6 +186,14 @@ type Client struct { // reviewEvidence resolves the evidence-bundle settings for a repo. Nil // means no bundles are written (see review_evidence.go). reviewEvidence func(repo string) ReviewEvidenceSettings + // mergeCredit resolves issue-author credit for the hive's merges + // (merge_credit.go, hivecommons/hive#14581); creditIssueAuthors is the + // live auto_merge.credit_issue_authors switch and mergeCredits holds the + // credit decided for a PR until its pr_merged audit consumes it. + mergeCreditMu sync.Mutex + mergeCredit *MergeCreditor + creditIssueAuthors func(repo string) bool + mergeCredits map[string]MergeCredit // issueClaims reports whether issue claims are recognised at enumeration // time and the TTL an assignee-inferred claim runs for (#8380). Nil or // false → no comment is fetched, no Issue carries claim fields. Read live @@ -4375,14 +4383,16 @@ func (c *Client) RecordPRMergedAudit(repo string, number int, method, sha, path if c == nil { return } + credit := c.takeMergeCredit(repo, number) + extra := []string{"method", method, "sha", sha, "path", path} + if logins := mergeCreditLogins(credit); logins != "" { + extra = append(extra, "issue_authors", logins) + } c.recordWriteAudit(AuditActionPRMerged, InvocationMeta{Agent: AttributionAgentGovernor}, - WriteTarget{Repo: repo, Number: number}, - "method", method, - "sha", sha, - "path", path) + WriteTarget{Repo: repo, Number: number}, extra...) // Every merge path ends here, so this is where the merged head's evidence // bundle gains its merge event and the PR gets its evidence pointer. - c.recordReviewEvidenceMerge(repo, number, method, sha, path) + c.recordReviewEvidenceMerge(repo, number, method, sha, path, credit.Logins()) // A successful App merge on any path proves the repo is mergeable, so // retire its "merge blocked" alerts (#11924). c.clearMergeFailureAlertsForRepo(repo) diff --git a/src/pkg/github/merge_credit.go b/src/pkg/github/merge_credit.go new file mode 100644 index 0000000000..d2e4825b00 --- /dev/null +++ b/src/pkg/github/merge_credit.go @@ -0,0 +1,444 @@ +package github + +import ( + "context" + "fmt" + "log/slog" + "regexp" + "sort" + "strconv" + "strings" + "sync" + + gh "github.com/google/go-github/v72/github" +) + +// Issue-author credit at merge time (hivecommons/hive#14581). +// +// A PR the hive opens itself already credits the human who filed the issue it +// answers: `Co-authored-by: ` on its commits (RFC #6588, +// issue-coauthor.sh) and `requested_by=@login` in its `— hive:` trailer +// (#7208). A PR an external clanker opens — a contributor hive, or an agent +// behind the relay — bypasses that choke point, so the person who asked for +// the work lands nowhere in the history (#14552 → #14546, #12927 → #12922). +// The merge is the one place every lane passes through, so the credit is +// applied there: the hive's merge paths ask MergeCreditor for the commit +// message to send with the merge, and GitHub writes the trailer into the +// squash (or merge) commit. +// +// The trailer is additive. It never changes who authored the change — the +// squash is still attributed to the PR author, every Signed-off-by is kept — +// it only puts the issue author on the commit, where GitHub's contributor +// graph counts a Co-authored-by for them. + +// mergeCreditCaller labels the REST calls this file makes. +const mergeCreditCaller = "hive:merge_credit" + +// mergeCreditMaxIssues bounds the issue lookups one merge performs; a PR +// body closing more issues than this credits the first ones only. +const mergeCreditMaxIssues = 10 + +// mergeCreditMaxCommitPages bounds the commit read for the squash message +// (GitHub caps the endpoint at 250 commits, three pages of 100). +const mergeCreditMaxCommitPages = 3 + +// mergeCreditNoreplyDomain is the address domain GitHub resolves a +// co-author by; the id-prefixed form resolves regardless of profile email. +const mergeCreditNoreplyDomain = "users.noreply.github.com" + +// coAuthoredByRE matches one Co-authored-by trailer line, capturing the +// name and the address. +var coAuthoredByRE = regexp.MustCompile(`(?mi)^Co-authored-by:\s*(.*?)\s*<([^>]*)>\s*$`) + +// IssueAuthorCredit is one human issue author a merge credits. +type IssueAuthorCredit struct { + Login string `json:"login"` + ID int64 `json:"id,omitempty"` + Issues []int `json:"issues,omitempty"` +} + +// Email is the id-prefixed GitHub noreply address, the one form guaranteed +// to resolve to the account (issue-coauthor.sh chooses the same). +func (c IssueAuthorCredit) Email() string { + login := strings.TrimSpace(c.Login) + if c.ID > 0 { + return strconv.FormatInt(c.ID, 10) + "+" + login + "@" + mergeCreditNoreplyDomain + } + return login + "@" + mergeCreditNoreplyDomain +} + +// Trailer renders the Co-authored-by line. +func (c IssueAuthorCredit) Trailer() string { + return "Co-authored-by: " + strings.TrimSpace(c.Login) + " <" + c.Email() + ">" +} + +// ClosingIssueRefs returns the issue numbers body closes in fullRepo +// (owner/repo), in order of first appearance, de-duplicated. It reads the +// same closing keywords ParseClaimedIssues does (the ones GitHub auto-closes +// on, plus their bounded prose form); a reference to another repository is +// left out, the credit is for this repository's history only. +func ClosingIssueRefs(body, fullRepo string) []int { + fullRepo = strings.TrimSpace(fullRepo) + seen := map[int]bool{} + var out []int + for _, ref := range ParseClaimedIssues(body, fullRepo) { + if ref.Issue <= 0 || seen[ref.Issue] || !strings.EqualFold(ref.Repo, fullRepo) { + continue + } + seen[ref.Issue] = true + out = append(out, ref.Issue) + } + return out +} + +// MergeCredit is what MergeCreditor.Prepare decided for one merge. +type MergeCredit struct { + // Authors are the human issue authors the PR's closing references name, + // minus the PR author, de-duplicated. Recorded on the evidence bundle + // and the audit trail whether or not a trailer was added. + Authors []IssueAuthorCredit + // Added are the Authors whose trailer the merge commit message gains; + // an author the branch commits already credit is left out. + Added []IssueAuthorCredit + // CommitMessage is the body to send with the merge, or "" to keep + // GitHub's default message (nothing to add). + CommitMessage string +} + +// Logins returns the credited logins in order. +func (m MergeCredit) Logins() []string { + out := make([]string, 0, len(m.Authors)) + for _, a := range m.Authors { + out = append(out, a.Login) + } + return out +} + +type issueAuthorEntry struct { + login string + id int64 + human bool +} + +// MergeCreditor resolves issue-author credit for the hive's merges. Issue +// authors never change, so a resolved author is cached per owner/repo#n for +// the life of the process: a PR evaluated by several sweeps costs one +// GET /issues/{n} per referenced issue in total. +type MergeCreditor struct { + gh *gh.Client + enabled func(repo string) bool + logger *slog.Logger + + mu sync.Mutex + authors map[string]issueAuthorEntry +} + +// NewMergeCreditor returns a creditor over client. enabled reports the live +// auto_merge.credit_issue_authors setting for an owner/repo; nil means on. +func NewMergeCreditor(client *gh.Client, enabled func(repo string) bool, logger *slog.Logger) *MergeCreditor { + if logger == nil { + logger = slog.Default() + } + return &MergeCreditor{gh: client, enabled: enabled, logger: logger, authors: map[string]issueAuthorEntry{}} +} + +// Enabled reports whether the creditor applies to repo. +func (m *MergeCreditor) Enabled(repo string) bool { + if m == nil || m.gh == nil { + return false + } + return m.enabled == nil || m.enabled(repo) +} + +// Prepare resolves the credit for merging pr with method. It never fails +// the merge: a lookup error, a rebase merge (no message to write) or a PR +// with no human issue author behind it returns an empty credit and the +// merge proceeds with GitHub's default message. +func (m *MergeCreditor) Prepare(ctx context.Context, owner, repo string, pr *gh.PullRequest, method string) MergeCredit { + full := owner + "/" + repo + if pr == nil || !m.Enabled(full) { + return MergeCredit{} + } + method = strings.ToLower(strings.TrimSpace(method)) + if method == "" { + method = "squash" + } + if method == "rebase" { + return MergeCredit{} + } + refs := ClosingIssueRefs(pr.GetBody(), full) + if len(refs) == 0 { + return MergeCredit{} + } + if len(refs) > mergeCreditMaxIssues { + refs = refs[:mergeCreditMaxIssues] + } + ctx = WithRESTCaller(ctx, mergeCreditCaller) + authors := m.resolveAuthors(ctx, owner, repo, pr.GetNumber(), pr.GetUser().GetLogin(), refs) + if len(authors) == 0 { + return MergeCredit{} + } + credit := MergeCredit{Authors: authors} + switch method { + case "merge": + credit.Added = authors + credit.CommitMessage = mergeCommitCreditMessage(pr.GetTitle(), authors) + default: + commits, err := m.listCommits(ctx, owner, repo, pr.GetNumber()) + if err != nil { + // Without the branch commits the squash body cannot be rebuilt, + // and a body without them would drop their Signed-off-by lines: + // keep GitHub's default message rather than risk the DCO trail. + m.logger.Warn("merge credit: could not read PR commits, merging without the issue-author trailer", + slog.String("repo", full), slog.Int("number", pr.GetNumber()), slog.String("error", err.Error())) + return credit + } + credit.Added = uncreditedAuthors(commits, authors) + if len(credit.Added) > 0 { + credit.CommitMessage = squashCreditMessage(commits, credit.Added) + } + } + return credit +} + +// resolveAuthors maps the referenced issues to their human authors, skipping +// bots, the PR author and pull requests, and folding one person's several +// issues into one credit. +func (m *MergeCreditor) resolveAuthors(ctx context.Context, owner, repo string, number int, prAuthor string, refs []int) []IssueAuthorCredit { + var ( + out []IssueAuthorCredit + index = map[string]int{} + ) + for _, n := range refs { + if n == number { + continue + } + entry, ok := m.issueAuthor(ctx, owner, repo, n) + if !ok || !entry.human { + continue + } + key := strings.ToLower(entry.login) + if key == "" || key == strings.ToLower(strings.TrimSpace(prAuthor)) { + continue + } + if i, seen := index[key]; seen { + out[i].Issues = append(out[i].Issues, n) + continue + } + index[key] = len(out) + out = append(out, IssueAuthorCredit{Login: entry.login, ID: entry.id, Issues: []int{n}}) + } + return out +} + +func (m *MergeCreditor) issueAuthor(ctx context.Context, owner, repo string, n int) (issueAuthorEntry, bool) { + key := strings.ToLower(owner+"/"+repo) + "#" + strconv.Itoa(n) + m.mu.Lock() + entry, ok := m.authors[key] + m.mu.Unlock() + if ok { + return entry, true + } + issue, _, err := m.gh.Issues.Get(ctx, owner, repo, n) + if err != nil { + m.logger.Debug("merge credit: issue author lookup failed", + slog.String("repo", owner+"/"+repo), slog.Int("issue", n), slog.String("error", err.Error())) + return issueAuthorEntry{}, false + } + user := issue.GetUser() + entry = issueAuthorEntry{ + login: strings.TrimSpace(user.GetLogin()), + id: user.GetID(), + human: !issue.IsPullRequest() && isHumanIssueAuthor(user), + } + m.mu.Lock() + m.authors[key] = entry + m.mu.Unlock() + return entry, true +} + +// isHumanIssueAuthor applies issue-coauthor.sh's rule: `type` is the +// authoritative signal, the login shapes the belt-and-braces one. +func isHumanIssueAuthor(user *gh.User) bool { + login := strings.ToLower(strings.TrimSpace(user.GetLogin())) + if login == "" || strings.EqualFold(user.GetType(), "Bot") { + return false + } + return !strings.HasSuffix(login, "[bot]") && !strings.HasPrefix(login, "github-actions") && !strings.HasSuffix(login, "-bot") +} + +func (m *MergeCreditor) listCommits(ctx context.Context, owner, repo string, number int) ([]*gh.RepositoryCommit, error) { + opts := &gh.ListOptions{PerPage: 100} + var all []*gh.RepositoryCommit + for page := 0; page < mergeCreditMaxCommitPages; page++ { + commits, resp, err := m.gh.PullRequests.ListCommits(ctx, owner, repo, number, opts) + if err != nil { + return nil, err + } + all = append(all, commits...) + if resp == nil || resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + if len(all) == 0 { + return nil, fmt.Errorf("pull request has no commits") + } + return all, nil +} + +// uncreditedAuthors drops the authors whose Co-authored-by already appears +// on a branch commit (a hive-opened PR carries it from issue-coauthor.sh), +// matched by address or by login, so the squash never names one person +// twice. +func uncreditedAuthors(commits []*gh.RepositoryCommit, authors []IssueAuthorCredit) []IssueAuthorCredit { + existing := map[string]bool{} + for _, rc := range commits { + for _, m := range coAuthoredByRE.FindAllStringSubmatch(rc.GetCommit().GetMessage(), -1) { + if addr := strings.ToLower(strings.TrimSpace(m[2])); addr != "" { + existing[addr] = true + if local, _, ok := strings.Cut(addr, "@"); ok { + if _, login, hasID := strings.Cut(local, "+"); hasID { + existing["login:"+login] = true + } else { + existing["login:"+local] = true + } + } + } + if name := strings.ToLower(strings.TrimSpace(m[1])); name != "" { + existing["login:"+name] = true + } + } + } + var out []IssueAuthorCredit + for _, a := range authors { + if existing[strings.ToLower(a.Email())] || existing["login:"+strings.ToLower(strings.TrimSpace(a.Login))] { + continue + } + out = append(out, a) + } + return out +} + +// squashCreditMessage rebuilds GitHub's default squash body from the branch +// commits — a single commit's body, or one `* subject` paragraph per commit +// with its body — and appends the credit trailers after it. Merge-from-base +// commits are left out, as GitHub leaves them out. Every line the commits +// carried, Signed-off-by included, is kept where it was; the post-merge DCO +// monitor scans the whole body, not just the final trailer block. +func squashCreditMessage(commits []*gh.RepositoryCommit, added []IssueAuthorCredit) string { + var messages []string + for _, rc := range commits { + if rc == nil || len(rc.Parents) > 1 { + continue + } + if msg := strings.TrimSpace(rc.GetCommit().GetMessage()); msg != "" { + messages = append(messages, msg) + } + } + var parts []string + switch len(messages) { + case 0: + case 1: + _, rest, _ := strings.Cut(messages[0], "\n") + if rest = strings.TrimSpace(rest); rest != "" { + parts = append(parts, rest) + } + default: + for _, msg := range messages { + subject, rest, _ := strings.Cut(msg, "\n") + para := "* " + strings.TrimSpace(subject) + if rest = strings.TrimSpace(rest); rest != "" { + para += "\n\n" + rest + } + parts = append(parts, para) + } + } + return strings.Join(append(parts, creditTrailers(added)), "\n\n") +} + +// mergeCommitCreditMessage is the merge commit body: GitHub's default (the +// PR title) followed by the credit trailers. The branch commits land +// unchanged under a merge commit, so their own trailers need no rebuilding. +func mergeCommitCreditMessage(title string, added []IssueAuthorCredit) string { + parts := []string{} + if title = strings.TrimSpace(title); title != "" { + parts = append(parts, title) + } + return strings.Join(append(parts, creditTrailers(added)), "\n\n") +} + +func creditTrailers(added []IssueAuthorCredit) string { + lines := make([]string, 0, len(added)) + for _, a := range added { + lines = append(lines, a.Trailer()) + } + return strings.Join(lines, "\n") +} + +// mergeCreditLogins renders the credited logins for an audit detail. +func mergeCreditLogins(credit MergeCredit) string { + logins := credit.Logins() + sort.Strings(logins) + return strings.Join(logins, ",") +} + +// SetCreditIssueAuthors installs the live auto_merge.credit_issue_authors +// switch (nil means on). Nil-receiver safe like the other setters. +func (c *Client) SetCreditIssueAuthors(fn func(repo string) bool) { + if c == nil { + return + } + c.mergeCreditMu.Lock() + defer c.mergeCreditMu.Unlock() + c.creditIssueAuthors = fn + if c.mergeCredit != nil { + c.mergeCredit.enabled = fn + } +} + +// MergeCreditor returns the client's shared creditor (one issue-author cache +// for every merge path), or nil without an API client. +func (c *Client) MergeCreditor() *MergeCreditor { + if c == nil || c.client == nil { + return nil + } + c.mergeCreditMu.Lock() + defer c.mergeCreditMu.Unlock() + if c.mergeCredit == nil { + c.mergeCredit = NewMergeCreditor(c.client, c.creditIssueAuthors, c.logger) + } + return c.mergeCredit +} + +// NoteMergeCredit stashes the credit decided for repo#number so the merge's +// pr_merged audit and evidence merge event can name the issue authors. An +// empty credit clears any earlier note. +func (c *Client) NoteMergeCredit(repo string, number int, credit MergeCredit) { + if c == nil || number <= 0 { + return + } + key := strings.ToLower(strings.TrimSpace(repo)) + "#" + strconv.Itoa(number) + c.mergeCreditMu.Lock() + defer c.mergeCreditMu.Unlock() + if len(credit.Authors) == 0 { + delete(c.mergeCredits, key) + return + } + if c.mergeCredits == nil { + c.mergeCredits = map[string]MergeCredit{} + } + c.mergeCredits[key] = credit +} + +func (c *Client) takeMergeCredit(repo string, number int) MergeCredit { + if c == nil { + return MergeCredit{} + } + key := strings.ToLower(strings.TrimSpace(repo)) + "#" + strconv.Itoa(number) + c.mergeCreditMu.Lock() + defer c.mergeCreditMu.Unlock() + credit := c.mergeCredits[key] + delete(c.mergeCredits, key) + return credit +} diff --git a/src/pkg/github/merge_credit_test.go b/src/pkg/github/merge_credit_test.go new file mode 100644 index 0000000000..4c5aeb3a64 --- /dev/null +++ b/src/pkg/github/merge_credit_test.go @@ -0,0 +1,399 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + gh "github.com/google/go-github/v72/github" +) + +// Issue-author credit at merge time (hivecommons/hive#14581). + +func TestIssueAuthorCreditTrailer(t *testing.T) { + c := IssueAuthorCredit{Login: "Danathar", ID: 12345} + if got, want := c.Trailer(), "Co-authored-by: Danathar <12345+Danathar@users.noreply.github.com>"; got != want { + t.Fatalf("Trailer() = %q, want %q", got, want) + } + noID := IssueAuthorCredit{Login: "dana"} + if got, want := noID.Email(), "dana@users.noreply.github.com"; got != want { + t.Fatalf("Email() without id = %q, want %q", got, want) + } +} + +func TestMergeCreditClosingIssueRefs(t *testing.T) { + for _, tc := range []struct { + body string + want []int + }{ + {body: "Fixes #42", want: []int{42}}, + {body: "Closes #9 and fixes #3", want: []int{9, 3}}, + {body: "Resolves acme/widget#5", want: []int{5}}, + {body: "Fixes other/repo#5", want: nil}, + {body: "Refs #42\nRelated to #43", want: nil}, + {body: "Fixes #42\nFixes #42", want: []int{42}}, + {body: "fix: the thing (closes #60)", want: []int{60}}, + {body: "`Fixes #7` in a code span", want: nil}, + {body: "", want: nil}, + } { + got := ClosingIssueRefs(tc.body, "acme/widget") + if fmt.Sprint(got) != fmt.Sprint(tc.want) { + t.Errorf("ClosingIssueRefs(%q) = %v, want %v", tc.body, got, tc.want) + } + } +} + +func commitWithMessage(msg string) *gh.RepositoryCommit { + return &gh.RepositoryCommit{Commit: &gh.Commit{Message: gh.Ptr(msg)}, Parents: []*gh.Commit{{SHA: gh.Ptr("p")}}} +} + +func TestUncreditedAuthorsSkipsTrailersTheBranchCarries(t *testing.T) { + authors := []IssueAuthorCredit{ + {Login: "Danathar", ID: 12345}, + {Login: "gregoryhunt", ID: 77}, + {Login: "newperson", ID: 9}, + } + commits := []*gh.RepositoryCommit{ + // issue-coauthor.sh writes the display name with the id-prefixed address. + commitWithMessage("Fix\n\nSigned-off-by: K \nCo-authored-by: Dana Thar <12345+danathar@users.noreply.github.com>"), + // A hand-written trailer naming the login with a plain noreply address. + commitWithMessage("More\n\nCo-authored-by: GregoryHunt "), + } + got := uncreditedAuthors(commits, authors) + if len(got) != 1 || got[0].Login != "newperson" { + t.Fatalf("uncreditedAuthors = %+v, want only newperson", got) + } +} + +func TestSquashCreditMessagePreservesSignoffsAndAppendsTrailers(t *testing.T) { + added := []IssueAuthorCredit{{Login: "Danathar", ID: 12345}, {Login: "bob", ID: 2}} + t.Run("single commit keeps its body", func(t *testing.T) { + commits := []*gh.RepositoryCommit{commitWithMessage("Fix the widget\n\nLonger text.\n\nSigned-off-by: Karibhou ")} + got := squashCreditMessage(commits, added) + want := "Longer text.\n\nSigned-off-by: Karibhou \n\n" + + "Co-authored-by: Danathar <12345+Danathar@users.noreply.github.com>\n" + + "Co-authored-by: bob <2+bob@users.noreply.github.com>" + if got != want { + t.Fatalf("squashCreditMessage =\n%s\nwant\n%s", got, want) + } + }) + t.Run("several commits list each subject and body, merge commits dropped", func(t *testing.T) { + mergeFromBase := commitWithMessage("Merge branch 'v5' into fix") + mergeFromBase.Parents = append(mergeFromBase.Parents, &gh.Commit{SHA: gh.Ptr("q")}) + commits := []*gh.RepositoryCommit{ + commitWithMessage("First\n\nSigned-off-by: A "), + mergeFromBase, + commitWithMessage("Second"), + } + got := squashCreditMessage(commits, added[:1]) + want := "* First\n\nSigned-off-by: A \n\n* Second\n\n" + + "Co-authored-by: Danathar <12345+Danathar@users.noreply.github.com>" + if got != want { + t.Fatalf("squashCreditMessage =\n%s\nwant\n%s", got, want) + } + if strings.Count(got, "Signed-off-by:") != 1 { + t.Fatalf("sign-off lost or duplicated:\n%s", got) + } + }) + t.Run("merge commit body is the title then the trailers", func(t *testing.T) { + got := mergeCommitCreditMessage(" Fix the widget ", added[:1]) + want := "Fix the widget\n\nCo-authored-by: Danathar <12345+Danathar@users.noreply.github.com>" + if got != want { + t.Fatalf("mergeCommitCreditMessage = %q, want %q", got, want) + } + }) +} + +// mergeCreditAPI is a one-PR GitHub API: issues by number with a configured +// author, and the PR's commits. +type mergeCreditAPI struct { + issues map[int]map[string]any + commits []string + issueGets atomic.Int32 + listGets atomic.Int32 + commitsHTTP int +} + +func (a *mergeCreditAPI) server(t *testing.T) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/acme/widget/issues/"): + a.issueGets.Add(1) + var n int + fmt.Sscanf(strings.TrimPrefix(r.URL.Path, "/repos/acme/widget/issues/"), "%d", &n) + issue, ok := a.issues[n] + if !ok { + http.Error(w, `{"message":"Not Found"}`, http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(issue) + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7/commits": + a.listGets.Add(1) + if a.commitsHTTP != 0 { + http.Error(w, "boom", a.commitsHTTP) + return + } + out := make([]map[string]any, 0, len(a.commits)) + for i, msg := range a.commits { + out = append(out, map[string]any{"sha": fmt.Sprintf("c%d", i), "commit": map[string]any{"message": msg}, "parents": []map[string]any{{"sha": "p"}}}) + } + json.NewEncoder(w).Encode(out) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.String()) + http.Error(w, "unexpected", http.StatusTeapot) + } + })) +} + +func issueBy(login string, id int64, userType string) map[string]any { + return map[string]any{"number": 1, "state": "open", "user": map[string]any{"login": login, "id": id, "type": userType}} +} + +func newMergeCreditorForTest(t *testing.T, api *mergeCreditAPI, enabled func(string) bool) (*MergeCreditor, *mergeCreditAPI) { + t.Helper() + srv := api.server(t) + t.Cleanup(srv.Close) + c := NewClientForTest(srv.URL, "acme", []string{"widget"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + return NewMergeCreditor(c.client, enabled, c.logger), api +} + +func creditPR(body, author string) *gh.PullRequest { + return &gh.PullRequest{Number: gh.Ptr(7), Title: gh.Ptr("Fix the widget"), Body: gh.Ptr(body), User: &gh.User{Login: gh.Ptr(author)}} +} + +func TestMergeCreditorPrepareSquash(t *testing.T) { + api := &mergeCreditAPI{ + issues: map[int]map[string]any{ + 10: issueBy("Danathar", 12345, "User"), + 11: issueBy("Danathar", 12345, "User"), // same person twice → one trailer + 12: issueBy("dependabot[bot]", 1, "Bot"), + 13: issueBy("Karibhou", 5, "User"), // the PR author + 14: issueBy("gregoryhunt", 77, "User"), + }, + commits: []string{"Fix the widget\n\nSigned-off-by: Karibhou "}, + } + m, _ := newMergeCreditorForTest(t, api, nil) + pr := creditPR("Fixes #10, closes #11, resolves #12, fixes #13 and fixes #14.", "Karibhou") + credit := m.Prepare(context.Background(), "acme", "widget", pr, "squash") + if got := fmt.Sprint(credit.Logins()); got != "[Danathar gregoryhunt]" { + t.Fatalf("Logins = %s, want [Danathar gregoryhunt]; credit=%+v", got, credit) + } + if fmt.Sprint(credit.Authors[0].Issues) != "[10 11]" { + t.Fatalf("Danathar's issues = %v, want [10 11]", credit.Authors[0].Issues) + } + want := "Signed-off-by: Karibhou \n\n" + + "Co-authored-by: Danathar <12345+Danathar@users.noreply.github.com>\n" + + "Co-authored-by: gregoryhunt <77+gregoryhunt@users.noreply.github.com>" + if credit.CommitMessage != want { + t.Fatalf("CommitMessage =\n%s\nwant\n%s", credit.CommitMessage, want) + } + if n := api.issueGets.Load(); n != 5 { + t.Fatalf("issue GETs = %d, want 5 (one per referenced issue)", n) + } + // A second merge attempt for the same head costs no issue lookups. + m.Prepare(context.Background(), "acme", "widget", pr, "squash") + if n := api.issueGets.Load(); n != 5 { + t.Fatalf("issue GETs after re-prepare = %d, want 5 (cached)", n) + } +} + +func TestMergeCreditorPrepareBranchAlreadyCredits(t *testing.T) { + api := &mergeCreditAPI{ + issues: map[int]map[string]any{10: issueBy("Danathar", 12345, "User")}, + commits: []string{"Fix\n\nSigned-off-by: hive[bot] \nCo-authored-by: Dana <12345+Danathar@users.noreply.github.com>"}, + } + m, _ := newMergeCreditorForTest(t, api, nil) + credit := m.Prepare(context.Background(), "acme", "widget", creditPR("Fixes #10", "hive[bot]"), "squash") + if len(credit.Authors) != 1 || credit.Authors[0].Login != "Danathar" { + t.Fatalf("Authors = %+v, want Danathar recorded for the evidence", credit.Authors) + } + if len(credit.Added) != 0 || credit.CommitMessage != "" { + t.Fatalf("hive-opened PR already credits the author; got Added=%+v message=%q", credit.Added, credit.CommitMessage) + } +} + +func TestMergeCreditorPrepareOffPaths(t *testing.T) { + ctx := context.Background() + t.Run("disabled for the repo makes no request", func(t *testing.T) { + api := &mergeCreditAPI{issues: map[int]map[string]any{10: issueBy("Danathar", 12345, "User")}} + m, _ := newMergeCreditorForTest(t, api, func(repo string) bool { return repo != "acme/widget" }) + if credit := m.Prepare(ctx, "acme", "widget", creditPR("Fixes #10", "k"), "squash"); len(credit.Authors) != 0 || credit.CommitMessage != "" { + t.Fatalf("disabled: got %+v", credit) + } + if api.issueGets.Load() != 0 { + t.Fatal("disabled creditor still read the issue") + } + }) + t.Run("nil creditor and nil PR", func(t *testing.T) { + var m *MergeCreditor + if m.Enabled("acme/widget") { + t.Fatal("nil creditor reports enabled") + } + if credit := m.Prepare(ctx, "acme", "widget", nil, "squash"); credit.CommitMessage != "" { + t.Fatalf("nil: got %+v", credit) + } + }) + t.Run("rebase has no message to write", func(t *testing.T) { + api := &mergeCreditAPI{issues: map[int]map[string]any{10: issueBy("Danathar", 12345, "User")}} + m, _ := newMergeCreditorForTest(t, api, nil) + if credit := m.Prepare(ctx, "acme", "widget", creditPR("Fixes #10", "k"), "rebase"); credit.CommitMessage != "" || api.issueGets.Load() != 0 { + t.Fatalf("rebase: got %+v after %d issue GETs", credit, api.issueGets.Load()) + } + }) + t.Run("no closing reference makes no request", func(t *testing.T) { + api := &mergeCreditAPI{} + m, _ := newMergeCreditorForTest(t, api, nil) + if credit := m.Prepare(ctx, "acme", "widget", creditPR("Refs #10", "k"), "squash"); credit.CommitMessage != "" || api.issueGets.Load() != 0 { + t.Fatalf("refs: got %+v", credit) + } + }) + t.Run("only bots and self leaves the default message", func(t *testing.T) { + api := &mergeCreditAPI{issues: map[int]map[string]any{ + 10: issueBy("github-actions[bot]", 1, "Bot"), + 11: issueBy("k", 2, "User"), + 12: issueBy("release-bot", 3, "User"), + }} + m, _ := newMergeCreditorForTest(t, api, nil) + if credit := m.Prepare(ctx, "acme", "widget", creditPR("Fixes #10 #11\nCloses #12", "K"), "squash"); len(credit.Authors) != 0 || api.listGets.Load() != 0 { + t.Fatalf("bots/self: got %+v (commit lists %d)", credit, api.listGets.Load()) + } + }) + t.Run("missing issue is skipped, not fatal", func(t *testing.T) { + api := &mergeCreditAPI{issues: map[int]map[string]any{11: issueBy("dana", 4, "User")}, commits: []string{"Fix"}} + m, _ := newMergeCreditorForTest(t, api, nil) + credit := m.Prepare(ctx, "acme", "widget", creditPR("Fixes #10, fixes #11", "k"), "squash") + if got := fmt.Sprint(credit.Logins()); got != "[dana]" { + t.Fatalf("missing issue: Logins = %s", got) + } + }) + t.Run("commit read failure keeps the default message", func(t *testing.T) { + api := &mergeCreditAPI{issues: map[int]map[string]any{10: issueBy("dana", 4, "User")}, commitsHTTP: http.StatusBadGateway} + m, _ := newMergeCreditorForTest(t, api, nil) + credit := m.Prepare(ctx, "acme", "widget", creditPR("Fixes #10", "k"), "squash") + if len(credit.Authors) != 1 || credit.CommitMessage != "" || len(credit.Added) != 0 { + t.Fatalf("commits error: got %+v", credit) + } + }) + t.Run("merge commit credits on the title without reading commits", func(t *testing.T) { + api := &mergeCreditAPI{issues: map[int]map[string]any{10: issueBy("dana", 4, "User")}} + m, _ := newMergeCreditorForTest(t, api, nil) + credit := m.Prepare(ctx, "acme", "widget", creditPR("Fixes #10", "k"), "merge") + want := "Fix the widget\n\nCo-authored-by: dana <4+dana@users.noreply.github.com>" + if credit.CommitMessage != want || api.listGets.Load() != 0 { + t.Fatalf("merge: got %q (commit lists %d), want %q", credit.CommitMessage, api.listGets.Load(), want) + } + }) +} + +// The merge's pr_merged audit names the credited issue authors and the +// stash is consumed by the merge that noted it. +func TestRecordPRMergedAuditCarriesIssueAuthors(t *testing.T) { + c := NewClientForTest("http://127.0.0.1:0", "acme", []string{"widget"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + var details []string + c.SetAttributionAudit(func(action, detail, agent string) { + if action == AuditActionPRMerged { + details = append(details, detail) + } + }) + c.NoteMergeCredit("acme/widget", 7, MergeCredit{Authors: []IssueAuthorCredit{{Login: "gregoryhunt"}, {Login: "Danathar", ID: 1}}}) + c.RecordPRMergedAudit("acme/widget", 7, "squash", "m7", PRAuditPathSweep) + c.RecordPRMergedAudit("acme/widget", 7, "squash", "m7", PRAuditPathSweep) + if len(details) != 2 { + t.Fatalf("pr_merged entries = %d, want 2", len(details)) + } + if !strings.Contains(details[0], "issue_authors=Danathar,gregoryhunt") { + t.Fatalf("first pr_merged detail lacks issue_authors: %q", details[0]) + } + if strings.Contains(details[1], "issue_authors") { + t.Fatalf("credit stash not consumed by the first audit: %q", details[1]) + } + // An empty credit clears an earlier note. + c.NoteMergeCredit("acme/widget", 8, MergeCredit{Authors: []IssueAuthorCredit{{Login: "x"}}}) + c.NoteMergeCredit("acme/widget", 8, MergeCredit{}) + if got := c.takeMergeCredit("acme/widget", 8); len(got.Authors) != 0 { + t.Fatalf("empty note did not clear: %+v", got) + } +} + +// MergePRVia (hive-merge relay, forge adapter) sends the credited message +// with the squash and honours the off switch. +func TestMergePRViaSendsIssueAuthorCredit(t *testing.T) { + for _, tc := range []struct { + name string + enabled bool + }{ + {name: "credit on", enabled: true}, + {name: "credit off", enabled: false}, + } { + t.Run(tc.name, func(t *testing.T) { + green := greenFixture() + var mergeBody map[string]any + issueGets := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // The PR itself is served here (serveCI's copy has no body); + // CI, checks and commits come from the green fixture. + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/o/r/pulls/42": + json.NewEncoder(w).Encode(map[string]any{ + "number": 42, "state": "open", "title": "Fix the widget", "body": "Fixes #10", + "user": map[string]any{"login": "karibhou"}, + "head": map[string]any{"sha": "abc123", "ref": "fix/widget"}, + "base": map[string]any{"ref": "v5"}, + }) + case r.Method == http.MethodGet && r.URL.Path == "/repos/o/r/issues/10": + issueGets++ + json.NewEncoder(w).Encode(issueBy("Danathar", 12345, "User")) + case r.Method == http.MethodGet && r.URL.Path == "/repos/o/r/pulls/42/commits": + json.NewEncoder(w).Encode([]map[string]any{{"sha": "c0", "commit": map[string]any{"message": "Fix the widget\n\nSigned-off-by: K "}, "parents": []map[string]any{{"sha": "p"}}}}) + case r.Method == http.MethodPut && r.URL.Path == "/repos/o/r/pulls/42/merge": + mergeBody = map[string]any{} + _ = json.NewDecoder(r.Body).Decode(&mergeBody) + _, _ = io.WriteString(w, `{"sha":"deadbeef","merged":true,"message":"Pull Request successfully merged"}`) + default: + if green.serveCI(w, r) { + return + } + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + c := testMergeClient(t, srv.URL) + c.SetCreditIssueAuthors(func(string) bool { return tc.enabled }) + var details []string + c.SetAttributionAudit(func(action, detail, agent string) { + if action == AuditActionPRMerged { + details = append(details, detail) + } + }) + res, err := c.MergePRVia(context.Background(), "o/r", 42, "squash", "", PRAuditPathForge) + if err != nil || !res.Merged { + t.Fatalf("MergePRVia: %+v, %v", res, err) + } + msg, _ := mergeBody["commit_message"].(string) + if !tc.enabled { + if msg != "" || issueGets != 0 { + t.Fatalf("credit off: commit_message=%q issueGets=%d", msg, issueGets) + } + if len(details) != 1 || strings.Contains(details[0], "issue_authors") { + t.Fatalf("credit off: audit %v", details) + } + return + } + want := "Signed-off-by: K \n\nCo-authored-by: Danathar <12345+Danathar@users.noreply.github.com>" + if msg != want { + t.Fatalf("commit_message = %q, want %q", msg, want) + } + if len(details) != 1 || !strings.Contains(details[0], "issue_authors=Danathar") { + t.Fatalf("audit lacks issue_authors: %v", details) + } + }) + } +} diff --git a/src/pkg/github/pullrequest.go b/src/pkg/github/pullrequest.go index 52dcd48380..667cf8e81b 100644 --- a/src/pkg/github/pullrequest.go +++ b/src/pkg/github/pullrequest.go @@ -418,9 +418,15 @@ func (c *Client) MergePRVia(ctx context.Context, repo string, number int, mergeM // Forward-merges keep ancestry no matter which caller (sweep, the // hive-merge relay or the forge adapter) asked for the merge. A failed lookup falls through to // the requested method. + var ( + fetched *gh.PullRequest + fetchedTried bool + ) if mergeMethod != "merge" { restCtx := WithRESTCaller(ctx, "hive:merge_pr") + fetchedTried = true if pr, _, err := c.client.PullRequests.Get(restCtx, owner, repo, number); err == nil { + fetched = pr mergeMethod = ResolveForwardMergeMethod(restCtx, c.client, c.logger, owner, repo, pr, mergeMethod) } } @@ -429,6 +435,20 @@ func (c *Client) MergePRVia(ctx context.Context, repo string, number int, mergeM if expectSHA = strings.TrimSpace(expectSHA); expectSHA != "" { opts.SHA = expectSHA } + commitMessage := "" + // Issue-author credit (hivecommons/hive#14581) rides the PR already + // fetched above; a merge-commit request fetches it only when the credit + // is on for the repo. + if creditor := c.MergeCreditor(); creditor.Enabled(owner+"/"+repo) { + if fetched == nil && !fetchedTried { + if pr, _, err := c.client.PullRequests.Get(WithRESTCaller(ctx, mergeCreditCaller), owner, repo, number); err == nil { + fetched = pr + } + } + credit := creditor.Prepare(ctx, owner, repo, fetched, mergeMethod) + commitMessage = credit.CommitMessage + c.NoteMergeCredit(owner+"/"+repo, number, credit) + } var res *gh.PullRequestMergeResult boundary := c.mutationBoundary() claim := effects.Claim{ @@ -439,7 +459,7 @@ func (c *Client) MergePRVia(ctx context.Context, repo string, number int, mergeM } merge := func(ctx context.Context) (effects.Result, error) { var apiErr error - res, _, apiErr = c.client.PullRequests.Merge(ctx, owner, repo, number, "", opts) + res, _, apiErr = c.client.PullRequests.Merge(ctx, owner, repo, number, commitMessage, opts) if apiErr != nil { if isDefiniteMergeRefusal(apiErr) { return effects.Result{}, effects.NotApplied(apiErr) diff --git a/src/pkg/github/review_evidence_merge.go b/src/pkg/github/review_evidence_merge.go index 9b1345a44c..45d5b951e4 100644 --- a/src/pkg/github/review_evidence_merge.go +++ b/src/pkg/github/review_evidence_merge.go @@ -36,7 +36,7 @@ func ReviewEvidenceComment(repo string, number int, id, hash string) string { // RecordPRMergedAudit, which every merge path (relay, sweep, queue) calls once // GitHub has merged. Like the relay's writes, every failure is logged and // swallowed: the merge already happened and must not be reported as failed. -func (c *Client) recordReviewEvidenceMerge(repo string, number int, method, sha, path string) { +func (c *Client) recordReviewEvidenceMerge(repo string, number int, method, sha, path string, issueAuthors []string) { settings, ok := c.reviewEvidenceSettings(repo) if !ok || number <= 0 { return @@ -73,7 +73,7 @@ func (c *Client) recordReviewEvidenceMerge(repo string, number int, method, sha, if sha = strings.TrimSpace(sha); sha == "" { sha = head } - merge := evidence.MergeEvent{Actor: actor, Method: method, At: time.Now().UTC(), SHA: sha} + merge := evidence.MergeEvent{Actor: actor, Method: method, At: time.Now().UTC(), SHA: sha, IssueAuthors: issueAuthors} // A clock-skewed opened_at later than the merge is dropped rather than // recorded as a negative time to merge. if !opened.IsZero() && !opened.After(merge.At) { diff --git a/src/pkg/github/review_evidence_merge_at_start_test.go b/src/pkg/github/review_evidence_merge_at_start_test.go index 5ae8c8b1c8..2142521a97 100644 --- a/src/pkg/github/review_evidence_merge_at_start_test.go +++ b/src/pkg/github/review_evidence_merge_at_start_test.go @@ -1,6 +1,7 @@ package github import ( + "reflect" "testing" "time" @@ -39,8 +40,8 @@ func TestUpsertReviewEvidenceRecordsMergeAlreadyOnPR(t *testing.T) { t.Fatal("merge not recorded on bundle started after the PR merged") } want := evidence.MergeEvent{Actor: "hive[bot]", Method: reviewEvidenceMergeObservedMethod, At: mergedAt, SHA: "mergesha", OpenedAt: opened} - if *b.Merge != want { - t.Errorf("merge = %+v, want %+v", *b.Merge, want) + if got := *b.Merge; got.Actor != want.Actor || got.Method != want.Method || !got.At.Equal(want.At) || got.SHA != want.SHA || !got.OpenedAt.Equal(want.OpenedAt) || len(got.IssueAuthors) != 0 { + t.Errorf("merge = %+v, want %+v", got, want) } if b.Validate() != nil { t.Errorf("bundle does not validate: %v", b.Validate()) @@ -78,7 +79,7 @@ func TestReviewEvidenceMergeFromPRFallbacks(t *testing.T) { } m := reviewEvidenceMergeFromPR(&gh.PullRequest{Merged: gh.Ptr(true)}, "h1", now) want := evidence.MergeEvent{Actor: reviewEvidenceMergeObservedMethod, Method: reviewEvidenceMergeObservedMethod, At: now, SHA: "h1"} - if m == nil || *m != want { + if m == nil || !reflect.DeepEqual(*m, want) { t.Errorf("sparse merged PR: got %+v, want %+v", m, want) } // opened_at after the merge (clock skew) is dropped, not recorded negative. diff --git a/src/pkg/github/review_evidence_outcome_test.go b/src/pkg/github/review_evidence_outcome_test.go index 9760d3d792..55f0090e1b 100644 --- a/src/pkg/github/review_evidence_outcome_test.go +++ b/src/pkg/github/review_evidence_outcome_test.go @@ -1,6 +1,7 @@ package github import ( + "reflect" "testing" "time" @@ -59,7 +60,7 @@ func TestRecordReviewEvidenceOutcomeStampsNewestBundle(t *testing.T) { t.Fatalf("outcome = %+v", newest.Outcome) } want := evidence.MergeEvent{Actor: "bob", Method: evidence.MergeUnrecorded, At: mergedAt, SHA: "h2"} - if newest.Merge == nil || *newest.Merge != want { + if newest.Merge == nil || !reflect.DeepEqual(*newest.Merge, want) { t.Errorf("merge = %+v, want %+v", newest.Merge, want) } if !newest.UpdatedAt.Equal(now) || newest.Hash == "" { diff --git a/src/pkg/github/review_evidence_read_test.go b/src/pkg/github/review_evidence_read_test.go index 2e4d881abf..4a0bfac23e 100644 --- a/src/pkg/github/review_evidence_read_test.go +++ b/src/pkg/github/review_evidence_read_test.go @@ -478,11 +478,11 @@ func TestRecordReviewEvidenceMergeGuards(t *testing.T) { var nilClient *Client nilClient.RecordPRMergedAudit("o/r", 7, "squash", "m", PRAuditPathSweep) c := evidenceMergeClient(t, &evidenceMergeFixture{head: "h1"}, &ReviewEvidenceSettings{Enabled: true}) - c.recordReviewEvidenceMerge("o/r", 0, "squash", "m", PRAuditPathSweep) + c.recordReviewEvidenceMerge("o/r", 0, "squash", "m", PRAuditPathSweep, nil) // A client with no REST transport still records nothing and posts nothing. bare := &Client{logger: c.logger} bare.SetReviewEvidence(func(string) ReviewEvidenceSettings { return ReviewEvidenceSettings{Enabled: true} }) - bare.recordReviewEvidenceMerge("o/r", 7, "squash", "m", PRAuditPathSweep) + bare.recordReviewEvidenceMerge("o/r", 7, "squash", "m", PRAuditPathSweep, nil) } func TestReviewEvidencePublicKey(t *testing.T) {