From 120672bc41d4afabe77b390db4b81a5fb2090d03 Mon Sep 17 00:00:00 2001 From: Danathar Date: Mon, 9 Nov 2026 19:34:42 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(automerge):=20workflow=20fence?= =?UTF-8?q?=20can=20be=20limited=20to=20release-critical=20workflows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add auto_merge.contributor_lane.workflow_fence_scope. "all" (default) keeps today's fence on every .github/workflows / .github/actions edit. "human_merge_paths" fences only workflow / action files that also match the repository's auto_merge.human_merge_paths, so routine workflow edits go through review, CI and soak without an owner Approve on every head. The scoped fence fails closed: no human_merge_paths entry, a renamed workflow file, or a head GitHub refused to merge for want of workflows: write keeps the fence. One helper (contributorLaneMergeFence) feeds the lane, the stage notes and merge asks (headDiffFence) and /hive approve. The held-run approval guard and adoption's refusal to publish workflow edits upstream stay unscoped. The tests-removed fence, Sentinel and the human-merge hold are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- changelog.d/added-workflow-fence-scope.md | 1 + src/cmd/hive/merge_eligibility.go | 1 + src/docs/hive-merge.md | 43 ++- .../stage-labels.md | 7 +- src/docs/operator-reference/README.md | 1 + src/pkg/config/automerge_trusted_bot_test.go | 33 ++ src/pkg/config/review_config.go | 43 +++ src/pkg/dashboard/api_config_automerge.go | 17 + src/pkg/dashboard/api_config_sections_test.go | 15 + .../static-src/js/config-features.js | 11 +- .../dashboard/static-src/js/config-helpers.js | 2 + src/pkg/dashboard/static/index.html | 13 +- .../automerge/automerge_contributor_adopt.go | 55 ++- .../automerge_contributor_held_runs.go | 5 +- .../automerge/automerge_contributor_lane.go | 24 +- ...automerge_contributor_workflow_approval.go | 12 +- .../github/automerge/automerge_stage_human.go | 18 +- .../automerge_workflow_fence_scope.go | 150 ++++++++ .../automerge_workflow_fence_scope_test.go | 344 ++++++++++++++++++ .../github/automerge/pr_approve_command.go | 4 +- 20 files changed, 773 insertions(+), 26 deletions(-) create mode 100644 changelog.d/added-workflow-fence-scope.md create mode 100644 src/pkg/github/automerge/automerge_workflow_fence_scope.go create mode 100644 src/pkg/github/automerge/automerge_workflow_fence_scope_test.go diff --git a/changelog.d/added-workflow-fence-scope.md b/changelog.d/added-workflow-fence-scope.md new file mode 100644 index 0000000000..c51b261cc1 --- /dev/null +++ b/changelog.d/added-workflow-fence-scope.md @@ -0,0 +1 @@ +- **The contributor lane's workflow fence can be limited to release-critical workflows.** A new owner-only setting, `auto_merge.contributor_lane.workflow_fence_scope` (Settings → Features → Auto Merge → Contributor-lane auto-merge → **Workflow fence scope**), chooses which CI workflow / action edits wait for an owner's approval of the current head. `all`, the default, keeps today's behaviour: every edit under `.github/workflows/**` or `.github/actions/**` does. `human_merge_paths` fences only a file that also matches the repository's `auto_merge.human_merge_paths`, so routine edits such as pin bumps and permission tightening go through review, CI and soak instead of needing a fresh Approve after every push. It fails closed: a repository with no `human_merge_paths` entry keeps the full fence, a renamed workflow file always trips it, and a merge GitHub refuses for want of the App's Workflows permission parks the head for a person. The tests-removed fence, Sentinel, the human-merge hold, the guard that never approves held fork CI runs for a workflow edit, and adoption's refusal to publish workflow edits upstream are unchanged. The stage notes, the merge asks and `/hive approve` replies all read the same scoped fence as the lane. Sentinel's default `sensitive_path` list still labels these PRs `sentinel-alert`; see [hive-merge.md](src/docs/hive-merge.md#contributor-lane-auto-merge). diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index 33e32bccf0..cb31320e61 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -113,6 +113,7 @@ func contributorLanePolicyFunc(cfg *config.Config) func() automerge.ContributorL AutoPromotionScope: p.EffectiveAutoPromotionScope(), ApproveHeldRunsForRegistryTrusted: p.EffectiveApproveHeldRunsForRegistryTrusted(), OwnerApprovalReleasesWorkflowFence: p.EffectiveOwnerApprovalReleasesWorkflowFence(), + WorkflowFenceScope: p.EffectiveWorkflowFenceScope(), } } } diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 3461fc4222..03e69c8c2a 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -1075,6 +1075,44 @@ A PR merges through this tier only when all of the following hold: 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. + + Which edits trip this fence is `workflow_fence_scope` (default `all`). + With `all`, every file under `.github/workflows/**` or + `.github/actions/**` does. With `human_merge_paths`, only a workflow or + action file that also matches the repository's + `auto_merge.human_merge_paths` does, read with the same matcher as the + human-merge hold. Any other workflow edit, such as a pin bump or a + tightened `permissions:` block, needs no owner approval: it goes through + review, CI, soak and every other gate here like any other change. The + scoped fence fails closed: + - a repository with no `human_merge_paths` entry keeps the full fence; + - a renamed workflow or action file always trips it, because GitHub's + file list names only the new path; + - when GitHub refuses the merge for want of the App's **Workflows: Read + and write**, the head is marked `hive:unauthorized` + (`merge-workflow-path`) and stays fenced for a person's merge, as an + owner-released head does. + + A listed file still gets the human-merge hold as well. List every + reusable workflow and local action your release workflows call, not only + the top-level files: an edit to an unlisted one merges after review. + Three things ignore the scope: + - the tests-removed fence below; + - held fork CI runs, which the lane never approves for any workflow edit + (`approve_held_runs_for_registry_trusted`); + - adoption, which never publishes any workflow edit as an upstream + branch. + + Sentinel is separate. Its `sensitive_path` behaviour flags + `.github/workflows/**` and `.github/actions/**` by default and labels a + contributor's PR `sentinel-alert`, which blocks this lane until a person + clears it (`contributor-lane:sentinel-blocked`). For routine workflow + edits to merge without a person, `sentinel.sensitive_paths` must also + leave those globs out. That key replaces the whole default list, so copy + the defaults and drop only the workflow and action globs; Sentinel's + content rules (permission widening, secret exposure, CI-gate weakening, + remote code execution) still read every workflow patch (see + [Suspicious-activity alerts](operator-reference/sweeps-and-operations.md#suspicious-activity-alerts-sentinel)). - 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 @@ -1139,14 +1177,15 @@ auto_merge: 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 + workflow_fence_scope: all # human_merge_paths = fence only workflow / action files listed in auto_merge.human_merge_paths contributor_tier: auto_promote_after_merged: 5 # clean merged PRs before the lane trusts an author on its own; negative disables ``` The block is editable from **Settings → Features → Auto Merge → Contributor-lane auto-merge** (enable switch, soak minutes, reviewer-verdict -switch, required tiers, auto-promotion scope, excluded labels, repository -allow-list) through the +switch, required tiers, auto-promotion scope, workflow fence scope, +excluded labels, repository allow-list) through the same owner-only `GET/PUT /api/config/auto-merge` overlay. **Operator workflow.** To let a known contributor's relay PRs merge diff --git a/src/docs/labels-and-control-signals/stage-labels.md b/src/docs/labels-and-control-signals/stage-labels.md index 9f5fb006fc..8a503cc56a 100644 --- a/src/docs/labels-and-control-signals/stage-labels.md +++ b/src/docs/labels-and-control-signals/stage-labels.md @@ -1051,7 +1051,12 @@ When a contributor-agent PR goes red the hive does not just relabel it (a human- note says the hive adopted it to repair CI and why it still will not merge it (for `workflow-path` with the owner-approval release on, the 085 note instead asks for a trusted merger's approval on the current - head, which releases the fence, [#14664](https://github.com/hivecommons/hive/issues/14664)). + head, which releases the fence, [#14664](https://github.com/hivecommons/hive/issues/14664); + with `auto_merge.contributor_lane.workflow_fence_scope: + human_merge_paths`, an edit to a workflow file the repository does not + list there is no merge fence, so the adoption comment does not say the + merge stays manual and the lane merges the green head after review). + Supersession still refuses every workflow edit, whatever the scope. - **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/README.md b/src/docs/operator-reference/README.md index fcd00228c0..e640ddd7fa 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -557,6 +557,7 @@ advanced into the merge path. | `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:` (or at `ci-unverified` with every `pull_request` run on the head held), approve the head's `action_required` workflow runs once per hive process (`POST /repos/{owner}/{repo}/actions/runs/{id}/approve`; only fork `pull_request` runs and Actions-bot runs, the ones GitHub accepts; a 403 is not retried until the head changes or the App gains Actions write), 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 `/hive decision approve` (typed on the PR by the merger, or from the dashboard) bound to it — releases the contributor lane's `contributor-lane:workflow-path` fence (never for a head that also removes tests, which stays `contributor-lane:tests-removed`), so the lane merges a PR editing `.github/workflows/**` / `.github/actions/**` itself once CI, soak and the other gates are clear. The same approval answers a `requires_human` reviewer verdict on that head (a typed one is recorded as the decision, logging `typed approval recorded as the answer to the reviewer's requires_human question`); `/hive approve` answers the verdict but never releases the fence, so on the owner's own PR, where GitHub refuses the self-review, `/hive decision approve` is the one command for both ([Danathar/zfs-aurora-complex#254](https://github.com/Danathar/zfs-aurora-complex/pull/254)). Logs `workflow-path fence released by owner approval`, leaves one `hive:workflow-approval` audit comment per head, which says whether the verdict is answered; approval on an older head does not count, except across the hive's own base refresh: when only GitHub-verified App merges of the base branch (at most five) separate the approved head from the current one and the PR's three-dot diff is unchanged, the approval carries over and the lane logs `workflow-path fence approval carried over hive base refresh`. Any contributor push re-arms the fence. An unmarked approval binds to the PR `updated_at` pinned on the hive's first sweep of the head, not to the push, so one typed between the push and that sweep is judged stale and must be typed again ([#14754](https://github.com/hivecommons/hive/issues/14754)). 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.workflow_fence_scope` | `all` | Which CI workflow / action edits trip the `contributor-lane:workflow-path` fence. `all` fences every edit under `.github/workflows/**` or `.github/actions/**`. `human_merge_paths` fences only a workflow / action file that also matches the repository's `auto_merge.human_merge_paths` (the human-merge hold's matcher), so routine workflow edits go through review, CI and soak without an owner's approval. Fails closed: a repository with no `human_merge_paths` entry keeps the full fence, a renamed workflow / action file always trips it, and a head GitHub refused to merge for want of the App's **Workflows: Read and write** is marked `hive:unauthorized` (`merge-workflow-path`) and stays fenced. The tests-removed fence, Sentinel, the human-merge hold, the held-run approval guard (never for any workflow edit) and adoption's refusal to publish workflow edits upstream are unchanged. Sentinel's default `sensitive_path` list still labels such PRs `sentinel-alert`. Any other value is rejected on save and read as `all`. Owner-only through `PUT /api/config/auto-merge`; Settings → Features → Auto Merge → Contributor-lane auto-merge → **Workflow fence scope**. 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 306c6f78ba..ef8b0433cd 100644 --- a/src/pkg/config/automerge_trusted_bot_test.go +++ b/src/pkg/config/automerge_trusted_bot_test.go @@ -213,6 +213,39 @@ func TestContributorLaneAutoMergeConfigOwnerApprovalReleasesWorkflowFence(t *tes } } +// workflow_fence_scope defaults to all (today's full fence), accepts +// human_merge_paths in any case, and rejects anything else; a rejected value +// still reads as all, so it never narrows the fence. +func TestContributorLaneAutoMergeConfigWorkflowFenceScope(t *testing.T) { + var cfg ContributorLaneAutoMergeConfig + if got := cfg.EffectiveWorkflowFenceScope(); got != ContributorLaneWorkflowFenceScopeAll { + t.Fatalf("default workflow_fence_scope = %q, want all", got) + } + cfg.WorkflowFenceScope = " Human_Merge_Paths " + if err := cfg.Validate(); err != nil { + t.Fatalf("human_merge_paths scope should validate: %v", err) + } + if got := cfg.EffectiveWorkflowFenceScope(); got != ContributorLaneWorkflowFenceScopeHumanMergePaths { + t.Fatalf("workflow_fence_scope = %q, want human_merge_paths (trimmed, lower-cased)", got) + } + cfg.WorkflowFenceScope = "release_only" + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "workflow_fence_scope") { + t.Fatalf("invalid scope must fail validation, got %v", err) + } + if got := cfg.EffectiveWorkflowFenceScope(); got != ContributorLaneWorkflowFenceScopeAll { + t.Fatalf("unknown workflow_fence_scope = %q, want all (never narrows the fence)", got) + } + var parsed struct { + ContributorLane ContributorLaneAutoMergeConfig `yaml:"contributor_lane"` + } + if err := yaml.Unmarshal([]byte("contributor_lane:\n workflow_fence_scope: human_merge_paths\n"), &parsed); err != nil { + t.Fatal(err) + } + if got := parsed.ContributorLane.EffectiveWorkflowFenceScope(); got != ContributorLaneWorkflowFenceScopeHumanMergePaths { + t.Fatalf("yaml workflow_fence_scope = %q, want human_merge_paths", got) + } +} + func TestContributorTierAutoMergeConfigAutoPromoteDefault(t *testing.T) { var cfg ContributorTierAutoMergeConfig if got := cfg.EffectiveAutoPromoteAfterMerged(); got != DefaultContributorTierAutoPromoteAfterMerged { diff --git a/src/pkg/config/review_config.go b/src/pkg/config/review_config.go index 6ed2a2bf05..d4ec0e1f73 100644 --- a/src/pkg/config/review_config.go +++ b/src/pkg/config/review_config.go @@ -892,6 +892,46 @@ type ContributorLaneAutoMergeConfig struct { // 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"` + // WorkflowFenceScope picks which CI workflow / action edits trip the + // workflow-path fence. `all` (the default) fences every edit under + // `.github/workflows/**` or `.github/actions/**`. `human_merge_paths` + // fences only an edit to a file that also matches the repository's + // auto_merge.human_merge_paths, so routine workflow edits go through + // review, CI and soak like any other change; a repository with no + // human_merge_paths entry keeps the full fence. An unknown value is + // rejected by Validate and treated as `all`. + WorkflowFenceScope string `yaml:"workflow_fence_scope,omitempty" json:"workflow_fence_scope,omitempty"` +} + +// Contributor-lane workflow fence scopes +// (auto_merge.contributor_lane.workflow_fence_scope). +const ( + ContributorLaneWorkflowFenceScopeAll = "all" + ContributorLaneWorkflowFenceScopeHumanMergePaths = "human_merge_paths" +) + +// ContributorLaneWorkflowFenceScopes lists the accepted workflow_fence_scope +// values. +var ContributorLaneWorkflowFenceScopes = []string{ContributorLaneWorkflowFenceScopeAll, ContributorLaneWorkflowFenceScopeHumanMergePaths} + +// normalizedWorkflowFenceScope is workflow_fence_scope trimmed and +// lower-cased, with unset meaning `all`. +func (c ContributorLaneAutoMergeConfig) normalizedWorkflowFenceScope() string { + scope := strings.ToLower(strings.TrimSpace(c.WorkflowFenceScope)) + if scope == "" { + return ContributorLaneWorkflowFenceScopeAll + } + return scope +} + +// EffectiveWorkflowFenceScope returns the workflow fence scope the lane +// applies: `human_merge_paths` only when set to exactly that (any case), +// otherwise `all`, so an unknown value never narrows the fence. +func (c ContributorLaneAutoMergeConfig) EffectiveWorkflowFenceScope() string { + if c.normalizedWorkflowFenceScope() == ContributorLaneWorkflowFenceScopeHumanMergePaths { + return ContributorLaneWorkflowFenceScopeHumanMergePaths + } + return ContributorLaneWorkflowFenceScopeAll } // Contributor-lane auto-promotion scopes @@ -1067,6 +1107,9 @@ func (c ContributorLaneAutoMergeConfig) Validate() error { if scope := c.EffectiveAutoPromotionScope(); scope != ContributorLaneAutoPromotionScopeHive && scope != ContributorLaneAutoPromotionScopeRepo { return fmt.Errorf("auto_merge.contributor_lane.auto_promotion_scope: %q is not valid (allowed: %s)", c.AutoPromotionScope, strings.Join(ContributorLaneAutoPromotionScopes, ", ")) } + if scope := c.normalizedWorkflowFenceScope(); scope != ContributorLaneWorkflowFenceScopeAll && scope != ContributorLaneWorkflowFenceScopeHumanMergePaths { + return fmt.Errorf("auto_merge.contributor_lane.workflow_fence_scope: %q is not valid (allowed: %s)", c.WorkflowFenceScope, strings.Join(ContributorLaneWorkflowFenceScopes, ", ")) + } return nil } diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index 0108bef0e9..30cd6fff02 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -191,6 +191,7 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { AutoPromotionScope *string `json:"auto_promotion_scope"` ApproveHeldRunsForRegistryTrusted *bool `json:"approve_held_runs_for_registry_trusted"` OwnerApprovalReleasesWorkflowFence *bool `json:"owner_approval_releases_workflow_fence"` + WorkflowFenceScope *string `json:"workflow_fence_scope"` } `json:"contributor_lane"` } if err := decodeBody(r, &body); err != nil { @@ -274,6 +275,7 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { var contributorLaneLabels []string var contributorLaneTiers []string var contributorLaneScope string + var contributorLaneWorkflowFenceScope string if body.ContributorLane != nil { if body.ContributorLane.SoakMinutes != nil && *body.ContributorLane.SoakMinutes < 0 { jsonError(w, "contributor_lane.soak_minutes must be 0 (default 30) or greater", http.StatusBadRequest) @@ -308,6 +310,16 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { } contributorLaneScope = scope.EffectiveAutoPromotionScope() } + if body.ContributorLane.WorkflowFenceScope != nil { + // An unknown value is refused here; the lane reads anything but + // human_merge_paths as the full fence (EffectiveWorkflowFenceScope). + scope := config.ContributorLaneAutoMergeConfig{WorkflowFenceScope: *body.ContributorLane.WorkflowFenceScope} + if err := scope.Validate(); err != nil { + jsonError(w, "contributor_lane.workflow_fence_scope must be one of "+strings.Join(config.ContributorLaneWorkflowFenceScopes, ", "), http.StatusBadRequest) + return + } + contributorLaneWorkflowFenceScope = scope.EffectiveWorkflowFenceScope() + } } // --- apply --- @@ -425,6 +437,9 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { if body.ContributorLane.AutoPromotionScope != nil { cfg.AutoMerge.ContributorLane.AutoPromotionScope = contributorLaneScope } + if body.ContributorLane.WorkflowFenceScope != nil { + cfg.AutoMerge.ContributorLane.WorkflowFenceScope = contributorLaneWorkflowFenceScope + } } syncAutoMergePolicyToGitHubClient(cfg, s.deps.GHClient) @@ -554,6 +569,8 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "grantable_tiers": config.ContributorLaneGrantableTiers, "approve_held_runs_for_registry_trusted": cl.EffectiveApproveHeldRunsForRegistryTrusted(), "owner_approval_releases_workflow_fence": cl.EffectiveOwnerApprovalReleasesWorkflowFence(), + "workflow_fence_scope": cl.EffectiveWorkflowFenceScope(), + "workflow_fence_scopes": config.ContributorLaneWorkflowFenceScopes, }, } } diff --git a/src/pkg/dashboard/api_config_sections_test.go b/src/pkg/dashboard/api_config_sections_test.go index f73813f5fd..460b589463 100644 --- a/src/pkg/dashboard/api_config_sections_test.go +++ b/src/pkg/dashboard/api_config_sections_test.go @@ -643,6 +643,8 @@ func TestAutoMergeGet_ContributorLaneDefaults(t *testing.T) { AutoPromotionScopes []string `json:"auto_promotion_scopes"` ApproveHeldRuns bool `json:"approve_held_runs_for_registry_trusted"` OwnerApprovalWorkflow bool `json:"owner_approval_releases_workflow_fence"` + WorkflowFenceScope string `json:"workflow_fence_scope"` + WorkflowFenceScopes []string `json:"workflow_fence_scopes"` GrantableTiers []string `json:"grantable_tiers"` } `json:"contributor_lane"` } @@ -662,6 +664,9 @@ func TestAutoMergeGet_ContributorLaneDefaults(t *testing.T) { if cl.AutoPromotionScope != config.ContributorLaneAutoPromotionScopeHive || strings.Join(cl.AutoPromotionScopes, ",") != "hive,repo" { t.Fatalf("contributor_lane auto_promotion_scope defaults wrong: %+v", cl) } + if cl.WorkflowFenceScope != config.ContributorLaneWorkflowFenceScopeAll || strings.Join(cl.WorkflowFenceScopes, ",") != "all,human_merge_paths" { + t.Fatalf("contributor_lane workflow_fence_scope defaults wrong: %+v", cl) + } if strings.Join(cl.ExcludeLabels, ",") != strings.Join(config.DefaultContributorLaneExcludeLabels, ",") { t.Fatalf("contributor_lane default labels wrong: %v", cl.ExcludeLabels) } @@ -681,6 +686,7 @@ func TestAutoMergePut_ContributorLaneValidation(t *testing.T) { "auto_promotion_scope": " Repo ", "approve_held_runs_for_registry_trusted": false, "owner_approval_releases_workflow_fence": false, + "workflow_fence_scope": " Human_Merge_Paths ", }, } if rec := doPut(s, "/api/config/auto-merge", valid); rec.Code != http.StatusOK { @@ -696,6 +702,15 @@ func TestAutoMergePut_ContributorLaneValidation(t *testing.T) { if rec := doPut(s, "/api/config/auto-merge", map[string]any{"contributor_lane": map[string]any{"auto_promotion_scope": "fleet"}}); rec.Code != http.StatusBadRequest { t.Fatalf("invalid auto_promotion_scope: expected 400, got %d", rec.Code) } + if cl.WorkflowFenceScope != config.ContributorLaneWorkflowFenceScopeHumanMergePaths { + t.Fatalf("contributor_lane workflow_fence_scope not normalized: %q", cl.WorkflowFenceScope) + } + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"contributor_lane": map[string]any{"workflow_fence_scope": "release_only"}}); rec.Code != http.StatusBadRequest { + t.Fatalf("invalid workflow_fence_scope: expected 400, got %d", rec.Code) + } + if got := s.deps.Config.AutoMerge.ContributorLane.WorkflowFenceScope; got != config.ContributorLaneWorkflowFenceScopeHumanMergePaths { + t.Fatalf("rejected workflow_fence_scope write changed the stored value to %q", got) + } if strings.Join(cl.Repos, ",") != "widget" || strings.Join(cl.ExcludeLabels, ",") != "hold" { t.Fatalf("contributor_lane lists not normalized: repos=%v labels=%v", cl.Repos, cl.ExcludeLabels) } diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 04668fdcc2..b568f4421f 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -401,6 +401,10 @@ const amContributorLaneScopes = Array.isArray(amContributorLane.auto_promotion_scopes) && amContributorLane.auto_promotion_scopes.length ? amContributorLane.auto_promotion_scopes : ['hive','repo']; const amContributorLaneScopeLabel = { hive: "hive — every repository this hive manages", repo: "repo — the PR's repository only" }; const amContributorLaneScopeOptions = amContributorLaneScopes.map(v => ``).join(''); + const amContributorLaneFenceScope = typeof amContributorLane.workflow_fence_scope === 'string' && amContributorLane.workflow_fence_scope ? amContributorLane.workflow_fence_scope : 'all'; + const amContributorLaneFenceScopes = Array.isArray(amContributorLane.workflow_fence_scopes) && amContributorLane.workflow_fence_scopes.length ? amContributorLane.workflow_fence_scopes : ['all','human_merge_paths']; + const amContributorLaneFenceScopeLabel = { all: "all — every workflow / action file edit", human_merge_paths: "human_merge_paths — only workflow / action files listed in Human-merge paths" }; + const amContributorLaneFenceScopeOptions = amContributorLaneFenceScopes.map(v => ``).join(''); const amContributorLaneRepoSet = new Set((Array.isArray(amContributorLane.repos) ? amContributorLane.repos : []).map(r => String(r).toLowerCase())); const amContributorLaneRepoOptions = watchedRepos.map(r => ``).join(''); // Per-repo merge policy lists offer project.repos as owner/repo (the form @@ -643,6 +647,11 @@

A contributor's trust is a property of the person, not the repository: with hive, nine clean merges in the main repo also admit their first PR to a docs repo.

+
+ + +

With human_merge_paths, list every workflow, reusable workflow and local action your release workflows use in Human-merge paths: an edit to an unlisted one merges after review without an owner's approval.

+
@@ -652,7 +661,7 @@

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.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[].

+

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.workflow_fence_scope, auto_merge.contributor_lane.auto_promotion_scope, auto_merge.contributor_lane.repos[], auto_merge.contributor_lane.exclude_labels[], auto_merge.contributor_lane.require_tiers[].

Merge train
diff --git a/src/pkg/dashboard/static-src/js/config-helpers.js b/src/pkg/dashboard/static-src/js/config-helpers.js index d0a6d98b98..2c55343a89 100644 --- a/src/pkg/dashboard/static-src/js/config-helpers.js +++ b/src/pkg/dashboard/static-src/js/config-helpers.js @@ -442,6 +442,7 @@ const repos = document.getElementById('am-contributor-lane-repos'); const tiers = document.getElementById('am-contributor-lane-require-tiers'); const scope = document.getElementById('am-contributor-lane-auto-promotion-scope'); + const fenceScope = document.getElementById('am-contributor-lane-workflow-fence-scope'); const soakMinutes = soak ? parseInt(soak.value, 10) : 30; markDirty('auto-merge', 'contributor_lane', { enabled: !!(enabled && enabled.classList.contains('on')), @@ -451,6 +452,7 @@ 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', + workflow_fence_scope: fenceScope && fenceScope.value ? fenceScope.value : 'all', exclude_labels: labels ? labels.value.split(',').map(s => s.trim()).filter(Boolean) : [], repos: repos ? Array.from(repos.selectedOptions).map(o => o.value).filter(Boolean) : [], require_tiers: tiers ? tiers.value.split(',').map(s => s.trim().toLowerCase()).filter(Boolean) : [] diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 0fa54f9591..a4e2d13c01 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -66851,6 +66851,10 @@

${esc(s.title)}

const amContributorLaneScopes = Array.isArray(amContributorLane.auto_promotion_scopes) && amContributorLane.auto_promotion_scopes.length ? amContributorLane.auto_promotion_scopes : ['hive','repo']; const amContributorLaneScopeLabel = { hive: "hive — every repository this hive manages", repo: "repo — the PR's repository only" }; const amContributorLaneScopeOptions = amContributorLaneScopes.map(v => ``).join(''); + const amContributorLaneFenceScope = typeof amContributorLane.workflow_fence_scope === 'string' && amContributorLane.workflow_fence_scope ? amContributorLane.workflow_fence_scope : 'all'; + const amContributorLaneFenceScopes = Array.isArray(amContributorLane.workflow_fence_scopes) && amContributorLane.workflow_fence_scopes.length ? amContributorLane.workflow_fence_scopes : ['all','human_merge_paths']; + const amContributorLaneFenceScopeLabel = { all: "all — every workflow / action file edit", human_merge_paths: "human_merge_paths — only workflow / action files listed in Human-merge paths" }; + const amContributorLaneFenceScopeOptions = amContributorLaneFenceScopes.map(v => ``).join(''); const amContributorLaneRepoSet = new Set((Array.isArray(amContributorLane.repos) ? amContributorLane.repos : []).map(r => String(r).toLowerCase())); const amContributorLaneRepoOptions = watchedRepos.map(r => ``).join(''); // Per-repo merge policy lists offer project.repos as owner/repo (the form @@ -67093,6 +67097,11 @@

${esc(s.title)}

A contributor's trust is a property of the person, not the repository: with hive, nine clean merges in the main repo also admit their first PR to a docs repo.

+
+ + +

With human_merge_paths, list every workflow, reusable workflow and local action your release workflows use in Human-merge paths: an edit to an unlisted one merges after review without an owner's approval.

+
@@ -67102,7 +67111,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.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[].

+

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.workflow_fence_scope, auto_merge.contributor_lane.auto_promotion_scope, auto_merge.contributor_lane.repos[], auto_merge.contributor_lane.exclude_labels[], auto_merge.contributor_lane.require_tiers[].

Merge train
@@ -70237,6 +70246,7 @@

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'} s.trim()).filter(Boolean) : [], repos: repos ? Array.from(repos.selectedOptions).map(o => o.value).filter(Boolean) : [], require_tiers: tiers ? tiers.value.split(',').map(s => s.trim().toLowerCase()).filter(Boolean) : [] diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index ca73ba591d..e7a682419c 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -16,6 +16,7 @@ import ( "github.com/hivecommons/hive/pkg/delegatedecision" "github.com/hivecommons/hive/pkg/effects" hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/intent" "github.com/hivecommons/hive/pkg/stagelabels" "github.com/hivecommons/hive/pkg/writeback" ) @@ -266,22 +267,52 @@ func adoptionBlocked(labels []string) string { // return) is a standing files-evidence verdict with a nil error. A transport // failure reports files-evidence with the error set, so callers can tell a // transient read fault from a verdict; both are re-read on the next sweep. +// +// The verdict is deliberately the UNSCOPED one (workflow_fence_scope does not +// apply): every caller in this file uses the workflow-path verdict to refuse +// publishing workflow edits as an upstream branch, an execution guard, not a +// merge decision. The merge-side readers use adoptionMergeFence. func (c *Engine) adoptionDiffRefusal(ctx context.Context, obs stageObservation) (string, error) { + files, reason, err := c.adoptionDiffFiles(ctx, obs) + if reason != "" || err != nil { + return reason, err + } + return contributorLaneDiffReason(files), nil +} + +// adoptionMergeFence is adoptionDiffRefusal for merge decisions: the same +// head check and file evidence, judged by the lane's scoped merge fence +// (contributorLaneMergeFence), so the stage engine's explanations and merge +// asks name the fence the lane itself applies. +func (c *Engine) adoptionMergeFence(ctx context.Context, obs stageObservation) (string, error) { + files, reason, err := c.adoptionDiffFiles(ctx, obs) + if reason != "" || err != nil { + return reason, err + } + return c.contributorLaneMergeFence(c.currentContributorLanePolicy(), obs.Owner, obs.Repo, obs.Number, obs.HeadSHA, files), nil +} + +// adoptionDiffFiles reads obs's head's complete changed-file list for the +// diff fences. reason is non-empty when the fence cannot judge the head: +// adoptionReasonHeadChanged when the PR's head moved past obs, or +// contributorLaneReasonFilesEvidence (err set for a transport failure, nil +// for an incomplete list). +func (c *Engine) adoptionDiffFiles(ctx context.Context, obs stageObservation) ([]intent.ChangedFile, string, error) { pr, _, err := c.gh.PullRequests.Get(ctx, obs.Owner, obs.Repo, obs.Number) if err != nil { - return contributorLaneReasonFilesEvidence, err + return nil, contributorLaneReasonFilesEvidence, err } if head := pr.GetHead().GetSHA(); head == "" || head != obs.HeadSHA { - return adoptionReasonHeadChanged, nil + return nil, adoptionReasonHeadChanged, nil } files, err := ListChangedFiles(ctx, c.gh, obs.Owner, obs.Repo, pr) if errors.Is(err, hgithub.ErrIncompletePRFileList) { - return contributorLaneReasonFilesEvidence, nil + return nil, contributorLaneReasonFilesEvidence, nil } if err != nil { - return contributorLaneReasonFilesEvidence, err + return nil, contributorLaneReasonFilesEvidence, err } - return contributorLaneDiffReason(files), nil + return files, "", nil } // adoptionReasonHeadChanged is adoptionDiffRefusal's verdict for a PR whose @@ -859,7 +890,17 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor return 0, nil } store.ClearAdoptionBlocked(key) - fence, err := c.adoptionDiffRefusal(ctx, obs) + files, fence, err := c.adoptionDiffFiles(ctx, obs) + if fence == "" && err == nil { + fence = contributorLaneDiffReason(files) + } + // fence (unscoped) decides whether the head may be published upstream; + // mergeFence is what the lane will apply to its merge under + // workflow_fence_scope, which is what the adoption comment tells people. + mergeFence := fence + if fence == contributorLaneReasonWorkflowPath { + mergeFence = c.contributorLaneMergeFence(c.currentContributorLanePolicy(), obs.Owner, obs.Repo, obs.Number, obs.HeadSHA, files) + } if fence != "" && (err != nil || adoptionFenceDefers(fence)) { // The fence could not judge this head (it moved, or its file list // is incomplete / unreadable). Not recorded as an attempt: the PR @@ -930,7 +971,7 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor store.MarkAdoptedForReview(key, obs.HeadSHA) } c.recordContributorAbandon(ctx, obs, reason, 0, now) - body := AdoptionInPlaceComment(obs, policy.HiveID, reason, grace, rec.NudgeOnline) + adoptionFenceNote(fence) + body := AdoptionInPlaceComment(obs, policy.HiveID, reason, grace, rec.NudgeOnline) + adoptionFenceNote(mergeFence) if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { c.warn("stage labels: adoption comment failed", "repo", obs.Display, "pr", obs.Number, "error", err) return 0, err diff --git a/src/pkg/github/automerge/automerge_contributor_held_runs.go b/src/pkg/github/automerge/automerge_contributor_held_runs.go index 152e970af1..433422b50d 100644 --- a/src/pkg/github/automerge/automerge_contributor_held_runs.go +++ b/src/pkg/github/automerge/automerge_contributor_held_runs.go @@ -74,7 +74,10 @@ func (c *Engine) approveHeldRunsForRegistryTrusted(ctx context.Context, displayR if c.sentinelLabelPresent(labels) || policy.excludedLabel(labels) != "" || c.labelBlockReason(labels, false) != "" { return nil, reason } - if contributorLaneDiffReason(files) == contributorLaneReasonWorkflowPath { + // Unscoped on purpose: approving held runs decides what code runs in CI, + // so every workflow / action edit stays a person's call whatever + // workflow_fence_scope narrows the merge fence to. + if contributorLaneTouchesWorkflowFiles(files) { return nil, reason } fullRepo := owner + "/" + repo diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 13a52c614f..5e098c4a01 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -230,6 +230,11 @@ type ContributorLanePolicy struct { // (auto_merge.contributor_lane.owner_approval_releases_workflow_fence, // default on). See automerge_contributor_workflow_approval.go. OwnerApprovalReleasesWorkflowFence bool + // WorkflowFenceScope is auto_merge.contributor_lane.workflow_fence_scope: + // "human_merge_paths" fences only workflow / action edits that match the + // repository's auto_merge.human_merge_paths; anything else (the default, + // "all") fences every such edit. See automerge_workflow_fence_scope.go. + WorkflowFenceScope string } // Contributor-lane auto-promotion scopes; mirrors @@ -1436,6 +1441,11 @@ type contributorLaneEval struct { // workflowApprover is the trusted merger whose approval released the // workflow-path fence for headSHA ("" when the fence did not trip). workflowApprover string + // workflowUnfenced is set when the head edits CI workflow / action files + // that workflow_fence_scope left outside the fence, so a merge GitHub + // refuses for want of `workflows: write` is handled like a released + // fence's (workflowFenceMergeUnauthorized). + workflowUnfenced bool // soakStartedAt / soakRemaining are the soak clock the lane holds // headSHA on when the skip reason is contributorLaneReasonSoaking: // when the head was first seen green and how long is left. The reason @@ -1540,7 +1550,19 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own if err != nil { return eval, contributorLaneReasonFilesEvidence, err } - if reason := contributorLaneDiffReason(files); reason != "" { + // The merge fence for this head, with the workflow-path verdict scoped by + // workflow_fence_scope (automerge_workflow_fence_scope.go). A workflow + // edit the scope waives still stays fenced once the App has been refused + // this head's merge for want of `workflows: write`. + diffReason := c.contributorLaneMergeFence(policy, owner, repo, number, headSHA, files) + if diffReason == "" && contributorLaneTouchesWorkflowFiles(files) { + if c.workflowMergeRefusedOnRecord(ctx, displayRepo, owner, repo, pr, number, headSHA) { + diffReason = contributorLaneReasonWorkflowPath + } else { + eval.workflowUnfenced = true + } + } + if reason := diffReason; reason != "" { // contributorLaneDiffReason names only the first fence, and the // owner-approval release lifts the workflow fence alone: a head that // also removes tests merged on that approval with its test removal diff --git a/src/pkg/github/automerge/automerge_contributor_workflow_approval.go b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go index e5a4b61cdd..78f5490ac7 100644 --- a/src/pkg/github/automerge/automerge_contributor_workflow_approval.go +++ b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go @@ -3,7 +3,10 @@ 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). +// `.github/workflows/**` or `.github/actions/**` (contributorLaneDiffReason), +// or with workflow_fence_scope: human_merge_paths only one whose edited +// workflow / action file is also a human-merge path +// (automerge_workflow_fence_scope.go). // 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 @@ -514,17 +517,18 @@ func (c *Engine) commentWorkflowApproval(ctx context.Context, owner, repo string } // workflowFenceMergeUnauthorized handles a merge failure on a PR whose -// workflow-path fence owner approval released. When GitHub refused the merge +// workflow-path fence owner approval released, or whose workflow edits +// workflow_fence_scope left outside the fence. 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) { + if (eval.workflowApprover == "" && !eval.workflowUnfenced) || !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.warn("workflow-path merge refused: App lacks workflows permission", "repo", displayRepo, "pr", eval.pr.GetNumber(), "head", eval.headSHA, "approver", eval.workflowApprover, "outside_fence_scope", eval.workflowUnfenced, "error", err) c.markUnauthorized(ctx, displayRepo, owner, repo, eval.pr, eval.pr.GetNumber(), eval.headSHA, unauthorizedStepMergeWorkflowPath, unauthorizedPermissionWorkflowsWrite, mergeWorkflowPathHumanAction()) return contributorLaneReasonWorkflowPath } diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index bfafca01fd..4e6c1386ac 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -104,26 +104,30 @@ func (c *Engine) headChecks(ctx context.Context, tracker *StageTracker, key stri } // humanFenceEntry is one head's contributor-lane diff fence ("" when the -// diff is clean). +// diff is clean), with the workflow fence scope it was judged under. type humanFenceEntry struct { head string + scope string fence string } -// headDiffFence returns the contributor lane's diff fence for obs's head -// (contributorLaneDiffReason: workflow / action files, tests removed), cached -// per head: a head's diff does not change, and a push is a new head. ok is +// headDiffFence returns the contributor lane's merge diff fence for obs's +// head (contributorLaneMergeFence: workflow / action files as +// workflow_fence_scope scopes them, tests removed), cached per head and +// scope: a head's diff does not change, a push is a new head, and a change +// to the scope or the repository's human_merge_paths is re-read. ok is // false when it could not be read (transport error, incomplete file list, or // the PR's head moved past obs); nothing is cached then, so the next pass // tries again. func (c *Engine) headDiffFence(ctx context.Context, tracker *StageTracker, key string, obs stageObservation) (string, bool) { + scope := c.workflowFenceScopeKey(c.currentContributorLanePolicy(), obs.Owner, obs.Repo, obs.Number, obs.HeadSHA) tracker.mu.Lock() entry, ok := tracker.fences[key] tracker.mu.Unlock() - if ok && entry.head == obs.HeadSHA { + if ok && entry.head == obs.HeadSHA && entry.scope == scope { return entry.fence, true } - fence, err := c.adoptionDiffRefusal(ctx, obs) + fence, err := c.adoptionMergeFence(ctx, obs) if err != nil { c.warn("stage labels: diff fence read failed", "repo", obs.Display, "pr", obs.Number, "error", err) return "", false @@ -135,7 +139,7 @@ func (c *Engine) headDiffFence(ctx context.Context, tracker *StageTracker, key s if tracker.fences == nil { tracker.fences = map[string]humanFenceEntry{} } - tracker.fences[key] = humanFenceEntry{head: obs.HeadSHA, fence: fence} + tracker.fences[key] = humanFenceEntry{head: obs.HeadSHA, scope: scope, fence: fence} tracker.mu.Unlock() return fence, true } diff --git a/src/pkg/github/automerge/automerge_workflow_fence_scope.go b/src/pkg/github/automerge/automerge_workflow_fence_scope.go new file mode 100644 index 0000000000..8cdb19b2ea --- /dev/null +++ b/src/pkg/github/automerge/automerge_workflow_fence_scope.go @@ -0,0 +1,150 @@ +package automerge + +// Workflow fence scope (auto_merge.contributor_lane.workflow_fence_scope). +// +// The contributor lane's workflow-path fence keeps a PR that edits CI +// workflow / action definitions (contributorLaneWorkflowPaths) from merging +// without a hive owner's approval of its head (automerge_contributor_workflow_approval.go). +// With the default scope, "all", every such edit trips it. With +// "human_merge_paths" only an edit to a file that also matches the +// repository's auto_merge.human_merge_paths does, so a routine pin bump or +// permission change in a workflow the operator did not list goes through +// review, CI and soak like any other change. The operator already lists the +// release-critical workflows there for the human-merge hold; this reuses the +// list and its matcher (intent.HumanMergePathMatches) rather than adding a +// second one. +// +// Fail closed: a repository with no human_merge_paths entry keeps the full +// fence, as does a renamed workflow / action file (the files API reports the +// new name only, so a listed file renamed away would otherwise escape) and a +// head the App could not merge for want of `workflows: write`. +// +// Only the MERGE fence is scoped. Two guards stay on every workflow edit: +// - automerge_contributor_held_runs.go never approves held fork Actions +// runs for a diff that touches CI definitions (contributorLaneTouchesWorkflowFiles): +// that decides what code runs in CI, not what merges. +// - adoption never publishes a workflow edit as an upstream branch +// (adoptionDiffRefusal, hivecommons/hive#14055): pull_request workflows +// there run with repository context before any merge gate. +// The tests-removed fence, Sentinel, the human-merge hold and the pin-only +// exception are untouched. +// +// Every merge-side reader (the lane, the stage engine's explanations via +// headDiffFence, the merge asks via headManualMergeRule, `/hive approve`) +// goes through contributorLaneMergeFence, so they cannot disagree. + +import ( + "context" + "strings" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/config" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/intent" +) + +// workflowFenceScopedToHumanMergePaths reports whether the policy limits the +// workflow-path fence to human_merge_paths. Anything but that exact value +// (any case) is the full fence. +func (p ContributorLanePolicy) workflowFenceScopedToHumanMergePaths() bool { + return strings.EqualFold(strings.TrimSpace(p.WorkflowFenceScope), config.ContributorLaneWorkflowFenceScopeHumanMergePaths) +} + +// contributorLaneWorkflowFiles returns the changed files that are CI +// workflow / action definitions (contributorLaneWorkflowPaths). +func contributorLaneWorkflowFiles(files []intent.ChangedFile) []intent.ChangedFile { + var out []intent.ChangedFile + for _, f := range files { + if intent.PathMatchesAny(f.Filename, contributorLaneWorkflowPaths) { + out = append(out, f) + } + } + return out +} + +// contributorLaneTouchesWorkflowFiles reports whether the diff edits any CI +// workflow / action definition, whatever the fence scope. Execution guards +// (held-run approval) use it; merge decisions use contributorLaneMergeFence. +func contributorLaneTouchesWorkflowFiles(files []intent.ChangedFile) bool { + return len(contributorLaneWorkflowFiles(files)) > 0 +} + +// workflowFenceCovers reports whether the workflow-path fence applies to +// this head's workflow / action edits under policy's scope: always for the +// full fence; under human_merge_paths when the repository lists no paths, +// when a workflow / action file was renamed, when the App was refused this +// head's merge for want of `workflows: write`, or when a workflow / action +// file matches the repository's human_merge_paths. +func (c *Engine) workflowFenceCovers(policy ContributorLanePolicy, owner, repo string, number int, headSHA string, files []intent.ChangedFile) bool { + if !policy.workflowFenceScopedToHumanMergePaths() { + return true + } + patterns := c.currentHumanMergePaths(owner + "/" + repo) + if len(patterns) == 0 { + return true + } + if c.unauthorizedStep(owner, repo, number, headSHA) == unauthorizedStepMergeWorkflowPath { + return true + } + workflow := contributorLaneWorkflowFiles(files) + for _, f := range workflow { + if strings.EqualFold(strings.TrimSpace(f.Status), "renamed") { + return true + } + } + return len(intent.HumanMergePathMatches(workflow, patterns)) > 0 +} + +// contributorLaneMergeFence is the contributor lane's merge diff fence for a +// head: contributorLaneDiffReason with the workflow-path verdict scoped by +// auto_merge.contributor_lane.workflow_fence_scope. A workflow edit outside +// the scope falls through to the tests-removed check, so test deletion +// still stops the merge. It returns "" when the diff may merge unattended. +func (c *Engine) contributorLaneMergeFence(policy ContributorLanePolicy, owner, repo string, number int, headSHA string, files []intent.ChangedFile) string { + reason := contributorLaneDiffReason(files) + if reason != contributorLaneReasonWorkflowPath || c.workflowFenceCovers(policy, owner, repo, number, headSHA, files) { + return reason + } + return contributorLaneTestsRemovedReason(files) +} + +// workflowFenceScopeKey names the inputs contributorLaneMergeFence reads +// besides the diff, so a cached verdict for a head (headDiffFence) is +// re-read when the scope, the repository's human_merge_paths or the +// head's workflows-permission refusal changes. +func (c *Engine) workflowFenceScopeKey(policy ContributorLanePolicy, owner, repo string, number int, headSHA string) string { + if !policy.workflowFenceScopedToHumanMergePaths() { + return config.ContributorLaneWorkflowFenceScopeAll + } + key := config.ContributorLaneWorkflowFenceScopeHumanMergePaths + "\x00" + strings.Join(c.currentHumanMergePaths(owner+"/"+repo), "\x00") + if c.unauthorizedStep(owner, repo, number, headSHA) == unauthorizedStepMergeWorkflowPath { + key += "\x00unauthorized" + } + return key +} + +// workflowMergeRefusedOnRecord reports whether an earlier pass already +// learnt that the App cannot merge this head's workflow edits (the durable +// hive:unauthorized merge-workflow-path comment covers it), re-arming the +// in-memory mark so the head stays fenced without another merge attempt. +// The lane asks only for a workflow edit the scope waived; the fence's own +// release path re-arms the mark the same way (workflowFenceReleased). An +// unreadable comment list keeps the fence (fail closed) without marking. +func (c *Engine) workflowMergeRefusedOnRecord(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, number int, headSHA string) bool { + if c == nil || c.gh == nil { + return true + } + if c.unauthorizedStep(owner, repo, number, headSHA) == unauthorizedStepMergeWorkflowPath { + return true + } + comments, err := c.listIssueComments(hgithub.WithRESTCaller(ctx, workflowApprovalRESTCaller), owner, repo, number) + if err != nil { + c.warn("workflow fence scope: could not read comments; keeping the fence", "repo", displayRepo, "pr", number, "head", headSHA, "error", err) + return true + } + if !unauthorizedCommentCoversHead(comments, unauthorizedStepMergeWorkflowPath, headSHA) { + return false + } + c.markUnauthorized(ctx, displayRepo, owner, repo, pr, number, headSHA, unauthorizedStepMergeWorkflowPath, unauthorizedPermissionWorkflowsWrite, mergeWorkflowPathHumanAction()) + return true +} diff --git a/src/pkg/github/automerge/automerge_workflow_fence_scope_test.go b/src/pkg/github/automerge/automerge_workflow_fence_scope_test.go new file mode 100644 index 0000000000..8df2931f38 --- /dev/null +++ b/src/pkg/github/automerge/automerge_workflow_fence_scope_test.go @@ -0,0 +1,344 @@ +package automerge + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/config" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/intent" +) + +// testReleaseWorkflow is the release-critical workflow the scope tests list +// in auto_merge.human_merge_paths, as knuckle's repos list build.yml. +const testReleaseWorkflow = ".github/workflows/build.yml" + +func scopedFencePolicy() ContributorLanePolicy { + policy := defaultContributorLanePolicy() + policy.WorkflowFenceScope = config.ContributorLaneWorkflowFenceScopeHumanMergePaths + return policy +} + +// workflow_fence_scope: human_merge_paths fences only the workflow / action +// files the repository lists in human_merge_paths; every other rule stays +// as it was. On v6 tip the fence ignores the list, so every case that +// expects a merge (or tests-removed) instead stops at workflow-path. +func TestContributorLaneWorkflowFenceScope(t *testing.T) { + file := func(name, status string) map[string]any { + return map[string]any{"filename": name, "status": status, "additions": 2, "deletions": 1} + } + listed := humanPathsFor("acme/widget", testReleaseWorkflow) + for _, tc := range []struct { + name string + scope string + paths func(string) []string + files []map[string]any + wantReason string + wantMerges int + }{ + { + name: "scope all keeps the full fence on an unlisted workflow", + scope: config.ContributorLaneWorkflowFenceScopeAll, + paths: listed, + files: []map[string]any{file(".github/workflows/lint.yml", "modified")}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "unset scope keeps the full fence", + paths: listed, + files: []map[string]any{file(".github/workflows/lint.yml", "modified")}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "unknown scope keeps the full fence", + scope: "release_only", + paths: listed, + files: []map[string]any{file(".github/workflows/lint.yml", "modified")}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "scoped: unlisted workflow merges through review, CI and soak", + scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, + paths: listed, + files: []map[string]any{file(".github/workflows/lint.yml", "modified")}, + wantMerges: 1, + }, + { + name: "scoped: unlisted local action merges", + scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, + paths: listed, + files: []map[string]any{file(".github/actions/setup/action.yml", "modified")}, + wantMerges: 1, + }, + { + name: "scoped: listed workflow keeps the fence", + scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, + paths: listed, + files: []map[string]any{file(".github/workflows/lint.yml", "modified"), file(testReleaseWorkflow, "modified")}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "scoped: repo without a human_merge_paths entry keeps the fence", + scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, + paths: humanPathsFor("acme/other", testReleaseWorkflow), + files: []map[string]any{file(".github/workflows/lint.yml", "modified")}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "scoped: renamed workflow keeps the fence", + scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, + paths: listed, + files: []map[string]any{file(".github/workflows/lint.yml", "renamed")}, + wantReason: contributorLaneReasonWorkflowPath, + }, + { + name: "scoped: tests removed still wins", + scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, + paths: listed, + files: []map[string]any{file(".github/workflows/lint.yml", "modified"), {"filename": "pkg/widget/widget_test.go", "status": "removed", "additions": 0, "deletions": 40}}, + wantReason: contributorLaneReasonTestsRemoved, + }, + } { + t.Run(tc.name, func(t *testing.T) { + fx := validContributorFixture() + fx.files = tc.files + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.WorkflowFenceScope = tc.scope + clock := &contributorLaneClock{at: mustParseTime(t, "2026-10-27T13:00:00Z")} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock), HumanMergePaths: tc.paths}) + _, 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) + } + }) + } +} + +// A workflow edit the scope waives still needs the App's workflows: write to +// merge. A refusal for want of it marks the head hive:unauthorized and stops +// at workflow-path, as for an owner-released fence, and neither a second +// tick nor a restart that sees the marker tries the merge again. On v6 tip +// the head never reaches the merge at all (no merge attempt on tick one). +func TestContributorLaneWorkflowFenceScopeMergeUnauthorized(t *testing.T) { + for _, tc := range []struct { + name string + restart bool + wantMerges int + }{ + {name: "first refusal marks the head", wantMerges: 1}, + {name: "restart sees the marker and does not retry", restart: true, wantMerges: 0}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := validContributorFixture() + fx.files = []map[string]any{{"filename": ".github/workflows/lint.yml", "status": "modified", "additions": 1, "deletions": 1}} + fx.mergeStatus = http.StatusForbidden + fx.mergeMessage = "Resource not accessible by integration" + 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", unauthorizedAttempts{Count: 1, Heads: []string{"sha7"}}), + }} + } + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := scopedFencePolicy() + clock := &contributorLaneClock{at: mustParseTime(t, "2026-10-27T13:00:00Z")} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ContributorSoak: soakedTracker(clock), HumanMergePaths: humanPathsFor("acme/widget", testReleaseWorkflow)}) + 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 !engine.workflowFenceManual("acme", "widget", 7, "sha7") { + t.Fatal("workflowFenceManual = false after an unauthorized merge, want true") + } + }) + } +} + +// The held-run guard is an execution guard, not the merge fence: a registry- +// trusted fork PR whose workflow edit the scope lets merge still never has +// its held Actions runs approved by the hive. Scoping that guard with the +// merge fence would approve runs 11 and 12 here. +func TestContributorLaneWorkflowFenceScopeKeepsHeldRunsRefused(t *testing.T) { + fx := validContributorFixture() + fx.body = "Part of #42\n\nSome change." + fx.issueComments = nil + fx.baseRef = "main" + fx.requiredContexts = []string{"ci/build", contributorHeldRunsTestContext} + fx.headRepo = "thatguywob/widget" + fx.files = []map[string]any{{"filename": ".github/workflows/lint.yml", "status": "modified", "additions": 1, "deletions": 1}} + fx.workflowRuns = []map[string]any{heldRun(11, fx.headRepo), heldRun(12, fx.headRepo)} + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := scopedFencePolicy() + policy.RegistryTiersSufficient = true + policy.ApproveHeldRunsForRegistryTrusted = true + clock := &contributorLaneClock{at: mustParseTime(t, "2026-10-27T13:00:00Z")} + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ + ContributorRegistryTier: registryTiers(map[string]string{contributorLaneTestAuthor: "trusted"}), + ContributorSoak: soakedTracker(clock), + HumanMergePaths: humanPathsFor("acme/widget", testReleaseWorkflow), + }) + _, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatal(err) + } + if want := requiredCheckMissingPrefix + contributorHeldRunsTestContext; reason != want { + t.Fatalf("reason = %q, want %q (the scoped fence lets the head reach CI)", reason, want) + } + if len(fx.approvedRuns) != 0 || fx.merges != 0 { + t.Fatalf("approved runs = %v merges = %d, want none: held runs stay a person's call for any workflow edit", fx.approvedRuns, fx.merges) + } +} + +// The helpers on their own: the merge fence is scoped, the execution check +// is not. +func TestContributorLaneMergeFenceHelpers(t *testing.T) { + e := New(nil, Options{HumanMergePaths: humanPathsFor("acme/widget", testReleaseWorkflow)}) + unlisted := []intent.ChangedFile{{Filename: ".github/workflows/lint.yml", Status: "modified"}} + listedFiles := []intent.ChangedFile{{Filename: testReleaseWorkflow, Status: "modified"}} + scoped := scopedFencePolicy() + all := defaultContributorLanePolicy() + if got := e.contributorLaneMergeFence(all, "acme", "widget", 7, "sha7", unlisted); got != contributorLaneReasonWorkflowPath { + t.Fatalf("scope all, unlisted = %q, want workflow-path", got) + } + if got := e.contributorLaneMergeFence(scoped, "acme", "widget", 7, "sha7", unlisted); got != "" { + t.Fatalf("scoped, unlisted = %q, want no fence", got) + } + if got := e.contributorLaneMergeFence(scoped, "acme", "widget", 7, "sha7", listedFiles); got != contributorLaneReasonWorkflowPath { + t.Fatalf("scoped, listed = %q, want workflow-path", got) + } + if got := e.contributorLaneMergeFence(scoped, "acme", "gadget", 7, "sha7", unlisted); got != contributorLaneReasonWorkflowPath { + t.Fatalf("scoped, repo without paths = %q, want workflow-path", got) + } + if !contributorLaneTouchesWorkflowFiles(unlisted) || contributorLaneTouchesWorkflowFiles([]intent.ChangedFile{{Filename: "src/x.go"}}) { + t.Fatal("contributorLaneTouchesWorkflowFiles must report every workflow edit, whatever the scope") + } + if e.workflowFenceScopeKey(scoped, "acme", "widget", 7, "sha7") == e.workflowFenceScopeKey(all, "acme", "widget", 7, "sha7") { + t.Fatal("the stage cache key must change with the scope") + } +} + +// scopedStageFence turns on the scoped fence with build.yml listed for +// acme/widget, on the stage engine the 085 notes come from. +func scopedStageFence(release bool) func(*Engine) { + return func(e *Engine) { + e.contributorLanePolicy = func() ContributorLanePolicy { + return ContributorLanePolicy{Enabled: true, RequireTiers: map[string]bool{"trusted": true}, OwnerApprovalReleasesWorkflowFence: release, WorkflowFenceScope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths} + } + e.SetHumanMergePaths(humanPathsFor("acme/widget", testReleaseWorkflow)) + } +} + +// The stage engine's 085 note names the fence the lane applies. Behind a +// sentinel alert (which the lane reaches before its diff fence) an unlisted +// workflow edit is not called a manual merge or an approval-gated fence, +// and a listed one still is. On v6 tip the unlisted case reads "merge this +// PR manually", as for any workflow edit. +func TestWorkflowFenceScopeStageNoteAgreesWithLane(t *testing.T) { + t.Run("unlisted workflow", func(t *testing.T) { + _, closeAPI, sweep := manualMergeSweepWith(t, scopedStageFence(false), []string{".github/workflows/lint.yml"}, requiresHumanVerdict, + contributorLaneReasonSentinelBlocked, "role/trusted", "author/clanker", "stage/050-review-pending", "sentinel-alert") + defer closeAPI() + comments := sweep() + if len(comments) != 1 { + t.Fatalf("comments = %q", comments) + } + c := comments[0] + if !strings.Contains(c, "Needs a decision, not a merge") || !strings.Contains(c, "approves this head") { + t.Fatalf("085 comment = %q", c) + } + for _, unwanted := range []string{"merge this PR manually", "edits CI workflow / action files", "workflow-file fence"} { + if strings.Contains(c, unwanted) { + t.Fatalf("085 comment must not say %q for a workflow edit outside the fence scope:\n%s", unwanted, c) + } + } + }) + t.Run("listed workflow", func(t *testing.T) { + _, closeAPI, sweep := manualMergeSweepWith(t, scopedStageFence(false), []string{testReleaseWorkflow}, requiresHumanVerdict, + contributorLaneReasonSentinelBlocked, "role/trusted", "author/clanker", "stage/050-review-pending", "sentinel-alert") + defer closeAPI() + comments := sweep() + if len(comments) != 1 || !strings.Contains(comments[0], "edits CI workflow / action files") || + !strings.Contains(comments[0], "a maintainer must review and merge this PR manually") { + t.Fatalf("085 comment = %q", comments) + } + }) +} + +// `/hive approve` reads the same scoped fence as the lane: an unlisted +// workflow edit gets the ordinary acknowledgement (the lane merges it +// after review), a listed one is still a person's merge, and scope all +// keeps today's owner-approval wording. On v6 tip the unlisted case gets +// the owner-approval wording instead. +func TestPRApproveReplyWorkflowFenceScope(t *testing.T) { + for _, tc := range []struct { + name, file, scope, want string + }{ + {name: "scoped unlisted workflow", file: ".github/workflows/lint.yml", scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, want: "`/hive approve` acknowledged: "}, + {name: "scoped listed workflow", file: testReleaseWorkflow, scope: config.ContributorLaneWorkflowFenceScopeHumanMergePaths, want: "requires a person to merge manually"}, + {name: "scope all unlisted workflow", file: ".github/workflows/lint.yml", scope: config.ContributorLaneWorkflowFenceScopeAll, want: "merges only on a hive owner's explicit approval"}, + } { + t.Run(tc.name, func(t *testing.T) { + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Errorf("feedback must not mutate: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusForbidden) + return + } + switch r.URL.Path { + case "/repos/acme/widget/pulls/7": + json.NewEncoder(w).Encode(&gh.PullRequest{Number: gh.Ptr(7), State: gh.Ptr("open"), User: &gh.User{Login: gh.Ptr("contributor")}, Head: &gh.PullRequestBranch{SHA: gh.Ptr("sha7")}}) + case "/repos/acme/widget/pulls/7/files": + json.NewEncoder(w).Encode([]*gh.CommitFile{{Filename: gh.Ptr(tc.file), Status: gh.Ptr("modified")}}) + default: + t.Errorf("unexpected read: %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer api.Close() + client := hgithub.NewClient("token", "acme", []string{"widget"}, nil, api.URL) + client.SetAppBotLogin(testHiveAppBotLogin) + e := New(client, Options{ + MergerAuthorizer: func(login string) bool { return login == "owner" }, + TrustedAuthorPolicy: func() TrustedAuthorPolicy { return TrustedAuthorPolicy{} }, + TrustedAuthorizer: func(string, string) TrustedAuthorDecision { return TrustedAuthorDecision{} }, + ContributorLanePolicy: func() ContributorLanePolicy { + return ContributorLanePolicy{Enabled: true, OwnerApprovalReleasesWorkflowFence: true, WorkflowFenceScope: tc.scope} + }, + ContributorLaneVerdict: func(string, int, string) ContributorLaneVerdict { + return ContributorLaneVerdict{Configured: true, Verdict: "requires_human"} + }, + HumanMergePaths: humanPathsFor("acme/widget", testReleaseWorkflow), + RepoAutoMergeEnabled: func(string) bool { return true }, + }) + reply, err := e.PRApproveReply(context.Background(), "acme/widget", 7, &gh.IssueComment{Body: gh.Ptr("/hive approve"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}}) + if err != nil || !strings.Contains(reply, tc.want) { + t.Fatalf("reply=%q err=%v, want %q", reply, err, tc.want) + } + }) + } +} diff --git a/src/pkg/github/automerge/pr_approve_command.go b/src/pkg/github/automerge/pr_approve_command.go index ced1f37640..48e91f194d 100644 --- a/src/pkg/github/automerge/pr_approve_command.go +++ b/src/pkg/github/automerge/pr_approve_command.go @@ -83,7 +83,9 @@ func (c *Engine) PRApproveReply(ctx context.Context, displayRepo string, number } diffReason := "" if contributor { - diffReason = contributorLaneDiffReason(files) + // The lane's own merge fence, scoped the same way + // (automerge_workflow_fence_scope.go). + diffReason = c.contributorLaneMergeFence(c.currentContributorLanePolicy(), owner, repo, number, head, files) } // The same pin-only exception the sweep lanes apply (#16266), so the // reply never contradicts what the lane will do on its next pass.