@sentry/junior-github 0.308.0 → 0.309.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.
@@ -1,8 +1,8 @@
1
1
  import * as z from "zod";
2
+ import pLimit from "p-limit";
2
3
  import { PluginToolInputError, eventMatchFieldsSchema, mergeEventMatchFields } from "@sentry/junior-plugin-api";
3
4
  import { lexer } from "marked";
4
5
  import { createPrivateKey, createSign } from "node:crypto";
5
- import pLimit from "p-limit";
6
6
  // src/tool-support/github-api.ts
7
7
  const GITHUB_API_BASE = "https://api.github.com";
8
8
  const MAX_REDIRECTS = 3;
@@ -2111,8 +2111,7 @@ async function loadCheckSuiteFacts(args) {
2111
2111
  privateKeyEnv: args.privateKeyEnv,
2112
2112
  repositories: [target.repoName]
2113
2113
  });
2114
- const limit = pLimit(PULL_REQUEST_LOAD_CONCURRENCY);
2115
- const loaded = await Promise.all(target.pullRequestNumbers.map((number) => limit(async () => {
2114
+ const loaded = await pLimit(PULL_REQUEST_LOAD_CONCURRENCY).map(target.pullRequestNumbers, async (number) => {
2116
2115
  try {
2117
2116
  const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, { token: token.token }));
2118
2117
  return loadedFacts ? [number, loadedFacts] : void 0;
@@ -2123,7 +2122,7 @@ async function loadCheckSuiteFacts(args) {
2123
2122
  });
2124
2123
  return;
2125
2124
  }
2126
- })));
2125
+ });
2127
2126
  const pullRequestFactsByNumber = {};
2128
2127
  for (const entry of loaded) {
2129
2128
  if (!entry) continue;
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
- import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRequest, 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 githubRepositoryFromUrl, 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 logFailOpenFailure, 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 definedValues, 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 pullRequestTargets, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as isRecord, 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-CAZiit9g.js";
1
+ import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRequest, 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 githubRepositoryFromUrl, 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 logFailOpenFailure, 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 definedValues, 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 pullRequestTargets, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as isRecord, 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-D5Zs75yy.js";
2
2
  import * as z from "zod";
3
+ import pLimit from "p-limit";
3
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";
4
5
  import { lexer, walkTokens } from "marked";
5
6
  import { parseFragment } from "parse5";
@@ -10,7 +11,6 @@ import { boolean, index, integer, pgTable, primaryKey, text, timestamp as timest
10
11
  import ignore from "ignore";
11
12
  import { Kind, parse, print, visit } from "@0no-co/graphql.web";
12
13
  import { createHmac, timingSafeEqual } from "node:crypto";
13
- import pLimit from "p-limit";
14
14
  import { fromMarkdown } from "mdast-util-from-markdown";
15
15
  import { gfmFromMarkdown } from "mdast-util-gfm";
16
16
  import { gfm } from "micromark-extension-gfm";
@@ -167,7 +167,8 @@ async function updateGitHubAnnotation(store, input) {
167
167
  * conversation does not stop the others. Each failure is logged.
168
168
  */
169
169
  async function updateGitHubAnnotations(args) {
170
- const results = await Promise.allSettled(args.conversationIds.map((conversationId) => updateGitHubAnnotation(args.annotations.forConversation(conversationId), args.update)));
170
+ const limit = pLimit(8);
171
+ const results = await Promise.allSettled(args.conversationIds.map((conversationId) => limit(() => updateGitHubAnnotation(args.annotations.forConversation(conversationId), args.update))));
171
172
  for (const result of results) {
172
173
  if (result.status === "fulfilled") continue;
173
174
  args.log?.error("GitHub conversation annotation update failed", {
@@ -1613,6 +1614,11 @@ const DESCRIPTION_CHECKS = [
1613
1614
  fix: MISSING_REASON_FIX
1614
1615
  }
1615
1616
  ];
1617
+ /**
1618
+ * The `DESCRIPTION_CHECKS` rules, for the `body` param of the pull request
1619
+ * tools, so the first draft can pass without a rejection.
1620
+ */
1621
+ const PULL_REQUEST_BODY_RULES = "Say what changes and why. Omit your own test or CI results, test plans or coverage, work logs, and the request or chat behind it. Describing what a test tool checks is fine. The runtime appends attribution and the footer.";
1616
1622
  /** List the fixes that a pull request description needs. Empty means it passes. */
1617
1623
  async function pullRequestDescriptionFixes(decider, body) {
1618
1624
  if (!body.trim()) return [MISSING_REASON_FIX];
@@ -1649,13 +1655,14 @@ var GitHubPullRequestCreateRejectedError = class extends Error {
1649
1655
  this.status = status;
1650
1656
  }
1651
1657
  };
1658
+ const BODY_DESCRIPTION = `Pull request body. ${PULL_REQUEST_BODY_RULES}`;
1652
1659
  const REVIEWERS_DESCRIPTION = "GitHub logins to ask for a review. Set this only when the person names who should review. Without it, the tool asks the requester's linked GitHub account. A draft gets the request when it becomes ready for review.";
1653
1660
  const createPullRequestInputSchema = Type.Object({
1654
1661
  repo: Type.String({ description: "Repository in \"owner/name\" format." }),
1655
1662
  title: Type.String({ description: "Pull request title." }),
1656
1663
  head: Type.String({ description: "Head branch or owner:branch ref." }),
1657
1664
  base: Type.String({ description: "Base branch." }),
1658
- body: Type.Optional(Type.String({ description: "Pull request body. The runtime appends the conversation footer." })),
1665
+ body: Type.Optional(Type.String({ description: BODY_DESCRIPTION })),
1659
1666
  draft: Type.Optional(Type.Boolean({ description: "Whether to open the pull request as a draft." })),
1660
1667
  reviewers: Type.Optional(Type.Array(Type.String(), {
1661
1668
  description: REVIEWERS_DESCRIPTION,
@@ -1667,7 +1674,7 @@ const createPullRequestToolInputSchema = z.object({
1667
1674
  title: z.string().describe("Pull request title."),
1668
1675
  head: z.string().describe("Head branch or owner:branch ref."),
1669
1676
  base: z.string().describe("Base branch."),
1670
- body: z.string().describe("Pull request body. The runtime appends the conversation footer.").optional(),
1677
+ body: z.string().describe(BODY_DESCRIPTION).optional(),
1671
1678
  draft: z.boolean().describe("Whether to open the pull request as a draft.").optional(),
1672
1679
  reviewers: z.array(z.string()).min(1).describe(REVIEWERS_DESCRIPTION).optional()
1673
1680
  }).strict();
@@ -2980,7 +2987,7 @@ const inputSchema$3 = z.object({
2980
2987
  repo: z.string().describe("Repository in \"owner/name\" format."),
2981
2988
  number: z.number().int().positive().describe("Pull request number."),
2982
2989
  title: z.string().trim().min(1).optional().describe("Replacement pull request title."),
2983
- body: z.string().optional().describe("Replacement pull request body. The runtime appends requester attribution and the conversation footer."),
2990
+ body: z.string().optional().describe(`Replacement pull request body. ${PULL_REQUEST_BODY_RULES}`),
2984
2991
  base: z.string().trim().min(1).optional().describe("Replacement base branch."),
2985
2992
  state: z.enum(["open", "closed"]).optional().describe("Replacement pull request state."),
2986
2993
  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.")
@@ -3122,6 +3129,27 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3122
3129
  }
3123
3130
  });
3124
3131
  }
3132
+ // src/pull-request-reviews.ts
3133
+ const REVIEWS_PAGE_SIZE = 100;
3134
+ const reviewsSchema = z.array(z.object({
3135
+ commit_id: z.string().nullable().optional(),
3136
+ state: z.string(),
3137
+ user: z.object({ login: z.string() }).nullable()
3138
+ }));
3139
+ /**
3140
+ * Read every page of a pull request's reviews, and return the latest
3141
+ * approval, change request, or dismissal of each reviewer by lowercase
3142
+ * login. Comments do not count. `readPage` reads the reviews with the given
3143
+ * query string.
3144
+ */
3145
+ async function loadLatestReviews(readPage) {
3146
+ const latest = /* @__PURE__ */ new Map();
3147
+ for (let page = 1;; page++) {
3148
+ const batch = reviewsSchema.parse(await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`));
3149
+ for (const review of batch) if (review.user && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.user.login.toLowerCase(), review);
3150
+ if (batch.length < REVIEWS_PAGE_SIZE) return latest;
3151
+ }
3152
+ }
3125
3153
  // src/tools/update-pull-request-feedback.ts
3126
3154
  /**
3127
3155
  * GitHub has reactions but no feedback state. This tool maps each state to a
@@ -3248,7 +3276,10 @@ async function commentReactions(egress, input) {
3248
3276
  })
3249
3277
  };
3250
3278
  }
3251
- /** Return the GraphQL reactions of a review on `pullRequest`. */
3279
+ /**
3280
+ * Return the GraphQL reactions of a review on `pullRequest`, and the login of
3281
+ * its author when the review requests changes.
3282
+ */
3252
3283
  async function reviewBodyReactions(egress, input) {
3253
3284
  const reviewResponse = await githubApi(egress, {
3254
3285
  operation: "github.pull.review.get",
@@ -3259,7 +3290,12 @@ async function reviewBodyReactions(egress, input) {
3259
3290
  if (reviewResponse.status === 404) throw new PluginToolInputError(message);
3260
3291
  throw new Error(message);
3261
3292
  }
3262
- const subjectId = z.object({ node_id: z.string().min(1) }).parse(reviewResponse.body).node_id;
3293
+ const review = z.object({
3294
+ node_id: z.string().min(1),
3295
+ state: z.string().optional(),
3296
+ user: z.object({ login: z.string().min(1) }).nullable().optional()
3297
+ }).parse(reviewResponse.body);
3298
+ const subjectId = review.node_id;
3263
3299
  const graphql = (operation, document, variables) => githubApi(egress, {
3264
3300
  operation,
3265
3301
  method: "POST",
@@ -3271,6 +3307,7 @@ async function reviewBodyReactions(egress, input) {
3271
3307
  });
3272
3308
  const update = `github.pull.review-reaction.update:${input.owner}/${input.name}`.toLowerCase();
3273
3309
  return {
3310
+ ...review.state === "CHANGES_REQUESTED" && review.user ? { changesRequestedBy: review.user.login } : void 0,
3274
3311
  list: () => graphql("github.pull.review-reaction.list", REVIEW_REACTIONS, { subjectId }),
3275
3312
  botReactions: (body) => reviewReactionsSchema.parse(body).data.node.reactionGroups.filter((group) => group.reactors.nodes.some((reactor) => reactor.databaseId === input.botUserId)).map((group) => ({ content: REST_REACTION_CONTENT.get(group.content) ?? group.content })),
3276
3313
  remove: (reaction) => graphql(update, REMOVE_REVIEW_REACTION, {
@@ -3283,6 +3320,50 @@ async function reviewBodyReactions(egress, input) {
3283
3320
  })
3284
3321
  };
3285
3322
  }
3323
+ /**
3324
+ * Ask the reviewer who requested changes to review again, while their latest
3325
+ * review still requests changes. GitHub stops asking a reviewer once they
3326
+ * review, so the fixed pull request would not wait on them. A reviewer who
3327
+ * approved since then is not asked. The request is optional, so a failure is
3328
+ * logged and does not fail the tool.
3329
+ */
3330
+ async function requestReviewAgain(ctx, input) {
3331
+ const fields = {
3332
+ number: input.pullRequest,
3333
+ repo: `${input.owner}/${input.name}`
3334
+ };
3335
+ try {
3336
+ const pullPath = `${repoPath(input)}/pulls/${input.pullRequest}`;
3337
+ let rejectedStatus;
3338
+ const latest = await loadLatestReviews(async (query) => {
3339
+ const page = await githubApi(ctx.egress, {
3340
+ operation: "github.pull.review.list",
3341
+ path: `${pullPath}/reviews?${query}`
3342
+ });
3343
+ if (page.ok) return page.body;
3344
+ rejectedStatus = page.status;
3345
+ return [];
3346
+ });
3347
+ if (rejectedStatus === void 0 && latest.get(input.reviewer.toLowerCase())?.state === "CHANGES_REQUESTED") {
3348
+ const response = await githubApi(ctx.egress, {
3349
+ operation: "github.pull.request_reviewers",
3350
+ method: "POST",
3351
+ path: `${pullPath}/requested_reviewers`,
3352
+ body: { reviewers: [input.reviewer] }
3353
+ });
3354
+ if (!response.ok) rejectedStatus = response.status;
3355
+ }
3356
+ if (rejectedStatus !== void 0) ctx.log.warn("github.pull_request.request_reviewers_after_feedback.rejected", {
3357
+ ...fields,
3358
+ status: rejectedStatus
3359
+ });
3360
+ } catch (error) {
3361
+ ctx.log.warn("github.pull_request.request_reviewers_after_feedback.failed", {
3362
+ ...fields,
3363
+ errorType: error instanceof Error ? error.name : "UnknownError"
3364
+ });
3365
+ }
3366
+ }
3286
3367
  function failed(response) {
3287
3368
  const errors = response.body?.errors;
3288
3369
  return !response.ok || Array.isArray(errors) && errors.length > 0;
@@ -3290,6 +3371,7 @@ function failed(response) {
3290
3371
  /**
3291
3372
  * Set Junior's feedback reaction on a pull request comment or review body.
3292
3373
  * Replace only state reactions Junior previously added to the same comment.
3374
+ * Addressed change requests ask their reviewer to review again.
3293
3375
  */
3294
3376
  function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3295
3377
  return definePluginTool({
@@ -3300,7 +3382,7 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3300
3382
  openWorldHint: true,
3301
3383
  readOnlyHint: false
3302
3384
  },
3303
- description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after acting on the feedback. Replaces only your prior status reaction on that comment. Only works on pull requests the bot authored.",
3385
+ description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after acting on the feedback. Replaces only your prior status reaction on that comment. Addressed on a change request asks its reviewer to review again, unless they approved since. Only works on pull requests the bot authored.",
3304
3386
  exposure: "direct",
3305
3387
  inputSchema: inputSchema$2,
3306
3388
  outputSchema: outputSchema$2,
@@ -3336,13 +3418,19 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3336
3418
  const listPayload = listResponse.body;
3337
3419
  if (failed(listResponse)) throw new Error(`GitHub reaction lookup failed with HTTP ${listResponse.status}: ${githubErrorMessage$1(listPayload)}`);
3338
3420
  const botReactions = reactions.botReactions(listPayload).filter((reaction) => FEEDBACK_REACTION_CONTENTS.has(reaction.content));
3339
- const deleteResponses = await Promise.all(botReactions.filter((stale) => stale.content !== targetContent).map((stale) => reactions.remove(stale)));
3421
+ const deleteResponses = await pLimit(FEEDBACK_REACTION_CONTENTS.size).map(botReactions.filter((stale) => stale.content !== targetContent), (stale) => reactions.remove(stale));
3340
3422
  for (const deleteResponse of deleteResponses) if (failed(deleteResponse) && deleteResponse.status !== 404) throw new Error(`GitHub reaction removal failed with HTTP ${deleteResponse.status}: ${githubErrorMessage$1(deleteResponse.body)}`);
3341
3423
  if (!botReactions.some((reaction) => reaction.content === targetContent)) {
3342
3424
  const createResponse = await reactions.add(targetContent);
3343
3425
  const createPayload = createResponse.body;
3344
3426
  if (failed(createResponse)) throw new Error(`GitHub reaction creation failed with HTTP ${createResponse.status}: ${githubErrorMessage$1(createPayload)}`);
3345
3427
  }
3428
+ if (status === "addressed" && reactions.changesRequestedBy) await requestReviewAgain(ctx, {
3429
+ owner: repo.owner,
3430
+ name: repo.name,
3431
+ pullRequest,
3432
+ reviewer: reactions.changesRequestedBy
3433
+ });
3346
3434
  return {
3347
3435
  target: "updatePullRequestFeedback",
3348
3436
  repo: repo.ref,
@@ -3815,11 +3903,16 @@ async function recordGitHubPullRequestConversations(db, input) {
3815
3903
  /** Link an existing Junior-owned PR to tracked issues across repositories. */
3816
3904
  async function recordGitHubPullRequestLinkedIssues(db, input) {
3817
3905
  const association = githubPullRequestLinkedIssuesInputSchema.parse(input);
3818
- return (await Promise.all(association.linkedIssues.map((issue) => db.insert(juniorGitHubPullRequestIssues).select(db.select({
3906
+ const list = (values) => sql.join(values.map((value) => sql`${value}`), sql`, `);
3907
+ const issues = sql`unnest(
3908
+ ARRAY[${list(association.linkedIssues.map((issue) => issue.repositoryFullName))}]::text[],
3909
+ ARRAY[${list(association.linkedIssues.map((issue) => issue.number))}]::integer[]
3910
+ ) AS issue(repository_full_name, number)`;
3911
+ return (await db.insert(juniorGitHubPullRequestIssues).select(db.select({
3819
3912
  pullRequestId: juniorGitHubPullRequests.pullRequestId,
3820
- issueRepositoryFullName: sql`lower(${issue.repositoryFullName})`.as("issue_repository_full_name"),
3821
- issueNumber: sql`${issue.number}`.as("issue_number")
3822
- }).from(juniorGitHubPullRequests).where(eq(juniorGitHubPullRequests.pullRequestId, association.pullRequestId))).onConflictDoNothing().returning({ issueNumber: juniorGitHubPullRequestIssues.issueNumber })))).some((rows) => rows.length > 0);
3913
+ issueRepositoryFullName: sql`lower(issue.repository_full_name)`.as("issue_repository_full_name"),
3914
+ issueNumber: sql`issue.number`.as("issue_number")
3915
+ }).from(juniorGitHubPullRequests).crossJoin(issues).where(eq(juniorGitHubPullRequests.pullRequestId, association.pullRequestId))).onConflictDoNothing().returning({ issueNumber: juniorGitHubPullRequestIssues.issueNumber })).length > 0;
3823
3916
  }
3824
3917
  /** Match one pull request row by repository name, in any case, and number. */
3825
3918
  function pullRequestRow(target) {
@@ -4268,7 +4361,6 @@ function normalizeGitHubPullRequestActivity(input) {
4268
4361
  return senderType === "Bot" ? void 0 : activity;
4269
4362
  }
4270
4363
  // src/webhooks/pull-request-preview.ts
4271
- const ANNOTATION_UPDATE_CONCURRENCY = 8;
4272
4364
  const previewWebhookSchema = z.object({
4273
4365
  action: z.enum([
4274
4366
  "opened",
@@ -4297,7 +4389,7 @@ async function refreshGitHubPullRequestPreview(args) {
4297
4389
  const key = `${repository.full_name.toLowerCase()}#${pullRequest.number}`;
4298
4390
  const previewImageUrls = githubPreviewImageUrls(pullRequest.body);
4299
4391
  const updatedAt = Date.parse(pullRequest.updated_at);
4300
- const limit = pLimit(ANNOTATION_UPDATE_CONCURRENCY);
4392
+ const limit = pLimit(8);
4301
4393
  const results = await Promise.allSettled(conversationIds.map((conversationId) => limit(async () => {
4302
4394
  const store = args.annotations.forConversation(conversationId);
4303
4395
  const current = (await store.list()).find((annotation) => annotation.key === key);
@@ -4628,8 +4720,7 @@ async function loadGitHubMergeConflictEvents(args) {
4628
4720
  return [];
4629
4721
  }
4630
4722
  };
4631
- const limit = pLimit(PULL_REQUEST_CHECK_CONCURRENCY);
4632
- return (await Promise.all(pullRequestRefs(args.events).map((ref) => limit(() => check(ref))))).flat();
4723
+ return (await pLimit(PULL_REQUEST_CHECK_CONCURRENCY).map(pullRequestRefs(args.events), (ref) => check(ref))).flat();
4633
4724
  }
4634
4725
  // src/merge-conflict-checks/store.ts
4635
4726
  /** A key that waits longer than this was lost and expires. */
@@ -4921,6 +5012,7 @@ async function loadRepositoryRole(env, cache, target) {
4921
5012
  const pullRequestSchema = z.object({
4922
5013
  auto_merge: z.object({}).nullable().optional(),
4923
5014
  draft: z.boolean().optional(),
5015
+ head: z.object({ sha: z.string().min(1) }),
4924
5016
  html_url: z.string().url(),
4925
5017
  mergeable_state: z.string().nullable().optional(),
4926
5018
  merged: z.boolean(),
@@ -4928,18 +5020,16 @@ const pullRequestSchema = z.object({
4928
5020
  state: z.enum(["open", "closed"]),
4929
5021
  title: z.string()
4930
5022
  });
4931
- const reviewsSchema = z.array(z.object({
4932
- state: z.string(),
4933
- user: z.object({ login: z.string() }).nullable()
4934
- }));
4935
5023
  /**
4936
- * Read whether a pull request is ready to merge, with a read-only token.
4937
- * GitHub computes `mergeable_state` after a change, so an unknown state is
4938
- * read once more. Reviews load only for an open pull request that is not a
4939
- * draft, has no auto-merge, and can merge cleanly. Each reviewer counts by their latest
4940
- * approval, change request, or dismissal. Comments do not change the result.
5024
+ * Read whether a pull request is ready to merge, and whether the requester
5025
+ * changed their review, with a read-only token. GitHub computes
5026
+ * `mergeable_state` after a change, so an unknown state is read once more.
5027
+ * Reviews load for an open pull request that is not a draft, when it can
5028
+ * merge cleanly or GitHub does not ask the requester for a review. Each
5029
+ * reviewer counts by their latest approval, change request, or dismissal.
5030
+ * Comments do not change the result.
4941
5031
  */
4942
- async function loadPullRequestMergeState(env, pullRequest) {
5032
+ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4943
5033
  const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request merge state");
4944
5034
  const token = await issueInstallationToken({
4945
5035
  ...env,
@@ -4954,6 +5044,7 @@ async function loadPullRequestMergeState(env, pullRequest) {
4954
5044
  approved: false,
4955
5045
  autoMerge: Boolean(pull.auto_merge),
4956
5046
  draft: pull.draft === true,
5047
+ headSha: pull.head.sha,
4957
5048
  ...mergeableState ? { mergeableState } : void 0,
4958
5049
  requestedReviewers: (pull.requested_reviewers ?? []).map((reviewer) => reviewer.login),
4959
5050
  state: pull.merged ? "merged" : pull.state,
@@ -4962,19 +5053,18 @@ async function loadPullRequestMergeState(env, pullRequest) {
4962
5053
  };
4963
5054
  };
4964
5055
  let state = await readPull();
4965
- if (state.state !== "open" || state.draft || state.autoMerge) return state;
4966
- if (!state.mergeableState) state = await readPull();
4967
- if (state.mergeableState !== "clean") return state;
4968
- const reviews = [];
4969
- for (let page = 1;; page++) {
4970
- const batch = reviewsSchema.parse(await read(`/reviews?per_page=100&page=${page}`));
4971
- reviews.push(...batch);
4972
- if (batch.length < 100) break;
4973
- }
4974
- const latestReviews = /* @__PURE__ */ new Map();
4975
- for (const review of reviews) if (review.user && review.state !== "COMMENTED" && review.state !== "PENDING") latestReviews.set(review.user.login.toLowerCase(), review.state);
4976
- const reviewStates = [...latestReviews.values()];
4977
- state.approved = reviewStates.includes("APPROVED") && !reviewStates.includes("CHANGES_REQUESTED");
5056
+ if (state.state !== "open" || state.draft) return state;
5057
+ const canMerge = !state.autoMerge;
5058
+ if (canMerge && !state.mergeableState) state = await readPull();
5059
+ const login = requesterLogin?.toLowerCase();
5060
+ const readsChanges = login !== void 0 && !state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === login);
5061
+ const readsApproval = canMerge && state.mergeableState === "clean";
5062
+ if (!readsApproval && !readsChanges) return state;
5063
+ const latestReviews = await loadLatestReviews(async (query) => await read(`/reviews?${query}`));
5064
+ const reviewStates = [...latestReviews.values()].map((review) => review.state);
5065
+ if (readsApproval) state.approved = reviewStates.includes("APPROVED") && !reviewStates.includes("CHANGES_REQUESTED");
5066
+ const requesterReview = login ? latestReviews.get(login) : void 0;
5067
+ if (requesterReview?.state === "CHANGES_REQUESTED" && requesterReview.commit_id) state.changesRequestedCommit = requesterReview.commit_id;
4978
5068
  return state;
4979
5069
  }
4980
5070
  // src/webhooks/pull-request-action.ts
@@ -5039,6 +5129,10 @@ function nextAction(state, requesterLogin, saved) {
5039
5129
  if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5040
5130
  const login = requesterLogin?.toLowerCase();
5041
5131
  if (login && state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === login)) return { action: "review" };
5132
+ if (state.changesRequestedCommit && state.changesRequestedCommit !== state.headSha) return {
5133
+ action: "review",
5134
+ rereview: true
5135
+ };
5042
5136
  if (canMerge && !state.mergeableState) return void 0;
5043
5137
  return {};
5044
5138
  }
@@ -5073,7 +5167,7 @@ async function showAction(items, args) {
5073
5167
  const { action, number, state } = args;
5074
5168
  if (action) await items.upsert({
5075
5169
  assigneeIdentityIds: [args.identityId],
5076
- body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` : `GitHub asks you to review #${number}.\n\n${state.url}`,
5170
+ body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` : args.rereview ? `#${number} has new commits since you requested changes.\n\n${state.url}` : `GitHub asks you to review #${number}.\n\n${state.url}`,
5077
5171
  dedupeKey: args.dedupeKey,
5078
5172
  subject: {
5079
5173
  id: state.url,
@@ -5108,7 +5202,7 @@ async function syncOne(args, target) {
5108
5202
  let requests = claim.requests;
5109
5203
  let failure;
5110
5204
  const check = async (previous) => {
5111
- const state = await loadPullRequestMergeState(args.env, target);
5205
+ const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
5112
5206
  const next = nextAction(state, requesterLogin, previous);
5113
5207
  const changed = next !== void 0 && next.action !== previous;
5114
5208
  if (changed) await showAction(items, {
@@ -5117,6 +5211,7 @@ async function syncOne(args, target) {
5117
5211
  identityId: opener.identityId,
5118
5212
  number: target.number,
5119
5213
  previous,
5214
+ rereview: next.rereview === true,
5120
5215
  state
5121
5216
  });
5122
5217
  await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
@@ -5152,8 +5247,7 @@ async function syncOne(args, target) {
5152
5247
  * and does not fail the delivery.
5153
5248
  */
5154
5249
  async function syncGitHubPullRequestActions(args) {
5155
- const limit = pLimit(PULL_REQUEST_SYNC_CONCURRENCY);
5156
- await Promise.all(args.targets.map((target) => limit(async () => {
5250
+ await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map(args.targets, async (target) => {
5157
5251
  try {
5158
5252
  await syncOne(args, target);
5159
5253
  } catch (error) {
@@ -5163,7 +5257,7 @@ async function syncGitHubPullRequestActions(args) {
5163
5257
  repository: target.repositoryFullName
5164
5258
  });
5165
5259
  }
5166
- })));
5260
+ });
5167
5261
  }
5168
5262
  // src/webhooks/pull-request-ready-reviewers.ts
5169
5263
  const readyForReviewSchema = z.object({
@@ -5277,14 +5371,13 @@ async function withJuniorOpeners(context, events) {
5277
5371
  repositoryFullName: context.repositoryFullName
5278
5372
  });
5279
5373
  const logins = /* @__PURE__ */ new Map();
5280
- const limit = pLimit(LOGIN_LOAD_CONCURRENCY);
5281
- await Promise.all([...new Set([...openers.values()].map((opener) => opener.identityId))].map((identityId) => limit(async () => {
5374
+ await pLimit(LOGIN_LOAD_CONCURRENCY).map([...new Set([...openers.values()].map((opener) => opener.identityId))], async (identityId) => {
5282
5375
  try {
5283
5376
  logins.set(identityId, await context.loadGitHubLogin?.(identityId));
5284
5377
  } catch (error) {
5285
5378
  logFailure(context, "opener", error);
5286
5379
  }
5287
- })));
5380
+ });
5288
5381
  return events.map((event) => {
5289
5382
  const number = botNumber(event);
5290
5383
  if (number === void 0) return event;
@@ -6898,8 +6991,7 @@ function objectTitle(kind, object) {
6898
6991
  * References that `loadObject` cannot read are left out.
6899
6992
  */
6900
6993
  async function loadGitHubConversationTitleContext(args) {
6901
- const limit = pLimit(REFERENCE_LOAD_CONCURRENCY);
6902
- return (await Promise.all(parseGitHubReferences(args.text, args.config).map((reference) => limit(async () => {
6994
+ return (await pLimit(REFERENCE_LOAD_CONCURRENCY).map(parseGitHubReferences(args.text, args.config), async (reference) => {
6903
6995
  try {
6904
6996
  const title = objectTitle(reference.kind, await args.loadObject(reference));
6905
6997
  if (!title) return void 0;
@@ -6911,7 +7003,7 @@ async function loadGitHubConversationTitleContext(args) {
6911
7003
  });
6912
7004
  return;
6913
7005
  }
6914
- })))).filter((line) => Boolean(line));
7006
+ })).filter((line) => Boolean(line));
6915
7007
  }
6916
7008
  // src/workspace-prepare.ts
6917
7009
  /** Clone missing GitHub repositories or refresh existing Workspace checkouts. */
package/dist/testing.js CHANGED
@@ -1 +1 @@
1
- export { n as normalizeGitHubEvents } from "./events-CAZiit9g.js";
1
+ export { n as normalizeGitHubEvents } from "./events-D5Zs75yy.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/junior-github",
3
- "version": "0.308.0",
3
+ "version": "0.309.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "dependencies": {
31
31
  "@0no-co/graphql.web": "^1.3.4",
32
- "@sentry/junior-plugin-api": "0.308.0",
32
+ "@sentry/junior-plugin-api": "0.309.0",
33
33
  "@sinclair/typebox": "^0.34.49",
34
34
  "drizzle-orm": "^0.45.4",
35
35
  "ignore": "^7.0.5",
@@ -44,7 +44,7 @@ Open this when making repository edits, not for read-only inspection.
44
44
  4. Resolve the actual default branch.
45
45
  5. Update an existing PR for the branch with `github_updatePullRequest`, or create with `github_createPullRequest` (`draft: true` unless the requester asked for a ready PR).
46
46
  6. PR title matches the current dominant change, same conventional form as commits.
47
- 7. PR body: short, plain English, what changed and why. Only context the diff cannot show. No empty sections, file lists, commit logs, or Checks/Verification/Test plan blocks.
47
+ 7. PR body: only context the diff cannot show. No empty sections, file lists, or commit logs.
48
48
  8. After material follow-up commits, refresh title and body against the current diff.
49
49
  9. Never put customer data, PII, secrets, or sensitive thread context in public PR text.
50
50
  10. If PR create/update is blocked, report the exact failure and leave the committed branch intact.