diff --git a/changelog.d/fixed-let-hive-decide-already-fixed.md b/changelog.d/fixed-let-hive-decide-already-fixed.md new file mode 100644 index 0000000000..bb4fb596b3 --- /dev/null +++ b/changelog.d/fixed-let-hive-decide-already-fixed.md @@ -0,0 +1 @@ +- "Let hive decide" now walks a decision ladder for contributor PRs — already fixed by a merged PR → mergeable as-is → rebase-then-merge → return to a connected contributor → adopt-supersede as the last resort — so a PR whose issue was already fixed and merged is closed as superseded with a note naming the merging PR instead of being adopted (#15219 / #15240). The decision names the author's tooling truthfully ("the author's clanker" vs "the author's hive"), the toast and PR comment say why, and the decide API exposes `decision.ladder {decision, reason, ruled_out}`. diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index b4cfe73489..8721bfeed5 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -286,7 +286,7 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. Rows also carry `rebase_merge: {state: approved|rebasing|ci-pending|merged|failed, actor, base, text, fail_reason, conflict_files[], armed_at}` while a *Rebase, then merge as maintainer* follow-through is live or just settled (persisted in `/data/rebase-merge-followups.json`; `fail_reason: foreign-head` when the head moved after the approval by someone other than the hive, so nothing merged), and `rebase: {attempt, max, exhausted, head, text}` on a conflicting PR the fixer is rebasing under the two-attempt loop guard (`/data/rebase-attempts.json`). | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:337`, `pkg/dashboard/api_repo_hold.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `merge-now` (*Approve & merge as maintainer*) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`; `queue-merge` (*Approve — let hive merge*) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` for the hive's merge sweep once CI is green and the head has soaked. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_repo_item_decision.go` | -| `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park}, notes, error}`); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | +| `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, summary, why, consequences[], alternatives[], writes: false, prior, notes}` — *Hive would: re-author #15029 as a hive PR with the same commits and merge it; #15029 will be closed as superseded. Why: author @Karibhou is untrusted and their clanker is offline.* The confirm popover shows **Let hive do that** / **Approve & merge as-is** / **Cancel**; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:341`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:342` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:343` | diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index 7efa15f542..de22e3af4d 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -1456,9 +1456,10 @@ The plain-words comment the delegate posts has four lines — **Hive decided** ( | Token | Plain words | Detail | |---|---|---| +| `already-fixed` | the issue was already fixed by a merged PR; closed as superseded | The issue this PR fixes is already closed and a merged PR closed it (or a merged PR declares it supersedes this one), so nothing is left to deliver. The hive closes the PR as superseded with a note naming the merging PR; it never adopts it. | | `capability-gap` | the GitHub App lacks a permission; deciding cannot clear it | The blocker is a missing GitHub App permission (for example `workflows`). Approving a direction would only re-apply needs-human, so the park stays until the owner grants the permission or a person applies the change. | | `ci-ratchet` | a CI hygiene gate, landed as a ratchet | A new CI hygiene gate lands as a ratchet: it records today's baseline and fails only on increases, so existing work is never blocked. | -| `contributor-offline` | the author's clanker hasn't been connected since the nudge | The PR's author has been offline since the hive nudged them, so the hive takes the work over instead of waiting. | +| `contributor-offline` | the author hasn't been reachable since the nudge | The PR's author (or their clanker or hive) has been offline since the hive nudged them, so the hive takes the work over instead of waiting. The decision itself names which: the author's clanker, a connected hive, or the author. | | `dedupe` | an older issue already tracks this | An older issue already tracks the same work; one thread keeps it moving. | | `default-approve` | no special rule applies; the hive took its own recommendation | No owner rule singles this issue out, so the hive went with its own recommendation — the reversible choice that keeps work moving. | | `default-release` | no special rule applies; a green branch is approved | No owner rule holds this PR back; its branch is green and a merge is reversible, so it is approved. | @@ -1467,10 +1468,13 @@ The plain-words comment the delegate posts has four lines — **Hive decided** ( | `flaky-test` | a flaky test, quarantined with a retry | The failure is a flaky test: it is quarantined with a retry and a separate deflake task is filed, so it blocks nothing. | | `hive-policy` | this changes the hive's own rules | This changes the hive's own settings, governance or security posture; the hive only recommends and the owner confirms. | | `llm-delegate` | decided by the hive's model under the owner's rules | No mechanical rule applied, so the hive's model decided under the owner's standing rules; the same safety rails applied. | +| `mergeable-as-is` | mergeable and green as it is; handed to the merge gate | The head is mergeable with green CI, so no adoption is needed: the hive approves it and the merge gate takes it as it is. | | `owner-only`, `owner_only` | only the hive owner can do this | This needs a secret, token or organization permission that only the hive owner holds; the hive cannot do it for you. | | `prefer-contributor` | a contributor's PR and a hive PR do the same work | A contributor's PR and a hive-authored PR cover the same work; the hive prefers the contributor's when it is mergeable and current. | | `rail-hold` | the item is on hold | The item carries the hold label; the hive never acts on a held item until a person releases the hold. | +| `rebase-then-merge` | only conflicts block it; a rebase then merge | Conflicts are the only blocker. The unattended rebase-then-merge path lands with hivecommons/hive#15104; until then the ladder records this rung and moves on. | | `reporter-trust` | the hold on an unknown reporter is cleared because the fix is sound | The PR was held until the reporter's trust was known; its fix is green and mergeable, so the hold is cleared. | +| `return-to-contributor` | the author's clanker or hive is connected; returned to them with the fix list | The author's clanker or hive is connected (or has picked the rework up), so the hive hands the PR back to them with the exact fix list instead of adopting it. | | `review-backlog` | the PR closed without merging, so the issue stays open | The fixing PR closed unmerged; the issue stays open and is re-triaged rather than auto-closed. | | `sentinel-trusted` | security-sensitive files changed, but the author is trusted | Security-sensitive files changed; because the author is trusted the hive approved, but a person must still remove the sentinel label before it merges. | | `sentinel-untrusted` | security-sensitive files changed; a maintainer must approve | Security-sensitive files changed in a PR from an author without write access; a maintainer must review and approve it. | @@ -1505,7 +1509,7 @@ The plain-words comment the delegate posts has four lines — **Hive decided** ( | `adoption-stalled:contributor-lane:workflow-path`, `capability:workflows-permission`, `contributor-lane:workflow-path`, `workflow-path` | the PR edits .github/workflows; the hive's App lacks the `workflows` permission, so it cannot adopt it | The PR changes files under .github/workflows. The hive's GitHub App has no `workflows` permission, so the adoption fence refuses to publish those edits from the hive. Grant the App the `workflows` permission and re-run the decision, or have a person rebase and merge it on GitHub, or close it as superseded. | | `adoption-undone` | the hive's copy was closed without merging and the adoption was undone | The hive opened its copy, but the copy was closed without merging and a fresh one could not be opened, so the adoption was undone and the PR is back in its normal flow. Re-run the decision to adopt it again, or act on GitHub. | | `author-association`, `contributor-lane:author-association`, `human-merge`, `ready-for-human-merge`, `untrusted-author` | no merge lane vouches for this PR's author; a maintainer merges | The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve & merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors. | -| `author-online` | the author's clanker is connected, so hive won't take the PR over | Adoption is for authors whose clanker has gone offline; this author's clanker is connected, so the hive leaves the PR with them. | +| `author-online` | the author's clanker or hive is connected, so hive won't take the PR over | Adoption is for authors whose clanker or hive has gone offline; this author's is connected, so the hive leaves the PR with them. | | `blocker`, `capability`, `human-only` | the hive can't do this itself | The item is blocked on something the hive cannot do: a permission the GitHub App lacks, or a step only a person may take. No decision clears it; grant the permission (and re-check) or do the step by hand (hivecommons/hive#15099). | | `behind` | the branch is behind the base branch | The branch is behind the base branch and must be updated before it can merge. | | `changes-requested`, `changes_requested`, `contributor-lane:changes-requested`, `human-changes-requested`, `request_changes`, `reviewer-verdict:request_changes` | a reviewer asked for changes; a new commit is needed | A reviewer asked for changes on this branch. Approving cannot override that: only a new commit, or a maintainer merging by hand, moves it. | diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index abdd22ca0e..535e9389b9 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -561,6 +561,7 @@ func (s *Server) decideDelegatedOne(ctx context.Context, repoFull string, number "verdict", string(d.Verdict), "rule", d.Rule, "actions", "", "noop", noop, "policy", delegatedecision.PolicyName, "decision", d.Text), "", repoFull, number) return delegatedOutcome{Decision: &d, Notes: notes, Result: &res} } + s.logDelegatedLadder(repoFull, number, d) notes, execErr := s.executeDelegatedDecision(ctx, in, d, user, mergerRole) notes = append(deciderNotes, notes...) result := delegatedRowActionResult(in, d, notes) @@ -632,6 +633,9 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb if err := s.gatherDelegatedPRContext(ctx, repoFull, pr, &in); err != nil { return in, err } + if err := s.gatherDelegatedLadderInput(ctx, repoFull, pr, &in); err != nil { + return in, err + } state := strings.ToLower(pr.GetMergeableState()) in.Conflicting = state == "dirty" || (pr.Mergeable != nil && !pr.GetMergeable()) green, err := delegatedHeadCIGreen(ctx, api, owner, repoName, pr, in.Conflicting, state) diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_test.go b/src/pkg/dashboard/api_repo_item_decide_delegated_test.go index 38f3972b33..b32177a47a 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_test.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_test.go @@ -935,3 +935,70 @@ func TestDelegatedDecisionLiftsStaleNeedsHuman(t *testing.T) { t.Fatalf("recommend-only lifted labels: %v", mock.removed) } } + +// hivecommons/hive#15289: the #15219 scenario end to end. A conflicting, +// offline clanker PR whose issue a merged PR already closed is closed as +// superseded with a note naming that PR — not adopted — and the job +// exposes the ladder. +func TestDelegatedAlreadyFixedClosesInsteadOfAdopting(t *testing.T) { + pinDelegatedClock(t, "2026-10-28T14:23:00Z") + mock := &repoItemDecisionMock{prForeign: true, prMergeState: "dirty", prBody: "Fixes #42", fixedIssueClosedBy: 43, + prLabels: []string{"author/clanker", "adoption/supersede", "stage/085-needs-decision", "needs-rebase"}} + srv := newDelegatedServer(t, mock) + srv.deps.Config.Governor.Labels.Stage.Adoption.Enabled = boolPtr(true) + w := postDelegated(t, srv, 8, "writer", `{"type":"pr","reason":"adoption-stalled:contributor-offline","caption":"adoption stalled"}`, nil) + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + job := decodeDelegatedJob(t, w) + d := job.Decision + if d == nil || d.Verdict != delegatedecision.VerdictCloseSuperseded || d.Rule != delegatedecision.RuleAlreadyFixed { + t.Fatalf("decision = %+v err=%s notes=%v", d, job.Error, job.Notes) + } + if d.Ladder == nil || d.Ladder.Decision != delegatedecision.RuleAlreadyFixed || len(d.Ladder.RuledOut) != 0 || !strings.Contains(d.Ladder.Reason, "#42 was already fixed by merged PR #43 (25de3ba)") { + t.Fatalf("ladder = %+v", d.Ladder) + } + if strings.Contains(strings.Join(mock.added, ","), delegatedecision.LabelAdoptSupersede) { + t.Fatalf("adoption queued for an already-fixed PR: %v", mock.added) + } + if len(mock.comments) != 1 || !strings.Contains(mock.comments[0], "#42 was already fixed by merged PR #43 (25de3ba)") || !strings.Contains(mock.comments[0], "Thank you") { + t.Fatalf("close note = %v", mock.comments) + } + closed := false + for _, e := range mock.edits { + if e["state"] == "closed" { + closed = true + } + } + if !closed || !strings.Contains(strings.Join(mock.added, ","), github.SupersededLabel) { + t.Fatalf("PR not closed as superseded: edits=%v added=%v", mock.edits, mock.added) + } + if job.Result == nil || job.Result.Action != rowActionClosed || job.Result.Outcome != "Closed as superseded: #42 already fixed by #43 (25de3ba)." { + t.Fatalf("result = %+v", job.Result) + } +} + +// Without a merged closer the same PR falls to the last rung — and the +// decision names the author's clanker, not a hive. +func TestDelegatedOfflineClankerAdoptsWithClankerWording(t *testing.T) { + pinDelegatedClock(t, "2026-10-28T14:23:00Z") + mock := &repoItemDecisionMock{prForeign: true, prMergeState: "dirty", prBody: "Fixes #42", + prLabels: []string{"author/clanker", "stage/085-needs-decision"}} + srv := newDelegatedServer(t, mock) + srv.deps.Config.Governor.Labels.Stage.Adoption.Enabled = boolPtr(true) + w := postDelegated(t, srv, 8, "writer", `{"type":"pr","reason":"adoption-stalled:contributor-offline","caption":"adoption stalled"}`, nil) + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + job := decodeDelegatedJob(t, w) + d := job.Decision + if d == nil || d.Verdict != delegatedecision.VerdictAdoptSupersede || d.Rule != delegatedecision.RuleContributorOffline { + t.Fatalf("decision = %+v err=%s", d, job.Error) + } + if d.Ladder == nil || len(d.Ladder.RuledOut) != 4 || !strings.Contains(strings.Join(d.Ladder.RuledOut, "\n"), "return-to-contributor: the author's clanker hasn't been connected since the nudge") { + t.Fatalf("ladder = %+v", d.Ladder) + } + if strings.Contains(d.Rationale, "author's hive") || job.Result == nil || !strings.HasSuffix(job.Result.Outcome, " Why: the author's clanker hasn't been connected since the nudge.") { + t.Fatalf("wording: rationale=%q result=%+v", d.Rationale, job.Result) + } +} diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index c6c061b681..75f3cab323 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -55,6 +55,12 @@ type repoItemDecisionMock struct { // commitBy maps a head SHA to the login GET /commits/{sha} reports as // its committer; an unlisted SHA reads as a person's push. commitBy map[string]string + // prBody is PR #8's body; fixedIssueClosedBy > 0 makes GET /issues/42 + // a closed issue whose closedByPullRequestsReferences names that merged + // PR (GET /pulls/ answers merged with a merge_commit_sha): the + // already-fixed rung of hivecommons/hive#15289. + prBody string + fixedIssueClosedBy int } func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { @@ -83,6 +89,20 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { n = 9 } _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "labels": []any{}, "pull_request": map[string]any{"url": "x"}, "user": map[string]any{"login": "hive[bot]", "type": "Bot"}}) + case r.Method == http.MethodGet && strings.HasSuffix(path, "/issues/42"): + state := "open" + if m.fixedIssueClosedBy > 0 { + state = "closed" + } + _ = json.NewEncoder(w).Encode(map[string]any{"number": 42, "state": state, "labels": []any{}, "user": map[string]any{"login": "someone", "type": "User"}}) + case r.Method == http.MethodPost && strings.HasSuffix(path, "/graphql"): + if m.fixedIssueClosedBy == 0 { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"repository": map[string]any{"issue": map[string]any{"closedByPullRequestsReferences": map[string]any{"nodes": []map[string]any{{"number": m.fixedIssueClosedBy, "url": "https://example.test/pr/" + strconv.Itoa(m.fixedIssueClosedBy), "merged": true, "mergedAt": "2026-10-28T11:00:00Z"}}}}}}}) + case r.Method == http.MethodGet && m.fixedIssueClosedBy > 0 && strings.HasSuffix(path, "/pulls/"+strconv.Itoa(m.fixedIssueClosedBy)): + _ = json.NewEncoder(w).Encode(map[string]any{"number": m.fixedIssueClosedBy, "state": "closed", "merged": true, "merged_at": "2026-10-28T11:00:00Z", "merge_commit_sha": "25de3ba24fa0c0ffee0000000000000000000000", "user": map[string]any{"login": "hive[bot]", "type": "Bot"}, "head": map[string]any{"sha": "cafecafecafecafecafecafecafecafecafecafe"}, "base": map[string]any{"ref": "main"}}) case r.Method == http.MethodGet && strings.HasSuffix(path, "/pulls/90"): if m.supersederState == "" { http.NotFound(w, r) @@ -108,7 +128,7 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { for _, label := range m.prLabels { prLabels = append(prLabels, map[string]string{"name": label}) } - _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "labels": prLabels, "user": author, "mergeable": true, "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}, "base": map[string]any{"ref": "main"}}) + _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "body": m.prBody, "labels": prLabels, "user": author, "mergeable": mergeState != "dirty", "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}, "base": map[string]any{"ref": "main"}}) case r.Method == http.MethodPut && strings.HasSuffix(path, "/pulls/8/update-branch"): m.updates++ w.WriteHeader(http.StatusAccepted) diff --git a/src/pkg/dashboard/delegated_ladder.go b/src/pkg/dashboard/delegated_ladder.go new file mode 100644 index 0000000000..758afc15ba --- /dev/null +++ b/src/pkg/dashboard/delegated_ladder.go @@ -0,0 +1,140 @@ +package dashboard + +import ( + "context" + "fmt" + "log/slog" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// The decision ladder's inputs (hivecommons/hive#15289). "Let hive decide" +// on #15219 adopted a conflicting clanker PR in supersede mode although +// its issue #15202 had already been fixed and merged by #15240 2.7h +// earlier. The ladder in pkg/delegatedecision needs three cheap facts the +// gather did not read: whether a merged PR already delivered the work, +// what the author drives (clanker / hive / person, for the wording), and +// whether their relay has picked the rework up. + +// gatherDelegatedLadderInput fills Input.SupersededBy, AuthorTooling, +// ReworkPickedUp and RepoPaused for a contributor PR. A supersession +// lookup failure aborts the decision: the fallback rung is adoption, and +// "unknown" must not read as "not superseded". +func (s *Server) gatherDelegatedLadderInput(ctx context.Context, repoFull string, pr *gh.PullRequest, in *delegatedecision.Input) error { + client := s.deps.GHClient + in.RepoPaused = client.RepoIsPaused(repoFull) + in.AuthorTooling = s.delegatedAuthorTooling(in.Labels, in.OwnerAuthor) + if in.HiveAuthored { + return nil + } + sup, ok, err := client.DetectMergedSupersession(ctx, repoFull, pr) + if err != nil { + return fmt.Errorf("reading whether %s#%d is already fixed: %w", repoFull, pr.GetNumber(), err) + } + if ok { + in.SupersededBy = &delegatedecision.MergedCloser{PR: sup.Closer, Issue: sup.Issue, SHA: sup.MergeSHA} + } + if !in.PersonAuthored() { + in.ReworkPickedUp = s.delegatedReworkPickedUp(repoFull, pr, in.Author, time.Now()) + } + return nil +} + +// delegatedAuthorTooling reads the author-kind labels (names from +// governor.labels.author) into the wording the decision uses. +func (s *Server) delegatedAuthorTooling(labels []string, owner bool) delegatedecision.AuthorTooling { + human, clanker, hive := authorKindLabelPfx+authorKindHuman, authorKindLabelPfx+authorKindClanker, authorKindLabelPfx+authorKindHive + if s != nil && s.deps != nil && s.deps.Config != nil { + a := s.deps.Config.Governor.Labels.Author + if strings.TrimSpace(a.Human) != "" { + human = a.Human + } + if strings.TrimSpace(a.Clanker) != "" { + clanker = a.Clanker + } + if strings.TrimSpace(a.Hive) != "" { + hive = a.Hive + } + } + return delegatedecision.AuthorToolingFromLabels(labels, hive, clanker, human, owner) +} + +// delegatedReworkPickedUp reads the rework-pickup signal of +// hivecommons/hive#15280 for the PR's author: their relay holds or queued +// the fix task, someone acted on the PR since the request, or a new head +// is up. It rests on the stage record and the hub's fix queue; no GitHub +// call. "requested" (nobody has acted) is not a pickup. +func (s *Server) delegatedReworkPickedUp(repoFull string, pr *gh.PullRequest, author string, now time.Time) bool { + rec, ok := s.stageStoreOrShared().Get(stagelabels.Key(repoFull, pr.GetNumber())) + if !ok { + return false + } + it := StageTrackerItem{Repo: repoFull, Kind: "pr", Number: pr.GetNumber(), Head: strings.TrimSpace(pr.GetHead().GetSHA())} + if u := pr.GetUpdatedAt(); !u.IsZero() { + t := u.Time + it.UpdatedAt = &t + } + rw := stageTrackerReworkFor(it, author, stagelabels.ReturnedToContributor, rec, true, s.stageTrackerFixWorkLookup(), now) + if rw == nil { + return false + } + switch rw.State { + case reworkStateAcknowledged, reworkStateInProgress, reworkStatePushed: + return true + } + return false +} + +// logDelegatedLadder writes the one structured line per decision that says +// which rung decided and why the rungs above it did not apply. +func (s *Server) logDelegatedLadder(repoFull string, number int, d delegatedecision.Decision) { + if d.Ladder == nil || s == nil || s.logger == nil { + return + } + s.logger.Info("delegated decision ladder", + slog.String("repo", repoFull), slog.Int("number", number), + slog.String("decision", d.Ladder.Decision), slog.String("reason", d.Ladder.Reason), + slog.Any("ruled_out", d.Ladder.RuledOut), slog.String("verdict", string(d.Verdict))) +} + +// delegatedLadderOutcome is the toast's outcome line for a ladder decision +// that the generic verdict text would understate: "Closed as superseded: +// #15202 already fixed by #15240 (25de3ba)". ok is false when the generic +// text stands. +func delegatedLadderOutcome(in delegatedecision.Input, d delegatedecision.Decision) (string, bool) { + switch d.Rule { + case delegatedecision.RuleAlreadyFixed: + c := in.SupersededBy + if c == nil || d.Verdict != delegatedecision.VerdictCloseSuperseded { + return "", false + } + ref := fmt.Sprintf("#%d", c.PR) + if c.SHA != "" { + ref += " (" + delegatedShortSHA(c.SHA) + ")" + } + if c.Issue > 0 { + return fmt.Sprintf("Closed as superseded: #%d already fixed by %s.", c.Issue, ref), true + } + return fmt.Sprintf("Closed as superseded by merged %s.", ref), true + case delegatedecision.RuleContributorOffline: + if d.Verdict != delegatedecision.VerdictAdoptSupersede { + return "", false + } + // Appended to the adopt outcome as its "Why:", naming the author's + // clanker, hive or the author — never the wrong one. + return "Why: " + in.OfflineWording() + ".", true + } + return "", false +} + +func delegatedShortSHA(sha string) string { + sha = strings.TrimSpace(sha) + if len(sha) > 7 { + return sha[:7] + } + return sha +} diff --git a/src/pkg/dashboard/row_action_result.go b/src/pkg/dashboard/row_action_result.go index 81d6e0c177..f3dfa4d9e8 100644 --- a/src/pkg/dashboard/row_action_result.go +++ b/src/pkg/dashboard/row_action_result.go @@ -127,6 +127,8 @@ func delegatedRowActionResult(in delegatedecision.Input, d delegatedecision.Deci if in.Kind == delegatedecision.KindIssue { parkedAt = "045" } + // The ladder's own outcome line names the facts (hivecommons/hive#15289). + ladderOutcome, hasLadderOutcome := delegatedLadderOutcome(in, d) switch { case d.Verdict == delegatedecision.VerdictRefused: out.Action = rowActionRefused @@ -144,11 +146,17 @@ func delegatedRowActionResult(in delegatedecision.Input, d delegatedecision.Deci out.Outcome = "Adopted — hive will re-author " + ref + " as a hive PR with the same commits and merge it next pass; " + ref + " will be closed as superseded." out.Next = "Until the copy opens the row reads Adopted at the merge gate; the copy then carries the chevron and " + ref + " is listed under it as superseded." } + if hasLadderOutcome { + out.Outcome += " " + ladderOutcome + } case d.Verdict == delegatedecision.VerdictCloseDuplicate || d.Verdict == delegatedecision.VerdictCloseSuperseded: out.Action = rowActionClosed - if actionTarget > 0 { + switch { + case hasLadderOutcome: + out.Outcome = ladderOutcome + case actionTarget > 0: out.Outcome = fmt.Sprintf("Closed in favour of #%d%s.", actionTarget, ruleTag) - } else { + default: out.Outcome = "Closed" + ruleTag + "." } out.Next = "Nothing further to do; the row leaves the tracker on its next refresh." diff --git a/src/pkg/dashboard/stage_tracker_linked_progress_test.go b/src/pkg/dashboard/stage_tracker_linked_progress_test.go index 06e36fc78a..8fbfdbb58e 100644 --- a/src/pkg/dashboard/stage_tracker_linked_progress_test.go +++ b/src/pkg/dashboard/stage_tracker_linked_progress_test.go @@ -92,13 +92,13 @@ func TestStageTrackerLinkedPRProgressRowsAndEvents(t *testing.T) { {Repo: "acme/console", Number: 15223, Kind: "pr", Stage: trackerNumberNeedsAuthor, Caption: "Needs @pat to fix CI", LinkedIssues: []StageTrackerLinkedIssue{{Number: 15218}}}, } - stageTrackerResolveLinkedPRs(items) + stageTrackerResolveLinkedPRs(items, nil) before, err := json.Marshal(items) if err != nil { t.Fatal(err) } items[1].Caption = "Needs @pat to rebase" - stageTrackerResolveLinkedPRs(items) + stageTrackerResolveLinkedPRs(items, nil) after, err := json.Marshal(items) if err != nil { t.Fatal(err) diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 7f57026f56..28f51b9357 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -1023,7 +1023,7 @@ let text = stageTrackerResultText(decided, issue, { id: 'decide:delegate', rowRe // The decision toast leads with the outcome; the rule in plain words // (never the bare slug) is the second line (#15126). assert.strictEqual(text.head, 'Adopted o/r#14947 in supersede mode as o/r#14977.', 'the outcome leads'); -assert.strictEqual(text.outcome, "Hive decided on o/r#14938 → PR #14947: adopted (the author's clanker hasn't been connected since the nudge)", 'the rule in plain words, never the bare slug'); +assert.strictEqual(text.outcome, "Hive decided on o/r#14938 → PR #14947: adopted (the author hasn't been reachable since the nudge)", 'the rule in plain words, never the bare slug'); assert.strictEqual(text.next, decided.next); assert.strictEqual(text.type, 'success'); assert.strictEqual(text.url, 'u947'); assert.strictEqual(text.linkText, 'Open PR #14947'); text = stageTrackerResultText({ action: 'held', target: { repo: 'o/r', kind: 'issue', number: 7, url: 'u7' }, outcome: 'hold applied.', next: '' }, held, { id: 'hold' }); @@ -1039,7 +1039,7 @@ const stuck = { action: 'no-effect', rule: 'contributor-offline', why: 'self-dec options: [{ action: 'decide:merge-now', label: 'Merge as maintainer', enabled: true }, { action: 'decide:delegate:rerun', label: 'Re-run decision', enabled: true }, { action: 'decide:close-superseded', label: 'Close as superseded', enabled: false, reason_if_disabled: 'write required' }, { action: 'decide:direction', label: 'Send back for a new commit', enabled: true }, { label: 'no action' }] }; const stuckNow = Date.parse('2026-10-28T15:01:29Z'); text = stageTrackerResultText(stuck, issue, { id: 'decide:delegate', nowMs: stuckNow }); -assert.strictEqual(text.head, "Hive decided on o/r#14938 → PR #14947: no effect yet (the author's clanker hasn't been connected since the nudge)", 'the headline does not say "decided" twice'); +assert.strictEqual(text.head, "Hive decided on o/r#14938 → PR #14947: no effect yet (the author hasn't been reachable since the nudge)", 'the headline does not say "decided" twice'); assert.strictEqual(text.type, 'warning'); assert.strictEqual(text.options.length, 4, 'options without an action are dropped'); // The raw RFC3339 stamp never reaches the operator (#15126). assert.ok(!/2026-10-28T13:01:29Z/.test(text.outcome) && / at 13:01( today)?, but/.test(text.outcome), text.outcome); @@ -1063,11 +1063,11 @@ assert.strictEqual(stageTrackerPlainWords('approve'), 'approved for merge', 'no assert.strictEqual(stageTrackerPlainWords('close-superseded', true, 'issue'), 'Closed because another issue already tracks the same work; the discussion continues there.'); assert.strictEqual(stageTrackerPlainWords('close-duplicate', false, 'issue'), 'closed as a duplicate', 'an entry without issue words keeps its plain words'); assert.strictEqual(stageTrackerPlainWords('supersede'), 'close this PR and open a fresh hive-authored PR with the same commits'); -assert.strictEqual(stageTrackerPlainWords('adoption-stalled:contributor-offline'), "the author's clanker hasn't been connected since the nudge"); +assert.strictEqual(stageTrackerPlainWords('adoption-stalled:contributor-offline'), "the author hasn't been reachable since the nudge"); assert.strictEqual(stageTrackerPlainWords('contributor-lane:changes-requested'), stageTrackerPlainWords('changes_requested')); assert.strictEqual(stageTrackerPlainWords('some-new-rule'), 'some new rule', 'unknown slugs are humanised, never raw'); assert.strictEqual(stageTrackerPlainWords(''), ''); -assert.strictEqual(stageTrackerResultOf('decide:delegate', issue, { decision: { verdict: 'supersede', rule: 'contributor-offline' } }).outcome, "close this PR and open a fresh hive-authored PR with the same commits (the author's clanker hasn't been connected since the nudge)"); +assert.strictEqual(stageTrackerResultOf('decide:delegate', issue, { decision: { verdict: 'supersede', rule: 'contributor-offline' } }).outcome, "close this PR and open a fresh hive-authored PR with the same commits (the author hasn't been reachable since the nudge)"); text = stageTrackerResultText(stageTrackerErrorResult('hold', held, 'write permission required'), held, { id: 'hold' }); assert.strictEqual(text.head, 'Hold failed on o/r#7'); assert.strictEqual(text.outcome, 'write permission required'); assert.strictEqual(text.type, 'error'); // Legacy answers (no result) still describe what happened. @@ -1172,7 +1172,7 @@ assert.ok(!acting('o/r/issue#7'), 'a no-op or an error clears at once'); global.fetch = async (url, init) => ({ ok: true, status: 200, json: async () => ({ status: 'done', result: decided }) }); stageTrackerSetConfirmSkip('decide:delegate', true); const del = await runRowAction('decide:delegate', issue); - assert.strictEqual(del.toast.text.outcome, "Hive decided on o/r#14947: adopted (the author's clanker hasn't been connected since the nudge)", del.toast.text.outcome); + assert.strictEqual(del.toast.text.outcome, "Hive decided on o/r#14947: adopted (the author hasn't been reachable since the nudge)", del.toast.text.outcome); assert.deepStrictEqual(del.pending[0].keys, ['o/r/pr#14947', 'o/r/issue#14938']); assert.ok(acting('o/r/issue#14938') && acting('o/r/pr#14947')); // An approval is recorded when the server answers: "Approving…" clears diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index d57e2c9d3c..caaf24e311 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -17709,11 +17709,12 @@

All labels

"adoption-stalled:contributor-lane:workflow-path": {"kind": "reason", "plain": "the PR edits .github/workflows; the hive's App lacks the `workflows` permission, so it cannot adopt it", "detail": "The PR changes files under .github/workflows. The hive's GitHub App has no `workflows` permission, so the adoption fence refuses to publish those edits from the hive. Grant the App the `workflows` permission and re-run the decision, or have a person rebase and merge it on GitHub, or close it as superseded."}, "adoption-undone": {"kind": "reason", "plain": "the hive's copy was closed without merging and the adoption was undone", "detail": "The hive opened its copy, but the copy was closed without merging and a fresh one could not be opened, so the adoption was undone and the PR is back in its normal flow. Re-run the decision to adopt it again, or act on GitHub."}, "adoption/supersede": {"kind": "action", "plain": "close this PR and open a fresh hive-authored PR with the same commits", "detail": "Supersede means the hive closes this PR and opens a fresh hive-authored PR carrying the same commits and sign-off, then finishes it itself."}, + "already-fixed": {"kind": "rule", "plain": "the issue was already fixed by a merged PR; closed as superseded", "detail": "The issue this PR fixes is already closed and a merged PR closed it (or a merged PR declares it supersedes this one), so nothing is left to deliver. The hive closes the PR as superseded with a note naming the merging PR; it never adopts it."}, "approve": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge gate merges it once every check passes.", "issue_plain": "approved to proceed — an agent may claim it", "issue_detail": "The hive approved the direction; the issue leaves Needs decision and an agent may claim it. Nothing is merged."}, "approve-review": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge gate merges it once every check passes.", "issue_plain": "approved to proceed — an agent may claim it", "issue_detail": "The hive approved the direction; the issue leaves Needs decision and an agent may claim it. Nothing is merged."}, "approved": {"kind": "action", "plain": "approved for merge", "detail": "The hive approved it; the merge gate merges it once every check passes.", "issue_plain": "approved to proceed — an agent may claim it", "issue_detail": "The hive approved the direction; the issue leaves Needs decision and an agent may claim it. Nothing is merged."}, "author-association": {"kind": "reason", "plain": "no merge lane vouches for this PR's author; a maintainer merges", "detail": "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve \u0026 merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors."}, - "author-online": {"kind": "reason", "plain": "the author's clanker is connected, so hive won't take the PR over", "detail": "Adoption is for authors whose clanker has gone offline; this author's clanker is connected, so the hive leaves the PR with them."}, + "author-online": {"kind": "reason", "plain": "the author's clanker or hive is connected, so hive won't take the PR over", "detail": "Adoption is for authors whose clanker or hive has gone offline; this author's is connected, so the hive leaves the PR with them."}, "behind": {"kind": "reason", "plain": "the branch is behind the base branch", "detail": "The branch is behind the base branch and must be updated before it can merge."}, "blocker": {"kind": "reason", "plain": "the hive can't do this itself", "detail": "The item is blocked on something the hive cannot do: a permission the GitHub App lacks, or a step only a person may take. No decision clears it; grant the permission (and re-check) or do the step by hand (hivecommons/hive#15099)."}, "capability": {"kind": "reason", "plain": "the hive can't do this itself", "detail": "The item is blocked on something the hive cannot do: a permission the GitHub App lacks, or a step only a person may take. No decision clears it; grant the permission (and re-check) or do the step by hand (hivecommons/hive#15099)."}, @@ -17736,7 +17737,7 @@

All labels

"contributor-lane:changes-requested": {"kind": "reason", "plain": "a reviewer asked for changes; a new commit is needed", "detail": "A reviewer asked for changes on this branch. Approving cannot override that: only a new commit, or a maintainer merging by hand, moves it."}, "contributor-lane:sentinel-blocked": {"kind": "reason", "plain": "security-sensitive files changed; a maintainer must approve", "detail": "Security-sensitive files changed. The hive never merges until a maintainer reviews and removes the sentinel label."}, "contributor-lane:workflow-path": {"kind": "reason", "plain": "the PR edits .github/workflows; the hive's App lacks the `workflows` permission, so it cannot adopt it", "detail": "The PR changes files under .github/workflows. The hive's GitHub App has no `workflows` permission, so the adoption fence refuses to publish those edits from the hive. Grant the App the `workflows` permission and re-run the decision, or have a person rebase and merge it on GitHub, or close it as superseded."}, - "contributor-offline": {"kind": "rule", "plain": "the author's clanker hasn't been connected since the nudge", "detail": "The PR's author has been offline since the hive nudged them, so the hive takes the work over instead of waiting."}, + "contributor-offline": {"kind": "rule", "plain": "the author hasn't been reachable since the nudge", "detail": "The PR's author (or their clanker or hive) has been offline since the hive nudged them, so the hive takes the work over instead of waiting. The decision itself names which: the author's clanker, a connected hive, or the author."}, "dco": {"kind": "reason", "plain": "a commit is missing its sign-off", "detail": "A commit on the branch is missing its Developer Certificate of Origin sign-off; the author must sign it off."}, "dco-missing": {"kind": "reason", "plain": "a commit is missing its sign-off", "detail": "A commit on the branch is missing its Developer Certificate of Origin sign-off; the author must sign it off."}, "dedupe": {"kind": "rule", "plain": "an older issue already tracks this", "detail": "An older issue already tracks the same work; one thread keeps it moving."}, @@ -17759,6 +17760,7 @@

All labels

"labels-remove": {"kind": "action", "plain": "removed labels", "detail": "The hive removed labels from the item."}, "link": {"kind": "action", "plain": "cross-linked a related item", "detail": "The hive left a comment linking a related issue or PR."}, "llm-delegate": {"kind": "rule", "plain": "decided by the hive's model under the owner's rules", "detail": "No mechanical rule applied, so the hive's model decided under the owner's standing rules; the same safety rails applied."}, + "mergeable-as-is": {"kind": "rule", "plain": "mergeable and green as it is; handed to the merge gate", "detail": "The head is mergeable with green CI, so no adoption is needed: the hive approves it and the merge gate takes it as it is."}, "needs-human": {"kind": "reason", "plain": "marked needs-human; a person must remove the label", "detail": "The item is marked needs-human: automated fixes ran out or a person flagged it. The hive waits until the label is removed."}, "no-effect": {"kind": "reason", "plain": "the decision hasn't taken effect", "detail": "The hive recorded this decision, but what it was supposed to cause has not happened within the expected time."}, "no-new-commit": {"kind": "reason", "plain": "no new commit has been pushed", "detail": "The hive gave direction, but no new commit has been pushed yet."}, @@ -17771,6 +17773,7 @@

All labels

"quarantine-flaky": {"kind": "action", "plain": "quarantined the flaky test", "detail": "The flaky test is quarantined with a retry and a deflake task is filed."}, "rail-hold": {"kind": "rule", "plain": "the item is on hold", "detail": "The item carries the hold label; the hive never acts on a held item until a person releases the hold."}, "ready-for-human-merge": {"kind": "reason", "plain": "no merge lane vouches for this PR's author; a maintainer merges", "detail": "The PR is ready, but its author is not a collaborator and holds no trusted or merger tier, so no merge lane vouches for them and the hive never merges it unattended. A maintainer merges it (Approve \u0026 merge as maintainer, or Approve — let hive merge), or trusts the author under 👥 Contributors."}, + "rebase-then-merge": {"kind": "rule", "plain": "only conflicts block it; a rebase then merge", "detail": "Conflicts are the only blocker. The unattended rebase-then-merge path lands with hivecommons/hive#15104; until then the ladder records this rung and moves on."}, "recommend-only": {"kind": "action", "plain": "recommended only; a person confirms", "detail": "The hive only recommended; the item stays parked until a person confirms."}, "recommended": {"kind": "action", "plain": "recommended only; a person confirms", "detail": "The hive only recommended; the item stays parked until a person confirms."}, "red": {"kind": "reason", "plain": "CI is failing on this branch", "detail": "Required checks are failing on this branch; nothing merges until they are green."}, @@ -17779,6 +17782,7 @@

All labels

"request_changes": {"kind": "reason", "plain": "a reviewer asked for changes; a new commit is needed", "detail": "A reviewer asked for changes on this branch. Approving cannot override that: only a new commit, or a maintainer merging by hand, moves it."}, "requires_human": {"kind": "reason", "plain": "marked needs-human; a person must remove the label", "detail": "The item is marked needs-human: automated fixes ran out or a person flagged it. The hive waits until the label is removed."}, "return-to-author": {"kind": "rule", "plain": "a person pushed this PR; the hive asked them, not adopted it", "detail": "The PR was pushed by a person (author/human or one of this hive's owners), so the hive never adopts it. It told the author by name what to fix (rebase, sign-off, CI) and relayed the reviewer's question."}, + "return-to-contributor": {"kind": "rule", "plain": "the author's clanker or hive is connected; returned to them with the fix list", "detail": "The author's clanker or hive is connected (or has picked the rework up), so the hive hands the PR back to them with the exact fix list instead of adopting it."}, "review-backlog": {"kind": "rule", "plain": "the PR closed without merging, so the issue stays open", "detail": "The fixing PR closed unmerged; the issue stays open and is re-triaged rather than auto-closed."}, "reviewer-verdict:request_changes": {"kind": "reason", "plain": "a reviewer asked for changes; a new commit is needed", "detail": "A reviewer asked for changes on this branch. Approving cannot override that: only a new commit, or a maintainer merging by hand, moves it."}, "self-decision-read-as-changes": {"kind": "reason", "plain": "hive's own decision comment was read as a reviewer asking for changes", "detail": "The merge gate read the hive's own `/hive decision` comment as a reviewer asking for changes, so the decision blocked the PR it meant to advance (hivecommons/hive#14822). A new commit or a maintainer merge clears it."}, diff --git a/src/pkg/delegatedecision/decision_glossary.go b/src/pkg/delegatedecision/decision_glossary.go index 02c5b87df4..0153cad7e1 100644 --- a/src/pkg/delegatedecision/decision_glossary.go +++ b/src/pkg/delegatedecision/decision_glossary.go @@ -32,8 +32,8 @@ const ( ) // GlossaryEntry is one slug in plain words. Plain is a short phrase that -// fits a toast headline in parentheses ("adopted (the author's clanker hasn't -// been connected since the nudge)"); Detail is one full sentence for a +// fits a toast headline in parentheses ("adopted (the author hasn't been +// reachable since the nudge)"); Detail is one full sentence for a // popover, tooltip or PR comment. Aliases are other spellings of the same // slug (lane tokens, label names) that resolve to this entry. type GlossaryEntry struct { @@ -87,8 +87,16 @@ const ( var glossary = []GlossaryEntry{ // Rules — why the delegate chose what it chose. - {Slug: "contributor-offline", Kind: GlossaryRule, Plain: "the author's clanker hasn't been connected since the nudge", - Detail: "The PR's author has been offline since the hive nudged them, so the hive takes the work over instead of waiting."}, + {Slug: RuleContributorOffline, Kind: GlossaryRule, Plain: "the author hasn't been reachable since the nudge", + Detail: "The PR's author (or their clanker or hive) has been offline since the hive nudged them, so the hive takes the work over instead of waiting. The decision itself names which: the author's clanker, a connected hive, or the author."}, + {Slug: RuleAlreadyFixed, Kind: GlossaryRule, Plain: "the issue was already fixed by a merged PR; closed as superseded", + Detail: "The issue this PR fixes is already closed and a merged PR closed it (or a merged PR declares it supersedes this one), so nothing is left to deliver. The hive closes the PR as superseded with a note naming the merging PR; it never adopts it."}, + {Slug: RuleMergeableAsIs, Kind: GlossaryRule, Plain: "mergeable and green as it is; handed to the merge gate", + Detail: "The head is mergeable with green CI, so no adoption is needed: the hive approves it and the merge gate takes it as it is."}, + {Slug: RuleRebaseThenMerge, Kind: GlossaryRule, Plain: "only conflicts block it; a rebase then merge", + Detail: "Conflicts are the only blocker. The unattended rebase-then-merge path lands with hivecommons/hive#15104; until then the ladder records this rung and moves on."}, + {Slug: RuleReturnToContributor, Kind: GlossaryRule, Plain: "the author's clanker or hive is connected; returned to them with the fix list", + Detail: "The author's clanker or hive is connected (or has picked the rework up), so the hive hands the PR back to them with the exact fix list instead of adopting it."}, {Slug: "dedupe", Kind: GlossaryRule, Plain: "an older issue already tracks this", Detail: "An older issue already tracks the same work; one thread keeps it moving."}, {Slug: "fix-then-merge", Kind: GlossaryRule, Plain: "the branch isn't mergeable yet", @@ -182,8 +190,8 @@ var glossary = []GlossaryEntry{ Detail: "Required checks are failing on this branch; nothing merges until they are green.", Aliases: []string{"ci-failing", "checks-failing", "red"}}, {Slug: GlossaryBehind, Kind: GlossaryReason, Plain: "the branch is behind the base branch", Detail: "The branch is behind the base branch and must be updated before it can merge."}, - {Slug: GlossaryAuthorOnline, Kind: GlossaryReason, Plain: "the author's clanker is connected, so hive won't take the PR over", - Detail: "Adoption is for authors whose clanker has gone offline; this author's clanker is connected, so the hive leaves the PR with them."}, + {Slug: GlossaryAuthorOnline, Kind: GlossaryReason, Plain: "the author's clanker or hive is connected, so hive won't take the PR over", + Detail: "Adoption is for authors whose clanker or hive has gone offline; this author's is connected, so the hive leaves the PR with them."}, {Slug: GlossaryHold, Kind: GlossaryReason, Plain: "on hold; the hive does nothing until it is released", Detail: "The PR is on hold. The hive does nothing with it until a person releases the hold.", IssueDetail: "The issue is on hold. No agent claims it until a person releases the hold."}, diff --git a/src/pkg/delegatedecision/decision_glossary_test.go b/src/pkg/delegatedecision/decision_glossary_test.go index e13c52fa9b..4f66201e02 100644 --- a/src/pkg/delegatedecision/decision_glossary_test.go +++ b/src/pkg/delegatedecision/decision_glossary_test.go @@ -128,7 +128,7 @@ func TestCommentBodyPlainWords(t *testing.T) { for _, want := range []string{ "/hive decision supersede now", "**Hive decided:** Close this PR and open a fresh hive-authored PR with the same commits.", - "**Why:** The author's clanker hasn't been connected since the nudge.", + "**Why:** The author hasn't been reachable since the nudge.", "**What happens next:** The hive closes this PR and opens a fresh hive-authored PR with the same commits and sign-off, then finishes that one — expected within 30 min.", "**If it doesn't happen:** A maintainer can merge this PR by hand, re-run the decision, close it as superseded, or send it back for a new commit.", MarkerPrefix, diff --git a/src/pkg/delegatedecision/ladder.go b/src/pkg/delegatedecision/ladder.go new file mode 100644 index 0000000000..6571c7a4a1 --- /dev/null +++ b/src/pkg/delegatedecision/ladder.go @@ -0,0 +1,318 @@ +package delegatedecision + +import ( + "fmt" + "strings" +) + +// The contributor-PR decision ladder (hivecommons/hive#15289). +// +// On hive's own spoke an operator pressed "Let hive decide" on PR #15219 +// (author via a clanker relay, conflicting, author/clanker). The policy +// fell straight through to the contributor-offline rule and adopted it in +// supersede mode — but its issue #15202 had been fixed and merged 2.7h +// earlier by #15240. The right answer was "superseded by a merged PR; +// close with a courteous comment". The ladder below evaluates the cheap, +// decisive facts first and only reaches adopt-supersede as the last +// resort. Each rung that does not apply is recorded in Ladder.RuledOut so +// the operator (toast, API, log) can see why the lower rung was reached. + +// Ladder rung slugs. Each is also a Decision.Rule with a glossary entry. +const ( + // RuleAlreadyFixed: the PR's issue is closed and another merged PR + // closed it (or a merged PR declares it supersedes this one). The PR + // is closed as superseded; it is never adopted. + RuleAlreadyFixed = "already-fixed" + // RuleMergeableAsIs: the head is mergeable and green; the merge gate + // takes it with no adoption. + RuleMergeableAsIs = "mergeable-as-is" + // RuleRebaseThenMerge: conflicts are the only blocker. The unattended + // rebase-then-merge path (hivecommons/hive#15104) is not merged yet, so + // the rung is recorded as ruled out and the ladder continues. + RuleRebaseThenMerge = "rebase-then-merge" + // RuleReturnToContributor: the author's clanker or hive is connected + // (or has picked the rework up), so the PR goes back to them with the + // fix list instead of being adopted. + RuleReturnToContributor = "return-to-contributor" + // RuleContributorOffline: the last rung — adopt in supersede mode. + RuleContributorOffline = "contributor-offline" +) + +// ladderRungs is the evaluation order. +var ladderRungs = []string{RuleAlreadyFixed, RuleMergeableAsIs, RuleRebaseThenMerge, RuleReturnToContributor, RuleContributorOffline} + +// AuthorTooling says what the PR's author drives: a hive, a clanker (a +// relay), a person pushing by hand, or unknown. It picks the words a +// decision uses for them (AuthorWord). +type AuthorTooling string + +// Author tooling values. +const ( + AuthorToolingUnknown AuthorTooling = "" + AuthorToolingHive AuthorTooling = "hive" + AuthorToolingClanker AuthorTooling = "clanker" + AuthorToolingPerson AuthorTooling = "person" +) + +// MergedCloser names the merged PR that already delivered this PR's work. +type MergedCloser struct { + // PR is the merged pull request; Issue is the issue it closed (0 when + // the closer declared `Supersedes #N` rather than closing an issue). + PR int `json:"pr"` + Issue int `json:"issue,omitempty"` + SHA string `json:"sha,omitempty"` +} + +// Ladder is the rung the decision landed on and why the rungs above it did +// not apply. It rides on Decision (json `ladder`) into the decide API. +type Ladder struct { + Decision string `json:"decision"` + Reason string `json:"reason"` + RuledOut []string `json:"ruled_out,omitempty"` +} + +// AuthorWord is how a decision refers to the author's tooling: "the +// author's clanker" for a clanker relay, "the author's hive" only when a +// hive is known, otherwise "the author" (hivecommons/hive#15289: #15219's +// author has a clanker, and the decision called it their hive). +func (in Input) AuthorWord() string { + switch in.AuthorTooling { + case AuthorToolingClanker: + return "the author's clanker" + case AuthorToolingHive: + return "the author's hive" + } + return "the author" +} + +// OfflineWording is the contributor-offline rationale in the author's own +// terms: a clanker or hive "hasn't been connected"; a bare author "hasn't +// been reachable". +func (in Input) OfflineWording() string { + who := in.AuthorWord() + if who == "the author" { + return who + " hasn't been reachable since the nudge" + } + return who + " hasn't been connected since the nudge" +} + +// AuthorToolingFromLabels reads author/ labels (hive beats clanker +// beats human, as in pkg/authorkind). An owner is a person whatever the +// labels say. hiveLabel/clankerLabel/humanLabel are the configured label +// names. +func AuthorToolingFromLabels(labels []string, hiveLabel, clankerLabel, humanLabel string, owner bool) AuthorTooling { + if owner { + return AuthorToolingPerson + } + out := AuthorToolingUnknown + for _, l := range labels { + l = strings.TrimSpace(l) + switch { + case strings.EqualFold(l, hiveLabel): + return AuthorToolingHive + case strings.EqualFold(l, clankerLabel): + out = AuthorToolingClanker + case strings.EqualFold(l, humanLabel) && out == AuthorToolingUnknown: + out = AuthorToolingPerson + } + } + return out +} + +// shortSHA is the seven-character form used in comments and toasts. +func shortSHA(sha string) string { + sha = strings.TrimSpace(sha) + if len(sha) > 7 { + return sha[:7] + } + return sha +} + +// SupersededText is the one-line close note for an already-fixed PR: +// "superseded: #15202 was already fixed by #15240 (25de3ba)". +func SupersededText(c MergedCloser) string { + ref := "#" + itoa(c.PR) + if c.SHA != "" { + ref += " (" + shortSHA(c.SHA) + ")" + } + if c.Issue > 0 { + return fmt.Sprintf("superseded: #%d was already fixed by merged PR %s", c.Issue, ref) + } + return "superseded by merged PR " + ref +} + +// ladderCandidate: the ladder governs an open PR that is not the hive's +// own (hive PRs have their own direction rules). +func ladderCandidate(in Input) bool { + return in.Kind == KindPR && !in.HiveAuthored +} + +// decideLadder walks the rungs for a contributor PR. ok is false when no +// rung applies (the ordinary fix-then-merge / release rules follow). +func decideLadder(in Input, ref string) (Decision, bool) { + if !ladderCandidate(in) { + return Decision{}, false + } + var ruledOut []string + out := func(d Decision, reason string) (Decision, bool) { + d.Ladder = &Ladder{Decision: d.Rule, Reason: reason, RuledOut: ruledOut} + return d, true + } + skip := func(rung, why string) { ruledOut = append(ruledOut, rung+": "+why) } + + // Rung 1 — already fixed. Cheap and decisive: nothing is left to + // deliver, so neither adoption nor a nudge makes sense. + if c := in.SupersededBy; c != nil && c.PR > 0 { + return out(decideAlreadyFixed(in, ref, *c)) + } + skip(RuleAlreadyFixed, "no merged PR has closed this PR's issue") + + // A person's PR never reaches the contributor rungs: decideReturnToAuthor + // and the adoption rail own it (hivecommons/hive#15202). + if in.PersonAuthored() { + return Decision{}, false + } + + // Rung 2 — mergeable as-is: the merge gate takes it; no adoption. An + // adoption that already stalled on a lane blocker (changes requested, + // attribution) is not one the gate would take on a green head alone. + if !in.Conflicting && in.CIGreen && !in.DCOMissing && !in.ReporterTrustHold && !in.AdoptionStalled { + d := releasePR(RuleMergeableAsIs, "approve "+ref+": the head is mergeable and green, so it goes to the merge gate as it is", "a mergeable, green head needs no adoption; the merge gate takes it (hivecommons/hive#15289)") + return out(d, "mergeable and green; handed to the merge gate") + } + skip(RuleMergeableAsIs, mergeBlockers(in)) + + // Rung 3 — rebase-then-merge: conflicts are the only blocker. The + // unattended rebase path is hivecommons/hive#15104 (still open); until + // it lands the rung only records itself. + // TODO(hivecommons/hive#15104): hand a conflicts-only head to the + // rebase-then-merge hook once it is merged. + if in.Conflicting && in.CIGreen && !in.DCOMissing { + skip(RuleRebaseThenMerge, "conflicts are the only blocker, but the unattended rebase path (hivecommons/hive#15104) is not available yet") + } else { + skip(RuleRebaseThenMerge, "not a conflicts-only head") + } + + // The reporter-trust gate is decided by the rules after the ladder; a + // workflow-path PR is the capability-gap rule's; a reachable author + // adds their own sign-off (fix-then-merge). + if in.ReporterTrustHold || in.WorkflowPath || (in.DCOMissing && in.ContributorOnline) { + return Decision{}, false + } + + // Rung 4 — return to contributor: their clanker or hive is reachable + // (presence, or the rework-pickup signal of hivecommons/hive#15280). + if in.ContributorOnline || in.ReworkPickedUp { + fix := fixList(in) + if len(fix) == 0 { + return Decision{}, false + } + who := in.AuthorWord() + why := who + " is connected" + if in.ReworkPickedUp { + why = who + " has picked the rework up" + } + text := why + ": " + strings.Join(fix, ", ") + " on " + ref + "; then it merges" + d := Decision{ + Verdict: VerdictDirection, Rule: RuleReturnToContributor, Text: text, + Rationale: why + ", so the PR goes back to them with the fix list instead of being adopted (hivecommons/hive#15289)", + Actions: []Action{decisionComment(text)}, + } + return out(d, why+"; returned with the fix list") + } + skip(RuleReturnToContributor, in.OfflineWording()) + + // Rung 5 — adopt-supersede, the last resort. + if in.AdoptionGraceElapsed { + text := "adopt now: the offline grace on " + ref + " has already elapsed; adopt in supersede mode at once, preserving the author's commits and sign-off" + d := Decision{ + Verdict: VerdictAdoptSupersede, Rule: RuleAdoptNow, Text: text, + Rationale: in.OfflineWording() + " and the grace window has run out; waiting longer helps no one (hivecommons/hive#15038)", + Actions: []Action{decisionComment(text), {Kind: ActionAdoptSupersede}}, + } + return out(d, in.OfflineWording()+" and the grace has elapsed; adopted now") + } + if in.AdoptionStalled || in.Conflicting || !in.CIGreen || in.DCOMissing { + text := "supersede now: adopt " + ref + " in supersede mode, preserving the author's commits and sign-off; do not wait for the grace deadline" + d := Decision{ + Verdict: VerdictAdoptSupersede, Rule: RuleContributorOffline, Text: text, + Rationale: in.OfflineWording() + "; adoption in supersede mode keeps the work moving (hivecommons/hive#13975)", + Actions: []Action{decisionComment(text), {Kind: ActionAdoptSupersede}}, + } + return out(d, in.OfflineWording()+"; adopted in supersede mode") + } + return Decision{}, false +} + +// decideAlreadyFixed is rung 1: close as superseded by the merged closer, +// with a courteous note naming it. A paused repo or a person's PR gets a +// recommendation instead of a write. +func decideAlreadyFixed(in Input, ref string, c MergedCloser) (Decision, string) { + text := SupersededText(c) + closer := "#" + itoa(c.PR) + if c.SHA != "" { + closer += " (" + shortSHA(c.SHA) + ")" + } + var rationale string + if c.Issue > 0 { + rationale = fmt.Sprintf("issue #%d is closed and merged PR %s closed it, so %s has nothing left to deliver; it is closed as superseded, not adopted (hivecommons/hive#15289)", c.Issue, closer, ref) + } else { + rationale = fmt.Sprintf("merged PR %s declares that it supersedes %s, so nothing is left to deliver; it is closed as superseded, not adopted (hivecommons/hive#15289)", closer, ref) + } + switch { + case in.RepoPaused: + return recommendOnly(RuleAlreadyFixed, rationale+"; the repo is paused, so the hive only recommends", "close "+ref+" as "+text), text + " (repo paused: recommend only)" + case in.PersonAuthored(): + return recommendOnly(RuleAlreadyFixed, rationale+"; a person pushed it themselves, so the hive asks them to close it", "close "+ref+" as "+text), text + " (person-authored: recommend only)" + } + note := fmt.Sprintf("Thank you for this PR. %s, so there is nothing left for it to deliver and the hive is closing it as superseded. Your work is credited on the issue.", strings.ToUpper(text[:1])+text[1:]) + return Decision{ + Verdict: VerdictCloseSuperseded, Rule: RuleAlreadyFixed, Text: text, + Rationale: rationale, + Actions: []Action{{Kind: ActionCloseDuplicate, Target: c.PR, Text: note}}, + }, text +} + +// mergeBlockers names what keeps a head from the merge gate. +func mergeBlockers(in Input) string { + var b []string + if in.Conflicting { + b = append(b, "conflicting") + } + if !in.CIGreen { + b = append(b, "CI not green") + } + if in.DCOMissing { + b = append(b, "DCO missing") + } + if in.ReporterTrustHold { + b = append(b, "reporter-trust hold") + } + if in.AdoptionStalled { + b = append(b, "adoption stalled on a lane blocker") + } + if len(b) == 0 { + return "not mergeable" + } + return strings.Join(b, ", ") +} + +// fixList is the author's to-do for a head that is not mergeable. +func fixList(in Input) []string { + var fix []string + if in.Conflicting { + fix = append(fix, "rebase onto the base branch") + } + if in.DCOMissing { + fix = append(fix, "add the DCO sign-off") + } + if !in.CIGreen { + fix = append(fix, "make CI green without widening scope") + } + return fix +} + +func itoa(n int) string { return fmt.Sprintf("%d", n) } + +// LadderRungs returns the rung slugs in evaluation order (for docs/tests). +func LadderRungs() []string { return append([]string(nil), ladderRungs...) } diff --git a/src/pkg/delegatedecision/ladder_test.go b/src/pkg/delegatedecision/ladder_test.go new file mode 100644 index 0000000000..18c4dae186 --- /dev/null +++ b/src/pkg/delegatedecision/ladder_test.go @@ -0,0 +1,197 @@ +package delegatedecision + +import ( + "strings" + "testing" +) + +// hivecommons/hive#15289: the contributor-PR ladder. #15219 (author via a +// clanker, conflicting, offline) was adopted in supersede mode although +// #15202 had already been fixed and merged by #15240; the ladder closes it +// as superseded instead, and only reaches adoption as the last resort. +func TestDecideLadder(t *testing.T) { + // The #15219 scenario as the dashboard gathers it. + incident := Input{Repo: "hivecommons/hive", Kind: KindPR, Number: 15219, Title: "Fix the thing", Author: "thatguywob", + Labels: []string{"author/clanker", "adoption/supersede", "stage/085-needs-decision", "needs-rebase"}, + Conflicting: true, CIGreen: false, ContributorOnline: false, AdoptionStalled: true, AuthorTooling: AuthorToolingClanker} + fixed := &MergedCloser{PR: 15240, Issue: 15202, SHA: "25de3ba24fa0c0ffee0000000000000000000000"} + cases := []struct { + name string + in Input + verdict Verdict + rule string + kinds []ActionKind + target int + textHas []string + ruledOutHas []string + noLadder bool + }{ + { + name: "15219: issue closed by merged 15240 → close as superseded, never adopt", + in: with(incident, func(i *Input) { i.SupersededBy = fixed }), + verdict: VerdictCloseSuperseded, rule: RuleAlreadyFixed, kinds: []ActionKind{ActionCloseDuplicate}, target: 15240, + textHas: []string{"#15202 was already fixed by merged PR #15240 (25de3ba)"}, + }, + { + name: "already fixed on a paused repo → recommend only, no write", + in: with(incident, func(i *Input) { i.SupersededBy = fixed; i.RepoPaused = true }), + verdict: VerdictRecommendOnly, rule: RuleAlreadyFixed, kinds: []ActionKind{ActionRecommendOnly}, + textHas: []string{"close #15219 as superseded"}, + }, + { + name: "already fixed, person-authored → recommend only (theirs to close)", + in: with(incident, func(i *Input) { i.SupersededBy = fixed; i.HumanAuthor = true; i.AuthorTooling = AuthorToolingPerson }), + verdict: VerdictRecommendOnly, rule: RuleAlreadyFixed, kinds: []ActionKind{ActionRecommendOnly}, + }, + { + name: "declared supersession (no issue) → close as superseded", + in: with(incident, func(i *Input) { i.SupersededBy = &MergedCloser{PR: 15206} }), + verdict: VerdictCloseSuperseded, rule: RuleAlreadyFixed, target: 15206, textHas: []string{"superseded by merged PR #15206"}, + }, + { + name: "mergeable as-is → merge gate, no adoption", + in: with(incident, func(i *Input) { i.Conflicting = false; i.CIGreen = true; i.AdoptionStalled = false }), + verdict: VerdictApprove, rule: RuleMergeableAsIs, kinds: []ActionKind{ActionCommentDecision, ActionApproveReview}, + ruledOutHas: []string{RuleAlreadyFixed + ": no merged PR has closed this PR's issue"}, + }, + { + name: "offline clanker, conflicting → adopt-supersede as the last resort", + in: incident, + verdict: VerdictAdoptSupersede, rule: RuleContributorOffline, kinds: []ActionKind{ActionCommentDecision, ActionAdoptSupersede}, + ruledOutHas: []string{ + RuleAlreadyFixed + ":", RuleMergeableAsIs + ": conflicting", RuleRebaseThenMerge + ":", + RuleReturnToContributor + ": the author's clanker hasn't been connected since the nudge", + }, + }, + { + name: "conflicts only, offline → rung 3 recorded as unavailable (#15104), adopted", + in: with(incident, func(i *Input) { i.CIGreen = true; i.AdoptionStalled = false }), + verdict: VerdictAdoptSupersede, rule: RuleContributorOffline, + ruledOutHas: []string{RuleRebaseThenMerge + ": conflicts are the only blocker, but the unattended rebase path (hivecommons/hive#15104) is not available yet"}, + }, + { + name: "online clanker, conflicting → returned to the contributor, not adopted", + in: with(incident, func(i *Input) { i.ContributorOnline = true }), + verdict: VerdictDirection, rule: RuleReturnToContributor, kinds: []ActionKind{ActionCommentDecision}, + textHas: []string{"the author's clanker is connected: rebase onto the base branch, make CI green"}, + }, + { + name: "rework picked up by the relay → returned to the contributor", + in: with(incident, func(i *Input) { i.ReworkPickedUp = true; i.AuthorTooling = AuthorToolingHive }), + verdict: VerdictDirection, rule: RuleReturnToContributor, + textHas: []string{"the author's hive has picked the rework up"}, + }, + { + name: "owner PR, offline, conflicting → never adopted (return to author)", + in: with(incident, func(i *Input) { i.OwnerAuthor = true; i.Author = "clubanderson"; i.AuthorTooling = AuthorToolingPerson }), + verdict: VerdictDirection, rule: RuleReturnToAuthor, textHas: []string{"@clubanderson"}, noLadder: true, + }, + { + name: "hive PR is not the ladder's", + in: with(incident, func(i *Input) { i.HiveAuthored = true; i.TrustedAuthor = true }), + verdict: VerdictDirection, rule: "fix-then-merge", noLadder: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + d := Run(tc.in) + if d.Verdict != tc.verdict || d.Rule != tc.rule { + t.Fatalf("verdict/rule = %s/%s, want %s/%s (%+v)", d.Verdict, d.Rule, tc.verdict, tc.rule, d) + } + if tc.kinds != nil { + var got []ActionKind + for _, a := range d.Actions { + got = append(got, a.Kind) + } + if strings.Join(kindsOf(got), ",") != strings.Join(kindsOf(tc.kinds), ",") { + t.Fatalf("actions = %v, want %v", got, tc.kinds) + } + } + if tc.target > 0 { + found := false + for _, a := range d.Actions { + if a.Target == tc.target { + found = true + } + } + if !found { + t.Fatalf("no action targets #%d: %+v", tc.target, d.Actions) + } + } + for _, w := range tc.textHas { + if !strings.Contains(d.Text, w) { + t.Errorf("text %q lacks %q", d.Text, w) + } + } + for _, a := range d.Actions { + if a.Kind == ActionAdoptSupersede && tc.in.PersonAuthored() { + t.Fatalf("a person's PR was adopted: %+v", d) + } + } + if tc.noLadder { + if d.Ladder != nil { + t.Fatalf("ladder set on a non-ladder decision: %+v", d.Ladder) + } + return + } + if d.Ladder == nil || d.Ladder.Decision != tc.rule || d.Ladder.Reason == "" { + t.Fatalf("ladder = %+v", d.Ladder) + } + joined := strings.Join(d.Ladder.RuledOut, "\n") + for _, w := range tc.ruledOutHas { + if !strings.Contains(joined, w) { + t.Errorf("ruled_out lacks %q:\n%s", w, joined) + } + } + }) + } +} + +func kindsOf(k []ActionKind) []string { + out := make([]string, 0, len(k)) + for _, x := range k { + out = append(out, string(x)) + } + return out +} + +// The decision names the author's tooling truthfully: a clanker relay is +// not a hive (hivecommons/hive#15289: #15219's decision said "the author's +// hive" for a clanker-relayed author). +func TestAuthorWording(t *testing.T) { + cases := []struct { + tooling AuthorTooling + word string + offline string + }{ + {AuthorToolingClanker, "the author's clanker", "the author's clanker hasn't been connected since the nudge"}, + {AuthorToolingHive, "the author's hive", "the author's hive hasn't been connected since the nudge"}, + {AuthorToolingPerson, "the author", "the author hasn't been reachable since the nudge"}, + {AuthorToolingUnknown, "the author", "the author hasn't been reachable since the nudge"}, + } + for _, tc := range cases { + in := Input{AuthorTooling: tc.tooling} + if got := in.AuthorWord(); got != tc.word { + t.Errorf("%q: AuthorWord = %q, want %q", tc.tooling, got, tc.word) + } + if got := in.OfflineWording(); got != tc.offline { + t.Errorf("%q: OfflineWording = %q, want %q", tc.tooling, got, tc.offline) + } + } + d := Run(Input{Kind: KindPR, Number: 15219, Conflicting: true, AuthorTooling: AuthorToolingClanker}) + if d.Rule != RuleContributorOffline || !strings.Contains(d.Rationale, "the author's clanker hasn't been connected") || strings.Contains(d.Rationale, "author's hive") { + t.Fatalf("offline rationale must name the clanker: %+v", d) + } + if got := AuthorToolingFromLabels([]string{"author/clanker"}, "author/hive", "author/clanker", "author/human", false); got != AuthorToolingClanker { + t.Errorf("labels → %q", got) + } + if got := AuthorToolingFromLabels([]string{"author/clanker", "author/hive"}, "author/hive", "author/clanker", "author/human", false); got != AuthorToolingHive { + t.Errorf("hive beats clanker: %q", got) + } + if got := AuthorToolingFromLabels([]string{"author/clanker"}, "author/hive", "author/clanker", "author/human", true); got != AuthorToolingPerson { + t.Errorf("owner is a person: %q", got) + } + if Plain(RuleContributorOffline) != "the author hasn't been reachable since the nudge" { + t.Errorf("glossary plain words must not presume a hive: %q", Plain(RuleContributorOffline)) + } +} diff --git a/src/pkg/delegatedecision/policy.go b/src/pkg/delegatedecision/policy.go index 254ef418a7..c1d87a440f 100644 --- a/src/pkg/delegatedecision/policy.go +++ b/src/pkg/delegatedecision/policy.go @@ -207,6 +207,20 @@ type Input struct { WorkflowPath bool // BlockedOnPRClosed: a review-backlog item whose PR closed unmerged. BlockedOnPRClosed bool + // SupersededBy names the merged PR that already delivered this PR's + // work (its issue is closed by that merge, or that PR declares + // `Supersedes #N`); nil when none is known (hivecommons/hive#15289). + SupersededBy *MergedCloser + // AuthorTooling: what the author drives (hive / clanker / person); + // picks the words a decision uses for them (AuthorWord). + AuthorTooling AuthorTooling + // ReworkPickedUp: the author's relay has acknowledged, claimed or + // pushed the requested rework (hivecommons/hive#15280's signal), so + // they are responsive even without recent activity. + ReworkPickedUp bool + // RepoPaused: the repo is under an operator pause; a decision that + // would write (close) is recommend-only instead. + RepoPaused bool } // RuleAdoptNow is the rule name of the grace-elapsed Adopt now decision; @@ -225,6 +239,9 @@ type Decision struct { // KeepsPark is true when the item stays at 085/045 (recommend-only, // owner-only, refused). KeepsPark bool `json:"keeps_park"` + // Ladder is the contributor-PR rung the decision landed on and why + // the rungs above it did not apply (hivecommons/hive#15289). + Ladder *Ladder `json:"ladder,omitempty"` } // Marker is the audit stamp every delegated comment carries. @@ -475,6 +492,14 @@ func decidePR(in Input) Decision { return d } } + // The contributor-PR ladder (hivecommons/hive#15289): already fixed → + // mergeable as-is → rebase-then-merge → return to contributor → + // adopt-supersede, in that order, so a PR whose issue a merged PR + // already closed is closed as superseded rather than adopted. A + // person's PR leaves the ladder after the already-fixed rung. + if d, ok := decideLadder(in, ref); ok { + return d + } // A person pushed this PR themselves (an owner, or author/human): // it is theirs to fix, never the hive's to adopt (hivecommons/hive#15202). if in.PersonAuthored() { @@ -491,22 +516,6 @@ func decidePR(in Input) Decision { return recommendOnly(RuleCapabilityGap, "the PR edits .github/workflows and the hive's GitHub App lacks the `workflows` permission, so the adoption fence refuses to supersede it; deciding to adopt cannot take effect", "grant the App the `workflows` permission and re-run the decision, or have a person rebase and merge "+ref+" on GitHub, or close it as superseded") } - if !in.HiveAuthored && !in.PersonAuthored() && in.Kind == KindPR && in.AdoptionGraceElapsed { - text := "adopt now: the offline grace on " + ref + " has already elapsed; adopt in supersede mode at once, preserving the author's commits and sign-off" - return Decision{ - Verdict: VerdictAdoptSupersede, Rule: RuleAdoptNow, Text: text, - Rationale: "the contributor's grace window has run out and nothing moved; waiting longer helps no one (hivecommons/hive#15038)", - Actions: []Action{decisionComment(text), {Kind: ActionAdoptSupersede}}, - } - } - if !in.HiveAuthored && !in.PersonAuthored() && !in.ContributorOnline && (in.AdoptionStalled || in.Conflicting || !in.CIGreen || in.DCOMissing) { - text := "supersede now: adopt " + ref + " in supersede mode, preserving the author's commits and sign-off; do not wait for the grace deadline" - return Decision{ - Verdict: VerdictAdoptSupersede, Rule: "contributor-offline", Text: text, - Rationale: "the contributor is offline; adoption in supersede mode keeps the work moving (hivecommons/hive#13975)", - Actions: []Action{decisionComment(text), {Kind: ActionAdoptSupersede}}, - } - } if in.ReporterTrustHold && in.CIGreen && !in.Conflicting && !in.DCOMissing { d := releasePR("reporter-trust", "approve "+ref+": the fixing PR is sound, so the reporter-trust hold is cleared", "a reporter-trust hold is cleared when the fixing PR is sound") d.Actions = append(d.Actions, Action{Kind: ActionLabelsAdd, Labels: []string{LabelTriageAccepted}}) diff --git a/src/pkg/github/pr_merged_supersession.go b/src/pkg/github/pr_merged_supersession.go new file mode 100644 index 0000000000..ad7e2ceea2 --- /dev/null +++ b/src/pkg/github/pr_merged_supersession.go @@ -0,0 +1,77 @@ +package github + +import ( + "context" + "fmt" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// MergedSupersession names the merged pull request that already delivered +// an open PR's work: the issue the open PR claims to close is closed and +// Closer merged closing it (Issue > 0), or Closer's body declares +// `Supersedes #` (Issue == 0). It is the "already fixed" fact the +// delegated-decision ladder reads before it considers adopting a PR +// (hivecommons/hive#15289: #15219 was adopted although #15240 had already +// fixed #15202). +type MergedSupersession struct { + Closer int + Issue int + MergeSHA string + MergedAt time.Time + URL string +} + +// DetectMergedSupersession reports whether pr (an open PR of repo, +// "owner/name") has been superseded by a merged PR, reusing the supersession +// sweep's detectors: the closed-issue / merged-closer rule first, then the +// declared `Supersedes #N` rule (hivecommons/hive#15208). The closer's merge +// commit is read so callers can name it. A lookup failure is returned, not +// read as "not superseded", because the caller's fallback is adoption. +func (c *Client) DetectMergedSupersession(ctx context.Context, repo string, pr *gh.PullRequest) (MergedSupersession, bool, error) { + if c == nil || c.client == nil { + return MergedSupersession{}, false, ErrNoGitHubClient + } + if pr == nil || pr.GetNumber() <= 0 { + return MergedSupersession{}, false, nil + } + owner, name := c.splitRepo(repo) + identity := c.getHiveIdentity() + if identity.AppLogin == "" { + identity.AppLogin = c.appBotLogin + } + candidate, closer, detected, err := c.detectSupersession(ctx, repo, pr, identity, time.Now()) + if err != nil { + return MergedSupersession{}, false, err + } + out := MergedSupersession{} + switch { + case detected: + out = MergedSupersession{Closer: closer.Number, Issue: candidate.Issue, MergedAt: closer.MergedAt, URL: closer.URL} + default: + declared, by, err := c.detectDeclaredSupersession(ctx, owner, name, pr) + if err != nil { + return MergedSupersession{}, false, fmt.Errorf("reading declared supersession for %s#%d: %w", repo, pr.GetNumber(), err) + } + if !declared { + return MergedSupersession{}, false, nil + } + out = MergedSupersession{Closer: by.Number, MergedAt: by.MergedAt, URL: by.URL} + } + closerPR, _, err := c.client.PullRequests.Get(ctx, owner, name, out.Closer) + if err != nil { + return MergedSupersession{}, false, fmt.Errorf("reading superseding PR %s#%d: %w", repo, out.Closer, err) + } + if !closerPR.GetMerged() && closerPR.GetMergedAt().Time.IsZero() { + // The reference said merged but the PR does not: do not close on + // a stale or inconsistent read. + return MergedSupersession{}, false, nil + } + out.MergeSHA = strings.TrimSpace(closerPR.GetMergeCommitSHA()) + if out.URL == "" { + out.URL = closerPR.GetHTMLURL() + } + return out, true, nil +}