diff --git a/api/openapi.yaml b/api/openapi.yaml index 4cc58cf5..a71d92b3 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -3218,6 +3218,7 @@ components: - review.approve - thread.reply - thread.resolve + - ci.rerun - push-branch - stack.push - stack.rebase diff --git a/design/workstreams/agent/LLD/effector.md b/design/workstreams/agent/LLD/effector.md index a6af6f63..3388f368 100644 --- a/design/workstreams/agent/LLD/effector.md +++ b/design/workstreams/agent/LLD/effector.md @@ -31,6 +31,7 @@ func (e *Effector) Do(ctx context.Context, op string, args map[string]any) (Resu | `factory pr merge --pr N` | | API | | `factory review --pr N --event approve\|request-changes\|comment --body-file f [--comments-file c.json]` | inline comments `[{path, line, body}]` | API | | `factory thread reply --thread ID --body-file f` / `factory thread resolve --thread ID` | | API | +| `factory ci rerun --pr N [--key k]` | `ci.rerun` (MCP `ci_rerun`): re-runs the failed jobs of the PR head commit's failed workflow runs; `--pr` is `N`, `#N` or `owner/name#N`. With `--key` it acts **once per task per key** (the dispatcher replays the recorded effect), so re-running a later head in the same task needs a per-head key (`--key rerun-`) or no key | API | | `factory push [--branch B]` | `git push` with the scoped token; records `push-branch` | git | | `factory stack push` / `factory stack rebase` | git (an atomic leased push / `rebase --update-refs`), records op | git | | `factory result --file out/result.json` | validates locally, copies to `$FACTORY_RESULT` | local | diff --git a/design/workstreams/foundation/LLD/contracts.md b/design/workstreams/foundation/LLD/contracts.md index a2a02fa2..caca97f7 100644 --- a/design/workstreams/foundation/LLD/contracts.md +++ b/design/workstreams/foundation/LLD/contracts.md @@ -122,6 +122,7 @@ Canonical names (as used in the PoC catalog), constants in `v1alpha1/effects.go` | `pr.open`, `pr.update`, `pr.retarget`, `pr.merge` | API | `pr.merge` honours repo merge method; falls back to label if review requirement blocks (Q5) | | `review.comment`, `review.request-changes`, `review.approve` | API | reviewer identity only (TaskSpec `identity: reviewer`) | | `thread.reply`, `thread.resolve` | API | both identities: the author addresses review feedback, the reviewer follows up on its threads | +| `ci.rerun` | API | target: a PR. Re-runs the PR head commit's failed workflow runs, keeping only the latest run per workflow and event: `failure`/`timed_out` re-run their failed jobs, `cancelled`/`startup_failure` the whole run. A run at its **3rd attempt (`MaxRunAttempts`)** is never re-run again (a safety net against rule-driven loops). A run GitHub refuses is skipped and the others still re-run (outcome `partially-rerun: skipped …`); nothing re-run is outcome `nothing-to-rerun`, or `ErrInvalid` when every candidate was refused. Needs the identity's App to have **Actions: write** (only the author App, `ccf-factory`, is granted it). **Idempotency: once per task per key.** The Effector path's effect store replays a recorded `(task, key)` before the provider is called, and every successful apply is recorded, `nothing-to-rerun` included, so `--key k` acts once per task whatever the head: to re-run a new head in the same task, use a per-head key (`--key rerun-`) or no key. The provider also keys by head SHA for rule effects and retries ([github-provider.md §Decisions taken in fx/ci-rerun-effect](../../provider-github/LLD/github-provider.md#decisions-taken-in-fxci-rerun-effect)) | | `push-branch`, `stack.push`, `stack.rebase` | **git (agent)** | executed in the workspace with the scoped git token; the agent still records them via `POST /effects` (op + ref) for audit | ## Provider interface diff --git a/design/workstreams/poc-rollout/LLD/rollout.md b/design/workstreams/poc-rollout/LLD/rollout.md index dae75efa..92197e92 100644 --- a/design/workstreams/poc-rollout/LLD/rollout.md +++ b/design/workstreams/poc-rollout/LLD/rollout.md @@ -18,7 +18,7 @@ Created by an org owner (RUN-S0-T02). Settings → Developer settings → GitHub | Setting | `ccf-factory` (author + events) | `ccf-factory-reviewer` | |---|---|---| | Webhook | **active**, URL `https:///hooks/github-public`, secret = random 32 bytes | inactive | -| Repository permissions | Contents RW, Pull requests RW, Issues RW, Checks R, Actions R, Deployments R, Metadata R | Contents RW, Pull requests RW, Issues R, Checks R, Metadata R | +| Repository permissions | Contents RW, Pull requests RW, Issues RW, Checks R, Actions RW (write: `ci.rerun`), Deployments R, Metadata R | Contents RW, Pull requests RW, Issues R, Checks R, Metadata R | | Organization permissions | Members R | — | | Events | Issues, Issue comment, Pull request, Pull request review, Pull request review comment, Pull request review thread, Release, Deployment status, Check suite, Sub issues | — | | Install on | `docs`, `mock-docs`, `workflows`, `mock-*` | `docs`, `mock-docs` | diff --git a/design/workstreams/provider-github/LLD/github-provider.md b/design/workstreams/provider-github/LLD/github-provider.md index 7e52d503..f3d6aee5 100644 --- a/design/workstreams/provider-github/LLD/github-provider.md +++ b/design/workstreams/provider-github/LLD/github-provider.md @@ -7,7 +7,7 @@ | App | Role | Webhook | Permissions (repository) | Events | |---|---|---|---|---| -| `ccf-factory` | `author` identity **and the only event source** | **yes** → `https:///hooks/github-public` | contents RW, pull requests RW, issues RW, metadata R, checks R, actions R, deployments R | `issues`, `issue_comment`, `pull_request`, `pull_request_review`, `pull_request_review_comment`, `pull_request_review_thread`, `release`, `deployment_status`, `check_suite`, `sub_issues` | +| `ccf-factory` | `author` identity **and the only event source** | **yes** → `https:///hooks/github-public` | contents RW, pull requests RW, issues RW, metadata R, checks R, actions RW (read: Observe's `workflowRun`; write: `ci.rerun`), deployments R | `issues`, `issue_comment`, `pull_request`, `pull_request_review`, `pull_request_review_comment`, `pull_request_review_thread`, `release`, `deployment_status`, `check_suite`, `sub_issues` | | `ccf-factory-reviewer` | `reviewer` identity | **no** | contents RW (merge/rebase), pull requests RW, issues R, metadata R, checks R | none | Org-level: members R on `ccf-factory` (to resolve `role: admin` and teams). Installations: `docs`, `mock-docs`, `workflows` (read-only usage), mock repos (dev). Full creation steps: [rollout.md §GitHub Apps](../../poc-rollout/LLD/rollout.md#github-apps). @@ -106,6 +106,7 @@ Implemented in GH-S1-T03; the details are in [§Decisions taken in GH-S1-T03](#d | `pr.merge` | `PUT …/pulls/{n}/merge` (method from repo settings; `sha` = observed head) | 405 "already merged" → success; 405 review-required → fall back to `label.add` of the repo's merge label if configured (Q5), result `labelled-for-merge` | | `review.comment` / `review.request-changes` / `review.approve` | `POST …/pulls/{n}/reviews` (with `commit_id` = head, inline `comments[]`) | key in review body marker; skip if a review with the key exists | | `thread.reply` / `thread.resolve` | GraphQL `addPullRequestReviewThreadReply` / `resolveReviewThread` | reply key marker; resolve idempotent | +| `ci.rerun` | `GET …/pulls/{n}` (head SHA), `GET …/actions/runs?head_sha=`, then per latest failed run below its 3rd attempt `POST …/actions/runs/{id}/rerun-failed-jobs` (cancelled or startup_failure: `POST …/actions/runs/{id}/rerun`) | Effector path: once per task per key (the Effect store); provider: per (key, head SHA), remembered by the Conn for rule effects and retries; see §Decisions taken in fx/ci-rerun-effect | Rate limits: respect `X-RateLimit-Remaining`/`Retry-After`; exponential backoff (max 5 tries) for 5xx/secondary limits; effects return `retryable` errors to the API, which surfaces 503 to the agent. @@ -196,3 +197,12 @@ P3 §No rebuild from markers removed the work-item rebuild, the only reader of ` - **Gap for RT.** The Effector checks only `label.add`/`label.remove` against `effects.labels`, so `pr.merge`'s `args.mergeLabel` is unchecked: a merge task can add any one label to its PR when review requirements block the merge. The Effector should check `mergeLabel` against `effects.labels` like the label ops (or the merge label should become Provider configuration). - **`githubtest`** now models issue and PR title, body, id, state reason, head branch, sub-issues, reviews (with inline comments), review threads and merge blocks (`MergeBlock`: `MergeReviewRequired`, `MergeNotMergeable`), repo settings (`SetRepo`: merge methods, default branch), and serves `GET /repos/{o}/{r}`, issue list (`creator`, `state`, `direction`), create and update, a single comment, sub-issues (list, add), PR get/create/update, open PRs by head, merge (method allowed, `sha` at head, 405/409 as GitHub), reviews (list, get, create; no self-approval) and the GraphQL `ApplyThread`, `ApplyThreadReply` and `ApplyResolveThread` (mutations are now answered too). Every route checks the token's repo and permission, the merge both `contents` and `pull_requests` write. `html_url`s are under `githubtest.WebURL`. - **Tests.** Every op against `githubtest`: what it wrote, the token it used, and **a replay with the same key that writes nothing** and returns the same object and URL with `Replayed`; a forged marker by a human; the merge fallback (blocked → label → replay → merged once unblocked), the refusals and the method choice; retries on the fake clock (`Retry-After`, `X-RateLimit-Reset`, 5xx backoff, the bound, a long `Retry-After` returned, cancellation); refused requests with their errors; `ReadContent` for every ref form, the marker stripping and the errors; and **`TestServeGitHubEndToEnd`**: `factory serve` without `--dev-fake-providers` on the PoC catalog pointed at `githubtest`, health checked at connect, a signed `issues.opened` (202, redelivery 200, a bad signature 401) → a plan-epic Task → a fake agent leases it (a real scoped installation token), reads its context (fenced, no markers), creates and links a sub-issue and comments through the Effector (the replay by key writes nothing), completes it, and the comment, the sub-issue, the projection marker and build-stack-start's epic-plan notification land in `githubtest`; no secret or token in the logs. All with `-race`. + +## Decisions taken in fx/ci-rerun-effect + +- **`ci.rerun`** (`effects_ci.go`) re-runs CI on a PR so an agent can treat a failure as a flake. It acts on a **PR** (in `prOps`: an issue target is `ErrInvalid`, an issue number `ErrNotFound`), as the request's identity with **`{actions: write, pull_requests: read}`** on the repo. Only the `ccf-factory` App (author) is meant to have Actions: write, so a reviewer task asking for it fails at the mint with `ErrInvalid`. Steps: read the PR (closed or merged: `ErrInvalid`) for its head SHA; list the head's workflow runs (`GET …/actions/runs?head_sha=`, `per_page=100`, up to 5 pages); keep the **latest run per workflow and event** (`latestRuns`: the same superseding rule and `runOrder` as `checksOf`, so a run its concurrency group cancelled isn't re-run when a later run of that workflow exists); of those, take the ones `completed` with `failure`, `timed_out`, `cancelled` or `startup_failure`. **A run whose `run_attempt` is `MaxRunAttempts` (3) or more is skipped**: the provider never takes a run past its third attempt, a safety net for rule-driven use. `failure` and `timed_out` get `rerun-failed-jobs`; `cancelled` and `startup_failure` get `rerun` (a run cancelled by its concurrency group, or one that failed to start, can have no failed job). **A run GitHub refuses** (403 or 422 on its re-run: over 30 days old, already re-running, …) **is skipped and the others are still re-run**. If at least one run was re-run, the op succeeds, and when some were skipped (refused or capped) the outcome is `partially-rerun: skipped run (refused|attempt ), …`. If nothing was re-run and something was refused, the op is `ErrInvalid` with every refusal. Otherwise, with nothing to re-run (green, running or capped), it succeeds with outcome **`nothing-to-rerun`**. The result's object is the PR and its URL the PR's checks page. +- **Idempotency: once per task per key on the Effector path; per (key, head SHA) in the provider.** On the agent path, `CreateEffect` (`internal/server/effects.go`) replays any recorded `effectID(task, key)` before the provider is called, and every successful Apply is recorded (`nothing-to-rerun` included). So **`--key k` acts once per task**, whatever the head. To re-run a new head in the same task, use a per-head key (`--key rerun-`, as the catalog does) or omit `--key` (each successful call then gets a fresh key). This is the contract; the head SHA is deliberately not folded into the server's effect key. In the provider, the effective key is `@`, and the Conn remembers the effective keys it re-ran something with (`rerunLog`, the last 1024): the same key on the same head is a replay (`Replayed`, nothing posted). That covers what the store doesn't: a rule's effect is applied before it is recorded and again when its reconcile retries (rule keys are per event), and an Effector call whose Apply succeeded but whose record failed is applied again. A re-run leaves nothing on GitHub that could carry the key (the endpoints take no body), so the replay can't be read back from GitHub as the other ops' are. Nothing to re-run isn't remembered. The memory belongs to the process: a replay it has forgotten still posts nothing while the runs it re-ran are queued or running, because only completed runs are re-run. A retry inside `Apply` (rate limit, 5xx) re-lists the runs, so a run re-run before the failure is queued by then and isn't posted again. +- **Errors.** A 404 (the PR or a run) is `ErrNotFound`. A 403 that isn't a rate limit is `ErrInvalid`. When GitHub says the integration can't access the resource, or the installation wasn't granted the permission at the mint, the message names **Actions: write** (or **Pull requests: read** for the PR read). Any other 403 (a run over 30 days old, a run already running) keeps GitHub's message. A 422 is `ErrInvalid`. On a run's re-run, 403 and 422 skip that run rather than fail the op (see above). Rate limits and 5xx are retried, as for the other ops. +- **Deploy prerequisite.** The `ccf-factory` App needs **Actions: write**, a manual change in the GitHub App's settings that each installation then accepts (see [rollout.md §GitHub Apps](../../poc-rollout/LLD/rollout.md)). +- **`githubtest`** serves `GET /repos/{o}/{r}/actions/runs` (actions: read, `head_sha`, paged), `POST …/actions/runs/{id}/rerun-failed-jobs` and `…/rerun` (actions: write; 201; a run that isn't completed and, for failed jobs, a run without a failed conclusion are refused with 403 as on GitHub). A re-run is a new attempt that queues the run again (`AddWorkflowRuns`, `WorkflowRuns`, `SetWorkflowRun`). The routes are `RouteWorkflowRuns`, `RouteRerunFailedJobs` and `RouteRerun`. +- **Tests.** `TestApplyOps` has a `ci.rerun` case (token, writes, replay). `TestApplyCIRerun*` cover: only the latest failed run per workflow is re-run; green, running, neutral and other-commit runs are skipped; cancelled and startup failure get `/rerun`, timed out gets failed jobs; a replay with the same key posts nothing; another key and a new head re-run; nothing-to-rerun, which isn't remembered; pagination; a partly refused re-run (403, 422) that still re-runs the rest and names the skipped run, and all refused (`ErrInvalid` with both refusals); the attempt cap (alone: nothing to re-run; beside another run: named; a run re-run up to the cap skipped next time); a closed or merged PR, an issue target, a missing PR, a missing Actions: write (installation, reviewer App, GitHub's 403), a 403 on the PR, a 404; a 5xx retried without re-posting the run already re-run. diff --git a/internal/agent/effector/effector_test.go b/internal/agent/effector/effector_test.go index 58703884..cc1b7a56 100644 --- a/internal/agent/effector/effector_test.go +++ b/internal/agent/effector/effector_test.go @@ -268,6 +268,7 @@ func apiCases(t *testing.T) []struct { {"review comment", []string{"review", "--pr", "9", "--event", "comment", "--body", "A nit.", "--comments", `[{"path": "README.md", "line": 1, "body": "nit"}]`, "--commit", "4b825dc"}}, {"thread reply", []string{"thread", "reply", "--thread", "PRRT_kwDOA", "--body", "Fixed in 4b825dc."}}, {"thread resolve", []string{"thread", "resolve", "--thread", "PRRT_kwDOA", "--pr", "9"}}, + {"ci rerun", []string{"ci", "rerun", "--pr", "#9"}}, } } @@ -528,6 +529,7 @@ func TestPrecheck(t *testing.T) { {[]string{"push"}, 3, "push-branch is not allowed"}, {[]string{"stack", "push"}, 3, "stack.push is not allowed"}, {[]string{"stack", "rebase"}, 3, "stack.rebase is not allowed"}, + {[]string{"ci", "rerun", "--pr", "9"}, 3, "ci.rerun is not allowed"}, {[]string{"label", "add", "--name", "triage:bug"}, 0, ""}, {[]string{"review", "--pr", "9", "--event", "comment", "--body", "hm"}, 0, ""}, } diff --git a/internal/agent/effector/mcp_test.go b/internal/agent/effector/mcp_test.go index a1ab9250..756268b7 100644 --- a/internal/agent/effector/mcp_test.go +++ b/internal/agent/effector/mcp_test.go @@ -82,8 +82,8 @@ func TestMCPToolsMatchTheCLI(t *testing.T) { if !slices.Equal(names, want) { t.Fatalf("tools %q, want the ops %q", names, want) } - if len(ops) != 19 { - t.Errorf("%d ops, want the 18 of effector.md's table and link-duplicate", len(ops)) + if len(ops) != 20 { + t.Errorf("%d ops, want the 19 of effector.md's table and link-duplicate", len(ops)) } for _, tool := range res.Tools { o := ops[slices.IndexFunc(ops, func(o *effector.Op) bool { return o.Name() == tool.Name })] diff --git a/internal/agent/effector/ops.go b/internal/agent/effector/ops.go index 8f06caac..0f29a078 100644 --- a/internal/agent/effector/ops.go +++ b/internal/agent/effector/ops.go @@ -278,6 +278,17 @@ var ops = []*Op{ return t, map[string]any{"thread": a.str("thread")}, err }), }, + { + Words: []string{"ci", "rerun"}, Effects: []v1alpha1.EffectOp{v1alpha1.OpCIRerun}, + Help: "Re-run the failed jobs of the failed workflow runs on a pull request's head commit (the latest run of each " + + "workflow; a cancelled run is re-run whole). Nothing to re-run (all green or still running) is not an error. " + + "With --key it acts once per task per key: to re-run a later head, use --key rerun- or no key.", + Params: []Param{pPR, pKey}, + run: apiOp(v1alpha1.OpCIRerun, func(e *Effector, a args) (string, map[string]any, error) { + t, err := e.ref(a.str("pr")) + return t, nil, err + }), + }, { Words: []string{"push"}, Effects: []v1alpha1.EffectOp{v1alpha1.OpPushBranch}, Help: "Push a branch of the workspace's repo to origin with the task's scoped token, and record it (push-branch).", diff --git a/internal/agent/effector/testdata/requests.golden.json b/internal/agent/effector/testdata/requests.golden.json index f1537c44..1efb8dcb 100644 --- a/internal/agent/effector/testdata/requests.golden.json +++ b/internal/agent/effector/testdata/requests.golden.json @@ -1,4 +1,9 @@ { + "ci rerun": { + "idempotencyKey": "tsk_1/ci.rerun/5fca7643095dbbee.0", + "op": "ci.rerun", + "target": "acme/docs#9" + }, "comment": { "args": { "body": "Planning the epic." diff --git a/internal/apis/v1alpha1/effects.go b/internal/apis/v1alpha1/effects.go index f554fb88..4ea09584 100644 --- a/internal/apis/v1alpha1/effects.go +++ b/internal/apis/v1alpha1/effects.go @@ -36,6 +36,7 @@ const ( OpReviewApprove EffectOp = "review.approve" OpThreadReply EffectOp = "thread.reply" OpThreadResolve EffectOp = "thread.resolve" + OpCIRerun EffectOp = "ci.rerun" OpPushBranch EffectOp = "push-branch" OpStackPush EffectOp = "stack.push" OpStackRebase EffectOp = "stack.rebase" @@ -62,6 +63,7 @@ var effectOps = []struct { {OpReviewApprove, SideAPI}, {OpThreadReply, SideAPI}, {OpThreadResolve, SideAPI}, + {OpCIRerun, SideAPI}, {OpPushBranch, SideGit}, {OpStackPush, SideGit}, {OpStackRebase, SideGit}, diff --git a/internal/apis/v1alpha1/vocabulary_test.go b/internal/apis/v1alpha1/vocabulary_test.go index bc6eec1b..87415e51 100644 --- a/internal/apis/v1alpha1/vocabulary_test.go +++ b/internal/apis/v1alpha1/vocabulary_test.go @@ -85,6 +85,7 @@ func TestEffectOpSide(t *testing.T) { {OpPRMerge, SideAPI, true}, {OpReviewRequestChanges, SideAPI, true}, {OpThreadResolve, SideAPI, true}, + {OpCIRerun, SideAPI, true}, {OpPushBranch, SideGit, true}, {OpStackPush, SideGit, true}, {OpStackRebase, SideGit, true}, @@ -104,7 +105,7 @@ func TestEffectOpSide(t *testing.T) { git++ } } - if n := len(EffectOps()); n != 20 || git != 3 { - t.Errorf("%d ops (%d git), contracts.md lists 20 (3 git)", n, git) + if n := len(EffectOps()); n != 21 || git != 3 { + t.Errorf("%d ops (%d git), contracts.md lists 21 (3 git)", n, git) } } diff --git a/internal/catalog/phases_test.go b/internal/catalog/phases_test.go index ba9d4808..c10f7966 100644 --- a/internal/catalog/phases_test.go +++ b/internal/catalog/phases_test.go @@ -305,6 +305,18 @@ func TestStrictTurnsWarningsIntoErrors(t *testing.T) { } } +// TestCIRerunOp: ci.rerun is an API-side op a TaskSpec can allow and a rule's effect action can +// apply to its primary PR. +func TestCIRerunOp(t *testing.T) { + fsys := fsWith(map[string]string{ + "taskspecs/work.yaml": strings.Replace(base["taskspecs/work.yaml"], "[push-branch, pr.open]", "[push-branch, pr.open, ci.rerun]", 1), + "rules/work.yaml": rule(ruleHead + " actions: [{ effect: { op: ci.rerun, target: primary } }]\n"), + }) + if c, errs := LoadDir(fsys, Options{Strict: true}); c == nil || len(errs) > 0 { + t.Errorf("ci.rerun in effects.allow and a rule's effect:\n%s", format(errs)) + } +} + // TestThreadOpsForAuthors: thread.reply and thread.resolve are allowed for both identities // (the author addresses review feedback); only review.* needs the reviewer (CAT902). func TestThreadOpsForAuthors(t *testing.T) { diff --git a/internal/catalog/testdata/golden/unknown-op.golden b/internal/catalog/testdata/golden/unknown-op.golden index 00051976..0a05e38f 100644 --- a/internal/catalog/testdata/golden/unknown-op.golden +++ b/internal/catalog/testdata/golden/unknown-op.golden @@ -1,2 +1,2 @@ -taskspecs/work.yaml:13: CAT100 spec.effects.allow[1]: value must be one of 'comment', 'pr.comment', 'label.add', 'label.remove', 'create-issue', 'sub-issue.add', 'close', 'link-duplicate', 'pr.open', 'pr.update', 'pr.retarget', 'pr.merge', 'review.comment', 'review.request-changes', 'review.approve', 'thread.reply', 'thread.resolve', 'push-branch', 'stack.push', 'stack.rebase' +taskspecs/work.yaml:13: CAT100 spec.effects.allow[1]: value must be one of 'comment', 'pr.comment', 'label.add', 'label.remove', 'create-issue', 'sub-issue.add', 'close', 'link-duplicate', 'pr.open', 'pr.update', 'pr.retarget', 'pr.merge', 'review.comment', 'review.request-changes', 'review.approve', 'thread.reply', 'thread.resolve', 'ci.rerun', 'push-branch', 'stack.push', 'stack.rebase' taskspecs/work.yaml:13: CAT900 spec.effects.allow[1]: unknown effect op "force-push" diff --git a/internal/provider/fake/effects.go b/internal/provider/fake/effects.go index bed847f2..a5e8bed8 100644 --- a/internal/provider/fake/effects.go +++ b/internal/provider/fake/effects.go @@ -163,8 +163,8 @@ func (c *Conn) projectLocked(ref v1alpha1.ObjectRef, p provider.Projection) (boo // close; link-duplicate (label "duplicate" and close); create-issue and pr.open (Target.Ref is // the repo; args.labels, args.base, args.head, args.draft) create the next number in the // repo; sub-issue.add (args.issue: a ref); pr.retarget (args.base); pr.merge; review.approve -// (approves the head for Identity); thread.resolve. Other API ops only need the target to -// exist. Git-side ops are ErrUnsupported (the agent executes them). +// (approves the head for Identity); thread.resolve; ci.rerun (needs a PR; there's no CI to +// re-run). Other API ops only need the target to exist. Git-side ops are ErrUnsupported (the agent executes them). func (c *Conn) Apply(ctx context.Context, e provider.EffectRequest) (provider.EffectResult, error) { if err := ctx.Err(); err != nil { return provider.EffectResult{}, err @@ -325,6 +325,11 @@ func (c *Conn) mutateLocked(e provider.EffectRequest) (provider.EffectResult, er return provider.EffectResult{}, err } p.UnresolvedThreads = max(0, p.UnresolvedThreads-1) + case v1alpha1.OpCIRerun: + // The fake has no CI: re-running it changes nothing, but needs a PR. + if _, err := pr(); err != nil { + return provider.EffectResult{}, err + } } o.UpdatedAt = c.opts.Clock.Now() return res, nil diff --git a/internal/provider/fake/fake_test.go b/internal/provider/fake/fake_test.go index 4c17a4bc..4c7b4288 100644 --- a/internal/provider/fake/fake_test.go +++ b/internal/provider/fake/fake_test.go @@ -757,6 +757,11 @@ func TestApply(t *testing.T) { }, {name: "unknown target", req: provider.EffectRequest{Op: v1alpha1.OpClose, Target: ref("issue", "o/r#404")}, wantErr: provider.ErrNotFound}, {name: "PR op on an issue", req: provider.EffectRequest{Op: v1alpha1.OpPRMerge, Target: issue}, wantErr: provider.ErrInvalid}, + { + name: "ci.rerun", req: provider.EffectRequest{Op: v1alpha1.OpCIRerun, Target: pr}, + wantURL: "https://fake.invalid/compliance-framework/docs/pull/57", wantObj: pr, + }, + {name: "ci.rerun on an issue", req: provider.EffectRequest{Op: v1alpha1.OpCIRerun, Target: issue}, wantErr: provider.ErrInvalid}, {name: "create in a non-repo", req: provider.EffectRequest{Op: v1alpha1.OpCreateIssue, Target: issue}, wantErr: provider.ErrInvalid}, {name: "git-side op", req: provider.EffectRequest{Op: v1alpha1.OpPushBranch, Target: pr}, wantErr: provider.ErrUnsupported}, {name: "unknown op", req: provider.EffectRequest{Op: "explode", Target: pr}, wantErr: provider.ErrInvalid}, diff --git a/internal/provider/github/effects.go b/internal/provider/github/effects.go index 9fe43fff..7ef13f4c 100644 --- a/internal/provider/github/effects.go +++ b/internal/provider/github/effects.go @@ -27,7 +27,9 @@ import ( // returns it with Replayed; // - what it changes (labels, sub-issue links, state, base, title and body, merges, resolved // threads) is read first: when the object is already as asked, nothing is written and the -// result has Replayed. +// result has Replayed; +// - ci.rerun leaves nothing on GitHub that carries the key: it is remembered by key and head +// SHA instead (applyCIRerun). // // A rate limit, a 5xx or a transport failure retries the whole op (lookup included, so a // write GitHub made before failing is found rather than repeated), up to maxApplyTries times, @@ -172,13 +174,14 @@ var effectOps = map[v1alpha1.EffectOp]opFunc{ v1alpha1.OpReviewApprove: (*Conn).applyReview, v1alpha1.OpThreadReply: (*Conn).applyThreadReply, v1alpha1.OpThreadResolve: (*Conn).applyThreadResolve, + v1alpha1.OpCIRerun: (*Conn).applyCIRerun, } // prOps act on a PR whatever the target's kind says. var prOps = []v1alpha1.EffectOp{ v1alpha1.OpPRComment, v1alpha1.OpPRUpdate, v1alpha1.OpPRRetarget, v1alpha1.OpPRMerge, v1alpha1.OpReviewComment, v1alpha1.OpReviewRequestChanges, v1alpha1.OpReviewApprove, - v1alpha1.OpThreadReply, v1alpha1.OpThreadResolve, + v1alpha1.OpThreadReply, v1alpha1.OpThreadResolve, v1alpha1.OpCIRerun, } // reviewOps act only as ReviewerIdentity. diff --git a/internal/provider/github/effects_ci.go b/internal/provider/github/effects_ci.go new file mode 100644 index 00000000..bab68c0a --- /dev/null +++ b/internal/provider/github/effects_ci.go @@ -0,0 +1,269 @@ +package github + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "sync" + "time" + + "github.com/ContainerSolutions/factory/internal/provider" + "github.com/ContainerSolutions/factory/internal/provider/tokens" +) + +// The CI op, ci.rerun: re-run the failed GitHub Actions workflow runs of a PR's head commit +// (github-provider.md §Effects). Its token is actions: write on the target repo, with +// pull_requests: read for the PR's head. + +const ( + // OutcomeNothingToRerun is ci.rerun's outcome when the head has no failed run to re-run: + // the latest run of every workflow passed, is still running or is at MaxRunAttempts. + OutcomeNothingToRerun = "nothing-to-rerun" + // OutcomePartiallyRerun starts ci.rerun's outcome when some runs were re-run and others + // skipped (refused by GitHub, or at MaxRunAttempts); the outcome names the skipped runs: + // "partially-rerun: skipped run 12 (refused), run 13 (attempt 3)". + OutcomePartiallyRerun = "partially-rerun" + // MaxRunAttempts is the attempt ci.rerun never takes a run past: a run whose latest + // attempt is MaxRunAttempts or more is skipped, a safety net against a rule re-running a + // failing run forever. + MaxRunAttempts = 3 + // maxRunPages bounds the pages of a head commit's workflow runs ci.rerun reads. + maxRunPages = 5 + // maxReruns bounds the ci.rerun effects a Conn remembers for replays (rerunLog). + maxReruns = 1024 +) + +func ciRerunPerms() map[string]string { + return map[string]string{"actions": "write", "pull_requests": "read"} +} + +// rerunConclusions are the conclusions of a run ci.rerun re-runs. +var rerunConclusions = []string{"failure", "timed_out", "cancelled", "startup_failure"} + +// ghWorkflowRun is a workflow run as the Actions API shows it: its latest attempt's status and +// conclusion. +type ghWorkflowRun struct { + ID int64 `json:"id"` + WorkflowID int64 `json:"workflow_id"` + RunNumber int `json:"run_number"` + RunAttempt int `json:"run_attempt"` + Event string `json:"event"` + Status string `json:"status"` + Conclusion *string `json:"conclusion"` + CreatedAt time.Time `json:"created_at"` +} + +func (r *ghWorkflowRun) conclusion() string { + if r.Conclusion == nil { + return "" + } + return *r.Conclusion +} + +// rerunLog remembers the ci.rerun effects a Conn applied that re-ran something, by effective +// key (the request's key and the head SHA), so the same key on the same head is a replay. A +// re-run leaves nothing on GitHub that carries the key (the API takes no body to put a marker +// in), so unlike the other ops the replay can't be found there; the dispatcher's Effect store +// is the durable record (see applyCIRerun). Bounded to maxReruns, the oldest forgotten first. +type rerunLog struct { + mu sync.Mutex + done map[string]provider.EffectResult + order []string +} + +func (l *rerunLog) get(key string) (provider.EffectResult, bool) { + l.mu.Lock() + defer l.mu.Unlock() + res, ok := l.done[key] + if ok && res.Object != nil { + ref := *res.Object // each caller gets its own copy + res.Object = &ref + } + return res, ok +} + +func (l *rerunLog) put(key string, res provider.EffectResult) { + l.mu.Lock() + defer l.mu.Unlock() + if l.done == nil { + l.done = map[string]provider.EffectResult{} + } + if _, ok := l.done[key]; !ok { + l.order = append(l.order, key) + } + l.done[key] = res + for len(l.order) > maxReruns { + delete(l.done, l.order[0]) + l.order = l.order[1:] + } +} + +// applyCIRerun re-runs the failed workflow runs of the PR's head commit: of the head's runs, +// the latest of each workflow and event (latestRuns, the superseding rule of checksOf), and of +// those the completed ones that concluded failure, timed_out, cancelled or startup_failure, +// below MaxRunAttempts. A failure or timed_out run is re-run with POST …/rerun-failed-jobs; a +// cancelled or startup_failure one with POST …/rerun (a run cancelled by its concurrency group, +// or one that failed to start, may have no failed job). With nothing to re-run (every latest +// run passed, is still running or is at MaxRunAttempts) the outcome is OutcomeNothingToRerun, +// not an error. A run GitHub refuses (403, 422: over 30 days old, already re-running, …) is +// skipped and the others are still re-run; the outcome then names it (OutcomePartiallyRerun). +// Only when nothing was re-run and something was refused is the op ErrInvalid. The result's +// URL is the PR's checks page. A closed or merged PR is ErrInvalid. +// +// Idempotency: the effective key is the request's key and the head SHA. The Conn remembers the +// effective keys it re-ran something with (rerunLog), so the same key on the same head is a +// replay (Replayed, nothing posted). This covers what the dispatcher's Effect store doesn't: +// a rule's effect is applied before it is recorded and again when its reconcile retries, and +// an Effector call whose Apply succeeded but whose record failed is applied again. On the +// Effector path the store answers first: CreateEffect replays any recorded effectID(task, key) +// before the provider is called, and every successful Apply is recorded (nothing-to-rerun +// included), so a --key acts once per task whatever the head; to re-run a new head in the +// same task the agent uses a per-head key (--key rerun-) or no key. The Conn's memory is +// the process's; a replay it forgot still posts nothing while the runs it re-ran are queued or +// running, since only completed runs are re-run. +// +// Errors: a 404 is ErrNotFound; a 403 or 422 is ErrInvalid, naming Actions: write when the +// App lacks it (as does a token the installation can't be granted). +func (c *Conn) applyCIRerun(ctx context.Context, e *effect) (provider.EffectResult, error) { + tok, err := c.token(ctx, e, ciRerunPerms()) + if err != nil { + if errors.Is(err, provider.ErrInvalid) { + return provider.EffectResult{}, fmt.Errorf("ci.rerun needs the %s identity's App to have %s on %s: %w", e.identity, actionsWrite, e.repo, err) + } + return provider.EffectResult{}, err + } + p, err := c.pull(ctx, tok, e) + if err != nil { + return provider.EffectResult{}, ciError(err, e.repo, "Pull requests: read") + } + if p.Merged || p.State != "open" { + state := p.State + if p.Merged { + state = "merged" + } + return provider.EffectResult{}, fmt.Errorf("%s#%d is %s: no CI to re-run: %w", e.repo, e.number, state, provider.ErrInvalid) + } + key := e.key() + "@" + p.Head.SHA + if res, ok := c.reruns.get(key); ok { + res.Replayed = true + return res, nil + } + runs, err := c.headRuns(ctx, tok, e.repo, p.Head.SHA) + if err != nil { + return provider.EffectResult{}, ciError(err, e.repo, actionsWrite) + } + res := c.result(provider.KindPR, e.repo, e.number, strings.TrimSuffix(p.HTMLURL, "/")+"/checks", false) + var ( + rerun []int64 + skipped []string // "run ()", for the outcome + refusals []error + ) + for _, r := range latestRuns(runs) { + if r.Status != "completed" || !slices.Contains(rerunConclusions, r.conclusion()) { + continue + } + if r.RunAttempt >= MaxRunAttempts { + skipped = append(skipped, fmt.Sprintf("run %d (attempt %d)", r.ID, r.RunAttempt)) + continue + } + path := fmt.Sprintf("repos/%s/actions/runs/%d/rerun-failed-jobs", e.repo, r.ID) + if wholeRerun(r.conclusion()) { + path = fmt.Sprintf("repos/%s/actions/runs/%d/rerun", e.repo, r.ID) + } + if _, err := c.minter.Do(ctx, tok, http.MethodPost, path, nil, nil, http.StatusCreated, nil); err != nil { + err = fmt.Errorf("re-run workflow run %d: %w", r.ID, ciError(err, e.repo, actionsWrite)) + if !errors.Is(err, provider.ErrInvalid) { + return provider.EffectResult{}, err // not found, or retryable: the whole op again + } + skipped = append(skipped, fmt.Sprintf("run %d (refused)", r.ID)) + refusals = append(refusals, err) + continue + } + rerun = append(rerun, r.ID) + } + ref := e.repo + "#" + strconv.Itoa(e.number) + switch { + case len(rerun) == 0 && len(refusals) > 0: + return provider.EffectResult{}, fmt.Errorf("no workflow run could be re-run: %w", errors.Join(refusals...)) + case len(rerun) == 0: + res.Outcome = OutcomeNothingToRerun + return res, nil + case len(skipped) > 0: + res.Outcome = OutcomePartiallyRerun + ": skipped " + strings.Join(skipped, ", ") + } + c.reruns.put(key, res) + c.log.DebugContext(ctx, "workflow runs re-run", "ref", ref, "head", p.Head.SHA, "runs", rerun, "skipped", skipped, "refusals", refusals) + return res, nil +} + +// wholeRerun reports whether a run with conclusion is re-run whole (POST …/rerun) rather than +// its failed jobs: a cancelled run or one that failed to start may have no failed job. +func wholeRerun(conclusion string) bool { + return conclusion == "cancelled" || conclusion == "startup_failure" +} + +// headRuns lists the workflow runs of the head commit sha (up to maxRunPages pages). +func (c *Conn) headRuns(ctx context.Context, tok, repo, sha string) ([]ghWorkflowRun, error) { + q := url.Values{"head_sha": {sha}, "per_page": {strconv.Itoa(perPage)}} + var out []ghWorkflowRun + for range maxRunPages { + var page struct { + WorkflowRuns []ghWorkflowRun `json:"workflow_runs"` + } + h, err := c.minter.Get(ctx, tok, "repos/"+repo+"/actions/runs", q, &page) + if err != nil { + return nil, fmt.Errorf("list workflow runs of %s: %w", sha, err) + } + out = append(out, page.WorkflowRuns...) + next, ok := nextQuery(h) + if !ok { + break + } + q = next + } + return out, nil +} + +// latestRuns are the runs no later run of the same workflow and event supersedes, in their +// order: checksOf's rule for check suites (a run cancelled by its concurrency group, or +// re-triggered, is superseded by the later run). +func latestRuns(runs []ghWorkflowRun) []ghWorkflowRun { + kind := func(r ghWorkflowRun) string { return strconv.FormatInt(r.WorkflowID, 10) + "/" + r.Event } + order := func(r ghWorkflowRun) runOrder { return runOrder{number: r.RunNumber, created: r.CreatedAt, id: r.ID} } + latest := map[string]int{} + for i, r := range runs { + if j, seen := latest[kind(r)]; !seen || order(r).after(order(runs[j])) { + latest[kind(r)] = i + } + } + var out []ghWorkflowRun + for i, r := range runs { + if latest[kind(r)] == i { + out = append(out, r) + } + } + return out +} + +// actionsWrite is the App permission ci.rerun's Actions calls need, as GitHub's App settings +// name it. +const actionsWrite = "Actions: write" + +// ciError maps a GitHub refusal of ci.rerun's calls: a 403 that isn't a rate limit is +// ErrInvalid, naming perm when GitHub says the App may not do it; anything else as is (404 +// ErrNotFound, 422 ErrInvalid, rate limits and 5xx retryable). +func ciError(err error, repo, perm string) error { + if !errors.Is(err, tokens.ErrForbidden) { + return err + } + var apiErr *tokens.APIError + if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.Message), "not accessible by integration") { + return fmt.Errorf("the App lacks %s on %s (grant it in the GitHub App's permissions): %w: %w", perm, repo, err, provider.ErrInvalid) + } + return fmt.Errorf("%w: %w", err, provider.ErrInvalid) +} diff --git a/internal/provider/github/effects_ci_test.go b/internal/provider/github/effects_ci_test.go new file mode 100644 index 00000000..b7a38ef3 --- /dev/null +++ b/internal/provider/github/effects_ci_test.go @@ -0,0 +1,336 @@ +package github_test + +import ( + "context" + "errors" + "maps" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/ContainerSolutions/factory/internal/apis/v1alpha1" + "github.com/ContainerSolutions/factory/internal/provider" + "github.com/ContainerSolutions/factory/internal/provider/github" + "github.com/ContainerSolutions/factory/internal/provider/github/githubtest" +) + +// PR #60's head (seedEffects) and the workflows of its runs. +const ( + head60 = "abc123" + ciWorkflow = 67470646 + preview = 379691137 + lint = 11 +) + +// wfRun is a workflow run on PR #60's head; id orders the runs in time too. +func wfRun(id int64, workflow int64, number int, status, conclusion string) githubtest.WorkflowRun { + return githubtest.WorkflowRun{ID: id, WorkflowID: workflow, RunNumber: number, HeadSHA: head60, Status: status, Conclusion: conclusion, + Created: t0.Add(time.Duration(id) * time.Minute)} +} + +func ciRerun(key string) provider.EffectRequest { + r := effectReq(v1alpha1.OpCIRerun, provider.KindPR, docs+"#60", "author", nil) + if key != "" { + r.IdempotencyKey = key + } + return r +} + +// reruns are the runs re-run so far, by ID: true for rerun-failed-jobs, false for a whole +// re-run. +func reruns(s *githubtest.Server) map[int64]bool { + out := map[int64]bool{} + for _, r := range s.WorkflowRuns(docs) { + if r.Attempt > 1 { + out[r.ID] = r.FailedJobsOnly + } + } + return out +} + +// TestApplyCIRerun: ci.rerun re-runs the latest failed run of each workflow on the PR's head, +// skipping green and running ones and superseded runs, a cancelled run whole; nothing to +// re-run is an outcome; the same key on the same head is a replay, a new head is re-run again. +func TestApplyCIRerun(t *testing.T) { + ctx := context.Background() + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, + wfRun(1, ciWorkflow, 10, "completed", "failure"), // superseded by 2 + wfRun(2, ciWorkflow, 11, "completed", "failure"), // re-run: failed jobs + wfRun(3, preview, 20, "completed", "cancelled"), // re-run whole + wfRun(4, lint, 30, "completed", "success"), // green + wfRun(5, 12, 40, "in_progress", ""), // still running + wfRun(6, 13, 50, "completed", "timed_out"), // re-run: failed jobs + wfRun(7, 14, 60, "completed", "startup_failure"), // re-run whole + wfRun(8, 15, 70, "completed", "neutral"), // not a failure + githubtest.WorkflowRun{ID: 9, WorkflowID: 16, RunNumber: 1, HeadSHA: "0ther0", Status: "completed", Conclusion: "failure"}, // another commit + ) + c := e.connect(t) + res, err := c.Apply(ctx, ciRerun("")) + if err != nil { + t.Fatal(err) + } + if res.Replayed || res.Outcome != "" || res.Object == nil || res.Object.Ref != docs+"#60" || res.URL != githubtest.WebURL+"/"+docs+"/pull/60/checks" { + t.Errorf("result %+v (object %+v)", res, res.Object) + } + want := map[int64]bool{2: true, 3: false, 6: true, 7: false} + if got := reruns(e.srv); !maps.Equal(got, want) { + t.Errorf("re-runs %v, want %v", got, want) + } + for _, tr := range e.srv.TokenRequests() { + if tr.InstallationID != 1 || !maps.Equal(tr.Permissions, map[string]string{"actions": "write", "pull_requests": "read"}) { + t.Errorf("token request %+v, want the author's actions: write, pull_requests: read", tr) + } + } + + // The same key on the same head: a replay that posts nothing, even once the runs failed again. + for _, r := range e.srv.WorkflowRuns(docs) { + if r.Attempt > 1 { + e.srv.SetWorkflowRun(docs, r.ID, func(r *githubtest.WorkflowRun) { r.Status, r.Conclusion = "completed", "failure" }) + } + } + posts := e.srv.Count(githubtest.RouteRerunFailedJobs) + e.srv.Count(githubtest.RouteRerun) + again, err := c.Apply(ctx, ciRerun("")) + if err != nil || !again.Replayed || again.URL != res.URL || again.Outcome != "" { + t.Errorf("replay = %+v, %v", again, err) + } + if n := e.srv.Count(githubtest.RouteRerunFailedJobs) + e.srv.Count(githubtest.RouteRerun); n != posts { + t.Errorf("the replay posted %d re-runs", n-posts) + } + + // Another key is another effect: the runs that failed again are re-run. + if res, err := c.Apply(ctx, ciRerun("eff_other")); err != nil || res.Replayed { + t.Errorf("another key = %+v, %v", res, err) + } + if n := e.srv.Count(githubtest.RouteRerunFailedJobs) + e.srv.Count(githubtest.RouteRerun); n != posts+4 { + t.Errorf("another key posted %d re-runs, want 4", n-posts) + } + + // A new head with the first key: its failed run is re-run. + e.srv.UpdateObject(docs, 60, func(o *githubtest.Object) { o.Head = "def456" }) + e.srv.AddWorkflowRuns(docs, githubtest.WorkflowRun{ID: 10, WorkflowID: ciWorkflow, RunNumber: 12, HeadSHA: "def456", Status: "completed", Conclusion: "failure"}) + if res, err := c.Apply(ctx, ciRerun("")); err != nil || res.Replayed || res.Outcome != "" { + t.Errorf("new head = %+v, %v", res, err) + } + if got := reruns(e.srv); !got[10] { + t.Errorf("the new head's run wasn't re-run: %v", got) + } +} + +// Nothing to re-run (every latest run green or running, or no runs at all) is the +// nothing-to-rerun outcome, posts nothing, and isn't remembered: once a run fails, the same +// key re-runs it. +func TestApplyCIRerunNothing(t *testing.T) { + ctx := context.Background() + e := newEnv(t) + seedEffects(e.srv) + c := e.connect(t) + if res, err := c.Apply(ctx, ciRerun("")); err != nil || res.Outcome != github.OutcomeNothingToRerun || res.Replayed { + t.Fatalf("no runs: %+v, %v", res, err) + } + e.srv.AddWorkflowRuns(docs, + wfRun(1, ciWorkflow, 10, "completed", "failure"), wfRun(2, ciWorkflow, 11, "completed", "success"), // superseded failure + wfRun(3, preview, 20, "queued", ""), wfRun(4, lint, 30, "completed", "skipped")) + if res, err := c.Apply(ctx, ciRerun("")); err != nil || res.Outcome != github.OutcomeNothingToRerun || res.Replayed { + t.Fatalf("green and running: %+v, %v", res, err) + } + if n := e.srv.Count(githubtest.RouteRerunFailedJobs) + e.srv.Count(githubtest.RouteRerun); n != 0 { + t.Errorf("posted %d re-runs", n) + } + e.srv.SetWorkflowRun(docs, 3, func(r *githubtest.WorkflowRun) { r.Status, r.Conclusion = "completed", "failure" }) + if res, err := c.Apply(ctx, ciRerun("")); err != nil || res.Outcome != "" || res.Replayed || !reruns(e.srv)[3] { + t.Errorf("after a failure: %+v, %v, re-runs %v", res, err, reruns(e.srv)) + } +} + +// The runs list is read page by page. +func TestApplyCIRerunPages(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.SetPageSize(2) + e.srv.AddWorkflowRuns(docs, wfRun(1, 1, 1, "completed", "success"), wfRun(2, 2, 1, "completed", "success"), + wfRun(3, 3, 1, "completed", "success"), wfRun(4, 4, 1, "completed", "failure")) + if _, err := e.connect(t).Apply(context.Background(), ciRerun("")); err != nil { + t.Fatal(err) + } + if got := reruns(e.srv); !got[4] || len(got) != 1 { + t.Errorf("re-runs %v, want run 4", got) + } +} + +// A run GitHub refuses (403, 422) is skipped and the others are still re-run: the outcome names +// the skipped run, and a replay returns it. Only when nothing could be re-run is it an error. +func TestApplyCIRerunPartlyRefused(t *testing.T) { + ctx := context.Background() + for _, status := range []int{http.StatusUnprocessableEntity, http.StatusForbidden} { + t.Run(strconv.Itoa(status), func(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, wfRun(1, ciWorkflow, 10, "completed", "failure"), wfRun(2, preview, 20, "completed", "failure")) + e.srv.FailNext(githubtest.RouteRerunFailedJobs, githubtest.Failure{Status: status, Message: "Unable to re-run this workflow run because it was created over a month ago"}) + c := e.connect(t) + res, err := c.Apply(ctx, ciRerun("")) + if err != nil || res.Replayed || res.Outcome != github.OutcomePartiallyRerun+": skipped run 1 (refused)" { + t.Fatalf("Apply = %+v, %v", res, err) + } + if got := reruns(e.srv); !maps.Equal(got, map[int64]bool{2: true}) { + t.Errorf("re-runs %v, want run 2", got) + } + again, err := c.Apply(ctx, ciRerun("")) + if err != nil || !again.Replayed || again.Outcome != res.Outcome { + t.Errorf("replay = %+v, %v", again, err) + } + }) + } + t.Run("every run refused", func(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, wfRun(1, ciWorkflow, 10, "completed", "failure"), wfRun(2, preview, 20, "completed", "cancelled")) + e.srv.FailNext(githubtest.RouteRerunFailedJobs, githubtest.Failure{Status: http.StatusUnprocessableEntity, Message: "Validation Failed"}) + e.srv.FailNext(githubtest.RouteRerun, githubtest.Failure{Status: http.StatusForbidden, Message: "This workflow is already running"}) + _, err := e.connect(t).Apply(ctx, ciRerun("")) + if !errors.Is(err, provider.ErrInvalid) || !strings.Contains(err.Error(), "already running") || !strings.Contains(err.Error(), "Validation Failed") { + t.Errorf("Apply = %v, want ErrInvalid naming both refusals", err) + } + }) +} + +// A run at MaxRunAttempts is never re-run: alone it leaves nothing to re-run, beside another +// failed run the outcome names it; a run re-run up to the cap is skipped next time. +func TestApplyCIRerunAttemptCap(t *testing.T) { + ctx := context.Background() + capped := func(r githubtest.WorkflowRun, attempt int) githubtest.WorkflowRun { + r.Attempt = attempt + return r + } + t.Run("alone", func(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, capped(wfRun(1, ciWorkflow, 10, "completed", "failure"), github.MaxRunAttempts)) + res, err := e.connect(t).Apply(ctx, ciRerun("")) + posts := e.srv.Count(githubtest.RouteRerunFailedJobs) + e.srv.Count(githubtest.RouteRerun) + if err != nil || res.Outcome != github.OutcomeNothingToRerun || posts != 0 { + t.Errorf("Apply = %+v, %v; %d re-runs posted", res, err, posts) + } + }) + t.Run("beside another failed run", func(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, capped(wfRun(1, ciWorkflow, 10, "completed", "failure"), 4), capped(wfRun(2, preview, 20, "completed", "failure"), 2)) + res, err := e.connect(t).Apply(ctx, ciRerun("")) + if err != nil || res.Outcome != github.OutcomePartiallyRerun+": skipped run 1 (attempt 4)" { + t.Fatalf("Apply = %+v, %v", res, err) + } + if rs := e.srv.WorkflowRuns(docs); rs[0].Attempt != 4 || rs[1].Attempt != 3 { + t.Errorf("attempts %d and %d, want 4 and 3", rs[0].Attempt, rs[1].Attempt) + } + }) + t.Run("re-run up to the cap", func(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, capped(wfRun(1, ciWorkflow, 10, "completed", "failure"), github.MaxRunAttempts-1)) + c := e.connect(t) + if res, err := c.Apply(ctx, ciRerun("eff_a")); err != nil || res.Outcome != "" { + t.Fatalf("first = %+v, %v", res, err) + } + e.srv.SetWorkflowRun(docs, 1, func(r *githubtest.WorkflowRun) { r.Status, r.Conclusion = "completed", "failure" }) + if res, err := c.Apply(ctx, ciRerun("eff_b")); err != nil || res.Outcome != github.OutcomeNothingToRerun { + t.Errorf("at the cap = %+v, %v", res, err) + } + if n := e.srv.Count(githubtest.RouteRerunFailedJobs); n != 1 { + t.Errorf("%d re-runs, want 1", n) + } + }) +} + +// TestApplyCIRerunRefused: a closed or merged PR and a non-PR target are ErrInvalid; an App +// without Actions: write is ErrInvalid naming it; GitHub's 403, 404 and 5xx map as the other +// ops' do. Nothing is re-run. +func TestApplyCIRerunRefused(t *testing.T) { + ctx := context.Background() + tests := []struct { + name string + seed func(*githubtest.Server) + req provider.EffectRequest + is error + msg string + }{ + {name: "closed PR", seed: func(s *githubtest.Server) { + s.UpdateObject(docs, 60, func(o *githubtest.Object) { o.State = "closed" }) + }, + req: ciRerun(""), is: provider.ErrInvalid, msg: "is closed"}, + {name: "merged PR", seed: func(s *githubtest.Server) { + s.UpdateObject(docs, 60, func(o *githubtest.Object) { o.State = "merged" }) + }, + req: ciRerun(""), is: provider.ErrInvalid, msg: "is merged"}, + {name: "an issue target", req: effectReq(v1alpha1.OpCIRerun, provider.KindIssue, docs+"#57", "author", nil), is: provider.ErrInvalid}, + {name: "an issue number", req: effectReq(v1alpha1.OpCIRerun, "", docs+"#57", "author", nil), is: provider.ErrNotFound}, + {name: "a missing PR", req: effectReq(v1alpha1.OpCIRerun, provider.KindPR, docs+"#999", "author", nil), is: provider.ErrNotFound}, + {name: "an installation without actions: write", seed: func(s *githubtest.Server) { + s.SetInstallationPermissions(1, map[string]string{"contents": "write", "pull_requests": "write", "issues": "write", "metadata": "read", "actions": "read"}) + }, req: ciRerun(""), is: provider.ErrInvalid, msg: "Actions: write"}, + {name: "the reviewer App, which has no Actions", req: effectReq(v1alpha1.OpCIRerun, provider.KindPR, docs+"#60", "reviewer", nil), + is: provider.ErrInvalid, msg: "Actions: write"}, + {name: "GitHub's 403 on the re-run", seed: func(s *githubtest.Server) { + s.FailNext(githubtest.RouteRerunFailedJobs, githubtest.Failure{Status: http.StatusForbidden, Message: "Resource not accessible by integration"}) + }, req: ciRerun(""), is: provider.ErrInvalid, msg: "Actions: write"}, + {name: "GitHub's 403 on the PR", seed: func(s *githubtest.Server) { + s.FailNext(githubtest.RoutePull, githubtest.Failure{Status: http.StatusForbidden, Message: "Resource not accessible by integration"}) + }, req: ciRerun(""), is: provider.ErrInvalid, msg: "Pull requests: read"}, + {name: "GitHub's 403 for another reason", seed: func(s *githubtest.Server) { + s.FailNext(githubtest.RouteRerunFailedJobs, githubtest.Failure{Status: http.StatusForbidden, Message: "Unable to re-run this workflow run because it was created over a month ago"}) + }, req: ciRerun(""), is: provider.ErrInvalid, msg: "over a month ago"}, + {name: "GitHub's 422 on the re-run", seed: func(s *githubtest.Server) { + s.FailNext(githubtest.RouteRerunFailedJobs, githubtest.Failure{Status: http.StatusUnprocessableEntity, Message: "Validation Failed"}) + }, req: ciRerun(""), is: provider.ErrInvalid}, + {name: "a run gone", seed: func(s *githubtest.Server) { + s.FailNext(githubtest.RouteRerunFailedJobs, githubtest.Failure{Status: http.StatusNotFound, Message: "Not Found"}) + }, req: ciRerun(""), is: provider.ErrNotFound}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, wfRun(1, ciWorkflow, 10, "completed", "failure")) + if tt.seed != nil { + tt.seed(e.srv) + } + _, err := e.connect(t).Apply(ctx, tt.req) + if !errors.Is(err, tt.is) || !strings.Contains(err.Error(), tt.msg) { + t.Errorf("Apply = %v, want %v with %q", err, tt.is, tt.msg) + } + if got := reruns(e.srv); len(got) != 0 { + t.Errorf("re-ran %v", got) + } + }) + } +} + +// A 5xx on a re-run retries the whole op: the run already re-run is queued by then, so only +// the one that failed is posted again. +func TestApplyCIRerunRetries(t *testing.T) { + e := newEnv(t) + seedEffects(e.srv) + e.srv.AddWorkflowRuns(docs, wfRun(1, ciWorkflow, 10, "completed", "failure"), wfRun(2, preview, 20, "completed", "cancelled")) + c := e.connect(t) + e.srv.FailNext(githubtest.RouteRerun, githubtest.Failure{Status: http.StatusBadGateway, Message: "Server Error"}) + done := make(chan error, 1) + go func() { + _, err := c.Apply(context.Background(), ciRerun("")) + done <- err + }() + e.clk.BlockUntil(1) + e.clk.Advance(time.Second) + if err := <-done; err != nil { + t.Fatalf("Apply: %v", err) + } + if f, w := e.srv.Count(githubtest.RouteRerunFailedJobs), e.srv.Count(githubtest.RouteRerun); f != 1 || w != 2 { + t.Errorf("rerun-failed-jobs %d, rerun %d; want 1 and 2", f, w) + } + if got := reruns(e.srv); !maps.Equal(got, map[int64]bool{1: true, 2: false}) { + t.Errorf("re-runs %v", got) + } +} diff --git a/internal/provider/github/effects_test.go b/internal/provider/github/effects_test.go index d67935a4..8d3f79bb 100644 --- a/internal/provider/github/effects_test.go +++ b/internal/provider/github/effects_test.go @@ -51,6 +51,7 @@ func writeCounts(s *githubtest.Server) map[string]int { githubtest.RouteCreateComment, githubtest.RouteUpdateComment, githubtest.RouteAddLabels, githubtest.RouteRemoveLabel, githubtest.RouteCreateIssue, githubtest.RouteUpdateIssue, githubtest.RouteAddSubIssue, githubtest.RouteCreatePull, githubtest.RouteUpdatePull, githubtest.RouteMerge, githubtest.RouteCreateReview, + githubtest.RouteRerunFailedJobs, githubtest.RouteRerun, } { out[r] = s.Count(r) } @@ -317,6 +318,21 @@ func TestApplyOps(t *testing.T) { } }, }, + { + name: "ci.rerun", + seed: func(s *githubtest.Server) { + s.AddWorkflowRuns(docs, githubtest.WorkflowRun{ID: 1, WorkflowID: 7, RunNumber: 3, HeadSHA: "abc123", Status: "completed", Conclusion: "failure"}) + }, + req: effectReq(v1alpha1.OpCIRerun, provider.KindPR, docs+"#60", "author", nil), + perms: map[string]string{"actions": "write", "pull_requests": "read"}, + writes: map[string]int{githubtest.RouteRerunFailedJobs: 1}, + object: docs + "#60", url: githubtest.WebURL + "/" + docs + "/pull/60/checks", + check: func(t *testing.T, s *githubtest.Server) { + if rs := s.WorkflowRuns(docs); len(rs) != 1 || rs[0].Attempt != 2 || !rs[0].FailedJobsOnly { + t.Errorf("runs %+v", rs) + } + }, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/provider/github/github.go b/internal/provider/github/github.go index 40202b6c..14e5d39e 100644 --- a/internal/provider/github/github.go +++ b/internal/provider/github/github.go @@ -183,6 +183,9 @@ type Conn struct { // bots maps the factory Apps' bot logins (lower-case) to identities; nil until learned. bots map[string]string memberCache map[string]membersEntry // group member sources resolved for trust, by source key + + // reruns are the ci.rerun effects applied, for replays (effects_ci.go). + reruns rerunLog } var _ provider.Conn = (*Conn)(nil) diff --git a/internal/provider/github/github_test.go b/internal/provider/github/github_test.go index d908ce08..389302a6 100644 --- a/internal/provider/github/github_test.go +++ b/internal/provider/github/github_test.go @@ -49,7 +49,7 @@ func newEnv(t *testing.T) *env { srv.AddApp(reviewerApp, &reviewerRSA.PublicKey) srv.AddInstallation(githubtest.Installation{ID: 1, AppID: authorApp, Owner: org, Permissions: map[string]string{ "contents": "write", "pull_requests": "write", "issues": "write", "metadata": "read", "members": "read", - "checks": "read", "actions": "read", "deployments": "read", + "checks": "read", "actions": "write", "deployments": "read", }}) srv.AddInstallation(githubtest.Installation{ID: 2, AppID: reviewerApp, Owner: org, Permissions: map[string]string{ "contents": "write", "pull_requests": "write", "issues": "read", "metadata": "read", diff --git a/internal/provider/github/githubtest/actions.go b/internal/provider/github/githubtest/actions.go new file mode 100644 index 00000000..359d17e1 --- /dev/null +++ b/internal/provider/github/githubtest/actions.go @@ -0,0 +1,151 @@ +package githubtest + +import ( + "fmt" + "net/http" + "slices" + "strconv" + "strings" + "time" +) + +// WorkflowRun is one GitHub Actions workflow run as the Actions API shows it: its latest +// attempt's Status (queued, in_progress, completed) and Conclusion once completed (success, +// failure, cancelled, …). A re-run (rerun-failed-jobs, rerun) is a new attempt of the same run: +// Attempt goes up and the run is queued again. +type WorkflowRun struct { + ID int64 + WorkflowID int64 + RunNumber int + Attempt int + Event string + HeadSHA string + Status string + Conclusion string + Created time.Time + // FailedJobsOnly records how the run was last re-run: true for rerun-failed-jobs, false + // for a whole re-run (or never re-run: Attempt is 1). + FailedJobsOnly bool +} + +// rerunnable are the conclusions of a run GitHub lets rerun-failed-jobs re-run: one with a +// failed (or cancelled) job. A green run has none. +var rerunnable = []string{"failure", "timed_out", "cancelled", "startup_failure"} + +// AddWorkflowRuns adds workflow runs to repo ("owner/name"); a run's Attempt defaults to 1 and +// its Event to pull_request. +func (s *Server) AddWorkflowRuns(repo string, runs ...WorkflowRun) { + s.mu.Lock() + defer s.mu.Unlock() + key := strings.ToLower(repo) + for _, r := range runs { + if r.Attempt == 0 { + r.Attempt = 1 + } + if r.Event == "" { + r.Event = "pull_request" + } + s.runs[key] = append(s.runs[key], r) + } +} + +// WorkflowRuns returns repo's workflow runs, in the order they were added. +func (s *Server) WorkflowRuns(repo string) []WorkflowRun { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.runs[strings.ToLower(repo)]) +} + +func (s *Server) routeActions(mux *http.ServeMux) { + mux.HandleFunc("GET /repos/{owner}/{repo}/actions/runs", s.handleWorkflowRuns) + mux.HandleFunc("POST /repos/{owner}/{repo}/actions/runs/{id}/rerun-failed-jobs", s.handleRerun(RouteRerunFailedJobs, true)) + mux.HandleFunc("POST /repos/{owner}/{repo}/actions/runs/{id}/rerun", s.handleRerun(RouteRerun, false)) +} + +func restWorkflowRun(repo string, r WorkflowRun) map[string]any { + var conclusion any + if r.Conclusion != "" { + conclusion = r.Conclusion + } + return map[string]any{ + "id": r.ID, "workflow_id": r.WorkflowID, "run_number": r.RunNumber, "run_attempt": r.Attempt, "event": r.Event, + "head_sha": r.HeadSHA, "status": r.Status, "conclusion": conclusion, "created_at": r.Created.UTC().Format(time.RFC3339), + "html_url": fmt.Sprintf("%s/%s/actions/runs/%d", WebURL, repo, r.ID), + } +} + +// handleWorkflowRuns lists a repo's workflow runs (actions: read), filtered by head_sha, in +// pages: {total_count, workflow_runs}. +func (s *Server) handleWorkflowRuns(w http.ResponseWriter, r *http.Request) { + m, ok := s.beginToken(w, r, RouteWorkflowRuns) + if !ok { + return + } + owner, repo := r.PathValue("owner"), r.PathValue("repo") + if !allowRepo(w, m, owner, repo, "actions") { + return + } + sha := r.URL.Query().Get("head_sha") + s.mu.Lock() + var items []any + for _, run := range s.runs[strings.ToLower(owner+"/"+repo)] { + if sha == "" || run.HeadSHA == sha { + items = append(items, restWorkflowRun(owner+"/"+repo, run)) + } + } + s.mu.Unlock() + lo, hi := s.pageBounds(w, r, len(items)) + writeJSON(w, http.StatusOK, map[string]any{"total_count": len(items), "workflow_runs": append([]any{}, items[lo:hi]...)}) +} + +// handleRerun re-runs a completed workflow run (actions: write): its failed jobs (failedOnly, +// which needs a failed or cancelled run) or all of them. As on GitHub, a run that hasn't +// completed is refused with 403, and a run with no failed job by rerun-failed-jobs with 403. +func (s *Server) handleRerun(route string, failedOnly bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + m, ok := s.beginToken(w, r, route) + if !ok { + return + } + owner, repo := r.PathValue("owner"), r.PathValue("repo") + if !allowRepoAny(w, m, owner, repo, []string{"actions"}, "write") { + return + } + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + writeError(w, http.StatusNotFound, "Not Found") + return + } + s.mu.Lock() + runs := s.runs[strings.ToLower(owner+"/"+repo)] + i := slices.IndexFunc(runs, func(run WorkflowRun) bool { return run.ID == id }) + status, msg := 0, "" + switch { + case i < 0: + status, msg = http.StatusNotFound, "Not Found" + case runs[i].Status != "completed": + status, msg = http.StatusForbidden, "This workflow is already running" + case failedOnly && !slices.Contains(rerunnable, runs[i].Conclusion): + status, msg = http.StatusForbidden, "This workflow run has no failed jobs to re-run" + default: + runs[i].Attempt++ + runs[i].Status, runs[i].Conclusion, runs[i].FailedJobsOnly = "queued", "", failedOnly + } + s.mu.Unlock() + if status != 0 { + writeError(w, status, msg) + return + } + writeJSON(w, http.StatusCreated, map[string]any{}) + } +} + +// SetWorkflowRun changes repo's workflow run id with fn (a run finishing, say). +func (s *Server) SetWorkflowRun(repo string, id int64, fn func(*WorkflowRun)) { + s.mu.Lock() + defer s.mu.Unlock() + runs := s.runs[strings.ToLower(repo)] + if i := slices.IndexFunc(runs, func(r WorkflowRun) bool { return r.ID == id }); i >= 0 { + fn(&runs[i]) + } +} diff --git a/internal/provider/github/githubtest/api.go b/internal/provider/github/githubtest/api.go index bb23679a..33d91f33 100644 --- a/internal/provider/github/githubtest/api.go +++ b/internal/provider/github/githubtest/api.go @@ -123,6 +123,7 @@ func (s *Server) routeAPI(mux *http.ServeMux) { mux.HandleFunc("GET /repos/{owner}/{repo}/compare/{basehead}", s.handleCompare) s.routeObjects(mux) s.routeEffects(mux) + s.routeActions(mux) } // beginToken records a request authenticated with an installation token and returns what diff --git a/internal/provider/github/githubtest/githubtest.go b/internal/provider/github/githubtest/githubtest.go index beac30d9..b29cdcab 100644 --- a/internal/provider/github/githubtest/githubtest.go +++ b/internal/provider/github/githubtest/githubtest.go @@ -132,6 +132,10 @@ const ( RouteReviews = "reviews" RouteReview = "review" RouteCreateReview = "create_review" + + RouteWorkflowRuns = "workflow_runs" + RouteRerunFailedJobs = "rerun_failed_jobs" + RouteRerun = "rerun" ) // Server is an httptest GitHub. @@ -162,14 +166,15 @@ type Server struct { hooks map[int64]bool // apps with a webhook deliveries map[int64][]Delivery // by app, newest first - objects map[string]*Object // by objectKey - commentSeq int64 // comment IDs - idSeq int64 // object IDs - repoConfig map[string]Repo // repo (lower) → settings - canned map[string][]byte // GraphQL responses, by cannedKey - deployments map[string][]Deployment // repo (lower), newest first - accountRepo map[string][]string // owner (lower) → repo names, for "all" installations - queries []GraphQLRequest // GraphQL requests received + objects map[string]*Object // by objectKey + commentSeq int64 // comment IDs + idSeq int64 // object IDs + repoConfig map[string]Repo // repo (lower) → settings + canned map[string][]byte // GraphQL responses, by cannedKey + deployments map[string][]Deployment // repo (lower), newest first + accountRepo map[string][]string // owner (lower) → repo names, for "all" installations + queries []GraphQLRequest // GraphQL requests received + runs map[string][]WorkflowRun // repo (lower) → workflow runs } // mintedToken is what an installation token the server minted covers. @@ -205,6 +210,7 @@ func NewServer(t testing.TB, c clock.Clock) *Server { deployments: map[string][]Deployment{}, accountRepo: map[string][]string{}, repoConfig: map[string]Repo{}, + runs: map[string][]WorkflowRun{}, } mux := http.NewServeMux() mux.HandleFunc("GET /app", s.handleApp) diff --git a/internal/provider/github/observe.go b/internal/provider/github/observe.go index 14cd3be4..8346c002 100644 --- a/internal/provider/github/observe.go +++ b/internal/provider/github/observe.go @@ -491,16 +491,34 @@ func suiteKind(s gqlCheckSuite) (string, bool) { return strconv.FormatInt(s.App.DatabaseID, 10) + "/" + strconv.FormatInt(w.Workflow.DatabaseID, 10) + "/" + w.Event, true } -// newerSuite reports whether a is later than b, two suites of one kind: the higher workflow -// run number, then the newer createdAt, then the higher databaseId. -func newerSuite(a, b gqlCheckSuite) bool { - if a.WorkflowRun != nil && b.WorkflowRun != nil && a.WorkflowRun.RunNumber != b.WorkflowRun.RunNumber { - return a.WorkflowRun.RunNumber > b.WorkflowRun.RunNumber +// newerSuite reports whether a is later than b, two suites of one kind (runOrder). +func newerSuite(a, b gqlCheckSuite) bool { return suiteOrder(a).after(suiteOrder(b)) } + +func suiteOrder(s gqlCheckSuite) runOrder { + o := runOrder{created: s.CreatedAt, id: s.DatabaseID} + if s.WorkflowRun != nil { + o.number = s.WorkflowRun.RunNumber + } + return o +} + +// runOrder places a run of one kind (a check suite, a workflow run) in time, for the +// superseding rule checksOf and ci.rerun share: the higher workflow run number, then the newer +// creation, then the higher ID. +type runOrder struct { + number int + created time.Time + id int64 +} + +func (a runOrder) after(b runOrder) bool { + if a.number != b.number { + return a.number > b.number } - if !a.CreatedAt.Equal(b.CreatedAt) { - return a.CreatedAt.After(b.CreatedAt) + if !a.created.Equal(b.created) { + return a.created.After(b.created) } - return a.DatabaseID > b.DatabaseID + return a.id > b.id } // objectState maps an issue's or PR's GraphQL state. diff --git a/schemas/rule.schema.json b/schemas/rule.schema.json index b0be62ca..7555c429 100644 --- a/schemas/rule.schema.json +++ b/schemas/rule.schema.json @@ -234,6 +234,7 @@ "review.approve", "thread.reply", "thread.resolve", + "ci.rerun", "push-branch", "stack.push", "stack.rebase" diff --git a/schemas/ruleset.schema.json b/schemas/ruleset.schema.json index e8868a45..1247e88e 100644 --- a/schemas/ruleset.schema.json +++ b/schemas/ruleset.schema.json @@ -258,6 +258,7 @@ "review.approve", "thread.reply", "thread.resolve", + "ci.rerun", "push-branch", "stack.push", "stack.rebase" diff --git a/schemas/taskspec.schema.json b/schemas/taskspec.schema.json index 172d4f71..0c81c83d 100644 --- a/schemas/taskspec.schema.json +++ b/schemas/taskspec.schema.json @@ -26,6 +26,7 @@ "review.approve", "thread.reply", "thread.resolve", + "ci.rerun", "push-branch", "stack.push", "stack.rebase" diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index d1ae0d1a..29459579 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -1714,7 +1714,7 @@ export interface components { * @description EffectOp is a provider effect, as named in TaskSpec effects.allow and the effect action. * @enum {string} */ - EffectOp: "comment" | "pr.comment" | "label.add" | "label.remove" | "create-issue" | "sub-issue.add" | "close" | "link-duplicate" | "pr.open" | "pr.update" | "pr.retarget" | "pr.merge" | "review.comment" | "review.request-changes" | "review.approve" | "thread.reply" | "thread.resolve" | "push-branch" | "stack.push" | "stack.rebase"; + EffectOp: "comment" | "pr.comment" | "label.add" | "label.remove" | "create-issue" | "sub-issue.add" | "close" | "link-duplicate" | "pr.open" | "pr.update" | "pr.retarget" | "pr.merge" | "review.comment" | "review.request-changes" | "review.approve" | "thread.reply" | "thread.resolve" | "ci.rerun" | "push-branch" | "stack.push" | "stack.rebase"; /** @description EffectResult is the outcome of an effect. */ EffectResult: { url?: string;