From a8efb46982ae2d24235f7de21b9b4ead4f1b80ab Mon Sep 17 00:00:00 2001 From: Danathar <6772335+Danathar@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:46:04 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20auto-merge:=20an=20owner's=20ap?= =?UTF-8?q?proval=20of=20the=20head=20releases=20the=20human-merge-path=20?= =?UTF-8?q?hold=20(opt-in=20per=20repo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New key auto_merge.human_merge_owner_approval, a list of owner/repo, empty by default. On a listed repository a trusted merger's explicit approval of a PR's current head releases the hold the human-merge-path gate put on it, and the merge lanes merge the PR once CI, review, soak and every other gate pass. Unlisted repositories keep today's rule and `/hive approve` reply word for word. - Approval: the workflow-path fence's (workflowFenceApproval: Approve review, dashboard approve, typed /hive decision approve) plus a trusted merger's /hive approve posted after the head was first seen. - Release: the stage-label pass, next to the stale-head lift, through ReleaseApprovedHumanMergePathHold. It shares the pin-only release's provenance checks, widened only so it may lift the hold on the head it was put on and a hold the App re-added on a later head; any person's hold application, another hold source, or a write-back refusal keeps the hold. The gate lets an approved head through instead of re-holding. - Audit: one comment per head names the approver and head, plus a log line. - 085 route asks for the approval instead of a manual merge; the /hive approve reply says "released for ". - Dashboard multi-select with help mark, PUT/PATCH validation (400 for a repo outside project.repos), admin MCP auto_merge.update row. - Docs: hive-merge.md section, maintainer-commands.md, settings.md, admin-mcp.md, api-reference.md; changelog fragment. Refs Danathar/goodreads-mcp#463. Signed-off-by: Danathar <6772335+Danathar@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 --- .../added-human-merge-owner-approval.md | 1 + src/cmd/hive/main.go | 1 + src/cmd/hive/main_sweeps.go | 2 + src/docs/admin-mcp.md | 8 +- src/docs/api-reference.md | 2 +- src/docs/hive-merge.md | 44 +++ src/docs/maintainer-commands.md | 8 +- src/docs/settings.md | 2 +- src/pkg/adminmcp/tools_automerge_ops.go | 1 + src/pkg/adminmcp/tools_automerge_ops_test.go | 32 ++ src/pkg/adminmcp/tools_settings.go | 2 +- ...tomerge_human_merge_owner_approval_test.go | 25 ++ src/pkg/config/review_config.go | 16 + src/pkg/dashboard/api_config_automerge.go | 22 ++ .../api_config_automerge_repo_policy_test.go | 46 +++ .../dashboard_mcp_parity_controls_test.go | 40 +++ src/pkg/dashboard/diag_config_value_keys.txt | 1 + .../static-src/js/config-features.js | 6 +- .../dashboard/static-src/js/config-helpers.js | 1 + src/pkg/dashboard/static/index.html | 7 +- .../automerge_human_merge_owner_approval.go | 274 ++++++++++++++++++ ...tomerge_human_merge_owner_approval_test.go | 257 ++++++++++++++++ .../automerge_human_merge_path_fence.go | 16 +- .../github/automerge/automerge_human_paths.go | 8 +- .../github/automerge/automerge_stage_human.go | 16 +- .../automerge/automerge_stage_labels.go | 18 ++ src/pkg/github/automerge/automerge_sweep.go | 7 + .../github/automerge/pr_approve_command.go | 3 + src/pkg/github/human_merge_path_release.go | 78 ++++- .../github/human_merge_path_release_test.go | 77 +++++ src/pkg/stageengine/prstage/causes.go | 4 + src/pkg/stagelabels/human.go | 33 ++- src/pkg/stagelabels/human_test.go | 40 +++ src/pkg/stagelabels/sentinel_step.go | 2 +- 34 files changed, 1070 insertions(+), 30 deletions(-) create mode 100644 changelog.d/added-human-merge-owner-approval.md create mode 100644 src/pkg/config/automerge_human_merge_owner_approval_test.go create mode 100644 src/pkg/github/automerge/automerge_human_merge_owner_approval.go create mode 100644 src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go diff --git a/changelog.d/added-human-merge-owner-approval.md b/changelog.d/added-human-merge-owner-approval.md new file mode 100644 index 0000000000..078e7df976 --- /dev/null +++ b/changelog.d/added-human-merge-owner-approval.md @@ -0,0 +1 @@ +- New opt-in setting `auto_merge.human_merge_owner_approval`, a list of repositories, empty by default. A listed repository lets a trusted merger's explicit approval of a pull request's current head release the hold the hive puts on a pull request that touches a path a person must merge (`auto_merge.human_merge_paths`). The approval can be a GitHub **Approve** review, a `/hive decision approve` reply or a `/hive approve` reply posted after the head. The hive then merges the pull request once CI, review, soak and every other gate pass. A new push needs a new approval, a `hold` a person added is never lifted, and one comment per head records who approved which head. On a listed repository `/hive approve` replies "released for "; other repositories keep today's rule and reply. The setting is in **Settings → Features → Auto-merge → Per-repository merge policy**, `PUT`/`PATCH /api/config/auto-merge` and the admin MCP's `auto_merge.update` (Danathar/goodreads-mcp#463). diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index ef53171968..9d4d695482 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -2515,6 +2515,7 @@ func (b *boot) bootAgentsWith(deps bootAgentsDeps) { // a reload of auto_merge.human_merge_paths applies without a restart. autoMergeOpts.HumanMergePaths = func(repo string) []string { return humanMergePathsFor(b.cfg, repo) } autoMergeOpts.HumanMergePinOnly = func(repo string) (config.PinOnlyException, bool) { return humanMergePinOnlyFor(b.cfg, repo) } + autoMergeOpts.HumanMergeOwnerApproval = func(repo string) bool { return b.cfg != nil && b.cfg.AutoMerge.HumanMergeOwnerApprovalFor(repo) } autoMergeOpts.HumanMergeRule = func() prstage.HumanMergeRule { return humanMergeRuleFor(b.cfg) } autoMergeOpts.RequireCurrentBase = func(repo string) bool { return b.cfg != nil && b.cfg.AutoMerge.RequireCurrentBaseFor(repo) } // Commit messages on a merge-ready head are read for closing keywords diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index cfca4f2025..213eb8ea40 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -923,6 +923,7 @@ func runAutoMergeSweepIfDue(ctx context.Context, ghClient *github.Client, cfg *c opts.RepoOnGitHub = func(repo string) bool { return cfg.RepoOnGitHub(repo) } opts.HumanMergePaths = func(repo string) []string { return humanMergePathsFor(cfg, repo) } opts.HumanMergePinOnly = func(repo string) (config.PinOnlyException, bool) { return humanMergePinOnlyFor(cfg, repo) } + opts.HumanMergeOwnerApproval = func(repo string) bool { return cfg.AutoMerge.HumanMergeOwnerApprovalFor(repo) } opts.HumanMergeRule = func() prstage.HumanMergeRule { return humanMergeRuleFor(cfg) } opts.RequireCurrentBase = func(repo string) bool { return cfg.AutoMerge.RequireCurrentBaseFor(repo) } opts.RequireCurrentBaseStrict = func(repo string) bool { return cfg.AutoMerge.RequireCurrentBaseStrictFor(repo) } @@ -1561,6 +1562,7 @@ func runIssueUnparkSweepIfDue(ctx context.Context, ghClient *github.Client, cfg approveOpts.RepoAutoMergeEnabled = cfg.RepoAutoMergeEnabled approveOpts.HumanMergePaths = func(repo string) []string { return humanMergePathsFor(cfg, repo) } approveOpts.HumanMergePinOnly = func(repo string) (config.PinOnlyException, bool) { return humanMergePinOnlyFor(cfg, repo) } + approveOpts.HumanMergeOwnerApproval = func(repo string) bool { return cfg.AutoMerge.HumanMergeOwnerApprovalFor(repo) } approveOpts.HumanMergeRule = func() prstage.HumanMergeRule { return humanMergeRuleFor(cfg) } approveOpts.TrustedBotAuthors = func() map[string]bool { return cfg.AutoMerge.TrustedBotAuthorSet() } approveOpts.TrustedBotSkipReview = func() bool { return cfg.AutoMerge.TrustedBotSkipsReview() } diff --git a/src/docs/admin-mcp.md b/src/docs/admin-mcp.md index d694dfdfe3..1fd2e81e22 100644 --- a/src/docs/admin-mcp.md +++ b/src/docs/admin-mcp.md @@ -764,8 +764,9 @@ The keys and names whose values are shown: `agents.*.backend`, `agents.*.model`, `agents.*.enabled`, `agents.*.paused`, the API proxy's GitHub API hourly cap `agents.github_api_hourly_cap` and `agents.*.github_api_hourly_cap`, and the per-repository merge policy: `auto_merge.squash_only[*]`, - `auto_merge.require_current_base[*]` and `auto_merge.human_merge_paths.*[*]` - (the path globs listed under each `owner/repo`). A `*` segment is one map key + `auto_merge.require_current_base[*]`, `auto_merge.human_merge_paths.*[*]` + (the path globs listed under each `owner/repo`) and + `auto_merge.human_merge_owner_approval[*]`. A `*` segment is one map key and `[*]` any list index. - **Per-agent GitHub API caps:** the result also carries `agent_github_api_hourly_caps`, the API proxy's cap as this configuration @@ -1190,6 +1191,9 @@ only. pin-only exception, `{"enabled": true, "paths": [...], "kinds": [...], "trusted_authors": [...]}`; `null` removes it. An enabled exception needs `human_merge_paths` for the repository, set already or in the same change. + `human_merge_owner_approval` is a list of `owner/repo` like `squash_only`; + adding a repository is named as widening (a trusted merger's approval + then lets the hive merge its human-merge paths). `kinds` takes the same list the dashboard offers (`action-sha`, `image-digest`, `version-pin`, `action-sha-ref`), and the schema says what each admits. `action-sha-ref` lets a bare `key: <40-hex>` line follow a diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 7e75102cc4..6d44c09bf9 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -210,7 +210,7 @@ summary and the `health_deep_read` diagnostic tool. | `GET` | `/api/config/governor/general-advanced` | Owner only | Settings → General governor settings: `eval_interval_s`, the loop pacing knobs with `loop_defaults`, `explain_mode`, `attribution_trailer`, `api_budget_pacing` (`governor.api_budget_pacing`) and `api_budget_pacing_state` `{enabled, active, factor, effective_interval_s, burn_per_min, reason}`, what the loop is doing with it | `pkg/dashboard/api.go:246` | | `PUT` | `/api/config/governor/general-advanced` | Owner only | Change those settings; every field is optional and an absent one is left alone. `api_budget_pacing` (boolean) turns GitHub API budget pacing on or off from the next eval cycle. Returns the GET payload | `pkg/dashboard/api.go:247` | | `GET` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Get | `pkg/dashboard/api.go:251` | -| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed; `contributor_lane.workflow_fence_scope_repos` (`{owner/repo: "all", "human_merge_paths" or null}`) sets or clears single repositories' own workflow fence scope (`project.repo_policies[].workflow_fence_scope`) and leaves repositories it does not name, and the hive-wide scope, unchanged; a repository outside `project.repos` or another value is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:252` | +| `PUT` | `/api/config/auto-merge` | Owner only | Auto-Merge Config Set; `human_merge_pin_only` replaces the whole pin-only map (`{}` clears it), and an invalid entry is a 400 with nothing changed; `human_merge_owner_approval` replaces the list of repositories where a trusted merger's approval of the head releases the human-merge-path hold (`[]` clears it; a repository outside `project.repos` is a 400 with nothing changed); `contributor_lane.workflow_fence_scope_repos` (`{owner/repo: "all", "human_merge_paths" or null}`) sets or clears single repositories' own workflow fence scope (`project.repo_policies[].workflow_fence_scope`) and leaves repositories it does not name, and the hive-wide scope, unchanged; a repository outside `project.repos` or another value is a 400 with nothing changed, and a change is audited per repository | `pkg/dashboard/api.go:252` | | `GET` | `/api/config/convergence` | Owner only | Convergence Config Get | `pkg/dashboard/api.go:258` | | `PUT` | `/api/config/convergence` | Owner only | Convergence Config Set | `pkg/dashboard/api.go:260` | | `GET` | `/api/config/governor/advisory` | Owner only | Governor Advisory Get | `pkg/dashboard/api.go:264` | diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index c45b14ad25..dc2961cbb3 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -394,6 +394,50 @@ auto_merge: - your-org/docs-only-repo ``` +### Owner approval releases the human-merge-path hold + +`auto_merge.human_merge_owner_approval` is an opt-in list of `owner/repo` +names, empty by default. A repository not listed keeps the rule above: a pull +request touching one of its `human_merge_paths` is held and a person merges +it. In a listed repository a trusted merger's explicit approval of the pull +request's current head releases that hold instead, and the merge lanes merge +the pull request once every other gate passes. CI, required checks, +freshness, soak, review verdicts, other holds and the sentinel all still +apply: the approval is not a merge override. + +- **What counts as approval.** A trusted merger's GitHub **Approve** review + on the current head, a `/hive decision approve` reply (typed on the PR or + sent from the dashboard), or a `/hive approve` reply posted after the hive + first saw the head. These are the workflow-path fence's approvals plus + `/hive approve`; an edited comment never counts, and someone who is not a + trusted merger cannot approve. +- **Bound to the head.** A new push needs a new approval. The one exception + is the fence's: an Approve review or dashboard approval carries over the + hive's own update from the base branch when the PR's diff is unchanged. +- **What is released.** The stage-label pass removes only the `hold` the + human-merge-path gate put on for this refusal, through the shared release + API with its provenance checks: the App's single, unedited, head-stamped + notice, and every `hold` the PR was ever labelled with applied by the App. + A `hold` a person added or re-added is never removed, and neither is one + another hold source explains (a pause, the reporter-trust gate). The + release goes through the write-back gate (`human_merge_path_release`). +- **What is recorded.** One comment per head names who approved which head + (``), and the hive logs + `owner approval released human-merge-path hold`. +- **What `/hive approve` replies.** In a listed repository the reply says + the hold is released for the head and that the hive merges the PR when the + other gates clear, or, when no approval of the current head is recorded + yet, which approvals do it. In other repositories the reply is unchanged. +- **The PR's stage.** An unapproved head parks at `085` asking for the + approval; an approved head goes on through the lanes like any other PR. + +Owners set the list from **Settings → Features → Auto-merge → Per-repository +merge policy → Owner approval merges paths a person must merge**, through +`human_merge_owner_approval` on `PUT /api/config/auto-merge`, or with the +admin MCP operation `auto_merge.update`; it applies on the next sweep. A +repository outside `project.repos` is refused. The `hive-merge` relay path is +unchanged: it still refuses such a pull request. + ### One human step at L5: approve and unhold At ACMM L5 an agent PR carries the level `hold`, and Hive cannot merge its own diff --git a/src/docs/maintainer-commands.md b/src/docs/maintainer-commands.md index 1cc10499f2..9250618eb8 100644 --- a/src/docs/maintainer-commands.md +++ b/src/docs/maintainer-commands.md @@ -208,7 +208,13 @@ that queue flow. A swarm `changes_requested` or `reject` verdict is not overridden by a human approval; the head must be fixed or merged manually. Neither form bypasses CI, `hold`-class labels, a sentinel alert or a lane that only merges by hand (CI workflow / action files edited, tests removed, -an `auto_merge.human_merge_paths` match): the `stage/085-needs-decision` +an `auto_merge.human_merge_paths` match, except in a repository listed in +`auto_merge.human_merge_owner_approval`, where a trusted merger's Approve +review, `/hive decision approve` or `/hive approve` on the current head +releases the hive's human-merge-path hold and the lanes merge the PR once +every other gate passes; see +[hive-merge.md](hive-merge.md#owner-approval-releases-the-human-merge-path-hold)): +the `stage/085-needs-decision` entry comment names, per lane, what actually clears the park — the trusted merger's approval, the label a person must remove, or a manual merge ([#13087](https://github.com/hivecommons/hive/issues/13087)). A `/hive diff --git a/src/docs/settings.md b/src/docs/settings.md index d86c707842..d7dae635ab 100644 --- a/src/docs/settings.md +++ b/src/docs/settings.md @@ -88,7 +88,7 @@ Optional capabilities, each off or inert until you turn it on. Where a feature h - Audit publication: [Audit campaign](audit-campaign.md#publication). - Token mint: [Token mint](token-mint.md). - Spek stage runner: [Spektacular](spektacular.md). -- Auto-merge: [App self-merge sweep](operator-reference.md#app-self-merge-sweep-auto_merge), [Trusted bot authors](hive-merge.md#trusted-bot-authors), [Trusted-author auto-merge](hive-merge.md#trusted-author-auto-merge), and the per-repository merge policy (`auto_merge.require_current_base`, `auto_merge.squash_only`, `auto_merge.human_merge_paths`, `auto_merge.human_merge_pin_only`). +- Auto-merge: [App self-merge sweep](operator-reference.md#app-self-merge-sweep-auto_merge), [Trusted bot authors](hive-merge.md#trusted-bot-authors), [Trusted-author auto-merge](hive-merge.md#trusted-author-auto-merge), and the per-repository merge policy (`auto_merge.require_current_base`, `auto_merge.squash_only`, `auto_merge.human_merge_paths`, `auto_merge.human_merge_pin_only`, `auto_merge.human_merge_owner_approval`). - Review gate: [Review swarm](review-swarm.md#configuration), [Blocking line and backlog](review-swarm.md#blocking-line-reviewseverity-reviewbacklog), and [external review bot threads](review-bot-threads.md). - Trajectory review: [Trajectory-Review Lane](trajectory-review.md#configuration). - Linear agent: [Linear agent integration](linear-agent.md). diff --git a/src/pkg/adminmcp/tools_automerge_ops.go b/src/pkg/adminmcp/tools_automerge_ops.go index ca19ed129c..1a96963ba4 100644 --- a/src/pkg/adminmcp/tools_automerge_ops.go +++ b/src/pkg/adminmcp/tools_automerge_ops.go @@ -113,6 +113,7 @@ var autoMergeFields = []amField{ {key: "require_current_base", kind: amList, entry: amEntryRepo, widen: amWidenRemove, why: "pull requests there may merge without the current base tip"}, {key: "human_merge_paths", kind: amRepoPaths, widen: amWidenPaths, why: "pull requests touching these paths no longer wait for a person to merge them"}, {key: "human_merge_pin_only", kind: amPinOnly, widen: amWidenPinOnly}, + {key: "human_merge_owner_approval", kind: amList, entry: amEntryRepo, widen: amWidenAdd, why: "a trusted merger's approval of a pull request's head lets the hive merge it there although it touches a path a person must merge"}, {key: "bot_takeover_enabled", kind: amBool, widen: amWidenOn, why: "the App re-authors trusted github-actions[bot] pull requests and merges its copy"}, {key: "dependency_bot_adopt_enabled", kind: amBool, widen: amWidenOn, why: "the hive adopts red trusted dependency-bot pull requests its review asked to change, and merges its fixed copy"}, {key: "require_current_base_default", kind: amBool, widen: amWidenOff, why: "repositories without an override may merge without the current base tip"}, diff --git a/src/pkg/adminmcp/tools_automerge_ops_test.go b/src/pkg/adminmcp/tools_automerge_ops_test.go index 43322c5938..d011b6e82a 100644 --- a/src/pkg/adminmcp/tools_automerge_ops_test.go +++ b/src/pkg/adminmcp/tools_automerge_ops_test.go @@ -56,6 +56,7 @@ func autoMergeFixture() map[string]any { "squash_only": []string{"org/a", "org/b"}, "require_current_base": []string{}, "human_merge_paths": map[string][]string{"org/a": {".github/workflows/**", ".claude/hooks/**"}, "org/b": {"CODEOWNERS"}}, + "human_merge_owner_approval": []string{"org/b"}, "project_repos": []string{"org/a", "org/b", "org/c"}, "trusted_bot_authors": []string{"dependabot[bot]"}, "bot_takeover_enabled": false, @@ -284,3 +285,34 @@ func TestAutoMergeUpdateRefusesNonOwner(t *testing.T) { t.Fatalf("wrote without owner access: %+v", p.requests) } } + +// auto_merge.human_merge_owner_approval is a repository list like +// squash_only: a change sends the whole list, keeping the repositories it +// does not name, and adding one is widening (an owner's approval then lets +// the hive merge that repository's human-merge paths); removing one is not. +func TestAutoMergeUpdateHumanMergeOwnerApproval(t *testing.T) { + p := &autoMergeProvider{settings: autoMergeFixture()} + h := autoMergeHandler(p) + preview, id := autoMergePreview(t, h, map[string]any{"human_merge_owner_approval": map[string]any{"add": []any{"org/a"}}}) + want := `{"human_merge_owner_approval":["org/b","org/a"]}` + if got := compactJSON(preview.Request.Body); got != want { + t.Fatalf("body = %s, want %s", got, want) + } + if !strings.HasPrefix(preview.WideningDisclosure, "Widening:") || !strings.Contains(preview.WideningDisclosure, "human_merge_owner_approval") { + t.Fatalf("adding a repository must be widening: %s", preview.WideningDisclosure) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(p.requests) != 1 || compactJSON(p.requests[0].Body) != want { + t.Fatalf("executed %+v, want body %s", p.requests, want) + } + + removal, _ := autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: autoMergeFixture()}), map[string]any{"human_merge_owner_approval": map[string]any{"remove": []any{"org/b"}}}) + if got := compactJSON(removal.Request.Body); got != `{"human_merge_owner_approval":[]}` { + t.Fatalf("removal body = %s", got) + } + if strings.HasPrefix(removal.WideningDisclosure, "Widening:") { + t.Fatalf("removing a repository is not widening: %s", removal.WideningDisclosure) + } +} diff --git a/src/pkg/adminmcp/tools_settings.go b/src/pkg/adminmcp/tools_settings.go index a6d739f3a4..53bccde905 100644 --- a/src/pkg/adminmcp/tools_settings.go +++ b/src/pkg/adminmcp/tools_settings.go @@ -36,7 +36,7 @@ var settingsSections = []SettingsSection{ {"dashboard", "/api/config/dashboard", "Dashboard settings."}, {"channels", "/api/config/channels", "Channels: email, push, Slack, Matrix, Microsoft Teams and Telegram targets, GitHub mentions and Actions identity (secret values are never returned; secrets are named by environment variable)."}, {"escalation", "/api/config/escalation", "Escalation settings."}, - {"auto_merge", "/api/config/auto-merge", "Merge settings, including the per-repository merge policy (squash_only, require_current_base, human_merge_paths, human_merge_pin_only) and which repositories override the contributor lane's workflow_fence_scope (contributor_lane.workflow_fence_scope_repos)."}, + {"auto_merge", "/api/config/auto-merge", "Merge settings, including the per-repository merge policy (squash_only, require_current_base, human_merge_paths, human_merge_pin_only, human_merge_owner_approval) and which repositories override the contributor lane's workflow_fence_scope (contributor_lane.workflow_fence_scope_repos)."}, {"review", "/api/config/review", "Review settings: reviewers, perspectives, review bots and gates."}, {"convergence", "/api/config/convergence", "Convergence settings."}, {"sla", "/api/config/sla", "SLA settings."}, diff --git a/src/pkg/config/automerge_human_merge_owner_approval_test.go b/src/pkg/config/automerge_human_merge_owner_approval_test.go new file mode 100644 index 0000000000..be83dee26f --- /dev/null +++ b/src/pkg/config/automerge_human_merge_owner_approval_test.go @@ -0,0 +1,25 @@ +package config + +import "testing" + +func TestHumanMergeOwnerApprovalFor(t *testing.T) { + cfg := AutoMergeConfig{HumanMergeOwnerApproval: []string{" Acme/Widget ", ""}} + for _, tc := range []struct { + name string + cfg AutoMergeConfig + repo string + want bool + }{ + {"unset is off everywhere", AutoMergeConfig{}, "acme/widget", false}, + {"not listed", cfg, "hivecommons/hive", false}, + {"listed case-insensitive", cfg, "acme/widget", true}, + {"listed with spaces", cfg, " ACME/WIDGET ", true}, + {"empty repo", cfg, "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := tc.cfg.HumanMergeOwnerApprovalFor(tc.repo); got != tc.want { + t.Fatalf("HumanMergeOwnerApprovalFor(%q) = %v, want %v", tc.repo, got, tc.want) + } + }) + } +} diff --git a/src/pkg/config/review_config.go b/src/pkg/config/review_config.go index a663575d8e..514d63c8df 100644 --- a/src/pkg/config/review_config.go +++ b/src/pkg/config/review_config.go @@ -629,6 +629,15 @@ type AutoMergeConfig struct { // automerge sweep and /approve gates (#16266), and the hive-merge relay // (#16265). HumanMergePinOnly map[string]PinOnlyException `yaml:"human_merge_pin_only,omitempty" json:"human_merge_pin_only,omitempty"` + // HumanMergeOwnerApproval lists owner/repo names where a trusted + // merger's explicit approval of a pull request's current head releases + // the human-merge-path hold: the merge lanes then merge it once every + // other gate passes. Explicit approval is a GitHub Approve review on that + // head, a `/hive decision approve` (typed or from the dashboard) or a + // `/hive approve` posted after the head, by a trusted merger. A later push + // needs a new approval. Unset (the default) keeps the rule absolute: a + // person merges every such pull request by hand. + HumanMergeOwnerApproval []string `yaml:"human_merge_owner_approval,omitempty" json:"human_merge_owner_approval,omitempty"` // Unset uses the default owner-merge rule; explicit empty lists disable // their half of the title/label rule. HumanMergeTitlePrefixes []string `yaml:"human_merge_title_prefixes,omitempty" json:"human_merge_title_prefixes,omitempty"` @@ -829,6 +838,13 @@ func (a AutoMergeConfig) SquashOnlyFor(repo string) bool { return repoListSet(a.SquashOnly)[strings.ToLower(strings.TrimSpace(repo))] } +// HumanMergeOwnerApprovalFor reports whether repo (owner/repo) is listed in +// auto_merge.human_merge_owner_approval: an owner's explicit approval of a +// pull request's current head releases its human-merge-path hold there. +func (a AutoMergeConfig) HumanMergeOwnerApprovalFor(repo string) bool { + return repoListSet(a.HumanMergeOwnerApproval)[strings.ToLower(strings.TrimSpace(repo))] +} + // SupersessionSweepConfig tunes the supersession sweep // (github.SweepSupersededOpenPRs), which finds open PRs whose claimed issue was // already closed by a different merged PR (hivecommons/hive#11418). diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index 563d43c177..5bd6f8b226 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -170,6 +170,11 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { // map, replaced whole like HumanMergePaths: an empty (non-nil) map // clears it, absent leaves it untouched. HumanMergePinOnly map[string]config.PinOnlyException `json:"human_merge_pin_only"` + // HumanMergeOwnerApproval is the FULL desired + // auto_merge.human_merge_owner_approval list, keyed and stored like + // RequireCurrentBase: an empty (non-nil) list clears it, absent + // leaves it untouched. + HumanMergeOwnerApproval []string `json:"human_merge_owner_approval"` // TrustedBotSkipReview is auto_merge.trusted_bot_skip_review: the // review swarm's verdict is advisory on the trusted-bot lane. TrustedBotSkipReview *bool `json:"trusted_bot_skip_review"` @@ -255,6 +260,15 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { } requireCurrentBase = repos } + var humanMergeOwnerApproval []string + if body.HumanMergeOwnerApproval != nil { + repos, msg := s.autoMergeWatchedRepoList("human_merge_owner_approval", body.HumanMergeOwnerApproval) + if msg != "" { + jsonError(w, msg, http.StatusBadRequest) + return + } + humanMergeOwnerApproval = repos + } var humanMergePaths map[string][]string if body.HumanMergePaths != nil { paths, msg := s.autoMergeHumanMergePaths(body.HumanMergePaths) @@ -431,6 +445,9 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { if body.HumanMergePinOnly != nil { cfg.AutoMerge.HumanMergePinOnly = humanMergePinOnly } + if body.HumanMergeOwnerApproval != nil { + cfg.AutoMerge.HumanMergeOwnerApproval = humanMergeOwnerApproval + } if body.TrustedBotSkipReview != nil { v := *body.TrustedBotSkipReview cfg.AutoMerge.TrustedBotSkipReview = &v @@ -562,6 +579,10 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { if requireCurrentBase == nil { requireCurrentBase = []string{} } + humanMergeOwnerApproval := am.HumanMergeOwnerApproval + if humanMergeOwnerApproval == nil { + humanMergeOwnerApproval = []string{} + } humanMergePaths := am.HumanMergePaths if humanMergePaths == nil { humanMergePaths = map[string][]string{} @@ -620,6 +641,7 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "require_current_base": requireCurrentBase, "human_merge_paths": humanMergePaths, "human_merge_pin_only": humanMergePinOnly, + "human_merge_owner_approval": humanMergeOwnerApproval, "pin_only_kinds": config.PinOnlyKinds, "project_repos": projectRepos, "trusted_bot_authors": trustedBots, diff --git a/src/pkg/dashboard/api_config_automerge_repo_policy_test.go b/src/pkg/dashboard/api_config_automerge_repo_policy_test.go index 5bfd51fd06..e585ee5379 100644 --- a/src/pkg/dashboard/api_config_automerge_repo_policy_test.go +++ b/src/pkg/dashboard/api_config_automerge_repo_policy_test.go @@ -166,3 +166,49 @@ func TestAutoMergeRepoPolicy_PersistsToSavedConfig(t *testing.T) { t.Fatalf("saved auto_merge missing the per-repo policy: %+v", saved.AutoMerge) } } + +// auto_merge.human_merge_owner_approval is a repository list like +// squash_only: it round-trips through GET, a repository outside +// project.repos is a 400 with nothing changed, and an empty list clears it. +func TestAutoMergeRepoPolicy_HumanMergeOwnerApproval(t *testing.T) { + s := repoPolicyServer(t) + rec := doOwnerGet(s, "/api/config/auto-merge") + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"human_merge_owner_approval":[]`) { + t.Fatalf("GET before any put: expected an empty human_merge_owner_approval list, got %d: %s", rec.Code, rec.Body.String()) + } + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_owner_approval": []string{" api ", "ACME/api", "acme/docs"}}); rec.Code != http.StatusOK { + t.Fatalf("valid put: expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + am := s.deps.Config.AutoMerge + if got := strings.Join(am.HumanMergeOwnerApproval, ","); got != "acme/api,acme/docs" { + t.Fatalf("human_merge_owner_approval = %q, want acme/api,acme/docs", got) + } + if !am.HumanMergeOwnerApprovalFor("acme/api") || am.HumanMergeOwnerApprovalFor("acme/web") { + t.Fatalf("stored list does not match the sweep's owner/repo lookup: %+v", am.HumanMergeOwnerApproval) + } + rec = doOwnerGet(s, "/api/config/auto-merge") + var got struct { + HumanMergeOwnerApproval []string `json:"human_merge_owner_approval"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode GET: %v", err) + } + if strings.Join(got.HumanMergeOwnerApproval, ",") != "acme/api,acme/docs" { + t.Fatalf("human_merge_owner_approval did not round-trip: %v", got.HumanMergeOwnerApproval) + } + + rec = doPut(s, "/api/config/auto-merge", map[string]any{"max_merges": 7, "human_merge_owner_approval": []string{"api", "other/repo"}}) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "human_merge_owner_approval: other/repo is not in project.repos") { + t.Fatalf("repo outside project.repos: expected 400, got %d: %s", rec.Code, rec.Body.String()) + } + if am := s.deps.Config.AutoMerge; strings.Join(am.HumanMergeOwnerApproval, ",") != "acme/api,acme/docs" || am.MaxMerges != 0 { + t.Fatalf("rejected write mutated config: %+v", am) + } + + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"human_merge_owner_approval": []string{}}); rec.Code != http.StatusOK { + t.Fatalf("clear put: expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + if s.deps.Config.AutoMerge.HumanMergeOwnerApprovalFor("acme/api") { + t.Fatalf("empty list did not clear: %+v", s.deps.Config.AutoMerge.HumanMergeOwnerApproval) + } +} diff --git a/src/pkg/dashboard/dashboard_mcp_parity_controls_test.go b/src/pkg/dashboard/dashboard_mcp_parity_controls_test.go index 3155182461..661cfe3f2d 100644 --- a/src/pkg/dashboard/dashboard_mcp_parity_controls_test.go +++ b/src/pkg/dashboard/dashboard_mcp_parity_controls_test.go @@ -138,3 +138,43 @@ assert.equal(modeEmoji('NO_GITHUB'), modeEmoji('ADVISORY')); assert(!render('ADVISORY').includes('NO_GITHUB')); `) } + +// auto_merge.human_merge_owner_approval ships with its dashboard control +// beside the per-repository merge policy, with a help mark, and the control +// stages the whole selection for the PUT. +func TestDashboardParityAutoMergeHumanMergeOwnerApproval(t *testing.T) { + html := indexHTML(t) + features := extractJSFunction(t, html, "renderGovFeatures") + for _, want := range []string{ + `id="am-human-merge-owner-approval"`, + "amRepoPolicyOptions(am.human_merge_owner_approval)", + "yamlHint('auto_merge.human_merge_owner_approval')", + "settingHelpMark('hive-merge', 'owner-approval-releases-the-human-merge-path-hold'", + "auto_merge.human_merge_owner_approval[]", + } { + if !strings.Contains(features, want) { + t.Fatalf("Settings → Features → Auto-merge has no %q", want) + } + } + runNodeScript(t, parityMarkDirtyStub+jsFunc(t, html, "markDirty")+"\n"+jsFunc(t, html, "markDirtyAutoMergeRepoPolicy")+` +const selects = { + 'am-squash-only': ['o/a'], + 'am-human-merge-owner-approval': ['o/goodreads'], +}; +const document = { + getElementById: id => selects[id] ? { selectedOptions: selects[id].map(value => ({ value })) } : null, + querySelectorAll: () => [], +}; +global.document = document; + +markDirtyAutoMergeRepoPolicy.call({ id: 'am-squash-only', classList: { contains: () => false } }); +assert.equal(_configState.dirty['auto-merge'].human_merge_owner_approval, undefined); + +markDirtyAutoMergeRepoPolicy.call({ id: 'am-human-merge-owner-approval', classList: { contains: () => false } }); +assert.deepEqual(_configState.dirty['auto-merge'].human_merge_owner_approval, ['o/goodreads']); + +selects['am-human-merge-owner-approval'] = []; +markDirtyAutoMergeRepoPolicy.call({ id: 'am-human-merge-owner-approval', classList: { contains: () => false } }); +assert.deepEqual(_configState.dirty['auto-merge'].human_merge_owner_approval, []); +`) +} diff --git a/src/pkg/dashboard/diag_config_value_keys.txt b/src/pkg/dashboard/diag_config_value_keys.txt index 80ddea2067..625453b739 100644 --- a/src/pkg/dashboard/diag_config_value_keys.txt +++ b/src/pkg/dashboard/diag_config_value_keys.txt @@ -43,3 +43,4 @@ agents.*.github_api_hourly_cap auto_merge.squash_only[*] auto_merge.require_current_base[*] auto_merge.human_merge_paths.*[*] +auto_merge.human_merge_owner_approval[*] diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 01d4f45432..f8575f483d 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -634,7 +634,11 @@ `; }).join('') : '

Set paths a person must merge for a repository first; its pin-only exception is edited here.

'} -

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], auto_merge.no_ci_ok[], auto_merge.allow_unprotected_base[],${esc('auto_merge.human_merge_paths.')}, ${esc('auto_merge.human_merge_pin_only..enabled')}, ${esc('auto_merge.human_merge_pin_only..paths[]')}, ${esc('auto_merge.human_merge_pin_only..kinds[]')}, ${esc('auto_merge.human_merge_pin_only..trusted_authors[]')}.

+
+ + +
+

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], auto_merge.no_ci_ok[], auto_merge.allow_unprotected_base[],${esc('auto_merge.human_merge_paths.')}, ${esc('auto_merge.human_merge_pin_only..enabled')}, ${esc('auto_merge.human_merge_pin_only..paths[]')}, ${esc('auto_merge.human_merge_pin_only..kinds[]')}, ${esc('auto_merge.human_merge_pin_only..trusted_authors[]')}, auto_merge.human_merge_owner_approval[].

diff --git a/src/pkg/dashboard/static-src/js/config-helpers.js b/src/pkg/dashboard/static-src/js/config-helpers.js index 534f6b431e..ca2b3d231f 100644 --- a/src/pkg/dashboard/static-src/js/config-helpers.js +++ b/src/pkg/dashboard/static-src/js/config-helpers.js @@ -456,6 +456,7 @@ if (this && this.id === 'am-squash-only') markDirty('auto-merge', 'squash_only', selected('am-squash-only')); if (this && this.id === 'am-no-ci-ok') markDirty('auto-merge', 'no_ci_ok', selected('am-no-ci-ok')); if (this && this.id === 'am-allow-unprotected-base') markDirty('auto-merge', 'allow_unprotected_base', selected('am-allow-unprotected-base')); + if (this && this.id === 'am-human-merge-owner-approval') markDirty('auto-merge', 'human_merge_owner_approval', selected('am-human-merge-owner-approval')); if (this && this.classList && this.classList.contains('am-human-merge-path-input')) { const paths = {}; document.querySelectorAll('#am-human-merge-paths .am-human-merge-path-row').forEach(row => { diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 391a104725..9c39c69a1d 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -82341,7 +82341,11 @@

${esc(s.title)}

`; }).join('') : '

Set paths a person must merge for a repository first; its pin-only exception is edited here.

'} -

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], auto_merge.no_ci_ok[], auto_merge.allow_unprotected_base[],${esc('auto_merge.human_merge_paths.')}, ${esc('auto_merge.human_merge_pin_only..enabled')}, ${esc('auto_merge.human_merge_pin_only..paths[]')}, ${esc('auto_merge.human_merge_pin_only..kinds[]')}, ${esc('auto_merge.human_merge_pin_only..trusted_authors[]')}.

+
+ + +
+

Select nothing (or leave paths empty) to turn a rule off for every repo. YAML keys: auto_merge.require_current_base[], auto_merge.squash_only[], auto_merge.no_ci_ok[], auto_merge.allow_unprotected_base[],${esc('auto_merge.human_merge_paths.')}, ${esc('auto_merge.human_merge_pin_only..enabled')}, ${esc('auto_merge.human_merge_pin_only..paths[]')}, ${esc('auto_merge.human_merge_pin_only..kinds[]')}, ${esc('auto_merge.human_merge_pin_only..trusted_authors[]')}, auto_merge.human_merge_owner_approval[].

@@ -85966,6 +85970,7 @@

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

{ diff --git a/src/pkg/github/automerge/automerge_human_merge_owner_approval.go b/src/pkg/github/automerge/automerge_human_merge_owner_approval.go new file mode 100644 index 0000000000..e00d088686 --- /dev/null +++ b/src/pkg/github/automerge/automerge_human_merge_owner_approval.go @@ -0,0 +1,274 @@ +package automerge + +// Owner approval releases the human-merge-path hold (opt-in, per repository). +// +// auto_merge.human_merge_paths makes every App merge lane refuse a pull +// request that touches a listed path: the lane adds `hold`, posts one marker +// comment and leaves the merge to a person. On a repository listed in +// auto_merge.human_merge_owner_approval a trusted merger's explicit approval +// of the PR's current head lifts that refusal instead, and the lane merges +// the PR once CI, soak, review and every other gate pass +// (Danathar/goodreads-mcp#463: the owner approved the head, GitHub required +// no review and reported the PR clean, and the hive still answered that a +// person must merge it). +// +// "Explicit approval" is the workflow-path fence's (workflowFenceApproval: a +// trusted merger's GitHub Approve review on the head or carried over the +// hive's own base refresh, a dashboard approval, or a typed +// `/hive decision approve`), plus a trusted merger's `/hive approve` reply +// posted after the head was first seen, bound to the head the same way a +// typed decision is (humanMergeApproveCommandActor). A new push needs a new +// approval. A repository not listed keeps the rule absolute. +// +// The release reuses the human-merge-path hold's provenance check +// (hgithub.ReleaseApprovedHumanMergePathHold): only a `hold` the App put on +// for this refusal is ever removed, never one a person added or re-added, +// and never while another hold source explains it. The gate itself +// (humanMergePathGate) then lets the approved head through instead of +// holding it again. One audit comment per head names the approver. + +import ( + "context" + "fmt" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/writeback" +) + +// humanMergeOwnerApprovalConfigKey is the config key named in log lines and +// replies. +const humanMergeOwnerApprovalConfigKey = "auto_merge.human_merge_owner_approval" + +// humanMergeApprovalMarkerPrefix opens the one-per-head audit comment left +// when an owner's approval releases the human-merge-path refusal. +const humanMergeApprovalMarkerPrefix = "" +} + +// humanMergeOwnerApprovalEnabled reports whether repo (owner/repo) is listed +// in auto_merge.human_merge_owner_approval. +func (c *Engine) humanMergeOwnerApprovalEnabled(repo string) bool { + if c == nil || c.humanMergeOwnerApproval == nil { + return false + } + return c.humanMergeOwnerApproval(repo) +} + +// humanMergeOwnerApprovalFor returns the trusted merger's explicit approval +// of pr's current head on a repository that lets one release the +// human-merge-path refusal, or false. comments are the PR's comments, oldest +// first. Read failures and an unlisted repository answer false: the refusal +// stays. +func (c *Engine) humanMergeOwnerApprovalFor(ctx context.Context, owner, repo string, pr *gh.PullRequest, comments []*gh.IssueComment) (workflowApproval, bool) { + if c == nil || c.gh == nil || pr == nil || !c.humanMergeOwnerApprovalEnabled(owner+"/"+repo) { + return workflowApproval{}, false + } + head := strings.TrimSpace(pr.GetHead().GetSHA()) + if head == "" { + return workflowApproval{}, false + } + number := pr.GetNumber() + if approval, ok := c.workflowFenceApproval(ctx, owner, repo, pr, number, head, comments); ok { + return approval, true + } + headPushedAt := c.headObservedAt(owner, repo, number, head, pr) + appLogin := strings.TrimSpace(c.transport.AppBotLogin()) + for i := len(comments) - 1; i >= 0; i-- { + login, ok := humanMergeApproveCommandActor(comments[i], headPushedAt, appLogin) + if !ok { + continue + } + if trusted, configured := c.isTrustedMerger(login); !configured || !trusted { + continue + } + c.noteStageTrustedHumanApproval(owner, repo, number, head, login) + return workflowApproval{Login: login}, true + } + return workflowApproval{}, false +} + +// humanMergeApproveCommandActor reads one comment as a person's +// `/hive approve` of the head first seen at headPushedAt and returns its +// author: the command on the first line, the comment unedited (collaborators +// can edit others' comments) and posted after the head. With no known head +// time nothing binds, so nothing counts. +func humanMergeApproveCommandActor(comment *gh.IssueComment, headPushedAt time.Time, appLogin string) (string, bool) { + if comment == nil || headPushedAt.IsZero() { + return "", false + } + created, updated := comment.GetCreatedAt().Time, comment.GetUpdatedAt().Time + if created.IsZero() || updated.After(created) || created.Before(headPushedAt) { + return "", false + } + if !hgithub.IsPersonLogin(comment.GetUser(), appLogin) { + return "", false + } + line := strings.ToLower(strings.Join(strings.Fields(firstCommentLine(comment.GetBody())), " ")) + if line != hgithub.ReviewHoldReleaseCommand { + return "", false + } + return strings.TrimSpace(hgithub.SafeGetLogin(comment.GetUser())), true +} + +// humanMergeOwnerApprovalGate is humanMergePathGate's owner-approval +// exception: true when the repository lets an owner's approval release the +// refusal and pr's current head carries one. It records the release once +// per head (log line and audit comment). A comment read failure answers +// false, so the gate holds as before. +func (c *Engine) humanMergeOwnerApprovalGate(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, matches []string) bool { + if !c.humanMergeOwnerApprovalEnabled(owner + "/" + repo) { + return false + } + number := pr.GetNumber() + comments, err := c.listIssueComments(ctx, owner, repo, number) + if err != nil { + c.warn("human-merge-path owner approval: could not read comments; hold kept", "repo", displayRepo, "pr", number, "error", err) + return false + } + approval, ok := c.humanMergeOwnerApprovalFor(ctx, owner, repo, pr, comments) + if !ok { + return false + } + head := pr.GetHead().GetSHA() + if !hasCommentWithPrefix(comments, humanMergeApprovalMarker(head)) { + c.info("automerge sweep: owner approval releases human-merge paths", "repo", displayRepo, "pr", number, "paths", matches, "login", approval.Login, "head", head, "config", humanMergeOwnerApprovalConfigKey) + appBot := strings.TrimSpace(c.transport.AppBotLogin()) + author := hgithub.SafeGetLogin(pr.GetUser()) + item := writeback.Item{Number: number, IsPR: true, Author: author, Labels: labelNames(pr.Labels), CreatedAt: pr.GetCreatedAt().Time, + HiveAuthored: appBot != "" && strings.EqualFold(normalizeBotLogin(author), normalizeBotLogin(appBot))} + c.commentHumanMergeApproval(ctx, owner+"/"+repo, owner, repo, number, head, approval, item) + } + return true +} + +// releaseApprovedHumanMergePathHold is the stage pass's half: on a repository +// listed in auto_merge.human_merge_owner_approval it removes the `hold` the +// hive put on for the human-merge-path refusal once a trusted merger +// explicitly approved the PR's current head, so the lanes reach the gate, +// which lets the approved head through. It never removes a hold another +// source explains (a person's, a pause, the reporter-trust gate), and the +// label removal itself re-checks the hold's provenance +// (hgithub.ReleaseApprovedHumanMergePathHold). Anything it cannot establish +// keeps the hold. +func (c *Engine) releaseApprovedHumanMergePathHold(ctx context.Context, obs stageObservation, prov *stagelabels.HoldProvenance) (bool, error) { + if c == nil || c.gh == nil || c.transport == nil || !prov.SelfImposed() || !prov.HumanMergePath() { + return false, nil + } + repo := obs.Owner + "/" + obs.Repo + head := strings.TrimSpace(obs.HeadSHA) + if head == "" || !c.humanMergeOwnerApprovalEnabled(repo) { + return false, nil + } + pr, _, err := c.gh.PullRequests.Get(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil { + return false, fmt.Errorf("reading PR: %w", err) + } + if pr.GetHead().GetSHA() != head { + // The pass observed an older head; the next pass judges this one. + return false, nil + } + comments, err := c.listAllIssueComments(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil { + return false, fmt.Errorf("listing comments: %w", err) + } + approval, ok := c.humanMergeOwnerApprovalFor(ctx, obs.Owner, obs.Repo, pr, comments) + if !ok { + return false, nil + } + others, ok := c.transport.(otherHoldSourcesTransport) + if !ok { + return false, nil + } + if sources := others.OtherHoldSourcesForPR(repo, obs.Number, obs.Labels, comments); len(sources) > 0 { + c.info("stage labels: human-merge-path hold approved but another hold source keeps it", "repo", obs.Display, "pr", obs.Number, "head", head, "login", approval.Login, "sources", strings.Join(sources, ",")) + return false, nil + } + appBot := strings.TrimSpace(c.transport.AppBotLogin()) + allowed := func(item writeback.Item) bool { + d := c.writebackAllowed(repo, item, writeback.KindHumanMergePathRelease, "") + if !d.Allowed { + c.info("stage labels: human-merge-path hold approved; release refused by the write-back gate", "repo", obs.Display, "pr", obs.Number, "head", head, "reason", d.Reason) + } + return d.Allowed + } + released, err := hgithub.ReleaseApprovedHumanMergePathHold(ctx, c.gh, allowed, obs.Owner, obs.Repo, obs.Number, appBot, head) + if err != nil || !released { + return false, err + } + c.info("stage labels: owner approval released human-merge-path hold", "repo", obs.Display, "pr", obs.Number, "head", head, "login", approval.Login, "config", humanMergeOwnerApprovalConfigKey) + if !hasCommentWithPrefix(comments, humanMergeApprovalMarker(head)) { + item := writebackItemForObservation(obs) + item.HiveAuthored = strings.EqualFold(normalizeBotLogin(obs.Author), normalizeBotLogin(appBot)) + c.commentHumanMergeApproval(ctx, repo, obs.Owner, obs.Repo, obs.Number, head, approval, item) + } + return true, nil +} + +// humanMergeApprovalComment is the audit comment's text: who released the +// refusal for which head, and that every other gate still applies. +func humanMergeApprovalComment(head string, approval workflowApproval) string { + short := "`" + stagelabels.ShortSHA(head) + "`" + var b strings.Builder + b.WriteString(humanMergeApprovalMarker(head) + "\n") + fmt.Fprintf(&b, "Hold released for %s: `%s` approved this head, and `%s` lets a trusted merger's approval release this repository's human-merge paths (`%s`). ", short, approval.Login, humanMergeOwnerApprovalConfigKey, hgithub.HumanMergePathsConfigKey) + b.WriteString("The hive merges this PR once CI, review, soak and every other merge gate are clear; the approval is not a merge override. ") + b.WriteString("A new push puts the hold back until that head is approved, except the hive's own update from the base branch, which leaves the change as approved. A `hold` a person adds is never lifted this way.\n") + return b.String() +} + +// commentHumanMergeApproval posts the audit comment through the write-back +// gate; a refusal or a failed write is logged and nothing else changes. +func (c *Engine) commentHumanMergeApproval(ctx context.Context, repoKey, owner, repo string, number int, head string, approval workflowApproval, item writeback.Item) { + body := humanMergeApprovalComment(head, approval) + if d := c.writebackAllowed(repoKey, item, writeback.KindHumanMergePathRelease, body); !d.Allowed { + c.debug("human-merge-path owner approval: audit comment withheld by the write-back gate", "repo", repoKey, "pr", number, "head", head, "reason", d.Reason) + return + } + if _, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + c.warn("human-merge-path owner approval: could not post audit comment", "repo", repoKey, "pr", number, "head", head, "error", err) + return + } + c.noteOwnStageComment(owner, repo, number) +} + +// headHumanMergeOwnerApproval returns the login whose explicit approval of +// obs's head releases the human-merge-path refusal, for the stage route. Read +// failures answer false: the route stays a person's merge. +func (c *Engine) headHumanMergeOwnerApproval(ctx context.Context, obs stageObservation) (string, bool) { + if c == nil || c.gh == nil || strings.TrimSpace(obs.HeadSHA) == "" { + return "", false + } + pr, _, err := c.gh.PullRequests.Get(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil || pr.GetHead().GetSHA() != obs.HeadSHA { + return "", false + } + comments, err := c.listAllIssueComments(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil { + return "", false + } + approval, ok := c.humanMergeOwnerApprovalFor(ctx, obs.Owner, obs.Repo, pr, comments) + return approval.Login, ok +} + +// humanMergeOwnerApprovalReply is the `/hive approve` reply on a PR that +// touches a human-merge path in a repository listed in +// auto_merge.human_merge_owner_approval: it says what happens to the hold, +// never "cannot override". It is read-only like the rest of PRApproveReply; +// the stage pass releases the hold and the lane merges. +func (c *Engine) humanMergeOwnerApprovalReply(ctx context.Context, owner, repo string, pr *gh.PullRequest, head string) (string, error) { + short := "`" + stagelabels.ShortSHA(head) + "`" + comments, err := c.listIssueComments(ctx, owner, repo, pr.GetNumber()) + if err != nil { + return "", err + } + if approval, ok := c.humanMergeOwnerApprovalFor(ctx, owner, repo, pr, comments); ok { + return "`/hive approve` acknowledged: released for " + short + ". This PR changes a path a person must merge (`" + hgithub.HumanMergePathsConfigKey + "`), and on this repository (`" + humanMergeOwnerApprovalConfigKey + "`) `" + approval.Login + "`'s approval of this head releases the hive's hold: the hive takes it off on its next pass and merges the PR when CI, review, soak and the other merge gates clear. A new push needs a new approval. This reply does not mean the PR has merged.", nil + } + return "`/hive approve` acknowledged, but no approval of the current head (" + short + ") is recorded yet. This PR changes a path a person must merge (`" + hgithub.HumanMergePathsConfigKey + "`); on this repository (`" + humanMergeOwnerApprovalConfigKey + "`) a trusted merger's GitHub **Approve** review on that head, a `/hive decision approve` reply, or a `/hive approve` reply posted after the head releases the hive's hold, and the hive then merges the PR once the other gates clear.", nil +} diff --git a/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go b/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go new file mode 100644 index 0000000000..dcb3d62799 --- /dev/null +++ b/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go @@ -0,0 +1,257 @@ +package automerge + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// auto_merge.human_merge_owner_approval (Danathar/goodreads-mcp#463): on a +// listed repository a trusted merger's explicit approval of the current head +// releases the hive's human-merge-path hold; everywhere else, and for any +// approval that is not bound to the head, the hold stays. + +var ownerApprovalHead = strings.Repeat("d", 40) + +func TestHumanMergeApproveCommandActor(t *testing.T) { + head := time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC) + at := func(d time.Duration) *gh.Timestamp { return &gh.Timestamp{Time: head.Add(d)} } + comment := func(login, typ, body string, created, updated *gh.Timestamp) *gh.IssueComment { + return &gh.IssueComment{User: &gh.User{Login: gh.Ptr(login), Type: gh.Ptr(typ)}, Body: gh.Ptr(body), CreatedAt: created, UpdatedAt: updated} + } + for _, tc := range []struct { + name string + comment *gh.IssueComment + headAt time.Time + want string + }{ + {name: "after the head", comment: comment("owner", "User", "/hive approve", at(time.Hour), at(time.Hour)), headAt: head, want: "owner"}, + {name: "trailing text on later lines", comment: comment("owner", "User", "/Hive Approve\n\nship it", at(time.Hour), at(time.Hour)), headAt: head, want: "owner"}, + {name: "before the head", comment: comment("owner", "User", "/hive approve", at(-time.Hour), at(-time.Hour)), headAt: head}, + {name: "head time unknown", comment: comment("owner", "User", "/hive approve", at(time.Hour), at(time.Hour))}, + {name: "edited", comment: comment("owner", "User", "/hive approve", at(time.Hour), at(2*time.Hour)), headAt: head}, + {name: "the App", comment: comment(testHiveAppBotLogin, "Bot", "/hive approve", at(time.Hour), at(time.Hour)), headAt: head}, + {name: "another bot", comment: comment("renovate[bot]", "Bot", "/hive approve", at(time.Hour), at(time.Hour)), headAt: head}, + {name: "a decision is the fence's", comment: comment("owner", "User", "/hive decision approve", at(time.Hour), at(time.Hour)), headAt: head}, + {name: "not on the first line", comment: comment("owner", "User", "LGTM\n/hive approve", at(time.Hour), at(time.Hour)), headAt: head}, + } { + t.Run(tc.name, func(t *testing.T) { + got, ok := humanMergeApproveCommandActor(tc.comment, tc.headAt, testHiveAppBotLogin) + if got != tc.want || ok != (tc.want != "") { + t.Fatalf("actor = %q/%v, want %q", got, ok, tc.want) + } + }) + } +} + +func TestHumanMergeApprovalCommentNamesApproverAndHead(t *testing.T) { + body := humanMergeApprovalComment(ownerApprovalHead, workflowApproval{Login: "owner"}) + for _, want := range []string{ + humanMergeApprovalMarker(ownerApprovalHead), + "Hold released for `dddddddd", + "`owner` approved this head", + humanMergeOwnerApprovalConfigKey, + "not a merge override", + "A new push puts the hold back", + "A `hold` a person adds is never lifted", + } { + if !strings.Contains(body, want) { + t.Fatalf("audit comment lacks %q:\n%s", want, body) + } + } +} + +// ownerApprovalStageAPI is the human-merge-path lift fixture with a real +// 40-character head, the App's head-stamped notice and hold event as the +// gate writes them, and reviews served for the PR. +func ownerApprovalStageAPI(t *testing.T, reviews, events []map[string]any) *stageAPI { + t.Helper() + app := map[string]string{"login": testHiveAppBotLogin, "type": "Bot"} + notice := map[string]any{ + "id": 11, + "body": hgithub.HumanMergePathComment([]string{".github/workflows/release.yml"}) + "\n", + "user": app, + "created_at": "2026-11-10T16:00:03Z", + "updated_at": "2026-11-10T16:00:03Z", + } + if events == nil { + events = []map[string]any{{"event": "labeled", "label": map[string]string{"name": "hold"}, "actor": app, "created_at": humanMergePathLiftHoldAt}} + } + files := append([]string{".github/workflows/release.yml"}, humanMergePathLiftCleanFiles...) + api := newHumanMergePathLiftAPI(t, 21, files, []map[string]any{notice}, events) + api.extra = func(w http.ResponseWriter, r *http.Request) bool { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/21": + _ = json.NewEncoder(w).Encode(map[string]any{ + "number": 21, "head": map[string]string{"sha": ownerApprovalHead}, "base": map[string]string{"ref": "main"}, + "user": map[string]string{"login": "shared-pat-account", "type": "User"}, "changed_files": len(files), + "labels": []map[string]string{{"name": "hold"}, {"name": "needs-human"}}, + }) + return true + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/21/reviews": + if reviews == nil { + reviews = []map[string]any{} + } + _ = json.NewEncoder(w).Encode(reviews) + return true + } + return false + } + return api +} + +func ownerApprovalReview(login, commit string) map[string]any { + return map[string]any{"id": 1, "state": "APPROVED", "commit_id": commit, "user": map[string]string{"login": login, "type": "User"}} +} + +func ownerApprovalNotices(api *stageAPI) []string { + api.mu.Lock() + defer api.mu.Unlock() + var out []string + for _, body := range api.comments { + if strings.HasPrefix(body, humanMergeApprovalMarkerPrefix) { + out = append(out, body) + } + } + return out +} + +func TestApplyStageLabels_OwnerApprovalReleasesHumanMergePathHold(t *testing.T) { + app := map[string]string{"login": testHiveAppBotLogin, "type": "Bot"} + appHold := map[string]any{"event": "labeled", "label": map[string]string{"name": "hold"}, "actor": app, "created_at": humanMergePathLiftHoldAt} + for _, tc := range []struct { + name string + unlisted bool + reviews []map[string]any + events []map[string]any + released bool + }{ + {name: "trusted merger approved the head", reviews: []map[string]any{ownerApprovalReview("maintainer", ownerApprovalHead)}, released: true}, + {name: "repository not listed", unlisted: true, reviews: []map[string]any{ownerApprovalReview("maintainer", ownerApprovalHead)}}, + {name: "no approval", reviews: nil}, + {name: "approval by someone who is not a trusted merger", reviews: []map[string]any{ownerApprovalReview("passerby", ownerApprovalHead)}}, + {name: "approval of an older head", reviews: []map[string]any{ownerApprovalReview("maintainer", strings.Repeat("e", 40))}}, + {name: "a person re-added the hold", reviews: []map[string]any{ownerApprovalReview("maintainer", ownerApprovalHead)}, events: []map[string]any{ + appHold, + holdEvent("unlabeled", "maintainer", "2026-11-10T17:00:00Z"), + holdEvent("labeled", "maintainer", "2026-11-10T17:00:05Z"), + }}, + } { + t.Run(tc.name, func(t *testing.T) { + api := ownerApprovalStageAPI(t, tc.reviews, tc.events) + e, store := newHumanMergePathLiftEngine(t, api) + e.SetMergerAuthorizer(func(login string) bool { return login == "maintainer" }) + e.humanMergeOwnerApproval = func(repo string) bool { return !tc.unlisted && strings.EqualFold(repo, "acme/widget") } + + pr := stagePR(21, "hold", "needs-human", "author/human", "role/contributor", "stage/050-review-pending") + pr.Head.SHA = gh.Ptr(ownerApprovalHead) + pr.User = &gh.User{Login: gh.Ptr("shared-pat-account")} + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, "excluded-label:hold", false, nil) + e.noteStageRole("acme", "widget", 21, stagelabels.RoleContributor) + if _, err := e.ApplyStageLabels(context.Background()); err != nil { + t.Fatal(err) + } + removed := removedHold(api) + notices := ownerApprovalNotices(api) + if !tc.released { + if removed != 0 || len(notices) != 0 { + t.Fatalf("hold removed %d times, audit comments %q; want the hold kept", removed, notices) + } + return + } + if removed != 1 { + t.Fatalf("hold removed %d times (removed=%v), want once", removed, api.removed) + } + if len(notices) != 1 || !strings.HasPrefix(notices[0], humanMergeApprovalMarker(ownerApprovalHead)) || !strings.Contains(notices[0], "`maintainer` approved this head") { + t.Fatalf("audit comments = %q, want one naming the approver and head", notices) + } + if rec, ok := store.Get(stageKey("acme", "widget", 21)); ok && rec.Hold != nil { + t.Fatalf("stored hold provenance survived the release: %+v", rec.Hold) + } + }) + } +} + +// The `/hive approve` reply on a listed repository says the hold is released +// for the head (or which approval it still needs); on any other repository +// it is today's reply word for word. +func TestPRApproveReplyHumanMergeOwnerApproval(t *testing.T) { + const unlistedReply = "`/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." + for _, tc := range []struct { + name string + unlisted bool + reviews []*gh.PullRequestReview + comments []*gh.IssueComment + want string + exact bool + }{ + {name: "unlisted repository keeps today's reply", unlisted: true, reviews: []*gh.PullRequestReview{{ID: gh.Ptr(int64(1)), State: gh.Ptr("APPROVED"), CommitID: gh.Ptr("sha7"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}}}, want: unlistedReply, exact: true}, + {name: "Approve review on the head", reviews: []*gh.PullRequestReview{{ID: gh.Ptr(int64(1)), State: gh.Ptr("APPROVED"), CommitID: gh.Ptr("sha7"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}}}, want: "released for `sha7`. "}, + {name: "this /hive approve after the head", comments: []*gh.IssueComment{{ID: gh.Ptr(int64(5)), Body: gh.Ptr("/hive approve"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}, CreatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 11, 0, 0, 0, time.UTC)}}}, want: "released for `sha7`. "}, + {name: "/hive approve before the head", comments: []*gh.IssueComment{{ID: gh.Ptr(int64(5)), Body: gh.Ptr("/hive approve"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}, CreatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC)}}}, want: "no approval of the current head (`sha7`) is recorded yet"}, + {name: "approval by someone who is not a trusted merger", reviews: []*gh.PullRequestReview{{ID: gh.Ptr(int64(1)), State: gh.Ptr("APPROVED"), CommitID: gh.Ptr("sha7"), User: &gh.User{Login: gh.Ptr("passerby"), Type: gh.Ptr("User")}}}, want: "no approval of the current head"}, + } { + 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(testHiveAppBotLogin)}, Head: &gh.PullRequestBranch{SHA: gh.Ptr("sha7")}, UpdatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC)}}) + case "/repos/acme/widget/pulls/7/files": + _ = json.NewEncoder(w).Encode([]*gh.CommitFile{{Filename: gh.Ptr("sensitive/config.yaml"), Status: gh.Ptr("modified")}}) + case "/repos/acme/widget/pulls/7/reviews": + reviews := tc.reviews + if reviews == nil { + reviews = []*gh.PullRequestReview{} + } + _ = json.NewEncoder(w).Encode(reviews) + case "/repos/acme/widget/issues/7/comments": + comments := tc.comments + if comments == nil { + comments = []*gh.IssueComment{} + } + _ = json.NewEncoder(w).Encode(comments) + 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{ + Now: func() time.Time { return time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) }, + HeadFirstSeen: NewHeadFirstSeenTracker(), + MergerAuthorizer: func(login string) bool { return login == "owner" }, + HumanMergePaths: func(string) []string { return []string{"sensitive/**"} }, + HumanMergeOwnerApproval: func(repo string) bool { return !tc.unlisted && repo == "acme/widget" }, + 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 { + t.Fatal(err) + } + if tc.exact && !strings.HasPrefix(reply, tc.want) { + t.Fatalf("reply = %q, want today's reply %q", reply, tc.want) + } + if !strings.Contains(reply, tc.want) { + t.Fatalf("reply = %q, want it to contain %q", reply, tc.want) + } + if !tc.unlisted && strings.Contains(reply, "cannot override") { + t.Fatalf("listed repository still says the command cannot override: %q", reply) + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_human_merge_path_fence.go b/src/pkg/github/automerge/automerge_human_merge_path_fence.go index acc73959cc..c0ec6d3ba7 100644 --- a/src/pkg/github/automerge/automerge_human_merge_path_fence.go +++ b/src/pkg/github/automerge/automerge_human_merge_path_fence.go @@ -165,7 +165,13 @@ func (c *Engine) humanMergePathFencePersonMerge(ctx context.Context, tracker *St // hand-off for another decision (a sentinel alert with a requires_human // verdict, needs-human, a reporter-trust hold, …) keeps its own route and // wording. -func applyHumanMergePathFenceRoute(e *stagelabels.Evidence, obs stageObservation) { +// +// ownerApproval is true on a repository listed in +// auto_merge.human_merge_owner_approval (and the head not yet approved): +// there a trusted merger's approval of the head does release the refusal, +// so instead of the manual-merge rule the route asks for that approval at +// 085 (ApprovalReleasesPathHold). +func applyHumanMergePathFenceRoute(e *stagelabels.Evidence, obs stageObservation, ownerApproval bool) { e.ApprovalReleasesFence = false hiveHold := obs.Hold.SelfImposed() && obs.Hold.HumanMergePath() for _, h := range e.Holds { @@ -183,9 +189,15 @@ func applyHumanMergePathFenceRoute(e *stagelabels.Evidence, obs stageObservation if e.Cause == stagelabels.CauseDecision && !owns { return } + e.LaneReason = autoMergeReasonHumanMergePath + if ownerApproval { + e.CauseReason = prstage.CauseHumanMergePathAwaitingApproval + e.ApprovalReleasesPathHold = true + e.Cause = stagelabels.CauseDecision + return + } e.CauseReason = prstage.CauseHumanMergePath e.ManualMergeRule = true - e.LaneReason = autoMergeReasonHumanMergePath if e.Cause == stagelabels.CauseDecision && (e.Verdict != stagelabels.VerdictRequiresHuman || strings.TrimSpace(e.HumanApprover) != "") { e.Cause = stagelabels.CauseTrust } diff --git a/src/pkg/github/automerge/automerge_human_paths.go b/src/pkg/github/automerge/automerge_human_paths.go index 37de5e733a..741e22b2ac 100644 --- a/src/pkg/github/automerge/automerge_human_paths.go +++ b/src/pkg/github/automerge/automerge_human_paths.go @@ -166,7 +166,10 @@ func pinOnlyTrustedLogin(policy config.PinOnlyException, login string) bool { // auto_merge.human_merge_pin_only exception qualifies the PR (trusted author, // complete list, every changed line a pin replacement, every commit a // verified trusted-author commit, every action SHA anchored in its upstream -// repository) and returns ("", nil). +// repository) and returns ("", nil). On a repository listed in +// auto_merge.human_merge_owner_approval a trusted merger's explicit approval +// of the current head lets it through the same way +// (humanMergeOwnerApprovalGate). func (c *Engine) humanMergePathGate(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest) (string, error) { patterns := c.currentHumanMergePaths(owner + "/" + repo) if len(patterns) == 0 { @@ -189,6 +192,9 @@ func (c *Engine) humanMergePathGate(ctx context.Context, displayRepo, owner, rep if why != "" { c.info("automerge sweep pin-only exception not applied", "repo", displayRepo, "pr", number, "config", humanMergePinOnlyConfigKey, "reason", why) } + if c.humanMergeOwnerApprovalGate(ctx, displayRepo, owner, repo, pr, matches) { + return "", nil + } c.info("automerge sweep held PR touching human-merge paths", "repo", displayRepo, "pr", number, "paths", matches, "config", hgithub.HumanMergePathsConfigKey) if err := hgithub.HoldForHumanMergePaths(ctx, c.gh, owner, repo, number, matches, pr.GetHead().GetSHA()); err != nil { return autoMergeReasonHumanMergePath, err diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index d614fa1250..57fad358d8 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -536,6 +536,17 @@ func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key s // an owner's approval releases the workflow fence only into the // human-merge-path refusal, so it is never asked for. humanMergePath := c.humanMergePathFencePersonMerge(ctx, tracker, key, obs) + // On a repository that lets an owner's approval release the refusal + // (auto_merge.human_merge_owner_approval) the head is a person's merge + // only until a trusted merger approves it: an approved head is routed on + // its own progress, and an unapproved one is asked for that approval. + humanMergeOwnerApproval := humanMergePath && c.humanMergeOwnerApprovalEnabled(obs.Owner+"/"+obs.Repo) + humanMergeApprover := "" + if humanMergeOwnerApproval { + if login, ok := c.headHumanMergeOwnerApproval(ctx, obs); ok { + humanMergePath, humanMergeApprover = false, login + } + } workflowManual := c.workflowFenceManual(obs.Owner, obs.Repo, obs.Number, obs.HeadSHA) || humanMergePath // A gate stops the lane before it reads mergeability, so the head's // mergeable_state comes from the hive's own reads of it @@ -630,7 +641,10 @@ func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key s e.HumanApprover = c.headTrustedApproval(ctx, tracker, key, obs, contributorVerdict, now) } if humanMergePath { - applyHumanMergePathFenceRoute(&e, obs) + applyHumanMergePathFenceRoute(&e, obs, humanMergeOwnerApproval) + } + if humanMergeApprover != "" && e.HumanApprover == "" { + e.HumanApprover = humanMergeApprover } e.CauseAwaitsApproval = e.ApprovalReleasesFence && strings.HasSuffix(e.CauseReason, prstage.CauseWorkflowPathAwaitingApproval) if strings.HasPrefix(obs.Reason, stageReasonForkGuard) { diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 44a0c0636c..f627588104 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -1196,6 +1196,24 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) } if stale { prov = staleHumanMergePathHold(prov) + } else { + // The head still touches the path: on a repository + // that lets an owner's approval release it, an + // approved head's hold comes off here and the lanes + // take the PR from the gate. + released, err := c.releaseApprovedHumanMergePathHold(ctx, obs, prov) + if err != nil { + c.warn("stage labels: could not release approved human-merge-path hold", "repo", obs.Display, "pr", obs.Number, "error", err) + if firstErr == nil { + firstErr = err + } + } + if released { + result.Comments++ + result.Skipped++ + store.ClearHold(key) + continue + } } } obs.Hold = prov diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 8b5294bef0..860cd97e1c 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -130,6 +130,11 @@ type Options struct { // A qualifying pin-only PR by a trusted author is not held by // HumanMergePaths. nil, or false, means no exception. HumanMergePinOnly func(repo string) (config.PinOnlyException, bool) + // HumanMergeOwnerApproval reports whether an owner/repo is listed in + // auto_merge.human_merge_owner_approval: a trusted merger's explicit + // approval of a PR's current head releases the HumanMergePaths refusal + // there. nil, or false, keeps the refusal absolute. + HumanMergeOwnerApproval func(repo string) bool // HumanMergeRule returns the live auto_merge.human_merge_title_prefixes / // human_merge_labels rule (hivecommons/hive#15442). Every lane and the // merge train skip a PR RequiresHumanMerge. nil means the defaults. @@ -406,6 +411,7 @@ type Engine struct { recordReviewHoldRelease ReviewHoldReleaseFunc humanMergePinOnlyMu sync.RWMutex humanMergePinOnly func(repo string) (config.PinOnlyException, bool) + humanMergeOwnerApproval func(repo string) bool humanMergeRuleMu sync.RWMutex humanMergeRule func() prstage.HumanMergeRule @@ -558,6 +564,7 @@ func New(transport Transport, opts Options) *Engine { recordReviewHoldRelease: opts.RecordReviewHoldRelease, scanCommitClosingKeywords: opts.ScanCommitClosingKeywords, humanMergePinOnly: opts.HumanMergePinOnly, + humanMergeOwnerApproval: opts.HumanMergeOwnerApproval, humanMergeRule: opts.HumanMergeRule, requireCurrentBase: opts.RequireCurrentBase, requireCurrentBaseStrict: opts.RequireCurrentBaseStrict, diff --git a/src/pkg/github/automerge/pr_approve_command.go b/src/pkg/github/automerge/pr_approve_command.go index 48e91f194d..a376666e42 100644 --- a/src/pkg/github/automerge/pr_approve_command.go +++ b/src/pkg/github/automerge/pr_approve_command.go @@ -99,6 +99,9 @@ func (c *Engine) PRApproveReply(ctx context.Context, displayRepo string, number if len(matches) == 0 && diffReason == contributorLaneReasonWorkflowPath && contributorLaneTestsRemovedReason(files) == "" && c.currentContributorLanePolicy().OwnerApprovalReleasesWorkflowFence { return "`/hive approve` acknowledged, but it does not release this PR's fence: the PR edits CI workflow / action files, which the contributor lane merges only on a hive owner's explicit approval of the current head (`" + stagelabels.ShortSHA(head) + "`). That is a trusted merger's GitHub **Approve** review, or a `/hive decision approve` reply (typed here or from the Hive dashboard), and either one also answers a `requires_human` review verdict on that head; the owner of their own PR, whom GitHub refuses as a reviewer, replies `/hive decision approve`. The lane merges once CI and the other gates are clear. Approval on an earlier head carries over only the hive's own merge of the base branch, never another push.", nil } + if len(matches) > 0 && diffReason == "" && c.humanMergeOwnerApprovalEnabled(owner+"/"+repo) { + return c.humanMergeOwnerApprovalReply(ctx, owner, repo, pr, head) + } if len(matches) > 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/human_merge_path_release.go b/src/pkg/github/human_merge_path_release.go index 4c11718962..0a0d1777fa 100644 --- a/src/pkg/github/human_merge_path_release.go +++ b/src/pkg/github/human_merge_path_release.go @@ -112,12 +112,44 @@ func humanMergeHeadMarker(head string) string { // Callers must supply the process writeback gate (nil fails closed), re-read // labels after release, and retain exact-head merge binding. func ReleaseHumanMergePathHold(ctx context.Context, client *gh.Client, gate *writeback.Gate, owner, repo string, number int, appLogin, expectedHead string, qualified bool) (bool, error) { - if !qualified || client == nil || gate == nil || strings.TrimSpace(appLogin) == "" || !validHumanMergeHead(expectedHead) { + if !qualified || gate == nil { + return false, nil + } + allowed := func(item writeback.Item) bool { + return gate.Allowed(owner+"/"+repo, item, writeback.KindHoldGateNotice).Allowed + } + return releaseHumanMergePathHold(ctx, client, allowed, owner, repo, number, appLogin, expectedHead, false) +} + +// ReleaseApprovedHumanMergePathHold removes the `hold` the human-merge-path +// gate put on PR number once a trusted merger explicitly approved +// expectedHead on a repository listed in auto_merge.human_merge_owner_approval +// (the caller establishes both). Unlike the pin-only release it may lift a +// hold recorded for expectedHead itself, which is the point: the person +// approved exactly what the hold was put on. The provenance rules are the +// pin-only release's, widened only for the hold the gate re-adds on a later +// head (it posts no second notice): every `hold` the PR was ever labelled +// with must be the App's, the first of them added within a minute before +// the App's single, unedited, head-stamped notice, and the hold the PR +// wears now the latest of them. A hold a person added or re-added at any +// point is never removed. allowed is the caller's write-back decision for +// the item (nil fails closed). It only removes a label: CI, soak, review and +// every other merge gate still apply. +func ReleaseApprovedHumanMergePathHold(ctx context.Context, client *gh.Client, allowed func(writeback.Item) bool, owner, repo string, number int, appLogin, expectedHead string) (bool, error) { + return releaseHumanMergePathHold(ctx, client, allowed, owner, repo, number, appLogin, expectedHead, true) +} + +// releaseHumanMergePathHold is the shared body. approved selects the +// owner-approval rules described on ReleaseApprovedHumanMergePathHold; +// otherwise the pin-only rules apply (a stale head only, exactly one hold +// application). +func releaseHumanMergePathHold(ctx context.Context, client *gh.Client, allowed func(writeback.Item) bool, owner, repo string, number int, appLogin, expectedHead string, approved bool) (bool, error) { + if client == nil || allowed == nil || strings.TrimSpace(appLogin) == "" || !validHumanMergeHead(expectedHead) { return false, nil } pr, _, err := client.PullRequests.Get(ctx, owner, repo, number) if err != nil { - return false, fmt.Errorf("fetching pin-only head: %w", err) + return false, fmt.Errorf("fetching human-merge-path head: %w", err) } if pr.GetHead().GetSHA() != expectedHead { return false, nil @@ -155,8 +187,12 @@ func ReleaseHumanMergePathHold(ctx context.Context, client *gh.Client, gate *wri if len(tail) < 44 || !validHumanMergeHead(tail[:40]) || !strings.HasPrefix(tail[40:], " -->") { return false, nil } - // Only stale path holds may be released, never the currently refused head. - if tail[:40] == expectedHead || comment.GetCreatedAt().IsZero() || !comment.GetUpdatedAt().Time.Equal(comment.GetCreatedAt().Time) { + if comment.GetCreatedAt().IsZero() || !comment.GetUpdatedAt().Time.Equal(comment.GetCreatedAt().Time) { + return false, nil + } + // The pin-only release lifts only a stale path hold, never the + // currently refused head; an owner's approval of that head may. + if !approved && tail[:40] == expectedHead { return false, nil } notice = comment @@ -173,10 +209,13 @@ func ReleaseHumanMergePathHold(ctx context.Context, client *gh.Client, gate *wri return false, nil } - // Require exactly one hold transition in the complete history, owned by the - // configured App and immediately preceding its notice. Older remove/re-add - // cycles are deliberately not guessed at, even when the latest actor is App. - var applied *gh.IssueEvent + // Pin-only: exactly one hold transition in the complete history, owned + // by the configured App and immediately preceding its notice. Older + // remove/re-add cycles are deliberately not guessed at, even when the + // latest actor is App. Approved: the first application is that one, + // every later application is also the App's (the gate re-holding a new + // head), and the latest transition is an application. + var first, last *gh.IssueEvent eventsOpts := &gh.ListOptions{PerPage: 100} for { events, resp, err := client.Issues.ListIssueEvents(ctx, owner, repo, number, eventsOpts) @@ -190,14 +229,25 @@ func ReleaseHumanMergePathHold(ctx context.Context, client *gh.Client, gate *wri if event.GetEvent() != "labeled" && event.GetEvent() != "unlabeled" { continue } - if applied != nil || event.GetEvent() != "labeled" || !strings.EqualFold(event.GetActor().GetLogin(), appLogin) || event.GetActor().GetType() != "Bot" { + appApplied := event.GetEvent() == "labeled" && strings.EqualFold(event.GetActor().GetLogin(), appLogin) && event.GetActor().GetType() == "Bot" + if first == nil { + if !appApplied { + return false, nil + } + delta := notice.GetCreatedAt().Sub(event.GetCreatedAt().Time) + if event.GetCreatedAt().IsZero() || delta < 0 || delta > time.Minute { + return false, nil + } + first, last = event, event + continue + } + if !approved { return false, nil } - delta := notice.GetCreatedAt().Sub(event.GetCreatedAt().Time) - if event.GetCreatedAt().IsZero() || delta < 0 || delta > time.Minute { + if event.GetEvent() == "labeled" && !appApplied { return false, nil } - applied = event + last = event } if resp == nil { return false, nil @@ -207,7 +257,7 @@ func ReleaseHumanMergePathHold(ctx context.Context, client *gh.Client, gate *wri } eventsOpts.Page = resp.NextPage } - if applied == nil { + if first == nil || last == nil || last.GetEvent() != "labeled" { return false, nil } // Refetch the head immediately before the write; GitHub label deletion has no @@ -229,7 +279,7 @@ func ReleaseHumanMergePathHold(ctx context.Context, client *gh.Client, gate *wri for _, label := range current.Labels { item.Labels = append(item.Labels, label.GetName()) } - if !gate.Allowed(owner+"/"+repo, item, writeback.KindHoldGateNotice).Allowed { + if !allowed(item) { return false, nil } if _, err := client.Issues.RemoveLabelForIssue(ctx, owner, repo, number, HumanMergePathHoldLabel); err != nil { // writeback:gated diff --git a/src/pkg/github/human_merge_path_release_test.go b/src/pkg/github/human_merge_path_release_test.go index 967b693dee..b7bb294d8d 100644 --- a/src/pkg/github/human_merge_path_release_test.go +++ b/src/pkg/github/human_merge_path_release_test.go @@ -163,3 +163,80 @@ func TestHumanMergeHoldHeadAttribution(t *testing.T) { }) } } + +// The owner-approval release (auto_merge.human_merge_owner_approval) may lift +// the hold on the head it was put on, and a hold the gate re-added on a later +// head with no second notice; a person's application anywhere in the history, +// a history that ends removed, or a write-back refusal keeps the hold. The +// pin-only release still refuses the same head. +func TestReleaseApprovedHumanMergePathHold(t *testing.T) { + head := strings.Repeat("b", 40) + oldHead := strings.Repeat("a", 40) + app := map[string]string{"login": "hive[bot]", "type": "Bot"} + person := map[string]string{"login": "person", "type": "User"} + event := func(kind, at string, actor map[string]string) map[string]any { + return map[string]any{"event": kind, "created_at": at, "label": map[string]string{"name": "hold"}, "actor": actor} + } + appHold := event("labeled", "2026-11-02T12:00:01Z", app) + for _, tc := range []struct { + name string + noticeHead string + events []map[string]any + pinOnly bool + refuse bool + want bool + }{ + {name: "hold on the approved head", noticeHead: head, events: []map[string]any{appHold}, want: true}, + {name: "pin-only keeps the same-head hold", noticeHead: head, events: []map[string]any{appHold}, pinOnly: true}, + {name: "App re-held a later head", noticeHead: oldHead, events: []map[string]any{appHold, event("unlabeled", "2026-11-03T09:00:00Z", app), event("labeled", "2026-11-03T10:00:00Z", app)}, want: true}, + {name: "person re-added the hold", noticeHead: head, events: []map[string]any{appHold, event("unlabeled", "2026-11-03T09:00:00Z", person), event("labeled", "2026-11-03T10:00:00Z", person)}}, + {name: "person's hold first", noticeHead: head, events: []map[string]any{event("labeled", "2026-11-02T12:00:01Z", person)}}, + {name: "history ends removed", noticeHead: head, events: []map[string]any{appHold, event("unlabeled", "2026-11-03T09:00:00Z", app)}}, + {name: "write-back gate refuses", noticeHead: head, events: []map[string]any{appHold}, refuse: true}, + } { + t.Run(tc.name, func(t *testing.T) { + deletes := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/pulls/1"): + _ = json.NewEncoder(w).Encode(map[string]any{"head": map[string]string{"sha": head}, "labels": []map[string]string{{"name": "hold"}}}) + case strings.HasSuffix(r.URL.Path, "/comments"): + body := HumanMergePathComment([]string{"Containerfile"}) + humanMergeHeadMarker(tc.noticeHead) + _ = json.NewEncoder(w).Encode([]map[string]any{{"body": body, "created_at": "2026-11-02T12:00:02Z", "updated_at": "2026-11-02T12:00:02Z", "user": app}}) + case strings.HasSuffix(r.URL.Path, "/events"): + _ = json.NewEncoder(w).Encode(tc.events) + case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/labels/hold"): + deletes++ + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(404) + } + })) + defer srv.Close() + client, err := gh.NewClient(srv.Client()).WithEnterpriseURLs(srv.URL, srv.URL) + if err != nil { + t.Fatal(err) + } + var released bool + if tc.pinOnly { + gate := writeback.New(writeback.Config{PerRepo: map[string]writeback.RepoOverride{"o/r": {Mode: writeback.RepoModeFull}}}, writeback.Deps{}, "") + released, err = ReleaseHumanMergePathHold(context.Background(), client, gate, "o", "r", 1, "hive[bot]", head, true) + } else { + allowed := func(writeback.Item) bool { return !tc.refuse } + released, err = ReleaseApprovedHumanMergePathHold(context.Background(), client, allowed, "o", "r", 1, "hive[bot]", head) + } + if err != nil { + t.Fatal(err) + } + if released != tc.want || (deletes == 1) != tc.want { + t.Fatalf("released=%v deletes=%d, want %v", released, deletes, tc.want) + } + }) + } + + if released, err := ReleaseApprovedHumanMergePathHold(context.Background(), gh.NewClient(nil), nil, "o", "r", 1, "hive[bot]", head); released || err != nil { + t.Fatalf("nil write-back decision: released=%v err=%v, want a refusal with no call", released, err) + } +} diff --git a/src/pkg/stageengine/prstage/causes.go b/src/pkg/stageengine/prstage/causes.go index fa4b3a8085..d60b9b4b63 100644 --- a/src/pkg/stageengine/prstage/causes.go +++ b/src/pkg/stageengine/prstage/causes.go @@ -17,6 +17,10 @@ const ( CauseTestsRemoved = "the PR removes tests, which the lane never merges unattended" CauseReporterTrustHold = "the reporter-trust hold is in place" CauseHumanMergePath = "the PR touches a human-merge path (auto_merge.human_merge_paths)" + // CauseHumanMergePathAwaitingApproval: the same refusal on a repository + // listed in auto_merge.human_merge_owner_approval, where a trusted + // merger's approval of the current head releases it. + CauseHumanMergePathAwaitingApproval = "the PR touches a human-merge path (auto_merge.human_merge_paths): awaiting a trusted merger's approval of the current head, which on this repository (auto_merge.human_merge_owner_approval) releases the hive's hold so it merges the PR once the other gates clear" // CauseHumanMergeRequired: the breaking-change title or the // needs-owner-merge label; the words the 090 chip and gate reuse. CauseHumanMergeRequired = "breaking change — owner merges" diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index ecd3ed1360..afada967a5 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -170,6 +170,12 @@ type Evidence struct { // stays true until that approval, but the 085 actions must ask for the // approval rather than say no approval helps. ApprovalReleasesFence bool + // ApprovalReleasesPathHold is true when the manual-merge reason is a + // human-merge path on a repository listed in + // auto_merge.human_merge_owner_approval: a trusted merger's explicit + // approval of Head releases the hive's hold and the hive merges the PR + // once the other gates clear, so the 085 actions ask for that approval. + ApprovalReleasesPathHold bool // CauseAwaitsApproval is true when CauseReason is that fence awaiting // the owner's approval. Once HumanApprover is set the approval has // released it, so the 085 note stops listing it: a lane stopped at a @@ -356,6 +362,10 @@ type Route struct { // ApprovalReleasesFence is Evidence.ApprovalReleasesFence: the // manual-merge reason is a workflow-path fence an approval releases. ApprovalReleasesFence bool + // ApprovalReleasesPathHold is Evidence.ApprovalReleasesPathHold: the + // 085 actions ask for the approval that releases the human-merge-path + // hold. + ApprovalReleasesPathHold bool // HumanApprover is the trusted merger whose approval on Head settled // the requires_human verdict / manual-merge rule ("" when none). HumanApprover string @@ -727,7 +737,7 @@ func routeProgress(e Evidence) Route { } if len(decide) > 0 { return Route{Stage: NeedsDecision, Reasons: decide, Summary: summary, Head: e.Head, SelfAuthored: e.SelfAuthored, Verdict: e.Verdict, - Holds: append([]string(nil), e.Holds...), Sentinel: e.Sentinel, ManualMerge: e.ManualMerge, ApprovalReleasesFence: e.ManualMerge && e.ApprovalReleasesFence, HumanApprover: approver, Hold: e.Hold} + Holds: append([]string(nil), e.Holds...), Sentinel: e.Sentinel, ManualMerge: e.ManualMerge, ApprovalReleasesFence: e.ManualMerge && e.ApprovalReleasesFence, ApprovalReleasesPathHold: e.ManualMerge && e.ApprovalReleasesPathHold, HumanApprover: approver, Hold: e.Hold} } if e.HeadDirty { // GitHub reports this very head `dirty`: it cannot merge, by the @@ -1016,12 +1026,20 @@ func readyCommentAccept(r Route) string { return "`/lgtm` `/approve` (or merge)" } +// approvalReleases reports whether a trusted merger's approval of the head +// releases the manual-merge reason: the workflow-path fence +// (ApprovalReleasesFence) or a human-merge path on a repository listed in +// auto_merge.human_merge_owner_approval (ApprovalReleasesPathHold). +func (r Route) approvalReleases() bool { + return r.ApprovalReleasesFence || r.ApprovalReleasesPathHold +} + // DecisionComment renders the 085 entry comment naming what is owed. A // route with no reasons names DecisionReasonUnnamed instead of an empty list. func DecisionComment(r Route) string { var b strings.Builder b.WriteString(DecisionCommentMarker) - if r.ManualMerge && !r.ApprovalReleasesFence { + if r.ManualMerge && !r.approvalReleases() { b.WriteString("\nNeeds a manual merge decision") } else { b.WriteString("\nNeeds a decision, not a merge") @@ -1150,7 +1168,7 @@ func DecisionActions(r Route) string { if r.Stage != NeedsDecision { return "" } - if r.ManualMerge && !r.ApprovalReleasesFence { + if r.ManualMerge && !r.approvalReleases() { return "**What to do:** a maintainer must review and merge this PR manually; an approving review or `/hive approve` does not override this lane's manual-merge rule." } var steps []string @@ -1162,6 +1180,15 @@ func DecisionActions(r Route) string { // "a trusted merger approves this head" next to "approved by // @Danathar"). Say it is done; the reasons name what is left. steps = append(steps, "nothing more to approve: @"+approver+" approved this head ("+head+"); resolve the other reasons listed above") + } else if r.ManualMerge && r.ApprovalReleasesPathHold { + // auto_merge.human_merge_owner_approval: an explicit approval of the + // head releases the hive's human-merge-path hold; `/hive approve` + // counts here, unlike for the workflow-path fence. + settles := "" + if r.Verdict == VerdictRequiresHuman { + settles = " (a GitHub **Approve** review or `/hive decision approve` also settles the reviewer's `requires_human` verdict)" + } + steps = append(steps, "a trusted merger approves this head ("+head+") with a GitHub **Approve** review, a `/hive decision approve` reply (typed here or from the dashboard) or a `/hive approve` reply; that releases the hive's hold for this repository's human-merge paths"+settles+", and the hive merges the PR once the other gates clear. A new push needs a new approval, except the hive's own update from the base branch") } else if r.ManualMerge { // Only `/hive decision approve` (typed or from the dashboard) and // an Approve review release the fence; `/hive approve` never does diff --git a/src/pkg/stagelabels/human_test.go b/src/pkg/stagelabels/human_test.go index d495dd7388..cc62db827c 100644 --- a/src/pkg/stagelabels/human_test.go +++ b/src/pkg/stagelabels/human_test.go @@ -1044,3 +1044,43 @@ func TestRequiresHumanReasons(t *testing.T) { t.Fatalf("RouteHuman reasons = %q, want %q", r.Reasons, want) } } + +// On a repository listed in auto_merge.human_merge_owner_approval the 085 +// actions for a human-merge path ask for the approval that releases the +// hive's hold (`/hive approve` included) instead of a manual merge; without +// a manual-merge reason the flag offers nothing. +func TestDecisionActionsHumanMergePathOwnerApproval(t *testing.T) { + e := readyEvidence() + e.ManualMerge = true + e.ApprovalReleasesPathHold = true + e.Cause = CauseDecision + e.CauseReason = "the PR touches a human-merge path (auto_merge.human_merge_paths): awaiting a trusted merger's approval of the current head" + r := RouteHuman(e) + if r.Stage != NeedsDecision || !r.ManualMerge || !r.ApprovalReleasesPathHold { + t.Fatalf("route = %+v", r) + } + got := DecisionComment(r) + for _, want := range []string{ + "Needs a decision, not a merge", + "a trusted merger approves this head (`abc1234`) with a GitHub **Approve** review, a `/hive decision approve` reply", + "or a `/hive approve` reply; that releases the hive's hold for this repository's human-merge paths", + "the hive merges the PR once the other gates clear", + "A new push needs a new approval", + } { + if !strings.Contains(got, want) { + t.Fatalf("owner-approval DecisionComment missing %q:\n%s", want, got) + } + } + for _, unwanted := range []string{"merge this PR manually", "does not override", "Needs a manual merge decision"} { + if strings.Contains(got, unwanted) { + t.Fatalf("owner-approval DecisionComment says %q:\n%s", unwanted, got) + } + } + + stray := readyEvidence() + stray.Sentinel = true + stray.ApprovalReleasesPathHold = true + if r := RouteHuman(stray); r.ApprovalReleasesPathHold || strings.Contains(DecisionActions(r), "human-merge paths") { + t.Fatalf("path-hold release offered without a manual-merge reason: %+v", r) + } +} diff --git a/src/pkg/stagelabels/sentinel_step.go b/src/pkg/stagelabels/sentinel_step.go index eb826bfd03..364884a73b 100644 --- a/src/pkg/stagelabels/sentinel_step.go +++ b/src/pkg/stagelabels/sentinel_step.go @@ -27,7 +27,7 @@ const sentinelLabelOnlyStep = "resolve the sentinel alert and have a maintainer // label is left for the alert, removed on GitHub or with the row's // Confirm safe, which clears the label and records no approval. func oneApproveSentinelStep(r Route) string { - if (r.ManualMerge && !r.ApprovalReleasesFence) || (!r.ManualMerge && r.Verdict != VerdictRequiresHuman) { + if (r.ManualMerge && !r.approvalReleases()) || (!r.ManualMerge && r.Verdict != VerdictRequiresHuman) { return sentinelLabelOnlyStep } if strings.TrimPrefix(strings.TrimSpace(r.HumanApprover), "@") != "" { From c04ad8b83052ca6d7d99a310be2ff3af35dd3d3e Mon Sep 17 00:00:00 2001 From: Danathar Date: Wed, 18 Nov 2026 16:00:02 +0000 Subject: [PATCH 2/3] test(automerge): expect the 7-char ShortSHA in the human-merge approval comment humanMergeApprovalComment renders the head via stagelabels.ShortSHA, which trims to 7 characters; the test asserted an 8-character prefix, so it failed on every run. Assert the exact backticked 7-char form. Hive-Run: hivecommons/hive#19015 Hive-Plan: fix-pr check-failure Hive-Spec: auto_merge.human_merge_owner_approval#audit-comment Co-Authored-By: Claude Opus 5.5 Signed-off-by: Danathar --- .../automerge/automerge_human_merge_owner_approval_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go b/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go index dcb3d62799..fc57c0a28f 100644 --- a/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go +++ b/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go @@ -56,7 +56,7 @@ func TestHumanMergeApprovalCommentNamesApproverAndHead(t *testing.T) { body := humanMergeApprovalComment(ownerApprovalHead, workflowApproval{Login: "owner"}) for _, want := range []string{ humanMergeApprovalMarker(ownerApprovalHead), - "Hold released for `dddddddd", + "Hold released for `ddddddd`:", "`owner` approved this head", humanMergeOwnerApprovalConfigKey, "not a merge override", From 2bb0e8416d0e241e56c19e591da3ad72ccf297a3 Mon Sep 17 00:00:00 2001 From: Danathar Date: Wed, 18 Nov 2026 17:33:41 +0000 Subject: [PATCH 3/3] fix(automerge): the PR author's own approval never releases the human-merge-path hold Review asked whether a trusted merger who authors a PR touching a human_merge_paths file could approve it themselves. They could (typed /hive decision approve or /hive approve); reject any approval whose login is the PR author. Also add the missing auto_merge.human_merge_owner_approval row to the operator reference. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Danathar --- src/docs/hive-merge.md | 3 +++ src/docs/operator-reference/README.md | 6 +++-- .../automerge_human_merge_owner_approval.go | 19 +++++++++++--- ...tomerge_human_merge_owner_approval_test.go | 26 ++++++++++++++++++- 4 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index dc2961cbb3..a14b86d8ae 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -411,6 +411,9 @@ apply: the approval is not a merge override. first saw the head. These are the workflow-path fence's approvals plus `/hive approve`; an edited comment never counts, and someone who is not a trusted merger cannot approve. +- **Not the author.** The pull request author's own approval never counts, + whatever form it takes, so one account cannot stand in for the second + person the hold exists to bring in. - **Bound to the head.** A new push needs a new approval. The one exception is the fence's: an Approve review or dashboard approval carries over the hive's own update from the base branch when the PR's diff is unchanged. diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 7c8d4d9844..41eebc8341 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -302,7 +302,8 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `auto_merge.allow_unprotected_base` | Deprecated no-op. | Accepted so older configs keep loading. `hive-merge` now merges into any protected or unprotected branch the App can write, subject to the CI-evidence gate and GitHub's own merge rules. | | `auto_merge.no_ci_ok` | Empty by default. | Explicit repo list whose zero-CI merge-request verdict may pass; failing or pending CI evidence is still enforced. | | `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), and by the `hive-merge` relay (#16265), which additionally requires the requested head SHA to match the PR head before and after fetching files. | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`, `action-sha-ref`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. Owners set it per repository from **Settings → Features → Auto-merge** or with the admin MCP operation `auto_merge.update`; an enabled entry is refused for a repository with no `human_merge_paths`. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | -| `auto_merge.human_merge_paths` | Unset (off). | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge. Applies to every merge lane (App self-merge, trusted-author, label-queued, merge-request relay) whatever the intent tier; a matching PR is held with one comment, and an incomplete changed-file list fails closed. The hive lifts its own hold once a later head touches none of the paths. Details in the sweep key table below. | +| `auto_merge.human_merge_paths` | Unset (off). | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge (except in a repository listed in `auto_merge.human_merge_owner_approval`). Applies to every merge lane (App self-merge, trusted-author, label-queued, merge-request relay) whatever the intent tier; a matching PR is held with one comment, and an incomplete changed-file list fails closed. The hive lifts its own hold once a later head touches none of the paths. Details in the sweep key table below. | +| `auto_merge.human_merge_owner_approval` | `[]` (off) | List of `owner/repo`. In a listed repository a trusted merger's approval of the current head (Approve review, `/hive decision approve`, or `/hive approve` posted after the head was seen) releases the hive's own human-merge-path `hold`; every other gate still applies. The PR author's own approval never counts. See [hive-merge.md](../hive-merge.md#owner-approval-releases-the-human-merge-path-hold). | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | Title prefixes (after trimming) that mark a PR as a breaking change a person must merge. Every auto-merge lane and the merge train skip the PR; the tracker parks it at 090 *Ready for human merge · human merge*. Set to `[]` to disable. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive) that mark a PR a person must merge; same effect as the title prefixes. Set to `[]` to disable. | | `forgestate.enabled` | `false` | Runs the per-repo ForgeState cache ([#13373](https://github.com/hivecommons/hive/issues/13373)) and switches the automerge sweep lanes (self-authored, trusted-author, contributor lane) to it: no `/pulls` list per 10 s tick, passes triggered by `check_suite`/`check_run`/`status`/`pull_request_review`/`pull_request` webhooks for the affected PR plus a 5-minute floor pass, and a 60 s freshness-bounded read-through before every merge; a stale snapshot never merges ([#13377](https://github.com/hivecommons/hive/issues/13377)). `forgestate.reconcile_interval_s` (900), `freshness_bound_s` (60), `drift_threshold` (0.05) and `search_budget` (20) tune the cache. | @@ -612,7 +613,8 @@ advanced into the merge path. | `auto_merge.no_ci_ok` | unset (refuse) | **Merge-request watcher key, not a sweep key.** Per-repo opt-in that downgrades only the "unverified" CI verdict (zero statuses, check runs, and workflow runs) to green, for adopted repos with no CI by design. Red and pending verdicts are never downgraded (#6281). See [hive-merge.md](../hive-merge.md). | | `auto_merge.queue_on_approve_and_unhold` | empty (off) | Per-repo opt-in, ACMM L5 only (#13629). When one trusted merger both submits an Approve review on an agent PR's current head and removes its level `hold`, the queued sweep queues the PR through the same path as the dashboard's queue-auto-merge button. Nothing else counts as consent; the self-merge floor (L6), head-SHA re-check, hold guard and Sentinel are unchanged. See [hive-merge.md](../hive-merge.md#one-human-step-at-l5-approve-and-unhold). | | `auto_merge.squash_only` | unset (no repo) | Repo list (`owner/repo`) whose branch policy forbids merge commits. Elsewhere, a `role/trusted` PR (or one whose current head a trusted merger approved) whose head mixes the contributor's commits with App-linked, App-signed ones (the hive's own in-place adoption fixes), every commit self-signed, is labelled `merge-method/merge` and merged with a merge commit instead of parking at `stage/085` as `adoption-stalled:hive-signoff-attribution`; a listed repo keeps squash-only policy and re-homes an in-place adoption to an App-authored superseder instead (#13975). | -| `auto_merge.human_merge_paths` | unset | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge, e.g. `Danathar/goodreads-mcp: [".claude/settings.json", ".claude/hooks/**"]`. Every App merge path honors it: the automerge sweep lanes (App self-merge, trusted-author, label-queued) and the agent merge-request relay refuse a PR that touches a listed path, add `hold`, and post one `` comment naming the path(s); a person must merge it. The sweep lanes and GitHub relay skip that hold only for a PR admitted by `auto_merge.human_merge_pin_only` (#16266, #16265); the relay also requires the exact requested head before and after fetching files. If the changed-file list cannot be fetched completely for a configured repo, the merge is withheld (#11038, #11039). The hold follows the PR's current head: when a later head touches none of the listed paths (a dependency bot moved the file to another PR, a contributor dropped the change), the stage-label pass removes the hive's own `hold` and posts one `` notice for that head, and the merge lanes take the PR from there. It never removes a hold a person set or one with a second hold source (reporter trust, level gate, holdguard, a pause); such a hold stays, and the row and the 085 comment no longer say the PR changes a human-merge path. The lift is write-back kind `human_merge_path_release` (default L5 with the opt-in label, like `needs_decision_comment`). | +| `auto_merge.human_merge_paths` | unset | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge (except in a repository listed in `auto_merge.human_merge_owner_approval`), e.g. `Danathar/goodreads-mcp: [".claude/settings.json", ".claude/hooks/**"]`. Every App merge path honors it: the automerge sweep lanes (App self-merge, trusted-author, label-queued) and the agent merge-request relay refuse a PR that touches a listed path, add `hold`, and post one `` comment naming the path(s); a person must merge it. The sweep lanes and GitHub relay skip that hold only for a PR admitted by `auto_merge.human_merge_pin_only` (#16266, #16265); the relay also requires the exact requested head before and after fetching files. If the changed-file list cannot be fetched completely for a configured repo, the merge is withheld (#11038, #11039). The hold follows the PR's current head: when a later head touches none of the listed paths (a dependency bot moved the file to another PR, a contributor dropped the change), the stage-label pass removes the hive's own `hold` and posts one `` notice for that head, and the merge lanes take the PR from there. It never removes a hold a person set or one with a second hold source (reporter trust, level gate, holdguard, a pause); such a hold stays, and the row and the 085 comment no longer say the PR changes a human-merge path. The lift is write-back kind `human_merge_path_release` (default L5 with the opt-in label, like `needs_decision_comment`). | +| `auto_merge.human_merge_owner_approval` | `[]` (off) | List of `owner/repo`. In a listed repository a trusted merger's approval of the current head (Approve review, `/hive decision approve`, or `/hive approve` posted after the head was seen) releases the hive's own human-merge-path `hold`; every other gate still applies. The PR author's own approval never counts. See [hive-merge.md](../hive-merge.md#owner-approval-releases-the-human-merge-path-hold). | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | PR-title prefixes that mean "breaking change — owner merges" (U+26A0 with or without the VS16 selector by default, matched after trimming leading whitespace). One shared predicate, `automerge.RequiresHumanMerge(pr)`, runs where each lane computes eligibility — App self-merge, label-queued, trusted-author and contributor lanes, plus the refetch before a merge — so a matching PR is never merged by hive and never fronts a merge train, however green and however approved. The PR parks at stage 090 *Ready for human merge* with the `human merge` chip and reason *breaking change — owner merges*; the owner merges it with **Approve & merge as maintainer** or on GitHub. Hive posts one writeback-gated comment saying it will wait for a human. Set to `[]` to turn the title rule off. Added after a ⚠️-titled PR was auto-merged by the trusted-author lane while its owner was still deciding whether to ship it. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive, trimmed) that carry the same "a person merges this" meaning as the title prefixes above; either match is enough. Set to `[]` to turn the label rule off. | | `auto_merge.require_current_base` | unset | Repo list (`owner/repo`) with an explicit **on** override for the current-base merge gate (Settings → Repos → "Merge only on current base"). On a gated repo the App self-merge, trusted-author and contributor lanes only merge a head that contains the current base tip. A green head tested against an older base is updated with GitHub update-branch (a merge commit; no author commit is rewritten) and merges once CI is green on the new head, so a semantic conflict with work merged since turns that PR red instead of breaking the base ([#13634](https://github.com/hivecommons/hive/issues/13634), [#15335](https://github.com/hivecommons/hive/issues/15335)). Costs one compare call per merge candidate. Listing a repo here is also **strict**: a behind head the App cannot update (fork without maintainer edits, branch protection or a missing `contents: write`) is parked (`fork-not-editable` / `update-branch`) rather than merged as tested. Wins over `skip_current_base` and over the default. A dependency bot's branch (`renovate/*` head ref, or a Renovate, Dependabot or Mergeraptor author) is never updated: on a listed repo, or when GitHub itself reports it `behind`, it holds as `behind` until the bot rebases it; a repo gated only by the default merges it as tested (projectbluefin/utah#1097). On v6, a base that refused a direct merge as merge-queue-only (`merge-queue-required`) in the last 24 hours is not updated: GitHub's queue tests base plus PR itself; the PR stays at `100-merge-queue` for a person to enqueue (projectbluefin/finpilot#599). | diff --git a/src/pkg/github/automerge/automerge_human_merge_owner_approval.go b/src/pkg/github/automerge/automerge_human_merge_owner_approval.go index e00d088686..ded9313977 100644 --- a/src/pkg/github/automerge/automerge_human_merge_owner_approval.go +++ b/src/pkg/github/automerge/automerge_human_merge_owner_approval.go @@ -18,7 +18,8 @@ package automerge // `/hive decision approve`), plus a trusted merger's `/hive approve` reply // posted after the head was first seen, bound to the head the same way a // typed decision is (humanMergeApproveCommandActor). A new push needs a new -// approval. A repository not listed keeps the rule absolute. +// approval. The PR author's own approval never counts +// (humanMergeSelfApproval). A repository not listed keeps the rule absolute. // // The release reuses the human-merge-path hold's provenance check // (hgithub.ReleaseApprovedHumanMergePathHold): only a `hold` the App put on @@ -74,14 +75,15 @@ func (c *Engine) humanMergeOwnerApprovalFor(ctx context.Context, owner, repo str return workflowApproval{}, false } number := pr.GetNumber() - if approval, ok := c.workflowFenceApproval(ctx, owner, repo, pr, number, head, comments); ok { + author := strings.TrimSpace(hgithub.SafeGetLogin(pr.GetUser())) + if approval, ok := c.workflowFenceApproval(ctx, owner, repo, pr, number, head, comments); ok && !humanMergeSelfApproval(approval.Login, author) { return approval, true } headPushedAt := c.headObservedAt(owner, repo, number, head, pr) appLogin := strings.TrimSpace(c.transport.AppBotLogin()) for i := len(comments) - 1; i >= 0; i-- { login, ok := humanMergeApproveCommandActor(comments[i], headPushedAt, appLogin) - if !ok { + if !ok || humanMergeSelfApproval(login, author) { continue } if trusted, configured := c.isTrustedMerger(login); !configured || !trusted { @@ -93,6 +95,17 @@ func (c *Engine) humanMergeOwnerApprovalFor(ctx context.Context, owner, repo str return workflowApproval{}, false } +// humanMergeSelfApproval reports whether approver is the PR's own author. The +// author's approval never releases the human-merge-path refusal: the hold +// exists so a second person looks at the change, and a trusted merger who +// opened the PR cannot be that person (GitHub already refuses an author's +// Approve review; a typed `/hive approve` or `/hive decision approve` would +// otherwise let one account stand in for two). +func humanMergeSelfApproval(approver, author string) bool { + approver, author = strings.TrimSpace(approver), strings.TrimSpace(author) + return approver != "" && author != "" && strings.EqualFold(approver, author) +} + // humanMergeApproveCommandActor reads one comment as a person's // `/hive approve` of the head first seen at headPushedAt and returns its // author: the command on the first line, the comment unedited (collaborators diff --git a/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go b/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go index fc57c0a28f..838372c7f0 100644 --- a/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go +++ b/src/pkg/github/automerge/automerge_human_merge_owner_approval_test.go @@ -52,6 +52,24 @@ func TestHumanMergeApproveCommandActor(t *testing.T) { } } +func TestHumanMergeSelfApproval(t *testing.T) { + for _, tc := range []struct { + approver, author string + want bool + }{ + {"owner", "owner", true}, + {"Owner", " owner ", true}, + {"owner", "contributor", false}, + {"owner", testHiveAppBotLogin, false}, + {"", "", false}, + {"owner", "", false}, + } { + if got := humanMergeSelfApproval(tc.approver, tc.author); got != tc.want { + t.Errorf("humanMergeSelfApproval(%q, %q) = %v, want %v", tc.approver, tc.author, got, tc.want) + } + } +} + func TestHumanMergeApprovalCommentNamesApproverAndHead(t *testing.T) { body := humanMergeApprovalComment(ownerApprovalHead, workflowApproval{Login: "owner"}) for _, want := range []string{ @@ -188,6 +206,7 @@ func TestPRApproveReplyHumanMergeOwnerApproval(t *testing.T) { for _, tc := range []struct { name string unlisted bool + author string reviews []*gh.PullRequestReview comments []*gh.IssueComment want string @@ -197,6 +216,7 @@ func TestPRApproveReplyHumanMergeOwnerApproval(t *testing.T) { {name: "Approve review on the head", reviews: []*gh.PullRequestReview{{ID: gh.Ptr(int64(1)), State: gh.Ptr("APPROVED"), CommitID: gh.Ptr("sha7"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}}}, want: "released for `sha7`. "}, {name: "this /hive approve after the head", comments: []*gh.IssueComment{{ID: gh.Ptr(int64(5)), Body: gh.Ptr("/hive approve"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}, CreatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 11, 0, 0, 0, time.UTC)}}}, want: "released for `sha7`. "}, {name: "/hive approve before the head", comments: []*gh.IssueComment{{ID: gh.Ptr(int64(5)), Body: gh.Ptr("/hive approve"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}, CreatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC)}}}, want: "no approval of the current head (`sha7`) is recorded yet"}, + {name: "the PR author's own /hive approve does not count", author: "owner", comments: []*gh.IssueComment{{ID: gh.Ptr(int64(5)), Body: gh.Ptr("/hive approve"), User: &gh.User{Login: gh.Ptr("owner"), Type: gh.Ptr("User")}, CreatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 11, 0, 0, 0, time.UTC)}}}, want: "cannot enable an automerge lane"}, {name: "approval by someone who is not a trusted merger", reviews: []*gh.PullRequestReview{{ID: gh.Ptr(int64(1)), State: gh.Ptr("APPROVED"), CommitID: gh.Ptr("sha7"), User: &gh.User{Login: gh.Ptr("passerby"), Type: gh.Ptr("User")}}}, want: "no approval of the current head"}, } { t.Run(tc.name, func(t *testing.T) { @@ -208,7 +228,11 @@ func TestPRApproveReplyHumanMergeOwnerApproval(t *testing.T) { } 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(testHiveAppBotLogin)}, Head: &gh.PullRequestBranch{SHA: gh.Ptr("sha7")}, UpdatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC)}}) + author := tc.author + if author == "" { + author = testHiveAppBotLogin + } + _ = json.NewEncoder(w).Encode(&gh.PullRequest{Number: gh.Ptr(7), State: gh.Ptr("open"), User: &gh.User{Login: gh.Ptr(author)}, Head: &gh.PullRequestBranch{SHA: gh.Ptr("sha7")}, UpdatedAt: &gh.Timestamp{Time: time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC)}}) case "/repos/acme/widget/pulls/7/files": _ = json.NewEncoder(w).Encode([]*gh.CommitFile{{Filename: gh.Ptr("sensitive/config.yaml"), Status: gh.Ptr("modified")}}) case "/repos/acme/widget/pulls/7/reviews":