diff --git a/changelog.d/added-human-merge-breaking-title.md b/changelog.d/added-human-merge-breaking-title.md new file mode 100644 index 0000000000..90fca30683 --- /dev/null +++ b/changelog.d/added-human-merge-breaking-title.md @@ -0,0 +1 @@ +- Auto-merge never merges a breaking-titled (`⚠️`/`⚠`) or `needs-owner-merge`-labelled PR: one shared `RequiresHumanMerge` predicate skips it in every lane and the merge train, the tracker parks it at 090 *Ready for human merge · human merge* ("breaking change — owner merges") with **Approve & merge as maintainer** as the lead action, and hive posts one writeback-gated comment saying it waits for a human. Configurable via `auto_merge.human_merge_title_prefixes` and `auto_merge.human_merge_labels`. diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index a24e6f37f1..70caa7a86a 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -81,6 +81,7 @@ import ( "github.com/hivecommons/hive/pkg/snapshot" "github.com/hivecommons/hive/pkg/spokealerts" "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stageengine/prstage" "github.com/hivecommons/hive/pkg/stagelabels" "github.com/hivecommons/hive/pkg/timeline" "github.com/hivecommons/hive/pkg/tokens" @@ -2569,6 +2570,7 @@ func (b *boot) bootAgentsWith(deps bootAgentsDeps) { // Human-merge paths (#11038): read through b.cfg on every evaluation so // a reload of auto_merge.human_merge_paths applies without a restart. autoMergeOpts.HumanMergePaths = func(repo string) []string { return humanMergePathsFor(b.cfg, 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) } autoMergeOpts.RequireCurrentBaseStrict = func(repo string) bool { return b.cfg != nil && b.cfg.AutoMerge.RequireCurrentBaseStrictFor(repo) @@ -9454,6 +9456,7 @@ func runAutoMergeSweepIfDue(ctx context.Context, ghClient *github.Client, cfg *c opts.RepoAutoMergeEnabled = func(repo string) bool { return cfg.RepoAutoMergeEnabled(repo) } opts.RepoOnGitHub = func(repo string) bool { return cfg.RepoOnGitHub(repo) } opts.HumanMergePaths = func(repo string) []string { return humanMergePathsFor(cfg, 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) } opts.MergeForwardTrustedHuman = func(repo string) bool { return cfg.AutoMerge.MergeForwardTrustedHumanFor(repo) } @@ -10036,6 +10039,7 @@ func runIssueUnparkSweepIfDue(ctx context.Context, ghClient *github.Client, cfg if cfg != nil { approveOpts.RepoAutoMergeEnabled = cfg.RepoAutoMergeEnabled approveOpts.HumanMergePaths = func(repo string) []string { return humanMergePathsFor(cfg, repo) } + approveOpts.HumanMergeRule = func() prstage.HumanMergeRule { return humanMergeRuleFor(cfg) } approveOpts.TrustedBotAuthors = func() map[string]bool { return cfg.AutoMerge.TrustedBotAuthorSet() } } approveEngine := automerge.New(ghClient, approveOpts) diff --git a/src/cmd/hive/main_helpers.go b/src/cmd/hive/main_helpers.go index fa434b31ee..7b7a64e167 100644 --- a/src/cmd/hive/main_helpers.go +++ b/src/cmd/hive/main_helpers.go @@ -15,6 +15,7 @@ import ( "github.com/hivecommons/hive/pkg/github/automerge" "github.com/hivecommons/hive/pkg/holdguard" "github.com/hivecommons/hive/pkg/intent" + "github.com/hivecommons/hive/pkg/stageengine/prstage" "github.com/hivecommons/hive/pkg/writeback" ) @@ -409,6 +410,16 @@ func humanMergePathsFor(cfg *config.Config, repo string) []string { return cfg.AutoMerge.HumanMergePathsFor(repo) } +// humanMergeRuleFor reads auto_merge.human_merge_title_prefixes / +// human_merge_labels through cfg on every call so a reload applies +// (hivecommons/hive#15442). A nil config means the defaults. +func humanMergeRuleFor(cfg *config.Config) prstage.HumanMergeRule { + if cfg == nil { + return prstage.HumanMergeRule{} + } + return cfg.AutoMerge.HumanMergeRule() +} + // selfMergeIntentGate builds the intent-tier gate the App self-merge sweep // enforces (#6258) from the same config and bead evidence the human merge // lane uses. Enforce is read through cfg on every call so a reload applies. diff --git a/src/docs/dashboard-copy-inventory.md b/src/docs/dashboard-copy-inventory.md index 599c634f37..d37f1bd98a 100644 --- a/src/docs/dashboard-copy-inventory.md +++ b/src/docs/dashboard-copy-inventory.md @@ -39,6 +39,7 @@ The new hover, verbatim (title line omitted): | `stageTrackerUntrustedAuthorWhy` (all 10 trust reasons, summed) | question, reason text, delegated outcome | 314 | 68 | `TestStageTrackerHumanMergeSaysItOnce` (no config keys, no jargon) | | `stageTrackerUntrustedAuthorFix` (new; the how-to-trust line, Details only) | Details | — | 81 | same | | `stageTrackerHumanMergeReasonWords` tips (9 codes, summed) | chip hover, 090 chevron tip | 227 | 101 | `TestStageTrackerHumanMergeReason` | +| `stageTrackerHumanMergeReasonWords[breaking-change]` (new: chip `human merge`, caption *Ready for human merge (breaking change — owner merges)*) | chip, caption, chevron tip, `new.gates[]` | — | 14 | `TestStageTrackerHumanMergeRequiredRow` | | `HumanMergeReasonText` composition (090 untrusted author) | chevron tip, row tooltip, feed | 43 + 24 ("Until then a maintainer merges — Approve & merge…") | 11 | `TestStageTrackerHumanMergeSaysItOnce` | | `HumanMergeReasonText` admitted prefix | same | 41 | 9 | `TestStageTrackerDecisionForHumanMerge/admitted…` | | `stageTrackerCaption` 090 | row caption, feed | 19 | 7 | `TestStageTrackerCaption…` cases in `stage_tracker_test.go` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 1d09f03f6e..f937ac1553 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -774,7 +774,7 @@ Side stages share a column rather than adding columns: The author legend is a blue Hive hexagon, purple contributor-agent robot or teal human silhouette. The kind is `author/*`, inferred from the snapshot if its label is absent; the link tooltip names the login. On Claimed, the actor is the claim holder; on PR in progress and Returned to contributor it is the author. Hive owns review, adoption and auto-merge work; a human owns a human decision or manual merge. The payload's `stage_actor` is the authoritative actor (see [Who is on it](#who-is-on-it-actor-icons)). -At 090 the row explains why: `· workflow files`, `· tests removed`, `· manual-merge policy`, `· branch protection`, `· merge method`, `· auto-merge off`, `· untrusted author`, `· unauthorized`, `· reviewer deferred` or `· policy` ([#14658](https://github.com/hivecommons/hive/issues/14658)). `human_merge_reason` is a `prstage.HumanMergeReason*` code from the stage record's lane reason; `human_merge_reason_text` supplies the sentence and next step. For example, workflow-file changes require Merge on GitHub. Manual-merge text can read *Awaiting human merge · workflow files · approved by @login*; search and needs-attention text carry the same reason. A nested PR mirrors `human_approver`, `manual_merge` and both reason fields on `linked_prs`. +At 090 the row explains why: `· workflow files`, `· tests removed`, `· manual-merge policy`, `· branch protection`, `· merge method`, `· auto-merge off`, `· untrusted author`, `· unauthorized`, `· reviewer deferred`, `· policy` or `· human merge` (a ⚠️-titled or `needs-owner-merge` PR — the caption reads *Ready for human merge (breaking change — owner merges)*, `human_merge_reason` is `breaking-change`, and hive never merges it, so **Approve — let hive merge** is greyed) ([#14658](https://github.com/hivecommons/hive/issues/14658)). `human_merge_reason` is a `prstage.HumanMergeReason*` code from the stage record's lane reason; `human_merge_reason_text` supplies the sentence and next step. For example, workflow-file changes require Merge on GitHub. Manual-merge text can read *Awaiting human merge · workflow files · approved by @login*; search and needs-attention text carry the same reason. A nested PR mirrors `human_approver`, `manual_merge` and both reason fields on `linked_prs`. ### Pairing, rows and counts diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index eea1248866..ef067fcdff 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -312,6 +312,28 @@ auto_merge: enabled: true # default; set false to leave such PRs held ``` +### Breaking-titled or `needs-owner-merge` PRs wait for a human + +A PR whose trimmed title starts with `⚠️` (U+26A0, with or without the VS16 +selector — the PR-title convention for a breaking change) or that carries a +`needs-owner-merge` label is never merged by hive. One shared predicate, +`automerge.RequiresHumanMerge(pr)`, is evaluated once per PR where each lane +already computes eligibility (the App self-merge, label-queued, trusted-author +and contributor prefilters, and the refetch just before a merge), so the merge +train — which draws its candidates from the same prefilters — never fronts or +carries such a PR either. The prefixes and labels are configurable via +`auto_merge.human_merge_title_prefixes` and `auto_merge.human_merge_labels` +(see the operator reference); an empty list turns that half of the rule off. + +When the PR is otherwise merge-ready (green checks, approvals satisfied) the +stage tracker parks it at **090 Ready for human merge** with the chip +*human merge* and the reason *breaking change — owner merges*; the owner +merges it with **Approve & merge as maintainer** (the existing gated +operator path) or on GitHub. Hive posts one comment, through the writeback +gate, saying it will wait for a human. The rule exists because a ⚠️-titled +PR was auto-merged by the trusted-author lane while its owner was still +deciding whether to ship it. + ### Trusted-author auto-merge `auto_merge.trusted_authors` is a third, default-off sweep tier for diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 8610f1725a..539d829a24 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -231,6 +231,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_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. Details in the sweep key table below. | +| `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. | | `evidence.enabled` | On by default. | The review relay writes one [review evidence bundle](review-evidence.md) per PR head to `/data/evidence////.json` when it records a verdict or posts a review; the sentinel sweep adds its findings to the flagged head's bundle; and every merge path adds the head's CI check-run summary, the human approvals and label changes, and the merge event. Owners and mergers read bundles through `GET /api/review/evidence` and `GET /api/review/evidence/list` (see the [API reference](api-reference.md)). Set `false` to stop writing new bundles; existing ones are left in place. | | `evidence.signing_key_file` | Unset (bundles unsigned). | Path to an Ed25519 private key (32-byte seed or 64-byte key, hex or base64). When set and readable, bundles are signed. Dashboard/API readers require a valid signature under its public half and fail closed when the configured key is unavailable; unsigned mode verifies only the bundle content hash. Writers still record `"signed": false` when the key is empty, absent or unusable and log a warning for an unusable key, so an evidence write failure never blocks review or merge work. Keep the key off shared hosts. | @@ -430,6 +432,8 @@ advanced into the merge path. | `auto_merge.allow_unprotected_base` | deprecated no-op | Accepted for compatibility only. [`hive-merge`](hive-merge.md) no longer refuses solely because a base branch has no GitHub branch protection; it may merge into any branch the App can write after positive CI evidence. | | `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.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. If the changed-file list cannot be fetched completely for a configured repo, the merge is withheld (#11038, #11039). | +| `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. | | `auto_merge.require_current_base_default` | `false` | Hive-wide default of the current-base gate for repos in neither `require_current_base` nor `skip_current_base` (Settings → Features → Auto-merge → "Merge only on current base"). **Off** by default: the merge train already update-branches overlapping siblings, so the gate is being soaked per repo (hive's own hive first, via `require_current_base`) before any hive turns it on everywhere. When `true`, a behind head the App cannot update merges as it was tested, with one WARN per PR (`automerge current-base gate: … merging as tested`), so fork-heavy repos are not parked wholesale. | | `auto_merge.skip_current_base` | unset | Repo list (`owner/repo`) with an explicit **off** override for the current-base gate (Settings → Repos → "Merge only on current base" unchecked): a green head there merges even if the base has moved, whatever `require_current_base_default` says. An explicit `require_current_base` entry wins over this list. | diff --git a/src/pkg/config/automerge_human_merge_test.go b/src/pkg/config/automerge_human_merge_test.go new file mode 100644 index 0000000000..94fbd3a471 --- /dev/null +++ b/src/pkg/config/automerge_human_merge_test.go @@ -0,0 +1,41 @@ +package config + +import ( + "reflect" + "testing" + + "github.com/hivecommons/hive/pkg/stageengine/prstage" +) + +func TestAutoMergeHumanMergeRuleDefaultsAndOverrides(t *testing.T) { + var unset AutoMergeConfig + if got := unset.HumanMergeRule(); !reflect.DeepEqual(got.TitlePrefixes, prstage.DefaultHumanMergeTitlePrefixes) || !reflect.DeepEqual(got.Labels, prstage.DefaultHumanMergeLabels) { + t.Fatalf("unset keys should yield the defaults, got %+v", got) + } + if ok, _ := unset.HumanMergeRule().RequiresHumanMerge("\u26a0\ufe0f break", nil); !ok { + t.Fatal("default rule must catch a ⚠️ title") + } + + off := AutoMergeConfig{HumanMergeTitlePrefixes: []string{}, HumanMergeLabels: []string{}} + if got := off.HumanMergeRule(); len(got.TitlePrefixes) != 0 || got.TitlePrefixes == nil || len(got.Labels) != 0 || got.Labels == nil { + t.Fatalf("explicit empty lists must stay empty (non-nil), got %+v", got) + } + if ok, _ := off.HumanMergeRule().RequiresHumanMerge("\u26a0\ufe0f break", []string{"needs-owner-merge"}); ok { + t.Fatal("empty lists must switch the rule off") + } + + custom := AutoMergeConfig{HumanMergeTitlePrefixes: []string{"BREAKING:"}, HumanMergeLabels: []string{"ship-by-owner"}} + prefixes := custom.HumanMergeTitlePrefixesEffective() + prefixes[0] = "mutated" + if custom.HumanMergeTitlePrefixes[0] != "BREAKING:" { + t.Fatal("HumanMergeTitlePrefixesEffective must return a copy") + } + labels := custom.HumanMergeLabelsEffective() + labels[0] = "mutated" + if custom.HumanMergeLabels[0] != "ship-by-owner" { + t.Fatal("HumanMergeLabelsEffective must return a copy") + } + if ok, reason := custom.HumanMergeRule().RequiresHumanMerge("x", []string{"Ship-By-Owner"}); !ok || reason != "label:ship-by-owner" { + t.Fatalf("custom label rule = %v %q", ok, reason) + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index c55e7bab46..ee94e973b6 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -28,6 +28,7 @@ import ( "github.com/hivecommons/hive/pkg/modelfamily" "github.com/hivecommons/hive/pkg/resolve" "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stageengine/prstage" "github.com/hivecommons/hive/pkg/writeback" "gopkg.in/yaml.v3" ) @@ -8032,6 +8033,16 @@ type AutoMergeConfig struct { // means no such paths. This key only declares the paths; enforcement // lives in the merge sweeps. HumanMergePaths map[string][]string `yaml:"human_merge_paths,omitempty" json:"human_merge_paths,omitempty"` + // HumanMergeTitlePrefixes lists title prefixes (matched after trimming + // the title) that mark a PR as one the owner merges by hand; no lane and + // no merge train merges it (hivecommons/hive#15442). Unset means the + // breaking-change sign, ["⚠️", "⚠"] (U+26A0 with and without VS16); an + // explicit empty list switches the title half of the rule off. + HumanMergeTitlePrefixes []string `yaml:"human_merge_title_prefixes,omitempty" json:"human_merge_title_prefixes,omitempty"` + // HumanMergeLabels lists labels (case-insensitive) with the same effect. + // Unset means ["needs-owner-merge"]; an explicit empty list switches the + // label half of the rule off. + HumanMergeLabels []string `yaml:"human_merge_labels,omitempty" json:"human_merge_labels,omitempty"` // RequireCurrentBase lists owner/repo names whose automerge sweeps only // merge a PR head that already contains the current base branch tip // (hivecommons/hive#13634). A head that is green but was tested against @@ -8509,6 +8520,32 @@ func (a AutoMergeConfig) HumanMergePathsFor(repo string) []string { return nil } +// HumanMergeTitlePrefixesEffective returns auto_merge.human_merge_title_prefixes +// with the default applied when the key is unset (nil). An explicit empty +// list stays empty. +func (a AutoMergeConfig) HumanMergeTitlePrefixesEffective() []string { + if a.HumanMergeTitlePrefixes == nil { + return append([]string(nil), prstage.DefaultHumanMergeTitlePrefixes...) + } + return append(make([]string, 0, len(a.HumanMergeTitlePrefixes)), a.HumanMergeTitlePrefixes...) +} + +// HumanMergeLabelsEffective returns auto_merge.human_merge_labels with the +// default applied when the key is unset (nil). An explicit empty list stays +// empty. +func (a AutoMergeConfig) HumanMergeLabelsEffective() []string { + if a.HumanMergeLabels == nil { + return append([]string(nil), prstage.DefaultHumanMergeLabels...) + } + return append(make([]string, 0, len(a.HumanMergeLabels)), a.HumanMergeLabels...) +} + +// HumanMergeRule is the configured human-merge rule the automerge lanes +// and the dashboard share. +func (a AutoMergeConfig) HumanMergeRule() prstage.HumanMergeRule { + return prstage.HumanMergeRule{TitlePrefixes: a.HumanMergeTitlePrefixesEffective(), Labels: a.HumanMergeLabelsEffective()} +} + // RequireCurrentBaseFor reports whether the automerge lanes must see a head // that contains the current base tip before merging into repo (owner/repo, // matched case-insensitively). Resolution order: an explicit diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 6013cc9a6a..2750c503f4 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -155,6 +155,8 @@ agents.session_recycle.min_idle # TODO #11854 auto_merge.credit_issue_authors # merge-time Co-authored-by credit (#14581); yaml-only auto_merge.allow_unprotected_base[] # TODO #11854 auto_merge.human_merge_paths. # TODO #11854 +auto_merge.human_merge_title_prefixes[] # breaking-titled PRs wait for a human; yaml-only +auto_merge.human_merge_labels[] # needs-owner-merge PRs wait for a human; yaml-only auto_merge.merge_forward_trusted_human[] # TODO #11854 auto_merge.merge_train.enabled # conflict-aware merge train (#15117); yaml-only auto_merge.merge_train.max_rebase_attempts # merge train rebase loop guard (#15117); yaml-only diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 23d32a2d4d..e1f1cdd75d 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -1410,6 +1410,8 @@ func humanizeStageReason(reason string) string { return "tests removed" case stageengineprstage.AutoMergeReasonHumanMergePath: return "human-merge path" + case stageengineprstage.AutoMergeReasonHumanMergeRequired: + return "human merge" } if rest, ok := strings.CutPrefix(lower, "contributor-lane:"); ok { return strings.ReplaceAll(strings.ReplaceAll(rest, "-", " "), "_", " ") @@ -1453,7 +1455,8 @@ func stageTrackerUnauthorized(reason string) (step, tip string) { // on a maintainer's merge click rather than on /lgtm /approve. func stageTrackerManualMergeReason(reason string) bool { switch strings.ToLower(strings.TrimSpace(reason)) { - case stageengineprstage.ContributorLaneReasonWorkflowPath, stageengineprstage.ContributorLaneReasonTestsRemoved, stageengineprstage.AutoMergeReasonHumanMergePath: + case stageengineprstage.ContributorLaneReasonWorkflowPath, stageengineprstage.ContributorLaneReasonTestsRemoved, stageengineprstage.AutoMergeReasonHumanMergePath, + stageengineprstage.AutoMergeReasonHumanMergeRequired: return true } return false @@ -1472,6 +1475,7 @@ var stageTrackerHumanMergeReasonWords = map[string][2]string{ stageengineprstage.HumanMergeReasonUntrustedAuthor: {"untrusted author", "Hive won't merge it alone — the author isn't a trusted author yet"}, stageengineprstage.HumanMergeReasonUnauthorized: {"unauthorized", "GitHub does not let hive merge here; a person merges"}, stageengineprstage.HumanMergeReasonReviewerDeferred: {"reviewer deferred", "A reviewer asked for a person to merge this one"}, + stageengineprstage.HumanMergeReasonBreakingChange: {"human merge", "Breaking change — owner merges; hive never merges a ⚠️-titled or needs-owner-merge PR"}, } // stageTrackerHumanMergeReason derives, from a 090 stage reason, the @@ -1749,6 +1753,15 @@ func stageTrackerCaption(stage stagelabels.Stage, reason, author string, kind st return joinClause("A human decision is owed", clause), "maintainer" case stagelabels.ReadyForHumanMerge: if base, approver := stagelabels.HumanApprovedReason(reason); stageTrackerManualMergeReason(base) { + if strings.EqualFold(strings.TrimSpace(base), stageengineprstage.AutoMergeReasonHumanMergeRequired) { + // The breaking-change rule (hivecommons/hive#15442): no + // approval releases it; the owner's merge click does. + c := "Ready for human merge (" + stageengineprstage.CauseHumanMergeRequired + ")" + if approver != "" { + c += " — approved by @" + approver + } + return c, "maintainer" + } c := "Ready to merge (" + humanizeStageReason(base) + ")" if approver != "" { c += " — approved by @" + approver @@ -2103,8 +2116,10 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.HumanMergeReasonText = "Hive won't merge it alone — " + why } } - // A person already took the trust call for this head (#15136). - if login := stagelabels.AdmissionLogin(it.AdmittedBy); login != "" { + // A person already took the trust call for this head (#15136) — + // unless the breaking-change rule holds, which no approval + // releases (hivecommons/hive#15442). + if login := stagelabels.AdmissionLogin(it.AdmittedBy); login != "" && it.HumanMergeReason != stageengineprstage.HumanMergeReasonBreakingChange { it.HumanMergeReasonText = "@" + login + " approved it; hive merges it on its next pass" } } diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index 24b22bde89..245b730696 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -286,6 +286,11 @@ func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision details = append(details, "Approved by @"+approver+".") } admitter := stagelabels.AdmissionLogin(it.AdmittedBy) + breaking := strings.EqualFold(base, stageengineprstage.AutoMergeReasonHumanMergeRequired) + if breaking { + // No approval lets hive merge a breaking change (hivecommons/hive#15442). + admitter = "" + } if admitter != "" { // A person already took the trust call for this head (#15136): // the lane merges it as-is; nothing is adopted or re-authored. @@ -305,6 +310,12 @@ func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision if admitter != "" && !held { queue.Enabled, queue.ReasonIfDisabled = false, "@"+admitter+" already approved it; hive merges it next pass" } + if breaking { + // The lanes skip a breaking-titled / needs-owner-merge PR however + // it is queued (hivecommons/hive#15442): the merge-now click is the + // one path, so queueing is offered greyed with the reason. + queue.Enabled, queue.ReasonIfDisabled = false, "Hive never merges a breaking change; merge it as maintainer" + } if it.DCOUnsigned > 0 { mergeNow.Consequence += "; " + decisionDCOConsequence(it) queue.Consequence += "; " + decisionDCOConsequence(it) @@ -616,7 +627,7 @@ func decisionLaneRule(base string) bool { stageengineprstage.AutoMergeReasonHumanMergePath, stageengineprstage.AutoMergeReasonHumanMergePathEvidence, stageengineprstage.AutoMergeReasonIntentUnauthorized, stageengineprstage.AutoMergeReasonIntentEvidence, stageengineprstage.AutoMergeReasonMergeRefusedReview, stageengineprstage.AutoMergeReasonMergeRefusedMethod, - stageengineprstage.AutoMergeReasonNoAppBotLogin: + stageengineprstage.AutoMergeReasonNoAppBotLogin, stageengineprstage.AutoMergeReasonHumanMergeRequired: return true } return false @@ -640,6 +651,8 @@ func decisionPlainReason(base string) string { return "the hive could not read its changed files" case stageengineprstage.AutoMergeReasonHumanMergePath, stageengineprstage.AutoMergeReasonHumanMergePathEvidence: return "it touches files a person must merge" + case stageengineprstage.AutoMergeReasonHumanMergeRequired: + return "it is a breaking change (⚠️ title or needs-owner-merge label) — the owner merges it" case stageengineprstage.AutoMergeReasonIntentUnauthorized, stageengineprstage.AutoMergeReasonIntentEvidence: return "the hive could not confirm the author's merge intent" case stageengineprstage.AutoMergeReasonMergeRefusedReview: diff --git a/src/pkg/dashboard/stage_tracker_human_merge_test.go b/src/pkg/dashboard/stage_tracker_human_merge_test.go new file mode 100644 index 0000000000..b6d53f842d --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_human_merge_test.go @@ -0,0 +1,81 @@ +package dashboard + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// A ⚠️-titled PR the lanes parked with the human-merge rule +// (hivecommons/hive#15442) renders at 090 as "Ready for human merge" with +// the "human merge" chip and the owner-merges reason; the lead decision is +// the operator's merge-as-maintainer click and queueing for the hive is +// offered greyed, since no lane merges it however it is queued. +func TestStageTrackerHumanMergeRequiredRow(t *testing.T) { + now := time.Date(2026, 10, 27, 14, 0, 0, 0, time.UTC) + s, store := stageTrackerFixture(t, now) + store.Observe(stagelabels.Key("acme/console", 15442), stagelabels.ReadyForHumanMerge, "human-merge-required") + s.statusMu.Lock() + s.status.Repos[0].OpenPrs = append(s.status.Repos[0].OpenPrs, + FrontendPR{PullRequest: github.PullRequest{Number: 15442, Title: "\u26a0\ufe0f drop the v4 API", Author: "pat", Labels: []string{"stage/090-ready-for-human-merge", "lgtm"}}}, + // Not yet staged: the 000-new narration names the human-merge gate. + FrontendPR{PullRequest: github.PullRequest{Number: 15443, Title: "\u2728 add a thing", Author: "pat", Labels: []string{"needs-owner-merge"}}}) + s.statusMu.Unlock() + resp := s.buildStageTracker(s.status, store, now) + + it := trackerItem(t, resp, "pr", 15442) + if it.Stage != 90 || !it.ManualMerge || it.HumanMergeReason != "breaking-change" { + t.Fatalf("row = stage %d manual %v reason %q", it.Stage, it.ManualMerge, it.HumanMergeReason) + } + if it.Caption != "Ready for human merge (breaking change — owner merges)" || it.Actor != "maintainer" { + t.Fatalf("caption %q actor %q", it.Caption, it.Actor) + } + if !strings.HasPrefix(it.HumanMergeReasonText, "Breaking change — owner merges") { + t.Fatalf("reason text %q", it.HumanMergeReasonText) + } + raw, err := json.Marshal(it) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"manual_merge":true,"human_merge_reason":"breaking-change"`) { + t.Fatalf("payload lacks the chip fields: %s", raw) + } + if it.DecisionNeeded == nil || len(it.DecisionNeeded.Options) < 2 { + t.Fatalf("decision = %+v", it.DecisionNeeded) + } + mergeNow, queue := it.DecisionNeeded.Options[0], it.DecisionNeeded.Options[1] + if mergeNow.Action != decisionActionMergeNow || !mergeNow.Enabled { + t.Fatalf("lead option = %+v, want an enabled merge-now", mergeNow) + } + if queue.Action != decisionActionQueueMerge || queue.Enabled || !strings.Contains(queue.ReasonIfDisabled, "never merges a breaking change") { + t.Fatalf("queue option = %+v, want it greyed with the rule", queue) + } + if !strings.Contains(strings.ToLower(it.DecisionNeeded.Question), "breaking change") { + t.Fatalf("question %q must name the rule", it.DecisionNeeded.Question) + } + + fresh := trackerItem(t, resp, "pr", 15443) + if fresh.New == nil { + t.Fatalf("PR 15443 should be 000-new: %+v", fresh) + } + var gate *StageTrackerGate + for i := range fresh.New.Gates { + if fresh.New.Gates[i].Name == StageTrackerGateHumanMerge { + gate = &fresh.New.Gates[i] + } + } + if gate == nil || gate.Text != "breaking change — owner merges" { + t.Fatalf("new.gates = %+v, want a human-merge gate", fresh.New.Gates) + } + if plain := trackerItem(t, resp, "pr", 103); plain.New != nil { + for _, g := range plain.New.Gates { + if g.Name == StageTrackerGateHumanMerge { + t.Fatalf("PR 103 must not carry the human-merge gate: %+v", plain.New.Gates) + } + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_new.go b/src/pkg/dashboard/stage_tracker_new.go index 695ac757bb..e4a3089f12 100644 --- a/src/pkg/dashboard/stage_tracker_new.go +++ b/src/pkg/dashboard/stage_tracker_new.go @@ -7,6 +7,7 @@ import ( "time" "github.com/hivecommons/hive/pkg/config" + stageengineprstage "github.com/hivecommons/hive/pkg/stageengine/prstage" ) // StageTrackerNewSlug is the pre-stage slug a brand-new open item wears in @@ -31,6 +32,9 @@ const ( StageTrackerGateDone = "done" StageTrackerGateNext = "next" StageTrackerGateLater = "later" + // StageTrackerGateHumanMerge names the gate a breaking-titled or + // needs-owner-merge PR ends on: the owner's merge click. + StageTrackerGateHumanMerge = "human-merge" ) // StageTrackerGate is one gate ahead of a 000-new item. @@ -135,6 +139,13 @@ func stageTrackerNewState(it StageTrackerItem, hasRec bool, filter *config.Issue {Name: "review", State: StageTrackerGateNext, Text: "the stage-label pass places it at 050 review pending"}, {Name: "merge-gate", State: StageTrackerGateLater, Text: "reviews and checks admit it to the merge queue"}, } + // A ⚠️-titled or needs-owner-merge PR ends at 090, not in the + // merge queue: the owner merges it (hivecommons/hive#15442). The + // row knows the default rule only; the lanes apply the configured one. + if ok, _ := (stageengineprstage.HumanMergeRule{}).RequiresHumanMerge(it.Title, it.Labels); ok { + n.Gates[1] = StageTrackerGate{Name: "merge-gate", State: StageTrackerGateLater, Text: "reviews and checks park it at 090 Ready for human merge"} + n.Gates = append(n.Gates, StageTrackerGate{Name: StageTrackerGateHumanMerge, State: StageTrackerGateLater, Text: stageengineprstage.CauseHumanMergeRequired}) + } default: n.NextMover = StageTrackerMoverHive n.NextMoverText = "the stage-label pass (→ 010 actionable), then the scanner" diff --git a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go index b6602a8996..fa8146f4b6 100644 --- a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go +++ b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go @@ -46,6 +46,8 @@ func stageTrackerManualMergeJS(t *testing.T, html string) string { return strings.Join([]string{ jsConstLine(t, html, "STAGE_TRACKER_READY_FOR_HUMAN_MERGE"), jsConstLine(t, html, "STAGE_TRACKER_MANUAL_MERGE_WORD"), + jsConstLine(t, html, "STAGE_TRACKER_BREAKING_CHANGE_CODE"), + jsConstLine(t, html, "STAGE_TRACKER_READY_FOR_HUMAN_MERGE_WORD"), jsConstLine(t, html, "STAGE_TRACKER_HUMAN_MERGE_REASON_WORD"), jsFunc(t, html, "stageTrackerHumanMergeReasonWord"), jsFunc(t, html, "stageTrackerManualMergeWord"), @@ -466,6 +468,11 @@ const whyPlain = stageTrackerRowHtml(P('o/r', 402, 90, { human_merge_reason: 'un assert.ok(whyPlain.includes('Ready for human merge · untrusted author') && whyPlain.includes('title="Ready for human merge · untrusted author — No lane can vouch for the author'), 'plain 090 word carries the reason: ' + whyPlain); const whyNested = stageTrackerRowHtml(I('o/r', 400, 90, { linked_prs: [{ number: 401, stage: 90, title: 'Shard', manual_merge: true, human_approver: 'clubanderson', human_merge_reason: 'workflow-files', human_merge_reason_text: whyTip }] }), stages, ctx); assert.ok(whyNested.includes('Awaiting human merge · workflow files · approved by @clubanderson'), 'nested 090 PR carries the reason: ' + whyNested); +// The breaking-change rule (hivecommons/hive#15442): the stage's own word +// leads and the chip says "human merge"; an approval changes nothing. +assert.strictEqual(stageTrackerManualMergeWord({ manual_merge: true, human_merge_reason: 'breaking-change' }), 'Ready for human merge · human merge'); +const breaking = stageTrackerRowHtml(P('o/r', 403, 90, { manual_merge: true, human_merge_reason: 'breaking-change', human_merge_reason_text: 'Breaking change — owner merges' }), stages, ctx); +assert.ok(breaking.includes('Ready for human merge · human merge') && !breaking.includes('Awaiting human merge'), 'breaking-change 090 word: ' + breaking); // Decide… preface: one line per flagged PR, nothing for clean ones. assert.strictEqual(stageTrackerSentinelPreface([P('o/r', 109, 85, flagged), P('o/r', 104, 85)]), '⚠ o/r#109 — ' + TIP); diff --git a/src/pkg/dashboard/stage_tracker_test.go b/src/pkg/dashboard/stage_tracker_test.go index 598098c32a..9c0f673edb 100644 --- a/src/pkg/dashboard/stage_tracker_test.go +++ b/src/pkg/dashboard/stage_tracker_test.go @@ -153,6 +153,7 @@ func TestHumanizeStageReason(t *testing.T) { "contributor-lane:workflow-path": "workflow path", "contributor-lane:tests-removed": "tests removed", "human-merge-path": "human-merge path", + "human-merge-required": "human merge", "contributor-lane:workflow-path:human-approved@clubanderson": "workflow path — approved by @clubanderson", "reviewer-verdict:requires_human:human-approved@octocat": "review verdict requires human — approved by @octocat", } @@ -190,6 +191,15 @@ func TestStageTrackerManualMergeApproved(t *testing.T) { wantCaption: "Ready to merge (tests removed) — a person merges it", wantManual: true, wantActor: "maintainer", }, + { + name: "breaking change parks at 090 for the owner", stage: stagelabels.ReadyForHumanMerge, reason: "human-merge-required", + wantCaption: "Ready for human merge (breaking change — owner merges)", wantManual: true, wantActor: "maintainer", wantNoCaption: "Ready to merge", + }, + { + name: "breaking change approved still waits for the owner", stage: stagelabels.ReadyForHumanMerge, reason: "human-merge-required:human-approved@clubanderson", + wantCaption: "Ready for human merge (breaking change — owner merges) — approved by @clubanderson", + wantApprover: "clubanderson", wantManual: true, wantActor: "maintainer", + }, { name: "trust-blocked 090 unchanged", stage: stagelabels.ReadyForHumanMerge, reason: "untrusted-author-role", wantCaption: "Ready to merge — a maintainer merges it — author's role is not trusted for unattended merge", wantActor: "maintainer", @@ -263,6 +273,7 @@ func TestStageTrackerHumanMergeReason(t *testing.T) { {"contributor-lane:claim-tier-untrusted", "untrusted-author", "untrusted author", "Hive won't merge it alone"}, {"repo-auto-merge-disabled", "auto-merge-off", "auto-merge off", "Auto-merge is off for this repo"}, {"reviewer-verdict:requires_human:human-approved@octocat", "reviewer-deferred", "reviewer deferred", "A reviewer asked for a person to merge"}, + {"human-merge-required", "breaking-change", "human merge", "Breaking change — owner merges"}, {"something-brand-new", "policy", "policy", "Hive's merge rules leave this one to a person (`something-brand-new`)"}, {"", "", "", ""}, } diff --git a/src/pkg/dashboard/static-src/js/agent-now.js b/src/pkg/dashboard/static-src/js/agent-now.js index 4365c2fb3f..9203feab21 100644 --- a/src/pkg/dashboard/static-src/js/agent-now.js +++ b/src/pkg/dashboard/static-src/js/agent-now.js @@ -407,4 +407,11 @@ // "workflow-files" / "untrusted-author" / "branch-protection", falling // back to "policy"); the tooltip carries the payload's one-sentence // human_merge_reason_text (hivecommons/hive#14658). - const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'unauthorized', 'reviewer-deferred': 'reviewer deferred', 'policy': 'policy' }; + const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'unauthorized', 'reviewer-deferred': 'reviewer deferred', 'breaking-change': 'human merge', 'policy': 'policy' }; + // 090 under the breaking-change rule (human_merge_reason + // "breaking-change": a ⚠️ title or needs-owner-merge label, + // hivecommons/hive#15442): no approval lets the hive merge it, so the + // word is the stage's own, "Ready for human merge", and the chip says + // "human merge". + const STAGE_TRACKER_BREAKING_CHANGE_CODE = 'breaking-change'; + const STAGE_TRACKER_READY_FOR_HUMAN_MERGE_WORD = 'Ready for human merge'; diff --git a/src/pkg/dashboard/static-src/js/tracker-words.js b/src/pkg/dashboard/static-src/js/tracker-words.js index eab7cd8d41..7671ed2886 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words.js +++ b/src/pkg/dashboard/static-src/js/tracker-words.js @@ -6,7 +6,9 @@ function stageTrackerManualMergeWord(item) { const approver = String((item && item.human_approver) || '').trim(); const why = stageTrackerHumanMergeReasonWord(item); - return STAGE_TRACKER_MANUAL_MERGE_WORD + (why ? ' · ' + why : '') + (approver ? ' · approved by @' + approver : ''); + const code = String((item && item.human_merge_reason) || '').trim(); + const lead = code === STAGE_TRACKER_BREAKING_CHANGE_CODE ? STAGE_TRACKER_READY_FOR_HUMAN_MERGE_WORD : STAGE_TRACKER_MANUAL_MERGE_WORD; + return lead + (why ? ' · ' + why : '') + (approver ? ' · approved by @' + approver : ''); } // The plain 090 word (no manual-merge rule): the stage's short word // plus the reason, "Ready for human merge · untrusted author". diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 0aa2513327..c256c885a9 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14180,7 +14180,14 @@

Where to get help

// "workflow-files" / "untrusted-author" / "branch-protection", falling // back to "policy"); the tooltip carries the payload's one-sentence // human_merge_reason_text (hivecommons/hive#14658). - const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'unauthorized', 'reviewer-deferred': 'reviewer deferred', 'policy': 'policy' }; + const STAGE_TRACKER_HUMAN_MERGE_REASON_WORD = { 'workflow-files': 'workflow files', 'tests-removed': 'tests removed', 'manual-merge-policy': 'manual-merge policy', 'branch-protection': 'branch protection', 'merge-method': 'merge method', 'auto-merge-off': 'auto-merge off', 'untrusted-author': 'untrusted author', 'unauthorized': 'unauthorized', 'reviewer-deferred': 'reviewer deferred', 'breaking-change': 'human merge', 'policy': 'policy' }; + // 090 under the breaking-change rule (human_merge_reason + // "breaking-change": a ⚠️ title or needs-owner-merge label, + // hivecommons/hive#15442): no approval lets the hive merge it, so the + // word is the stage's own, "Ready for human merge", and the chip says + // "human merge". + const STAGE_TRACKER_BREAKING_CHANGE_CODE = 'breaking-change'; + const STAGE_TRACKER_READY_FOR_HUMAN_MERGE_WORD = 'Ready for human merge'; function stageTrackerHumanMergeReasonWord(item) { const code = String((item && item.human_merge_reason) || '').trim(); if (!code) return ''; @@ -14189,7 +14196,9 @@

Where to get help

function stageTrackerManualMergeWord(item) { const approver = String((item && item.human_approver) || '').trim(); const why = stageTrackerHumanMergeReasonWord(item); - return STAGE_TRACKER_MANUAL_MERGE_WORD + (why ? ' · ' + why : '') + (approver ? ' · approved by @' + approver : ''); + const code = String((item && item.human_merge_reason) || '').trim(); + const lead = code === STAGE_TRACKER_BREAKING_CHANGE_CODE ? STAGE_TRACKER_READY_FOR_HUMAN_MERGE_WORD : STAGE_TRACKER_MANUAL_MERGE_WORD; + return lead + (why ? ' · ' + why : '') + (approver ? ' · approved by @' + approver : ''); } // The plain 090 word (no manual-merge rule): the stage's short word // plus the reason, "Ready for human merge · untrusted author". diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 598cf05ec8..d0f6f78006 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -527,6 +527,9 @@ func (c *Engine) prefilterContributorLanePR(pr *gh.PullRequest, policy Contribut // marker or registry tier admits a FIRST_TIME_CONTRIBUTOR, and only // admitContributor can tell. See trySweepContributorLanePR. labels := labelNames(pr.Labels) + if reason := c.humanMergeRequiredReason(pr.GetTitle(), labels); reason != "" { + return reason + } // trusted=false so the sentinel label blocks outright: a contributor PR // gets the label, not the trusted-author courtesy comment. if blocked := c.labelBlockReason(labels, false); blocked != "" { diff --git a/src/pkg/github/automerge/automerge_human_merge.go b/src/pkg/github/automerge/automerge_human_merge.go new file mode 100644 index 0000000000..8a8bc897dd --- /dev/null +++ b/src/pkg/github/automerge/automerge_human_merge.go @@ -0,0 +1,69 @@ +package automerge + +import ( + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/stageengine/prstage" +) + +// autoMergeReasonHumanMergeRequired is the one skip reason every lane and +// the merge train report for a PR a person must merge: a breaking-change +// title (⚠️ or an auto_merge.human_merge_title_prefixes prefix) or an +// auto_merge.human_merge_labels label (hivecommons/hive#15442). The +// classifier parks such a PR at 090 Ready for human merge with the +// manual-merge rule; the train never admits or fronts it. +const autoMergeReasonHumanMergeRequired = prstage.AutoMergeReasonHumanMergeRequired + +// SetHumanMergeRule installs (or, with nil, resets to the defaults) the +// live human-merge rule. fn is read on every evaluation so a config reload +// applies without a restart. +func (c *Engine) SetHumanMergeRule(fn func() prstage.HumanMergeRule) { + if c == nil { + return + } + c.humanMergeRuleMu.Lock() + defer c.humanMergeRuleMu.Unlock() + c.humanMergeRule = fn +} + +func (c *Engine) currentHumanMergeRule() prstage.HumanMergeRule { + if c == nil { + return prstage.HumanMergeRule{} + } + c.humanMergeRuleMu.RLock() + fn := c.humanMergeRule + c.humanMergeRuleMu.RUnlock() + if fn == nil { + return prstage.HumanMergeRule{} + } + return fn() +} + +// RequiresHumanMerge is the single predicate behind the rule "breaking or +// owner-flagged PRs never auto-merge": true when the PR's trimmed title +// starts with a configured prefix (default ⚠️ / ⚠) or the PR wears a +// configured label (default needs-owner-merge, case-insensitive). A nil +// engine applies the defaults. +func (c *Engine) RequiresHumanMerge(pr *gh.PullRequest) bool { + if pr == nil { + return false + } + ok, _ := c.currentHumanMergeRule().RequiresHumanMerge(pr.GetTitle(), labelNames(pr.Labels)) + return ok +} + +// RequiresHumanMerge applies the default rule to a PR; the engine method +// applies the configured one. +func RequiresHumanMerge(pr *gh.PullRequest) bool { + return (*Engine)(nil).RequiresHumanMerge(pr) +} + +// humanMergeRequiredReason is the lane prefilters' one shared check: the +// skip reason for a PR RequiresHumanMerge, "" otherwise. The queued issue +// form of a PR (the merger-queue lane lists issues) goes through the same +// rule. +func (c *Engine) humanMergeRequiredReason(title string, labels []string) string { + if ok, _ := c.currentHumanMergeRule().RequiresHumanMerge(title, labels); ok { + return autoMergeReasonHumanMergeRequired + } + return "" +} diff --git a/src/pkg/github/automerge/automerge_human_merge_test.go b/src/pkg/github/automerge/automerge_human_merge_test.go new file mode 100644 index 0000000000..f48756c0a8 --- /dev/null +++ b/src/pkg/github/automerge/automerge_human_merge_test.go @@ -0,0 +1,175 @@ +package automerge + +import ( + "context" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine/prstage" +) + +func humanMergePR(title string, labels ...string) *gh.PullRequest { + pr := &gh.PullRequest{ + Title: gh.Ptr(title), + State: gh.Ptr("open"), + User: &gh.User{Login: gh.Ptr("alice")}, + Head: &gh.PullRequestBranch{SHA: gh.Ptr("sha")}, + } + for _, l := range labels { + pr.Labels = append(pr.Labels, &gh.Label{Name: gh.Ptr(l)}) + } + return pr +} + +func TestRequiresHumanMergeDefaults(t *testing.T) { + for _, tc := range []struct { + name string + pr *gh.PullRequest + want bool + }{ + {name: "warning sign with VS16", pr: humanMergePR("\u26a0\ufe0f drop the v4 API"), want: true}, + {name: "bare warning sign", pr: humanMergePR("\u26a0 drop the v4 API"), want: true}, + {name: "leading whitespace", pr: humanMergePR(" \t\u26a0\ufe0f drop the v4 API"), want: true}, + {name: "sign inside the title does not count", pr: humanMergePR("fix: handle \u26a0\ufe0f in titles"), want: false}, + {name: "needs-owner-merge label", pr: humanMergePR("\u2728 add a thing", "needs-owner-merge"), want: true}, + {name: "label match is case-insensitive and trimmed", pr: humanMergePR("\u2728 add a thing", " Needs-Owner-Merge "), want: true}, + {name: "other labels", pr: humanMergePR("\u2728 add a thing", "hold", "needs-rebase"), want: false}, + {name: "plain feature", pr: humanMergePR("\u2728 add a thing"), want: false}, + {name: "nil PR", pr: nil, want: false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := RequiresHumanMerge(tc.pr); got != tc.want { + t.Fatalf("RequiresHumanMerge = %v, want %v", got, tc.want) + } + engine := New(hgithub.NewClient("token", "acme", []string{"widget"}, nil, ""), Options{}) + if got := engine.RequiresHumanMerge(tc.pr); got != tc.want { + t.Fatalf("engine.RequiresHumanMerge (default rule) = %v, want %v", got, tc.want) + } + }) + } +} + +func TestRequiresHumanMergeConfiguredRule(t *testing.T) { + rule := prstage.HumanMergeRule{TitlePrefixes: []string{"BREAKING:"}, Labels: []string{"owner-only"}} + engine := New(hgithub.NewClient("token", "acme", []string{"widget"}, nil, ""), Options{HumanMergeRule: func() prstage.HumanMergeRule { return rule }}) + if !engine.RequiresHumanMerge(humanMergePR("BREAKING: new wire format")) { + t.Fatal("configured prefix must match") + } + if !engine.RequiresHumanMerge(humanMergePR("feat", "Owner-Only")) { + t.Fatal("configured label must match case-insensitively") + } + // The configured list replaces the defaults; an empty list switches + // that half off. + if engine.RequiresHumanMerge(humanMergePR("\u26a0\ufe0f default sign", "needs-owner-merge")) { + t.Fatal("defaults must not apply once the rule is configured") + } + off := prstage.HumanMergeRule{TitlePrefixes: []string{}, Labels: []string{}} + if ok, _ := off.RequiresHumanMerge("\u26a0\ufe0f x", []string{"needs-owner-merge"}); ok { + t.Fatal("explicitly empty lists switch the rule off") + } + if ok, why := (prstage.HumanMergeRule{}).RequiresHumanMerge("x", []string{"needs-owner-merge"}); !ok || why != "label:needs-owner-merge" { + t.Fatalf("zero rule = %v %q, want the defaults", ok, why) + } +} + +// Every lane prefilter reports the one shared reason for a PR the owner +// merges, so neither a lane nor the merge train ever admits it. +func TestHumanMergeRequiredSkipsEveryLanePrefilter(t *testing.T) { + client := hgithub.NewClient("token", "acme", []string{"widget"}, nil, "") + client.SetAppBotLogin(testHiveAppBotLogin) + engine := New(client, Options{ + TrustedAuthorizer: func(login, requireRole string) TrustedAuthorDecision { + return TrustedAuthorDecision{Allowed: true, Role: requireRole} + }, + }) + breaking := humanMergePR("\u26a0\ufe0f remove the v4 API") + flagged := humanMergePR("\u2728 add a thing", "needs-owner-merge") + for name, pr := range map[string]*gh.PullRequest{"breaking title": breaking, "owner label": flagged} { + if got := engine.prefilterTrustedAuthorPR(pr, TrustedAuthorPolicy{RequireRole: "merger"}); got != autoMergeReasonHumanMergeRequired { + t.Fatalf("%s: trusted-author prefilter = %q, want %q", name, got, autoMergeReasonHumanMergeRequired) + } + if got := engine.prefilterContributorLanePR(pr, ContributorLanePolicy{}); got != autoMergeReasonHumanMergeRequired { + t.Fatalf("%s: contributor-lane prefilter = %q, want %q", name, got, autoMergeReasonHumanMergeRequired) + } + appPR := *pr + appPR.User = &gh.User{Login: gh.Ptr(testHiveAppBotLogin)} + if got := engine.prefilterSelfAuthoredPR(&appPR); got != autoMergeReasonHumanMergeRequired { + t.Fatalf("%s: self-authored prefilter = %q, want %q", name, got, autoMergeReasonHumanMergeRequired) + } + issue := &gh.Issue{Title: pr.Title, PullRequestLinks: &gh.PullRequestLinks{URL: gh.Ptr("u")}, Labels: append([]*gh.Label{{Name: gh.Ptr("hive/automerge")}}, pr.Labels...)} + if got := engine.prefilterQueuedIssue(issue, "hive/automerge"); got != autoMergeReasonHumanMergeRequired { + t.Fatalf("%s: queued-issue prefilter = %q, want %q", name, got, autoMergeReasonHumanMergeRequired) + } + if mergeTrainCandidate(engine.prefilterTrustedAuthorPR(pr, TrustedAuthorPolicy{RequireRole: "merger"})) { + t.Fatalf("%s: the merge train must not admit a human-merge PR", name) + } + } + if got := engine.prefilterTrustedAuthorPR(humanMergePR("\u2728 add a thing"), TrustedAuthorPolicy{RequireRole: "merger"}); got != "" { + t.Fatalf("a plain PR must stay eligible, got %q", got) + } +} + +// A green, approved ⚠️ PR by a trusted author is skipped by the trusted-author +// sweep with the human-merge reason and is never merged. +func TestSweepTrustedAuthorSkipsBreakingTitle(t *testing.T) { + fx := trustedSweepFixture{title: "\u26a0\ufe0f drop the v4 API"} + api := newTrustedSweepAPI(t, &fx) + defer api.Close() + engine := newTrustedSweepEngine(api.URL, TrustedAuthorPolicy{Enabled: true}, Options{}) + var audits []AutoMergeSweepEvent + result, err := engine.SweepTrustedAuthorAutoMerges(context.Background(), AutoMergeSweepOptions{ + Audit: func(event AutoMergeSweepEvent) { audits = append(audits, event) }, + }) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if result.Seen != 1 || result.Skipped != 1 || len(result.Merged) != 0 || len(audits) != 0 || fx.merges != 0 { + t.Fatalf("result = %+v audits=%d merges=%d, want the PR seen, skipped and unmerged", result, len(audits), fx.merges) + } + if got := engine.prefilterTrustedAuthorPR(humanMergePR(fx.title), TrustedAuthorPolicy{Enabled: true}); got != autoMergeReasonHumanMergeRequired { + t.Fatalf("skip reason = %q, want %q", got, autoMergeReasonHumanMergeRequired) + } + // The same PR with a plain title merges: the title is the only difference. + fx2 := trustedSweepFixture{title: "\u2728 drop nothing"} + api2 := newTrustedSweepAPI(t, &fx2) + defer api2.Close() + engine2 := newTrustedSweepEngine(api2.URL, TrustedAuthorPolicy{Enabled: true}, Options{}) + result2, err := engine2.SweepTrustedAuthorAutoMerges(context.Background(), AutoMergeSweepOptions{}) + if err != nil || len(result2.Merged) != 1 { + t.Fatalf("plain title: result=%+v err=%v, want one merge", result2, err) + } +} + +// The merge train never groups, admits or fronts a human-merge PR: it is +// left out of the plan even when it overlaps every other member. +func TestPlanMergeTrainsExcludesHumanMergePR(t *testing.T) { + t0 := time.Date(2026, 10, 20, 9, 0, 0, 0, time.UTC) + api := &mergeTrainAPI{ + files: map[int][]string{20: {"a.go", "b.go"}, 21: {"a.go"}, 22: {"b.go"}}, + state: map[int]string{20: "clean", 21: "clean", 22: "behind"}, + } + srv := newMergeTrainServer(t, api) + defer srv.Close() + c, _ := newMergeTrainEngine(t, srv.URL, DefaultMergeTrainPolicy, nil) + breaking := mtPR(20, t0, "") + breaking.Title = gh.Ptr("\u26a0\ufe0f breaking: rename everything") + breaking.User = &gh.User{Login: gh.Ptr("alice")} + prs := []*gh.PullRequest{breaking, mtPR(21, t0.Add(time.Minute), ""), mtPR(22, t0.Add(2*time.Minute), "")} + prefilter := func(pr *gh.PullRequest) string { + if c.RequiresHumanMerge(pr) { + return autoMergeReasonHumanMergeRequired + } + return "" + } + plan := c.planMergeTrains(context.Background(), "trusted", "acme/widget", "acme", "widget", prs, prefilter) + if plan.isFront(20) || plan.isSibling(20) { + t.Fatalf("the ⚠️ PR must never be in the train: front=%v sibling=%v", plan.isFront(20), plan.isSibling(20)) + } + // #21 and #22 share no file, so without #20 there is no train at all; + // the breaking PR's files bridged them and it must not count. + if plan.isFront(21) || plan.isSibling(21) || plan.isFront(22) || plan.isSibling(22) { + t.Fatalf("no train expected without the excluded PR; groups %+v", plan.groups) + } +} diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index 7ada2a9c71..bb726a2743 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -21,6 +21,7 @@ import ( "github.com/hivecommons/hive/pkg/stageengine" "github.com/hivecommons/hive/pkg/stageengine/prstage" "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/writeback" ) // humanChecksTTL bounds how often one head's checks are re-read. A new head @@ -241,7 +242,7 @@ func manualMergeRuleReasonFor(reason string, workflowManual bool) bool { switch reason { case contributorLaneReasonWorkflowPath: return workflowManual - case contributorLaneReasonTestsRemoved, autoMergeReasonHumanMergePath: + case contributorLaneReasonTestsRemoved, autoMergeReasonHumanMergePath, autoMergeReasonHumanMergeRequired: return true } return false @@ -391,6 +392,8 @@ func decisionCauseFor(reason string, workflowManual bool) string { return prstage.CauseReporterTrustHold case reason == autoMergeReasonHumanMergePath, reason == autoMergeReasonHumanMergePathEvidence: return prstage.CauseHumanMergePath + case reason == autoMergeReasonHumanMergeRequired: + return prstage.CauseHumanMergeRequired case reason == autoMergeReasonIntentUnauthorized, reason == autoMergeReasonIntentEvidence: return prstage.CauseIntentUnauthorized case strings.HasPrefix(reason, workflowApprovalUntrustedPrefix): @@ -448,6 +451,17 @@ func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, k default: return 0, nil } + if obs.Reason == autoMergeReasonHumanMergeRequired { + // The "waiting for a person" note on a breaking-titled or + // owner-flagged PR is an unsolicited write (hivecommons/hive#15442): + // it goes through the write-back gate like every other hive + // comment, and a refusal leaves the record unmarked so the next + // pass asks again. + if d := c.writebackAllowed(obs.Display, writebackItemForObservation(obs), writeback.KindNeedsDecisionComment, body); !d.Allowed { + c.info("stage labels: entry comment withheld by the write-back gate", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "reason", d.Reason) + return 0, nil + } + } if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { c.warn("stage labels: entry comment failed", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "error", err) return 0, err diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index 390703dc0c..76ed1ffe35 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -377,6 +377,12 @@ func TestClassifyStageMapping(t *testing.T) { {name: "no claim but needs-rebase", obs: stageObservation{AuthorKind: authorkind.Clanker, Lane: stageLaneContributor, Reason: contributorLaneReasonNoClaim, Labels: []string{"needs-rebase"}}, want: stagelabels.ReturnedToContributor, rank: stageRankOwned}, {name: "untrusted role weak", obs: stageObservation{Lane: stageLaneTrusted, Reason: "untrusted-author-role"}, want: stagelabels.ReadyForHumanMerge, rank: stageRankRole}, {name: "human merge path", obs: stageObservation{Lane: stageLaneSelf, Reason: autoMergeReasonHumanMergePath}, want: stagelabels.NeedsDecision, rank: stageRankOwned}, + // A breaking-titled / needs-owner-merge PR owes no decision, only + // the owner's merge click: an OWNED 090 whatever the lane + // (hivecommons/hive#15442), fixing while it wears needs-rebase. + {name: "human merge required is owned 090", obs: stageObservation{Lane: stageLaneTrusted, Reason: autoMergeReasonHumanMergeRequired, Detail: approve}, want: stagelabels.ReadyForHumanMerge, rank: stageRankOwned}, + {name: "human merge required self lane", obs: stageObservation{Lane: stageLaneSelf, Reason: autoMergeReasonHumanMergeRequired}, want: stagelabels.ReadyForHumanMerge, rank: stageRankOwned}, + {name: "human merge required needs-rebase", obs: stageObservation{Lane: stageLaneSelf, Reason: autoMergeReasonHumanMergeRequired, Labels: []string{"needs-rebase"}}, want: stagelabels.Fixing, rank: stageRankOwned}, // A merge GitHub refuses for a missing approving review or a // disabled merge method is not imminent: a person acts (085). {name: "merge refused review required", obs: stageObservation{Lane: stageLaneSelf, Reason: autoMergeReasonMergeRefusedReview, Detail: approve}, want: stagelabels.NeedsDecision, rank: stageRankOwned}, diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 3c78307572..e141933451 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -91,6 +91,10 @@ type Options struct { // for an owner/repo. Every sweep lane refuses a PR touching one (#11038). // nil means no repo has any. HumanMergePaths func(repo string) []string + // 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. + HumanMergeRule func() prstage.HumanMergeRule // RequireCurrentBase returns the live current-base gate switch for an // owner/repo (hivecommons/hive#13634; since #15335 resolved from the // hive-wide default plus per-repo overrides via @@ -250,6 +254,9 @@ type Engine struct { humanMergePathsMu sync.RWMutex humanMergePaths func(repo string) []string + humanMergeRuleMu sync.RWMutex + humanMergeRule func() prstage.HumanMergeRule + requireCurrentBase func(repo string) bool requireCurrentBaseStrict func(repo string) bool mergeForwardTrustedHuman func(repo string) bool @@ -358,6 +365,7 @@ func New(transport Transport, opts Options) *Engine { reviewGate: opts.ReviewGate, humanChangeRequests: opts.HumanChangeRequests, humanMergePaths: opts.HumanMergePaths, + humanMergeRule: opts.HumanMergeRule, requireCurrentBase: opts.RequireCurrentBase, requireCurrentBaseStrict: opts.RequireCurrentBaseStrict, mergeForwardTrustedHuman: opts.MergeForwardTrustedHuman, @@ -1776,6 +1784,11 @@ func (c *Engine) trySweepSelfAuthoredPR(ctx context.Context, displayRepo, owner, return AutoMergeSweepEvent{}, "not-app-authored", nil } selfLabels := labelNames(pr.Labels) + // The refetched PR is the one that merges: a title or label edited + // since listing re-applies the human-merge rule (hivecommons/hive#15442). + if reason := c.humanMergeRequiredReason(pr.GetTitle(), selfLabels); reason != "" { + return AutoMergeSweepEvent{}, reason, nil + } blocked := c.labelBlockReason(selfLabels, true) // A conflicting head — GitHub's mergeable_state or the needs-rebase // label a lane already put on it — is asked the superseded question @@ -2143,6 +2156,9 @@ func (c *Engine) prefilterSelfAuthoredPR(pr *gh.PullRequest) string { return "not-app-authored" } labels := labelNames(pr.Labels) + if reason := c.humanMergeRequiredReason(pr.GetTitle(), labels); reason != "" { + return reason + } if blocked := c.labelBlockReason(labels, true); blocked != "" { return blocked } @@ -2163,6 +2179,9 @@ func (c *Engine) prefilterQueuedIssue(issue *gh.Issue, label string) string { if !hasLabel(labels, label) { return "label-removed" } + if reason := c.humanMergeRequiredReason(issue.GetTitle(), labels); reason != "" { + return reason + } if blocked := c.labelBlockReason(labels, false); blocked != "" { return blocked } @@ -2183,6 +2202,9 @@ func (c *Engine) prefilterTrustedAuthorPR(pr *gh.PullRequest, policy TrustedAuth return "draft" } labels := labelNames(pr.Labels) + if reason := c.humanMergeRequiredReason(pr.GetTitle(), labels); reason != "" { + return reason + } if blocked := c.labelBlockReason(labels, true); blocked != "" && !staleNeedsRebaseLabel(blocked, pr) { return blocked } @@ -2590,6 +2612,9 @@ func (c *Engine) trySweepQueuedPR(ctx context.Context, displayRepo, owner, repo if !hasLabel(labels, label) { return AutoMergeSweepEvent{}, "label-removed", nil } + if reason := c.humanMergeRequiredReason(pr.GetTitle(), labels); reason != "" { + return AutoMergeSweepEvent{}, reason, nil + } // Hold labels outrank the merger queue (#5589): a hold applied AFTER a // merger queued the PR — including the hold guard re-applying one because // the branch moved while hold-gated — must stop the sweep, not race it. diff --git a/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go b/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go index e9f15d7934..f8e41c51c5 100644 --- a/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go +++ b/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go @@ -35,6 +35,7 @@ type trustedSweepFixture struct { updates int updateStatus int labels []string + title string } func newTrustedSweepAPI(t *testing.T, fx *trustedSweepFixture) *httptest.Server { @@ -56,6 +57,7 @@ func newTrustedSweepAPI(t *testing.T, fx *trustedSweepFixture) *httptest.Server } return map[string]any{ "number": 7, + "title": fx.title, "state": "open", "mergeable_state": state, "mergeable": state == "clean", diff --git a/src/pkg/stageengine/derive_pr_classify.go b/src/pkg/stageengine/derive_pr_classify.go index 2a738c14bf..a23bde09fc 100644 --- a/src/pkg/stageengine/derive_pr_classify.go +++ b/src/pkg/stageengine/derive_pr_classify.go @@ -30,6 +30,7 @@ const ( autoMergeReasonHumanChangesRequested = prstage.AutoMergeReasonHumanChangesRequested autoMergeReasonHumanMergePath = prstage.AutoMergeReasonHumanMergePath autoMergeReasonHumanMergePathEvidence = prstage.AutoMergeReasonHumanMergePathEvidence + autoMergeReasonHumanMergeRequired = prstage.AutoMergeReasonHumanMergeRequired autoMergeReasonIntentEvidence = prstage.AutoMergeReasonIntentEvidence autoMergeReasonIntentUnauthorized = prstage.AutoMergeReasonIntentUnauthorized autoMergeReasonMergeQueueRequired = prstage.AutoMergeReasonMergeQueueRequired @@ -395,6 +396,20 @@ func ClassifyStage(o stageObservation) stageVerdict { // can take it (hivecommons/hive#14589). The reason keeps the step. return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: stageRankOwned, Human: true} } + if reason == autoMergeReasonHumanMergeRequired { + // A breaking-change title or a needs-owner-merge label + // (hivecommons/hive#15442): no decision is owed, only the owner's + // merge click, so the PR parks at 090 with the manual-merge rule + // once the head is green. Owned, so the trusted tier cannot drop it + // (ResolveStage keeps only owned 090 opinions for trusted authors). + if HasLabelFold(o.Labels, "needs-rebase") { + return stageVerdict{Stage: fixing, Rank: stageRankOwned} + } + if v, ok := HumanChangeRequestStage(o); ok { + return v + } + return WithHumanApprovalReason(stageVerdict{Stage: stagelabels.ReadyForHumanMerge, Rank: stageRankOwned, Human: true}, humanApprovalReason) + } if strings.HasPrefix(reason, "excluded-label:") || stageNeedsHumanReasons[reason] { if HasLabelFold(o.Labels, "needs-rebase") { return stageVerdict{Stage: fixing, Rank: stageRankOwned} diff --git a/src/pkg/stageengine/prstage/causes.go b/src/pkg/stageengine/prstage/causes.go index 4356bf6706..61a167e44e 100644 --- a/src/pkg/stageengine/prstage/causes.go +++ b/src/pkg/stageengine/prstage/causes.go @@ -10,9 +10,12 @@ const WorkflowApprovalCommand = "/ok-to-test" // human-only lane reason. The automerge sweep renders them and the stage // goldens expect them, so the wording lives here once (hivecommons/hive#15384). 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)" + 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)" + // CauseHumanMergeRequired: the breaking-change title or the + // needs-owner-merge label; the words the 090 chip and gate reuse. + CauseHumanMergeRequired = "breaking change — owner merges" CauseIntentUnauthorized = "the merge intent could not be authorized" CauseApprovalDeskWithheld = "the approval desk withheld this merge" // CauseWorkflowPathManual is the workflow-path fence read as a rule a diff --git a/src/pkg/stageengine/prstage/human_merge.go b/src/pkg/stageengine/prstage/human_merge.go new file mode 100644 index 0000000000..25d4df0da9 --- /dev/null +++ b/src/pkg/stageengine/prstage/human_merge.go @@ -0,0 +1,54 @@ +package prstage + +import "strings" + +// Defaults for the human-merge rule (hivecommons/hive#15442): a PR whose +// title starts with the breaking-change sign — ⚠️ (U+26A0 U+FE0F) or the +// bare ⚠ (U+26A0) — or that wears needs-owner-merge is never merged by a +// lane or a merge train; the owner merges it. +var ( + DefaultHumanMergeTitlePrefixes = []string{"\u26a0\ufe0f", "\u26a0"} + DefaultHumanMergeLabels = []string{"needs-owner-merge"} +) + +// HumanMergeRule is the configured shape of the rule: the title prefixes +// and labels that park a PR for a human's merge. A zero value applies the +// defaults; an explicitly empty list switches that half of the rule off. +type HumanMergeRule struct { + TitlePrefixes []string + Labels []string +} + +// RequiresHumanMerge reports whether a PR with this title and these labels +// must wait for a person, and the sub-reason: "title" when a configured +// prefix opens the trimmed title, "label:" when a configured label is +// present (case-insensitive). Nil slices mean the defaults. +func (r HumanMergeRule) RequiresHumanMerge(title string, labels []string) (bool, string) { + prefixes := r.TitlePrefixes + if prefixes == nil { + prefixes = DefaultHumanMergeTitlePrefixes + } + trimmed := strings.TrimSpace(title) + for _, p := range prefixes { + p = strings.TrimSpace(p) + if p != "" && strings.HasPrefix(trimmed, p) { + return true, "title" + } + } + want := r.Labels + if want == nil { + want = DefaultHumanMergeLabels + } + for _, w := range want { + w = strings.TrimSpace(w) + if w == "" { + continue + } + for _, l := range labels { + if strings.EqualFold(strings.TrimSpace(l), w) { + return true, "label:" + strings.ToLower(w) + } + } + } + return false, "" +} diff --git a/src/pkg/stageengine/prstage/human_merge_test.go b/src/pkg/stageengine/prstage/human_merge_test.go new file mode 100644 index 0000000000..6df69376a1 --- /dev/null +++ b/src/pkg/stageengine/prstage/human_merge_test.go @@ -0,0 +1,41 @@ +package prstage + +import "testing" + +func TestHumanMergeRuleRequiresHumanMerge(t *testing.T) { + cases := []struct { + name string + rule HumanMergeRule + title string + labels []string + want bool + reason string + }{ + {name: "warning sign with VS16", title: "\u26a0\ufe0f drop v4", want: true, reason: "title"}, + {name: "bare warning sign", title: "\u26a0 drop v4", want: true, reason: "title"}, + {name: "leading whitespace trimmed", title: " \t\u26a0\ufe0f drop v4", want: true, reason: "title"}, + {name: "sign inside the title is not a prefix", title: "fix: handle \u26a0\ufe0f icons", want: false}, + {name: "default label case-insensitive", title: "feat", labels: []string{"lgtm", " Needs-Owner-Merge "}, want: true, reason: "label:needs-owner-merge"}, + {name: "plain PR", title: "\u2728 add thing", labels: []string{"lgtm"}, want: false}, + {name: "configured prefix", rule: HumanMergeRule{TitlePrefixes: []string{"BREAKING:"}}, title: "BREAKING: rename", want: true, reason: "title"}, + {name: "configured prefix replaces default", rule: HumanMergeRule{TitlePrefixes: []string{"BREAKING:"}}, title: "\u26a0\ufe0f rename", want: false}, + {name: "empty prefix list turns the title half off", rule: HumanMergeRule{TitlePrefixes: []string{}}, title: "\u26a0\ufe0f rename", want: false}, + {name: "configured label", rule: HumanMergeRule{Labels: []string{"ship-by-owner"}}, title: "x", labels: []string{"SHIP-BY-OWNER"}, want: true, reason: "label:ship-by-owner"}, + {name: "empty label list turns the label half off", rule: HumanMergeRule{Labels: []string{}}, title: "x", labels: []string{"needs-owner-merge"}, want: false}, + {name: "blank entries are ignored", rule: HumanMergeRule{TitlePrefixes: []string{" ", ""}, Labels: []string{""}}, title: "anything", labels: []string{""}, want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, reason := tc.rule.RequiresHumanMerge(tc.title, tc.labels) + if got != tc.want || reason != tc.reason { + t.Fatalf("RequiresHumanMerge(%q, %v) = %v %q, want %v %q", tc.title, tc.labels, got, reason, tc.want, tc.reason) + } + }) + } +} + +func TestHumanMergeReasonMapsHumanMergeRequired(t *testing.T) { + if got := HumanMergeReason(AutoMergeReasonHumanMergeRequired); got != HumanMergeReasonBreakingChange { + t.Fatalf("HumanMergeReason(%q) = %q", AutoMergeReasonHumanMergeRequired, got) + } +} diff --git a/src/pkg/stageengine/prstage/reasons.go b/src/pkg/stageengine/prstage/reasons.go index 00a7767191..655b8674bb 100644 --- a/src/pkg/stageengine/prstage/reasons.go +++ b/src/pkg/stageengine/prstage/reasons.go @@ -13,14 +13,19 @@ const ReasonSupersessionPending = "supersession-decision-pending" // Lane reasons are shared by the producers and the stage classifier. const ( - ReviewGateOutcomeAwaiting = "awaiting-review-approval" - ReviewGateOutcomeChangesRequested = "changes-requested" - ReviewGateOutcomeNoBundle = "no-review-bundle" - AutoMergeReasonBehindBudgetExhausted = "behind-update-budget-exhausted" - AutoMergeReasonForkNotEditable = "fork-not-editable" - AutoMergeReasonHumanChangesRequested = stagelabels.LaneReasonHumanChangesRequested - AutoMergeReasonHumanMergePath = "human-merge-path" - AutoMergeReasonHumanMergePathEvidence = "human-merge-path-evidence" + ReviewGateOutcomeAwaiting = "awaiting-review-approval" + ReviewGateOutcomeChangesRequested = "changes-requested" + ReviewGateOutcomeNoBundle = "no-review-bundle" + AutoMergeReasonBehindBudgetExhausted = "behind-update-budget-exhausted" + AutoMergeReasonForkNotEditable = "fork-not-editable" + AutoMergeReasonHumanChangesRequested = stagelabels.LaneReasonHumanChangesRequested + AutoMergeReasonHumanMergePath = "human-merge-path" + AutoMergeReasonHumanMergePathEvidence = "human-merge-path-evidence" + // AutoMergeReasonHumanMergeRequired: the PR's title says breaking + // change (⚠️, or an auto_merge.human_merge_title_prefixes prefix) or it + // wears an auto_merge.human_merge_labels label; no lane and no merge + // train ever merges it — the owner does (hivecommons/hive#15442). + AutoMergeReasonHumanMergeRequired = "human-merge-required" AutoMergeReasonIntentEvidence = "intent-evidence" AutoMergeReasonIntentUnauthorized = "intent-unauthorized" AutoMergeReasonMergeQueueRequired = "merge-queue-required" @@ -109,6 +114,9 @@ const ( // requires_human and a trusted merger approved the head; the hive // leaves the merge itself to a person. HumanMergeReasonReviewerDeferred = "reviewer-deferred" + // HumanMergeReasonBreakingChange: the PR's title or label marks it a + // breaking change the owner merges by hand (AutoMergeReasonHumanMergeRequired). + HumanMergeReasonBreakingChange = "breaking-change" // HumanMergeReasonPolicy: a lane rule no more specific code names. HumanMergeReasonPolicy = "policy" ) @@ -138,6 +146,8 @@ func HumanMergeReason(reason string) string { return HumanMergeReasonTestsRemoved case base == AutoMergeReasonHumanMergePath, base == AutoMergeReasonHumanMergePathEvidence: return HumanMergeReasonManualMergePolicy + case base == AutoMergeReasonHumanMergeRequired: + return HumanMergeReasonBreakingChange case base == AutoMergeReasonMergeRefusedReview, strings.HasPrefix(base, AutoMergeReasonReviewGatePrefix): return HumanMergeReasonBranchProtection case base == AutoMergeReasonMergeRefusedMethod: diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 2ed660a8a7..93b37a9350 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -406,6 +406,18 @@ func RouteHuman(e Evidence) Route { } return route } + if e.Cause == CauseTrust && e.ManualMergeRule && strings.TrimSpace(e.CauseReason) != "" { + // A manual-merge rule that owes no decision — the breaking-change + // title or the needs-owner-merge label (hivecommons/hive#15442): + // the head is green and reviewed, and the hive still never merges + // it; the owner's merge click is the one step left. + route := Route{Stage: ReadyForHumanMerge, ManualMerge: true, Summary: summary, Head: e.Head, SelfAuthored: e.SelfAuthored, Verdict: e.Verdict, HumanApprover: approver, + Reasons: []string{e.CauseReason}, LaneReason: strings.TrimSpace(e.LaneReason)} + if approver != "" && route.LaneReason != "" { + route.LaneReason += HumanApprovedReasonSuffix + approver + } + return route + } return Route{Stage: ReadyForHumanMerge, Summary: summary, HumanApprover: approver} }