@sentry/junior-github 0.267.0 → 0.269.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
@@ -29,6 +29,7 @@ import {
29
29
  USER_WRITE_REQUIREMENTS,
30
30
  botLoginFromEmail,
31
31
  botUserIdFromEmail,
32
+ checkSuitePullRequests,
32
33
  createPermissionCache,
33
34
  definedValues,
34
35
  gitHubDeploymentSourceSubscribable,
@@ -56,7 +57,7 @@ import {
56
57
  readGrantPermissions,
57
58
  requireEnv,
58
59
  resolveUserAccount
59
- } from "./chunk-PQFFT2UO.js";
60
+ } from "./chunk-DGGPIWTT.js";
60
61
 
61
62
  // src/tool-support/attribution.ts
62
63
  var GITHUB_REQUEST_ATTRIBUTION_START = "<!-- junior-request-attribution:start -->";
@@ -1250,7 +1251,23 @@ var juniorGitHubPullRequests = pgTable(
1250
1251
  openedAt: timestamp("opened_at", { withTimezone: true }).notNull(),
1251
1252
  mergedAt: timestamp("merged_at", { withTimezone: true }),
1252
1253
  closedAt: timestamp("closed_at", { withTimezone: true }),
1253
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull()
1254
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
1255
+ /**
1256
+ * When Junior saw the pull request become ready to merge and added its
1257
+ * review desk notice. Null when it is not ready.
1258
+ */
1259
+ readyToMergeAt: timestamp("ready_to_merge_at", { withTimezone: true }),
1260
+ /**
1261
+ * Webhooks that asked to check whether the pull request is ready to
1262
+ * merge. The check runs again when this changes during a check.
1263
+ */
1264
+ readySyncRequests: integer("ready_sync_requests").notNull().default(0),
1265
+ /**
1266
+ * The request that runs the current check. Null when no check runs.
1267
+ */
1268
+ readySyncId: integer("ready_sync_id"),
1269
+ /** When the current check started. */
1270
+ readySyncAt: timestamp("ready_sync_at", { withTimezone: true })
1254
1271
  },
1255
1272
  (table2) => [
1256
1273
  index("junior_github_pull_requests_opened_at_idx").on(table2.openedAt),
@@ -1287,6 +1304,8 @@ var juniorGitHubPullRequestRequesters = pgTable(
1287
1304
  number: integer("number").notNull(),
1288
1305
  /** Core `junior_identities.id` of the person who acted. */
1289
1306
  identityId: text("identity_id").notNull(),
1307
+ /** The Conversation where the person asked Junior to open the pull request. */
1308
+ conversationId: text("conversation_id"),
1290
1309
  createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
1291
1310
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull()
1292
1311
  },
@@ -1302,6 +1321,7 @@ var table = juniorGitHubPullRequestRequesters;
1302
1321
  async function recordGitHubPullRequestOpener(db, input) {
1303
1322
  const repositoryFullName = input.repositoryFullName.toLowerCase();
1304
1323
  await db.insert(table).values({
1324
+ conversationId: input.conversationId,
1305
1325
  createdAt: input.createdAt,
1306
1326
  identityId: input.identityId,
1307
1327
  number: input.number,
@@ -1309,7 +1329,7 @@ async function recordGitHubPullRequestOpener(db, input) {
1309
1329
  updatedAt: /* @__PURE__ */ new Date()
1310
1330
  }).onConflictDoUpdate({
1311
1331
  target: [table.repositoryFullName, table.number, table.identityId],
1312
- set: { createdAt: input.createdAt }
1332
+ set: { conversationId: input.conversationId, createdAt: input.createdAt }
1313
1333
  });
1314
1334
  await db.delete(table).where(
1315
1335
  and(
@@ -1342,7 +1362,12 @@ async function listGitHubPullRequestOpeners(db, input) {
1342
1362
  )
1343
1363
  ).orderBy(asc(table.createdAt));
1344
1364
  for (const row of rows) {
1345
- if (!openers.has(row.number)) openers.set(row.number, row.identityId);
1365
+ if (!openers.has(row.number)) {
1366
+ openers.set(row.number, {
1367
+ identityId: row.identityId,
1368
+ ...row.conversationId ? { conversationId: row.conversationId } : void 0
1369
+ });
1370
+ }
1346
1371
  }
1347
1372
  return openers;
1348
1373
  }
@@ -1578,10 +1603,12 @@ async function createGitHubPullRequest(ctx, request) {
1578
1603
  url: pullRequest.html_url
1579
1604
  };
1580
1605
  }
1581
- async function recordOpener(ctx, input, state, identityId) {
1606
+ async function recordOpener(ctx, input, state, requester) {
1607
+ const { conversationId, identityId } = requester;
1582
1608
  if (!identityId) return;
1583
1609
  const repo = parseRepo4(input.repo);
1584
1610
  await recordGitHubPullRequestOpener(ctx.db, {
1611
+ conversationId,
1585
1612
  createdAt: new Date(state.createdAtMs),
1586
1613
  identityId,
1587
1614
  number: state.number,
@@ -1722,12 +1749,10 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
1722
1749
  const state = createPullRequestState(await ctx.state.get(key));
1723
1750
  if (state?.status === "completed") {
1724
1751
  const completedInput = state.input ?? parsedInput;
1725
- await recordOpener(
1726
- ctx,
1727
- completedInput,
1728
- state,
1729
- (await resolveGitHubRequester(ctx))?.identity?.id
1730
- );
1752
+ await recordOpener(ctx, completedInput, state, {
1753
+ conversationId,
1754
+ identityId: (await resolveGitHubRequester(ctx))?.identity?.id
1755
+ });
1731
1756
  const completedResult = {
1732
1757
  facts: state.facts === void 0 ? void 0 : objectFactsSchema2.parse(state.facts),
1733
1758
  sourceUpdatedAt: state.sourceUpdatedAt,
@@ -1792,7 +1817,10 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
1792
1817
  { cause: error }
1793
1818
  );
1794
1819
  }
1795
- await recordOpener(ctx, parsedInput, completedState, identityId);
1820
+ await recordOpener(ctx, parsedInput, completedState, {
1821
+ conversationId,
1822
+ identityId
1823
+ });
1796
1824
  await assignPullRequestRequester(ctx, parsedInput, result, requester);
1797
1825
  return await gitHubPullRequestStructuredResult(
1798
1826
  ctx,
@@ -2619,9 +2647,12 @@ function parseRepo10(value) {
2619
2647
  }
2620
2648
  return { owner: parts[0], name: parts[1], ref: `${parts[0]}/${parts[1]}` };
2621
2649
  }
2622
- function pullRequestCommentReactionsPath(input) {
2650
+ function pullRequestCommentPath(input) {
2623
2651
  const segment = input.commentKind === "conversation" ? "issues" : "pulls";
2624
- return `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.name)}/${segment}/comments/${input.commentId}/reactions`;
2652
+ return `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.name)}/${segment}/comments/${input.commentId}`;
2653
+ }
2654
+ function pullRequestCommentReactionsPath(input) {
2655
+ return `${pullRequestCommentPath(input)}/reactions`;
2625
2656
  }
2626
2657
  function pullRequestFeedbackReactionContent(status) {
2627
2658
  return STATUS_TO_REACTION_CONTENT[status];
@@ -2647,15 +2678,67 @@ var reactionSchema = z12.object({
2647
2678
  content: z12.string(),
2648
2679
  user: z12.object({ id: z12.number() }).nullable()
2649
2680
  });
2681
+ async function assertBotAuthoredPullRequest(egress, input) {
2682
+ const headers = {
2683
+ Accept: "application/vnd.github+json",
2684
+ "X-GitHub-Api-Version": "2022-11-28"
2685
+ };
2686
+ const commentResponse = await egress.fetch({
2687
+ provider: "github",
2688
+ operation: "github.pull.comment.get",
2689
+ request: new Request(
2690
+ `https://api.github.com${pullRequestCommentPath(input)}`,
2691
+ { headers }
2692
+ )
2693
+ });
2694
+ const commentPayload = await readJson7(commentResponse);
2695
+ if (!commentResponse.ok) {
2696
+ const message = `GitHub comment lookup failed with HTTP ${commentResponse.status}: ${githubError(commentPayload)}`;
2697
+ if (commentResponse.status === 404) throw new PluginToolInputError11(message);
2698
+ throw new Error(message);
2699
+ }
2700
+ const comment = z12.object({
2701
+ issue_url: z12.string().optional(),
2702
+ pull_request_url: z12.string().optional()
2703
+ }).safeParse(commentPayload);
2704
+ const parentUrl = comment.success ? input.commentKind === "conversation" ? comment.data.issue_url : comment.data.pull_request_url : void 0;
2705
+ const number = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
2706
+ if (!number) {
2707
+ throw new Error("GitHub comment did not name its issue or pull request.");
2708
+ }
2709
+ const pullResponse = await egress.fetch({
2710
+ provider: "github",
2711
+ operation: "github.pull.get",
2712
+ request: new Request(
2713
+ `https://api.github.com/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.name)}/pulls/${number}`,
2714
+ { headers }
2715
+ )
2716
+ });
2717
+ const pullPayload = await readJson7(pullResponse);
2718
+ if (!pullResponse.ok && pullResponse.status !== 404) {
2719
+ throw new Error(
2720
+ `GitHub pull request lookup failed with HTTP ${pullResponse.status}: ${githubError(pullPayload)}`
2721
+ );
2722
+ }
2723
+ const pull = z12.object({ user: z12.object({ id: z12.number() }).nullable() }).safeParse(pullPayload);
2724
+ if (!pullResponse.ok || !pull.success || pull.data.user?.id !== input.botUserId) {
2725
+ throw new PluginToolInputError11(
2726
+ "This bot can only set feedback status on comments on pull requests it authored."
2727
+ );
2728
+ }
2729
+ }
2650
2730
  function createGitHubUpdatePullRequestFeedbackTool(ctx, botEmail) {
2651
2731
  return definePluginTool10({
2732
+ // No action review: the tool checks in code that the bot authored the pull
2733
+ // request, and it changes only the bot's own reaction, which is reversible.
2734
+ approvalMode: "approve",
2652
2735
  annotations: {
2653
2736
  destructiveHint: true,
2654
2737
  idempotentHint: true,
2655
2738
  openWorldHint: true,
2656
2739
  readOnlyHint: false
2657
2740
  },
2658
- description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Use the commentId and commentKind from the event after acting on the feedback. Replaces only your prior status reaction on that comment.",
2741
+ description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Use the commentId and commentKind from the event after acting on the feedback. Replaces only your prior status reaction on that comment. Only works on pull requests the bot authored.",
2659
2742
  exposure: "direct",
2660
2743
  inputSchema: inputSchema8,
2661
2744
  outputSchema: outputSchema8,
@@ -2673,6 +2756,13 @@ function createGitHubUpdatePullRequestFeedbackTool(ctx, botEmail) {
2673
2756
  if (botUserId === void 0) {
2674
2757
  throw new Error("GitHub App bot identity is not configured.");
2675
2758
  }
2759
+ await assertBotAuthoredPullRequest(ctx.egress, {
2760
+ owner: repo.owner,
2761
+ name: repo.name,
2762
+ commentKind,
2763
+ commentId,
2764
+ botUserId
2765
+ });
2676
2766
  const targetContent = pullRequestFeedbackReactionContent(status);
2677
2767
  const baseUrl = `https://api.github.com${pullRequestCommentReactionsPath({
2678
2768
  owner: repo.owner,
@@ -2801,6 +2891,10 @@ function githubError2(payload) {
2801
2891
  }
2802
2892
  function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
2803
2893
  return definePluginTool11({
2894
+ // No action review: the tool checks in code that the bot authored the pull
2895
+ // request, and it changes only the thread's resolved state, which is
2896
+ // reversible.
2897
+ approvalMode: "approve",
2804
2898
  annotations: {
2805
2899
  destructiveHint: true,
2806
2900
  idempotentHint: true,
@@ -3097,7 +3191,7 @@ function createGitHubTools(ctx, botEmail, pullRequestSubscription) {
3097
3191
 
3098
3192
  // src/webhooks/handler.ts
3099
3193
  import { createHmac, timingSafeEqual } from "crypto";
3100
- import { z as z21 } from "zod";
3194
+ import { z as z23 } from "zod";
3101
3195
 
3102
3196
  // src/issue-outcomes/store.ts
3103
3197
  import { and as and2, eq as eq2, lte, sql as sql2 } from "drizzle-orm";
@@ -3369,6 +3463,44 @@ async function recordGitHubPullRequestLinkedIssues(db, input) {
3369
3463
  );
3370
3464
  return inserted.some((rows) => rows.length > 0);
3371
3465
  }
3466
+ function pullRequestRow(target) {
3467
+ return and3(
3468
+ sql3`lower(${juniorGitHubPullRequests.repositoryFullName}) = ${target.repositoryFullName.toLowerCase()}`,
3469
+ eq3(juniorGitHubPullRequests.number, target.number)
3470
+ );
3471
+ }
3472
+ async function claimGitHubPullRequestReadySync(db, target, options) {
3473
+ const t = juniorGitHubPullRequests;
3474
+ const staleBefore = new Date(options.now.getTime() - options.staleMs);
3475
+ const free = sql3`(${t.readySyncId} is null or ${t.readySyncAt} < ${staleBefore.toISOString()}::timestamptz)`;
3476
+ const [row] = await db.update(t).set({
3477
+ readySyncRequests: sql3`${t.readySyncRequests} + 1`,
3478
+ // Each request has its own number, so it is the id of the claim.
3479
+ readySyncId: sql3`case when ${free} then ${t.readySyncRequests} + 1 else ${t.readySyncId} end`,
3480
+ readySyncAt: sql3`case when ${free} then ${options.now.toISOString()}::timestamptz else ${t.readySyncAt} end`
3481
+ }).where(pullRequestRow(target)).returning({
3482
+ id: t.readySyncId,
3483
+ readyToMergeAt: t.readyToMergeAt,
3484
+ requests: t.readySyncRequests
3485
+ });
3486
+ if (!row || row.id !== row.requests) return void 0;
3487
+ return {
3488
+ id: row.id,
3489
+ ready: row.readyToMergeAt !== null,
3490
+ requests: row.requests
3491
+ };
3492
+ }
3493
+ async function setGitHubPullRequestReadyToMerge(db, target) {
3494
+ await db.update(juniorGitHubPullRequests).set({ readyToMergeAt: target.ready ? /* @__PURE__ */ new Date() : null }).where(pullRequestRow(target));
3495
+ }
3496
+ async function releaseGitHubPullRequestReadySync(db, target, claim) {
3497
+ const t = juniorGitHubPullRequests;
3498
+ const claimed = and3(pullRequestRow(target), eq3(t.readySyncId, claim.id));
3499
+ const released = await db.update(t).set({ readySyncAt: null, readySyncId: null }).where(and3(claimed, eq3(t.readySyncRequests, claim.requests))).returning({ number: t.number });
3500
+ if (released.length > 0) return void 0;
3501
+ const [row] = await db.select({ requests: t.readySyncRequests }).from(t).where(claimed);
3502
+ return row?.requests;
3503
+ }
3372
3504
 
3373
3505
  // src/webhooks/issue-outcome.ts
3374
3506
  import { z as z17 } from "zod";
@@ -3671,8 +3803,262 @@ function normalizeGitHubPullRequestLinkedIssues(args) {
3671
3803
  } : void 0;
3672
3804
  }
3673
3805
 
3674
- // src/webhooks/pull-request-match-data.ts
3806
+ // src/webhooks/pull-request-ready.ts
3807
+ import { z as z20 } from "zod";
3808
+
3809
+ // src/webhooks/installation-requests.ts
3675
3810
  import { z as z19 } from "zod";
3811
+ function splitRepository(fullName, label) {
3812
+ const [owner, name, ...extra] = fullName.split("/");
3813
+ if (!owner || !name || extra.length > 0) {
3814
+ throw new Error(`GitHub ${label} received an invalid repository name`);
3815
+ }
3816
+ return { owner, name };
3817
+ }
3818
+ async function loadPullRequestCommitPages(env, pullRequest) {
3819
+ const { owner, name } = splitRepository(
3820
+ pullRequest.repositoryFullName,
3821
+ "pull request commits"
3822
+ );
3823
+ const token = await issueInstallationToken({
3824
+ ...env,
3825
+ permissions: { pull_requests: "read" },
3826
+ repositories: [name]
3827
+ });
3828
+ return async (page, perPage) => await githubRequest(
3829
+ "https://api.github.com",
3830
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}/commits?per_page=${perPage}&page=${page}`,
3831
+ { token: token.token }
3832
+ );
3833
+ }
3834
+ async function markPullRequestFeedbackReviewing(env, target) {
3835
+ const { owner, name } = splitRepository(target.repo, "pull request feedback");
3836
+ const token = await issueInstallationToken({
3837
+ ...env,
3838
+ repositories: [name]
3839
+ });
3840
+ await githubRequest(
3841
+ "https://api.github.com",
3842
+ pullRequestCommentReactionsPath({
3843
+ owner,
3844
+ name,
3845
+ commentKind: target.commentKind,
3846
+ commentId: target.commentId
3847
+ }),
3848
+ {
3849
+ body: { content: pullRequestFeedbackReactionContent("reviewing") },
3850
+ method: "POST",
3851
+ token: token.token
3852
+ }
3853
+ );
3854
+ }
3855
+ var repositoryPermissionSchema = z19.object({
3856
+ permission: z19.string().min(1),
3857
+ role_name: z19.string().optional()
3858
+ });
3859
+ var REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1e3;
3860
+ async function loadRepositoryRole(env, cache, target) {
3861
+ const { owner, name } = splitRepository(
3862
+ target.repositoryFullName,
3863
+ "repository role"
3864
+ );
3865
+ return await cache.getOrLoad(
3866
+ `repository-role:${owner}/${name}:${target.login}`.toLowerCase(),
3867
+ async () => {
3868
+ const token = await issueInstallationToken({
3869
+ ...env,
3870
+ permissions: { metadata: "read" },
3871
+ repositories: [name]
3872
+ });
3873
+ const response = repositoryPermissionSchema.parse(
3874
+ await githubRequest(
3875
+ "https://api.github.com",
3876
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/collaborators/${encodeURIComponent(target.login)}/permission`,
3877
+ { token: token.token }
3878
+ )
3879
+ );
3880
+ return {
3881
+ value: response.role_name?.trim() || response.permission,
3882
+ ttlMs: REPOSITORY_ROLE_TTL_MS
3883
+ };
3884
+ }
3885
+ );
3886
+ }
3887
+ var pullRequestSchema3 = z19.object({
3888
+ draft: z19.boolean().optional(),
3889
+ html_url: z19.string().url(),
3890
+ mergeable_state: z19.string().nullable().optional(),
3891
+ merged: z19.boolean(),
3892
+ state: z19.enum(["open", "closed"]),
3893
+ title: z19.string()
3894
+ });
3895
+ var reviewsSchema = z19.array(
3896
+ z19.object({
3897
+ state: z19.string(),
3898
+ user: z19.object({ login: z19.string() }).nullable()
3899
+ })
3900
+ );
3901
+ async function loadPullRequestMergeState(env, pullRequest) {
3902
+ const { owner, name } = splitRepository(
3903
+ pullRequest.repositoryFullName,
3904
+ "pull request merge state"
3905
+ );
3906
+ const token = await issueInstallationToken({
3907
+ ...env,
3908
+ permissions: { pull_requests: "read" },
3909
+ repositories: [name]
3910
+ });
3911
+ const read = async (path) => await githubRequest(
3912
+ "https://api.github.com",
3913
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}${path}`,
3914
+ { token: token.token }
3915
+ );
3916
+ const readPull = async () => {
3917
+ const pull = pullRequestSchema3.parse(await read(""));
3918
+ const mergeableState = pull.mergeable_state && pull.mergeable_state !== "unknown" ? pull.mergeable_state : void 0;
3919
+ return {
3920
+ approved: false,
3921
+ draft: pull.draft === true,
3922
+ ...mergeableState ? { mergeableState } : void 0,
3923
+ state: pull.merged ? "merged" : pull.state,
3924
+ title: pull.title,
3925
+ url: pull.html_url
3926
+ };
3927
+ };
3928
+ let state = await readPull();
3929
+ if (state.state !== "open" || state.draft) return state;
3930
+ if (!state.mergeableState) state = await readPull();
3931
+ if (state.mergeableState !== "clean") return state;
3932
+ const reviews = [];
3933
+ for (let page = 1; ; page++) {
3934
+ const batch = reviewsSchema.parse(
3935
+ await read(`/reviews?per_page=100&page=${page}`)
3936
+ );
3937
+ reviews.push(...batch);
3938
+ if (batch.length < 100) break;
3939
+ }
3940
+ const latestReviews = /* @__PURE__ */ new Map();
3941
+ for (const review of reviews) {
3942
+ if (review.user && review.state !== "COMMENTED" && review.state !== "PENDING") {
3943
+ latestReviews.set(review.user.login.toLowerCase(), review.state);
3944
+ }
3945
+ }
3946
+ const reviewStates = [...latestReviews.values()];
3947
+ state.approved = reviewStates.includes("APPROVED") && !reviewStates.includes("CHANGES_REQUESTED");
3948
+ return state;
3949
+ }
3950
+
3951
+ // src/webhooks/pull-request-ready.ts
3952
+ var READY_SYNC_STALE_MS = 6e4;
3953
+ var READY_ACTIONS = {
3954
+ pull_request: /* @__PURE__ */ new Set([
3955
+ "closed",
3956
+ "converted_to_draft",
3957
+ "ready_for_review",
3958
+ "reopened",
3959
+ "synchronize"
3960
+ ]),
3961
+ pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
3962
+ };
3963
+ var pullRequestWebhookSchema = z20.object({
3964
+ action: z20.string(),
3965
+ pull_request: z20.object({ number: z20.number().int().positive() }),
3966
+ repository: z20.object({ full_name: z20.string().min(1) })
3967
+ });
3968
+ function pullRequestReadyTargets(eventName, body) {
3969
+ if (eventName === "check_suite") return checkSuitePullRequests(body);
3970
+ const actions = READY_ACTIONS[eventName];
3971
+ const parsed = pullRequestWebhookSchema.safeParse(body);
3972
+ if (!actions || !parsed.success || !actions.has(parsed.data.action)) {
3973
+ return [];
3974
+ }
3975
+ return [
3976
+ {
3977
+ number: parsed.data.pull_request.number,
3978
+ repositoryFullName: parsed.data.repository.full_name
3979
+ }
3980
+ ];
3981
+ }
3982
+ function closeReason(state) {
3983
+ if (state.state === "merged") {
3984
+ return { reason: "The pull request merged.", status: "done" };
3985
+ }
3986
+ if (state.state === "closed") {
3987
+ return {
3988
+ reason: "The pull request closed without merging.",
3989
+ status: "dismissed"
3990
+ };
3991
+ }
3992
+ return {
3993
+ reason: "The pull request is no longer ready to merge.",
3994
+ status: "dismissed"
3995
+ };
3996
+ }
3997
+ async function syncOne(args, target) {
3998
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
3999
+ numbers: [target.number],
4000
+ repositoryFullName: target.repositoryFullName
4001
+ })).get(target.number);
4002
+ if (!opener?.conversationId) return;
4003
+ const items = args.reviewItems.forConversation(opener.conversationId);
4004
+ const name = `${target.repositoryFullName}#${target.number}`;
4005
+ const dedupeKey = `pull-request-ready:${name.toLowerCase()}`;
4006
+ const claim = await claimGitHubPullRequestReadySync(args.db, target, {
4007
+ now: /* @__PURE__ */ new Date(),
4008
+ staleMs: READY_SYNC_STALE_MS
4009
+ });
4010
+ if (!claim) return;
4011
+ const { id } = claim;
4012
+ let saved = claim.ready;
4013
+ let requests = claim.requests;
4014
+ let failure;
4015
+ while (requests !== void 0) {
4016
+ try {
4017
+ const state = await loadPullRequestMergeState(args.env, target);
4018
+ const open = state.state === "open" && !state.draft;
4019
+ const ready = open && state.mergeableState === "clean" && state.approved;
4020
+ if ((!open || state.mergeableState) && ready !== saved) {
4021
+ if (ready) {
4022
+ await items.upsert({
4023
+ assigneeIdentityIds: [opener.identityId],
4024
+ body: `**${state.title}** is approved, and GitHub says that it can merge. Merge it, or say why not: ${state.url}`,
4025
+ dedupeKey,
4026
+ subject: { id: state.url, title: name, url: state.url },
4027
+ title: `Ready to merge: ${name}`
4028
+ });
4029
+ } else {
4030
+ await items.close({ dedupeKey, ...closeReason(state) });
4031
+ }
4032
+ await setGitHubPullRequestReadyToMerge(args.db, { ...target, ready });
4033
+ saved = ready;
4034
+ }
4035
+ } catch (error) {
4036
+ failure ??= error;
4037
+ }
4038
+ requests = await releaseGitHubPullRequestReadySync(args.db, target, {
4039
+ id,
4040
+ requests
4041
+ });
4042
+ }
4043
+ if (failure !== void 0) throw failure;
4044
+ }
4045
+ async function syncGitHubPullRequestReadyNotices(args) {
4046
+ for (const target of args.targets) {
4047
+ try {
4048
+ await syncOne(args, target);
4049
+ } catch (error) {
4050
+ args.log?.error("GitHub pull request ready notice failed", {
4051
+ deliveryId: args.deliveryId,
4052
+ errorType: error instanceof Error ? error.name : "UnknownError",
4053
+ number: target.number,
4054
+ repository: target.repositoryFullName
4055
+ });
4056
+ }
4057
+ }
4058
+ }
4059
+
4060
+ // src/webhooks/pull-request-match-data.ts
4061
+ import { z as z21 } from "zod";
3676
4062
  var LOOKUPS_BY_MATCH_KEY = {
3677
4063
  authors: ["authors"],
3678
4064
  openerEmail: ["opener"],
@@ -3680,16 +4066,16 @@ var LOOKUPS_BY_MATCH_KEY = {
3680
4066
  openerUsername: ["opener"]
3681
4067
  };
3682
4068
  var ALL_LOOKUPS = ["authors", "opener", "openerRole"];
3683
- var lookupDataSchema = z19.object({
3684
- authors: z19.array(z19.string().min(1)).min(1).optional(),
3685
- openerRole: z19.string().min(1).optional(),
3686
- openerUsername: z19.string().min(1).optional()
4069
+ var lookupDataSchema = z21.object({
4070
+ authors: z21.array(z21.string().min(1)).min(1).optional(),
4071
+ openerRole: z21.string().min(1).optional(),
4072
+ openerUsername: z21.string().min(1).optional()
3687
4073
  }).strict();
3688
4074
  function lookupData(input) {
3689
4075
  return lookupDataSchema.parse(definedValues(input));
3690
4076
  }
3691
- var webhookSchema = z19.object({
3692
- repository: z19.object({ full_name: z19.string().min(1) })
4077
+ var webhookSchema = z21.object({
4078
+ repository: z21.object({ full_name: z21.string().min(1) })
3693
4079
  });
3694
4080
  function pullRequestNumbers(events) {
3695
4081
  const numbers = /* @__PURE__ */ new Map();
@@ -3719,7 +4105,9 @@ async function withJuniorOpeners(context, events) {
3719
4105
  repositoryFullName: context.repositoryFullName
3720
4106
  });
3721
4107
  const logins = /* @__PURE__ */ new Map();
3722
- for (const identityId of new Set(openers.values())) {
4108
+ for (const identityId of new Set(
4109
+ [...openers.values()].map((opener) => opener.identityId)
4110
+ )) {
3723
4111
  try {
3724
4112
  logins.set(identityId, await context.loadGitHubLogin?.(identityId));
3725
4113
  } catch (error) {
@@ -3729,7 +4117,7 @@ async function withJuniorOpeners(context, events) {
3729
4117
  return events.map((event) => {
3730
4118
  const number = botNumber(event);
3731
4119
  if (number === void 0) return event;
3732
- const identityId = openers.get(number);
4120
+ const identityId = openers.get(number)?.identityId;
3733
4121
  const login = identityId ? logins.get(identityId) : void 0;
3734
4122
  const {
3735
4123
  openerEmail: _email,
@@ -3830,7 +4218,7 @@ async function withGitHubPullRequestMatchData(args) {
3830
4218
  }
3831
4219
 
3832
4220
  // src/webhooks/pull-request-people.ts
3833
- import { z as z20 } from "zod";
4221
+ import { z as z22 } from "zod";
3834
4222
  var PEOPLE_EVENTS = /* @__PURE__ */ new Set([
3835
4223
  "pull_request.review.approved",
3836
4224
  "pull_request.merged"
@@ -3840,18 +4228,18 @@ var PAGE_SIZE = 100;
3840
4228
  var MAX_PAGES = 3;
3841
4229
  var CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
3842
4230
  var GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
3843
- var webhookSchema2 = z20.object({
3844
- pull_request: z20.object({
3845
- assignees: z20.array(z20.object({ login: z20.string().min(1) })).nullish(),
3846
- number: z20.number(),
3847
- user: z20.object({ login: z20.string().min(1) }).nullish()
4231
+ var webhookSchema2 = z22.object({
4232
+ pull_request: z22.object({
4233
+ assignees: z22.array(z22.object({ login: z22.string().min(1) })).nullish(),
4234
+ number: z22.number(),
4235
+ user: z22.object({ login: z22.string().min(1) }).nullish()
3848
4236
  }),
3849
- repository: z20.object({ full_name: z20.string().min(1) })
4237
+ repository: z22.object({ full_name: z22.string().min(1) })
3850
4238
  });
3851
- var commitPageSchema = z20.array(
3852
- z20.object({
3853
- author: z20.object({ login: z20.string().min(1) }).nullish(),
3854
- commit: z20.object({ message: z20.string() })
4239
+ var commitPageSchema = z22.array(
4240
+ z22.object({
4241
+ author: z22.object({ login: z22.string().min(1) }).nullish(),
4242
+ commit: z22.object({ message: z22.string() })
3855
4243
  })
3856
4244
  );
3857
4245
  function shareCommitPages(load) {
@@ -3996,10 +4384,10 @@ function webhookInstallationId(body) {
3996
4384
  }
3997
4385
  return parseInstallationId(installation.id);
3998
4386
  }
3999
- var feedbackTargetSchema = z21.object({
4000
- commentId: z21.number(),
4001
- commentKind: z21.enum(["conversation", "review"]),
4002
- repo: z21.string().min(1)
4387
+ var feedbackTargetSchema = z23.object({
4388
+ commentId: z23.number(),
4389
+ commentKind: z23.enum(["conversation", "review"]),
4390
+ repo: z23.string().min(1)
4003
4391
  });
4004
4392
  function pullRequestFeedbackTarget(events) {
4005
4393
  const event = events.find(
@@ -4215,6 +4603,18 @@ function createGitHubWebhookRoute(args) {
4215
4603
  objectType: event.eventType.startsWith("pull_request.") ? "code_change" : event.eventType.startsWith("issue.") ? "task" : event.eventType.startsWith("deployment.") ? "deployment" : "item"
4216
4604
  });
4217
4605
  }
4606
+ await syncGitHubPullRequestReadyNotices({
4607
+ db: args.db,
4608
+ deliveryId,
4609
+ env: {
4610
+ appIdEnv: args.appIdEnv,
4611
+ installationIdEnv: args.installationIdEnv,
4612
+ privateKeyEnv: args.privateKeyEnv
4613
+ },
4614
+ log: args.log,
4615
+ reviewItems: args.reviewItems,
4616
+ targets: pullRequestReadyTargets(eventName, body)
4617
+ });
4218
4618
  if (!pullRequestOutcome && !issueOutcome && !recordedIssueConversations && !recordedPullRequestConversations && !recordedPullRequestLinkedIssues && events.length === 0) {
4219
4619
  return new Response("Ignored", { status: 202 });
4220
4620
  }
@@ -4242,98 +4642,19 @@ function gitHubEventDeclarations(pullRequestGuidance) {
4242
4642
  return declarations;
4243
4643
  }
4244
4644
 
4245
- // src/webhooks/installation-requests.ts
4246
- import { z as z22 } from "zod";
4247
- function splitRepository(fullName, label) {
4248
- const [owner, name, ...extra] = fullName.split("/");
4249
- if (!owner || !name || extra.length > 0) {
4250
- throw new Error(`GitHub ${label} received an invalid repository name`);
4251
- }
4252
- return { owner, name };
4253
- }
4254
- async function loadPullRequestCommitPages(env, pullRequest) {
4255
- const { owner, name } = splitRepository(
4256
- pullRequest.repositoryFullName,
4257
- "pull request commits"
4258
- );
4259
- const token = await issueInstallationToken({
4260
- ...env,
4261
- permissions: { pull_requests: "read" },
4262
- repositories: [name]
4263
- });
4264
- return async (page, perPage) => await githubRequest(
4265
- "https://api.github.com",
4266
- `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}/commits?per_page=${perPage}&page=${page}`,
4267
- { token: token.token }
4268
- );
4269
- }
4270
- async function markPullRequestFeedbackReviewing(env, target) {
4271
- const { owner, name } = splitRepository(target.repo, "pull request feedback");
4272
- const token = await issueInstallationToken({
4273
- ...env,
4274
- repositories: [name]
4275
- });
4276
- await githubRequest(
4277
- "https://api.github.com",
4278
- pullRequestCommentReactionsPath({
4279
- owner,
4280
- name,
4281
- commentKind: target.commentKind,
4282
- commentId: target.commentId
4283
- }),
4284
- {
4285
- body: { content: pullRequestFeedbackReactionContent("reviewing") },
4286
- method: "POST",
4287
- token: token.token
4288
- }
4289
- );
4290
- }
4291
- var repositoryPermissionSchema = z22.object({
4292
- permission: z22.string().min(1),
4293
- role_name: z22.string().optional()
4294
- });
4295
- var REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1e3;
4296
- async function loadRepositoryRole(env, cache, target) {
4297
- const { owner, name } = splitRepository(
4298
- target.repositoryFullName,
4299
- "repository role"
4300
- );
4301
- return await cache.getOrLoad(
4302
- `repository-role:${owner}/${name}:${target.login}`.toLowerCase(),
4303
- async () => {
4304
- const token = await issueInstallationToken({
4305
- ...env,
4306
- permissions: { metadata: "read" },
4307
- repositories: [name]
4308
- });
4309
- const response = repositoryPermissionSchema.parse(
4310
- await githubRequest(
4311
- "https://api.github.com",
4312
- `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/collaborators/${encodeURIComponent(target.login)}/permission`,
4313
- { token: token.token }
4314
- )
4315
- );
4316
- return {
4317
- value: response.role_name?.trim() || response.permission,
4318
- ttlMs: REPOSITORY_ROLE_TTL_MS
4319
- };
4320
- }
4321
- );
4322
- }
4323
-
4324
4645
  // src/pull-request-outcomes/commit-composition.ts
4325
- import { z as z23 } from "zod";
4326
- var canonicalCommitSchema = z23.object({
4327
- authorEmail: z23.string().nullable(),
4328
- authorLogin: z23.string().nullable()
4646
+ import { z as z24 } from "zod";
4647
+ var canonicalCommitSchema = z24.object({
4648
+ authorEmail: z24.string().nullable(),
4649
+ authorLogin: z24.string().nullable()
4329
4650
  }).strict();
4330
- var providerCommitSchema = z23.object({
4331
- author: z23.object({ login: z23.string() }).passthrough().nullable(),
4332
- commit: z23.object({
4333
- author: z23.object({ email: z23.string() }).passthrough().nullable()
4651
+ var providerCommitSchema = z24.object({
4652
+ author: z24.object({ login: z24.string() }).passthrough().nullable(),
4653
+ commit: z24.object({
4654
+ author: z24.object({ email: z24.string() }).passthrough().nullable()
4334
4655
  }).passthrough()
4335
4656
  }).passthrough();
4336
- var commitPageSchema2 = z23.array(providerCommitSchema).transform(
4657
+ var commitPageSchema2 = z24.array(providerCommitSchema).transform(
4337
4658
  (commits) => commits.map(
4338
4659
  (commit) => canonicalCommitSchema.parse({
4339
4660
  authorEmail: commit.commit.author?.email ?? null,
@@ -5830,6 +6151,7 @@ function githubPlugin(options = {}) {
5830
6151
  markFeedbackReviewing: async (target) => await markPullRequestFeedbackReviewing(installationEnv, target),
5831
6152
  privateKeyEnv,
5832
6153
  events: ctx.events,
6154
+ reviewItems: ctx.reviewItems,
5833
6155
  webhookSecret: () => readEnv("GITHUB_WEBHOOK_SECRET")
5834
6156
  })
5835
6157
  ];