From 5153ac1bf966647ede386d9eb3d22042522b5ffd Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 15:38:26 -0400 Subject: [PATCH] fix(reporter-trust): never hold hive-authored PRs, judge only linked issues, show and release hive-set holds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #9665 reporter-trust merge hold judged hivecommons/hive#15020, a hive-authored PR, via a bare '#15017' mention that resolved to a sibling PR, attributed that PR's author as an untrusted issue reporter and held the PR two seconds after it opened; the tracker then showed only 'hold +1 · Needs human decision'. - Gate rationale is closing-keyword and declared issue links only; a link that resolves to a PR is skipped; hive self-reports are trusted; the gate is skipped for hive-authored PRs (kept for contributor and shared-PAT PRs). - Stage-label pass records hold provenance (by/source/reason/since) from the reporter-trust notice and the newest hold label event; tracker pill reads 'Held by hive · reporter trust (issue #N by @X, contributor)' or 'Held by @login'; the decision popover asks release/keep with Release leading; the 085 comment names who set the hold and why. - The same pass releases a hive-set reporter-trust hold on a hive-authored PR and logs 'stage labels: releasing self-imposed reporter-trust hold'; operator holds are left alone. Fixes #15075 Signed-off-by: Andrew Anderson --- ...fixed-reporter-trust-hold-hive-authored.md | 1 + src/docs/dashboard-sections.md | 2 + src/docs/labels-and-control-signals.md | 4 +- src/pkg/dashboard/stage_tracker.go | 38 ++ src/pkg/dashboard/stage_tracker_decision.go | 63 +++- .../stage_tracker_hold_provenance_test.go | 186 ++++++++++ src/pkg/dashboard/static/index.html | 35 +- .../github/automerge/automerge_stage_human.go | 11 + .../automerge/automerge_stage_labels.go | 27 ++ .../automerge/automerge_stage_labels_test.go | 19 + .../automerge/reporter_trust_release.go | 157 ++++++++ .../automerge/reporter_trust_release_test.go | 335 ++++++++++++++++++ src/pkg/github/pr_level_hold.go | 2 +- src/pkg/github/pr_reporter_trust.go | 171 ++++++++- src/pkg/github/pr_request_watcher.go | 11 +- src/pkg/github/pr_self_authorization_test.go | 20 +- src/pkg/github/reporter_trust_test.go | 111 +++++- src/pkg/stageengine/prstage/types.go | 4 + src/pkg/stagelabels/hold.go | 118 ++++++ src/pkg/stagelabels/hold_test.go | 137 +++++++ src/pkg/stagelabels/human.go | 13 +- src/pkg/stagelabels/store.go | 28 ++ 22 files changed, 1453 insertions(+), 40 deletions(-) create mode 100644 changelog.d/fixed-reporter-trust-hold-hive-authored.md create mode 100644 src/pkg/dashboard/stage_tracker_hold_provenance_test.go create mode 100644 src/pkg/github/automerge/reporter_trust_release.go create mode 100644 src/pkg/github/automerge/reporter_trust_release_test.go create mode 100644 src/pkg/stagelabels/hold.go create mode 100644 src/pkg/stagelabels/hold_test.go diff --git a/changelog.d/fixed-reporter-trust-hold-hive-authored.md b/changelog.d/fixed-reporter-trust-hold-hive-authored.md new file mode 100644 index 0000000000..15f19e90bf --- /dev/null +++ b/changelog.d/fixed-reporter-trust-hold-hive-authored.md @@ -0,0 +1 @@ +- The reporter-trust merge hold (#9665) no longer holds hive-authored PRs, judges only linked issues (closing-keyword and declared links; a link that resolves to a PR is skipped, hive self-reports count as trusted), and the stage-label pass releases a hive-set reporter-trust hold left on a hive-authored PR; the stage tracker pill now reads "Held by hive · reporter trust (issue #N by @X, contributor)" / "Held by @login" with a release/keep decision popover, and the needs-decision comment names who set the hold and why. diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 85b8788e5f..97d5d7a6f7 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -708,6 +708,8 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p **Needs-human decision popover.** Hovering — or, by keyboard, focusing — the *Needs human decision* chevron word on a row (an issue at 045, a PR at 085, an issue whose nested PR is parked there) or a lead *needs-human* / *triage needed* pill opens an in-app popover (no native tooltip on that element) that says, in this order: **what the row is waiting on** — the reviewer's own question when the hive has one (the text the hive's "Needs a decision" comment on the PR prints after *reviewer question:*, read from the same verdict record), else a plain-words sentence for the park reason, plus the blocker in plain words ("A reviewer requested changes on b0f5f80 — needs a new commit. Approving cannot override that."); **what you can do** — one button per applicable action, *Let hive decide* first, then Approve / Give direction / Close as superseded / Close as won't fix / Hold or Release hold (an issue at 015: Accept triage, Hold, Mark needs-human), each disabled with its reason when the row's state or your role rules it out; **who asked and when** ("Asked by a reviewer · 2 hours ago"); then the chevron's stage line. The buttons run the row context menu's code path, so the same result toast and in-flight chevron apply. The popover stays open while the pointer is over it or its trigger, pins on click or focus, and closes on Esc (focus returns to the trigger), click-away, scroll or resize. The text comes from the tracker payload's `decision_needed` (`question`, `asked_by`, `since`, `blocker`, `blocker_reason`, `options[] {action, label, enabled, reason_if_disabled}`), whose `action` ids are the context menu's own (`decide:delegate`, `decide:approve`, …). +**Hold pill with provenance.** When the hive can say who set a row's `hold` label and why, the pill does not read a bare *hold*: it reads **Held by hive · reporter trust (issue #15017 by @Karibhou, contributor)** when the hive's own reporter-trust gate ([#9665](https://github.com/hivecommons/hive/issues/9665)) set it, **Held by hive** when the hive set it for another reason, or **Held by @login** when a person added the label; a hold the hive cannot attribute keeps the plain *hold* word. The hover text repeats the pill, says since when, and for a hive-set reporter-trust hold explains that the hive set it itself and that *Release hold* lifts it. That same pill opens the needs-human decision popover: its question reads *The hive held this PR itself for reporter trust (issue #N by @X, contributor). Release the hold, or keep it?*, **Release hold** leads the buttons (enabled), *Let hive decide* waits until the hold is released, and `blocker_reason` is `hold:hive`. A person's hold names them in the blocker instead (*On hold (set by @login) — the hive does nothing until the hold is released.*). The data rides the tracker payload as `hold {by, source, reason, since, issue, reporter, association, pill}` on the item and on each nested `linked_pr`; `by` is `hive` or the login of the person whose label event set it, `source` is `reporter-trust` or `label`. It comes from the stage-label pass, which reads the hive's `` notice and the newest `hold` label event ([#15020](https://github.com/hivecommons/hive/pull/15020): a hive-authored PR sat 49 minutes as *hold +1 · Needs human decision* with no way to tell that the hive had held it two seconds after opening it). A hive-authored PR never keeps a hive-set reporter-trust hold: the same pass releases it, so the pill is normally seen only on contributor PRs. + **Cue tokens.** The three cues of the legend above (state pill, working spin, decision badge) share one `tracker-cues` CSS block on `.ham-row`: `--cue-state` (what the row waits on — the pill and this popover), `--cue-work` (the hive is working right now — the chevron spin), `--cue-decision` (what people and the hive decided — the ✓ badge). Nothing else blinks; motion stays in the 150–300 ms range. ### Let hive decide diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index b01c3d1780..1b5d01cff5 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -65,7 +65,7 @@ Some hive-authored labels look like provenance but are read as signals, so they | `hold` from ACMM level gate | PRs | PR-request watcher, self-authored auto-merge release | Agent PRs at L3-L5 get literal `hold`; `outreach` PRs whose target repo is not one the hive manages (cross-repo outreach) are held at every level, while same-repo outreach PRs follow the level. The watcher, not the policy prompt, applies it from the PR's target repo (`config.AgentOwnsRepo`). | Hard merge gate | Hive App | PR creation, later self-authored auto-merge release | Auto-release only when current policy no longer requires the level hold, latest hold event was by the App, and the release path runs; otherwise a human removes it | Hive-wide ACMM and agent (`src/pkg/github/pr_request_watcher.go:452-524`, `src/pkg/github/pr_level_hold.go:16-124`) | | `hold` from #5117 self-authorization | PRs | PR-request watcher and self-authorization release | A PR whose only rationale is unacknowledged hive-filed issues gets literal `hold`. Acknowledging the issue later does not remove an existing PR hold by itself. At ACMM L6 (Autonomous), the unset default is off; lower levels default on. | Hard merge gate | Hive App | PR creation; evaluated only when no level hold applies | Acknowledge the issue and remove the PR `hold`; disabled policy release can remove Hive's own hold. At L6, that release path also clears existing Hive-applied #5117 holds when no explicit config keeps the policy on. | `github.self_authorization_hold`, per-repo `project.repo_policies[].self_authorization_hold`, `HIVE_SELF_AUTHORIZATION_HOLD` (`src/pkg/github/pr_self_authorization.go:14-226`, `src/pkg/github/pr_request_watcher.go:452-524`) | | `triage/accepted` (or `project.issue_filter.reporter_trust.untrusted_require_labels`); `needs-triage` while waiting | Human-filed issues from untrusted reporters | GitHub enumeration | With `reporter_trust.enabled: true`, an issue whose reporter's GitHub `author_association` is outside the trusted set (default `OWNER`, `MEMBER`, `COLLABORATOR`) and whose login is not in `trusted_logins` is not actionable until it carries one of these labels. On the first excluded scan, core `github.Client.fetchIssues` posts one marked explanation comment and applies `needs-triage` (or `awaiting_label`); later scans do not repeat the comment. This is a poller-side write, not an agent prompt, and is capped at 10 new notices per poll. When the triage label appears, the same poll loop removes `needs-triage` only if the marker records that Hive added it, then the issue enters the backlog. Independently of the marker, the stage sweep removes `needs-triage` once the issue reaches 020 or later (claiming settles triage; see `stage/015-triage-needed` below) — this is what retires the `needs-triage` that `fleetreport` stamps on hive-filed self-reports at filing. Trusted reporters' issues pass untouched. Runs after holds/exempts and before `require_labels`, so the ordinary allow-list still applies afterwards. Hive- and bot-filed issues are not judged here (#5117 owns them). Counted as "needs triage" on the repo card, not as a generic filter refusal. | Hard admission gate (off by default) | Human; Hive App for the visibility comment/label | Enumeration | Add the label, trust the login or association under **Settings → Labels → Reporter trust**, or disable the gate | `project.issue_filter.reporter_trust.{enabled,trusted_associations,trusted_logins,untrusted_require_labels,awaiting_label,comment}` (`src/pkg/config/reporter_trust.go`, `src/pkg/github/client.go` `fetchIssues`) | -| `hold` from #9665 reporter trust | PRs | PR-request watcher, level-hold release | A PR whose rationale (closing or referencing links, or the request's declared issues) traces to an issue filed by an untrusted reporter gets literal `hold` at **every** ACMM level, including L6, plus `needs-human` (so it surfaces as waiting on a person, #10773) and a marked notice naming the untrusted reporter and stating the PR itself was authored by the hive. Any one untrusted citation holds. Evaluated even at hold-gated levels, because the notice is what stops promotion to L6 from releasing the label. | Hard merge gate | Hive App | PR creation; re-checked by the level-hold release path | A human removes `hold`. Hive never auto-releases it: the release sweep sees the notice (or re-evaluates and re-posts it) and leaves the label. Holdguard re-holds on a new head SHA. | `github.reporter_trust_hold` (nil follows `reporter_trust.enabled`), per-repo `project.repo_policies[].reporter_trust_hold`, `HIVE_REPORTER_TRUST_HOLD` (`src/pkg/github/pr_reporter_trust.go`, `src/pkg/github/pr_level_hold.go`) | +| `hold` from #9665 reporter trust | PRs **not authored by the hive** | PR-request watcher, level-hold release | A PR whose rationale traces to an issue filed by an untrusted reporter gets literal `hold` at **every** ACMM level, including L6, plus `needs-human` (so it surfaces as waiting on a person, #10773) and a marked notice (`` + ``) naming the untrusted reporter and stating that the hold concerns the issue reporter, not the PR author. The rationale is **only the linked issues**: closing-keyword links (`Fixes`/`Closes`/`Resolves`) and the request's declared issues — bare `#N` mentions are not consulted, and a link that resolves to a pull request is skipped rather than judged (hivecommons/hive#15020: `Refs #15009 (closed by #15017)` made the gate judge sibling PR #15017 and attribute a `CONTRIBUTOR` who had merely commented). A hive-filed issue (`[selfreport]`, app or AI author) counts as trusted. The gate is **skipped entirely for hive-authored PRs** (App bot, `project.ai_author`, `author/hive`): the hive is the author, so the reporter's trust says nothing about whether its own fix may merge; it still applies to contributor PRs and to PRs opened under a shared PAT account. Any one untrusted citation holds. Evaluated even at hold-gated levels, because the notice is what stops promotion to L6 from releasing the label. | Hard merge gate | Hive App | PR creation; re-checked by the level-hold release path | A human removes `hold` on a contributor PR; Hive never auto-releases it there. On a **hive-authored** PR still wearing a hive-set reporter-trust hold (newest `hold` event labeled by the App bot with the notice at or after it — a person's hold is left alone), the stage-label pass releases `hold` (and `needs-human` when the notice says the gate added it), posts one `` comment and logs `stage labels: releasing self-imposed reporter-trust hold`. The pass also records the hold's provenance (`by`, `source`, `reason`, `since`) on the stage store, so the tracker pill reads *Held by hive · reporter trust (issue #N by @X, contributor)* and the 085 comment names who set the hold and why. Holdguard re-holds on a new head SHA. | `github.reporter_trust_hold` (nil follows `reporter_trust.enabled`), per-repo `project.repo_policies[].reporter_trust_hold`, `HIVE_REPORTER_TRUST_HOLD` (`src/pkg/github/pr_reporter_trust.go`, `src/pkg/github/pr_level_hold.go`, `src/pkg/github/automerge/reporter_trust_release.go`) | | `project.repo_policies[].auto_merge: false` | PRs | `hive-merge` relay, App self-authored auto-merge sweep, proxy | Below L6 this resolves off for every repo; at L6, PRs can still be opened, reviewed and held when the per-repo switch is off, but Hive refuses every merge path for that repo. Existing `hold` / `hive-pause/` labels stay put because the disabled repo is skipped before hold release or merge. | Hard merge gate | Operator/dashboard | Merge relay request, self-merge sweep tick, proxy direct merge attempt | Dashboard repo-card switch or config edit sets `auto_merge: true`/removes the override at L6; enabling is rejected below L6 | `project.repo_policies[].auto_merge` (`src/pkg/config/repo_policy.go`, `src/pkg/agent/manager_modes.go`, `src/pkg/github/automerge/automerge_sweep.go`, `src/pkg/proxy/rules.go`) | | `hold` from holdguard | PRs | Holdguard ledger | If the head SHA changes while held, lifting the hold causes Hive to comment and re-apply literal `hold`; the next human removal is the fresh approval. Exception (#13603): when a human (not a Hive account, not a bot) removed the gate label after the current head arrived on the branch, they reviewed the current head, so the lift clears without a comment or re-hold. The head is accepted only on evidence a contributor cannot forge: the server-stamped `head_ref_force_pushed` timeline event that produced it (dated before the lift), or the hive itself having observed that exact head on the PR while the gate was still on (`observed_held_head_sha` in the holdguard ledger). Commit committer dates and SHA-keyed `check_suite` / `status` times are never used; a push after the lift, or a head the hive never saw while held, still re-holds. | Hard merge gate | Hive | Governor holdguard pass | Human removes the re-applied hold | Built-in `holdguard.ReHoldLabel` (`src/pkg/holdguard/holdguard.go:1-43`) | | `hold` from SHA-hold | Issues | SHA-hold sweep | Human-filed primary-repo `kind/bug` without a 7-40 hex SHA gets `hold` and a notice carrying ``; once a SHA appears in body/comments, Hive removes `hold` only if the current hold is its own (newest `hold` event labeled by the App bot, paired with an App-authored notice at or after it). A human's hold, a re-hold, or another subsystem's hold stays. Reporters whose author association is trusted (`issue_filter.reporter_trust.trusted_associations`, default OWNER/MEMBER/COLLABORATOR) get the soft `needs-sha` row below instead, and a SHA-hold `hold` already on such an issue is swapped for it (#12002). The hard-suppress reconcile also lifts this `hold` once a PR referencing the issue merges after it was applied. | Hard issue hold | Hive | Eval tick SHA sweep; hard-suppress reconcile | Add SHA evidence or merge the fix; sweep removes its own `hold`, a human removes any other | Primary repo and SHA-hold config (`src/pkg/github/client.go` `EnforceSHAHold`, `src/pkg/github/hard_suppress_reconcile.go`) | @@ -227,7 +227,7 @@ referenced it) a lone `stage/050-review-pending` | `stage/072-returned-to-contributor` | PR | clanker PR (`author/clanker`, relay or external hive): CI red / changes requested / conflicting; the hive posted its diagnosis, the ball is in the contributor hive's court. (Briefly spelled `stage/072-needs-author` by [#12713](https://github.com/hivecommons/hive/pull/12713); the engine renames that label back in place) | 24h | | `stage/074-adopted-by-hive` | PR | the author (a clanker) was unavailable — relay offline, never registered, or silent past the grace (see below); the hive took the PR over: in place on the PR's own branch when it may push there (the scanner's red-PR fix kick rebases and fixes it), otherwise via `hive/adopt-` and a superseding App PR that keeps the author's commits (the original closes automatically when the superseder merges). Adoption is an **ownership** state, not a CI state: the PR reads 074 for as long as the hive owns it — through its fixes going pending, green, reviewed or red again (074 outranks 050/060/070/071/072, and a 085 whose only cause is the review swarm's `requires_human` / decision request — the hive answers that on the superseding PR, so the original leaves the merge gate for the CI/Review column with an "Adopted → #N" pill in the adopting pass, never "Needs human decision" (hivecommons/hive#14975 → #14980, #14947 → #14977); a hold, sentinel alert, `needs-human` a person applied, fork-guard or manual-merge lane rule keeps 085) — and leaves 074 only at the merge gate (080/090/100), when the adoption is released, or to 085 `adoption-stalled:` when the head sat unchanged past the dwell with CI idle and a real blocker the hive cannot push past — a red optional check alone never counts, and the escalation releases back to 074 as soon as the reason clears (an in-place adoption with a blocking review finding re-homes to `hive/adopt-` first instead; one with a squash-unsafe hive commit elects a merge commit on a `role/trusted` PR — `merge-method/merge` label, lane continues — and otherwise immediately re-homes to an App-authored superseder (`signoff-rehome`), preserving commits and sign-offs while changing squash attribution; loss of push access re-homes immediately, and idle rebase work re-homes after the dwell). For in-place adoption, a changed head must be linked to the App bot by GitHub commit metadata (the stage store only remembers heads that already passed that check); otherwise the hive treats it as a contributor push and hands the PR back (072 if red, else the normal path). Forgeable git author/committer names and emails never keep 074. A PR whose author holds **admin** or **maintain** on the repository is never adopted or re-homed (one cached permission read per repo and author per 10 minutes; a failed read is not cached and defers: no adoption, and an existing adoption is neither released nor re-homed until the read succeeds), and an adoption of such an author is released on the next pass, closing a still-open hive superseder with a note first. | 3h | | `stage/080-awaiting-merge-admission` | PR | nothing left for the author: CI green (no red check on the head, required or not), verdict approve, no modifiers — and the automerge lane has not admitted it yet (prefilter not evaluated for this head, labels not synced, lane tripped). A stall here means a lane problem, so the hive also posts one `` comment with the lane's last skip reason | 30m | -| `stage/085-needs-decision` | PR | **PR-only** since the owner decision of 2026-10-17 (issues park at `stage/045-needs-decision`; before that this stage carried both, [#12683](https://github.com/hivecommons/hive/issues/12683)). A person owes a **decision**, not a merge: a `requires_human` swarm verdict (reason `reviewer-verdict:requires_human`), `sentinel-alert`, `hold` / `do-not-merge*` / `needs-decision` modifier, no reviewer configured, GitHub workflow approval is required for a trusted same-repo bot/App/clanker PR (`workflow-approval-required:`); Hive has posted `/ok-to-test` and is waiting for the repo-local `hive-ok-to-test` workflow or a maintainer, or a human-only lane rule unrelated to trust (workflow-path edits, tests removed, human-merge path, reporter-trust hold). A trusted human's normal GitHub **Approve** review on the exact current head clears a `requires_human` verdict for any author kind/lane and records `reviewer-verdict:requires_human:human-approved@`; a new head invalidates it. The same approval also clears the merge-lane review gate over any non-approved swarm outcome, a perspective's `changes_requested` included (the `review_evaluated` audit line records `human_approver` and `overrode`); without it, `changes_requested` / `reject` still require fixes or manual merge. Under `review.self_authored_decision_policy: resolve`, a Hive-authored PR's reviewer decision question parks here only when it matches a named risk class (`review.DecisionRiskClasses`: permissions/credentials, security, sensitive paths, data loss/irreversible, merge/trust policy, external side effects, licensing/legal, unverifiable) or carries ``; any other question is resolved by policy and recorded as an advisory reason on the approving aggregate. Hive-authored non-risk incomplete-fix reviews with concrete remediation are normalized to `changes_requested` at verdict load/aggregation time and by the stage-label detail selector, even when the finding was marked high severity; duplicate summary/changelog intent-alignment cleanup with a concrete trim/reword fix is included. Those PRs go to `stage/070-fixing`, not here. On a hive-authored PR the trusted human can also answer with a **changes requested** review on the head, or `/hive decision `, which moves the PR to `stage/070-fixing` and kicks the author agent with the text verbatim ([#13041](https://github.com/hivecommons/hive/issues/13041)); `/hive decision` on a PR the hive did not open gets one reply naming the review-side equivalents. One `` comment on entry names what is owed, and for a hive-authored `requires_human` park names the two actions: approve the head to merge as-is, or request changes and the hive pushes the fix | none | +| `stage/085-needs-decision` | PR | **PR-only** since the owner decision of 2026-10-17 (issues park at `stage/045-needs-decision`; before that this stage carried both, [#12683](https://github.com/hivecommons/hive/issues/12683)). A person owes a **decision**, not a merge: a `requires_human` swarm verdict (reason `reviewer-verdict:requires_human`), `sentinel-alert`, `hold` / `do-not-merge*` / `needs-decision` modifier, no reviewer configured, GitHub workflow approval is required for a trusted same-repo bot/App/clanker PR (`workflow-approval-required:`); Hive has posted `/ok-to-test` and is waiting for the repo-local `hive-ok-to-test` workflow or a maintainer, or a human-only lane rule unrelated to trust (workflow-path edits, tests removed, human-merge path, reporter-trust hold). A trusted human's normal GitHub **Approve** review on the exact current head clears a `requires_human` verdict for any author kind/lane and records `reviewer-verdict:requires_human:human-approved@`; a new head invalidates it. The same approval also clears the merge-lane review gate over any non-approved swarm outcome, a perspective's `changes_requested` included (the `review_evaluated` audit line records `human_approver` and `overrode`); without it, `changes_requested` / `reject` still require fixes or manual merge. Under `review.self_authored_decision_policy: resolve`, a Hive-authored PR's reviewer decision question parks here only when it matches a named risk class (`review.DecisionRiskClasses`: permissions/credentials, security, sensitive paths, data loss/irreversible, merge/trust policy, external side effects, licensing/legal, unverifiable) or carries ``; any other question is resolved by policy and recorded as an advisory reason on the approving aggregate. Hive-authored non-risk incomplete-fix reviews with concrete remediation are normalized to `changes_requested` at verdict load/aggregation time and by the stage-label detail selector, even when the finding was marked high severity; duplicate summary/changelog intent-alignment cleanup with a concrete trim/reword fix is included. Those PRs go to `stage/070-fixing`, not here. On a hive-authored PR the trusted human can also answer with a **changes requested** review on the head, or `/hive decision `, which moves the PR to `stage/070-fixing` and kicks the author agent with the text verbatim ([#13041](https://github.com/hivecommons/hive/issues/13041)); `/hive decision` on a PR the hive did not open gets one reply naming the review-side equivalents. One `` comment on entry names what is owed, and for a hive-authored `requires_human` park names the two actions: approve the head to merge as-is, or request changes and the hive pushes the fix. When the park is a `hold`, the comment says who set it — *the `hold` label was set by the hive itself: reporter trust (issue #N by @X, contributor)* or *by @login* — and for a hive-set hold offers *release the hold* / *keep it* (hivecommons/hive#15020) | none | | `stage/090-ready-for-human-merge` | PR | the hive would merge this itself but trust/role blocks it: reviewer verdict approve at the **current** head, required checks green (tide excluded), DCO yes, no sentinel alert, no conflicts, soak elapsed, no hold — and the only remaining lane reason is the author's tier/role. A maintainer's `/lgtm` `/approve` is the only missing step. One `` comment on entry carries the evidence. Always read with the `role/*` and `author/*` labels. (Was `stage/090-needs-human` before [#12528](https://github.com/hivecommons/hive/issues/12528); the engine renames the GitHub label in place) | none | | `stage/095-pre-merge-soak` | PR | lane admitted; the pre-merge soak window (`automerge.contributor_lane.soak_minutes`, default 30) is running before the merge is attempted. The dashboard shows it as **Soaking** on the merge-gate column with the time left; a quiet 095 past its dwell is a lane bug (the soak elapsed but the lane never promoted), so the stall note says so. 100 → 095 on a re-evaluation is a reclassification, not a regression | 45m (30m soak + 15m grace) | | `stage/100-merge-queue` | PR | lane admitted and soak complete: merge-eligible, waiting for tide / the merge window — and every check on the head is green (tide excluded). A red optional check is 070/071/072 like any red CI | 3h | diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 0f5d2473ad..1ad5465f91 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -311,6 +311,11 @@ type StageTrackerItem struct { // OnHold is true when the item wears a hold pill: paused on purpose, // waiting on nobody. OnHold bool `json:"on_hold,omitempty"` + // Hold says who set the `hold` label and why, when the stage-label + // pass could read it (hivecommons/hive#15020): the pill then reads + // "Held by hive · reporter trust (issue #N by @X, contributor)" or + // "Held by @login" instead of a bare "hold". + Hold *StageTrackerHold `json:"hold,omitempty"` // RegressedFrom / RegressedTo / RegressedAt / RegressedReason narrate // the unresolved regression behind the `regressed` modifier: the // high-water stage the item fell from, the stage that fall landed on @@ -492,6 +497,37 @@ type StageTrackerLinkedPR struct { // row fields so its sub-row wears the ✓ badge too. LastOperatorAction *StageTrackerOperatorAction `json:"last_operator_action,omitempty"` OperatorActionCount int `json:"operator_action_count,omitempty"` + // Hold mirrors the nested PR's own row field (hivecommons/hive#15020). + Hold *StageTrackerHold `json:"hold,omitempty"` +} + +// StageTrackerHold is the row's hold provenance (stagelabels.HoldProvenance +// in payload shape). By is "hive" for the hive's own holds, else the login. +type StageTrackerHold struct { + By string `json:"by"` + Source string `json:"source,omitempty"` + Reason string `json:"reason,omitempty"` + Since *time.Time `json:"since,omitempty"` + Issue int `json:"issue,omitempty"` + Reporter string `json:"reporter,omitempty"` + Association string `json:"association,omitempty"` + // Pill is the ready-made pill text ("Held by hive · reporter trust + // (issue #15017 by @Karibhou, contributor)"). + Pill string `json:"pill"` +} + +// stageTrackerHoldFrom maps the store's provenance to the payload; nil when +// the record has none or the row no longer wears `hold`. +func stageTrackerHoldFrom(rec stagelabels.Record, hasRec bool, labels []string) *StageTrackerHold { + if !hasRec || rec.Hold == nil || strings.TrimSpace(rec.Hold.By) == "" || !slices.ContainsFunc(labels, func(l string) bool { return strings.EqualFold(strings.TrimSpace(l), modHold) }) { + return nil + } + h := &StageTrackerHold{By: rec.Hold.By, Source: rec.Hold.Source, Reason: rec.Hold.Reason, Issue: rec.Hold.Issue, Reporter: rec.Hold.Reporter, Association: strings.ToLower(rec.Hold.Association), Pill: rec.Hold.Pill()} + if !rec.Hold.Since.IsZero() { + t := rec.Hold.Since + h.Since = &t + } + return h } // Stage numbers the tracker lays out by. Pinned to stagelabels.Table in @@ -1575,6 +1611,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.AdoptedBy = rec.AdoptedBy it.SoakRemainingSeconds = int64(stageTrackerSoakRemaining(rec, now) / time.Second) } + it.Hold = stageTrackerHoldFrom(rec, hasRec, labels) it.Stage = stage.Number() it.StageSlug = stage.Slug() it.StageLabel = stage.Label() @@ -2507,6 +2544,7 @@ func stageTrackerResolveLinkedPRs(items []StageTrackerItem) { lp.BaseRef = pr.BaseRef lp.DecisionNeeded = pr.DecisionNeeded lp.LastOperatorAction, lp.OperatorActionCount = pr.LastOperatorAction, pr.OperatorActionCount + lp.Hold = pr.Hold if len(pr.Modifiers) > 0 { lp.Modifiers = append([]string(nil), pr.Modifiers...) } diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index 5ea451e525..68eedd8548 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -89,13 +89,14 @@ const ( const ( decisionBlockerSentinel = "sentinel-alert" decisionBlockerHold = "hold" + decisionBlockerHoldHive = "hold:hive" ) const ( decisionWhyHeld = "On hold — release the hold first" decisionWhyNoPermission = "Only a person with the permission can do this" decisionWhyApproveNoGrant = "Approving does not grant the missing permission" - decisionHeldBlocker = "On hold — the hive does nothing until the hold is released." + decisionHeldBlockerPlain = "On hold — the hive does nothing until the hold is released." ) // stageTrackerVerdictLookup returns a lookup over review-verdicts.json for @@ -176,7 +177,7 @@ func decisionForAdoption(it StageTrackerItem, held bool, now time.Time) *StageTr d.Question = who + " maintains this repository and " + gone + "; adopt the PR? The hive would take it over as it does any contributor's (the author's commits and sign-off are kept)." d.Blocker = "maintainer_policy is ask: the hive never adopts a maintainer's PR on its own; a person decides." if held { - d.Blocker += " " + decisionHeldBlocker + d.Blocker += " " + decisionHeldBlocker(it.Hold) } d.Options = []StageTrackerDecisionOption{ decisionOption(decisionActionAdopt, "Adopt (hive takes over)", !held, "Release the hold first"), @@ -242,7 +243,7 @@ func decisionPlainReason(base string) string { case stageengineprstage.ContributorLaneReasonNoReviewer: return "no reviewer is configured for this repo" case stageengineprstage.ContributorLaneReasonReporterTrustHold: - return "the author's trust level is not yet known" + return "the hive held it for the trust level of the linked issue's reporter" case stageengineprstage.ContributorLaneReasonNoAppBotLogin, stageengineprstage.AutoMergeReasonNoAppBotLogin: return "the hive's GitHub App login is not known" case stageengineprstage.ContributorLaneReasonFilesEvidence: @@ -274,6 +275,10 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByLane, BlockerReason: base} approveOK, approveWhy := true, "" delegateOK, delegateWhy := !held, decisionWhyHeld + var selfHold *StageTrackerHold + if held && it.Hold != nil && strings.EqualFold(it.Hold.By, stagelabels.HoldByHive) && it.Hold.Source != "" && it.Hold.Source != stagelabels.HoldSourceLabel { + selfHold = it.Hold + } sentinel := it.SentinelAlert || lower == "sentinel" || lower == stageengineprstage.ContributorLaneReasonSentinelBlocked changes := decisionChangesRequested(base) @@ -300,6 +305,17 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel t := verdict.RecordedAt d.Since = &t } + case selfHold != nil: + // The hive held the PR itself (hivecommons/hive#15020): say so, + // name the gate and the issue, and offer release / keep. + d.AskedBy = decisionAskedByLane + d.Question = "The hive held this PR itself for " + decisionHoldReason(selfHold) + ". Release the hold (the lane then merges it on its next pass once the other gates are clear), or keep it?" + if selfHold.Since != nil { + t := *selfHold.Since + d.Since = &t + } + d.Blocker = "The hive set `hold` on its own: " + decisionHoldReason(selfHold) + ". It does nothing more until the hold is released." + d.BlockerReason = decisionBlockerHoldHive case verdict != nil && decisionFirstNonEmpty(verdict.HumanSummaries) != "": d.AskedBy = decisionAskedByReviewer d.Question = "A reviewer handed this to a person: " + decisionFirstNonEmpty(verdict.HumanSummaries) @@ -356,11 +372,11 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel case reviewerDeferred: d.Blocker = "The hive will not merge until a person decides." } - if held { + if held && selfHold == nil { if d.Blocker != "" { d.Blocker += " " } - d.Blocker += decisionHeldBlocker + d.Blocker += decisionHeldBlocker(it.Hold) if d.BlockerReason == "" { d.BlockerReason = decisionBlockerHold } @@ -374,15 +390,46 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel decisionOption(decisionActionCloseWontfix, "Close as won't fix", true, ""), decisionHoldOption(held), } + if selfHold != nil { + // Release leads: it is the one action that answers the question. + d.Options = append([]StageTrackerDecisionOption{decisionHoldOption(true)}, d.Options[:len(d.Options)-1]...) + } return d } +// decisionHoldReason is the hold's plain-words reason for the popover. +func decisionHoldReason(h *StageTrackerHold) string { + if h != nil { + if reason := strings.TrimSpace(h.Reason); reason != "" { + return reason + } + } + return "its own gate" +} + +// decisionHeldBlocker is the "On hold" blocker sentence, naming who set the +// hold when the row knows (hivecommons/hive#15020). +func decisionHeldBlocker(h *StageTrackerHold) string { + if h == nil || strings.TrimSpace(h.By) == "" { + return decisionHeldBlockerPlain + } + who := "@" + strings.TrimSpace(h.By) + if strings.EqualFold(h.By, stagelabels.HoldByHive) { + who = "the hive" + } + s := "On hold (set by " + who + if reason := strings.TrimSpace(h.Reason); reason != "" { + s += ": " + reason + } + return s + ") — the hive does nothing until the hold is released." +} + func decisionForIssue(it StageTrackerItem, held bool) *StageTrackerDecision { d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByHiveAgent, BlockerReason: strings.TrimSpace(it.Reason)} d.Question = "The hive parked this issue for a person. Approve the direction, send it back with direction, or close it?" d.Blocker = "No agent picks this up until a person answers. The hive's question is in its latest comment on the issue." if held { - d.Blocker += " " + decisionHeldBlocker + d.Blocker += " " + decisionHeldBlocker(it.Hold) if d.BlockerReason == "" { d.BlockerReason = decisionBlockerHold } @@ -403,7 +450,7 @@ func decisionForTriage(it StageTrackerItem, held bool) *StageTrackerDecision { d.Question = "Should the hive work on this issue? Accept triage so an agent can take it, hold it, or mark it needs-human." d.Blocker = "No agent picks up an issue until a maintainer accepts triage." if held { - d.Blocker += " " + decisionHeldBlocker + d.Blocker += " " + decisionHeldBlocker(it.Hold) } d.Options = []StageTrackerDecisionOption{ decisionOption(decisionActionAcceptTriage, "Accept triage", true, ""), @@ -424,7 +471,7 @@ func decisionForNeedsHuman(it StageTrackerItem, held bool) *StageTrackerDecision d.Question = "This " + what + " is marked needs-human: automated fixes ran out, or a person flagged it. Review it on GitHub and remove the label when the hive may continue." d.Blocker = "The hive does nothing with a needs-human item until a person removes the label." if held { - d.Blocker += " " + decisionHeldBlocker + d.Blocker += " " + decisionHeldBlocker(it.Hold) } d.Options = []StageTrackerDecisionOption{decisionHoldOption(held)} return d diff --git a/src/pkg/dashboard/stage_tracker_hold_provenance_test.go b/src/pkg/dashboard/stage_tracker_hold_provenance_test.go new file mode 100644 index 0000000000..29b326842b --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_hold_provenance_test.go @@ -0,0 +1,186 @@ +package dashboard + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#15020: the hive held its own approved PR for the trust of +// an issue reporter and the row read "hold +1 · Needs human decision" with +// nothing saying who held it or why. The tracker now carries the hold's +// provenance from the stage store: the pill reads "Held by hive · reporter +// trust (issue #N by @X, contributor)" and the decision popover asks +// release / keep. + +func reporterTrustHold15020(since time.Time) *stagelabels.HoldProvenance { + return &stagelabels.HoldProvenance{By: stagelabels.HoldByHive, Source: stagelabels.HoldSourceReporterTrust, + Reason: stagelabels.ReporterTrustReason(15017, "Karibhou", "CONTRIBUTOR"), Since: since, Issue: 15017, Reporter: "Karibhou", Association: "CONTRIBUTOR"} +} + +func TestStageTrackerHoldProvenancePayload(t *testing.T) { + now := time.Date(2026, 10, 20, 18, 0, 0, 0, time.UTC) + heldAt := time.Date(2026, 10, 20, 17, 14, 14, 0, time.UTC) + s, store := stageTrackerFixture(t, now) + key := stagelabels.Key("acme/console", 15020) + store.Observe(key, stagelabels.NeedsDecision, "label:hold") + store.NoteHold(key, reporterTrustHold15020(heldAt)) + keyPerson := stagelabels.Key("acme/console", 15021) + store.Observe(keyPerson, stagelabels.Reviewed, "required-check-pending:build") + store.NoteHold(keyPerson, &stagelabels.HoldProvenance{By: "clubanderson", Source: stagelabels.HoldSourceLabel, Since: heldAt}) + keyStale := stagelabels.Key("acme/console", 15022) + store.Observe(keyStale, stagelabels.Reviewed, "queued") + store.NoteHold(keyStale, reporterTrustHold15020(heldAt)) + s.statusMu.Lock() + s.status.Repos[0].OpenPrs = append(s.status.Repos[0].OpenPrs, + FrontendPR{PullRequest: github.PullRequest{Number: 15020, Title: "fix(stage): hold provenance", Author: "hive-app[bot]", AppAuthored: true, Labels: []string{"stage/085-needs-decision", "hold", "needs-human", "author/hive", "role/trusted"}}}, + FrontendPR{PullRequest: github.PullRequest{Number: 15021, Title: "Parked by pat", Author: "hive-app[bot]", AppAuthored: true, Labels: []string{"stage/060-reviewed", "hold", "author/hive"}}}, + // The label is gone but the store still says held: no provenance rides a row without the label. + FrontendPR{PullRequest: github.PullRequest{Number: 15022, Title: "Released", Author: "hive-app[bot]", AppAuthored: true, Labels: []string{"stage/060-reviewed", "author/hive"}}}, + ) + s.statusMu.Unlock() + resp := s.buildStageTracker(s.status, store, now) + + it := trackerItem(t, resp, "pr", 15020) + if it.Hold == nil || it.Hold.By != "hive" || it.Hold.Source != "reporter-trust" || it.Hold.Issue != 15017 || it.Hold.Reporter != "Karibhou" || it.Hold.Association != "contributor" { + t.Fatalf("hold = %+v", it.Hold) + } + if it.Hold.Pill != "Held by hive · reporter trust (issue #15017 by @Karibhou, contributor)" || it.Hold.Since == nil || !it.Hold.Since.Equal(heldAt) { + t.Fatalf("pill/since = %q %v", it.Hold.Pill, it.Hold.Since) + } + if !it.OnHold || !hasMod(it, modHold) { + t.Fatalf("row must still wear the hold pill: on_hold=%v mods=%v", it.OnHold, it.Modifiers) + } + d := it.DecisionNeeded + if d == nil { + t.Fatal("a hive-held 085 row must carry a decision") + } + if !strings.Contains(d.Question, "The hive held this PR itself for reporter trust (issue #15017 by @Karibhou, contributor). Release the hold") || !strings.Contains(d.Question, "or keep it?") { + t.Fatalf("question = %q", d.Question) + } + if d.AskedBy != decisionAskedByLane || d.BlockerReason != decisionBlockerHoldHive || !strings.Contains(d.Blocker, "The hive set `hold` on its own") || d.Since == nil || !d.Since.Equal(heldAt) { + t.Fatalf("decision = %+v", d) + } + if len(d.Options) == 0 || d.Options[0].Action != decisionActionRelease || !d.Options[0].Enabled || d.Options[0].Label != "Release hold" { + t.Fatalf("release must lead the options: %+v", d.Options) + } + if opt := decisionOptionByAction(t, d, decisionActionDelegate); opt.Enabled { + t.Fatalf("Let hive decide must wait for the release: %+v", opt) + } + raw, err := json.Marshal(it) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"hold":{"by":"hive","source":"reporter-trust","reason":"reporter trust (issue #15017 by @Karibhou, contributor)","since":"2026-10-20T17:14:14Z","issue":15017,"reporter":"Karibhou","association":"contributor","pill":"Held by hive · reporter trust (issue #15017 by @Karibhou, contributor)"}`) { + t.Fatalf("payload hold = %s", raw) + } + + person := trackerItem(t, resp, "pr", 15021) + if person.Hold == nil || person.Hold.By != "clubanderson" || person.Hold.Pill != "Held by @clubanderson" || person.Hold.Source != "label" { + t.Fatalf("person hold = %+v", person.Hold) + } + if person.DecisionNeeded != nil && strings.Contains(person.DecisionNeeded.Question, "held this PR itself") { + t.Fatalf("a person's hold must not read as the hive's: %+v", person.DecisionNeeded) + } + if stale := trackerItem(t, resp, "pr", 15022); stale.Hold != nil { + t.Fatalf("no hold label, no provenance: %+v", stale.Hold) + } + if clean := trackerItem(t, resp, "pr", 102); clean.Hold != nil { + t.Fatalf("PR 102 must carry no hold: %+v", clean.Hold) + } +} + +// A person's hold on a 085 row names them in the blocker; an unattributed +// hold keeps the plain sentence. +func TestStageTrackerDecisionHeldBlockerNamesWhoHeld(t *testing.T) { + since := time.Date(2026, 10, 27, 9, 0, 0, 0, time.UTC) + it := StageTrackerItem{Repo: "acme/console", Number: 9, Kind: "pr", Stage: stagelabels.NeedsDecision.Number(), StageSince: &since, Reason: "label:hold", Modifiers: []string{modHold}} + d := stageTrackerDecisionNeeded(it, nil, "") + if d == nil || !strings.Contains(d.Blocker, decisionHeldBlockerPlain) || d.BlockerReason != "label:hold" { + t.Fatalf("plain held decision = %+v", d) + } + it.Hold = &StageTrackerHold{By: "clubanderson", Source: "label", Pill: "Held by @clubanderson"} + d = stageTrackerDecisionNeeded(it, nil, "") + if d == nil || !strings.Contains(d.Blocker, "On hold (set by @clubanderson)") || strings.Contains(d.Question, "held this PR itself") { + t.Fatalf("person-held decision = %+v", d) + } + // A hive hold the pass could only attribute to the label (no gate on + // record) is named but asks no release/keep question of its own. + it.Hold = &StageTrackerHold{By: "hive", Source: "label", Pill: "Held by hive"} + d = stageTrackerDecisionNeeded(it, nil, "") + if d == nil || !strings.Contains(d.Blocker, "On hold (set by the hive)") || strings.Contains(d.Question, "held this PR itself") { + t.Fatalf("hive label-only decision = %+v", d) + } + if got := decisionPlainReason("contributor-lane:reporter-trust-hold"); !strings.Contains(got, "linked issue's reporter") { + t.Fatalf("decisionPlainReason = %q", got) + } +} + +// The frontend: the hold pill names who held it and why, its hover text +// says since when, the nested PR mirror carries `hold`, and a hive-set hold +// pill opens the decision popover. +func TestStageTrackerHoldProvenanceJS(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + "hold: lp.hold || null", + "function stageTrackerHoldPill(item)", + "function stageTrackerHoldTip(item, nowMs)", + } { + if !strings.Contains(html, want) { + t.Fatalf("index.html lacks %q", want) + } + } + if strings.Count(html, "hold: lp.hold || null") < 2 { + t.Fatal("every nested-PR mirror must carry hold") + } + runStageTrackerRowActionsScript(t, strings.Join([]string{ + "const assert = require('assert');", + "var _stageTracker = { stages: [{ number: 85, short: 'Needs decision' }] };", + "function agentNowClockTime(ms, nowMs) { return 'T' + ms; }", + "function agentNowAgo(ms) { return Math.round(ms / 60000) + 'm'; }", + "function esc(s) { return String(s).replace(/&/g, '&').replace(/' + inner + ''; }", + jsConstLine(t, html, "STAGE_TRACKER_MOD_PRIORITY"), + jsConstLine(t, html, "STAGE_TRACKER_MOD_TEXT"), + jsConstLine(t, html, "STAGE_TRACKER_HANDLED_TEXT"), + jsConstLine(t, html, "STAGE_TRACKER_DRAFT_TIP"), + stageTrackerSentinelJS(t, html), + jsFunc(t, html, "stageTrackerRegressionHandled"), + jsFunc(t, html, "stageTrackerRegressionText"), + jsFunc(t, html, "stageTrackerDecisionOf"), + jsFunc(t, html, "stageTrackerHoldPill"), + jsFunc(t, html, "stageTrackerHoldTip"), + jsFunc(t, html, "stageTrackerChipsHtml"), + }, "\n")+` +const hold = { by: 'hive', source: 'reporter-trust', reason: 'reporter trust (issue #15017 by @Karibhou, contributor)', since: '2026-10-20T17:14:14Z', issue: 15017, reporter: 'Karibhou', association: 'contributor', pill: 'Held by hive · reporter trust (issue #15017 by @Karibhou, contributor)' }; +const decision = { question: 'The hive held this PR itself for reporter trust (issue #15017 by @Karibhou, contributor). Release the hold, or keep it?', asked_by: 'the hive', options: [ { action: 'release', label: 'Release hold', enabled: true } ] }; +const item = { repo: 'hivecommons/hive', kind: 'pr', number: 15020, stage: 85, modifiers: ['hold', 'needs-human'], hold, decision_needed: decision }; +assert.strictEqual(stageTrackerHoldPill(item), hold.pill); +const pill = stageTrackerChipsHtml(item); +assert.ok(pill.includes('ham-mod-hold'), pill); +assert.ok(pill.includes('>Held by hive · reporter trust (issue #15017 by @Karibhou, contributor) +1<'), pill); +assert.ok(pill.includes('ham-decision-trigger') && pill.includes('data-ham-decision="hivecommons/hive/pr#15020"'), pill); +const tip = stageTrackerHoldTip(item, Date.parse('2026-10-20T18:04:14Z')); +assert.ok(tip.startsWith(hold.pill), tip); +assert.ok(tip.includes('The hive set this hold itself') && tip.includes('Release it'), tip); +assert.ok(tip.includes('Since T' + Date.parse(hold.since) + ' · 50m'), tip); +// A person's hold: named, plain tooltip, no popover trigger. +const person = { repo: 'o/r', kind: 'pr', number: 2, stage: 60, modifiers: ['hold'], hold: { by: 'clubanderson', source: 'label' } }; +assert.strictEqual(stageTrackerHoldPill(person), 'Held by @clubanderson'); +const ppill = stageTrackerChipsHtml(person); +assert.ok(ppill.includes('>Held by @clubanderson<') && !ppill.includes('ham-decision-trigger'), ppill); +assert.ok(ppill.includes('title="Held by @clubanderson"'), ppill); +// No provenance: the plain word stays, no tooltip is invented. +const plain = stageTrackerChipsHtml({ repo: 'o/r', kind: 'pr', number: 3, stage: 60, modifiers: ['hold', 'draft'] }); +assert.ok(plain.includes('>hold +1<'), plain); +assert.strictEqual(stageTrackerHoldPill({ hold: null }), ''); +assert.strictEqual(stageTrackerHoldTip({ hold: {} }, 0), ''); +// Without the pill field the text is built from the parts. +assert.strictEqual(stageTrackerHoldPill({ hold: { by: 'hive', reason: 'r' } }), 'Held by hive · r'); +`) +} diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 483ad40908..cbca72ba5b 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14563,6 +14563,7 @@

Where to get help

const regressed = stageTrackerRegressionText(item, nowMs); if (regressed) lines.push(regressed.charAt(0).toUpperCase() + regressed.slice(1)); if (mods.indexOf('unauthorized') >= 0 && item.unauthorized) lines.push('Unauthorized: ' + item.unauthorized); + if (mods.indexOf('hold') >= 0 && typeof stageTrackerHoldPill === 'function' && stageTrackerHoldPill(item)) lines.push(stageTrackerHoldPill(item)); if (sinceMs) lines.push('Since ' + agentNowClockTime(sinceMs, nowMs) + ' · ' + agentNowAgo(nowMs - sinceMs)); if (trail) lines.push('Trail: ' + trail); return lines.filter(Boolean).join('\n'); @@ -14575,6 +14576,26 @@

Where to get help

return `${esc(STAGE_TRACKER_SENTINEL_CHIP)}`; } + // Pure: the hold pill text from the row's `hold` provenance ('' when the + // pass could not attribute the hold, so the plain "hold" word stays). + function stageTrackerHoldPill(item) { + const h = item && item.hold; + if (!h || !h.by) return ''; + if (h.pill) return h.pill; + const who = h.by === 'hive' ? 'hive' : '@' + h.by; + return 'Held by ' + who + (h.reason ? ' · ' + h.reason : ''); + } + // Pure: the hold pill's hover text — who, why, since when. + function stageTrackerHoldTip(item, nowMs) { + const h = item && item.hold; + if (!h || !h.by) return ''; + const sinceMs = Date.parse(h.since || ''); + const lines = [stageTrackerHoldPill(item)]; + if (h.by === 'hive') lines.push(h.source === 'reporter-trust' ? 'The hive set this hold itself: the linked issue\'s reporter is below the trust the gate requires. Release it to let the lane merge, or keep it until a maintainer has reviewed the reporter.' : 'The hive set this hold itself.'); + if (sinceMs) lines.push('Since ' + agentNowClockTime(sinceMs, nowMs) + ' · ' + agentNowAgo(nowMs - sinceMs)); + return lines.join('\n'); + } + function stageTrackerChipsHtml(item) { const sentinel = stageTrackerSentinelChipHtml(item) + (typeof stageTrackerAdoptionChipHtml === 'function' ? stageTrackerAdoptionChipHtml(item) : ''); const mods = (Array.isArray(item.modifiers) ? item.modifiers.slice() : []) @@ -14585,6 +14606,12 @@

Where to get help

const handled = stageTrackerRegressionHandled(item); if (handled && mods.length > 1) mods.push(mods.shift()); let text = handled && mods[0] === 'regressed' ? STAGE_TRACKER_HANDLED_TEXT : (STAGE_TRACKER_MOD_TEXT[mods[0]] || mods[0].replace(/-/g, ' ')); + // A hold the stage-label pass could attribute names who set it and why + // ("Held by hive · reporter trust (issue #N by @X, contributor)"), so the + // operator is not left reading "hold +1" (hivecommons/hive#15020). + // Guarded: the test harnesses load helpers by name, and this one is additive. + const holdPill = mods[0] === 'hold' && typeof stageTrackerHoldPill === 'function' ? stageTrackerHoldPill(item) : ''; + if (holdPill) text = holdPill; // A row the scheduler withholds for open GitHub "blocked by" dependencies names them (hivecommons/hive#14765); // one blocked on a PR (hive:blocked-on marker) names it and links to it (hivecommons/hive#14952). const blockedPR = mods[0] === 'blocked' ? stageTrackerBlockedOnPR(item) : null; @@ -14602,6 +14629,7 @@

Where to get help

// failing all three, a draft pill does. const anyBlockedPR = mods.indexOf('blocked') >= 0 ? stageTrackerBlockedOnPR(item) : null; const tip = (mods.indexOf('unauthorized') >= 0 && String(item.unauthorized || '').trim()) || regressed + || (holdPill && typeof stageTrackerHoldTip === 'function' ? stageTrackerHoldTip(item, Date.now()) : '') || (mods.indexOf('blocked') >= 0 && Array.isArray(item.blocked_on) && item.blocked_on.length ? 'Withheld from the scanner until ' + item.blocked_on.join(', ') + (item.blocked_on.length > 1 ? ' close' : ' closes') : '') || (anyBlockedPR ? anyBlockedPR.tip : '') || (mods.indexOf('draft') >= 0 ? STAGE_TRACKER_DRAFT_TIP : ''); @@ -14612,7 +14640,8 @@

Where to get help

// A lead needs-human / needs human decision pill opens the decision // popover (what to decide, who asked, the applicable actions) instead // of a native tooltip. - const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision') && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + // A hive-set hold is a decision too (release or keep): its pill opens the same popover. + const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; if (decision) return sentinel + stageTrackerDecisionTriggerHtml(decision, inner, tip, 'ham-badge ham-badge-mod ' + cls); return sentinel + `${inner}`; } @@ -14855,7 +14884,7 @@

Where to get help

stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', decision_needed: lp.decision_needed || null, adoption: lp.adoption || null, superseded: !!lp.superseded, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), - last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0 }; + last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null }; } // Pure: whether a linked PR is still open (not merged / closed / superseded). function stageTrackerLinkedPROpen(lp) { @@ -15048,7 +15077,7 @@

Where to get help

const who = (lp.author_kind || 'hive') + (lp.author ? ' · @' + lp.author : ''); prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)) + (lp.base_ref ? ` ${esc(lp.base_ref)}` : '')]; shown = Object.assign({}, item, { via_pr: true, stage: lp.stage || 40, stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', decision_needed: lp.decision_needed || null, adoption: lp.adoption || null }); + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', decision_needed: lp.decision_needed || null, hold: lp.hold || null, adoption: lp.adoption || null }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed // and nothing lit; one sub-row per PR carries the live chevron. diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index b77070bddf..0ad09c201f 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -92,6 +92,7 @@ func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key s Verdict: humanVerdict(contributorVerdict), Conflict: humanConflictReasons[obs.Reason] || hasLabelFold(obs.Labels, "needs-rebase"), Holds: stagelabels.Holds(obs.Labels), + Hold: obs.Hold, Cause: cause, CauseReason: decisionCauseFor(obs.Reason, workflowManual), DecisionQuestion: strings.TrimSpace(contributorVerdict.DecisionQuestion), @@ -222,6 +223,16 @@ func decisionActions(obs stageObservation, e stagelabels.Evidence) ([]string, bo actions = append(actions, "Resolve the sentinel alert and have a maintainer clear its label.") } for _, label := range e.Holds { + if label == "hold" && e.Hold.SelfImposed() { + // The hive's own hold: name the gate and the two choices, so + // the operator is not left reading "hold +1" (hivecommons/hive#15020). + reason := strings.TrimSpace(e.Hold.Reason) + if reason == "" { + reason = "its own gate" + } + actions = append(actions, "The hive set `hold` itself for "+reason+". **Release** it (dashboard row menu → Release hold, or remove the `hold` label) and the lane merges on its next pass once the other gates are clear, or **keep** it until a maintainer has reviewed the issue's reporter; `/hive approve` does not remove it.") + continue + } actions = append(actions, "Resolve the reason for `"+label+"`, then have a maintainer remove that label; `/hive approve` does not remove it.") } if obs.Reason == "label:needs-human" || hasLabelFold(obs.Labels, "needs-human") { diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index c2dd02b8b6..b0b66b899b 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -851,6 +851,32 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) verdict = replacement obs.Reason = replacement.Reason } + if hasLabelFold(obs.Labels, "hold") && !verdict.Terminal { + // Who held it and why rides the row (hivecommons/hive#15020); + // a reporter-trust hold the hive put on its own PR is lifted + // here — the hive is the author, the reporter's trust is moot. + prov, notice, err := c.holdProvenance(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil { + c.debug("stage labels: hold provenance unreadable", "repo", obs.Display, "pr", obs.Number, "error", err) + } + hiveAuthored := pass.AuthorIsApp || obs.AuthorKind == authorkind.Hive + if hiveAuthored && prov.SelfImposed() && prov.ReporterTrust() { + released, err := c.releaseSelfImposedReporterTrustHold(ctx, obs, prov, notice) + if err != nil { + c.warn("stage labels: could not release self-imposed reporter-trust hold", "repo", obs.Display, "pr", obs.Number, "error", err) + if firstErr == nil { + firstErr = err + } + } + if released { + result.Comments++ + result.Skipped++ + store.ClearHold(key) + continue + } + } + obs.Hold = prov + } var route stagelabels.Route if verdict.Human && !verdict.Terminal && verdict.Reason != prstage.ReasonSupersessionPending { var evidence stagelabels.Evidence @@ -988,6 +1014,7 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) // hivecommons/hive#12502: remember the author so the dashboard can // list "PRs returned to this contributor" from the store alone. store.NoteAuthor(key, obs.Author) + store.NoteHold(key, obs.Hold) if dcoRead { store.NoteDCO(key, obs.HeadSHA, obs.Detail.DCOTotal, obs.Detail.DCOUnsigned, obs.Detail.DCOUnsignedHive, obs.Detail.DCOSquashUnsafeHive) } diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index 6875829d7f..44761dca7d 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -45,6 +45,11 @@ type stageAPI struct { // extra handles routes beyond labels/comments (returns true when it // served the request); the adoption tests use it for refs and pulls. extra func(w http.ResponseWriter, r *http.Request) bool + // issueComments / issueEvents are what GET /issues/N/comments and + // /issues/N/events answer: the hold-provenance read a held PR takes + // (hivecommons/hive#15020). Unlisted PRs answer empty lists. + issueComments map[int][]map[string]any + issueEvents map[int][]map[string]any } type stageCommitFixture struct { @@ -103,6 +108,20 @@ func newStageAPI(t *testing.T, api *stageAPI) *httptest.Server { } stagePRTruthMu.Unlock() _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "labels": labels}) + case r.Method == http.MethodGet && strings.HasPrefix(path, "/repos/acme/widget/issues/") && strings.HasSuffix(path, "/comments"): + n, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(path, "/repos/acme/widget/issues/"), "/comments")) + out := api.issueComments[n] + if out == nil { + out = []map[string]any{} + } + _ = json.NewEncoder(w).Encode(out) + case r.Method == http.MethodGet && strings.HasPrefix(path, "/repos/acme/widget/issues/") && strings.HasSuffix(path, "/events"): + n, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(path, "/repos/acme/widget/issues/"), "/events")) + out := api.issueEvents[n] + if out == nil { + out = []map[string]any{} + } + _ = json.NewEncoder(w).Encode(out) case r.Method == http.MethodGet && strings.HasPrefix(path, "/repos/acme/widget/pulls/") && strings.HasSuffix(path, "/commits"): n, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(path, "/repos/acme/widget/pulls/"), "/commits")) api.commitReads++ diff --git a/src/pkg/github/automerge/reporter_trust_release.go b/src/pkg/github/automerge/reporter_trust_release.go new file mode 100644 index 0000000000..189a3e85ae --- /dev/null +++ b/src/pkg/github/automerge/reporter_trust_release.go @@ -0,0 +1,157 @@ +package automerge + +import ( + "context" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// reporterTrustReleaseMarker opens the comment the stage-label pass leaves +// when it lifts a reporter-trust hold the hive had put on its own PR +// (hivecommons/hive#15020). +const reporterTrustReleaseMarker = "" + +// holdProvenance reads who set the `hold` label a PR wears and why: the +// newest `hold` label event names the actor and the time; a hive-set hold +// is attributed to the reporter-trust gate when the gate's notice comment +// (hivecommons/hive#9665) is on the thread and no later unlabel event has +// cleared it. The second result is the gate's notice when one was read. +// nil, nil when nothing about the hold could be read. +func (c *Engine) holdProvenance(ctx context.Context, owner, repo string, number int) (*stagelabels.HoldProvenance, *hgithub.ReporterTrustHoldNotice, error) { + if c == nil || c.gh == nil || c.transport == nil { + return nil, nil, nil + } + appBot := strings.TrimSpace(c.transport.AppBotLogin()) + comments, err := c.listAllIssueComments(ctx, owner, repo, number) + if err != nil { + return nil, nil, err + } + var notice *hgithub.ReporterTrustHoldNotice + if n, ok := hgithub.ReporterTrustNoticeFromComments(comments, appBot); ok { + notice = &n + } + latest, err := c.latestHoldLabelEvent(ctx, owner, repo, number) + if err != nil { + return nil, notice, err + } + if latest != nil && latest.GetEvent() == "unlabeled" { + // The current label, if any, postdates what the events show; say + // nothing rather than attribute it to a stale actor. + return nil, notice, nil + } + if latest == nil { + if notice == nil { + return nil, nil, nil + } + prov := notice.Finding.HoldProvenance(notice.PostedAt) + return prov, notice, nil + } + actor := strings.ToLower(strings.TrimSpace(hgithub.SafeGetLogin(latest.GetActor()))) + since := latest.GetCreatedAt().Time + if actor == "" || !strings.EqualFold(actor, appBot) { + return &stagelabels.HoldProvenance{By: actor, Source: stagelabels.HoldSourceLabel, Since: since}, notice, nil + } + // The hive set it. The reporter-trust notice explains it when it is the + // hive's reason on record (posted around the label, never before an + // intervening unlabel — latestHoldLabelEvent already ruled that out). + if notice != nil && !notice.PostedAt.Before(since.Add(-reporterTrustNoticeSlack)) { + return notice.Finding.HoldProvenance(since), notice, nil + } + return &stagelabels.HoldProvenance{By: stagelabels.HoldByHive, Source: stagelabels.HoldSourceLabel, Since: since}, notice, nil +} + +// reporterTrustNoticeSlack is how far before the `hold` label event the +// gate's notice may have been posted and still explain it: the watcher +// labels first and comments seconds later, but a stale notice from an +// earlier, released hold must not explain a fresh one. +const reporterTrustNoticeSlack = 2 * time.Minute + +func (c *Engine) listAllIssueComments(ctx context.Context, owner, repo string, number int) ([]*gh.IssueComment, error) { + var all []*gh.IssueComment + opts := &gh.IssueListCommentsOptions{ListOptions: gh.ListOptions{PerPage: 100}} + for { + comments, resp, err := c.gh.Issues.ListComments(ctx, owner, repo, number, opts) + if err != nil { + return nil, fmt.Errorf("listing comments: %w", err) + } + all = append(all, comments...) + if resp == nil || resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return all, nil +} + +// latestHoldLabelEvent returns the newest labeled / unlabeled event for the +// literal `hold` label, nil when there is none. +func (c *Engine) latestHoldLabelEvent(ctx context.Context, owner, repo string, number int) (*gh.IssueEvent, error) { + var latest *gh.IssueEvent + opts := &gh.ListOptions{PerPage: 100} + for { + events, resp, err := c.gh.Issues.ListIssueEvents(ctx, owner, repo, number, opts) + if err != nil { + return nil, fmt.Errorf("listing issue events: %w", err) + } + for _, event := range events { + if event == nil || !strings.EqualFold(event.GetLabel().GetName(), "hold") { + continue + } + if event.GetEvent() != "labeled" && event.GetEvent() != "unlabeled" { + continue + } + if latest == nil || event.GetCreatedAt().Time.After(latest.GetCreatedAt().Time) { + latest = event + } + } + if resp == nil || resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return latest, nil +} + +// releaseSelfImposedReporterTrustHold lifts a reporter-trust hold the hive +// put on a PR it authored itself (hivecommons/hive#15020): the hive is the +// author, so the issue reporter's trust is not what decides whether its own +// fix merges. prov must be a hive-set reporter-trust hold (the caller checked +// SelfImposed && ReporterTrust) and the PR hive-authored. Removes `hold`, and +// `needs-human` when the gate's notice says it added it, and leaves a short +// comment. Holds a person set are never touched: the caller only reaches +// this with prov.By == "hive". +func (c *Engine) releaseSelfImposedReporterTrustHold(ctx context.Context, obs stageObservation, prov *stagelabels.HoldProvenance, notice *hgithub.ReporterTrustHoldNotice) (bool, error) { + if c == nil || c.gh == nil || prov == nil || !prov.SelfImposed() || !prov.ReporterTrust() { + return false, nil + } + remove := []string{"hold"} + if notice != nil && notice.Finding.OwnsNeedsHuman && hasLabelFold(obs.Labels, "needs-human") { + remove = append(remove, "needs-human") + } + for _, label := range remove { + if _, err := c.gh.Issues.RemoveLabelForIssue(ctx, obs.Owner, obs.Repo, obs.Number, url.PathEscape(label)); err != nil && !isGitHubStatus(err, http.StatusNotFound) { + return false, fmt.Errorf("removing %s label: %w", label, err) + } + } + body := reporterTrustReleaseMarker + "\nHold released: the hive had held its own PR for " + strings.TrimSpace(prov.Reason) + + ". The hive is this PR's author, so the issue reporter's trust does not gate its merge; the automerge lane re-evaluates it on its next pass. A hold a person sets is never released this way." + if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + return false, fmt.Errorf("posting release comment: %w", err) + } + c.noteOwnStageComment(obs.Owner, obs.Repo, obs.Number) + c.info("stage labels: releasing self-imposed reporter-trust hold", "repo", obs.Display, "pr", obs.Number, "reason", prov.Reason, "issue", prov.Issue, "reporter", prov.Reporter, "removed", strings.Join(remove, ",")) + return true, nil +} + +// IsReporterTrustReleaseComment reports whether body is the comment +// releaseSelfImposedReporterTrustHold leaves. +func IsReporterTrustReleaseComment(body string) bool { + return strings.HasPrefix(strings.TrimSpace(body), reporterTrustReleaseMarker) +} diff --git a/src/pkg/github/automerge/reporter_trust_release_test.go b/src/pkg/github/automerge/reporter_trust_release_test.go new file mode 100644 index 0000000000..ac740ffcc6 --- /dev/null +++ b/src/pkg/github/automerge/reporter_trust_release_test.go @@ -0,0 +1,335 @@ +package automerge + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#15020: the hive held its own approved PR for the trust of +// an issue reporter, and the operator could not tell who held it or why. +// The stage-label pass now reads the hold's provenance (label event actor + +// the gate's notice), records it on the row, and lifts a reporter-trust hold +// the hive put on a PR it authored itself. Holds a person set stay. + +func reporterTrustFinding15020() hgithub.ReporterTrust { + return hgithub.ReporterTrust{OwnsNeedsHuman: true, Held: true, Issue: 15017, Repo: "acme/widget", Reporter: "Karibhou", Association: "CONTRIBUTOR", Reason: "issue acme/widget#15017 reporter @Karibhou (CONTRIBUTOR) is not trusted"} +} + +func reporterTrustNoticeComment(at string) map[string]any { + return map[string]any{ + "body": hgithub.ReporterTrustNoticeBody(reporterTrustFinding15020()), + "user": map[string]string{"login": testHiveAppBotLogin}, + "created_at": at, + } +} + +func holdEvent(event, actor, at string) map[string]any { + return map[string]any{ + "event": event, + "label": map[string]string{"name": "hold"}, + "actor": map[string]string{"login": actor}, + "created_at": at, + } +} + +func TestHoldProvenance(t *testing.T) { + const labelAt = "2026-10-20T17:14:14Z" + for _, tc := range []struct { + name string + comments []map[string]any + events []map[string]any + want *stagelabels.HoldProvenance + notice bool + }{ + { + name: "hive label plus notice is a reporter-trust hold", + comments: []map[string]any{reporterTrustNoticeComment("2026-10-20T17:14:18Z")}, + events: []map[string]any{holdEvent("labeled", testHiveAppBotLogin, labelAt)}, + want: &stagelabels.HoldProvenance{By: "hive", Source: "reporter-trust", Reason: "reporter trust (issue #15017 by @Karibhou, contributor)", Issue: 15017, Reporter: "Karibhou", Association: "CONTRIBUTOR", Since: time.Date(2026, 10, 20, 17, 14, 14, 0, time.UTC)}, + notice: true, + }, + { + name: "hive label without a notice is only attributed", + events: []map[string]any{holdEvent("labeled", testHiveAppBotLogin, labelAt)}, + want: &stagelabels.HoldProvenance{By: "hive", Source: "label", Since: time.Date(2026, 10, 20, 17, 14, 14, 0, time.UTC)}, + }, + { + name: "a stale notice from an earlier hold does not explain a fresh one", + comments: []map[string]any{reporterTrustNoticeComment("2026-10-19T09:00:00Z")}, + events: []map[string]any{holdEvent("labeled", testHiveAppBotLogin, "2026-10-19T08:59:58Z"), holdEvent("unlabeled", "clubanderson", "2026-10-19T10:00:00Z"), holdEvent("labeled", testHiveAppBotLogin, labelAt)}, + want: &stagelabels.HoldProvenance{By: "hive", Source: "label", Since: time.Date(2026, 10, 20, 17, 14, 14, 0, time.UTC)}, + notice: true, + }, + { + name: "a person's hold is theirs even with a hive notice on the thread", + comments: []map[string]any{reporterTrustNoticeComment("2026-10-20T17:14:18Z")}, + events: []map[string]any{holdEvent("labeled", testHiveAppBotLogin, labelAt), holdEvent("unlabeled", "clubanderson", "2026-10-20T18:00:00Z"), holdEvent("labeled", "ClubAnderson", "2026-10-20T18:00:05Z")}, + want: &stagelabels.HoldProvenance{By: "clubanderson", Source: "label", Since: time.Date(2026, 10, 20, 18, 0, 5, 0, time.UTC)}, + notice: true, + }, + { + name: "newest event is an unlabel: nothing to attribute", + comments: []map[string]any{reporterTrustNoticeComment("2026-10-20T17:14:18Z")}, + events: []map[string]any{holdEvent("labeled", testHiveAppBotLogin, labelAt), holdEvent("unlabeled", "clubanderson", "2026-10-20T18:00:00Z")}, + notice: true, + }, + { + name: "no events readable: the notice alone attributes it", + comments: []map[string]any{reporterTrustNoticeComment("2026-10-20T17:14:18Z")}, + want: &stagelabels.HoldProvenance{By: "hive", Source: "reporter-trust", Reason: "reporter trust (issue #15017 by @Karibhou, contributor)", Issue: 15017, Reporter: "Karibhou", Association: "CONTRIBUTOR", Since: time.Date(2026, 10, 20, 17, 14, 18, 0, time.UTC)}, + notice: true, + }, + {name: "nothing at all"}, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := releaseEngine(t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/acme/widget/issues/15020/comments": + if tc.comments == nil { + tc.comments = []map[string]any{} + } + _ = json.NewEncoder(w).Encode(tc.comments) + case "/repos/acme/widget/issues/15020/events": + if tc.events == nil { + tc.events = []map[string]any{} + } + _ = json.NewEncoder(w).Encode(tc.events) + default: + http.NotFound(w, r) + } + }) + got, notice, err := c.holdProvenance(context.Background(), "acme", "widget", 15020) + if err != nil { + t.Fatal(err) + } + if (notice != nil) != tc.notice { + t.Fatalf("notice = %+v, want present=%v", notice, tc.notice) + } + if !got.Equal(tc.want) { + t.Fatalf("provenance = %+v, want %+v", got, tc.want) + } + }) + } +} + +func TestHoldProvenanceErrors(t *testing.T) { + var nilEngine *Engine + if prov, notice, err := nilEngine.holdProvenance(context.Background(), "acme", "widget", 1); prov != nil || notice != nil || err != nil { + t.Fatalf("nil engine = (%v, %v, %v), want no-op", prov, notice, err) + } + c, _ := releaseEngine(t, func(w http.ResponseWriter, r *http.Request) { http.Error(w, "boom", http.StatusInternalServerError) }) + if _, _, err := c.holdProvenance(context.Background(), "acme", "widget", 1); err == nil || !strings.Contains(err.Error(), "listing comments") { + t.Fatalf("err = %v, want listing-comments failure", err) + } + c, _ = releaseEngine(t, func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/comments") { + _ = json.NewEncoder(w).Encode([]map[string]any{reporterTrustNoticeComment("2026-10-20T17:14:18Z")}) + return + } + http.Error(w, "boom", http.StatusInternalServerError) + }) + if _, notice, err := c.holdProvenance(context.Background(), "acme", "widget", 1); err == nil || !strings.Contains(err.Error(), "listing issue events") || notice == nil { + t.Fatalf("(%v, %v), want listing-issue-events failure with the notice still returned", notice, err) + } +} + +func TestReleaseSelfImposedReporterTrustHoldGuards(t *testing.T) { + obs := stageObservation{Owner: "acme", Repo: "widget", Number: 15020, Labels: []string{"hold", "needs-human"}} + c, _ := releaseEngine(t, func(w http.ResponseWriter, r *http.Request) { t.Errorf("unexpected %s %s", r.Method, r.URL.Path) }) + for name, prov := range map[string]*stagelabels.HoldProvenance{ + "nil": nil, + "operator hold": {By: "clubanderson", Source: "label"}, + "hive, no gate": {By: "hive", Source: "label"}, + "hive, other": {By: "hive", Source: "self-authorization"}, + "gate, operator": {By: "pat", Source: "reporter-trust"}, + } { + if released, err := c.releaseSelfImposedReporterTrustHold(context.Background(), obs, prov, nil); released || err != nil { + t.Fatalf("%s: (%v, %v), want untouched", name, released, err) + } + } +} + +func TestReleaseSelfImposedReporterTrustHoldErrors(t *testing.T) { + obs := stageObservation{Owner: "acme", Repo: "widget", Number: 15020, Labels: []string{"hold", "needs-human"}} + prov := &stagelabels.HoldProvenance{By: "hive", Source: "reporter-trust", Reason: "reporter trust (issue #15017 by @Karibhou, contributor)"} + c, _ := releaseEngine(t, func(w http.ResponseWriter, r *http.Request) { http.Error(w, "boom", http.StatusInternalServerError) }) + if released, err := c.releaseSelfImposedReporterTrustHold(context.Background(), obs, prov, nil); released || err == nil || !strings.Contains(err.Error(), "removing hold label") { + t.Fatalf("(%v, %v), want removing-hold-label failure", released, err) + } + c, _ = releaseEngine(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + http.Error(w, "gone", http.StatusNotFound) // already removed: tolerated + return + } + http.Error(w, "boom", http.StatusInternalServerError) + }) + if released, err := c.releaseSelfImposedReporterTrustHold(context.Background(), obs, prov, nil); released || err == nil || !strings.Contains(err.Error(), "posting release comment") { + t.Fatalf("(%v, %v), want posting-release-comment failure after tolerated 404", released, err) + } +} + +// The live case end to end through ApplyStageLabels: a hive-authored PR +// carrying the hive's own reporter-trust hold has `hold` and the gate's +// `needs-human` released on the pass, with a comment saying why; the row is +// skipped for this pass (re-staged next pass without the hold) and its +// stored provenance cleared. +func TestApplyStageLabels_ReleasesSelfImposedReporterTrustHold(t *testing.T) { + api := &stageAPI{labels: map[string]string{}} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + api.issueComments = map[int][]map[string]any{15020: {reporterTrustNoticeComment("2026-10-20T17:14:18Z")}} + api.issueEvents = map[int][]map[string]any{15020: {holdEvent("labeled", testHiveAppBotLogin, "2026-10-20T17:14:14Z")}} + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 17, 40, 0, 0, time.UTC)} + e, _, store := newStageEngine(t, srv.URL, clock) + ctx := context.Background() + + pr := stagePR(15020, "hold", "needs-human", "author/hive", "role/trusted", "stage/085-needs-decision") + pr.User = &gh.User{Login: gh.Ptr(testHiveAppBotLogin), Type: gh.Ptr("Bot")} + e.recordStage(stageLaneSelf, "acme/widget", "acme", "widget", pr, "label:hold", false, nil) + res, err := e.ApplyStageLabels(ctx) + if err != nil { + t.Fatal(err) + } + if res.Skipped != 1 || res.Comments != 1 { + t.Fatalf("result = %+v, want the row skipped after the release with one comment", res) + } + if strings.Join(api.removed, ",") != "hold,needs-human" || len(api.added) != 0 { + t.Fatalf("removed=%v added=%v, want hold and needs-human released and nothing staged yet", api.removed, api.added) + } + if len(api.comments) != 1 || !IsReporterTrustReleaseComment(api.comments[0]) || !strings.Contains(api.comments[0], "reporter trust (issue #15017 by @Karibhou, contributor)") || !strings.Contains(api.comments[0], "The hive is this PR's author") { + t.Fatalf("release comment = %q", api.comments) + } + if rec, ok := store.Get(stageKey("acme", "widget", 15020)); ok && rec.Hold != nil { + t.Fatalf("stored hold provenance survived the release: %+v", rec.Hold) + } + + // Next pass, the hold gone: the PR stages normally and nothing is + // released again (the events now end in the hive's own unlabel). + api.reset() + api.issueEvents[15020] = append(api.issueEvents[15020], holdEvent("unlabeled", testHiveAppBotLogin, "2026-10-20T17:40:01Z")) + pr = stagePR(15020, "author/hive", "role/trusted", "stage/085-needs-decision") + pr.User = &gh.User{Login: gh.Ptr(testHiveAppBotLogin), Type: gh.Ptr("Bot")} + e.recordStage(stageLaneSelf, "acme/widget", "acme", "widget", pr, "queued", false, nil) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + for _, body := range api.comments { + if IsReporterTrustReleaseComment(body) { + t.Fatalf("a second release comment was posted: %q", body) + } + } + for _, removed := range api.removed { + if removed == "hold" || removed == "needs-human" { + t.Fatalf("removed %q again on an unheld PR: %v", removed, api.removed) + } + } +} + +// A hold a person set on a hive-authored PR is theirs: the pass records who +// and leaves it, and the 085 comment names them. +func TestApplyStageLabels_OperatorHoldOnHivePRIsKept(t *testing.T) { + api := &stageAPI{labels: map[string]string{}} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + api.issueComments = map[int][]map[string]any{15020: {reporterTrustNoticeComment("2026-10-20T17:14:18Z")}} + api.issueEvents = map[int][]map[string]any{15020: { + holdEvent("labeled", testHiveAppBotLogin, "2026-10-20T17:14:14Z"), + holdEvent("unlabeled", "clubanderson", "2026-10-20T18:00:00Z"), + holdEvent("labeled", "clubanderson", "2026-10-20T18:00:05Z"), + }} + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 18, 30, 0, 0, time.UTC)} + e, _, store := newStageEngine(t, srv.URL, clock) + ctx := context.Background() + + pr := stagePR(15020, "hold", "author/hive", "role/trusted", "stage/060-reviewed") + pr.User = &gh.User{Login: gh.Ptr(testHiveAppBotLogin), Type: gh.Ptr("Bot")} + e.recordStage(stageLaneSelf, "acme/widget", "acme", "widget", pr, "label:hold", false, nil) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + for _, removed := range api.removed { + if removed == "hold" { + t.Fatalf("a person's hold was released: %v", api.removed) + } + } + rec, ok := store.Get(stageKey("acme", "widget", 15020)) + if !ok || rec.Hold == nil || rec.Hold.By != "clubanderson" || rec.Hold.Source != stagelabels.HoldSourceLabel { + t.Fatalf("record hold = %+v (ok=%v), want attributed to clubanderson", rec.Hold, ok) + } + var decision string + for _, body := range api.comments { + if strings.HasPrefix(body, stagelabels.DecisionCommentMarker) { + decision = body + } + } + if !strings.Contains(decision, "the `hold` label was set by @clubanderson") { + t.Fatalf("085 comment does not name who held it:\n%s", decision) + } +} + +// A contributor's PR the hive held for reporter trust keeps its hold (the +// gate still applies to PRs the hive did not author); the row carries the +// provenance and the 085 comment says the hive set it, why, and how to +// release or keep it. +func TestApplyStageLabels_ReporterTrustHoldOnContributorPRIsNamed(t *testing.T) { + api := &stageAPI{labels: map[string]string{}} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + api.issueComments = map[int][]map[string]any{21: {reporterTrustNoticeComment("2026-10-20T17:14:18Z")}} + api.issueEvents = map[int][]map[string]any{21: {holdEvent("labeled", testHiveAppBotLogin, "2026-10-20T17:14:14Z")}} + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 17, 40, 0, 0, time.UTC)} + e, _, store := newStageEngine(t, srv.URL, clock) + ctx := context.Background() + + pr := stagePR(21, "hold", "needs-human", "author/human", "role/contributor", "stage/050-review-pending") + pr.User = &gh.User{Login: gh.Ptr("shared-pat-account")} + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, "excluded-label:hold", false, nil) + e.noteStageRole("acme", "widget", 21, stagelabels.RoleContributor) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + for _, removed := range api.removed { + if removed == "hold" || removed == "needs-human" { + t.Fatalf("the gate's hold on a PR the hive did not author was released: %v", api.removed) + } + } + rec, ok := store.Get(stageKey("acme", "widget", 21)) + if !ok || !rec.Hold.SelfImposed() || !rec.Hold.ReporterTrust() || rec.Hold.Issue != 15017 || rec.Hold.Reporter != "Karibhou" { + t.Fatalf("record hold = %+v (ok=%v), want the hive's reporter-trust provenance", rec.Hold, ok) + } + var decision string + for _, body := range api.comments { + if strings.HasPrefix(body, stagelabels.DecisionCommentMarker) { + decision = body + } + } + for _, want := range []string{ + "the `hold` label was set by the hive itself: reporter trust (issue #15017 by @Karibhou, contributor)", + "The hive set `hold` itself for reporter trust (issue #15017 by @Karibhou, contributor). **Release** it", + "or **keep** it", + } { + if !strings.Contains(decision, want) { + t.Fatalf("085 comment lacks %q:\n%s", want, decision) + } + } + if strings.Contains(decision, "the `hold` label is set") { + t.Fatalf("085 comment still prints the bare hold line:\n%s", decision) + } +} diff --git a/src/pkg/github/pr_level_hold.go b/src/pkg/github/pr_level_hold.go index 3cb6fe7c09..78d77ec246 100644 --- a/src/pkg/github/pr_level_hold.go +++ b/src/pkg/github/pr_level_hold.go @@ -219,7 +219,7 @@ func (c *Client) levelHoldReleaseBlockedByOtherPolicy(ctx context.Context, owner return true, nil } if c.reporterTrustHoldActive(repoRef) { - reporter := c.EvaluateReporterTrust(ctx, repoRef, pr.GetTitle(), pr.GetBody(), nil) + reporter := c.EvaluateReporterTrust(ctx, repoRef, pr.GetTitle(), pr.GetBody(), nil, pr.GetUser().GetLogin()) if reporter.Held { if err := c.AddLabels(ctx, repoRef, number, []string{issueNeedsHumanLabel}); err != nil { return true, fmt.Errorf("applying needs-human for reporter-trust hold on %s#%d: %w", repoRef, number, err) diff --git a/src/pkg/github/pr_reporter_trust.go b/src/pkg/github/pr_reporter_trust.go index 43deeefe73..18edbb3d5a 100644 --- a/src/pkg/github/pr_reporter_trust.go +++ b/src/pkg/github/pr_reporter_trust.go @@ -7,8 +7,10 @@ import ( "regexp" "strconv" "strings" + "time" gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/stagelabels" ) // The reporter-trust hold (hivecommons/hive#9665) is the merge-side half of @@ -17,8 +19,17 @@ import ( // an unaccepted stranger's request never merges without a human, at any ACMM // level. A PR whose rationale traces to an unaccepted issue filed by a reporter // the operator does not trust receives literal `hold` plus `needs-human` and a -// notice, and only a person removes it — the App never auto-releases a reporter-trust hold. -// An issue's configured acceptance label already supplies that sign-off. +// notice, and only a person removes it — the App never auto-releases a +// reporter-trust hold it placed on somebody else's PR. An issue's configured +// acceptance label already supplies that sign-off. +// +// The gate judges the PR's linked issues only (closing keywords and the +// request's declared issues), never a pull request a number happens to +// resolve to, and never a PR the hive itself authored (hivecommons/hive#15020: +// the hive held its own approved fix because "closed by #15017" named a +// sibling PR and that PR's author was read as an untrusted reporter). A +// hive-set reporter-trust hold left on a hive-authored PR by an older build +// is released by the stage-label pass (automerge.releaseSelfImposedReporterTrustHold). // // It composes with, and never replaces, the #5117 self-authorization gate: // that one asks "did a person ask for this at all"; this one asks "was that @@ -99,8 +110,64 @@ func (c *Client) reporterIsTrusted(login, association string) bool { return fn(login, association) } -// EvaluateReporterTrust decides whether a PR request's rationale traces to an -// issue filed by a reporter the operator does not trust. +// hiveSelfReportMarkerPrefix opens the marker fleetreport writes into every +// issue a hive files about itself (fleetreport.SelfReportMarkerPrefix; not +// imported to keep this package free of that dependency). A self-report's +// reporter is the hive, whatever account posted it. +const hiveSelfReportMarkerPrefix = "\n\nA hive hit an unusual runtime error"}}, + body: "Fixes #15009", + wantHeld: false, }, { name: "a maintainer accepted a stranger's issue: no hold", issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE", Labels: []string{"triage/accepted"}}}, @@ -595,7 +619,7 @@ func TestEvaluateReporterTrust(t *testing.T) { 581: {Author: "stranger", Association: "NONE", Labels: []string{"triage/accepted"}}, 590: {Author: "another-stranger", Association: "NONE"}, }, - body: "Closes #581\nRefs #590", + body: "Closes #581\nCloses #590", wantHeld: true, }, { name: "a maintainer asked: no hold", @@ -623,7 +647,7 @@ func TestEvaluateReporterTrust(t *testing.T) { 581: {Author: "maintainer", Association: "OWNER"}, 590: {Author: "stranger", Association: "FIRST_TIME_CONTRIBUTOR"}, }, - body: "Closes #581\nRefs #590", + body: "Closes #581\nCloses #590", wantHeld: true, }, { name: "the request's declared issue list counts", @@ -646,7 +670,11 @@ func TestEvaluateReporterTrust(t *testing.T) { t.Run(tc.name, func(t *testing.T) { srv := &selfAuthServer{issues: tc.issues} c := reporterTrustTestClient(t, srv, true) - got := c.EvaluateReporterTrust(context.Background(), "o/r", "t", tc.body, tc.declared) + author := tc.author + if author == "" { + author = "contributor" + } + got := c.EvaluateReporterTrust(context.Background(), "o/r", "t", tc.body, tc.declared, author) if got.Held != tc.wantHeld { t.Fatalf("Held = %v, want %v (reason %q)", got.Held, tc.wantHeld, got.Reason) } @@ -675,8 +703,47 @@ func runReporterTrustWatcher(t *testing.T, c *Client) (reqPath string) { return reqPath } +// outsideAccountPR is the login the fake attributes a created PR to in the +// tests that exercise the hold itself: an account outside the hive identity +// (a shared PAT the hive does not list as project.ai_author). A PR GitHub +// attributes to the hive is never reporter-trust held (hivecommons/hive#15020), +// so those tests opt out of that skip explicitly. +const outsideAccountPR = "shared-pat-account" + +func TestPRRequestWatcher_HiveAuthoredPRNeverReporterTrustHeld(t *testing.T) { + // hivecommons/hive#15020: the hive held its own approved fix for the + // trust level of the issue reporter. The App-authored PR (the author the + // fake omits resolves to the App login; an explicit App login likewise) + // is never held by this gate, whatever the rationale's reporter. + for _, author := range []string{"", "kubestellar-hive[bot]"} { + t.Run("author="+author, func(t *testing.T) { + srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}, prAuthor: author} + c := reporterTrustTestClient(t, srv, true) + c.prHoldLabel = func(string, string) bool { return false } + reqPath := runReporterTrustWatcher(t, c) + if applied := srv.applied(); len(applied) != 0 { + t.Fatalf("labels applied = %v, want none on a hive-authored PR", applied) + } + if comments := srv.postedComments(); len(comments) != 0 { + t.Fatalf("posted %d comments, want none: %v", len(comments), comments) + } + raw, err := os.ReadFile(strings.TrimSuffix(reqPath, ".json") + ".result.json") + if err != nil { + t.Fatal(err) + } + var resp PRResponse + if err := json.Unmarshal(raw, &resp); err != nil { + t.Fatal(err) + } + if !resp.OK || resp.ReporterTrustHeld { + t.Fatalf("result = %+v, want OK and not reporter_trust_held", resp) + } + }) + } +} + func TestPRRequestWatcher_HoldsUntrustedReporterPRAtL6(t *testing.T) { - srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}} + srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}, prAuthor: outsideAccountPR} c := reporterTrustTestClient(t, srv, true) // L6: no level hold. The reporter gate is the only thing between a // stranger's request and an unattended merge. @@ -700,7 +767,7 @@ func TestPRRequestWatcher_HoldsUntrustedReporterPRAtL6(t *testing.T) { if len(comments) != 1 { t.Fatalf("posted %d comments, want 1 explaining the hold", len(comments)) } - for _, want := range []string{ReporterTrustNoticeMarker, "#581", "@stranger", "NONE", "9665", "issue reporter, not the PR author", "authored by the hive", "untrusted **reporter**", "`needs-human`", "reporter-trust hold — issue #581 filed by @stranger"} { + for _, want := range []string{ReporterTrustNoticeMarker, "#581", "@stranger", "NONE", "9665", "issue reporter, not the PR author", "not this PR's author", "untrusted **reporter**", "`needs-human`", "reporter-trust hold — issue #581 filed by @stranger"} { if !strings.Contains(comments[0], want) { t.Errorf("hold explanation does not mention %q:\n%s", want, comments[0]) } @@ -756,15 +823,15 @@ func TestPRRequestWatcher_UntrustedReporterAcceptance(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "CONTRIBUTOR", Labels: tc.labels}}} + srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "CONTRIBUTOR", Labels: tc.labels}}, prAuthor: outsideAccountPR} c := reporterTrustTestClient(t, srv, true) filter := enabledReporterTrust() filter.ReporterTrust.UntrustedRequireLabels = tc.required filter.ReporterTrust.Enabled = gh.Ptr(!tc.gateOff) c.SetIssueFilter(filter) c.prHoldLabel = func(string, string) bool { return false } - // The watcher creates an App-authored PR; only its rationale's - // reporter and acceptance labels should decide this hold. + // Only the rationale's reporter and acceptance labels decide + // this hold on a PR the hive identity does not cover. reqPath := runReporterTrustWatcher(t, c) labels := srv.applied() comments := srv.postedComments() @@ -792,7 +859,7 @@ func TestPRRequestWatcher_UntrustedReporterAcceptance(t *testing.T) { } func TestPRRequestWatcher_TrustedReporterPRNotHeld(t *testing.T) { - srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "maintainer", Association: "COLLABORATOR"}}} + srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "maintainer", Association: "COLLABORATOR"}}, prAuthor: outsideAccountPR} c := reporterTrustTestClient(t, srv, true) c.prHoldLabel = func(string, string) bool { return false } runReporterTrustWatcher(t, c) @@ -805,7 +872,7 @@ func TestPRRequestWatcher_TrustedReporterPRNotHeld(t *testing.T) { } func TestPRRequestWatcher_ReporterTrustOffDoesNothing(t *testing.T) { - srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}} + srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}, prAuthor: outsideAccountPR} c := reporterTrustTestClient(t, srv, false) c.prHoldLabel = func(string, string) bool { return false } runReporterTrustWatcher(t, c) @@ -818,7 +885,7 @@ func TestPRRequestWatcher_ReporterTrustOffDoesNothing(t *testing.T) { // the reporter-trust notice ALSO lands, because it is what stops the level // hold release from lifting the label on promotion to L6. func TestPRRequestWatcher_HoldGatedLevelStillPostsReporterTrustNotice(t *testing.T) { - srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}} + srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}, prAuthor: outsideAccountPR} c := reporterTrustTestClient(t, srv, true) c.prHoldLabel = func(string, string) bool { return true } runReporterTrustWatcher(t, c) @@ -843,6 +910,7 @@ func TestPRRequestWatcher_HoldGatedLevelStillPostsReporterTrustNotice(t *testing func reporterHeldPR(number int) *gh.PullRequest { return &gh.PullRequest{ Number: gh.Ptr(number), + User: &gh.User{Login: gh.Ptr(outsideAccountPR)}, Title: gh.Ptr("make the default dashboard theme Barbie"), Body: gh.Ptr("Closes #581"), Labels: []*gh.Label{{Name: gh.Ptr("hold")}}, @@ -882,6 +950,27 @@ func TestReleaseLevelHold_ReEvaluatesAndPostsMissingReporterNotice(t *testing.T) } } +func TestReleaseLevelHold_HiveAuthoredPRNotReporterHeld(t *testing.T) { + // A hive-authored level-held PR promoted to L6: the reporter gate does + // not re-hold it for the issue reporter's trust (hivecommons/hive#15020). + srv := &selfAuthServer{issues: map[int]*selfAuthIssue{581: {Author: "stranger", Association: "NONE"}}} + srv.comments = []string{levelHoldNotice("quality")} + c := reporterTrustTestClient(t, srv, true) + c.prHoldLabel = func(string, string) bool { return false } + + pr := reporterHeldPR(583) + pr.User = &gh.User{Login: gh.Ptr("kubestellar-hive[bot]"), Type: gh.Ptr("Bot")} + _, reason, _ := c.releaseLevelHoldIfEligible(context.Background(), "o", "r", pr) + if reason != "hold" { + t.Fatalf("reason = %q; a hive-authored PR must not be held by the reporter gate", reason) + } + for _, body := range srv.postedComments() { + if IsReporterTrustHoldNotice(body) { + t.Fatalf("a reporter-trust notice was posted on a hive-authored PR:\n%s", body) + } + } +} + func TestReleaseLevelHold_TrustedReporterStillReleases(t *testing.T) { // Positive control: with a maintainer's rationale, the reporter gate does // not interfere and the level hold reaches its ordinary release checks. diff --git a/src/pkg/stageengine/prstage/types.go b/src/pkg/stageengine/prstage/types.go index f4d07c9e78..1c62f3df31 100644 --- a/src/pkg/stageengine/prstage/types.go +++ b/src/pkg/stageengine/prstage/types.go @@ -136,6 +136,10 @@ type Observation struct { // because it is from a fork (StageLabelPolicy.ForkGuard); non-empty only // when every failing check does. ForkGuardChecks []string + // Hold is who set the `hold` label the PR wears and why, read by + // ApplyStageLabels from the label event and the hive's notice comment + // (hivecommons/hive#15020); nil when not held or unreadable. + Hold *stagelabels.HoldProvenance } // Verdict is a lane's opinion about a PR's stage. diff --git a/src/pkg/stagelabels/hold.go b/src/pkg/stagelabels/hold.go new file mode 100644 index 0000000000..4f024cea38 --- /dev/null +++ b/src/pkg/stagelabels/hold.go @@ -0,0 +1,118 @@ +package stagelabels + +import ( + "strconv" + "strings" + "time" +) + +// HoldProvenance records who set the `hold` label on an item and why, so the +// stage tracker row, the 085 entry comment and the decision popover can say +// "Held by hive · reporter trust (issue #15017 by @Karibhou, contributor)" +// instead of a bare "hold +1" (hivecommons/hive#15020). The stage-label +// pass reads it from the newest `hold` label event's actor and, for the +// hive's own holds, from the notice comment the gate left. +type HoldProvenance struct { + // By is "hive" when the hive's own GitHub App set the label, else the + // lower-cased login of the person (or other app) who did; "" unknown. + By string `json:"by,omitempty"` + // Source names the hive gate behind a hive-set hold: HoldSourceReporterTrust + // for the reporter-trust gate (#9665), HoldSourceLabel for a hold the + // hive can only attribute to the label event. + Source string `json:"source,omitempty"` + // Reason is the plain-words cause ("reporter trust (issue #N by @X, + // contributor)"), "" when only the label is known. + Reason string `json:"reason,omitempty"` + // Since is when the current hold was applied (the label event time, or + // the notice time when no event was readable). + Since time.Time `json:"since,omitempty"` + // Issue / Reporter / Association detail a reporter-trust hold: the + // linked issue the gate judged, its reporter and their association. + Issue int `json:"issue,omitempty"` + Reporter string `json:"reporter,omitempty"` + Association string `json:"association,omitempty"` +} + +// Hold sources. +const ( + HoldByHive = "hive" + HoldSourceReporterTrust = "reporter-trust" + HoldSourceLabel = "label" +) + +// SelfImposed reports whether the hive itself set this hold. +func (h *HoldProvenance) SelfImposed() bool { + return h != nil && strings.EqualFold(strings.TrimSpace(h.By), HoldByHive) +} + +// ReporterTrust reports whether the hold came from the reporter-trust gate. +func (h *HoldProvenance) ReporterTrust() bool { + return h != nil && strings.EqualFold(strings.TrimSpace(h.Source), HoldSourceReporterTrust) +} + +// Pill is the tracker pill text: "Held by hive · reporter trust (issue #N +// by @X, contributor)", "Held by @octocat", or "" when nothing is known. +func (h *HoldProvenance) Pill() string { + if h == nil || strings.TrimSpace(h.By) == "" { + return "" + } + who := "@" + strings.TrimSpace(h.By) + if h.SelfImposed() { + who = HoldByHive + } + s := "Held by " + who + if reason := strings.TrimSpace(h.Reason); reason != "" { + s += " · " + reason + } + return s +} + +// Clause is the sentence fragment the 085 comment and the popover use for +// "the `hold` label was set by hive: reporter trust (…)"; "" when unknown. +func (h *HoldProvenance) Clause() string { + if h == nil || strings.TrimSpace(h.By) == "" { + return "" + } + who := "@" + strings.TrimSpace(h.By) + if h.SelfImposed() { + who = "the hive itself" + } + s := "the `hold` label was set by " + who + if reason := strings.TrimSpace(h.Reason); reason != "" { + s += ": " + reason + } + return s +} + +// ReporterTrustReason renders the gate's finding the way the pill and the +// comment print it: "reporter trust (issue #N by @X, contributor)". +func ReporterTrustReason(issue int, reporter, association string) string { + var parts []string + if issue > 0 { + parts = append(parts, "issue #"+strconv.Itoa(issue)) + } + if reporter = strings.TrimSpace(reporter); reporter != "" { + parts = append(parts, "by @"+reporter) + } + detail := strings.Join(parts, " ") + if assoc := strings.ToLower(strings.TrimSpace(association)); assoc != "" { + if detail != "" { + detail += ", " + } + detail += strings.ReplaceAll(assoc, "_", " ") + } + if detail == "" { + return "reporter trust" + } + return "reporter trust (" + detail + ")" +} + +// Equal reports whether two provenances say the same thing (Since compared +// to the second, so a re-read of the same label event is a no-op). +func (h *HoldProvenance) Equal(o *HoldProvenance) bool { + if h == nil || o == nil { + return h == o + } + return h.By == o.By && h.Source == o.Source && h.Reason == o.Reason && h.Issue == o.Issue && + h.Reporter == o.Reporter && h.Association == o.Association && h.Since.Truncate(time.Second).Equal(o.Since.Truncate(time.Second)) +} diff --git a/src/pkg/stagelabels/hold_test.go b/src/pkg/stagelabels/hold_test.go new file mode 100644 index 0000000000..a06f8bb514 --- /dev/null +++ b/src/pkg/stagelabels/hold_test.go @@ -0,0 +1,137 @@ +package stagelabels + +import ( + "path/filepath" + "strings" + "testing" + "time" +) + +// hivecommons/hive#15020: who held an item and why rides the record so the +// tracker, the 085 comment and the popover can say it. + +func TestHoldProvenanceWords(t *testing.T) { + hive := &HoldProvenance{By: HoldByHive, Source: HoldSourceReporterTrust, Reason: ReporterTrustReason(15017, "Karibhou", "CONTRIBUTOR"), Issue: 15017, Reporter: "Karibhou", Association: "CONTRIBUTOR"} + if got := hive.Pill(); got != "Held by hive · reporter trust (issue #15017 by @Karibhou, contributor)" { + t.Fatalf("Pill = %q", got) + } + if got := hive.Clause(); got != "the `hold` label was set by the hive itself: reporter trust (issue #15017 by @Karibhou, contributor)" { + t.Fatalf("Clause = %q", got) + } + if !hive.SelfImposed() || !hive.ReporterTrust() { + t.Fatal("hive reporter-trust provenance must report both") + } + person := &HoldProvenance{By: "clubanderson", Source: HoldSourceLabel} + if got := person.Pill(); got != "Held by @clubanderson" { + t.Fatalf("Pill = %q", got) + } + if got := person.Clause(); got != "the `hold` label was set by @clubanderson" { + t.Fatalf("Clause = %q", got) + } + if person.SelfImposed() || person.ReporterTrust() { + t.Fatal("a person's hold is neither self-imposed nor reporter trust") + } + var none *HoldProvenance + if none.Pill() != "" || none.Clause() != "" || none.SelfImposed() || none.ReporterTrust() { + t.Fatal("nil provenance must say nothing") + } + if (&HoldProvenance{}).Pill() != "" { + t.Fatal("an unattributed provenance must say nothing") + } + for _, tc := range []struct{ issue, reporter, assoc, want string }{ + {"15017", "Karibhou", "CONTRIBUTOR", "reporter trust (issue #15017 by @Karibhou, contributor)"}, + {"7", "x", "FIRST_TIME_CONTRIBUTOR", "reporter trust (issue #7 by @x, first time contributor)"}, + {"0", "", "", "reporter trust"}, + {"9", "", "", "reporter trust (issue #9)"}, + } { + var n int + for _, ch := range tc.issue { + n = n*10 + int(ch-'0') + } + if got := ReporterTrustReason(n, tc.reporter, tc.assoc); got != tc.want { + t.Fatalf("ReporterTrustReason(%s, %q, %q) = %q, want %q", tc.issue, tc.reporter, tc.assoc, got, tc.want) + } + } +} + +func TestHoldProvenanceEqual(t *testing.T) { + at := time.Date(2026, 10, 20, 17, 14, 14, 0, time.UTC) + a := &HoldProvenance{By: HoldByHive, Source: HoldSourceReporterTrust, Reason: "r", Since: at, Issue: 1} + b := *a + b.Since = at.Add(300 * time.Millisecond) + if !a.Equal(&b) { + t.Fatal("sub-second drift must compare equal") + } + b.By = "pat" + if a.Equal(&b) || a.Equal(nil) || (*HoldProvenance)(nil).Equal(a) { + t.Fatal("different provenance / nil must not compare equal") + } + if !(*HoldProvenance)(nil).Equal(nil) { + t.Fatal("nil equals nil") + } +} + +func TestStoreNoteHold(t *testing.T) { + now := time.Date(2026, 10, 20, 17, 40, 0, 0, time.UTC) + s := NewStore(filepath.Join(t.TempDir(), "stage.json"), func() time.Time { return now }) + key := Key("acme/widget", 15020) + hold := &HoldProvenance{By: HoldByHive, Source: HoldSourceReporterTrust, Reason: "reporter trust (issue #15017 by @Karibhou, contributor)", Since: now, Issue: 15017, Reporter: "Karibhou", Association: "CONTRIBUTOR"} + s.NoteHold(key, hold) // no record yet: nothing to annotate + if _, ok := s.Get(key); ok { + t.Fatal("NoteHold must not create a record") + } + s.Observe(key, NeedsDecision, "label:hold") + s.NoteHold(key, hold) + rec, _ := s.Get(key) + if rec.Hold == nil || !rec.Hold.Equal(hold) { + t.Fatalf("record hold = %+v, want %+v", rec.Hold, hold) + } + hold.Reason = "mutated after the call" + if rec, _ := s.Get(key); rec.Hold.Reason != "reporter trust (issue #15017 by @Karibhou, contributor)" { + t.Fatal("the store must copy the provenance, not alias the caller's pointer") + } + if err := s.Save(); err != nil { + t.Fatal(err) + } + s.dirty = false + s.NoteHold(key, &HoldProvenance{By: HoldByHive, Source: HoldSourceReporterTrust, Reason: "reporter trust (issue #15017 by @Karibhou, contributor)", Since: now, Issue: 15017, Reporter: "Karibhou", Association: "CONTRIBUTOR"}) + if s.dirty { + t.Fatal("re-noting the same provenance must not dirty the store") + } + reloaded := NewStore(s.path, func() time.Time { return now }) + if err := reloaded.Load(); err != nil { + t.Fatal(err) + } + if rec, ok := reloaded.Get(key); !ok || rec.Hold == nil || rec.Hold.By != HoldByHive || rec.Hold.Issue != 15017 { + t.Fatalf("reloaded hold = %+v (ok=%v)", rec.Hold, ok) + } + s.ClearHold(key) + if rec, _ := s.Get(key); rec.Hold != nil { + t.Fatalf("ClearHold left %+v", rec.Hold) + } +} + +func TestRouteHumanNamesWhoHeld(t *testing.T) { + base := Evidence{Head: "abc1234", Verdict: VerdictApproved, Checks: CheckSummary{Total: 3, Green: 3, Known: true}, DCO: DCOYes, Holds: []string{"hold"}, Cause: CauseDecision, SelfAuthored: true} + plain := RouteHuman(base) + if plain.Stage != NeedsDecision || strings.Join(plain.Reasons, "|") != "the `hold` label is set|the automerge lane will not merge this unattended" || plain.Hold != nil { + t.Fatalf("plain route = %+v", plain) + } + hive := base + hive.Hold = &HoldProvenance{By: HoldByHive, Source: HoldSourceReporterTrust, Reason: ReporterTrustReason(15017, "Karibhou", "CONTRIBUTOR")} + route := RouteHuman(hive) + if route.Reasons[0] != "the `hold` label was set by the hive itself: reporter trust (issue #15017 by @Karibhou, contributor)" || route.Hold != hive.Hold { + t.Fatalf("hive-held route = %+v", route) + } + comment := DecisionComment(route) + if !strings.Contains(comment, "set by the hive itself: reporter trust (issue #15017 by @Karibhou, contributor)") || strings.Contains(comment, "the `hold` label is set") { + t.Fatalf("085 comment:\n%s", comment) + } + person := base + person.Holds = []string{"do-not-merge", "hold"} + person.Hold = &HoldProvenance{By: "clubanderson", Source: HoldSourceLabel} + route = RouteHuman(person) + if strings.Join(route.Reasons, "|") != "the `do-not-merge` label is set|the `hold` label was set by @clubanderson|the automerge lane will not merge this unattended" { + t.Fatalf("person-held route reasons = %q", route.Reasons) + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 402193d967..a880701b51 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -109,6 +109,10 @@ type Evidence struct { // Holds lists the decision-class modifier labels present, lower-cased // (see HoldLabels). Holds []string + // Hold is who set the `hold` label and why, when the pass could read + // it (hivecommons/hive#15020); the 085 reason then names them instead + // of the bare "the `hold` label is set". + Hold *HoldProvenance // Cause is why the lane handed off; CauseTrust is the only one that can // end at 090. Cause HumanCause @@ -214,6 +218,9 @@ type Route struct { // HumanApprover is the trusted merger whose approval on Head settled // the requires_human verdict / manual-merge rule ("" when none). HumanApprover string + // Hold carries the `hold` provenance into the 085 comment so it can + // name who set the hold and offer release / keep (hivecommons/hive#15020). + Hold *HoldProvenance } // Lane-vocabulary reasons RouteHuman emits for the fixing stages. @@ -307,6 +314,10 @@ func RouteHuman(e Evidence) Route { decide = append(decide, "a sentinel alert is open on this PR") } for _, h := range e.Holds { + if h == "hold" && e.Hold.Clause() != "" { + decide = append(decide, e.Hold.Clause()) + continue + } decide = append(decide, "the `"+h+"` label is set") } manualMergeApproved := e.Cause == CauseDecision && e.ManualMergeRule && approver != "" && strings.TrimSpace(e.CauseReason) != "" && len(decide) == 0 @@ -316,7 +327,7 @@ func RouteHuman(e Evidence) Route { decide = append(decide, "the automerge lane will not merge this unattended") } if len(decide) > 0 { - return Route{Stage: NeedsDecision, Reasons: decide, Summary: summary, Head: e.Head, SelfAuthored: e.SelfAuthored, Verdict: e.Verdict, HumanApprover: approver} + return Route{Stage: NeedsDecision, Reasons: decide, Summary: summary, Head: e.Head, SelfAuthored: e.SelfAuthored, Verdict: e.Verdict, HumanApprover: approver, Hold: e.Hold} } var wait []string switch { diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 4f21deba16..412ec1be16 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -170,6 +170,11 @@ type Record struct { // when the blocker clears or the head moves. AdoptEscalatedHead string `json:"adopt_escalated_head,omitempty"` AdoptEscalatedReason string `json:"adopt_escalated_reason,omitempty"` + // Hold is who set the `hold` label the item wears and why, read by the + // stage-label pass from the label event and the hive's notice comment + // (hivecommons/hive#15020); nil when the item is not held or nothing + // about the hold could be read. + Hold *HoldProvenance `json:"hold,omitempty"` // AdoptEscalationNotedHead is the head the escalation note was posted // for; it survives ClearAdoptionEscalation so a blocker that flaps on // one head is noted once. @@ -1383,6 +1388,29 @@ func (s *Store) NoteAuthor(key, login string) { s.dirty = true } +// NoteHold records the hold provenance on an existing record; a nil +// provenance clears it (the item is no longer held, or the hold is now +// somebody else's). +func (s *Store) NoteHold(key string, hold *HoldProvenance) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.Hold.Equal(hold) { + return + } + if hold == nil { + r.Hold = nil + } else { + cp := *hold + r.Hold = &cp + } + s.items[key] = r + s.dirty = true +} + +// ClearHold drops the hold provenance from an existing record. +func (s *Store) ClearHold(key string) { s.NoteHold(key, nil) } + // NoteDCO caches the commit check for head on an existing record: // unsignedHive is the App-linked share of the unsigned commits, the rest // is recorded as other.