diff --git a/changelog.d/changed-hive-superseding-automerge.md b/changelog.d/changed-hive-superseding-automerge.md new file mode 100644 index 0000000000..37dd1d745e --- /dev/null +++ b/changelog.d/changed-hive-superseding-automerge.md @@ -0,0 +1 @@ +- Hive-authored superseding PRs (`Supersedes #N`, opened by the hive App) now auto-merge with no operator decision: a reviewer `requires_human` — security-sensitive included — is routed to the fixer instead of parking at `stage/085`, and only an unacknowledged sentinel finding, a hold, exhausted fix attempts, red CI after fixes or an unresolvable base conflict park it, each named in the 085 caption. New knob `auto_merge.hive_superseding.auto_merge` (default `true`). diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index f51a1ffaca..04eac946a7 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -2049,18 +2049,19 @@ func (b *boot) bootAgentsWith(deps bootAgentsDeps) { // its open-PR set and run on webhook events instead of listing /pulls. forgeOpenPRs := b.forgeStateOpenPRs() autoMergeOpts := automerge.Options{ - Logger: b.logger, - MergerAuthorizer: trustedMergerFunc(b.cfg), - HumanChangeRequests: review.DefaultHumanChangeRequests(), - TrustedAuthorizer: trustedAuthorFunc(b.cfg), - TrustedAuthorPolicy: trustedAuthorPolicyFunc(b.cfg), - ContributorLanePolicy: contributorLanePolicyFunc(b.cfg), - ContributorLaneVerdict: contributorLaneVerdictFunc(b.cfg, b.logger), - ContributorRegistryTier: contributorRegistryTierFunc(), - StageLabelPolicy: stageLabelPolicyFunc(b.cfg), - StageEngine: stageEngineOptions(b.cfg, b.logger), - SentinelLabel: func() string { return b.cfg.Sentinel.LabelOrDefault() }, - SweepTrigger: b.sweepTrigger, + Logger: b.logger, + MergerAuthorizer: trustedMergerFunc(b.cfg), + HumanChangeRequests: review.DefaultHumanChangeRequests(), + TrustedAuthorizer: trustedAuthorFunc(b.cfg), + TrustedAuthorPolicy: trustedAuthorPolicyFunc(b.cfg), + ContributorLanePolicy: contributorLanePolicyFunc(b.cfg), + ContributorLaneVerdict: contributorLaneVerdictFunc(b.cfg, b.logger), + ContributorRegistryTier: contributorRegistryTierFunc(), + StageLabelPolicy: stageLabelPolicyFunc(b.cfg), + StageEngine: stageEngineOptions(b.cfg, b.logger), + SentinelLabel: func() string { return b.cfg.Sentinel.LabelOrDefault() }, + HiveSupersedingAutoMerge: func() bool { return b.cfg.AutoMerge.HiveSuperseding.AutoMergeEnabled() }, + SweepTrigger: b.sweepTrigger, } if forgeOpenPRs != nil { autoMergeOpts.OpenPRs = forgeOpenPRs diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index e887e67799..394c7fb005 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -834,6 +834,7 @@ func runAutoMergeSweepIfDue(ctx context.Context, ghClient *github.Client, cfg *c } if cfg != nil { opts.SentinelLabel = func() string { return cfg.Sentinel.LabelOrDefault() } + opts.HiveSupersedingAutoMerge = func() bool { return cfg.AutoMerge.HiveSuperseding.AutoMergeEnabled() } if set, ok := cfg.AutoMerge.RequiredCheckSet(); ok { opts.RequiredChecks = set } @@ -2651,10 +2652,13 @@ func refreshReviewVerdicts(cfg *config.Config, logger *slog.Logger) { MaxPerspectivesPerPR: cfg.Review.MaxPerspectivesPerPR, Perspectives: reviewPerspectiveSet(cfg, logger), SelfAuthoredDecisionPolicy: cfg.Review.EffectiveSelfAuthoredDecisionPolicy(), - SensitivePaths: cfg.Security.SensitivePaths, - ModelStamps: reviewModelStamps(logger), - ExpectedHeads: cfg.ExpectedReviewHeads(), - MissingHeads: reviewMissingHeads(), + // Owner rule: the hive's superseding copies auto-merge; their + // reviewer findings go to the fixer, not to a person. + HiveSupersedingAutoMergeOff: !cfg.AutoMerge.HiveSuperseding.AutoMergeEnabled(), + SensitivePaths: cfg.Security.SensitivePaths, + ModelStamps: reviewModelStamps(logger), + ExpectedHeads: cfg.ExpectedReviewHeads(), + MissingHeads: reviewMissingHeads(), }, time.Now().UTC()) if err != nil { if !os.IsNotExist(err) { diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index de75260387..be395258d7 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -1021,6 +1021,61 @@ recorded trusted decision on a PR's head (the tracker's Approve, or any what lifts the gate for that PR; closing the other ends it ([#15810](https://github.com/hivecommons/hive/issues/15810)). +### Hive-authored superseding PRs auto-merge + +Owner rule (@clubanderson): *"if a pr is superseded by a pr that a hive +agent creates, it should auto merge"* — *"the only exception would be if +this is sentinel or some other emergent problem with the pr."* + +A **hive superseding PR** is a PR the hive App itself authored +(`@hivecommons-hive[bot]`) whose body declares `Supersedes #N` — the PR a +takeover, close-first adoption or re-author lead opens to carry a +contributor's or bot's change. `github.IsHiveSupersedingPR` / +`github.HiveSupersedingPR` detect it; `PullRequest.Supersedes` carries the +number. Twice in one morning such PRs (#15649, #15646) parked at +`stage/085-needs-decision` on a reviewer's security-sensitive +`requires_human` and the owner had to click approve for work the hive had +already decided to carry. Under this rule they do not: + +- **Reviewer findings go to the fixer.** On a hive superseding PR the + aggregate (`review.hiveSupersedingFixRoute`) turns a `requires_human` — + a risk-class decision question, a security-sensitive finding, an + unresolved escalation — into `changes_requested` with the reason + `hive-authored superseding PR: reviewer requires_human routed to the fixer; auto-merges once CI and review are clean`; the fixer + addresses it and the swarm re-reviews, exactly like any other finding. + A `reject` is not converted: it is an emergent problem with the PR. The + stage engine captions the head *"hive-authored superseding PR — + auto-merging once CI/review are clean"* (lane reason + `hive-superseder:fixer`) rather than "needs your decision", and the + reviewer prompts say so (`hiveSupersedingGuidance`). +- **Green and clean merges with no decision.** Once CI is green and the + review has no open findings the PR follows the hive-authored admission + path (`stage/080` → merge). The superseded PR is closed as superseded by + the existing writeback (`Superseded by #N`) once it merges, as before. +- **The only exceptions are the hard stops**, computed in one place + (`automerge.hiveSupersederHardStop`) and named in the 085 caption + (`hive-superseder-hard-stop:`): + - `sentinel-unacknowledged` — the sentinel label is on and nobody has + acknowledged its finding (`sentinel_acknowledged` in the review + evidence bundle; an acknowledged sentinel, as on #15650, is not a + stop); + - `hold` — a `hold` / decision-class label or a repo/global hold; + - `fix-attempts-exhausted` — the fixer spent its cycle cap on the + reviewer's findings; reported as `ci-red-after-fixes` when CI is + still red, `base-conflict-unresolved` when the head still conflicts; + - `base-conflict-unresolved` — the hive's rebase-resolve episode + already failed twice. + + A pending check, a first conflict or an ordinary reviewer finding is + never a stop. The tracker row reads *"The hive's superseding PR would + auto-merge (owner rule), but "*, and *Let hive decide* answers + recommend-only, naming the stop (`delegatedecision.RuleHiveSuperseder`); + without a stop it releases the PR under the same rule. + +`auto_merge.hive_superseding.auto_merge: false` turns the rule off and +restores the previous behaviour (a `requires_human` parks the superseding +PR at 085 like any hive-authored PR). + ### Empty-diff PRs of the hive's own A PR of the hive's own (the App's, or an adoption it opened) whose diff diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 779199ce78..352b79ab51 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -445,6 +445,7 @@ advanced into the merge path. | `auto_merge.native_merge_queue.repos` | unset (every watched repo once enabled) | `owner/repo` allow-list for the hand-off, matched case-insensitively. | | `auto_merge.native_merge_queue.skip_current_base_gate` | `false` | Explicitly lets a queue-enabled base bypass the `auto_merge.require_current_base` gate and the `behind` update-branch, because the merge group re-tests the merged result and a pushed head drops the PR from the queue. Off keeps both gates in force on queue bases. | | `auto_merge.native_merge_queue.probe_ttl` | `30m` | How long one base branch's `isMergeQueueEnabled` GraphQL answer is cached before re-reading. | +| `auto_merge.hive_superseding.auto_merge` | `true` | Owner rule: a PR the hive App itself opened to supersede another PR (`Supersedes #N` in its body — takeover, close-first adoption, re-author) auto-merges with no operator decision. A reviewer `requires_human`, security-sensitive included, is routed to the fixer as `changes_requested` instead of parking at `stage/085`; the head merges through the hive-authored lane once CI and review are clean. The only stops are an unacknowledged sentinel finding, a hold, exhausted fix attempts (CI still red / base still conflicting), or a conflict the hive already failed to rebase twice — each named in the 085 caption as `hive-superseder-hard-stop:`. `false` restores the old park. See [hive-merge.md](hive-merge.md#hive-authored-superseding-prs-auto-merge). | | `auto_merge.squash_only` | unset (no repo) | Repo list (`owner/repo`) whose branch policy forbids merge commits. Elsewhere, a `role/trusted` PR whose head mixes the contributor's commits with App-linked, App-signed ones (the hive's own in-place adoption fixes), every commit self-signed, is labelled `merge-method/merge` and merged with a merge commit instead of parking at `stage/085` as `adoption-stalled:hive-signoff-attribution`; a listed repo keeps squash-only policy and re-homes an in-place adoption to an App-authored superseder instead (#13975). | | `auto_merge.credit_issue_authors` | `true` | Append `Co-authored-by: ` for the human authors of the issues a PR closes (`Fixes|Closes|Resolves #N`) to the squash (or merge) commit message on every hive-performed merge, so reporters land on the contributor graph when an external clanker fixed their issue. Bots, the PR author and logins already credited on the branch are skipped; the logins are recorded as `issue_authors=` on the merge audit entry and in review evidence. One cached `GET /issues/{n}` per newly referenced issue. `false` leaves GitHub's default squash message untouched (#14581). | | `auto_merge.bot_takeover.enabled` | `true` | When `github-actions[bot]` is in `auto_merge.trusted_bot_authors`, re-author its same-repo PRs whose required `pull_request` checks can never run (the bot opened them with a workflow `GITHUB_TOKEN`). After the head is older than both `min_head_age` and 30 minutes with no `pull_request` run, the App pushes the same change as one signed-off commit to `hive/takeover-`, opens a PR with the original title/body plus `Supersedes #`, comments `Superseded by #N` on the bot PR and closes it. One attempt per bot head SHA. See [hive-merge.md](hive-merge.md#github-actionsbot-pr-takeover). | diff --git a/src/docs/review-swarm.md b/src/docs/review-swarm.md index 296638500a..b53beea683 100644 --- a/src/docs/review-swarm.md +++ b/src/docs/review-swarm.md @@ -96,6 +96,8 @@ Aggregation rules are deterministic: 6. Every delivered perspective approving while some the PR is owed have not reported yields `incomplete`: not merge-eligible, not a human hold, with a reason naming the missing perspectives (`review coverage incomplete: missing docs-currency`). An incomplete head stays in the dispatcher: only the missing perspectives are re-asked (under `pending_ttl` / `max_redispatch`), never the ones whose reports already exist. The exception is a head that already holds a settled non-approve verdict (`requires_human`, `changes_requested` or `reject`): an incomplete re-review of the same head does not replace it. The artifact keeps the prior decision, its findings or question and its `recorded_at`, so the dispatcher never sees `incomplete` for that head — a `requires_human` head keeps taking the human-hold path and stays at 085, and a `changes_requested` or `reject` head stays on the fix path (rather than dropping back to 050 to re-ask the missing perspectives) until a complete replacement review lands. When the stale entries expire under `pending_ttl`, the whole perspective set is asked again for that head, not just the missing ones (hivecommons/hive#12878). Before this state existed a reviewer kick that died after its peers had reported left the head on a `requires_human` hold that no re-dispatch could clear (hivecommons/hive#12045). 7. Any other non-unanimous result requires human review. +One exception to rules 2–3: on a **hive superseding PR** (the App's own PR declaring `Supersedes #N`, `PerspectiveReport.hive_superseding`) a `requires_human` — security-sensitive included — becomes `changes_requested` and enters the fix cycle, because the owner's rule is that such PRs auto-merge with no operator decision; only the fix cap, a `reject`, or the stage engine's hard stops (sentinel, hold, red CI, unresolvable conflict) hand it to a person. `auto_merge.hive_superseding.auto_merge: false` turns this off. See [hive-merge.md](hive-merge.md#hive-authored-superseding-prs-auto-merge). + Out-of-scope findings alone are normalized to an approving perspective for aggregation and confidence. They remain in the structured record, but they never lower the verdict or the 0–5 confidence score for the PR. The default human threshold is `high`. Review-triggered fix cycles use the same cap value as the escalation re-engagement circuit breaker (`escalation.MaxReEngagements`) so bot loops remain bounded. diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index d80a693a69..6a7e3f91d2 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:4936-4946`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:4942-4952`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/pkg/config/automerge_merge_train_test.go b/src/pkg/config/automerge_merge_train_test.go index d63ec89cef..c0b4462657 100644 --- a/src/pkg/config/automerge_merge_train_test.go +++ b/src/pkg/config/automerge_merge_train_test.go @@ -26,3 +26,20 @@ func TestMergeTrainAutoMergeConfigDefaults(t *testing.T) { }) } } + +func TestHiveSupersedingAutoMergeEnabledDefaultsOn(t *testing.T) { + on, off := true, false + for _, tc := range []struct { + name string + cfg HiveSupersedingAutoMergeConfig + want bool + }{ + {"default", HiveSupersedingAutoMergeConfig{}, true}, + {"explicit on", HiveSupersedingAutoMergeConfig{AutoMerge: &on}, true}, + {"explicit off", HiveSupersedingAutoMergeConfig{AutoMerge: &off}, false}, + } { + if got := tc.cfg.AutoMergeEnabled(); got != tc.want { + t.Fatalf("%s: AutoMergeEnabled = %v want %v", tc.name, got, tc.want) + } + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 3f7edac76d..5245bda3f7 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -8336,6 +8336,10 @@ type AutoMergeConfig struct { // opt-in per repo: a hive that never sets it keeps the pre-queue // behaviour, including the `merge-queue-required` park. NativeMergeQueue NativeMergeQueueAutoMergeConfig `yaml:"native_merge_queue,omitempty" json:"native_merge_queue,omitempty"` + // HiveSuperseding is the owner's rule for the hive's own superseding + // copies of other PRs (@clubanderson: "if a pr is superseded by a pr + // that a hive agent creates, it should auto merge"). Default ON. + HiveSuperseding HiveSupersedingAutoMergeConfig `yaml:"hive_superseding,omitempty" json:"hive_superseding,omitempty"` } // NativeMergeQueueAutoMergeConfig is auto_merge.native_merge_queue.*. @@ -8389,6 +8393,26 @@ func (n NativeMergeQueueAutoMergeConfig) EffectiveProbeTTL() time.Duration { return n.ProbeTTL } +// HiveSupersedingAutoMergeConfig is auto_merge.hive_superseding.*. +type HiveSupersedingAutoMergeConfig struct { + // AutoMerge: a PR the hive App authored that declares "Supersedes #N" + // auto-merges with no operator decision. A reviewer's requires_human + // — a risk-class question or a security-sensitive finding included — + // is routed to the fixer and re-reviewed like any other finding; the + // PR parks at stage 085 only for a sentinel finding nobody has + // acknowledged or an emergent hard-stop (fix attempts exhausted, a + // hold, CI red after fixes, an unresolvable base conflict). nil/unset + // means ON; `auto_merge: false` restores the ordinary hive-authored + // routing, where such findings wait for a person. + AutoMerge *bool `yaml:"auto_merge,omitempty" json:"auto_merge,omitempty"` +} + +// AutoMergeEnabled reports the auto_merge.hive_superseding.auto_merge +// switch; unset is on. +func (h HiveSupersedingAutoMergeConfig) AutoMergeEnabled() bool { + return h.AutoMerge == nil || *h.AutoMerge +} + // MergeTrainAutoMergeConfig is auto_merge.merge_train.*. type MergeTrainAutoMergeConfig struct { // Enabled turns the train on. nil/unset means ON; `enabled: false` diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index 60304184f7..ba4d22bcaa 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -723,7 +723,8 @@ "contributor_lane": {}, "contributor_tier": {}, "merge_train": {}, - "native_merge_queue": {} + "native_merge_queue": {}, + "hive_superseding": {} }, "decisions": { "delegate": {} diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 0c2a9f04a5..f3a55f7094 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -884,6 +884,15 @@ func (s *Server) sentinelLabel() string { return s.deps.Config.Sentinel.LabelOrDefault() } +// hiveSupersedingAutoMerge is the live hive-superseding auto-merge switch +// (config.HiveSupersedingAutoMergeConfig; nil config = on). +func (s *Server) hiveSupersedingAutoMerge() bool { + if s == nil || s.deps == nil || s.deps.Config == nil { + return true + } + return s.deps.Config.AutoMerge.HiveSuperseding.AutoMergeEnabled() +} + func (s *Server) handleHistory(w http.ResponseWriter, r *http.Request) { evalHistoryResponse(w, r, s.historyPayload()) } diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index 996d25cd49..0a80595514 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -679,6 +679,10 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb } in.SentinelReason = strings.TrimSpace(req.SentinelReason) lowerReason := strings.ToLower(reason) + if in.Kind == delegatedecision.KindPR && in.HiveAuthored && s.hiveSupersedingAutoMerge() { + in.HiveSuperseding = ghpkg.HiveSupersedingPR(true, in.Body) + in.HiveSupersederHardStop = stagelabels.HiveSupersederHardStopReason(reason) + } in.AdoptionStalled = strings.HasPrefix(lowerReason, stagelabels.LaneReasonAdoptionStalledPrefix) if in.Kind == delegatedecision.KindPR && !in.HiveAuthored { in.AdoptionGraceElapsed = s.delegatedAdoptionGraceElapsed(repoFull, number) diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 473faf83c6..fa1b538a81 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -164,6 +164,7 @@ auto_merge.native_merge_queue.enabled # native merge queue hand-off opt-in (#151 auto_merge.native_merge_queue.probe_ttl # merge-queue probe cache TTL (#15198); yaml-only auto_merge.native_merge_queue.repos[] # native merge queue per-repo allow-list (#15198); yaml-only auto_merge.native_merge_queue.skip_current_base_gate # explicit current-base bypass on queue bases (#15198); yaml-only +auto_merge.hive_superseding.auto_merge # hive-authored superseding PRs auto-merge without an operator decision; yaml-only auto_merge.no_ci_ok[] # TODO #11854 auto_merge.repos..required_checks[] # TODO #11854 auto_merge.require_current_base[] # current-base gate per-repo "on" override, written by the Repos tab (#15335) diff --git a/src/pkg/dashboard/stage_tracker_decision_hive_superseder_test.go b/src/pkg/dashboard/stage_tracker_decision_hive_superseder_test.go new file mode 100644 index 0000000000..bd23af89ae --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_decision_hive_superseder_test.go @@ -0,0 +1,19 @@ +package dashboard + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// The hive's superseding PR parked by its one exception class: the tracker +// names the stop rather than "needs your decision". +func TestDecisionForPRHiveSupersederHardStopNamesReason(t *testing.T) { + it := StageTrackerItem{Repo: "hivecommons/hive", Number: 15649, Kind: "pr", Stage: 85, Head: "abc1234", + Reason: stagelabels.LaneReasonHiveSupersederHardStopPrefix + stagelabels.HiveSupersederHardStopSentinel} + d := decisionForPR(it, nil, "", false) + if d.AskedBy != decisionAskedByLane || !strings.Contains(d.Question, "would auto-merge") || !strings.Contains(d.Question, stagelabels.HiveSupersederHardStopProse(stagelabels.HiveSupersederHardStopSentinel)) { + t.Fatalf("decision = %+v", d) + } +} diff --git a/src/pkg/dashboard/stage_tracker_decision_pr.go b/src/pkg/dashboard/stage_tracker_decision_pr.go index b0873756de..7d09211323 100644 --- a/src/pkg/dashboard/stage_tracker_decision_pr.go +++ b/src/pkg/dashboard/stage_tracker_decision_pr.go @@ -38,6 +38,7 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel // supersedes) after the fixer's two rebase-resolve attempts failed. rebaseFailedTwice := lower == stagelabels.LaneReasonRebaseFailedTwice || (adoptionStalled && adoptionLane == stagelabels.LaneReasonRebaseFailedTwice) reviewerDeferred := lower == stageengine.StageReasonVerdictRequiresHuman || lower == stageengine.StageReasonDecisionRequested + hiveSupersederStop := stagelabels.HiveSupersederHardStopReason(base) // WHAT it is waiting on: the question, most specific source first. A // reviewer's own question is quoted verbatim — it is the text the @@ -50,6 +51,12 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel d.Blocker = strings.TrimSpace(it.Unauthorized) delegateOK, delegateWhy = false, decisionWhyNoPermission approveOK, approveWhy = false, decisionWhyApproveNoGrant + case hiveSupersederStop != "": + // The owner's superseder rule (hive-authored superseding PRs + // auto-merge with no decision) was overridden by its one exception + // class; the caption names which stop, never "needs your decision". + d.AskedBy = decisionAskedByLane + d.Question = "The hive's superseding PR would auto-merge (owner rule), but " + stagelabels.HiveSupersederHardStopProse(hiveSupersederStop) + ". Clear that stop and the lane merges it on its next pass, or close it?" case verdict != nil && strings.TrimSpace(verdict.DecisionQuestion) != "": d.AskedBy = decisionAskedByReviewer d.Question = strings.TrimSpace(verdict.DecisionQuestion) diff --git a/src/pkg/delegatedecision/hive_superseder_test.go b/src/pkg/delegatedecision/hive_superseder_test.go new file mode 100644 index 0000000000..4787220dfa --- /dev/null +++ b/src/pkg/delegatedecision/hive_superseder_test.go @@ -0,0 +1,42 @@ +package delegatedecision + +import ( + "strings" + "testing" +) + +// TestDecideHiveSuperseder: the owner's rule in the delegate — the hive's +// superseding PR is released with no decision; a hard stop is the one +// thing that holds it, and the recommendation names it. +func TestDecideHiveSuperseder(t *testing.T) { + base := Input{Repo: "hivecommons/hive", Kind: KindPR, Number: 15649, Author: "hivecommons-hive[bot]", + Body: "Supersedes #15646", HiveAuthored: true, TrustedAuthor: true, HiveSuperseding: true, CIGreen: true, + Reasons: []string{"verdict:requires_human"}} + + d := Decide(base) + if d.Verdict != VerdictApprove || d.Rule != RuleHiveSuperseder || !strings.Contains(d.Text, "auto-merging once CI/review are clean") { + t.Fatalf("decision = %+v, want release under the superseder rule", d) + } + + stopped := base + stopped.HiveSupersederHardStop = "sentinel-unacknowledged" + stopped.SentinelAlert = true + d = Decide(stopped) + if d.Verdict != VerdictRecommendOnly || d.Rule != RuleHiveSuperseder || !strings.Contains(d.Text, "sentinel-unacknowledged") { + t.Fatalf("decision = %+v, want recommend-only naming the stop", d) + } + + // An unacknowledged sentinel with no stop token recorded still defers + // to the sentinel rules rather than releasing. + sentinel := base + sentinel.SentinelAlert = true + if d = Decide(sentinel); d.Rule == RuleHiveSuperseder { + t.Fatalf("decision = %+v, sentinel must not be released by the superseder rule", d) + } + + plain := base + plain.HiveSuperseding = false + if d = Decide(plain); d.Rule == RuleHiveSuperseder { + t.Fatalf("decision = %+v, a non-superseding PR takes the ordinary rules", d) + } +} diff --git a/src/pkg/delegatedecision/policy.go b/src/pkg/delegatedecision/policy.go index ae0c2662fe..d63b04ba65 100644 --- a/src/pkg/delegatedecision/policy.go +++ b/src/pkg/delegatedecision/policy.go @@ -301,6 +301,13 @@ type Input struct { ReviewerRequiresHuman bool ReviewerFinding string SecurityFinding bool + // HiveSuperseding: the hive App's own superseding copy of another PR + // (hive-authored, body declares `Supersedes #N`). The owner's rule is + // that it auto-merges with no operator decision; HiveSupersederHardStop + // is the one stagelabels.HiveSupersederHardStop* token that parked it + // anyway ("" when the park is an ordinary one the rule overrides). + HiveSuperseding bool + HiveSupersederHardStop string } // CIRed reports a head that is not green because a check failed (or none @@ -653,6 +660,9 @@ func decidePR(in Input) Decision { if OwnerOnly(in) { return ownerOnlyDecision(in, "secrets, PATs and org permissions are the owner's alone") } + if d, ok := decideHiveSuperseder(in, ref); ok { + return d + } if in.SentinelAlert { if !in.TrustedAuthor { return recommendOnly("sentinel-untrusted", "a sentinel alert on a PR from an author without write access is a human review", "review the sentinel finding on "+ref+" and remove the sentinel label if intended") @@ -785,6 +795,33 @@ func decideAdoptedByHive(in Input, ref string) (Decision, bool) { }, true } +// RuleHiveSuperseder is the owner's superseder rule: "if a pr is superseded +// by a pr that a hive agent creates, it should auto merge" — the only +// exception being the sentinel or some other emergent problem with the PR. +const RuleHiveSuperseder = "hive-superseder-automerge" + +// decideHiveSuperseder applies RuleHiveSuperseder to the hive's own +// superseding PR. Without a hard stop the PR is released (the lane merges +// it once CI/review are clean; an ordinary reviewer finding is the fixer's, +// not a decision). With a hard stop the delegate only recommends, naming +// the stop, because that is exactly the case the owner reserved. +func decideHiveSuperseder(in Input, ref string) (Decision, bool) { + if in.Kind != KindPR || !in.HiveSuperseding { + return Decision{}, false + } + if stop := strings.TrimSpace(in.HiveSupersederHardStop); stop != "" { + return recommendOnly(RuleHiveSuperseder, + "the hive's superseding PR auto-merges by the owner's rule, except for the sentinel or an emergent problem — and this one has one: "+stop, + "look at "+ref+" ("+stop+"): clear the stop (acknowledge the sentinel finding, release the hold, or fix the head) and the lane merges it; else close it"), true + } + if in.SentinelAlert { + return Decision{}, false + } + return releasePR(RuleHiveSuperseder, + "approve "+ref+": hive-authored superseding PR — auto-merging once CI/review are clean (owner rule: a PR the hive creates to supersede another auto-merges; reviewer findings go to the fixer)", + "the owner's rule: a PR the hive creates to supersede another auto-merges with no operator decision; only the sentinel or an emergent problem (hold, exhausted fixes, red CI, unresolvable conflict) parks it"), true +} + // RuleOnePRPerIssue: the merge queue carries one PR per issue; the one it // held as a duplicate closes as superseded by the one it kept. const RuleOnePRPerIssue = "one-pr-per-issue" diff --git a/src/pkg/github/automerge/automerge_hive_superseder.go b/src/pkg/github/automerge/automerge_hive_superseder.go new file mode 100644 index 0000000000..839ca1e927 --- /dev/null +++ b/src/pkg/github/automerge/automerge_hive_superseder.go @@ -0,0 +1,90 @@ +package automerge + +// The owner's superseder rule (@clubanderson): "if a pr is superseded by a +// pr that a hive agent creates, it should auto merge" — "the only exception +// would be if this is sentinel or some other emergent problem with the pr". +// A hive-authored superseding PR therefore never parks at 085 on an +// ordinary reviewer requires_human (the aggregate routes those to the +// fixer, review.hiveSupersedingFixRoute); hiveSupersederHardStop is the +// whole list of what does park it, and the 085 caption names which. + +import ( + "strings" + + "github.com/hivecommons/hive/pkg/authorkind" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hiveSupersedingPR reports whether obs is the hive App's own superseding +// copy of another PR under the (default-on) auto_merge.hive_superseding +// switch: hive-authored and declaring "Supersedes #N" in its body. +func (c *Engine) hiveSupersedingPR(obs stageObservation) bool { + if c != nil && c.hiveSupersedingAutoMerge != nil && !c.hiveSupersedingAutoMerge() { + return false + } + hiveAuthored := obs.AuthorKind == authorkind.Hive || obs.Lane == stageLaneSelf + return hgithub.HiveSupersedingPR(hiveAuthored, obs.Body) +} + +// sentinelAcknowledgedFor returns who acknowledged the sentinel's findings +// on the head ("" when nobody has): the configured hook, else the review +// evidence bundle's newest sentinel_acknowledged human action. +func (c *Engine) sentinelAcknowledgedFor(repo string, number int, head string) string { + if c != nil && c.sentinelAcknowledgedBy != nil { + return strings.TrimSpace(c.sentinelAcknowledgedBy(repo, number, head)) + } + if strings.TrimSpace(head) == "" { + return "" + } + b, err := hgithub.LoadReviewEvidence(hgithub.ReviewEvidencePath("", repo, number, head)) + if err != nil || b == nil { + return "" + } + return strings.TrimSpace(b.SentinelAcknowledgedBy()) +} + +// hiveSupersederHardStop is the one exception list for a hive-authored +// superseding PR. It returns the stagelabels.HiveSupersederHardStop* token +// and true when the PR must park at 085: +// +// - the sentinel has a finding on the PR (its label is on) and nobody +// has acknowledged it (sentinelAckBy == ""); +// - a hold is set (`hold`, `do-not-merge/*`, a repo/global hold); +// - the fixer's attempts are exhausted (FixCycleCapReached), reported as +// CI red / base conflict when that is what is still wrong, else as +// fix attempts exhausted; +// - the base conflict is one the hive already failed to resolve +// (rebase-failed-twice). +// +// An ordinary reviewer finding, a pending check or a conflict the fixer has +// not yet been asked to rebase is NOT a hard stop: those are the fixer's. +func hiveSupersederHardStop(e stagelabels.Evidence, verdict ContributorLaneVerdict, sentinelAckBy string) (reason string, ok bool) { + switch { + case e.Sentinel && strings.TrimSpace(sentinelAckBy) == "": + return stagelabels.HiveSupersederHardStopSentinel, true + case len(e.Holds) > 0 || e.Hold != nil: + return stagelabels.HiveSupersederHardStopHold, true + case verdict.FixCycleCapReached && e.Checks.Known && len(e.Checks.Red) > 0: + return stagelabels.HiveSupersederHardStopCIRed, true + case verdict.FixCycleCapReached && e.Conflict: + return stagelabels.HiveSupersederHardStopConflict, true + case verdict.FixCycleCapReached: + return stagelabels.HiveSupersederHardStopFixExhausted, true + case e.Conflict && conflictUnresolvable(e): + return stagelabels.HiveSupersederHardStopConflict, true + } + return "", false +} + +// conflictUnresolvable says the conflict already defeated the hive's +// rebase-resolve episode (both attempts spent). +func conflictUnresolvable(e stagelabels.Evidence) bool { + for _, r := range []string{e.LaneReason, e.CauseReason} { + r = strings.TrimSpace(r) + if r == stagelabels.LaneReasonRebaseFailedTwice || strings.HasSuffix(r, stagelabels.LaneReasonAdoptionStalledPrefix+stagelabels.LaneReasonRebaseFailedTwice) { + return true + } + } + return false +} diff --git a/src/pkg/github/automerge/automerge_hive_superseder_test.go b/src/pkg/github/automerge/automerge_hive_superseder_test.go new file mode 100644 index 0000000000..c308cf1f86 --- /dev/null +++ b/src/pkg/github/automerge/automerge_hive_superseder_test.go @@ -0,0 +1,90 @@ +package automerge + +import ( + "testing" + + "github.com/hivecommons/hive/pkg/authorkind" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// TestHiveSupersederHardStop: the owner's exception list, one branch each — +// and the ordinary cases (a reviewer finding, a pending check, a first +// conflict, an acknowledged sentinel) that are NOT stops. +func TestHiveSupersederHardStop(t *testing.T) { + cap := ContributorLaneVerdict{FixCycleCapReached: true} + cases := []struct { + name string + e stagelabels.Evidence + verdict ContributorLaneVerdict + ackBy string + want string + }{ + {"sentinel unacknowledged", stagelabels.Evidence{Sentinel: true}, ContributorLaneVerdict{}, "", stagelabels.HiveSupersederHardStopSentinel}, + {"sentinel acknowledged", stagelabels.Evidence{Sentinel: true}, ContributorLaneVerdict{}, "clubanderson", ""}, + {"hold label", stagelabels.Evidence{Holds: []string{"hold"}}, ContributorLaneVerdict{}, "", stagelabels.HiveSupersederHardStopHold}, + {"hold provenance", stagelabels.Evidence{Hold: &stagelabels.HoldProvenance{By: "hive"}}, ContributorLaneVerdict{}, "", stagelabels.HiveSupersederHardStopHold}, + {"fix exhausted, CI red", stagelabels.Evidence{Checks: stagelabels.CheckSummary{Known: true, Red: []string{"unit"}}}, cap, "", stagelabels.HiveSupersederHardStopCIRed}, + {"fix exhausted, conflict", stagelabels.Evidence{Conflict: true}, cap, "", stagelabels.HiveSupersederHardStopConflict}, + {"fix exhausted", stagelabels.Evidence{Verdict: stagelabels.VerdictRequiresHuman}, cap, "", stagelabels.HiveSupersederHardStopFixExhausted}, + {"rebase failed twice", stagelabels.Evidence{Conflict: true, LaneReason: stagelabels.LaneReasonRebaseFailedTwice}, ContributorLaneVerdict{}, "", stagelabels.HiveSupersederHardStopConflict}, + {"adoption-stalled rebase failed twice", stagelabels.Evidence{Conflict: true, CauseReason: stagelabels.LaneReasonAdoptionStalledPrefix + stagelabels.LaneReasonRebaseFailedTwice}, ContributorLaneVerdict{}, "", stagelabels.HiveSupersederHardStopConflict}, + {"first conflict is the fixer's", stagelabels.Evidence{Conflict: true}, ContributorLaneVerdict{}, "", ""}, + {"reviewer requires_human is the fixer's", stagelabels.Evidence{Verdict: stagelabels.VerdictRequiresHuman, DecisionFinding: "security"}, ContributorLaneVerdict{HiveAuthored: true}, "", ""}, + {"red CI before fixes is the fixer's", stagelabels.Evidence{Checks: stagelabels.CheckSummary{Known: true, Red: []string{"unit"}}}, ContributorLaneVerdict{}, "", ""}, + {"sentinel beats hold", stagelabels.Evidence{Sentinel: true, Holds: []string{"hold"}}, cap, "", stagelabels.HiveSupersederHardStopSentinel}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, ok := hiveSupersederHardStop(tc.e, tc.verdict, tc.ackBy) + if got != tc.want || ok != (tc.want != "") { + t.Fatalf("hiveSupersederHardStop = %q,%v want %q", got, ok, tc.want) + } + }) + } +} + +// TestEngineHiveSupersedingPR: hive-authored + `Supersedes #N` under the +// (default-on) knob; off when the knob is off, a contributor wrote it, or +// the body does not declare a supersession. +func TestEngineHiveSupersedingPR(t *testing.T) { + body := "Supersedes #15646\n\nRe-authored from the contributor's branch." + off := false + cases := []struct { + name string + c *Engine + obs stageObservation + want bool + }{ + {"hive author kind", &Engine{}, stageObservation{AuthorKind: authorkind.Hive, Body: body}, true}, + {"self lane", &Engine{}, stageObservation{Lane: stageLaneSelf, Body: body}, true}, + {"nil engine defaults on", nil, stageObservation{AuthorKind: authorkind.Hive, Body: body}, true}, + {"contributor", &Engine{}, stageObservation{AuthorKind: authorkind.Clanker, Body: body}, false}, + {"no marker", &Engine{}, stageObservation{AuthorKind: authorkind.Hive, Body: "Fixes #1"}, false}, + {"knob off", &Engine{hiveSupersedingAutoMerge: func() bool { return off }}, stageObservation{AuthorKind: authorkind.Hive, Body: body}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := tc.c.hiveSupersedingPR(tc.obs); got != tc.want { + t.Fatalf("hiveSupersedingPR = %v want %v", got, tc.want) + } + }) + } +} + +func TestEngineSentinelAcknowledgedForUsesHook(t *testing.T) { + c := &Engine{sentinelAcknowledgedBy: func(repo string, number int, head string) string { + if repo == "hivecommons/hive" && number == 15650 && head == "abc" { + return " clubanderson " + } + return "" + }} + if got := c.sentinelAcknowledgedFor("hivecommons/hive", 15650, "abc"); got != "clubanderson" { + t.Fatalf("ack = %q", got) + } + if got := c.sentinelAcknowledgedFor("hivecommons/hive", 15650, "def"); got != "" { + t.Fatalf("ack = %q, want none", got) + } + if got := (&Engine{}).sentinelAcknowledgedFor("hivecommons/hive", 15650, ""); got != "" { + t.Fatalf("empty head ack = %q", got) + } +} diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index 5548bdd1b0..2213c5ab02 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -414,6 +414,10 @@ func (c *Engine) humanEvidence(ctx context.Context, tracker *StageTracker, key s e.Sentinel = hasLabelFold(obs.Labels, sentinel) summary, known := c.headChecks(ctx, tracker, key, obs, now) e.Checks = stagelabels.CheckSummary{Total: summary.Total, Green: summary.Green, Pending: summary.Pending, Red: summary.Red, Known: known} + if c.hiveSupersedingPR(obs) { + e.HiveSuperseder = true + e.HiveSupersederHardStop, _ = hiveSupersederHardStop(e, contributorVerdict, c.sentinelAcknowledgedFor(obs.Owner+"/"+obs.Repo, obs.Number, obs.HeadSHA)) + } switch summary.DCO { case 1: e.DCO = stagelabels.DCOYes diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index f924124ebd..9849c56cb7 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -175,6 +175,14 @@ type Options struct { // skip distinctly so operators can tell a sentinel block from an ordinary // hold in tick stats. SentinelLabel func() string + // HiveSupersedingAutoMerge is the live auto_merge.hive_superseding.auto_merge + // switch (owner rule: the hive's superseding copy of another PR + // auto-merges with no operator decision). nil means on. + HiveSupersedingAutoMerge func() bool + // SentinelAcknowledgedBy returns the person whose approval acknowledged + // the sentinel's findings on repo#number@head ("" when none stands), + // for the superseder hard-stop; nil reads the review evidence bundle. + SentinelAcknowledgedBy func(repo string, number int, head string) string // MinHeadAge is the youngest PR head commit age the sweep may merge when // the required-check set is not config-declared and fully green. MinHeadAge time.Duration @@ -322,6 +330,8 @@ type Engine struct { contributorSoak *ContributorSoakTracker headFirstSeen *HeadFirstSeenTracker sentinelLabel func() string + hiveSupersedingAutoMerge func() bool + sentinelAcknowledgedBy func(repo string, number int, head string) string minHeadAge time.Duration now func() time.Time evaluatedHeadsMu sync.Mutex @@ -430,6 +440,8 @@ func New(transport Transport, opts Options) *Engine { contributorSoak: opts.ContributorSoak, headFirstSeen: opts.HeadFirstSeen, sentinelLabel: opts.SentinelLabel, + hiveSupersedingAutoMerge: opts.HiveSupersedingAutoMerge, + sentinelAcknowledgedBy: opts.SentinelAcknowledgedBy, minHeadAge: opts.MinHeadAge, now: opts.Now, stageLabelPolicy: opts.StageLabelPolicy, diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index eaf3d7c93a..47ca632235 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -935,6 +935,11 @@ type PullRequest struct { // CI (#7471). Never consulted by any gate — mergeableFromState owns the // policy; this is the evidence the pill tooltip shows for it. MergeableState string `json:"mergeable_state,omitempty"` + // Supersedes is the PR this one declares it supersedes ("Supersedes + // #N" in the body: the hive's adoption / takeover / re-author copy of + // a contributor PR), read from the list payload; 0 when none. + // IsHiveSupersedingPR pairs it with AppAuthored. + Supersedes int `json:"supersedes,omitempty"` // BaseDiffEmpty is true when the per-PR detail fetch reported zero // changed files, additions and deletions against the base: the PR // carries nothing the base does not already have (an adoption whose @@ -2279,6 +2284,7 @@ func (c *Client) fetchPRsWithDetails(ctx context.Context, repo string, clankerBu RequestedReviewers: reqLogins, RequestedTeams: reqTeams, ReferencedIssues: PRReferencedIssues(pr.GetTitle(), pr.GetBody(), repo, pr.GetNumber()), + Supersedes: prSupersedesNumberOrZero(pr.GetBody()), }) } diff --git a/src/pkg/github/pr_hive_superseding.go b/src/pkg/github/pr_hive_superseding.go new file mode 100644 index 0000000000..738ed6e421 --- /dev/null +++ b/src/pkg/github/pr_hive_superseding.go @@ -0,0 +1,43 @@ +package github + +import "strconv" + +// PRSupersedesNumber returns the first pull request a PR body declares it +// supersedes ("Supersedes #N", the line the hive's adoption / takeover / +// re-author flows write — AdoptionPRBody), or 0, false when it declares +// none. +func PRSupersedesNumber(body string) (int, bool) { + for _, m := range prSupersedesRe.FindAllStringSubmatch(body, -1) { + if v, err := strconv.Atoi(m[1]); err == nil && v > 0 { + return v, true + } + } + return 0, false +} + +// HiveSupersedingPR reports whether a PR is the hive's own superseding +// copy of another PR: authored by the hive App identity (hiveAuthored) and +// declaring "Supersedes #N" in its body. Owner rule (@clubanderson): "if a +// PR is superseded by a PR that a hive agent creates, it should auto merge" +// — such a PR never waits on an operator decision for an ordinary reviewer +// finding; only a sentinel finding or an emergent hard-stop parks it +// (hiveSupersederHardStop in pkg/github/automerge). +func HiveSupersedingPR(hiveAuthored bool, body string) bool { + if !hiveAuthored { + return false + } + _, ok := PRSupersedesNumber(body) + return ok +} + +// IsHiveSupersedingPR is HiveSupersedingPR over an enumerated PullRequest: +// the App's own login (AppAuthored) with a recorded Supersedes number. +func IsHiveSupersedingPR(pr PullRequest) bool { + return pr.AppAuthored && pr.Supersedes > 0 +} + +// prSupersedesNumberOrZero is PRSupersedesNumber for struct literals. +func prSupersedesNumberOrZero(body string) int { + n, _ := PRSupersedesNumber(body) + return n +} diff --git a/src/pkg/github/pr_hive_superseding_test.go b/src/pkg/github/pr_hive_superseding_test.go new file mode 100644 index 0000000000..961966f920 --- /dev/null +++ b/src/pkg/github/pr_hive_superseding_test.go @@ -0,0 +1,39 @@ +package github + +import "testing" + +func TestPRSupersedesNumber(t *testing.T) { + cases := []struct { + body string + want int + }{ + {"Supersedes #15646\n\nRe-authored.", 15646}, + {"Closes #1\n\nsupersedes #42 (contributor PR)", 42}, + {"Fixes #15646", 0}, + {"", 0}, + } + for _, tc := range cases { + n, ok := PRSupersedesNumber(tc.body) + if n != tc.want || ok != (tc.want > 0) { + t.Fatalf("PRSupersedesNumber(%q) = %d,%v want %d", tc.body, n, ok, tc.want) + } + } +} + +func TestIsHiveSupersedingPR(t *testing.T) { + body := "Supersedes #15646" + if !HiveSupersedingPR(true, body) || HiveSupersedingPR(false, body) || HiveSupersedingPR(true, "Fixes #1") { + t.Fatal("HiveSupersedingPR: hive-authored + Supersedes marker only") + } + pr := PullRequest{AppAuthored: true, Supersedes: prSupersedesNumberOrZero(body)} + if !IsHiveSupersedingPR(pr) { + t.Fatalf("IsHiveSupersedingPR(%+v) = false", pr) + } + pr.AppAuthored = false + if IsHiveSupersedingPR(pr) { + t.Fatal("a contributor's superseding PR is not the hive's") + } + if IsHiveSupersedingPR(PullRequest{AppAuthored: true}) { + t.Fatal("no Supersedes number → not superseding") + } +} diff --git a/src/pkg/github/review_verdict_relay.go b/src/pkg/github/review_verdict_relay.go index 0ec15d9689..c862f0eb56 100644 --- a/src/pkg/github/review_verdict_relay.go +++ b/src/pkg/github/review_verdict_relay.go @@ -175,6 +175,10 @@ type reviewedPRSnapshot struct { // Base is the PR's base branch, for the same-patch test across a head // move (hivecommons/hive#15823). Base string + // Supersedes is the PR the body declares this one supersedes (0 when + // none): with hive authorship it marks the hive's superseding copy, + // whose reviewer findings route to the fixer rather than a person. + Supersedes int } // reviewedPRSnapshotFunc returns a memoized lookup of req's PR head SHA and @@ -208,6 +212,7 @@ func (c *Client) reviewedPRSnapshotFunc(ctx context.Context, req ReviewRequest) BodyDigest: review.PullRequestBodyDigest(pr.GetTitle(), pr.GetBody()), Author: safeGetLogin(pr.GetUser()), Base: strings.TrimSpace(pr.GetBase().GetRef()), + Supersedes: prSupersedesNumberOrZero(pr.GetBody()), } return snap } @@ -427,15 +432,23 @@ func (c *Client) writeOneVerdict(ctx context.Context, req ReviewRequest, report report.HeadSHA = c.canonicalVerdictHead(req, report.HeadSHA, auth.HeadSHA, prHead) } report.HiveAuthored = auth.HiveAuthored - if !report.HiveAuthored && prSnapshot != nil && (report.DecisionRequested || report.Verdict == review.VerdictRequiresHuman) && c.IsHiveAuthorLogin(prSnapshot().Author) { - // The App's own PR under a dispatch record that did not carry - // authorship (an adoption with no agent attribution, or a record - // written before hive_authored existed): the login settles it, so - // the aggregate can self-resolve its decision questions and the - // stage engine routes it as the hive's (hivecommons/hive#15499). + if prSnapshot != nil && (report.DecisionRequested || report.Verdict == review.VerdictRequiresHuman) { // Only a verdict whose routing depends on authorship pays for the // PR fetch; an approve or changes_requested never does. - report.HiveAuthored = true + snap := prSnapshot() + if !report.HiveAuthored && c.IsHiveAuthorLogin(snap.Author) { + // The App's own PR under a dispatch record that did not carry + // authorship (an adoption with no agent attribution, or a record + // written before hive_authored existed): the login settles it, so + // the aggregate can self-resolve its decision questions and the + // stage engine routes it as the hive's (hivecommons/hive#15499). + report.HiveAuthored = true + } + // The hive's superseding copy of another PR ("Supersedes #N" under + // the App's login): its requires_human findings — security-sensitive + // included — go to the fixer, never to an operator decision + // (owner rule, hivecommons/hive: hive superseder auto-merge). + report.HiveSuperseding = report.HiveAuthored && snap.Supersedes > 0 && c.IsHiveAuthorLogin(snap.Author) } // The review head, and whether this is the decision step's reconciled // report, come from the dispatch record this verdict bound to, never the diff --git a/src/pkg/github/webhook_item_patch.go b/src/pkg/github/webhook_item_patch.go index f9b5956ce1..46691c73c6 100644 --- a/src/pkg/github/webhook_item_patch.go +++ b/src/pkg/github/webhook_item_patch.go @@ -165,6 +165,7 @@ func (c *Client) classifyWebhookPR(repo string, pr *gh.PullRequest, labels []str HivePlan: planRef, ScopeContract: scopeContract, BodyDigest: review.PullRequestBodyDigest(pr.GetTitle(), pr.GetBody()), + Supersedes: prSupersedesNumberOrZero(pr.GetBody()), MergeableState: pr.GetMergeableState(), HeadSHA: prHeadSHA(pr), HeadRef: headRef, diff --git a/src/pkg/review/hive_superseding_test.go b/src/pkg/review/hive_superseding_test.go new file mode 100644 index 0000000000..13bd8d76d9 --- /dev/null +++ b/src/pkg/review/hive_superseding_test.go @@ -0,0 +1,114 @@ +package review + +import ( + "strings" + "testing" +) + +// hiveSupersederSecurityReport is a security-sensitive requires_human on a +// PR the hive created to supersede another PR. +func hiveSupersederSecurityReport() PerspectiveReport { + r := baseReport(PerspectiveSecurity, VerdictRequiresHuman) + r.HiveAuthored = true + r.HiveSuperseding = true + r.DecisionRequested = true + r.DecisionQuestion = "Should we accept this public-facing auth behavior change?" + return r +} + +// TestAggregateHiveSupersedingRiskRequiresHumanRoutesToFixer: the owner's +// rule — a security/risk requires_human on the hive's superseding PR is a +// fix request, not an 085 park. +func TestAggregateHiveSupersedingRiskRequiresHumanRoutesToFixer(t *testing.T) { + got := AggregateReports([]PerspectiveReport{hiveSupersederSecurityReport()}, AggregateOptions{}) + + if got.Verdict != VerdictChangesRequested || !got.FixCycle || got.RequiresHuman || got.DecisionRequested || got.DecisionQuestion != "" { + t.Fatalf("aggregate = %+v, want changes_requested fixer route", got) + } + if !got.HiveSuperseding || got.Perspectives[PerspectiveSecurity] != VerdictChangesRequested { + t.Fatalf("aggregate = %+v, want hive_superseding + normalized perspective", got) + } + if !hasReason(got.Reasons, HiveSupersedingFixRouteReason) { + t.Fatalf("reasons = %v, want %q", got.Reasons, HiveSupersedingFixRouteReason) + } +} + +// TestAggregateHiveSupersedingPlainRequiresHumanRoutesToFixer: an +// unresolved (non-question) requires_human on the superseding PR goes the +// same way. +func TestAggregateHiveSupersedingPlainRequiresHumanRoutesToFixer(t *testing.T) { + r := baseReport(PerspectiveSecurity, VerdictRequiresHuman) + r.HiveAuthored = true + r.HiveSuperseding = true + r.Summary = "Could not read the diff for an authorization change." + + got := AggregateReports([]PerspectiveReport{r}, AggregateOptions{}) + + if got.Verdict != VerdictChangesRequested || !got.FixCycle || got.RequiresHuman { + t.Fatalf("aggregate = %+v, want changes_requested fixer route", got) + } +} + +// TestAggregateContributorRiskRequiresHumanStillParks: the same finding on +// a PR that is not the hive's superseding copy keeps the human hold. +func TestAggregateContributorRiskRequiresHumanStillParks(t *testing.T) { + for name, mutate := range map[string]func(*PerspectiveReport){ + "contributor": func(r *PerspectiveReport) { r.HiveAuthored = false; r.HiveSuperseding = false }, + "hive but not superseding": func(r *PerspectiveReport) { r.HiveSuperseding = false }, + } { + t.Run(name, func(t *testing.T) { + r := hiveSupersederSecurityReport() + mutate(&r) + got := AggregateReports([]PerspectiveReport{r}, AggregateOptions{}) + if got.Verdict != VerdictRequiresHuman || !got.RequiresHuman || got.FixCycle { + t.Fatalf("aggregate = %+v, want requires_human", got) + } + }) + } +} + +// TestAggregateHiveSupersedingKnobOffKeepsOldBehaviour: +// auto_merge.hive_superseding.auto_merge: false restores the park. +func TestAggregateHiveSupersedingKnobOffKeepsOldBehaviour(t *testing.T) { + got := AggregateReports([]PerspectiveReport{hiveSupersederSecurityReport()}, AggregateOptions{HiveSupersedingAutoMergeOff: true}) + if got.Verdict != VerdictRequiresHuman || !got.RequiresHuman || !got.DecisionRequested || got.FixCycle { + t.Fatalf("aggregate = %+v, want requires_human with knob off", got) + } + if hasReason(got.Reasons, HiveSupersedingFixRouteReason) { + t.Fatalf("reasons = %v, must not carry the fix-route reason", got.Reasons) + } +} + +// TestAggregateHiveSupersedingFixCapExhaustedParks: once the fixer's +// attempts are spent the superseding PR does park — the emergent-problem +// exception — and says so. +func TestAggregateHiveSupersedingFixCapExhaustedParks(t *testing.T) { + got := AggregateReports([]PerspectiveReport{hiveSupersederSecurityReport()}, AggregateOptions{FixAttempts: DefaultFixCycleCap}) + if got.Verdict != VerdictRequiresHuman || !got.RequiresHuman || got.FixCycle { + t.Fatalf("aggregate = %+v, want requires_human at fix cap", got) + } + if len(got.Reasons) != 1 || !strings.HasPrefix(got.Reasons[0], "fix cycle cap reached") { + t.Fatalf("reasons = %v, want fix cycle cap reason", got.Reasons) + } +} + +// TestAggregateHiveSupersedingRejectStaysReject: a reject is an emergent +// problem with the PR, never converted to a fix request. +func TestAggregateHiveSupersedingRejectStaysReject(t *testing.T) { + reject := baseReport(PerspectiveCorrectness, VerdictReject) + reject.HiveAuthored = true + reject.HiveSuperseding = true + got := AggregateReports([]PerspectiveReport{hiveSupersederSecurityReport(), reject}, AggregateOptions{}) + if got.Verdict == VerdictChangesRequested || got.FixCycle || hasReason(got.Reasons, HiveSupersedingFixRouteReason) { + t.Fatalf("aggregate = %+v, must not become a fix request", got) + } +} + +func hasReason(reasons []string, want string) bool { + for _, r := range reasons { + if r == want { + return true + } + } + return false +} diff --git a/src/pkg/review/prompts.go b/src/pkg/review/prompts.go index 71299c6df1..98e707a377 100644 --- a/src/pkg/review/prompts.go +++ b/src/pkg/review/prompts.go @@ -340,6 +340,7 @@ func BuildPerspectivePromptWith(p Perspective, pr PullRequest, opts PromptOption b.WriteString("Use approve only when this perspective finds no IN-SCOPE blocker. Use changes_requested for agent-fixable in-scope issues. Use requires_human for ambiguous/high-risk in-scope judgment. Use reject for fundamentally unsuitable or harmful PRs. Out-of-scope findings alone must not lower the verdict.\n") b.WriteString("For Hive-authored PRs, resolve sequencing, naming, config-shape, scope, and land-now-vs-later questions yourself: prefer approve with an advisory note, or changes_requested only for a concrete in-scope fix. Use requires_human only for risk a human must own: security, data loss, irreversible or public-facing behavior, policy/governance, licensing, spend, or when you could not read the diff.\n") b.WriteString(permissionsTighteningGuidance) + b.WriteString(hiveSupersedingGuidance) b.WriteString("A Hive-authored incomplete fix with concrete remediation is changes_requested, not requires_human. If there are two engineering remedies (for example, add producer code OR reword a changelog), choose the best route yourself and state it as the requested change; do not escalate the choice to a human unless it falls into one of the risk categories above. Intent-alignment cleanup such as trimming a PR summary or changelog fragment that duplicates already-landed work is also changes_requested when the remediation is concrete.\n") if head := strings.TrimSpace(opts.HeadRecordOnly); head != "" { b.WriteString(buildHeadRecordOnlyInstruction(pr, head)) diff --git a/src/pkg/review/prompts_combined.go b/src/pkg/review/prompts_combined.go index a106d5c848..916f261f14 100644 --- a/src/pkg/review/prompts_combined.go +++ b/src/pkg/review/prompts_combined.go @@ -78,6 +78,7 @@ func BuildCombinedPrompt(pr PullRequest, perspectives []Perspective, opts Prompt b.WriteString("Give each perspective its OWN verdict. Use approve only when THAT perspective finds no in-scope blocker. Use changes_requested for agent-fixable in-scope issues. Use requires_human for ambiguous/high-risk in-scope judgment. Use reject for fundamentally unsuitable or harmful PRs. Out-of-scope findings alone must not lower any verdict.\n") b.WriteString("For Hive-authored PRs, resolve sequencing, naming, config-shape, scope, and land-now-vs-later questions yourself: prefer approve with an advisory note, or changes_requested only for a concrete in-scope fix. Use requires_human only for risk a human must own: security, data loss, irreversible or public-facing behavior, policy/governance, licensing, spend, or when you could not read the diff.\n") b.WriteString(permissionsTighteningGuidance) + b.WriteString(hiveSupersedingGuidance) b.WriteString("A Hive-authored incomplete fix with concrete remediation is changes_requested, not requires_human. If there are two engineering remedies (for example, add producer code OR reword a changelog), choose the best route yourself and state it as the requested change; do not escalate the choice to a human unless it falls into one of the risk categories above. Intent-alignment cleanup such as trimming a PR summary or changelog fragment that duplicates already-landed work is also changes_requested when the remediation is concrete.\n") b.WriteString("A perspective you could not meaningfully assess is requires_human, not approve. Approving a perspective you did not actually consider is the one failure mode that makes this whole review worthless, because it is indistinguishable from having considered it.\n") if head := strings.TrimSpace(opts.HeadRecordOnly); head != "" { diff --git a/src/pkg/review/prompts_decision.go b/src/pkg/review/prompts_decision.go index d6c36aff24..3820843455 100644 --- a/src/pkg/review/prompts_decision.go +++ b/src/pkg/review/prompts_decision.go @@ -62,6 +62,7 @@ func BuildDecisionPrompt(pr PullRequest, perspectives []Perspective, agg Aggrega b.WriteString("4. Decide the perspective's verdict from the confirmed findings only: approve when none blocks; changes_requested for agent-fixable in-scope issues; requires_human for ambiguous or high-risk judgement a person must own; reject for a fundamentally unsuitable change. When the heads disagreed on a verdict, resolve it on the evidence and say why.\n") b.WriteString("For Hive-authored PRs, resolve sequencing, naming, config-shape, scope, and land-now-vs-later questions yourself; use requires_human only for risk a human must own: security, data loss, irreversible or public-facing behavior, policy/governance, licensing, spend, or when you could not read the diff.\n") b.WriteString(permissionsTighteningGuidance) + b.WriteString(hiveSupersedingGuidance) reportPerspectives := append([]Perspective(nil), perspectives...) seen := map[Perspective]bool{} diff --git a/src/pkg/review/prompts_publish.go b/src/pkg/review/prompts_publish.go index 015968aa8f..61786ee84e 100644 --- a/src/pkg/review/prompts_publish.go +++ b/src/pkg/review/prompts_publish.go @@ -103,6 +103,11 @@ func mentionableAuthor(author string) string { // The relay proves the same property structurally (WorkflowPermissionsTighteningOnly) // and suppresses the permissions classes; this text keeps the model's verdict // consistent with that code path instead of fighting it. +// hiveSupersedingGuidance tells the reviewer how its verdict is routed on +// the hive's own superseding copy of another PR (owner rule: those +// auto-merge; a requires_human there becomes a fix request, not a park). +const hiveSupersedingGuidance = "When a Hive-authored PR supersedes another PR (its body says `Supersedes #N`), it auto-merges once CI and review are clean and no operator decides on it: a requires_human you raise there — security-sensitive or not — is routed to the fixer as a concrete fix request, so state the remediation, not the question. Only the sentinel or an emergent problem with the head parks such a PR.\n" + const permissionsTighteningGuidance = "Narrowing GitHub Actions permissions is not a security risk a human must own: a workflow diff that only removes `permissions:` scopes or lowers them (write to read or none, a block replaced by `permissions: {}`) with no new job, step, trigger such as pull_request_target or workflow_run, `uses:` change, `secrets.*`/token reference, or added `id-token: write` is a mechanical reduction — approve it with an advisory note. Any widened or newly granted scope, or a tightening mixed with any other change, stays requires_human.\n" // findingSchemaInstruction spells out the Finding object field by field. The diff --git a/src/pkg/review/review.go b/src/pkg/review/review.go index f9b29541c5..02f92ac258 100644 --- a/src/pkg/review/review.go +++ b/src/pkg/review/review.go @@ -129,8 +129,14 @@ type PerspectiveReport struct { HeadSHA string `json:"head_sha,omitempty"` BodyDigest string `json:"body_digest,omitempty"` HiveAuthored bool `json:"hive_authored,omitempty"` - AuthorModel string `json:"author_model,omitempty"` - ReviewModel string `json:"review_model,omitempty"` + // HiveSuperseding marks the hive App's own superseding copy of another + // PR ("Supersedes #N" in its body), stamped by the verdict relay from + // the PR, never from the reviewer's JSON. Its requires_human findings + // — security-sensitive included — route to the fixer instead of + // parking for an operator (hiveSupersedingFixRoute). + HiveSuperseding bool `json:"hive_superseding,omitempty"` + AuthorModel string `json:"author_model,omitempty"` + ReviewModel string `json:"review_model,omitempty"` // Head is the review head (agents..review_heads key, e.g. // code-reviewer-sol) this report came from, set by the relay from the // dispatch record. Empty for ordinary single-reviewer perspectives. @@ -195,6 +201,13 @@ type AggregateOptions struct { // a decision question that matches no DecisionRiskClass and carries no // `hive-decision-risk: high` marker. SelfAuthoredDecisionPolicy string + // HiveSupersedingAutoMergeOff is `auto_merge.hive_superseding.auto_merge: + // false`: the hive's superseding copy of another PR is then judged like + // any other hive-authored PR, so a risk / security-sensitive + // requires_human parks it for a person. Off (the zero value) is the + // owner's rule: such findings go to the fixer and the PR auto-merges + // once CI and review are clean. + HiveSupersedingAutoMergeOff bool // SensitivePaths are the operator's extra `security.sensitive_paths` // globs; a contributor-PR finding on one of them (or on a // sentinel.DefaultSensitivePaths path) is a security finding that may @@ -228,14 +241,17 @@ type AggregateOptions struct { } type Aggregate struct { - Repo string `json:"repo"` - Number int `json:"number"` - HeadSHA string `json:"head_sha,omitempty"` - BodyDigest string `json:"body_digest,omitempty"` - AuthorModel string `json:"author_model,omitempty"` - ReviewModel string `json:"review_model,omitempty"` - HiveAuthored bool `json:"hive_authored,omitempty"` - HiveAuthoredKnown bool `json:"hive_authored_known,omitempty"` + Repo string `json:"repo"` + Number int `json:"number"` + HeadSHA string `json:"head_sha,omitempty"` + BodyDigest string `json:"body_digest,omitempty"` + AuthorModel string `json:"author_model,omitempty"` + ReviewModel string `json:"review_model,omitempty"` + HiveAuthored bool `json:"hive_authored,omitempty"` + HiveAuthoredKnown bool `json:"hive_authored_known,omitempty"` + // HiveSuperseding is true when any report marked the PR as the hive's + // superseding copy of another PR (PerspectiveReport.HiveSuperseding). + HiveSuperseding bool `json:"hive_superseding,omitempty"` Verdict Verdict `json:"verdict"` MergeEligible bool `json:"merge_eligible"` FixCycle bool `json:"fix_cycle"` @@ -408,6 +424,7 @@ func aggregateReports(reports []PerspectiveReport, opts AggregateOptions) Aggreg } agg.HiveAuthoredKnown = true agg.HiveAuthored = reportsHiveAuthored(reports) + agg.HiveSuperseding = reportsHiveSuperseding(reports) agg.PermissionsTighteningOnly = reportsPermissionsTighteningOnly(reports) seenVerdicts := map[Verdict]bool{} var decisionRequested bool @@ -491,6 +508,36 @@ func aggregateReports(reports []PerspectiveReport, opts AggregateOptions) Aggreg sortReasons(agg.Reasons) sort.Strings(agg.HumanSummaries) + if hiveSupersedingFixRoute(agg, opts, hasReject, decisionRequested, riskEscalation, unresolvedRequiresHuman) { + // Owner rule: a PR the hive created to supersede another PR auto- + // merges with no operator decision. A reviewer's requires_human — + // a risk-class question, a security-sensitive finding — is a + // finding the fixer addresses and the swarm re-reviews, exactly + // like a changes_requested; only an exhausted fix cycle hands the + // head to a person (the stage engine's hard-stops cover the + // sentinel, holds, red CI and conflicts). + if finding, backed := securityFindingAcross(reports, sensitivePaths); backed { + agg.DecisionFinding = finding + } + if opts.FixAttempts >= maxFix { + agg.Verdict = VerdictRequiresHuman + agg.RequiresHuman = true + agg.DecisionRequested = decisionRequested + agg.DecisionQuestion = decisionQuestion + agg.Reasons = []string{fmt.Sprintf("fix cycle cap reached (%d/%d)", opts.FixAttempts, maxFix)} + return agg + } + agg.Verdict = VerdictChangesRequested + agg.FixCycle = true + markRequiresHumanPerspectivesAsChangesRequested(&agg) + agg.RequiresHuman = false + agg.DecisionRequested = false + agg.DecisionQuestion = "" + agg.Reasons = append(append([]string{}, agg.Reasons...), HiveSupersedingFixRouteReason) + sortReasons(agg.Reasons) + return agg + } + if decisionRequested { if finding, backed := securityFindingAcross(reports, sensitivePaths); !backed && contributorHandsFree(agg, opts) { // Owner rule (hivecommons/hive#15640): no human decision while @@ -861,6 +908,40 @@ func resolveSelfAuthoredDecisionQuestions(reports []PerspectiveReport, opts Aggr return true } +// HiveSupersedingFixRouteReason is the aggregate reason recorded when a +// hive-authored superseding PR's requires_human was routed to the fixer +// instead of an operator decision (owner rule, @clubanderson: "if a pr is +// superseded by a pr that a hive agent creates, it should auto merge"). +const HiveSupersedingFixRouteReason = "hive-authored superseding PR: reviewer requires_human routed to the fixer; auto-merges once CI and review are clean" + +// hiveSupersedingFixRoute says whether this aggregate is one the owner's +// superseder rule turns from a human park into a fix cycle: the PR is the +// hive's superseding copy, the knob is on, no perspective rejected, and +// the only thing holding it is a requires_human / decision question the +// ordinary self-authored resolution would have escalated (a risk-class +// question, a security-sensitive finding, an unresolvable summary). A +// reject stays a reject: it is an emergent problem with the PR, not a +// finding to fix. Everything the self-authored path already resolves on +// its own (non-risk questions, concrete remediation) keeps that path. +func hiveSupersedingFixRoute(agg Aggregate, opts AggregateOptions, hasReject, decisionRequested, riskEscalation, unresolvedRequiresHuman bool) bool { + if !agg.HiveSuperseding || !agg.HiveAuthored || opts.HiveSupersedingAutoMergeOff || hasReject { + return false + } + if strings.EqualFold(strings.TrimSpace(opts.SelfAuthoredDecisionPolicy), "escalate") { + return false + } + return unresolvedRequiresHuman || (decisionRequested && riskEscalation) +} + +func reportsHiveSuperseding(reports []PerspectiveReport) bool { + for _, r := range reports { + if r.HiveSuperseding { + return true + } + } + return false +} + func reportsHiveAuthored(reports []PerspectiveReport) bool { for _, r := range reports { if r.HiveAuthored { diff --git a/src/pkg/stagelabels/hive_superseder_test.go b/src/pkg/stagelabels/hive_superseder_test.go new file mode 100644 index 0000000000..d71717f9e2 --- /dev/null +++ b/src/pkg/stagelabels/hive_superseder_test.go @@ -0,0 +1,83 @@ +package stagelabels + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/authorkind" +) + +func hiveSupersederEvidence() Evidence { + e := readyEvidence() + e.SelfAuthored = true + e.AuthorKind = authorkind.Hive + e.HiveSuperseder = true + e.Verdict = VerdictRequiresHuman + e.DecisionFinding = "the security review withheld approval" + return e +} + +// TestRouteHumanHiveSupersederRequiresHumanGoesToFixer: the owner's rule — +// a reviewer requires_human on the hive's superseding PR is the fixer's +// (070), never an 085 decision, and the caption says so. +func TestRouteHumanHiveSupersederRequiresHumanGoesToFixer(t *testing.T) { + r := RouteHuman(hiveSupersederEvidence()) + if r.Stage != Fixing || r.LaneReason != LaneReasonHiveSupersederFix { + t.Fatalf("route = %+v, want 070 fixer route", r) + } + if len(r.Reasons) != 1 || !strings.HasPrefix(r.Reasons[0], HiveSupersederAutoMergeCaption) { + t.Fatalf("reasons = %v, want the auto-merge caption", r.Reasons) + } +} + +// TestRouteHumanHiveSupersederHardStopsPark: each hard-stop token parks at +// 085 with a lane reason naming the stop and a caption that names it. +func TestRouteHumanHiveSupersederHardStopsPark(t *testing.T) { + for _, token := range []string{ + HiveSupersederHardStopSentinel, + HiveSupersederHardStopHold, + HiveSupersederHardStopFixExhausted, + HiveSupersederHardStopCIRed, + HiveSupersederHardStopConflict, + } { + t.Run(token, func(t *testing.T) { + e := hiveSupersederEvidence() + e.HiveSupersederHardStop = token + r := RouteHuman(e) + if r.Stage != NeedsDecision || r.LaneReason != LaneReasonHiveSupersederHardStopPrefix+token { + t.Fatalf("route = %+v, want 085 with hard-stop lane reason", r) + } + prose := HiveSupersederHardStopProse(token) + if prose == "" || !strings.Contains(r.Reasons[0], prose) { + t.Fatalf("reasons = %v, want prose %q", r.Reasons, prose) + } + if !strings.Contains(strings.Join(r.Reasons, "\n"), "requires_human") || !strings.Contains(strings.Join(r.Reasons, "\n"), e.DecisionFinding) { + t.Fatalf("reasons = %v, want the reviewer's finding named", r.Reasons) + } + if HiveSupersederHardStopReason(r.LaneReason) != token { + t.Fatalf("HiveSupersederHardStopReason(%q) = %q", r.LaneReason, HiveSupersederHardStopReason(r.LaneReason)) + } + }) + } +} + +// TestRouteHumanNonSupersederRequiresHumanStillParks: without the +// superseder flag the same evidence still owes a decision. +func TestRouteHumanNonSupersederRequiresHumanStillParks(t *testing.T) { + e := hiveSupersederEvidence() + e.HiveSuperseder = false + if r := RouteHuman(e); r.Stage != NeedsDecision { + t.Fatalf("route = %+v, want 085", r) + } +} + +func TestHiveSupersederHardStopReasonRejectsOtherReasons(t *testing.T) { + for _, reason := range []string{"", LaneReasonChangesRequested, LaneReasonHiveSupersederFix, "hive-superseder-hard-stop"} { + if got := HiveSupersederHardStopReason(reason); got != "" { + t.Fatalf("HiveSupersederHardStopReason(%q) = %q, want empty", reason, got) + } + } + if HiveSupersederHardStopProse("unknown") != "" { + t.Fatal("unknown token must have no prose") + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 906ffce740..cf1f95ac4e 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -163,6 +163,63 @@ type Evidence struct { // ("contributor-lane:workflow-path"); the 090 route for an approved // manual-merge rule records it suffixed with the approver. LaneReason string + // HiveSuperseder is true for the hive App's own superseding copy of + // another PR ("Supersedes #N") under the owner's rule that such a PR + // auto-merges with no operator decision: a reviewer's requires_human + // is the fixer's, never 085. HiveSupersederHardStop is the one + // exception that does park it (a HiveSupersederHardStop* token, "" + // when none): the sentinel's unacknowledged finding, or an emergent + // problem with the PR itself. + HiveSuperseder bool + HiveSupersederHardStop string +} + +// Hard-stop tokens for a hive-authored superseding PR: the only reasons +// such a PR parks at 085 (owner refinement: "the only exception would be if +// this is sentinel or some other emergent problem with the pr"). Recorded +// as the 085 lane reason under LaneReasonHiveSupersederHardStopPrefix so +// the tracker pill and the delegated plan can name the reason. +const ( + HiveSupersederHardStopSentinel = "sentinel-unacknowledged" + HiveSupersederHardStopHold = "hold" + HiveSupersederHardStopFixExhausted = "fix-attempts-exhausted" + HiveSupersederHardStopCIRed = "ci-red-after-fixes" + HiveSupersederHardStopConflict = "base-conflict-unresolved" + LaneReasonHiveSupersederHardStopPrefix = "hive-superseder-hard-stop:" + // LaneReasonHiveSupersederFix is the fixing-stage reason when the + // reviewer's requires_human on a hive superseding PR goes to the fixer. + LaneReasonHiveSupersederFix = "hive-superseder:fixer" + // HiveSupersederAutoMergeCaption is the tracker / plan wording for a + // hive superseding PR that is not parked. + HiveSupersederAutoMergeCaption = "hive-authored superseding PR — auto-merging once CI/review are clean" +) + +// HiveSupersederHardStopProse renders a hard-stop token for the 085 +// comment and tracker ("" for an unknown token). +func HiveSupersederHardStopProse(token string) string { + switch strings.TrimSpace(token) { + case HiveSupersederHardStopSentinel: + return "the sentinel has an open finding on this PR that nobody has acknowledged" + case HiveSupersederHardStopHold: + return "a hold is set on this PR" + case HiveSupersederHardStopFixExhausted: + return "the fixer used all its attempts on the reviewer's findings" + case HiveSupersederHardStopCIRed: + return "CI is still red after the fixer's attempts" + case HiveSupersederHardStopConflict: + return "the head conflicts with the base and the hive could not resolve it" + } + return "" +} + +// HiveSupersederHardStopReason splits a 085 lane reason into its hard-stop +// token ("" when the reason is not one). +func HiveSupersederHardStopReason(reason string) string { + token, ok := strings.CutPrefix(strings.TrimSpace(reason), LaneReasonHiveSupersederHardStopPrefix) + if !ok { + return "" + } + return token } // HumanApprovedReasonSuffix joins a lane reason to the trusted merger who @@ -294,6 +351,26 @@ func RouteHuman(e Evidence) Route { // or the lane rule's "needs a human" is answered for it, and the // author acts next (hivecommons/hive#15159). A new head re-asks. note("@"+requester+" requested changes @"+ShortSHA(e.Head), LaneReasonHumanChangesRequested) + } else if e.HiveSuperseder { + if token := strings.TrimSpace(e.HiveSupersederHardStop); token != "" { + // The one exception to the superseder rule: an emergent + // problem with the PR itself parks it, and the caption names it. + reasons := []string{"hive-authored superseding PR parked: " + HiveSupersederHardStopProse(token)} + if e.Verdict == VerdictRequiresHuman { + reasons = append(reasons, "the reviewer swarm returned `requires_human` @"+ShortSHA(e.Head)) + if f := strings.TrimSpace(e.DecisionFinding); f != "" { + reasons = append(reasons, "the review found: "+f) + } + } + return Route{Stage: NeedsDecision, Reasons: reasons, LaneReason: LaneReasonHiveSupersederHardStopPrefix + token, Summary: summary, Head: e.Head, SelfAuthored: e.SelfAuthored, Verdict: e.Verdict, HumanApprover: strings.TrimSpace(e.HumanApprover), Hold: e.Hold} + } + if e.Verdict == VerdictRequiresHuman && strings.TrimSpace(e.HumanApprover) == "" { + // Owner rule: the reviewer's finding — security-sensitive + // included — is the fixer's to address, not a person's to rule + // on. The aggregate routes it as changes_requested; the stage + // says so rather than "needs your decision". + note(HiveSupersederAutoMergeCaption+": the reviewer's finding @"+ShortSHA(e.Head)+" goes to the fixer", LaneReasonHiveSupersederFix) + } } if e.Verdict == VerdictChangesRequested { note("verdict changes_requested @"+ShortSHA(e.Head), LaneReasonChangesRequested) @@ -378,7 +455,9 @@ func RouteHuman(e Evidence) Route { } } } - if e.Sentinel { + if e.Sentinel && !(e.HiveSuperseder && strings.TrimSpace(e.HiveSupersederHardStop) == "") { + // A hive superseding PR with no hard-stop has an acknowledged + // sentinel finding: the person already ruled on it. decide = append(decide, "a sentinel alert is open on this PR") } for _, h := range e.Holds {