From 9e1821eb25676ab733bc493cbff5add80f1bb8f3 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:38:36 -0500 Subject: [PATCH 1/7] feat(github): auto-approve gated workflow runs for trusted actors Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../added-auto-approve-gated-workflows.md | 1 + src/cmd/hive/main_eval_cycle.go | 7 + .../api-reference/health-status-events.md | 2 +- .../operator-reference/runtime-and-quota.md | 37 ++ src/docs/webhooks.md | 2 + src/hive.yaml.example | 6 + src/pkg/config/config.go | 2 + src/pkg/config/governor_ci.go | 31 ++ src/pkg/config/governor_ci_test.go | 49 +++ .../config/testdata/agent_runtime_golden.json | 1 + src/pkg/dashboard/server.go | 6 + .../dashboard/settings_parity_allowlist.txt | 2 + src/pkg/dashboard/stage_tracker_activity.go | 6 + .../stage_tracker_workflow_approval_test.go | 3 + .../workflow_approvals_status_test.go | 40 ++ src/pkg/github/client.go | 3 +- src/pkg/github/workflow_approval.go | 17 +- src/pkg/github/workflow_auto_approval.go | 345 ++++++++++++++++++ src/pkg/github/workflow_auto_approval_test.go | 341 +++++++++++++++++ 19 files changed, 895 insertions(+), 6 deletions(-) create mode 100644 changelog.d/added-auto-approve-gated-workflows.md create mode 100644 src/pkg/config/governor_ci.go create mode 100644 src/pkg/config/governor_ci_test.go create mode 100644 src/pkg/dashboard/workflow_approvals_status_test.go create mode 100644 src/pkg/github/workflow_auto_approval.go create mode 100644 src/pkg/github/workflow_auto_approval_test.go diff --git a/changelog.d/added-auto-approve-gated-workflows.md b/changelog.d/added-auto-approve-gated-workflows.md new file mode 100644 index 0000000000..564e6ada48 --- /dev/null +++ b/changelog.d/added-auto-approve-gated-workflows.md @@ -0,0 +1 @@ +- The hive approves workflow runs GitHub holds behind "Approve and run workflows" once per PR head for trusted bots (`governor.ci.auto_approve_workflow_actors`, default dependabot and renovate), its own App and owner-admitted PRs (`governor.ci.auto_approve_workflows`, default on); counts are in `/api/status` `workflow_approvals`, and a missing `actions: write` permission shows `CI waiting · needs workflow approval on GitHub`. diff --git a/src/cmd/hive/main_eval_cycle.go b/src/cmd/hive/main_eval_cycle.go index 3aacf02c1b..d837fd8479 100644 --- a/src/cmd/hive/main_eval_cycle.go +++ b/src/cmd/hive/main_eval_cycle.go @@ -581,6 +581,13 @@ func runEvalCycle( } ghClient.EnrichCIStatus(ctx, actionable.PRs.Items) + // Approve workflow runs GitHub holds behind its approve-workflows gate + // on trusted heads (hivecommons/hive#16603). An optional step: shed with + // the other enrichment steps, while EnrichCIStatus keeps the gate and any + // recorded permission refusal visible. + 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 diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 48e9983a4f..46f7325057 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -28,7 +28,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1646` | | `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1647` | | `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1653` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1658` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1658` | | `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1659` | | `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1660` | | `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1661` | diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index b2f0a62153..d69f28cf92 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -262,6 +262,43 @@ 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.** GitHub holds + workflow runs for dependabot and first-time/fork contributors behind + "Approve and run workflows" (`action_required`); such runs create no check + runs, so CI never reports. `EnrichCIStatus` detects them on pending heads + and the CI caption reads `CI waiting · N workflow runs need approval on + GitHub`. Right after it, the eval cycle runs the workflow-approval sweep, + which approves a head's gated `pull_request` runs **at most once per PR + head** ([#16603](https://github.com/hivecommons/hive/issues/16603)) when + the head is trusted: the PR carries the owner's automerge admission label + (`lgtm` by default), or the PR author or the run's triggering actor is + this hive's App or is listed in `governor.ci.auto_approve_workflow_actors` + (default `['dependabot[bot]', 'renovate[bot]']`; an explicit `[]` trusts + only the App and owner admission). Runs of other events (for example + `pull_request_target`) are counted in the caption but never approved. + Guards: `governor.ci.auto_approve_workflows` (default `true` — unset + means on; `false` leaves the gate to a person), the repo pause, hold / + exempt / sentinel labels, a fresh `GET /pulls/N` (open, non-draft, same + head, author, labels) before any write, a head-repository match on every + run, and the write-back gate (`ci_rerun`). Approval starts CI only; + review, hold and merge gates are unchanged. **The sweep does not run on + every cycle:** it is an optional enrichment step, so it is skipped + whenever the API-budget decision sets `SkipOptional` — `conserve` and + `critical` budget modes, off-cadence cycles under + `governor.optional_sweep_every_n_cycles`, and cached-snapshot (webhook + wake) cycles — and a gated head then waits for the next cycle that runs + it. `EnrichCIStatus` still runs on those cycles, so the gate stays + visible. A `403`/`404` from `POST /actions/runs/{id}/approve` (the App + lacks `actions: write`) is recorded once, never retried for that head, + logged as `workflow approval refused; needs workflow approval on GitHub`, + and the caption becomes `CI waiting · needs workflow approval on GitHub` + on every later cycle, including ones that skip the sweep. Each approved + run logs one `approved gated workflow run` INFO line; counts since boot + are at `/api/status` `workflow_approvals` (`approved`, `denied`, + `permission_errors`, `last`). 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`. - **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 diff --git a/src/docs/webhooks.md b/src/docs/webhooks.md index d46de916a5..65df42f28b 100644 --- a/src/docs/webhooks.md +++ b/src/docs/webhooks.md @@ -114,6 +114,8 @@ These are the acceptance criteria of #13373 and the tests that hold them. | `governor.webhook_wake_debounce_s` | `10` | a delivery and its check fan-out coalesce into one wake cycle | | `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.auto_approve_workflows` | `true` (unset = on) | approve GitHub-gated (`action_required`) `pull_request` workflow runs once per trusted PR head, in the sweep right after CI enrichment; the sweep is skipped on cycles where the API-budget decision sets `SkipOptional` (`conserve`/`critical` mode, off-cadence and cached-snapshot cycles). `false` leaves the gate to a person. 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 for workflow approval, besides this hive's App and owner-admitted (automerge-labelled) PRs; an explicit `[]` trusts only those two | | `governor.ci_failure_kick_cooldown_s` | `600` | at most one webhook-triggered CI-failure kick or nudge per PR head in this window | | `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 | diff --git a/src/hive.yaml.example b/src/hive.yaml.example index a895a2abf9..b3d64c038a 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -413,6 +413,12 @@ agents: # Governor — adaptive scheduler that adjusts agent cadences based on queue depth governor: + # GitHub's "Approve and run workflows" gate (#16603). Approval starts CI + # only; 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) diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 401f97b80d..e6d22adce5 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -1574,6 +1574,8 @@ func (g *GovernorConfig) ReleaseCadenceOwnership(mode, agent string) { } type GovernorConfig struct { + // CI is governor.ci (hivecommons/hive#16603); see GovernorCIConfig. + 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"` diff --git a/src/pkg/config/governor_ci.go b/src/pkg/config/governor_ci.go new file mode 100644 index 0000000000..8cbb571ecc --- /dev/null +++ b/src/pkg/config/governor_ci.go @@ -0,0 +1,31 @@ +package config + +// GovernorCIConfig is governor.ci: approval of workflow runs GitHub holds +// behind its "approve and run workflows" gate (hivecommons/hive#16603). +// Approval starts CI only; every review, hold and merge gate still applies. +type GovernorCIConfig struct { + // AutoApproveWorkflows (default true) lets the hive approve gated runs + // on trusted PR heads; false leaves the gate to a person. + AutoApproveWorkflows *bool `yaml:"auto_approve_workflows,omitempty" json:"auto_approve_workflows,omitempty"` + // AutoApproveWorkflowActors are the PR authors / triggering actors + // trusted besides the hive's App and owner-admitted PRs. Unset means + // DefaultAutoApproveWorkflowActors; an explicit [] trusts neither. + AutoApproveWorkflowActors *[]string `yaml:"auto_approve_workflow_actors,omitempty" json:"auto_approve_workflow_actors,omitempty"` +} + +// DefaultAutoApproveWorkflowActors is governor.ci.auto_approve_workflow_actors +// when unset. +var DefaultAutoApproveWorkflowActors = []string{"dependabot[bot]", "renovate[bot]"} + +// AutoApproveWorkflowsEnabled is the effective auto_approve_workflows. +func (c GovernorCIConfig) AutoApproveWorkflowsEnabled() bool { + return c.AutoApproveWorkflows == nil || *c.AutoApproveWorkflows +} + +// WorkflowApprovalActors is the effective auto_approve_workflow_actors. +func (c GovernorCIConfig) WorkflowApprovalActors() []string { + if c.AutoApproveWorkflowActors == nil { + return append([]string(nil), DefaultAutoApproveWorkflowActors...) + } + return *c.AutoApproveWorkflowActors +} diff --git a/src/pkg/config/governor_ci_test.go b/src/pkg/config/governor_ci_test.go new file mode 100644 index 0000000000..b197de8444 --- /dev/null +++ b/src/pkg/config/governor_ci_test.go @@ -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, explicit empty", "governor:\n ci:\n auto_approve_workflows: false\n auto_approve_workflow_actors: []", false, []string{}}, + {"custom", "governor:\n ci:\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=%+v actors=%v", cfg.Governor.CI, cfg.Governor.CI.WorkflowApprovalActors()) + } + // A save/reload must keep an explicit [] rather than restore + // the default bots. + 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) + } + } + }) + } +} diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index 00fa498043..80962ac227 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -150,6 +150,7 @@ "pr_follow_up": {} }, "Governor": { + "ci": {}, "Modes": { "busy": { "Threshold": 16, diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index b6a84cb3e8..ab71f23c91 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -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"))) } @@ -3784,6 +3787,9 @@ type statusWithWebhooks struct { // 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"` + // WorkflowApprovals counts the hive's approvals of GitHub-gated + // workflow runs (hivecommons/hive#16603). + 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 diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 499677130e..3bc01dbd59 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -218,6 +218,8 @@ governor.budget.coins..budget # TODO #11854 governor.budget.coins..label # TODO #11854 governor.budget.coins..tokens_per_coin # TODO #11854 governor.budget.coins..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 diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 1a89343b02..94f1647aa5 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -281,6 +281,12 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA if wa.ObservedAt != nil { out.Since = wa.ObservedAt } + if wa.PermissionDenied { + // The hive tried and GitHub refused: the click is a + // person's (hivecommons/hive#16603). + out.Caption = "CI waiting · needs workflow approval on GitHub" + out.Detail = fmt.Sprintf("Hive tried to approve %s for the PR's current commit, but GitHub refused: the App lacks the actions: write permission. A maintainer has to approve workflows on GitHub before required check %s can report.", plural(wa.Pending, "gated workflow run"), check) + } break } out.Caption = "CI waiting · required check " + check + " hasn't reported for this head yet" diff --git a/src/pkg/dashboard/stage_tracker_workflow_approval_test.go b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go index 0fbad0e85c..52cbd62a44 100644 --- a/src/pkg/dashboard/stage_tracker_workflow_approval_test.go +++ b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go @@ -34,6 +34,9 @@ func TestStageTrackerCIActivityWorkflowApproval(t *testing.T) { {"gated", &github.PRWorkflowApproval{Pending: 10, RunIDs: []int64{1}, Actor: "dependabot[bot]", ObservedAt: &seen}, "workflow-approval-required:10", "CI waiting · 10 workflow runs need approval on GitHub", "dependabot[bot]"}, {"single gated run", &github.PRWorkflowApproval{Pending: 1}, "workflow-approval-required:1", "CI waiting · 1 workflow run needs approval on GitHub", ""}, + // The hive's own approval was refused (no actions: write): the + // caption says the click is a person's (hivecommons/hive#16603). + {"approval refused", &github.PRWorkflowApproval{Pending: 3, PermissionDenied: true}, "workflow-approval-required:3", "CI waiting · needs workflow approval on GitHub", ""}, {"no gate", nil, "build", "hasn't reported for this head yet", ""}, {"empty record", &github.PRWorkflowApproval{}, "build", "hasn't reported for this head yet", ""}, } { diff --git a/src/pkg/dashboard/workflow_approvals_status_test.go b/src/pkg/dashboard/workflow_approvals_status_test.go new file mode 100644 index 0000000000..ec9c46ffaf --- /dev/null +++ b/src/pkg/dashboard/workflow_approvals_status_test.go @@ -0,0 +1,40 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/hivecommons/hive/pkg/github" +) + +// /api/status carries the workflow-approval counters (hivecommons/hive#16603). +func TestStatusWorkflowApprovals(t *testing.T) { + s := newTestServer() + s.deps = &Dependencies{GHClient: github.NewClient("fake", "org", []string{"repo"}, s.logger, "")} + s.UpdateStatus(minimalPayload()) + rec := httptest.NewRecorder() + s.handleStatus(rec, httptest.NewRequest(http.MethodGet, "/api/status?fields=workflow_approvals", nil)) + var payload map[string]json.RawMessage + if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil { + t.Fatalf("decode: %v: %s", err, rec.Body.String()) + } + raw, ok := payload["workflow_approvals"] + if !ok { + t.Fatalf("workflow_approvals missing: %s", rec.Body.String()) + } + var got github.WorkflowApprovalsStatus + if err := json.Unmarshal(raw, &got); err != nil || got.Approved != 0 || got.Denied != 0 || got.PermissionErrors != 0 || got.Last != nil { + t.Fatalf("workflow_approvals=%s err=%v", raw, err) + } + var fields map[string]any + if err := json.Unmarshal(raw, &fields); err != nil { + t.Fatal(err) + } + for _, key := range []string{"approved", "denied", "permission_errors"} { + if _, ok := fields[key]; !ok { + t.Fatalf("workflow_approvals lacks %q: %s", key, raw) + } + } +} diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 333f1cdeaa..f98c491b96 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -163,6 +163,7 @@ type Client struct { mergeAlertIDsByRepo map[string]map[string]*mergeAlertEntry mergeAlertLastRevalidate time.Time logger *slog.Logger + workflowApprovals workflowApprovalLedger mergedClaimScanTransient sync.Map // repo -> true while its merged-PR scan is timing out stageFacts stageFactsState // out-of-cycle stage writes; see StageFacts apiBudget apiBudgetState @@ -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.workflowApprovalWithLedger(prs[i].Repo, prs[i].Number, prs[i].HeadSHA, c.workflowRunsAwaitingApproval(ctx, prs[i].Repo, prs[i].HeadSHA)) } if prs[i].CIStatus == "failure" { prs[i].SharedCIIncident = c.openSharedCIIncident(ctx, &prs[i], incidents) diff --git a/src/pkg/github/workflow_approval.go b/src/pkg/github/workflow_approval.go index dc23eacf1c..1b5e7a524e 100644 --- a/src/pkg/github/workflow_approval.go +++ b/src/pkg/github/workflow_approval.go @@ -15,11 +15,19 @@ import ( // runs create no check runs, so from the check-run listing alone the required // checks simply look unreported; this is the evidence that they are in fact // waiting on a person clicking Approve (hivecommons/hive#16599). +// +// PermissionDenied is set once the hive tried to approve the runs itself and +// GitHub refused for want of `actions: write`, so the click is a person's +// (hivecommons/hive#16603). type PRWorkflowApproval struct { - Pending int `json:"pending"` - RunIDs []int64 `json:"run_ids,omitempty"` - Actor string `json:"actor,omitempty"` - ObservedAt *time.Time `json:"observed_at,omitempty"` + Pending int `json:"pending"` + RunIDs []int64 `json:"run_ids,omitempty"` + Actor string `json:"actor,omitempty"` + ObservedAt *time.Time `json:"observed_at,omitempty"` + PermissionDenied bool `json:"permission_denied,omitempty"` + // runs are the gated runs themselves, read-only, for the auto-approval + // decision (triggering actor, event, head repository). + runs []*gh.WorkflowRun } // WorkflowApprovalStatus is the workflow-run status GitHub reports while a @@ -108,6 +116,7 @@ func workflowApprovalFromRuns(runs []*gh.WorkflowRun, now time.Time) *PRWorkflow out = &PRWorkflowApproval{ObservedAt: &at} } out.Pending++ + out.runs = append(out.runs, run) if id := run.GetID(); id != 0 { out.RunIDs = append(out.RunIDs, id) } diff --git a/src/pkg/github/workflow_auto_approval.go b/src/pkg/github/workflow_auto_approval.go new file mode 100644 index 0000000000..e341f65c63 --- /dev/null +++ b/src/pkg/github/workflow_auto_approval.go @@ -0,0 +1,345 @@ +package github + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Auto-approval of GitHub's "approve and run workflows" gate +// (hivecommons/hive#16603). EnrichCIStatus detects gated runs on a pending +// head (hivecommons/hive#16599); SweepWorkflowApprovals, right after it, +// approves the ones a trust policy covers, at most once per PR head. + +const workflowApprovalRESTCaller = "hive:workflow_auto_approval" + +// workflowApprovalAttemptTTL bounds the ledger: an entry no sweep has +// touched for this long belongs to a merged, closed or superseded head. +const workflowApprovalAttemptTTL = 24 * time.Hour + +type workflowApprovalKey struct { + repo string + number int + head string +} + +type workflowApprovalAttempt struct { + attempted bool + deniedCounted bool + permissionDenied bool + seen time.Time +} + +// workflowApprovalLedger is the process-local record of approval passes, +// one entry per PR head, plus the /api/status counters. +type workflowApprovalLedger struct { + mu sync.Mutex + attempts map[workflowApprovalKey]workflowApprovalAttempt + status WorkflowApprovalsStatus +} + +// WorkflowApprovalsStatus is /api/status.workflow_approvals: decisions +// since the process started. +type WorkflowApprovalsStatus struct { + Approved int `json:"approved"` + Denied int `json:"denied"` + PermissionErrors int `json:"permission_errors"` + Last *WorkflowApprovalEvent `json:"last,omitempty"` +} + +// WorkflowApprovalEvent is the most recent approval decision. +type WorkflowApprovalEvent struct { + Repo string `json:"repo"` + Number int `json:"number"` + Head string `json:"head"` + RunID int64 `json:"run_id"` + Outcome string `json:"outcome"` + At time.Time `json:"at"` +} + +// WorkflowApprovalsStatus returns a copy of the approval counters. +func (c *Client) WorkflowApprovalsStatus() WorkflowApprovalsStatus { + if c == nil { + return WorkflowApprovalsStatus{} + } + c.workflowApprovals.mu.Lock() + defer c.workflowApprovals.mu.Unlock() + out := c.workflowApprovals.status + if out.Last != nil { + last := *out.Last + out.Last = &last + } + return out +} + +// touchLocked returns the head's entry, marking it live, and evicts +// superseded heads of the same PR and entries older than the TTL. +func (l *workflowApprovalLedger) touchLocked(key workflowApprovalKey, now time.Time) workflowApprovalAttempt { + if l.attempts == nil { + l.attempts = map[workflowApprovalKey]workflowApprovalAttempt{} + } + for other, entry := range l.attempts { + if other == key { + continue + } + if (other.repo == key.repo && other.number == key.number) || now.Sub(entry.seen) >= workflowApprovalAttemptTTL { + delete(l.attempts, other) + } + } + attempt := l.attempts[key] + attempt.seen = now + l.attempts[key] = attempt + return attempt +} + +func (l *workflowApprovalLedger) record(key workflowApprovalKey, runID int64, outcome string) { + l.mu.Lock() + defer l.mu.Unlock() + switch outcome { + case "approved": + l.status.Approved++ + case "denied": + l.status.Denied++ + case "permission_error": + l.status.PermissionErrors++ + attempt := l.attempts[key] + attempt.permissionDenied = true + l.attempts[key] = attempt + } + l.status.Last = &WorkflowApprovalEvent{Repo: key.repo, Number: key.number, Head: key.head, RunID: runID, Outcome: outcome, At: time.Now().UTC()} +} + +func (c *Client) workflowApprovalKey(repo string, number int, head string) workflowApprovalKey { + owner, name := c.splitRepo(repo) + return workflowApprovalKey{repo: owner + "/" + name, number: number, head: head} +} + +// workflowApprovalWithLedger carries a recorded permission refusal onto the +// head's probe, so the "needs workflow approval" caption holds on every +// cycle, including the ones that skip the sweep. The cached probe is shared +// and never mutated. +func (c *Client) workflowApprovalWithLedger(repo string, number int, head string, wa *PRWorkflowApproval) *PRWorkflowApproval { + if c == nil || wa == nil || wa.PermissionDenied { + return wa + } + key := c.workflowApprovalKey(repo, number, head) + c.workflowApprovals.mu.Lock() + denied := c.workflowApprovals.attempts[key].permissionDenied + c.workflowApprovals.mu.Unlock() + if !denied { + return wa + } + out := *wa + out.PermissionDenied = true + return &out +} + +// workflowApprovalTrusted is the trust policy: the owner admitted the PR +// (automerge label), or the PR author or the run's triggering actor is the +// hive's App or in the allowlist. A trusted author covers every gated run +// on the head, since the code under test is theirs. +func workflowApprovalTrusted(author, actor, app string, admitted bool, actors []string) bool { + if admitted { + return true + } + for _, login := range []string{author, actor} { + login = strings.TrimSpace(login) + if login == "" { + continue + } + if app != "" && strings.EqualFold(login, app) { + return true + } + for _, trusted := range actors { + if strings.EqualFold(login, strings.TrimSpace(trusted)) { + return true + } + } + } + return false +} + +// workflowRunApprovable says whether a gated run belongs to this PR head +// and may be approved at all. The event filter lives here, not in the +// shared probe, so the #16599 caption still counts every gated run +// (hivecommons/hive#16682): only `pull_request` runs are approved, never +// `pull_request_target` or other events that run with repository secrets. +// headRepo is checked only when known. +func workflowRunApprovable(run *gh.WorkflowRun, number int, head, headRepo string) bool { + if run == nil || run.GetID() <= 0 || run.GetEvent() != "pull_request" || !strings.EqualFold(run.GetHeadSHA(), head) { + return false + } + if headRepo != "" && !strings.EqualFold(run.GetHeadRepository().GetFullName(), headRepo) { + return false + } + if len(run.PullRequests) == 0 { + return true + } + for _, linked := range run.PullRequests { + if linked.GetNumber() == number { + return true + } + } + return false +} + +func workflowTriggeringActor(run *gh.WorkflowRun) string { + if login := run.GetTriggeringActor().GetLogin(); login != "" { + return login + } + return run.GetActor().GetLogin() +} + +func (c *Client) workflowApprovalHeld(labels []string) bool { + return c.isHeld(labels) || c.isExempt(labels) || c.sentinelBlockedLabel(labels) != "" +} + +func (c *Client) workflowApprovalAdmitted(labels []string) bool { + for _, label := range labels { + if strings.EqualFold(strings.TrimSpace(label), c.AutoMergeLabel()) { + return true + } + } + return false +} + +// splitTrustedWorkflowRuns partitions the approvable gated runs by policy. +func (c *Client) splitTrustedWorkflowRuns(runs []*gh.WorkflowRun, number int, head, headRepo, author string, labels, actors []string) (trusted, denied []*gh.WorkflowRun) { + admitted := c.workflowApprovalAdmitted(labels) + app := c.AppBotLogin() + for _, run := range runs { + if !workflowRunApprovable(run, number, head, headRepo) { + continue + } + if workflowApprovalTrusted(author, workflowTriggeringActor(run), app, admitted, actors) { + trusted = append(trusted, run) + } else { + denied = append(denied, run) + } + } + return trusted, denied +} + +// SweepWorkflowApprovals approves gated workflow runs that EnrichCIStatus +// found on the PRs' heads, when policy trusts them, at most once per PR +// head. Call it right after EnrichCIStatus on the same slice. A 403/404 is +// recorded once and surfaces as PermissionDenied instead of being retried. +func (c *Client) SweepWorkflowApprovals(ctx context.Context, prs []PullRequest, policy config.GovernorCIConfig) { + if c == nil || c.client == nil || !policy.AutoApproveWorkflowsEnabled() { + return + } + actors := policy.WorkflowApprovalActors() + for i := range prs { + pr := &prs[i] + a := pr.CIActivity + if a == nil || a.WorkflowApproval == nil || a.WorkflowApproval.Pending <= 0 || !strings.EqualFold(a.Head, pr.HeadSHA) { + continue + } + if pr.Draft || pr.HeadSHA == "" || pr.Number <= 0 || (pr.State != "" && pr.State != "open") { + continue + } + key := c.workflowApprovalKey(pr.Repo, pr.Number, pr.HeadSHA) + if c.workflowApprovalHeld(pr.Labels) || c.RepoIsPaused(key.repo) { + continue + } + wa := a.WorkflowApproval + c.workflowApprovals.mu.Lock() + previous := c.workflowApprovals.touchLocked(key, time.Now()) + c.workflowApprovals.mu.Unlock() + if previous.attempted { + continue + } + trusted, denied := c.splitTrustedWorkflowRuns(wa.runs, pr.Number, pr.HeadSHA, "", pr.Author, pr.Labels, actors) + if len(denied) > 0 && !previous.deniedCounted { + c.workflowApprovals.mu.Lock() + attempt := c.workflowApprovals.attempts[key] + attempt.deniedCounted = true + c.workflowApprovals.attempts[key] = attempt + c.workflowApprovals.mu.Unlock() + for _, run := range denied { + c.workflowApprovals.record(key, run.GetID(), "denied") + } + } + if len(trusted) == 0 { + continue + } + owner, name := c.splitRepo(pr.Repo) + // The listing may be a cycle old. Re-read head, author and labels + // before letting the head run with the repository's CI rights. + fresh, _, err := c.client.PullRequests.Get(WithRESTCaller(ctx, workflowApprovalRESTCaller), owner, name, pr.Number) + if err != nil || fresh == nil || fresh.GetState() != "open" || fresh.GetDraft() || fresh.GetHead().GetSHA() != pr.HeadSHA { + continue + } + labels := labelNames(fresh.Labels) + headRepo := fresh.GetHead().GetRepo().GetFullName() + if c.workflowApprovalHeld(labels) || headRepo == "" { + continue + } + trusted, _ = c.splitTrustedWorkflowRuns(wa.runs, pr.Number, pr.HeadSHA, headRepo, fresh.GetUser().GetLogin(), labels, actors) + if len(trusted) == 0 { + continue + } + item := c.WritebackItemForPR(*pr) + item.Author, item.Labels = fresh.GetUser().GetLogin(), labels + if !c.WritebackAllowed(key.repo, item, writeback.KindCIRerun, "approve gated workflow runs").Allowed { + continue + } + // Claim before the first POST: neither a concurrent cycle nor an + // unchanged head repeats the pass, even after a partial failure. + c.workflowApprovals.mu.Lock() + attempt := c.workflowApprovals.attempts[key] + claimed := !attempt.attempted + attempt.attempted = true + c.workflowApprovals.attempts[key] = attempt + c.workflowApprovals.mu.Unlock() + if !claimed { + continue + } + approved := false + for _, run := range trusted { + err := c.approveWorkflowRun(ctx, owner, name, run.GetID()) + if err == nil { + approved = true + c.workflowApprovals.record(key, run.GetID(), "approved") + c.logger.Info("approved gated workflow run", "repo", key.repo, "pr", pr.Number, "head", pr.HeadSHA, "run_id", run.GetID(), "actor", workflowTriggeringActor(run)) + continue + } + var apiErr *gh.ErrorResponse + if errors.As(err, &apiErr) && apiErr.Response != nil && (apiErr.Response.StatusCode == http.StatusForbidden || apiErr.Response.StatusCode == http.StatusNotFound) { + c.workflowApprovals.record(key, run.GetID(), "permission_error") + c.logger.Warn("workflow approval refused; needs workflow approval on GitHub (App lacks actions: write?)", "repo", key.repo, "pr", pr.Number, "head", pr.HeadSHA, "run_id", run.GetID(), "error", err) + refused := *wa + refused.PermissionDenied = true + activity := cloneCIActivity(a) + activity.WorkflowApproval = &refused + pr.CIActivity = activity + break + } + c.logger.Warn("failed to approve gated workflow run", "repo", key.repo, "pr", pr.Number, "head", pr.HeadSHA, "run_id", run.GetID(), "error", err) + } + if approved { + // Let the next cycle observe the runs starting. + forgetWorkflowApproval(pr.Repo, pr.HeadSHA) + } + } +} + +// approveWorkflowRun calls POST /repos/{o}/{r}/actions/runs/{id}/approve, +// which go-github v72 does not bind. +func (c *Client) approveWorkflowRun(ctx context.Context, owner, repo string, runID int64) error { + req, err := c.client.NewRequest(http.MethodPost, fmt.Sprintf("repos/%s/%s/actions/runs/%d/approve", owner, repo, runID), nil) + if err != nil { + return err + } + resp, err := c.client.Do(WithRESTCaller(ctx, workflowApprovalRESTCaller), req, nil) + c.noteWritebackOutcome(owner+"/"+repo, resp, err) + return err +} diff --git a/src/pkg/github/workflow_auto_approval_test.go b/src/pkg/github/workflow_auto_approval_test.go new file mode 100644 index 0000000000..6dad6daf53 --- /dev/null +++ b/src/pkg/github/workflow_auto_approval_test.go @@ -0,0 +1,341 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/config" +) + +func TestWorkflowApprovalTrusted(t *testing.T) { + defaults := (config.GovernorCIConfig{}).WorkflowApprovalActors() + for _, tc := range []struct { + name, author, actor, app string + admitted bool + actors []string + want bool + }{ + {name: "dependabot author", author: "dependabot[bot]", actor: "someone", actors: defaults, want: true}, + {name: "renovate triggering actor", author: "outsider", actor: "renovate[bot]", actors: defaults, want: true}, + {name: "app author", author: "hive[bot]", actor: "outsider", app: "hive[bot]", want: true}, + {name: "app triggering actor", author: "outsider", actor: "hive[bot]", app: "hive[bot]", want: true}, + {name: "owner admission", author: "outsider", actor: "outsider", admitted: true, want: true}, + {name: "case and whitespace", author: "outsider", actor: "CUSTOM[bot]", actors: []string{" custom[bot] "}, want: true}, + {name: "untrusted human", author: "outsider", actor: "outsider", actors: defaults}, + {name: "other app", author: "other[bot]", actor: "other[bot]", app: "hive[bot]", actors: defaults}, + {name: "empty identities", actors: []string{""}}, + {name: "explicit empty allowlist", author: "dependabot[bot]", actor: "dependabot[bot]", actors: []string{}}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := workflowApprovalTrusted(tc.author, tc.actor, tc.app, tc.admitted, tc.actors); got != tc.want { + t.Fatalf("trusted = %v, want %v", got, tc.want) + } + }) + } +} + +func TestWorkflowRunApprovable(t *testing.T) { + base := func() *gh.WorkflowRun { return gatedRun(11, "head1", "dependabot[bot]") } + for _, tc := range []struct { + name string + mutate func(*gh.WorkflowRun) + headRepo string + want bool + }{ + {name: "pull_request run on head", want: true}, + {name: "head repository matches", headRepo: "fork/repo", want: true}, + {name: "pull_request_target is never approved", mutate: func(r *gh.WorkflowRun) { r.Event = gh.Ptr("pull_request_target") }}, + {name: "push event", mutate: func(r *gh.WorkflowRun) { r.Event = gh.Ptr("push") }}, + {name: "other head", mutate: func(r *gh.WorkflowRun) { r.HeadSHA = gh.Ptr("old") }}, + {name: "other head repository", headRepo: "other/repo"}, + {name: "linked to other PR", mutate: func(r *gh.WorkflowRun) { r.PullRequests = []*gh.PullRequest{{Number: gh.Ptr(8)}} }}, + {name: "linked to this PR", mutate: func(r *gh.WorkflowRun) { r.PullRequests = []*gh.PullRequest{{Number: gh.Ptr(7)}} }, want: true}, + {name: "no id", mutate: func(r *gh.WorkflowRun) { r.ID = nil }}, + } { + t.Run(tc.name, func(t *testing.T) { + run := base() + if tc.mutate != nil { + tc.mutate(run) + } + if got := workflowRunApprovable(run, 7, "head1", tc.headRepo); got != tc.want { + t.Fatalf("approvable = %v, want %v", got, tc.want) + } + }) + } +} + +// The probe behind the #16599 caption must keep counting every gated run, +// whatever its event; the event filter belongs to the approval decision +// only (hivecommons/hive#16682). +func TestWorkflowApprovalProbeCountsEveryEvent(t *testing.T) { + target := gatedRun(12, "head1", "outsider") + target.Event = gh.Ptr("pull_request_target") + got := workflowApprovalFromRuns([]*gh.WorkflowRun{gatedRun(11, "head1", "outsider"), target}, time.Now()) + if got == nil || got.Pending != 2 { + t.Fatalf("probe narrowed the caption: %+v", got) + } + var event string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + event = r.URL.Query().Get("event") + _ = json.NewEncoder(w).Encode(map[string]any{"workflow_runs": []*gh.WorkflowRun{target}}) + })) + defer srv.Close() + c := newTestClient(t, srv, "org", []string{"probe-events"}) + t.Cleanup(func() { forgetWorkflowApproval("org/probe-events", "head1") }) + if wa := c.workflowRunsAwaitingApproval(context.Background(), "org/probe-events", "head1"); wa == nil || wa.Pending != 1 { + t.Fatalf("pull_request_target gated run dropped from the probe: %+v", wa) + } + if event != "" { + t.Fatalf("probe filtered by event=%q", event) + } +} + +func gatedRun(id int64, head, actor string) *gh.WorkflowRun { + return &gh.WorkflowRun{ + ID: gh.Ptr(id), HeadSHA: gh.Ptr(head), Event: gh.Ptr("pull_request"), + Status: gh.Ptr("completed"), Conclusion: gh.Ptr(WorkflowApprovalStatus), + TriggeringActor: &gh.User{Login: gh.Ptr(actor)}, + HeadRepository: &gh.Repository{FullName: gh.Ptr("fork/repo")}, + } +} + +type workflowApprovalFixture struct { + mu sync.Mutex + fresh *gh.PullRequest + posts []string + freshReads int + approvalStatus int +} + +func (f *workflowApprovalFixture) counts() (int, int) { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.posts), f.freshReads +} + +// newWorkflowApprovalFixture serves the PR re-read and the approve POST +// for org/repo#7 at head1, a dependabot PR with two gated runs triggered +// by an untrusted actor. +func newWorkflowApprovalFixture(t *testing.T) (*Client, *workflowApprovalFixture, []PullRequest) { + t.Helper() + f := &workflowApprovalFixture{ + fresh: &gh.PullRequest{State: gh.Ptr("open"), Number: gh.Ptr(7), User: &gh.User{Login: gh.Ptr("dependabot[bot]")}, + Head: &gh.PullRequestBranch{SHA: gh.Ptr("head1"), Repo: &gh.Repository{FullName: gh.Ptr("fork/repo")}}}, + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/org/repo/pulls/7": + f.freshReads++ + _ = json.NewEncoder(w).Encode(f.fresh) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/approve"): + f.posts = append(f.posts, r.URL.Path) + if f.approvalStatus != 0 { + http.Error(w, `{"message":"Resource not accessible by integration"}`, f.approvalStatus) + return + } + w.WriteHeader(http.StatusCreated) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL) + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + c := newTestClient(t, srv, "org", []string{"repo"}) + return c, f, []PullRequest{gatedPR("dependabot[bot]", gatedRun(11, "head1", "outsider"), gatedRun(12, "head1", "outsider"))} +} + +func gatedPR(author string, runs ...*gh.WorkflowRun) PullRequest { + now := time.Now().UTC() + return PullRequest{Repo: "org/repo", Number: 7, Author: author, HeadSHA: "head1", CIStatus: "pending", State: "open", + CIActivity: &PRCIActivity{Head: "head1", ObservedAt: &now, WorkflowApproval: workflowApprovalFromRuns(runs, now)}} +} + +func TestSweepWorkflowApprovalsOncePerHeadAndForgetsProbe(t *testing.T) { + c, f, prs := newWorkflowApprovalFixture(t) + workflowApprovalCache.Store("org/repo@head1", workflowApprovalEntry{at: time.Now(), val: prs[0].CIActivity.WorkflowApproval}) + t.Cleanup(func() { forgetWorkflowApproval("org/repo", "head1") }) + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + if posts, reads := f.counts(); posts != 2 || reads != 1 { + t.Fatalf("first pass: posts=%d fresh reads=%d", posts, reads) + } + if _, ok := workflowApprovalCache.Load("org/repo@head1"); ok { + t.Fatal("probe cache kept after approving; the next cycle would not see the runs start") + } + stats := c.WorkflowApprovalsStatus() + if stats.Approved != 2 || stats.Denied != 0 || stats.Last == nil || stats.Last.RunID != 12 || stats.Last.Outcome != "approved" { + t.Fatalf("stats=%+v", stats) + } + // Same head still gated next cycle: no second pass, not even a re-read. + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + if posts, reads := f.counts(); posts != 2 || reads != 1 { + t.Fatalf("second pass repeated: posts=%d fresh reads=%d", posts, reads) + } + // A new head re-arms the pass. + next := gatedPR("dependabot[bot]", gatedRun(21, "head2", "outsider")) + next.HeadSHA, next.CIActivity.Head = "head2", "head2" + f.mu.Lock() + f.fresh.Head.SHA = gh.Ptr("head2") + f.mu.Unlock() + c.SweepWorkflowApprovals(context.Background(), []PullRequest{next}, config.GovernorCIConfig{}) + if posts, _ := f.counts(); posts != 3 { + t.Fatalf("new head not approved: posts=%d", posts) + } +} + +func TestSweepWorkflowApprovalsConcurrentPassesApproveOnce(t *testing.T) { + c, f, _ := newWorkflowApprovalFixture(t) + var wg sync.WaitGroup + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + prs := []PullRequest{gatedPR("dependabot[bot]", gatedRun(11, "head1", "outsider"))} + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + }() + } + wg.Wait() + if posts, _ := f.counts(); posts != 1 { + t.Fatalf("concurrent passes approved %d times", posts) + } +} + +func TestSweepWorkflowApprovalsPermissionRefusalOnce(t *testing.T) { + for _, code := range []int{http.StatusForbidden, http.StatusNotFound} { + t.Run(http.StatusText(code), func(t *testing.T) { + c, f, prs := newWorkflowApprovalFixture(t) + f.approvalStatus = code + original := prs[0].CIActivity.WorkflowApproval + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + if wa := prs[0].CIActivity.WorkflowApproval; wa == nil || !wa.PermissionDenied { + t.Fatalf("refusal not surfaced: %+v", wa) + } + if original.PermissionDenied { + t.Fatal("shared probe result was mutated") + } + // Next cycle: a fresh probe snapshot, no new POST, and the + // refusal still reaches the caption through EnrichCIStatus's + // ledger overlay, even on cycles that skip the sweep. + prs = []PullRequest{gatedPR("dependabot[bot]", gatedRun(11, "head1", "outsider"), gatedRun(12, "head1", "outsider"))} + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + if posts, _ := f.counts(); posts != 1 { + t.Fatalf("refusal retried: posts=%d", posts) + } + if wa := c.workflowApprovalWithLedger("org/repo", 7, "head1", prs[0].CIActivity.WorkflowApproval); wa == nil || !wa.PermissionDenied { + t.Fatalf("ledger lost the refusal: %+v", wa) + } + if wa := c.workflowApprovalWithLedger("org/repo", 8, "head1", prs[0].CIActivity.WorkflowApproval); wa.PermissionDenied { + t.Fatal("refusal leaked to another PR") + } + stats := c.WorkflowApprovalsStatus() + if stats.PermissionErrors != 1 || stats.Approved != 0 || stats.Last == nil || stats.Last.Outcome != "permission_error" { + t.Fatalf("stats=%+v", stats) + } + }) + } +} + +func TestSweepWorkflowApprovalsUntrustedThenAdmitted(t *testing.T) { + c, f, _ := newWorkflowApprovalFixture(t) + f.fresh.User.Login = gh.Ptr("outsider") + for range 2 { + prs := []PullRequest{gatedPR("outsider", gatedRun(11, "head1", "outsider"), gatedRun(12, "head1", "outsider"))} + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + } + if posts, reads := f.counts(); posts != 0 || reads != 0 { + t.Fatalf("untrusted head: posts=%d fresh reads=%d", posts, reads) + } + if stats := c.WorkflowApprovalsStatus(); stats.Denied != 2 { + t.Fatalf("denials not counted once per head: %+v", stats) + } + f.mu.Lock() + f.fresh.Labels = []*gh.Label{{Name: gh.Ptr(c.AutoMergeLabel())}} + f.mu.Unlock() + prs := []PullRequest{gatedPR("outsider", gatedRun(11, "head1", "outsider"))} + prs[0].Labels = []string{c.AutoMergeLabel()} + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + if posts, _ := f.counts(); posts != 1 { + t.Fatalf("owner admission did not release the head: posts=%d", posts) + } +} + +func TestSweepWorkflowApprovalsGuards(t *testing.T) { + for _, tc := range []struct { + name string + setup func(*Client, *workflowApprovalFixture, []PullRequest, *config.GovernorCIConfig) + }{ + {"disabled", func(_ *Client, _ *workflowApprovalFixture, _ []PullRequest, p *config.GovernorCIConfig) { + p.AutoApproveWorkflows = gh.Ptr(false) + }}, + {"explicit empty actors", func(_ *Client, _ *workflowApprovalFixture, _ []PullRequest, p *config.GovernorCIConfig) { + p.AutoApproveWorkflowActors = &[]string{} + }}, + {"pull_request_target runs", func(_ *Client, _ *workflowApprovalFixture, p []PullRequest, _ *config.GovernorCIConfig) { + for _, r := range p[0].CIActivity.WorkflowApproval.runs { + r.Event = gh.Ptr("pull_request_target") + } + }}, + {"draft", func(_ *Client, _ *workflowApprovalFixture, p []PullRequest, _ *config.GovernorCIConfig) { + p[0].Draft = true + }}, + {"held", func(_ *Client, _ *workflowApprovalFixture, p []PullRequest, _ *config.GovernorCIConfig) { + p[0].Labels = []string{"hold"} + }}, + {"paused", func(c *Client, _ *workflowApprovalFixture, _ []PullRequest, _ *config.GovernorCIConfig) { + c.SetRepoPausedFunc(func(string) bool { return true }) + }}, + {"stale activity head", func(_ *Client, _ *workflowApprovalFixture, p []PullRequest, _ *config.GovernorCIConfig) { + p[0].CIActivity.Head = "old" + }}, + {"fresh head moved", func(_ *Client, f *workflowApprovalFixture, _ []PullRequest, _ *config.GovernorCIConfig) { + f.fresh.Head.SHA = gh.Ptr("head2") + }}, + {"fresh closed", func(_ *Client, f *workflowApprovalFixture, _ []PullRequest, _ *config.GovernorCIConfig) { + f.fresh.State = gh.Ptr("closed") + }}, + {"fresh hold label", func(_ *Client, f *workflowApprovalFixture, _ []PullRequest, _ *config.GovernorCIConfig) { + f.fresh.Labels = []*gh.Label{{Name: gh.Ptr("hold")}} + }}, + {"fresh author untrusted", func(_ *Client, f *workflowApprovalFixture, _ []PullRequest, _ *config.GovernorCIConfig) { + f.fresh.User.Login = gh.Ptr("outsider") + }}, + {"run from other head repository", func(_ *Client, f *workflowApprovalFixture, _ []PullRequest, _ *config.GovernorCIConfig) { + f.fresh.Head.Repo.FullName = gh.Ptr("other/repo") + }}, + } { + t.Run(tc.name, func(t *testing.T) { + c, f, prs := newWorkflowApprovalFixture(t) + policy := config.GovernorCIConfig{} + tc.setup(c, f, prs, &policy) + c.SweepWorkflowApprovals(context.Background(), prs, policy) + if posts, _ := f.counts(); posts != 0 { + t.Fatalf("guard allowed %d approvals", posts) + } + }) + } +} + +func TestWorkflowApprovalLedgerEviction(t *testing.T) { + var l workflowApprovalLedger + now := time.Now() + old := workflowApprovalKey{repo: "org/repo", number: 7, head: "head1"} + other := workflowApprovalKey{repo: "org/repo", number: 9, head: "head9"} + l.touchLocked(old, now) + l.touchLocked(other, now) + l.touchLocked(workflowApprovalKey{repo: "org/repo", number: 7, head: "head2"}, now) + if _, ok := l.attempts[old]; ok || len(l.attempts) != 2 { + t.Fatalf("superseded head kept: %+v", l.attempts) + } + l.touchLocked(other, now.Add(workflowApprovalAttemptTTL)) + if _, ok := l.attempts[other]; !ok || len(l.attempts) != 1 { + t.Fatalf("TTL eviction wrong: %+v", l.attempts) + } +} From f868e0a33e73008a7cabc9e7095362858ee0f506 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:58:55 -0500 Subject: [PATCH 2/7] fix(github): bind workflow-run approval admission to the approved head The sweep trusted a PR for the automerge label alone, which is bound to no head and names no approver. Read the stage record's head-bound admission (dashboard Approve by a verified owner or merger, #15136) instead; a label on its own never approves a run. Move the ledger mutations into markDeniedCounted/claim so the once-per-head invariant lives on the ledger type. Document that the default-on sweep needs the App's Actions: Read and write and how it relates to /ok-to-test. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../added-auto-approve-gated-workflows.md | 2 +- src/docs/acmm-policy-matrix.md | 19 ++-- src/docs/github-app-setup.md | 6 +- .../operator-reference/runtime-and-quota.md | 15 ++- src/docs/webhooks.md | 2 +- src/hive.yaml.example | 4 +- src/pkg/config/governor_ci.go | 3 +- src/pkg/github/workflow_auto_approval.go | 94 +++++++++++++------ src/pkg/github/workflow_auto_approval_test.go | 47 ++++++++++ 9 files changed, 147 insertions(+), 45 deletions(-) diff --git a/changelog.d/added-auto-approve-gated-workflows.md b/changelog.d/added-auto-approve-gated-workflows.md index 564e6ada48..967f91cca5 100644 --- a/changelog.d/added-auto-approve-gated-workflows.md +++ b/changelog.d/added-auto-approve-gated-workflows.md @@ -1 +1 @@ -- The hive approves workflow runs GitHub holds behind "Approve and run workflows" once per PR head for trusted bots (`governor.ci.auto_approve_workflow_actors`, default dependabot and renovate), its own App and owner-admitted PRs (`governor.ci.auto_approve_workflows`, default on); counts are in `/api/status` `workflow_approvals`, and a missing `actions: write` permission shows `CI waiting · needs workflow approval on GitHub`. +- The hive approves workflow runs GitHub holds behind "Approve and run workflows" once per PR head for trusted bots (`governor.ci.auto_approve_workflow_actors`, default dependabot and renovate), its own App and heads a person admitted from the dashboard (`governor.ci.auto_approve_workflows`, default on; needs App **Actions: Read and write**, or set it `false` to keep Actions: Read); counts are in `/api/status` `workflow_approvals`, and a missing `actions: write` permission shows `CI waiting · needs workflow approval on GitHub`. diff --git a/src/docs/acmm-policy-matrix.md b/src/docs/acmm-policy-matrix.md index d4ab1c384e..fe32ca11b1 100644 --- a/src/docs/acmm-policy-matrix.md +++ b/src/docs/acmm-policy-matrix.md @@ -193,12 +193,19 @@ unverifiable claims, or `hive-decision-risk: high`. Set `escalate` to park every decision question at PR stage 085. Use actual holds or GitHub branch rules for a universal merge stop. -#### Workflow approval, not App Actions-write permission - -For trusted same-repo bot/App/registry-trusted clanker PRs with -`action_required` workflow runs, Hive posts `/ok-to-test` once per head. -The repository's self-contained `hive-ok-to-test` workflow approves the runs -using its own `GITHUB_TOKEN`; the App needs no Actions-write grant. If that +#### Workflow approval + +By default (`governor.ci.auto_approve_workflows: true`) Hive approves +`action_required` `pull_request` runs itself, once per PR head, with the +App token: for Dependabot/Renovate/App-authored or -triggered runs and for +heads a verified owner or merger admitted from the dashboard. This needs +the App's **Actions: Read and write**; a `403` is recorded once as a +`permission_error` and the CI caption says the run needs approval on +GitHub. With the sweep set to `false` (or the grant missing), trusted +same-repo bot/App/registry-trusted clanker PRs fall back to the +`/ok-to-test` path: Hive posts the command once per head and the +repository's self-contained `hive-ok-to-test` workflow approves the runs +using its own `GITHUB_TOKEN`, with no App Actions-write grant. If that workflow is missing or `sentinel-alert` is present, Hive surfaces `workflow-approval-required:` / PR stage 085 for human action. diff --git a/src/docs/github-app-setup.md b/src/docs/github-app-setup.md index 32fc466ff8..ead7c7fb8e 100644 --- a/src/docs/github-app-setup.md +++ b/src/docs/github-app-setup.md @@ -40,10 +40,10 @@ Fine-grained PATs are supported — the token is sent as a plain bearer, same as | Issues | Read and write | Read and write | Read and write | | Pull requests | Read | Read | Read and write | | Checks | Read | Read | Read | -| Actions | Read | Read | Read | +| Actions | Read and write | Read and write | Read and write — needed by the default-on gated-run approval sweep (`governor.ci.auto_approve_workflows`); Read suffices with it set to `false`, see below | | Commit statuses | Read | Read | Read and write — needed when `governor.labels.automerge` is the default `lgtm` on a Prow repository, so the queue action can set the `prow/lgtm` status beside the label. With only Read, every queue action still applies the label but posts a PR comment that the status could not be set. | -Hive does not require **Actions: Read and write** for bot workflow-run approvals; **Actions: Read** is enough to inspect runs. The one direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — does need Read and write. Granting it is **optional**: without it the call fails with `403 Resource not accessible by integration`, the hive labels the PR `hive:unauthorized`, posts one comment naming the permission and the human step (**Approve and run** on the checks banner or Actions tab, with the run ids), logs `lane unauthorized` once per head, parks the PR at 085 (`Awaiting human: approve workflow runs` in the activity monitor), and clears all of it the tick the required checks report ([#14589](https://github.com/hivecommons/hive/issues/14589)). When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; no Prow and no Hive App Actions-write grant are required. Hive never approves fork heads or PRs carrying `sentinel-alert`. +Since the gated-run approval sweep (`governor.ci.auto_approve_workflows`, **default on**, [#16603](https://github.com/hivecommons/hive/issues/16603)) Hive approves `action_required` `pull_request` runs with the App token — `POST /actions/runs/{id}/approve`, once per PR head, for Dependabot/Renovate/App-authored or -triggered runs and for heads a verified owner or merger admitted from the dashboard — which needs **Actions: Read and write**. With only **Actions: Read** the call fails with `403`, the hive records one `permission_error` in `/api/status` `workflow_approvals`, logs `workflow approval refused; needs workflow approval on GitHub`, and the CI caption reads `CI waiting · needs workflow approval on GitHub`; set `governor.ci.auto_approve_workflows: false` to stay on Read and leave approvals to the `/ok-to-test` workflow described below. The other direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — needs the same grant. For that path it is **optional**: without it the call fails with `403 Resource not accessible by integration`, the hive labels the PR `hive:unauthorized`, posts one comment naming the permission and the human step (**Approve and run** on the checks banner or Actions tab, with the run ids), logs `lane unauthorized` once per head, parks the PR at 085 (`Awaiting human: approve workflow runs` in the activity monitor), and clears all of it the tick the required checks report ([#14589](https://github.com/hivecommons/hive/issues/14589)). When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, and the approval sweep is off or lacks the grant, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; that path needs no Prow and no Hive App Actions-write grant. Hive never approves fork heads or PRs carrying `sentinel-alert`. Install the workflow in each governed repository: run `hivectl ok-to-test-template > .github/workflows/hive-ok-to-test.yml` against your hive (it reads the App bot login from `/api/config`; pass `--app-login [bot]` to override), or copy `src/docs/templates/hive-ok-to-test.yml` and replace `HIVE_APP_LOGIN[bot]` with the App bot login shown by Hive for that installation. @@ -90,7 +90,7 @@ Repository permissions used by the dashboard setup UI are: | Issues | Read/write | Enumerate, comment on, create, and close issues. | | Pull requests | Read/write | Create, update, approve/merge, and inspect PRs. | | Checks | Read-only | Monitor CI status. | -| Actions | Read-only (Read and write to approve registry-trusted contributors' held runs) | Inspect workflow runs. If GitHub holds trusted Dependabot/App/clanker runs in `action_required`, Hive posts `/ok-to-test`; the repository-local `hive-ok-to-test` workflow uses its own `GITHUB_TOKEN` with Actions write to approve those runs. With Read and write, the contributor lane also approves held runs directly for a PR author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`). Optional: without it the hive marks such a PR `hive:unauthorized` and waits for a maintainer to click **Approve and run** ([#14589](https://github.com/hivecommons/hive/issues/14589)). | +| Actions | Read and write (Read-only with `governor.ci.auto_approve_workflows: false`) | Inspect workflow runs; the default-on approval sweep approves gated `pull_request` runs for trusted bots, the App and dashboard-admitted heads with the App token ([#16603](https://github.com/hivecommons/hive/issues/16603)). If the sweep is off or refused and GitHub holds trusted Dependabot/App/clanker runs in `action_required`, Hive posts `/ok-to-test`; the repository-local `hive-ok-to-test` workflow uses its own `GITHUB_TOKEN` with Actions write to approve those runs. With Read and write, the contributor lane also approves held runs directly for a PR author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`). Optional: without it the hive marks such a PR `hive:unauthorized` and waits for a maintainer to click **Approve and run** ([#14589](https://github.com/hivecommons/hive/issues/14589)). | | Administration | Read-only | Read branch-protection rules before the merge-request watcher lands a PR; Hive refuses closed if it cannot verify the base branch is protected. | | Commit statuses | Read/write | Needed when `governor.labels.automerge` is the default `lgtm` on a repository running Prow's commit-bound `lgtm` (prow-github-actions v3): the queue action sets a `prow/lgtm` success status on the approved head so Prow does not strip the label. Without the write grant the label and approval still land, but every queue action takes the failure branch and posts a PR comment saying the status could not be set. Choose a distinct label such as `hive/auto-merge` if you would rather keep this at Read. | diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index d69f28cf92..17eeebac08 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -270,8 +270,11 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. GitHub`. Right after it, the eval cycle runs the workflow-approval sweep, which approves a head's gated `pull_request` runs **at most once per PR head** ([#16603](https://github.com/hivecommons/hive/issues/16603)) when - the head is trusted: the PR carries the owner's automerge admission label - (`lgtm` by default), or the PR author or the run's triggering actor is + the head is trusted: a person admitted **this head** (a verified owner's + or merger's dashboard Approve, recorded on the stage record and dropped + by the next push — [#15136](https://github.com/hivecommons/hive/issues/15136); + the automerge label on its own never counts, since it is bound to no head + and names no approver), or the PR author or the run's triggering actor is this hive's App or is listed in `governor.ci.auto_approve_workflow_actors` (default `['dependabot[bot]', 'renovate[bot]']`; an explicit `[]` trusts only the App and owner admission). Runs of other events (for example @@ -292,7 +295,13 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. lacks `actions: write`) is recorded once, never retried for that head, logged as `workflow approval refused; needs workflow approval on GitHub`, and the caption becomes `CI waiting · needs workflow approval on GitHub` - on every later cycle, including ones that skip the sweep. Each approved + on every later cycle, including ones that skip the sweep. The sweep uses + the App token, so it needs **Actions: Read and write** on the App + ([github-app-setup.md](../github-app-setup.md)); it runs alongside the + older `/ok-to-test` path, in which the contributor lane posts a comment + and the repository's own `hive-ok-to-test` workflow approves with its + `GITHUB_TOKEN` — operators who want to stay on Actions: Read and that + path alone set `governor.ci.auto_approve_workflows: false`. Each approved run logs one `approved gated workflow run` INFO line; counts since boot are at `/api/status` `workflow_approvals` (`approved`, `denied`, `permission_errors`, `last`). Approved runs execute the head's workflow diff --git a/src/docs/webhooks.md b/src/docs/webhooks.md index 65df42f28b..53743ab215 100644 --- a/src/docs/webhooks.md +++ b/src/docs/webhooks.md @@ -115,7 +115,7 @@ 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.auto_approve_workflows` | `true` (unset = on) | approve GitHub-gated (`action_required`) `pull_request` workflow runs once per trusted PR head, in the sweep right after CI enrichment; the sweep is skipped on cycles where the API-budget decision sets `SkipOptional` (`conserve`/`critical` mode, off-cadence and cached-snapshot cycles). `false` leaves the gate to a person. 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 for workflow approval, besides this hive's App and owner-admitted (automerge-labelled) PRs; an explicit `[]` trusts only those two | +| `governor.ci.auto_approve_workflow_actors` | `['dependabot[bot]', 'renovate[bot]']` | PR authors / triggering actors trusted for workflow approval, besides this hive's App and heads a person admitted from the dashboard (the automerge label alone does not count); an explicit `[]` trusts only those two | | `governor.ci_failure_kick_cooldown_s` | `600` | at most one webhook-triggered CI-failure kick or nudge per PR head in this window | | `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 | diff --git a/src/hive.yaml.example b/src/hive.yaml.example index b3d64c038a..6c7dd13751 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -418,7 +418,9 @@ governor: # 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. + # An explicit [] trusts only this hive's App and heads a person admitted + # from the dashboard (Approve); the automerge label alone never counts. + # Approving uses the App token: the App needs Actions: Read and write. 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) diff --git a/src/pkg/config/governor_ci.go b/src/pkg/config/governor_ci.go index 8cbb571ecc..01af42735f 100644 --- a/src/pkg/config/governor_ci.go +++ b/src/pkg/config/governor_ci.go @@ -8,7 +8,8 @@ type GovernorCIConfig struct { // on trusted PR heads; false leaves the gate to a person. AutoApproveWorkflows *bool `yaml:"auto_approve_workflows,omitempty" json:"auto_approve_workflows,omitempty"` // AutoApproveWorkflowActors are the PR authors / triggering actors - // trusted besides the hive's App and owner-admitted PRs. Unset means + // trusted besides the hive's App and heads a person admitted from the + // dashboard (stage-record admission, head-bound). Unset means // DefaultAutoApproveWorkflowActors; an explicit [] trusts neither. AutoApproveWorkflowActors *[]string `yaml:"auto_approve_workflow_actors,omitempty" json:"auto_approve_workflow_actors,omitempty"` } diff --git a/src/pkg/github/workflow_auto_approval.go b/src/pkg/github/workflow_auto_approval.go index e341f65c63..1b45f9f2b2 100644 --- a/src/pkg/github/workflow_auto_approval.go +++ b/src/pkg/github/workflow_auto_approval.go @@ -11,6 +11,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/stagelabels" "github.com/hivecommons/hive/pkg/writeback" ) @@ -44,6 +45,9 @@ type workflowApprovalLedger struct { mu sync.Mutex attempts map[workflowApprovalKey]workflowApprovalAttempt status WorkflowApprovalsStatus + // stageStore is where owner admissions are read from; nil means the + // process-wide stagelabels.Shared(). Tests inject their own. + stageStore *stagelabels.Store } // WorkflowApprovalsStatus is /api/status.workflow_approvals: decisions @@ -100,6 +104,38 @@ func (l *workflowApprovalLedger) touchLocked(key workflowApprovalKey, now time.T return attempt } +// touch marks the head live and returns its entry as it was. +func (l *workflowApprovalLedger) touch(key workflowApprovalKey, now time.Time) workflowApprovalAttempt { + l.mu.Lock() + defer l.mu.Unlock() + return l.touchLocked(key, now) +} + +// markDeniedCounted notes that the head's denials went into the counters, +// so a later pass over the same head does not count them again. +func (l *workflowApprovalLedger) markDeniedCounted(key workflowApprovalKey) { + l.mu.Lock() + defer l.mu.Unlock() + attempt := l.attempts[key] + attempt.deniedCounted = true + l.attempts[key] = attempt +} + +// claim takes the head's one approval pass. It returns false when another +// pass (a concurrent cycle, or an earlier one on the same head) already +// has it; the once-per-head invariant lives here, not with callers. +func (l *workflowApprovalLedger) claim(key workflowApprovalKey) bool { + l.mu.Lock() + defer l.mu.Unlock() + attempt := l.attempts[key] + if attempt.attempted { + return false + } + attempt.attempted = true + l.attempts[key] = attempt + return true +} + func (l *workflowApprovalLedger) record(key workflowApprovalKey, runID int64, outcome string) { l.mu.Lock() defer l.mu.Unlock() @@ -142,10 +178,10 @@ func (c *Client) workflowApprovalWithLedger(repo string, number int, head string return &out } -// workflowApprovalTrusted is the trust policy: the owner admitted the PR -// (automerge label), or the PR author or the run's triggering actor is the -// hive's App or in the allowlist. A trusted author covers every gated run -// on the head, since the code under test is theirs. +// workflowApprovalTrusted is the trust policy: a person admitted this very +// head (workflowApprovalAdmitted), or the PR author or the run's triggering +// actor is the hive's App or in the allowlist. A trusted author covers +// every gated run on the head, since the code under test is theirs. func workflowApprovalTrusted(author, actor, app string, admitted bool, actors []string) bool { if admitted { return true @@ -202,18 +238,27 @@ func (c *Client) workflowApprovalHeld(labels []string) bool { return c.isHeld(labels) || c.isExempt(labels) || c.sentinelBlockedLabel(labels) != "" } -func (c *Client) workflowApprovalAdmitted(labels []string) bool { - for _, label := range labels { - if strings.EqualFold(strings.TrimSpace(label), c.AutoMergeLabel()) { - return true - } +// workflowApprovalAdmitted reports whether a person's approval admitted +// exactly this head: the stage record's admission (hivecommons/hive#15136), +// which the dashboard Approve writes for a verified owner or merger and +// which a new push drops. The automerge label on its own never counts: it +// is not bound to a head and says nothing about who applied it, so a +// contributor admitted at one head could otherwise push another with +// edited workflow files and have its runs approved without a human click. +func (c *Client) workflowApprovalAdmitted(repo string, number int, head string) bool { + if c == nil || strings.TrimSpace(head) == "" { + return false } - return false + store := c.workflowApprovals.stageStore + if store == nil { + store = stagelabels.Shared() + } + rec, ok := store.Get(stagelabels.Key(repo, number)) + return ok && rec.Admission(head) != "" } // splitTrustedWorkflowRuns partitions the approvable gated runs by policy. -func (c *Client) splitTrustedWorkflowRuns(runs []*gh.WorkflowRun, number int, head, headRepo, author string, labels, actors []string) (trusted, denied []*gh.WorkflowRun) { - admitted := c.workflowApprovalAdmitted(labels) +func (c *Client) splitTrustedWorkflowRuns(runs []*gh.WorkflowRun, number int, head, headRepo, author string, admitted bool, actors []string) (trusted, denied []*gh.WorkflowRun) { app := c.AppBotLogin() for _, run := range runs { if !workflowRunApprovable(run, number, head, headRepo) { @@ -251,19 +296,16 @@ func (c *Client) SweepWorkflowApprovals(ctx context.Context, prs []PullRequest, continue } wa := a.WorkflowApproval - c.workflowApprovals.mu.Lock() - previous := c.workflowApprovals.touchLocked(key, time.Now()) - c.workflowApprovals.mu.Unlock() + previous := c.workflowApprovals.touch(key, time.Now()) if previous.attempted { continue } - trusted, denied := c.splitTrustedWorkflowRuns(wa.runs, pr.Number, pr.HeadSHA, "", pr.Author, pr.Labels, actors) + admitted := c.workflowApprovalAdmitted(key.repo, pr.Number, pr.HeadSHA) + // This first split only counts denials off the listing; its trusted + // set is discarded and recomputed after the fresh PR read below. + trusted, denied := c.splitTrustedWorkflowRuns(wa.runs, pr.Number, pr.HeadSHA, "", pr.Author, admitted, actors) if len(denied) > 0 && !previous.deniedCounted { - c.workflowApprovals.mu.Lock() - attempt := c.workflowApprovals.attempts[key] - attempt.deniedCounted = true - c.workflowApprovals.attempts[key] = attempt - c.workflowApprovals.mu.Unlock() + c.workflowApprovals.markDeniedCounted(key) for _, run := range denied { c.workflowApprovals.record(key, run.GetID(), "denied") } @@ -283,7 +325,7 @@ func (c *Client) SweepWorkflowApprovals(ctx context.Context, prs []PullRequest, if c.workflowApprovalHeld(labels) || headRepo == "" { continue } - trusted, _ = c.splitTrustedWorkflowRuns(wa.runs, pr.Number, pr.HeadSHA, headRepo, fresh.GetUser().GetLogin(), labels, actors) + trusted, _ = c.splitTrustedWorkflowRuns(wa.runs, pr.Number, pr.HeadSHA, headRepo, fresh.GetUser().GetLogin(), admitted, actors) if len(trusted) == 0 { continue } @@ -294,13 +336,7 @@ func (c *Client) SweepWorkflowApprovals(ctx context.Context, prs []PullRequest, } // Claim before the first POST: neither a concurrent cycle nor an // unchanged head repeats the pass, even after a partial failure. - c.workflowApprovals.mu.Lock() - attempt := c.workflowApprovals.attempts[key] - claimed := !attempt.attempted - attempt.attempted = true - c.workflowApprovals.attempts[key] = attempt - c.workflowApprovals.mu.Unlock() - if !claimed { + if !c.workflowApprovals.claim(key) { continue } approved := false diff --git a/src/pkg/github/workflow_auto_approval_test.go b/src/pkg/github/workflow_auto_approval_test.go index 6dad6daf53..3ec65ee761 100644 --- a/src/pkg/github/workflow_auto_approval_test.go +++ b/src/pkg/github/workflow_auto_approval_test.go @@ -12,6 +12,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/stagelabels" ) func TestWorkflowApprovalTrusted(t *testing.T) { @@ -150,9 +151,22 @@ func newWorkflowApprovalFixture(t *testing.T) (*Client, *workflowApprovalFixture })) t.Cleanup(srv.Close) c := newTestClient(t, srv, "org", []string{"repo"}) + c.workflowApprovals.stageStore = stagelabels.NewStore("", nil) return c, f, []PullRequest{gatedPR("dependabot[bot]", gatedRun(11, "head1", "outsider"), gatedRun(12, "head1", "outsider"))} } +// admitHead records a person's dashboard Approve of head on org/repo#7's +// stage record, the way api_repo_item_decision.go does. +func admitHead(t *testing.T, c *Client, head string) { + t.Helper() + key := stagelabels.Key("org/repo", 7) + store := c.workflowApprovals.stageStore + store.Observe(key, stagelabels.ReviewPending, "test") + if !store.NoteAdmission(key, head, stagelabels.OperatorApprovalAdmission("owner"), time.Now()) { + t.Fatal("NoteAdmission refused the record") + } +} + func gatedPR(author string, runs ...*gh.WorkflowRun) PullRequest { now := time.Now().UTC() return PullRequest{Repo: "org/repo", Number: 7, Author: author, HeadSHA: "head1", CIStatus: "pending", State: "open", @@ -256,17 +270,50 @@ func TestSweepWorkflowApprovalsUntrustedThenAdmitted(t *testing.T) { if stats := c.WorkflowApprovalsStatus(); stats.Denied != 2 { t.Fatalf("denials not counted once per head: %+v", stats) } + // The automerge label alone is not an admission: it is not bound to a + // head and says nothing about who applied it. f.mu.Lock() f.fresh.Labels = []*gh.Label{{Name: gh.Ptr(c.AutoMergeLabel())}} f.mu.Unlock() prs := []PullRequest{gatedPR("outsider", gatedRun(11, "head1", "outsider"))} prs[0].Labels = []string{c.AutoMergeLabel()} c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) + if posts, _ := f.counts(); posts != 0 { + t.Fatalf("bare automerge label released the head: posts=%d", posts) + } + // A person's admission of this head does. + admitHead(t, c, "head1") + c.SweepWorkflowApprovals(context.Background(), prs, config.GovernorCIConfig{}) if posts, _ := f.counts(); posts != 1 { t.Fatalf("owner admission did not release the head: posts=%d", posts) } } +// A contributor admitted at one head pushes another: the admission was for +// what the person read, so the new head's gated runs wait for a person. +func TestSweepWorkflowApprovalsAdmissionIsHeadBound(t *testing.T) { + c, f, _ := newWorkflowApprovalFixture(t) + admitHead(t, c, "head1") + f.mu.Lock() + f.fresh.User.Login = gh.Ptr("outsider") + f.fresh.Head.SHA = gh.Ptr("head2") + f.fresh.Labels = []*gh.Label{{Name: gh.Ptr(c.AutoMergeLabel())}} + f.mu.Unlock() + next := gatedPR("outsider", gatedRun(21, "head2", "outsider")) + next.HeadSHA, next.CIActivity.Head = "head2", "head2" + next.Labels = []string{c.AutoMergeLabel()} + c.SweepWorkflowApprovals(context.Background(), []PullRequest{next}, config.GovernorCIConfig{}) + if posts, reads := f.counts(); posts != 0 || reads != 0 { + t.Fatalf("admission at head1 approved head2: posts=%d fresh reads=%d", posts, reads) + } + if stats := c.WorkflowApprovalsStatus(); stats.Denied != 1 || stats.Approved != 0 { + t.Fatalf("stats=%+v", stats) + } + if !c.workflowApprovalAdmitted("org/repo", 7, "head1") || c.workflowApprovalAdmitted("org/repo", 7, "head2") || c.workflowApprovalAdmitted("org/repo", 8, "head1") { + t.Fatal("admission lookup is not bound to repo, number and head") + } +} + func TestSweepWorkflowApprovalsGuards(t *testing.T) { for _, tc := range []struct { name string From aa82bc78730c6d2ac413b7027b73867cd8df7aba Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:10:09 -0500 Subject: [PATCH 3/7] docs(github): state the App-actor trust boundary for gated-run approval Document why trusting the App as a run's triggering actor cannot approve contributor code: GitHub gates only fork pull_request runs and the App cannot push to a fork, so an App-pushed same-repository branch is never gated. Code comment on workflowApprovalTrusted and the operator reference. The default of governor.ci.auto_approve_workflows stays as #16603 specifies (on); flipping it is the owner's call, not a code defect. Hive-Fix-Attempt: 2/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/operator-reference/runtime-and-quota.md | 7 ++++++- src/pkg/github/workflow_auto_approval.go | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index 17eeebac08..06866e27d1 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -277,7 +277,12 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. and names no approver), or the PR author or the run's triggering actor is this hive's App or is listed in `governor.ci.auto_approve_workflow_actors` (default `['dependabot[bot]', 'renovate[bot]']`; an explicit `[]` trusts - only the App and owner admission). Runs of other events (for example + only the App and owner admission). Trusting the App as triggering actor + covers heads the App pushed itself (its own PRs, rebases, review-fix + commits); it does not extend to contributor code, because GitHub holds + only fork `pull_request` runs behind the gate and the App cannot push to + a fork — a same-repository branch the App pushes to is never gated. Runs + of other events (for example `pull_request_target`) are counted in the caption but never approved. Guards: `governor.ci.auto_approve_workflows` (default `true` — unset means on; `false` leaves the gate to a person), the repo pause, hold / diff --git a/src/pkg/github/workflow_auto_approval.go b/src/pkg/github/workflow_auto_approval.go index 1b45f9f2b2..7b2d05f1a1 100644 --- a/src/pkg/github/workflow_auto_approval.go +++ b/src/pkg/github/workflow_auto_approval.go @@ -182,6 +182,15 @@ func (c *Client) workflowApprovalWithLedger(repo string, number int, head string // head (workflowApprovalAdmitted), or the PR author or the run's triggering // actor is the hive's App or in the allowlist. A trusted author covers // every gated run on the head, since the code under test is theirs. +// +// Trusting the App as triggering actor covers heads the App pushed itself +// (its own PRs, rebases and review-fix commits). GitHub only holds fork +// `pull_request` runs behind "Approve and run workflows", and the App +// cannot push to a fork, so this never approves a contributor's head the +// App merely pushed to: a same-repository branch is not gated, and a fork +// head is always triggered by the fork owner. Trust is per head, not per +// repository: a contributor PR later pushed by the App earns no trust for +// the heads the contributor pushed. func workflowApprovalTrusted(author, actor, app string, admitted bool, actors []string) bool { if admitted { return true From 2b258e64ea9573318f6f875287ca731177a67f67 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:24:29 -0500 Subject: [PATCH 4/7] docs(github): state which approval paths reach fork heads github-app-setup.md still said Hive never approves fork heads, which the gated-run approval sweep contradicts: GitHub holds only fork pull_request runs behind the gate, so the sweep (and the registry-trusted contributor lane) are exactly the paths that approve fork heads with the App token. Say so, keep the sentinel-alert exclusion, note the same second exception in the operator-reference automerge bullet, and document that a trusted author covers runs a fork collaborator pushed to the head. Hive-Fix-Attempt: 3/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/github-app-setup.md | 2 +- src/docs/operator-reference/README.md | 13 +++++++++---- src/docs/operator-reference/runtime-and-quota.md | 6 +++++- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/docs/github-app-setup.md b/src/docs/github-app-setup.md index ead7c7fb8e..3cc14622c5 100644 --- a/src/docs/github-app-setup.md +++ b/src/docs/github-app-setup.md @@ -43,7 +43,7 @@ Fine-grained PATs are supported — the token is sent as a plain bearer, same as | Actions | Read and write | Read and write | Read and write — needed by the default-on gated-run approval sweep (`governor.ci.auto_approve_workflows`); Read suffices with it set to `false`, see below | | Commit statuses | Read | Read | Read and write — needed when `governor.labels.automerge` is the default `lgtm` on a Prow repository, so the queue action can set the `prow/lgtm` status beside the label. With only Read, every queue action still applies the label but posts a PR comment that the status could not be set. | -Since the gated-run approval sweep (`governor.ci.auto_approve_workflows`, **default on**, [#16603](https://github.com/hivecommons/hive/issues/16603)) Hive approves `action_required` `pull_request` runs with the App token — `POST /actions/runs/{id}/approve`, once per PR head, for Dependabot/Renovate/App-authored or -triggered runs and for heads a verified owner or merger admitted from the dashboard — which needs **Actions: Read and write**. With only **Actions: Read** the call fails with `403`, the hive records one `permission_error` in `/api/status` `workflow_approvals`, logs `workflow approval refused; needs workflow approval on GitHub`, and the CI caption reads `CI waiting · needs workflow approval on GitHub`; set `governor.ci.auto_approve_workflows: false` to stay on Read and leave approvals to the `/ok-to-test` workflow described below. The other direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — needs the same grant. For that path it is **optional**: without it the call fails with `403 Resource not accessible by integration`, the hive labels the PR `hive:unauthorized`, posts one comment naming the permission and the human step (**Approve and run** on the checks banner or Actions tab, with the run ids), logs `lane unauthorized` once per head, parks the PR at 085 (`Awaiting human: approve workflow runs` in the activity monitor), and clears all of it the tick the required checks report ([#14589](https://github.com/hivecommons/hive/issues/14589)). When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, and the approval sweep is off or lacks the grant, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; that path needs no Prow and no Hive App Actions-write grant. Hive never approves fork heads or PRs carrying `sentinel-alert`. +Since the gated-run approval sweep (`governor.ci.auto_approve_workflows`, **default on**, [#16603](https://github.com/hivecommons/hive/issues/16603)) Hive approves `action_required` `pull_request` runs with the App token — `POST /actions/runs/{id}/approve`, once per PR head, for Dependabot/Renovate/App-authored or -triggered runs and for heads a verified owner or merger admitted from the dashboard — which needs **Actions: Read and write**. With only **Actions: Read** the call fails with `403`, the hive records one `permission_error` in `/api/status` `workflow_approvals`, logs `workflow approval refused; needs workflow approval on GitHub`, and the CI caption reads `CI waiting · needs workflow approval on GitHub`; set `governor.ci.auto_approve_workflows: false` to stay on Read and leave approvals to the `/ok-to-test` workflow described below. The other direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — needs the same grant. For that path it is **optional**: without it the call fails with `403 Resource not accessible by integration`, the hive labels the PR `hive:unauthorized`, posts one comment naming the permission and the human step (**Approve and run** on the checks banner or Actions tab, with the run ids), logs `lane unauthorized` once per head, parks the PR at 085 (`Awaiting human: approve workflow runs` in the activity monitor), and clears all of it the tick the required checks report ([#14589](https://github.com/hivecommons/hive/issues/14589)). When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, and the approval sweep is off or lacks the grant, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; that path needs no Prow and no Hive App Actions-write grant, and it never covers fork heads. Fork heads are reached only by the two App-token paths above — the gated-run approval sweep and the registry-trusted contributor lane — since GitHub holds only fork `pull_request` runs behind the gate; a trusted head's workflow files then run on the repository's runners, which is what the **Actions: Read and write** grant buys. No path approves runs on PRs carrying `sentinel-alert`. Install the workflow in each governed repository: run `hivectl ok-to-test-template > .github/workflows/hive-ok-to-test.yml` against your hive (it reads the App bot login from `/api/config`; pass `--app-login [bot]` to override), or copy `src/docs/templates/hive-ok-to-test.yml` and replace `HIVE_APP_LOGIN[bot]` with the App bot login shown by Hive for that installation. diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index cd7e9ed183..b9a301d475 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -434,12 +434,17 @@ runs when a required check is missing or pending: - workflow-approval and never-started holds are logged once per PR head as `automerge hold`; later ticks only count the PR in the skip stats instead of emitting `automerge skip` every tick. -- fork heads, sentinel-alert PRs, and human-authored lanes are never touched; a - first-time contributor's held run is still a person's decision — with one - exception: a contributor-lane PR whose author the **contributor registry** +- sentinel-alert PRs are never touched, and a first-time contributor's held run + is still a person's decision — with two exceptions that reach fork heads: the + gated-run approval sweep (`governor.ci.auto_approve_workflows`, default `true`) + approves a head's `pull_request` runs once when a verified owner or merger + admitted that head from the dashboard or the PR author / triggering actor is + the App or in `governor.ci.auto_approve_workflow_actors` + ([runtime-and-quota.md](runtime-and-quota.md), hivecommons/hive#16603); and a + contributor-lane PR whose author the **contributor registry** admitted at a `require_tiers` tier has its held runs approved once per head by the App (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, - default `true`; needs Actions: Read and write). The operator already trusts + default `true`). Both need Actions: Read and write. The operator already trusts that author to merge, so holding their CI is pure drag (hivecommons/docs#481). Per-repo `project.repo_policies[].auto_merge: false` is stronger than the diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index 06866e27d1..52d01de4ff 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -277,7 +277,11 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. and names no approver), or the PR author or the run's triggering actor is this hive's App or is listed in `governor.ci.auto_approve_workflow_actors` (default `['dependabot[bot]', 'renovate[bot]']`; an explicit `[]` trusts - only the App and owner admission). Trusting the App as triggering actor + only the App and owner admission). A trusted **author** covers every + gated run on the head regardless of who pushed it — including commits a + fork collaborator pushed to the author's branch — so keep the actor list + to bot logins unless that is acceptable for a human login you add. + Trusting the App as triggering actor covers heads the App pushed itself (its own PRs, rebases, review-fix commits); it does not extend to contributor code, because GitHub holds only fork `pull_request` runs behind the gate and the App cannot push to From c79e9f572883cedf2fe972ac98c217ceb1059e20 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:36:08 -0500 Subject: [PATCH 5/7] docs(github): name the approval sweep as the primary cure for held runs operator-reference "Held and never-started required checks" now leads with the default-on gated-run approval sweep (App token, Actions: Read and write) and describes /ok-to-test as the fallback that never reaches fork heads; hive-merge.md no longer claims the hive never approves a human-authored lane's held runs, since dashboard-admitted heads are approved by the sweep. Hive-Fix-Attempt: 4/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/hive-merge.md | 8 +++++--- src/docs/operator-reference/README.md | 19 +++++++++++++++---- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 9b9fffb750..ae7658b9ad 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -786,9 +786,11 @@ Every other gate below still applies to a registry-admitted PR. Set A registry-admitted author also gets their CI started. GitHub's fork-approval policy holds a first-time contributor's `pull_request` runs in -`action_required`, and the hive otherwise never approves a human-authored -lane's held runs (the `hive-ok-to-test` workflow approves same-repo heads -only). hivecommons/docs#481 by a `trusted` registry contributor sat 17 hours +`action_required`, and the hive otherwise approves a human-authored lane's +held runs in only one other case: the gated-run approval sweep +(`governor.ci.auto_approve_workflows`, default `true`, hivecommons/hive#16603) +approves a head a verified owner or merger admitted from the dashboard (the +`hive-ok-to-test` workflow approves same-repo heads only). hivecommons/docs#481 by a `trusted` registry contributor sat 17 hours at `required-check-missing:Audit production dependencies` until an operator clicked "Approve and run". When the registry path admitted the author and the lane stops at `required-check-missing:`, it now approves the head's held diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index b9a301d475..d05f698fe9 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -410,9 +410,19 @@ Dependabot branch), GitHub may create the `pull_request` runs and hold them for approval (`action_required`) under the repository or organization workflow approval policy; the required contexts never appear and the PR sits at `required-check-missing:` or `required-check-pending:` indefinitely -(hivecommons/hive#11552). For the App self-merge, trusted-bot, and -registry-trusted clanker lanes only, the sweep now inspects the head's workflow -runs when a required check is missing or pending: +(hivecommons/hive#11552). The primary cure is the gated-run approval sweep +(`governor.ci.auto_approve_workflows`, default `true`, +hivecommons/hive#16603): once per PR head it approves the held `pull_request` +runs with the App token (`POST /actions/runs/{id}/approve`) when the PR author +or triggering actor is Dependabot/Renovate (`auto_approve_workflow_actors`) or +the App itself, or a verified owner or merger admitted that head from the +dashboard. That path needs the App's **Actions: Read and write** grant; with +only Read the call `403`s, the hive records one `permission_error` per head in +`/api/status` `workflow_approvals`, and the CI caption reads `CI waiting · +needs workflow approval on GitHub`. For the App self-merge, trusted-bot, and +registry-trusted clanker lanes only, the automerge sweep additionally inspects +the head's workflow runs when a required check is missing or pending, as the +fallback when the approval sweep is off or refused: - held runs whose head repository is the base repository cause Hive to post one `/ok-to-test` issue comment per head and report `workflow-approval-required:`. @@ -420,7 +430,8 @@ runs when a required check is missing or pending: listens for that comment and approves the held runs with the repository `GITHUB_TOKEN` (not the Hive App token). It references no reusable workflow, so it also works under "allow select actions" policies and on GHES. - No Prow and no Hive App Actions-write permission are required. + This fallback needs no Prow and no Hive App Actions-write permission; it + never reaches fork heads. - if the held runs remain `action_required` after the grace period, Hive reports `workflow-approval-required:missing-workflow:` so the attention panel and stage entry name the likely missing workflow, and the 085 entry comment From f14e28893a2fb5d4ecd36dba621a83400b039c18 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:51:16 -0500 Subject: [PATCH 6/7] docs(github): state that a recorded approval refusal is not retried on the same head Spell out the operational consequence of the once-per-head ledger in the operator reference and App setup guide: granting Actions: write after a 403 was recorded does not retry that head; a new push, a restart, or Approve and run on GitHub is needed. Hive-Fix-Attempt: 5/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/github-app-setup.md | 2 +- src/docs/operator-reference/runtime-and-quota.md | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/docs/github-app-setup.md b/src/docs/github-app-setup.md index 3cc14622c5..57de9096cf 100644 --- a/src/docs/github-app-setup.md +++ b/src/docs/github-app-setup.md @@ -43,7 +43,7 @@ Fine-grained PATs are supported — the token is sent as a plain bearer, same as | Actions | Read and write | Read and write | Read and write — needed by the default-on gated-run approval sweep (`governor.ci.auto_approve_workflows`); Read suffices with it set to `false`, see below | | Commit statuses | Read | Read | Read and write — needed when `governor.labels.automerge` is the default `lgtm` on a Prow repository, so the queue action can set the `prow/lgtm` status beside the label. With only Read, every queue action still applies the label but posts a PR comment that the status could not be set. | -Since the gated-run approval sweep (`governor.ci.auto_approve_workflows`, **default on**, [#16603](https://github.com/hivecommons/hive/issues/16603)) Hive approves `action_required` `pull_request` runs with the App token — `POST /actions/runs/{id}/approve`, once per PR head, for Dependabot/Renovate/App-authored or -triggered runs and for heads a verified owner or merger admitted from the dashboard — which needs **Actions: Read and write**. With only **Actions: Read** the call fails with `403`, the hive records one `permission_error` in `/api/status` `workflow_approvals`, logs `workflow approval refused; needs workflow approval on GitHub`, and the CI caption reads `CI waiting · needs workflow approval on GitHub`; set `governor.ci.auto_approve_workflows: false` to stay on Read and leave approvals to the `/ok-to-test` workflow described below. The other direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — needs the same grant. For that path it is **optional**: without it the call fails with `403 Resource not accessible by integration`, the hive labels the PR `hive:unauthorized`, posts one comment naming the permission and the human step (**Approve and run** on the checks banner or Actions tab, with the run ids), logs `lane unauthorized` once per head, parks the PR at 085 (`Awaiting human: approve workflow runs` in the activity monitor), and clears all of it the tick the required checks report ([#14589](https://github.com/hivecommons/hive/issues/14589)). When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, and the approval sweep is off or lacks the grant, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; that path needs no Prow and no Hive App Actions-write grant, and it never covers fork heads. Fork heads are reached only by the two App-token paths above — the gated-run approval sweep and the registry-trusted contributor lane — since GitHub holds only fork `pull_request` runs behind the gate; a trusted head's workflow files then run on the repository's runners, which is what the **Actions: Read and write** grant buys. No path approves runs on PRs carrying `sentinel-alert`. +Since the gated-run approval sweep (`governor.ci.auto_approve_workflows`, **default on**, [#16603](https://github.com/hivecommons/hive/issues/16603)) Hive approves `action_required` `pull_request` runs with the App token — `POST /actions/runs/{id}/approve`, once per PR head, for Dependabot/Renovate/App-authored or -triggered runs and for heads a verified owner or merger admitted from the dashboard — which needs **Actions: Read and write**. With only **Actions: Read** the call fails with `403`, the hive records one `permission_error` in `/api/status` `workflow_approvals`, logs `workflow approval refused; needs workflow approval on GitHub`, and the CI caption reads `CI waiting · needs workflow approval on GitHub`; the refusal is recorded per PR head and not retried, so granting the permission afterwards takes effect for new heads (or after a hive restart), while an already-refused head needs **Approve and run** on GitHub or a fresh push; set `governor.ci.auto_approve_workflows: false` to stay on Read and leave approvals to the `/ok-to-test` workflow described below. The other direct approval Hive performs — a contributor-lane PR whose author the contributor registry admitted at a `require_tiers` tier (`auto_merge.contributor_lane.approve_held_runs_for_registry_trusted`, default on) — needs the same grant. For that path it is **optional**: without it the call fails with `403 Resource not accessible by integration`, the hive labels the PR `hive:unauthorized`, posts one comment naming the permission and the human step (**Approve and run** on the checks banner or Actions tab, with the run ids), logs `lane unauthorized` once per head, parks the PR at 085 (`Awaiting human: approve workflow runs` in the activity monitor), and clears all of it the tick the required checks report ([#14589](https://github.com/hivecommons/hive/issues/14589)). When GitHub leaves same-repository `pull_request` runs in `action_required` on trusted Dependabot/Renovate/App PRs or registry-trusted `author/clanker` PRs, and the approval sweep is off or lacks the grant, Hive posts `/ok-to-test` once for that head and reports `workflow-approval-required:` / `stage/085-needs-decision` until the repository's own self-contained `hive-ok-to-test` workflow approves the held runs. The approval is performed by that repository's `GITHUB_TOKEN` through `.github/workflows/hive-ok-to-test.yml`; that path needs no Prow and no Hive App Actions-write grant, and it never covers fork heads. Fork heads are reached only by the two App-token paths above — the gated-run approval sweep and the registry-trusted contributor lane — since GitHub holds only fork `pull_request` runs behind the gate; a trusted head's workflow files then run on the repository's runners, which is what the **Actions: Read and write** grant buys. No path approves runs on PRs carrying `sentinel-alert`. Install the workflow in each governed repository: run `hivectl ok-to-test-template > .github/workflows/hive-ok-to-test.yml` against your hive (it reads the App bot login from `/api/config`; pass `--app-login [bot]` to override), or copy `src/docs/templates/hive-ok-to-test.yml` and replace `HIVE_APP_LOGIN[bot]` with the App bot login shown by Hive for that installation. diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index 52d01de4ff..4b24dde531 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -304,7 +304,12 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. lacks `actions: write`) is recorded once, never retried for that head, logged as `workflow approval refused; needs workflow approval on GitHub`, and the caption becomes `CI waiting · needs workflow approval on GitHub` - on every later cycle, including ones that skip the sweep. The sweep uses + on every later cycle, including ones that skip the sweep. That refusal + is bound to the head: granting the App **Actions: Read and write** + afterwards does not make the hive retry a head it already recorded a + refusal for — the operator approves that run on GitHub, or a new push to + the PR (a new head) or a hive restart (the ledger is in memory) lets the + sweep attempt it again. The sweep uses the App token, so it needs **Actions: Read and write** on the App ([github-app-setup.md](../github-app-setup.md)); it runs alongside the older `/ok-to-test` path, in which the contributor lane posts a comment From d18fb6c110841112d90afb4a7ebcc12f8d570b02 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:44:57 -0500 Subject: [PATCH 7/7] docs: align operator docs with the workflow auto-approval sweep Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/hive-merge.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index ae7658b9ad..21c68f9668 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -789,7 +789,8 @@ policy holds a first-time contributor's `pull_request` runs in `action_required`, and the hive otherwise approves a human-authored lane's held runs in only one other case: the gated-run approval sweep (`governor.ci.auto_approve_workflows`, default `true`, hivecommons/hive#16603) -approves a head a verified owner or merger admitted from the dashboard (the +approves held runs for allowlisted actors (`auto_approve_workflow_actors`) and +for a head a verified owner or merger admitted from the dashboard (the `hive-ok-to-test` workflow approves same-repo heads only). hivecommons/docs#481 by a `trusted` registry contributor sat 17 hours at `required-check-missing:Audit production dependencies` until an operator clicked "Approve and run". When the registry path admitted the author and the