From 3b9cd6955e3ca5b3bfe6384d53748b1c5e8de132 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 27 Oct 2026 11:56:26 -0400 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20feat:=20mark=20lanes=20unauthor?= =?UTF-8?q?ized=20when=20the=20App=20lacks=20rights=20for=20the=20next=20s?= =?UTF-8?q?tep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A GitHub App API call the contributor lane needs to advance that fails with 403 Resource not accessible by integration now routes through markUnauthorized: label hive:unauthorized, one comment per (head, step) naming the missing permission and the human step, reason unauthorized: parking the PR at 085, one INFO log per head, and clearUnauthorized in the tick the step is no longer needed. First call site: held-run approval without actions: write. Dashboard draws a muted unauthorized pill and reads Awaiting human: approve workflow runs. Fixes #14589 Signed-off-by: Andy Anderson --- changelog.d/added-unauthorized-label.md | 1 + src/docs/dashboard-sections.md | 2 + src/docs/github-app-setup.md | 4 +- src/docs/labels-and-control-signals.md | 4 +- src/pkg/dashboard/label_presets.go | 3 + src/pkg/dashboard/label_presets_test.go | 6 +- src/pkg/dashboard/stage_tracker.go | 64 ++++- .../stage_tracker_sentinel_lane_test.go | 7 +- .../stage_tracker_unauthorized_test.go | 140 ++++++++++ src/pkg/dashboard/static/index.html | 25 +- .../automerge/automerge_contributor_adopt.go | 5 + .../automerge_contributor_held_runs.go | 46 +++- .../automerge_contributor_held_runs_test.go | 162 ++++++++++- .../automerge/automerge_contributor_lane.go | 9 +- .../automerge_contributor_lane_test.go | 26 ++ .../automerge/automerge_merge_forward.go | 5 + .../github/automerge/automerge_stage_human.go | 2 + src/pkg/github/automerge/automerge_sweep.go | 12 + .../automerge/automerge_unauthorized.go | 260 ++++++++++++++++++ src/pkg/stageengine/derive_pr_classify.go | 6 + .../derive_pr_unauthorized_test.go | 38 +++ src/pkg/stageengine/prstage/reasons.go | 15 +- src/pkg/stagelabels/stagelabels.go | 8 + 23 files changed, 811 insertions(+), 39 deletions(-) create mode 100644 changelog.d/added-unauthorized-label.md create mode 100644 src/pkg/dashboard/stage_tracker_unauthorized_test.go create mode 100644 src/pkg/github/automerge/automerge_unauthorized.go create mode 100644 src/pkg/stageengine/derive_pr_unauthorized_test.go diff --git a/changelog.d/added-unauthorized-label.md b/changelog.d/added-unauthorized-label.md new file mode 100644 index 0000000000..6cede2ce14 --- /dev/null +++ b/changelog.d/added-unauthorized-label.md @@ -0,0 +1 @@ +- Mark lanes `unauthorized` when the hive's GitHub App lacks the permission for the next step: a `403 Resource not accessible by integration` on a prerequisite call (first: approving held workflow runs without `actions: write`) adds `hive:unauthorized`, posts one comment per head naming the permission and the human step, logs once per head, parks the PR at 085 as `Awaiting human: approve workflow runs`, shows a muted `unauthorized` pill in the activity monitor, and clears itself the tick the step is no longer needed ([#14589](https://github.com/hivecommons/hive/issues/14589)). diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 4731839428..bca03ab384 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -654,6 +654,8 @@ Fed by `GET /api/stage-tracker`. Every issue and pull request follows the same p **Sentinel alert.** A pull request the suspicious-activity sentinel flagged — it wears the `sentinel-alert` label (`sentinel.label`), or the review evidence bundle for its current head records sentinel findings — carries `sentinel_alert: true` in the tracker payload (with `sentinel_findings` and a short `sentinel_reason` when the bundle has them); a webhook label change flips it live. In the **Needs human decision** lane the lit chevron's own words read **Sentinel alert · needs human** (danger-tinted, the same wording in the cell's `title` and `aria-label`, and in the compact caption), so a maintainer reads the security implication before the stage mechanics; in every other lane the row shows a compact danger-tinted `sentinel` chip ahead of `needs rebase` / `regressed` / `stalled`. The tooltip reads "Sentinel flagged security-relevant changes at ``: ``" (a generic description stands in when the bundle has no reason). An issue carried by one flagged PR shows the lane text too, and a nested PR sub-row shows its own. The *Decide…* dialogs for a flagged PR open with a ⚠ line per flagged PR naming the sentinel reason, and *Approve* is styled as a dangerous action. Lane text and chip update in place on refresh (keyed reconcile, no flash). +**Unauthorized pill.** A pull request the hive cannot move because its GitHub App lacks a permission for the next step — it wears `hive:unauthorized` ([#14589](https://github.com/hivecommons/hive/issues/14589)); first case: approving held `action_required` workflow runs needs `actions: write` — carries the `unauthorized` modifier in the tracker payload, drawn in the far-right pill column exactly like `stalled` / `hold` / `draft` but muted (dashed, `--text-muted`), never red: it is nothing wrong, just a step only a person may take. It counts under **Needs attention**. Its tooltip (payload `unauthorized`) names the missing permission and the human step; on the **Needs human decision** lane the lit chevron and the caption read **Awaiting human: approve workflow runs** (payload `unauthorized_step`, from the `unauthorized:` stage reason). The pill, label and payload fields clear themselves in the tick the step is no longer needed. + **Row gutter.** Every issue and PR row (never a column or repo-group header) carries a left gutter with a select checkbox and a ⋯ actions button that is always present and always visible: dimmed at rest (`--ham-tool-rest-opacity`), at full emphasis on the row under the pointer or holding focus, on a selected row, and on every row while anything is selected or the context menu is open — the only animation is the hover fade (`--ham-tool-fade-ms`, ≤ 120 ms), and nothing about it depends on scrolling, row position or which rows the live refresh re-created. **Row actions (right-click, ⋯, Shift+F10).** Right-clicking a row — or a nested PR sub-row — opens an in-app context menu of the actions that fit that item's current state; the ⋯ button in the row's left gutter opens the same menu for pointer-free use, and so do **Shift+F10** and the context-menu key while the row or anything in it has focus (every row is a tab stop). The menu is positioned at the pointer, clamped to the viewport, uses `menu` / `menuitem` roles, moves focus with ↑ ↓ Home End, opens the *Decide…* group with → and closes it with ←, and closes on Esc, Tab, click-away, scroll or resize, returning focus to the row. Shift+right-click keeps the browser's own menu. Entries, each shown only when it applies: **Decide…** on a row waiting on a person — a PR wearing the *Needs human decision* pill at 085 on the Merge gate column (the primary case: e.g. two competing `dibs` PRs), an issue row whose nested PR is parked there (the menu reads *Decide PR #458…* and acts on that PR, since the issue's own stage is only mirrored from it), or an issue parked at 045. The first entry is always *Let hive decide* (see [Let hive decide](#let-hive-decide) below): the hive decides as the owner's delegate and records it the way a person's decision is recorded. For a PR: *Approve (/lgtm + /approve)* posts those two commands as comments attributed to you — the merge gate takes it from there exactly as if you had typed them; the dashboard reviews, labels and merges nothing — *Close as superseded by…* (a picker listing the other open PRs in the repo, or type `#458` / `owner/repo#458` / a URL; then an optional comment, then the sweep's labelled close), *Won't fix…* (a comment naming you, then a not-planned close) and *Give direction…* (your text is recorded as `/hive decision ` against the head, so the author agent pushes a new head; only on PRs the hive opened). For an issue: *Approve direction* (records the same `/hive approve` a maintainer would comment: the parking labels come off, `approved-direction` goes on, the stage engine logs the un-park and a reply comment names you; nothing is merged), *Send back to the hive…* (`/hive decision `), *Close as superseded by…* and *Close as won't-fix…*. A selection mixing parked issues and parked PRs has Decide… greyed; **Hold** or **Release hold** depending on the `hold` chip (the same `…/items/{number}/hold` toggle as the repository cards, and the same permission — owner, or a signed-in user with write access to the repo); **Re-evaluate now** (the hive-wide read-only rescan behind the Overview's refresh — a rescan already running is reported, not duplicated); **Accept triage** (only on an issue the chevron calls *Triage needed* — stage 015, or the `needs-triage` chip on another stage — never on a PR; the one-click form of a maintainer accepting triage on GitHub: adds the reporter-trust triage label, `triage/accepted` by default or the first of `issue_filter.reporter_trust.untrusted_require_labels`, removes the awaiting label `needs-triage` / `reporter_trust.awaiting_label` and a Hive-written `stage/015-triage-needed`; the row re-reads *Actionable* with the 👤 gone at once, the reporter-trust gate admits the issue on its next poll and the stage engine records 015 → 010; same permission as Hold, audited as `repo_item_accept_triage`, a no-op when already accepted); **Mark needs-human…** (hidden once the chip is on; merger or owner role, applies `needs-human` and a marker comment through the review pipeline's send-to-human endpoint); **Open on GitHub**; **Copy link**. Entries you may not use are greyed with the reason in their tooltip, never hidden. Confirmation and free-text input use the dashboard's own dialogs — no browser prompts. Every action is an existing audited dashboard endpoint (the decision endpoint is `POST /api/repos/{owner}/{repo}/items/{number}/decision` and triage acceptance is `POST /api/repos/{owner}/{repo}/items/{number}/accept-triage`, see [api-reference.md](api-reference.md)); none of them bypasses the hive's governance or merges anything. diff --git a/src/docs/github-app-setup.md b/src/docs/github-app-setup.md index 01d54a4a48..000dffa68e 100644 --- a/src/docs/github-app-setup.md +++ b/src/docs/github-app-setup.md @@ -43,7 +43,7 @@ Fine-grained PATs are supported — the token is sent as a plain bearer, same as | Actions | Read | Read | Read | | Commit statuses | Read | Read | Read and write — needed when `governor.labels.automerge` is the default `lgtm` on a Prow repository, so the queue action can set the `prow/lgtm` status beside the label. With only Read, every queue action still applies the label but posts a PR comment that the status could not be set. | -Hive does not require **Actions: Read and write** for bot workflow-run approvals; **Actions: Read** is enough to inspect runs. The one direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — does need Read and write; without it that call fails, is logged once per head, and the PR waits for a person. When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; no Prow and no Hive App Actions-write grant are required. Hive never approves fork heads or PRs carrying `sentinel-alert`. +Hive does not require **Actions: Read and write** for bot workflow-run approvals; **Actions: Read** is enough to inspect runs. The one direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — does need Read and write. Granting it is **optional**: without it the call fails with `403 Resource not accessible by integration`, the hive labels the PR `hive:unauthorized`, posts one comment naming the permission and the human step (**Approve and run** on the checks banner or Actions tab, with the run ids), logs `lane unauthorized` once per head, parks the PR at 085 (`Awaiting human: approve workflow runs` in the activity monitor), and clears all of it the tick the required checks report ([#14589](https://github.com/hivecommons/hive/issues/14589)). When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; no Prow and no Hive App Actions-write grant are required. Hive never approves fork heads or PRs carrying `sentinel-alert`. Install the workflow in each governed repository: run `hivectl ok-to-test-template > .github/workflows/hive-ok-to-test.yml` against your hive (it reads the App bot login from `/api/config`; pass `--app-login [bot]` to override), or copy `src/docs/templates/hive-ok-to-test.yml` and replace `HIVE_APP_LOGIN[bot]` with the App bot login shown by Hive for that installation. @@ -90,7 +90,7 @@ Repository permissions used by the dashboard setup UI are: | Issues | Read/write | Enumerate, comment on, create, and close issues. | | Pull requests | Read/write | Create, update, approve/merge, and inspect PRs. | | Checks | Read-only | Monitor CI status. | -| Actions | Read-only (Read and write to approve registry-trusted contributors' held runs) | Inspect workflow runs. If GitHub holds trusted Dependabot/App/clanker runs in `action_required`, Hive posts `/ok-to-test`; the repository-local `hive-ok-to-test` workflow uses its own `GITHUB_TOKEN` with Actions write to approve those runs. With Read and write, the contributor lane also approves held runs directly for a PR author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`). | +| Actions | Read-only (Read and write to approve registry-trusted contributors' held runs) | Inspect workflow runs. If GitHub holds trusted Dependabot/App/clanker runs in `action_required`, Hive posts `/ok-to-test`; the repository-local `hive-ok-to-test` workflow uses its own `GITHUB_TOKEN` with Actions write to approve those runs. With Read and write, the contributor lane also approves held runs directly for a PR author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`). Optional: without it the hive marks such a PR `hive:unauthorized` and waits for a maintainer to click **Approve and run** ([#14589](https://github.com/hivecommons/hive/issues/14589)). | | Administration | Read-only | Read branch-protection rules before the merge-request watcher lands a PR; Hive refuses closed if it cannot verify the base branch is protected. | | Commit statuses | Read/write | Needed when `governor.labels.automerge` is the default `lgtm` on a repository running Prow's commit-bound `lgtm` (prow-github-actions v3): the queue action sets a `prow/lgtm` success status on the approved head so Prow does not strip the label. Without the write grant the label and approval still land, but every queue action takes the failure branch and posts a PR comment saying the status could not be set. Choose a distinct label such as `hive/auto-merge` if you would rather keep this at Read. | diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index 0642e4bbe8..575f591f4e 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -77,6 +77,7 @@ Some hive-authored labels look like provenance but are read as signals, so they | `needs-spec` from the clarity gate | Issues | Scheduler kick assembly (`runs.triage.clarity_gate`) | With the gate on (default off), a human-filed, unclaimed issue whose clarity score (goal, acceptance criteria, scope, detail, open choices) is under `runs.triage.clarity_gate.threshold` gets one `` comment with concise questions for its author and the `needs-spec` hard-suppress label instead of a claim; it derives `stage/045-needs-decision` and leaves the agent queue ([#13577](https://github.com/hivecommons/hive/issues/13577)). | Hard suppress | Hive | Before kicks are built | The issue author, or a non-hive commenter with write/maintain/admin, replies after the marker and the resume sweep removes the hive's own `needs-spec` and records the un-park so the issue re-derives `stage/010-actionable` ([#13588](https://github.com/hivecommons/hive/issues/13588)); a `needs-spec` a person added is never lifted by the sweep. Or remove `needs-spec` by hand. The marker keeps the gate from asking again | `runs.triage.clarity_gate` (`src/pkg/scheduler/clarity_gate.go`, `src/pkg/classify/clarity.go`, `src/pkg/github/clarity_gate_resume.go`) | | `stage/017-possible-existing` from the prior-art gate | Issues | Scheduler kick assembly (`runs.triage.prior_art`) | With the gate on (default on), an unclaimed feature / RFC / epic issue whose key terms match an existing knowledge bead, setting, merged PR, closed issue, doc or code identifier at `runs.triage.prior_art.threshold` (default 70) gets one `` comment quoting the findings and the `stage/017-possible-existing` label instead of a claim; hive-filed issues get a `` note and are never parked ([#13575](https://github.com/hivecommons/hive/issues/13575)). | Hard suppress | Hive | Before kicks are built | The author or a write+ commenter replies `/hive decision proceed — ` (label lifted, a *Scope vs existing* section appended to the body, re-derives 010) or `/hive decision exists` (closed `not_planned` with `already-exists`); a plain reply lifts the label too. A clanker-filed park with no reply is closed `already-exists` after `runs.triage.prior_art.bot_close_ttl` (default 72h); reopen to continue. A 017 a person added is never lifted by the sweep | `runs.triage.prior_art` (`src/pkg/priorart`, `src/pkg/scheduler/prior_art_gate.go`, `src/pkg/github/prior_art_gate_resume.go`) | | `hive/handoff` | Issues | Task-list sweep | Soft hand-off marker. When a merged PR's `Refs #N` remainder section says in prose that the rest needs a person or another lane ("needs a human", "fix lane", "quality lane", "production change", …) without the explicit `needs-human:` marker, the sweep adds this label and notes "handed off to the next lane" in its remainder comment instead of parking the issue. It is not a hold, suppress, or enumeration filter: the issue stays actionable, so the next lane can still claim it ([#12002](https://github.com/hivecommons/hive/issues/12002)). Not added when the same sweep is applying `needs-human`. | Informational | Hive (task-list sweep) | Task-list sweep | Human or the claiming lane removes it; Hive never removes it | Fixed label (`src/pkg/github/task_list_sweep.go:85`, `src/pkg/github/task_list_sweep.go:576-596`, `src/pkg/github/task_list_sweep.go:635-665`) | +| `hive:unauthorized` | PRs (issues when a step on one is blocked) | Contributor lane (`markUnauthorized`), dashboard activity monitor | The hive's GitHub App was refused (`403 Resource not accessible by integration`) on an API call the lane needs to advance, so only a person can take the next step. First wired call site: approving held `action_required` workflow runs for a registry-trusted author needs `actions: write`, which an operator may decline to grant ([#14589](https://github.com/hivecommons/hive/issues/14589)). The lane reports `unauthorized:` (`unauthorized:approve-workflow-runs`), the stage engine parks the PR at 085, one `` comment names the missing permission, the exact human step (**Approve and run** on the checks banner or Actions tab, with the run ids) and the alternative of granting the permission, and the hive logs `lane unauthorized` once per head at INFO instead of a WARN per tick. The activity monitor draws a muted `unauthorized` pill (counted under Needs attention) whose tooltip repeats the permission and the step, and the 085 cell reads **Awaiting human: approve workflow runs**. | Human-gated hold | Hive | Every lane tick that hits the refused call | Removed by the hive in the tick the step is no longer needed (the required checks for the head report, the lane advances); a new head re-posts the comment once. No human label edit required; removing it by hand is harmless — it is re-applied if the step is still refused | Not configurable; outside `stage/`, so the reconciler never strips it (`src/pkg/github/automerge/automerge_unauthorized.go`) | | `needs-human` | PRs | Escalation ledger, reviewer lane, self-authored auto-merge sweep, queued auto-merge sweep, supersession sweep | Applied when red-CI fix budget is exhausted or a workflow needs a person; stops automated fix dispatch, sends the PR to the human/reviewer lane, and blocks auto-merge sweeps while present. It is not a PR enumeration filter. The stage engine reads it as a park (`label:needs-human` → `stage/085-needs-decision`), so a writer that adds it must also submit a `Parked` fact (`FactSink.Parked(ref, "needs-human")`) in the same pass; the label alone leaves the previous lane stage standing until the next auto-merge tick. The supersession sweep does this for a contributor PR that touches files the merged closer PR did not, and for a hive PR below ACMM L6; it never adds the label to a hive PR at L6, which it resolves itself (see [Supersession](#supersession-closed-issue-another-merged-pr)). | Hard fix-dispatch and merge gate | Hive | Escalation pass/kick building/auto-merge sweeps/supersession sweep | Human removes after root cause or reviewer un-escalates; budget resets after grace; auto-merge reconsiders on the next tick because no persisted hold state is kept; the supersession sweep removes only the `needs-human` it applied itself (label timeline actor is a hive account) when it takes a hive PR's resolution over | Fixed label (`src/pkg/escalation/escalation.go:400-470`, `src/pkg/escalation/escalation.go:1185-1205`) | | `hive/advisory` | Issues | Standing meta classifier | Hive advisory report is never actionable and never appears on the Hold list. | Hard exclusion | Hive | Before holds/exempts | Remove label, but exact advisory title still excludes | Fixed label/name (`src/pkg/github/standing_issues.go:1-57`, `src/pkg/github/client.go:983-1001`) | | `triage/advisory` | Issues | Standing meta classifier | Advisory-only dedupe checklist (`Decision required: no`, #11864) is never actionable and never appears on the Hold list; action-required checklists are parked with `needs-decision` instead. The close-on-merge backfill closes it once every `#N` it references is closed or merged, or after 7 days, and swaps it for `needs-decision` plus the "What to reply" notice if line two turns to `Decision required: yes` (#11871). | Hard exclusion | Dedupe agent | Before holds/exempts | Remove label | Fixed label/name (`src/pkg/github/standing_issues.go`) | @@ -1167,7 +1168,8 @@ without the marker the next sweep would treat it as a fresh supersession. These existing labels qualify a stage and may coexist with any stage label; the reconciler never touches them: `hold` / `hold/*`, `needs-human`, -`blocked`, `needs-rebase`, +`blocked`, `needs-rebase`, `hive:unauthorized` (the App lacks a permission +for the next step; see the reference table), `hive/likely-done`, `hive/partially-addressed`, `hive/verified-open`, `hive/claimed-by-` (the grey "who" modifier a stage cannot carry), `lgtm`, `role/*`, `author/*`, `dco` / `no-dco`, and the agent provenance diff --git a/src/pkg/dashboard/label_presets.go b/src/pkg/dashboard/label_presets.go index e37c7a1231..6813d4821b 100644 --- a/src/pkg/dashboard/label_presets.go +++ b/src/pkg/dashboard/label_presets.go @@ -43,6 +43,8 @@ const ( // - github.HoldLabels plus this hive's canonical hold label; // - stage/071-needs-author, the PR stage where a human author must push // or answer the hive's diagnosis; +// - hive:unauthorized, the PR whose next step the hive's GitHub App is +// not permitted to take (hivecommons/hive#14589); // - the sentinel alert label (sentinel.label, default sentinel-alert): the // sweep refuses to merge a flagged PR until a maintainer reviews it and // removes the label (hivecommons/hive#13780); @@ -84,6 +86,7 @@ func needsHumanPresetLabels(cfg *config.Config, hiveID string) []string { add(github.HoldLabels...) add(github.CanonicalHiveHoldLabel(hiveID)) add(stagelabels.NeedsAuthor.Label()) + add(stagelabels.UnauthorizedLabel) if cfg != nil { add(cfg.Sentinel.LabelOrDefault()) add(cfg.Project.IssueFilter.ReporterTrustAwaitingLabel()) diff --git a/src/pkg/dashboard/label_presets_test.go b/src/pkg/dashboard/label_presets_test.go index ce32e8e078..906a3d7730 100644 --- a/src/pkg/dashboard/label_presets_test.go +++ b/src/pkg/dashboard/label_presets_test.go @@ -14,12 +14,12 @@ import ( func TestNeedsHumanPresetLabelsDefaultOrder(t *testing.T) { got := needsHumanPresetLabels(nil, "") want := append([]string{github.NeedsDecisionStageLabel, github.PRNeedsDecisionStageLabel, "needs-decision", "needs-direction", "needs-spec", "needs-signal", "needs-human"}, github.HoldLabels...) - want = append(want, stagelabels.NeedsAuthor.Label(), config.DefaultSentinelLabel, config.DefaultReporterTrustAwaitingLabel) + want = append(want, stagelabels.NeedsAuthor.Label(), stagelabels.UnauthorizedLabel, config.DefaultSentinelLabel, config.DefaultReporterTrustAwaitingLabel) if !reflect.DeepEqual(got, want) { t.Fatalf("default needs-human preset = %v, want %v", got, want) } - if got[len(got)-3] != "stage/071-needs-author" || got[len(got)-2] != "sentinel-alert" || got[len(got)-1] != "needs-triage" { - t.Fatalf("needs-author, sentinel-alert and needs-triage must close the default set, got %v", got) + if got[len(got)-4] != "stage/071-needs-author" || got[len(got)-3] != "hive:unauthorized" || got[len(got)-2] != "sentinel-alert" || got[len(got)-1] != "needs-triage" { + t.Fatalf("needs-author, hive:unauthorized, sentinel-alert and needs-triage must close the default set, got %v", got) } } diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 30016606b2..b82ef6cfc0 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -299,11 +299,19 @@ type StageTrackerItem struct { // a human-merge path): at 090 the merge gate then reads "Awaiting // human merge" and names the approver, since the only step left is // the maintainer's merge click. - HumanApprover string `json:"human_approver,omitempty"` - ManualMerge bool `json:"manual_merge,omitempty"` - NudgeCount int `json:"nudge_count,omitempty"` - LastNudgeAt *time.Time `json:"last_nudge_at,omitempty"` - AdoptedBy int `json:"adopted_by,omitempty"` + HumanApprover string `json:"human_approver,omitempty"` + ManualMerge bool `json:"manual_merge,omitempty"` + // UnauthorizedStep is set when the item wears hive:unauthorized: the + // step the hive's GitHub App is not permitted to take, in words + // ("approve workflow runs"), from the `unauthorized:` stage + // reason; the gate cell reads "Awaiting human: ". Unauthorized + // is the pill's tooltip naming the permission and the human action + // (hivecommons/hive#14589). + UnauthorizedStep string `json:"unauthorized_step,omitempty"` + Unauthorized string `json:"unauthorized,omitempty"` + NudgeCount int `json:"nudge_count,omitempty"` + LastNudgeAt *time.Time `json:"last_nudge_at,omitempty"` + AdoptedBy int `json:"adopted_by,omitempty"` // ClaimantKind is the author kind of whoever holds the live claim on a // claimed issue (human / clanker / hive), from the worker-claim ledger. ClaimantKind string `json:"claimant_kind,omitempty"` @@ -409,6 +417,10 @@ const ( modNeedsRebase = "needs-rebase" modBlocked = "blocked" modDraft = "draft" + // modUnauthorized: the item wears stagelabels.UnauthorizedLabel — the + // hive's GitHub App lacks the permission for its next step and a + // person must take it (hivecommons/hive#14589). + modUnauthorized = "unauthorized" ) // Lane names. @@ -653,6 +665,8 @@ func stageTrackerModifiers(labels []string, hiveID string, rec stagelabels.Recor set[modNeedsRebase] = true case "blocked": set[modBlocked] = true + case stagelabels.UnauthorizedLabel: + set[modUnauthorized] = true } } if len(holdLabels(labels, hiveID)) > 0 { @@ -670,7 +684,7 @@ func stageTrackerModifiers(labels []string, hiveID string, rec stagelabels.Recor set[modDraft] = true } out := make([]string, 0, len(set)) - for _, m := range []string{modStalled, modRegressed, modHold, modNeedsHuman, modNeedsDecision, modNeedsTriage, modPossibleDupe, modNeedsRebase, modBlocked, modDraft} { + for _, m := range []string{modStalled, modRegressed, modHold, modUnauthorized, modNeedsHuman, modNeedsDecision, modNeedsTriage, modPossibleDupe, modNeedsRebase, modBlocked, modDraft} { if set[m] { out = append(out, m) } @@ -742,6 +756,9 @@ func humanizeStageReason(reason string) string { if rest, ok := strings.CutPrefix(r, "base-branch-red:"); ok { return "waiting for the base branch's CI to recover (" + strings.ReplaceAll(rest, ",", ", ") + ") — not this PR's fault" } + if rest, ok := strings.CutPrefix(r, stageengineprstage.StageReasonUnauthorizedPrefix); ok { + return "the hive's GitHub App is not permitted to " + unauthorizedStepWords(rest) + "; a maintainer must" + } if rest, ok := strings.CutPrefix(r, "fork-guard:"); ok { return "check " + strings.ReplaceAll(rest, ",", ", ") + " refuses fork PRs — a maintainer must push this branch to the repository" } @@ -795,6 +812,33 @@ func humanizeStageReason(reason string) string { return strings.NewReplacer("-", " ", "_", " ", ":", ": ").Replace(r) } +// unauthorizedStepWords renders an `unauthorized:` step as words. +func unauthorizedStepWords(step string) string { + return strings.ReplaceAll(strings.TrimSpace(step), "-", " ") +} + +// Tooltip for the unauthorized pill, per step; the generic form serves a +// label whose stage reason does not (or no longer) names the step. +const ( + stageTrackerUnauthorizedApproveRuns = "The hive's GitHub App lacks `actions: write`, so it cannot approve the workflow runs GitHub is holding for this head. A maintainer must click Approve and run on the PR's checks banner (or the Actions tab); see the hive:unauthorized comment for the run ids. Hive resumes, and clears the label, once the required checks report." + stageTrackerUnauthorizedGeneric = "The hive's GitHub App lacks a permission for the next step, so only a person can take it; the hive:unauthorized comment on the PR names the permission and the step. Hive resumes, and clears the label, once the step is done." +) + +// stageTrackerUnauthorized derives the gate word and the tooltip for an +// item wearing hive:unauthorized from its stage reason. +func stageTrackerUnauthorized(reason string) (step, tip string) { + base, _ := stagelabels.HumanApprovedReason(strings.TrimSpace(reason)) + rest, ok := strings.CutPrefix(base, stageengineprstage.StageReasonUnauthorizedPrefix) + if !ok || strings.TrimSpace(rest) == "" { + return "", stageTrackerUnauthorizedGeneric + } + step = unauthorizedStepWords(rest) + if rest == stageengineprstage.UnauthorizedStepApproveWorkflowRuns { + return step, stageTrackerUnauthorizedApproveRuns + } + return step, "The hive's GitHub App lacks the permission to " + step + ", so only a person can take that step; the hive:unauthorized comment on the PR names the permission and the action. Hive resumes, and clears the label, once the step is done." +} + // stageTrackerManualMergeReason reports whether a bare stage reason is a // lane rule the hive never merges unattended, so a 090 under it is waiting // on a maintainer's merge click rather than on /lgtm /approve. @@ -928,6 +972,11 @@ func stageTrackerCaption(stage stagelabels.Stage, reason, author string, kind st case stagelabels.AwaitingMergeAdmission: return joinClause("Green and approved; waiting for the automerge lane to admit it", clause), "automerge lane" case stagelabels.NeedsDecision, stagelabels.IssueNeedsDecision: + if step, _ := stageTrackerUnauthorized(reason); step != "" { + // hivecommons/hive#14589: not a decision but a step only a + // person may take; the gate cell says the same. + return joinClause("Awaiting human: "+step, clause), "maintainer" + } return joinClause("A human decision is owed", clause), "maintainer" case stagelabels.ReadyForHumanMerge: if base, approver := stagelabels.HumanApprovedReason(reason); stageTrackerManualMergeReason(base) { @@ -1128,6 +1177,9 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto base, approver := stagelabels.HumanApprovedReason(it.Reason) it.HumanApprover = approver it.ManualMerge = stageTrackerManualMergeReason(base) + if slices.Contains(it.Modifiers, modUnauthorized) { + it.UnauthorizedStep, it.Unauthorized = stageTrackerUnauthorized(it.Reason) + } it.History = stageTrackerHistory(rec) } seen := map[string]bool{} diff --git a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go index 47c126904d..9d3ac06197 100644 --- a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go +++ b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go @@ -32,14 +32,17 @@ func stageTrackerSentinelJS(t *testing.T, html string) string { } // stageTrackerManualMergeJS is the 090 manual-merge surface (the stage -// number, the word and its builder) every harness that runs -// stageTrackerSegments needs beside the sentinel one. +// number, the word and its builder) and the 085 unauthorized one every +// harness that runs stageTrackerSegments needs beside the sentinel one. func stageTrackerManualMergeJS(t *testing.T, html string) string { t.Helper() return strings.Join([]string{ jsConstLine(t, html, "STAGE_TRACKER_READY_FOR_HUMAN_MERGE"), jsConstLine(t, html, "STAGE_TRACKER_MANUAL_MERGE_WORD"), jsFunc(t, html, "stageTrackerManualMergeWord"), + jsConstLine(t, html, "STAGE_TRACKER_HUMAN_GATED"), + jsConstLine(t, html, "STAGE_TRACKER_UNAUTHORIZED_WORD"), + jsFunc(t, html, "stageTrackerUnauthorizedWord"), }, "\n") } diff --git a/src/pkg/dashboard/stage_tracker_unauthorized_test.go b/src/pkg/dashboard/stage_tracker_unauthorized_test.go new file mode 100644 index 0000000000..eb034c4403 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_unauthorized_test.go @@ -0,0 +1,140 @@ +package dashboard + +import ( + "encoding/json" + "os/exec" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine/prstage" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hive:unauthorized — the hive's GitHub App lacks the permission for the +// item's next step (hivecommons/hive#14589) — is a tracker modifier like +// hold: it rides the label, outranks the needs-* chips and counts under +// Needs attention, since only a person can clear it. +func TestStageTrackerModifiers_Unauthorized(t *testing.T) { + got := stageTrackerModifiers([]string{stagelabels.UnauthorizedLabel, "needs-human", "bug"}, "hv", stagelabels.Record{}, false, nil, time.Now(), false) + if len(got) != 2 || got[0] != modUnauthorized || got[1] != modNeedsHuman { + t.Fatalf("modifiers = %v, want [%s %s]", got, modUnauthorized, modNeedsHuman) + } + if got := stageTrackerModifiers([]string{"hold", stagelabels.UnauthorizedLabel}, "hv", stagelabels.Record{}, false, nil, time.Now(), false); len(got) != 2 || got[0] != modHold || got[1] != modUnauthorized { + t.Fatalf("hold (a human instruction) must lead: %v", got) + } +} + +func TestStageTrackerUnauthorizedFromReason(t *testing.T) { + approve := prstage.StageReasonUnauthorizedPrefix + prstage.UnauthorizedStepApproveWorkflowRuns + for _, tc := range []struct { + name, reason, wantStep, wantTip string + }{ + {name: "approve workflow runs", reason: approve, wantStep: "approve workflow runs", wantTip: "`actions: write`"}, + {name: "human-approved suffix is stripped", reason: approve + ":human-approved@pat", wantStep: "approve workflow runs", wantTip: "Approve and run"}, + {name: "another step", reason: prstage.StageReasonUnauthorizedPrefix + "update-branch", wantStep: "update branch", wantTip: "permission to update branch"}, + {name: "label without a reason", reason: "contributor-lane:soaking(1h)", wantTip: "lacks a permission for the next step"}, + {name: "empty", reason: "", wantTip: "lacks a permission for the next step"}, + } { + t.Run(tc.name, func(t *testing.T) { + step, tip := stageTrackerUnauthorized(tc.reason) + if step != tc.wantStep || !strings.Contains(tip, tc.wantTip) || !strings.Contains(tip, "hive:unauthorized") { + t.Fatalf("stageTrackerUnauthorized(%q) = %q, %q; want step %q tip containing %q", tc.reason, step, tip, tc.wantStep, tc.wantTip) + } + }) + } + if got := humanizeStageReason(approve); !strings.Contains(got, "not permitted to approve workflow runs") { + t.Fatalf("humanizeStageReason = %q", got) + } +} + +// End to end through the payload: a PR parked on 085 by +// `unauthorized:approve-workflow-runs` and wearing hive:unauthorized carries +// the modifier, the step words for the gate cell, the tooltip, and a caption +// naming what the App may not do; a PR without the label carries none. +func TestStageTrackerUnauthorizedPayload(t *testing.T) { + now := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC) + s, store := stageTrackerFixture(t, now) + store.Observe(stagelabels.Key("acme/console", 130), stagelabels.NeedsDecision, prstage.StageReasonUnauthorizedPrefix+prstage.UnauthorizedStepApproveWorkflowRuns) + s.statusMu.Lock() + s.status.Repos[0].OpenPrs = append(s.status.Repos[0].OpenPrs, + FrontendPR{PullRequest: github.PullRequest{Number: 130, Title: "Audit deps", Author: "pat", Labels: []string{stagelabels.NeedsDecision.Label(), stagelabels.UnauthorizedLabel}}}) + s.statusMu.Unlock() + resp := s.buildStageTracker(s.status, store, now) + it := trackerItem(t, resp, "pr", 130) + if it.Stage != 85 || !hasMod(it, modUnauthorized) || it.UnauthorizedStep != "approve workflow runs" || !strings.Contains(it.Unauthorized, "`actions: write`") { + t.Fatalf("row = stage %d mods %v step %q tip %q", it.Stage, it.Modifiers, it.UnauthorizedStep, it.Unauthorized) + } + if !strings.Contains(it.Caption, "not permitted to approve workflow runs") || it.Actor != "maintainer" { + t.Fatalf("caption %q actor %q", it.Caption, it.Actor) + } + raw, err := json.Marshal(it) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"unauthorized_step":"approve workflow runs"`) || !strings.Contains(string(raw), `"unauthorized":"The hive's GitHub App lacks`) { + t.Fatalf("payload lacks the unauthorized fields: %s", raw) + } + if clean := trackerItem(t, resp, "pr", 101); clean.UnauthorizedStep != "" || clean.Unauthorized != "" || hasMod(clean, modUnauthorized) { + t.Fatalf("PR 101 must not carry unauthorized fields: %+v", clean) + } +} + +// The frontend: the pill is muted and explains itself on hover, it counts +// under Needs attention, and the 085 chevron reads "Awaiting human: ". +func TestStageTrackerUnauthorizedJS(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + ".ham-badge-mod.ham-mod-unauthorized { color: var(--text-muted);", + "'hold', 'unauthorized', 'needs-human'", + } { + if !strings.Contains(html, want) { + t.Fatalf("index.html lacks %q", want) + } + } + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not on PATH — unauthorized pill was NOT executed by this run") + } + script := strings.Join([]string{ + "const assert = require('assert');", + "var _stageTracker = { stages: [{ number: 85, short: 'Needs decision' }] };", + "function agentNowClockTime(ms, nowMs) { return 'T' + ms; }", + "function esc(s) { return String(s).replace(/&/g, '&').replace(/unauthorized<'), pill); +assert.ok(pill.includes('title="' + esc(tip) + '"'), pill); +assert.ok(STAGE_TRACKER_HUMAN_MODS.includes('unauthorized') && STAGE_TRACKER_MOTION_HUMAN_MODS.includes('unauthorized')); +assert.ok(stageTrackerNeedsAttention(item)); +// unauthorized outranks the needs-* chips but yields to hold, a human instruction. +assert.ok(stageTrackerChipsHtml({ stage: 85, modifiers: ['needs-decision', 'unauthorized'] }).includes('>unauthorized +1<')); +assert.ok(stageTrackerChipsHtml({ stage: 10, modifiers: ['unauthorized', 'hold'] }).includes('>hold +1<')); +// The 085 chevron names the human step owed; without a step the generic word stays. +assert.strictEqual(stageTrackerUnauthorizedWord(item), 'Awaiting human: approve workflow runs'); +assert.strictEqual(stageTrackerUnauthorizedWord({ stage: 85, modifiers: ['unauthorized'] }), ''); +assert.strictEqual(STAGE_TRACKER_HUMAN_GATED, 85); +` + out, err := exec.Command(node, "-e", script).CombinedOutput() + if err != nil { + t.Fatalf("node: %v\n%s", err, out) + } +} diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index a8bdc6aaba..04ebb7d554 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1460,6 +1460,8 @@ /* A regression the hive is already working through: muted, never red. */ .ham-badge-mod.ham-mod-regressed.ham-mod-handled { color: var(--text-muted); border-color: var(--line-subtle); border-style: dashed; } .ham-badge-mod.ham-mod-needs-triage { color: var(--amber); border-color: color-mix(in srgb, var(--amber) 45%, transparent); } + /* hive:unauthorized — the App lacks a permission for the next step; muted, never red: a person must take the step. */ + .ham-badge-mod.ham-mod-unauthorized { color: var(--text-muted); border-color: var(--line-subtle); border-style: dashed; } .ham-badge-mod.ham-mod-possible-dupe { color: var(--purple); border-color: color-mix(in srgb, var(--purple) 45%, transparent); } /* Sentinel-flagged PR, #13535 follow-up: the chip beside needs rebase / regressed, and the human-decision chevron itself when its word @@ -13702,6 +13704,16 @@

Where to get help

const approver = String((item && item.human_approver) || '').trim(); return STAGE_TRACKER_MANUAL_MERGE_WORD + (approver ? ' · approved by @' + approver : ''); } + // 085 under hive:unauthorized (payload unauthorized_step, e.g. "approve + // workflow runs"): the hive's GitHub App lacks the permission for that + // step, so the lit chevron names the human step owed instead of the + // generic "Needs human decision" (hivecommons/hive#14589). + const STAGE_TRACKER_HUMAN_GATED = 85; + const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Awaiting human'; + function stageTrackerUnauthorizedWord(item) { + const step = String((item && item.unauthorized_step) || '').trim(); + return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ': ' + step : ''; + } // Issue-slot placeholders for a closing reference whose title the server // could not resolve (the issue is closed and unreadable, or of unknown state). const STAGE_TRACKER_CLOSED_ISSUE_TITLE = '(closed issue)'; @@ -13757,7 +13769,7 @@

Where to get help

50: STAGE_TRACKER_MOTION_ACTIVE, 60: STAGE_TRACKER_MOTION_ACTIVE, 70: STAGE_TRACKER_MOTION_ACTIVE, 74: STAGE_TRACKER_MOTION_ACTIVE, 80: STAGE_TRACKER_MOTION_ACTIVE, 95: STAGE_TRACKER_MOTION_ACTIVE, 100: STAGE_TRACKER_MOTION_ACTIVE, }; const STAGE_TRACKER_MOTION_AUTHOR_STAGES = [30, 40]; - const STAGE_TRACKER_MOTION_HUMAN_MODS = ['stalled', 'blocked', 'needs-human', 'needs-decision', 'needs-triage']; + const STAGE_TRACKER_MOTION_HUMAN_MODS = ['stalled', 'blocked', 'needs-human', 'needs-decision', 'needs-triage', 'unauthorized']; function stageTrackerMotion(item) { const mods = Array.isArray(item && item.modifiers) ? item.modifiers : []; if (mods.indexOf('hold') >= 0) return STAGE_TRACKER_MOTION_STATIC; @@ -13943,7 +13955,7 @@

Where to get help

const terminal = anchor >= STAGE_TRACKER_TERMINAL; const sentinelLane = stageTrackerSentinelInLane(item); const detour = (!terminal && STAGE_TRACKER_PATH.indexOf(cur) < 0 && cur !== STAGE_TRACKER_TRIAGE_NEEDED && cur !== STAGE_TRACKER_POSSIBLY_EXISTS && cur !== 40 && cur !== 60 && cur !== STAGE_TRACKER_PRE_MERGE_SOAK && cur !== 100) - ? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null; + ? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null; const segs = STAGE_TRACKER_PATH.map(n => { const st = n === 0 ? { label: 'Open', short: 'Open', description: 'Open, not yet in a stage' } : (byNum[n] || {}); let state = 'todo'; @@ -13972,7 +13984,7 @@

Where to get help

return segs; } - const STAGE_TRACKER_MOD_PRIORITY = ['stalled', 'regressed', 'hold', 'needs-human', 'needs-decision', 'needs-triage', 'possible-dupe', 'needs-rebase', 'blocked', 'draft']; + const STAGE_TRACKER_MOD_PRIORITY = ['stalled', 'regressed', 'hold', 'unauthorized', 'needs-human', 'needs-decision', 'needs-triage', 'possible-dupe', 'needs-rebase', 'blocked', 'draft']; const STAGE_TRACKER_MOD_TEXT = { 'needs-decision': 'needs human decision', 'needs-triage': 'triage needed', 'possible-dupe': 'possible dupe' }; // 16-unit monochrome stroke icons, one per strip column (and the two kinds). const STAGE_TRACKER_ICONS = { @@ -14119,7 +14131,7 @@

Where to get help

// Modifiers that park an item on a person. A regression on a row that // carries none of these and sits on a hive-driven stage is the hive's // to work through, so the dashboard must not dress it as a human call. - const STAGE_TRACKER_HUMAN_MODS = ['hold', 'needs-human', 'needs-decision', 'needs-rebase', 'blocked', 'stalled']; + const STAGE_TRACKER_HUMAN_MODS = ['hold', 'unauthorized', 'needs-human', 'needs-decision', 'needs-rebase', 'blocked', 'stalled']; const STAGE_TRACKER_HANDLED_TEXT = 'stage ↓'; const STAGE_TRACKER_HANDLED_NOTE = 'the hive is handling it — no action needed; clears on the next forward step'; @@ -14173,6 +14185,7 @@

Where to get help

if (item.sentinel_alert) lines.push(stageTrackerSentinelTip(item)); 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 (sinceMs) lines.push('Since ' + agentNowClockTime(sinceMs, nowMs) + ' · ' + agentNowAgo(nowMs - sinceMs)); if (trail) lines.push('Trail: ' + trail); return lines.filter(Boolean).join('\n'); @@ -14201,8 +14214,10 @@

Where to get help

if (!isNaN(recheckMs)) text += ' · re-check at ' + agentNowClockTime(recheckMs, Date.now()); // The regressed pill (lead or folded into "+1") explains itself on hover. const regressed = stageTrackerRegressionText(item, Date.now()); + // An unauthorized pill names the missing App permission and the human step. + const tip = (mods.indexOf('unauthorized') >= 0 && String(item.unauthorized || '').trim()) || regressed; const cls = 'ham-mod-' + mods[0] + (handled && mods[0] === 'regressed' ? ' ham-mod-handled' : ''); - return sentinel + `${esc(text)}${mods.length > 1 ? ' +' + (mods.length - 1) : ''}`; + return sentinel + `${esc(text)}${mods.length > 1 ? ' +' + (mods.length - 1) : ''}`; } // Ghost strip for a title line: the lead cell (Open..Claimed) carries diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index a014602a94..7119193994 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -879,6 +879,11 @@ func (c *Engine) closeSupersededOriginal(ctx context.Context, store *stagelabels store.MarkSuperseded(key, rec.AdoptedBy, true, now) if _, _, err := c.gh.PullRequests.Edit(ctx, obs.Owner, obs.Repo, obs.Number, &gh.PullRequest{State: gh.Ptr("closed")}); err != nil { if isGitHubStatus(err, http.StatusForbidden) || isGitHubStatus(err, http.StatusNotFound) { + // TODO(hivecommons/hive#14589): a 403 here may be the App + // lacking pull_requests: write on this repository, or an + // archived/locked PR; only the former is a markUnauthorized + // case. Route it through markUnauthorized once the cause is + // told apart (the note already asks a person to close it). c.warn("stage labels: cannot close superseded PR (permission); left open with the note, tracker row dropped", "repo", obs.Display, "pr", obs.Number, "superseded_by", rec.AdoptedBy, "error", err) return 1, nil } diff --git a/src/pkg/github/automerge/automerge_contributor_held_runs.go b/src/pkg/github/automerge/automerge_contributor_held_runs.go index b0ff8e57ad..f63ecafd43 100644 --- a/src/pkg/github/automerge/automerge_contributor_held_runs.go +++ b/src/pkg/github/automerge/automerge_contributor_held_runs.go @@ -42,26 +42,36 @@ const ( // registry path and the lane stopped at reason (`required-check-missing:`). // It refuses for any other admission path, when the toggle is off, when the // PR carries the sentinel or an exclude label, or when the diff touches CI -// definitions. It returns the run ids it approved (nil when it did nothing). -func (c *Engine) approveHeldRunsForRegistryTrusted(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, number int, headSHA string, claim contributorClaimMatch, policy ContributorLanePolicy, files []intent.ChangedFile, reason string) []int64 { +// definitions. It returns the run ids it approved (nil when it did nothing) +// and the lane reason to report: the input reason, or +// `unauthorized:approve-workflow-runs` while the App lacks `actions: write` +// for this head (hivecommons/hive#14589) — GitHub answers 403 "Resource not +// accessible by integration", the PR is marked via markUnauthorized, and the +// mark holds until the head's required checks exist or the head changes. +func (c *Engine) approveHeldRunsForRegistryTrusted(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, number int, headSHA string, claim contributorClaimMatch, policy ContributorLanePolicy, files []intent.ChangedFile, reason string) ([]int64, string) { if c == nil || c.gh == nil || pr == nil || headSHA == "" { - return nil + return nil, reason } if !policy.ApproveHeldRunsForRegistryTrusted || !claim.admittedByRegistry() { - return nil + return nil, reason } if !strings.HasPrefix(reason, requiredCheckMissingPrefix) { - return nil + return nil, reason } labels := labelNames(pr.Labels) if c.sentinelLabelPresent(labels) || policy.excludedLabel(labels) != "" || c.labelBlockReason(labels, false) != "" { - return nil + return nil, reason } if contributorLaneDiffReason(files) == contributorLaneReasonWorkflowPath { - return nil + return nil, reason } if c.contributorHeldRunsApprovalAttempted(owner, repo, number, headSHA) { - return nil + // Already tried this head; keep reporting the permission gap while + // it stands, without another API call or another log line. + if step := c.unauthorizedStep(owner, repo, number, headSHA); step == unauthorizedStepApproveWorkflowRuns { + return nil, unauthorizedReason(step) + } + return nil, reason } missing := strings.TrimPrefix(reason, requiredCheckMissingPrefix) runs, _, err := c.gh.Actions.ListRepositoryWorkflowRuns(hgithub.WithRESTCaller(ctx, "hive:contributor_lane_automerge_sweep"), owner, repo, &gh.ListWorkflowRunsOptions{ @@ -71,35 +81,43 @@ func (c *Engine) approveHeldRunsForRegistryTrusted(ctx context.Context, displayR }) if err != nil || runs == nil { c.warn("contributor-lane could not list workflow runs for held-run approval", "repo", displayRepo, "pr", number, "head", headSHA, "error", err) - return nil + return nil, reason } held := heldWorkflowRunsForHead(runs.WorkflowRuns, contributorLaneHeadRepo(pr, owner, repo)) if len(held) == 0 { - return nil + return nil, reason } // Mark before calling the API: a partial failure must not be retried // every tick against the same head. if !c.markContributorHeldRunsApprovalAttempted(owner, repo, number, headSHA) { - return nil + return nil, reason } author := hgithub.SafeGetLogin(pr.GetUser()) - var approved []int64 + var approved, forbidden []int64 for _, run := range held { if err := c.approveWorkflowRun(ctx, owner, repo, run.GetID()); err != nil { + if isResourceNotAccessible(err) { + forbidden = append(forbidden, run.GetID()) + continue + } c.warn("contributor-lane could not approve held workflow run", "repo", displayRepo, "pr", number, "head", headSHA, "author", author, "tier", claim.RegistryTier, "run_id", run.GetID(), "workflow", run.GetName(), "context", missing, "error", err) continue } approved = append(approved, run.GetID()) } + if len(forbidden) > 0 && len(approved) == 0 { + sort.Slice(forbidden, func(i, j int) bool { return forbidden[i] < forbidden[j] }) + return nil, c.markUnauthorized(ctx, displayRepo, owner, repo, pr, number, headSHA, unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, approveWorkflowRunsHumanAction(owner, repo, missing, forbidden)) + } if len(approved) == 0 { - return nil + return nil, reason } sort.Slice(approved, func(i, j int) bool { return approved[i] < approved[j] }) c.info("contributor-lane approved held runs", "repo", displayRepo, "pr", number, "head", headSHA, "author", author, "tier", claim.RegistryTier, "run_ids", approved, "context", missing) if err := c.commentContributorHeldRunsApproved(ctx, owner, repo, number, headSHA, author, claim.RegistryTier, approved); err != nil { c.warn("contributor-lane held-run approval audit comment failed", "repo", displayRepo, "pr", number, "head", headSHA, "error", err) } - return approved + return approved, reason } // approveWorkflowRun is POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve. diff --git a/src/pkg/github/automerge/automerge_contributor_held_runs_test.go b/src/pkg/github/automerge/automerge_contributor_held_runs_test.go index 130555146f..a509af3477 100644 --- a/src/pkg/github/automerge/automerge_contributor_held_runs_test.go +++ b/src/pkg/github/automerge/automerge_contributor_held_runs_test.go @@ -7,7 +7,11 @@ package automerge import ( "context" + "errors" + "fmt" "net/http" + "net/url" + "slices" "strings" "testing" "time" @@ -107,9 +111,11 @@ func TestContributorLaneApprovesHeldRunsForRegistryTrusted(t *testing.T) { wantReason: wantReason, }, { - name: "approve forbidden logs and posts no comment", + // A non-403 approve failure is logged and otherwise changes nothing + // (the unauthorized path is TestContributorLaneUnauthorizedWhenApproveForbidden). + name: "approve server error posts no comment and sets no label", registry: registryTrusted, - mutate: func(fx *contributorLaneFixture) { noMarker(fx); fx.approveStatus = http.StatusForbidden }, + mutate: func(fx *contributorLaneFixture) { noMarker(fx); fx.approveStatus = http.StatusInternalServerError }, wantReason: wantReason, wantApproved: []int64{11, 12}, }, @@ -168,6 +174,9 @@ func TestContributorLaneApprovesHeldRunsForRegistryTrusted(t *testing.T) { if fx.comments != tc.wantComments { t.Fatalf("comments = %d, want %d last=%q", fx.comments, tc.wantComments, fx.lastComment) } + if len(fx.labelsAdded) != 0 || len(fx.labelsRemoved) != 0 { + t.Fatalf("label writes added=%v removed=%v, want none", fx.labelsAdded, fx.labelsRemoved) + } if len(tc.wantApproved) > 0 && tc.wantComments > 0 { wantMarker := contributorHeldRunsApprovedMarkerPrefix + " head=sha7 author=" + contributorLaneTestAuthor + " tier=trusted runs=11,12 -->" if !strings.HasPrefix(fx.lastComment, wantMarker) || !strings.Contains(fx.lastComment, "registry-trusted at tier `trusted`") { @@ -246,3 +255,152 @@ func TestContributorLaneHeadRepoFallsBackToBase(t *testing.T) { t.Fatalf("head repo = %q, want fork", got) } } + +// TestContributorLaneUnauthorizedWhenApproveForbidden pins the +// hive:unauthorized signal (hivecommons/hive#14589): a 403 "Resource not +// accessible by integration" on held-run approval marks the lane +// unauthorized once per head — label + one marker comment + reason +// `unauthorized:approve-workflow-runs` — repeats without a duplicate on the +// next tick, and clears label and state in the tick the required check +// reports. +func TestContributorLaneUnauthorizedWhenApproveForbidden(t *testing.T) { + wantReason := unauthorizedReasonPrefix + unauthorizedStepApproveWorkflowRuns + wantMarker := unauthorizedMarker("sha7", unauthorizedStepApproveWorkflowRuns) + for _, tc := range []struct { + name string + // labelled pre-seeds hive:unauthorized and the marker comment on + // the PR, as a restarted hive sees them. + labelled bool + }{ + {name: "fresh head marks once then clears"}, + {name: "restart sees label and marker and re-posts nothing", labelled: true}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := validContributorFixture() + fx.baseRef = "main" + fx.body = "Part of #42\n\nSome change." + fx.issueComments = nil + fx.requiredContexts = []string{"ci/build", contributorHeldRunsTestContext} + fx.workflowRuns = []map[string]any{heldRun(11, "acme/widget"), heldRun(12, "acme/widget")} + fx.approveStatus = http.StatusForbidden + if tc.labelled { + fx.labels = []string{unauthorizedLabel} + fx.prComments = []map[string]any{{ + "id": 5, + "user": map[string]string{"login": testHiveAppBotLogin}, + "body": unauthorizedComment("sha7", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, "do it"), + }} + } + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.RegistryTiersSufficient = true + policy.ApproveHeldRunsForRegistryTrusted = true + clock := &contributorLaneClock{at: time.Date(2026, 10, 27, 13, 0, 0, 0, time.UTC)} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorRegistryTier: registryTiers(map[string]string{contributorLaneTestAuthor: "trusted"}), ContributorSoak: soakedTracker(clock)}) + + for tick := 1; tick <= 2; tick++ { + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatalf("tick %d err = %v", tick, err) + } + if reason != wantReason { + t.Fatalf("tick %d reason = %q, want %q", tick, reason, wantReason) + } + } + if got := fx.approvedRuns; len(got) != 2 || got[0] != 11 || got[1] != 12 { + t.Fatalf("approve attempts = %v, want [11 12] once across two ticks", got) + } + wantAdds, wantComments := 1, 1 + if tc.labelled { + wantAdds, wantComments = 0, 0 + } + if len(fx.labelsAdded) != wantAdds || (wantAdds == 1 && fx.labelsAdded[0] != unauthorizedLabel) { + t.Fatalf("labels added = %v, want %d × %q", fx.labelsAdded, wantAdds, unauthorizedLabel) + } + if fx.labelsCreated > 1 { + t.Fatalf("label definition created %d times, want at most once", fx.labelsCreated) + } + if fx.comments != wantComments { + t.Fatalf("comments = %d, want %d last=%q", fx.comments, wantComments, fx.lastComment) + } + if wantComments == 1 { + if !strings.HasPrefix(fx.lastComment, wantMarker) || !strings.Contains(fx.lastComment, "`"+unauthorizedPermissionActionsWrite+"`") || + !strings.Contains(fx.lastComment, "Approve and run") || !strings.Contains(fx.lastComment, "11, 12") || !strings.Contains(fx.lastComment, contributorHeldRunsTestContext) { + t.Fatalf("comment = %q, want marker %q naming the permission, the button, the runs and the missing check", fx.lastComment, wantMarker) + } + } + if !slices.Contains(fx.labels, unauthorizedLabel) || len(fx.labelsRemoved) != 0 { + t.Fatalf("labels = %v removed = %v, want %q still on while the check is missing", fx.labels, fx.labelsRemoved, unauthorizedLabel) + } + if step := engine.unauthorizedStep("acme", "widget", 7, "sha7"); step != unauthorizedStepApproveWorkflowRuns { + t.Fatalf("unauthorizedStep = %q, want %q", step, unauthorizedStepApproveWorkflowRuns) + } + + // The maintainer clicked Approve and run: the held check reports, + // the required set is satisfied, and the same tick clears the signal. + fx.requiredContexts = []string{"ci/build"} + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatalf("clear tick err = %v", err) + } + if strings.HasPrefix(reason, unauthorizedReasonPrefix) { + t.Fatalf("clear tick reason = %q, want the lane past the unauthorized step", reason) + } + if len(fx.labelsRemoved) != 1 || fx.labelsRemoved[0] != unauthorizedLabel || slices.Contains(fx.labels, unauthorizedLabel) { + t.Fatalf("labels removed = %v labels = %v, want %q removed once", fx.labelsRemoved, fx.labels, unauthorizedLabel) + } + if step := engine.unauthorizedStep("acme", "widget", 7, "sha7"); step != "" { + t.Fatalf("unauthorizedStep after clear = %q, want empty", step) + } + if fx.comments != wantComments { + t.Fatalf("comments after clear = %d, want %d (no clear note)", fx.comments, wantComments) + } + }) + } +} + +func TestIsResourceNotAccessible(t *testing.T) { + mk := func(status int, msg string) error { + return &gh.ErrorResponse{Response: &http.Response{StatusCode: status, Request: &http.Request{Method: "POST", URL: &url.URL{Path: "/x"}}}, Message: msg} + } + for _, tc := range []struct { + name string + err error + want bool + }{ + {name: "nil", err: nil}, + {name: "plain error", err: errors.New("Resource not accessible by integration")}, + {name: "403 integration", err: mk(http.StatusForbidden, "Resource not accessible by integration"), want: true}, + {name: "403 integration wrapped", err: fmt.Errorf("approve: %w", mk(http.StatusForbidden, "resource not accessible by integration")), want: true}, + {name: "403 rate limit", err: mk(http.StatusForbidden, "API rate limit exceeded")}, + {name: "404", err: mk(http.StatusNotFound, "Resource not accessible by integration")}, + {name: "500", err: mk(http.StatusInternalServerError, "Resource not accessible by integration")}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := isResourceNotAccessible(tc.err); got != tc.want { + t.Fatalf("isResourceNotAccessible = %v, want %v", got, tc.want) + } + }) + } +} + +func TestUnauthorizedCommentAndMarker(t *testing.T) { + marker := unauthorizedMarker("E3E9F5CABCDEF1234567", unauthorizedStepApproveWorkflowRuns) + if marker != "" { + t.Fatalf("marker = %q", marker) + } + action := approveWorkflowRunsHumanAction("acme", "widget", "CI / Mutation (advisory)", []int64{40459320512, 40459320537}) + body := unauthorizedComment("e3e9f5cabcdef1234567", unauthorizedStepApproveWorkflowRuns, unauthorizedPermissionActionsWrite, action) + for _, want := range []string{marker, "`actions: write`", "approve workflow runs", "e3e9f5cabcdef", "Approve and run", "40459320512, 40459320537", "CI / Mutation (advisory)", "Actions tab of acme/widget"} { + if !strings.Contains(body, want) { + t.Fatalf("comment lacks %q:\n%s", want, body) + } + } + if !strings.HasPrefix(body, marker+"\n") { + t.Fatalf("comment must start with the marker line:\n%s", body) + } + if got := unauthorizedReason(unauthorizedStepApproveWorkflowRuns); got != "unauthorized:approve-workflow-runs" { + t.Fatalf("reason = %q", got) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index c830945d50..907d93b8d7 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -1254,10 +1254,17 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own } if !green { if strings.HasPrefix(reason, requiredCheckMissingPrefix) { - c.approveHeldRunsForRegistryTrusted(ctx, displayRepo, owner, repo, pr, number, headSHA, claim, policy, files, reason) + _, reason = c.approveHeldRunsForRegistryTrusted(ctx, displayRepo, owner, repo, pr, number, headSHA, claim, policy, files, reason) + } + if !strings.HasPrefix(reason, unauthorizedReasonPrefix) { + // The required check exists now (pending or red), or the head + // moved on: whoever approved the runs did the step, so the + // unauthorized mark comes off in this same tick (#14589). + c.clearUnauthorized(ctx, displayRepo, owner, repo, pr, number, unauthorizedStepApproveWorkflowRuns) } return eval, reason, nil } + c.clearUnauthorized(ctx, displayRepo, owner, repo, pr, number, unauthorizedStepApproveWorkflowRuns) if !verdict.Configured { return eval, contributorLaneReasonNoReviewer, nil } diff --git a/src/pkg/github/automerge/automerge_contributor_lane_test.go b/src/pkg/github/automerge/automerge_contributor_lane_test.go index 65d4eec226..0cb1993408 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane_test.go +++ b/src/pkg/github/automerge/automerge_contributor_lane_test.go @@ -11,6 +11,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" "strconv" "strings" "testing" @@ -120,6 +121,12 @@ type contributorLaneFixture struct { commitLists int // mergeBody is the JSON body of the last PUT pulls/7/merge. mergeBody map[string]any + // labelsCreated counts POST labels (repo label definitions); + // labelsAdded / labelsRemoved record issue label writes on PR 7. An + // added label joins fx.labels so later ticks see it on the PR. + labelsCreated int + labelsAdded []string + labelsRemoved []string } func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.Server { @@ -350,6 +357,25 @@ func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.S case r.Method == http.MethodPut && r.URL.Path == "/repos/acme/widget/pulls/7/update-branch": fx.updates++ json.NewEncoder(w).Encode(map[string]any{"message": "Updating pull request branch."}) + case r.Method == http.MethodPost && r.URL.Path == "/repos/acme/widget/labels": + fx.labelsCreated++ + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(map[string]any{"name": "created"}) + case r.Method == http.MethodPost && r.URL.Path == "/repos/acme/widget/issues/7/labels": + var names []string + _ = json.NewDecoder(r.Body).Decode(&names) + for _, n := range names { + fx.labelsAdded = append(fx.labelsAdded, n) + if !slices.Contains(fx.labels, n) { + fx.labels = append(fx.labels, n) + } + } + json.NewEncoder(w).Encode([]any{}) + case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/repos/acme/widget/issues/7/labels/"): + name := strings.TrimPrefix(r.URL.Path, "/repos/acme/widget/issues/7/labels/") + fx.labelsRemoved = append(fx.labelsRemoved, name) + fx.labels = slices.DeleteFunc(slices.Clone(fx.labels), func(l string) bool { return l == name }) + w.WriteHeader(http.StatusOK) case r.Method == http.MethodPost && r.URL.Path == "/repos/acme/widget/issues/7/comments": fx.comments++ if fx.commentStatus != 0 { diff --git a/src/pkg/github/automerge/automerge_merge_forward.go b/src/pkg/github/automerge/automerge_merge_forward.go index 8762a7110a..575b27f916 100644 --- a/src/pkg/github/automerge/automerge_merge_forward.go +++ b/src/pkg/github/automerge/automerge_merge_forward.go @@ -113,6 +113,11 @@ func (c *Engine) mergeForwardOrConflict(ctx context.Context, displayRepo, owner, c.postMergeForwardConflictNote(ctx, displayRepo, owner, repo, number, hgithub.SafeGetLogin(pr.GetUser()), headSHA, baseRef, files) return AutoMergeSweepEvent{}, "conflicting", nil case status == http.StatusForbidden || status == http.StatusNotFound: + // TODO(hivecommons/hive#14589): a 403 on a same-repo branch is the + // App lacking contents: write (markUnauthorized, step + // merge-forward); on a fork head it is the fork's "allow edits by + // maintainers" setting, which no App permission cures. Left as a + // skip until the two are separated. c.info("automerge merge-forward skipped: branch not writable by the app", "repo", displayRepo, "pr", number, "status", status) return AutoMergeSweepEvent{}, "conflicting", nil } diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index 766d567a14..bfeda63b9f 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -259,6 +259,8 @@ func decisionCause(reason string) string { return "GitHub Actions is holding the workflow runs for approval and Hive cannot start them: `" + workflowApprovalCommand + "` on this repository belongs to Prow, which does not trust the Hive App. A maintainer must comment `" + workflowApprovalCommand + "` (and `/lgtm` + `/approve` for tide), or install `" + oktotest.WorkflowPath + "` (`hivectl ok-to-test-template`) so the repository GITHUB_TOKEN approves trusted same-repo bot runs on Hive's command." case strings.HasPrefix(reason, workflowApprovalWorkflowMissingPrefix): return "GitHub Actions is still waiting after Hive posted `" + workflowApprovalCommand + "`. Install the self-contained `" + oktotest.WorkflowPath + "` below (or render it with `hivectl ok-to-test-template`) so the repository GITHUB_TOKEN can approve trusted same-repo bot runs, or manually approve the runs from the PR checks banner." + case strings.HasPrefix(reason, unauthorizedReasonPrefix): + return "the hive's GitHub App is not permitted to " + strings.ReplaceAll(strings.TrimPrefix(reason, unauthorizedReasonPrefix), "-", " ") + " (GitHub answered 403 Resource not accessible by integration); the `" + unauthorizedLabel + "` note above names the permission and the step a maintainer must take" case strings.HasPrefix(reason, workflowApprovalRequiredPrefix): return "GitHub Actions is waiting for workflow approval. Hive posted `" + workflowApprovalCommand + "`; install `" + oktotest.WorkflowPath + "` (`hivectl ok-to-test-template`) if the runs do not start, or manually approve them from the PR checks banner." case reason == "approval-desk-withheld": diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index bad9269684..274e110888 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -247,6 +247,13 @@ type Engine struct { // terminalHoldsLogged remembers PR head+reason pairs already reported as a // terminal held/never-started hold so later ticks only count them. terminalHoldsLogged map[string]bool + // unauthorized remembers, per PR, the head and step this process marked + // `hive:unauthorized` for, so the same head logs once and the mark + // clears when the step is done; unauthorizedLabelReady remembers the + // repositories whose label is provisioned (automerge_unauthorized.go). + unauthorizedMu sync.Mutex + unauthorized map[string]unauthorizedState + unauthorizedLabelReady map[string]bool // mergeQueueBases remembers base branches whose ruleset refused a direct // merge as merge-queue-only, so the self-authored sweep stops re-issuing // a REST merge that cannot succeed (hivecommons/hive#14068). @@ -2297,6 +2304,11 @@ func classifyUpdateBranchError(err error, fork bool) updateBranchFailure { if fork { return updateBranchForkNotEditable } + // TODO(hivecommons/hive#14589): a same-repo 403 "Resource not + // accessible by integration" means the App lacks contents: write + // and should mark the lane unauthorized (step: update-branch); + // a rate-limit 403 must not. Wire through markUnauthorized once + // the two are told apart here (isResourceNotAccessible). case http.StatusUnprocessableEntity: switch { case strings.Contains(msg, "maintainer") || strings.Contains(msg, "permission") || strings.Contains(msg, "not authorized"): diff --git a/src/pkg/github/automerge/automerge_unauthorized.go b/src/pkg/github/automerge/automerge_unauthorized.go new file mode 100644 index 0000000000..6313cc1451 --- /dev/null +++ b/src/pkg/github/automerge/automerge_unauthorized.go @@ -0,0 +1,260 @@ +package automerge + +// Lanes the App is not permitted to advance (hivecommons/hive#14589). +// +// Some lane steps are App API calls the installation may lack the permission +// for: approving held workflow runs needs `actions: write`, which an operator +// may decline to grant. GitHub answers 403 "Resource not accessible by +// integration", the lane cannot take the step, and without this file the PR +// sits at its previous reason (`required-check-missing:`) looking like +// CI is merely slow while the sweep WARNs every tick. The owner's decision is +// to say so plainly instead of widening the App: the lane marks the PR +// `unauthorized` — label hive:unauthorized, one comment per head naming the +// missing permission and the exact human step, reason `unauthorized:` +// so the stage engine parks it at 085 and the tracker's pill column shows +// the word — and clears all of it in the same tick the step stops being +// needed. Every call site that hits such a 403 routes through +// markUnauthorized; clearUnauthorized runs where the lane observes the step +// is done (or no longer applies). + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/effects" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine/prstage" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +const ( + // unauthorizedLabel is the GitHub label the lane adds; it lives outside + // the stage/ family so the reconciler never strips it. + unauthorizedLabel = stagelabels.UnauthorizedLabel + // unauthorizedLabelColor / unauthorizedLabelDescription provision the + // label on first use so it does not appear in GitHub's random colour. + unauthorizedLabelColor = "6e7781" + unauthorizedLabelDescription = "The hive's GitHub App lacks the permission for the next step; a maintainer must take it (see the hive:unauthorized comment)" + // unauthorizedMarkerPrefix tags the one comment per head; the marker + // carries the head and the step so a new push, or a different blocked + // step, gets a fresh note while the same head never gets two. + unauthorizedMarkerPrefix = "" +} + +// unauthorizedComment is the comment body: the marker, then the permission +// the App lacks, the step it therefore cannot take, and what a person does. +func unauthorizedComment(headSHA, step, permission, humanAction string) string { + return fmt.Sprintf("%s\nThe hive's GitHub App lacks `%s`, so it cannot %s for head `%s`. %s Hive will resume automatically once the step is done; this label and note clear themselves.", + unauthorizedMarker(headSHA, step), permission, strings.ReplaceAll(step, "-", " "), shortSHA(headSHA), strings.TrimSpace(humanAction)) +} + +// commentUnauthorized posts the note once per (head, step): an existing +// marker on the PR, or a prior effects claim, suppresses it. +func (c *Engine) commentUnauthorized(ctx context.Context, owner, repo string, number int, headSHA, step, permission, humanAction string) error { + comments, err := c.listIssueComments(ctx, owner, repo, number) + if err != nil { + return err + } + marker := unauthorizedMarker(headSHA, step) + for _, comment := range comments { + if comment != nil && strings.HasPrefix(comment.GetBody(), marker) { + return nil + } + } + body := unauthorizedComment(headSHA, step, permission, humanAction) + _, err = effects.Execute(ctx, c.mutation, effects.Claim{ + Repo: owner + "/" + repo, + Kind: effects.KindIssueComment, + Target: strconv.Itoa(number), + Actor: "automerge", + Inputs: map[string]string{"head_sha": headSHA, "body": effects.StableDigest(marker)}, + }, func(ctx context.Context) (effects.Result, error) { + comment, _, apiErr := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) + if apiErr != nil { + return effects.Result{}, effects.NotApplied(apiErr) + } + c.noteOwnStageComment(owner, repo, number) + return effects.Result{Provenance: comment.GetHTMLURL()}, nil + }) + return err +} + +// approveWorkflowRunsHumanAction is the human step for held runs: the +// Actions tab's "Approve and run", with the run ids and the contexts they +// would produce. +func approveWorkflowRunsHumanAction(owner, repo, missingContext string, runIDs []int64) string { + ids := make([]string, 0, len(runIDs)) + for _, id := range runIDs { + ids = append(ids, strconv.FormatInt(id, 10)) + } + ctxNote := "" + if missingContext != "" { + ctxNote = " (required check `" + missingContext + "`)" + } + return fmt.Sprintf("A maintainer must click **Approve and run** on the PR's checks banner or the Actions tab of %s/%s%s — runs %s — or grant the App `%s` to let the hive do it.", + owner, repo, ctxNote, strings.Join(ids, ", "), unauthorizedPermissionActionsWrite) +} diff --git a/src/pkg/stageengine/derive_pr_classify.go b/src/pkg/stageengine/derive_pr_classify.go index 094b13c3ec..489c5741f5 100644 --- a/src/pkg/stageengine/derive_pr_classify.go +++ b/src/pkg/stageengine/derive_pr_classify.go @@ -65,6 +65,7 @@ const ( stageReasonSharedCIIncident = prstage.StageReasonSharedCIIncident trustedBotLaneSkipReason = prstage.TrustedBotLaneSkipReason workflowApprovalRequiredPrefix = prstage.WorkflowApprovalRequiredPrefix + stageReasonUnauthorizedPrefix = prstage.StageReasonUnauthorizedPrefix ) func normalizeContributorLaneVerdict(v ContributorLaneVerdict) ContributorLaneVerdict { @@ -318,6 +319,11 @@ func ClassifyStage(o stageObservation) stageVerdict { if strings.HasPrefix(reason, workflowApprovalRequiredPrefix) { return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: stageRankOwned, Human: true} } + if strings.HasPrefix(reason, stageReasonUnauthorizedPrefix) { + // The App lacks the permission the next step needs; only a person + // can take it (hivecommons/hive#14589). The reason keeps the step. + return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: stageRankOwned, Human: true} + } if strings.HasPrefix(reason, "excluded-label:") || stageNeedsHumanReasons[reason] { if HasLabelFold(o.Labels, "needs-rebase") { return stageVerdict{Stage: fixing, Rank: stageRankOwned} diff --git a/src/pkg/stageengine/derive_pr_unauthorized_test.go b/src/pkg/stageengine/derive_pr_unauthorized_test.go new file mode 100644 index 0000000000..c08b5be229 --- /dev/null +++ b/src/pkg/stageengine/derive_pr_unauthorized_test.go @@ -0,0 +1,38 @@ +package stageengine + +import ( + "testing" + + "github.com/hivecommons/hive/pkg/authorkind" + "github.com/hivecommons/hive/pkg/stageengine/prstage" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// A lane that reports `unauthorized:` — the hive's GitHub App lacks +// the permission the next step needs (hivecommons/hive#14589) — parks the +// PR at 085 with the step kept in the reason, so the entry comment and the +// tracker's gate cell can name the human step owed. +func TestClassifyStageUnauthorizedParksForMaintainer(t *testing.T) { + reason := prstage.StageReasonUnauthorizedPrefix + prstage.UnauthorizedStepApproveWorkflowRuns + cases := []struct { + name string + obs stageObservation + want stagelabels.Stage + human bool + }{ + {name: "contributor lane", obs: stageObservation{Lane: stageLaneContributor, HeadSHA: "sha", Reason: reason, AuthorKind: authorkind.Clanker}, want: stagelabels.NeedsDecision, human: true}, + {name: "contributor lane human author", obs: stageObservation{Lane: stageLaneContributor, HeadSHA: "sha", Reason: reason, AuthorKind: authorkind.Human}, want: stagelabels.NeedsDecision, human: true}, + {name: "other step", obs: stageObservation{Lane: stageLaneContributor, HeadSHA: "sha", Reason: prstage.StageReasonUnauthorizedPrefix + "update-branch", AuthorKind: authorkind.Clanker}, want: stagelabels.NeedsDecision, human: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := ClassifyStage(tc.obs) + if got.Stage != tc.want || got.Rank != stageRankOwned || got.Human != tc.human { + t.Fatalf("ClassifyStage=%+v want owned stage %v human=%v", got, tc.want, tc.human) + } + if got.Reason != "" && got.Reason != tc.obs.Reason { + t.Fatalf("ClassifyStage reason = %q, want the lane's %q kept", got.Reason, tc.obs.Reason) + } + }) + } +} diff --git a/src/pkg/stageengine/prstage/reasons.go b/src/pkg/stageengine/prstage/reasons.go index 0229eeeb9f..537a8f7d25 100644 --- a/src/pkg/stageengine/prstage/reasons.go +++ b/src/pkg/stageengine/prstage/reasons.go @@ -44,7 +44,16 @@ const ( StageReasonForkGuard = "fork-guard:" StageReasonOptionalCheckFailing = "optional-check-failing:" StageReasonSharedCIIncident = "shared-ci-incident:" - TrustedAuthorReasonAppAuthored = "trusted-author:app-authored" - TrustedBotLaneSkipReason = "trusted-bot-lane" - WorkflowApprovalRequiredPrefix = "workflow-approval-required:" + // StageReasonUnauthorizedPrefix: the lane's next step needs an API + // call the hive's GitHub App is not permitted to make (403 "Resource + // not accessible by integration"); the rest names the step + // (UnauthorizedStepApproveWorkflowRuns, …). A person must take the + // step; the lane parks at 085 (hivecommons/hive#14589). + StageReasonUnauthorizedPrefix = "unauthorized:" + // UnauthorizedStepApproveWorkflowRuns: approving held `action_required` + // workflow runs needs `actions: write`. + UnauthorizedStepApproveWorkflowRuns = "approve-workflow-runs" + TrustedAuthorReasonAppAuthored = "trusted-author:app-authored" + TrustedBotLaneSkipReason = "trusted-bot-lane" + WorkflowApprovalRequiredPrefix = "workflow-approval-required:" ) diff --git a/src/pkg/stagelabels/stagelabels.go b/src/pkg/stagelabels/stagelabels.go index c7b20e3315..446214c93b 100644 --- a/src/pkg/stagelabels/stagelabels.go +++ b/src/pkg/stagelabels/stagelabels.go @@ -137,6 +137,14 @@ const PartiallyAddressedLabel = "hive/partially-addressed" // StalledLabel is the health label; it coexists with the stage label. const StalledLabel = Prefix + "stalled" +// UnauthorizedLabel marks a PR (or issue) whose next step the hive cannot +// take because its GitHub App lacks the permission the API call needs +// (403 "Resource not accessible by integration"; hivecommons/hive#14589). +// The automerge lane adds it with a comment naming the permission and the +// human step, and removes it in the same tick the step stops being needed. +// It is deliberately outside Prefix so the stage reconciler never strips it. +const UnauthorizedLabel = "hive:unauthorized" + // RegressedLabel is the RETIRED backward-move marker (hivecommons/hive#12534). // It is no longer provisioned or emitted; being under Prefix it is Owned, so // Plan removes it from every item the reconciler touches. From 979278434ccd88f3d95a8ef8f8afb2792c1f3b50 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 27 Oct 2026 12:16:41 -0400 Subject: [PATCH 2/2] test: clear tick lets the lane post its own note Signed-off-by: Andy Anderson --- .../automerge/automerge_contributor_held_runs_test.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/pkg/github/automerge/automerge_contributor_held_runs_test.go b/src/pkg/github/automerge/automerge_contributor_held_runs_test.go index a509af3477..967918da3e 100644 --- a/src/pkg/github/automerge/automerge_contributor_held_runs_test.go +++ b/src/pkg/github/automerge/automerge_contributor_held_runs_test.go @@ -353,8 +353,15 @@ func TestContributorLaneUnauthorizedWhenApproveForbidden(t *testing.T) { if step := engine.unauthorizedStep("acme", "widget", 7, "sha7"); step != "" { t.Fatalf("unauthorizedStep after clear = %q, want empty", step) } - if fx.comments != wantComments { - t.Fatalf("comments after clear = %d, want %d (no clear note)", fx.comments, wantComments) + // The lane goes on (here: to the merge note); clearing posts no + // note of its own and never a second unauthorized one. + for _, body := range fx.allComments { + if strings.HasPrefix(body, unauthorizedMarkerPrefix) && !strings.HasPrefix(body, wantMarker) { + t.Fatalf("unexpected unauthorized note after clear: %q", body) + } + } + if n := strings.Count(strings.Join(fx.allComments, "\n"), wantMarker); n != wantComments { + t.Fatalf("unauthorized notes posted = %d, want %d", n, wantComments) } }) }