diff --git a/.github/scripts/community-pr-followup.mjs b/.github/scripts/community-pr-followup.mjs new file mode 100644 index 0000000..2291e6d --- /dev/null +++ b/.github/scripts/community-pr-followup.mjs @@ -0,0 +1,941 @@ +// Follow-up logic for open community pull requests. .github/workflows/community-pr-followup.yml +// checks out the default branch's copy of this module so fork pull requests never run their own. +import { readFileSync } from "node:fs"; + +export const DAY_MS = 24 * 60 * 60 * 1000; + +export const POLICY = { + maintainerReminderDays: 4, + authorNudgeDays: 7, + authorCloseAfterNudgeDays: 7, + draftNudgeDays: 14, + draftCloseAfterNudgeDays: 14, +}; + +export const LABELS = { + waitingForAuthor: { + name: "waiting-for-author", + color: "d4c5f9", + description: "Waiting for changes or a reply from the pull request author", + }, + needsReview: { + name: "needs-review", + color: "fbca04", + description: "Community pull request waiting for a maintainer", + }, + keepOpen: "keep-open", +}; + +const TEAM_ASSOCIATIONS = new Set(["OWNER", "MEMBER", "COLLABORATOR"]); +const DECISIVE_REVIEW_STATES = new Set(["APPROVED", "CHANGES_REQUESTED", "DISMISSED"]); +const FAILING_CHECK_CONCLUSIONS = new Set(["FAILURE", "TIMED_OUT", "STARTUP_FAILURE"]); +const FAILING_STATUS_STATES = new Set(["FAILURE", "ERROR"]); +const MARKER_PREFIX = "\s*$/; +// The workflow comments as GitHub Actions (its GraphQL and REST logins). Only its markers count: +// anyone can get another bot, such as CodeRabbit, to repeat text. +const FOLLOWUP_BOT_LOGINS = new Set(["github-actions", "github-actions[bot]"]); + +const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`; + +/** Inline code span that neutralizes markdown, HTML and mentions in untrusted names. */ +function code(text, limit = 120) { + const cleaned = Array.from(String(text ?? "").replace(/\s+/g, " ").trim()); + const cut = cleaned.length <= limit ? cleaned.join("") : `${cleaned.slice(0, limit - 1).join("")}…`; + return `\`${cut.replaceAll("`", "'") || " "}\``; +} + +/** Safe JSON embedded inside an HTML comment so no value can terminate the comment early. */ +function encodeMarker(data) { + const json = JSON.stringify(data).replace(/[<>&]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`); + return `${MARKER_PREFIX}${json} -->`; +} + +/** Valid GitHub login (without `@`) formatted as a mention. */ +function mention(login) { + return typeof login === "string" && /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(login) ? `@${login}` : null; +} + +function parseTime(value) { + if (!value) return null; + const ms = Date.parse(value); + return Number.isFinite(ms) ? ms : null; +} + +function maxTime(...values) { + let latest = null; + for (const value of values) { + const ms = typeof value === "number" ? value : parseTime(value); + if (ms !== null && (latest === null || ms > latest)) latest = ms; + } + return latest; +} + +function minTime(...values) { + let earliest = null; + for (const value of values) { + const ms = typeof value === "number" ? value : parseTime(value); + if (ms !== null && (earliest === null || ms < earliest)) earliest = ms; + } + return earliest; +} + +/** Whether a GraphQL or REST user object represents a bot account. */ +export function isBotUser(user) { + if (!user) return true; + if (user.__typename === "Bot" || user.type === "Bot") return true; + const login = String(user.login ?? ""); + return login === "" || /\[bot\]$/i.test(login); +} + +/** A bot account that is still there: a deleted account's comments have no author and prove nothing. */ +function isReviewBot(user) { + return Boolean(user?.login) && isBotUser(user); +} + +/** Community contributors are non-bot accounts outside OWNER, MEMBER and COLLABORATOR. */ +export function isCommunityAuthor(author, authorAssociation) { + if (isBotUser(author)) return false; + return !TEAM_ASSOCIATIONS.has(authorAssociation); +} + +export function isTeamMember(author, authorAssociation) { + if (isBotUser(author)) return false; + return TEAM_ASSOCIATIONS.has(authorAssociation); +} + +/** Reads default fallback reviewers from the `*` rule in `.github/CODEOWNERS`. */ +export function defaultCodeowners(codeownersText) { + const text = codeownersText ?? readFileSync(new URL("../CODEOWNERS", import.meta.url), "utf8"); + const owners = []; + for (const rawLine of text.split(/\r?\n/)) { + const line = rawLine.replace(/#.*$/, "").trim(); + if (!line) continue; + const parts = line.split(/\s+/); + if (parts[0] === "*") { + for (const token of parts.slice(1)) { + if (token.startsWith("@") && !token.includes("/")) { + const login = token.slice(1); + if (mention(login) && !owners.includes(login)) owners.push(login); + } + } + } + } + return owners; +} + +/** Parses our own follow-up marker from a bot comment, preferring GitHub's publication timestamp. */ +export function readFollowupMarker(comment) { + const actor = comment?.author ?? comment?.user; + if (!actor || !isBotUser(actor) || !FOLLOWUP_BOT_LOGINS.has(actor.login)) return null; + const match = String(comment.body ?? "").match(MARKER_PATTERN); + if (!match) return null; + try { + const data = JSON.parse(match[1]); + if (!data || typeof data !== "object" || typeof data.kind !== "string") return null; + const at = parseTime(comment.createdAt ?? comment.created_at) ?? parseTime(data.at); + return { ...data, at }; + } catch { + return null; + } +} + +/** Summarizes the head commit's check runs and commit statuses, keeping the newest entry per name. */ +export function analyzeChecks(contexts = []) { + const latestRuns = new Map(); + const latestStatuses = new Map(); + + for (const item of contexts) { + if (!item) continue; + if (item.__typename === "CheckRun" || "conclusion" in item) { + const name = item.name; + if (!name) continue; + const ts = maxTime(item.completedAt, item.startedAt) ?? 0; + const prev = latestRuns.get(name); + if (!prev || ts >= prev.ts) latestRuns.set(name, { item, ts }); + } else if (item.__typename === "StatusContext" || "context" in item) { + const name = item.context; + if (!name) continue; + const ts = parseTime(item.createdAt) ?? 0; + const prev = latestStatuses.get(name); + if (!prev || ts >= prev.ts) latestStatuses.set(name, { item, ts }); + } + } + + const failingChecks = []; + + for (const [name, { item }] of latestRuns) { + if (item.status === "COMPLETED" && FAILING_CHECK_CONCLUSIONS.has(item.conclusion)) { + failingChecks.push(name); + } + } + + for (const [name, { item }] of latestStatuses) { + if (FAILING_STATUS_STATES.has(String(item.state ?? "").toUpperCase())) { + failingChecks.push(name); + } + } + + failingChecks.sort(); + return { failingChecks }; +} + +/** + * Classifies an open community PR's current state, whose court the ball is in, the relevant + * blockers/reasons, and the timestamps that govern follow-up and closing windows. + */ +export function evaluatePullRequest(pr, { now, policy = POLICY, fallbackReviewers = [] } = {}) { + const labels = (pr.labels ?? []).map((label) => (typeof label === "string" ? label : label.name)); + const hasLabel = (name) => labels.includes(name); + + if (!isCommunityAuthor(pr.author, pr.authorAssociation)) { + return { action: "skip", reason: "not-community", labelsToAdd: [], labelsToRemove: [] }; + } + + if (hasLabel(LABELS.keepOpen)) { + return { action: "skip", reason: "keep-open", labelsToAdd: [], labelsToRemove: [] }; + } + + const authorLogin = pr.author.login.toLowerCase(); + const isAuthor = (user) => !isBotUser(user) && user?.login?.toLowerCase() === authorLogin; + + // GitHub no longer populates Commit.pushedDate, so also use the earliest check-suite or check-run + // timestamp on the head commit (immutable across reruns) to detect fast-forward pushes of older commits. + const firstHeadCheckAt = minTime( + ...(pr.headCommit?.checkSuiteCreatedAts ?? []), + ...(pr.statusContexts ?? []).map((item) => (item?.__typename === "CheckRun" || "conclusion" in (item ?? {}) ? item.startedAt : item?.createdAt)), + ); + const headCommitAt = maxTime(pr.headCommit?.pushedDate, pr.headCommit?.committedDate, pr.headCommit?.authoredDate, firstHeadCheckAt); + const timelineAt = maxTime(...(pr.timelineDates ?? [])); + + let lastAuthorCommentAt = null; + let lastHumanCommentAt = null; + let lastAuthorNudge = null; + let lastMaintainerReminder = null; + + for (const comment of pr.comments ?? []) { + const marker = readFollowupMarker(comment); + if (marker) { + if (marker.kind === "author-nudge" && (!lastAuthorNudge || (marker.at ?? 0) >= (lastAuthorNudge.at ?? 0))) { + lastAuthorNudge = marker; + } else if ( + marker.kind === "maintainer-reminder" + && (!lastMaintainerReminder || (marker.at ?? 0) >= (lastMaintainerReminder.at ?? 0)) + ) { + lastMaintainerReminder = marker; + } + continue; + } + if (isBotUser(comment.author)) continue; + const at = parseTime(comment.createdAt); + lastHumanCommentAt = maxTime(lastHumanCommentAt, at); + if (isAuthor(comment.author)) lastAuthorCommentAt = maxTime(lastAuthorCommentAt, at); + } + + // Track latest decisive human maintainer review per reviewer, including DISMISSED so dismissed + // change requests no longer block. + const latestMaintainerReview = new Map(); + let lastHumanReviewAt = null; + let lastAuthorReviewAt = null; + + for (const review of pr.reviews ?? []) { + if (isBotUser(review.author)) continue; + const at = parseTime(review.submittedAt); + lastHumanReviewAt = maxTime(lastHumanReviewAt, at); + if (isAuthor(review.author)) lastAuthorReviewAt = maxTime(lastAuthorReviewAt, at); + if (isTeamMember(review.author, review.authorAssociation) && DECISIVE_REVIEW_STATES.has(review.state)) { + const login = review.author.login; + const prev = latestMaintainerReview.get(login); + if (!prev || (at ?? 0) >= (prev.at ?? 0)) { + latestMaintainerReview.set(login, { state: review.state, at, login }); + } + } + } + + // An unresolved thread waits on the author when the newest comment that counts came from the team + // or a review bot, and on maintainers when it came from the author, picked by createdAt rather + // than array order. The author's and the team's comments count, and a bot's only when it opened + // the thread: anyone can get a bot to reply. Nobody outside the team can put a pull request on + // its author and get it closed. + let unresolvedAuthorThreads = 0; + let unresolvedMaintainerThreads = 0; + let lastAuthorThreadAt = null; + let lastHumanThreadAt = null; + + for (const thread of pr.reviewThreads ?? []) { + const threadComments = thread.comments ?? []; + const opener = threadComments.reduce((first, c) => (first === null + || (parseTime(c.createdAt) ?? Infinity) < (parseTime(first.createdAt) ?? Infinity) ? c : first), null); + let latestComment = null; + let latestCommentAt = null; + for (const c of threadComments) { + const at = parseTime(c.createdAt); + const fromAuthor = isAuthor(c.author); + if (!isBotUser(c.author)) lastHumanThreadAt = maxTime(lastHumanThreadAt, at); + if (fromAuthor) lastAuthorThreadAt = maxTime(lastAuthorThreadAt, at); + const counts = fromAuthor || isTeamMember(c.author, c.authorAssociation) || (c === opener && isReviewBot(c.author)); + if (!counts) continue; + if (latestComment === null || (at ?? -Infinity) >= (latestCommentAt ?? -Infinity)) { + latestComment = c; + latestCommentAt = at; + } + } + if (thread.isResolved || !latestComment) continue; + if (isAuthor(latestComment.author)) { + unresolvedMaintainerThreads += 1; + } else { + unresolvedAuthorThreads += 1; + } + } + + const createdAt = parseTime(pr.createdAt); + const lastAuthorActivityAt = maxTime(createdAt, headCommitAt, timelineAt, lastAuthorCommentAt, lastAuthorReviewAt, lastAuthorThreadAt); + const lastHumanActivityAt = maxTime(lastAuthorActivityAt, lastHumanCommentAt, lastHumanReviewAt, lastHumanThreadAt); + + if (pr.isDraft) { + const labelsToRemove = hasLabel(LABELS.needsReview.name) ? [LABELS.needsReview.name] : []; + const activeNudge = lastAuthorNudge + && lastAuthorNudge.draft === true + && lastAuthorNudge.headSha === pr.headRefOid + && (lastAuthorNudge.at ?? 0) >= lastHumanActivityAt + ? lastAuthorNudge + : null; + + if (activeNudge) { + const daysSinceNudge = (now - activeNudge.at) / DAY_MS; + if (daysSinceNudge >= policy.draftCloseAfterNudgeDays) { + return { + action: "close-author", + court: "author", + isDraft: true, + blockers: ["draft"], + daysIdle: Math.floor((now - lastHumanActivityAt) / DAY_MS), + daysSinceNudge: Math.floor(daysSinceNudge), + labelsToAdd: [], + labelsToRemove, + }; + } + return { + action: "wait", + reason: "already-nudged-draft", + court: "author", + isDraft: true, + blockers: ["draft"], + labelsToAdd: hasLabel(LABELS.waitingForAuthor.name) ? [] : [LABELS.waitingForAuthor.name], + labelsToRemove, + }; + } + + if (hasLabel(LABELS.waitingForAuthor.name)) labelsToRemove.push(LABELS.waitingForAuthor.name); + const daysIdle = (now - lastHumanActivityAt) / DAY_MS; + if (daysIdle >= policy.draftNudgeDays) { + return { + action: "nudge-author", + court: "author", + isDraft: true, + blockers: ["draft"], + daysIdle: Math.floor(daysIdle), + closeInDays: policy.draftCloseAfterNudgeDays, + labelsToAdd: hasLabel(LABELS.waitingForAuthor.name) ? [] : [LABELS.waitingForAuthor.name], + labelsToRemove: labelsToRemove.filter((name) => name !== LABELS.waitingForAuthor.name), + }; + } + return { + action: "none", + court: "author", + isDraft: true, + blockers: ["draft"], + labelsToAdd: [], + labelsToRemove, + }; + } + + const { failingChecks } = analyzeChecks(pr.statusContexts ?? []); + const changesRequestedReviews = [...latestMaintainerReview.values()].filter((r) => r.state === "CHANGES_REQUESTED"); + const latestChangesRequestedAt = maxTime(...changesRequestedReviews.map((r) => r.at)); + const authorUpdatedAfterChangesRequested = latestChangesRequestedAt !== null + && maxTime(headCommitAt, lastAuthorCommentAt, lastAuthorThreadAt) > latestChangesRequestedAt; + const changesRequestedPendingAuthor = changesRequestedReviews.length > 0 && !authorUpdatedAfterChangesRequested; + + const authorBlockers = []; + if (failingChecks.length > 0) authorBlockers.push({ kind: "failing-checks", checks: failingChecks }); + if (pr.mergeable === "CONFLICTING") authorBlockers.push({ kind: "merge-conflicts" }); + if (changesRequestedPendingAuthor) authorBlockers.push({ kind: "changes-requested" }); + if (unresolvedAuthorThreads > 0) authorBlockers.push({ kind: "unresolved-threads", count: unresolvedAuthorThreads }); + + if (authorBlockers.length > 0) { + const labelsToRemove = hasLabel(LABELS.needsReview.name) ? [LABELS.needsReview.name] : []; + const activeNudge = lastAuthorNudge + && lastAuthorNudge.draft === false + && lastAuthorNudge.headSha === pr.headRefOid + && (lastAuthorNudge.at ?? 0) >= lastHumanActivityAt + ? lastAuthorNudge + : null; + + if (activeNudge) { + const daysSinceNudge = (now - activeNudge.at) / DAY_MS; + if (daysSinceNudge >= policy.authorCloseAfterNudgeDays) { + return { + action: "close-author", + court: "author", + isDraft: false, + blockers: authorBlockers, + daysIdle: Math.floor((now - lastHumanActivityAt) / DAY_MS), + daysSinceNudge: Math.floor(daysSinceNudge), + labelsToAdd: [], + labelsToRemove, + }; + } + return { + action: "wait", + reason: "already-nudged", + court: "author", + isDraft: false, + blockers: authorBlockers, + labelsToAdd: hasLabel(LABELS.waitingForAuthor.name) ? [] : [LABELS.waitingForAuthor.name], + labelsToRemove, + }; + } + + if (hasLabel(LABELS.waitingForAuthor.name)) labelsToRemove.push(LABELS.waitingForAuthor.name); + const daysIdle = (now - lastHumanActivityAt) / DAY_MS; + if (daysIdle >= policy.authorNudgeDays) { + return { + action: "nudge-author", + court: "author", + isDraft: false, + blockers: authorBlockers, + daysIdle: Math.floor(daysIdle), + closeInDays: policy.authorCloseAfterNudgeDays, + labelsToAdd: hasLabel(LABELS.waitingForAuthor.name) ? [] : [LABELS.waitingForAuthor.name], + labelsToRemove: labelsToRemove.filter((name) => name !== LABELS.waitingForAuthor.name), + }; + } + + return { + action: "none", + court: "author", + isDraft: false, + blockers: authorBlockers, + labelsToAdd: [], + labelsToRemove, + }; + } + + const labelsToRemove = hasLabel(LABELS.waitingForAuthor.name) ? [LABELS.waitingForAuthor.name] : []; + const maintainerReasons = []; + if (pr.awaitingWorkflowApproval) maintainerReasons.push("workflow-approval"); + if (changesRequestedReviews.length > 0 && authorUpdatedAfterChangesRequested) maintainerReasons.push("re-review"); + if (unresolvedMaintainerThreads > 0) maintainerReasons.push("thread-reply"); + if (maintainerReasons.length === 0) maintainerReasons.push("review"); + + const reviewersToPing = selectReviewersToPing(pr, latestMaintainerReview, fallbackReviewers); + const activeReminder = lastMaintainerReminder + && (!lastMaintainerReminder.headSha || lastMaintainerReminder.headSha === pr.headRefOid) + && (lastMaintainerReminder.at ?? 0) >= lastHumanActivityAt + ? lastMaintainerReminder + : null; + + if (activeReminder) { + return { + action: "wait", + reason: "already-reminded-maintainers", + court: "maintainer", + isDraft: false, + maintainerReasons, + reviewersToPing, + labelsToAdd: hasLabel(LABELS.needsReview.name) ? [] : [LABELS.needsReview.name], + labelsToRemove, + }; + } + + const daysIdle = (now - lastHumanActivityAt) / DAY_MS; + if (daysIdle >= policy.maintainerReminderDays) { + return { + action: "remind-maintainers", + court: "maintainer", + isDraft: false, + maintainerReasons, + reviewersToPing, + daysIdle: Math.floor(daysIdle), + labelsToAdd: hasLabel(LABELS.needsReview.name) ? [] : [LABELS.needsReview.name], + labelsToRemove, + }; + } + + if (hasLabel(LABELS.needsReview.name)) labelsToRemove.push(LABELS.needsReview.name); + + return { + action: "none", + court: "maintainer", + isDraft: false, + maintainerReasons, + reviewersToPing, + labelsToAdd: [], + labelsToRemove, + }; +} + +function selectReviewersToPing(pr, latestMaintainerReview, fallbackReviewers) { + const requested = (pr.requestedReviewers ?? []).filter((login) => mention(login)); + if (requested.length > 0) return [...new Set(requested)]; + const priorMaintainers = [...latestMaintainerReview.keys()].filter((login) => mention(login)); + if (priorMaintainers.length > 0) return [...new Set(priorMaintainers)]; + return [...new Set((fallbackReviewers ?? []).filter((login) => mention(login)))]; +} + +function formatBlockerBullet(blocker) { + switch (blocker.kind) { + case "failing-checks": + return `- Failing ${blocker.checks.length === 1 ? "check" : "checks"}: ${blocker.checks.map((name) => code(name)).join(", ")}`; + case "merge-conflicts": + return "- Merge conflicts with the base branch"; + case "changes-requested": + return "- Changes were requested in review"; + case "unresolved-threads": + return `- ${plural(blocker.count, "unresolved review thread")}`; + default: + return null; + } +} + +function formatMaintainerReasonBullet(reason) { + switch (reason) { + case "workflow-approval": + return "- First-time contributor workflow runs are waiting for approval to run"; + case "re-review": + return "- The author pushed an update or replied after requested changes"; + case "thread-reply": + return "- The author replied in an unresolved review thread"; + case "review": + return "- Ready for review"; + default: + return null; + } +} + +export function formatAuthorNudgeComment({ authorLogin, headSha, isDraft, blockers, daysIdle, closeInDays, now }) { + const authorRef = mention(authorLogin) ?? "there"; + const marker = encodeMarker({ kind: "author-nudge", headSha, draft: Boolean(isDraft), at: new Date(now).toISOString() }); + + if (isDraft) { + return [ + `Hi ${authorRef}, checking in on this draft pull request — it has been quiet for ${plural(daysIdle, "day")}.`, + "", + `If you're still working on it, push a commit, leave a comment, or mark it ready for review whenever you're ready. Without an update, this draft will close automatically in ${plural(closeInDays, "day")} (you can always reopen it later). Maintainers can add \`${LABELS.keepOpen}\` to pause follow-ups.`, + "", + marker, + ].join("\n"); + } + + const bullets = blockers.map(formatBlockerBullet).filter(Boolean); + return [ + `Hi ${authorRef}, checking in on this pull request — it has been quiet for ${plural(daysIdle, "day")} and is waiting on updates before it can move forward:`, + "", + ...bullets, + "", + `If you're still working on it, push an update or leave a comment whenever you're ready. Without an update, this pull request will close automatically in ${plural(closeInDays, "day")} (you can always reopen it later). Maintainers can add \`${LABELS.keepOpen}\` to pause follow-ups.`, + "", + marker, + ].join("\n"); +} + +export function formatAuthorCloseComment({ headSha, isDraft, daysSinceNudge, now }) { + const marker = encodeMarker({ kind: "author-close", headSha, draft: Boolean(isDraft), at: new Date(now).toISOString() }); + const kind = isDraft ? "draft pull request" : "pull request"; + return [ + `Closing this ${kind} for now since there hasn't been an update since the follow-up ${plural(daysSinceNudge, "day")} ago.`, + "", + "Thanks for the contribution — feel free to reopen it or open a fresh pull request whenever you have time to pick it back up.", + "", + marker, + ].join("\n"); +} + +export function formatMaintainerReminderComment({ headSha, reviewersToPing, maintainerReasons, daysIdle, now }) { + const marker = encodeMarker({ kind: "maintainer-reminder", headSha, at: new Date(now).toISOString() }); + const pings = reviewersToPing.map(mention).filter(Boolean); + const greeting = pings.length > 0 ? `Friendly reminder for ${pings.join(" ")}:` : "Friendly reminder for maintainers:"; + const bullets = maintainerReasons.map(formatMaintainerReasonBullet).filter(Boolean); + return [ + `${greeting} this community pull request has been waiting on a maintainer for ${plural(daysIdle, "day")}.`, + "", + ...bullets, + "", + marker, + ].join("\n"); +} + +const PR_FIELDS = ` + number + state + title + isDraft + createdAt + mergeable + authorAssociation + author { __typename login } + headRefOid + headRefName + headRepository { nameWithOwner } + labels(first: 50) { nodes { name } } + reviewRequests(first: 20) { + nodes { + requestedReviewer { + ... on User { login } + } + } + } + commits(last: 1) { + nodes { + commit { + oid + authoredDate + committedDate + pushedDate + checkSuites(first: 10) { + nodes { createdAt } + } + statusCheckRollup { + contexts(first: 100) { + nodes { + __typename + ... on CheckRun { name status conclusion startedAt completedAt } + ... on StatusContext { context state description createdAt } + } + } + } + } + } + } + timelineItems(last: 30, itemTypes: [READY_FOR_REVIEW_EVENT, CONVERT_TO_DRAFT_EVENT, REOPENED_EVENT, HEAD_REF_FORCE_PUSHED_EVENT]) { + nodes { + __typename + ... on ReadyForReviewEvent { createdAt } + ... on ConvertToDraftEvent { createdAt } + ... on ReopenedEvent { createdAt } + ... on HeadRefForcePushedEvent { createdAt } + } + } + reviews(last: 50) { + nodes { + author { __typename login } + authorAssociation + state + submittedAt + } + } + reviewThreads(first: 100) { + nodes { + id + isResolved + comments(first: 20) { + pageInfo { hasNextPage endCursor } + nodes { + author { __typename login } + authorAssociation + createdAt + } + } + } + } + comments(last: 100) { + nodes { + author { __typename login } + authorAssociation + body + createdAt + } + } +`; + +const OPEN_PRS_QUERY = ` +query($owner: String!, $repo: String!, $cursor: String) { + repository(owner: $owner, name: $repo) { + pullRequests(states: OPEN, first: 25, after: $cursor, orderBy: { field: CREATED_AT, direction: ASC }) { + pageInfo { hasNextPage endCursor } + nodes { ${PR_FIELDS} } + } + } +}`; + +const SINGLE_PR_QUERY = ` +query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { ${PR_FIELDS} } + } +}`; + +const THREAD_COMMENTS_QUERY = ` +query($threadId: ID!, $cursor: String!) { + node(id: $threadId) { + ... on PullRequestReviewThread { + comments(first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + author { __typename login } + authorAssociation + createdAt + } + } + } + } +}`; + +function normalizeGraphQLPullRequest(node) { + const headCommit = node.commits?.nodes?.[0]?.commit ?? null; + return { + number: node.number, + state: node.state ?? "OPEN", + title: node.title, + isDraft: node.isDraft, + createdAt: node.createdAt, + mergeable: node.mergeable, + authorAssociation: node.authorAssociation, + author: node.author, + headRefOid: node.headRefOid, + headRefName: node.headRefName, + headRepository: node.headRepository?.nameWithOwner ?? null, + labels: (node.labels?.nodes ?? []).map((l) => l.name), + requestedReviewers: (node.reviewRequests?.nodes ?? []).map((r) => r.requestedReviewer?.login).filter(Boolean), + headCommit: headCommit ? { + oid: headCommit.oid, + authoredDate: headCommit.authoredDate, + committedDate: headCommit.committedDate, + pushedDate: headCommit.pushedDate, + checkSuiteCreatedAts: (headCommit.checkSuites?.nodes ?? []).map((suite) => suite?.createdAt).filter(Boolean), + } : null, + statusContexts: headCommit?.statusCheckRollup?.contexts?.nodes ?? [], + timelineDates: (node.timelineItems?.nodes ?? []).map((item) => item?.createdAt).filter(Boolean), + reviews: node.reviews?.nodes ?? [], + reviewThreads: (node.reviewThreads?.nodes ?? []).map((thread) => ({ + id: thread.id ?? null, + isResolved: thread.isResolved, + comments: [...(thread.comments?.nodes ?? [])], + commentsPageInfo: thread.comments?.pageInfo ?? { hasNextPage: false, endCursor: null }, + })), + comments: node.comments?.nodes ?? [], + }; +} + +/** Fetches remaining comments on any review thread that exceeded the initial page. */ +async function hydrateThreadComments({ github, pr }) { + for (const thread of pr.reviewThreads ?? []) { + if (!thread.id || !thread.commentsPageInfo?.hasNextPage) continue; + let cursor = thread.commentsPageInfo.endCursor; + while (cursor) { + const data = await github.graphql(THREAD_COMMENTS_QUERY, { threadId: thread.id, cursor }); + const page = data?.node?.comments; + if (!page) break; + thread.comments.push(...(page.nodes ?? [])); + cursor = page.pageInfo?.hasNextPage ? page.pageInfo.endCursor : null; + } + thread.commentsPageInfo = { hasNextPage: false, endCursor: null }; + } +} + +async function hasActionRequiredWorkflowRuns({ github, owner, repo, pr }) { + if (!pr.headRefOid) return false; + const { data } = await github.rest.actions.listWorkflowRunsForRepo({ + owner, + repo, + head_sha: pr.headRefOid, + status: "action_required", + per_page: 20, + }); + return (data.workflow_runs ?? []).some((run) => run.event === "pull_request" + && (!pr.headRefName || run.head_branch === pr.headRefName) + && (!pr.headRepository || !run.head_repository?.full_name || run.head_repository.full_name === pr.headRepository)); +} + +async function hydrateCommunityPullRequest({ github, owner, repo, pr }) { + await hydrateThreadComments({ github, pr }); + if (!pr.isDraft && !pr.labels.includes(LABELS.keepOpen)) { + pr.awaitingWorkflowApproval = await hasActionRequiredWorkflowRuns({ github, owner, repo, pr }); + } +} + +async function fetchSinglePullRequest({ github, owner, repo, number }) { + const data = await github.graphql(SINGLE_PR_QUERY, { owner, repo, number }); + const node = data?.repository?.pullRequest; + if (!node) return null; + const pr = normalizeGraphQLPullRequest(node); + if (pr.state === "OPEN" && isCommunityAuthor(pr.author, pr.authorAssociation)) { + await hydrateCommunityPullRequest({ github, owner, repo, pr }); + } + return pr; +} + +async function ensureLabel({ github, owner, repo, labelSpec, knownLabels }) { + if (knownLabels.has(labelSpec.name)) return; + try { + await github.rest.issues.createLabel({ + owner, + repo, + name: labelSpec.name, + color: labelSpec.color, + description: labelSpec.description, + }); + } catch (error) { + if (error?.status !== 422) throw error; + } + knownLabels.add(labelSpec.name); +} + +async function listOpenPullRequests({ github, owner, repo }) { + const prs = []; + let cursor = null; + do { + const data = await github.graphql(OPEN_PRS_QUERY, { owner, repo, cursor }); + const connection = data.repository.pullRequests; + for (const node of connection.nodes) prs.push(normalizeGraphQLPullRequest(node)); + cursor = connection.pageInfo.hasNextPage ? connection.pageInfo.endCursor : null; + } while (cursor); + return prs; +} + +async function applyLabelChanges({ github, owner, repo, number, labelsToAdd, labelsToRemove, labelSpecsByName, knownLabels }) { + for (const labelName of labelsToAdd ?? []) { + const spec = labelSpecsByName.get(labelName); + if (spec) await ensureLabel({ github, owner, repo, labelSpec: spec, knownLabels }); + } + if ((labelsToAdd ?? []).length > 0) { + await github.rest.issues.addLabels({ owner, repo, issue_number: number, labels: labelsToAdd }); + } + for (const labelName of labelsToRemove ?? []) { + try { + await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: labelName }); + } catch (error) { + if (error?.status !== 404) throw error; + } + } +} + +/** + * Runs the daily follow-up sweep across open community pull requests (or a single PR if `pullRequestNumber` is set). + * Catches and records per-PR errors so one failing PR does not block follow-ups on the rest. + */ +export async function runSweep({ github, context, core, dryRun = false, pullRequestNumber = null, now = Date.now(), fallbackReviewers = defaultCodeowners() }) { + const { owner, repo } = context.repo; + const allOpen = await listOpenPullRequests({ github, owner, repo }); + const targets = pullRequestNumber ? allOpen.filter((pr) => pr.number === Number(pullRequestNumber)) : allOpen; + const labelSpecsByName = new Map([ + [LABELS.waitingForAuthor.name, LABELS.waitingForAuthor], + [LABELS.needsReview.name, LABELS.needsReview], + ]); + const knownLabels = new Set(); + const results = []; + + for (const pr of targets) { + if (!isCommunityAuthor(pr.author, pr.authorAssociation)) { + results.push({ number: pr.number, action: "skip", reason: "not-community" }); + continue; + } + + try { + await hydrateCommunityPullRequest({ github, owner, repo, pr }); + let activePr = pr; + let decision = evaluatePullRequest(activePr, { now, fallbackReviewers }); + + const summary = `#${activePr.number} (${activePr.author.login}): ${decision.action}` + + (decision.court ? ` [court=${decision.court}]` : "") + + (decision.reason ? ` (${decision.reason})` : ""); + core.info(dryRun ? `[dry-run] ${summary}` : summary); + + if (dryRun) { + results.push({ number: activePr.number, ...decision }); + continue; + } + + // Re-verify live PR state right before nudging or closing so concurrent pushes, replies or + // keep-open labels are never overridden by the earlier bulk snapshot. + if (decision.action === "nudge-author" || decision.action === "close-author") { + const expectedAction = decision.action; + const fresh = await fetchSinglePullRequest({ github, owner, repo, number: activePr.number }); + const freshDecision = fresh && fresh.state === "OPEN" + ? evaluatePullRequest(fresh, { now, fallbackReviewers }) + : null; + if (!fresh || fresh.state !== "OPEN" || fresh.headRefOid !== activePr.headRefOid || freshDecision?.action !== expectedAction) { + core.info(`#${activePr.number}: skipped ${expectedAction} because PR state changed before write.`); + results.push({ number: activePr.number, action: "skip", reason: "state-changed" }); + continue; + } + activePr = fresh; + decision = freshDecision; + } + + await applyLabelChanges({ + github, + owner, + repo, + number: activePr.number, + labelsToAdd: decision.labelsToAdd, + labelsToRemove: decision.labelsToRemove, + labelSpecsByName, + knownLabels, + }); + + if (decision.action === "nudge-author") { + const body = formatAuthorNudgeComment({ + authorLogin: activePr.author.login, + headSha: activePr.headRefOid, + isDraft: activePr.isDraft, + blockers: decision.blockers, + daysIdle: decision.daysIdle, + closeInDays: decision.closeInDays, + now, + }); + await github.rest.issues.createComment({ owner, repo, issue_number: activePr.number, body }); + } else if (decision.action === "close-author") { + // Close before posting the closure notice so a failed close never leaves a misleading notice on an open PR. + await github.rest.pulls.update({ owner, repo, pull_number: activePr.number, state: "closed" }); + const body = formatAuthorCloseComment({ + headSha: activePr.headRefOid, + isDraft: activePr.isDraft, + daysSinceNudge: decision.daysSinceNudge, + now, + }); + await github.rest.issues.createComment({ owner, repo, issue_number: activePr.number, body }); + } else if (decision.action === "remind-maintainers") { + const body = formatMaintainerReminderComment({ + headSha: activePr.headRefOid, + reviewersToPing: decision.reviewersToPing, + maintainerReasons: decision.maintainerReasons, + daysIdle: decision.daysIdle, + now, + }); + await github.rest.issues.createComment({ owner, repo, issue_number: activePr.number, body }); + } + + results.push({ number: activePr.number, ...decision }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + (core.warning ?? core.info)(`#${pr.number}: follow-up failed: ${message}`); + results.push({ number: pr.number, action: "error", error: message }); + } + } + + return results; +} + +/** + * Clears `waiting-for-author` immediately when a community contributor pushes, reopens, or marks ready. + */ +export async function clearWaitingLabel({ github, context, core }) { + const { owner, repo } = context.repo; + const pr = context.payload.pull_request; + if (!pr || !isCommunityAuthor(pr.user, pr.author_association)) return false; + if (!(pr.labels ?? []).some((label) => label.name === LABELS.waitingForAuthor.name)) return false; + // Someone else's push, such as a maintainer's, isn't the update the author was asked for. + if (context.payload.action === "synchronize" && context.payload.sender?.login?.toLowerCase() !== pr.user.login.toLowerCase()) { + return false; + } + try { + await github.rest.issues.removeLabel({ owner, repo, issue_number: pr.number, name: LABELS.waitingForAuthor.name }); + core.info(`Removed ${LABELS.waitingForAuthor.name} from #${pr.number} after ${context.payload.action}.`); + return true; + } catch (error) { + if (error?.status === 404) return false; + throw error; + } +} diff --git a/.github/scripts/community-pr-followup.test.mjs b/.github/scripts/community-pr-followup.test.mjs new file mode 100644 index 0000000..2b534be --- /dev/null +++ b/.github/scripts/community-pr-followup.test.mjs @@ -0,0 +1,816 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { + DAY_MS, + LABELS, + analyzeChecks, + clearWaitingLabel, + defaultCodeowners, + evaluatePullRequest, + formatAuthorCloseComment, + formatAuthorNudgeComment, + formatMaintainerReminderComment, + isCommunityAuthor, + readFollowupMarker, + runSweep, +} from "./community-pr-followup.mjs"; + +const BASE_TIME = Date.parse("2026-11-26T09:23:00Z"); +const daysAgo = (days) => new Date(BASE_TIME - days * DAY_MS).toISOString(); + +function makePR(overrides = {}) { + return { + number: 100, + state: "OPEN", + title: "fix: sample community change", + isDraft: false, + createdAt: daysAgo(10), + mergeable: "MERGEABLE", + authorAssociation: "FIRST_TIME_CONTRIBUTOR", + author: { __typename: "User", login: "alice" }, + headRefOid: "abc1234", + headRefName: "fix/sample", + headRepository: "alice/stablebar-packages", + labels: [], + requestedReviewers: ["Seb-GRAF"], + headCommit: { oid: "abc1234", pushedDate: daysAgo(10), committedDate: daysAgo(10) }, + statusContexts: [ + { __typename: "CheckRun", name: "Test", status: "COMPLETED", conclusion: "SUCCESS", completedAt: daysAgo(10) }, + ], + timelineDates: [], + reviews: [], + reviewThreads: [], + comments: [], + awaitingWorkflowApproval: false, + ...overrides, + }; +} + +function botComment(body, createdAt) { + return { author: { __typename: "Bot", login: "github-actions" }, authorAssociation: "NONE", body, createdAt }; +} + +test("isCommunityAuthor excludes team members and bots", () => { + assert.equal(isCommunityAuthor({ __typename: "User", login: "alice" }, "FIRST_TIME_CONTRIBUTOR"), true); + assert.equal(isCommunityAuthor({ __typename: "User", login: "bob" }, "CONTRIBUTOR"), true); + assert.equal(isCommunityAuthor({ __typename: "User", login: "carol" }, "NONE"), true); + + assert.equal(isCommunityAuthor({ __typename: "User", login: "Seb-GRAF" }, "OWNER"), false); + assert.equal(isCommunityAuthor({ __typename: "User", login: "M4n0x" }, "COLLABORATOR"), false); + assert.equal(isCommunityAuthor({ __typename: "User", login: "member" }, "MEMBER"), false); + assert.equal(isCommunityAuthor({ __typename: "Bot", login: "dependabot" }, "NONE"), false); + assert.equal(isCommunityAuthor({ type: "Bot", login: "github-actions[bot]" }, "NONE"), false); + assert.equal(isCommunityAuthor(null, "NONE"), false); +}); + +test("defaultCodeowners parses wildcard user owners and matches the repository file", () => { + assert.deepEqual(defaultCodeowners("# comment\n* @alice @bob @org/team\n/docs/ @carol\n"), ["alice", "bob"]); + const repoCodeowners = readFileSync(new URL("../CODEOWNERS", import.meta.url), "utf8"); + const owners = defaultCodeowners(); + assert.ok(owners.length > 0); + assert.deepEqual(owners, defaultCodeowners(repoCodeowners)); +}); + +test("readFollowupMarker trusts only the workflow's own comments and prefers publication createdAt", () => { + const body = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "abc1234", + isDraft: false, + blockers: [{ kind: "merge-conflicts" }], + daysIdle: 7, + closeInDays: 7, + now: BASE_TIME - 60_000, + }); + + const publishedAt = new Date(BASE_TIME).toISOString(); + const parsed = readFollowupMarker(botComment(body, publishedAt)); + assert.equal(parsed?.kind, "author-nudge"); + assert.equal(parsed?.headSha, "abc1234"); + assert.equal(parsed?.draft, false); + assert.equal(parsed?.at, BASE_TIME); + + const fallbackParsed = readFollowupMarker(botComment(body, null)); + assert.equal(fallbackParsed?.at, BASE_TIME - 60_000); + + assert.equal(readFollowupMarker({ author: { __typename: "User", login: "alice" }, body, createdAt: daysAgo(1) }), null); + // Anyone can get another bot to repeat text, so only the workflow's own markers count. + assert.equal(readFollowupMarker({ author: { __typename: "Bot", login: "coderabbitai" }, body, createdAt: daysAgo(1) }), null); + assert.equal(readFollowupMarker({ user: { type: "Bot", login: "github-actions[bot]" }, body, created_at: publishedAt })?.kind, "author-nudge"); +}); + +test("analyzeChecks deduplicates reruns and reads failing check runs and commit statuses", () => { + const result = analyzeChecks([ + { __typename: "CheckRun", name: "Validate", status: "COMPLETED", conclusion: "FAILURE", completedAt: daysAgo(2) }, + { __typename: "CheckRun", name: "Validate", status: "COMPLETED", conclusion: "SUCCESS", completedAt: daysAgo(1) }, + { __typename: "CheckRun", name: "Lint", status: "COMPLETED", conclusion: "FAILURE", completedAt: daysAgo(1) }, + { __typename: "CheckRun", name: "Slow", status: "IN_PROGRESS", conclusion: null, startedAt: daysAgo(1) }, + { __typename: "StatusContext", context: "External", state: "PENDING", description: "Waiting", createdAt: daysAgo(1) }, + ]); + assert.deepEqual(result, { failingChecks: ["Lint"] }); + + const statusFailed = analyzeChecks([ + { __typename: "StatusContext", context: "External", state: "FAILURE", description: "Failed", createdAt: daysAgo(2) }, + { __typename: "StatusContext", context: "Other", state: "ERROR", description: "Errored", createdAt: daysAgo(1) }, + ]); + assert.deepEqual(statusFailed, { failingChecks: ["External", "Other"] }); +}); + +test("skips team PRs and PRs with keep-open", () => { + assert.equal(evaluatePullRequest(makePR({ authorAssociation: "COLLABORATOR" }), { now: BASE_TIME }).reason, "not-community"); + assert.equal(evaluatePullRequest(makePR({ labels: [LABELS.keepOpen] }), { now: BASE_TIME }).reason, "keep-open"); +}); + +test("ready PR waiting on author nudges at 7 days, waits before 14, and closes 7 days after nudge", () => { + const failing = [ + { __typename: "CheckRun", name: "Description", status: "COMPLETED", conclusion: "FAILURE", completedAt: daysAgo(6) }, + { __typename: "CheckRun", name: "Test", status: "COMPLETED", conclusion: "FAILURE", completedAt: daysAgo(6) }, + ]; + + const day6 = evaluatePullRequest(makePR({ createdAt: daysAgo(6), headCommit: { pushedDate: daysAgo(6) }, statusContexts: failing }), { now: BASE_TIME }); + assert.equal(day6.action, "none"); + assert.equal(day6.court, "author"); + + const day7 = evaluatePullRequest(makePR({ + createdAt: daysAgo(7), + headCommit: { pushedDate: daysAgo(7) }, + statusContexts: failing, + mergeable: "CONFLICTING", + labels: [LABELS.needsReview.name], + }), { now: BASE_TIME }); + assert.equal(day7.action, "nudge-author"); + assert.deepEqual(day7.labelsToAdd, [LABELS.waitingForAuthor.name]); + assert.deepEqual(day7.labelsToRemove, [LABELS.needsReview.name]); + assert.deepEqual(day7.blockers, [ + { kind: "failing-checks", checks: ["Description", "Test"] }, + { kind: "merge-conflicts" }, + ]); + + const nudgeBody = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "abc1234", + isDraft: false, + blockers: day7.blockers, + daysIdle: 7, + closeInDays: 7, + now: BASE_TIME - 6 * DAY_MS, + }); + const day13 = evaluatePullRequest(makePR({ + createdAt: daysAgo(13), + headCommit: { pushedDate: daysAgo(13) }, + statusContexts: failing, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(nudgeBody, daysAgo(6))], + }), { now: BASE_TIME }); + assert.equal(day13.action, "wait"); + assert.equal(day13.reason, "already-nudged"); + + const oldNudgeBody = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "abc1234", + isDraft: false, + blockers: day7.blockers, + daysIdle: 7, + closeInDays: 7, + now: BASE_TIME - 7 * DAY_MS, + }); + const day14 = evaluatePullRequest(makePR({ + createdAt: daysAgo(14), + headCommit: { pushedDate: daysAgo(14) }, + statusContexts: failing, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(oldNudgeBody, daysAgo(7))], + }), { now: BASE_TIME }); + assert.equal(day14.action, "close-author"); + assert.equal(day14.daysSinceNudge, 7); +}); + +test("nudge from an earlier headSha cannot authorize closing and old-dated pushes reset activity via checkSuite timing", () => { + const failing = [{ __typename: "CheckRun", name: "Test", status: "COMPLETED", conclusion: "FAILURE", completedAt: daysAgo(14) }]; + const oldNudge = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "old-head", + isDraft: false, + blockers: [{ kind: "failing-checks", checks: ["Test"] }], + daysIdle: 7, + closeInDays: 7, + now: BASE_TIME - 7 * DAY_MS, + }); + // Fast-forward push of a locally-old commit today: checkSuite created 1 day ago resets the clock + // and clears waiting-for-author rather than re-nudging immediately. + const readyAfterPush = evaluatePullRequest(makePR({ + headRefOid: "new-head", + createdAt: daysAgo(14), + headCommit: { oid: "new-head", committedDate: daysAgo(12), authoredDate: daysAgo(12), checkSuiteCreatedAts: [daysAgo(1)] }, + statusContexts: failing, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(oldNudge, daysAgo(7))], + }), { now: BASE_TIME }); + assert.equal(readyAfterPush.action, "none"); + assert.deepEqual(readyAfterPush.labelsToRemove, [LABELS.waitingForAuthor.name]); + + // Even without checkSuite timing, a changed headSha never authorizes closing on an older nudge. + const readyAfterPushNoChecks = evaluatePullRequest(makePR({ + headRefOid: "new-head", + createdAt: daysAgo(14), + headCommit: { oid: "new-head", committedDate: daysAgo(12), authoredDate: daysAgo(12) }, + statusContexts: failing, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(oldNudge, daysAgo(7))], + }), { now: BASE_TIME }); + assert.equal(readyAfterPushNoChecks.action, "nudge-author"); + + // Later reruns do not push the inactivity clock forward (earliest checkSuite/checkRun wins). + const rerunDoesNotReset = evaluatePullRequest(makePR({ + headRefOid: "same-head", + createdAt: daysAgo(10), + headCommit: { oid: "same-head", committedDate: daysAgo(10), checkSuiteCreatedAts: [daysAgo(10), daysAgo(1)] }, + statusContexts: [{ __typename: "CheckRun", name: "Test", status: "COMPLETED", conclusion: "FAILURE", startedAt: daysAgo(1), completedAt: daysAgo(1) }], + }), { now: BASE_TIME }); + assert.equal(rerunDoesNotReset.action, "nudge-author"); + + // Fast-forward push of an old-dated commit after CHANGES_REQUESTED moves the PR to maintainers. + const changesAddressedByOldCommit = evaluatePullRequest(makePR({ + headRefOid: "new-head", + createdAt: daysAgo(15), + headCommit: { oid: "new-head", committedDate: daysAgo(12), checkSuiteCreatedAts: [daysAgo(5)] }, + reviews: [ + { author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", state: "CHANGES_REQUESTED", submittedAt: daysAgo(8) }, + ], + }), { now: BASE_TIME }); + assert.equal(changesAddressedByOldCommit.court, "maintainer"); + assert.equal(changesAddressedByOldCommit.action, "remind-maintainers"); + + const oldDraftNudge = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "old-head", + isDraft: true, + blockers: ["draft"], + daysIdle: 14, + closeInDays: 14, + now: BASE_TIME - 14 * DAY_MS, + }); + const draftAfterPush = evaluatePullRequest(makePR({ + isDraft: true, + headRefOid: "new-head", + createdAt: daysAgo(28), + headCommit: { oid: "new-head", committedDate: daysAgo(20), authoredDate: daysAgo(20) }, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(oldDraftNudge, daysAgo(14))], + }), { now: BASE_TIME }); + assert.equal(draftAfterPush.action, "nudge-author"); +}); + +test("bot comments do not reset the inactivity clock, while author comments and reopens do", () => { + const failing = [{ __typename: "CheckRun", name: "Test", status: "COMPLETED", conclusion: "FAILURE", completedAt: daysAgo(8) }]; + const botNoise = { author: { __typename: "Bot", login: "coderabbitai" }, body: "rate limited", createdAt: daysAgo(1) }; + + const withBotNoise = evaluatePullRequest(makePR({ + createdAt: daysAgo(8), + headCommit: { pushedDate: daysAgo(8) }, + statusContexts: failing, + comments: [botNoise], + }), { now: BASE_TIME }); + assert.equal(withBotNoise.action, "nudge-author"); + + const nudgeBody = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "abc1234", + isDraft: false, + blockers: [{ kind: "failing-checks", checks: ["Test"] }], + daysIdle: 7, + closeInDays: 7, + now: BASE_TIME - 8 * DAY_MS, + }); + const afterAuthorReply = evaluatePullRequest(makePR({ + createdAt: daysAgo(15), + headCommit: { pushedDate: daysAgo(15) }, + statusContexts: failing, + labels: [LABELS.waitingForAuthor.name], + comments: [ + botComment(nudgeBody, daysAgo(8)), + { author: { __typename: "User", login: "alice" }, authorAssociation: "FIRST_TIME_CONTRIBUTOR", body: "Working on it this weekend!", createdAt: daysAgo(2) }, + ], + }), { now: BASE_TIME }); + assert.equal(afterAuthorReply.action, "none"); + assert.deepEqual(afterAuthorReply.labelsToRemove, [LABELS.waitingForAuthor.name]); + + const reopened = evaluatePullRequest(makePR({ + createdAt: daysAgo(30), + headCommit: { pushedDate: daysAgo(30) }, + timelineDates: [daysAgo(1)], + statusContexts: failing, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(nudgeBody, daysAgo(10))], + }), { now: BASE_TIME }); + assert.equal(reopened.action, "none"); + assert.deepEqual(reopened.labelsToRemove, [LABELS.waitingForAuthor.name]); +}); + +test("draft PRs use the longer 14d nudge and 14d close windows", () => { + const day10 = evaluatePullRequest(makePR({ + isDraft: true, + createdAt: daysAgo(10), + headCommit: { pushedDate: daysAgo(10) }, + labels: [LABELS.needsReview.name], + }), { now: BASE_TIME }); + assert.equal(day10.action, "none"); + assert.deepEqual(day10.labelsToRemove, [LABELS.needsReview.name]); + + const day14 = evaluatePullRequest(makePR({ + isDraft: true, + createdAt: daysAgo(14), + headCommit: { pushedDate: daysAgo(14) }, + }), { now: BASE_TIME }); + assert.equal(day14.action, "nudge-author"); + assert.equal(day14.isDraft, true); + assert.equal(day14.closeInDays, 14); + + const draftNudge10d = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "abc1234", + isDraft: true, + blockers: ["draft"], + daysIdle: 14, + closeInDays: 14, + now: BASE_TIME - 10 * DAY_MS, + }); + const day24 = evaluatePullRequest(makePR({ + isDraft: true, + createdAt: daysAgo(24), + headCommit: { pushedDate: daysAgo(24) }, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(draftNudge10d, daysAgo(10))], + }), { now: BASE_TIME }); + assert.equal(day24.action, "wait"); + + const draftNudge14d = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "abc1234", + isDraft: true, + blockers: ["draft"], + daysIdle: 14, + closeInDays: 14, + now: BASE_TIME - 14 * DAY_MS, + }); + const day28 = evaluatePullRequest(makePR({ + isDraft: true, + createdAt: daysAgo(28), + headCommit: { pushedDate: daysAgo(28) }, + labels: [LABELS.waitingForAuthor.name], + comments: [botComment(draftNudge14d, daysAgo(14))], + }), { now: BASE_TIME }); + assert.equal(day28.action, "close-author"); + assert.equal(day28.isDraft, true); +}); + +test("review threads, CHANGES_REQUESTED, and DISMISSED reviews classify ownership accurately", () => { + const waitingAuthor = evaluatePullRequest(makePR({ + createdAt: daysAgo(9), + headCommit: { pushedDate: daysAgo(9) }, + reviews: [ + { author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", state: "CHANGES_REQUESTED", submittedAt: daysAgo(8) }, + ], + reviewThreads: [ + { isResolved: false, comments: [{ author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", createdAt: daysAgo(8) }] }, + ], + }), { now: BASE_TIME }); + assert.equal(waitingAuthor.action, "nudge-author"); + assert.deepEqual(waitingAuthor.blockers, [ + { kind: "changes-requested" }, + { kind: "unresolved-threads", count: 1 }, + ]); + + // Dismissing an earlier CHANGES_REQUESTED clears that blocker. + const dismissed = evaluatePullRequest(makePR({ + createdAt: daysAgo(10), + headCommit: { pushedDate: daysAgo(10) }, + reviews: [ + { author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", state: "CHANGES_REQUESTED", submittedAt: daysAgo(8) }, + { author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", state: "DISMISSED", submittedAt: daysAgo(5) }, + ], + }), { now: BASE_TIME }); + assert.equal(dismissed.court, "maintainer"); + assert.equal(dismissed.action, "remind-maintainers"); + + // Unordered review thread comments still pick the newest reply by createdAt. + const waitingMaintainer = evaluatePullRequest(makePR({ + createdAt: daysAgo(10), + headCommit: { pushedDate: daysAgo(5) }, + requestedReviewers: [], + labels: [LABELS.waitingForAuthor.name], + reviews: [ + { author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", state: "CHANGES_REQUESTED", submittedAt: daysAgo(8) }, + ], + reviewThreads: [ + { + isResolved: false, + comments: [ + { author: { __typename: "User", login: "alice" }, authorAssociation: "FIRST_TIME_CONTRIBUTOR", createdAt: daysAgo(5) }, + { author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", createdAt: daysAgo(8) }, + ], + }, + ], + }), { now: BASE_TIME, fallbackReviewers: ["Seb-GRAF"] }); + assert.equal(waitingMaintainer.action, "remind-maintainers"); + assert.equal(waitingMaintainer.court, "maintainer"); + assert.deepEqual(waitingMaintainer.maintainerReasons, ["re-review", "thread-reply"]); + assert.deepEqual(waitingMaintainer.reviewersToPing, ["Seb-GRAF"]); + assert.deepEqual(waitingMaintainer.labelsToAdd, [LABELS.needsReview.name]); + assert.deepEqual(waitingMaintainer.labelsToRemove, [LABELS.waitingForAuthor.name]); +}); + +test("review threads from outsiders don't put a PR on its author, while the team's and review bots' still do", () => { + const thread = (...comments) => ({ isResolved: false, comments }); + const outsider = { author: { __typename: "User", login: "mallory" }, authorAssociation: "CONTRIBUTOR", createdAt: daysAgo(9) }; + const bot = { author: { __typename: "Bot", login: "coderabbitai" }, authorAssociation: "NONE", createdAt: daysAgo(9) }; + const maintainer = { author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", createdAt: daysAgo(9) }; + const outsiderPlusOne = { ...outsider, createdAt: daysAgo(8) }; + + const fromOutsider = evaluatePullRequest(makePR({ reviewThreads: [thread(outsider)] }), { now: BASE_TIME }); + assert.equal(fromOutsider.court, "maintainer"); + assert.equal(fromOutsider.action, "remind-maintainers"); + + // Review bots are installed by the team, and their threads have to be answered before merging. + const fromBot = evaluatePullRequest(makePR({ reviewThreads: [thread(bot)] }), { now: BASE_TIME }); + assert.equal(fromBot.action, "nudge-author"); + assert.deepEqual(fromBot.blockers, [{ kind: "unresolved-threads", count: 1 }]); + + // Anyone can get a bot to reply, so a bot's reply after the author's doesn't count. + const botReply = { ...bot, createdAt: daysAgo(7) }; + const answeredThenBot = evaluatePullRequest(makePR({ + reviewThreads: [thread(bot, { author: { __typename: "User", login: "alice" }, authorAssociation: "FIRST_TIME_CONTRIBUTOR", createdAt: daysAgo(8) }, botReply)], + }), { now: BASE_TIME }); + assert.equal(answeredThenBot.court, "maintainer"); + + // A deleted account's comment has no author and doesn't pass for a bot. + const fromDeleted = evaluatePullRequest(makePR({ reviewThreads: [thread({ ...outsider, author: null })] }), { now: BASE_TIME }); + assert.equal(fromDeleted.court, "maintainer"); + + // An outsider's reply after the author's doesn't hand the thread back to the author either. + const authorReply = { author: { __typename: "User", login: "alice" }, authorAssociation: "FIRST_TIME_CONTRIBUTOR", createdAt: daysAgo(8) }; + const answeredThenOutsider = evaluatePullRequest(makePR({ + reviewThreads: [thread(maintainer, authorReply, { ...outsider, createdAt: daysAgo(7) })], + }), { now: BASE_TIME }); + assert.equal(answeredThenOutsider.court, "maintainer"); + assert.deepEqual(answeredThenOutsider.maintainerReasons, ["thread-reply"]); + + // An outsider's reply after a maintainer's request doesn't take the thread off the author. + const maintainerThenOutsider = evaluatePullRequest(makePR({ reviewThreads: [thread(maintainer, outsiderPlusOne)] }), { now: BASE_TIME }); + assert.equal(maintainerThenOutsider.action, "nudge-author"); + assert.deepEqual(maintainerThenOutsider.blockers, [{ kind: "unresolved-threads", count: 1 }]); + + // Outsiders' recent comments still delay a follow-up in either court. + const recentOutsider = evaluatePullRequest(makePR({ reviewThreads: [thread({ ...outsider, createdAt: daysAgo(2) })] }), { now: BASE_TIME }); + assert.equal(recentOutsider.court, "maintainer"); + assert.equal(recentOutsider.action, "none"); + const maintainerThenRecentOutsider = evaluatePullRequest(makePR({ + reviewThreads: [thread(maintainer, { ...outsider, createdAt: daysAgo(2) })], + }), { now: BASE_TIME }); + assert.equal(maintainerThenRecentOutsider.court, "author"); + assert.equal(maintainerThenRecentOutsider.action, "none"); +}); + +test("PRs waiting on maintainers remind once after 4 days (including workflow approval) and never close", () => { + const day3 = evaluatePullRequest(makePR({ + createdAt: daysAgo(3), + headCommit: { pushedDate: daysAgo(3) }, + awaitingWorkflowApproval: true, + labels: [LABELS.needsReview.name], + }), { now: BASE_TIME }); + assert.equal(day3.action, "none"); + assert.deepEqual(day3.labelsToRemove, [LABELS.needsReview.name]); + + const day4 = evaluatePullRequest(makePR({ + createdAt: daysAgo(4), + headCommit: { pushedDate: daysAgo(4) }, + awaitingWorkflowApproval: true, + requestedReviewers: ["M4n0x", "Seb-GRAF"], + }), { now: BASE_TIME }); + assert.equal(day4.action, "remind-maintainers"); + assert.deepEqual(day4.maintainerReasons, ["workflow-approval"]); + assert.deepEqual(day4.reviewersToPing, ["M4n0x", "Seb-GRAF"]); + assert.deepEqual(day4.labelsToAdd, [LABELS.needsReview.name]); + + const reminderBody = formatMaintainerReminderComment({ + headSha: "abc1234", + reviewersToPing: ["M4n0x", "Seb-GRAF"], + maintainerReasons: ["review"], + daysIdle: 4, + now: BASE_TIME - 26 * DAY_MS, + }); + const day30 = evaluatePullRequest(makePR({ + createdAt: daysAgo(30), + headCommit: { pushedDate: daysAgo(30) }, + labels: [LABELS.needsReview.name], + comments: [botComment(reminderBody, daysAgo(26))], + }), { now: BASE_TIME }); + assert.equal(day30.action, "wait"); + assert.equal(day30.reason, "already-reminded-maintainers"); +}); + +test("comment formatting sanitizes check names and embeds valid markers", () => { + const nudge = formatAuthorNudgeComment({ + authorLogin: "alice", + headSha: "abc1234", + isDraft: false, + blockers: [{ kind: "failing-checks", checks: ["Test `evil` @everyone -->"] }], + daysIdle: 7, + closeInDays: 7, + now: BASE_TIME, + }); + assert.match(nudge, /Hi @alice/); + assert.ok(nudge.includes("`Test 'evil' @everyone -->`")); + assert.ok(readFollowupMarker(botComment(nudge, new Date(BASE_TIME).toISOString()))?.kind === "author-nudge"); + + const close = formatAuthorCloseComment({ headSha: "abc1234", isDraft: true, daysSinceNudge: 14, now: BASE_TIME }); + assert.match(close, /draft pull request/); + assert.match(close, /14 days ago/); + assert.equal(readFollowupMarker(botComment(close, new Date(BASE_TIME).toISOString()))?.kind, "author-close"); + + const reminder = formatMaintainerReminderComment({ + headSha: "abc1234", + reviewersToPing: ["Seb-GRAF", "M4n0x"], + maintainerReasons: ["workflow-approval", "review"], + daysIdle: 4, + now: BASE_TIME, + }); + assert.match(reminder, /@Seb-GRAF @M4n0x/); + assert.match(reminder, /waiting for approval to run/); + assert.match(reminder, /Ready for review/); + assert.equal(readFollowupMarker(botComment(reminder, new Date(BASE_TIME).toISOString()))?.kind, "maintainer-reminder"); +}); + +function makeGraphQLNode(overrides = {}) { + return { + number: 1, + state: "OPEN", + title: "Community PR", + isDraft: false, + createdAt: daysAgo(5), + mergeable: "MERGEABLE", + authorAssociation: "FIRST_TIME_CONTRIBUTOR", + author: { __typename: "User", login: "bob" }, + headRefOid: "sha-1", + headRefName: "fix/ready", + headRepository: { nameWithOwner: "bob/stablebar-packages" }, + labels: { nodes: [] }, + reviewRequests: { nodes: [{ requestedReviewer: { login: "Seb-GRAF" } }] }, + commits: { nodes: [{ commit: { oid: "sha-1", pushedDate: daysAgo(5), statusCheckRollup: { contexts: { nodes: [] } } } }] }, + timelineItems: { nodes: [] }, + reviews: { nodes: [] }, + reviewThreads: { nodes: [] }, + comments: { nodes: [] }, + ...overrides, + }; +} + +test("runSweep handles dry-run, live close ordering, thread pagination, recheck abort, and per-PR error isolation", async () => { + const ops = []; + const oldNudge = (login, headSha) => formatAuthorNudgeComment({ + authorLogin: login, + headSha, + isDraft: false, + blockers: [{ kind: "merge-conflicts" }], + daysIdle: 7, + closeInDays: 7, + now: BASE_TIME - 7 * DAY_MS, + }); + + const pr1 = makeGraphQLNode({ + number: 1, + authorAssociation: "COLLABORATOR", + author: { __typename: "User", login: "M4n0x" }, + mergeable: "CONFLICTING", + createdAt: daysAgo(20), + commits: { nodes: [{ commit: { oid: "sha-team", pushedDate: daysAgo(20), statusCheckRollup: { contexts: { nodes: [] } } } }] }, + }); + + // Paginated review thread: page 1 ends with maintainer, page 2 has author reply -> maintainer's court. + const pr2 = makeGraphQLNode({ + number: 2, + headRefOid: "sha-ready", + createdAt: daysAgo(8), + commits: { nodes: [{ commit: { oid: "sha-ready", pushedDate: daysAgo(8), statusCheckRollup: { contexts: { nodes: [] } } } }] }, + reviewThreads: { + nodes: [{ + id: "thread-2", + isResolved: false, + comments: { + pageInfo: { hasNextPage: true, endCursor: "c1" }, + nodes: [{ author: { __typename: "User", login: "Seb-GRAF" }, authorAssociation: "OWNER", createdAt: daysAgo(8) }], + }, + }], + }, + }); + + // Eligible to close and stays eligible on recheck -> closes BEFORE posting comment. + const pr3 = makeGraphQLNode({ + number: 3, + author: { __typename: "User", login: "carol" }, + headRefOid: "sha-close", + headRefName: "fix/close", + headRepository: { nameWithOwner: "carol/stablebar-packages" }, + mergeable: "CONFLICTING", + createdAt: daysAgo(15), + labels: { nodes: [{ name: LABELS.waitingForAuthor.name }] }, + commits: { nodes: [{ commit: { oid: "sha-close", pushedDate: daysAgo(15), statusCheckRollup: { contexts: { nodes: [] } } } }] }, + comments: { nodes: [botComment(oldNudge("carol", "sha-close"), daysAgo(7))] }, + }); + + // Eligible to close in bulk snapshot, but maintainer adds keep-open before write -> close aborted. + const pr4 = makeGraphQLNode({ + number: 4, + author: { __typename: "User", login: "dave" }, + headRefOid: "sha-race", + headRefName: "fix/race", + headRepository: { nameWithOwner: "dave/stablebar-packages" }, + mergeable: "CONFLICTING", + createdAt: daysAgo(15), + labels: { nodes: [{ name: LABELS.waitingForAuthor.name }] }, + commits: { nodes: [{ commit: { oid: "sha-race", pushedDate: daysAgo(15), statusCheckRollup: { contexts: { nodes: [] } } } }] }, + comments: { nodes: [botComment(oldNudge("dave", "sha-race"), daysAgo(7))] }, + }); + const pr4Fresh = { ...pr4, labels: { nodes: [{ name: LABELS.waitingForAuthor.name }, { name: LABELS.keepOpen }] } }; + + // Fails on label write, but PR #6 still runs afterwards. + const pr5 = makeGraphQLNode({ + number: 5, + author: { __typename: "User", login: "erin" }, + headRefOid: "sha-err", + createdAt: daysAgo(6), + commits: { nodes: [{ commit: { oid: "sha-err", pushedDate: daysAgo(6), statusCheckRollup: { contexts: { nodes: [] } } } }] }, + }); + const pr6 = makeGraphQLNode({ + number: 6, + author: { __typename: "User", login: "frank" }, + headRefOid: "sha-after", + createdAt: daysAgo(6), + commits: { nodes: [{ commit: { oid: "sha-after", pushedDate: daysAgo(6), statusCheckRollup: { contexts: { nodes: [] } } } }] }, + }); + + const nodes = [pr1, pr2, pr3, pr4, pr5, pr6]; + const singleNodes = new Map([[3, pr3], [4, pr4Fresh]]); + + const makeGitHub = () => ({ + graphql: async (query, vars) => { + if (query.includes("pullRequests(states: OPEN")) { + return { repository: { pullRequests: { pageInfo: { hasNextPage: false, endCursor: null }, nodes } } }; + } + if (query.includes("pullRequest(number:")) { + return { repository: { pullRequest: singleNodes.get(vars.number) ?? null } }; + } + if (query.includes("PullRequestReviewThread") && vars.threadId === "thread-2" && vars.cursor === "c1") { + return { + node: { + comments: { + pageInfo: { hasNextPage: false, endCursor: null }, + nodes: [{ author: { __typename: "User", login: "bob" }, authorAssociation: "FIRST_TIME_CONTRIBUTOR", createdAt: daysAgo(5) }], + }, + }, + }; + } + throw new Error(`Unexpected query: ${query}`); + }, + rest: { + actions: { + listWorkflowRunsForRepo: async ({ head_sha }) => ({ + data: { + workflow_runs: head_sha === "sha-ready" + ? [{ event: "pull_request", head_branch: "fix/ready", head_repository: { full_name: "bob/stablebar-packages" } }] + : [], + }, + }), + }, + issues: { + createLabel: async (args) => { ops.push(["createLabel", args.name]); }, + addLabels: async (args) => { + if (args.issue_number === 5) throw new Error("Simulated label failure"); + ops.push(["addLabels", args.issue_number, args.labels]); + }, + removeLabel: async (args) => { ops.push(["removeLabel", args.issue_number, args.name]); }, + createComment: async (args) => { ops.push(["comment", args.issue_number, args.body]); }, + }, + pulls: { + update: async (args) => { ops.push(["close", args.pull_number, args.state]); }, + }, + }, + }); + + const context = { repo: { owner: "stablebox", repo: "stablebar-packages" } }; + const warnings = []; + const core = { info: () => {}, warning: (msg) => warnings.push(msg) }; + + const dryResults = await runSweep({ + github: makeGitHub(), + context, + core, + dryRun: true, + now: BASE_TIME, + fallbackReviewers: ["Seb-GRAF"], + }); + assert.deepEqual( + dryResults.map((r) => [r.number, r.action]), + [[1, "skip"], [2, "remind-maintainers"], [3, "close-author"], [4, "close-author"], [5, "remind-maintainers"], [6, "remind-maintainers"]], + ); + assert.equal(ops.length, 0); + + const liveResults = await runSweep({ + github: makeGitHub(), + context, + core, + dryRun: false, + now: BASE_TIME, + fallbackReviewers: ["Seb-GRAF"], + }); + assert.deepEqual( + liveResults.map((r) => [r.number, r.action]), + [[1, "skip"], [2, "remind-maintainers"], [3, "close-author"], [4, "skip"], [5, "error"], [6, "remind-maintainers"]], + ); + assert.equal(warnings.length, 1); + + // Verify PR #3 closed BEFORE posting the closure notice, and PR #4 was never closed or commented on. + const pr3Ops = ops.filter((op) => op[1] === 3).map((op) => op[0]); + assert.deepEqual(pr3Ops, ["close", "comment"]); + assert.equal(ops.some((op) => op[1] === 4), false); + assert.equal(ops.some((op) => op[0] === "comment" && op[1] === 6), true); +}); + +test("clearWaitingLabel removes waiting-for-author on community PR activity", async () => { + const removed = []; + const github = { + rest: { + issues: { + removeLabel: async (args) => { removed.push(args); }, + }, + }, + }; + const core = { info: () => {} }; + + const cleared = await clearWaitingLabel({ + github, + core, + context: { + repo: { owner: "stablebox", repo: "stablebar-packages" }, + payload: { + action: "synchronize", + sender: { login: "Alice" }, + pull_request: { + number: 42, + user: { type: "User", login: "alice" }, + author_association: "FIRST_TIME_CONTRIBUTOR", + labels: [{ name: LABELS.waitingForAuthor.name }], + }, + }, + }, + }); + assert.equal(cleared, true); + assert.deepEqual(removed, [{ owner: "stablebox", repo: "stablebar-packages", issue_number: 42, name: LABELS.waitingForAuthor.name }]); + + // A maintainer's push to the contributor's branch isn't the author's update. + const communityPullRequest = { + number: 44, + user: { type: "User", login: "alice" }, + author_association: "FIRST_TIME_CONTRIBUTOR", + labels: [{ name: LABELS.waitingForAuthor.name }], + }; + const maintainerPush = await clearWaitingLabel({ + github, + core, + context: { + repo: { owner: "stablebox", repo: "stablebar-packages" }, + payload: { action: "synchronize", sender: { login: "Seb-GRAF" }, pull_request: communityPullRequest }, + }, + }); + assert.equal(maintainerPush, false); + assert.equal(removed.length, 1); + + // Reopening or marking it ready clears the label whoever does it. + const maintainerReopen = await clearWaitingLabel({ + github, + core, + context: { + repo: { owner: "stablebox", repo: "stablebar-packages" }, + payload: { action: "reopened", sender: { login: "Seb-GRAF" }, pull_request: communityPullRequest }, + }, + }); + assert.equal(maintainerReopen, true); + + const skipped = await clearWaitingLabel({ + github, + core, + context: { + repo: { owner: "stablebox", repo: "stablebar-packages" }, + payload: { + action: "synchronize", + pull_request: { + number: 43, + user: { type: "User", login: "Seb-GRAF" }, + author_association: "OWNER", + labels: [{ name: LABELS.waitingForAuthor.name }], + }, + }, + }, + }); + assert.equal(skipped, false); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 50ca1b5..c69e0e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,13 @@ jobs: run: ./scripts/check-listing.sh - name: Test the scripts run: ./scripts/test.sh + # The follow-up workflow runs the default branch's copy of .github/scripts, so a change to it + # is tested here before it merges. + - uses: actions/setup-node@v7 + with: + node-version: 24 + - name: Test the workflow scripts + run: node --test .github/scripts/*.test.mjs - name: Check versions if: github.event_name == 'pull_request' env: diff --git a/.github/workflows/community-pr-followup.yml b/.github/workflows/community-pr-followup.yml new file mode 100644 index 0000000..77e8f89 --- /dev/null +++ b/.github/workflows/community-pr-followup.yml @@ -0,0 +1,104 @@ +name: Community PR follow-up + +# Follows up on open community pull requests so they don't sit idle without action: +# - Waiting on contributor (failing checks, conflicts, requested changes, unresolved team or bot threads): +# labels waiting-for-author and nudges after 7 days, then closes 7 days later if still silent. +# - Draft PRs get a longer window: nudge after 14 days, close 14 days later. +# - Waiting on maintainers (ready for review, or first-time CI approval): +# never marks stale or closes; labels needs-review and reminds maintainers after 4 days. +# - Add `keep-open` to pause follow-ups on a pull request. +# +# Runs the default branch's copy of this workflow and of .github/scripts, so a pull request never +# runs its own code here. The logic and its tests are in .github/scripts/community-pr-followup.mjs. +on: + schedule: + - cron: "23 9 * * *" + workflow_dispatch: + inputs: + dry_run: + description: Log planned actions without commenting, labeling, or closing + type: boolean + default: true + pull_request: + description: Optional single pull request number to inspect + type: string + required: false + pull_request_target: + types: [synchronize, reopened, ready_for_review] + +permissions: {} + +concurrency: + group: community-pr-followup-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || 'sweep' }} + cancel-in-progress: ${{ github.event_name == 'pull_request_target' }} + +jobs: + clear-waiting: + name: Clear waiting-for-author label + if: >- + github.event_name == 'pull_request_target' + && contains(github.event.pull_request.labels.*.name, 'waiting-for-author') + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: | + .github/CODEOWNERS + .github/scripts + persist-credentials: false + - uses: actions/github-script@v9 + with: + script: | + const { clearWaitingLabel } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/community-pr-followup.mjs`); + await clearWaitingLabel({ github, context, core }); + + sweep: + name: Follow up on community PRs + if: github.event_name != 'pull_request_target' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + actions: read + checks: read + contents: read + issues: write + pull-requests: write + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: | + .github/CODEOWNERS + .github/scripts + persist-credentials: false + - uses: actions/github-script@v9 + env: + DRY_RUN: ${{ inputs.dry_run || 'false' }} + PULL_REQUEST: ${{ inputs.pull_request || '' }} + with: + script: | + const { runSweep } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/community-pr-followup.mjs`); + const dryRun = process.env.DRY_RUN === "true"; + const pullRequestNumber = process.env.PULL_REQUEST ? Number(process.env.PULL_REQUEST) : null; + if (process.env.PULL_REQUEST && (!Number.isInteger(pullRequestNumber) || pullRequestNumber <= 0)) { + throw new Error(`Invalid pull_request input: ${process.env.PULL_REQUEST}`); + } + const results = await runSweep({ github, context, core, dryRun, pullRequestNumber }); + const acted = results.filter((r) => ["nudge-author", "close-author", "remind-maintainers"].includes(r.action)); + const failed = results.filter((r) => r.action === "error"); + const lines = [`Inspected ${results.length} open pull request(s); ${acted.length} action(s) ${dryRun ? "planned" : "taken"}.`]; + if (failed.length > 0) { + lines.push("", "Failures:", ...failed.map((r) => `- #${r.number}: ${r.error}`)); + } + await core.summary + .addHeading(dryRun ? "Community PR follow-up (dry run)" : "Community PR follow-up", 3) + .addRaw(`${lines.join("\n")}\n`) + .write(); + if (failed.length > 0) { + core.setFailed(`Follow-up failed for ${failed.length} pull request(s): ${failed.map((r) => `#${r.number}`).join(", ")}`); + } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 66cf16d..de42c94 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -99,13 +99,15 @@ To try the package on your own bar, install it from its folder in **Settings → 4. **Wait for CI.** `Lint` and `Validate` must pass. 5. **Review.** Themes and widget packages merge once CI passes. A package that runs commands waits for a maintainer to read every script and command string and check them against `requires`, `permissions` and `hosts`. This holds for every new version, however small the change. +Open community pull requests are followed up on daily by [Community PR follow-up](.github/workflows/community-pr-followup.yml). A pull request waiting on its author (failing checks, merge conflicts, requested changes or unresolved review threads from the team or a review bot) gets `waiting-for-author` and a check-in after 7 days, and closes automatically 7 days later without an update (drafts get 14 days before a check-in and 14 days after). A ready pull request waiting on maintainers (review or first-time CI approval) never closes automatically; after 4 days it gets `needs-review` and reminds maintainers. Add `keep-open` to pause follow-ups on a pull request. + Package ideas and bugs in a package go in [issues](https://github.com/stablebox/stablebar-packages/issues/new/choose). Bugs in StableBar itself go to [StableBar's issues](https://github.com/stablebox/StableBar/issues). ## What CI checks On every pull request and push to `main`: -- **Lint:** ShellCheck on every `.sh` file, the package list in the README, `scripts/check-suggestions.sh`, `scripts/check-listing.sh`, `scripts/test.sh`, which tests the scripts on scratch repositories and packages, and on pull requests `scripts/check-versions.sh`, which requires every package that changed to raise its version above every version it had, and `scripts/check-one-package.sh`, which allows one package per pull request. +- **Lint:** ShellCheck on every `.sh` file, the package list in the README, `scripts/check-suggestions.sh`, `scripts/check-listing.sh`, `scripts/test.sh`, which tests the scripts on scratch repositories and packages, the tests in `.github/scripts`, and on pull requests `scripts/check-versions.sh`, which requires every package that changed to raise its version above every version it had, and `scripts/check-one-package.sh`, which allows one package per pull request. - **Validate:** builds the current StableBar `main`, downloads its latest release, and runs `scripts/check-package.sh` on every package: the folder name matches the `id`, the file rules and the preview above, then `--inspect-package`, `--install-package` into a scratch configuration, and `--validate` with the package enabled, with `main` and with the release. The release may refuse a package whose `minimumVersion` is above it. - **Publish:** on `main` only, after both. `scripts/build-index.sh` writes `index.json`, with the suggestions from `suggestions.json` and each package's category and symbol from `listing.json`, and a `-.tar.gz` archive for each new version, and uploads them to the `store` prerelease. A version already in the index keeps its archive and checksum. Each package lists its newest version for each `minimumVersion`, oldest requirement first, so a StableBar that can't run the newest keeps getting a version it can: StableBar 0.17 and earlier take the first entry for a package, and later releases the newest one they can run. A version that another needing no newer StableBar outranks leaves the index. A version whose archive is already on the release but not in the index, because a publish failed halfway, is listed with that archive when it holds the same files; a publish that fails can be re-run. StableBar reads the index at `https://github.com/stablebox/stablebar-packages/releases/download/store/index.json`.