AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
ci(infra): batch-deploy bot — /batch, /batch-remove, /batch-merge (#13465)
Nicholas Tindlebd66b8daae76
diff --git a/.github/batch-bot/README.md b/.github/batch-bot/README.mdnew file mode 100644index 0000000000..b5158132df--- /dev/null+++ b/.github/batch-bot/README.md@@ -0,0 +1,131 @@+# Batch-deploy bot++Batch several approved PRs onto one **rollup branch** so the preview environment+deploys and is tested **once** for all of them — instead of waiting on N serial+preview deploys to verify N unrelated features. The rollup branch is both the+deploy artifact and the merge artifact: `/batch-merge` lands it and its members+go together.++Deterministic GitHub Actions ChatOps — no AI, nothing needs Claude to run.++## Commands++Comment on any PR (requires **write** access; the listener does a real+repo-permission lookup, not the unreliable `author_association`):++| Command | Effect |+|---|---|+| `/batch` | Add this PR to the current batch; rebuild + redeploy the shared preview |+| `/batch-remove` | Remove this PR from the batch; rebuild + redeploy |+| `/batch-merge` | Land every PR in the batch together (enables auto-merge on the rollup) |+| `/batch help` | Post the command list |++## How it works++- **Membership** = the `batch` label. No database; the label is the source of truth.+- On every change the bot **rebuilds `batch/rollup`** from a fresh `dev` by+ sequentially `git merge`-ing each member. A member that is a fork branch, has an+ unsafe ref name, or conflicts with the group is **ejected** (label removed,+ author told to rebase) so one bad PR never stalls the batch.+- A **rollup PR** (`batch/rollup` → `dev`) is the sticky status surface, the thing+ the preview env deploys, and the thing `/batch-merge` lands.+- **Preview:** the bot reuses the repo's existing per-PR preview system. On each+ batch change it posts a bare **`!deploy`** comment on the rollup PR, which the+ `platform-dev-deploy-event-dispatcher.yml` → `AutoGPT_cloud_infrastructure`+ pipeline turns into ONE **isolated per-PR environment** keyed by the rollup PR's+ number (namespace `pr-<n>`, Postgres schema `pr_<n>`, URLs `pr-<n>-server.agpt.co`+ / `autogpt-pr-<n>.vercel.app`) that **runs all the batched migrations against its+ own schema**. That isolation is provided by the preview system, not this bot.+- `/batch-merge` requires every member **`reviewDecision === APPROVED` + green**,+ then enables **auto-merge (squash)** on the rollup. It lands once the rollup PR's+ own required human approval + checks pass.+- After the rollup squash-merges, `batch-reconcile.yml` posts **`!undeploy`** to+ tear the preview down and **closes each member** with a comment crediting the+ rollup (squash rewrites SHAs, so members would otherwise show neither "Merged"+ nor closed), then deletes the rollup branch. (The deploy dispatcher also+ auto-undeploys on the rollup PR's close; the overlap is idempotent.)++`dev` is squash-only with linear history and no merge queue, so this uses+auto-merge, not a queue. If you later add a native merge queue you get the+always-green-merge-result guarantee; swap the `--auto` enable for an enqueue.++## Migrations batch on purpose++Migrations are the highest-value thing to test in a combined deploy — you cannot+verify two migrations coexist and apply in order without deploying them together.+During assembly `schema.prisma` is merged with git's **union driver**+(`.git/info/attributes`, assembly-scoped, never committed) so additive migrations+combine. The **preview's `prisma migrate` is the backstop**: union can concatenate+two edits to the same model into a valid-but-wrong schema, so the combined preview+run is what actually proves the migrations are compatible. Give each batch build a+**fresh database**. (Cross-PR migration ordering is timestamp-driven — review the+rollup if ordering matters.)++## Security requirements (must hold before enabling)++This bot was security-reviewed. The following are **hard requirements**, not+suggestions:++1. **The rollup PR must get a genuine human approval — never auto-approved or+ bypassed.** The rollup is the *union* of everyone's code plus a union-merged+ schema; per-member approvals do not cover the merged result. The bot authors the+ rollup PR, so a maintainer approving it is never a self-approval. Keep `dev`'s+ required-review rule; do **not** add a bot self-approve or a review bypass.+2. **Enable "dismiss stale reviews on push"** on `dev`, and **protect+ `batch/rollup`** so only the bot identity can push to it. Otherwise a member+ could get the rollup approved, then push, and land on a stale approval.+3. **Preview isolation.** `/batch` deploys code that is not yet code-reviewed (that+ is the point — test early), co-locating multiple authors' code + migration SQL in+ one environment. This is handled by the existing per-PR preview system+ (`AutoGPT_cloud_infrastructure`): each rollup gets its own namespace `pr-<n>`,+ Postgres schema `pr_<n>`, and URLs — non-prod and per-PR isolated. Confirm those+ previews use non-prod secrets (they do by design). Nuance: isolation is+ schema-level within a shared preview Postgres cluster, not separate DB servers —+ fine for non-prod previews. Optionally set `BATCH_REQUIRE_APPROVAL=1` to require+ an approval before a PR can be added to the batch.+4. **Pinned actions.** All actions are pinned to commit SHAs (`slash-command-dispatch`,+ `checkout`, `setup-node`); keep them pinned when bumping.+5. **No shell.** `batch.mjs` uses array-arg `execFileSync` only — attacker-controlled+ PR titles / branch names are passed as single argv entries and cannot inject.+ Do not reintroduce string-form `exec`.++## Setup++### 1. Bot token — `BATCH_BOT_TOKEN` (repo secret)++Needed (not just `GITHUB_TOKEN`) because a `repository_dispatch` made with+`GITHUB_TOKEN` won't trigger the handler, and pushes by `GITHUB_TOKEN` won't+trigger the preview-deploy — and the payoff is the rollup push kicking off one+preview.++**Prefer a GitHub App installation token** (short-lived, auto-rotating,+repo-scoped) over a PAT. If you must use a PAT, make it **fine-grained,+single-repo, with an expiry** — never a classic PAT. Either way grant only:++| Permission | Level | Why |+|---|---|---|+| Contents | Read/write | create + update the ephemeral `batch/rollup` branch |+| Pull requests | Read/write | label, comment, open/update/merge the rollup PR |+| Issues | Read/write | label CRUD + PR conversation comments |+| Actions | Read | read member CI status before batch/merge |+| Metadata | Read | required baseline |++Add the identity as a **write collaborator**. Do **not** grant admin or a+review-bypass — that would turn the token into a review-bypass primitive.++Optional repo **variables**: `BATCH_BASE_BRANCH` (default `dev`), `BATCH_BOT_NAME`,+`BATCH_BOT_EMAIL`.++### 2. Preview environment++No new preview infra needed — the bot reuses the repo's existing per-PR preview+system by posting `!deploy` on the rollup PR (handled by+`platform-dev-deploy-event-dispatcher.yml` → `AutoGPT_cloud_infrastructure`'s+`autogpt-platform-preview-env-cd.yml`). Two prerequisites: that per-PR preview+system is enabled, and the bot identity is a **write collaborator** so the deploy+dispatcher honors its `!deploy`/`!undeploy` comments (the dispatcher gates on the+commenter's `author_association`).++## Opt-out++Opt a PR out of batching with the `batch:never` label.diff --git a/.github/batch-bot/batch.mjs b/.github/batch-bot/batch.mjsnew file mode 100644index 0000000000..2be00db8ff--- /dev/null+++ b/.github/batch-bot/batch.mjs@@ -0,0 +1,348 @@+#!/usr/bin/env node+// Deterministic PR-batching bot for preview-deploy testing.+//+// Purpose: batch several approved PRs onto ONE unified branch so the preview+// environment deploys and is tested ONCE for all of them, instead of N serial+// preview deploys. The unified branch is both the deploy artifact AND the merge+// artifact — `/batch-merge` lands it and its members go together.+//+// Commands (from repository_dispatch action, minus the `-command` suffix), plus+// `reconcile` (fired by batch-reconcile.yml when the rollup PR merges):+// batch — add the commenting PR to the batch, rebuild + redeploy the group+// batch-remove — remove the commenting PR from the batch, rebuild + redeploy+// batch-merge — enable auto-merge on the rollup; members land once it's approved+green+// batch help — post the command list (ARG1 === "help")+// reconcile — after the rollup squash-merges, close members with credit + clean up+//+// State lives in GitHub, not a DB: the `batch` label is the source of truth; the+// ROLLUP branch is rebuilt from scratch on every change; a "rollup PR"+// (ROLLUP -> BASE) is the sticky status surface + deploy + merge target.+//+// SECURITY: every `git`/`gh` call goes through execFileSync with ARRAY args — no+// shell, so attacker-controlled PR titles / branch names can never break out+// (they are passed as single argv entries). Do not reintroduce string commands.+//+// Migrations batch on purpose: a combined preview deploy is the only way to test+// that two migrations coexist and apply in order. `schema.prisma` is union-merged+// during assembly; the preview's `prisma migrate` is the backstop that catches a+// genuine clash (union can otherwise concatenate into a valid-but-wrong schema).++import { execFileSync } from "node:child_process";+import { writeFileSync, mkdirSync } from "node:fs";++const REPO = req("REPO");+const BASE = process.env.BASE || "dev";+const ROLLUP = process.env.ROLLUP_BRANCH || "batch/rollup";+const LABEL = process.env.BATCH_LABEL || "batch";+const NEVER = process.env.NEVER_BATCH_LABEL || "batch:never"; // opt-out escape hatch+const REQUIRE_APPROVAL_TO_ADD = process.env.BATCH_REQUIRE_APPROVAL === "1";+const MARKER = "<!-- batch-bot:rollup -->";+const command = req("COMMAND").replace(/-command$/, ""); // batch | batch-remove | batch-merge | reconcile+const prNumber = process.env.PR_NUMBER ? Number(process.env.PR_NUMBER) : null;+const arg1 = (process.env.ARG1 || "").trim();+const rollupUrl = process.env.ROLLUP_URL || "";+const rollupPr = process.env.ROLLUP_PR ? Number(process.env.ROLLUP_PR) : null;+const SAFE_REF = /^[\w./-]+$/; // git ref chars we allow through, defense-in-depth++function req(name) {+ const v = process.env[name];+ if (!v) throw new Error(`missing required env ${name}`);+ return v;+}++// --- exec: array args only, never a shell string -------------------------+function run(file, args, opts = {}) {+ return execFileSync(file, args, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], ...opts }).trim();+}+function tryRun(file, args) {+ try {+ return { ok: true, out: run(file, args) };+ } catch (e) {+ return { ok: false, out: (e.stdout || "") + (e.stderr || "") };+ }+}+const git = (args) => run("git", args);+const tryGit = (args) => tryRun("git", args);+const gh = (args) => run("gh", args);+const tryGh = (args) => tryRun("gh", args);+const ghJSON = (args) => JSON.parse(gh(args));++// --- membership ----------------------------------------------------------++function members() {+ const rows = ghJSON([+ "pr", "list", "--repo", REPO, "--state", "open", "--label", LABEL, "--limit", "100",+ "--json", "number,title,headRefName,headRefOid,url,labels,reviewDecision,mergeable,isDraft",+ ]);+ return rows.filter((p) => !p.labels.some((l) => l.name === NEVER));+}++function comment(pr, body) {+ const f = `/tmp/batch-comment-${Number(pr)}.md`;+ writeFileSync(f, body);+ gh(["pr", "comment", String(Number(pr)), "--repo", REPO, "--body-file", f]);+}++function unlabel(pr) {+ tryGh(["pr", "edit", String(Number(pr)), "--repo", REPO, "--remove-label", LABEL]);+}++// --- rollup branch assembly ---------------------------------------------++// Rebuild ROLLUP from a fresh BASE by sequentially merging each member. A member+// with an unsafe branch name, an unfetchable branch (e.g. a fork), or a non-schema+// conflict is EJECTED (label removed) so one bad PR never stalls the batch.+function buildRollup(list) {+ git(["fetch", "origin", BASE, "--quiet"]);+ git(["checkout", "-B", ROLLUP, `origin/${BASE}`]);++ // Local-only union driver for schema.prisma (never committed, assembly-scoped).+ mkdirSync(".git/info", { recursive: true });+ writeFileSync(".git/info/attributes", "**/schema.prisma merge=union\n");++ const merged = [];+ const ejected = [];+ for (const p of list) {+ if (!SAFE_REF.test(p.headRefName)) {+ ejected.push({ ...p, files: "unsafe branch name" });+ unlabel(p.number);+ comment(p.number, `${MARKER}\n🤖 Removed from the batch — branch name is not a plain git ref.`);+ continue;+ }+ const fetched = tryGit(["fetch", "origin", p.headRefName, "--quiet"]);+ if (!fetched.ok) {+ ejected.push({ ...p, files: "branch not on origin (fork?)" });+ unlabel(p.number);+ comment(+ p.number,+ `${MARKER}\n🤖 Removed from the batch — the head branch could not be fetched from \`origin\` ` ++ `(cross-fork PRs cannot be batched). Push the branch to the main repo to batch it.`,+ );+ continue;+ }+ const res = tryGit(["merge", "--no-ff", "FETCH_HEAD", "-m", `batch: ${p.title} (#${p.number})`]);+ if (res.ok) {+ merged.push(p);+ continue;+ }+ tryGit(["merge", "--abort"]);+ const files = tryGit(["diff", "--name-only", "--diff-filter=U"]).out || "conflicting files";+ ejected.push({ ...p, files });+ unlabel(p.number);+ comment(+ p.number,+ `${MARKER}\n🤖 Removed from the batch — this PR conflicts with the rest of the current ` ++ `group and could not be merged onto \`${ROLLUP}\` (${files}). Rebase onto \`${BASE}\` ` ++ `(or resolve against the other batched PRs) and re-add with \`/batch\`.`,+ );+ }++ // Force-update the ephemeral, bot-owned rollup branch via the refs API. This is+ // a non-ff update of a throwaway branch nobody builds on — protect it in branch+ // settings so only the bot can push to it (see README).+ const sha = git(["rev-parse", "HEAD"]);+ const ref = `refs/heads/${ROLLUP}`;+ const exists = tryGh(["api", `repos/${REPO}/git/${ref}`]).ok;+ if (exists) {+ gh(["api", "-X", "PATCH", `repos/${REPO}/git/${ref}`, "-f", `sha=${sha}`, "-F", "force=true"]);+ } else {+ gh(["api", "-X", "POST", `repos/${REPO}/git/refs`, "-f", `ref=${ref}`, "-f", `sha=${sha}`]);+ }+ return { merged, ejected };+}++// --- rollup PR (sticky status + deploy + merge target) -------------------++function findRollupPR() {+ const owner = REPO.split("/")[0];+ const rows = ghJSON([+ "pr", "list", "--repo", REPO, "--head", `${owner}:${ROLLUP}`, "--base", BASE, "--state", "open",+ "--json", "number,url",+ ]);+ return rows[0] || null;+}++function rollupBody(merged, ejected) {+ const lines = [MARKER, "", `### Batch rollup — ${merged.length} PR(s)`, ""];+ lines.push("Deploying the union of these PRs to a single preview so they are tested together.", "");+ for (const p of merged) lines.push(`- [ ] #${p.number} — ${p.title}`);+ if (ejected.length) {+ lines.push("", "**Ejected (conflicted with the group, rebase to re-add):**");+ for (const p of ejected) lines.push(`- #${p.number} — ${p.title}`);+ }+ lines.push(+ "",+ "---",+ "Commands (comment on any PR): `/batch` add · `/batch-remove` drop · `/batch-merge` land all · `/batch help`",+ "Preview: an isolated per-PR full-stack env (namespace `pr-<n>`, its own DB schema running the",+ "batched migrations) is (re)deployed automatically via `!deploy` on each batch change, and torn",+ "down when this PR merges or closes.",+ "",+ "> This PR is the union of everyone's code. Its approval must be a real human review of the",+ "> merged result — do not auto-approve or bypass; per-member approvals do not cover the union.",+ );+ return lines.join("\n");+}++function upsertRollupPR(merged, ejected) {+ const f = "/tmp/rollup-body.md";+ writeFileSync(f, rollupBody(merged, ejected));+ const title = `Batch rollup: ${merged.length} PR(s)`;+ let pr = findRollupPR();+ if (!pr) {+ if (merged.length === 0) return null;+ const url = gh([+ "pr", "create", "--repo", REPO, "--head", ROLLUP, "--base", BASE, "--draft",+ "--title", title, "--body-file", f,+ ]);+ return { number: Number(url.split("/").pop()), url };+ }+ gh(["pr", "edit", String(pr.number), "--repo", REPO, "--title", title, "--body-file", f]);+ if (merged.length === 0) {+ // Closing the rollup PR triggers the deploy dispatcher's PR-close auto-undeploy.+ tryGh(["pr", "close", String(pr.number), "--repo", REPO, "--delete-branch"]);+ return null;+ }+ return pr;+}++// The infra preview system deploys a per-PR isolated env on an exact `!deploy`+// comment (autogpt-platform-preview-env-cd.yml, keyed by PR number). Posting it on+// the rollup PR (re)deploys ONE env whose DB runs all the batched migrations. The+// bot must be a write collaborator for the deploy dispatcher to honor the comment.+function deployRollup(pr) {+ tryGh(["pr", "comment", String(pr.number), "--repo", REPO, "--body", "!deploy"]);+}++// --- commands ------------------------------------------------------------++function assertBatchable(pr) {+ const p = ghJSON([+ "pr", "view", String(Number(pr)), "--repo", REPO,+ "--json", "number,isDraft,state,labels,reviewDecision",+ ]);+ if (p.state !== "OPEN") throw new Error(`PR #${pr} is not open`);+ if (p.labels.some((l) => l.name === NEVER))+ throw new Error(`PR #${pr} is labeled ${NEVER} (opted out of batching)`);+ if (REQUIRE_APPROVAL_TO_ADD && p.reviewDecision !== "APPROVED")+ throw new Error(`PR #${pr} is not approved (${p.reviewDecision || "no reviews"}) and BATCH_REQUIRE_APPROVAL is set`);+ return p;+}++function rebuildAndReport(actionNote) {+ const { merged, ejected } = buildRollup(members());+ const pr = upsertRollupPR(merged, ejected);+ if (pr) deployRollup(pr); // (re)deploy the combined preview to reflect the new batch+ if (prNumber) {+ const names = merged.map((p) => `#${p.number}`).join(", ") || "none";+ comment(+ prNumber,+ `${MARKER}\n🤖 ${actionNote} Current batch (${merged.length}): ${names}.` ++ (ejected.length ? ` Ejected: ${ejected.map((p) => "#" + p.number).join(", ")}.` : "") ++ (pr ? `\n\nDeploying the combined preview (${pr.url}); \`/batch-merge\` lands them together.` : ""),+ );+ }+ console.log(`batch: ${merged.length} member(s)${pr ? ` → ${pr.url}` : " (empty)"}`);+}++function cmdBatch() {+ if (arg1.toLowerCase() === "help") return cmdHelp();+ if (!prNumber) throw new Error("no PR number");+ assertBatchable(prNumber);+ gh(["pr", "edit", String(prNumber), "--repo", REPO, "--add-label", LABEL]);+ rebuildAndReport(`Added #${prNumber} to the batch.`);+}++function cmdBatchRemove() {+ if (!prNumber) throw new Error("no PR number");+ unlabel(prNumber);+ rebuildAndReport(`Removed #${prNumber} from the batch.`);+}++function cmdBatchMerge() {+ const list = members();+ if (list.length === 0) {+ if (prNumber) comment(prNumber, `${MARKER}\n🤖 The batch is empty — nothing to merge.`);+ return;+ }+ // Every member must be explicitly approved and green. `reviewDecision` must be+ // exactly APPROVED — null / REVIEW_REQUIRED / CHANGES_REQUESTED all block.+ const blockers = [];+ for (const p of list) {+ if (p.reviewDecision !== "APPROVED")+ blockers.push(`#${p.number} not approved (${p.reviewDecision || "no reviews"})`);+ const checks = tryGh(["pr", "checks", String(p.number), "--repo", REPO, "--json", "bucket"]);+ if (checks.ok) {+ const bad = JSON.parse(checks.out).filter((c) => c.bucket === "fail" || c.bucket === "cancel");+ if (bad.length) blockers.push(`#${p.number} has failing checks`);+ }+ }+ const { merged, ejected } = buildRollup(list);+ const pr = upsertRollupPR(merged, ejected);+ if (!pr) throw new Error("rollup PR missing after build");+ if (blockers.length) {+ comment(prNumber || pr.number, `${MARKER}\n🤖 Not merging — resolve first:\n- ${blockers.join("\n- ")}`);+ return;+ }+ // No merge queue on dev + squash-only: use auto-merge (squash). It lands the+ // rollup once its OWN required human approval + green checks are satisfied — the+ // bot never approves or bypasses. batch-reconcile.yml closes members afterward.+ gh(["pr", "ready", String(pr.number), "--repo", REPO]);+ const enq = tryGh(["pr", "merge", String(pr.number), "--repo", REPO, "--squash", "--auto"]);+ const note = enq.ok+ ? `Auto-merge enabled on the rollup (${merged.length} PR(s)). It lands once a maintainer ` ++ `approves ${pr.url} and checks are green — then all members merge together.`+ : `Could not enable auto-merge on the rollup: ${enq.out}. Check branch protection / that a ` ++ `reviewer can approve ${pr.url}.`;+ comment(prNumber || pr.number, `${MARKER}\n🤖 ${note}`);+}++// Fired by batch-reconcile.yml after the rollup PR squash-merges. Squash rewrites+// SHAs, so members won't auto-flip to "Merged" — close them explicitly with credit.+function cmdReconcile() {+ // Tear the combined preview down explicitly (the deploy dispatcher also+ // auto-undeploys on the rollup PR's close; this is the guaranteed path and+ // idempotent teardown makes the overlap harmless).+ if (rollupPr) tryGh(["pr", "comment", String(rollupPr), "--repo", REPO, "--body", "!undeploy"]);+ const list = members();+ for (const p of list) {+ comment(p.number, `${MARKER}\n🤖 Landed on \`${BASE}\` via batch rollup${rollupUrl ? ` ${rollupUrl}` : ""}. Closing — your change is merged.`);+ unlabel(p.number);+ tryGh(["pr", "close", String(p.number), "--repo", REPO]);+ }+ tryGit(["push", "origin", "--delete", ROLLUP]);+ console.log(`reconciled ${list.length} member(s)`);+}++function cmdHelp() {+ const target = prNumber || (findRollupPR() || {}).number;+ if (!target) return;+ comment(+ target,+ `${MARKER}\n🤖 **Batch commands** (comment on any PR):\n` ++ "- `/batch` — add this PR to the current batch (rebuilds the shared preview branch)\n" ++ "- `/batch-remove` — remove this PR from the batch\n" ++ "- `/batch-merge` — land every PR in the batch together (enables auto-merge on the rollup)\n" ++ "- `/batch help` — show this message\n\n" ++ `Requires write access. Opt a PR out with the \`${NEVER}\` label.`,+ );+}++// --- dispatch ------------------------------------------------------------++try {+ if (command === "batch") cmdBatch();+ else if (command === "batch-remove") cmdBatchRemove();+ else if (command === "batch-merge") cmdBatchMerge();+ else if (command === "reconcile") cmdReconcile();+ else throw new Error(`unknown command: ${command}`);+} catch (e) {+ const msg = e && e.message ? e.message : String(e);+ if (prNumber) {+ try {+ comment(prNumber, `${MARKER}\n🤖 Batch command failed: ${msg}`);+ } catch {}+ }+ console.error(msg);+ process.exit(1);+}diff --git a/.github/workflows/batch-command-handler.yml b/.github/workflows/batch-command-handler.ymlnew file mode 100644index 0000000000..7814422ceb--- /dev/null+++ b/.github/workflows/batch-command-handler.yml@@ -0,0 +1,52 @@+name: batch-command-handler++# Handles the repository_dispatch events from batch-command-listener.yml.+# All work lives in .github/batch-bot/batch.mjs (dependency-free Node driving+# `git` + `gh` via array-arg execFileSync — no shell). repository_dispatch always+# checks out the DEFAULT branch, so this workflow never runs PR-controlled code;+# member branches are only ever `git merge`d (data), never executed here.+# Runs under BATCH_BOT_TOKEN so the rollup-branch push triggers the preview deploy+# (GITHUB_TOKEN pushes do not trigger other workflows).+on:+ repository_dispatch:+ types: [batch-command, batch-remove-command, batch-merge-command]++permissions:+ contents: write+ pull-requests: write+ issues: write+ actions: read++concurrency:+ group: batch-bot+ cancel-in-progress: false++jobs:+ handle:+ runs-on: ubuntu-latest+ env:+ GH_TOKEN: ${{ secrets.BATCH_BOT_TOKEN }}+ REPO: ${{ github.repository }}+ BASE: ${{ vars.BATCH_BASE_BRANCH || 'dev' }}+ COMMAND: ${{ github.event.action }}+ PR_NUMBER: ${{ github.event.client_payload.slash_command.args.named.pr }}+ ARG1: ${{ github.event.client_payload.slash_command.args.unnamed.arg1 }}+ BOT_NAME: ${{ vars.BATCH_BOT_NAME || 'autogpt-batch-bot' }}+ BOT_EMAIL: ${{ vars.BATCH_BOT_EMAIL || '[email protected]' }}+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ fetch-depth: 0+ token: ${{ secrets.BATCH_BOT_TOKEN }}++ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ with:+ node-version: "20"++ - name: Configure bot git identity+ run: |+ git config user.name "$BOT_NAME"+ git config user.email "$BOT_EMAIL"++ - name: Run batch bot+ run: node .github/batch-bot/batch.mjsdiff --git a/.github/workflows/batch-command-listener.yml b/.github/workflows/batch-command-listener.ymlnew file mode 100644index 0000000000..51d5fed7e4--- /dev/null+++ b/.github/workflows/batch-command-listener.yml@@ -0,0 +1,40 @@+name: batch-command-listener++# Turns `/batch`, `/batch-remove`, `/batch-merge` PR comments into repository_dispatch+# events handled by batch-command-handler.yml. Deterministic ChatOps — no AI.+#+# Why a bot token (BATCH_BOT_TOKEN) and not GITHUB_TOKEN:+# A repository_dispatch created with GITHUB_TOKEN does NOT trigger the handler+# workflow (GitHub suppresses workflow-triggered-by-GITHUB_TOKEN to avoid loops).+# The dispatch must be made by a real identity (PAT on a bot account, or a+# GitHub App token) for the handler to run.+on:+ issue_comment:+ types: [created]++permissions:+ contents: read++jobs:+ dispatch:+ # PR comments only, and only when the FIRST line starts with `/batch`+ # (peter-evans/slash-command-dispatch additionally enforces first-line + a+ # real repo-permission lookup — `author_association` is unreliable in orgs).+ if: >-+ github.event.issue.pull_request != null &&+ startsWith(github.event.comment.body, '/batch')+ runs-on: ubuntu-latest+ steps:+ - name: Slash command dispatch+ uses: peter-evans/slash-command-dispatch@0683e68ce8b375f2dc24214e065a3ae1ef93040e # v5+ with:+ token: ${{ secrets.BATCH_BOT_TOKEN }}+ issue-type: pull-request+ permission: write+ commands: |+ batch+ batch-remove+ batch-merge+ # Pass the PR number explicitly so the handler never has to guess it.+ static-args: |+ pr=${{ github.event.issue.number }}diff --git a/.github/workflows/batch-reconcile.yml b/.github/workflows/batch-reconcile.ymlnew file mode 100644index 0000000000..4ea458eca6--- /dev/null+++ b/.github/workflows/batch-reconcile.yml@@ -0,0 +1,36 @@+name: batch-reconcile++# When the rollup PR squash-merges into BASE, its members' commit SHAs are+# rewritten, so GitHub will not auto-mark them "Merged". This closes each batched+# member with a comment crediting the rollup and cleans up the rollup branch.+on:+ pull_request:+ types: [closed]++permissions:+ contents: write+ pull-requests: write+ issues: write++jobs:+ reconcile:+ # Only when the ROLLUP branch's PR actually merged.+ if: >-+ github.event.pull_request.merged == true &&+ github.event.pull_request.head.ref == 'batch/rollup'+ runs-on: ubuntu-latest+ env:+ GH_TOKEN: ${{ secrets.BATCH_BOT_TOKEN }}+ REPO: ${{ github.repository }}+ BASE: ${{ vars.BATCH_BASE_BRANCH || 'dev' }}+ COMMAND: reconcile+ ROLLUP_URL: ${{ github.event.pull_request.html_url }}+ ROLLUP_PR: ${{ github.event.pull_request.number }}+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ token: ${{ secrets.BATCH_BOT_TOKEN }}+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ with:+ node-version: "20"+ - run: node .github/batch-bot/batch.mjs