From d4253823d96a04da0a9d22d8f0b9d3b26a372f71 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 26 Oct 2026 23:50:06 -0400 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20feat(automerge):=20contributor?= =?UTF-8?q?=20auto-promotion=20counts=20clean=20merges=20across=20the=20hi?= =?UTF-8?q?ve's=20repos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The contributor-lane clean-merge ratchet counted an author's merged PRs per repository, so a contributor with nine clean merges in hivecommons/hive was still contributor-lane:claim-tier-untrusted on their first PR to hivecommons/docs (docs#481 sat 17h green and approved). Trust is a property of the person, not the repo, and the satellite repos of a multi-repo hive never reach a per-repo threshold. - auto_merge.contributor_lane.auto_promotion_scope: hive|repo (default hive), validated, wired through the policy func and the Settings auto-merge API/UI. - With scope hive the PR's own repo is walked first; only when short does one search/issues query (is:pr is:merged author:X repo:... chunked to 256 chars) find the other hive repos holding the author's merges, and only those are walked for revert/sentinel evidence. A search failure degrades to the own-repo count with a warning. - Audit marker gains scope= and repos=; the admission log line carries scope and repos; comment text says "in this hive's repositories" for the hive scope. Fixes #14517 Signed-off-by: Andy Anderson --- ...d-contributor-auto-promotion-hive-scope.md | 1 + src/cmd/hive/merge_eligibility.go | 1 + src/docs/hive-merge.md | 28 +- src/docs/operator-reference.md | 2 + src/pkg/config/automerge_trusted_bot_test.go | 20 ++ src/pkg/config/config.go | 33 +++ src/pkg/dashboard/api_config_automerge.go | 15 + src/pkg/dashboard/api_config_sections_test.go | 12 + src/pkg/dashboard/static/index.html | 13 +- .../automerge/automerge_contributor_lane.go | 269 ++++++++++++++++-- .../automerge_contributor_lane_test.go | 263 ++++++++++++++++- 11 files changed, 627 insertions(+), 30 deletions(-) create mode 100644 changelog.d/changed-contributor-auto-promotion-hive-scope.md diff --git a/changelog.d/changed-contributor-auto-promotion-hive-scope.md b/changelog.d/changed-contributor-auto-promotion-hive-scope.md new file mode 100644 index 0000000000..f58c730407 --- /dev/null +++ b/changelog.d/changed-contributor-auto-promotion-hive-scope.md @@ -0,0 +1 @@ +- Contributor-lane auto-promotion now counts an author's clean merged PRs across every repository the hive manages (`auto_merge.contributor_lane.auto_promotion_scope: hive`, the default; `repo` restores the per-repository count), so a contributor trusted in the main repo is admitted on their first PR to a satellite repo; the audit marker and admission log carry the scope and a per-repo breakdown (#14517). diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index 019be8c6bc..4add12684f 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -89,6 +89,7 @@ func contributorLanePolicyFunc(cfg *config.Config) func() automerge.ContributorL RequireTiers: p.RequireTierSet(), RegistryTiersSufficient: p.EffectiveRegistryTiersSufficient(), AutoPromoteAfterMergedPR: tier.EffectiveAutoPromoteAfterMerged(), + AutoPromotionScope: p.EffectiveAutoPromotionScope(), } } } diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 458142f70d..1f333daaeb 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -432,6 +432,28 @@ A PR merges through this tier only when all of the following hold: with `contributor-lane:no-linked-issue`. The marker's `tier=` must be in `require_tiers` (`contributor-lane:claim-tier-untrusted`) and it must say `verified=true` (`contributor-lane:claim-unverified`). + - **Auto-promotion**: when the marker path fails on tier, the conservative + clean-history ratchet (`auto_merge.contributor_tier.auto_promote_after_merged`, + default 5; negative disables) admits the author if their last N merged + PRs have no revert or sentinel-alert evidence — none is itself a revert, + none carries the sentinel label, none was undone by a later merged + `Revert ""` / "This reverts commit <sha>" PR — and the author is + not `revoked` in the registry. By default the merges are counted across + **every repository the hive manages** + (`auto_merge.contributor_lane.auto_promotion_scope: hive`): trust is a + property of the person, and the small satellite repos of a multi-repo + hive never reach the threshold on their own (hivecommons/docs#481 sat 17h + at `contributor-lane:claim-tier-untrusted` while the same author had nine + clean merges in hivecommons/hive; #14517). The PR's own repository is + walked first; only when it is short does one `search/issues` query + (`is:pr is:merged author:<login> repo:… repo:…`) find which other hive + repos hold the author's merges, and only those are walked for revert + evidence — a revert or sentinel hit in any repository blocks. The sweep + posts a `<!-- hive:contributor-auto-promoted author=… merged=N scope=hive + repos=hive:4,docs:1 -->` audit comment once per PR and logs + `contributor-lane admitted reason=contributor-lane:auto-promoted + merged_prs=5 scope=hive repos=hive:4,docs:1`. `auto_promotion_scope: + repo` restores the per-repository count. - When neither admission path above vouches for the author, GitHub's `author_association` for the PR author must be `OWNER`, `MEMBER`, `COLLABORATOR` or `CONTRIBUTOR`; `NONE`, `FIRST_TIMER`, @@ -491,11 +513,15 @@ auto_merge: - trusted - merger registry_tiers_sufficient: true # a require_tiers tier on the author's registry profile admits without a claim marker + auto_promotion_scope: hive # count clean merged PRs across every hive repo (repo = this repository only) + contributor_tier: + auto_promote_after_merged: 5 # clean merged PRs before the lane trusts an author on its own; negative disables ``` The block is editable from **Settings → Features → Auto Merge → Contributor-lane auto-merge** (enable switch, soak minutes, reviewer-verdict -switch, required tiers, excluded labels, repository allow-list) through the +switch, required tiers, auto-promotion scope, excluded labels, repository +allow-list) through the same owner-only `GET/PUT /api/config/auto-merge` overlay. **Operator workflow.** To let a known contributor's relay PRs merge diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index fdc1773891..43c996d071 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -433,6 +433,8 @@ advanced into the merge path. | `auto_merge.contributor_lane.require_reviewer_verdict` | `true` | Require an approving aggregate reviewer verdict for the current head. Independently of this key, a hive with no reviewer agent never merges through the tier (`contributor-lane:no-reviewer`). | | `auto_merge.contributor_lane.require_tiers` | `trusted`, `merger` | Contributor trust tiers whose verified claims the tier may merge. Only operator-granted tiers (`trusted`, `merger`, `advisor`) are accepted; `newcomer` and `contributor` are rejected at validation. | | `auto_merge.contributor_lane.registry_tiers_sufficient` | `true` | Admit a PR whose author's contributor-registry profile carries a `require_tiers` tier without a linked issue or `hive:claim` marker (logged as `contributor-lane:registry-trusted`). All other gates still apply. `false` requires the claim marker for every contributor. | +| `auto_merge.contributor_lane.auto_promotion_scope` | `hive` | Where the clean-merged-PR ratchet (`auto_merge.contributor_tier.auto_promote_after_merged`) counts an author's merges: `hive` counts across every repository the hive manages (one `search/issues` query finds the repos holding the author's merges; the PR's own repo is always walked first), `repo` counts only the PR's repository. Revert and sentinel-alert evidence blocks promotion in either scope. | +| `auto_merge.contributor_tier.auto_promote_after_merged` | `5` | Clean merged PRs (no revert, no sentinel label, not undone by a later merged revert) after which the contributor lane treats an author as `trusted` without an operator grant, unless the registry marks them `revoked`. Negative disables the ratchet. | | `auto_merge.contributor_lane.repos` | empty = all watched repos | Optional repo allow-list for the contributor-lane tier (bare name or `owner/repo`). | | `auto_merge.contributor_lane.exclude_labels` | `hold`, `do-not-merge`, `needs-human`, `blocked`, `needs-rebase` | Labels that keep a PR out of contributor-lane auto-merge (`do-not-merge/*` always excluded). | diff --git a/src/pkg/config/automerge_trusted_bot_test.go b/src/pkg/config/automerge_trusted_bot_test.go index bc3cd31825..03d36cec14 100644 --- a/src/pkg/config/automerge_trusted_bot_test.go +++ b/src/pkg/config/automerge_trusted_bot_test.go @@ -135,6 +135,26 @@ func TestContributorLaneAutoMergeConfigRequireTiers(t *testing.T) { } } +// auto_promotion_scope defaults to hive (fleet-wide clean-merge count, +// #14517), accepts repo, and rejects anything else. +func TestContributorLaneAutoMergeConfigAutoPromotionScope(t *testing.T) { + var cfg ContributorLaneAutoMergeConfig + if got := cfg.EffectiveAutoPromotionScope(); got != ContributorLaneAutoPromotionScopeHive { + t.Fatalf("default auto_promotion_scope = %q, want hive", got) + } + cfg.AutoPromotionScope = " Repo " + if err := cfg.Validate(); err != nil { + t.Fatalf("repo scope should validate: %v", err) + } + if got := cfg.EffectiveAutoPromotionScope(); got != ContributorLaneAutoPromotionScopeRepo { + t.Fatalf("auto_promotion_scope = %q, want repo (trimmed, lower-cased)", got) + } + cfg.AutoPromotionScope = "fleet" + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "auto_promotion_scope") { + t.Fatalf("invalid scope must fail validation, got %v", err) + } +} + func TestBotTakeoverAutoMergeConfigDefaultsOnAndHonorsExplicitOff(t *testing.T) { var a AutoMergeConfig if !a.BotTakeover.IsEnabled() { diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 170c2eabc5..70bff59fc4 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -7726,6 +7726,36 @@ type ContributorLaneAutoMergeConfig struct { // than closes its issue, or was claimed outside the relay, waits for a // human (`contributor-lane:no-linked-issue` / `no-claim`). RegistryTiersSufficient *bool `yaml:"registry_tiers_sufficient,omitempty" json:"registry_tiers_sufficient,omitempty"` + // AutoPromotionScope is where the clean-merged-PR ratchet + // (auto_merge.contributor_tier.auto_promote_after_merged) counts an + // author's merges. `hive` (default) counts clean merged PRs across every + // repository this hive manages: trust in a contributor is a property of + // the person, and the small satellite repos of a multi-repo hive never + // reach a per-repo threshold on their own. `repo` counts only the PR's + // own repository (the pre-#14517 behaviour). Revert and sentinel-alert + // evidence is applied per PR in either scope. + AutoPromotionScope string `yaml:"auto_promotion_scope,omitempty" json:"auto_promotion_scope,omitempty"` +} + +// Contributor-lane auto-promotion scopes +// (auto_merge.contributor_lane.auto_promotion_scope). +const ( + ContributorLaneAutoPromotionScopeHive = "hive" + ContributorLaneAutoPromotionScopeRepo = "repo" +) + +// ContributorLaneAutoPromotionScopes lists the accepted +// auto_promotion_scope values. +var ContributorLaneAutoPromotionScopes = []string{ContributorLaneAutoPromotionScopeHive, ContributorLaneAutoPromotionScopeRepo} + +// EffectiveAutoPromotionScope returns the normalized auto_promotion_scope, +// defaulting to ContributorLaneAutoPromotionScopeHive. +func (c ContributorLaneAutoMergeConfig) EffectiveAutoPromotionScope() string { + scope := strings.ToLower(strings.TrimSpace(c.AutoPromotionScope)) + if scope == "" { + return ContributorLaneAutoPromotionScopeHive + } + return scope } // ContributorTierAutoMergeConfig is auto_merge.contributor_tier.*. @@ -7864,6 +7894,9 @@ func (c ContributorLaneAutoMergeConfig) Validate() error { return fmt.Errorf("auto_merge.contributor_lane.require_tiers: %q is not an operator-granted tier (allowed: %s)", tier, strings.Join(ContributorLaneGrantableTiers, ", ")) } } + if scope := c.EffectiveAutoPromotionScope(); scope != ContributorLaneAutoPromotionScopeHive && scope != ContributorLaneAutoPromotionScopeRepo { + return fmt.Errorf("auto_merge.contributor_lane.auto_promotion_scope: %q is not valid (allowed: %s)", c.AutoPromotionScope, strings.Join(ContributorLaneAutoPromotionScopes, ", ")) + } return nil } diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index b3cd57f116..50aec7d910 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -168,6 +168,7 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { ExcludeLabels []string `json:"exclude_labels"` RequireTiers []string `json:"require_tiers"` RegistryTiersSufficient *bool `json:"registry_tiers_sufficient"` + AutoPromotionScope *string `json:"auto_promotion_scope"` } `json:"contributor_lane"` } if err := decodeBody(r, &body); err != nil { @@ -215,6 +216,7 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { var contributorLaneRepos []string var contributorLaneLabels []string var contributorLaneTiers []string + var contributorLaneScope string if body.ContributorLane != nil { if body.ContributorLane.SoakMinutes != nil && *body.ContributorLane.SoakMinutes < 0 { jsonError(w, "contributor_lane.soak_minutes must be 0 (default 30) or greater", http.StatusBadRequest) @@ -241,6 +243,14 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { } contributorLaneTiers = normalizeAutoMergeRepoList(body.ContributorLane.RequireTiers) } + if body.ContributorLane.AutoPromotionScope != nil { + scope := config.ContributorLaneAutoMergeConfig{AutoPromotionScope: *body.ContributorLane.AutoPromotionScope} + if err := scope.Validate(); err != nil { + jsonError(w, "contributor_lane.auto_promotion_scope must be one of "+strings.Join(config.ContributorLaneAutoPromotionScopes, ", "), http.StatusBadRequest) + return + } + contributorLaneScope = scope.EffectiveAutoPromotionScope() + } } // --- apply --- @@ -321,6 +331,9 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { if body.ContributorLane.RequireTiers != nil { cfg.AutoMerge.ContributorLane.RequireTiers = contributorLaneTiers } + if body.ContributorLane.AutoPromotionScope != nil { + cfg.AutoMerge.ContributorLane.AutoPromotionScope = contributorLaneScope + } } syncAutoMergePolicyToGitHubClient(cfg, s.deps.GHClient) @@ -404,6 +417,8 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "exclude_labels": contributorLaneLabels, "require_tiers": cl.EffectiveRequireTiers(), "registry_tiers_sufficient": cl.EffectiveRegistryTiersSufficient(), + "auto_promotion_scope": cl.EffectiveAutoPromotionScope(), + "auto_promotion_scopes": config.ContributorLaneAutoPromotionScopes, "grantable_tiers": config.ContributorLaneGrantableTiers, }, } diff --git a/src/pkg/dashboard/api_config_sections_test.go b/src/pkg/dashboard/api_config_sections_test.go index c5e63442c3..7af3a4d98b 100644 --- a/src/pkg/dashboard/api_config_sections_test.go +++ b/src/pkg/dashboard/api_config_sections_test.go @@ -639,6 +639,8 @@ func TestAutoMergeGet_ContributorLaneDefaults(t *testing.T) { ExcludeLabels []string `json:"exclude_labels"` RequireTiers []string `json:"require_tiers"` RegistryTiers bool `json:"registry_tiers_sufficient"` + AutoPromotionScope string `json:"auto_promotion_scope"` + AutoPromotionScopes []string `json:"auto_promotion_scopes"` GrantableTiers []string `json:"grantable_tiers"` } `json:"contributor_lane"` } @@ -655,6 +657,9 @@ func TestAutoMergeGet_ContributorLaneDefaults(t *testing.T) { if !cl.Enabled || cl.SoakMinutes != config.DefaultContributorLaneSoakMinutes || !cl.RequireReviewerVerdict || !cl.RegistryTiers || len(cl.Repos) != 0 { t.Fatalf("contributor_lane defaults wrong: %+v", cl) } + if cl.AutoPromotionScope != config.ContributorLaneAutoPromotionScopeHive || strings.Join(cl.AutoPromotionScopes, ",") != "hive,repo" { + t.Fatalf("contributor_lane auto_promotion_scope defaults wrong: %+v", cl) + } if strings.Join(cl.ExcludeLabels, ",") != strings.Join(config.DefaultContributorLaneExcludeLabels, ",") { t.Fatalf("contributor_lane default labels wrong: %v", cl.ExcludeLabels) } @@ -671,6 +676,7 @@ func TestAutoMergePut_ContributorLaneValidation(t *testing.T) { "repos": []string{" widget ", ""}, "exclude_labels": []string{"hold"}, "require_tiers": []string{" merger "}, + "auto_promotion_scope": " Repo ", }, } if rec := doPut(s, "/api/config/auto-merge", valid); rec.Code != http.StatusOK { @@ -680,6 +686,12 @@ func TestAutoMergePut_ContributorLaneValidation(t *testing.T) { if cl.IsEnabled() || cl.EffectiveSoakMinutes() != 30 || cl.EffectiveRequireReviewerVerdict() || cl.EffectiveRegistryTiersSufficient() { t.Fatalf("contributor_lane write did not apply: %+v", cl) } + if cl.AutoPromotionScope != config.ContributorLaneAutoPromotionScopeRepo { + t.Fatalf("contributor_lane auto_promotion_scope not normalized: %q", cl.AutoPromotionScope) + } + if rec := doPut(s, "/api/config/auto-merge", map[string]any{"contributor_lane": map[string]any{"auto_promotion_scope": "fleet"}}); rec.Code != http.StatusBadRequest { + t.Fatalf("invalid auto_promotion_scope: expected 400, got %d", rec.Code) + } if strings.Join(cl.Repos, ",") != "widget" || strings.Join(cl.ExcludeLabels, ",") != "hold" { t.Fatalf("contributor_lane lists not normalized: repos=%v labels=%v", cl.Repos, cl.ExcludeLabels) } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index eb427631ac..cf786c412d 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -49641,6 +49641,10 @@ <h3 class="features-section-title">${esc(s.title)}</h3> const amContributorLaneLabels = Array.isArray(amContributorLane.exclude_labels) ? amContributorLane.exclude_labels : ['hold','do-not-merge','needs-human','blocked','needs-rebase']; const amContributorLaneTiers = Array.isArray(amContributorLane.require_tiers) && amContributorLane.require_tiers.length ? amContributorLane.require_tiers : ['merger','trusted']; const amContributorLaneGrantable = Array.isArray(amContributorLane.grantable_tiers) ? amContributorLane.grantable_tiers : ['trusted','merger','advisor']; + const amContributorLaneScope = typeof amContributorLane.auto_promotion_scope === 'string' && amContributorLane.auto_promotion_scope ? amContributorLane.auto_promotion_scope : 'hive'; + const amContributorLaneScopes = Array.isArray(amContributorLane.auto_promotion_scopes) && amContributorLane.auto_promotion_scopes.length ? amContributorLane.auto_promotion_scopes : ['hive','repo']; + const amContributorLaneScopeLabel = { hive: "hive — every repository this hive manages", repo: "repo — the PR's repository only" }; + const amContributorLaneScopeOptions = amContributorLaneScopes.map(v => `<option value="${esc(v)}"${v === amContributorLaneScope ? ' selected' : ''}>${esc(amContributorLaneScopeLabel[v] || v)}</option>`).join(''); const amContributorLaneRepoSet = new Set((Array.isArray(amContributorLane.repos) ? amContributorLane.repos : []).map(r => String(r).toLowerCase())); const amContributorLaneRepoOptions = watchedRepos.map(r => `<option value="${esc(r)}"${amContributorLaneRepoSet.has(String(r).toLowerCase()) ? ' selected' : ''}>${esc(r)}</option>`).join(''); const amBotSourceLabel = { known: 'known bot', discovered: 'seen in open PRs', custom: 'added manually' }; @@ -49827,6 +49831,11 @@ <h3 class="features-section-title">${esc(s.title)}</h3> </div> </div> </div> + <div class="config-field mt-4"> + <label for="am-contributor-lane-auto-promotion-scope">Auto-promotion scope ${settingHelpMark('hive-merge', 'contributor-lane-auto-merge', 'Auto-promotion scope', `Where the clean-merged-PR ratchet (auto_merge.contributor_tier.auto_promote_after_merged) counts an author's merges. hive (the default) counts clean merged PRs across every repository this hive manages, so a contributor trusted in the main repo is trusted in the small satellite repos too; repo counts only the PR's own repository. Revert and sentinel-alert evidence blocks promotion in either scope.`)}</label> + <select id="am-contributor-lane-auto-promotion-scope" data-change-action="gh104">${amContributorLaneScopeOptions}</select> + <p class="am-trusted-authors-note">A contributor's trust is a property of the person, not the repository: with <code>hive</code>, nine clean merges in the main repo also admit their first PR to a docs repo.</p> + </div> <div class="config-field mt-4"> <label for="am-contributor-lane-exclude-labels">Excluded labels</label> <input id="am-contributor-lane-exclude-labels" type="text" value="${esc(amContributorLaneLabels.join(', '))}" placeholder="hold, do-not-merge, needs-human, blocked, needs-rebase" data-change-action="gh104"> @@ -49836,7 +49845,7 @@ <h3 class="features-section-title">${esc(s.title)}</h3> <label for="am-contributor-lane-repos">Repositories</label> <select id="am-contributor-lane-repos" multiple size="${Math.min(Math.max(watchedRepos.length || 3, 3), 8)}" data-change-action="gh104" class="am-trusted-authors-repos">${amContributorLaneRepoOptions}</select> <p class="am-trusted-authors-note">Leave every repo unselected to allow all watched repositories. Skips are logged as <code>contributor-lane:*</code> reasons (no-claim, no-linked-issue, claim-author-mismatch, claim-other-hive, claim-tier-untrusted, claim-unverified, author-association, workflow-path, tests-removed, no-reviewer, no-verdict, soaking, sentinel-blocked); a registry-admitted PR logs <code>contributor-lane:registry-trusted</code>.</p> - <p class="config-help">YAML keys: <code>auto_merge.contributor_lane.enabled</code>, <code>auto_merge.contributor_lane.soak_minutes</code>, <code>auto_merge.contributor_lane.require_reviewer_verdict</code>, <code>auto_merge.contributor_lane.registry_tiers_sufficient</code>, <code>auto_merge.contributor_lane.repos[]</code>, <code>auto_merge.contributor_lane.exclude_labels[]</code>, <code>auto_merge.contributor_lane.require_tiers[]</code>.</p> + <p class="config-help">YAML keys: <code>auto_merge.contributor_lane.enabled</code>, <code>auto_merge.contributor_lane.soak_minutes</code>, <code>auto_merge.contributor_lane.require_reviewer_verdict</code>, <code>auto_merge.contributor_lane.registry_tiers_sufficient</code>, <code>auto_merge.contributor_lane.auto_promotion_scope</code>, <code>auto_merge.contributor_lane.repos[]</code>, <code>auto_merge.contributor_lane.exclude_labels[]</code>, <code>auto_merge.contributor_lane.require_tiers[]</code>.</p> </div> </div> </div> @@ -52143,12 +52152,14 @@ <h3 class="features-section-title">${esc(s.title)}</h3> const labels = document.getElementById('am-contributor-lane-exclude-labels'); const repos = document.getElementById('am-contributor-lane-repos'); const tiers = document.getElementById('am-contributor-lane-require-tiers'); + const scope = document.getElementById('am-contributor-lane-auto-promotion-scope'); const soakMinutes = soak ? parseInt(soak.value, 10) : 30; markDirty('auto-merge', 'contributor_lane', { enabled: !!(enabled && enabled.classList.contains('on')), soak_minutes: Number.isFinite(soakMinutes) && soakMinutes >= 0 ? soakMinutes : 30, require_reviewer_verdict: !!(verdict && verdict.classList.contains('on')), registry_tiers_sufficient: !!(registry && registry.classList.contains('on')), + auto_promotion_scope: scope && scope.value ? scope.value : 'hive', exclude_labels: labels ? labels.value.split(',').map(s => s.trim()).filter(Boolean) : [], repos: repos ? Array.from(repos.selectedOptions).map(o => o.value).filter(Boolean) : [], require_tiers: tiers ? tiers.value.split(',').map(s => s.trim().toLowerCase()).filter(Boolean) : [] diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 0d14ef3d81..6a7ecad766 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -193,8 +193,26 @@ type ContributorLanePolicy struct { // marker (auto_merge.contributor_lane.registry_tiers_sufficient). RegistryTiersSufficient bool // AutoPromoteAfterMergedPRs admits the author after this many recent - // merged PRs in the repo have no revert or sentinel-alert evidence. + // merged PRs have no revert or sentinel-alert evidence. AutoPromoteAfterMergedPR int + // AutoPromotionScope is where those merges are counted + // (auto_merge.contributor_lane.auto_promotion_scope): "repo" counts the + // PR's own repository only; anything else (the default, "hive") counts + // every repository this hive manages (#14517). + AutoPromotionScope string +} + +// Contributor-lane auto-promotion scopes; mirrors +// config.ContributorLaneAutoPromotionScope*. +const ( + contributorAutoPromotionScopeHive = "hive" + contributorAutoPromotionScopeRepo = "repo" +) + +// hiveWideAutoPromotion reports whether the policy counts clean merges across +// every repository the hive manages rather than the PR's own repository. +func (p ContributorLanePolicy) hiveWideAutoPromotion() bool { + return !strings.EqualFold(strings.TrimSpace(p.AutoPromotionScope), contributorAutoPromotionScopeRepo) } // ContributorRegistryTierFunc looks up the operator-set trust tier of a @@ -488,7 +506,12 @@ type contributorClaimMatch struct { Issue int RegistryTier string AutoPromoted int - Reason string + // AutoPromotedHiveWide is set when AutoPromoted counted clean merges + // across the hive's repositories rather than the PR's own repository; + // AutoPromotedRepos is the per-repo breakdown ("hive:8,docs:1"). + AutoPromotedHiveWide bool + AutoPromotedRepos string + Reason string // AdoptedHead is set when the hive's own in-place adoption admitted the // PR: the head SHA the stage store records as adopted/pushed by the // hive, which the lane verified equals the PR head it is evaluating. @@ -588,18 +611,18 @@ func (c *Engine) admitContributor(ctx context.Context, owner, repo string, pr *g match.ObservedTier = c.observedRegistryTier(author) } if err == nil && match.Reason != "" && policy.AutoPromoteAfterMergedPR > 0 && !contributorRegistryTierRevoked(c.observedRegistryTier(author)) { - clean, checked, reason, promoteErr := c.contributorCleanMergedHistory(ctx, owner, repo, author, policy.AutoPromoteAfterMergedPR) + history, promoteErr := c.contributorCleanMergedHistory(ctx, owner, repo, author, policy.AutoPromoteAfterMergedPR, policy.hiveWideAutoPromotion()) if promoteErr != nil { return contributorClaimMatch{Reason: "contributor-lane:auto-promote-history"}, promoteErr } - if clean { - if commentErr := c.commentContributorAutoPromotion(ctx, owner, repo, pr.GetNumber(), author, checked); commentErr != nil { + if history.Clean { + if commentErr := c.commentContributorAutoPromotion(ctx, owner, repo, pr.GetNumber(), author, history); commentErr != nil { c.warn("contributor-lane auto-promotion audit comment failed", "repo", owner+"/"+repo, "pr", pr.GetNumber(), "author", author, "error", commentErr) } - return contributorClaimMatch{AutoPromoted: checked, ObservedTier: "trusted"}, nil + return contributorClaimMatch{AutoPromoted: history.Checked, AutoPromotedHiveWide: history.HiveWide, AutoPromotedRepos: history.repoBreakdown(), ObservedTier: "trusted"}, nil } - if reason != "" { - c.debug("contributor-lane auto-promotion skipped", "repo", owner+"/"+repo, "pr", pr.GetNumber(), "author", author, "reason", reason, "clean_merged", checked) + if history.Reason != "" { + c.debug("contributor-lane auto-promotion skipped", "repo", owner+"/"+repo, "pr", pr.GetNumber(), "author", author, "reason", history.Reason, "clean_merged", history.Checked, "scope", history.scopeName(), "repos", history.repoBreakdown()) } } return match, err @@ -633,36 +656,218 @@ func contributorRegistryTierRevoked(tier string) bool { const contributorRegistryTierRevokedName = "revoked" -// contributorCleanMergedHistory walks the repository's recently merged PRs and -// reports whether the author's last `need` merges are clean: none is itself a -// revert, none carries the sentinel label, and none was undone by a later -// merged revert PR (matched by merge-commit SHA in a "This reverts commit" -// body or by a `Revert "<title>"` title) — the revert evidence the audit -// comment promises to have checked. -func (c *Engine) contributorCleanMergedHistory(ctx context.Context, owner, repo, author string, need int) (bool, int, string, error) { +// contributorMergedHistory is the outcome of the clean-merged-PR ratchet +// for one author: whether the threshold was met, how many clean merges were +// counted, where they were found, and why it stopped when it did. +type contributorMergedHistory struct { + Clean bool + Checked int + HiveWide bool + Reason string + // Repos is the per-repo clean-merge count in evaluation order (the PR's + // own repository first). + Repos []contributorRepoMerges +} + +type contributorRepoMerges struct { + Repo string + Clean int +} + +// repoBreakdown renders Repos as "hive:8,docs:1" for log lines and markers. +func (h contributorMergedHistory) repoBreakdown() string { + parts := make([]string, 0, len(h.Repos)) + for _, r := range h.Repos { + parts = append(parts, r.Repo+":"+strconv.Itoa(r.Clean)) + } + return strings.Join(parts, ",") +} + +func (h contributorMergedHistory) scopeName() string { + return contributorAutoPromotionScopeName(h.HiveWide) +} + +func contributorAutoPromotionScopeName(hiveWide bool) string { + if hiveWide { + return contributorAutoPromotionScopeHive + } + return contributorAutoPromotionScopeRepo +} + +// contributorCleanMergedHistory reports whether the author's last `need` +// merges are clean: none is itself a revert, none carries the sentinel +// label, and none was undone by a later merged revert PR (matched by +// merge-commit SHA in a "This reverts commit" body or by a `Revert "<title>"` +// title) — the revert evidence the audit comment promises to have checked. +// +// With hiveWide the merges are counted across every repository the hive +// manages (#14517: trust is a property of the person, and the satellite +// repos of a multi-repo hive never reach a per-repo threshold on their own). +// The PR's own repository is walked first and settles the common case +// alone; only when it is short are the other repositories discovered, with +// one search/issues query for the author's merged PRs rather than a +// closed-PR listing per repository, and only the ones that hold a merge by +// the author are walked for revert evidence. A single revert or sentinel +// hit in any repository blocks promotion. +func (c *Engine) contributorCleanMergedHistory(ctx context.Context, owner, repo, author string, need int, hiveWide bool) (contributorMergedHistory, error) { + history := contributorMergedHistory{HiveWide: hiveWide} if c == nil || c.gh == nil || need <= 0 || strings.TrimSpace(author) == "" { - return false, 0, "disabled", nil + history.Reason = "disabled" + return history, nil } + walk := func(ref contributorRepoRef) (done bool, err error) { + clean, blocked, err := c.contributorCleanMergesInRepo(ctx, ref.Owner, ref.Repo, author, need-history.Checked) + if err != nil { + history.Reason = "list-merged-prs" + return true, err + } + history.Checked += clean + history.Repos = append(history.Repos, contributorRepoMerges{Repo: ref.Repo, Clean: clean}) + if blocked { + history.Reason = "revert-or-sentinel" + return true, nil + } + if history.Checked >= need { + history.Clean = true + return true, nil + } + return false, nil + } + if done, err := walk(contributorRepoRef{Owner: owner, Repo: repo}); done { + return history, err + } + if hiveWide { + for _, ref := range c.contributorMergedRepos(ctx, owner, repo, author) { + if done, err := walk(ref); done { + return history, err + } + } + } + history.Reason = "insufficient-clean-merges" + return history, nil +} + +// contributorCleanMergesInRepo walks one repository's recently merged PRs +// and counts the author's clean merges, up to need. blocked is true when a +// merge by the author is itself a revert, carries the sentinel label, or +// was undone by a later merged revert PR. +func (c *Engine) contributorCleanMergesInRepo(ctx context.Context, owner, repo, author string, need int) (clean int, blocked bool, err error) { opts := &gh.PullRequestListOptions{State: "closed", Sort: "updated", Direction: "desc", ListOptions: gh.ListOptions{PerPage: 100}} prs, _, err := c.gh.PullRequests.List(ctx, owner, repo, opts) if err != nil { - return false, 0, "list-merged-prs", err + return 0, false, err } reverted := mergedRevertTargets(prs) - clean := 0 for _, old := range prs { if old == nil || !strings.EqualFold(hgithub.SafeGetLogin(old.GetUser()), author) || old.GetMergedAt().IsZero() { continue } if contributorPromotionBlockedByHistory(old) || reverted.contains(old) { - return false, clean, "revert-or-sentinel", nil + return clean, true, nil } clean++ if clean >= need { - return true, clean, "", nil + return clean, false, nil } } - return false, clean, "insufficient-clean-merges", nil + return clean, false, nil +} + +type contributorRepoRef struct { + Owner string + Repo string +} + +// contributorSearchQueryMaxLen is GitHub's limit on a search `q` parameter. +const contributorSearchQueryMaxLen = 256 + +// contributorMergedRepos returns the hive's other active repositories that +// hold at least one merged PR by author, in the order the transport lists +// them, excluding the PR's own (owner, repo). It asks search/issues +// `is:pr is:merged author:<login> repo:… repo:…`, chunked to GitHub's +// 256-character query limit, so a ten-repo hive costs one or two search +// calls instead of ten closed-PR listings. A search failure degrades to the +// PR's own repository with a warning rather than blocking the sweep: the +// result is then exactly the pre-#14517 per-repo count. +func (c *Engine) contributorMergedRepos(ctx context.Context, owner, repo, author string) []contributorRepoRef { + if c == nil || c.gh == nil || c.transport == nil { + return nil + } + own := strings.ToLower(owner + "/" + repo) + var candidates []contributorRepoRef + seen := map[string]bool{} + for _, display := range c.activeRepos() { + o, r := c.transport.SplitRepo(display) + if o == "" || r == "" { + continue + } + full := strings.ToLower(o + "/" + r) + if full == own || seen[full] { + continue + } + seen[full] = true + candidates = append(candidates, contributorRepoRef{Owner: o, Repo: r}) + } + if len(candidates) == 0 { + return nil + } + base := "is:pr is:merged author:" + strings.TrimPrefix(strings.TrimSpace(author), "@") + found := map[string]bool{} + query := base + flush := func() error { + if query == base { + return nil + } + result, _, err := c.gh.Search.Issues(ctx, query, &gh.SearchOptions{Sort: "updated", Order: "desc", ListOptions: gh.ListOptions{PerPage: 100}}) + query = base + if err != nil { + return err + } + for _, issue := range result.Issues { + if issue == nil { + continue + } + if full := repoFromRepositoryURL(issue.GetRepositoryURL()); full != "" { + found[full] = true + } + } + return nil + } + for _, ref := range candidates { + qualifier := " repo:" + ref.Owner + "/" + ref.Repo + if len(query)+len(qualifier) > contributorSearchQueryMaxLen { + if err := flush(); err != nil { + c.warn("contributor-lane auto-promotion repo search failed; counting the PR's repository only", "repo", owner+"/"+repo, "author", author, "error", err) + return nil + } + } + query += qualifier + } + if err := flush(); err != nil { + c.warn("contributor-lane auto-promotion repo search failed; counting the PR's repository only", "repo", owner+"/"+repo, "author", author, "error", err) + return nil + } + out := make([]contributorRepoRef, 0, len(found)) + for _, ref := range candidates { + if found[strings.ToLower(ref.Owner+"/"+ref.Repo)] { + out = append(out, ref) + } + } + return out +} + +// repoFromRepositoryURL extracts lower-cased owner/repo from a search +// result's repository_url (https://api.github.com/repos/owner/repo). +func repoFromRepositoryURL(u string) string { + _, rest, ok := strings.Cut(strings.TrimSpace(u), "/repos/") + if !ok { + return "" + } + parts := strings.Split(strings.TrimSuffix(rest, "/"), "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "" + } + return strings.ToLower(parts[0] + "/" + parts[1]) } // revertTargets indexes what the merged revert PRs in a window undid. @@ -735,7 +940,16 @@ func contributorPromotionBlockedByHistory(pr *gh.PullRequest) bool { return false } -func (c *Engine) commentContributorAutoPromotion(ctx context.Context, owner, repo string, number int, author string, merged int) error { +// contributorAutoPromotionWhere names where the clean merges were counted, +// for the audit and merge comments. +func contributorAutoPromotionWhere(hiveWide bool) string { + if hiveWide { + return "in this hive's repositories" + } + return "in this repository" +} + +func (c *Engine) commentContributorAutoPromotion(ctx context.Context, owner, repo string, number int, author string, history contributorMergedHistory) error { if c == nil || c.gh == nil || number <= 0 { return nil } @@ -748,8 +962,9 @@ func (c *Engine) commentContributorAutoPromotion(ctx context.Context, owner, rep return nil } } - body := fmt.Sprintf("%s author=%s merged=%d -->\n@%s is auto-promoted for contributor-lane merging on this PR: the last %d merged PRs by this author in this repository have no revert or sentinel-alert evidence. CI, reviewer verdict, diff fences, soak, holds and branch protection still apply.", - contributorAutoPromotionMarkerPrefix, strings.TrimPrefix(author, "@"), merged, strings.TrimPrefix(author, "@"), merged) + login := strings.TrimPrefix(author, "@") + body := fmt.Sprintf("%s author=%s merged=%d scope=%s repos=%s -->\n@%s is auto-promoted for contributor-lane merging on this PR: the last %d merged PRs by this author %s have no revert or sentinel-alert evidence. CI, reviewer verdict, diff fences, soak, holds and branch protection still apply.", + contributorAutoPromotionMarkerPrefix, login, history.Checked, history.scopeName(), history.repoBreakdown(), login, history.Checked, contributorAutoPromotionWhere(history.HiveWide)) _, _, err = c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) return err } @@ -979,7 +1194,7 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own c.info("contributor-lane admitted", "repo", displayRepo, "pr", number, "author", author, "reason", contributorLaneReasonRegistryTrusted, "registry_tier", claim.RegistryTier) } if claim.admittedByAutoPromotion() { - c.info("contributor-lane admitted", "repo", displayRepo, "pr", number, "author", author, "reason", "contributor-lane:auto-promoted", "merged_prs", claim.AutoPromoted) + c.info("contributor-lane admitted", "repo", displayRepo, "pr", number, "author", author, "reason", "contributor-lane:auto-promoted", "merged_prs", claim.AutoPromoted, "scope", contributorAutoPromotionScopeName(claim.AutoPromotedHiveWide), "repos", claim.AutoPromotedRepos) } files, err := ListChangedFiles(caller, c.gh, owner, repo, pr) if err != nil { @@ -1191,8 +1406,8 @@ func contributorLaneMergeComment(author string, claim contributorClaimMatch, soa int(soak.Minutes()), verdictText, login, claim.RegistryTier) } if claim.admittedByAutoPromotion() { - return fmt.Sprintf("Merged by hive contributor-lane auto-merge: CI green for ≥%dm, %s, @%s was auto-promoted after %d clean merged PRs in this repository.", - int(soak.Minutes()), verdictText, login, claim.AutoPromoted) + return fmt.Sprintf("Merged by hive contributor-lane auto-merge: CI green for ≥%dm, %s, @%s was auto-promoted after %d clean merged PRs %s.", + int(soak.Minutes()), verdictText, login, claim.AutoPromoted, contributorAutoPromotionWhere(claim.AutoPromotedHiveWide)) } return fmt.Sprintf("Merged by hive contributor-lane auto-merge: CI green for ≥%dm, %s, claim by @%s on #%d verified.", int(soak.Minutes()), verdictText, login, claim.Issue) diff --git a/src/pkg/github/automerge/automerge_contributor_lane_test.go b/src/pkg/github/automerge/automerge_contributor_lane_test.go index 4cc11b1065..0fa8739214 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane_test.go +++ b/src/pkg/github/automerge/automerge_contributor_lane_test.go @@ -56,6 +56,15 @@ type contributorLaneFixture struct { issueComments []map[string]any // comments on the linked issue prComments []map[string]any // comments on the PR mergedHistory []map[string]any + // otherHistory is the closed-PR list of the hive's other repositories + // (acme/<name>), served to the hive-wide auto-promotion walk; the fake + // search/issues endpoint reports a repo only when it holds a merged PR + // by the searched author. + otherHistory map[string][]map[string]any + searchStatus int + searches int + searchQuery string + otherLists []string issueCommentsSt int reviews []map[string]any mergeStatus int @@ -66,6 +75,7 @@ type contributorLaneFixture struct { comments int updates int lastComment string + allComments []string // checkCompletedAt, when set, is the completed_at the check-runs // endpoint reports for sha7 (RFC 3339); empty omits the field. checkCompletedAt string @@ -148,6 +158,43 @@ func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.S return } json.NewEncoder(w).Encode([]map[string]any{pull("sha7")}) + case r.Method == http.MethodGet && r.URL.Path == "/search/issues": + fx.searches++ + fx.searchQuery = r.URL.Query().Get("q") + if fx.searchStatus != 0 { + http.Error(w, "search error", fx.searchStatus) + return + } + searchedAuthor := "" + var searchedRepos []string + for _, term := range strings.Fields(fx.searchQuery) { + switch { + case strings.HasPrefix(term, "author:"): + searchedAuthor = strings.TrimPrefix(term, "author:") + case strings.HasPrefix(term, "repo:"): + searchedRepos = append(searchedRepos, strings.TrimPrefix(term, "repo:")) + } + } + items := []map[string]any{} + for _, full := range searchedRepos { + name := strings.TrimPrefix(full, "acme/") + for _, pr := range fx.otherHistory[name] { + user, _ := pr["user"].(map[string]string) + if merged, _ := pr["merged_at"].(string); merged != "" && strings.EqualFold(user["login"], searchedAuthor) { + items = append(items, map[string]any{"number": pr["number"], "repository_url": "https://api.github.com/repos/" + full, "pull_request": map[string]any{}}) + break + } + } + } + json.NewEncoder(w).Encode(map[string]any{"total_count": len(items), "incomplete_results": false, "items": items}) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/acme/") && strings.HasSuffix(r.URL.Path, "/pulls") && r.URL.Path != "/repos/acme/widget/pulls" && r.URL.Query().Get("state") == "closed": + name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/repos/acme/"), "/pulls") + fx.otherLists = append(fx.otherLists, name) + history := fx.otherHistory[name] + if history == nil { + history = []map[string]any{} + } + json.NewEncoder(w).Encode(history) case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7": fetches++ if fetches == 1 && fx.getStatus != 0 { @@ -234,6 +281,7 @@ func newContributorLaneAPI(t *testing.T, fx *contributorLaneFixture) *httptest.S } _ = json.NewDecoder(r.Body).Decode(&payload) fx.lastComment = payload.Body + fx.allComments = append(fx.allComments, payload.Body) json.NewEncoder(w).Encode(map[string]any{"id": 1}) default: t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) @@ -275,7 +323,13 @@ func approvedVerdict(string, int, string) ContributorLaneVerdict { } func newContributorLaneEngine(apiURL string, policy ContributorLanePolicy, clock *contributorLaneClock, opts Options) *Engine { - client := hgithub.NewClient("token", "acme", []string{"widget"}, nil, apiURL) + return newContributorLaneEngineRepos(apiURL, []string{"widget"}, policy, clock, opts) +} + +// newContributorLaneEngineRepos is newContributorLaneEngine for a hive that +// manages repos (acme/<name>…); the PR under test still lives in acme/widget. +func newContributorLaneEngineRepos(apiURL string, repos []string, policy ContributorLanePolicy, clock *contributorLaneClock, opts Options) *Engine { + client := hgithub.NewClient("token", "acme", repos, nil, apiURL) client.SetAppBotLogin(testHiveAppBotLogin) opts.ContributorLanePolicy = func() ContributorLanePolicy { return policy } if opts.ContributorLaneVerdict == nil { @@ -888,6 +942,213 @@ func TestTrySweepContributorLanePRAutoPromotion(t *testing.T) { } } +// Regression for #14517: the clean-merge ratchet counts across every +// repository the hive manages by default, so a contributor trusted in the +// main repo is admitted on their first PR to a satellite repo; scope=repo +// keeps the old per-repo count; revert and sentinel evidence in any +// repository still blocks; a failed repo search degrades to the own-repo +// count instead of blocking the sweep. +func TestTrySweepContributorLanePRAutoPromotionScope(t *testing.T) { + cleanHistory := func(n int) []map[string]any { + history := make([]map[string]any, 0, n) + for i := 0; i < n; i++ { + history = append(history, mergedHistoryPR(contributorLaneTestAuthor, "fix: clean change")) + } + return history + } + hiveRepos := []string{"widget", "hive", "docs", "homebrew-hive"} + for _, tc := range []struct { + name string + scope string + own []map[string]any + other map[string][]map[string]any + searchStatus int + wantReason string + wantMerges int + wantSearches int + wantLists []string + wantComment string + }{ + { + name: "hive scope admits on first PR to a satellite repo", + own: nil, + other: map[string][]map[string]any{"hive": cleanHistory(9), "docs": cleanHistory(1)}, + wantMerges: 1, + wantSearches: 1, + wantLists: []string{"hive"}, + wantComment: "merged=5 scope=hive repos=widget:0,hive:5 -->", + }, + { + name: "hive scope sums clean merges across repos", + own: cleanHistory(2), + other: map[string][]map[string]any{"hive": cleanHistory(2), "docs": cleanHistory(1)}, + wantMerges: 1, + wantSearches: 1, + wantLists: []string{"hive", "docs"}, + wantComment: "merged=5 scope=hive repos=widget:2,hive:2,docs:1 -->", + }, + { + name: "hive scope skips repos without the author's merges", + own: cleanHistory(1), + other: map[string][]map[string]any{"hive": cleanHistory(2), "docs": cleanHistory(0), "homebrew-hive": {mergedHistoryPR("someone-else", "fix: theirs")}}, + wantReason: contributorLaneReasonClaimTier, + wantSearches: 1, + wantLists: []string{"hive"}, + }, + { + name: "hive scope blocks on a revert in another repo", + own: cleanHistory(2), + other: map[string][]map[string]any{"hive": append(cleanHistory(1), mergedHistoryPR(contributorLaneTestAuthor, "Revert \"fix: clean change\"")), "docs": cleanHistory(3)}, + wantReason: contributorLaneReasonClaimTier, + wantSearches: 1, + wantLists: []string{"hive"}, + }, + { + name: "hive scope blocks on a sentinel label in another repo", + own: cleanHistory(4), + other: map[string][]map[string]any{"docs": {mergedHistoryPR(contributorLaneTestAuthor, "fix: risky", defaultSentinelLabel)}}, + wantReason: contributorLaneReasonClaimTier, + wantSearches: 1, + wantLists: []string{"docs"}, + }, + { + name: "repo scope counts the PR's repository only", + scope: "repo", + own: cleanHistory(1), + other: map[string][]map[string]any{"hive": cleanHistory(9)}, + wantReason: contributorLaneReasonClaimTier, + wantSearches: 0, + }, + { + name: "repo scope still admits on own history", + scope: "repo", + own: cleanHistory(5), + other: map[string][]map[string]any{"hive": cleanHistory(9)}, + wantMerges: 1, + wantComment: "merged=5 scope=repo repos=widget:5 -->", + }, + { + name: "own repository meeting the threshold needs no search", + own: cleanHistory(5), + other: map[string][]map[string]any{"hive": cleanHistory(9)}, + wantMerges: 1, + wantComment: "merged=5 scope=hive repos=widget:5 -->", + }, + { + name: "search failure degrades to the PR's repository", + own: cleanHistory(1), + other: map[string][]map[string]any{"hive": cleanHistory(9)}, + searchStatus: http.StatusUnprocessableEntity, + wantReason: contributorLaneReasonClaimTier, + wantSearches: 1, + }, + } { + t.Run(tc.name, func(t *testing.T) { + fx := validContributorFixture() + fx.issueComments[0]["body"] = contributorClaimMarkerTier(contributorLaneTestAuthor, "contributor", contributorLaneTestHive, " tier=contributor verified=true") + fx.mergedHistory = tc.own + fx.otherHistory = tc.other + fx.searchStatus = tc.searchStatus + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.AutoPromoteAfterMergedPR = 5 + policy.AutoPromotionScope = tc.scope + clock := &contributorLaneClock{at: time.Date(2026, 10, 15, 13, 0, 0, 0, time.UTC)} + engine := newContributorLaneEngineRepos(api.URL, hiveRepos, policy, clock, Options{ContributorSoak: soakedTracker(clock)}) + event, reason, err := engine.trySweepContributorLanePR(context.Background(), "widget", "acme", "widget", 7, policy) + if err != nil { + t.Fatalf("err = %v", err) + } + if reason != tc.wantReason { + t.Fatalf("reason = %q, want %q", reason, tc.wantReason) + } + if fx.merges != tc.wantMerges { + t.Fatalf("merges = %d, want %d", fx.merges, tc.wantMerges) + } + if fx.searches != tc.wantSearches { + t.Fatalf("searches = %d, want %d (q=%q)", fx.searches, tc.wantSearches, fx.searchQuery) + } + if fx.searches > 0 { + for _, want := range []string{"is:pr", "is:merged", "author:" + contributorLaneTestAuthor, "repo:acme/hive", "repo:acme/docs", "repo:acme/homebrew-hive"} { + if !strings.Contains(fx.searchQuery, want) { + t.Fatalf("search query %q missing %q", fx.searchQuery, want) + } + } + if strings.Contains(fx.searchQuery, "repo:acme/widget") { + t.Fatalf("search query %q must not include the PR's own repository", fx.searchQuery) + } + } + if strings.Join(fx.otherLists, ",") != strings.Join(tc.wantLists, ",") { + t.Fatalf("other repos listed = %v, want %v", fx.otherLists, tc.wantLists) + } + if tc.wantMerges > 0 { + if event.Tier != contributorLaneTier || !strings.Contains(fx.lastComment, "auto-promoted after 5 clean merged PRs") { + t.Fatalf("event=%+v comment=%q", event, fx.lastComment) + } + where := "in this hive's repositories" + if tc.scope == "repo" { + where = "in this repository" + } + if !strings.Contains(fx.lastComment, where) { + t.Fatalf("merge comment %q should say %q", fx.lastComment, where) + } + } + if tc.wantComment != "" { + var auditComment string + for _, body := range fx.allComments { + if strings.HasPrefix(body, contributorAutoPromotionMarkerPrefix) { + auditComment = body + } + } + if !strings.Contains(auditComment, tc.wantComment) { + t.Fatalf("audit comment %q should contain %q", auditComment, tc.wantComment) + } + } + }) + } +} + +func TestContributorMergedHistoryHelpers(t *testing.T) { + h := contributorMergedHistory{HiveWide: true, Repos: []contributorRepoMerges{{Repo: "hive", Clean: 8}, {Repo: "docs", Clean: 1}}} + if got := h.repoBreakdown(); got != "hive:8,docs:1" { + t.Fatalf("repoBreakdown = %q", got) + } + if h.scopeName() != "hive" || (contributorMergedHistory{}).scopeName() != "repo" { + t.Fatalf("scopeName wrong: %q / %q", h.scopeName(), (contributorMergedHistory{}).scopeName()) + } + for _, tc := range []struct{ in, want string }{ + {"https://api.github.com/repos/HiveCommons/Docs", "hivecommons/docs"}, + {"https://api.github.com/repos/acme/widget/", "acme/widget"}, + {"", ""}, + {"https://api.github.com/repos/", ""}, + {"nonsense", ""}, + } { + if got := repoFromRepositoryURL(tc.in); got != tc.want { + t.Fatalf("repoFromRepositoryURL(%q) = %q, want %q", tc.in, got, tc.want) + } + } + for _, tc := range []struct { + scope string + want bool + }{{"", true}, {"hive", true}, {" HIVE ", true}, {"repo", false}, {" Repo ", false}} { + if got := (ContributorLanePolicy{AutoPromotionScope: tc.scope}).hiveWideAutoPromotion(); got != tc.want { + t.Fatalf("hiveWideAutoPromotion(%q) = %v, want %v", tc.scope, got, tc.want) + } + } + if contributorAutoPromotionWhere(true) != "in this hive's repositories" || contributorAutoPromotionWhere(false) != "in this repository" { + t.Fatal("contributorAutoPromotionWhere wording changed") + } + var nilEngine *Engine + if got := nilEngine.contributorMergedRepos(context.Background(), "acme", "widget", "bob"); got != nil { + t.Fatalf("nil engine repos = %v", got) + } + history, err := nilEngine.contributorCleanMergedHistory(context.Background(), "acme", "widget", "bob", 5, true) + if err != nil || history.Clean || history.Reason != "disabled" { + t.Fatalf("nil engine history = %+v err=%v", history, err) + } +} + func TestContributorLaneAdmitPathAndRegistryTierHelpers(t *testing.T) { if got := contributorLaneAdmitPath(contributorClaimMatch{RegistryTier: "trusted"}); got != contributorLaneReasonRegistryTrusted { t.Fatalf("admit path = %q, want %q", got, contributorLaneReasonRegistryTrusted) From ee746340941a8208365a16724de5f16fc0712a08 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Mon, 26 Oct 2026 23:55:15 -0400 Subject: [PATCH 2/2] fix(dashboard): drop auto_promote_after_merged from settings parity allowlist The contributor-lane auto-promotion scope help text now references the key, so the parity test requires the allowlist entry to go. Signed-off-by: Andy Anderson <andy@clubanderson.com> --- src/pkg/dashboard/settings_parity_allowlist.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index ee4efac904..536a284075 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -140,7 +140,6 @@ agents.<key>.variables.<key>.url # TODO #11854 agents.<key>.variables.<key>.value # TODO #11854 agents.github_api_hourly_cap # TODO #11854 auto_merge.allow_unprotected_base[] # TODO #11854 -auto_merge.contributor_tier.auto_promote_after_merged # contributor trust ratchet; yaml-only (#12839) auto_merge.human_merge_paths.<key> # TODO #11854 auto_merge.merge_forward_trusted_human[] # TODO #11854 auto_merge.no_ci_ok[] # TODO #11854