From 9e1e4c172b5f1a781f7d75a7890a2bdb90f3c452 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Tue, 27 Oct 2026 23:58:59 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(claims):=20record=20PR?= =?UTF-8?q?=E2=86=92issue=20claims=20from=20pull=5Frequest=20webhooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The duplicate-PR claim ledger only learned which issues an open PR claims from FetchClaimScan on the full reconcile pass; cached eval cycles skip applyDuplicatePRGuard (SkipOptional) and the pull_request webhook patched the PR row but never linked its Fixes #N. An owner PR opened between passes left its issue offerable for up to an hour and the contribute lane handed it to a contributor minutes later. - parse claims from the pull_request payload (same claimsFromPR grammar) and apply them to the ledger via a process-wide PRClaimsHook: open → record, edited/closed-unmerged → release, merged → merged claim - governor hook persists the ledger and re-filters the cached actionable snapshot through FilterClaimedIssues; open-PR link cache invalidated - IssueDispatchBlockReason refuses a closed issue ("issue closed") - webhook response lists claimed_issues; docs + changelog fragment Fixes #14814 Signed-off-by: Andrew Anderson --- changelog.d/fixed-14814-webhook-pr-claims.md | 1 + src/cmd/hive/eval_cycle_source.go | 3 + src/cmd/hive/webhook_pr_claims.go | 77 ++++++ src/cmd/hive/webhook_pr_claims_test.go | 67 +++++ src/docs/operator-reference.md | 24 +- src/pkg/dashboard/api_github_webhook.go | 11 +- src/pkg/dashboard/webhook_pr_claims_test.go | 145 +++++++++++ src/pkg/github/issue_claim_gate.go | 71 +++-- src/pkg/github/webhook_cache.go | 23 +- src/pkg/github/webhook_pr_claims.go | 221 ++++++++++++++++ src/pkg/github/webhook_pr_claims_test.go | 259 +++++++++++++++++++ 11 files changed, 875 insertions(+), 27 deletions(-) create mode 100644 changelog.d/fixed-14814-webhook-pr-claims.md create mode 100644 src/cmd/hive/webhook_pr_claims.go create mode 100644 src/cmd/hive/webhook_pr_claims_test.go create mode 100644 src/pkg/dashboard/webhook_pr_claims_test.go create mode 100644 src/pkg/github/webhook_pr_claims.go create mode 100644 src/pkg/github/webhook_pr_claims_test.go diff --git a/changelog.d/fixed-14814-webhook-pr-claims.md b/changelog.d/fixed-14814-webhook-pr-claims.md new file mode 100644 index 0000000000..c496072895 --- /dev/null +++ b/changelog.d/fixed-14814-webhook-pr-claims.md @@ -0,0 +1 @@ +- A `pull_request` webhook now records the issues the PR claims (`Fixes #N`, branch name, references) into the duplicate-PR claim ledger and filters the cached actionable snapshot on the event, releases them when the PR is edited to drop them or closes unmerged, and converts them to merged claims on merge; the dispatch gate also refuses an issue the confirming read says is closed. Before, the PR→issue link was only made on the full reconcile pass (~1h apart on a busy spoke), so an owner PR opened with `Fixes #N` between passes left #N offerable and the `/contribute` lane handed it to a contributor minutes later ([#14814](https://github.com/hivecommons/hive/issues/14814)). diff --git a/src/cmd/hive/eval_cycle_source.go b/src/cmd/hive/eval_cycle_source.go index fe78862757..077a4a79bb 100644 --- a/src/cmd/hive/eval_cycle_source.go +++ b/src/cmd/hive/eval_cycle_source.go @@ -126,6 +126,9 @@ func (b *boot) applyWebhookItemsFunc() func([]github.WebhookItemSnapshot) { if b.evalLoop != nil { b.snapshotPatch.onPatch = b.evalLoop.notePatch } + // A `pull_request` delivery's issue claims land in the ledger and + // drop out of this snapshot on the event (hivecommons/hive#14814). + github.SetPRClaimsHook(prClaimsHookFor(func() *github.ClaimLedger { return getClaimLedger(b.logger) }, b.snapshotPatch, b.logger)) } return func(snaps []github.WebhookItemSnapshot) { b.snapshotPatch.apply(snaps) } } diff --git a/src/cmd/hive/webhook_pr_claims.go b/src/cmd/hive/webhook_pr_claims.go new file mode 100644 index 0000000000..6f1c93fd5d --- /dev/null +++ b/src/cmd/hive/webhook_pr_claims.go @@ -0,0 +1,77 @@ +package main + +import ( + "log/slog" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// prClaimsHookFor builds the github.PRClaimsHook the governor installs +// (hivecommons/hive#14814): a `pull_request` webhook's claims go into the +// duplicate-PR claim ledger at once, the ledger is persisted, and the cached +// actionable snapshot is re-filtered through the same FilterClaimedIssues +// the reconcile pass applies — so an issue a just-opened PR fixes leaves +// the offerable set the moment the delivery lands instead of on the next +// enumeration, for the contribute lane (which reads the ledger at offer +// time) and the hub's own agents (which plan from the snapshot) alike. The +// ledger is resolved per call because it loads lazily; a nil patcher skips +// the snapshot step. +func prClaimsHookFor(ledger func() *github.ClaimLedger, patch *snapshotPatcher, logger *slog.Logger) github.PRClaimsHook { + return func(d github.PRClaimDelivery) { + if ledger == nil { + return + } + l := ledger() + if l == nil { + return + } + recorded, released := l.ApplyPRDelivery(d) + if recorded == 0 && released == 0 { + return + } + if err := l.Save(); err != nil && logger != nil { + logger.Warn("webhook PR claims: failed to persist claim ledger", + "repo", d.Repo, "pr", d.Number, "error", err) + } + suppressed := patch.suppressClaimed(l, logger) + if logger != nil { + logger.Info("webhook PR claims applied to claim ledger", + "repo", d.Repo, "pr", d.Number, "action", d.Action, "pr_state", d.State, + "issues", d.ClaimedIssues(), "recorded", recorded, "released", released, + "suppressed", suppressed, "source", "webhook") + } + } +} + +// suppressClaimed re-filters the stored actionable snapshot against the +// claim ledger, copy-on-write, and reports how many issues it dropped. The +// red+stale release valve is not consulted: a claim the webhook just +// recorded is seconds old, and the reconcile pass re-applies the valve with +// live CI state. No stored snapshot is a no-op. +func (p *snapshotPatcher) suppressClaimed(ledger *github.ClaimLedger, logger *slog.Logger) int { + if p == nil || p.target == nil || ledger == nil { + return 0 + } + p.mu.Lock() + defer p.mu.Unlock() + cur := p.target.Load() + if cur == nil { + return 0 + } + next := cur.Clone() + suppressed := github.FilterClaimedIssues(next, ledger, nil, logger) + if suppressed == 0 { + return 0 + } + p.target.Store(next) + if p.logger != nil { + p.logger.Info("webhook PR claims filtered the cached actionable snapshot", + "suppressed", suppressed, "issues", next.Issues.Count, + "snapshot_age", time.Since(next.GeneratedAt).Round(time.Second).String()) + } + if p.onPatch != nil { + p.onPatch(suppressed) + } + return suppressed +} diff --git a/src/cmd/hive/webhook_pr_claims_test.go b/src/cmd/hive/webhook_pr_claims_test.go new file mode 100644 index 0000000000..f560be269a --- /dev/null +++ b/src/cmd/hive/webhook_pr_claims_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "io" + "log/slog" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// hivecommons/hive#14814: the governor's PRClaimsHook must write the ledger, +// persist it, and drop the claimed issue from the cached actionable snapshot +// on the webhook — not on the next enumeration. +func TestPRClaimsHookRecordsAndFiltersSnapshot(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + now := time.Now().UTC() + path := filepath.Join(t.TempDir(), "claims.json") + ledger := github.NewClaimLedger(path, logger) + + var target atomic.Pointer[github.ActionableResult] + target.Store(&github.ActionableResult{GeneratedAt: now, Issues: github.IssueResult{ + Count: 2, Items: []github.Issue{{Repo: "repo", Number: 14765}, {Repo: "repo", Number: 14766}}, + }}) + var patched []int + patch := &snapshotPatcher{target: &target, logger: logger, onPatch: func(n int) { patched = append(patched, n) }} + + hook := prClaimsHookFor(func() *github.ClaimLedger { return ledger }, patch, logger) + hook(github.PRClaimDelivery{ + Repo: "repo", Number: 14772, Action: "opened", State: github.PRStateOpen, At: now, + Claims: []github.IssueClaim{{Repo: "repo", Issue: 14765, PRNumber: 14772, PRRepo: "repo", PRAuthor: "owner", ExternalAuthor: true, ObservedAt: now}}, + }) + + if _, ok := ledger.Lookup("repo", 14765); !ok { + t.Fatal("claim not recorded in the ledger") + } + cur := target.Load() + if cur.Issues.Count != 1 || len(cur.Issues.Items) != 1 || cur.Issues.Items[0].Number != 14766 { + t.Fatalf("snapshot after hook = %+v, want only #14766", cur.Issues) + } + if len(patched) != 1 || patched[0] != 1 { + t.Fatalf("onPatch calls = %v, want [1]", patched) + } + // Persisted: a fresh ledger from the same path sees the claim. + reloaded, err := github.LoadClaimLedger(path, logger) + if err != nil { + t.Fatal(err) + } + if _, ok := reloaded.Lookup("repo", 14765); !ok { + t.Fatal("claim not persisted") + } + + // A delivery with nothing to apply does not touch the snapshot. + hook(github.PRClaimDelivery{Repo: "repo", Number: 99, Action: "edited", State: github.PRStateOpen, At: now}) + if len(patched) != 1 { + t.Fatalf("onPatch calls after no-op delivery = %v", patched) + } + + // Nil ledger resolver / nil patcher are safe. + prClaimsHookFor(nil, nil, logger)(github.PRClaimDelivery{Repo: "repo", Number: 1}) + prClaimsHookFor(func() *github.ClaimLedger { return nil }, nil, logger)(github.PRClaimDelivery{Repo: "repo", Number: 1}) + if (*snapshotPatcher)(nil).suppressClaimed(ledger, logger) != 0 { + t.Fatal("nil patcher must be a no-op") + } +} diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 2b0a8041f8..0f2a7ab2a3 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -763,7 +763,29 @@ between. Two mechanisms close that gap already links this issue (claim skipped)* with the PR as evidence (reason `open_pr_linked`). A failed listing fails **open**: the ledger-backed guards still apply, and a flaky listing must not stall every - claim. + claim. The gate also refuses an issue the confirming read says is already + **closed** (`issue closed`), so an issue closed between enumerations is + never dispatched from the cached snapshot. +- **Webhook claim linking.** A `pull_request` delivery (opened, reopened, + edited, synchronize, ready-for-review, draft, closed) is parsed with the + same closing-keyword and branch-name grammar and written into the claim + ledger the moment it lands + ([#14814](https://github.com/hivecommons/hive/issues/14814); + `src/pkg/github/webhook_pr_claims.go`): an open PR's claims are recorded + (and the cached actionable snapshot re-filtered, so the hub's own agents + stop seeing the issue too), a PR edited to stop naming an issue or closed + without merging releases it, and a merged PR's claims become merged + claims. Before this the link was only made on the full reconcile pass — + about an hour apart on a busy spoke — and an owner PR opened with + `Fixes #N` in between left #N offerable for that long; the `/contribute` + lane handed [#14765](https://github.com/hivecommons/hive/issues/14765) out + nine minutes after #14772 (Fixes #14765) opened. The receiver's response + lists the issues as `claimed_issues`, the governor logs `webhook PR claims + applied to claim ledger` with the PR, state and counts, and the open-PR + listing cache for the repo is invalidated so the pre-dispatch guard + re-lists on its next call. An `issues` closed delivery (or a PR merged + with a closing keyword, which GitHub delivers as the issue's own close) + already evicts the issue from the status snapshot the lane offers from. - **Duplicate-fix sweep.** Every ~15 minutes (an unstick step, alongside the supersession sweep) the hive looks for an open issue two or more open PRs close and resolves the pair deterministically. The **earlier-created PR diff --git a/src/pkg/dashboard/api_github_webhook.go b/src/pkg/dashboard/api_github_webhook.go index 12d972e65b..d42b61764a 100644 --- a/src/pkg/dashboard/api_github_webhook.go +++ b/src/pkg/dashboard/api_github_webhook.go @@ -37,8 +37,12 @@ func (s *Server) registerGitHubWebhookRoutes() { // events invalidate the matching cached PR state and mark it dirty for the // next eval cycle, queue a targeted re-read of the named PR or issue for the // activity monitor (webhook_tracker_refresh.go), and every delivery for a -// managed repo refreshes webhook health. A `pull_request` opened/synchronize/ -// reopened delivery also hands the PR to the sentinel (#13379), and the +// managed repo refreshes webhook health. A `pull_request` delivery records +// the issues the PR claims (`Fixes #N`, branch name, references) into the +// duplicate-PR claim ledger on the event (hivecommons/hive#14814), so the +// contribute lane stops offering them without waiting for the reconcile +// pass; opened/synchronize/reopened also hands the PR to the sentinel +// (#13379), and the // organization-scoped `projects_v2_item` delivery patches the GitHub // Projects work source cache. Deliveries for repositories this hive does not // manage are ignored. @@ -106,6 +110,9 @@ func (s *Server) handleGitHubWebhook(w http.ResponseWriter, r *http.Request) { // its own sample (WriterForgeState) when it applies the item patch. forgestate.RecordEventToPatch(r.Context(), res.Repo, forgestate.WriterCacheInvalidate, receivedAt, time.Now()) resp := map[string]any{"status": "ok", "event": event, "repo": res.Repo, "invalidated": res.Invalidated} + if len(res.ClaimedIssues) > 0 { + resp["claimed_issues"] = res.ClaimedIssues + } if n := s.scheduleWebhookTrackerRefresh(res, r.Header.Get("X-GitHub-Delivery")); n > 0 { resp["tracker_refresh"] = n } diff --git a/src/pkg/dashboard/webhook_pr_claims_test.go b/src/pkg/dashboard/webhook_pr_claims_test.go new file mode 100644 index 0000000000..01c6dfe750 --- /dev/null +++ b/src/pkg/dashboard/webhook_pr_claims_test.go @@ -0,0 +1,145 @@ +package dashboard + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + ghpkg "github.com/hivecommons/hive/pkg/github" +) + +// hivecommons/hive#14814 regression suite: an owner PR opened with +// `Fixes #N` between two reconcile passes left #N offerable for up to an +// hour, and the contribute lane handed #14765 to a contributor nine minutes +// after #14772 (Fixes #14765) opened. The `pull_request` webhook now records +// the claim into the duplicate-PR ledger on the event, and selectTask +// (which reads that ledger through Dependencies.IssueClaimed) stops +// offering the issue at once. An `issues` closed delivery already evicts +// the row from the status payload selectTask offers from; the second test +// pins that path for the same incident. + +// webhookClaimFixture wires the dashboard server the way the governor does: +// the webhook receiver's claim hook writes a real ledger, and the contribute +// admission gate reads the same ledger. +func webhookClaimFixture(t *testing.T) (*ContributeWSHub, *Server, *ghpkg.ClaimLedger) { + t.Helper() + const secret = "s3cr3t" + t.Setenv(githubWebhookSecretEnvVar, secret) + hub, s := covK2Hub(t) + // Typed items, as the governor publishes them (the map shape other + // contribute fixtures use is a JSON round-trip artefact). + s.statusMu.Lock() + s.status = &StatusPayload{Repos: []FrontendRepo{{ + Name: "dakota", Full: "projectbluefin/dakota", + ActionableIssues: []any{ + ghpkg.Issue{Repo: "dakota", Number: 353, Title: "the issue everyone kept fixing", URL: "https://github.com/projectbluefin/dakota/issues/353", Author: "someone"}, + ghpkg.Issue{Repo: "dakota", Number: 360, Title: "an unclaimed issue", URL: "https://github.com/projectbluefin/dakota/issues/360", Author: "someone"}, + }, + }}} + s.statusMu.Unlock() + ghSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // selectTask's trust check reads the contributor's permission; + // the webhook receiver itself must not call GitHub. + if strings.Contains(r.URL.Path, "/collaborators/") { + _ = json.NewEncoder(w).Encode(map[string]any{"permission": "read"}) + return + } + t.Errorf("webhook receiver must not call GitHub: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(ghSrv.Close) + s.deps.GHClient = ghpkg.NewClientForTest(ghSrv.URL, "projectbluefin", []string{"dakota"}, s.logger) + s.deps.Ctx = context.Background() + timers := &fakeTimers{} + s.webhookRefresh = newWebhookTrackerRefresher() + s.webhookRefresh.newTimer = timers.newTimer + + ledger := ghpkg.NewClaimLedger(filepath.Join(t.TempDir(), "claims.json"), s.logger) + ghpkg.SetPRClaimsHook(func(d ghpkg.PRClaimDelivery) { ledger.ApplyPRDelivery(d) }) + t.Cleanup(func() { ghpkg.SetPRClaimsHook(nil) }) + s.deps.IssueClaimed = ledger.Lookup + return hub, s, ledger +} + +func postSignedWebhook(t *testing.T, s *Server, event string, body []byte) map[string]any { + t.Helper() + rec := postGitHubWebhook(s, event, signGitHubWebhookForTest("s3cr3t", body), body) + if rec.Code != http.StatusOK { + t.Fatalf("%s: status = %d (%s)", event, rec.Code, rec.Body.String()) + } + var resp map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + return resp +} + +func TestWebhookPRClaimStopsSelectTaskOffering(t *testing.T) { + hub, s, ledger := webhookClaimFixture(t) + + // Baseline: nothing claimed, the first issue is offered. + if msg := hub.selectTask(claimedIssueConn()); msg == nil || msg.Type != "task_assign" || msg.Number != 353 { + t.Fatalf("baseline offer = %+v, want #353", msg) + } + + // An owner PR opens with `Fixes #353`. The claim must land before any + // reconcile pass. + body := []byte(`{"action":"opened","repository":{"full_name":"projectbluefin/dakota"},"pull_request":{"number":900,"state":"open","title":"fix it","body":"Fixes #353","html_url":"https://github.com/projectbluefin/dakota/pull/900","user":{"login":"castrojo"},"head":{"ref":"fix-353","sha":"abc"}}}`) + resp := postSignedWebhook(t, s, "pull_request", body) + claimed, _ := resp["claimed_issues"].([]any) + if len(claimed) != 1 || claimed[0] != float64(353) { + t.Fatalf("response claimed_issues = %v, want [353]", resp["claimed_issues"]) + } + if c, ok := ledger.Lookup("dakota", 353); !ok || c.PRNumber != 900 || !c.ExternalAuthor { + t.Fatalf("ledger claim = %+v ok=%v, want external claim by PR 900", c, ok) + } + + // Fresh contributor connection (the baseline one holds nothing: the + // offer above is not an assignment until accepted) — #353 is withheld. + msg := hub.selectTask(claimedIssueConn()) + if msg == nil || msg.Type != "task_assign" { + t.Fatalf("expected task_assign, got %+v", msg) + } + if msg.Number != 353 && msg.Number != 360 { + t.Fatalf("unexpected issue #%d", msg.Number) + } + if msg.Number == 353 { + t.Fatal("#353 offered after the webhook recorded an open PR claiming it") + } + + // The PR closes without merging: the claim is released and #353 is + // offerable again. + closed := []byte(`{"action":"closed","repository":{"full_name":"projectbluefin/dakota"},"pull_request":{"number":900,"state":"closed","title":"fix it","body":"Fixes #353","html_url":"https://github.com/projectbluefin/dakota/pull/900","user":{"login":"castrojo"},"head":{"ref":"fix-353","sha":"abc"}}}`) + postSignedWebhook(t, s, "pull_request", closed) + if _, ok := ledger.Lookup("dakota", 353); ok { + t.Fatal("claim must be released when the PR closes unmerged") + } + if msg := hub.selectTask(claimedIssueConn()); msg == nil || msg.Number != 353 { + t.Fatalf("offer after PR closed = %+v, want #353 back", msg) + } +} + +func TestWebhookIssueClosedStopsSelectTaskOffering(t *testing.T) { + hub, s, _ := webhookClaimFixture(t) + now := time.Date(2026, 10, 20, 1, 0, 0, 0, time.UTC) + t.Cleanup(ghpkg.ResetWebhookTrackerForTestWithClock(func() time.Time { return now })) + + body := []byte(`{"action":"closed","issue":{"number":353,"state":"closed","title":"the issue everyone kept fixing"},"repository":{"full_name":"projectbluefin/dakota"}}`) + postSignedWebhook(t, s, "issues", body) + + s.statusMu.RLock() + remaining := len(s.status.Repos[0].ActionableIssues) + s.statusMu.RUnlock() + if remaining != 1 { + t.Fatalf("actionable issues after close = %d, want 1 (#353 evicted)", remaining) + } + msg := hub.selectTask(claimedIssueConn()) + if msg == nil || msg.Type != "task_assign" || msg.Number != 360 { + t.Fatalf("offer after #353 closed = %+v, want #360", msg) + } +} diff --git a/src/pkg/github/issue_claim_gate.go b/src/pkg/github/issue_claim_gate.go index 43aab561c0..dc2c0b29e9 100644 --- a/src/pkg/github/issue_claim_gate.go +++ b/src/pkg/github/issue_claim_gate.go @@ -16,6 +16,12 @@ import ( // families are disjoint). A PR's stage is the PR sweep's alone. const ClaimBlockReasonPullRequest = "pull request" +// ClaimBlockReasonIssueClosed is the IssueDispatchBlockReason for an issue +// the forge already reports closed (hivecommons/hive#14814): a closing +// keyword on a merged PR, or a person, closed it after the snapshot the +// producer is dispatching from was listed. There is nothing to start. +const ClaimBlockReasonIssueClosed = "issue closed" + // Prefixes of the IssueClaimBlockReason values that name the label at fault: // "never-claim label: Epic" for an umbrella issue // (governor.claims.never_claim_labels), "parked: stage/045-needs-decision" @@ -113,41 +119,54 @@ func (c *Client) issueClaimParkLabel(labels []string) string { // to start fresh work uses IssueDispatchBlockReason, which adds the open-PR // guard (hivecommons/hive#14799). func (c *Client) IssueClaimBlockReason(ctx context.Context, repo string, number int) (string, error) { - reason, _, err := c.issueClaimGate(ctx, repo, number) - return reason, err + gate, err := c.issueClaimGate(ctx, repo, number) + return gate.reason, err +} + +// issueClaimGateResult is what one issue read told the claim gate: the +// label-based refusal, the labels for the dispatch gate's open-PR step, and +// whether the forge reports the issue closed. +type issueClaimGateResult struct { + reason string + labels []string + closed bool } // issueClaimGate reads the issue once and applies every label-based refusal. -// labels are returned for the dispatch gate's open-PR step. -func (c *Client) issueClaimGate(ctx context.Context, repo string, number int) (reason string, labels []string, err error) { +func (c *Client) issueClaimGate(ctx context.Context, repo string, number int) (issueClaimGateResult, error) { if c == nil || c.client == nil { - return "", nil, ErrNoGitHubClient + return issueClaimGateResult{}, ErrNoGitHubClient } owner, name := c.splitRepo(repo) issue, _, err := c.client.Issues.Get(ctx, owner, name, number) if err != nil { - return "", nil, fmt.Errorf("checking issue claim labels: %w", err) + return issueClaimGateResult{}, fmt.Errorf("checking issue claim labels: %w", err) } if issue.IsPullRequest() { - return ClaimBlockReasonPullRequest, nil, nil + return issueClaimGateResult{reason: ClaimBlockReasonPullRequest}, nil } - labels = extractLabels(issue.Labels) - if hasIssueNeedsHumanLabel(labels) { - return "needs-human", labels, nil + res := issueClaimGateResult{ + labels: extractLabels(issue.Labels), + closed: strings.EqualFold(issue.GetState(), "closed"), } - if c.isHeld(labels) { - return "hold", labels, nil + labels := res.labels + switch { + case hasIssueNeedsHumanLabel(labels): + res.reason = "needs-human" + case c.isHeld(labels): + res.reason = "hold" + case hasBlockedLabel(labels): + res.reason = blockedClaimReason(issue.GetBody()) } - if hasBlockedLabel(labels) { - return blockedClaimReason(issue.GetBody()), labels, nil + if res.reason != "" { + return res, nil } if label := c.issueClaimParkLabel(labels); label != "" { - return ClaimBlockReasonParkedPrefix + label, labels, nil + res.reason = ClaimBlockReasonParkedPrefix + label + } else if label := claims.NeverClaimLabel(labels, c.neverClaimLabelSet()); label != "" { + res.reason = ClaimBlockReasonNeverClaimPrefix + label } - if label := claims.NeverClaimLabel(labels, c.neverClaimLabelSet()); label != "" { - return ClaimBlockReasonNeverClaimPrefix + label, labels, nil - } - return "", labels, nil + return res, nil } // IssueDispatchBlockReason is IssueClaimBlockReason for a producer about to @@ -161,12 +180,18 @@ func (c *Client) issueClaimGate(ctx context.Context, repo string, number int) (r // very PR it exists to protect. Off with scanner.skip_issues_with_open_pr: // false; a failed listing fails open with a warning. func (c *Client) IssueDispatchBlockReason(ctx context.Context, repo string, number int) (string, error) { - reason, labels, err := c.issueClaimGate(ctx, repo, number) - if err != nil || reason != "" { - return reason, err + gate, err := c.issueClaimGate(ctx, repo, number) + if err != nil || gate.reason != "" { + return gate.reason, err + } + // The same read says whether the issue is still open: a closing keyword + // on a PR that merged since the snapshot was listed closes it, and a + // closed issue is not work to start (hivecommons/hive#14814). + if gate.closed { + return ClaimBlockReasonIssueClosed, nil } // Last because it is the only step that costs a listing. The eval // cycle's claim ledger learns of a hand-opened PR one scan late; this // reads the forge now. - return c.openPRLinkBlockReason(ctx, repo, number, labels), nil + return c.openPRLinkBlockReason(ctx, repo, number, gate.labels), nil } diff --git a/src/pkg/github/webhook_cache.go b/src/pkg/github/webhook_cache.go index 58ade7f808..b3847ba9bc 100644 --- a/src/pkg/github/webhook_cache.go +++ b/src/pkg/github/webhook_cache.go @@ -57,6 +57,10 @@ type WebhookEventResult struct { // reported on; a reader with its own PR set (forgestate) resolves it to // a PR the detail cache may not hold (hivecommons/hive#13377). HeadSHA string `json:"head_sha,omitempty"` + // ClaimedIssues lists the issues a `pull_request` delivery's PR claims + // (closing keyword, branch name or reference) in its own repository, + // as recorded into the claim ledger on the event (hivecommons/hive#14814). + ClaimedIssues []int `json:"claimed_issues,omitempty"` // Item is the payload's own view of the issue or pull request the // delivery named (every `issues`, `issue_comment` and `pull_request*` // payload embeds the full object with its state), nil for deliveries @@ -416,9 +420,16 @@ type webhookEventPayload struct { State string `json:"state"` Merged bool `json:"merged"` MergedAt *time.Time `json:"merged_at"` + ClosedAt *time.Time `json:"closed_at"` + CreatedAt *time.Time `json:"created_at"` UpdatedAt *time.Time `json:"updated_at"` - Head struct { + HTMLURL string `json:"html_url"` + User *struct { + Login string `json:"login"` + } `json:"user"` + Head struct { SHA string `json:"sha"` + Ref string `json:"ref"` } `json:"head"` } `json:"pull_request"` Issue *struct { @@ -486,6 +497,16 @@ func (c *Client) HandleWebhookEvent(event string, payload []byte) (WebhookEventR hook(configured, n, sharedWebhookTracker.now()) } } + if d, ok := c.webhookPRClaimDelivery(event, configured, p, sharedWebhookTracker.now()); ok { + // The PR's claims take effect now, not on the next reconcile pass + // (hivecommons/hive#14814); the live open-PR index for the repo is + // stale the same instant, so the next guard call lists again. + res.ClaimedIssues = d.ClaimedIssues() + c.InvalidateOpenPRLinks(configured) + if hook := prClaimsHook(); hook != nil { + hook(d) + } + } if merged, ok := webhookMergedPR(event, p); ok { // A merged revert names the PR it undid; the payload already carries // the title and body, so this costs no GitHub call (#13241). diff --git a/src/pkg/github/webhook_pr_claims.go b/src/pkg/github/webhook_pr_claims.go new file mode 100644 index 0000000000..8adca28360 --- /dev/null +++ b/src/pkg/github/webhook_pr_claims.go @@ -0,0 +1,221 @@ +package github + +import ( + "sort" + "strings" + "sync" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// PR→issue claim linking on the webhook path (hivecommons/hive#14814). +// +// The duplicate-PR claim ledger used to learn which issues an open PR +// claims only from FetchClaimScan, which runs on the reconcile pass — on +// hive's own spoke about an hour apart during the incident. A `pull_request` +// webhook's targeted re-read patched the PR row into the cached snapshot but +// never re-ran the claim link, so an owner PR opened with `Fixes #N` between +// passes left #N offerable: #14765 was handed to a contributor 9 minutes +// after #14772 (Fixes #14765) opened, #14789 13 minutes after #14791. The +// delivery already carries the PR's title, body, author and head branch — +// everything claimsFromPR reads — so the claims are parsed from the payload +// and recorded the moment the PR exists, closed or merged, at no API cost. + +// PRClaimDelivery is what one `pull_request` webhook says about the issues +// the PR claims: the claims parsed from its payload with the ledger's own +// grammar, and the PR state that decides how the ledger applies them. +type PRClaimDelivery struct { + // Repo is the PR's repository in the configured spelling. + Repo string + // Number is the PR number. + Number int + // Action is the webhook action (opened, edited, closed, …). + Action string + // State is the PR state as the payload reports it: PRStateOpen, + // PRStateClosed (unmerged) or PRStateMerged. + State string + // MergedAt is when the PR merged; zero unless State is PRStateMerged. + MergedAt time.Time + // Claims are the issue claims the PR's title, body and head branch make, + // exactly as the reconcile pass would parse them. + Claims []IssueClaim + // At is the delivery time. + At time.Time +} + +// ClaimedIssues lists the issue numbers the delivery claims in the PR's own +// repository, ascending, for the receiver's response and log line. +func (d PRClaimDelivery) ClaimedIssues() []int { + seen := map[int]bool{} + var out []int + for _, c := range d.Claims { + if c.Repo != d.Repo || c.Issue <= 0 || seen[c.Issue] { + continue + } + seen[c.Issue] = true + out = append(out, c.Issue) + } + sort.Ints(out) + return out +} + +// PRClaimsHook is told about every `pull_request` delivery whose action can +// change which issues the PR claims or whether the PR is still open. The +// governor registers one that applies the delivery to the duplicate-PR claim +// ledger (ClaimLedger.ApplyPRDelivery) and filters the cached actionable +// snapshot, so the claim takes effect without waiting for the reconcile pass. +type PRClaimsHook func(PRClaimDelivery) + +var ( + prClaimsHookMu sync.RWMutex + prClaimsHookFn PRClaimsHook +) + +// SetPRClaimsHook installs (or, with nil, removes) the process-wide +// PRClaimsHook. +func SetPRClaimsHook(fn PRClaimsHook) { + prClaimsHookMu.Lock() + prClaimsHookFn = fn + prClaimsHookMu.Unlock() +} + +func prClaimsHook() PRClaimsHook { + prClaimsHookMu.RLock() + defer prClaimsHookMu.RUnlock() + return prClaimsHookFn +} + +// webhookPRClaimActions are the `pull_request` actions after which the PR's +// claims may differ from what the ledger holds: the PR appeared, its text +// changed, its head moved (a branch rename arrives as synchronize), it left +// or re-entered draft, or it closed. Label and review-request actions carry +// the same PR text and are skipped so they do not re-save the ledger. +var webhookPRClaimActions = map[string]bool{ + "opened": true, + "reopened": true, + "edited": true, + "synchronize": true, + "ready_for_review": true, + "converted_to_draft": true, + "closed": true, +} + +// webhookPRClaimDelivery builds the PRClaimDelivery for a `pull_request` +// event; ok is false for every other event, for an action that cannot +// change the claims, or for a payload with no PR object. +func (c *Client) webhookPRClaimDelivery(event, configured string, p webhookEventPayload, now time.Time) (PRClaimDelivery, bool) { + if event != "pull_request" || p.PullRequest == nil || p.PullRequest.Number <= 0 || !webhookPRClaimActions[p.Action] { + return PRClaimDelivery{}, false + } + wp := p.PullRequest + pr := &gh.PullRequest{ + Number: gh.Ptr(wp.Number), + Title: gh.Ptr(wp.Title), + Body: gh.Ptr(wp.Body), + HTMLURL: gh.Ptr(wp.HTMLURL), + State: gh.Ptr(wp.State), + Merged: gh.Ptr(wp.Merged), + Head: &gh.PullRequestBranch{Ref: gh.Ptr(wp.Head.Ref), SHA: gh.Ptr(wp.Head.SHA)}, + } + if wp.User != nil { + pr.User = &gh.User{Login: gh.Ptr(wp.User.Login)} + } + if wp.MergedAt != nil { + pr.MergedAt = &gh.Timestamp{Time: *wp.MergedAt} + } + if wp.ClosedAt != nil { + pr.ClosedAt = &gh.Timestamp{Time: *wp.ClosedAt} + } + if wp.CreatedAt != nil { + pr.CreatedAt = &gh.Timestamp{Time: *wp.CreatedAt} + } + d := PRClaimDelivery{Repo: configured, Number: wp.Number, Action: p.Action, State: observedPRState(pr), At: now} + switch { + case wp.Merged || (wp.MergedAt != nil && !wp.MergedAt.IsZero()): + d.State = PRStateMerged + if wp.MergedAt != nil { + d.MergedAt = *wp.MergedAt + } + if d.MergedAt.IsZero() { + d.MergedAt = now + } + case p.Action == "closed", !strings.EqualFold(d.State, PRStateOpen): + // GitHub reports a merged PR as state "closed" too; merged is + // decided above, so what is left here closed without merging. + d.State = PRStateClosed + } + identity := c.getHiveIdentity() + if identity.AppLogin == "" { + identity.AppLogin = c.appBotLogin + } + d.Claims = claimsFromPR(pr, configured, identity, now) + for i := range d.Claims { + d.Claims[i].PRState = d.State + } + return d, true +} + +// ApplyPRDelivery applies one `pull_request` webhook to the ledger and +// reports how many claims it recorded and how many it released. It makes +// the ledger say what the next FetchClaimScan would say about this PR: +// +// - every unsettled claim the PR held is dropped first, so a PR edited to +// stop naming an issue, or closed without merging, releases it; +// - an open PR's claims are recorded as the scan records open claims, the +// rank rule in insertLocked still deciding a collision with another PR's +// claim on the same issue; +// - a merged PR's claims are recorded as MergedPR claims anchored at the +// merge, as the merged-PR scan does (#6867). +// +// FirstObservedAt carries forward when the same PR already claimed the same +// issue, so the weak-claim deferral window is not reset by the delivery. +// Callers persist with Save. A nil ledger or an empty delivery is a no-op. +func (l *ClaimLedger) ApplyPRDelivery(d PRClaimDelivery) (recorded, released int) { + if l == nil || d.Number <= 0 || d.Repo == "" { + return 0, 0 + } + l.mu.Lock() + defer l.mu.Unlock() + now := d.At + if now.IsZero() { + now = l.now() + } + prev := make(map[string]IssueClaim, len(l.claims)) + dropped := map[string]bool{} + for key, c := range l.claims { + prev[key] = c + if c.PRNumber == d.Number && c.PRRepo == d.Repo && !c.MergedPR { + delete(l.claims, key) + dropped[key] = true + } + } + if d.State == PRStateClosed { + return 0, len(dropped) + } + for _, c := range d.Claims { + if c.Issue <= 0 || c.Repo == "" { + continue + } + c.ObservedAt = now + c.PRNumber, c.PRRepo = d.Number, d.Repo + if d.State == PRStateMerged { + c.MergedPR = true + c.MergedAt = d.MergedAt + if c.MergedAt.IsZero() { + c.MergedAt = now + } + c.PRState = PRStateMerged + c.FirstObservedAt = c.MergedAt + } else { + c.PRState = PRStateOpen + } + c = l.anchorFirstObservedLocked(prev, c) + l.insertLocked(c) + if held := l.claims[c.Key()]; held.PRNumber == d.Number && held.PRRepo == d.Repo { + recorded++ + delete(dropped, c.Key()) + } + } + return recorded, len(dropped) +} diff --git a/src/pkg/github/webhook_pr_claims_test.go b/src/pkg/github/webhook_pr_claims_test.go new file mode 100644 index 0000000000..d13fc88dc7 --- /dev/null +++ b/src/pkg/github/webhook_pr_claims_test.go @@ -0,0 +1,259 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// hivecommons/hive#14814: a `pull_request` webhook must link the PR to the +// issues it claims the moment it lands, not on the next reconcile pass. + +func webhookPRPayload(action string, pr map[string]any) []byte { + p := map[string]any{"action": action, "repository": map[string]any{"full_name": "org/repo"}, "pull_request": pr} + b, _ := json.Marshal(p) + return b +} + +func webhookPRObject(number int, body, author, state string) map[string]any { + return map[string]any{ + "number": number, + "title": "Fix the thing", + "body": body, + "state": state, + "html_url": "https://github.com/org/repo/pull/" + string(rune('0'+number)), + "user": map[string]any{"login": author}, + "head": map[string]any{"ref": "fix-thing", "sha": "abc123"}, + } +} + +func TestHandleWebhookEventPullRequestRecordsClaims(t *testing.T) { + c, clock := setupWebhookCacheTest(t) + var got []PRClaimDelivery + SetPRClaimsHook(func(d PRClaimDelivery) { got = append(got, d) }) + t.Cleanup(func() { SetPRClaimsHook(nil) }) + + // Pre-populate the open-PR link cache so the delivery's invalidation is observable. + cache := c.openPRLinks() + cache.mu.Lock() + cache.repos["repo"] = &openPRLinkIndex{fetchedAt: clock.now} + cache.mu.Unlock() + + res, err := c.HandleWebhookEvent("pull_request", webhookPRPayload("opened", webhookPRObject(9, "Fixes #7\nRefs #8", "alice", "open"))) + if err != nil { + t.Fatal(err) + } + if !res.KnownRepo { + t.Fatalf("result = %+v, want known repo", res) + } + if len(res.ClaimedIssues) != 2 || res.ClaimedIssues[0] != 7 || res.ClaimedIssues[1] != 8 { + t.Fatalf("ClaimedIssues = %v, want [7 8]", res.ClaimedIssues) + } + if len(got) != 1 { + t.Fatalf("hook calls = %d, want 1", len(got)) + } + d := got[0] + if d.Repo != "repo" || d.Number != 9 || d.Action != "opened" || d.State != PRStateOpen || !d.At.Equal(clock.now) { + t.Fatalf("delivery = %+v", d) + } + byIssue := map[int]IssueClaim{} + for _, cl := range d.Claims { + byIssue[cl.Issue] = cl + } + if cl := byIssue[7]; !cl.ExternalAuthor || cl.Reference || cl.PRAuthor != "alice" || cl.PRState != PRStateOpen { + t.Fatalf("claim on #7 = %+v, want external closing claim by alice", cl) + } + if cl := byIssue[8]; !cl.Reference { + t.Fatalf("claim on #8 = %+v, want reference claim", cl) + } + cache.mu.Lock() + _, still := cache.repos["repo"] + cache.mu.Unlock() + if still { + t.Fatal("open-PR link cache for repo must be invalidated by the delivery") + } + + // Actions that cannot change the claims do not fire the hook. + for _, action := range []string{"labeled", "review_requested", "assigned"} { + if _, err := c.HandleWebhookEvent("pull_request", webhookPRPayload(action, webhookPRObject(9, "Fixes #7", "alice", "open"))); err != nil { + t.Fatal(err) + } + } + if len(got) != 1 { + t.Fatalf("hook calls after no-op actions = %d, want still 1", len(got)) + } + + // Unknown repo: no hook. + if _, err := c.HandleWebhookEvent("pull_request", []byte(`{"action":"opened","repository":{"full_name":"other/repo"},"pull_request":{"number":1,"body":"Fixes #7","state":"open"}}`)); err != nil { + t.Fatal(err) + } + if len(got) != 1 { + t.Fatalf("hook fired for an unmanaged repo: %d calls", len(got)) + } + + // Merged close carries the merge state. + merged := webhookPRObject(9, "Fixes #7", "alice", "closed") + merged["merged"] = true + merged["merged_at"] = clock.now.Format(time.RFC3339) + if _, err := c.HandleWebhookEvent("pull_request", webhookPRPayload("closed", merged)); err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[1].State != PRStateMerged || !got[1].MergedAt.Equal(clock.now) { + t.Fatalf("merged delivery = %+v", got[len(got)-1]) + } + + // Unmerged close is closed. + if _, err := c.HandleWebhookEvent("pull_request", webhookPRPayload("closed", webhookPRObject(9, "Fixes #7", "alice", "closed"))); err != nil { + t.Fatal(err) + } + if len(got) != 3 || got[2].State != PRStateClosed { + t.Fatalf("closed delivery = %+v", got[len(got)-1]) + } + + // No hook installed: still accepted, response still lists the claims. + SetPRClaimsHook(nil) + res, err = c.HandleWebhookEvent("pull_request", webhookPRPayload("opened", webhookPRObject(10, "Closes #11", "bob", "open"))) + if err != nil { + t.Fatal(err) + } + if len(res.ClaimedIssues) != 1 || res.ClaimedIssues[0] != 11 { + t.Fatalf("ClaimedIssues without hook = %v, want [11]", res.ClaimedIssues) + } +} + +func TestClaimLedgerApplyPRDelivery(t *testing.T) { + now := time.Date(2026, 10, 20, 1, 0, 0, 0, time.UTC) + l := NewClaimLedger(filepath.Join(t.TempDir(), "claims.json"), testLogger()) + l.now = func() time.Time { return now } + identity := HiveIdentity{AppLogin: "hive[bot]"} + pr := func(number int, body, author string) *gh.PullRequest { + return &gh.PullRequest{ + Number: gh.Ptr(number), Title: gh.Ptr("t"), Body: gh.Ptr(body), + User: &gh.User{Login: gh.Ptr(author)}, State: gh.Ptr("open"), + Head: &gh.PullRequestBranch{Ref: gh.Ptr("branch")}, + } + } + delivery := func(number int, body, author, state string, at time.Time) PRClaimDelivery { + return PRClaimDelivery{Repo: "repo", Number: number, Action: "opened", State: state, At: at, + Claims: claimsFromPR(pr(number, body, author), "repo", identity, at)} + } + + // Open external PR: claim recorded and visible to Lookup. + rec, rel := l.ApplyPRDelivery(delivery(100, "Fixes #1\nFixes #2", "alice", PRStateOpen, now)) + if rec != 2 || rel != 0 { + t.Fatalf("open: recorded=%d released=%d, want 2/0", rec, rel) + } + c1, ok := l.Lookup("repo", 1) + if !ok || c1.PRNumber != 100 || !c1.ExternalAuthor || c1.PRState != PRStateOpen || !c1.FirstObservedAt.Equal(now) { + t.Fatalf("claim #1 = %+v ok=%v", c1, ok) + } + + // Edited to drop #2: #2 released, #1 kept with FirstObservedAt intact. + later := now.Add(5 * time.Minute) + rec, rel = l.ApplyPRDelivery(delivery(100, "Fixes #1", "alice", PRStateOpen, later)) + if rec != 1 || rel != 1 { + t.Fatalf("edited: recorded=%d released=%d, want 1/1", rec, rel) + } + if _, ok := l.Lookup("repo", 2); ok { + t.Fatal("#2 must be released after the PR stopped naming it") + } + c1, _ = l.Lookup("repo", 1) + if !c1.FirstObservedAt.Equal(now) || !c1.ObservedAt.Equal(later) { + t.Fatalf("claim #1 after edit = %+v, want FirstObservedAt carried forward", c1) + } + + // Another PR's claim on a different issue is untouched by this PR's deliveries. + if rec, _ := l.ApplyPRDelivery(delivery(200, "Fixes #3", "bob", PRStateOpen, later)); rec != 1 { + t.Fatalf("second PR recorded=%d, want 1", rec) + } + + // Closed without merging: this PR's claims released, the other PR's kept. + rec, rel = l.ApplyPRDelivery(delivery(100, "Fixes #1", "alice", PRStateClosed, later)) + if rec != 0 || rel != 1 { + t.Fatalf("closed: recorded=%d released=%d, want 0/1", rec, rel) + } + if _, ok := l.Lookup("repo", 1); ok { + t.Fatal("#1 must be released after the PR closed unmerged") + } + if _, ok := l.Lookup("repo", 3); !ok { + t.Fatal("#3 from the other PR must survive") + } + + // Merged: recorded as a merged claim anchored at the merge. + d := delivery(200, "Fixes #3", "bob", PRStateMerged, later) + d.MergedAt = later + rec, rel = l.ApplyPRDelivery(d) + if rec != 1 || rel != 0 { + t.Fatalf("merged: recorded=%d released=%d, want 1/0 (open claim replaced in place)", rec, rel) + } + c3, ok := l.Lookup("repo", 3) + if !ok || !c3.MergedPR || c3.PRState != PRStateMerged || !c3.MergedAt.Equal(later) { + t.Fatalf("merged claim #3 = %+v ok=%v", c3, ok) + } + + // Nil ledger / empty delivery: no-ops. + var nilLedger *ClaimLedger + if rec, rel := nilLedger.ApplyPRDelivery(d); rec != 0 || rel != 0 { + t.Fatal("nil ledger must be a no-op") + } + if rec, rel := l.ApplyPRDelivery(PRClaimDelivery{}); rec != 0 || rel != 0 { + t.Fatal("empty delivery must be a no-op") + } +} + +func TestClaimLedgerApplyPRDeliveryFiltersSnapshot(t *testing.T) { + now := time.Date(2026, 10, 20, 1, 0, 0, 0, time.UTC) + l := NewClaimLedger(filepath.Join(t.TempDir(), "claims.json"), testLogger()) + l.now = func() time.Time { return now } + snap := &ActionableResult{Issues: IssueResult{Items: []Issue{{Repo: "repo", Number: 1}, {Repo: "repo", Number: 2}}, Count: 2}} + + d := PRClaimDelivery{Repo: "repo", Number: 50, Action: "opened", State: PRStateOpen, At: now, + Claims: claimsFromPR(&gh.PullRequest{Number: gh.Ptr(50), Body: gh.Ptr("Fixes #1"), + User: &gh.User{Login: gh.Ptr("alice")}, State: gh.Ptr("open"), + Head: &gh.PullRequestBranch{Ref: gh.Ptr("b")}}, "repo", HiveIdentity{AppLogin: "hive[bot]"}, now)} + l.ApplyPRDelivery(d) + if n := FilterClaimedIssues(snap, l, nil, testLogger()); n != 1 { + t.Fatalf("suppressed=%d, want 1", n) + } + if snap.Issues.Count != 1 || snap.Issues.Items[0].Number != 2 { + t.Fatalf("snapshot after filter = %+v, want only #2", snap.Issues) + } +} + +func TestPRClaimDeliveryClaimedIssues(t *testing.T) { + d := PRClaimDelivery{Repo: "repo", Claims: []IssueClaim{ + {Repo: "repo", Issue: 9}, {Repo: "repo", Issue: 3}, {Repo: "repo", Issue: 9}, + {Repo: "other", Issue: 1}, {Repo: "repo", Issue: 0}, + }} + got := d.ClaimedIssues() + if len(got) != 2 || got[0] != 3 || got[1] != 9 { + t.Fatalf("ClaimedIssues = %v, want [3 9]", got) + } +} + +func TestIssueDispatchBlockReasonClosedIssue(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/org/repo/issues/7": + _ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": "closed", "labels": []any{}}) + default: + t.Errorf("unexpected GitHub call %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusInternalServerError) + } + })) + t.Cleanup(srv.Close) + c := newTestClient(t, srv, "org", []string{"repo"}) + reason, err := c.IssueDispatchBlockReason(context.Background(), "repo", 7) + if err != nil { + t.Fatal(err) + } + if reason != ClaimBlockReasonIssueClosed { + t.Fatalf("reason = %q, want %q", reason, ClaimBlockReasonIssueClosed) + } +}