#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 Stale PR bot (#8306)
James Brunton824339edc58d
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex 292828c796..2547451499 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -58,6 +58,7 @@ updates:- package-ecosystem: npmdirectories:+ - /.github/scripts- /devTools- /frontend- /testing/compose/mcp-client-checkdiff --git a/.github/labels.yml b/.github/labels.ymlindex 65861c0d4d..727df50de6 100644--- a/.github/labels.yml+++ b/.github/labels.yml@@ -156,6 +156,7 @@description: "Pull requests that require changes before they can be merged"- name: "on-hold"color: "2526F9"+ description: "Paused on purpose; never auto-closed as stale"- name: "python"color: "2b67c6"description: "Pull requests that update Python code"@@ -205,3 +206,12 @@- name: "has conflicts"color: "D93F0B"description: "Pull request has merge conflicts with the base branch"+- name: "Stale PR"+ color: "6E7781"+ description: "Waiting on the author; closes automatically a week after this was added"+- name: "backlog-cleanup"+ color: "BFD4F2"+ description: "Closed during the PR backlog cleanup; reopen to continue"+- 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.tsnew file mode 100644index 0000000000..02780653de--- /dev/null+++ b/.github/scripts/github.ts@@ -0,0 +1,69 @@+// The GitHub API surface and labels the PR bots share.++export const LABELS = {+ stale: "Stale PR",+ onHold: "on-hold",+ backlogCleanup: "backlog-cleanup",+ waitingOnAuthor: "waiting-on-author",+ conflicts: "has conflicts", // must match CONFLICT_LABEL in pr-conflict-labeler.yml+};++/** The login github.token acts as, so the actor on every write these bots make. */+export const BOT_LOGIN = "github-actions";++export interface Repo {+ owner: string;+ repo: string;+}++export type IssueRef = Repo & { issue_number: number };++export interface PullData {+ mergeable: boolean | null;+ mergeable_state: string;+ labels: { name: string }[];+ head: { ref: string; repo: { full_name: string } | null };+}++/** The parts of github-script's `github` client these scripts call. */+export interface GitHubClient {+ graphql<T>(query: string, variables: Record<string, unknown>): Promise<T>;+ rest: {+ issues: {+ createComment(params: IssueRef & { body: string }): Promise<unknown>;+ addLabels(params: IssueRef & { labels: string[] }): Promise<unknown>;+ removeLabel(params: IssueRef & { name: string }): Promise<unknown>;+ };+ pulls: {+ get(params: Repo & { pull_number: number }): Promise<{ data: PullData }>;+ update(params: Repo & { pull_number: number; state: "closed" }): Promise<unknown>;+ };+ };+}++type SummaryCell = string | { data: string; header?: boolean };++interface Summary {+ addHeading(text: string): Summary;+ addRaw(text: string, addEOL?: boolean): Summary;+ addTable(rows: SummaryCell[][]): Summary;+ write(): Promise<Summary>;+}++/** The parts of github-script's `core` (@actions/core) these scripts call. */+export interface Core {+ info(message: string): void;+ error(message: string): void;+ setFailed(message: string): void;+ summary: Summary;+}++export const isNotFound = (error: unknown) =>+ typeof error === "object" && error !== null && "status" in error && error.status === 404;++/** 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) => {+ if (!isNotFound(error)) throw error;+ });+}diff --git a/.github/scripts/package-lock.json b/.github/scripts/package-lock.jsonnew file mode 100644index 0000000000..5d71d060fc--- /dev/null+++ b/.github/scripts/package-lock.json@@ -0,0 +1,44 @@+{+ "name": "scripts",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "devDependencies": {+ "@types/node": "^24.5.2",+ "typescript": "^6.0.2"+ }+ },+ "node_modules/@types/node": {+ "version": "24.19.1",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.1.tgz",+ "integrity": "sha512-aS3/DG0oM05K0RIXXP+hKjinGG5IgSSVGzswZxW3O0sS3pH4/fycXundUC9XsszgKCk4gHXylTEK6hyFxVxnoQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": ">=7.24.0 <7.24.7"+ }+ },+ "node_modules/typescript": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",+ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "7.24.6",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",+ "dev": true,+ "license": "MIT"+ }+ }+}diff --git a/.github/scripts/package.json b/.github/scripts/package.jsonnew file mode 100644index 0000000000..6b0409f263--- /dev/null+++ b/.github/scripts/package.json@@ -0,0 +1,8 @@+{+ "private": true,+ "type": "module",+ "devDependencies": {+ "@types/node": "^24.5.2",+ "typescript": "^6.0.2"+ }+}diff --git a/.github/scripts/pr-turn.test.ts b/.github/scripts/pr-turn.test.tsnew file mode 100644index 0000000000..4ecc7d4fdb--- /dev/null+++ b/.github/scripts/pr-turn.test.ts@@ -0,0 +1,235 @@+import assert from "node:assert/strict";+import { describe, it } from "node:test";++import { type GitHubClient, LABELS } from "./github.ts";+import {+ clearStaleTurnLabel,+ type ReviewNode,+ type TimelineItem,+ turnChangeForEvent,+ type TurnPayload,+ updateTurnLabel,+} from "./pr-turn.ts";++type TurnItem = ReviewNode | TimelineItem;++const AUTHOR = "contributor";+const HEAD = "head-sha";+const FORK = "contributor/r";+const BRANCH = "feature";+const NOW = Date.parse("2026-10-01T12:00:00Z");+const repo = { owner: "o", repo: "r" };++interface FakeOptions {+ labelled?: boolean;+ alreadyRemoved?: boolean;+ missing?: boolean;+ pageSize?: number;+}++function fakeGitHub(items: TurnItem[] = [], { labelled = false, alreadyRemoved = false, missing = false, pageSize = 100 }: FakeOptions = {}) {+ const calls: string[] = [];+ const reads = { pages: 0 };+ const github: GitHubClient = {+ graphql: async <T>(query: string, variables: Record<string, unknown>) => {+ reads.pages += 1;+ if (query.includes("reviews(last")) {+ const reviews = { nodes: items.filter((item) => item.__typename === "PullRequestReview") };+ return { repository: { pullRequest: { author: { login: AUTHOR }, headRefOid: HEAD, reviews } } } as T;+ }+ const timeline = items.filter((item) => item.__typename !== "PullRequestReview");+ const end = typeof variables.before === "string" ? Number(variables.before) : timeline.length;+ const start = Math.max(0, end - pageSize);+ const timelineItems = { pageInfo: { hasPreviousPage: start > 0, startCursor: String(start) }, nodes: timeline.slice(start, end) };+ return { repository: { pullRequest: { timelineItems } } } as T;+ },+ rest: {+ issues: {+ createComment: async () => assert.fail("no comments"),+ addLabels: async ({ issue_number, labels }) => calls.push(`label #${issue_number} ${labels.join(",")}`),+ removeLabel: async ({ issue_number, name }) => {+ if (alreadyRemoved) throw Object.assign(new Error("Label does not exist"), { status: 404 });+ return calls.push(`unlabel #${issue_number} ${name}`);+ },+ },+ pulls: {+ get: async () => {+ if (missing) throw Object.assign(new Error("Not Found"), { status: 404 });+ const labels = labelled ? [{ name: LABELS.waitingOnAuthor }] : [];+ return { data: { mergeable: null, mergeable_state: "unknown", labels, head: { ref: BRANCH, repo: { full_name: FORK } } } };+ },+ update: async () => assert.fail("no closes"),+ },+ },+ };+ return { github, calls, reads };+}++const minutesAgo = (n: number) => new Date(NOW - n * 60 * 1000).toISOString();++const review = (state: string, login: string, canPush: boolean, ago: number, commit = HEAD, type = "User"): TurnItem => ({+ __typename: "PullRequestReview",+ submittedAt: minutesAgo(ago),+ state,+ authorCanPushToRepository: canPush,+ author: { login, __typename: type },+ commit: { oid: commit },+});+const comment = (login: string, ago: number): TurnItem => ({ __typename: "IssueComment", createdAt: minutesAgo(ago), author: { login } });+const dismissal = (ago: number): TurnItem => ({+ __typename: "ReviewDismissedEvent",+ createdAt: minutesAgo(ago),+ previousReviewState: "CHANGES_REQUESTED",+});+const labelEvent = (typename: "LabeledEvent" | "UnlabeledEvent", ago: number, name = LABELS.waitingOnAuthor): TurnItem => ({+ __typename: typename,+ createdAt: minutesAgo(ago),+ label: { name },+});++const pushBy = (login: string): TurnPayload => ({ sender: { login }, pull_request: { number: 7, user: { login: AUTHOR } } });+const commentBy = (login: string, onPullRequest = true): TurnPayload => ({+ issue: { number: 7, user: { login: AUTHOR }, ...(onPullRequest ? { pull_request: {} } : {}) },+ comment: { user: { login } },+});+const relayRun = ({ title = "Review on #7", event = "pull_request_review", headRepo = FORK, headBranch = BRANCH } = {}): TurnPayload => ({+ workflow_run: { event, display_title: title, head_branch: headBranch, head_repository: { full_name: headRepo } },+});++const changeFor = (payload: TurnPayload, items: TurnItem[] = [], options: FakeOptions = {}) =>+ turnChangeForEvent(fakeGitHub(items, options).github, { repo, payload });++describe("turn change for an author's event", () => {+ it("hands the turn back when the author pushes, re-requests review or marks it ready", async () => {+ assert.deepEqual(await changeFor(pushBy(AUTHOR)), { number: 7, add: false });+ });++ it("ignores a maintainer's push, such as Update branch", async () => {+ assert.equal(await changeFor(pushBy("maintainer")), null);+ });++ it("hands the turn back when the author comments", async () => {+ assert.deepEqual(await changeFor(commentBy(AUTHOR)), { number: 7, add: false });+ });++ it("ignores someone else's comment, and comments on issues", async () => {+ assert.equal(await changeFor(commentBy("maintainer")), null);+ assert.equal(await changeFor(commentBy(AUTHOR, false)), null);+ });+});++describe("turn change for a relayed review", () => {+ it("gives the author the turn on a changes-requested review from someone who can push", async () => {+ assert.deepEqual(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "maintainer", true, 1)]), { number: 7, add: true });+ });++ it("ignores changes requested by someone who cannot push, or by a bot", async () => {+ assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "passer-by", false, 1)]), null);+ assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "review-bot", true, 1, HEAD, "Bot")]), null);+ });++ it("hands the turn back on an approval from someone who can push", async () => {+ const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("APPROVED", "maintainer", true, 1)];+ assert.deepEqual(await changeFor(relayRun(), items, { labelled: true }), { number: 7, add: false });+ });++ it("ignores approvals from someone who cannot push, and comment-only reviews", async () => {+ const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9)];+ assert.equal(await changeFor(relayRun(), [...items, review("APPROVED", "passer-by", false, 1)], { labelled: true }), null);+ assert.equal(await changeFor(relayRun(), [...items, review("COMMENTED", "maintainer", true, 1)], { labelled: true }), null);+ });++ it("hands the turn back when the author replies in a review", async () => {+ const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("COMMENTED", AUTHOR, false, 1)];+ assert.deepEqual(await changeFor(relayRun(), items, { labelled: true }), { number: 7, add: false });+ });++ it("hands the turn back when a changes-requested review is dismissed", async () => {+ const items = [review("DISMISSED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), dismissal(1)];+ assert.deepEqual(await changeFor(relayRun(), items, { labelled: true }), { number: 7, add: false });+ });++ it("goes by the latest review, whichever run arrives first", async () => {+ const items = [review("CHANGES_REQUESTED", "maintainer", true, 2), review("APPROVED", "other-maintainer", true, 1)];+ assert.equal(await changeFor(relayRun(), items), null);+ });++ it("does not add the label when the author answered before the run", async () => {+ assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "maintainer", true, 2, "older-sha")]), null);+ assert.equal(await changeFor(relayRun(), [review("CHANGES_REQUESTED", "maintainer", true, 2), comment(AUTHOR, 1)]), null);+ });++ it("keeps a label added by hand", async () => {+ assert.equal(await changeFor(relayRun(), [review("APPROVED", "maintainer", true, 10), labelEvent("LabeledEvent", 1)], { labelled: true }), null);+ });++ it("reads further back in the timeline when the newest page moves nothing", async () => {+ const noise = Array.from({ length: 5 }, (_, index) => comment("maintainer", 5 - index));+ const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), comment(AUTHOR, 8), ...noise];+ const { github, reads } = fakeGitHub(items, { pageSize: 2 });+ assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun() }), null);+ assert.ok(reads.pages > 2);+ });++ it("hands the turn back when the author replies to a review thread", async () => {+ const items = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("COMMENTED", AUTHOR, false, 1)];+ const payload = relayRun({ event: "pull_request_review_comment" });+ assert.deepEqual(await changeFor(payload, items, { labelled: true }), { number: 7, add: false });+ });++ it("ignores a run built from another PR, whatever its title says", async () => {+ const { github, reads } = fakeGitHub([review("CHANGES_REQUESTED", "maintainer", true, 1)]);+ assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun({ headRepo: "attacker/r" }) }), null);+ assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun({ headBranch: "other" }) }), null);+ assert.equal(await turnChangeForEvent(github, { repo, payload: relayRun({ event: "pull_request" }) }), null);+ assert.equal(reads.pages, 0);+ });++ it("ignores runs it did not relay, and PRs that do not exist", async () => {+ assert.equal(await changeFor(relayRun({ title: "Something else" })), null);+ assert.equal(await changeFor(relayRun(), [], { missing: true }), null);+ });+});++describe("update turn label", () => {+ const core = { info: () => {} };++ it("adds the label", async () => {+ const { github, calls } = fakeGitHub([review("CHANGES_REQUESTED", "maintainer", true, 1)]);+ await updateTurnLabel({ github, context: { repo, payload: relayRun() }, core });+ assert.deepEqual(calls, ["label #7 waiting-on-author"]);+ });++ it("removes the label, and does not mind when it is not there", async () => {+ const present = fakeGitHub();+ await updateTurnLabel({ github: present.github, context: { repo, payload: pushBy(AUTHOR) }, core });+ assert.deepEqual(present.calls, ["unlabel #7 waiting-on-author"]);++ const absent = fakeGitHub([], { alreadyRemoved: true });+ await updateTurnLabel({ github: absent.github, context: { repo, payload: pushBy(AUTHOR) }, core });+ assert.deepEqual(absent.calls, []);+ });+});++describe("clear stale turn label", () => {+ const issue = { ...repo, issue_number: 7 };+ const answered = [review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9), review("COMMENTED", AUTHOR, false, 1)];++ it("removes a label whose turn has moved on", async () => {+ const { github, calls } = fakeGitHub(answered);+ assert.equal(await clearStaleTurnLabel(github, issue, true), true);+ assert.deepEqual(calls, ["unlabel #7 waiting-on-author"]);+ });++ it("keeps a label that still stands", async () => {+ const { github, calls } = fakeGitHub([review("CHANGES_REQUESTED", "maintainer", true, 10), labelEvent("LabeledEvent", 9)]);+ assert.equal(await clearStaleTurnLabel(github, issue, true), false);+ assert.deepEqual(calls, []);+ });++ it("changes nothing in a dry run", async () => {+ const { github, calls } = fakeGitHub(answered);+ assert.equal(await clearStaleTurnLabel(github, issue, false), true);+ assert.deepEqual(calls, []);+ });+});diff --git a/.github/scripts/pr-turn.ts b/.github/scripts/pr-turn.tsnew file mode 100644index 0000000000..bd2b293c2a--- /dev/null+++ b/.github/scripts/pr-turn.ts@@ -0,0 +1,242 @@+// Keeps waiting-on-author current. pr-turn-labels.yml runs it as each event happens, and+// the daily triage re-checks every ready PR that has the label, because the review relay+// does not always run: a conflicted PR has no merge ref to run it on. This file owns+// waiting-on-author and no other label.+//+// The author's turn starts with a changes-requested review from someone who can push, or+// the label added by hand. It ends when the author pushes, comments, replies to a review,+// re-requests review or marks the PR ready, when someone who can push approves, when a+// changes-requested review is dismissed, or when the label is removed.++import { type Core, type GitHubClient, type IssueRef, isNotFound, LABELS, type PullData, type Repo, removeLabel } from "./github.ts";++/** The parts of a github-script `context.payload` the turn events carry. */+export interface TurnPayload {+ sender?: { login: string };+ pull_request?: { number: number; user: { login: string } };+ issue?: { number: number; user: { login: string }; pull_request?: unknown };+ comment?: { user: { login: string } };+ workflow_run?: { event: string; display_title: string; head_branch: string; head_repository: { full_name: string } };+}++export interface TurnChange {+ number: number;+ add: boolean;+}++// Must match the run-name and the events in pr-review-events.yml.+const REVIEW_RUN_TITLE = /^Review on #(\d+)$/;+const RELAYED_EVENTS = ["pull_request_review", "pull_request_review_comment"];++// Reviews come from `reviews`, not the timeline: a reply to a review thread is a review+// of its own, and the timeline leaves those out.+const REVIEWS_QUERY = `+ query($owner: String!, $repo: String!, $number: Int!) {+ repository(owner: $owner, name: $repo) {+ pullRequest(number: $number) {+ author { login }+ headRefOid+ reviews(last: 100) {+ nodes { __typename submittedAt state authorCanPushToRepository author { login __typename } commit { oid } }+ }+ }+ }+ }+`;++const TIMELINE_QUERY = `+ query($owner: String!, $repo: String!, $number: Int!, $before: String) {+ repository(owner: $owner, name: $repo) {+ pullRequest(number: $number) {+ timelineItems(+ last: 100+ before: $before+ itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT, READY_FOR_REVIEW_EVENT, REVIEW_DISMISSED_EVENT, LABELED_EVENT, UNLABELED_EVENT]+ ) {+ pageInfo { hasPreviousPage startCursor }+ nodes {+ __typename+ ... on IssueComment { createdAt author { login } }+ ... on ReviewRequestedEvent { createdAt actor { login } }+ ... on ReadyForReviewEvent { createdAt actor { login } }+ ... on ReviewDismissedEvent { createdAt previousReviewState }+ ... on LabeledEvent { createdAt label { name } }+ ... on UnlabeledEvent { createdAt label { name } }+ }+ }+ }+ }+ }+`;++type Login = { login: string } | null;++/** One review as REVIEWS_QUERY returns it: must stay in sync with the query. */+export interface ReviewNode {+ __typename: "PullRequestReview";+ submittedAt: string | null;+ state: string;+ authorCanPushToRepository: boolean;+ author: { login: string; __typename: string } | null;+ commit: { oid: string } | null;+}++/** One timeline item as TIMELINE_QUERY returns it: must stay in sync with the query. */+export type TimelineItem =+ | { __typename: "IssueComment"; createdAt: string; author: Login }+ | { __typename: "ReviewRequestedEvent" | "ReadyForReviewEvent"; createdAt: string; actor: Login }+ | { __typename: "ReviewDismissedEvent"; createdAt: string; previousReviewState: string }+ | { __typename: "LabeledEvent" | "UnlabeledEvent"; createdAt: string; label: { name: string } };++export interface ReviewsPage {+ repository: {+ pullRequest: { author: Login; headRefOid: string; reviews: { nodes: ReviewNode[] } } | null;+ };+}++export interface TimelinePage {+ repository: {+ pullRequest: {+ timelineItems: {+ pageInfo: { hasPreviousPage: boolean; startCursor: string | null };+ nodes: TimelineItem[];+ };+ } | null;+ };+}++type Turn = "author" | "maintainers";++interface TurnMove {+ at: number;+ turn: Turn;+}++const isBy = (actor: Login, author: string | undefined) => actor !== null && actor.login === author;++function reviewTurn(review: ReviewNode, author: string | undefined, headOid: string): Turn | null {+ if (isBy(review.author, author)) return "maintainers";+ // Review bots can have push access, but only a person's verdict moves the turn.+ if (review.author?.__typename === "Bot" || !review.authorCanPushToRepository) return null;+ if (review.state === "APPROVED") return "maintainers";+ // A push has no time to compare against, so one since the review shows as the review+ // being of an older commit.+ return review.state === "CHANGES_REQUESTED" && review.commit?.oid === headOid ? "author" : null;+}++function timelineTurn(item: TimelineItem, author: string | undefined): Turn | null {+ const isAuthor = (actor: Login) => isBy(actor, author);+ switch (item.__typename) {+ case "IssueComment":+ return isAuthor(item.author) ? "maintainers" : null;+ case "ReviewRequestedEvent":+ case "ReadyForReviewEvent":+ return isAuthor(item.actor) ? "maintainers" : null;+ case "ReviewDismissedEvent":+ return item.previousReviewState === "CHANGES_REQUESTED" ? "maintainers" : null;+ case "LabeledEvent":+ case "UnlabeledEvent":+ if (item.label.name !== LABELS.waitingOnAuthor) return null;+ return item.__typename === "LabeledEvent" ? "author" : "maintainers";+ }+}++const move = (at: string | null, turn: Turn | null): TurnMove[] => (at === null || turn === null ? [] : [{ at: Date.parse(at), turn }]);++const latestMove = (moves: TurnMove[]) =>+ moves.reduce<TurnMove | null>((latest, candidate) => (latest === null || candidate.at >= latest.at ? candidate : latest), null);++// Pages run newest first, so the first page with a move holds the latest one.+async function latestTimelineMove(github: GitHubClient, repo: Repo, number: number, author: string | undefined) {+ let before: string | null = null;+ do {+ const page: TimelinePage = await github.graphql(TIMELINE_QUERY, { ...repo, number, before });+ const items = page.repository.pullRequest?.timelineItems;+ if (!items) return null;+ const latest = latestMove(items.nodes.flatMap((item) => move(item.createdAt, timelineTurn(item, author))));+ if (latest !== null) return latest;+ before = items.pageInfo.hasPreviousPage ? items.pageInfo.startCursor : null;+ } while (before !== null);+ return null;+}++/**+ * Whether the PR is waiting on its author. Read from the PR's history rather than the+ * event at hand, so runs that overlap, arrive late or are re-run all agree.+ */+export async function authorHasTurn(github: GitHubClient, { owner, repo }: Repo, number: number): Promise<boolean> {+ const page = await github.graphql<ReviewsPage>(REVIEWS_QUERY, { owner, repo, number });+ const pr = page.repository.pullRequest;+ if (pr === null) return false;+ const author = pr.author?.login;+ const fromReviews = pr.reviews.nodes.flatMap((review) => move(review.submittedAt, reviewTurn(review, author, pr.headRefOid)));+ const fromTimeline = await latestTimelineMove(github, { owner, repo }, number, author);+ return latestMove(fromTimeline === null ? fromReviews : [...fromReviews, fromTimeline])?.turn === "author";+}++async function relayedPull(github: GitHubClient, repo: Repo, run: NonNullable<TurnPayload["workflow_run"]>) {+ const match = REVIEW_RUN_TITLE.exec(run.display_title);+ if (!RELAYED_EVENTS.includes(run.event) || !match) return null;+ const number = Number(match[1]);+ const pull = await github.rest.pulls.get({ ...repo, pull_number: number }).then(+ ({ data }): PullData | null => data,+ (error: unknown) => {+ if (isNotFound(error)) return null;+ throw error;+ },+ );+ // Any PR can name a run, by editing pr-review-events.yml or adding a workflow of the+ // same name, so the title is only trusted for the PR the run was built from.+ const builtFrom = pull?.head.repo?.full_name === run.head_repository.full_name && pull.head.ref === run.head_branch;+ return builtFrom ? { number, pull } : null;+}++/** How the triggering event moves waiting-on-author, or null when it does not. */+export async function turnChangeForEvent(+ github: GitHubClient,+ { repo, payload }: { repo: Repo; payload: TurnPayload },+): Promise<TurnChange | null> {+ if (payload.pull_request) {+ const { number, user } = payload.pull_request;+ return payload.sender?.login === user.login ? { number, add: false } : null;+ }+ if (payload.issue) {+ const { number, user, pull_request } = payload.issue;+ return pull_request && payload.comment?.user.login === user.login ? { number, add: false } : null;+ }+ const relayed = payload.workflow_run ? await relayedPull(github, repo, payload.workflow_run) : null;+ if (relayed === null) return null;+ const add = await authorHasTurn(github, repo, relayed.number);+ const labelled = relayed.pull.labels.some((label) => label.name === LABELS.waitingOnAuthor);+ return add === labelled ? null : { number: relayed.number, add };+}++export async function updateTurnLabel({+ github,+ context,+ core,+}: {+ github: GitHubClient;+ context: { repo: Repo; payload: TurnPayload };+ core: Pick<Core, "info">;+}) {+ const change = await turnChangeForEvent(github, context);+ if (change === null) return;+ const issue = { ...context.repo, issue_number: change.number };+ if (change.add) {+ await github.rest.issues.addLabels({ ...issue, labels: [LABELS.waitingOnAuthor] });+ } else {+ await removeLabel(github, issue, LABELS.waitingOnAuthor);+ }+ core.info(`#${change.number}: ${change.add ? "+" : "-"}${LABELS.waitingOnAuthor}`);+}++/**+ * Removes waiting-on-author from a PR whose history says the turn has moved on. Returns+ * whether the label was stale; changes nothing unless `live`.+ */+export async function clearStaleTurnLabel(github: GitHubClient, issue: IssueRef, live: boolean) {+ if (await authorHasTurn(github, issue, issue.issue_number)) return false;+ if (live) await removeLabel(github, issue, LABELS.waitingOnAuthor);+ return true;+}diff --git a/.github/scripts/stale-prs.test.ts b/.github/scripts/stale-prs.test.tsnew file mode 100644index 0000000000..8dcf9c41a1--- /dev/null+++ b/.github/scripts/stale-prs.test.ts@@ -0,0 +1,541 @@+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 { ReviewNode, TimelineItem } from "./pr-turn.ts";+import triageStalePullRequests, {+ type Actor,+ closingComment,+ decide,+ latestActivity,+ type PullRequest,+ type PullRequestNode,+ type TimelineEvent,+ warningComment,+} from "./stale-prs.ts";++const DAY_MS = 24 * 60 * 60 * 1000;+const NOW = Date.parse("2026-10-01T12:00:00Z");+const daysAgo = (n: number) => new Date(NOW - n * DAY_MS).toISOString();++const BOT: Actor = { login: BOT_LOGIN, __typename: "Bot" };+const PERSON: Actor = { login: "maintainer", __typename: "User" };++interface PullRequestOptions {+ number?: number;+ isDraft?: boolean;+ activeDaysAgo?: number;+ authorType?: string;+}++function pullRequest({+ number = 1,+ isDraft = false,+ activeDaysAgo = 0,+ authorType = "User",+}: PullRequestOptions = {}): PullRequest {+ return {+ number,+ url: `https://github.com/o/r/pull/${number}`,+ isDraft,+ baseRefName: "main",+ author: { login: "contributor", __typename: authorType },+ labels: [],+ timeline: [],+ lastActivityAt: daysAgo(activeDaysAgo),+ };+}++function label(pr: PullRequest, name: string, daysAgoAdded: number, actor = BOT) {+ pr.labels.push(name);+ pr.timeline.push({ __typename: "LabeledEvent", createdAt: daysAgo(daysAgoAdded), label: { name }, actor });+ return pr;+}++function unlabel(pr: PullRequest, name: string, daysAgoRemoved: number, actor = BOT) {+ pr.labels = pr.labels.filter((existing) => existing !== name);+ pr.timeline.push({ __typename: "UnlabeledEvent", createdAt: daysAgo(daysAgoRemoved), label: { name }, actor });+ return pr;+}++function happened(pr: PullRequest, typename: "ReopenedEvent" | "ReadyForReviewEvent" | "ConvertToDraftEvent", daysAgoHappened: number) {+ pr.timeline.push({ __typename: typename, createdAt: daysAgo(daysAgoHappened), actor: PERSON });+ return pr;+}++const decision = (pr: PullRequest) => decide(pr, NOW);+const actionFor = (pr: PullRequest) => decision(pr).action;+const conflicted = (daysAgoAdded: number) => label(pullRequest(), LABELS.conflicts, daysAgoAdded);++describe("ready PRs", () => {+ it("does nothing without a turn label, however old", () => {+ assert.equal(actionFor(pullRequest({ activeDaysAgo: 200 })), "none");+ });++ for (const name of [LABELS.conflicts, LABELS.waitingOnAuthor]) {+ it(`warns once ${name} has been on for 7 days`, () => {+ assert.equal(actionFor(label(pullRequest(), name, 7)), "warn");+ });++ it(`waits while ${name} is younger than 7 days`, () => {+ assert.equal(actionFor(label(pullRequest(), name, 6)), "none");+ });+ }++ it("counts a conflict from when the label was last added", () => {+ const pr = label(unlabel(conflicted(20), LABELS.conflicts, 10), LABELS.conflicts, 3);+ assert.equal(actionFor(pr), "none");+ });++ it("names only the reasons that are due", () => {+ const pr = label(conflicted(9), LABELS.waitingOnAuthor, 2);+ assert.deepEqual(decision(pr), { action: "warn", reasons: ["conflicts"] });+ });++ it("ignores bot-authored PRs", () => {+ assert.equal(actionFor(label(pullRequest({ authorType: "Bot" }), LABELS.conflicts, 30)), "none");+ });++ it("ignores PRs on hold", () => {+ assert.equal(actionFor(label(conflicted(30), LABELS.onHold, 1)), "none");+ });++ it("gives a full period after Stale PR is removed", () => {+ assert.equal(actionFor(unlabel(label(conflicted(30), LABELS.stale, 5), LABELS.stale, 3)), "none");+ assert.equal(actionFor(unlabel(label(conflicted(30), LABELS.stale, 9), LABELS.stale, 7)), "warn");+ });++ it("counts a turn only from when the PR was last made ready or reopened", () => {+ assert.equal(actionFor(happened(conflicted(20), "ReadyForReviewEvent", 3)), "none");+ assert.equal(actionFor(happened(conflicted(20), "ReopenedEvent", 3)), "none");+ assert.equal(actionFor(happened(conflicted(20), "ReadyForReviewEvent", 8)), "warn");+ });+});++describe("Stale PR added by someone else", () => {+ it("is replaced with a warning when one is due", () => {+ assert.deepEqual(decision(label(conflicted(10), LABELS.stale, 9, PERSON)), { action: "warn", reasons: ["conflicts"] });+ });++ it("is dropped, not acted on, when nothing is due", () => {+ assert.equal(actionFor(label(pullRequest(), LABELS.stale, 10, PERSON)), "clear");+ assert.equal(actionFor(label(pullRequest({ isDraft: true, activeDaysAgo: 3 }), LABELS.stale, 10, PERSON)), "clear");+ });++ it("does not delay the next warning once dropped", () => {+ assert.equal(actionFor(unlabel(label(conflicted(10), LABELS.stale, 5, PERSON), LABELS.stale, 4)), "warn");+ });+});++describe("ready PRs after the warning", () => {+ it("stays pending until the week is up", () => {+ assert.equal(actionFor(label(conflicted(20), LABELS.stale, 6)), "pending");+ });++ it("closes a week after the warning", () => {+ assert.deepEqual(decision(label(conflicted(20), LABELS.stale, 7)), { action: "close", reasons: ["conflicts"] });+ });++ it("clears once the turn label is removed", () => {+ assert.equal(actionFor(unlabel(label(conflicted(20), LABELS.stale, 7), LABELS.conflicts, 1)), "clear");+ });++ it("clears when a conflict is resolved and a new one appears", () => {+ const pr = label(unlabel(label(conflicted(20), LABELS.stale, 8), LABELS.conflicts, 3), LABELS.conflicts, 2);+ assert.equal(actionFor(pr), "clear");+ });++ it("clears when one of two reasons is resolved", () => {+ const pr = unlabel(label(label(conflicted(20), LABELS.waitingOnAuthor, 20), LABELS.stale, 8), LABELS.waitingOnAuthor, 1);+ assert.equal(actionFor(pr), "clear");+ });++ it("closes only for the reasons that were outstanding when it warned", () => {+ const pr = label(label(conflicted(20), LABELS.stale, 8), LABELS.waitingOnAuthor, 2);+ assert.deepEqual(decision(pr), { action: "close", reasons: ["conflicts"] });+ });++ it("closes only for the reasons that were due when it warned", () => {+ const pr = label(label(conflicted(16), LABELS.waitingOnAuthor, 9), LABELS.stale, 7);+ assert.deepEqual(decision(pr), { action: "close", reasons: ["conflicts"] });+ });++ it("finishes a close that stopped partway, and not one a maintainer reopened", () => {+ const interrupted = () => label(label(conflicted(40), LABELS.stale, 8), LABELS.backlogCleanup, 1);+ assert.deepEqual(decision(interrupted()), { action: "resume", reasons: [] });+ assert.equal(actionFor(happened(interrupted(), "ReopenedEvent", 0.5)), "clear");+ });++ it("clears on a reopened PR rather than closing it again", () => {+ assert.equal(actionFor(happened(label(conflicted(40), LABELS.stale, 20), "ReopenedEvent", 1)), "clear");+ });++ it("clears when it went to draft and back since the warning", () => {+ const pr = label(conflicted(20), LABELS.stale, 8);+ happened(pr, "ConvertToDraftEvent", 3);+ happened(pr, "ReadyForReviewEvent", 2);+ assert.equal(actionFor(pr), "clear");+ });++ it("clears when it is put on hold", () => {+ assert.equal(actionFor(label(label(conflicted(20), LABELS.stale, 8), LABELS.onHold, 1)), "clear");+ });+});++describe("drafts", () => {+ const draft = (activeDaysAgo: number) => pullRequest({ isDraft: true, activeDaysAgo });++ it("warns once nothing has touched it for 30 days", () => {+ assert.deepEqual(decision(draft(30)), { action: "warn", reasons: ["idleDraft"] });+ });++ it("waits before 30 days", () => {+ assert.equal(actionFor(draft(29)), "none");+ });++ it("ignores turn labels, which are for ready PRs", () => {+ assert.equal(actionFor(label(draft(3), LABELS.conflicts, 20)), "none");+ });++ it("stays pending while untouched since the warning", () => {+ assert.equal(actionFor(label(draft(33), LABELS.stale, 3)), "pending");+ });++ it("closes a week after the warning if still untouched", () => {+ assert.deepEqual(decision(label(draft(37), LABELS.stale, 7)), { action: "close", reasons: ["idleDraft"] });+ });++ it("clears once something touches it after the warning", () => {+ assert.equal(actionFor(label(draft(2), LABELS.stale, 7)), "clear");+ });++ it("clears when a ready PR warned about conflicts becomes a draft", () => {+ const pr = label(label(draft(20), LABELS.conflicts, 20), LABELS.stale, 8);+ happened(pr, "ConvertToDraftEvent", 1);+ assert.equal(actionFor(pr), "clear");+ });++ it("clears a draft warning once the PR is marked ready", () => {+ const pr = label(label(pullRequest(), LABELS.conflicts, 40), LABELS.stale, 8);+ happened(pr, "ReadyForReviewEvent", 1);+ assert.equal(actionFor(pr), "clear");+ });+});++describe("comments", () => {+ const pr = label(label(pullRequest(), LABELS.conflicts, 9), LABELS.waitingOnAuthor, 8);+ const reasons = decision(pr).reasons;++ it("tells the author every reason and how to fix it", () => {+ const body = warningComment(pr, reasons, NOW);+ assert.match(body, /@contributor/);+ assert.match(body, /merge conflicts with `main`\. Merging or rebasing/);+ assert.match(body, /waiting on a response from you\. Please add a comment, a new push/);+ assert.match(body, /closed automatically/);+ assert.match(body, /just add a comment so a maintainer can take a look/);+ });++ it("says how long a draft has been idle", () => {+ assert.match(warningComment(pullRequest({ isDraft: true, activeDaysAgo: 31 }), ["idleDraft"], NOW), /for 31 days/);+ });++ it("says how long a closed draft was idle", () => {+ assert.match(closingComment(pullRequest({ isDraft: true, activeDaysAgo: 37 }), ["idleDraft"], NOW), /for 37 days/);+ });++ it("explains the close and how to reopen", () => {+ const body = closingComment(pr, reasons, NOW);+ assert.match(body, /closed automatically/);+ assert.match(body, /open a new PR/);+ assert.doesNotMatch(body, /keeps it open/);+ });++ it("stays ASCII", () => {+ for (const body of [warningComment(pr, reasons, NOW), closingComment(pr, reasons, NOW)]) {+ assert.match(body, /^[\x20-\x7E\n]*$/);+ }+ });+});++describe("latest activity", () => {+ const node = (activity: PullRequestNode["activity"]["nodes"], committedDaysAgo = 50): PullRequestNode => ({+ ...toNode(pullRequest({ activeDaysAgo: 60 }), 100, null),+ commits: { nodes: [{ commit: { committedDate: daysAgo(committedDaysAgo) } }] },+ activity: { nodes: activity },+ });+ 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));+ });++ it("counts a push from its newest commit, and force pushes", () => {+ assert.equal(latestActivity(node([], 20), []), daysAgo(20));+ const forcePush = { __typename: "HeadRefForcePushedEvent" as const, createdAt: daysAgo(10), actor: PERSON };+ assert.equal(latestActivity(node([forcePush]), []), daysAgo(10));+ });++ it("counts a person's label and state changes, but not the bots'", () => {+ const pr = label(label(pullRequest(), LABELS.stale, 2), "bug", 30, PERSON);+ assert.equal(latestActivity(node([]), pr.timeline), daysAgo(30));+ });++ it("skips a review still pending", () => {+ const pending = { __typename: "PullRequestReview" as const, submittedAt: null, author: PERSON };+ assert.equal(latestActivity(node([pending]), []), daysAgo(50));+ });+});++// The cursor is the index of the page's first event, so `before` slices the timeline.+function toNode(pr: PullRequest, pageSize: number, before: string | null): PullRequestNode {+ const end = before === null ? pr.timeline.length : Number(before);+ const start = Math.max(0, end - pageSize);+ return {+ number: pr.number,+ state: "OPEN",+ url: pr.url,+ isDraft: pr.isDraft,+ createdAt: pr.lastActivityAt,+ baseRefName: pr.baseRefName,+ author: pr.author,+ labels: { nodes: pr.labels.map((name) => ({ name })) },+ commits: { nodes: [] },+ activity: { nodes: [] },+ timelineItems: {+ pageInfo: { hasPreviousPage: start > 0, startCursor: String(start) },+ nodes: pr.timeline.slice(start, end) satisfies TimelineEvent[],+ },+ };+}++type TurnItem = ReviewNode | TimelineItem;++const STILL_WAITING: TurnItem[] = [{ __typename: "LabeledEvent", createdAt: daysAgo(40), label: { name: LABELS.waitingOnAuthor } }];++interface FakeOptions {+ /** What pulls.get reports for mergeable. */+ mergeable?: boolean | null;+ /** What pulls.get reports for mergeable_state; "dirty" exactly when mergeable is false by default. */+ mergeableState?: string;+ timelinePageSize?: number;+ failFor?: number;+ failWrite?: string;+ alreadyRemoved?: string[];+ /** The history pr-turn.ts reads to re-check waiting-on-author. */+ turnItems?: TurnItem[];+}++function fakeGitHub(+ prs: PullRequest[],+ {+ mergeable = false,+ mergeableState = mergeable === false ? "dirty" : "clean",+ timelinePageSize = 100,+ failFor,+ failWrite,+ alreadyRemoved = [],+ turnItems = STILL_WAITING,+ }: FakeOptions = {},+) {+ const calls: string[] = [];+ const writeTimes: number[] = [];+ const reads = { mergeable: 0, pages: 0 };+ const write = (call: string) => {+ if (failWrite !== undefined && call.startsWith(failWrite)) throw new Error(`${failWrite} failed`);+ calls.push(call);+ writeTimes.push(Date.now());+ };+ const graphql = async (query: string, variables: Record<string, unknown>) => {+ if (query.includes("pullRequests(states: OPEN")) {+ const nodes = prs.map((pr) => ({ number: pr.number }));+ return { repository: { pullRequests: { pageInfo: { hasNextPage: false, endCursor: null }, nodes } } };+ }+ if (query.includes("reviews(last")) {+ const reviews = { nodes: turnItems.filter((item) => item.__typename === "PullRequestReview") };+ return { repository: { pullRequest: { author: { login: "contributor" }, headRefOid: "head-sha", reviews } } };+ }+ if (query.includes("REVIEW_DISMISSED_EVENT")) {+ const nodes = turnItems.filter((item) => item.__typename !== "PullRequestReview");+ return { repository: { pullRequest: { timelineItems: { pageInfo: { hasPreviousPage: false, startCursor: null }, nodes } } } };+ }+ if (variables.number === failFor) throw new Error("boom");+ reads.pages += 1;+ const pr = prs.find((candidate) => candidate.number === variables.number);+ assert.ok(pr);+ return { repository: { pullRequest: toNode(pr, timelinePageSize, (variables.before as string | null) ?? null) } };+ };+ const github: GitHubClient = {+ graphql: async <T>(query: string, variables: Record<string, unknown>) => (await graphql(query, variables)) as T,+ rest: {+ issues: {+ createComment: async ({ issue_number }) => write(`comment #${issue_number}`),+ addLabels: async ({ issue_number, labels }) => write(`label #${issue_number} ${labels.join(",")}`),+ removeLabel: async ({ issue_number, name }) => {+ if (alreadyRemoved.includes(name)) throw Object.assign(new Error("Label does not exist"), { status: 404 });+ write(`unlabel #${issue_number} ${name}`);+ },+ },+ pulls: {+ get: async () => {+ reads.mergeable += 1;+ return { data: { mergeable, mergeable_state: mergeableState, labels: [], head: { ref: "feature", repo: null } } };+ },+ update: async ({ pull_number }) => write(`close #${pull_number}`),+ },+ },+ };+ return { github, calls, writeTimes, reads };+}++function recordingCore() {+ const errors: string[] = [];+ const failed: string[] = [];+ const tables: unknown[][][] = [];+ let summaries = 0;+ const summary: Core["summary"] = {+ addHeading: () => summary,+ addRaw: () => summary,+ addTable: (rows) => {+ tables.push(rows);+ return summary;+ },+ write: async () => {+ summaries += 1;+ return summary;+ },+ };+ const core: Core = { info: () => {}, 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 } = {}) {+ const recorded = recordingCore();+ await triageStalePullRequests({+ github,+ context: { repo: { owner: "o", repo: "r" } },+ core: recorded.core,+ live,+ writeIntervalMs,+ mergeabilityRetryMs: 0,+ });+ return recorded;+}++describe("triage run", () => {+ // Dated well before the real clock, which the run reads, so the close is always due.+ const overdue = () => label(conflicted(40), LABELS.stale, 30);++ it("warns: comments, then labels", async () => {+ const { github, calls } = fakeGitHub([conflicted(10)]);+ await triage(github);+ assert.deepEqual(calls, ["comment #1", "label #1 Stale PR"]);+ });++ it("warns over a Stale PR label someone else added, replacing it with its own", async () => {+ const { github, calls } = fakeGitHub([label(conflicted(10), LABELS.stale, 9, PERSON)]);+ await triage(github);+ assert.deepEqual(calls, ["comment #1", "unlabel #1 Stale PR", "label #1 Stale PR"]);+ });++ it("closes: comments, labels it backlog-cleanup, then closes", async () => {+ const { github, calls } = fakeGitHub([overdue()]);+ const { errors } = await triage(github);+ assert.deepEqual(errors, []);+ assert.deepEqual(calls, ["comment #1", "label #1 backlog-cleanup", "close #1"]);+ });++ it("finishes a close that stopped partway without commenting again", async () => {+ const { github, calls } = fakeGitHub([label(overdue(), LABELS.backlogCleanup, 1)]);+ await triage(github);+ assert.deepEqual(calls, ["close #1"]);+ });++ it("changes nothing in a dry run", async () => {+ const { github, calls } = fakeGitHub([overdue()]);+ await triage(github, { live: false });+ assert.deepEqual(calls, []);+ });++ it("does not warn about a conflict GitHub no longer reports", async () => {+ const { github, calls } = fakeGitHub([conflicted(10)], { mergeable: true });+ await triage(github);+ assert.deepEqual(calls, []);+ });++ it("counts a conflict only when GitHub calls it dirty, as the labeler does", async () => {+ const { github, calls } = fakeGitHub([conflicted(10)], { mergeable: false, mergeableState: "blocked" });+ await triage(github);+ assert.deepEqual(calls, []);+ });++ it("does not close while GitHub cannot say whether it conflicts", async () => {+ const { github, calls, reads } = fakeGitHub([overdue()], { mergeable: null });+ await triage(github);+ assert.equal(reads.mergeable, 7);+ assert.deepEqual(calls, []);+ });++ it("still closes for another reason when the conflict is gone", async () => {+ const pr = label(label(conflicted(40), LABELS.waitingOnAuthor, 40), LABELS.stale, 30);+ const { github, calls } = fakeGitHub([pr], { mergeable: true });+ await triage(github);+ assert.deepEqual(calls, ["comment #1", "label #1 backlog-cleanup", "close #1"]);+ });++ it("drops a waiting-on-author the author already answered, which ends the warning", async () => {+ const pr = label(label(pullRequest(), LABELS.waitingOnAuthor, 40), LABELS.stale, 30);+ const reply: TurnItem = {+ __typename: "PullRequestReview",+ submittedAt: daysAgo(31),+ state: "COMMENTED",+ authorCanPushToRepository: false,+ author: { login: "contributor", __typename: "User" },+ commit: { oid: "head-sha" },+ };+ const { github, calls } = fakeGitHub([pr], { turnItems: [...STILL_WAITING, reply] });+ await triage(github);+ assert.deepEqual(calls, ["unlabel #1 waiting-on-author", "unlabel #1 Stale PR"]);+ });++ it("reads a timeline longer than one page", async () => {+ const pr = conflicted(40);+ for (let day = 39; day > 0; day -= 1) label(pr, `noise-${day}`, day);+ const { github, calls, reads } = fakeGitHub([pr], { timelinePageSize: 10 });+ await triage(github);+ assert.ok(reads.pages > 1);+ assert.deepEqual(calls, ["comment #1", "label #1 Stale PR"]);+ });++ it("does not fail when the label it clears is already gone", async () => {+ const pr = unlabel(label(conflicted(20), LABELS.stale, 7), LABELS.conflicts, 1);+ pr.labels.push(LABELS.stale);+ const { github } = fakeGitHub([pr], { alreadyRemoved: [LABELS.stale] });+ const { errors, failed } = await triage(github);+ assert.deepEqual([errors, failed], [[], []]);+ });++ it("carries on past a PR that cannot be read, and still writes the summary", async () => {+ const { github, calls } = fakeGitHub([conflicted(10), label(pullRequest({ number: 2 }), LABELS.conflicts, 10)], { failFor: 1 });+ const { errors, failed, summaries } = await triage(github);+ assert.deepEqual(calls, ["comment #2", "label #2 Stale PR"]);+ assert.deepEqual(errors, ["#1: boom"]);+ assert.equal(failed.length, 1);+ assert.equal(summaries(), 1);+ });++ it("marks a write that failed in the summary", async () => {+ const { github } = fakeGitHub([overdue()], { failWrite: "close" });+ const { tables, failed } = await triage(github);+ assert.equal(failed.length, 1);+ assert.equal(tables[0]?.[1]?.[2], "close (failed)");+ });++ it("pauses between writes", async () => {+ const { github, writeTimes } = fakeGitHub([overdue()]);+ await triage(github, { writeIntervalMs: 30 });+ assert.equal(writeTimes.length, 3);+ for (let index = 1; index < writeTimes.length; index += 1) {+ assert.ok((writeTimes[index] ?? 0) - (writeTimes[index - 1] ?? 0) >= 28);+ }+ });+});diff --git a/.github/scripts/stale-prs.ts b/.github/scripts/stale-prs.tsnew file mode 100644index 0000000000..2beee9ed77--- /dev/null+++ b/.github/scripts/stale-prs.ts@@ -0,0 +1,584 @@+// Stale PR triage, run daily by .github/workflows/stale-prs.yml.++import {+ BOT_LOGIN,+ type Core,+ type GitHubClient,+ type IssueRef,+ LABELS,+ type PullData,+ type Repo,+ removeLabel,+} from "./github.ts";+import { clearStaleTurnLabel } from "./pr-turn.ts";++const DAY_MS = 24 * 60 * 60 * 1000;++export type Reason = "conflicts" | "waitingOnAuthor" | "idleDraft";++const TURN_LABELS: { label: string; reason: Reason }[] = [+ { label: LABELS.conflicts, reason: "conflicts" },+ { label: LABELS.waitingOnAuthor, reason: "waitingOnAuthor" },+];++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;++// The same wait pr-conflict-labeler.yml gives GitHub to compute mergeability.+const MERGEABILITY_ATTEMPTS = 7;+const MERGEABILITY_RETRY_MS = 5000;++// Numbers only: within a page of PRs GitHub silently truncates nested connections,+// dropping the newest events while reporting them complete, so each PR is read alone.+const OPEN_PULL_NUMBERS_QUERY = `+ query($owner: String!, $repo: String!, $cursor: String) {+ repository(owner: $owner, name: $repo) {+ pullRequests(states: OPEN, first: 100, after: $cursor) {+ pageInfo { hasNextPage endCursor }+ nodes { number }+ }+ }+ }+`;++const TIMELINE_ITEMS = `+ timelineItems(+ last: 100+ before: $before+ itemTypes: [LABELED_EVENT, UNLABELED_EVENT, REOPENED_EVENT, READY_FOR_REVIEW_EVENT, CONVERT_TO_DRAFT_EVENT]+ ) {+ pageInfo { hasPreviousPage startCursor }+ nodes {+ __typename+ ... on LabeledEvent { createdAt label { name } actor { login __typename } }+ ... on UnlabeledEvent { createdAt label { name } actor { login __typename } }+ ... on ReopenedEvent { createdAt actor { login __typename } }+ ... on ReadyForReviewEvent { createdAt actor { login __typename } }+ ... on ConvertToDraftEvent { createdAt actor { login __typename } }+ }+ }+`;++// `activity` is the newest 100 only, which is plenty to find a person among the bots.+const PULL_REQUEST_QUERY = `+ query($owner: String!, $repo: String!, $number: Int!, $before: String) {+ repository(owner: $owner, name: $repo) {+ pullRequest(number: $number) {+ number+ state+ url+ isDraft+ createdAt+ baseRefName+ author { login __typename }+ labels(first: 100) { nodes { name } }+ commits(last: 1) { nodes { commit { committedDate } } }+ activity: timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, PULL_REQUEST_REVIEW, HEAD_REF_FORCE_PUSHED_EVENT]) {+ nodes {+ __typename+ ... on IssueComment { createdAt author { login __typename } }+ ... on PullRequestReview { submittedAt author { login __typename } }+ ... on HeadRefForcePushedEvent { createdAt actor { login __typename } }+ }+ }+ ${TIMELINE_ITEMS}+ }+ }+ }+`;++const OLDER_TIMELINE_QUERY = `+ query($owner: String!, $repo: String!, $number: Int!, $before: String) {+ repository(owner: $owner, name: $repo) {+ pullRequest(number: $number) {+ ${TIMELINE_ITEMS}+ }+ }+ }+`;++export interface Actor {+ login: string;+ __typename: string;+}++export type TimelineEvent =+ | { __typename: "LabeledEvent" | "UnlabeledEvent"; createdAt: string; label: { name: string }; actor: Actor | null }+ | { __typename: "ReopenedEvent" | "ReadyForReviewEvent" | "ConvertToDraftEvent"; createdAt: string; actor: Actor | null };++export type ActivityItem =+ | { __typename: "IssueComment"; createdAt: string; author: Actor | null }+ | { __typename: "PullRequestReview"; submittedAt: string | null; author: Actor | null }+ | { __typename: "HeadRefForcePushedEvent"; createdAt: string; actor: Actor | null };++interface TimelinePage {+ pageInfo: { hasPreviousPage: boolean; startCursor: string | null };+ nodes: TimelineEvent[];+}++/** One PR as PULL_REQUEST_QUERY returns it: must stay in sync with the query. */+export interface PullRequestNode {+ number: number;+ state: "OPEN" | "CLOSED" | "MERGED";+ url: string;+ isDraft: boolean;+ createdAt: string;+ baseRefName: string;+ author: Actor | null;+ labels: { nodes: { name: string }[] };+ commits: { nodes: { commit: { committedDate: string } }[] };+ activity: { nodes: ActivityItem[] };+ timelineItems: TimelinePage;+}++/** An open PR with its complete label, reopen and draft history. */+export interface PullRequest {+ number: number;+ url: string;+ isDraft: boolean;+ baseRefName: string;+ author: Actor | null;+ labels: string[];+ timeline: TimelineEvent[];+ /** When a person last did anything on it; see latestActivity. */+ lastActivityAt: string;+}++export type Action = "none" | "warn" | "pending" | "close" | "resume" | "clear";++export interface Decision {+ action: Action;+ reasons: Reason[];+}++const time = (iso: string) => Date.parse(iso);+const days = (ms: number) => Math.floor(ms / DAY_MS);+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++const hasLabel = (pr: PullRequest, name: string) => pr.labels.includes(name);+const byPerson = (actor: Actor | null) => actor?.__typename !== "Bot";+const byTriageBot = (actor: Actor | null) => actor?.__typename === "Bot" && actor.login === BOT_LOGIN;++function lastEvent(pr: PullRequest, matches: (event: TimelineEvent) => boolean) {+ return pr.timeline+ .filter(matches)+ .reduce<TimelineEvent | null>((last, event) => (last === null || time(event.createdAt) >= time(last.createdAt) ? event : last), null);+}++function latestEvent(pr: PullRequest, matches: (event: TimelineEvent) => boolean) {+ const event = lastEvent(pr, matches);+ return event === null ? null : time(event.createdAt);+}++const labelled = (name: string) => (event: TimelineEvent) =>+ event.__typename === "LabeledEvent" && event.label.name === name;++const unlabelled = (name: string) => (event: TimelineEvent) =>+ event.__typename === "UnlabeledEvent" && event.label.name === name;++const reopened = (event: TimelineEvent) => event.__typename === "ReopenedEvent";++const becameReady = (event: TimelineEvent) => reopened(event) || event.__typename === "ReadyForReviewEvent";++const changedState = (event: TimelineEvent) => becameReady(event) || event.__typename === "ConvertToDraftEvent";++// What ends a warning on a ready PR: a turn label removed, a reopen, or a switch to draft and back.+const endsWarning = (event: TimelineEvent) =>+ changedState(event) || TURN_LABELS.some(({ label }) => unlabelled(label)(event));++/** When the triage's warning was posted; null without Stale PR, or when someone else added it. */+function warningTime(pr: PullRequest) {+ if (!hasLabel(pr, LABELS.stale)) return null;+ const added = lastEvent(pr, labelled(LABELS.stale));+ return added !== null && byTriageBot(added.actor) ? time(added.createdAt) : null;+}++// Removing a warning, by hand or by a clear, restarts the clock; dropping a Stale PR+// label someone else added does not, as it was never a warning.+function lastWarningEndedAt(pr: PullRequest) {+ let warning = false;+ let endedAt: number | null = null;+ for (const event of [...pr.timeline].sort((a, b) => time(a.createdAt) - time(b.createdAt))) {+ if (labelled(LABELS.stale)(event)) {+ warning = byTriageBot(event.actor);+ } else if (unlabelled(LABELS.stale)(event)) {+ if (warning) endedAt = time(event.createdAt);+ warning = false;+ }+ }+ return endedAt;+}++// 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) {+ const closingAt = latestEvent(pr, labelled(LABELS.backlogCleanup));+ return hasLabel(pr, LABELS.backlogCleanup) && closingAt !== null && closingAt >= warnedAt && (latestEvent(pr, reopened) ?? 0) < closingAt;+}++const NONE: Decision = { action: "none", reasons: [] };+const CLEAR: Decision = { action: "clear", reasons: [] };++const closeOrPending = (now: number, warnedAt: number, reasons: Reason[]): Decision => ({+ action: now - warnedAt >= CLOSE_AFTER_WARNING_DAYS * DAY_MS ? "close" : "pending",+ reasons,+});++function decideReady(pr: PullRequest, now: number, warnedAt: number | null): Decision {+ // A turn only counts while the PR is open and ready.+ const readyAt = latestEvent(pr, becameReady) ?? 0;+ const restartedAt = lastWarningEndedAt(pr) ?? 0;+ const turns = TURN_LABELS.filter(({ label }) => hasLabel(pr, label)).map(({ label, reason }) => ({+ reason,+ since: Math.max(latestEvent(pr, labelled(label)) ?? now, readyAt, restartedAt),+ }));+ const dueAt = (at: number) => turns.filter((turn) => at - turn.since >= TURN_DAYS * DAY_MS).map((turn) => turn.reason);++ if (warnedAt === null) {+ const due = dueAt(now);+ return due.length > 0 ? { action: "warn", reasons: due } : NONE;+ }++ // Only what was due when it warned: a turn that started later was not in the warning.+ const warned = dueAt(warnedAt);+ const endedAt = latestEvent(pr, endsWarning);+ if (warned.length === 0 || (endedAt !== null && endedAt > warnedAt)) return CLEAR;+ return closeOrPending(now, warnedAt, warned);+}++function decideDraft(pr: PullRequest, now: number, warnedAt: number | null): Decision {+ const activeAt = time(pr.lastActivityAt);+ if (warnedAt === null) {+ return now - activeAt >= IDLE_DRAFT_DAYS * DAY_MS ? { action: "warn", reasons: ["idleDraft"] } : NONE;+ }+ const changedAt = latestEvent(pr, changedState) ?? 0;+ if (Math.max(activeAt, changedAt) > warnedAt) return CLEAR;+ return closeOrPending(now, warnedAt, ["idleDraft"]);+}++/**+ * What to do with one PR at epoch ms `now`. `action` is one of:+ * - "none": nothing has been outstanding long enough to warn.+ * - "warn": post the warning naming `reasons` and add the Stale PR label.+ * - "pending": warned, `reasons` still stand, and the close is not due yet.+ * - "close": warned CLOSE_AFTER_WARNING_DAYS ago and `reasons` still stand.+ * - "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.+ */+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 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;+}++function problem(reason: Reason, pr: PullRequest, now: number): string {+ switch (reason) {+ case "conflicts":+ return `It has merge conflicts with \`${pr.baseRefName}\`.`;+ case "waitingOnAuthor":+ 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.`;+ }+}++function remedy(reason: Reason, pr: PullRequest): string {+ switch (reason) {+ case "conflicts":+ return `Merging or rebasing onto \`${pr.baseRefName}\` resolves them.`;+ case "waitingOnAuthor":+ 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.";+ }+}++const authorLogin = (pr: PullRequest) => pr.author?.login ?? "ghost";++export function warningComment(pr: PullRequest, reasons: Reason[], now: number) {+ return [+ `Hi @${authorLogin(pr)}, this PR has been marked as being stale because:`,+ "",+ ...reasons.map((reason) => `- ${problem(reason, pr, now)} ${remedy(reason, pr)}`),+ "",+ `If this is still outstanding in ${CLOSE_AFTER_WARNING_DAYS} days, the PR will be closed automatically.`,+ "If you think it's actually waiting on us rather than you, just add a comment so a maintainer can take a look.",+ ].join("\n");+}++export function closingComment(pr: PullRequest, reasons: Reason[], now: number) {+ return [+ `Hi @${authorLogin(pr)}, this PR has been closed automatically because the following issues haven't been resolved within ${CLOSE_AFTER_WARNING_DAYS} days of the reminder:`,+ "",+ ...reasons.map((reason) => `- ${problem(reason, pr, now)}`),+ "",+ "Thanks for the contribution! If you pick this up again, please feel free to open a new PR and fix the above issues.",+ ].join("\n");+}++function activityTime(item: ActivityItem) {+ switch (item.__typename) {+ case "IssueComment":+ return byPerson(item.author) ? item.createdAt : null;+ case "PullRequestReview":+ return byPerson(item.author) ? item.submittedAt : null;+ case "HeadRefForcePushedEvent":+ return byPerson(item.actor) ? item.createdAt : null;+ }+}++/**+ * When a person last opened, pushed to, commented on, reviewed, labelled or changed the+ * state of the PR. Bots don't count, this triage included. GitHub records no push time,+ * so a push counts from its newest commit's date: commits made long before they were+ * pushed look old.+ */+export function latestActivity(node: PullRequestNode, timeline: TimelineEvent[]) {+ const times = [+ node.createdAt,+ ...node.commits.nodes.map((pullCommit) => pullCommit.commit.committedDate),+ ...node.activity.nodes.map(activityTime),+ ...timeline.filter((event) => byPerson(event.actor)).map((event) => event.createdAt),+ ];+ return new Date(Math.max(...times.flatMap((iso) => (iso === null ? [] : [time(iso)])))).toISOString();+}++async function fetchOpenPullNumbers(github: GitHubClient, repo: Repo) {+ const numbers: number[] = [];+ let cursor: string | null = null;+ do {+ const page: {+ repository: {+ pullRequests: { pageInfo: { hasNextPage: boolean; endCursor: string | null }; nodes: { number: number }[] };+ };+ } = await github.graphql(OPEN_PULL_NUMBERS_QUERY, { ...repo, cursor });+ const { nodes, pageInfo } = page.repository.pullRequests;+ numbers.push(...nodes.map((node) => node.number));+ cursor = pageInfo.hasNextPage ? pageInfo.endCursor : null;+ } while (cursor);+ return numbers;+}++/** The PR with its whole timeline; null once it is closed or merged. */+async function fetchPullRequest(github: GitHubClient, repo: Repo, number: number): Promise<PullRequest | null> {+ const page = await github.graphql<{ repository: { pullRequest: PullRequestNode | null } }>(PULL_REQUEST_QUERY, {+ ...repo,+ number,+ });+ const node = page.repository.pullRequest;+ if (node?.state !== "OPEN") return null;+ const timeline = [...node.timelineItems.nodes];+ let { pageInfo } = node.timelineItems;+ while (pageInfo.hasPreviousPage) {+ const older = await github.graphql<{ repository: { pullRequest: { timelineItems: TimelinePage } | null } }>(+ OLDER_TIMELINE_QUERY,+ { ...repo, number, before: pageInfo.startCursor },+ );+ const items = older.repository.pullRequest?.timelineItems;+ if (!items) break;+ timeline.unshift(...items.nodes);+ pageInfo = items.pageInfo;+ }+ return {+ number: node.number,+ url: node.url,+ isDraft: node.isDraft,+ baseRefName: node.baseRefName,+ author: node.author,+ labels: node.labels.nodes.map((label) => label.name),+ timeline,+ lastActivityAt: latestActivity(node, timeline),+ };+}++// Must match hasConflicts in pr-conflict-labeler.yml, the owner of the label this confirms.+const conflicting = (pull: PullData) => pull.mergeable === false && pull.mergeable_state === "dirty";++async function confirmedConflicting(github: GitHubClient, repo: Repo, number: number, retryMs: number) {+ for (let attempt = 1; attempt <= MERGEABILITY_ATTEMPTS; attempt += 1) {+ if (attempt > 1) await sleep(retryMs);+ const { data } = await github.rest.pulls.get({ ...repo, pull_number: number });+ if (data.mergeable !== null) return conflicting(data);+ }+ return false;+}++// The has conflicts label can be hours behind main, so a warning or close only names+// a conflict GitHub confirms now. Unknown counts as resolved.+async function confirmConflicts(+ github: GitHubClient,+ repo: Repo,+ pr: PullRequest,+ decision: Decision,+ retryMs: number,+): Promise<Decision> {+ const acts = decision.action === "warn" || decision.action === "close";+ if (!acts || !decision.reasons.includes("conflicts")) return decision;+ if (await confirmedConflicting(github, repo, pr.number, retryMs)) return decision;+ const reasons = decision.reasons.filter((reason) => reason !== "conflicts");+ if (reasons.length > 0) return { ...decision, reasons };+ 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",+ 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] };+}++async function paced(intervalMs: number, writes: (() => Promise<unknown>)[]) {+ for (const [index, write] of writes.entries()) {+ if (index > 0) await sleep(intervalMs);+ await write();+ }+}++// Comment before labelling, and before closing: if a later call fails, the next run+// repeats a comment rather than closing a PR whose author was never told.+async function apply(+ github: GitHubClient,+ issue: IssueRef,+ pr: PullRequest,+ decision: Decision,+ now: number,+ intervalMs: number,+) {+ const { issues, pulls } = github.rest;+ const close = () => pulls.update({ owner: issue.owner, repo: issue.repo, pull_number: pr.number, state: "closed" });+ switch (decision.action) {+ case "warn":+ await paced(intervalMs, [+ () => issues.createComment({ ...issue, body: warningComment(pr, decision.reasons, now) }),+ // A Stale PR label someone else added has to go first, so the warning's own label+ // is the one that dates it.+ ...(hasLabel(pr, LABELS.stale) ? [() => removeLabel(github, issue, LABELS.stale)] : []),+ () => issues.addLabels({ ...issue, labels: [LABELS.stale] }),+ ]);+ break;+ case "close":+ await paced(intervalMs, [+ () => issues.createComment({ ...issue, body: closingComment(pr, decision.reasons, now) }),+ () => issues.addLabels({ ...issue, labels: [LABELS.backlogCleanup] }),+ close,+ ]);+ break;+ case "resume":+ await close();+ break;+ case "clear":+ await removeLabel(github, issue, LABELS.stale);+ break;+ }+}++const ACTION_ORDER: Action[] = ["close", "resume", "warn", "clear", "pending"];+const WRITES: Action[] = ["warn", "close", "resume", "clear"];++interface Result {+ pr: PullRequest;+ decision: Decision;+ failed: boolean;+}++async function writeSummary(core: Core, results: Result[], live: boolean) {+ const rows = results+ .filter(({ decision }) => decision.action !== "none")+ .sort((a, b) => ACTION_ORDER.indexOf(a.decision.action) - ACTION_ORDER.indexOf(b.decision.action))+ .map(({ pr, decision, failed }) => [+ `<a href="${pr.url}">#${pr.number}</a>`,+ authorLogin(pr),+ failed ? `${decision.action} (failed)` : decision.action,+ decision.reasons.join(", "),+ ]);+ await core.summary+ .addHeading(live ? "Stale PR triage" : "Stale PR triage (dry run: no PRs changed)")+ .addRaw(`${results.length} open PRs, ${rows.length} with something outstanding.`, true)+ .addTable([+ [+ { data: "PR", header: true },+ { data: "Author", header: true },+ { data: "Action", header: true },+ { data: "Reasons", header: true },+ ],+ ...rows,+ ])+ .write();+}++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. */+ live: boolean;+ /** Least pause between writes. Defaults to WRITE_INTERVAL_MS. */+ writeIntervalMs?: number;+ /** Pause between mergeability checks. Defaults to MERGEABILITY_RETRY_MS. */+ mergeabilityRetryMs?: number;+}++/**+ * 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.+ */+export default async function triageStalePullRequests({+ github,+ context,+ core,+ live,+ writeIntervalMs = WRITE_INTERVAL_MS,+ mergeabilityRetryMs = MERGEABILITY_RETRY_MS,+}: TriageInputs) {+ const now = Date.now();+ const { repo } = context;+ const results: Result[] = [];+ let failures = 0;++ for (const number of await fetchOpenPullNumbers(github, repo)) {+ const issue = { ...repo, issue_number: number };+ let result: Result | null = null;+ try {+ let pr = await fetchPullRequest(github, repo, number);+ 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);+ }+ 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)) {+ await apply(github, issue, pr, decision, now, writeIntervalMs);+ await sleep(writeIntervalMs);+ }+ results.push(result);+ } catch (error) {+ failures += 1;+ core.error(`#${number}: ${errorMessage(error)}`);+ if (result !== null) results.push({ ...result, failed: true });+ }+ }++ await writeSummary(core, results, live);+ if (failures > 0) core.setFailed(`${failures} PR(s) could not be updated.`);+}diff --git a/.github/scripts/tsconfig.json b/.github/scripts/tsconfig.jsonnew file mode 100644index 0000000000..a9ea9e7ba2--- /dev/null+++ b/.github/scripts/tsconfig.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "es2023",+ "lib": ["es2023"],+ "module": "nodenext",+ "strict": true,+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "erasableSyntaxOnly": true,+ "verbatimModuleSyntax": true,+ "noUncheckedIndexedAccess": true,+ "skipLibCheck": true,+ "types": ["node"]+ },+ "include": ["*.ts"]+}diff --git a/.github/workflows/pr-conflict-labeler.yml b/.github/workflows/pr-conflict-labeler.ymlindex be636913cc..1b09ae3fea 100644--- a/.github/workflows/pr-conflict-labeler.yml+++ b/.github/workflows/pr-conflict-labeler.yml@@ -101,8 +101,15 @@ jobs:}async function labelPullRequest(pull) {+ // Unknown is not resolved: stale-prs.ts reads a removal as the conflict fixed.+ if (pull.mergeable === null) {+ core.info(`PR #${pull.number}: mergeability still unknown; leaving the label as it is.`);+ return;+ }+const existingLabels = pull.labels.map((label) => label.name);const hasConflictLabel = existingLabels.includes(conflictLabel);+ // Must match `conflicting` in .github/scripts/stale-prs.ts.const hasConflicts = pull.mergeable === false && pull.mergeable_state === 'dirty';if (hasConflicts && !hasConflictLabel) {diff --git a/.github/workflows/pr-review-events.yml b/.github/workflows/pr-review-events.ymlnew file mode 100644index 0000000000..b218a81f16--- /dev/null+++ b/.github/workflows/pr-review-events.yml@@ -0,0 +1,38 @@+name: PR review events++# Lets pr-turn-labels.yml react to reviews. A review on a fork PR only gets a+# read-only token here, but the workflow_run it triggers gets a write token.+# Relays every review: pr-turn.ts decides which ones move the turn.++# Carries the PR to pr-turn-labels.yml: must match REVIEW_RUN_TITLE in pr-turn.ts.+run-name: "Review on #${{ github.event.pull_request.number }}"++on:+ pull_request_review:+ types: [submitted, dismissed]+ # A reply to a review thread is not guaranteed a review event of its own.+ pull_request_review_comment:+ types: [created]++permissions: {}++jobs:+ relay:+ name: Relay review event+ # Every inline comment raises this, but only the author's can move the turn.+ if: >-+ github.event_name != 'pull_request_review_comment' ||+ github.event.comment.user.login == github.event.pull_request.user.login+ runs-on: ubuntu-latest+ steps:+ - name: Harden Runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit++ - name: Record the event+ env:+ EVENT: ${{ github.event_name }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ run: |+ echo "$EVENT on #$PR_NUMBER"diff --git a/.github/workflows/pr-turn-labels.yml b/.github/workflows/pr-turn-labels.ymlnew file mode 100644index 0000000000..c0e1d21479--- /dev/null+++ b/.github/workflows/pr-turn-labels.yml@@ -0,0 +1,57 @@+name: PR turn labels++# Adds waiting-on-author on a changes-requested review and removes it on an approval+# or when the PR author responds. The rules live in .github/scripts/pr-turn.ts.+# Reviews arrive through pr-review-events.yml. Runs whatever STALE_PR_BOT_LIVE says:+# a label left stale while the triage is off would date its warning from before.++on:+ workflow_run:+ workflows: ["PR review events"]+ types: [completed]+ pull_request_target:+ types: [synchronize, ready_for_review, review_requested]+ issue_comment:+ types: [created]++permissions:+ contents: read++jobs:+ update:+ name: Update the turn label+ # Skips only events pr-turn.ts would do nothing with: a push, ready, re-request or comment+ # that is not the author's, or on a PR without the label. Must not skip anything+ # turnChangeForEvent acts on.+ if: >-+ vars.CI_PROFILE != 'lite' && (+ (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success') ||+ (github.event.pull_request && github.event.sender.login == github.event.pull_request.user.login &&+ contains(github.event.pull_request.labels.*.name, 'waiting-on-author')) ||+ (github.event.issue.pull_request && github.event.comment.user.login == github.event.issue.user.login &&+ contains(github.event.issue.labels.*.name, 'waiting-on-author'))+ )+ runs-on: ubuntu-latest+ permissions:+ contents: read # actions/checkout+ issues: write # add/remove labels+ pull-requests: write # add/remove labels on PRs+ 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: Update the turn label+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0+ with:+ github-token: ${{ github.token }}+ script: |+ const { updateTurnLabel } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/pr-turn.ts`);+ await updateTurnLabel({ github, context, core });diff --git a/.github/workflows/stale-prs.yml b/.github/workflows/stale-prs.ymlnew file mode 100644index 0000000000..24cddd1244--- /dev/null+++ b/.github/workflows/stale-prs.yml@@ -0,0 +1,110 @@+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.++on:+ schedule:+ - cron: "40 7 * * *"+ workflow_dispatch:+ inputs:+ dry_run:+ description: "Report what would happen without changing any PR"+ type: boolean+ default: true+ pull_request:+ paths:+ - ".github/workflows/stale-prs.yml"+ - ".github/scripts/*.ts"+ - ".github/workflows/pr-turn-labels.yml"+ - ".github/workflows/pr-review-events.yml"+ - ".github/scripts/package.json"+ - ".github/scripts/package-lock.json"+ - ".github/scripts/tsconfig.json"+ - ".github/workflows/pr-conflict-labeler.yml"++permissions:+ contents: read++concurrency:+ group: stale-prs-${{ github.event_name == 'pull_request' && github.event.pull_request.number || 'triage' }}+ cancel-in-progress: false++jobs:+ test:+ name: Test the triage rules+ if: github.event_name == 'pull_request'+ runs-on: ubuntu-latest+ permissions:+ contents: read+ issues: read+ pull-requests: read+ 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++ # Same Node as github-script v9, so the tests load the .ts the way the bot does.+ - name: Set up Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: "24"+ cache: "npm"+ cache-dependency-path: .github/scripts/package-lock.json++ - name: Install TypeScript+ working-directory: .github/scripts+ env:+ NPM_CONFIG_IGNORE_SCRIPTS: "true"+ run: npm ci --ignore-scripts --audit=false --fund=false++ - name: Typecheck+ working-directory: .github/scripts+ run: npx tsc --noEmit++ - name: Run unit tests+ run: node --test .github/scripts/*.test.ts++ - name: Dry run against open PRs+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0+ with:+ script: |+ const { default: triage } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/stale-prs.ts`);+ await triage({ github, context, core, live: false });++ triage:+ name: Warn and close stale PRs+ if: github.event_name != 'pull_request' && vars.CI_PROFILE != 'lite'+ runs-on: ubuntu-latest+ permissions:+ contents: read # actions/checkout+ issues: write # comment on and label PRs+ pull-requests: write # close PRs+ 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: Triage open PRs+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0+ env:+ LIVE: ${{ vars.STALE_PR_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" });diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 371630193b..84c038318e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -4,7 +4,7 @@ Thank you for your interest in contributing to Stirling-PDF! There are many ways## License-By contributing to this project, you agree that your contributions will be licensed under the project [license](LICENSE), which follows an open-core model.+By contributing to this project, you agree that your contributions will be licensed under the project [license](LICENSE), which follows an open-core model.The codebase is a mix of MIT and source-available code, so your contribution is licensed according to the directory it is committed to.PRs are welcome in any directory by any user, just be aware of which license applies to the code you change.@@ -44,6 +44,19 @@ 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](devGuide/CODE_COMMENTS.md); `task comment-lint` checks the mechanical part.+## Stale Pull Requests++To keep the list of open Pull Requests manageable, PRs that appear abandoned will automatically be closed (after a warning).++- When a maintainer requests changes, the Pull Request will be labelled `waiting-on-author`. The label will be removed when you push, comment, reply to the review, etc.+- If a Pull Request that is ready for review has had the `waiting-on-author` or `has conflicts` label for 7 days, the PR will gain the `Stale PR` label.+- If a draft Pull Request has had no activity for 30 days, it will get the `Stale PR` label.+- If the problem is still there 7 days after the warning, the Pull Request will be automatically closed.++A closed Pull Request is not rejected. If you pick it up again, please feel free to open a new Pull Request and address the problem.++If you think a Pull Request is waiting on us rather than on you, say so in a comment.+## TranslationsIf you would like to add or modify a translation, please see [How to add new languages to Stirling-PDF](devGuide/HowToAddNewLanguage.md). Also, please create a Pull Request so others can use it!