@sentry/junior-github 0.315.0 → 0.316.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRepositoryFromUrl, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubMessageSchema, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as definedValues, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as pullRequestTargets, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as logFailOpenFailure, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as githubRequest, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-D3Qnj4yY.js";
1
+ import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRepositoryFromUrl, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubMessageSchema, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as definedValues, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as pullRequestTargets, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as logFailOpenFailure, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as githubRequest, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-BoMOs5Rd.js";
2
2
  import * as z from "zod";
3
3
  import pLimit from "p-limit";
4
4
  import { EgressAuthRequired, EgressPolicyDenied, OBJECT_FACTS_MAX_BYTES, PluginToolInputError, decodeObjectImageRef, defineJuniorPlugin, definePluginTool, enforceEgressPolicy, mergeEventMatchFields, objectFactsBytes, objectFactsMatchType, objectFactsSchema, parseShellCommands, pluginToolOutputSchema, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
@@ -668,6 +668,24 @@ const PULL_REQUEST_DRAFT_READINESS = githubGraphql(`
668
668
  }
669
669
  }
670
670
  `);
671
+ /**
672
+ * Read whether GitHub asks one person to review a pull request, and their
673
+ * latest 20 submitted reviews. A pending review is not submitted.
674
+ */
675
+ const PULL_REQUEST_REVIEWER = githubGraphql(`
676
+ query PullRequestReviewer($owner: String!, $name: String!, $number: Int!, $login: String!) {
677
+ repository(owner: $owner, name: $name) {
678
+ pullRequest(number: $number) {
679
+ reviewRequests(first: 100) {
680
+ nodes { requestedReviewer { __typename ... on User { login } } }
681
+ }
682
+ reviews(last: 20, author: $login, states: [APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED]) {
683
+ nodes { state }
684
+ }
685
+ }
686
+ }
687
+ }
688
+ `);
671
689
  /** Read one page of a pull request search, with mergeability. */
672
690
  const OPEN_PULL_REQUEST_MERGEABILITY = githubGraphql(`
673
691
  query OpenPullRequestMergeability($query: String!, $after: String) {
@@ -720,6 +738,7 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
720
738
  repository(owner: $owner, name: $name) {
721
739
  pullRequest(number: $number) {
722
740
  autoMergeRequest { enabledAt }
741
+ commits(last: 1) { nodes { commit { committedDate } } }
723
742
  isDraft
724
743
  mergeStateStatus
725
744
  state
@@ -732,7 +751,7 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
732
751
  pageInfo { hasPreviousPage startCursor }
733
752
  nodes { ...NextActionReview }
734
753
  }
735
- timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT]) {
754
+ timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT, REVIEW_REQUEST_REMOVED_EVENT]) {
736
755
  nodes {
737
756
  __typename
738
757
  ... on IssueComment { createdAt author { __typename login } }
@@ -740,6 +759,11 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
740
759
  createdAt
741
760
  requestedReviewer { __typename ... on User { login } }
742
761
  }
762
+ ... on ReviewRequestRemovedEvent {
763
+ createdAt
764
+ actor { __typename login }
765
+ requestedReviewer { __typename ... on User { login } }
766
+ }
743
767
  }
744
768
  }
745
769
  }
@@ -753,9 +777,41 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
753
777
  }
754
778
  `);
755
779
  /**
780
+ * Read whether the required checks of a pull request's head commit pass:
781
+ * the checks of the head commit and the branch protection's required checks
782
+ * of the base branch. `PULL_REQUEST_REVIEW_AGAIN` reads the same fields.
783
+ */
784
+ const PULL_REQUEST_REQUIRED_CHECKS = githubGraphql(`
785
+ query PullRequestRequiredChecks($owner: String!, $name: String!, $number: Int!) {
786
+ repository(owner: $owner, name: $name) {
787
+ pullRequest(number: $number) {
788
+ baseRefName
789
+ baseRef { refUpdateRule { requiredStatusCheckContexts } }
790
+ commits(last: 1) {
791
+ nodes {
792
+ commit {
793
+ statusCheckRollup {
794
+ contexts(first: 100) {
795
+ pageInfo { hasNextPage }
796
+ nodes {
797
+ __typename
798
+ ... on CheckRun { name status conclusion }
799
+ ... on StatusContext { context state }
800
+ }
801
+ }
802
+ }
803
+ }
804
+ }
805
+ }
806
+ }
807
+ }
808
+ }
809
+ `);
810
+ /**
756
811
  * Read what decides whether a reviewer's change request is ready for their
757
- * review again: whether GitHub asks them, their latest review with the
758
- * reactors of its body and each of its comments, the checks of the head
812
+ * review again: whether GitHub asks them, when GitHub last asked people for
813
+ * a review, their latest 20 reviews with the reactors of each body and
814
+ * comment, the checks of the head
759
815
  * commit, and the branch protection's required checks of the base branch.
760
816
  */
761
817
  const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
@@ -767,10 +823,19 @@ const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
767
823
  reviewRequests(first: 100) {
768
824
  nodes { requestedReviewer { __typename ... on User { login } } }
769
825
  }
770
- reviews(last: 1, author: $reviewer, states: [APPROVED, CHANGES_REQUESTED, DISMISSED]) {
826
+ timelineItems(last: 100, itemTypes: [REVIEW_REQUESTED_EVENT]) {
827
+ nodes {
828
+ ... on ReviewRequestedEvent {
829
+ createdAt
830
+ requestedReviewer { __typename ... on User { login } }
831
+ }
832
+ }
833
+ }
834
+ reviews(last: 20, author: $reviewer, states: [APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED]) {
771
835
  nodes {
772
836
  databaseId
773
837
  state
838
+ submittedAt
774
839
  body
775
840
  ...FeedbackReactors
776
841
  comments(first: 100) {
@@ -1871,6 +1936,231 @@ async function listGitHubPullRequestsWithRequesters(db, input) {
1871
1936
  repositoryFullName: table.repositoryFullName
1872
1937
  }).from(table).where(after ? or(gt(table.repositoryFullName, after.repositoryFullName), and(eq(table.repositoryFullName, after.repositoryFullName), gt(table.number, after.number))) : void 0).orderBy(asc(table.repositoryFullName), asc(table.number)).limit(input.limit);
1873
1938
  }
1939
+ // src/pull-request-review-again.ts
1940
+ const reactorsSchema = z.object({ reactionGroups: z.array(z.object({
1941
+ content: z.string(),
1942
+ reactors: z.object({ nodes: z.array(z.object({ databaseId: z.number().optional() }).nullable()) })
1943
+ })) });
1944
+ const checkContextSchema$1 = z.discriminatedUnion("__typename", [z.object({
1945
+ __typename: z.literal("CheckRun"),
1946
+ conclusion: z.string().nullable(),
1947
+ name: z.string(),
1948
+ status: z.string()
1949
+ }), z.object({
1950
+ __typename: z.literal("StatusContext"),
1951
+ context: z.string(),
1952
+ state: z.string()
1953
+ })]);
1954
+ const requiredChecksSchema = z.object({
1955
+ baseRef: z.object({ refUpdateRule: z.object({ requiredStatusCheckContexts: z.array(z.string().nullable()).nullable() }).nullable() }).nullable(),
1956
+ baseRefName: z.string().min(1),
1957
+ commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ contexts: z.object({
1958
+ nodes: z.array(checkContextSchema$1.nullable()),
1959
+ pageInfo: z.object({ hasNextPage: z.boolean() })
1960
+ }) }).nullable() }) })) })
1961
+ });
1962
+ const requiredChecksReadSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: requiredChecksSchema }) }) });
1963
+ const reviewAgainSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: requiredChecksSchema.extend({
1964
+ reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({
1965
+ __typename: z.string(),
1966
+ login: z.string().optional()
1967
+ }).nullable() }).nullable()) }),
1968
+ reviews: z.object({ nodes: z.array(reactorsSchema.extend({
1969
+ body: z.string(),
1970
+ comments: z.object({
1971
+ nodes: z.array(reactorsSchema.extend({ databaseId: z.number().nullable() }).nullable()),
1972
+ totalCount: z.number()
1973
+ }),
1974
+ databaseId: z.number().nullable(),
1975
+ state: z.string(),
1976
+ submittedAt: z.string().nullable()
1977
+ }).nullable()) }),
1978
+ timelineItems: z.object({ nodes: z.array(z.object({
1979
+ createdAt: z.string().optional(),
1980
+ requestedReviewer: z.object({ login: z.string().optional() }).nullable().optional()
1981
+ }).nullable()) })
1982
+ }) }) }) });
1983
+ const branchRulesSchema = z.array(z.object({
1984
+ parameters: z.object({ required_status_checks: z.array(z.object({ context: z.string() })).optional() }).optional(),
1985
+ type: z.string()
1986
+ }));
1987
+ const MARKED_CONTENTS = /* @__PURE__ */ new Set(["THUMBS_DOWN", "THUMBS_UP"]);
1988
+ const PASSING_CONCLUSIONS = /* @__PURE__ */ new Set([
1989
+ "NEUTRAL",
1990
+ "SKIPPED",
1991
+ "SUCCESS"
1992
+ ]);
1993
+ /** Return whether one check run or commit status passes, fails, or waits. */
1994
+ function checkContextState(context) {
1995
+ if (context.__typename === "CheckRun") {
1996
+ if (context.status !== "COMPLETED") return "pending";
1997
+ return PASSING_CONCLUSIONS.has(context.conclusion ?? "") ? "passing" : "failing";
1998
+ }
1999
+ if (context.state === "SUCCESS") return "passing";
2000
+ return context.state === "PENDING" || context.state === "EXPECTED" ? "pending" : "failing";
2001
+ }
2002
+ function markedBy(reactable, botUserId) {
2003
+ return reactable.reactionGroups.some((group) => MARKED_CONTENTS.has(group.content) && group.reactors.nodes.some((reactor) => reactor?.databaseId === botUserId));
2004
+ }
2005
+ /**
2006
+ * Return whether every required check passes. A required check that has
2007
+ * not reported yet waits, so the ask does not go out before CI starts.
2008
+ */
2009
+ function requiredChecksPass(required, contexts, incomplete) {
2010
+ for (const name of required) {
2011
+ const states = contexts.filter((context) => (context.__typename === "CheckRun" ? context.name : context.context) === name).map(checkContextState);
2012
+ if (states.length === 0 && incomplete) return false;
2013
+ if (states.length === 0 || states.some((state) => state !== "passing")) return false;
2014
+ }
2015
+ return true;
2016
+ }
2017
+ const REVIEWS_READ = 20;
2018
+ /**
2019
+ * Return the reviews whose comments Junior must mark before it asks again,
2020
+ * oldest first, or undefined when there is no feedback to answer. The
2021
+ * feedback is the reviewer's latest change request. For the requester
2022
+ * (`commentsCount`), it also takes their comment-only reviews after their
2023
+ * latest approval or change request. After an approval, only the
2024
+ * comment-only reviews after a later ask count, so a comment on an
2025
+ * approved pull request does not ask again. For others, a comment-only
2026
+ * review is left out, so a reply to Junior does not hide their change
2027
+ * request. A full page of comment-only reviews can hide older reviews,
2028
+ * which count as open.
2029
+ */
2030
+ async function feedbackReviews(reviews, askedAt, commentsCount) {
2031
+ let decidedIndex = reviews.length - 1;
2032
+ while (decidedIndex >= 0 && reviews[decidedIndex]?.state === "COMMENTED") decidedIndex -= 1;
2033
+ const decided = reviews[decidedIndex];
2034
+ const decidedAt = decided?.state === "APPROVED" || decided?.state === "DISMISSED" ? Date.parse(decided.submittedAt ?? "") : void 0;
2035
+ const comments = reviews.slice(decidedIndex + 1).filter((review) => decidedAt === void 0 || askedAt > decidedAt && Date.parse(review.submittedAt ?? "") > askedAt);
2036
+ const changeRequest = decided?.state === "CHANGES_REQUESTED";
2037
+ if (comments.length > 0 && await commentsCount()) {
2038
+ if (decided === void 0 && reviews.length >= REVIEWS_READ) return;
2039
+ return changeRequest ? [decided, ...comments] : comments;
2040
+ }
2041
+ return changeRequest ? [decided] : void 0;
2042
+ }
2043
+ /**
2044
+ * Read whether `reviewer`'s latest change request on a pull request is
2045
+ * ready for their review again. The comments of a change request are its
2046
+ * inline comments and its body. An empty body counts only when the review
2047
+ * has no inline comments.
2048
+ */
2049
+ async function readReviewAgainReadiness(read, target) {
2050
+ const { name, number, owner, reviewer } = target;
2051
+ const pull = reviewAgainSchema.parse(await read({
2052
+ body: {
2053
+ ...PULL_REQUEST_REVIEW_AGAIN,
2054
+ variables: {
2055
+ name,
2056
+ number,
2057
+ owner,
2058
+ reviewer
2059
+ }
2060
+ },
2061
+ operation: "github.pull.review-again.get",
2062
+ path: "/graphql"
2063
+ })).data.repository.pullRequest;
2064
+ const lower = reviewer.toLowerCase();
2065
+ if (pull.reviewRequests.nodes.some((request) => request?.requestedReviewer?.login?.toLowerCase() === lower)) return "none";
2066
+ const askedAt = Math.max(Number.NEGATIVE_INFINITY, ...pull.timelineItems.nodes.flatMap((item) => item?.createdAt && item.requestedReviewer?.login?.toLowerCase() === lower ? [Date.parse(item.createdAt)] : []));
2067
+ const reviews = await feedbackReviews(pull.reviews.nodes.filter((review) => review !== null), askedAt, async () => await target.isRequester?.() ?? false);
2068
+ if (!reviews) return "none";
2069
+ const { marked } = target;
2070
+ const justMarked = (id, kind) => marked?.kind === kind && marked.id === id;
2071
+ for (const review of reviews) {
2072
+ const comments = review.comments.nodes.filter((comment) => comment !== null);
2073
+ if (comments.length < review.comments.totalCount) return "none";
2074
+ const bodyMarked = justMarked(review.databaseId, "review_body") || markedBy(review, target.botUserId);
2075
+ if ((review.body.trim() !== "" || comments.length === 0) && !bodyMarked) return "none";
2076
+ if (!comments.every((comment) => justMarked(comment.databaseId, "review") || markedBy(comment, target.botUserId))) return "none";
2077
+ }
2078
+ return await readRequiredChecksPass(read, target, pull) ? "ready" : "checks";
2079
+ }
2080
+ async function readRequiredChecksPass(read, target, pull) {
2081
+ const { name, owner } = target;
2082
+ const rules = branchRulesSchema.parse(await read({
2083
+ operation: "github.repo.branch-rules.get",
2084
+ path: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/rules/branches/${encodeURIComponent(pull.baseRefName)}?per_page=100`
2085
+ }));
2086
+ const required = /* @__PURE__ */ new Set([...(pull.baseRef?.refUpdateRule?.requiredStatusCheckContexts ?? []).filter((context) => Boolean(context)), ...rules.flatMap((rule) => rule.type === "required_status_checks" ? (rule.parameters?.required_status_checks ?? []).map((check) => check.context) : [])]);
2087
+ const rollup = pull.commits.nodes[0]?.commit.statusCheckRollup;
2088
+ return requiredChecksPass(required, (rollup?.contexts.nodes ?? []).filter((context) => context !== null), rollup?.contexts.pageInfo.hasNextPage ?? false);
2089
+ }
2090
+ /**
2091
+ * Read whether every required check of a pull request's head commit
2092
+ * passes, so an ask for a review does not go out before CI is green.
2093
+ */
2094
+ async function readGitHubRequiredChecksPass(read, target) {
2095
+ const { name, number, owner } = target;
2096
+ const pull = requiredChecksReadSchema.parse(await read({
2097
+ body: {
2098
+ ...PULL_REQUEST_REQUIRED_CHECKS,
2099
+ variables: {
2100
+ name,
2101
+ number,
2102
+ owner
2103
+ }
2104
+ },
2105
+ operation: "github.pull.required-checks.get",
2106
+ path: "/graphql"
2107
+ })).data.repository.pullRequest;
2108
+ return await readRequiredChecksPass(read, target, pull);
2109
+ }
2110
+ const HELD_ASK_TTL_MS = 2592e5;
2111
+ const heldAskSchema = z.object({
2112
+ at: z.iso.datetime(),
2113
+ reason: z.enum(["checks", "handled"]),
2114
+ reviewer: z.string().min(1),
2115
+ marked: z.object({
2116
+ id: z.number(),
2117
+ kind: z.enum(["review", "review_body"])
2118
+ }).optional()
2119
+ });
2120
+ function heldAskKey(target) {
2121
+ return `pull-request-review-again:${target.repositoryFullName.toLowerCase()}#${target.number}`;
2122
+ }
2123
+ /** Save the review ask that waits for the checks of one pull request. */
2124
+ async function holdGitHubReviewAsk(state, target, ask) {
2125
+ await state.set(heldAskKey(target), heldAskSchema.parse(ask), HELD_ASK_TTL_MS);
2126
+ }
2127
+ /** Return the review ask that waits for the checks of one pull request. */
2128
+ async function readHeldGitHubReviewAsk(state, target) {
2129
+ const saved = heldAskSchema.safeParse(await state.get(heldAskKey(target)));
2130
+ return saved.success ? saved.data : void 0;
2131
+ }
2132
+ /**
2133
+ * Drop the held review ask of one pull request. With `reviewer`, drop it
2134
+ * only when it is for that reviewer.
2135
+ */
2136
+ async function dropHeldGitHubReviewAsk(state, target, reviewer) {
2137
+ if (reviewer !== void 0) {
2138
+ if ((await readHeldGitHubReviewAsk(state, target))?.reviewer.toLowerCase() !== reviewer.toLowerCase()) return;
2139
+ }
2140
+ await state.delete(heldAskKey(target));
2141
+ }
2142
+ const ASKED_TTL_MS = 36e5;
2143
+ const askedSchema = z.object({
2144
+ at: z.iso.datetime(),
2145
+ reason: z.enum(["handled", "question"]).optional(),
2146
+ reviewer: z.string().min(1)
2147
+ });
2148
+ function askedKey(target) {
2149
+ return `pull-request-review-asked:${target.repositoryFullName.toLowerCase()}#${target.number}`;
2150
+ }
2151
+ /** Record that a Junior tool asked `reviewer` on one pull request. */
2152
+ async function markGitHubReviewAsked(state, target, asked) {
2153
+ await state.set(askedKey(target), askedSchema.parse(asked), ASKED_TTL_MS);
2154
+ }
2155
+ /** Return the review that a Junior tool asked for on one pull request. */
2156
+ async function readGitHubReviewAsked(state, target) {
2157
+ const saved = askedSchema.safeParse(await state.get(askedKey(target)));
2158
+ return saved.success ? saved.data : void 0;
2159
+ }
2160
+ /** Drop the record of a review that a Junior tool asked for. */
2161
+ async function dropGitHubReviewAsked(state, target) {
2162
+ await state.delete(askedKey(target));
2163
+ }
1874
2164
  // src/tools/comment-on-pull-request.ts
1875
2165
  const inputSchema$12 = z.object({
1876
2166
  repo: z.string().describe("Repository in \"owner/name\" format."),
@@ -1922,12 +2212,23 @@ async function askRequester(ctx, target) {
1922
2212
  }).then((openers) => openers.get(target.number)), ctx.resolveWorkOwner().then(requesterPerson)]);
1923
2213
  const login = opener?.conversationId && owner?.identity?.id === opener.identityId ? linkedGitHubLogin(owner.user) : void 0;
1924
2214
  if (!login) return false;
1925
- const response = await githubApi(ctx.egress, {
2215
+ await markGitHubReviewAsked(ctx.state, {
2216
+ number: target.number,
2217
+ repositoryFullName: target.repo
2218
+ }, {
2219
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2220
+ reason: "question",
2221
+ reviewer: login
2222
+ });
2223
+ const path = `${target.prefix}/pulls/${target.number}/requested_reviewers`;
2224
+ const removed = await isRequested$1(ctx, path, login) && (await githubApi(ctx.egress, {
1926
2225
  operation: "github.pull.request_reviewers",
1927
- method: "POST",
1928
- path: `${target.prefix}/pulls/${target.number}/requested_reviewers`,
2226
+ method: "DELETE",
2227
+ path,
1929
2228
  body: { reviewers: [login] }
1930
- });
2229
+ })).ok;
2230
+ let response = await requestReviewer$1(ctx, path, login);
2231
+ if (removed && isTransient(response.status)) response = await requestReviewer$1(ctx, path, login);
1931
2232
  if (response.ok) return true;
1932
2233
  ctx.log.warn("github.pull_request.request_reviewers_after_question.rejected", {
1933
2234
  ...fields,
@@ -1941,6 +2242,29 @@ async function askRequester(ctx, target) {
1941
2242
  }
1942
2243
  return false;
1943
2244
  }
2245
+ function requestReviewer$1(ctx, path, login) {
2246
+ return githubApi(ctx.egress, {
2247
+ operation: "github.pull.request_reviewers",
2248
+ method: "POST",
2249
+ path,
2250
+ body: { reviewers: [login] }
2251
+ });
2252
+ }
2253
+ function isTransient(status) {
2254
+ return status === 429 || status >= 500;
2255
+ }
2256
+ /** Whether GitHub asks `login` for a review of the pull request now. */
2257
+ async function isRequested$1(ctx, path, login) {
2258
+ const response = await githubApi(ctx.egress, {
2259
+ operation: "github.pull.request_reviewers",
2260
+ method: "GET",
2261
+ path
2262
+ });
2263
+ if (!response.ok) return false;
2264
+ const parsed = z.object({ users: z.array(z.object({ login: z.string() })) }).safeParse(response.body);
2265
+ const lower = login.toLowerCase();
2266
+ return parsed.success && parsed.data.users.some((user) => user.login.toLowerCase() === lower);
2267
+ }
1944
2268
  /**
1945
2269
  * Post a pull request comment as the App bot, or reply in an inline review
1946
2270
  * thread. GitHub keeps conversation comments under the issues endpoint and
@@ -3191,169 +3515,6 @@ async function readDraftReadiness(egress, repo, pullRequest) {
3191
3515
  codeOwners: codeOwners ? codeOwnersOf(parseCodeOwners(codeOwners), paths) : []
3192
3516
  };
3193
3517
  }
3194
- // src/pull-request-review-again.ts
3195
- const reactorsSchema = z.object({ reactionGroups: z.array(z.object({
3196
- content: z.string(),
3197
- reactors: z.object({ nodes: z.array(z.object({ databaseId: z.number().optional() }).nullable()) })
3198
- })) });
3199
- const checkContextSchema$1 = z.discriminatedUnion("__typename", [z.object({
3200
- __typename: z.literal("CheckRun"),
3201
- conclusion: z.string().nullable(),
3202
- name: z.string(),
3203
- status: z.string()
3204
- }), z.object({
3205
- __typename: z.literal("StatusContext"),
3206
- context: z.string(),
3207
- state: z.string()
3208
- })]);
3209
- const reviewAgainSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
3210
- baseRef: z.object({ refUpdateRule: z.object({ requiredStatusCheckContexts: z.array(z.string().nullable()).nullable() }).nullable() }).nullable(),
3211
- baseRefName: z.string().min(1),
3212
- commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ contexts: z.object({
3213
- nodes: z.array(checkContextSchema$1.nullable()),
3214
- pageInfo: z.object({ hasNextPage: z.boolean() })
3215
- }) }).nullable() }) })) }),
3216
- reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({
3217
- __typename: z.string(),
3218
- login: z.string().optional()
3219
- }).nullable() }).nullable()) }),
3220
- reviews: z.object({ nodes: z.array(reactorsSchema.extend({
3221
- body: z.string(),
3222
- comments: z.object({
3223
- nodes: z.array(reactorsSchema.extend({ databaseId: z.number().nullable() }).nullable()),
3224
- totalCount: z.number()
3225
- }),
3226
- databaseId: z.number().nullable(),
3227
- state: z.string()
3228
- }).nullable()) })
3229
- }) }) }) });
3230
- const branchRulesSchema = z.array(z.object({
3231
- parameters: z.object({ required_status_checks: z.array(z.object({ context: z.string() })).optional() }).optional(),
3232
- type: z.string()
3233
- }));
3234
- const MARKED_CONTENTS = /* @__PURE__ */ new Set(["THUMBS_DOWN", "THUMBS_UP"]);
3235
- const PASSING_CONCLUSIONS = /* @__PURE__ */ new Set([
3236
- "NEUTRAL",
3237
- "SKIPPED",
3238
- "SUCCESS"
3239
- ]);
3240
- /** Return whether one check run or commit status passes, fails, or waits. */
3241
- function checkContextState(context) {
3242
- if (context.__typename === "CheckRun") {
3243
- if (context.status !== "COMPLETED") return "pending";
3244
- return PASSING_CONCLUSIONS.has(context.conclusion ?? "") ? "passing" : "failing";
3245
- }
3246
- if (context.state === "SUCCESS") return "passing";
3247
- return context.state === "PENDING" || context.state === "EXPECTED" ? "pending" : "failing";
3248
- }
3249
- function markedBy(reactable, botUserId) {
3250
- return reactable.reactionGroups.some((group) => MARKED_CONTENTS.has(group.content) && group.reactors.nodes.some((reactor) => reactor?.databaseId === botUserId));
3251
- }
3252
- /**
3253
- * Return whether every required check passes. A required check that has
3254
- * not reported yet waits, so the ask does not go out before CI starts.
3255
- */
3256
- function requiredChecksPass(required, contexts, incomplete) {
3257
- for (const name of required) {
3258
- const states = contexts.filter((context) => (context.__typename === "CheckRun" ? context.name : context.context) === name).map(checkContextState);
3259
- if (states.length === 0 && incomplete) return false;
3260
- if (states.length === 0 || states.some((state) => state !== "passing")) return false;
3261
- }
3262
- return true;
3263
- }
3264
- /**
3265
- * Read whether `reviewer`'s latest change request on a pull request is
3266
- * ready for their review again. The comments of a change request are its
3267
- * inline comments and its body. An empty body counts only when the review
3268
- * has no inline comments.
3269
- */
3270
- async function readReviewAgainReadiness(read, target) {
3271
- const { name, number, owner, reviewer } = target;
3272
- const pull = reviewAgainSchema.parse(await read({
3273
- body: {
3274
- ...PULL_REQUEST_REVIEW_AGAIN,
3275
- variables: {
3276
- name,
3277
- number,
3278
- owner,
3279
- reviewer
3280
- }
3281
- },
3282
- operation: "github.pull.review-again.get",
3283
- path: "/graphql"
3284
- })).data.repository.pullRequest;
3285
- const lower = reviewer.toLowerCase();
3286
- const requested = pull.reviewRequests.nodes.some((request) => request?.requestedReviewer?.login?.toLowerCase() === lower);
3287
- const review = pull.reviews.nodes[0];
3288
- if (requested || review?.state !== "CHANGES_REQUESTED") return "none";
3289
- const comments = review.comments.nodes.filter((comment) => comment !== null);
3290
- if (comments.length < review.comments.totalCount) return "none";
3291
- const { marked } = target;
3292
- const justMarked = (id, kind) => marked?.kind === kind && marked.id === id;
3293
- const bodyMarked = justMarked(review.databaseId, "review_body") || markedBy(review, target.botUserId);
3294
- if ((review.body.trim() !== "" || comments.length === 0) && !bodyMarked) return "none";
3295
- if (!comments.every((comment) => justMarked(comment.databaseId, "review") || markedBy(comment, target.botUserId))) return "none";
3296
- const rules = branchRulesSchema.parse(await read({
3297
- operation: "github.repo.branch-rules.get",
3298
- path: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/rules/branches/${encodeURIComponent(pull.baseRefName)}?per_page=100`
3299
- }));
3300
- const required = /* @__PURE__ */ new Set([...(pull.baseRef?.refUpdateRule?.requiredStatusCheckContexts ?? []).filter((context) => Boolean(context)), ...rules.flatMap((rule) => rule.type === "required_status_checks" ? (rule.parameters?.required_status_checks ?? []).map((check) => check.context) : [])]);
3301
- const rollup = pull.commits.nodes[0]?.commit.statusCheckRollup;
3302
- return requiredChecksPass(required, (rollup?.contexts.nodes ?? []).filter((context) => context !== null), rollup?.contexts.pageInfo.hasNextPage ?? false) ? "ready" : "checks";
3303
- }
3304
- const HELD_ASK_TTL_MS = 2592e5;
3305
- const heldAskSchema = z.object({
3306
- at: z.iso.datetime(),
3307
- reason: z.enum(["checks", "handled"]),
3308
- reviewer: z.string().min(1),
3309
- marked: z.object({
3310
- id: z.number(),
3311
- kind: z.enum(["review", "review_body"])
3312
- }).optional()
3313
- });
3314
- function heldAskKey(target) {
3315
- return `pull-request-review-again:${target.repositoryFullName.toLowerCase()}#${target.number}`;
3316
- }
3317
- /** Save the review ask that waits for the checks of one pull request. */
3318
- async function holdGitHubReviewAsk(state, target, ask) {
3319
- await state.set(heldAskKey(target), heldAskSchema.parse(ask), HELD_ASK_TTL_MS);
3320
- }
3321
- /** Return the review ask that waits for the checks of one pull request. */
3322
- async function readHeldGitHubReviewAsk(state, target) {
3323
- const saved = heldAskSchema.safeParse(await state.get(heldAskKey(target)));
3324
- return saved.success ? saved.data : void 0;
3325
- }
3326
- /**
3327
- * Drop the held review ask of one pull request. With `reviewer`, drop it
3328
- * only when it is for that reviewer.
3329
- */
3330
- async function dropHeldGitHubReviewAsk(state, target, reviewer) {
3331
- if (reviewer !== void 0) {
3332
- if ((await readHeldGitHubReviewAsk(state, target))?.reviewer.toLowerCase() !== reviewer.toLowerCase()) return;
3333
- }
3334
- await state.delete(heldAskKey(target));
3335
- }
3336
- const ASKED_TTL_MS = 36e5;
3337
- const askedSchema = z.object({
3338
- at: z.iso.datetime(),
3339
- reviewer: z.string().min(1)
3340
- });
3341
- function askedKey(target) {
3342
- return `pull-request-review-asked:${target.repositoryFullName.toLowerCase()}#${target.number}`;
3343
- }
3344
- /** Record that the feedback tool asked `reviewer` again on one pull request. */
3345
- async function markGitHubReviewAsked(state, target, asked) {
3346
- await state.set(askedKey(target), askedSchema.parse(asked), ASKED_TTL_MS);
3347
- }
3348
- /** Return the review that the feedback tool asked for on one pull request. */
3349
- async function readGitHubReviewAsked(state, target) {
3350
- const saved = askedSchema.safeParse(await state.get(askedKey(target)));
3351
- return saved.success ? saved.data : void 0;
3352
- }
3353
- /** Drop the record of a review that the feedback tool asked for. */
3354
- async function dropGitHubReviewAsked(state, target) {
3355
- await state.delete(askedKey(target));
3356
- }
3357
3518
  // src/tools/get-pull-request.ts
3358
3519
  const commitShaSchema = z.string().regex(/^[0-9a-f]{40}$/i);
3359
3520
  const RELATED_CONVERSATIONS_MAX = 10;
@@ -3969,8 +4130,9 @@ const inputSchema$3 = z.object({
3969
4130
  body: z.string().optional().describe(`Replacement pull request body. ${PULL_REQUEST_BODY_RULES}`),
3970
4131
  base: z.string().trim().min(1).optional().describe("Replacement base branch."),
3971
4132
  state: z.enum(["open", "closed"]).optional().describe("Replacement pull request state."),
3972
- draft: z.boolean().optional().describe("Set false to mark a draft pull request ready for review, or true to convert it back to a draft.")
3973
- }).strict().refine(({ title, body, base, state, draft }) => title !== void 0 || body !== void 0 || base !== void 0 || state !== void 0 || draft !== void 0, { message: "At least one pull request field must be provided." });
4133
+ draft: z.boolean().optional().describe("Set false to mark a draft pull request ready for review, or true to convert it back to a draft."),
4134
+ request_review: z.literal(true).optional().describe("Set true to ask only the person who asked for the pull request to review it on GitHub. A draft stays a draft, so nobody else is asked. A person who has reviewed it is not asked again, unless their latest approval or change request was dismissed.")
4135
+ }).strict().refine(({ title, body, base, state, draft, request_review }) => title !== void 0 || body !== void 0 || base !== void 0 || state !== void 0 || draft !== void 0 || request_review !== void 0, { message: "At least one pull request field must be provided." });
3974
4136
  const draftMutationResponseSchema = z.object({ data: z.object({ result: z.object({ pullRequest: z.object({ isDraft: z.boolean() }) }) }) });
3975
4137
  const pullRequestSchema = z.object({
3976
4138
  base: z.string(),
@@ -3982,7 +4144,10 @@ const pullRequestSchema = z.object({
3982
4144
  title: z.string(),
3983
4145
  url: z.string()
3984
4146
  });
3985
- const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema.extend({ target: z.literal("updatePullRequest") }));
4147
+ const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema.extend({
4148
+ review_requested: z.boolean().optional().describe("With request_review: true when GitHub asks the person for a review, false when they have reviewed it and their latest approval or change request was not dismissed."),
4149
+ target: z.literal("updatePullRequest")
4150
+ }));
3986
4151
  function nonEmptyString(value, name) {
3987
4152
  if (!value?.trim()) throw new PluginToolInputError(`${name} is missing in this Turn, so the GitHub footer cannot be added. No change to the call can fix this.`);
3988
4153
  return value.trim();
@@ -4004,6 +4169,65 @@ async function setPullRequestDraft(input) {
4004
4169
  if (!response.ok || isDraft !== input.draft) throw new Error(`GitHub pull request draft update failed with HTTP ${response.status}: ${githubErrorMessage$1(payload)}`);
4005
4170
  return isDraft;
4006
4171
  }
4172
+ const reviewerSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4173
+ reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({ login: z.string().optional() }).nullable() })) }),
4174
+ reviews: z.object({ nodes: z.array(z.object({ state: z.string() })) })
4175
+ }) }) }) });
4176
+ /**
4177
+ * Ask the requester to review a pull request on GitHub, and return true when
4178
+ * GitHub asks them after the call.
4179
+ *
4180
+ * Junior keeps a draft for its requester when marking it ready would ask the
4181
+ * code owners. A review request asks only the person it names, and the Inbox
4182
+ * item follows from it (`webhooks/pull-request-action.ts`). A person whom
4183
+ * GitHub already asks is not asked again. Nor is a person who has reviewed
4184
+ * it, and the result is false: after a change request or a comment-only
4185
+ * review, only the review-again flow asks, and an approved draft's item says
4186
+ * to mark it ready. An approval stands when a comment follows it. A person
4187
+ * with no review yet is asked. So is one whose latest approval or change
4188
+ * request was dismissed, also with comments since: a dismissal resets their
4189
+ * decision, so those comments wait for a new ask
4190
+ * (`webhooks/pull-request-next-action.ts`).
4191
+ */
4192
+ async function requestRequesterReview(egress, repo, number, login) {
4193
+ const read = await githubApi(egress, {
4194
+ operation: "github.pull.reviewer.get",
4195
+ method: "POST",
4196
+ path: "/graphql",
4197
+ body: {
4198
+ ...PULL_REQUEST_REVIEWER,
4199
+ variables: {
4200
+ login,
4201
+ name: repo.name,
4202
+ number,
4203
+ owner: repo.owner
4204
+ }
4205
+ }
4206
+ });
4207
+ const parsed = reviewerSchema.safeParse(read.body);
4208
+ if (!read.ok || !parsed.success) {
4209
+ const message = `GitHub pull request reviewer lookup failed with HTTP ${read.status}: ${githubErrorMessage$1(read.body)}`;
4210
+ throw new Error(message);
4211
+ }
4212
+ const { pullRequest } = parsed.data.data.repository;
4213
+ const lower = login.toLowerCase();
4214
+ if (pullRequest.reviewRequests.nodes.some((node) => node.requestedReviewer?.login?.toLowerCase() === lower)) return true;
4215
+ const states = pullRequest.reviews.nodes.map((review) => review.state);
4216
+ const decided = [...states].reverse().find((state) => state !== "COMMENTED");
4217
+ if (decided ? decided !== "DISMISSED" : states.length > 0) return false;
4218
+ const response = await githubApi(egress, {
4219
+ operation: "github.pull.request_reviewers",
4220
+ method: "POST",
4221
+ path: `${repoPath(repo)}/pulls/${number}/requested_reviewers`,
4222
+ body: { reviewers: [login] }
4223
+ });
4224
+ if (!response.ok) {
4225
+ const message = `GitHub review request for ${login} failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`;
4226
+ if (response.status === 422) throw new PluginToolInputError(`${message}. Do not retry: tell them in the thread where they asked.`);
4227
+ throw new Error(message);
4228
+ }
4229
+ return true;
4230
+ }
4007
4231
  /** Update mutable PR metadata while preserving runtime-owned body attribution. */
4008
4232
  function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4009
4233
  return definePluginTool({
@@ -4023,6 +4247,8 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4023
4247
  if (descriptionChecks && update.body !== void 0) await checkPullRequestDescription(ctx.decider, update.body);
4024
4248
  const repo = parseRepo$1(update.repo);
4025
4249
  const requester = await resolveGitHubRequester(ctx);
4250
+ const reviewerLogin = update.request_review ? linkedGitHubLogin(requesterPerson(requester)?.user) : void 0;
4251
+ if (update.request_review && !reviewerLogin) throw new PluginToolInputError("The person who asked for this pull request has no linked GitHub account, so GitHub cannot ask for their review. Do not retry: tell them in the thread where they asked.");
4026
4252
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
4027
4253
  operation: "github.pull.get",
4028
4254
  path: `${repoPath(repo)}/pulls/${update.pull_request}`
@@ -4083,6 +4309,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4083
4309
  repositoryFullName: repo.ref
4084
4310
  });
4085
4311
  }
4312
+ const reviewRequested = reviewerLogin ? await requestRequesterReview(ctx.egress, repo, providerResult.number, reviewerLogin) : void 0;
4086
4313
  const subscribable = gitHubPullRequestSubscribable({
4087
4314
  canSubscribe: ctx.events.canSubscribe,
4088
4315
  number: providerResult.number,
@@ -4111,6 +4338,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4111
4338
  objectType: "code_change",
4112
4339
  status: providerResult.merged ? "merged" : providerResult.state === "open" && providerResult.draft ? "draft" : providerResult.state
4113
4340
  })],
4341
+ ...reviewRequested !== void 0 ? { review_requested: reviewRequested } : void 0,
4114
4342
  target: "updatePullRequest",
4115
4343
  ...data
4116
4344
  };
@@ -4296,8 +4524,22 @@ async function reviewBodyReactions(egress, input) {
4296
4524
  };
4297
4525
  }
4298
4526
  /**
4527
+ * Whether `reviewer` is the person who asked Junior for the pull request.
4528
+ * Only the opener row of a pull request that Junior opened has a
4529
+ * Conversation, and only that person's own work knows their linked GitHub
4530
+ * login, as when Junior asks them a question.
4531
+ */
4532
+ async function reviewerIsRequester(ctx, input) {
4533
+ const [opener, owner] = await Promise.all([listGitHubPullRequestOpeners(gitHubDbSchema.parse(ctx.db), {
4534
+ numbers: [input.pullRequest],
4535
+ repositoryFullName: `${input.owner}/${input.name}`
4536
+ }).then((openers) => openers.get(input.pullRequest)), ctx.resolveWorkOwner().then(requesterPerson)]);
4537
+ return (opener?.conversationId && owner?.identity?.id === opener.identityId ? linkedGitHubLogin(owner.user) : void 0)?.toLowerCase() === input.reviewer.toLowerCase();
4538
+ }
4539
+ /**
4299
4540
  * Ask the reviewer to review again when every comment of their latest
4300
- * change request is marked and the required checks pass. GitHub stops
4541
+ * change request is marked and the required checks pass. For the requester,
4542
+ * their comment-only reviews count as a change request. GitHub stops
4301
4543
  * asking a reviewer once they review, so the fixed pull request would not
4302
4544
  * wait on them. While the checks have not passed, the ask is held, and the
4303
4545
  * check suite webhook asks when they pass. The ask is optional, so a failure
@@ -4322,6 +4564,7 @@ async function askForReviewAgain(ctx, input) {
4322
4564
  return response.body;
4323
4565
  }, {
4324
4566
  ...input,
4567
+ isRequester: async () => await reviewerIsRequester(ctx, input),
4325
4568
  number: input.pullRequest
4326
4569
  });
4327
4570
  if (readiness === "none") return;
@@ -4401,7 +4644,7 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
4401
4644
  openWorldHint: true,
4402
4645
  readOnlyHint: false
4403
4646
  },
4404
- description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after you act on or reply to the feedback. Replaces only your prior status reaction on that comment. When every comment of the author's latest change request is marked and the required checks pass, asks the author to review again. Only works on pull requests the bot authored.",
4647
+ description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after you act on or reply to the feedback. Replaces only your prior status reaction on that comment. When every comment of the author's latest change request, or of the requester's latest comment-only reviews, is marked and the required checks pass, asks the author to review again. Only works on pull requests the bot authored.",
4405
4648
  exposure: "direct",
4406
4649
  inputSchema: inputSchema$2,
4407
4650
  outputSchema: outputSchema$2,
@@ -4887,19 +5130,105 @@ async function loadReleaseCategories(env, repositoryFullName) {
4887
5130
  return parseReleaseCategories(Buffer.from(file.data.content, "base64").toString("utf8"));
4888
5131
  }
4889
5132
  /**
4890
- * Return the title parts of a pull request title with its repository's
4891
- * changelog categories. Title parts are optional, so a failed read of the
4892
- * categories is logged, and the default categories apply.
5133
+ * Return the title parts of a pull request title with its repository's
5134
+ * changelog categories. Title parts are optional, so a failed read of the
5135
+ * categories is logged, and the default categories apply.
5136
+ */
5137
+ async function loadGitHubTitleParts(env, input, log) {
5138
+ let categories;
5139
+ try {
5140
+ categories = await loadReleaseCategories(env, input.repositoryFullName);
5141
+ } catch (error) {
5142
+ logFailOpenFailure(log, "GitHub release config read failed", error, { repository: input.repositoryFullName });
5143
+ categories = DEFAULT_CODE_CHANGE_CATEGORIES;
5144
+ }
5145
+ return parseCodeChangeTitle(input.title, categories);
5146
+ }
5147
+ // src/webhooks/pull-request-next-action.ts
5148
+ /** Whether two GitHub logins name the same account. */
5149
+ function sameLogin(a, b) {
5150
+ return b !== void 0 && a.toLowerCase() === b.toLowerCase();
5151
+ }
5152
+ /** Read the requester's latest activity from a pull request's activity. */
5153
+ function latestActivity(activity, requesterLogin) {
5154
+ const latest = {};
5155
+ const keep = (key, at) => {
5156
+ const saved = latest[key];
5157
+ if (!saved || at > saved) latest[key] = at;
5158
+ };
5159
+ for (const entry of activity) {
5160
+ if (!sameLogin(entry.login, requesterLogin)) continue;
5161
+ if (entry.kind === "reviewRequest") keep("askedAt", entry.at);
5162
+ else if (entry.kind === "reviewRequestRemoved") keep("removedAt", entry.at);
5163
+ else {
5164
+ keep("requesterAt", entry.at);
5165
+ if (entry.review !== "COMMENTED") keep("actedAt", entry.at);
5166
+ const review = entry.review && {
5167
+ at: entry.at,
5168
+ state: entry.review
5169
+ };
5170
+ if (review && (!latest.review || review.at > latest.review.at)) latest.review = review;
5171
+ if (review && review.state !== "COMMENTED" && (!latest.decided || review.at > latest.decided.at)) latest.decided = review;
5172
+ }
5173
+ }
5174
+ return latest;
5175
+ }
5176
+ /**
5177
+ * Whether the requester's latest review waits for Junior's answer: a change
5178
+ * request, or a comment-only review, which Junior handles like a change
5179
+ * request. After the requester approves, only a comment-only review after
5180
+ * a later ask counts, so a comment on an approved pull request leaves it
5181
+ * ready to merge. A dismissed review, such as an approval that a push
5182
+ * reset, works the same way: a comment since it waits for a new ask, so a
5183
+ * ready pull request is in limbo and Junior asks. A draft cannot merge, so
5184
+ * it is left out.
5185
+ */
5186
+ function requesterFeedback(state, activity) {
5187
+ const { decided, review } = activity;
5188
+ if (state.draft || !review) return false;
5189
+ if (review.state === "CHANGES_REQUESTED") return true;
5190
+ if (review.state !== "COMMENTED") return false;
5191
+ if (decided?.state !== "APPROVED" && decided?.state !== "DISMISSED") return true;
5192
+ const askedAt = timeOf(activity.askedAt);
5193
+ return askedAt > decided.at.getTime() && review.at.getTime() > askedAt;
5194
+ }
5195
+ /** A time in milliseconds. A missing time is older than every time. */
5196
+ function timeOf(at) {
5197
+ return at ? at.getTime() : Number.NEGATIVE_INFINITY;
5198
+ }
5199
+ /**
5200
+ * Derive the requester's next action. Return undefined when it cannot be
5201
+ * known yet, so a later event decides.
4893
5202
  */
4894
- async function loadGitHubTitleParts(env, input, log) {
4895
- let categories;
4896
- try {
4897
- categories = await loadReleaseCategories(env, input.repositoryFullName);
4898
- } catch (error) {
4899
- logFailOpenFailure(log, "GitHub release config read failed", error, { repository: input.repositoryFullName });
4900
- categories = DEFAULT_CODE_CHANGE_CATEGORIES;
4901
- }
4902
- return parseCodeChangeTitle(input.title, categories);
5203
+ function nextAction(state, requester, saved) {
5204
+ if (state.state !== "open") return {};
5205
+ const canMerge = !state.draft && !state.autoMerge && !state.reviewPending && !requester.feedback;
5206
+ if (canMerge && state.mergeableState === "clean" && state.reviewOutcome !== "changesRequested") return { action: "merge" };
5207
+ if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5208
+ const review = state.draft ? "review_draft" : "review";
5209
+ if (requester.askedAgain) return { action: review };
5210
+ if (isRequested(state, requester.login) && (!requester.actedLast || !requester.feedback)) return { action: review };
5211
+ if (state.draft && state.requesterApproved) return { action: "mark_ready" };
5212
+ if (canMerge && !state.mergeableState) return void 0;
5213
+ return {};
5214
+ }
5215
+ function isRequested(state, login) {
5216
+ const lower = login?.toLowerCase();
5217
+ return state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === lower);
5218
+ }
5219
+ /**
5220
+ * Whether a pull request whose action is none is in limbo: it waits on
5221
+ * nobody, so Junior asks for the requester's review on GitHub. It is open,
5222
+ * not a draft, and auto-merge is off. GitHub does not ask the requester
5223
+ * for a review, and the requester's feedback does not wait for Junior. The
5224
+ * requester has not reviewed since the last push, other than a comment-only
5225
+ * review. No reviewer approved it, so it does not wait only on others, and
5226
+ * no reviewer requests changes, so Junior does not act next. Junior does
5227
+ * not ask when the requester removed their own review request and no one
5228
+ * asked them since.
5229
+ */
5230
+ function inLimbo(state, activity, login) {
5231
+ return state.state === "open" && !state.draft && !state.autoMerge && !isRequested(state, login) && !requesterFeedback(state, activity) && timeOf(activity.removedAt) <= timeOf(activity.askedAt) && timeOf(activity.actedAt) <= timeOf(state.headCommittedAt) && state.reviewOutcome === void 0;
4903
5232
  }
4904
5233
  // src/pull-request-outcomes/store.ts
4905
5234
  /** One pull request lifecycle outcome, as the webhook and reconcile read it. */
@@ -4959,9 +5288,10 @@ async function findGitHubPullRequest(codeChanges, ref) {
4959
5288
  /**
4960
5289
  * Ask to check the next action of a Junior pull request, and claim the check
4961
5290
  * when no other webhook runs one. A claim older than `staleMs` is free.
4962
- * Return the claim and the saved action, or undefined when another webhook
4963
- * runs the check or Junior does not own the pull request. The webhook that
4964
- * runs the check sees the new request in `releaseGitHubPullRequestReadySync`.
5291
+ * Return the claim and the saved action, `held` when another webhook runs
5292
+ * the check, or undefined when Junior does not own the pull request. The
5293
+ * webhook that runs the check sees the new request in
5294
+ * `releaseGitHubPullRequestReadySync`.
4965
5295
  */
4966
5296
  async function claimGitHubPullRequestReadySync(db, pullRequestId, options) {
4967
5297
  const t = juniorGitHubPullRequests;
@@ -4976,7 +5306,8 @@ async function claimGitHubPullRequestReadySync(db, pullRequestId, options) {
4976
5306
  id: t.readySyncId,
4977
5307
  requests: t.readySyncRequests
4978
5308
  });
4979
- if (!row || row.id !== row.requests) return void 0;
5309
+ if (!row) return void 0;
5310
+ if (row.id !== row.requests) return "held";
4980
5311
  return {
4981
5312
  action: row.action ?? void 0,
4982
5313
  id: row.id,
@@ -5243,6 +5574,54 @@ async function closeGitHubConflictItems(args) {
5243
5574
  };
5244
5575
  await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
5245
5576
  }
5577
+ // src/webhooks/pull-request-action-text.ts
5578
+ /** Why an item closes when its pull request is no longer open. */
5579
+ const ENDED_REASONS = {
5580
+ closed: {
5581
+ reason: "The pull request closed without merging.",
5582
+ status: "dismissed"
5583
+ },
5584
+ merged: {
5585
+ reason: "The pull request merged.",
5586
+ status: "done"
5587
+ }
5588
+ };
5589
+ /** Why an item closes, when its pull request is no longer open. */
5590
+ function endedReason(state) {
5591
+ return state === "open" ? void 0 : ENDED_REASONS[state];
5592
+ }
5593
+ /** Why the item of a pull request whose next action ended closes. */
5594
+ function closeReason(state, previous) {
5595
+ const ended = endedReason(state.state);
5596
+ if (ended) return ended;
5597
+ if (previous !== "merge") return {
5598
+ reason: "The review request ended.",
5599
+ status: "done"
5600
+ };
5601
+ if (state.autoMerge) return {
5602
+ reason: "Auto-merge is on.",
5603
+ status: "dismissed"
5604
+ };
5605
+ return {
5606
+ reason: "The pull request is no longer ready to merge.",
5607
+ status: "dismissed"
5608
+ };
5609
+ }
5610
+ /** The item text that says why Junior asked for the review again. */
5611
+ const REVIEW_AGAIN_TEXT = {
5612
+ checks: "Checks now pass, and every comment is handled.",
5613
+ handled: "Every comment on your review is handled.",
5614
+ question: "A comment asks you a question."
5615
+ };
5616
+ /** The item text for a pull request's next action. */
5617
+ function actionText(action, number, reason, state) {
5618
+ if (action === "merge") return state.reviewOutcome === "approved" ? `#${number} is approved, and GitHub says that it can merge.` : `GitHub says that #${number} can merge with no review. Review it, then merge it.`;
5619
+ const asked = reason ? REVIEW_AGAIN_TEXT[reason] : void 0;
5620
+ if (action === "review") return asked ?? `GitHub asks you to review #${number}.`;
5621
+ if (action === "mark_ready") return `You approved #${number}. Mark it ready for review.`;
5622
+ const step = `#${number} is a draft. Review it, then mark it ready for review.`;
5623
+ return asked ? `${asked} ${step}` : step;
5624
+ }
5246
5625
  // src/webhooks/graphql-request.ts
5247
5626
  /**
5248
5627
  * GitHub GraphQL requests that fail on a response with errors and no data.
@@ -5252,9 +5631,12 @@ async function closeGitHubConflictItems(args) {
5252
5631
  * HTTP 200, such as when the installation is rate limited.
5253
5632
  */
5254
5633
  var GitHubGraphqlError = class extends Error {
5255
- constructor(message) {
5634
+ /** GitHub's error types, such as `RATE_LIMIT`. GitHub's own failures have none. */
5635
+ types;
5636
+ constructor(message, types) {
5256
5637
  super(message);
5257
5638
  this.name = "GitHubGraphqlError";
5639
+ this.types = types;
5258
5640
  }
5259
5641
  };
5260
5642
  const graphqlFailureSchema = z.object({
@@ -5275,7 +5657,7 @@ async function githubGraphqlRequest(params) {
5275
5657
  method: "POST"
5276
5658
  });
5277
5659
  const failure = graphqlFailureSchema.safeParse(response);
5278
- if (failure.success) throw new GitHubGraphqlError(failure.data.errors.map((error) => error.type ? `${error.type}: ${error.message}` : error.message).join("; "));
5660
+ if (failure.success) throw new GitHubGraphqlError(failure.data.errors.map((error) => error.type ? `${error.type}: ${error.message}` : error.message).join("; "), failure.data.errors.flatMap((error) => error.type ? [error.type] : []));
5279
5661
  return response;
5280
5662
  }
5281
5663
  // src/webhooks/installation-requests.ts
@@ -5319,6 +5701,22 @@ async function loadPullRequest(env, pullRequest) {
5319
5701
  token: token.token
5320
5702
  });
5321
5703
  }
5704
+ const rateLimitSchema = z.object({ resources: z.object({ graphql: z.object({ reset: z.number().int() }) }) });
5705
+ /**
5706
+ * Read when the installation's GraphQL rate limit resets, with the same
5707
+ * read-only token as the pull request reads. GitHub does not count this
5708
+ * read against the rate limit.
5709
+ */
5710
+ async function loadGraphqlRateLimitReset(env, repositoryFullName) {
5711
+ const { name } = splitRepository(repositoryFullName, "rate limit");
5712
+ const token = await issueInstallationToken({
5713
+ ...env,
5714
+ permissions: { pull_requests: "read" },
5715
+ repositories: [name]
5716
+ });
5717
+ const response = rateLimitSchema.parse(await githubRequest("https://api.github.com", "/rate_limit", { token: token.token }));
5718
+ return /* @__PURE__ */ new Date(response.resources.graphql.reset * 1e3);
5719
+ }
5322
5720
  /**
5323
5721
  * Return a reader of repository full names by repository id, with one
5324
5722
  * metadata-only token for every repository of the installation. The reader
@@ -5569,6 +5967,7 @@ const userLoginSchema = z.object({
5569
5967
  }).nullable();
5570
5968
  const nextActionSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
5571
5969
  autoMergeRequest: z.object({}).nullable(),
5970
+ commits: z.object({ nodes: nodesSchema(z.object({ commit: z.object({ committedDate: timestampSchema$1 }) })) }),
5572
5971
  isDraft: z.boolean(),
5573
5972
  mergeStateStatus: z.string(),
5574
5973
  reviewRequests: z.object({ nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })) }),
@@ -5578,15 +5977,24 @@ const nextActionSchema = z.object({ data: z.object({ repository: z.object({ pull
5578
5977
  "MERGED",
5579
5978
  "OPEN"
5580
5979
  ]),
5581
- timelineItems: z.object({ nodes: nodesSchema(z.discriminatedUnion("__typename", [z.object({
5582
- __typename: z.literal("IssueComment"),
5583
- author: actorSchema,
5584
- createdAt: timestampSchema$1
5585
- }), z.object({
5586
- __typename: z.literal("ReviewRequestedEvent"),
5587
- createdAt: timestampSchema$1,
5588
- requestedReviewer: userLoginSchema
5589
- })])) }),
5980
+ timelineItems: z.object({ nodes: nodesSchema(z.discriminatedUnion("__typename", [
5981
+ z.object({
5982
+ __typename: z.literal("IssueComment"),
5983
+ author: actorSchema,
5984
+ createdAt: timestampSchema$1
5985
+ }),
5986
+ z.object({
5987
+ __typename: z.literal("ReviewRequestedEvent"),
5988
+ createdAt: timestampSchema$1,
5989
+ requestedReviewer: userLoginSchema
5990
+ }),
5991
+ z.object({
5992
+ __typename: z.literal("ReviewRequestRemovedEvent"),
5993
+ actor: actorSchema,
5994
+ createdAt: timestampSchema$1,
5995
+ requestedReviewer: userLoginSchema
5996
+ })
5997
+ ])) }),
5590
5998
  title: z.string(),
5591
5999
  url: z.string().url()
5592
6000
  }) }) }) });
@@ -5648,18 +6056,26 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
5648
6056
  kind: "reviewRequest",
5649
6057
  login: item.requestedReviewer.login
5650
6058
  });
6059
+ else if (item.__typename === "ReviewRequestRemovedEvent" && item.requestedReviewer?.login && item.actor && restLogin(item.actor).toLowerCase() === item.requestedReviewer.login.toLowerCase()) activity.push({
6060
+ at: new Date(item.createdAt),
6061
+ kind: "reviewRequestRemoved",
6062
+ login: item.requestedReviewer.login
6063
+ });
5651
6064
  for (const review of reviews) if (review.author && review.submittedAt) activity.push({
5652
6065
  at: new Date(review.submittedAt),
5653
6066
  kind: "author",
5654
- login: restLogin(review.author)
6067
+ login: restLogin(review.author),
6068
+ review: review.state
5655
6069
  });
5656
6070
  const mergeableState = unknown(pull.mergeStateStatus) ? void 0 : pull.mergeStateStatus.toLowerCase();
6071
+ const headCommittedAt = pull.commits.nodes[0]?.commit.committedDate;
5657
6072
  const state = {
5658
6073
  activity,
5659
6074
  autoMerge: Boolean(pull.autoMergeRequest),
5660
- changesRequested: false,
5661
6075
  draft: pull.isDraft,
6076
+ ...headCommittedAt ? { headCommittedAt: new Date(headCommittedAt) } : void 0,
5662
6077
  ...mergeableState ? { mergeableState } : void 0,
6078
+ requesterApproved: false,
5663
6079
  requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" && request.requestedReviewer.login ? [request.requestedReviewer.login] : []),
5664
6080
  reviewPending: pull.reviewRequests.nodes.length > 0,
5665
6081
  reviewedBy: [],
@@ -5667,19 +6083,17 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
5667
6083
  title: pull.title,
5668
6084
  url: pull.url
5669
6085
  };
5670
- if (!open) return state;
5671
6086
  const latest = /* @__PURE__ */ new Map();
5672
6087
  for (const review of reviews) if (review.author && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.author.login.toLowerCase(), review);
6088
+ const login = requesterLogin?.toLowerCase();
6089
+ state.requesterApproved = (login ? latest.get(login) : void 0)?.state === "APPROVED";
6090
+ if (!open) return state;
5673
6091
  const latestSubmitted = /* @__PURE__ */ new Map();
5674
6092
  for (const review of reviews) if (review.author && review.submittedAt && review.state !== "PENDING") latestSubmitted.set(review.author.login.toLowerCase(), review.state);
5675
6093
  state.reviewedBy = [...latestSubmitted].flatMap(([login, reviewState]) => reviewState === "DISMISSED" ? [] : [login]);
5676
6094
  const reviewStates = [...latest.values()].map((review) => review.state);
5677
- if (!state.autoMerge && state.mergeableState === "clean") {
5678
- if (reviewStates.includes("CHANGES_REQUESTED")) state.reviewOutcome = "changesRequested";
5679
- else if (reviewStates.includes("APPROVED")) state.reviewOutcome = "approved";
5680
- }
5681
- const login = requesterLogin?.toLowerCase();
5682
- state.changesRequested = (login ? latest.get(login) : void 0)?.state === "CHANGES_REQUESTED";
6095
+ if (reviewStates.includes("CHANGES_REQUESTED")) state.reviewOutcome = "changesRequested";
6096
+ else if (reviewStates.includes("APPROVED")) state.reviewOutcome = "approved";
5683
6097
  return state;
5684
6098
  }
5685
6099
  // src/webhooks/pull-request-action.ts
@@ -5762,79 +6176,6 @@ function pullRequestActionTargets(eventName, body) {
5762
6176
  repositoryFullName: parsed.data.repository.full_name
5763
6177
  }];
5764
6178
  }
5765
- function sameLogin(a, b) {
5766
- return b !== void 0 && a.toLowerCase() === b.toLowerCase();
5767
- }
5768
- function latestActivity(activity, requesterLogin) {
5769
- const latest = {};
5770
- for (const entry of activity) {
5771
- if (!sameLogin(entry.login, requesterLogin)) continue;
5772
- const key = entry.kind === "reviewRequest" ? "askedAt" : "requesterAt";
5773
- const saved = latest[key];
5774
- if (!saved || entry.at > saved) latest[key] = entry.at;
5775
- }
5776
- return latest;
5777
- }
5778
- function timeOf(at) {
5779
- return at ? at.getTime() : Number.NEGATIVE_INFINITY;
5780
- }
5781
- /**
5782
- * Derive the requester's next action. Return undefined when it cannot be
5783
- * known yet, so a later event decides.
5784
- */
5785
- function nextAction(state, requester, saved) {
5786
- if (state.state !== "open") return {};
5787
- const canMerge = !state.draft && !state.autoMerge && !state.reviewPending;
5788
- if (canMerge && state.mergeableState === "clean" && state.reviewOutcome !== "changesRequested") return { action: "merge" };
5789
- if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5790
- if (requester.askedAgain) return { action: "review" };
5791
- if (isRequested(state, requester.login) && (!requester.actedLast || !state.changesRequested)) return { action: "review" };
5792
- if (canMerge && !state.mergeableState) return void 0;
5793
- return {};
5794
- }
5795
- function isRequested(state, login) {
5796
- const lower = login?.toLowerCase();
5797
- return state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === lower);
5798
- }
5799
- /** Why an item closes when its pull request is no longer open. */
5800
- const ENDED_REASONS = {
5801
- closed: {
5802
- reason: "The pull request closed without merging.",
5803
- status: "dismissed"
5804
- },
5805
- merged: {
5806
- reason: "The pull request merged.",
5807
- status: "done"
5808
- }
5809
- };
5810
- function endedReason(state) {
5811
- return state === "open" ? void 0 : ENDED_REASONS[state];
5812
- }
5813
- function closeReason(state, previous) {
5814
- const ended = endedReason(state.state);
5815
- if (ended) return ended;
5816
- if (previous === "review") return {
5817
- reason: "The review request ended.",
5818
- status: "done"
5819
- };
5820
- if (state.autoMerge) return {
5821
- reason: "Auto-merge is on.",
5822
- status: "dismissed"
5823
- };
5824
- return {
5825
- reason: "The pull request is no longer ready to merge.",
5826
- status: "dismissed"
5827
- };
5828
- }
5829
- /** The item text that says why Junior asked for the review again. */
5830
- const REVIEW_AGAIN_TEXT = {
5831
- checks: "Checks now pass, and every comment is handled.",
5832
- handled: "Every comment on your change request is handled."
5833
- };
5834
- function actionText(action, number, reason, state) {
5835
- if (action === "review") return reason ? REVIEW_AGAIN_TEXT[reason] : `GitHub asks you to review #${number}.`;
5836
- return state.reviewOutcome === "approved" ? `#${number} is approved, and GitHub says that it can merge.` : `GitHub says that #${number} can merge with no review. Review it, then merge it.`;
5837
- }
5838
6179
  async function showAction(items, args) {
5839
6180
  const { action, number, state } = args;
5840
6181
  if (action) await items.upsert({
@@ -5909,7 +6250,7 @@ async function requestReviewAgain(args, target, login) {
5909
6250
  * reviewer commented or reviewed since, or when their change request is no
5910
6251
  * longer ready.
5911
6252
  */
5912
- async function askHeldReview(args, target, state) {
6253
+ async function askHeldReview(args, target, state, requesterLogin) {
5913
6254
  const held = await readHeldGitHubReviewAsk(args.state, target);
5914
6255
  if (!held) return void 0;
5915
6256
  const heldAt = new Date(held.at);
@@ -5922,6 +6263,7 @@ async function askHeldReview(args, target, state) {
5922
6263
  const [owner = "", name = ""] = target.repositoryFullName.split("/");
5923
6264
  const readiness = await readReviewAgainReadiness(await loadReviewAgainReader(args.env, target.repositoryFullName), {
5924
6265
  botUserId,
6266
+ isRequester: async () => sameLogin(held.reviewer, requesterLogin),
5925
6267
  marked: held.marked,
5926
6268
  name,
5927
6269
  number: target.number,
@@ -5939,14 +6281,14 @@ async function askHeldReview(args, target, state) {
5939
6281
  await dropHeldGitHubReviewAsk(args.state, target);
5940
6282
  }
5941
6283
  /**
5942
- * Return why Junior asked the requester again, if it did: the reason of the
5943
- * held ask that this sync released, or `handled` when the feedback tool
5944
- * asked them and they have not acted since.
6284
+ * Return why Junior asked the requester, if it did: the reason of the held
6285
+ * ask that this sync released, or the reason of the mark that a Junior tool
6286
+ * wrote when it asked them, if they have not acted since.
5945
6287
  */
5946
6288
  async function askReason(state, target, args) {
5947
6289
  if (args.asked !== void 0) return sameLogin(args.asked.reviewer, args.requesterLogin) ? args.asked.reason : void 0;
5948
6290
  const asked = await readGitHubReviewAsked(state, target);
5949
- return asked && sameLogin(asked.reviewer, args.requesterLogin) && timeOf(args.requesterAt) <= Date.parse(asked.at) ? "handled" : void 0;
6291
+ return asked && sameLogin(asked.reviewer, args.requesterLogin) && timeOf(args.requesterAt) <= Date.parse(asked.at) ? asked.reason ?? "handled" : void 0;
5950
6292
  }
5951
6293
  async function syncOne(args, target) {
5952
6294
  const opener = (await listGitHubPullRequestOpeners(args.db, {
@@ -5965,15 +6307,17 @@ async function syncOne(args, target) {
5965
6307
  now: /* @__PURE__ */ new Date(),
5966
6308
  staleMs: READY_SYNC_STALE_MS
5967
6309
  });
6310
+ if (claim === "held") return "busy";
5968
6311
  if (!claim) return;
5969
6312
  const { id } = claim;
5970
6313
  let saved = claim.action;
5971
6314
  let requests = claim.requests;
5972
6315
  let failure;
6316
+ let askedRequester = false;
5973
6317
  const check = async (previous) => {
5974
6318
  const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
5975
6319
  const activity = latestActivity(state.activity, requesterLogin);
5976
- const asked = await askHeldReview(args, target, state);
6320
+ const asked = await askHeldReview(args, target, state, requesterLogin);
5977
6321
  const reason = await askReason(args.state, target, {
5978
6322
  asked,
5979
6323
  requesterAt: activity.requesterAt,
@@ -5982,9 +6326,22 @@ async function syncOne(args, target) {
5982
6326
  const next = nextAction(state, {
5983
6327
  actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt),
5984
6328
  askedAgain: asked !== void 0 && reason !== void 0,
6329
+ feedback: requesterFeedback(state, activity),
5985
6330
  login: requesterLogin
5986
6331
  }, previous);
5987
- const changed = next !== void 0 && next.action !== previous;
6332
+ if (!askedRequester && requesterLogin && next !== void 0 && next.action === void 0 && inLimbo(state, activity, requesterLogin) && (args.askAfterRequesterActed || activity.actedAt === void 0)) {
6333
+ const [owner = "", name = ""] = target.repositoryFullName.split("/");
6334
+ if (await readGitHubRequiredChecksPass(await loadReviewAgainReader(args.env, target.repositoryFullName), {
6335
+ name,
6336
+ number: target.number,
6337
+ owner
6338
+ })) {
6339
+ askedRequester = true;
6340
+ if (await requestReviewAgain(args, target, requesterLogin)) return await check(previous);
6341
+ }
6342
+ }
6343
+ const showsAsk = next?.action === "review" || next?.action === "review_draft";
6344
+ const changed = next !== void 0 && (next.action !== previous || reason === "question" && showsAsk);
5988
6345
  if (changed) await showAction(items, {
5989
6346
  action: next.action,
5990
6347
  dedupeKey,
@@ -6005,7 +6362,7 @@ async function syncOne(args, target) {
6005
6362
  status: "done"
6006
6363
  }
6007
6364
  }) : void 0]);
6008
- if (changed && next.action === "review" && reason === "handled") await dropGitHubReviewAsked(args.state, target);
6365
+ if (changed && showsAsk && (reason === "handled" || reason === "question")) await dropGitHubReviewAsked(args.state, target);
6009
6366
  if (!changed) return previous;
6010
6367
  await setGitHubPullRequestNextAction(args.db, pullRequestId, next.action);
6011
6368
  return next.action;
@@ -6023,23 +6380,126 @@ async function syncOne(args, target) {
6023
6380
  }
6024
6381
  if (failure !== void 0) throw failure;
6025
6382
  }
6383
+ /** The task that syncs one pull request again after a webhook's sync failed. */
6384
+ const GITHUB_PULL_REQUEST_ACTION_SYNC_TASK = "syncPullRequestAction";
6385
+ const syncTaskPayloadSchema = z.object({
6386
+ number: z.number().int().positive(),
6387
+ repositoryFullName: z.string().min(1),
6388
+ /** Tasks that ran before this one and hit the rate limit again. */
6389
+ restarts: z.number().int().nonnegative()
6390
+ }).strict();
6391
+ const MAX_SYNC_TASK_RESTARTS = 3;
6392
+ const RATE_LIMIT_RESET_MARGIN_SECONDS = 5;
6393
+ const MAX_SYNC_TASK_DELAY_SECONDS = 3300;
6394
+ /**
6395
+ * Return when to sync again after a failure that GitHub causes for a
6396
+ * while: after the GraphQL rate limit resets, or after the task backoff
6397
+ * for a GitHub outage. Return undefined for other failures, which a retry
6398
+ * cannot fix.
6399
+ */
6400
+ async function retryAfterFailure(env, target, error) {
6401
+ if (error instanceof GitHubGraphqlError) {
6402
+ if (!error.types.some((type) => type === "RATE_LIMIT" || type === "RATE_LIMITED")) return error.types.length === 0 ? {} : void 0;
6403
+ const reset = await loadGraphqlRateLimitReset(env, target.repositoryFullName).catch(() => void 0);
6404
+ if (!reset) return {};
6405
+ const seconds = Math.ceil((reset.getTime() - Date.now()) / 1e3);
6406
+ return { delaySeconds: Math.min(Math.max(seconds, 0) + RATE_LIMIT_RESET_MARGIN_SECONDS, MAX_SYNC_TASK_DELAY_SECONDS) };
6407
+ }
6408
+ return error instanceof GitHubRequestError && error.status >= 500 ? {} : void 0;
6409
+ }
6026
6410
  /**
6027
6411
  * Add, change, or close the next-action item of each Junior pull request that
6028
- * a webhook delivery can change. The item is optional, so a failure is logged
6029
- * and does not fail the delivery.
6412
+ * a webhook delivery can change. The item is optional, so a failure does not
6413
+ * fail the delivery. A failure that GitHub causes for a while starts a task
6414
+ * that syncs the pull request again, when `tasks` is given. Other failures
6415
+ * are logged. Return the pull requests that another webhook was checking.
6416
+ * That webhook checks them again, but without `askAfterRequesterActed`.
6030
6417
  */
6031
6418
  async function syncGitHubPullRequestActions(args) {
6419
+ const busy = [];
6032
6420
  await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map(args.targets, async (target) => {
6033
6421
  try {
6034
- await syncOne(args, target);
6422
+ if (await syncOne(args, target) === "busy") busy.push(target);
6035
6423
  } catch (error) {
6036
- logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
6424
+ const metadata = {
6037
6425
  deliveryId: args.deliveryId,
6038
6426
  number: target.number,
6039
6427
  repository: target.repositoryFullName
6428
+ };
6429
+ const retry = args.tasks ? await retryAfterFailure(args.env, target, error) : void 0;
6430
+ if (!args.tasks || !retry) {
6431
+ logFailOpenFailure(args.log, "GitHub pull request action failed", error, metadata);
6432
+ return;
6433
+ }
6434
+ args.log?.warn("GitHub pull request action failed; retrying in a task", {
6435
+ ...metadata,
6436
+ errorType: error instanceof Error ? error.name : "UnknownError"
6040
6437
  });
6438
+ await startSyncTask(args.tasks, target, retry, 0);
6041
6439
  }
6042
6440
  });
6441
+ return busy;
6442
+ }
6443
+ async function startSyncTask(tasks, target, retry, restarts) {
6444
+ const startsAt = Date.now() + (retry.delaySeconds ?? 0) * 1e3;
6445
+ await tasks.start({
6446
+ ...retry,
6447
+ key: `pull-request-action-sync:${itemName(target)}:${Math.floor(startsAt / 6e4)}:${restarts}`,
6448
+ name: GITHUB_PULL_REQUEST_ACTION_SYNC_TASK,
6449
+ payload: {
6450
+ number: target.number,
6451
+ repositoryFullName: target.repositoryFullName,
6452
+ restarts
6453
+ }
6454
+ });
6455
+ }
6456
+ /** The sync context of a started task, with fresh installation tokens. */
6457
+ function startedTaskSyncContext(ctx, options) {
6458
+ return {
6459
+ botEmail: options.botEmail,
6460
+ codeChanges: ctx.codeChanges,
6461
+ db: gitHubDbSchema.parse(ctx.db),
6462
+ env: {
6463
+ ...options.env,
6464
+ responses: ctx.state,
6465
+ tokens: /* @__PURE__ */ new Map()
6466
+ },
6467
+ loadGitHubLogin: async (identityId) => linkedGitHubLogin((await ctx.users.readIdentity(identityId))?.user),
6468
+ log: ctx.log,
6469
+ inboxItems: ctx.inboxItems,
6470
+ state: ctx.state
6471
+ };
6472
+ }
6473
+ /**
6474
+ * Sync the next action of one pull request again. A rate limit starts a new
6475
+ * task that waits for the reset: the queue rejects a task message an hour
6476
+ * after it starts, so the backoff of this one can end before the reset.
6477
+ * Other failures throw, so the task queue runs it again after its backoff,
6478
+ * a bounded number of times.
6479
+ */
6480
+ function githubPullRequestActionSyncTask(options) {
6481
+ return {
6482
+ payload: syncTaskPayloadSchema,
6483
+ async run(ctx) {
6484
+ const context = startedTaskSyncContext(ctx, {
6485
+ botEmail: options.botEmail(),
6486
+ env: options.env
6487
+ });
6488
+ const { restarts } = ctx.payload;
6489
+ try {
6490
+ await syncOne(context, ctx.payload);
6491
+ } catch (error) {
6492
+ const retry = await retryAfterFailure(context.env, ctx.payload, error);
6493
+ if (retry?.delaySeconds === void 0 || restarts >= MAX_SYNC_TASK_RESTARTS) throw error;
6494
+ ctx.log.warn("GitHub pull request action sync task hit the rate limit", {
6495
+ number: ctx.payload.number,
6496
+ repository: ctx.payload.repositoryFullName,
6497
+ restarts
6498
+ });
6499
+ await startSyncTask(ctx.tasks, ctx.payload, retry, restarts + 1);
6500
+ }
6501
+ }
6502
+ };
6043
6503
  }
6044
6504
  // src/pull-request-outcomes/apply.ts
6045
6505
  /**
@@ -6169,7 +6629,7 @@ async function publishGitHubConflictResolved(args) {
6169
6629
  // src/pull-request-patches.ts
6170
6630
  const GITHUB_PULL_REQUEST_PATCH_TASK = "patchPullRequest";
6171
6631
  const PATCH_DELAY_SECONDS = 5;
6172
- const payloadSchema$2 = z.object({
6632
+ const payloadSchema$3 = z.object({
6173
6633
  /** Cache entry `pulls:owner/repo#N`. */
6174
6634
  key: z.string().min(1),
6175
6635
  /** Head commit of the event. */
@@ -6272,7 +6732,7 @@ async function expirePending(cache, key) {
6272
6732
  */
6273
6733
  function githubPullRequestPatchTask(loadHeadFacts) {
6274
6734
  return {
6275
- payload: payloadSchema$2,
6735
+ payload: payloadSchema$3,
6276
6736
  async run(ctx) {
6277
6737
  const { key, sha } = ctx.payload;
6278
6738
  const ref = pullRequestRefFromCacheKey(key);
@@ -7218,7 +7678,7 @@ async function withGitHubPullRequestMatchData(args) {
7218
7678
  /** Pull request outcomes that the people involved need to hear about. */
7219
7679
  const PEOPLE_EVENTS = /* @__PURE__ */ new Set(["pull_request.review.approved", "pull_request.merged"]);
7220
7680
  const MAX_PEOPLE = 20;
7221
- const PAGE_SIZE$2 = 100;
7681
+ const PAGE_SIZE$3 = 100;
7222
7682
  const MAX_PAGES$2 = 3;
7223
7683
  const CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
7224
7684
  const GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
@@ -7263,12 +7723,12 @@ function shareCommitPages(load) {
7263
7723
  */
7264
7724
  async function forEachCommit(loadPage, visit) {
7265
7725
  for (let page = 1; page <= MAX_PAGES$2; page += 1) {
7266
- const commits = commitPageSchema$1.parse(await loadPage(page, PAGE_SIZE$2));
7726
+ const commits = commitPageSchema$1.parse(await loadPage(page, PAGE_SIZE$3));
7267
7727
  for (const commit of commits) visit({
7268
7728
  coAuthorEmails: [...commit.commit.message.matchAll(CO_AUTHOR_TRAILER)].map((match) => match[1]),
7269
7729
  ...commit.author ? { login: commit.author.login } : void 0
7270
7730
  });
7271
- if (commits.length < PAGE_SIZE$2) break;
7731
+ if (commits.length < PAGE_SIZE$3) break;
7272
7732
  }
7273
7733
  }
7274
7734
  /** The GitHub login in a noreply email such as `1+octocat@users.noreply.github.com`. */
@@ -7625,7 +8085,8 @@ function createGitHubWebhookRoute(args) {
7625
8085
  log: args.log,
7626
8086
  inboxItems: args.inboxItems,
7627
8087
  state: args.state,
7628
- targets: pullRequestActionTargets(eventName, body)
8088
+ targets: pullRequestActionTargets(eventName, body),
8089
+ tasks: args.tasks
7629
8090
  });
7630
8091
  await requestGitHubReviewersWhenReady({
7631
8092
  body,
@@ -8143,7 +8604,7 @@ const commitPageSchema = z.array(providerCommitSchema).transform((commits) => co
8143
8604
  authorEmail: commit.commit.author?.email ?? null,
8144
8605
  authorLogin: commit.author?.login ?? null
8145
8606
  })));
8146
- const PAGE_SIZE$1 = 100;
8607
+ const PAGE_SIZE$2 = 100;
8147
8608
  const MAX_PAGES = 3;
8148
8609
  const MAX_LISTED_COMMITS = 250;
8149
8610
  /** Classify whether every Git author in a PR commit list is Junior's bot. */
@@ -8153,7 +8614,7 @@ async function classifyGitHubPullRequestCommitComposition(args) {
8153
8614
  let foundCommit = false;
8154
8615
  let inspectedCommits = 0;
8155
8616
  for (let page = 1; page <= MAX_PAGES; page += 1) {
8156
- const commits = commitPageSchema.parse(await args.loadPage(page, PAGE_SIZE$1));
8617
+ const commits = commitPageSchema.parse(await args.loadPage(page, PAGE_SIZE$2));
8157
8618
  inspectedCommits += commits.length;
8158
8619
  for (const commit of commits) {
8159
8620
  foundCommit = true;
@@ -8161,7 +8622,7 @@ async function classifyGitHubPullRequestCommitComposition(args) {
8161
8622
  if (!isBotLogin(commit.authorLogin, botEmail) && authorEmail !== botEmail) return "mixed";
8162
8623
  }
8163
8624
  if (inspectedCommits >= MAX_LISTED_COMMITS) return void 0;
8164
- if (commits.length < PAGE_SIZE$1) break;
8625
+ if (commits.length < PAGE_SIZE$2) break;
8165
8626
  if (page === MAX_PAGES) return void 0;
8166
8627
  }
8167
8628
  return foundCommit ? "junior_only" : void 0;
@@ -8178,13 +8639,13 @@ async function classifyGitHubPullRequestCommitComposition(args) {
8178
8639
  * records the names that changed.
8179
8640
  */
8180
8641
  const GITHUB_REPOSITORY_NAME_REPAIR_TASK = "repairRepositoryNames";
8181
- const DONE_KEY$1 = "repository-name-repair:done";
8642
+ const DONE_KEY$2 = "repository-name-repair:done";
8182
8643
  /** GitHub reads at once. */
8183
8644
  const READ_CONCURRENCY = 4;
8184
- const payloadSchema$1 = z.object({}).strict();
8645
+ const payloadSchema$2 = z.object({}).strict();
8185
8646
  /** Start the repair until one run finishes. */
8186
8647
  async function startGitHubRepositoryNameRepair(args) {
8187
- if (await args.state.get(DONE_KEY$1)) return;
8648
+ if (await args.state.get(DONE_KEY$2)) return;
8188
8649
  await args.tasks.start({
8189
8650
  key: "repository-name-repair",
8190
8651
  name: GITHUB_REPOSITORY_NAME_REPAIR_TASK,
@@ -8198,9 +8659,9 @@ async function startGitHubRepositoryNameRepair(args) {
8198
8659
  */
8199
8660
  function githubRepositoryNameRepairTask(loadFullNames) {
8200
8661
  return {
8201
- payload: payloadSchema$1,
8662
+ payload: payloadSchema$2,
8202
8663
  async run(ctx) {
8203
- if (await ctx.state.get(DONE_KEY$1)) return;
8664
+ if (await ctx.state.get(DONE_KEY$2)) return;
8204
8665
  const stored = /* @__PURE__ */ new Map();
8205
8666
  for (const change of await ctx.codeChanges.list({})) stored.set(change.repository.providerId, change.repository.name);
8206
8667
  if (stored.size > 0) {
@@ -8220,21 +8681,21 @@ function githubRepositoryNameRepairTask(loadFullNames) {
8220
8681
  }
8221
8682
  });
8222
8683
  }
8223
- await ctx.state.set(DONE_KEY$1, true);
8684
+ await ctx.state.set(DONE_KEY$2, true);
8224
8685
  }
8225
8686
  };
8226
8687
  }
8227
8688
  // src/pull-request-requesters/backfill.ts
8228
8689
  const GITHUB_PULL_REQUEST_REQUESTER_BACKFILL_TASK = "backfillPullRequestRequesters";
8229
- const CURSOR_KEY = "pull-request-requester-backfill:cursor";
8230
- const DONE_KEY = "pull-request-requester-backfill:done";
8690
+ const CURSOR_KEY$1 = "pull-request-requester-backfill:cursor";
8691
+ const DONE_KEY$1 = "pull-request-requester-backfill:done";
8231
8692
  /** Pull requests per task run. Each needs a few small database writes. */
8232
- const PAGE_SIZE = 200;
8233
- const payloadSchema = z.object({}).strict();
8693
+ const PAGE_SIZE$1 = 200;
8694
+ const payloadSchema$1 = z.object({}).strict();
8234
8695
  /** Start the next page of the backfill until the last page is done. */
8235
8696
  async function startGitHubPullRequestRequesterBackfill(args) {
8236
- if (await args.state.get(DONE_KEY)) return;
8237
- const after = await args.state.get(CURSOR_KEY);
8697
+ if (await args.state.get(DONE_KEY$1)) return;
8698
+ const after = await args.state.get(CURSOR_KEY$1);
8238
8699
  await args.tasks.start({
8239
8700
  key: `pull-request-requester-backfill:${after ? `${after.repositoryFullName}#${after.number}` : "start"}`,
8240
8701
  name: GITHUB_PULL_REQUEST_REQUESTER_BACKFILL_TASK,
@@ -8246,13 +8707,13 @@ async function startGitHubPullRequestRequesterBackfill(args) {
8246
8707
  * code changes, in the order of repository name and number.
8247
8708
  */
8248
8709
  const githubPullRequestRequesterBackfillTask = {
8249
- payload: payloadSchema,
8710
+ payload: payloadSchema$1,
8250
8711
  async run(ctx) {
8251
- if (await ctx.state.get(DONE_KEY)) return;
8712
+ if (await ctx.state.get(DONE_KEY$1)) return;
8252
8713
  const db = gitHubDbSchema.parse(ctx.db);
8253
8714
  const page = await listGitHubPullRequestsWithRequesters(db, {
8254
- after: await ctx.state.get(CURSOR_KEY),
8255
- limit: PAGE_SIZE
8715
+ after: await ctx.state.get(CURSOR_KEY$1),
8716
+ limit: PAGE_SIZE$1
8256
8717
  });
8257
8718
  const numbers = /* @__PURE__ */ new Map();
8258
8719
  for (const ref of page) numbers.set(ref.repositoryFullName, [...numbers.get(ref.repositoryFullName) ?? [], ref.number]);
@@ -8263,10 +8724,68 @@ const githubPullRequestRequesterBackfillTask = {
8263
8724
  repositoryFullName
8264
8725
  });
8265
8726
  const last = page.at(-1);
8266
- if (!last || page.length < PAGE_SIZE) await ctx.state.set(DONE_KEY, true);
8267
- else await ctx.state.set(CURSOR_KEY, last);
8727
+ if (!last || page.length < PAGE_SIZE$1) await ctx.state.set(DONE_KEY$1, true);
8728
+ else await ctx.state.set(CURSOR_KEY$1, last);
8268
8729
  }
8269
8730
  };
8731
+ // src/pull-request-action-backfill.ts
8732
+ const GITHUB_PULL_REQUEST_ACTION_BACKFILL_TASK = "backfillPullRequestActions";
8733
+ const VERSION = "v1";
8734
+ const CURSOR_KEY = `pull-request-action-backfill:${VERSION}:cursor`;
8735
+ const DONE_KEY = `pull-request-action-backfill:${VERSION}:done`;
8736
+ const RERUNS_KEY = `pull-request-action-backfill:${VERSION}:reruns`;
8737
+ /**
8738
+ * Pull requests per task run. Most need no GitHub read, because no person
8739
+ * asked for them. The others read GitHub a few times each, five at once, so
8740
+ * one run stays well inside the function time and the hourly rate limit.
8741
+ */
8742
+ const PAGE_SIZE = 50;
8743
+ const payloadSchema = z.object({}).strict();
8744
+ /** Start the next page of the backfill until the last page is done. */
8745
+ async function startGitHubPullRequestActionBackfill(args) {
8746
+ if (await args.state.get(DONE_KEY)) return;
8747
+ const after = await args.state.get(CURSOR_KEY);
8748
+ const reruns = await args.state.get(RERUNS_KEY);
8749
+ await args.tasks.start({
8750
+ key: `pull-request-action-backfill:${VERSION}:${after ?? 0}:${reruns ?? 0}`,
8751
+ name: GITHUB_PULL_REQUEST_ACTION_BACKFILL_TASK,
8752
+ payload: {}
8753
+ });
8754
+ }
8755
+ /**
8756
+ * Sync the next action of the next page of open Junior pull requests, in
8757
+ * the order of their GitHub ids. A failure for one pull request is logged
8758
+ * and skips it.
8759
+ */
8760
+ function githubPullRequestActionBackfillTask(args) {
8761
+ return {
8762
+ payload: payloadSchema,
8763
+ async run(ctx) {
8764
+ if (await ctx.state.get(DONE_KEY)) return;
8765
+ const after = await ctx.state.get(CURSOR_KEY) ?? 0;
8766
+ const page = (await ctx.codeChanges.list({ state: "open" })).map((change) => ({
8767
+ change,
8768
+ id: Number(change.providerId)
8769
+ })).filter(({ id }) => id > after).sort((a, b) => a.id - b.id).slice(0, PAGE_SIZE);
8770
+ const busy = await syncGitHubPullRequestActions({
8771
+ askAfterRequesterActed: true,
8772
+ ...startedTaskSyncContext(ctx, {
8773
+ botEmail: args.botEmail(),
8774
+ env: args.env
8775
+ }),
8776
+ deliveryId: `pull-request-action-backfill:${VERSION}`,
8777
+ targets: page.map(({ change }) => ({
8778
+ number: change.number,
8779
+ repositoryFullName: change.repository.name
8780
+ }))
8781
+ });
8782
+ const last = page.at(-1);
8783
+ if (busy.length > 0) await ctx.state.set(RERUNS_KEY, (await ctx.state.get(RERUNS_KEY) ?? 0) + 1);
8784
+ else if (!last || page.length < PAGE_SIZE) await ctx.state.set(DONE_KEY, true);
8785
+ else await ctx.state.set(CURSOR_KEY, last.id);
8786
+ }
8787
+ };
8788
+ }
8270
8789
  // src/images.ts
8271
8790
  /**
8272
8791
  * Description images of GitHub objects, served through the Junior image
@@ -9321,6 +9840,136 @@ function overridesHooksPath([program, ...args]) {
9321
9840
  }
9322
9841
  return false;
9323
9842
  }
9843
+ // src/graphql-budget.ts
9844
+ /**
9845
+ * Hourly GitHub GraphQL budgets for Sandbox requests.
9846
+ *
9847
+ * The App installation has one hourly GraphQL points budget for all of
9848
+ * Junior. Each Conversation's Sandbox gets a share of it, and Sandbox
9849
+ * requests stop while the installation has only the host reserve left, so
9850
+ * host calls such as the PR next-action syncs keep working.
9851
+ *
9852
+ * Spend comes from GitHub's own rate limit headers on each response, not
9853
+ * from a prediction. A response's cost is the rise in `x-ratelimit-used`
9854
+ * since the last response that Junior saw. Spend that Junior does not see,
9855
+ * such as a webhook call that does not go through egress, counts toward the
9856
+ * next Sandbox response, so a Conversation can be charged more than its own
9857
+ * queries cost, never less.
9858
+ *
9859
+ * Spend is known only when a response comes back, so each Conversation may
9860
+ * have only a few Sandbox GraphQL requests in flight. Without that limit,
9861
+ * parallel copies of a costly query all pass the check before any of them
9862
+ * is charged.
9863
+ *
9864
+ * Counts live in the plugin cache, which every instance shares. A lost
9865
+ * entry only resets a count, which lets more requests through, never fewer.
9866
+ */
9867
+ /** Points that one Conversation's Sandbox may spend in one clock hour. */
9868
+ const GITHUB_SANDBOX_GRAPHQL_CONVERSATION_BUDGET = 2e3;
9869
+ /** Installation points that Sandbox requests leave for host calls. */
9870
+ const GITHUB_GRAPHQL_HOST_RESERVE = 2e3;
9871
+ /** Sandbox GraphQL requests that one Conversation may have in flight. */
9872
+ const GITHUB_SANDBOX_GRAPHQL_IN_FLIGHT_LIMIT = 2;
9873
+ /**
9874
+ * How long a request holds its in-flight slot when no response frees it,
9875
+ * such as when the upstream fetch fails. GitHub stops a GraphQL query after
9876
+ * 10 seconds.
9877
+ */
9878
+ const IN_FLIGHT_SLOT_MS = 6e4;
9879
+ const HOUR_MS = 36e5;
9880
+ const RATE_LIMIT_CACHE_KEY = "graphql-rate-limit";
9881
+ function resetText(resetAtMs, nowMs) {
9882
+ return `${new Date(resetAtMs).toISOString().slice(11, 16)} UTC (in ${Math.max(1, Math.ceil((resetAtMs - nowMs) / 6e4))} min)`;
9883
+ }
9884
+ function conversationKey(conversationId, hourStartMs) {
9885
+ return `graphql-budget:${conversationId}:${hourStartMs}`;
9886
+ }
9887
+ function inFlightKey(conversationId) {
9888
+ return `graphql-in-flight:${conversationId}`;
9889
+ }
9890
+ function heldSlots(starts, nowMs) {
9891
+ return (starts ?? []).filter((start) => nowMs - start < IN_FLIGHT_SLOT_MS);
9892
+ }
9893
+ async function takeInFlightSlot(ctx, conversationId, nowMs) {
9894
+ let taken = false;
9895
+ await ctx.cache.update(inFlightKey(conversationId), (current) => {
9896
+ const held = heldSlots(current, nowMs);
9897
+ if (held.length >= GITHUB_SANDBOX_GRAPHQL_IN_FLIGHT_LIMIT) return {
9898
+ ttlMs: IN_FLIGHT_SLOT_MS,
9899
+ value: held
9900
+ };
9901
+ taken = true;
9902
+ return {
9903
+ ttlMs: IN_FLIGHT_SLOT_MS,
9904
+ value: [...held, nowMs]
9905
+ };
9906
+ });
9907
+ if (taken) return;
9908
+ throw new EgressPolicyDenied(`GitHub GraphQL request denied: this Conversation already has ${GITHUB_SANDBOX_GRAPHQL_IN_FLIGHT_LIMIT} Sandbox GraphQL requests in flight. Wait for them to finish, and send GraphQL requests one after another, not in parallel.`);
9909
+ }
9910
+ function spendsSandboxBudget(request) {
9911
+ return !request.operation && !request.withoutCredential;
9912
+ }
9913
+ /**
9914
+ * Deny a Sandbox GitHub GraphQL request when its Conversation has spent its
9915
+ * hourly budget, or when the installation has only the host reserve left.
9916
+ */
9917
+ async function assertGitHubSandboxGraphqlBudgetLeft(ctx) {
9918
+ if (!spendsSandboxBudget(ctx.request)) return;
9919
+ const nowMs = Date.now();
9920
+ const rateLimit = await ctx.cache.get(RATE_LIMIT_CACHE_KEY);
9921
+ if (rateLimit && rateLimit.resetAtMs > nowMs && rateLimit.remaining <= GITHUB_GRAPHQL_HOST_RESERVE) throw new EgressPolicyDenied(`GitHub GraphQL request denied: the App installation has ${rateLimit.remaining} GraphQL points left this hour, and Sandbox requests leave ${GITHUB_GRAPHQL_HOST_RESERVE} for host calls. It resets at ${resetText(rateLimit.resetAtMs, nowMs)}. Use REST endpoints such as \`gh api repos/{owner}/{repo}/pulls/{number}\` until then. Do not retry GraphQL before the reset.`);
9922
+ const { conversationId } = ctx.request;
9923
+ if (!conversationId) return;
9924
+ const hourStartMs = nowMs - nowMs % HOUR_MS;
9925
+ const spent = await ctx.cache.get(conversationKey(conversationId, hourStartMs)) ?? 0;
9926
+ if (spent < GITHUB_SANDBOX_GRAPHQL_CONVERSATION_BUDGET) {
9927
+ await takeInFlightSlot(ctx, conversationId, nowMs);
9928
+ return;
9929
+ }
9930
+ throw new EgressPolicyDenied(`GitHub GraphQL request denied: this Conversation has used ${spent} of its ${GITHUB_SANDBOX_GRAPHQL_CONVERSATION_BUDGET} Sandbox GraphQL points for this hour. The budget resets at ${resetText(hourStartMs + HOUR_MS, nowMs)}. Use REST endpoints such as \`gh api repos/{owner}/{repo}/pulls/{number}\` until then.`);
9931
+ }
9932
+ /**
9933
+ * Keep the installation's GraphQL rate limit from a GraphQL response's
9934
+ * headers. When the response answers a Sandbox request, free its in-flight
9935
+ * slot and charge what it cost to its Conversation's hourly budget.
9936
+ */
9937
+ async function recordGitHubGraphqlSpend(ctx) {
9938
+ const nowMs = Date.now();
9939
+ const { conversationId } = ctx.request;
9940
+ const sandboxConversationId = conversationId && spendsSandboxBudget(ctx.request) ? conversationId : void 0;
9941
+ if (sandboxConversationId && ctx.response.status !== 403) await ctx.cache.update(inFlightKey(sandboxConversationId), (current) => ({
9942
+ ttlMs: IN_FLIGHT_SLOT_MS,
9943
+ value: heldSlots(current, nowMs).slice(1)
9944
+ }));
9945
+ if (!ctx.grant.name.startsWith("installation-")) return;
9946
+ const { headers } = ctx.response;
9947
+ if (headers.get("x-ratelimit-resource") !== "graphql") return;
9948
+ const remaining = Number(headers.get("x-ratelimit-remaining"));
9949
+ const used = Number(headers.get("x-ratelimit-used"));
9950
+ const resetAtMs = Number(headers.get("x-ratelimit-reset")) * 1e3;
9951
+ if (!Number.isInteger(remaining) || !Number.isInteger(used) || !(resetAtMs > nowMs)) return;
9952
+ let cost = 0;
9953
+ await ctx.cache.update(RATE_LIMIT_CACHE_KEY, (current) => {
9954
+ const sameWindow = current?.resetAtMs === resetAtMs;
9955
+ if (sameWindow && used <= current.used) return;
9956
+ cost = sameWindow ? used - current.used : 1;
9957
+ return {
9958
+ ttlMs: resetAtMs - nowMs,
9959
+ value: {
9960
+ remaining,
9961
+ resetAtMs,
9962
+ used
9963
+ }
9964
+ };
9965
+ });
9966
+ if (!sandboxConversationId || cost === 0) return;
9967
+ const hourStartMs = nowMs - nowMs % HOUR_MS;
9968
+ await ctx.cache.update(conversationKey(sandboxConversationId, hourStartMs), (spent = 0) => ({
9969
+ ttlMs: hourStartMs + HOUR_MS - nowMs,
9970
+ value: spent + cost
9971
+ }));
9972
+ }
9324
9973
  // src/pull-request-review-policy.ts
9325
9974
  /**
9326
9975
  * Deterministic pull request review policy enforced before credential grant.
@@ -9439,6 +10088,7 @@ function githubSmartHttpAccess(upstreamUrl) {
9439
10088
  if (pathname.endsWith("/git-receive-pack") || service === "git-receive-pack") return "write";
9440
10089
  if (pathname.endsWith("/git-upload-pack") || service === "git-upload-pack") return "read";
9441
10090
  }
10091
+ /** Whether a URL is GitHub's GraphQL endpoint. */
9442
10092
  function isGitHubGraphqlUrl(upstreamUrl) {
9443
10093
  return upstreamUrl.hostname.toLowerCase() === "api.github.com" && upstreamUrl.pathname.toLowerCase().endsWith("/graphql");
9444
10094
  }
@@ -9720,6 +10370,7 @@ function requireRepositoryTarget(upstreamUrl) {
9720
10370
  async function githubGrantForEgress(ctx, env) {
9721
10371
  const upstreamUrl = new URL(ctx.request.url);
9722
10372
  const grant = await selectGitHubGrant(ctx, env, upstreamUrl);
10373
+ if (isGitHubGraphqlUrl(upstreamUrl)) await assertGitHubSandboxGraphqlBudgetLeft(ctx);
9723
10374
  const repository = githubRepositoryFromUrl(upstreamUrl);
9724
10375
  return repository ? {
9725
10376
  ...grant,
@@ -9812,6 +10463,22 @@ function githubPlugin(options = {}) {
9812
10463
  githubPullRequestLinks
9813
10464
  ],
9814
10465
  tasks: {
10466
+ [GITHUB_PULL_REQUEST_ACTION_BACKFILL_TASK]: githubPullRequestActionBackfillTask({
10467
+ botEmail: () => readEnv(botEmailEnv),
10468
+ env: {
10469
+ appIdEnv,
10470
+ installationIdEnv,
10471
+ privateKeyEnv
10472
+ }
10473
+ }),
10474
+ [GITHUB_PULL_REQUEST_ACTION_SYNC_TASK]: githubPullRequestActionSyncTask({
10475
+ botEmail: () => readEnv(botEmailEnv),
10476
+ env: {
10477
+ appIdEnv,
10478
+ installationIdEnv,
10479
+ privateKeyEnv
10480
+ }
10481
+ }),
9815
10482
  [GITHUB_PULL_REQUEST_OUTCOME_TASK]: githubPullRequestOutcomeTask,
9816
10483
  [GITHUB_PULL_REQUEST_PATCH_TASK]: githubPullRequestPatchTask(async (refs) => await loadPullRequestHeadFacts({
9817
10484
  appIdEnv,
@@ -10038,6 +10705,10 @@ function githubPlugin(options = {}) {
10038
10705
  state: ctx.state,
10039
10706
  tasks: ctx.tasks
10040
10707
  });
10708
+ await startGitHubPullRequestActionBackfill({
10709
+ state: ctx.state,
10710
+ tasks: ctx.tasks
10711
+ });
10041
10712
  },
10042
10713
  async unfinishedWork(ctx) {
10043
10714
  return await listGitHubConversationWork(ctx.codeChanges, ctx.conversationIds);
@@ -10126,6 +10797,7 @@ function githubPlugin(options = {}) {
10126
10797
  });
10127
10798
  },
10128
10799
  async onEgressResponse(ctx) {
10800
+ if (isGitHubGraphqlUrl(new URL(ctx.request.url))) await recordGitHubGraphqlSpend(ctx);
10129
10801
  if (ctx.response.status === 403) ctx.log.warn("github.egress.upstream_forbidden", {
10130
10802
  "app.github.accepted_permissions": ctx.response.headers.get("x-accepted-github-permissions") ?? void 0,
10131
10803
  "app.github.sso": ctx.response.headers.get("x-github-sso") ?? void 0