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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3218,6 +3218,7 @@ components:
- review.approve
- thread.reply
- thread.resolve
- ci.rerun
- push-branch
- stack.push
- stack.rebase
Expand Down
1 change: 1 addition & 0 deletions design/workstreams/agent/LLD/effector.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<sha>`) 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 |
Expand Down
1 change: 1 addition & 0 deletions design/workstreams/foundation/LLD/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<sha>`) 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
Expand Down
2 changes: 1 addition & 1 deletion design/workstreams/poc-rollout/LLD/rollout.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<tunnel-host>/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` |
Expand Down
12 changes: 11 additions & 1 deletion design/workstreams/provider-github/LLD/github-provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

| App | Role | Webhook | Permissions (repository) | Events |
|---|---|---|---|---|
| `ccf-factory` | `author` identity **and the only event source** | **yes** → `https://<public-url>/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://<public-url>/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).
Expand Down Expand Up @@ -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=<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.

Expand Down Expand Up @@ -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 <id> (refused|attempt <n>), …`. 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-<sha>`, 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 `<key>@<head SHA>`, 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.
2 changes: 2 additions & 0 deletions internal/agent/effector/effector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"}},
}
}

Expand Down Expand Up @@ -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, ""},
}
Expand Down
4 changes: 2 additions & 2 deletions internal/agent/effector/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 })]
Expand Down
11 changes: 11 additions & 0 deletions internal/agent/effector/ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -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-<sha> 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).",
Expand Down
5 changes: 5 additions & 0 deletions internal/agent/effector/testdata/requests.golden.json
Original file line number Diff line number Diff line change
@@ -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."
Expand Down
2 changes: 2 additions & 0 deletions internal/apis/v1alpha1/effects.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -62,6 +63,7 @@ var effectOps = []struct {
{OpReviewApprove, SideAPI},
{OpThreadReply, SideAPI},
{OpThreadResolve, SideAPI},
{OpCIRerun, SideAPI},
{OpPushBranch, SideGit},
{OpStackPush, SideGit},
{OpStackRebase, SideGit},
Expand Down
5 changes: 3 additions & 2 deletions internal/apis/v1alpha1/vocabulary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand All @@ -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)
}
}
12 changes: 12 additions & 0 deletions internal/catalog/phases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading