Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-auto-approve-workflows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Hive approves GitHub-gated workflow runs once per PR head for trusted bots, its App, or owner-admitted PRs, with configurable trust, approval counters and a manual-action caption when permissions are missing.
3 changes: 3 additions & 0 deletions src/cmd/hive/main_eval_cycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,9 @@ func runEvalCycle(
}

ghClient.EnrichCIStatus(ctx, actionable.PRs.Items)
if !budgetDecision.SkipOptional {
ghClient.SweepWorkflowApprovals(ctx, actionable.PRs.Items, cfg.Governor.CI)
}
// Held PRs need CI status too, or a red held PR can never be repaired:
// the hold label kept it out of PRs.Items, so nothing ever learned it was
// red and no agent was ever told to fix it (hivecommons/hive#7438). This
Expand Down
30 changes: 30 additions & 0 deletions src/docs/operator-reference/runtime-and-quota.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,36 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode.
records `ci_failure_kick` — "CI failed on #N (check) — kicked agent X" /
"nudged contributor lane". **Agents never watch or poll CI themselves**:
detection is out-of-band via this webhook path, or the sweep as fallback.
- **Gated workflow runs are approved for trusted heads.** After the CI
enrichment pass of a full (non-cached) cycle in `normal` API-budget
mode, the sweep looks for open, non-draft PR heads whose
workflow runs sit behind GitHub's "Approve and run workflows" gate
(`action_required`) and approves them **at most once per PR head**
([#16603](https://github.com/hivecommons/hive/issues/16603)). A head is
trusted when the PR is admitted by the owner (carries the automerge
label), when its author or the run's triggering actor is this hive's App,
or when that login is in `governor.ci.auto_approve_workflow_actors`
(default `['dependabot[bot]', 'renovate[bot]']`; an explicit `[]` trusts
only the App and owner admission). Guards: `governor.ci.auto_approve_workflows`
(default `true` — **unset means on**; `false` keeps the gate read-only and
still surfaces `waiting on workflow approval`), the repo pause, hold /
exempt / sentinel labels, a fresh `GET /pulls/N` re-read (head SHA, open,
non-draft, author, labels) before any write, a head-repository match on
every run, and the writeback gate (`ci_rerun`). Approval starts CI only;
the review, hold and merge gates are unchanged. A `403`/`404` from
`POST /actions/runs/{id}/approve` is recorded once as a permission error
and the Activity Monitor shows the manual-action caption instead of
retrying. Counts are published at `/api/status.workflow_approvals`
(`approved`, `denied`, `permission_errors`, `last`), and the spoke logs
`approved gated workflow run` / `workflow approval refused; needs workflow
approval on GitHub`. Because approved runs execute the head's workflow
files on the repository's runners, operators on self-hosted runners who
want an explicit opt-in should set `governor.ci.auto_approve_workflows: false`.
The sweep is an optional enrichment step: it is shed in `conserve` /
`critical` mode, on off-cadence cycles and on cached (webhook-wake)
cycles, so a gated head waits for the next full `normal`-mode cycle.
`EnrichCIStatus` still runs on those cycles, so the
`waiting on workflow approval` state remains visible meanwhile.
- **A recorded review verdict also wakes the governor loop.** When the
relay records a verdict bound to a review dispatch, the head that wrote it
is free and the PR may be ready for its next head or its decision kick, so
Expand Down
2 changes: 2 additions & 0 deletions src/docs/webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ These are the acceptance criteria of #13373 and the tests that hold them.
| `governor.webhook_wake_min_gap_s` | `30` | minimum spacing between webhook-triggered cycles, and between the cycles recorded review verdicts trigger |
| `governor.ci_failure_webhook_kick` | `true` | a failed `check_run`/`check_suite`/`status` delivery kicks the owning agent (hive-authored PR) or runs a targeted contributor-lane pass (contributor PR) at once; `false` records the signal for the sweep only |
| `governor.ci_failure_kick_cooldown_s` | `600` | at most one webhook-triggered CI-failure kick or nudge per PR head in this window |
| `governor.ci.auto_approve_workflows` | `true` (unset = on) | after CI enrichment on a full `normal`-budget cycle (shed in `conserve`/`critical`, off-cadence and cached cycles), approve GitHub-gated (`action_required`) workflow runs once per trusted PR head; `false` keeps the gate read-only (`waiting on workflow approval` still shows). Starts CI only — review, hold and merge gates are unchanged. See [runtime-and-quota.md](operator-reference/runtime-and-quota.md) |
| `governor.ci.auto_approve_workflow_actors` | `['dependabot[bot]', 'renovate[bot]']` | PR authors / triggering actors trusted to have gated runs approved, in addition to this hive's App and owner-admitted (automerge-labelled) PRs; an explicit `[]` trusts only the App and owner admission |
| `forgestate.reconcile_interval_s` | `900` | ForgeState's own full-list interval per repo, shortened while drift is high |
| `forgestate.freshness_bound_s` | `60` | maximum item age before merge/close/claim/kick re-reads it |
| `forgestate.drift_threshold` | `0.05` | fraction of items a reconcile may find wrong before the interval shortens |
Expand Down
6 changes: 6 additions & 0 deletions src/hive.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,12 @@ agents:

# Governor — adaptive scheduler that adjusts agent cadences based on queue depth
governor:
# GitHub's Approve and run workflows gate. This starts CI only; the
# existing writeback, hold, review and merge gates still apply.
# ci:
# auto_approve_workflows: true
# auto_approve_workflow_actors: ['dependabot[bot]', 'renovate[bot]']
# An explicit [] trusts only this hive's App and owner-admitted PRs.
eval_interval_s: 300 # Seconds between governor evaluations
eval_interval_max_s: 1800 # Cap when API budget mode stretches evals
eval_interval_webhook_s: 900 # Base interval while GitHub webhooks are healthy (see /api/webhook/github)
Expand Down
1 change: 1 addition & 0 deletions src/pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1574,6 +1574,7 @@ func (g *GovernorConfig) ReleaseCadenceOwnership(mode, agent string) {
}

type GovernorConfig struct {
CI GovernorCIConfig `yaml:"ci,omitempty" json:"ci,omitempty"`
Modes map[string]ModeConfig `yaml:"modes"`
EvalIntervalS int `yaml:"eval_interval_s"`
EvalIntervalMaxS int `yaml:"eval_interval_max_s,omitempty"`
Expand Down
21 changes: 21 additions & 0 deletions src/pkg/config/governor_ci.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package config

// GovernorCIConfig controls approval of GitHub's gated workflow runs. Trust
// permits starting CI only; every existing review and merge gate still applies.
type GovernorCIConfig struct {
AutoApproveWorkflows *bool `yaml:"auto_approve_workflows,omitempty" json:"auto_approve_workflows,omitempty"`
AutoApproveWorkflowActors *[]string `yaml:"auto_approve_workflow_actors,omitempty" json:"auto_approve_workflow_actors,omitempty"`
}

func (c GovernorCIConfig) AutoApproveWorkflowsEnabled() bool {
return c.AutoApproveWorkflows == nil || *c.AutoApproveWorkflows
}

// WorkflowApprovalActors distinguishes an omitted list (trusted bot defaults)
// from an explicit empty list (only the App and owner admission are trusted).
func (c GovernorCIConfig) WorkflowApprovalActors() []string {
if c.AutoApproveWorkflowActors == nil {
return []string{"dependabot[bot]", "renovate[bot]"}
}
return *c.AutoApproveWorkflowActors
}
49 changes: 49 additions & 0 deletions src/pkg/config/governor_ci_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package config

import (
"encoding/json"
"reflect"
"testing"

"gopkg.in/yaml.v3"
)

func TestGovernorCIWorkflowApprovalConfig(t *testing.T) {
for _, tc := range []struct {
name, yaml string
enabled bool
actors []string
}{
{"defaults", "{}", true, []string{"dependabot[bot]", "renovate[bot]"}},
{"disabled", "governor:\n ci:\n auto_approve_workflows: false\n auto_approve_workflow_actors: []", false, []string{}},
{"custom", "governor:\n ci:\n auto_approve_workflows: true\n auto_approve_workflow_actors: [trusted-bot]", true, []string{"trusted-bot"}},
} {
t.Run(tc.name, func(t *testing.T) {
var cfg Config
if err := yaml.Unmarshal([]byte(tc.yaml), &cfg); err != nil {
t.Fatal(err)
}
if cfg.Governor.CI.AutoApproveWorkflowsEnabled() != tc.enabled || !reflect.DeepEqual(cfg.Governor.CI.WorkflowApprovalActors(), tc.actors) {
t.Fatalf("CI config=%+v actors=%v", cfg.Governor.CI, cfg.Governor.CI.WorkflowApprovalActors())
}
// Saving configuration must preserve an explicitly empty trust
// list rather than restoring the default bots after a reload.
for _, codec := range []struct {
marshal func(any) ([]byte, error)
unmarshal func([]byte, any) error
}{{yaml.Marshal, yaml.Unmarshal}, {json.Marshal, json.Unmarshal}} {
data, err := codec.marshal(cfg.Governor.CI)
if err != nil {
t.Fatal(err)
}
var restored GovernorCIConfig
if err := codec.unmarshal(data, &restored); err != nil {
t.Fatal(err)
}
if restored.AutoApproveWorkflowsEnabled() != tc.enabled || !reflect.DeepEqual(restored.WorkflowApprovalActors(), tc.actors) {
t.Fatalf("round trip changed trust: %s -> %+v", data, restored)
}
}
})
}
}
1 change: 1 addition & 0 deletions src/pkg/config/testdata/agent_runtime_golden.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@
"pr_follow_up": {}
},
"Governor": {
"ci": {},
"Modes": {
"busy": {
"Threshold": 16,
Expand Down
6 changes: 5 additions & 1 deletion src/pkg/dashboard/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3754,6 +3754,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
payload.Writeback = s.WritebackStatus()
payload.Hotspots = s.HotspotStatusBlock()
payload.Config = s.configHealthStatus()
if s.deps != nil {
payload.WorkflowApprovals = s.deps.GHClient.WorkflowApprovalsStatus()
}
statusJSONResponse(w, r, filterStatusPayload(&payload, r.URL.Query().Get("fields"), r.URL.Query().Get("omit")))
}

Expand Down Expand Up @@ -3783,7 +3786,8 @@ type statusWithWebhooks struct {
Webhooks github.WebhookHealth `json:"webhooks"`
// CIFailureSignals is the webhook CI-failure signal store: retained
// signals, the last one, webhook-triggered kicks and unmatched heads.
CIFailureSignals github.CIFailureSignalsStatus `json:"ci_failure_signals"`
CIFailureSignals github.CIFailureSignalsStatus `json:"ci_failure_signals"`
WorkflowApprovals github.WorkflowApprovalsStatus `json:"workflow_approvals"`
*EvalLoopStatus
// MatrixEnabled reports whether the Matrix block is active (enabled with
// at least one repo, see config.MatrixConfig.Active) so the header shows
Expand Down
2 changes: 2 additions & 0 deletions src/pkg/dashboard/settings_parity_allowlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ governor.budget.coins.<key>.budget # TODO #11854
governor.budget.coins.<key>.label # TODO #11854
governor.budget.coins.<key>.tokens_per_coin # TODO #11854
governor.budget.coins.<key>.usd_per_coin # TODO #11854
governor.ci.auto_approve_workflow_actors[] # trusted workflow-approval actors (#16603); yaml-only
governor.ci.auto_approve_workflows # gated workflow auto-approval flag (#16603); yaml-only
governor.ci_failure_kick_cooldown_s # webhook CI-failure kick cooldown (#15291); yaml-only
governor.ci_failure_webhook_kick # webhook CI-failure kick flag (#15291); yaml-only
governor.claims.contributor_flap_threshold # contributor flap cool-off (#13579); yaml-only
Expand Down
36 changes: 21 additions & 15 deletions src/pkg/dashboard/stage_tracker_activity.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,27 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA
if a.StatusesKnown {
out.Source += "+github-commit-statuses"
}
defer func() {
wa := a.WorkflowApproval
if wa == nil || wa.Pending <= 0 || (out.State != "missing" && out.State != "unknown") {
return
}
out.State, out.Blocker = "missing", stageTrackerWorkflowApprovalBlocker(wa.Pending)
verb := "need"
if wa.Pending == 1 {
verb = "needs"
}
out.Caption = fmt.Sprintf("CI waiting · %s %s approval on GitHub", plural(wa.Pending, "workflow run"), verb)
out.Detail = "GitHub is holding workflow runs for this commit until a maintainer can approve workflows on GitHub."
if wa.PermissionDenied {
out.Caption = "CI waiting · needs workflow approval on GitHub"
out.Detail = "The App was refused workflow approval (actions: write is required). A maintainer must click Approve and run workflows on GitHub."
}
if out.Active {
out.Caption += " · other checks still running"
}
out.Actor, out.Since = wa.Actor, wa.ObservedAt
}()
if !a.RequiredKnown || a.RequiredSource == "" || len(a.RequiredChecks) == 0 || len(a.Required) == 0 {
stageTrackerCountHeadChecks(out, a)
out.Active = out.State == "running"
Expand Down Expand Up @@ -268,21 +289,6 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA
out.Caption = "CI queued · " + check + " waiting for a runner"
out.Detail = "Required check " + check + " has been requested for the PR's current commit but has not started executing yet."
case "missing":
if wa := a.WorkflowApproval; wa != nil && wa.Pending > 0 {
// Unreported because GitHub holds the runs behind its
// approve-workflows gate: a person's click, not a push,
// moves it (hivecommons/hive#16599).
out.Blocker = stageTrackerWorkflowApprovalBlocker(wa.Pending)
out.Caption = fmt.Sprintf("CI waiting · %s %s approval on GitHub", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "needs", "need"))
out.Detail = fmt.Sprintf("%s for the PR's current commit %s waiting for a maintainer to approve workflows on GitHub (the gate GitHub applies to dependabot and first-time or fork contributors), so required check %s cannot report until someone approves them.", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "is", "are"), check)
if wa.Actor != "" {
out.Actor = wa.Actor
}
if wa.ObservedAt != nil {
out.Since = wa.ObservedAt
}
break
}
out.Caption = "CI waiting · required check " + check + " hasn't reported for this head yet"
out.Detail = "Branch protection requires a check named " + check + ", but no check run or commit status with that name exists for the PR's current commit. Usually the workflow that produces it has not been triggered; a push, re-run, or label can start it."
case "unknown":
Expand Down
102 changes: 102 additions & 0 deletions src/pkg/dashboard/workflow_approvals_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package dashboard

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"

"github.com/hivecommons/hive/pkg/config"
"github.com/hivecommons/hive/pkg/github"
)

func TestStageTrackerWorkflowApprovalCaption(t *testing.T) {
now := time.Now().UTC()
for _, tc := range []struct {
name string
pending int
permission bool
caption string
}{
{"one run", 1, false, "CI waiting · 1 workflow run needs approval on GitHub"},
{"several runs", 3, false, "CI waiting · 3 workflow runs need approval on GitHub"},
{"refused", 3, true, "CI waiting · needs workflow approval on GitHub"},
} {
t.Run(tc.name, func(t *testing.T) {
pr := github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{
Head: "head", Source: "github-check-runs", ObservedAt: &now,
WorkflowApproval: &github.PRWorkflowApproval{Pending: tc.pending, PermissionDenied: tc.permission, ObservedAt: &now},
}}
got := stageTrackerCIActivity(pr, now)
if got.Caption != tc.caption || got.State != "missing" || got.Active {
t.Fatalf("activity=%+v", got)
}
if tc.permission && !strings.Contains(got.Detail, "actions: write") {
t.Fatalf("permission requirement missing: %s", got.Detail)
}
pr.CIActivity.Head = "oldhead"
if got := stageTrackerCIActivity(pr, now); got.State != "unknown" || strings.Contains(got.Caption, "workflow approval") {
t.Fatalf("stale refusal leaked: %+v", got)
}
})
}
}

func TestStageTrackerWorkflowApprovalDoesNotHideRequiredFailure(t *testing.T) {
now := time.Now().UTC()
pr := github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{
Head: "head", Source: "github-check-runs", ObservedAt: &now,
RequiredKnown: true, RequiredSource: "protection", Required: []string{"build", "test"},
RequiredChecks: []github.PRRequiredCheck{{Name: "build", AppKnown: true}, {Name: "test", AppKnown: true}},
StatusesKnown: true, Checks: []github.PRActivityCheck{{Name: "build", State: "completed", Conclusion: "failure"}},
WorkflowApproval: &github.PRWorkflowApproval{Pending: 2, PermissionDenied: true},
}}
if got := stageTrackerCIActivity(pr, now); got.State != "failing" || got.ChecksFailed != 1 {
t.Fatalf("workflow approval hid a red required check: %+v", got)
}
}

func TestStatusWorkflowApprovals(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/repos/org/repo/actions/runs":
_, _ = w.Write([]byte(`{"workflow_runs":[{"id":11,"head_sha":"head","event":"pull_request","status":"action_required","head_repository":{"full_name":"org/repo"}}]}`))
case "/repos/org/repo/pulls/7":
_, _ = w.Write([]byte(`{"number":7,"state":"open","user":{"login":"dependabot[bot]"},"head":{"sha":"head","repo":{"full_name":"org/repo"}}}`))
case "/repos/org/repo/actions/runs/11/approve":
if r.Method != http.MethodPost {
t.Errorf("approval method=%s", r.Method)
}
http.Error(w, `{"message":"forbidden"}`, http.StatusForbidden)
default:
t.Errorf("unexpected request: %s", r.URL)
http.NotFound(w, r)
}
}))
defer srv.Close()
s := newTestServer()
c := github.NewClient("fake", "org", []string{"repo"}, s.logger, "")
base, err := url.Parse(srv.URL + "/")
if err != nil {
t.Fatal(err)
}
c.GoGitHub().BaseURL = base
c.SweepWorkflowApprovals(context.Background(), []github.PullRequest{{Repo: "org/repo", Number: 7, HeadSHA: "head", CIStatus: "pending"}}, config.GovernorCIConfig{})
s.deps = &Dependencies{GHClient: c}
s.UpdateStatus(minimalPayload())
rec := httptest.NewRecorder()
s.handleStatus(rec, httptest.NewRequest(http.MethodGet, "/api/status?fields=workflow_approvals", nil))
var payload struct {
Approvals github.WorkflowApprovalsStatus `json:"workflow_approvals"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Approvals.PermissionErrors != 1 || payload.Approvals.Last == nil || payload.Approvals.Last.RunID != 11 {
t.Fatalf("status=%s", rec.Body.String())
}
}
3 changes: 2 additions & 1 deletion src/pkg/github/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ type Client struct {
mergeAlertIDsByRepo map[string]map[string]*mergeAlertEntry
mergeAlertLastRevalidate time.Time
logger *slog.Logger
workflowApprovals workflowApprovalState
mergedClaimScanTransient sync.Map // repo -> true while its merged-PR scan is timing out
stageFacts stageFactsState // out-of-cycle stage writes; see StageFacts
apiBudget apiBudgetState
Expand Down Expand Up @@ -2564,7 +2565,7 @@ func (c *Client) EnrichCIStatus(ctx context.Context, prs []PullRequest) {
// approve-workflows gate (dependabot, forks); only a pending head
// pays for the extra listing (hivecommons/hive#16599).
if prs[i].CIStatus == "pending" && prs[i].CIActivity != nil {
prs[i].CIActivity.WorkflowApproval = c.workflowRunsAwaitingApproval(ctx, prs[i].Repo, prs[i].HeadSHA)
prs[i].CIActivity.WorkflowApproval = c.workflowApprovalForPR(ctx, prs[i].Repo, prs[i].Number, prs[i].HeadSHA)
}
if prs[i].CIStatus == "failure" {
prs[i].SharedCIIncident = c.openSharedCIIncident(ctx, &prs[i], incidents)
Expand Down
9 changes: 8 additions & 1 deletion src/pkg/github/webhook_ci_evidence.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,13 @@ func (s *ciEvidenceStore) merged(repo, head string, base *PRCIActivity) *PRCIAct
if base != nil && (listed == nil || observedAfter(base.ObservedAt, listed.ObservedAt)) {
listed = base
}
// The approval sweep runs after the check listing. Its workflow-run
// observation has a separate clock, so selecting check evidence must
// not discard (or revive) the base snapshot's approval gate.
if base != nil && listed != nil && listed != base {
listed = cloneCIActivity(listed)
listed.WorkflowApproval = base.WorkflowApproval
}
if len(events) == 0 {
return listed
}
Expand Down Expand Up @@ -488,7 +495,7 @@ func (c *Client) applyWebhookCIEvidence(event string, p webhookEventPayload, con
// Any CI delivery for the head — a workflow_run leaving action_required
// once someone clicked Approve, a check run starting — means the cached
// approval probe may be stale; re-list on the next cycle.
forgetWorkflowApproval(repo, head)
c.forgetWorkflowApproval(repo, head)
out := &WebhookCIEvidence{HeadSHA: head, PRs: append([]int(nil), numbers...)}
store := sharedCIEvidence()
checks := webhookCIChecks(event, p)
Expand Down
Loading
Loading