diff --git a/changelog.d/changed-owner-approval-workflow-fence.md b/changelog.d/changed-owner-approval-workflow-fence.md new file mode 100644 index 0000000000..cb919e13d8 --- /dev/null +++ b/changelog.d/changed-owner-approval-workflow-fence.md @@ -0,0 +1 @@ +- Contributor-lane auto-merge: a hive owner / trusted merger's explicit approval on the current head — a GitHub `APPROVED` review on that commit, or a dashboard `/hive decision approve` bound to it — now releases the `contributor-lane:workflow-path` fence, so the hive merges an approved PR editing `.github/workflows/**` / `.github/actions/**` itself instead of parking it at `stage/090-ready-for-human-merge` (`auto_merge.contributor_lane.owner_approval_releases_workflow_fence`, default on). Approval on an older head does not count; a merge refused for want of the App's `workflows: write` marks the PR `hive:unauthorized` (`merge-workflow-path`) and parks the approved head at 090 as before. The 085 note for an unapproved workflow-path PR now reads "awaiting owner approval" (#14664). diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index 9a1289da40..12a0cc8422 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -80,17 +80,18 @@ func contributorLanePolicyFunc(cfg *config.Config) func() automerge.ContributorL p := cfg.AutoMerge.ContributorLane tier := cfg.AutoMerge.ContributorTier return automerge.ContributorLanePolicy{ - Enabled: p.IsEnabled(), - HiveID: cfg.HiveID, - Soak: time.Duration(p.EffectiveSoakMinutes()) * time.Minute, - RequireReviewerVerdict: p.EffectiveRequireReviewerVerdict(), - Repos: p.RepoSet(), - ExcludeLabels: p.ExcludeLabelSet(), - RequireTiers: p.RequireTierSet(), - RegistryTiersSufficient: p.EffectiveRegistryTiersSufficient(), - AutoPromoteAfterMergedPR: tier.EffectiveAutoPromoteAfterMerged(), - AutoPromotionScope: p.EffectiveAutoPromotionScope(), - ApproveHeldRunsForRegistryTrusted: p.EffectiveApproveHeldRunsForRegistryTrusted(), + Enabled: p.IsEnabled(), + HiveID: cfg.HiveID, + Soak: time.Duration(p.EffectiveSoakMinutes()) * time.Minute, + RequireReviewerVerdict: p.EffectiveRequireReviewerVerdict(), + Repos: p.RepoSet(), + ExcludeLabels: p.ExcludeLabelSet(), + RequireTiers: p.RequireTierSet(), + RegistryTiersSufficient: p.EffectiveRegistryTiersSufficient(), + AutoPromoteAfterMergedPR: tier.EffectiveAutoPromoteAfterMerged(), + AutoPromotionScope: p.EffectiveAutoPromotionScope(), + ApproveHeldRunsForRegistryTrusted: p.EffectiveApproveHeldRunsForRegistryTrusted(), + OwnerApprovalReleasesWorkflowFence: p.EffectiveOwnerApprovalReleasesWorkflowFence(), } } } diff --git a/src/docs/github-app-setup.md b/src/docs/github-app-setup.md index 000dffa68e..a41c09dae7 100644 --- a/src/docs/github-app-setup.md +++ b/src/docs/github-app-setup.md @@ -94,7 +94,7 @@ Repository permissions used by the dashboard setup UI are: | 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. | -| Workflows | Read/write | Let trusted-tier agents push branches that modify `.github/workflows/`. Without it GitHub rejects any GitHub App-token push touching those files server-side ("refusing to allow a GitHub App to create or update workflow … without workflows permission") no matter what the token requests. Maintainer user credentials are separate and can still push workflow-file changes when their account has the normal repository rights; the Hive App cannot until this grant is added **and re-accepted on each installation** (an existing install must approve the new permission under Settings → Integrations → the app → Review request). See [`hive-open-pr`](hive-open-pr.md#workflow-file-pushes-rejected-by-app-tokens) for the agent delivery procedure and [#6985](https://github.com/hivecommons/hive/issues/6985) for the outstanding permission change. | +| Workflows | Read/write | Let trusted-tier agents push branches that modify `.github/workflows/`, and let the contributor lane merge an owner-approved PR that edits `.github/workflows/**` (`auto_merge.contributor_lane.owner_approval_releases_workflow_fence`, [#14664](https://github.com/hivecommons/hive/issues/14664)); without the grant such a merge is refused and the hive marks the PR `hive:unauthorized` (`merge-workflow-path`) and parks it at 090 for a maintainer's **Merge** click. Without it GitHub also rejects any GitHub App-token push touching those files server-side ("refusing to allow a GitHub App to create or update workflow … without workflows permission") no matter what the token requests. Maintainer user credentials are separate and can still push workflow-file changes when their account has the normal repository rights; the Hive App cannot until this grant is added **and re-accepted on each installation** (an existing install must approve the new permission under Settings → Integrations → the app → Review request). See [`hive-open-pr`](hive-open-pr.md#workflow-file-pushes-rejected-by-app-tokens) for the agent delivery procedure and [#6985](https://github.com/hivecommons/hive/issues/6985) for the outstanding permission change. | Organization permission: | Permission | Level | Why | diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 6b2beb20da..c23f21333d 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -484,9 +484,29 @@ A PR merges through this tier only when all of the following hold: skipping every cycle (#12344; #12195, #12290). An unmarked, unregistered first-timer is still never admitted. - The diff does not touch `.github/workflows/**` or `.github/actions/**` - (`contributor-lane:workflow-path`) and does not delete a test file or remove - 25+ test lines while deleting at least 3× what it adds - (`contributor-lane:tests-removed`). + (`contributor-lane:workflow-path`) — **or** a hive owner / trusted merger + has explicitly approved the current head + (`owner_approval_releases_workflow_fence`, default `true`, + [#14664](https://github.com/hivecommons/hive/issues/14664)). Explicit + approval is a GitHub pull-request review in state `APPROVED` whose commit + is the current head by a login the hive's merger authorizer trusts (the + same bar that releases a `requires_human` verdict), or a dashboard + approval (`/hive decision approve`, which posts `/lgtm` + `/approve` + attributed to the maintainer and bound to the head) or a trusted merger's + own `/hive decision approve` comment posted after the head. Approval on an + earlier head never counts: a new push re-arms the fence and the 085 note + reads "awaiting owner approval … re-approve after a push". When released + the lane logs `workflow-path fence released by owner approval login=… + head=…`, leaves one `` audit + comment per head, and the PR goes through every other gate below like any + other. Merging such a PR needs the App's **Workflows: Read and write**; + when GitHub refuses the merge for want of it the lane marks the PR + `hive:unauthorized` (step `merge-workflow-path`), stops retrying that + head, and the approved head parks at `090-ready-for-human-merge` for a + person's **Merge** click as before. With the toggle off, or with no + approval, a workflow-path PR is never merged by the hive. +- The diff does not delete a test file or remove 25+ test lines while + deleting at least 3× what it adds (`contributor-lane:tests-removed`). - Required CI is green on the current head, using the same merge-CI gate as the App self-merge tier. - A reviewer agent is configured (otherwise `contributor-lane:no-reviewer`: @@ -533,6 +553,7 @@ auto_merge: registry_tiers_sufficient: true # a require_tiers tier on the author's registry profile admits without a claim marker auto_promotion_scope: hive # count clean merged PRs across every hive repo (repo = this repository only) approve_held_runs_for_registry_trusted: true # approve action_required runs once per head for registry-admitted authors + owner_approval_releases_workflow_fence: true # a trusted merger's approval on the current head lets the lane merge .github/workflows/** PRs contributor_tier: auto_promote_after_merged: 5 # clean merged PRs before the lane trusts an author on its own; negative disables ``` diff --git a/src/docs/labels-and-control-signals.md b/src/docs/labels-and-control-signals.md index 2055426d7e..500a1f1629 100644 --- a/src/docs/labels-and-control-signals.md +++ b/src/docs/labels-and-control-signals.md @@ -464,7 +464,7 @@ used to admit the PR: | CI red (required or optional) while **every** failing check on the head is also red on the base branch's tip — the governor's `base_red_checks` / `base_red`, set during CI enrichment when a same-named latest check run on the base ref (meta checks excluded) concluded failure / timed_out / cancelled / action_required / startup_failure / stale **and** the PR's changed files include none of `.github/workflows/*`, `Dockerfile` / `Dockerfile.*` / `*.Dockerfile`, `go.mod` / `go.sum` (a PR touching those plausibly owns the check and stays author-facing; a lookup error or a diff beyond the file-list page budget also stays author-facing) | `050-review-pending` / `060-reviewed`, reason `base-branch-red:,` ("waiting for the base branch's CI to recover (…) — not this PR's fault"): never 070/071/072, never nudged, never stalled, still not merged (the lane's skip reason is the same token). The fix loop counts no attempt, kicks no fixer, and posts one `` hold comment per head; an escalation the hive itself raised (ledger `label_applied`) over such a head has its `needs-human` removed with the hold wording. The next evaluation after the base goes green re-evaluates the head: a still-red PR is handed back as usual. Conflicts and requested changes stay author-facing (seen on [#13270](https://github.com/hivecommons/hive/pull/13270) and [#13258](https://github.com/hivecommons/hive/pull/13258), 2026-10-20) | | CI red (required or optional) on a **fork** PR while **every** failing check's annotation says the check refuses forks (case-insensitive `fork pull request(s) cannot`, `maintainer must push this branch`, or `cannot publish` together with `fork` — a fork-publication / fork-secrets guard) | `085-needs-decision`, reason `fork-guard:,`: never 070/071/072, never nudged, never adopted (074) — neither the author nor the hive can turn the check green by pushing to the fork. The entry comment names the check and says a maintainer must push the branch to the repository (or approve the run as the repository requires). A same-repo PR with the same message, or a fork PR with any other red check, is handed back as usual ([#14273](https://github.com/hivecommons/hive/issues/14273)) | | any **non-required** check on the current head is red, whatever the lane's reason (the lane gates on required checks only, so it still soaks and merges; a reader of the rollup sees ✗). Parking modifiers (`hold`, `needs-human`, admission reasons) still win | `070-fixing` / `071-needs-author` / `072-returned-to-contributor` (by author kind), reason `optional-check-failing:` (the nudge lists every red check); never 080 or 100. A red *required* check is the lane's own `required-check-failing:*` → 070/071/072 ([#12538](https://github.com/hivecommons/hive/issues/12538), seen on [#12457](https://github.com/hivecommons/hive/pull/12457)) | -| `label:hold`, `held`, `label:needs-human`, `exempt-label`, `excluded-label:*`, `sentinel`, `human-merge-path*`, `intent-*`, `contributor-lane:workflow-path` / `tests-removed` / `no-reviewer` / `reporter-trust-hold` | human hand-off, **decision** cause → routed by the head's evidence (below); lands at `085-needs-decision` when the head is otherwise clean | +| `label:hold`, `held`, `label:needs-human`, `exempt-label`, `excluded-label:*`, `sentinel`, `human-merge-path*`, `intent-*`, `contributor-lane:workflow-path` / `tests-removed` / `no-reviewer` / `reporter-trust-hold` | human hand-off, **decision** cause → routed by the head's evidence (below); lands at `085-needs-decision` when the head is otherwise clean. `contributor-lane:workflow-path` reads "awaiting owner approval": a trusted merger's `APPROVED` review on the current head (or a dashboard `/hive decision approve`) releases the fence and the lane merges the PR itself (`owner_approval_releases_workflow_fence`, [#14664](https://github.com/hivecommons/hive/issues/14664)); only with the toggle off, or when the App lacks `workflows: write` for the merge (`hive:unauthorized`, `merge-workflow-path`), does an approved head park at `090-ready-for-human-merge` for a person's click | | `merge-refused:review-required` (GitHub answered the merge with 405 "At least N approving review(s) is/are required by reviewers with write access"), `merge-refused:method-not-allowed` (405 "Merge commits / Squash merges / Rebase merges are not allowed on this repository") | human hand-off, **decision** cause, as above: lands at `085-needs-decision` when the head is otherwise clean, and the entry comment names the rule GitHub refused the merge on. Every sweep (self-authored, trusted-author, queued, contributor lane) logs these as skips, not `merge-failed` errors, and stops calling merge: a review refusal is remembered per PR head and re-armed when the head moves, when GitHub's `mergeable_state` for the PR changes (an approving review turns `blocked` into `clean`), or after 30 minutes; a method refusal is remembered per repository and method for 30 minutes. The hive never switches the merge method on its own (a forward merge or a `merge-method/merge` PR must not be squashed), so `method-not-allowed` is a manual-merge park. Any other 405, 409 or 422 is still `merge-failed` | | `contributor-lane:no-claim` / `claim-*` / `author-association` / `no-linked-issue`, `untrusted-author-role`, `author-permission-missing` | human hand-off, **trust** cause → routed by the head's evidence (below); lands at `090-ready-for-human-merge` when the head is otherwise clean | | hand-offs (`not-app-authored`, `trusted-bot-lane`, `trusted-author:app-authored`, `contributor-lane:app-authored`), transient fetch errors | no opinion — the owning lane decides; nothing is written. An App-authored PR is handed off by the trusted-author and contributor-lane tiers under their own reason; the self-authored lane owns it, and its `review-gate:no-review-bundle` is the stage's reason while the swarm has not reviewed the head ([#14482](https://github.com/hivecommons/hive/issues/14482)) | @@ -952,8 +952,10 @@ When a clanker-authored contributor PR goes red the hive does not just relabel i lane re-reads its diff on every pass, so the fix lane rebases and repairs CI on the PR's branch (074) and the green head lands at `stage/085-needs-decision` with "a maintainer must review and merge - this PR manually" — the lane never merges it, and the 085 note says - the hive adopted it to repair CI and why it still will not merge it. + this PR manually" — the lane does not merge it unattended, and the 085 + note says the hive adopted it to repair CI and why it still will not + merge it (for `workflow-path`, a trusted merger's approval on the + current head releases the fence, [#14664](https://github.com/hivecommons/hive/issues/14664)). - **supersede** (and the `dco-rehome`, `signoff-rehome` and `in-place-stalled` second takeovers): the App PR's body opens with `` diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 435d3ccf02..e1acb43881 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -446,6 +446,7 @@ advanced into the merge path. | `auto_merge.contributor_lane.auto_promotion_scope` | `hive` | Where the clean-merged-PR ratchet (`auto_merge.contributor_tier.auto_promote_after_merged`) counts an author's merges: `hive` counts across every repository the hive manages (one `search/issues` query finds the repos holding the author's merges; the PR's own repo is always walked first), `repo` counts only the PR's repository. Revert and sentinel-alert evidence blocks promotion in either scope. | | `auto_merge.contributor_tier.auto_promote_after_merged` | `5` | Clean merged PRs (no revert, no sentinel label, not undone by a later merged revert) after which the contributor lane treats an author as `trusted` without an operator grant, unless the registry marks them `revoked`. Negative disables the ratchet. | | `auto_merge.contributor_lane.approve_held_runs_for_registry_trusted` | `true` | When the registry path admitted the PR author and the lane stops at `required-check-missing:`, approve the head's `action_required` workflow runs once (`POST /repos/{owner}/{repo}/actions/runs/{id}/approve`, fork heads included), post one `hive:contributor-held-runs-approved` audit comment and log `contributor-lane approved held runs`. Never acts for claim-marker, auto-promoted or association admissions, sentinel/exclude-labelled PRs, or diffs touching `.github/workflows/**`. Needs the App's **Actions: Read and write** permission. See [hive-merge.md](hive-merge.md#contributor-lane-auto-merge). | +| `auto_merge.contributor_lane.owner_approval_releases_workflow_fence` | `true` | A hive owner / trusted merger's explicit approval on the **current** head — a GitHub `APPROVED` review on that commit, or a dashboard `/hive decision approve` bound to it — releases the contributor lane's `contributor-lane:workflow-path` fence, so the lane merges a PR editing `.github/workflows/**` / `.github/actions/**` itself once CI, soak and the other gates are clear. Logs `workflow-path fence released by owner approval`, leaves one `hive:workflow-approval` audit comment per head; approval on an older head does not count. Needs the App's **Workflows: Read and write**; without it the merge is refused, the PR is marked `hive:unauthorized` (`merge-workflow-path`) and parks at 090 for a person's click. `false` keeps every workflow-path PR a person's merge ([#14664](https://github.com/hivecommons/hive/issues/14664)). See [hive-merge.md](hive-merge.md#contributor-lane-auto-merge). | | `auto_merge.contributor_lane.repos` | empty = all watched repos | Optional repo allow-list for the contributor-lane tier (bare name or `owner/repo`). | | `auto_merge.contributor_lane.exclude_labels` | `hold`, `do-not-merge`, `needs-human`, `blocked`, `needs-rebase` | Labels that keep a PR out of contributor-lane auto-merge (`do-not-merge/*` always excluded). | diff --git a/src/pkg/config/automerge_trusted_bot_test.go b/src/pkg/config/automerge_trusted_bot_test.go index 7f29d30bf6..306c6f78ba 100644 --- a/src/pkg/config/automerge_trusted_bot_test.go +++ b/src/pkg/config/automerge_trusted_bot_test.go @@ -198,6 +198,21 @@ func TestContributorLaneAutoMergeConfigApproveHeldRunsForRegistryTrusted(t *test } } +// owner_approval_releases_workflow_fence defaults on so an owner-approved +// workflow-path PR is the hive's to merge; an explicit false keeps every +// workflow-path PR a person's merge (hivecommons/hive#14664). +func TestContributorLaneAutoMergeConfigOwnerApprovalReleasesWorkflowFence(t *testing.T) { + var cfg ContributorLaneAutoMergeConfig + if !cfg.EffectiveOwnerApprovalReleasesWorkflowFence() { + t.Fatal("owner_approval_releases_workflow_fence must default to true") + } + off := false + cfg.OwnerApprovalReleasesWorkflowFence = &off + if cfg.EffectiveOwnerApprovalReleasesWorkflowFence() { + t.Fatal("explicit owner_approval_releases_workflow_fence: false must keep the fence absolute") + } +} + func TestContributorTierAutoMergeConfigAutoPromoteDefault(t *testing.T) { var cfg ContributorTierAutoMergeConfig if got := cfg.EffectiveAutoPromoteAfterMerged(); got != DefaultContributorTierAutoPromoteAfterMerged { diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 24eb5b5947..a6af0979d7 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -7826,6 +7826,17 @@ type ContributorLaneAutoMergeConfig struct { // write permission; without it the approve call fails and the lane keeps // waiting for a person. ApproveHeldRunsForRegistryTrusted *bool `yaml:"approve_held_runs_for_registry_trusted,omitempty" json:"approve_held_runs_for_registry_trusted,omitempty"` + // OwnerApprovalReleasesWorkflowFence lets a hive owner / trusted + // merger's explicit approval on the current head — a GitHub APPROVED + // review, or a dashboard / `/hive decision approve` — release the + // contributor lane's workflow-path fence, so the lane merges a PR that + // edits `.github/workflows/**` or `.github/actions/**` itself once the + // other gates are clear (hivecommons/hive#14664). Approval on an earlier + // head does not count. nil/unset means ON. Merging such a PR needs the + // App's Workflows: Read and write permission; without it the lane marks + // the PR hive:unauthorized and parks it for a person's merge click. + // false keeps every workflow-path PR a person's merge. + OwnerApprovalReleasesWorkflowFence *bool `yaml:"owner_approval_releases_workflow_fence,omitempty" json:"owner_approval_releases_workflow_fence,omitempty"` } // Contributor-lane auto-promotion scopes @@ -7920,6 +7931,13 @@ func (c ContributorLaneAutoMergeConfig) EffectiveApproveHeldRunsForRegistryTrust return c.ApproveHeldRunsForRegistryTrusted == nil || *c.ApproveHeldRunsForRegistryTrusted } +// EffectiveOwnerApprovalReleasesWorkflowFence reports whether a trusted +// merger's explicit approval on the current head lets the contributor lane +// merge a workflow-path PR (default on). +func (c ContributorLaneAutoMergeConfig) EffectiveOwnerApprovalReleasesWorkflowFence() bool { + return c.OwnerApprovalReleasesWorkflowFence == nil || *c.OwnerApprovalReleasesWorkflowFence +} + func (c ContributorLaneAutoMergeConfig) RepoSet() map[string]bool { return repoListSet(c.Repos) } diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index ec40e2ae7d..45b2657a07 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -161,15 +161,16 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { ExcludeLabels []string `json:"exclude_labels"` } `json:"trusted_authors"` ContributorLane *struct { - Enabled *bool `json:"enabled"` - SoakMinutes *int `json:"soak_minutes"` - RequireReviewerVerdict *bool `json:"require_reviewer_verdict"` - Repos []string `json:"repos"` - ExcludeLabels []string `json:"exclude_labels"` - RequireTiers []string `json:"require_tiers"` - RegistryTiersSufficient *bool `json:"registry_tiers_sufficient"` - AutoPromotionScope *string `json:"auto_promotion_scope"` - ApproveHeldRunsForRegistryTrusted *bool `json:"approve_held_runs_for_registry_trusted"` + Enabled *bool `json:"enabled"` + SoakMinutes *int `json:"soak_minutes"` + RequireReviewerVerdict *bool `json:"require_reviewer_verdict"` + Repos []string `json:"repos"` + ExcludeLabels []string `json:"exclude_labels"` + RequireTiers []string `json:"require_tiers"` + RegistryTiersSufficient *bool `json:"registry_tiers_sufficient"` + AutoPromotionScope *string `json:"auto_promotion_scope"` + ApproveHeldRunsForRegistryTrusted *bool `json:"approve_held_runs_for_registry_trusted"` + OwnerApprovalReleasesWorkflowFence *bool `json:"owner_approval_releases_workflow_fence"` } `json:"contributor_lane"` } if err := decodeBody(r, &body); err != nil { @@ -327,6 +328,10 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { v := *body.ContributorLane.ApproveHeldRunsForRegistryTrusted cfg.AutoMerge.ContributorLane.ApproveHeldRunsForRegistryTrusted = &v } + if body.ContributorLane.OwnerApprovalReleasesWorkflowFence != nil { + v := *body.ContributorLane.OwnerApprovalReleasesWorkflowFence + cfg.AutoMerge.ContributorLane.OwnerApprovalReleasesWorkflowFence = &v + } if body.ContributorLane.Repos != nil { cfg.AutoMerge.ContributorLane.Repos = contributorLaneRepos } @@ -426,6 +431,7 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "auto_promotion_scopes": config.ContributorLaneAutoPromotionScopes, "grantable_tiers": config.ContributorLaneGrantableTiers, "approve_held_runs_for_registry_trusted": cl.EffectiveApproveHeldRunsForRegistryTrusted(), + "owner_approval_releases_workflow_fence": cl.EffectiveOwnerApprovalReleasesWorkflowFence(), }, } } diff --git a/src/pkg/dashboard/api_config_sections_test.go b/src/pkg/dashboard/api_config_sections_test.go index 046be585fb..f73813f5fd 100644 --- a/src/pkg/dashboard/api_config_sections_test.go +++ b/src/pkg/dashboard/api_config_sections_test.go @@ -642,6 +642,7 @@ func TestAutoMergeGet_ContributorLaneDefaults(t *testing.T) { AutoPromotionScope string `json:"auto_promotion_scope"` AutoPromotionScopes []string `json:"auto_promotion_scopes"` ApproveHeldRuns bool `json:"approve_held_runs_for_registry_trusted"` + OwnerApprovalWorkflow bool `json:"owner_approval_releases_workflow_fence"` GrantableTiers []string `json:"grantable_tiers"` } `json:"contributor_lane"` } @@ -655,7 +656,7 @@ func TestAutoMergeGet_ContributorLaneDefaults(t *testing.T) { if strings.Join(cl.GrantableTiers, ",") != strings.Join(config.ContributorLaneGrantableTiers, ",") { t.Fatalf("contributor_lane grantable_tiers = %v", cl.GrantableTiers) } - if !cl.Enabled || cl.SoakMinutes != config.DefaultContributorLaneSoakMinutes || !cl.RequireReviewerVerdict || !cl.RegistryTiers || !cl.ApproveHeldRuns || len(cl.Repos) != 0 { + if !cl.Enabled || cl.SoakMinutes != config.DefaultContributorLaneSoakMinutes || !cl.RequireReviewerVerdict || !cl.RegistryTiers || !cl.ApproveHeldRuns || !cl.OwnerApprovalWorkflow || len(cl.Repos) != 0 { t.Fatalf("contributor_lane defaults wrong: %+v", cl) } if cl.AutoPromotionScope != config.ContributorLaneAutoPromotionScopeHive || strings.Join(cl.AutoPromotionScopes, ",") != "hive,repo" { @@ -679,13 +680,14 @@ func TestAutoMergePut_ContributorLaneValidation(t *testing.T) { "require_tiers": []string{" merger "}, "auto_promotion_scope": " Repo ", "approve_held_runs_for_registry_trusted": false, + "owner_approval_releases_workflow_fence": false, }, } if rec := doPut(s, "/api/config/auto-merge", valid); rec.Code != http.StatusOK { t.Fatalf("valid contributor_lane: expected 200, got %d: %s", rec.Code, rec.Body.String()) } cl := s.deps.Config.AutoMerge.ContributorLane - if cl.IsEnabled() || cl.EffectiveSoakMinutes() != 30 || cl.EffectiveRequireReviewerVerdict() || cl.EffectiveRegistryTiersSufficient() || cl.EffectiveApproveHeldRunsForRegistryTrusted() { + if cl.IsEnabled() || cl.EffectiveSoakMinutes() != 30 || cl.EffectiveRequireReviewerVerdict() || cl.EffectiveRegistryTiersSufficient() || cl.EffectiveApproveHeldRunsForRegistryTrusted() || cl.EffectiveOwnerApprovalReleasesWorkflowFence() { t.Fatalf("contributor_lane write did not apply: %+v", cl) } if cl.AutoPromotionScope != config.ContributorLaneAutoPromotionScopeRepo { diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index c15ad57108..97dcdf7712 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -828,6 +828,7 @@ func unauthorizedStepWords(step string) string { 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." + stageTrackerUnauthorizedMergeWF = "The hive's GitHub App lacks `workflows: write`, so it cannot merge this owner-approved PR that edits .github/workflows files. A maintainer must click Merge on GitHub (the approval already stands), or grant the App Workflows: Read and write so the hive can merge such PRs itself." ) // stageTrackerUnauthorized derives the gate word and the tooltip for an @@ -842,6 +843,9 @@ func stageTrackerUnauthorized(reason string) (step, tip string) { if rest == stageengineprstage.UnauthorizedStepApproveWorkflowRuns { return step, stageTrackerUnauthorizedApproveRuns } + if rest == stageengineprstage.UnauthorizedStepMergeWorkflowPath { + return step, stageTrackerUnauthorizedMergeWF + } 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." } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 6e56af7eb6..9cec46ec31 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -49792,6 +49792,7 @@

${esc(s.title)}

const amContributorLaneVerdict = amContributorLane.require_reviewer_verdict !== false; const amContributorLaneRegistry = amContributorLane.registry_tiers_sufficient !== false; const amContributorLaneHeldRuns = amContributorLane.approve_held_runs_for_registry_trusted !== false; + const amContributorLaneWorkflowApproval = amContributorLane.owner_approval_releases_workflow_fence !== false; const amContributorLaneSoak = Number.isFinite(Number(amContributorLane.soak_minutes)) ? Number(amContributorLane.soak_minutes) : 30; const amContributorLaneLabels = Array.isArray(amContributorLane.exclude_labels) ? amContributorLane.exclude_labels : ['hold','do-not-merge','needs-human','blocked','needs-rebase']; const amContributorLaneTiers = Array.isArray(amContributorLane.require_tiers) && amContributorLane.require_tiers.length ? amContributorLane.require_tiers : ['merger','trusted']; @@ -49992,6 +49993,13 @@

${esc(s.title)}

Start CI held by GitHub's fork-approval policy ${settingHelpMark('hive-merge', 'contributor-lane-auto-merge', 'Start CI held by fork-approval policy', `GitHub holds a first-time contributor's pull_request runs until someone clicks Approve and run. If the operator already trusts the author to merge via the registry, holding their CI is pure drag; the hive approves the head's held runs once and logs contributor-lane approved held runs.`)} +
+ +
+
+ Merge owner-approved workflow-file PRs ${settingHelpMark('hive-merge', 'contributor-lane-auto-merge', 'Merge owner-approved workflow-file PRs', `YAML: auto_merge.contributor_lane.owner_approval_releases_workflow_fence. If you approved it, the hive merges it; a stale approval re-arms the fence on the next push.`)} +
+
@@ -50007,7 +50015,7 @@

${esc(s.title)}

Leave every repo unselected to allow all watched repositories. Skips are logged as contributor-lane:* reasons (no-claim, no-linked-issue, claim-author-mismatch, claim-other-hive, claim-tier-untrusted, claim-unverified, author-association, workflow-path, tests-removed, no-reviewer, no-verdict, soaking, sentinel-blocked); a registry-admitted PR logs contributor-lane:registry-trusted.

-

YAML keys: auto_merge.contributor_lane.enabled, auto_merge.contributor_lane.soak_minutes, auto_merge.contributor_lane.require_reviewer_verdict, auto_merge.contributor_lane.registry_tiers_sufficient, auto_merge.contributor_lane.approve_held_runs_for_registry_trusted, auto_merge.contributor_lane.auto_promotion_scope, auto_merge.contributor_lane.repos[], auto_merge.contributor_lane.exclude_labels[], auto_merge.contributor_lane.require_tiers[].

+

YAML keys: auto_merge.contributor_lane.enabled, auto_merge.contributor_lane.soak_minutes, auto_merge.contributor_lane.require_reviewer_verdict, auto_merge.contributor_lane.registry_tiers_sufficient, auto_merge.contributor_lane.approve_held_runs_for_registry_trusted, auto_merge.contributor_lane.owner_approval_releases_workflow_fence, auto_merge.contributor_lane.auto_promotion_scope, auto_merge.contributor_lane.repos[], auto_merge.contributor_lane.exclude_labels[], auto_merge.contributor_lane.require_tiers[].

@@ -51526,6 +51534,7 @@

${esc(s.title)}

'auto_merge.contributor_lane.require_reviewer_verdict': { tab: 'Features', stage: v => complianceStageContributorLane('require_reviewer_verdict', v) }, 'auto_merge.contributor_lane.registry_tiers_sufficient': { tab: 'Features', stage: v => complianceStageContributorLane('registry_tiers_sufficient', v) }, 'auto_merge.contributor_lane.approve_held_runs_for_registry_trusted': { tab: 'Features', stage: v => complianceStageContributorLane('approve_held_runs_for_registry_trusted', v) }, + 'auto_merge.contributor_lane.owner_approval_releases_workflow_fence': { tab: 'Features', stage: v => complianceStageContributorLane('owner_approval_releases_workflow_fence', v) }, 'auto_merge.required_checks': { tab: 'Features' }, 'sentinel.enabled': { tab: 'Security', stage: v => markSentinelDirty('enabled', v) }, 'sentinel.disabled_behaviors': { tab: 'Security' }, @@ -52312,6 +52321,7 @@

${esc(s.title)}

const verdict = document.getElementById('am-contributor-lane-require-reviewer-verdict'); const registry = document.getElementById('am-contributor-lane-registry-tiers-sufficient'); const heldRuns = document.getElementById('am-contributor-lane-approve-held-runs'); + const workflowApproval = document.getElementById('am-contributor-lane-owner-approval-workflow-fence'); const soak = document.getElementById('am-contributor-lane-soak-minutes'); const labels = document.getElementById('am-contributor-lane-exclude-labels'); const repos = document.getElementById('am-contributor-lane-repos'); @@ -52324,6 +52334,7 @@

${esc(s.title)}

require_reviewer_verdict: !!(verdict && verdict.classList.contains('on')), registry_tiers_sufficient: !!(registry && registry.classList.contains('on')), approve_held_runs_for_registry_trusted: !!(heldRuns && heldRuns.classList.contains('on')), + owner_approval_releases_workflow_fence: !!(workflowApproval && workflowApproval.classList.contains('on')), auto_promotion_scope: scope && scope.value ? scope.value : 'hive', exclude_labels: labels ? labels.value.split(',').map(s => s.trim()).filter(Boolean) : [], repos: repos ? Array.from(repos.selectedOptions).map(o => o.value).filter(Boolean) : [], diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index 7119193994..39c8a57174 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -1034,10 +1034,13 @@ func (c *Engine) pushAccessLost(ctx context.Context, obs stageObservation) bool } // baseSyncTouchesWorkflows reports whether the base has moved past a change -// under .github/workflows/ since the PR's merge-base. The App token cannot -// push such a base-sync to the PR branch (no `workflows` permission, #6985), -// so in-place adoption would be a dead end (#12865). A compare failure counts -// as touching: a superseding PR is always deliverable. +// under .github/workflows/ since the PR's merge-base. Pushing such a +// base-sync to a contributor's fork branch is refused for an App token +// without the `workflows` grant (#6985; an installation with Workflows: +// Read and write can merge approved workflow-path PRs into the base, #14664, +// but a fork push is a separate matter), so in-place adoption would be a +// dead end (#12865). A compare failure counts as touching: a superseding PR +// is always deliverable. func (c *Engine) baseSyncTouchesWorkflows(ctx context.Context, obs stageObservation) bool { if obs.HeadSHA == "" || obs.BaseRef == "" { return false diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 907d93b8d7..d5bebc782c 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -205,6 +205,13 @@ type ContributorLanePolicy struct { // (auto_merge.contributor_lane.approve_held_runs_for_registry_trusted). // See automerge_contributor_held_runs.go. ApproveHeldRunsForRegistryTrusted bool + // OwnerApprovalReleasesWorkflowFence lets a trusted merger's explicit + // approval on the current head (a GitHub APPROVED review, or a + // dashboard / `/hive decision approve` comment) release the + // workflow-path fence so the lane merges the PR itself + // (auto_merge.contributor_lane.owner_approval_releases_workflow_fence, + // default on). See automerge_contributor_workflow_approval.go. + OwnerApprovalReleasesWorkflowFence bool } // Contributor-lane auto-promotion scopes; mirrors @@ -1139,6 +1146,9 @@ type contributorLaneEval struct { verdict ContributorLaneVerdict method string mergeClaim effects.Claim + // workflowApprover is the trusted merger whose approval released the + // workflow-path fence for headSHA ("" when the fence did not trip). + workflowApprover string } // evaluateContributorLanePR runs every contributor-lane gate except the @@ -1206,7 +1216,11 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own return eval, contributorLaneReasonFilesEvidence, err } if reason := contributorLaneDiffReason(files); reason != "" { - return eval, reason, nil + approver, released := c.workflowFenceReleased(ctx, displayRepo, owner, repo, pr, number, headSHA, reason, policy) + if !released { + return eval, reason, nil + } + eval.workflowApprover = approver } if held, err := c.hasReporterTrustHold(ctx, owner, repo, number); err != nil { return eval, "reporter-trust-check", err @@ -1338,6 +1352,9 @@ func (c *Engine) trySweepContributorLanePR(ctx context.Context, displayRepo, own if requiredChecksExpectedMergeError(err) { return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "required-checks-expected", c.isForkPR(eval.pr)) } + if reason := c.workflowFenceMergeUnauthorized(ctx, displayRepo, owner, repo, eval, err); reason != "" { + return AutoMergeSweepEvent{}, reason, nil + } if refused := c.refusedMerge(attempt, err); refused != "" { return AutoMergeSweepEvent{}, refused, nil } diff --git a/src/pkg/github/automerge/automerge_contributor_workflow_approval.go b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go new file mode 100644 index 0000000000..1c24540a00 --- /dev/null +++ b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go @@ -0,0 +1,268 @@ +package automerge + +// Owner approval releases the workflow-path fence (hivecommons/hive#14664). +// +// The contributor lane's diff fence refuses any PR that edits +// `.github/workflows/**` or `.github/actions/**` (contributorLaneDiffReason). +// Until #14664 that refusal was absolute: an owner's approval only moved the +// PR to stage/090 with a "click Merge" caption and the hive never merged it +// (hive#14568, hive#14498, rationguard#401). The owner's decision is that an +// explicitly approved workflow-path PR is the hive's to merge. "Explicit +// approval" is one of: +// +// - a GitHub pull-request review in state APPROVED whose commit_id is the +// current head, by a trusted merger (isTrustedMerger — the same bar +// `/hive decision` and the requires_human release use); +// - a dashboard approval (`/hive decision approve`, which posts `/lgtm` +// and `/approve` attributed to the maintainer — ParsePRApprovalCommandComment) +// or a person's own `/hive decision approve` comment, by a trusted +// merger, bound to the current head: the comment's head marker names +// it, or the comment was posted after the head was pushed. +// +// Approval on an older head never counts, so a new push re-arms the fence. +// A released fence is logged once per head and leaves one audit marker per +// head on the PR; the PR then goes through every other gate (CI, soak, +// holds, sentinel, verdict) exactly like any other contributor-lane PR. +// +// Merging a workflow-path PR needs the App's `workflows: write`. When the +// merge is refused for want of it, the lane falls back to the pre-#14664 +// behaviour for that head: hive:unauthorized (step merge-workflow-path) and +// the workflow-path reason, which the stage engine already routes to 090 +// "click Merge" for an approved head. The in-memory unauthorized mark and +// the durable marker comment keep the lane from retrying every tick. + +import ( + "context" + "errors" + "net/http" + "strconv" + "strings" + "time" + + 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" +) + +const ( + // workflowApprovalMarkerPrefix opens the one-per-head audit comment the + // lane leaves when owner approval releases the fence. + workflowApprovalMarkerPrefix = "\n" + + "@" + approver + " approved head `" + shortSHA(headSHA) + "`, which edits CI workflow / action files. That explicit owner approval releases the contributor lane's workflow-path fence: the hive merges this PR itself once the usual gates (CI, soak, holds, review verdict) are clear. A new push re-arms the fence until the new head is approved again." +} + +// commentWorkflowApproval posts the audit comment once per head: an existing +// marker on the PR, or a prior effects claim, suppresses it. +func (c *Engine) commentWorkflowApproval(ctx context.Context, owner, repo string, number int, headSHA, approver string) error { + marker := workflowApprovalMarker(headSHA) + body := workflowApprovalComment(headSHA, approver) + _, err := effects.Execute(hgithub.WithRESTCaller(ctx, workflowApprovalRESTCaller), 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 +} + +// workflowFenceMergeUnauthorized handles a merge failure on a PR whose +// workflow-path fence owner approval released. When GitHub refused the merge +// for want of the App's `workflows` permission, it marks the PR unauthorized +// for merge-workflow-path and returns the workflow-path reason — the +// pre-#14664 outcome, which the stage engine routes to 090 "click Merge" for +// an approved head. Any other failure, or a PR whose fence did not trip, +// returns "" so the caller's usual handling runs. +func (c *Engine) workflowFenceMergeUnauthorized(ctx context.Context, displayRepo, owner, repo string, eval contributorLaneEval, err error) string { + if eval.workflowApprover == "" || !isWorkflowsPermissionMergeError(err) { + return "" + } + c.warn("workflow-path merge refused: App lacks workflows permission", "repo", displayRepo, "pr", eval.pr.GetNumber(), "head", eval.headSHA, "approver", eval.workflowApprover, "error", err) + c.markUnauthorized(ctx, displayRepo, owner, repo, eval.pr, eval.pr.GetNumber(), eval.headSHA, unauthorizedStepMergeWorkflowPath, unauthorizedPermissionWorkflowsWrite, mergeWorkflowPathHumanAction()) + return contributorLaneReasonWorkflowPath +} + +// mergeWorkflowPathHumanAction is the human step named in the +// hive:unauthorized comment for a refused workflow-path merge. +func mergeWorkflowPathHumanAction() string { + return "A maintainer must click **Merge** on GitHub (the approval already stands), or grant the App `" + unauthorizedPermissionWorkflowsWrite + "` so the hive can merge approved workflow-path PRs itself." +} + +// isWorkflowsPermissionMergeError reports whether GitHub refused a merge +// because the App installation lacks the `workflows` permission: the +// generic 403 "Resource not accessible by integration", or a 403 / 422 +// whose message names the workflow permission (`refusing to allow a GitHub +// App to create or update workflow … without workflows permission`). +func isWorkflowsPermissionMergeError(err error) bool { + if err == nil { + return false + } + if isResourceNotAccessible(err) { + return true + } + var ghErr *gh.ErrorResponse + if !errors.As(err, &ghErr) || ghErr.Response == nil { + return false + } + if code := ghErr.Response.StatusCode; code != http.StatusForbidden && code != http.StatusUnprocessableEntity { + return false + } + msg := strings.ToLower(ghErr.Message) + if msg == "" { + msg = strings.ToLower(ghErr.Error()) + } + return strings.Contains(msg, "workflow") && strings.Contains(msg, "permission") +} diff --git a/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go b/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go new file mode 100644 index 0000000000..cc98cbb94e --- /dev/null +++ b/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go @@ -0,0 +1,428 @@ +package automerge + +import ( + "context" + "net/http" + "net/url" + "slices" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" +) + +func mustParseTime(t *testing.T, s string) time.Time { + t.Helper() + at, err := time.Parse(time.RFC3339, s) + if err != nil { + t.Fatal(err) + } + return at +} + +func newIssueComment(login, body string, at time.Time) *gh.IssueComment { + return &gh.IssueComment{User: &gh.User{Login: gh.Ptr(login)}, Body: gh.Ptr(body), CreatedAt: &gh.Timestamp{Time: at}} +} + +func ghErrorResponse(status int, msg string) error { + return &gh.ErrorResponse{Response: &http.Response{StatusCode: status, Request: &http.Request{Method: "PUT", URL: &url.URL{Path: "/x"}}}, Message: msg} +} + +// workflowPathFiles is a contributor-lane diff that trips the workflow-path +// fence. +func workflowPathFiles() []map[string]any { + return []map[string]any{{"filename": ".github/workflows/ci.yml", "status": "modified", "additions": 3, "deletions": 1}} +} + +func ownerApprovedReview(login, commit string) map[string]any { + return map[string]any{"id": 1, "state": "APPROVED", "commit_id": commit, "user": map[string]string{"login": login}} +} + +// dashboardApproveComment is the `/approve` the dashboard posts as the App on +// a maintainer's behalf (hgithub.RecordOperatorPullRequestApproval), with +// the head marker when head is non-empty. +func dashboardApproveComment(id int, actor, head, createdAt string) map[string]any { + body := "/approve\n\nPosted by @" + actor + " from the Hive dashboard; the merge gate decides from here." + if head != "" { + body += "\n" + } + c := map[string]any{"id": id, "user": map[string]string{"login": testHiveAppBotLogin}, "body": body} + if createdAt != "" { + c["created_at"] = createdAt + } + return c +} + +// Owner approval on the current head releases the workflow-path fence and the +// lane merges the PR itself; anything short of that leaves the fence as it +// was (hivecommons/hive#14664). +func TestContributorLaneWorkflowFenceOwnerApproval(t *testing.T) { + const clockAt = "2026-10-27T13:00:00Z" + for _, tc := range []struct { + name string + toggleOff bool + mutate func(fx *contributorLaneFixture) + trusted []string + wantReason string + wantMerges int + // wantMarker expects the one-per-head audit marker naming by. + wantMarker string + }{ + { + name: "APPROVED review by trusted merger on current head releases", + mutate: func(fx *contributorLaneFixture) { + fx.reviews = []map[string]any{ownerApprovedReview("clubanderson", "sha7")} + }, + trusted: []string{"clubanderson"}, + wantMerges: 1, + wantMarker: "", + }, + { + name: "APPROVED review by non-owner does not release", + mutate: func(fx *contributorLaneFixture) { + fx.reviews = []map[string]any{ownerApprovedReview("passerby", "sha7")} + }, + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "APPROVED review on a stale head does not release", + mutate: func(fx *contributorLaneFixture) { + fx.reviews = []map[string]any{ownerApprovedReview("clubanderson", "sha6")} + }, + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "dashboard decision approve bound to the head by marker releases", + mutate: func(fx *contributorLaneFixture) { + fx.prComments = []map[string]any{dashboardApproveComment(5, "clubanderson", "sha7", "")} + }, + trusted: []string{"clubanderson"}, + wantMerges: 1, + wantMarker: "", + }, + { + name: "dashboard decision approve marked for an older head does not release", + mutate: func(fx *contributorLaneFixture) { + fx.prComments = []map[string]any{dashboardApproveComment(5, "clubanderson", "sha6", "")} + }, + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "unmarked dashboard approve posted after the head push releases", + mutate: func(fx *contributorLaneFixture) { + fx.headCommittedAt = "2026-10-27T11:00:00Z" + fx.prComments = []map[string]any{dashboardApproveComment(5, "clubanderson", "", "2026-10-27T12:00:00Z")} + }, + trusted: []string{"clubanderson"}, + wantMerges: 1, + wantMarker: "", + }, + { + name: "unmarked dashboard approve posted before the head push does not release", + mutate: func(fx *contributorLaneFixture) { + fx.headCommittedAt = "2026-10-27T11:00:00Z" + fx.prComments = []map[string]any{dashboardApproveComment(5, "clubanderson", "", "2026-10-27T10:00:00Z")} + }, + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "dashboard approve for a non-owner does not release", + mutate: func(fx *contributorLaneFixture) { + fx.prComments = []map[string]any{dashboardApproveComment(5, "passerby", "sha7", "")} + }, + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "typed /hive decision approve by trusted merger after the push releases", + mutate: func(fx *contributorLaneFixture) { + fx.headCommittedAt = "2026-10-27T11:00:00Z" + fx.prComments = []map[string]any{{"id": 5, "user": map[string]string{"login": "clubanderson"}, "body": "/hive decision approve\n\nShip it.", "created_at": "2026-10-27T12:00:00Z"}} + }, + trusted: []string{"clubanderson"}, + wantMerges: 1, + wantMarker: "", + }, + { + name: "plain /hive approve is not consumed", + mutate: func(fx *contributorLaneFixture) { + fx.headCommittedAt = "2026-10-27T11:00:00Z" + fx.prComments = []map[string]any{{"id": 5, "user": map[string]string{"login": "clubanderson"}, "body": "/hive approve", "created_at": "2026-10-27T12:00:00Z"}} + }, + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "toggle off keeps the fence absolute", + toggleOff: true, + mutate: func(fx *contributorLaneFixture) { + fx.reviews = []map[string]any{ownerApprovedReview("clubanderson", "sha7")} + }, + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "no approval behaves as before", + trusted: []string{"clubanderson"}, + wantReason: contributorLaneReasonWorkflowPath, + }, + } { + t.Run(tc.name, func(t *testing.T) { + fx := validContributorFixture() + fx.files = workflowPathFiles() + if tc.mutate != nil { + tc.mutate(&fx) + } + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.OwnerApprovalReleasesWorkflowFence = !tc.toggleOff + clock := &contributorLaneClock{at: mustParseTime(t, clockAt)} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock)}) + engine.SetMergerAuthorizer(func(login string) bool { + return slices.ContainsFunc(tc.trusted, func(l string) bool { return strings.EqualFold(l, login) }) + }) + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatal(err) + } + if reason != tc.wantReason || fx.merges != tc.wantMerges { + t.Fatalf("reason=%q merges=%d, want %q/%d (comments=%v)", reason, fx.merges, tc.wantReason, tc.wantMerges, fx.allComments) + } + markers := 0 + for _, body := range fx.allComments { + if strings.HasPrefix(body, workflowApprovalMarkerPrefix) { + markers++ + if tc.wantMarker == "" || !strings.HasPrefix(body, tc.wantMarker) { + t.Fatalf("audit comment = %q, want prefix %q", body, tc.wantMarker) + } + } + } + if want := 0; tc.wantMarker != "" { + want = 1 + if markers != want { + t.Fatalf("workflow-approval markers = %d, want %d: %v", markers, want, fx.allComments) + } + } else if markers != 0 { + t.Fatalf("unexpected workflow-approval marker: %v", fx.allComments) + } + }) + } +} + +// The audit marker is left once per head: a second tick on a head already +// marked merges without a second comment. +func TestContributorLaneWorkflowFenceMarkerOncePerHead(t *testing.T) { + fx := validContributorFixture() + fx.files = workflowPathFiles() + fx.reviews = []map[string]any{ownerApprovedReview("clubanderson", "sha7")} + fx.prComments = []map[string]any{{"id": 5, "user": map[string]string{"login": testHiveAppBotLogin}, "body": workflowApprovalComment("sha7", "clubanderson")}} + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.OwnerApprovalReleasesWorkflowFence = true + clock := &contributorLaneClock{at: mustParseTime(t, "2026-10-27T13:00:00Z")} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock)}) + engine.SetMergerAuthorizer(func(login string) bool { return strings.EqualFold(login, "clubanderson") }) + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatal(err) + } + if reason != "" || fx.merges != 1 { + t.Fatalf("reason=%q merges=%d, want merged", reason, fx.merges) + } + for _, body := range fx.allComments { + if strings.HasPrefix(body, workflowApprovalMarkerPrefix) { + t.Fatalf("marker re-posted for an already-marked head: %v", fx.allComments) + } + } +} + +// A merge GitHub refuses for want of the App's workflows permission falls +// back to the pre-#14664 outcome for that head: hive:unauthorized for +// merge-workflow-path (label + one comment), the workflow-path reason so the +// stage engine parks the approved head at 090 for a person's click, and no +// second merge attempt on later ticks or after a restart that sees the marker. +func TestContributorLaneWorkflowFenceMergeUnauthorizedFallback(t *testing.T) { + for _, tc := range []struct { + name string + status int + message string + // restart pre-seeds the unauthorized marker as a restarted hive sees it. + restart bool + wantMerges int + }{ + {name: "403 resource not accessible", status: http.StatusForbidden, message: "Resource not accessible by integration", wantMerges: 1}, + {name: "422 refusing to update workflow without permission", status: http.StatusUnprocessableEntity, message: "refusing to allow a GitHub App to create or update workflow `.github/workflows/ci.yml` without `workflows` permission", wantMerges: 1}, + {name: "restart sees marker and does not retry", status: http.StatusForbidden, message: "Resource not accessible by integration", restart: true, wantMerges: 0}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := validContributorFixture() + fx.files = workflowPathFiles() + fx.reviews = []map[string]any{ownerApprovedReview("clubanderson", "sha7")} + fx.mergeStatus = tc.status + fx.mergeMessage = tc.message + if tc.restart { + fx.labels = []string{unauthorizedLabel} + fx.prComments = []map[string]any{{ + "id": 5, + "user": map[string]string{"login": testHiveAppBotLogin}, + "body": unauthorizedComment("sha7", unauthorizedStepMergeWorkflowPath, unauthorizedPermissionWorkflowsWrite, "click"), + }} + } + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.OwnerApprovalReleasesWorkflowFence = true + clock := &contributorLaneClock{at: mustParseTime(t, "2026-10-27T13:00:00Z")} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock)}) + engine.SetMergerAuthorizer(func(login string) bool { return strings.EqualFold(login, "clubanderson") }) + + 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 != contributorLaneReasonWorkflowPath { + t.Fatalf("tick %d reason = %q, want %q", tick, reason, contributorLaneReasonWorkflowPath) + } + } + if fx.merges != tc.wantMerges { + t.Fatalf("merge attempts = %d, want %d across two ticks", fx.merges, tc.wantMerges) + } + if step := engine.unauthorizedStep("acme", "widget", 7, "sha7"); step != unauthorizedStepMergeWorkflowPath { + t.Fatalf("unauthorizedStep = %q, want %q", step, unauthorizedStepMergeWorkflowPath) + } + if !slices.Contains(fx.labels, unauthorizedLabel) { + t.Fatalf("labels = %v, want %q", fx.labels, unauthorizedLabel) + } + marker := unauthorizedMarker("sha7", unauthorizedStepMergeWorkflowPath) + unauthorizedComments := 0 + for _, body := range fx.allComments { + if strings.HasPrefix(body, marker) { + unauthorizedComments++ + if !strings.Contains(body, "`"+unauthorizedPermissionWorkflowsWrite+"`") || !strings.Contains(body, "**Merge**") { + t.Fatalf("unauthorized comment = %q, want the permission and the merge click", body) + } + } + } + wantAdds, wantComments := 1, 1 + if tc.restart { + wantAdds, wantComments = 0, 0 + } + if unauthorizedComments != wantComments || len(fx.labelsAdded) != wantAdds { + t.Fatalf("unauthorized comments = %d labels added = %v, want %d/%d", unauthorizedComments, fx.labelsAdded, wantComments, wantAdds) + } + // The stage route for this head now reads as a manual merge. + if !engine.workflowFenceManual("acme", "widget", 7, "sha7") { + t.Fatal("workflowFenceManual = false after an unauthorized merge, want true") + } + }) + } +} + +// The 085 text for an unapproved workflow-path PR asks for owner approval +// when the release is on and reads as a manual-merge rule when it is off. +func TestWorkflowPathCauseText(t *testing.T) { + if got := workflowPathCause(false); !strings.Contains(got, "awaiting owner approval") || !strings.Contains(got, "re-approve after a push") { + t.Fatalf("released cause = %q", got) + } + if got := workflowPathCause(true); !strings.Contains(got, "never merges unattended") { + t.Fatalf("manual cause = %q", got) + } + if manualMergeRuleReasonFor(contributorLaneReasonWorkflowPath, false) || !manualMergeRuleReasonFor(contributorLaneReasonWorkflowPath, true) { + t.Fatal("manualMergeRuleReasonFor must follow the workflow fence's standing") + } + if !manualMergeRuleReasonFor(contributorLaneReasonTestsRemoved, false) { + t.Fatal("tests-removed stays a manual-merge rule") + } +} + +// workflowApprovalCommentActor reads dashboard and typed approvals, binds +// them to the head, and ignores everything else. +func TestWorkflowApprovalCommentActor(t *testing.T) { + pushed := mustParseTime(t, "2026-10-27T11:00:00Z") + after := mustParseTime(t, "2026-10-27T12:00:00Z") + before := mustParseTime(t, "2026-10-27T10:00:00Z") + comment := newIssueComment + dashboard := func(actor, head string) string { + b := "/approve\n\nPosted by @" + actor + " from the Hive dashboard; the merge gate decides from here." + if head != "" { + b += "\n" + } + return b + } + for _, tc := range []struct { + name string + comment *gh.IssueComment + wantLogin string + wantOK bool + }{ + {name: "dashboard approve marked for head", comment: comment(testHiveAppBotLogin, dashboard("clubanderson", "sha7"), before), wantLogin: "clubanderson", wantOK: true}, + {name: "dashboard approve marked for other head", comment: comment(testHiveAppBotLogin, dashboard("clubanderson", "sha6"), after)}, + {name: "dashboard approve unmarked after push", comment: comment(testHiveAppBotLogin, dashboard("clubanderson", ""), after), wantLogin: "clubanderson", wantOK: true}, + {name: "dashboard approve unmarked before push", comment: comment(testHiveAppBotLogin, dashboard("clubanderson", ""), before)}, + {name: "dashboard lgtm is not the approval", comment: comment(testHiveAppBotLogin, "/lgtm\n\nPosted by @clubanderson from the Hive dashboard; the merge gate decides from here.", after)}, + {name: "dashboard-shaped comment from a person is not trusted as the App", comment: comment("passerby", dashboard("clubanderson", "sha7"), after)}, + {name: "typed decision approve after push", comment: comment("clubanderson", "/hive decision approve\n\nfine", after), wantLogin: "clubanderson", wantOK: true}, + {name: "typed decision approve before push", comment: comment("clubanderson", "/hive decision approve", before)}, + {name: "quoted decision approve", comment: comment("clubanderson", "> /hive decision approve", after)}, + {name: "plain hive approve", comment: comment("clubanderson", "/hive approve", after)}, + {name: "decision with other text", comment: comment("clubanderson", "/hive decision approve the rename later", after)}, + {name: "bot typed decision", comment: comment("someone[bot]", "/hive decision approve", after)}, + } { + t.Run(tc.name, func(t *testing.T) { + login, ok := workflowApprovalCommentActor(tc.comment, "sha7", pushed, testHiveAppBotLogin) + if ok != tc.wantOK || login != tc.wantLogin { + t.Fatalf("got (%q, %v), want (%q, %v)", login, ok, tc.wantLogin, tc.wantOK) + } + }) + } + if _, ok := workflowApprovalCommentActor(comment("clubanderson", "/hive decision approve", after), "sha7", time.Time{}, testHiveAppBotLogin); ok { + t.Fatal("an unmarked comment must not bind to a head whose push time is unknown") + } +} + +// isWorkflowsPermissionMergeError recognises the two shapes GitHub uses and +// nothing else. +func TestIsWorkflowsPermissionMergeError(t *testing.T) { + for _, tc := range []struct { + name string + status int + message string + want bool + }{ + {name: "403 not accessible", status: http.StatusForbidden, message: "Resource not accessible by integration", want: true}, + {name: "422 workflows permission", status: http.StatusUnprocessableEntity, message: "refusing to allow a GitHub App to create or update workflow without `workflows` permission", want: true}, + {name: "403 workflow permission", status: http.StatusForbidden, message: "You need the workflows permission", want: true}, + {name: "405 not mergeable", status: http.StatusMethodNotAllowed, message: "Pull Request is not mergeable", want: false}, + {name: "422 head mismatch", status: http.StatusUnprocessableEntity, message: "Head branch was modified. Review and try the merge again.", want: false}, + {name: "403 rate limit", status: http.StatusForbidden, message: "API rate limit exceeded", want: false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := isWorkflowsPermissionMergeError(ghErrorResponse(tc.status, tc.message)); got != tc.want { + t.Fatalf("got %v, want %v", got, tc.want) + } + }) + } + if isWorkflowsPermissionMergeError(nil) || isWorkflowsPermissionMergeError(context.Canceled) { + t.Fatal("non-GitHub errors are not permission errors") + } +} + +// ParsePRApprovalCommandComment round-trips what the dashboard posts. +func TestParsePRApprovalCommandCommentRoundTrip(t *testing.T) { + command, actor, head, ok := hgithub.ParsePRApprovalCommandComment("/approve\n\nPosted by @ClubAnderson from the Hive dashboard; the merge gate decides from here.\n") + if !ok || command != "/approve" || actor != "ClubAnderson" || head != "abc123" { + t.Fatalf("got (%q, %q, %q, %v)", command, actor, head, ok) + } + if _, _, _, ok := hgithub.ParsePRApprovalCommandComment("/approve\n\nlooks good"); ok { + t.Fatal("a bare /approve is not a dashboard approval") + } +} diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index bfeda63b9f..b77070bddf 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -86,19 +86,20 @@ var humanConflictReasons = map[string]bool{"conflicting": true, "not-mergeable": // humanEvidence gathers the Evidence for one human-routed observation. func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key string, obs stageObservation, cause stagelabels.HumanCause, now time.Time) stagelabels.Evidence { contributorVerdict := normalizeContributorLaneVerdict(c.contributorLaneVerdictFor(obs.Owner+"/"+obs.Repo, obs.Number, obs.HeadSHA)) + workflowManual := c.workflowFenceManual(obs.Owner, obs.Repo, obs.Number, obs.HeadSHA) e := stagelabels.Evidence{ Head: obs.HeadSHA, Verdict: humanVerdict(contributorVerdict), Conflict: humanConflictReasons[obs.Reason] || hasLabelFold(obs.Labels, "needs-rebase"), Holds: stagelabels.Holds(obs.Labels), Cause: cause, - CauseReason: decisionCause(obs.Reason), + CauseReason: decisionCauseFor(obs.Reason, workflowManual), DecisionQuestion: strings.TrimSpace(contributorVerdict.DecisionQuestion), HumanSummaries: append([]string(nil), contributorVerdict.HumanSummaries...), SelfAuthored: obs.Lane == stageLaneSelf, AuthorKind: obs.AuthorKind, LaneReason: obs.Reason, - ManualMergeRule: manualMergeRuleReason(obs.Reason), + ManualMergeRule: manualMergeRuleReasonFor(obs.Reason, workflowManual), } // A trusted merger's APPROVED review on exactly this head is the human // decision the lane noted (latestTrustedHumanApproval): it settles a @@ -141,17 +142,35 @@ func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key s return e } -// manualMergeRuleReason reports whether a lane reason is a rule no review -// or reply overrides: the hive never merges the head unattended, a person -// clicks merge. -func manualMergeRuleReason(reason string) bool { +// manualMergeRuleReasonFor reports whether a lane reason is a rule no +// review or reply overrides: the hive never merges the head unattended, a +// person clicks merge. workflowManual supplies the workflow-path fence's +// standing: true when the hive will not merge the head itself even once +// approved (toggle off, or the App lacks `workflows: write` for this head); +// false when owner approval releases it (hivecommons/hive#14664). +func manualMergeRuleReasonFor(reason string, workflowManual bool) bool { switch reason { - case contributorLaneReasonWorkflowPath, contributorLaneReasonTestsRemoved, autoMergeReasonHumanMergePath: + case contributorLaneReasonWorkflowPath: + return workflowManual + case contributorLaneReasonTestsRemoved, autoMergeReasonHumanMergePath: return true } return false } +// workflowFenceManual reports whether a workflow-path PR at this head is +// one a person must merge: the owner-approval release is off, or the lane +// has learnt the App cannot merge the head (unauthorized merge-workflow-path). +func (c *Engine) workflowFenceManual(owner, repo string, number int, headSHA string) bool { + if c == nil { + return true + } + if !c.currentContributorLanePolicy().OwnerApprovalReleasesWorkflowFence { + return true + } + return c.unauthorizedStep(owner, repo, number, headSHA) == unauthorizedStepMergeWorkflowPath +} + // routeHuman refines a lane's human hand-off into the stage the evidence // supports. It returns the route (with the lane-vocabulary reason to // record) and the evidence it was decided on, which the stage pass hands @@ -175,7 +194,7 @@ func (c *Engine) routeHuman(ctx context.Context, tracker *StageTracker, key stri // consume `/hive approve` on a PR: the release lever for `requires_human` is // a trusted merger's GitHub Approve review on the current head. func decisionActions(obs stageObservation, e stagelabels.Evidence) ([]string, bool) { - if manualMergeRuleReason(obs.Reason) { + if e.ManualMergeRule { action := "The hive never merges this change itself: a maintainer must click **Merge** on GitHub (or comment `/lgtm` + `/approve` for tide). A GitHub Approve review records the decision but does not merge, and `/hive approve` cannot override this lane's manual-merge rule." if approver := strings.TrimSpace(e.HumanApprover); approver != "" { action = "@" + approver + " has approved this head; the only step left is the merge. " + action @@ -183,6 +202,9 @@ func decisionActions(obs stageObservation, e stagelabels.Evidence) ([]string, bo return []string{action}, true } var actions []string + if obs.Reason == contributorLaneReasonWorkflowPath { + actions = append(actions, "A hive owner / trusted merger submits a GitHub **Approve** review on the current head (or approves from the Hive dashboard, which posts `/hive decision approve` on their behalf); that explicit approval releases the workflow-path fence and the lane merges on its next pass once CI, soak and the other gates are clear. Approval on an earlier head does not carry over: re-approve after a push.") + } if len(e.ForkGuard) > 0 { actions = append(actions, "A maintainer must push this branch to the repository (or approve the guarded run as the repository requires); the contributor cannot clear a fork guard by pushing to the fork, and the hive does not adopt it.") } @@ -233,14 +255,31 @@ func trustCause(reason string, role stagelabels.Role) string { } // decisionCause renders a non-trust human-only lane reason as prose for the -// 085 comment ("" for reasons the labels already explain). +// 085 comment ("" for reasons the labels already explain). The workflow-path +// fence reads as a manual-merge rule; decisionCauseFor refines it. func decisionCause(reason string) string { + return decisionCauseFor(reason, true) +} + +// workflowPathCause is the 085 prose for the workflow-path fence: a rule a +// person merges around when workflowManual, otherwise a fence awaiting the +// owner's explicit approval (hivecommons/hive#14664). +func workflowPathCause(workflowManual bool) string { + if workflowManual { + return "the PR edits CI workflow / action files, which the lane never merges unattended" + } + return "the PR edits CI workflow / action files: awaiting owner approval — a hive owner / trusted merger's GitHub **Approve** review on the current head (or a dashboard `/hive decision approve`) releases the fence and the hive merges it; approval on an earlier head does not count, so re-approve after a push" +} + +// decisionCauseFor is decisionCause with the workflow-path fence's standing +// supplied (see workflowFenceManual). +func decisionCauseFor(reason string, workflowManual bool) string { switch { case reason == "held", reason == "label:hold", reason == "label:needs-human", reason == "exempt-label", strings.HasPrefix(reason, "excluded-label:"), reason == "sentinel", reason == contributorLaneReasonSentinelBlocked: return "" case reason == contributorLaneReasonWorkflowPath: - return "the PR edits CI workflow / action files, which the lane never merges unattended" + return workflowPathCause(workflowManual) case reason == contributorLaneReasonTestsRemoved: return "the PR removes tests, which the lane never merges unattended" case strings.HasPrefix(reason, stageReasonForkGuard): diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 274e110888..25acb82896 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -2946,7 +2946,7 @@ func mergeAPIErrorNotApplied(err error) error { return err } switch ghErr.Response.StatusCode { - case http.StatusMethodNotAllowed, http.StatusConflict, http.StatusUnprocessableEntity: + case http.StatusMethodNotAllowed, http.StatusConflict, http.StatusUnprocessableEntity, http.StatusForbidden: return effects.NotApplied(err) } return err diff --git a/src/pkg/github/automerge/pr_approve_command.go b/src/pkg/github/automerge/pr_approve_command.go index 8b66d0f6be..bbdeb585c8 100644 --- a/src/pkg/github/automerge/pr_approve_command.go +++ b/src/pkg/github/automerge/pr_approve_command.go @@ -83,7 +83,14 @@ func (c *Engine) PRApproveReply(ctx context.Context, displayRepo string, number if err != nil { return "", err } - if len(intent.HumanMergePathMatches(files, patterns)) > 0 || (contributor && contributorLaneDiffReason(files) != "") { + diffReason := "" + if contributor { + diffReason = contributorLaneDiffReason(files) + } + if len(intent.HumanMergePathMatches(files, patterns)) == 0 && diffReason == contributorLaneReasonWorkflowPath && c.currentContributorLanePolicy().OwnerApprovalReleasesWorkflowFence { + return "`/hive approve` acknowledged, but this PR edits CI workflow / action files, which the contributor lane merges only on a hive owner's explicit approval: a trusted merger submits a GitHub **Approve** review for the current head (`" + stagelabels.ShortSHA(head) + "`) or approves it from the Hive dashboard, and the lane merges once CI and the other gates are clear. Approval on an earlier head does not carry over.", nil + } + if len(intent.HumanMergePathMatches(files, patterns)) > 0 || diffReason != "" { return "`/hive approve` acknowledged, but this PR changes files that its lane requires a person to merge manually. The command cannot override that rule; a maintainer must review and merge it.", nil } } diff --git a/src/pkg/github/automerge/pr_approve_command_test.go b/src/pkg/github/automerge/pr_approve_command_test.go index 63a444ea26..a22c8db44e 100644 --- a/src/pkg/github/automerge/pr_approve_command_test.go +++ b/src/pkg/github/automerge/pr_approve_command_test.go @@ -110,12 +110,13 @@ func TestDecisionCommentNamesLaneAction(t *testing.T) { {name: "tests removed", lane: stageLaneContributor, reason: contributorLaneReasonTestsRemoved, want: "must click **Merge** on GitHub", manual: true}, {name: "human path", lane: stageLaneSelf, reason: autoMergeReasonHumanMergePath, want: "must click **Merge** on GitHub", manual: true}, {name: "workflow, approver named", lane: stageLaneContributor, reason: contributorLaneReasonWorkflowPath, approver: "octocat", want: "@octocat has approved this head; the only step left is the merge", manual: true}, + {name: "workflow, owner approval releases", lane: stageLaneContributor, reason: contributorLaneReasonWorkflowPath, want: "releases the workflow-path fence"}, {name: "label hold", lane: stageLaneSelf, holds: []string{"hold"}, want: "remove that label"}, {name: "label needs-human reason", lane: stageLaneTrusted, reason: "label:needs-human", want: "Answer the `needs-human` ask"}, {name: "label needs-human on the PR", lane: stageLaneTrusted, labels: []string{"Needs-Human"}, want: "Answer the `needs-human` ask"}, } { t.Run(tc.name, func(t *testing.T) { - e := stagelabels.Evidence{Verdict: stagelabels.VerdictRequiresHuman, Holds: tc.holds, HumanApprover: tc.approver, Sentinel: tc.approver != ""} + e := stagelabels.Evidence{Verdict: stagelabels.VerdictRequiresHuman, Holds: tc.holds, HumanApprover: tc.approver, Sentinel: tc.approver != "", ManualMergeRule: tc.manual} route := stagelabels.RouteHuman(e) route.Actions, route.ManualMerge = decisionActions(stageObservation{Lane: tc.lane, Reason: tc.reason, Labels: tc.labels}, e) body := stagelabels.DecisionComment(route) diff --git a/src/pkg/github/pr_decision_operator.go b/src/pkg/github/pr_decision_operator.go index e17ab60fd3..3b8596f188 100644 --- a/src/pkg/github/pr_decision_operator.go +++ b/src/pkg/github/pr_decision_operator.go @@ -50,8 +50,72 @@ type PullRequestApprovalEvent struct { Actor string } -func renderPRApprovalCommandComment(command, actor string) string { - return fmt.Sprintf("%s\n\nPosted by @%s from the Hive dashboard; the merge gate decides from here.", command, strings.TrimSpace(actor)) +// prApprovalCommentMarkerPrefix opens the hidden marker a dashboard approval +// comment carries so a later reader can bind the decision to the head it was +// made on (hivecommons/hive#14664). +const prApprovalCommentMarkerPrefix = "" + } + return body +} + +// ParsePRApprovalCommandComment reads a comment the dashboard posted on a +// maintainer's behalf (renderPRApprovalCommandComment). It returns the +// command (`/lgtm` or `/approve`), the actor the comment is attributed to, +// and the head SHA the marker bound it to ("" for comments posted before +// the marker existed). ok is false for any other comment. +func ParsePRApprovalCommandComment(body string) (command, actor, head string, ok bool) { + lines := strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n") + var rest []string + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" { + continue + } + if command == "" { + command = line + continue + } + rest = append(rest, line) + } + if len(rest) == 0 { + return "", "", "", false + } + known := false + for _, want := range PRApprovalCommands { + if command == want { + known = true + } + } + if !known { + return "", "", "", false + } + attribution := rest[0] + if !strings.HasPrefix(attribution, "Posted by @") || !strings.HasSuffix(attribution, prApprovalCommentSuffix) { + return "", "", "", false + } + actor = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(attribution, "Posted by @"), prApprovalCommentSuffix)) + if actor == "" || strings.ContainsAny(actor, " \t") { + return "", "", "", false + } + for _, line := range rest[1:] { + if !strings.HasPrefix(line, prApprovalCommentMarkerPrefix) { + continue + } + for _, field := range strings.Fields(strings.TrimSuffix(strings.TrimPrefix(line, prApprovalCommentMarkerPrefix), "-->")) { + if v, found := strings.CutPrefix(field, "head="); found { + head = strings.ToLower(strings.TrimSpace(v)) + } + } + } + return command, actor, head, true } // openPullRequestHead returns the PR's head SHA and whether the hive opened @@ -107,7 +171,7 @@ func (c *Client) RecordOperatorPullRequestApproval(ctx context.Context, repo str return PullRequestApprovalEvent{}, err } for _, command := range PRApprovalCommands { - if err := c.CreateIssueComment(ctx, owner+"/"+name, number, renderPRApprovalCommandComment(command, actor)); err != nil { + if err := c.CreateIssueComment(ctx, owner+"/"+name, number, renderPRApprovalCommandComment(command, actor, head)); err != nil { return PullRequestApprovalEvent{}, fmt.Errorf("posting %s on %s/%s#%d: %w", command, owner, name, number, err) } } diff --git a/src/pkg/stageengine/prstage/reasons.go b/src/pkg/stageengine/prstage/reasons.go index 537a8f7d25..9b0a669e1d 100644 --- a/src/pkg/stageengine/prstage/reasons.go +++ b/src/pkg/stageengine/prstage/reasons.go @@ -53,7 +53,11 @@ const ( // 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:" + // UnauthorizedStepMergeWorkflowPath: merging an owner-approved PR that + // edits `.github/workflows/**` needs `workflows: write`; without it the + // lane parks the PR for a person's merge click (hivecommons/hive#14664). + UnauthorizedStepMergeWorkflowPath = "merge-workflow-path" + TrustedAuthorReasonAppAuthored = "trusted-author:app-authored" + TrustedBotLaneSkipReason = "trusted-bot-lane" + WorkflowApprovalRequiredPrefix = "workflow-approval-required:" )