#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add PR size limit for OSS PRs (#8353)
James Bruntonbe9346fbe1b8
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex e14e4a0e45..1ca4eaa536 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -44,6 +44,15 @@ Please make sure your Pull Request adheres to the following guidelines:- References to the Issue number in the Pull Request and/or Commit message.- Every comment in the diff should say something the code does not. See [Code comments](../docs/developer/CODE_COMMENTS.md); `task comment-lint` checks the mechanical part.+## Pull Request Size++To keep reviews manageable, Pull Requests from contributors outside the team are limited to 1000 changed lines (lines added plus lines removed). Translation files and lockfiles don't count towards the limit.++- A Pull Request over the limit fails the "Check PR size" check, and will gain the `too-large` label.+- Please split large changes into smaller Pull Requests that can each be reviewed on their own.+- If you think a change can't be split, add a comment explaining why so a maintainer can take a look.+- If the Pull Request is still over the limit 7 days after gaining the `too-large` label, it will be automatically closed.+## Stale Pull RequestsTo keep the list of open Pull Requests manageable, PRs that appear abandoned will automatically be closed (after a warning).diff --git a/.github/labels.yml b/.github/labels.ymlindex 727df50de6..0de0eaab85 100644--- a/.github/labels.yml+++ b/.github/labels.yml@@ -212,6 +212,12 @@- name: "backlog-cleanup"color: "BFD4F2"description: "Closed during the PR backlog cleanup; reopen to continue"+- name: "large-pr-approved"+ color: "0E8A16"+ description: "A maintainer has accepted this PR's size; the size limit no longer applies"+- name: "too-large"+ color: "B60205"+ description: "Over the size limit for contributors outside the team; closes a week after this was added unless split or approved"- name: "waiting-on-author"color: "FEF2C0"description: "A maintainer is waiting on the author; removed when the author pushes or replies"diff --git a/.github/scripts/github.ts b/.github/scripts/github.tsindex 02780653de..2929a1cb07 100644--- a/.github/scripts/github.ts+++ b/.github/scripts/github.ts@@ -1,4 +1,4 @@-// The GitHub API surface and labels the PR bots share.+// The GitHub API surface, labels and timings the PR bots share.export const LABELS = {stale: "Stale PR",@@ -6,8 +6,13 @@ export const LABELS = {backlogCleanup: "backlog-cleanup",waitingOnAuthor: "waiting-on-author",conflicts: "has conflicts", // must match CONFLICT_LABEL in pr-conflict-labeler.yml+ largePrApproved: "large-pr-approved",+ tooLarge: "too-large",};+/** Days from a warning to the close, for the stale PR warning and the size warning alike. */+export const CLOSE_AFTER_WARNING_DAYS = 7;+/** The login github.token acts as, so the actor on every write these bots make. */export const BOT_LOGIN = "github-actions";@@ -33,10 +38,20 @@ export interface GitHubClient {createComment(params: IssueRef & { body: string }): Promise<unknown>;addLabels(params: IssueRef & { labels: string[] }): Promise<unknown>;removeLabel(params: IssueRef & { name: string }): Promise<unknown>;+ listComments(+ params: IssueRef & { per_page: number; page: number },+ ): Promise<{ data: { id: number; body?: string; user: { login: string; type: string } | null }[] }>;+ updateComment(params: Repo & { comment_id: number; body: string }): Promise<unknown>;+ };+ repos: {+ getCollaboratorPermissionLevel(params: Repo & { username: string }): Promise<{ data: { permission: string } }>;};pulls: {get(params: Repo & { pull_number: number }): Promise<{ data: PullData }>;update(params: Repo & { pull_number: number; state: "closed" }): Promise<unknown>;+ listFiles(+ params: Repo & { pull_number: number; per_page: number; page: number },+ ): Promise<{ data: { filename: string; additions: number; deletions: number }[] }>;};};}@@ -53,6 +68,7 @@ interface Summary {/** The parts of github-script's `core` (@actions/core) these scripts call. */export interface Core {info(message: string): void;+ warning(message: string): void;error(message: string): void;setFailed(message: string): void;summary: Summary;@@ -61,6 +77,33 @@ export interface Core {export const isNotFound = (error: unknown) =>typeof error === "object" && error !== null && "status" in error && error.status === 404;+// "maintain" reports as write.+const PUSH_PERMISSIONS = ["admin", "write"];++/** Whether a login can push to the repository. */+export type CanPush = (login: string) => Promise<boolean>;++/**+ * Asks GitHub once per login whether it can push. This, not author_association, marks the+ * team: org membership can be private, and github.token then sees a member as a CONTRIBUTOR.+ */+export function pushAccessChecker(github: GitHubClient, repo: Repo): CanPush {+ const answers = new Map<string, Promise<boolean>>();+ return (login) => {+ const known = answers.get(login);+ if (known) return known;+ const answer = github.rest.repos.getCollaboratorPermissionLevel({ ...repo, username: login }).then(+ ({ data }) => PUSH_PERMISSIONS.includes(data.permission),+ (error: unknown) => {+ if (isNotFound(error)) return false;+ throw error;+ },+ );+ answers.set(login, answer);+ return answer;+ };+}+/** Removes a label, treating one that is already gone as removed. */export async function removeLabel(github: GitHubClient, issue: IssueRef, name: string) {await github.rest.issues.removeLabel({ ...issue, name }).catch((error: unknown) => {diff --git a/.github/scripts/pr-size.test.ts b/.github/scripts/pr-size.test.tsnew file mode 100644index 0000000000..f361387e20--- /dev/null+++ b/.github/scripts/pr-size.test.ts@@ -0,0 +1,227 @@+import assert from "node:assert/strict";+import { describe, it } from "node:test";++import type { GitHubClient } from "./github.ts";+import {+ approval,+ authorExemption,+ type ChangedFile,+ checkPullRequestSize,+ countedLines,+ liftedComment,+ MAX_LINES,+ oversizedComment,+ type SizedPullRequest,+} from "./pr-size.ts";++const repo = { owner: "o", repo: "r" };++function pullRequest(overrides: Partial<SizedPullRequest> = {}): SizedPullRequest {+ return {+ number: 7,+ state: "open",+ additions: 10,+ deletions: 5,+ user: { login: "contributor", type: "User" },+ labels: [],+ ...overrides,+ };+}++const file = (filename: string, additions: number, deletions = 0): ChangedFile => ({ filename, additions, deletions });+const oversized = (additions: number, labels: { name: string }[] = []) => pullRequest({ additions, deletions: 0, labels });+const codeFiles = (lines: number) => [file("app/core/A.java", lines)];++interface Comment {+ id: number;+ body?: string;+ user: { login: string; type: string } | null;+}++const BOT = { login: "github-actions[bot]", type: "Bot" };++function fakeGitHub(files: ChangedFile[], comments: Comment[], writers: string[]) {+ const calls: string[] = [];+ const pages: number[] = [];+ const lookups: string[] = [];+ const github: GitHubClient = {+ graphql: async () => assert.fail("no graphql"),+ rest: {+ repos: {+ getCollaboratorPermissionLevel: async ({ username }) => {+ lookups.push(username);+ return { data: { permission: writers.includes(username) ? "write" : "read" } };+ },+ },+ issues: {+ createComment: async ({ body }) => {+ calls.push("comment");+ comments.push({ id: comments.length + 1, body, user: BOT });+ },+ addLabels: async ({ labels }) => calls.push(`label ${labels.join(",")}`),+ removeLabel: async ({ name }) => calls.push(`unlabel ${name}`),+ listComments: async ({ page, per_page }) => {+ calls.push("list comments");+ return { data: comments.slice((page - 1) * per_page, page * per_page) };+ },+ updateComment: async ({ comment_id, body }) => {+ calls.push(`edit ${comment_id}`);+ const comment = comments.find((candidate) => candidate.id === comment_id);+ assert.ok(comment);+ comment.body = body;+ },+ },+ pulls: {+ get: async () => assert.fail("no reads"),+ update: async () => assert.fail("no closes"),+ listFiles: async ({ page, per_page }) => {+ pages.push(page);+ return { data: files.slice((page - 1) * per_page, page * per_page) };+ },+ },+ },+ };+ return { github, calls, pages, lookups };+}++async function check(+ pr: SizedPullRequest,+ files: ChangedFile[] = [],+ { comments = [] as Comment[], live = true, writers = [] as string[] } = {},+) {+ const { github, calls, pages, lookups } = fakeGitHub(files, comments, writers);+ const failures: string[] = [];+ const warnings: string[] = [];+ const core = {+ info: () => {},+ warning: (message: string) => warnings.push(message),+ setFailed: (message: string) => failures.push(message),+ };+ await checkPullRequestSize({ github, context: { repo, payload: { pull_request: pr } }, core, live });+ return { failures, warnings, calls, pages, comments, lookups };+}++const TOO_LARGE = [{ name: "too-large" }];++describe("counted lines", () => {+ it("counts additions and deletions", () => {+ assert.equal(countedLines([file("app/core/A.java", 30, 20), file("frontend/editor/src/b.ts", 5)]), 55);+ });++ it("leaves out translations and lockfiles", () => {+ const files = [+ file("frontend/editor/public/locales/fr-FR/translation.toml", 900),+ file("app/core/src/main/resources/messages_fr_FR.properties", 900),+ file("frontend/package-lock.json", 900),+ file("engine/uv.lock", 900),+ file("app/core/gradle.lockfile", 900),+ file("app/core/A.java", 1),+ ];+ assert.equal(countedLines(files), 1);+ });+});++describe("exemptions", () => {+ const canPush = (writers: string[]) => async (login: string) => writers.includes(login);++ it("never limits anyone who can push, or bots", async () => {+ assert.notEqual(await authorExemption(pullRequest(), canPush(["contributor"])), null);+ assert.notEqual(await authorExemption(pullRequest({ user: { login: "dependabot[bot]", type: "Bot" } }), canPush([])), null);+ });++ it("lifts the limit for approved PRs", () => {+ assert.notEqual(approval(pullRequest({ labels: [{ name: "large-pr-approved" }] })), null);+ });++ it("holds everyone else to the limit", async () => {+ const pr = pullRequest({ labels: [{ name: "bug" }] });+ assert.deepEqual([await authorExemption(pr, canPush(["someone-else"])), approval(pr)], [null, null]);+ });+});++describe("check PR size", () => {+ it("passes a PR within the limit without listing its files", async () => {+ const { failures, pages } = await check(pullRequest({ additions: MAX_LINES, deletions: 0 }));+ assert.deepEqual([failures, pages], [[], []]);+ });++ it("fails a PR over the limit, tells the author how to get past it and labels it", async () => {+ const files = [file("app/core/A.java", 600), file("app/core/B.java", 401)];+ const { failures, calls, comments } = await check(oversized(1001), files);+ assert.equal(failures.length, 1);+ assert.deepEqual(calls, ["list comments", "comment", "label too-large"]);+ assert.match(comments[0]?.body ?? "", /@contributor, this PR has been marked as too large because it changes 1001 lines/);+ assert.match(comments[0]?.body ?? "", /add a comment explaining why/);+ assert.match(comments[0]?.body ?? "", /closed automatically/);+ });++ it("comments once, and edits that comment when the size changes", async () => {+ const comments = [{ id: 1, body: oversizedComment("contributor", 1200), user: BOT }];+ assert.deepEqual((await check(oversized(1200, TOO_LARGE), codeFiles(1200), { comments })).calls, ["list comments"]);+ const { calls } = await check(oversized(1500, TOO_LARGE), codeFiles(1500), { comments });+ assert.deepEqual(calls, ["list comments", "edit 1"]);+ assert.match(comments[0]?.body ?? "", /changes 1500 lines/);+ });++ it("does not take someone else's copy of the comment for its own", async () => {+ const comments = [{ id: 1, body: oversizedComment("contributor", 1200), user: { login: "contributor", type: "User" } }];+ assert.deepEqual((await check(oversized(1200, TOO_LARGE), codeFiles(1200), { comments })).calls, ["list comments", "comment"]);+ });++ it("says when a warned PR is split down or approved, and unlabels it", async () => {+ const split = [{ id: 1, body: oversizedComment("contributor", 1200), user: BOT }];+ const { calls } = await check(oversized(1200, TOO_LARGE), codeFiles(900), { comments: split });+ assert.deepEqual(calls, ["list comments", "edit 1", "unlabel too-large"]);+ assert.equal(split[0]?.body, liftedComment("it now changes 900 lines"));++ const approved = [{ id: 1, body: oversizedComment("contributor", 1200), user: BOT }];+ const labels = [...TOO_LARGE, { name: "large-pr-approved" }];+ const { failures } = await check(oversized(1200, labels), codeFiles(1200), { comments: approved });+ assert.deepEqual(failures, []);+ assert.match(approved[0]?.body ?? "", /no longer marked as too large, because it is labelled `large-pr-approved`/);+ });++ it("leaves a PR it never warned alone", async () => {+ const { calls } = await check(oversized(1200, [{ name: "large-pr-approved" }]), codeFiles(1200));+ assert.deepEqual(calls, []);+ });++ it("only warns until live: no failure, comment or label", async () => {+ const { failures, warnings, calls } = await check(oversized(1200), codeFiles(1200), { live: false });+ assert.deepEqual([failures, calls], [[], []]);+ assert.match(warnings[0] ?? "", /Not enforced yet: .*changes 1200 lines/);+ });++ it("passes a PR over the limit only because of translations", async () => {+ const files = [file("frontend/editor/public/locales/de-DE/translation.toml", 5000), file("app/core/A.java", 40)];+ assert.deepEqual((await check(oversized(5040), files)).failures, []);+ });++ it("reads every page of files", async () => {+ const files = Array.from({ length: 250 }, (_, index) => file(`app/core/F${index}.java`, 5));+ const { failures, pages } = await check(oversized(1250), files);+ assert.deepEqual(pages, [1, 2, 3]);+ assert.match(failures[0] ?? "", /changes 1250 lines/);+ });++ it("takes too-large off a PR whose author can push", async () => {+ const { calls } = await check(pullRequest({ additions: 50000, labels: TOO_LARGE }), [], { writers: ["contributor"] });+ assert.deepEqual(calls, ["list comments", "unlabel too-large"]);+ });++ it("leaves anyone who can push, bots and closed PRs alone", async () => {+ for (const [pr, writers] of [+ [pullRequest({ additions: 50000 }), ["contributor"]],+ [pullRequest({ additions: 50000, user: { login: "dependabot[bot]", type: "Bot" } }), []],+ [pullRequest({ additions: 50000, state: "closed" }), []],+ ] as const) {+ const { failures, calls, pages } = await check(pr, codeFiles(50000), { writers: [...writers] });+ assert.deepEqual([failures, calls, pages], [[], [], []]);+ }+ });++ it("asks GitHub who can push only for a PR over the limit", async () => {+ assert.deepEqual((await check(pullRequest())).lookups, []);+ assert.deepEqual((await check(oversized(1200), codeFiles(1200))).lookups, ["contributor"]);+ });+});diff --git a/.github/scripts/pr-size.ts b/.github/scripts/pr-size.tsnew file mode 100644index 0000000000..12953a31ae--- /dev/null+++ b/.github/scripts/pr-size.ts@@ -0,0 +1,180 @@+// Holds a PR from someone outside the team to MAX_LINES. pr-size-limit.yml runs it as+// the PR changes, and the daily triage runs it on every open PR, then closes one that+// has been too-large for CLOSE_AFTER_WARNING_DAYS. An oversized PR fails the check, is+// labelled too-large and gets one comment saying why, kept up to date as the PR changes;+// the label's age is the warning's. Anyone who can push, bots and PRs labelled+// large-pr-approved are exempt. This file owns too-large and no other label.++import {+ CLOSE_AFTER_WARNING_DAYS,+ type CanPush,+ type Core,+ type GitHubClient,+ type IssueRef,+ LABELS,+ pushAccessChecker,+ type Repo,+ removeLabel,+} from "./github.ts";++export const MAX_LINES = 1000;++// Translations arrive from the community in bulk, and lockfiles are generated.+const UNCOUNTED = [/\/locales\//, /(^|\/)messages_[\w-]+\.properties$/, /(^|\/)package-lock\.json$/, /\.lock$/, /\.lockfile$/];++const PER_PAGE = 100;++// Identifies the check's own comment, so each PR gets one that is edited, not a new one per push.+const COMMENT_MARKER = "<!-- pr-size-limit -->";++export interface ChangedFile {+ filename: string;+ additions: number;+ deletions: number;+}++/** The parts of a github-script `context.payload.pull_request` the check reads. */+export interface SizedPullRequest {+ number: number;+ state: string;+ additions: number;+ deletions: number;+ user: { login: string; type: string };+ labels: { name: string }[];+}++/** The outcome for one PR. `held` is whether it should carry too-large. */+export interface SizeVerdict {+ held: boolean;+ summary: string;+}++/** Lines added plus lines removed, leaving out translations and lockfiles. */+export function countedLines(files: ChangedFile[]) {+ return files+ .filter((file) => !UNCOUNTED.some((pattern) => pattern.test(file.filename)))+ .reduce((total, file) => total + file.additions + file.deletions, 0);+}++/** Why the limit never applies to this author, or null. */+export async function authorExemption(pr: SizedPullRequest, canPush: CanPush): Promise<string | null> {+ if (pr.user.type === "Bot") return `${pr.user.login} is a bot`;+ return (await canPush(pr.user.login)) ? `${pr.user.login} is on the team` : null;+}++/** Why a maintainer has lifted the limit for this PR, or null. */+export function approval(pr: SizedPullRequest): string | null {+ return pr.labels.some((label) => label.name === LABELS.largePrApproved) ? `it is labelled \`${LABELS.largePrApproved}\`` : null;+}++export function oversizedComment(login: string, lines: number) {+ return [+ COMMENT_MARKER,+ `Hi @${login}, this PR has been marked as too large because it changes ${lines} lines, not counting translations and lockfiles. To keep reviews manageable, PRs from contributors outside the team are limited to ${MAX_LINES} lines.`,+ "",+ "Please split it into smaller PRs that can each be reviewed on their own. If you think it can't be split, just add a comment explaining why so a maintainer can take a look.",+ "",+ `If this is still outstanding in ${CLOSE_AFTER_WARNING_DAYS} days, the PR will be closed automatically.`,+ ].join("\n");+}++const LIFTED = `${COMMENT_MARKER}\nThis PR is no longer marked as too large`;++export const liftedComment = (reason: string) => `${LIFTED}, because ${reason}.`;++async function allPages<T>(fetchPage: (page: number) => Promise<{ data: T[] }>) {+ const items: T[] = [];+ for (let page = 1; ; page += 1) {+ const { data } = await fetchPage(page);+ items.push(...data);+ if (data.length < PER_PAGE) return items;+ }+}++async function findOwnComment(github: GitHubClient, issue: IssueRef) {+ const comments = await allPages((page) => github.rest.issues.listComments({ ...issue, per_page: PER_PAGE, page }));+ return comments.find((comment) => comment.user?.type === "Bot" && comment.body?.startsWith(COMMENT_MARKER)) ?? null;+}++async function countLines(github: GitHubClient, repo: Repo, pr: SizedPullRequest) {+ const total = pr.additions + pr.deletions;+ // Counting only leaves lines out, so a PR within the limit in total needs no file list.+ if (total <= MAX_LINES) return total;+ // The files endpoint stops at 3000 files, far past the limit anyway.+ return countedLines(await allPages((page) => github.rest.pulls.listFiles({ ...repo, pull_number: pr.number, per_page: PER_PAGE, page })));+}++async function warn(github: GitHubClient, issue: IssueRef, pr: SizedPullRequest, lines: number, labelled: boolean) {+ const body = oversizedComment(pr.user.login, lines);+ const existing = await findOwnComment(github, issue);+ if (existing === null) await github.rest.issues.createComment({ ...issue, body });+ else if (existing.body !== body) await github.rest.issues.updateComment({ owner: issue.owner, repo: issue.repo, comment_id: existing.id, body });+ if (!labelled) await github.rest.issues.addLabels({ ...issue, labels: [LABELS.tooLarge] });+}++async function lift(github: GitHubClient, issue: IssueRef, reason: string) {+ const existing = await findOwnComment(github, issue);+ if (existing !== null && !existing.body?.startsWith(LIFTED)) {+ await github.rest.issues.updateComment({ owner: issue.owner, repo: issue.repo, comment_id: existing.id, body: liftedComment(reason) });+ }+ await removeLabel(github, issue, LABELS.tooLarge);+}++/**+ * Checks one open PR against the limit, and when `live`, warns or lifts the warning to+ * match: comments, and adds or removes too-large. Changes nothing unless `live`.+ */+export async function enforceSizeLimit(+ github: GitHubClient,+ repo: Repo,+ pr: SizedPullRequest,+ live: boolean,+ canPush: CanPush,+): Promise<SizeVerdict> {+ const issue = { ...repo, issue_number: pr.number };+ const labelled = pr.labels.some((label) => label.name === LABELS.tooLarge);+ const total = pr.additions + pr.deletions;+ if (!labelled && total <= MAX_LINES) return { held: false, summary: `Within the size limit: it changes ${total} lines.` };++ // Only a PR that was told it is too large hears that it no longer is.+ const release = async (reason: string): Promise<SizeVerdict> => {+ if (live && labelled) await lift(github, issue, reason);+ return { held: false, summary: `Within the size limit: ${reason}.` };+ };+ const exempt = (await authorExemption(pr, canPush)) ?? approval(pr);+ if (exempt !== null) return release(exempt);+ const lines = await countLines(github, repo, pr);+ if (lines <= MAX_LINES) return release(`it now changes ${lines} lines`);++ if (live) await warn(github, issue, pr, lines, labelled);+ return {+ held: true,+ summary: `This PR changes ${lines} lines, not counting translations and lockfiles, over the ${MAX_LINES}-line limit for contributors outside the team. Please split it into smaller PRs, or add a comment explaining why it can't be split.`,+ };+}++/**+ * pr-size-limit.yml's entry point: fails the check while the PR is over the limit. Until+ * `live`, it only warns, so the check can run before the limit is enforced.+ */+export async function checkPullRequestSize({+ github,+ context,+ core,+ live,+}: {+ github: GitHubClient;+ context: { repo: Repo; payload: { pull_request: SizedPullRequest } };+ core: Pick<Core, "info" | "warning" | "setFailed">;+ live: boolean;+}) {+ const pr = context.payload.pull_request;+ if (pr.state !== "open") {+ core.info("The PR is closed.");+ return;+ }+ const verdict = await enforceSizeLimit(github, context.repo, pr, live, pushAccessChecker(github, context.repo));+ if (!verdict.held) core.info(verdict.summary);+ else if (live) core.setFailed(verdict.summary);+ else core.warning(`Not enforced yet: ${verdict.summary}`);+}diff --git a/.github/scripts/pr-turn.test.ts b/.github/scripts/pr-turn.test.tsindex 4ecc7d4fdb..47c2241771 100644--- a/.github/scripts/pr-turn.test.ts+++ b/.github/scripts/pr-turn.test.ts@@ -44,6 +44,9 @@ function fakeGitHub(items: TurnItem[] = [], { labelled = false, alreadyRemoved =return { repository: { pullRequest: { timelineItems } } } as T;},rest: {+ repos: {+ getCollaboratorPermissionLevel: async () => assert.fail("no permission lookups"),+ },issues: {createComment: async () => assert.fail("no comments"),addLabels: async ({ issue_number, labels }) => calls.push(`label #${issue_number} ${labels.join(",")}`),@@ -51,6 +54,8 @@ function fakeGitHub(items: TurnItem[] = [], { labelled = false, alreadyRemoved =if (alreadyRemoved) throw Object.assign(new Error("Label does not exist"), { status: 404 });return calls.push(`unlabel #${issue_number} ${name}`);},+ listComments: async () => assert.fail("no comment reads"),+ updateComment: async () => assert.fail("no comment edits"),},pulls: {get: async () => {@@ -59,6 +64,7 @@ function fakeGitHub(items: TurnItem[] = [], { labelled = false, alreadyRemoved =return { data: { mergeable: null, mergeable_state: "unknown", labels, head: { ref: BRANCH, repo: { full_name: FORK } } } };},update: async () => assert.fail("no closes"),+ listFiles: async () => assert.fail("no file lists"),},},};diff --git a/.github/scripts/stale-prs.test.ts b/.github/scripts/stale-prs.test.tsindex 8dcf9c41a1..f29eed76d6 100644--- a/.github/scripts/stale-prs.test.ts+++ b/.github/scripts/stale-prs.test.ts@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import { describe, it } from "node:test";import { BOT_LOGIN, type Core, type GitHubClient, LABELS } from "./github.ts";+import { type ChangedFile, oversizedComment } from "./pr-size.ts";import type { ReviewNode, TimelineItem } from "./pr-turn.ts";import triageStalePullRequests, {type Actor,@@ -26,6 +27,7 @@ interface PullRequestOptions {isDraft?: boolean;activeDaysAgo?: number;authorType?: string;+ additions?: number;}function pullRequest({@@ -33,16 +35,20 @@ function pullRequest({isDraft = false,activeDaysAgo = 0,authorType = "User",+ additions = 10,}: PullRequestOptions = {}): PullRequest {return {number,url: `https://github.com/o/r/pull/${number}`,isDraft,baseRefName: "main",+ additions,+ deletions: 0,author: { login: "contributor", __typename: authorType },labels: [],timeline: [],lastActivityAt: daysAgo(activeDaysAgo),+ comments: [],};}@@ -58,6 +64,11 @@ function unlabel(pr: PullRequest, name: string, daysAgoRemoved: number, actor =return pr;}+function commented(pr: PullRequest, author: string, daysAgoPosted: number, fromTeam = false) {+ pr.comments.push({ createdAt: daysAgo(daysAgoPosted), author, fromTeam });+ return pr;+}+function happened(pr: PullRequest, typename: "ReopenedEvent" | "ReadyForReviewEvent" | "ConvertToDraftEvent", daysAgoHappened: number) {pr.timeline.push({ __typename: typename, createdAt: daysAgo(daysAgoHappened), actor: PERSON });return pr;@@ -182,6 +193,48 @@ describe("ready PRs after the warning", () => {});});+describe("too-large PRs", () => {+ const tooLarge = (daysAgoAdded: number, options: PullRequestOptions = {}) => label(pullRequest(options), LABELS.tooLarge, daysAgoAdded);++ it("are pending until a week after the size warning, then close", () => {+ assert.deepEqual(decision(tooLarge(3)), { action: "pending", reasons: ["tooLarge"] });+ assert.deepEqual(decision(tooLarge(7)), { action: "close", reasons: ["tooLarge"] });+ assert.deepEqual(decision(tooLarge(7, { isDraft: true, activeDaysAgo: 1 })), { action: "close", reasons: ["tooLarge"] });+ });++ it("still get the stale warnings while pending", () => {+ assert.deepEqual(decision(label(conflicted(10), LABELS.tooLarge, 2)), { action: "warn", reasons: ["conflicts"] });+ });++ it("are never closed on hold", () => {+ assert.equal(actionFor(label(tooLarge(30), LABELS.onHold, 1)), "none");+ });++ it("finish a size close that stopped partway", () => {+ assert.deepEqual(decision(label(tooLarge(8), LABELS.backlogCleanup, 1)), { action: "resume", reasons: [] });+ });++ it("get a fresh week when reopened after the size close", () => {+ const pr = label(tooLarge(10), LABELS.backlogCleanup, 3);+ assert.equal(actionFor(happened(pr, "ReopenedEvent", 2)), "pending");+ });++ it("are not closed while the author's explanation waits for the team", () => {+ assert.deepEqual(decision(commented(tooLarge(10), "contributor", 9)), { action: "pending", reasons: ["tooLarge"] });+ assert.equal(actionFor(commented(commented(tooLarge(20), "contributor", 15), "passer-by", 9)), "pending");+ });++ it("restart the week from the team's reply", () => {+ const replied = (daysAgoReplied: number) => commented(commented(tooLarge(20), "contributor", 15), "maintainer", daysAgoReplied, true);+ assert.equal(actionFor(replied(3)), "pending");+ assert.equal(actionFor(replied(8)), "close");+ });++ it("ignore what the author said before the warning", () => {+ assert.equal(actionFor(commented(tooLarge(10), "contributor", 11)), "close");+ });+});+describe("drafts", () => {const draft = (activeDaysAgo: number) => pullRequest({ isDraft: true, activeDaysAgo });@@ -263,7 +316,11 @@ describe("latest activity", () => {commits: { nodes: [{ commit: { committedDate: daysAgo(committedDaysAgo) } }] },activity: { nodes: activity },});- const commentBy = (author: Actor, ago: number) => ({ __typename: "IssueComment" as const, createdAt: daysAgo(ago), author });+ const commentBy = (author: Actor, ago: number) => ({+ __typename: "IssueComment" as const,+ createdAt: daysAgo(ago),+ author,+ });it("counts people, not bots", () => {assert.equal(latestActivity(node([commentBy(PERSON, 40), commentBy(BOT, 1)]), []), daysAgo(40));@@ -297,10 +354,18 @@ function toNode(pr: PullRequest, pageSize: number, before: string | null): PullRisDraft: pr.isDraft,createdAt: pr.lastActivityAt,baseRefName: pr.baseRefName,+ additions: pr.additions,+ deletions: pr.deletions,author: pr.author,labels: { nodes: pr.labels.map((name) => ({ name })) },commits: { nodes: [] },- activity: { nodes: [] },+ activity: {+ nodes: pr.comments.map((comment) => ({+ __typename: "IssueComment" as const,+ createdAt: comment.createdAt,+ author: { login: comment.author, __typename: "User" },+ })),+ },timelineItems: {pageInfo: { hasPreviousPage: start > 0, startCursor: String(start) },nodes: pr.timeline.slice(start, end) satisfies TimelineEvent[],@@ -323,6 +388,12 @@ interface FakeOptions {alreadyRemoved?: string[];/** The history pr-turn.ts reads to re-check waiting-on-author. */turnItems?: TurnItem[];+ /** What pulls.listFiles returns, for a PR over the size limit in total. */+ files?: ChangedFile[];+ /** What issues.listComments returns. */+ comments?: { id: number; body: string; user: { login: string; type: string } }[];+ /** Logins that can push to the repository. */+ writers?: string[];}function fakeGitHub(@@ -335,6 +406,9 @@ function fakeGitHub(failWrite,alreadyRemoved = [],turnItems = STILL_WAITING,+ files = [],+ comments = [],+ writers = [],}: FakeOptions = {},) {const calls: string[] = [];@@ -367,6 +441,9 @@ function fakeGitHub(const github: GitHubClient = {graphql: async <T>(query: string, variables: Record<string, unknown>) => (await graphql(query, variables)) as T,rest: {+ repos: {+ getCollaboratorPermissionLevel: async ({ username }) => ({ data: { permission: writers.includes(username) ? "write" : "read" } }),+ },issues: {createComment: async ({ issue_number }) => write(`comment #${issue_number}`),addLabels: async ({ issue_number, labels }) => write(`label #${issue_number} ${labels.join(",")}`),@@ -374,6 +451,8 @@ function fakeGitHub(if (alreadyRemoved.includes(name)) throw Object.assign(new Error("Label does not exist"), { status: 404 });write(`unlabel #${issue_number} ${name}`);},+ listComments: async () => ({ data: comments }),+ updateComment: async ({ comment_id }) => write(`edit comment ${comment_id}`),},pulls: {get: async () => {@@ -381,6 +460,7 @@ function fakeGitHub(return { data: { mergeable, mergeable_state: mergeableState, labels: [], head: { ref: "feature", repo: null } } };},update: async ({ pull_number }) => write(`close #${pull_number}`),+ listFiles: async ({ page }) => ({ data: page === 1 ? files : [] }),},},};@@ -404,17 +484,24 @@ function recordingCore() {return summary;},};- const core: Core = { info: () => {}, error: (message) => errors.push(message), setFailed: (message) => failed.push(message), summary };+ const core: Core = {+ info: () => {},+ warning: () => {},+ error: (message) => errors.push(message),+ setFailed: (message) => failed.push(message),+ summary,+ };return { core, errors, failed, tables, summaries: () => summaries };}-async function triage(github: GitHubClient, { live = true, writeIntervalMs = 0 } = {}) {+async function triage(github: GitHubClient, { live = true, sizeLive = true, writeIntervalMs = 0 } = {}) {const recorded = recordingCore();await triageStalePullRequests({github,context: { repo: { owner: "o", repo: "r" } },core: recorded.core,live,+ sizeLive,writeIntervalMs,mergeabilityRetryMs: 0,});@@ -523,6 +610,72 @@ describe("triage run", () => {assert.equal(summaries(), 1);});+ describe("size limit", () => {+ const javaFile = (lines: number): ChangedFile[] => [{ filename: "app/core/A.java", additions: lines, deletions: 0 }];++ it("warns a PR over the limit, then holds it pending", async () => {+ const { github, calls } = fakeGitHub([pullRequest({ additions: 1500 })], { files: javaFile(1500) });+ const { tables } = await triage(github);+ assert.deepEqual(calls, ["comment #1", "label #1 too-large"]);+ assert.deepEqual(tables[0]?.[1]?.slice(2), ["pending", "tooLarge"]);+ });++ it("closes a PR still over the limit a week after the warning", async () => {+ const pr = label(pullRequest({ additions: 1500 }), LABELS.tooLarge, 30);+ const comments = [{ id: 9, body: oversizedComment("contributor", 1500), user: { login: "github-actions[bot]", type: "Bot" } }];+ const { github, calls } = fakeGitHub([pr], { files: javaFile(1500), comments });+ await triage(github);+ assert.deepEqual(calls, ["comment #1", "label #1 backlog-cleanup", "close #1"]);+ });++ it("does not close a PR whose author explained why it can't be split", async () => {+ const pr = commented(label(pullRequest({ additions: 1500 }), LABELS.tooLarge, 30), "contributor", 20);+ const comments = [{ id: 9, body: oversizedComment("contributor", 1500), user: { login: "github-actions[bot]", type: "Bot" } }];+ const { github, calls } = fakeGitHub([pr], { files: javaFile(1500), comments });+ await triage(github);+ assert.deepEqual(calls, []);+ });++ it("restarts the week from a reply by someone who can push", async () => {+ const pr = () => commented(commented(label(pullRequest({ additions: 1500 }), LABELS.tooLarge, 30), "contributor", 20), "maintainer", 10);+ const comments = [{ id: 9, body: oversizedComment("contributor", 1500), user: { login: "github-actions[bot]", type: "Bot" } }];+ const replied = fakeGitHub([pr()], { files: javaFile(1500), comments, writers: ["maintainer"] });+ await triage(replied.github);+ assert.deepEqual(replied.calls, ["comment #1", "label #1 backlog-cleanup", "close #1"]);++ const passerBy = fakeGitHub([pr()], { files: javaFile(1500), comments });+ await triage(passerBy.github);+ assert.deepEqual(passerBy.calls, []);+ });++ it("lifts the warning once the PR is split down", async () => {+ const pr = label(pullRequest({ additions: 500 }), LABELS.tooLarge, 3);+ const comments = [{ id: 9, body: oversizedComment("contributor", 1500), user: { login: "github-actions[bot]", type: "Bot" } }];+ const { github, calls } = fakeGitHub([pr], { comments });+ await triage(github);+ assert.deepEqual(calls, ["edit comment 9", "unlabel #1 too-large"]);+ });++ it("only reports it until the size limit is live, whatever the stale switch says", async () => {+ const { github, calls } = fakeGitHub([pullRequest({ additions: 1500 })], { files: javaFile(1500) });+ const { tables } = await triage(github, { sizeLive: false });+ assert.deepEqual(calls, []);+ assert.deepEqual(tables[0]?.[1]?.slice(2), ["pending", "tooLarge"]);+ });++ it("closes for size on the size limit's switch alone", async () => {+ const overdue = () => label(pullRequest({ additions: 1500 }), LABELS.tooLarge, 30);+ const comments = [{ id: 9, body: oversizedComment("contributor", 1500), user: { login: "github-actions[bot]", type: "Bot" } }];+ const sizeOnly = fakeGitHub([overdue()], { files: javaFile(1500), comments });+ await triage(sizeOnly.github, { live: false });+ assert.deepEqual(sizeOnly.calls, ["comment #1", "label #1 backlog-cleanup", "close #1"]);++ const staleOnly = fakeGitHub([overdue()], { files: javaFile(1500), comments });+ await triage(staleOnly.github, { sizeLive: false });+ assert.deepEqual(staleOnly.calls, []);+ });+ });+it("marks a write that failed in the summary", async () => {const { github } = fakeGitHub([overdue()], { failWrite: "close" });const { tables, failed } = await triage(github);diff --git a/.github/scripts/stale-prs.ts b/.github/scripts/stale-prs.tsindex 2beee9ed77..5ff87cd0dd 100644--- a/.github/scripts/stale-prs.ts+++ b/.github/scripts/stale-prs.ts@@ -2,19 +2,23 @@import {BOT_LOGIN,+ type CanPush,+ CLOSE_AFTER_WARNING_DAYS,type Core,type GitHubClient,type IssueRef,LABELS,type PullData,+ pushAccessChecker,type Repo,removeLabel,} from "./github.ts";+import { enforceSizeLimit, MAX_LINES, type SizedPullRequest } from "./pr-size.ts";import { clearStaleTurnLabel } from "./pr-turn.ts";const DAY_MS = 24 * 60 * 60 * 1000;-export type Reason = "conflicts" | "waitingOnAuthor" | "idleDraft";+export type Reason = "conflicts" | "waitingOnAuthor" | "idleDraft" | "tooLarge";const TURN_LABELS: { label: string; reason: Reason }[] = [{ label: LABELS.conflicts, reason: "conflicts" },@@ -23,7 +27,6 @@ const TURN_LABELS: { label: string; reason: Reason }[] = [export const TURN_DAYS = 7;export const IDLE_DRAFT_DAYS = 30;-export const CLOSE_AFTER_WARNING_DAYS = 7;// GitHub asks for at least a second between writes to stay under its secondary rate limit.const WRITE_INTERVAL_MS = 1000;@@ -74,6 +77,8 @@ const PULL_REQUEST_QUERY = `isDraftcreatedAtbaseRefName+ additions+ deletionsauthor { login __typename }labels(first: 100) { nodes { name } }commits(last: 1) { nodes { commit { committedDate } } }@@ -128,6 +133,8 @@ export interface PullRequestNode {isDraft: boolean;createdAt: string;baseRefName: string;+ additions: number;+ deletions: number;author: Actor | null;labels: { nodes: { name: string }[] };commits: { nodes: { commit: { committedDate: string } }[] };@@ -141,11 +148,22 @@ export interface PullRequest {url: string;isDraft: boolean;baseRefName: string;+ additions: number;+ deletions: number;author: Actor | null;labels: string[];timeline: TimelineEvent[];/** When a person last did anything on it; see latestActivity. */lastActivityAt: string;+ /** The newest comments and reviews by people, oldest first. */+ comments: Comment[];+}++export interface Comment {+ createdAt: string;+ author: string;+ /** Whether the author can push; only looked up on a too-large PR, false elsewhere. */+ fromTeam: boolean;}export type Action = "none" | "warn" | "pending" | "close" | "resume" | "clear";@@ -213,6 +231,25 @@ function lastWarningEndedAt(pr: PullRequest) {return endedAt;}+// The size close runs from the warning or a reopen. The author explaining why the PR+// can't be split pauses it, and a reply from the team after that restarts it. Null+// while paused.+function sizeClockStart(pr: PullRequest, warnedAt: number) {+ let since = Math.max(warnedAt, latestEvent(pr, reopened) ?? 0);+ let paused = false;+ for (const comment of pr.comments) {+ const at = time(comment.createdAt);+ if (at <= since) continue;+ if (comment.author === pr.author?.login) {+ paused = true;+ } else if (paused && comment.fromTeam) {+ paused = false;+ since = at;+ }+ }+ return paused ? null : since;+}+// A close labels the PR backlog-cleanup before closing it, so one still open with that// label added since the warning, and not reopened since, stopped partway.function closeInterrupted(pr: PullRequest, warnedAt: number) {@@ -269,17 +306,27 @@ function decideDraft(pr: PullRequest, now: number, warnedAt: number | null): Dec* - "resume": a close stopped after its comment; close the PR without commenting again.* - "clear": warned, but something has changed since; remove the label.*- * Conflicts still need confirming with GitHub before acting; see confirmConflicts.+ * A too-large PR was warned when the label went on, by pr-size.ts's comment, so it is+ * "pending" until CLOSE_AFTER_WARNING_DAYS later and then "close"; see sizeClockStart+ * for what pauses and restarts that. Conflicts still need confirming with GitHub before+ * acting; see confirmConflicts.*/export function decide(pr: PullRequest, now: number): Decision {const stale = hasLabel(pr, LABELS.stale);if (pr.author?.__typename === "Bot" || hasLabel(pr, LABELS.onHold)) return stale ? CLEAR : NONE;const warnedAt = warningTime(pr);- if (warnedAt !== null && closeInterrupted(pr, warnedAt)) return { action: "resume", reasons: [] };+ const sizeWarnedAt = hasLabel(pr, LABELS.tooLarge) ? (latestEvent(pr, labelled(LABELS.tooLarge)) ?? now) : null;+ const warnings = [warnedAt, sizeWarnedAt].filter((at) => at !== null);+ if (warnings.length > 0 && closeInterrupted(pr, Math.min(...warnings))) return { action: "resume", reasons: [] };+ const sizeSince = sizeWarnedAt === null ? null : sizeClockStart(pr, sizeWarnedAt);+ const size: Decision | null =+ sizeWarnedAt === null ? null : sizeSince === null ? { action: "pending", reasons: ["tooLarge"] } : closeOrPending(now, sizeSince, ["tooLarge"]);+ if (size?.action === "close") return size;const decision = pr.isDraft ? decideDraft(pr, now, warnedAt) : decideReady(pr, now, warnedAt);// A Stale PR label someone else added warned nobody: replace it with a warning when one// is due, and drop it otherwise.- return stale && warnedAt === null && decision.action === "none" ? CLEAR : decision;+ const settled = stale && warnedAt === null && decision.action === "none" ? CLEAR : decision;+ return settled.action === "none" && size !== null ? size : settled;}function problem(reason: Reason, pr: PullRequest, now: number): string {@@ -290,6 +337,8 @@ function problem(reason: Reason, pr: PullRequest, now: number): string {return "A maintainer is waiting on a response from you.";case "idleDraft":return `It has been a draft with no activity for ${days(now - time(pr.lastActivityAt))} days.`;+ case "tooLarge":+ return `It changes more than ${MAX_LINES} lines, the limit for contributors outside the team.`;}}@@ -301,11 +350,22 @@ function remedy(reason: Reason, pr: PullRequest): string {return "Please add a comment, a new push or re-request review.";case "idleDraft":return "Any activity keeps it open, such as a push, a comment or marking it ready for review.";+ case "tooLarge":+ return "Please split it into smaller PRs.";}}const authorLogin = (pr: PullRequest) => pr.author?.login ?? "ghost";+const sizedPullRequest = (pr: PullRequest): SizedPullRequest => ({+ number: pr.number,+ state: "open",+ additions: pr.additions,+ deletions: pr.deletions,+ user: { login: authorLogin(pr), type: pr.author?.__typename === "Bot" ? "Bot" : "User" },+ labels: pr.labels.map((name) => ({ name })),+});+export function warningComment(pr: PullRequest, reasons: Reason[], now: number) {return [`Hi @${authorLogin(pr)}, this PR has been marked as being stale because:`,@@ -327,6 +387,13 @@ export function closingComment(pr: PullRequest, reasons: Reason[], now: number)].join("\n");}+function commentOf(item: ActivityItem): Comment | null {+ if (item.__typename === "HeadRefForcePushedEvent" || item.author === null || !byPerson(item.author)) return null;+ const createdAt = item.__typename === "IssueComment" ? item.createdAt : item.submittedAt;+ if (createdAt === null) return null;+ return { createdAt, author: item.author.login, fromTeam: false };+}+function activityTime(item: ActivityItem) {switch (item.__typename) {case "IssueComment":@@ -395,10 +462,15 @@ async function fetchPullRequest(github: GitHubClient, repo: Repo, number: numberurl: node.url,isDraft: node.isDraft,baseRefName: node.baseRefName,+ additions: node.additions,+ deletions: node.deletions,author: node.author,labels: node.labels.nodes.map((label) => label.name),timeline,lastActivityAt: latestActivity(node, timeline),+ comments: node.activity.nodes+ .flatMap((item) => commentOf(item) ?? [])+ .sort((a, b) => time(a.createdAt) - time(b.createdAt)),};}@@ -431,15 +503,25 @@ async function confirmConflicts(return decision.action === "close" ? { action: "pending", reasons: decision.reasons } : NONE;}-// Applies a label removal to the PR as read, so the decision sees it even in a dry run.-function withoutLabel(pr: PullRequest, name: string, now: number): PullRequest {- const removed: TimelineEvent = {- __typename: "UnlabeledEvent",+// Only a too-large PR's clock depends on who replied, so only its commenters are looked up.+async function withTeamComments(pr: PullRequest, canPush: CanPush): Promise<PullRequest> {+ if (!hasLabel(pr, LABELS.tooLarge)) return pr;+ const comments = await Promise.all(+ pr.comments.map(async (comment) => ({ ...comment, fromTeam: comment.author !== pr.author?.login && (await canPush(comment.author)) })),+ );+ return { ...pr, comments };+}++// Applies a label change to the PR as read, so the decision sees it even in a dry run.+function withLabel(pr: PullRequest, name: string, present: boolean, now: number): PullRequest {+ const change: TimelineEvent = {+ __typename: present ? "LabeledEvent" : "UnlabeledEvent",createdAt: new Date(now).toISOString(),label: { name },actor: { login: BOT_LOGIN, __typename: "Bot" },};- return { ...pr, labels: pr.labels.filter((label) => label !== name), timeline: [...pr.timeline, removed] };+ const others = pr.labels.filter((label) => label !== name);+ return { ...pr, labels: present ? [...others, name] : others, timeline: [...pr.timeline, change] };}async function paced(intervalMs: number, writes: (() => Promise<unknown>)[]) {@@ -496,7 +578,8 @@ interface Result {failed: boolean;}-async function writeSummary(core: Core, results: Result[], live: boolean) {+async function writeSummary(core: Core, results: Result[], live: boolean, sizeLive: boolean) {+ const dryRuns = [...(live ? [] : ["stale warnings and closes"]), ...(sizeLive ? [] : ["the size limit"])];const rows = results.filter(({ decision }) => decision.action !== "none").sort((a, b) => ACTION_ORDER.indexOf(a.decision.action) - ACTION_ORDER.indexOf(b.decision.action))@@ -507,7 +590,7 @@ async function writeSummary(core: Core, results: Result[], live: boolean) {decision.reasons.join(", "),]);await core.summary- .addHeading(live ? "Stale PR triage" : "Stale PR triage (dry run: no PRs changed)")+ .addHeading(dryRuns.length === 0 ? "Stale PR triage" : `Stale PR triage (dry run for ${dryRuns.join(" and ")})`).addRaw(`${results.length} open PRs, ${rows.length} with something outstanding.`, true).addTable([[@@ -521,14 +604,23 @@ async function writeSummary(core: Core, results: Result[], live: boolean) {.write();}+// A size close belongs to the size limit and everything else to the stale triage; a+// resumed close could have been either's.+function writesLive(decision: Decision, live: boolean, sizeLive: boolean) {+ if (decision.action === "resume") return live || sizeLive;+ return decision.reasons.includes("tooLarge") ? sizeLive : live;+}+const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));export interface TriageInputs {github: GitHubClient;context: { repo: Repo };core: Core;- /** false reports what would happen without commenting, labelling or closing. */+ /** false reports what the stale triage would do without commenting, labelling or closing. */live: boolean;+ /** The same for the size limit, its too-large comments, labels and closes. */+ sizeLive: boolean;/** Least pause between writes. Defaults to WRITE_INTERVAL_MS. */writeIntervalMs?: number;/** Pause between mergeability checks. Defaults to MERGEABILITY_RETRY_MS. */@@ -536,21 +628,23 @@ export interface TriageInputs {}/**- * Triages every open PR and writes a job summary. A PR that cannot be read or updated- * is logged and skipped, and the job is failed at the end. Throws if the open PRs- * cannot be listed.+ * Triages every open PR, holding each to the size limit first, and writes a job summary.+ * A PR that cannot be read or updated is logged and skipped, and the job is failed at+ * the end. Throws if the open PRs cannot be listed.*/export default async function triageStalePullRequests({github,context,core,live,+ sizeLive,writeIntervalMs = WRITE_INTERVAL_MS,mergeabilityRetryMs = MERGEABILITY_RETRY_MS,}: TriageInputs) {const now = Date.now();const { repo } = context;const results: Result[] = [];+ const canPush = pushAccessChecker(github, repo);let failures = 0;for (const number of await fetchOpenPullNumbers(github, repo)) {@@ -561,13 +655,19 @@ export default async function triageStalePullRequests({if (pr === null) continue;if (!pr.isDraft && hasLabel(pr, LABELS.waitingOnAuthor) && (await clearStaleTurnLabel(github, issue, live))) {core.info(`#${number}: -${LABELS.waitingOnAuthor} (the turn had already moved on)`);- pr = withoutLabel(pr, LABELS.waitingOnAuthor, now);+ pr = withLabel(pr, LABELS.waitingOnAuthor, false, now);+ }+ const size = await enforceSizeLimit(github, repo, sizedPullRequest(pr), sizeLive, canPush);+ if (size.held !== hasLabel(pr, LABELS.tooLarge)) {+ core.info(`#${number}: ${size.held ? "+" : "-"}${LABELS.tooLarge}`);+ pr = withLabel(pr, LABELS.tooLarge, size.held, now);}+ pr = await withTeamComments(pr, canPush);const decision = await confirmConflicts(github, repo, pr, decide(pr, now), mergeabilityRetryMs);result = { pr, decision, failed: false };if (decision.action !== "none") core.info(`#${number}: ${decision.action} (${decision.reasons.join(", ")})`);- if (live && WRITES.includes(decision.action)) {+ if (writesLive(decision, live, sizeLive) && WRITES.includes(decision.action)) {await apply(github, issue, pr, decision, now, writeIntervalMs);await sleep(writeIntervalMs);}@@ -579,6 +679,6 @@ export default async function triageStalePullRequests({}}- await writeSummary(core, results, live);+ await writeSummary(core, results, live, sizeLive);if (failures > 0) core.setFailed(`${failures} PR(s) could not be updated.`);}diff --git a/.github/workflows/pr-size-limit.yml b/.github/workflows/pr-size-limit.ymlnew file mode 100644index 0000000000..7e6810476e--- /dev/null+++ b/.github/workflows/pr-size-limit.yml@@ -0,0 +1,52 @@+name: PR size limit++# Fails PRs from outside the team that change more than MAX_LINES lines. The rules live+# in .github/scripts/pr-size.ts.+# Enforced only when the PR_SIZE_BOT_LIVE repository variable is "true": until then it+# warns in the check's log but never fails a PR, comments or labels it, and the daily+# triage never closes one for size.+# pull_request_target so a first-time contributor's PR is checked without approval; it+# reads the diff through the API and never checks out the PR's code.++on:+ pull_request_target:+ types: [opened, reopened, synchronize, ready_for_review, labeled, unlabeled]++permissions:+ contents: read++concurrency:+ group: pr-size-limit-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ check:+ name: Check PR size+ # No filtering by label: a skipped run on the same commit would pass a required check.+ if: vars.CI_PROFILE != 'lite'+ runs-on: ubuntu-latest+ permissions:+ contents: read # actions/checkout+ issues: write # label the PR+ pull-requests: write # list the PR's files, comment on and label it+ steps:+ - name: Harden Runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit++ - name: Check out the scripts+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false+ sparse-checkout: .github/scripts++ - name: Check the PR size+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0+ env:+ LIVE: ${{ vars.PR_SIZE_BOT_LIVE == 'true' }}+ with:+ github-token: ${{ github.token }}+ script: |+ const { checkPullRequestSize } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/pr-size.ts`);+ await checkPullRequestSize({ github, context, core, live: process.env.LIVE === "true" });diff --git a/.github/workflows/stale-prs.yml b/.github/workflows/stale-prs.ymlindex 24cddd1244..be1fcad14c 100644--- a/.github/workflows/stale-prs.yml+++ b/.github/workflows/stale-prs.yml@@ -1,7 +1,8 @@name: Stale PR triage# Dry run unless the STALE_PR_BOT_LIVE repository variable is "true"; unsetting it-# is the kill switch. The rules live in .github/scripts/stale-prs.ts.+# is the kill switch. The size limit's part has its own, PR_SIZE_BOT_LIVE. The rules+# live in .github/scripts/stale-prs.ts.on:schedule:@@ -22,6 +23,7 @@ on:- ".github/scripts/package-lock.json"- ".github/scripts/tsconfig.json"- ".github/workflows/pr-conflict-labeler.yml"+ - ".github/workflows/pr-size-limit.yml"permissions:contents: read@@ -77,7 +79,7 @@ jobs:with:script: |const { default: triage } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/stale-prs.ts`);- await triage({ github, context, core, live: false });+ await triage({ github, context, core, live: false, sizeLive: false });triage:name: Warn and close stale PRs@@ -103,8 +105,9 @@ jobs:uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0env:LIVE: ${{ vars.STALE_PR_BOT_LIVE == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) }}+ SIZE_LIVE: ${{ vars.PR_SIZE_BOT_LIVE == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) }}with:github-token: ${{ github.token }}script: |const { default: triage } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/stale-prs.ts`);- await triage({ github, context, core, live: process.env.LIVE === "true" });+ await triage({ github, context, core, live: process.env.LIVE === "true", sizeLive: process.env.SIZE_LIVE === "true" });