diff --git a/changelog.d/added-15023-relay-blocked-blocker.md b/changelog.d/added-15023-relay-blocked-blocker.md new file mode 100644 index 0000000000..f0fa0eaec3 --- /dev/null +++ b/changelog.d/added-15023-relay-blocked-blocker.md @@ -0,0 +1 @@ +- A contributor blocked verdict that names its blocker (`owner/repo#N`, `#N`, or an issue/PR URL) now records it on the task issue — a native GitHub "blocked by" link for an open issue, a `hive:blocked-on` marker for an open PR — so the hive lifts `blocked` itself once the blocker closes. diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index 73d596a71e..c264315203 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -112,7 +112,7 @@ Some hive-authored labels look like provenance but are read as signals, so they | `hive/partially-addressed` | Issues | Close-on-merge sweep, PR-claim label sync and task-list sweep | A merged PR covered only part of the issue ([#11931](https://github.com/hivecommons/hive/issues/11931)): applied instead of `hive/likely-done` when the PR has no closing keyword (`Fixes`/`Closes`/`Resolves #N`) for the issue, its body carries a remainder/out-of-scope paragraph, or none of the backtick-quoted paths cited in the issue body is among its changed files. No `/fixed` prompt is posted, `hive/likely-done` is suppressed, and the issue stays in the actionable pool; the `` comment lists the cited paths no merged PR changed as `Not yet touched: ...`. | Display; suppresses likely-done | Hive | Close-on-merge sweep for issues behind a confirmation gate | Hive removes it when a later merged PR fully covers the issue and `hive/likely-done` is applied; humans may remove it | Fixed label (`src/pkg/github/close_on_merge.go`, `src/pkg/github/task_list_sweep.go`) | | `hive/verified-open` | Issues | Verify-once kick path, PR-claim label sync and close-on-merge | A `hive/likely-done` / already-done claim from a merged PR was checked and the issue is NOT finished ([#11931](https://github.com/hivecommons/hive/issues/11931)): the agent that verified it labels the issue (`src/pkg/scheduler/kickmessage.go` "verify once" instruction) so later kicks say "already verified — implement the rest" and the claim sync never re-applies `hive/likely-done` from the same stale claim (`src/pkg/github/prclaims.go`). Merged-PR evidence, orthogonal to the stage: the issue keeps moving `010 → 020 → 030 → 040` as new work starts. | Suppresses likely-done; kick wording | Agent (verify-once kick) / Hive | Verify-once kick, claim sync | Human removes when the issue is really done, or close-on-merge closes the issue | Fixed label (`src/pkg/github/prclaims.go` `VerifiedOpenLabel`, `src/cmd/hive/verifyonce.go`) | | `hive/already-done` | Issues | Contributor queue, already-done verdict close path, and dashboard | Contributor already-done verdict/confirmation; default contributor skip label and done band. When the verdict cites a PR that the API verifies as merged on the default branch, Hive labels the issue and runs the normal completed close path; human-filed bugs close too unless `hive: needs-confirmation` or `issues.reporter_confirmation` opted into the reporter gate. A verdict that cites no PR/commit, or whose citation fails verification, is never labelled: Hive comments that the contributor reports it may be resolved and holds it from offers for `hub.contribute_already_done_hold_days`. | Contributor hard skip; dashboard display; conditional close | Hive/contributor flow | Contributor admission, verified verdict settlement, issue close gate | Human removes/reopens or confirms reporter-gated bugs | `hub.contribute_already_done_label`, fixed label (`src/pkg/config/hub_config.go:196-208`, `src/pkg/config/defaults.go:275-289`, `src/pkg/dashboard/contribute_verdict_settle.go`, `src/pkg/github/issue_close.go`) | -| `blocked` | Issues | Contributor queue, dashboard issue bands, un-park sweep | Always included in contributor skip patterns and default waiting band. Does not by itself stop spoke-agent enumeration unless also exempt/held/filtered. It parks the issue on a person for the un-park sweep (#12376): Hive keeps the "What to reply" notice on it, and `/hive approve` (lift and re-offer) or `/hive decision ` (lift with instructions) remove it; label approval removes it only when the App bot applied it. A contributor blocked verdict whose reason says a person must act (an admin, maintainer, owner or operator; no other item, upstream or release named) is labelled `needs-human` instead. The label records no reason: the dashboard row signal and BLOCKED pill hover name the open GitHub "blocked by" links when the issue has them (`Issue.DependsOn`), and otherwise say the label records no reason. Blocked-by links are read for actionable issues only, so held and parked rows always show the label-only text. | Contributor hard skip; display | Human, or Hive App on a contributor blocked verdict | Contributor admission/dashboard render | Remove label. Hive's hard-suppress reconcile (#12002) lifts a `blocked` whose newest label event is a `labeled` by the App bot once a PR referencing the issue merges after it (a PR in one of the hive's repos authored by the App bot or `project.ai_author`; a person's PR that only mentions the issue never counts), posting one note carrying ``; a human-applied (or re-applied) `blocked` is never lifted. The blocked sweep never lifts a contributor verdict's `blocked`: its marker-less lift is for review-backlog items only (see the review-backlog `blocked` row). | `hub.contribute_skip_labels`, dashboard bands (`src/pkg/config/hub_config.go:136-155`, `src/pkg/config/hub_config.go:469-492`, `src/docs/dashboard.md:105-140`) | +| `blocked` | Issues | Contributor queue, dashboard issue bands, un-park sweep | Always included in contributor skip patterns and default waiting band. Does not by itself stop spoke-agent enumeration unless also exempt/held/filtered. It parks the issue on a person for the un-park sweep (#12376): Hive keeps the "What to reply" notice on it, and `/hive approve` (lift and re-offer) or `/hive decision ` (lift with instructions) remove it; label approval removes it only when the App bot applied it. A contributor blocked verdict whose reason says a person must act (an admin, maintainer, owner or operator; no other item, upstream or release named) is labelled `needs-human` instead. When a contributor blocked verdict's reason names its blocker (`owner/repo#N`, `#N`, or an issue or PR URL; the first one that is not the issue itself), the hub records it once: an open issue becomes a native GitHub "blocked by" link on the task issue, an open PR a `` comment, so the hard-suppress reconcile or the blocked sweep lifts `blocked` when it closes; a closed or unreadable blocker records nothing ([#15023](https://github.com/hivecommons/hive/issues/15023)). Otherwise the label records no reason: the dashboard row signal and BLOCKED pill hover name the open GitHub "blocked by" links when the issue has them (`Issue.DependsOn`), and otherwise say the label records no reason. Blocked-by links are read for actionable issues only, so held and parked rows always show the label-only text. | Contributor hard skip; display | Human, or Hive App on a contributor blocked verdict | Contributor admission/dashboard render | Remove label. Hive's hard-suppress reconcile (#12002) lifts a `blocked` whose newest label event is a `labeled` by the App bot once a PR referencing the issue merges after it (a PR in one of the hive's repos authored by the App bot or `project.ai_author`; a person's PR that only mentions the issue never counts), posting one note carrying ``; a human-applied (or re-applied) `blocked` is never lifted. The blocked sweep never lifts a contributor verdict's `blocked`: its marker-less lift is for review-backlog items only (see the review-backlog `blocked` row). | `hub.contribute_skip_labels`, dashboard bands (`src/pkg/config/hub_config.go:136-155`, `src/pkg/config/hub_config.go:469-492`, `src/docs/dashboard.md:105-140`) | | `needs-direction` (retired) | Issues | Issue stage reconciler (migration only) | Retired ([#12683](https://github.com/hivecommons/hive/issues/12683)): nothing writes it. `stage/045-needs-decision` is the single "issue parked for a maintainer ruling" signal (owner decision: `stage/085-needs-decision` is PR-only). An open issue still carrying it is read as parked (same hard suppress, same un-park), the issue stage reconciler adds `stage/045-needs-decision` and then removes the retired label, and the label definition is deleted from the repo once no open item carries it. The scanner's "needs-direction (scanner): …" comment may remain as the explanation text accompanying the 045 transition — no label. | Hard suppress until migrated | — (legacy) | Issue stage reconciler | Migrated to `stage/045-needs-decision` (`src/pkg/github/legacy_decision_labels.go`) | Fixed legacy spelling (`src/pkg/config/issue_filter.go`) | | `needs-decision` (retired) | Issues, PRs | Issue stage reconciler (migration only); PR lanes read it as a hold modifier until gone | Retired ([#12683](https://github.com/hivecommons/hive/issues/12683)): nothing writes it. The relay's `hive-open-issue --needs-decision` and the configured `project.issue_filter.hard_suppress_labels.needs_decision` / `hub.contribute_needs_decision_label` now default to `stage/045-needs-decision`; a configured legacy spelling (or `stage/085-needs-decision`) is upgraded. Migration as for `needs-direction`. | Hard suppress until migrated | — (legacy) | Issue stage reconciler | Migrated to `stage/045-needs-decision` (`src/pkg/github/legacy_decision_labels.go`) | `hub.contribute_needs_decision_label` (`src/pkg/config/hub_config.go`, `src/pkg/config/issue_filter.go`) | | `needs-triage`, `discussion`, `question`, `tracking`, `epic` | Issues | Contributor queue | Default contributor skip labels/patterns. | Contributor hard skip | Human/Hive | Contributor admission | Remove label or config | `hub.contribute_skip_labels`, `HIVE_CONTRIBUTE_SKIP_LABELS` (`src/pkg/config/hub_config.go:136-155`, `src/pkg/config/hub_config.go:469-492`) | diff --git a/src/pkg/dashboard/contribute_verdict_blocker.go b/src/pkg/dashboard/contribute_verdict_blocker.go new file mode 100644 index 0000000000..87c974694e --- /dev/null +++ b/src/pkg/dashboard/contribute_verdict_blocker.go @@ -0,0 +1,60 @@ +package dashboard + +import ( + "context" + "time" + + ghpkg "github.com/hivecommons/hive/pkg/github" +) + +// A blocked verdict's `blocked` label is a gate only a human lifts unless the +// hive can read what it waits on (hivecommons/hive#15023). When the reason +// names its blocker, the hub records it — a native "blocked by" link for an +// open issue, a blocked-on marker for an open PR — so the existing reconciles +// lift `blocked` once the blocker closes. A reason with no resolvable +// reference, a closed blocker or a failed read records nothing: the block +// stays human-lifted, as before. + +// verdictBlockerRecordTimeout bounds the detached GitHub work: one blocker +// read, one blocker-list or comment read, at most one write. +const verdictBlockerRecordTimeout = 30 * time.Second + +// recordVerdictBlocker records the blocker a blocked verdict's reason names +// on the task issue. Runs detached from the read loop; callers `go` it. A +// re-delivered verdict naming the same blocker is written at most once per +// hub; GitHub-side checks cover restarts. +func (h *ContributeWSHub) recordVerdictBlocker(task *WSTaskAssign, reason string) { + if h == nil || task == nil || task.Kind != "issue" || task.Repo == "" || task.Number <= 0 || task.ExternalID != "" { + return + } + blocker, ok := ghpkg.ParseVerdictBlocker(reason, task.Repo, task.Number) + if !ok { + return + } + key := task.identityKey() + "->" + blocker.String() + if _, seen := h.verdictBlockersRecorded.LoadOrStore(key, struct{}{}); seen { + return + } + ctx, cancel := context.WithTimeout(context.Background(), verdictBlockerRecordTimeout) + defer cancel() + outcome, err := h.recordVerdictBlockerOnForge(ctx, task.Repo, task.Number, blocker) + if err != nil { + // Forget the key so a later re-delivery may try again. + h.verdictBlockersRecorded.Delete(key) + h.logger.Warn("[contribute-ws] blocked verdict: could not record the named blocker", + "repo", task.Repo, "number", task.Number, "blocker", blocker.String(), "error", err) + return + } + h.logger.Info("[contribute-ws] blocked verdict: recorded the named blocker", + "repo", task.Repo, "number", task.Number, "blocker", blocker.String(), "outcome", string(outcome)) +} + +func (h *ContributeWSHub) recordVerdictBlockerOnForge(ctx context.Context, repo string, number int, blocker ghpkg.VerdictBlocker) (ghpkg.VerdictBlockerOutcome, error) { + if h.verdictBlockerRecorder != nil { + return h.verdictBlockerRecorder(ctx, repo, number, blocker) + } + if h.server == nil || h.server.deps == nil || h.server.deps.GHClient == nil { + return "", ghpkg.ErrNoGitHubClient + } + return h.server.deps.GHClient.RecordVerdictBlocker(ctx, repo, number, blocker) +} diff --git a/src/pkg/dashboard/contribute_verdict_blocker_test.go b/src/pkg/dashboard/contribute_verdict_blocker_test.go new file mode 100644 index 0000000000..254ec31213 --- /dev/null +++ b/src/pkg/dashboard/contribute_verdict_blocker_test.go @@ -0,0 +1,94 @@ +package dashboard + +import ( + "context" + "errors" + "sync" + "testing" + + ghpkg "github.com/hivecommons/hive/pkg/github" +) + +// verdictBlockerFixture records what the hub asked the forge to record. +type verdictBlockerFixture struct { + mu sync.Mutex + calls []string + err error +} + +func (f *verdictBlockerFixture) record(_ context.Context, repo string, number int, b ghpkg.VerdictBlocker) (ghpkg.VerdictBlockerOutcome, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, repo+"->"+b.String()) + if f.err != nil { + return "", f.err + } + return ghpkg.VerdictBlockerLinked, nil +} + +func (f *verdictBlockerFixture) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.calls) +} + +// hivecommons/hive#15023: a blocked verdict that names its blocker records it +// once per task; a reason with no reference, a non-issue task and a +// re-delivered verdict write nothing. +func TestRecordVerdictBlocker_SeamAndDedupe(t *testing.T) { + hub, _ := covK2Hub(t) + fx := &verdictBlockerFixture{} + hub.verdictBlockerRecorder = fx.record + task := &WSTaskAssign{Kind: "issue", Repo: "projectbluefin/testsuite", Number: 975} + + hub.recordVerdictBlocker(nil, "blocked on ublue-os/server#450") + hub.recordVerdictBlocker(&WSTaskAssign{Kind: "pr", Repo: "o/r", Number: 5}, "blocked on #6") + hub.recordVerdictBlocker(&WSTaskAssign{Kind: "issue", Repo: "o/r", Number: 5, ExternalID: "LIN-1"}, "blocked on #6") + hub.recordVerdictBlocker(task, blockedReason) + if n := fx.count(); n != 0 { + t.Fatalf("no reference or a non-GitHub-issue task must record nothing, got %v", fx.calls) + } + + hub.recordVerdictBlocker(task, "#975 is blocked on the open issue ublue-os/server#450") + if len(fx.calls) != 1 || fx.calls[0] != "projectbluefin/testsuite->ublue-os/server#450" { + t.Fatalf("the named blocker must be recorded on the task issue, got %v", fx.calls) + } + hub.recordVerdictBlocker(task, "still blocked on ublue-os/server#450") + if n := fx.count(); n != 1 { + t.Fatalf("a re-delivered verdict must not record twice, got %v", fx.calls) + } +} + +func TestRecordVerdictBlocker_ErrorAllowsRetry(t *testing.T) { + hub, _ := covK2Hub(t) + fx := &verdictBlockerFixture{err: errors.New("boom")} + hub.verdictBlockerRecorder = fx.record + task := &WSTaskAssign{Kind: "issue", Repo: "o/r", Number: 5} + + hub.recordVerdictBlocker(task, "blocked on o/x#9") + fx.err = nil + hub.recordVerdictBlocker(task, "blocked on o/x#9") + if n := fx.count(); n != 2 { + t.Fatalf("a failed record must not dedupe the retry, got %v", fx.calls) + } +} + +// A tooling-failure verdict is reclassified idle before the blocker hook, so +// a reason that happens to cite a reference writes nothing. +func TestRecordVerdictBlocker_ToolingReclassifiedWritesNothing(t *testing.T) { + reason := "the push to my fork is rejected; see hivecommons/hive#11775" + verdict, ok := reclassifyToolingBlockedVerdict(completionVerdictBlocked, reason) + if !ok || verdict == completionVerdictBlocked { + t.Fatalf("tooling reason must be reclassified away from blocked, got (%q, %v)", verdict, ok) + } +} + +func TestRecordVerdictBlocker_NoClientIsLogged(t *testing.T) { + hub, _ := covK2Hub(t) + if hub.server != nil && hub.server.deps != nil { + hub.server.deps.GHClient = nil + } + if _, err := hub.recordVerdictBlockerOnForge(context.Background(), "o/r", 5, ghpkg.VerdictBlocker{Repo: "o/r", Number: 6}); !errors.Is(err, ghpkg.ErrNoGitHubClient) { + t.Fatalf("no GitHub client must report ErrNoGitHubClient, got %v", err) + } +} diff --git a/src/pkg/dashboard/contribute_ws.go b/src/pkg/dashboard/contribute_ws.go index a6ad28fc4e..03bc92d9ce 100644 --- a/src/pkg/dashboard/contribute_ws.go +++ b/src/pkg/dashboard/contribute_ws.go @@ -1213,6 +1213,11 @@ type ContributeWSHub struct { // GHClient. gateParkRekicks records the one re-kick each issue gets. gateParkReleaser func(ctx context.Context, repo string, number int, reporter, reason string) error gateParkRekicks gateParkRekicks + // verdictBlockerRecorder is the seam for recording the blocker a blocked + // verdict names (contribute_verdict_blocker.go); nil means use GHClient. + // verdictBlockersRecorded dedupes re-delivered verdicts per task. + verdictBlockerRecorder func(ctx context.Context, repo string, number int, blocker ghpkg.VerdictBlocker) (ghpkg.VerdictBlockerOutcome, error) + verdictBlockersRecorded sync.Map // wrongBaseBranchChecker validates a wrong_base target against the target // repository; nil means use GHClient.BranchExists. wrongBaseParker is the // mutation seam for the invalid/unverifiable fallback. @@ -4486,6 +4491,14 @@ func (s *wsSession) handleTaskComplete(msg WSMessage) { go h.releaseToolingBlockedIssue(completedTask, s.contributor.profile.GitHubUsername, verdictReason) } } + // A blocked verdict that names its blocker (owner/repo#N, #N, an + // issue or PR URL) is recorded as a native "blocked by" link or a + // blocked-on PR marker, so the hive lifts `blocked` itself when + // the blocker closes (hivecommons/hive#15023). + if verdict == completionVerdictBlocked && completedTask != nil { + taskCopy := *completedTask + go h.recordVerdictBlocker(&taskCopy, verdictReason) + } // A needs-decision verdict whose reason is the target repository's // OWN confirmation gate — "AGENTS.md says offer a spec and wait", // "registered sibling checkout missing" — is not a decision a diff --git a/src/pkg/dashboard/contribute_ws_blocked_verdict_test.go b/src/pkg/dashboard/contribute_ws_blocked_verdict_test.go index 236fbfe756..d251eaf178 100644 --- a/src/pkg/dashboard/contribute_ws_blocked_verdict_test.go +++ b/src/pkg/dashboard/contribute_ws_blocked_verdict_test.go @@ -202,6 +202,16 @@ func TestBlockedVerdict_WireShape(t *testing.T) { return ghpkg.SettleVerification{Settled: true, Claim: ghpkg.IssueClaim{PRNumber: ref.Number, MergedPR: true}}, nil } + // #15023: the blocker the reason names is recorded on the task issue. + recorded := make(chan string, 4) + hub.verdictBlockerRecorder = func(_ context.Context, repo string, number int, b ghpkg.VerdictBlocker) (ghpkg.VerdictBlockerOutcome, error) { + if number != 105 { + t.Errorf("blocker recorded on #%d, want #105", number) + } + recorded <- repo + "->" + b.String() + return ghpkg.VerdictBlockerLinked, nil + } + conn.WriteJSON(WSMessage{Type: "ready", Seq: 2}) assign := readMsg(t, conn) if assign.Type != "task_assign" { @@ -254,6 +264,15 @@ func TestBlockedVerdict_WireShape(t *testing.T) { if !ok || !rec.Blocked || rec.Reporter != "blocked-user" { t.Fatalf("ledger row must be the blocked marker for the reporting contributor, got ok=%v rec=%+v", ok, rec) } + + select { + case got := <-recorded: + if got != "myorg/repo1->projectbluefin/utah-packages#41" { + t.Fatalf("the named blocker must be recorded on the task issue, got %q", got) + } + case <-time.After(5 * time.Second): + t.Fatal("a blocked verdict naming its blocker must record it through the seam") + } } func TestNeedsDecisionVerdict_BooksFullCooldownAndLedgerMarker(t *testing.T) { diff --git a/src/pkg/github/verdict_blocker.go b/src/pkg/github/verdict_blocker.go new file mode 100644 index 0000000000..38aac0f83e --- /dev/null +++ b/src/pkg/github/verdict_blocker.go @@ -0,0 +1,153 @@ +package github + +// Verdict-named blockers (hivecommons/hive#15023). +// +// A contributor relay backs a blocked verdict with the repository's `blocked` +// label, but writes nothing the hive can read about WHAT it is blocked on, so +// only a human could ever lift it — and the next agent re-discovered the same +// dependency (projectbluefin/testsuite#975, blocked on server#450, was +// re-reported by eight agents in two weeks). When the verdict's reason names +// its blocker, the hub records it in a form the hive already lifts on close: +// +// - an open issue becomes a native GitHub "blocked by" link, which +// ReconcileHiveHardSuppress lifts once every native blocker is closed; +// - an open pull request becomes a `` marker +// comment, which ReconcileBlockedIssues lifts once it merges or closes; +// - anything else (closed target, unreadable target) records nothing and +// the block stays human-lifted, exactly as before. + +import ( + "context" + "fmt" + "regexp" + "strconv" + "strings" +) + +// VerdictBlocker is one blocker reference parsed from a blocked verdict. +type VerdictBlocker struct { + Repo string // owner/repo + Number int +} + +// String renders the reference as owner/repo#N. +func (b VerdictBlocker) String() string { + return b.Repo + "#" + strconv.Itoa(b.Number) +} + +// verdictBlockerRefRE matches, leftmost first, a GitHub issue or PR URL, an +// owner/repo#N reference, or a bare #N. The qualified and bare forms consume +// the preceding character (Go regexp has no look-behind) so a reference glued +// to a word, a path or an HTML entity (`'`) is not taken. +var verdictBlockerRefRE = regexp.MustCompile( + `https?://github\.com/([A-Za-z0-9-]+/[A-Za-z0-9_.-]+)/(?:issues|pull)/(\d+)` + + `|(?:^|[^A-Za-z0-9_./#&-])([A-Za-z0-9-]+/[A-Za-z0-9_.-]+)#(\d+)\b` + + `|(?:^|[^A-Za-z0-9_./#&-])#(\d+)\b`) + +// ParseVerdictBlocker returns the first blocker reference in a blocked +// verdict's reason. A bare #N names taskRepo. A reference to the task issue +// itself is skipped, so "#975 is blocked on server#450" yields server#450. +func ParseVerdictBlocker(reason, taskRepo string, taskNumber int) (VerdictBlocker, bool) { + taskRepo = strings.TrimSpace(taskRepo) + for _, m := range verdictBlockerRefRE.FindAllStringSubmatch(reason, -1) { + var ref VerdictBlocker + var num string + switch { + case m[1] != "": + ref.Repo, num = m[1], m[2] + case m[3] != "": + ref.Repo, num = m[3], m[4] + default: + if taskRepo == "" { + continue + } + ref.Repo, num = taskRepo, m[5] + } + n, err := strconv.Atoi(num) + if err != nil || n <= 0 { + continue + } + ref.Number = n + if n == taskNumber && strings.EqualFold(ref.Repo, taskRepo) { + continue + } + return ref, true + } + return VerdictBlocker{}, false +} + +// VerdictBlockerOutcome is what RecordVerdictBlocker did. +type VerdictBlockerOutcome string + +const ( + // VerdictBlockerLinked: a native "blocked by" link was added. + VerdictBlockerLinked VerdictBlockerOutcome = "linked" + // VerdictBlockerAlreadyLinked: the native link already existed. + VerdictBlockerAlreadyLinked VerdictBlockerOutcome = "already_linked" + // VerdictBlockerMarked: a blocked-on PR marker comment was posted. + VerdictBlockerMarked VerdictBlockerOutcome = "marked" + // VerdictBlockerAlreadyMarked: the marker comment already existed. + VerdictBlockerAlreadyMarked VerdictBlockerOutcome = "already_marked" + // VerdictBlockerClosed: the blocker is already closed; nothing recorded. + VerdictBlockerClosed VerdictBlockerOutcome = "closed" +) + +// RecordVerdictBlocker records blocker as what repo#number is blocked on. It +// reads the blocker once: an open issue is linked natively (unless the link +// exists), an open PR gets the blocked-on marker comment (unless it is +// already there), and a closed one records nothing. A read failure is +// returned and nothing is written. +func (c *Client) RecordVerdictBlocker(ctx context.Context, repo string, number int, blocker VerdictBlocker) (VerdictBlockerOutcome, error) { + if c == nil || c.client == nil { + return "", ErrNoGitHubClient + } + owner, repoName := c.splitRepo(repo) + if err := validateRepoRef(owner, repoName); err != nil { + return "", fmt.Errorf("RecordVerdictBlocker: %w", err) + } + bOwner, bRepo := c.splitRepo(blocker.Repo) + if err := validateRepoRef(bOwner, bRepo); err != nil || number <= 0 || blocker.Number <= 0 { + return "", fmt.Errorf("RecordVerdictBlocker: invalid blocker %q for %s/%s#%d", blocker.String(), owner, repoName, number) + } + issue, _, err := c.client.Issues.Get(ctx, bOwner, bRepo, blocker.Number) + if err != nil { + return "", fmt.Errorf("reading blocker %s/%s#%d: %w", bOwner, bRepo, blocker.Number, err) + } + if !strings.EqualFold(issue.GetState(), "open") { + return VerdictBlockerClosed, nil + } + if issue.IsPullRequest() { + marker := BlockedOnMarker(bOwner+"/"+bRepo, blocker.Number) + posted, err := c.IssueCommentsContain(ctx, owner+"/"+repoName, number, marker) + if err != nil { + return "", err + } + if posted { + return VerdictBlockerAlreadyMarked, nil + } + if err := c.CreateIssueComment(ctx, owner+"/"+repoName, number, verdictBlockerMarkerComment(bOwner+"/"+bRepo, blocker.Number)); err != nil { + return "", err + } + return VerdictBlockerMarked, nil + } + existing, err := c.fetchBlockedBy(ctx, owner, repoName, number) + if err != nil { + return "", fmt.Errorf("listing blockers of %s/%s#%d: %w", owner, repoName, number, err) + } + for _, b := range existing { + if b.Number == blocker.Number && strings.EqualFold(b.Owner, bOwner) && strings.EqualFold(b.Repo, bRepo) { + return VerdictBlockerAlreadyLinked, nil + } + } + if err := c.AddBlockedBy(ctx, owner+"/"+repoName, number, issue.GetID()); err != nil { + return "", err + } + return VerdictBlockerLinked, nil +} + +// verdictBlockerMarkerComment is the comment that carries the blocked-on +// marker for a PR a blocked verdict named. +func verdictBlockerMarkerComment(prRepo string, pr int) string { + return BlockedOnMarker(prRepo, pr) + "\n" + + fmt.Sprintf("Hive: a contributor's agent reported this issue blocked on %s#%d, an open pull request. The `%s` label is lifted when it merges or closes.", prRepo, pr, BlockedLabel) +} diff --git a/src/pkg/github/verdict_blocker_test.go b/src/pkg/github/verdict_blocker_test.go new file mode 100644 index 0000000000..1590581900 --- /dev/null +++ b/src/pkg/github/verdict_blocker_test.go @@ -0,0 +1,202 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +func TestParseVerdictBlocker(t *testing.T) { + cases := []struct { + name string + reason string + want string // owner/repo#N, "" for no reference + }{ + {"qualified", "waiting on ublue-os/server#450 to land", "ublue-os/server#450"}, + {"bare names the task repo", "blocked until #12 is fixed", "projectbluefin/testsuite#12"}, + {"issue URL", "needs https://github.com/ublue-os/server/issues/450 first", "ublue-os/server#450"}, + {"PR URL", "see https://github.com/o/r/pull/7 which has not merged", "o/r#7"}, + {"no reference", "the upstream library has not released the API this needs", ""}, + {"first of two wins", "blocked on a/b#1 and later c/d#2", "a/b#1"}, + {"URL before qualified", "https://github.com/a/b/issues/3 then c/d#4", "a/b#3"}, + {"self reference skipped", "#975 is blocked on ublue-os/server#450", "ublue-os/server#450"}, + {"qualified self reference skipped", "projectbluefin/testsuite#975 waits on #976", "projectbluefin/testsuite#976"}, + {"only self", "#975 cannot move", ""}, + {"html entity is not a ref", "it's waiting on the release", ""}, + {"anchor in a word is not a ref", "see foo#12 and section#3", ""}, + {"comment anchor ignored", "https://github.com/a/b/issues/9#issuecomment-123", "a/b#9"}, + {"empty", "", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, ok := ParseVerdictBlocker(tc.reason, "projectbluefin/testsuite", 975) + if tc.want == "" { + if ok { + t.Fatalf("want no reference, got %s", got) + } + return + } + if !ok || got.String() != tc.want { + t.Fatalf("want %s, got %s (ok=%v)", tc.want, got, ok) + } + }) + } + if _, ok := ParseVerdictBlocker("blocked on #12", "", 1); ok { + t.Fatal("a bare #N with no task repo must not resolve") + } +} + +// verdictBlockerFake serves the blocker read, the task issue's blocked_by +// list and comments, and records every write. +type verdictBlockerFake struct { + mu sync.Mutex + blockers map[string]map[string]any // "owner/repo#N" -> issue JSON; absent -> 404 + blockedBy []wireBlocker + comments []string + links []int64 + posted []string +} + +func (f *verdictBlockerFake) server(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + path := r.URL.Path + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(path, "/dependencies/blocked_by") && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode(f.blockedBy) + case strings.HasSuffix(path, "/dependencies/blocked_by") && r.Method == http.MethodPost: + var body struct { + IssueID int64 `json:"issue_id"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + f.links = append(f.links, body.IssueID) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{}`)) + case strings.HasSuffix(path, "/comments") && r.Method == http.MethodGet: + out := make([]map[string]any, 0, len(f.comments)) + for i, c := range f.comments { + out = append(out, map[string]any{"id": i + 1, "body": c}) + } + _ = json.NewEncoder(w).Encode(out) + case strings.HasSuffix(path, "/comments") && r.Method == http.MethodPost: + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + f.posted = append(f.posted, body.Body) + f.comments = append(f.comments, body.Body) + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1000 + len(f.posted), "body": body.Body}) + case strings.HasPrefix(path, "/repos/") && strings.Contains(path, "/issues/") && r.Method == http.MethodGet: + var owner, repo string + var n int + parts := strings.Split(strings.TrimPrefix(path, "/repos/"), "/") + if len(parts) == 4 { + owner, repo = parts[0], parts[1] + fmt.Sscanf(parts[3], "%d", &n) + } + issue, ok := f.blockers[fmt.Sprintf("%s/%s#%d", owner, repo, n)] + if !ok { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"Not Found"}`)) + return + } + _ = json.NewEncoder(w).Encode(issue) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func TestRecordVerdictBlocker_OpenIssueLinksOnceByID(t *testing.T) { + f := &verdictBlockerFake{blockers: map[string]map[string]any{ + "ublue-os/server#450": {"id": 987654, "number": 450, "state": "open"}, + }} + c := newTestClient(t, f.server(t), "projectbluefin", []string{"testsuite"}) + ref := VerdictBlocker{Repo: "ublue-os/server", Number: 450} + + got, err := c.RecordVerdictBlocker(context.Background(), "projectbluefin/testsuite", 975, ref) + if err != nil || got != VerdictBlockerLinked { + t.Fatalf("want linked, got %q err=%v", got, err) + } + if len(f.links) != 1 || f.links[0] != 987654 { + t.Fatalf("AddBlockedBy must be called once with the blocker's database id, got %v", f.links) + } + + // Re-delivery: the link now exists on GitHub, so nothing is written again. + f.blockedBy = []wireBlocker{{Number: 450, State: "open", RepositoryURL: "https://api.github.com/repos/ublue-os/server"}} + got, err = c.RecordVerdictBlocker(context.Background(), "projectbluefin/testsuite", 975, ref) + if err != nil || got != VerdictBlockerAlreadyLinked { + t.Fatalf("want already_linked, got %q err=%v", got, err) + } + if len(f.links) != 1 || len(f.posted) != 0 { + t.Fatalf("re-delivery must write nothing, links=%v posted=%v", f.links, f.posted) + } +} + +func TestRecordVerdictBlocker_OpenPRPostsMarkerOnce(t *testing.T) { + f := &verdictBlockerFake{blockers: map[string]map[string]any{ + "o/r#7": {"id": 77, "number": 7, "state": "open", "pull_request": map[string]any{"url": "https://api.github.com/repos/o/r/pulls/7"}}, + }} + c := newTestClient(t, f.server(t), "o", []string{"r"}) + ref := VerdictBlocker{Repo: "o/r", Number: 7} + + got, err := c.RecordVerdictBlocker(context.Background(), "o/r", 5, ref) + if err != nil || got != VerdictBlockerMarked { + t.Fatalf("want marked, got %q err=%v", got, err) + } + if len(f.posted) != 1 || !strings.Contains(f.posted[0], BlockedOnMarker("o/r", 7)) { + t.Fatalf("the blocked-on marker comment must be posted once, got %v", f.posted) + } + if repo, pr, ok := ParseBlockedOnMarker(f.posted[0]); !ok || repo != "o/r" || pr != 7 { + t.Fatalf("the posted comment must parse as the blocked-on marker the sweep reads, got %s#%d ok=%v", repo, pr, ok) + } + if len(f.links) != 0 { + t.Fatalf("a PR blocker must not be linked natively, got %v", f.links) + } + + got, err = c.RecordVerdictBlocker(context.Background(), "o/r", 5, ref) + if err != nil || got != VerdictBlockerAlreadyMarked || len(f.posted) != 1 { + t.Fatalf("re-delivery must not post twice, got %q err=%v posted=%d", got, err, len(f.posted)) + } +} + +func TestRecordVerdictBlocker_ClosedOrMissingWritesNothing(t *testing.T) { + f := &verdictBlockerFake{blockers: map[string]map[string]any{ + "o/r#8": {"id": 88, "number": 8, "state": "closed"}, + }} + c := newTestClient(t, f.server(t), "o", []string{"r"}) + + got, err := c.RecordVerdictBlocker(context.Background(), "o/r", 5, VerdictBlocker{Repo: "o/r", Number: 8}) + if err != nil || got != VerdictBlockerClosed { + t.Fatalf("closed blocker: want closed, got %q err=%v", got, err) + } + if _, err := c.RecordVerdictBlocker(context.Background(), "o/r", 5, VerdictBlocker{Repo: "o/r", Number: 404}); err == nil { + t.Fatal("a 404 on the blocker read must be reported") + } + if len(f.links) != 0 || len(f.posted) != 0 { + t.Fatalf("closed or missing blockers must write nothing, links=%v posted=%v", f.links, f.posted) + } +} + +func TestRecordVerdictBlocker_RejectsBadInput(t *testing.T) { + var nilClient *Client + if _, err := nilClient.RecordVerdictBlocker(context.Background(), "o/r", 1, VerdictBlocker{Repo: "o/r", Number: 2}); err == nil { + t.Fatal("nil client must error") + } + f := &verdictBlockerFake{} + c := newTestClient(t, f.server(t), "o", []string{"r"}) + if _, err := c.RecordVerdictBlocker(context.Background(), "o/r", 1, VerdictBlocker{Repo: "o/r", Number: 0}); err == nil { + t.Fatal("a zero blocker number must error") + } +}