@sentry/junior-github 0.295.0 → 0.297.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
@@ -38,6 +38,8 @@ import {
38
38
  gitHubPullRequestEventGuidance,
39
39
  gitHubPullRequestResource,
40
40
  gitHubPullRequestSubscribable,
41
+ gitHubPullRequestSubscription,
42
+ gitHubPullRequestTerminalEvents,
41
43
  gitHubReleaseSourceSubscribable,
42
44
  gitHubRepoDataSchema,
43
45
  gitHubRepositorySubscribable,
@@ -59,7 +61,7 @@ import {
59
61
  readGrantPermissions,
60
62
  requireEnv,
61
63
  resolveUserAccount
62
- } from "./chunk-D74ZUIJR.js";
64
+ } from "./chunk-OK6BNAGC.js";
63
65
 
64
66
  // src/tool-support/attribution.ts
65
67
  import * as z from "zod";
@@ -682,6 +684,9 @@ function githubObjectFacts(type, response) {
682
684
  }
683
685
 
684
686
  // src/annotations.ts
687
+ import {
688
+ objectFactsMatchType
689
+ } from "@sentry/junior-plugin-api";
685
690
  function githubObjectType(annotation) {
686
691
  if (annotation.objectType === "task" || annotation.objectType === "code_change") {
687
692
  return annotation.objectType;
@@ -738,10 +743,13 @@ async function updateGitHubAnnotation(store, input) {
738
743
  plugin: _plugin,
739
744
  createdAt: _createdAt,
740
745
  updatedAt: _updatedAt,
746
+ facts,
741
747
  ...annotation
742
748
  } = current;
743
749
  await store.upsert({
744
750
  ...annotation,
751
+ // Facts saved for another object type are not valid for this one.
752
+ ...facts && objectFactsMatchType(facts, input.objectType) ? { facts } : void 0,
745
753
  objectType: input.objectType,
746
754
  status: input.status
747
755
  });
@@ -756,6 +764,25 @@ async function updateGitHubAnnotation(store, input) {
756
764
  status: input.status
757
765
  });
758
766
  }
767
+ async function updateGitHubAnnotations(args) {
768
+ const results = await Promise.allSettled(
769
+ args.conversationIds.map(
770
+ (conversationId) => updateGitHubAnnotation(
771
+ args.annotations.forConversation(conversationId),
772
+ args.update
773
+ )
774
+ )
775
+ );
776
+ for (const result of results) {
777
+ if (result.status === "fulfilled") continue;
778
+ args.log?.error("GitHub conversation annotation update failed", {
779
+ errorType: result.reason instanceof Error ? result.reason.name : "UnknownError",
780
+ number: args.update.number,
781
+ objectType: args.update.objectType,
782
+ repository: args.update.repo
783
+ });
784
+ }
785
+ }
759
786
 
760
787
  // src/tools/create-issue.ts
761
788
  import {
@@ -854,11 +881,11 @@ function githubLinkedIssues(body, repositoryFullName) {
854
881
  if (!body) return [];
855
882
  const references = /* @__PURE__ */ new Map();
856
883
  const add = (linkedRepository, rawNumber) => {
857
- const number27 = Number.parseInt(rawNumber, 10);
858
- if (!Number.isInteger(number27) || number27 <= 0) return;
884
+ const number29 = Number.parseInt(rawNumber, 10);
885
+ if (!Number.isInteger(number29) || number29 <= 0) return;
859
886
  const normalizedRepository = linkedRepository.toLowerCase();
860
- references.set(`${normalizedRepository}#${number27}`, {
861
- number: number27,
887
+ references.set(`${normalizedRepository}#${number29}`, {
888
+ number: number29,
862
889
  repositoryFullName: linkedRepository
863
890
  });
864
891
  };
@@ -1122,7 +1149,7 @@ function createGitHubIssueTool(ctx) {
1122
1149
  conversationId,
1123
1150
  parsedInput,
1124
1151
  ctx,
1125
- ctx.slack?.conversationLink?.url
1152
+ ctx.conversationLink?.url
1126
1153
  );
1127
1154
  const pendingState = {
1128
1155
  status: "pending",
@@ -1642,6 +1669,7 @@ var GITHUB_STACKS_API_VERSION = "2026-03-10";
1642
1669
  var stackTargetSchema = z10.object({
1643
1670
  number: z10.number().int().positive(),
1644
1671
  head: z10.object({
1672
+ ref: z10.string().min(1),
1645
1673
  repo: z10.object({ full_name: z10.string().min(1) }).nullable()
1646
1674
  }),
1647
1675
  base: z10.object({
@@ -1664,7 +1692,8 @@ var stackSchema = z10.object({
1664
1692
  });
1665
1693
  async function stackGitHubPullRequest(ctx, target) {
1666
1694
  const repo = target.base.repo.full_name;
1667
- if (target.base.ref === target.base.repo.default_branch || target.head.repo?.full_name !== repo) {
1695
+ const trunk = target.base.repo.default_branch;
1696
+ if (target.base.ref === trunk || target.head.ref === trunk || target.head.repo?.full_name !== repo) {
1668
1697
  return void 0;
1669
1698
  }
1670
1699
  const [owner, name] = repo.split("/");
@@ -1694,7 +1723,7 @@ async function stackGitHubPullRequest(ctx, target) {
1694
1723
  try {
1695
1724
  const chain = [target.number];
1696
1725
  let branch = target.base.ref;
1697
- for (let depth = 0; depth < MAX_STACK_DEPTH; depth += 1) {
1726
+ for (let depth = 0; depth < MAX_STACK_DEPTH && branch !== trunk; depth += 1) {
1698
1727
  const parents = await github(
1699
1728
  "github.pull.list",
1700
1729
  `${api}/pulls?state=open&per_page=2&head=${encodeURIComponent(`${owner}:${branch}`)}`,
@@ -1703,6 +1732,7 @@ async function stackGitHubPullRequest(ctx, target) {
1703
1732
  if (!parents) return void 0;
1704
1733
  if (parents.length !== 1) break;
1705
1734
  const parent = parents[0];
1735
+ if (chain.includes(parent.number)) return void 0;
1706
1736
  const stacks = await github(
1707
1737
  "github.stack.read",
1708
1738
  `${api}/stacks?pull_request=${parent.number}`,
@@ -2082,7 +2112,7 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2082
2112
  parsedInput,
2083
2113
  ctx,
2084
2114
  requester,
2085
- ctx.slack?.conversationLink?.url
2115
+ ctx.conversationLink?.url
2086
2116
  );
2087
2117
  const pendingState = {
2088
2118
  status: "pending",
@@ -2636,7 +2666,7 @@ function createGitHubUpdateIssueTool(ctx) {
2636
2666
  currentBody
2637
2667
  ),
2638
2668
  nonEmptyString4(ctx.conversationId, "conversationId"),
2639
- ctx.slack?.conversationLink?.url
2669
+ ctx.conversationLink?.url
2640
2670
  )
2641
2671
  } : void 0,
2642
2672
  ...update.state !== void 0 ? { state: update.state } : void 0
@@ -2826,7 +2856,7 @@ function createGitHubUpdatePullRequestTool(ctx) {
2826
2856
  currentBody
2827
2857
  ),
2828
2858
  nonEmptyString5(ctx.conversationId, "conversationId"),
2829
- ctx.slack?.conversationLink?.url
2859
+ ctx.conversationLink?.url
2830
2860
  )
2831
2861
  } : void 0,
2832
2862
  ...update.base !== void 0 ? { base: update.base } : void 0,
@@ -2988,17 +3018,17 @@ async function commentParentNumber(egress, input) {
2988
3018
  pull_request_url: z19.string().optional()
2989
3019
  }).safeParse(commentPayload);
2990
3020
  const parentUrl = comment.success ? input.commentKind === "conversation" ? comment.data.issue_url : comment.data.pull_request_url : void 0;
2991
- const number27 = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
2992
- if (!number27) {
3021
+ const number29 = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
3022
+ if (!number29) {
2993
3023
  throw new Error("GitHub comment did not name its issue or pull request.");
2994
3024
  }
2995
- return number27;
3025
+ return number29;
2996
3026
  }
2997
3027
  async function assertBotAuthoredPullRequest(egress, input) {
2998
- const { number: number27 } = input;
3028
+ const { number: number29 } = input;
2999
3029
  const pullResponse = await githubApi(egress, {
3000
3030
  operation: "github.pull.get",
3001
- path: `${repoPath(input)}/pulls/${number27}`
3031
+ path: `${repoPath(input)}/pulls/${number29}`
3002
3032
  });
3003
3033
  const pullPayload = pullResponse.body;
3004
3034
  if (!pullResponse.ok && pullResponse.status !== 404) {
@@ -3504,7 +3534,7 @@ function createGitHubTools(ctx, botEmail, pullRequestSubscription) {
3504
3534
 
3505
3535
  // src/webhooks/handler.ts
3506
3536
  import { createHmac, timingSafeEqual } from "crypto";
3507
- import * as z34 from "zod";
3537
+ import * as z35 from "zod";
3508
3538
 
3509
3539
  // src/issue-outcomes/store.ts
3510
3540
  import { and as and2, eq as eq2, lte, sql as sql2 } from "drizzle-orm";
@@ -3586,7 +3616,7 @@ async function recordGitHubIssueConversations(db, input) {
3586
3616
  }
3587
3617
 
3588
3618
  // src/pull-request-outcomes/store.ts
3589
- import { and as and3, eq as eq3, lte as lte2, ne, sql as sql3 } from "drizzle-orm";
3619
+ import { and as and3, eq as eq3, lt as lt2, lte as lte2, ne, sql as sql3 } from "drizzle-orm";
3590
3620
  import * as z23 from "zod";
3591
3621
  var githubPullRequestOutcomeInputSchema = z23.object({
3592
3622
  candidateOwned: z23.boolean(),
@@ -3723,6 +3753,10 @@ async function listGitHubFinishedWork(db, conversationIds) {
3723
3753
  })
3724
3754
  );
3725
3755
  }
3756
+ async function listGitHubStaleOpenPullRequests(db, before) {
3757
+ const t = juniorGitHubPullRequests;
3758
+ return await db.select({ number: t.number, repositoryFullName: t.repositoryFullName }).from(t).where(and3(eq3(t.state, "open"), lt2(t.updatedAt, before))).orderBy(t.updatedAt);
3759
+ }
3726
3760
  async function listGitHubAssignedWork(db, conversationIds) {
3727
3761
  if (conversationIds.length === 0) return [];
3728
3762
  const values = sql3.join(
@@ -3817,6 +3851,49 @@ async function releaseGitHubPullRequestReadySync(db, target, claim) {
3817
3851
  return row?.requests;
3818
3852
  }
3819
3853
 
3854
+ // src/pull-request-outcomes/apply.ts
3855
+ function githubCodeChange(outcome, conversationIds) {
3856
+ return {
3857
+ closedAt: outcome.closedAt,
3858
+ conversationIds,
3859
+ mergedAt: outcome.mergedAt,
3860
+ number: outcome.number,
3861
+ openedAt: outcome.openedAt,
3862
+ providerId: outcome.pullRequestId,
3863
+ repository: {
3864
+ name: outcome.repositoryFullName,
3865
+ providerId: outcome.repositoryId,
3866
+ url: `https://github.com/${outcome.repositoryFullName}`
3867
+ },
3868
+ state: outcome.state === "closed_unmerged" ? "closed" : outcome.state,
3869
+ title: outcome.title,
3870
+ updatedAt: outcome.updatedAt,
3871
+ url: `https://github.com/${outcome.repositoryFullName}/pull/${outcome.number}`
3872
+ };
3873
+ }
3874
+ async function applyGitHubPullRequestOutcome(args) {
3875
+ const { outcome } = args;
3876
+ const recorded = await recordGitHubPullRequestOutcome(args.db, outcome);
3877
+ if (!recorded.applied) return recorded;
3878
+ await args.codeChanges.record(
3879
+ githubCodeChange(outcome, recorded.conversationIds)
3880
+ );
3881
+ if (outcome.state !== "open") {
3882
+ await updateGitHubAnnotations({
3883
+ annotations: args.annotations,
3884
+ conversationIds: recorded.conversationIds,
3885
+ log: args.log,
3886
+ update: {
3887
+ repo: outcome.repositoryFullName,
3888
+ number: outcome.number,
3889
+ objectType: "code_change",
3890
+ status: outcome.state === "merged" ? "merged" : "closed"
3891
+ }
3892
+ });
3893
+ }
3894
+ return recorded;
3895
+ }
3896
+
3820
3897
  // src/webhooks/issue-outcome.ts
3821
3898
  import * as z24 from "zod";
3822
3899
  var canonicalIssueOutcomeSchema = z24.object({
@@ -4071,11 +4148,9 @@ function normalizeGitHubPullRequestOutcome(args) {
4071
4148
  );
4072
4149
  const candidateOwned = hasOwnershipMarker && (parsed.action === "opened" || parsed.action === "closed");
4073
4150
  const state = parsed.action !== "closed" ? "open" : pullRequest.merged ? "merged" : "closed_unmerged";
4074
- const closedAt = timestamp3(pullRequest.closed_at);
4075
- const mergedAt = timestamp3(pullRequest.merged_at);
4076
- if (parsed.action === "closed" && (pullRequest.merged ? !mergedAt : !closedAt)) {
4077
- throw new Error("GitHub pull request terminal timestamp is invalid");
4078
- }
4151
+ const closed = parsed.action === "closed";
4152
+ const closedAt = timestamp3(pullRequest.closed_at) ?? (closed ? updatedAt : void 0);
4153
+ const mergedAt = timestamp3(pullRequest.merged_at) ?? (closed && pullRequest.merged ? updatedAt : void 0);
4079
4154
  return {
4080
4155
  candidateOwned,
4081
4156
  closedAt,
@@ -4118,21 +4193,88 @@ function normalizeGitHubPullRequestLinkedIssues(args) {
4118
4193
  } : void 0;
4119
4194
  }
4120
4195
 
4121
- // src/webhooks/merge-conflict.ts
4196
+ // src/webhooks/pull-request-activity.ts
4122
4197
  import * as z26 from "zod";
4198
+ var timestampSchema = z26.iso.datetime({ offset: true });
4199
+ var numberSchema = z26.number().int().positive();
4200
+ var repositorySchema2 = z26.object({ id: numberSchema });
4201
+ var senderSchema = z26.object({ type: z26.string() });
4202
+ var activitySchemas = {
4203
+ issue_comment: z26.object({
4204
+ action: z26.literal("created"),
4205
+ comment: z26.object({ created_at: timestampSchema }),
4206
+ // Only comments on a pull request carry `issue.pull_request`.
4207
+ issue: z26.object({ number: numberSchema, pull_request: z26.object({}) }),
4208
+ repository: repositorySchema2,
4209
+ sender: senderSchema
4210
+ }).transform((event) => ({
4211
+ at: new Date(event.comment.created_at),
4212
+ number: event.issue.number,
4213
+ repositoryProviderId: String(event.repository.id),
4214
+ senderType: event.sender.type
4215
+ })),
4216
+ pull_request: z26.object({
4217
+ action: z26.literal("synchronize"),
4218
+ pull_request: z26.object({
4219
+ number: numberSchema,
4220
+ updated_at: timestampSchema
4221
+ }),
4222
+ repository: repositorySchema2,
4223
+ sender: senderSchema
4224
+ }).transform((event) => ({
4225
+ at: new Date(event.pull_request.updated_at),
4226
+ number: event.pull_request.number,
4227
+ repositoryProviderId: String(event.repository.id),
4228
+ senderType: event.sender.type
4229
+ })),
4230
+ pull_request_review: z26.object({
4231
+ action: z26.literal("submitted"),
4232
+ pull_request: z26.object({ number: numberSchema }),
4233
+ repository: repositorySchema2,
4234
+ review: z26.object({ submitted_at: timestampSchema }),
4235
+ sender: senderSchema
4236
+ }).transform((event) => ({
4237
+ at: new Date(event.review.submitted_at),
4238
+ number: event.pull_request.number,
4239
+ repositoryProviderId: String(event.repository.id),
4240
+ senderType: event.sender.type
4241
+ })),
4242
+ pull_request_review_comment: z26.object({
4243
+ action: z26.literal("created"),
4244
+ comment: z26.object({ created_at: timestampSchema }),
4245
+ pull_request: z26.object({ number: numberSchema }),
4246
+ repository: repositorySchema2,
4247
+ sender: senderSchema
4248
+ }).transform((event) => ({
4249
+ at: new Date(event.comment.created_at),
4250
+ number: event.pull_request.number,
4251
+ repositoryProviderId: String(event.repository.id),
4252
+ senderType: event.sender.type
4253
+ }))
4254
+ };
4255
+ function normalizeGitHubPullRequestActivity(input) {
4256
+ const schema = Object.hasOwn(activitySchemas, input.eventName) ? activitySchemas[input.eventName] : void 0;
4257
+ const parsed = schema?.safeParse(input.body);
4258
+ if (!parsed?.success) return void 0;
4259
+ const { senderType, ...activity } = parsed.data;
4260
+ return senderType === "Bot" ? void 0 : activity;
4261
+ }
4262
+
4263
+ // src/webhooks/merge-conflict.ts
4264
+ import * as z27 from "zod";
4123
4265
  var EVENT_TYPE = "pull_request.merge_conflict";
4124
4266
  var CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set([
4125
4267
  "pull_request.closed_unmerged",
4126
4268
  "pull_request.merged"
4127
4269
  ]);
4128
- var pullRequestSchema3 = z26.object({
4129
- base: z26.object({ ref: z26.string().min(1) }),
4130
- number: z26.number().int().positive().optional(),
4131
- head: z26.object({ sha: z26.string().min(1) }),
4132
- html_url: z26.string().min(1).optional(),
4133
- mergeable: z26.boolean().nullable().optional(),
4134
- mergeable_state: z26.string().optional(),
4135
- state: z26.string()
4270
+ var pullRequestSchema3 = z27.object({
4271
+ base: z27.object({ ref: z27.string().min(1) }),
4272
+ number: z27.number().int().positive().optional(),
4273
+ head: z27.object({ sha: z27.string().min(1) }),
4274
+ html_url: z27.string().min(1).optional(),
4275
+ mergeable: z27.boolean().nullable().optional(),
4276
+ mergeable_state: z27.string().optional(),
4277
+ state: z27.string()
4136
4278
  });
4137
4279
  function gitHubMergeConflictEvents(input) {
4138
4280
  const { conflict } = input;
@@ -4166,7 +4308,7 @@ function pullRequestRefs(events) {
4166
4308
  return [...refs.values()];
4167
4309
  }
4168
4310
  function deliveredPullRequest(payload, ref) {
4169
- const parsed = z26.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
4311
+ const parsed = z27.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
4170
4312
  const pullRequest = parsed.success ? parsed.data.pull_request : void 0;
4171
4313
  return pullRequest?.number === ref.number && typeof pullRequest.mergeable === "boolean" ? pullRequest : void 0;
4172
4314
  }
@@ -4204,16 +4346,16 @@ async function loadGitHubMergeConflictEvents(args) {
4204
4346
  }
4205
4347
 
4206
4348
  // src/merge-conflict-checks/webhooks.ts
4207
- import * as z28 from "zod";
4349
+ import * as z29 from "zod";
4208
4350
 
4209
4351
  // src/merge-conflict-checks/store.ts
4210
4352
  import { and as and4, eq as eq4 } from "drizzle-orm";
4211
- import * as z27 from "zod";
4353
+ import * as z28 from "zod";
4212
4354
  var CHECK_TTL_MS = 30 * 6e4;
4213
- var repeatSchema = z27.object({
4355
+ var repeatSchema = z28.object({
4214
4356
  /** Checks since the last push that ended with an unknown answer. */
4215
- attempts: z27.number().int().positive(),
4216
- dueAtMs: z27.number()
4357
+ attempts: z28.number().int().positive(),
4358
+ dueAtMs: z28.number()
4217
4359
  });
4218
4360
  function pushKey(repositoryFullName) {
4219
4361
  return `merge-conflict-check:push:${repositoryFullName}`;
@@ -4281,12 +4423,12 @@ async function settleGitHubConflictCheck(state, check, retryAtMs) {
4281
4423
 
4282
4424
  // src/merge-conflict-checks/webhooks.ts
4283
4425
  var CONFLICT_CHECK_DELAY_MS = 2 * 6e4;
4284
- var pushSchema = z28.object({
4285
- deleted: z28.boolean().optional(),
4286
- ref: z28.string(),
4287
- repository: z28.object({
4288
- default_branch: z28.string().min(1),
4289
- full_name: z28.string().min(1)
4426
+ var pushSchema = z29.object({
4427
+ deleted: z29.boolean().optional(),
4428
+ ref: z29.string(),
4429
+ repository: z29.object({
4430
+ default_branch: z29.string().min(1),
4431
+ full_name: z29.string().min(1)
4290
4432
  })
4291
4433
  });
4292
4434
  async function scheduleGitHubPushConflictCheck(args) {
@@ -4303,10 +4445,10 @@ async function scheduleGitHubPushConflictCheck(args) {
4303
4445
  }
4304
4446
 
4305
4447
  // src/webhooks/pull-request-ready.ts
4306
- import * as z30 from "zod";
4448
+ import * as z31 from "zod";
4307
4449
 
4308
4450
  // src/webhooks/installation-requests.ts
4309
- import * as z29 from "zod";
4451
+ import * as z30 from "zod";
4310
4452
  function splitRepository(fullName, label) {
4311
4453
  const [owner, name, ...extra] = fullName.split("/");
4312
4454
  if (!owner || !name || extra.length > 0) {
@@ -4346,6 +4488,35 @@ async function loadPullRequest(env, pullRequest) {
4346
4488
  { token: token.token }
4347
4489
  );
4348
4490
  }
4491
+ async function loadPullRequestLifecycles(env, input) {
4492
+ const { owner, name } = splitRepository(
4493
+ input.repositoryFullName,
4494
+ "pull request lifecycle"
4495
+ );
4496
+ const token = await issueInstallationToken({
4497
+ ...env,
4498
+ permissions: { pull_requests: "read" },
4499
+ repositories: [name]
4500
+ });
4501
+ const variables = input.numbers.map((_, index2) => `$n${index2}: Int!`);
4502
+ const pullRequests = input.numbers.map(
4503
+ (_, index2) => `pr${index2}: pullRequest(number: $n${index2}) { ...lifecycle }`
4504
+ );
4505
+ return await githubRequest("https://api.github.com", "/graphql", {
4506
+ body: {
4507
+ query: `query($owner: String!, $name: String!, ${variables.join(", ")}) { repository(owner: $owner, name: $name) { databaseId nameWithOwner ${pullRequests.join(" ")} } } fragment lifecycle on PullRequest { assignees(first: 20) { nodes { login } } author { __typename login } closedAt createdAt databaseId headRefName isDraft merged mergedAt number state title updatedAt }`,
4508
+ variables: {
4509
+ name,
4510
+ owner,
4511
+ ...Object.fromEntries(
4512
+ input.numbers.map((number29, index2) => [`n${index2}`, number29])
4513
+ )
4514
+ }
4515
+ },
4516
+ method: "POST",
4517
+ token: token.token
4518
+ });
4519
+ }
4349
4520
  async function searchOpenPullRequestMergeability(env, input) {
4350
4521
  const { name } = splitRepository(
4351
4522
  input.repositoryFullName,
@@ -4376,7 +4547,7 @@ async function markPullRequestFeedbackReviewing(env, target) {
4376
4547
  });
4377
4548
  const content = pullRequestFeedbackReactionContent("reviewing");
4378
4549
  if (target.commentKind === "review_body") {
4379
- const review = z29.object({ node_id: z29.string().min(1) }).parse(
4550
+ const review = z30.object({ node_id: z30.string().min(1) }).parse(
4380
4551
  await githubRequest(
4381
4552
  "https://api.github.com",
4382
4553
  pullRequestReviewPath({
@@ -4388,7 +4559,7 @@ async function markPullRequestFeedbackReviewing(env, target) {
4388
4559
  { token: token.token }
4389
4560
  )
4390
4561
  );
4391
- const result = z29.object({ errors: z29.array(z29.unknown()).optional() }).parse(
4562
+ const result = z30.object({ errors: z30.array(z30.unknown()).optional() }).parse(
4392
4563
  await githubRequest("https://api.github.com", "/graphql", {
4393
4564
  body: {
4394
4565
  operationName: "AddReviewReaction",
@@ -4424,9 +4595,9 @@ async function markPullRequestFeedbackReviewing(env, target) {
4424
4595
  }
4425
4596
  );
4426
4597
  }
4427
- var repositoryPermissionSchema = z29.object({
4428
- permission: z29.string().min(1),
4429
- role_name: z29.string().optional()
4598
+ var repositoryPermissionSchema = z30.object({
4599
+ permission: z30.string().min(1),
4600
+ role_name: z30.string().optional()
4430
4601
  });
4431
4602
  var REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1e3;
4432
4603
  async function loadRepositoryRole(env, cache, target) {
@@ -4456,19 +4627,19 @@ async function loadRepositoryRole(env, cache, target) {
4456
4627
  }
4457
4628
  );
4458
4629
  }
4459
- var pullRequestSchema4 = z29.object({
4460
- auto_merge: z29.object({}).nullable().optional(),
4461
- draft: z29.boolean().optional(),
4462
- html_url: z29.string().url(),
4463
- mergeable_state: z29.string().nullable().optional(),
4464
- merged: z29.boolean(),
4465
- state: z29.enum(["open", "closed"]),
4466
- title: z29.string()
4630
+ var pullRequestSchema4 = z30.object({
4631
+ auto_merge: z30.object({}).nullable().optional(),
4632
+ draft: z30.boolean().optional(),
4633
+ html_url: z30.string().url(),
4634
+ mergeable_state: z30.string().nullable().optional(),
4635
+ merged: z30.boolean(),
4636
+ state: z30.enum(["open", "closed"]),
4637
+ title: z30.string()
4467
4638
  });
4468
- var reviewsSchema = z29.array(
4469
- z29.object({
4470
- state: z29.string(),
4471
- user: z29.object({ login: z29.string() }).nullable()
4639
+ var reviewsSchema = z30.array(
4640
+ z30.object({
4641
+ state: z30.string(),
4642
+ user: z30.object({ login: z30.string() }).nullable()
4472
4643
  })
4473
4644
  );
4474
4645
  async function loadPullRequestMergeState(env, pullRequest) {
@@ -4536,10 +4707,10 @@ var READY_ACTIONS = {
4536
4707
  ]),
4537
4708
  pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
4538
4709
  };
4539
- var pullRequestWebhookSchema = z30.object({
4540
- action: z30.string(),
4541
- pull_request: z30.object({ number: z30.number().int().positive() }),
4542
- repository: z30.object({ full_name: z30.string().min(1) })
4710
+ var pullRequestWebhookSchema = z31.object({
4711
+ action: z31.string(),
4712
+ pull_request: z31.object({ number: z31.number().int().positive() }),
4713
+ repository: z31.object({ full_name: z31.string().min(1) })
4543
4714
  });
4544
4715
  function pullRequestReadyTargets(eventName, body) {
4545
4716
  if (eventName === "check_suite") return checkSuitePullRequests(body);
@@ -4638,32 +4809,32 @@ async function syncGitHubPullRequestReadyNotices(args) {
4638
4809
  }
4639
4810
 
4640
4811
  // src/webhooks/pull-request-review-request.ts
4641
- import * as z31 from "zod";
4642
- var login = z31.object({ login: z31.string().min(1) });
4643
- var pullRequestEventSchema = z31.object({
4644
- action: z31.enum([
4812
+ import * as z32 from "zod";
4813
+ var login = z32.object({ login: z32.string().min(1) });
4814
+ var pullRequestEventSchema = z32.object({
4815
+ action: z32.enum([
4645
4816
  "closed",
4646
4817
  "reopened",
4647
4818
  "review_request_removed",
4648
4819
  "review_requested"
4649
4820
  ]),
4650
- pull_request: z31.object({
4651
- html_url: z31.string().url(),
4652
- merged: z31.boolean().optional(),
4653
- number: z31.number().int().positive(),
4821
+ pull_request: z32.object({
4822
+ html_url: z32.string().url(),
4823
+ merged: z32.boolean().optional(),
4824
+ number: z32.number().int().positive(),
4654
4825
  // The people whose review is still requested. Teams are listed apart.
4655
- requested_reviewers: z31.array(login).optional(),
4656
- title: z31.string()
4826
+ requested_reviewers: z32.array(login).optional(),
4827
+ title: z32.string()
4657
4828
  }),
4658
- repository: z31.object({ full_name: z31.string().min(1) }),
4829
+ repository: z32.object({ full_name: z32.string().min(1) }),
4659
4830
  // A team request has `requested_team` instead.
4660
4831
  requested_reviewer: login.optional()
4661
4832
  });
4662
- var reviewEventSchema = z31.object({
4663
- action: z31.literal("submitted"),
4664
- pull_request: z31.object({ number: z31.number().int().positive() }),
4665
- repository: z31.object({ full_name: z31.string().min(1) }),
4666
- review: z31.object({ user: login })
4833
+ var reviewEventSchema = z32.object({
4834
+ action: z32.literal("submitted"),
4835
+ pull_request: z32.object({ number: z32.number().int().positive() }),
4836
+ repository: z32.object({ full_name: z32.string().min(1) }),
4837
+ review: z32.object({ user: login })
4667
4838
  });
4668
4839
  function reviewRequestChange(eventName, body) {
4669
4840
  if (eventName === "pull_request_review") {
@@ -4744,14 +4915,14 @@ function sameLogin(left, right) {
4744
4915
  async function syncGitHubPullRequestReviewRequest(args) {
4745
4916
  const parsed = reviewRequestChange(args.eventName, args.body);
4746
4917
  if (!parsed) return;
4747
- const { change, number: number27, repository: repository2 } = parsed;
4918
+ const { change, number: number29, repository: repository2 } = parsed;
4748
4919
  try {
4749
4920
  const opener = (await listGitHubPullRequestOpeners(args.db, {
4750
- numbers: [number27],
4921
+ numbers: [number29],
4751
4922
  repositoryFullName: repository2
4752
- })).get(number27);
4923
+ })).get(number29);
4753
4924
  if (!opener?.conversationId) return;
4754
- const name = `${repository2}#${number27}`;
4925
+ const name = `${repository2}#${number29}`;
4755
4926
  const dedupeKey = `pull-request-review-requested:${name.toLowerCase()}`;
4756
4927
  const items = args.reviewItems.forConversation(opener.conversationId);
4757
4928
  const reviewers = change.kind === "requested" ? change.reviewers : change.reviewer === void 0 ? void 0 : [change.reviewer];
@@ -4774,21 +4945,21 @@ async function syncGitHubPullRequestReviewRequest(args) {
4774
4945
  body: `GitHub asks you to review **${change.title}**: ${change.url}`,
4775
4946
  dedupeKey,
4776
4947
  subject: { id: change.url, title: name, url: change.url },
4777
- title: `Review requested \xB7 #${number27}`,
4948
+ title: `Review requested \xB7 #${number29}`,
4778
4949
  waitsOnAssignees: true
4779
4950
  });
4780
4951
  } catch (error) {
4781
4952
  args.log?.error("GitHub pull request review request failed", {
4782
4953
  deliveryId: args.deliveryId,
4783
4954
  errorType: error instanceof Error ? error.name : "UnknownError",
4784
- number: number27,
4955
+ number: number29,
4785
4956
  repository: repository2
4786
4957
  });
4787
4958
  }
4788
4959
  }
4789
4960
 
4790
4961
  // src/webhooks/pull-request-match-data.ts
4791
- import * as z32 from "zod";
4962
+ import * as z33 from "zod";
4792
4963
  var LOOKUPS_BY_MATCH_KEY = {
4793
4964
  authors: ["authors"],
4794
4965
  openerEmail: ["opener"],
@@ -4796,22 +4967,22 @@ var LOOKUPS_BY_MATCH_KEY = {
4796
4967
  openerUsername: ["opener"]
4797
4968
  };
4798
4969
  var ALL_LOOKUPS = ["authors", "opener", "openerRole"];
4799
- var lookupDataSchema = z32.object({
4800
- authors: z32.array(z32.string().min(1)).min(1).optional(),
4801
- openerRole: z32.string().min(1).optional(),
4802
- openerUsername: z32.string().min(1).optional()
4970
+ var lookupDataSchema = z33.object({
4971
+ authors: z33.array(z33.string().min(1)).min(1).optional(),
4972
+ openerRole: z33.string().min(1).optional(),
4973
+ openerUsername: z33.string().min(1).optional()
4803
4974
  }).strict();
4804
4975
  function lookupData(input) {
4805
4976
  return lookupDataSchema.parse(definedValues(input));
4806
4977
  }
4807
- var webhookSchema = z32.object({
4808
- repository: z32.object({ full_name: z32.string().min(1) })
4978
+ var webhookSchema = z33.object({
4979
+ repository: z33.object({ full_name: z33.string().min(1) })
4809
4980
  });
4810
4981
  function pullRequestNumbers(events) {
4811
4982
  const numbers = /* @__PURE__ */ new Map();
4812
4983
  for (const event of events) {
4813
- const number27 = event.data?.pullRequest;
4814
- if (typeof number27 === "number") numbers.set(event.eventKey, number27);
4984
+ const number29 = event.data?.pullRequest;
4985
+ if (typeof number29 === "number") numbers.set(event.eventKey, number29);
4815
4986
  }
4816
4987
  return numbers;
4817
4988
  }
@@ -4825,8 +4996,8 @@ function logFailure(context, lookup, error) {
4825
4996
  }
4826
4997
  async function withJuniorOpeners(context, events) {
4827
4998
  const botNumber = (event) => {
4828
- const number27 = context.numbers.get(event.eventKey);
4829
- return number27 !== void 0 && isBotLogin(event.data?.openerUsername, context.botEmail) ? number27 : void 0;
4999
+ const number29 = context.numbers.get(event.eventKey);
5000
+ return number29 !== void 0 && isBotLogin(event.data?.openerUsername, context.botEmail) ? number29 : void 0;
4830
5001
  };
4831
5002
  const numbers = events.flatMap((event) => botNumber(event) ?? []);
4832
5003
  if (numbers.length === 0) return events;
@@ -4845,9 +5016,9 @@ async function withJuniorOpeners(context, events) {
4845
5016
  }
4846
5017
  }
4847
5018
  return events.map((event) => {
4848
- const number27 = botNumber(event);
4849
- if (number27 === void 0) return event;
4850
- const identityId = openers.get(number27)?.identityId;
5019
+ const number29 = botNumber(event);
5020
+ if (number29 === void 0) return event;
5021
+ const identityId = openers.get(number29)?.identityId;
4851
5022
  const login2 = identityId ? logins.get(identityId) : void 0;
4852
5023
  const {
4853
5024
  openerEmail: _email,
@@ -4869,8 +5040,8 @@ async function withRolesAndAuthors(context, events, lookups) {
4869
5040
  if (!loadRole && !loadAuthors) return events;
4870
5041
  return await Promise.all(
4871
5042
  events.map(async (event) => {
4872
- const number27 = context.numbers.get(event.eventKey);
4873
- if (number27 === void 0) return event;
5043
+ const number29 = context.numbers.get(event.eventKey);
5044
+ if (number29 === void 0) return event;
4874
5045
  const login2 = event.data?.openerUsername;
4875
5046
  if (loadRole && typeof login2 === "string" && !roles.has(login2)) {
4876
5047
  roles.set(
@@ -4880,16 +5051,16 @@ async function withRolesAndAuthors(context, events, lookups) {
4880
5051
  )
4881
5052
  );
4882
5053
  }
4883
- if (loadAuthors && !authors.has(number27)) {
5054
+ if (loadAuthors && !authors.has(number29)) {
4884
5055
  authors.set(
4885
- number27,
4886
- loadAuthors({ number: number27, repositoryFullName }).catch(
5056
+ number29,
5057
+ loadAuthors({ number: number29, repositoryFullName }).catch(
4887
5058
  (error) => logFailure(context, "authors", error)
4888
5059
  )
4889
5060
  );
4890
5061
  }
4891
5062
  const role = loadRole && typeof login2 === "string" ? await roles.get(login2) : void 0;
4892
- const logins = loadAuthors ? await authors.get(number27) : void 0;
5063
+ const logins = loadAuthors ? await authors.get(number29) : void 0;
4893
5064
  if (!role && !logins?.length) return event;
4894
5065
  return {
4895
5066
  ...event,
@@ -4946,7 +5117,7 @@ async function withGitHubPullRequestMatchData(args) {
4946
5117
  }
4947
5118
 
4948
5119
  // src/webhooks/pull-request-people.ts
4949
- import * as z33 from "zod";
5120
+ import * as z34 from "zod";
4950
5121
  var PEOPLE_EVENTS = /* @__PURE__ */ new Set([
4951
5122
  "pull_request.review.approved",
4952
5123
  "pull_request.merged"
@@ -4956,18 +5127,18 @@ var PAGE_SIZE = 100;
4956
5127
  var MAX_PAGES = 3;
4957
5128
  var CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
4958
5129
  var GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
4959
- var webhookSchema2 = z33.object({
4960
- pull_request: z33.object({
4961
- assignees: z33.array(z33.object({ login: z33.string().min(1) })).nullish(),
4962
- number: z33.number(),
4963
- user: z33.object({ login: z33.string().min(1) }).nullish()
5130
+ var webhookSchema2 = z34.object({
5131
+ pull_request: z34.object({
5132
+ assignees: z34.array(z34.object({ login: z34.string().min(1) })).nullish(),
5133
+ number: z34.number(),
5134
+ user: z34.object({ login: z34.string().min(1) }).nullish()
4964
5135
  }),
4965
- repository: z33.object({ full_name: z33.string().min(1) })
5136
+ repository: z34.object({ full_name: z34.string().min(1) })
4966
5137
  });
4967
- var commitPageSchema = z33.array(
4968
- z33.object({
4969
- author: z33.object({ login: z33.string().min(1) }).nullish(),
4970
- commit: z33.object({ message: z33.string() })
5138
+ var commitPageSchema = z34.array(
5139
+ z34.object({
5140
+ author: z34.object({ login: z34.string().min(1) }).nullish(),
5141
+ commit: z34.object({ message: z34.string() })
4971
5142
  })
4972
5143
  );
4973
5144
  function shareCommitPages(load) {
@@ -5109,11 +5280,11 @@ function webhookInstallationId(body) {
5109
5280
  }
5110
5281
  return parseInstallationId(installation.id);
5111
5282
  }
5112
- var feedbackTargetSchema = z34.object({
5113
- commentId: z34.number(),
5114
- commentKind: z34.enum(["conversation", "review", "review_body"]),
5115
- pullRequest: z34.number(),
5116
- repo: z34.string().min(1)
5283
+ var feedbackTargetSchema = z35.object({
5284
+ commentId: z35.number(),
5285
+ commentKind: z35.enum(["conversation", "review", "review_body"]),
5286
+ pullRequest: z35.number(),
5287
+ repo: z35.string().min(1)
5117
5288
  });
5118
5289
  function pullRequestFeedbackTarget(events) {
5119
5290
  for (const event of events) {
@@ -5123,25 +5294,6 @@ function pullRequestFeedbackTarget(events) {
5123
5294
  }
5124
5295
  return void 0;
5125
5296
  }
5126
- function githubCodeChange(outcome, conversationIds) {
5127
- return {
5128
- closedAt: outcome.closedAt,
5129
- conversationIds,
5130
- mergedAt: outcome.mergedAt,
5131
- number: outcome.number,
5132
- openedAt: outcome.openedAt,
5133
- providerId: outcome.pullRequestId,
5134
- repository: {
5135
- name: outcome.repositoryFullName,
5136
- providerId: outcome.repositoryId,
5137
- url: `https://github.com/${outcome.repositoryFullName}`
5138
- },
5139
- state: outcome.state === "closed_unmerged" ? "closed" : outcome.state,
5140
- title: outcome.title,
5141
- updatedAt: outcome.updatedAt,
5142
- url: `https://github.com/${outcome.repositoryFullName}/pull/${outcome.number}`
5143
- };
5144
- }
5145
5297
  function createGitHubWebhookRoute(args) {
5146
5298
  return {
5147
5299
  method: "POST",
@@ -5185,34 +5337,13 @@ function createGitHubWebhookRoute(args) {
5185
5337
  const pullRequestConversations = eventName === "pull_request" ? normalizeGitHubPullRequestConversations({ body, botEmail }) : void 0;
5186
5338
  const pullRequestLinkedIssues = eventName === "pull_request" ? normalizeGitHubPullRequestLinkedIssues({ body, botEmail }) : void 0;
5187
5339
  if (pullRequestOutcome) {
5188
- const recordedOutcome = await recordGitHubPullRequestOutcome(
5189
- args.db,
5190
- pullRequestOutcome
5191
- );
5192
- if (recordedOutcome.applied) {
5193
- await args.codeChanges.record(
5194
- githubCodeChange(
5195
- pullRequestOutcome,
5196
- recordedOutcome.conversationIds
5197
- )
5198
- );
5199
- }
5200
- if (recordedOutcome.applied && pullRequestOutcome.state !== "open") {
5201
- const status = pullRequestOutcome.state === "merged" ? "merged" : "closed";
5202
- await Promise.all(
5203
- recordedOutcome.conversationIds.map(
5204
- (conversationId) => updateGitHubAnnotation(
5205
- args.annotations.forConversation(conversationId),
5206
- {
5207
- repo: pullRequestOutcome.repositoryFullName,
5208
- number: pullRequestOutcome.number,
5209
- objectType: "code_change",
5210
- status
5211
- }
5212
- )
5213
- )
5214
- );
5215
- }
5340
+ const recordedOutcome = await applyGitHubPullRequestOutcome({
5341
+ annotations: args.annotations,
5342
+ codeChanges: args.codeChanges,
5343
+ db: args.db,
5344
+ log: args.log,
5345
+ outcome: pullRequestOutcome
5346
+ });
5216
5347
  if (recordedOutcome.applied && !recordedOutcome.commitComposition && pullRequestOutcome.state === "merged" && args.classifyPullRequestCommits) {
5217
5348
  let commitComposition;
5218
5349
  try {
@@ -5242,19 +5373,17 @@ function createGitHubWebhookRoute(args) {
5242
5373
  issueOutcome
5243
5374
  );
5244
5375
  if (recordedOutcome.applied && issueOutcome.state === "closed") {
5245
- await Promise.all(
5246
- recordedOutcome.conversationIds.map(
5247
- (conversationId) => updateGitHubAnnotation(
5248
- args.annotations.forConversation(conversationId),
5249
- {
5250
- repo: issueOutcome.repositoryFullName,
5251
- number: issueOutcome.number,
5252
- objectType: "task",
5253
- status: "closed"
5254
- }
5255
- )
5256
- )
5257
- );
5376
+ await updateGitHubAnnotations({
5377
+ annotations: args.annotations,
5378
+ conversationIds: recordedOutcome.conversationIds,
5379
+ log: args.log,
5380
+ update: {
5381
+ repo: issueOutcome.repositoryFullName,
5382
+ number: issueOutcome.number,
5383
+ objectType: "task",
5384
+ status: "closed"
5385
+ }
5386
+ });
5258
5387
  }
5259
5388
  }
5260
5389
  const recordedIssueConversations = issueConversations ? await recordGitHubIssueConversations(args.db, issueConversations) : false;
@@ -5268,6 +5397,13 @@ function createGitHubWebhookRoute(args) {
5268
5397
  providerId: pullRequestConversations.pullRequestId
5269
5398
  });
5270
5399
  }
5400
+ const pullRequestActivity = normalizeGitHubPullRequestActivity({
5401
+ body,
5402
+ eventName
5403
+ });
5404
+ if (pullRequestActivity) {
5405
+ await args.codeChanges.recordActivity(pullRequestActivity);
5406
+ }
5271
5407
  const recordedPullRequestLinkedIssues = pullRequestLinkedIssues ? await recordGitHubPullRequestLinkedIssues(
5272
5408
  args.db,
5273
5409
  pullRequestLinkedIssues
@@ -5380,30 +5516,30 @@ function createGitHubWebhookRoute(args) {
5380
5516
  }
5381
5517
 
5382
5518
  // src/merge-conflict-checks/heartbeat.ts
5383
- import * as z35 from "zod";
5519
+ import * as z36 from "zod";
5384
5520
  var CHECK_LIMIT = 10;
5385
5521
  var MAX_PAGES2 = 5;
5386
5522
  var CLAIM_MS = 5 * 6e4;
5387
5523
  var UNKNOWN_RETRY_MS = 6e4;
5388
5524
  var MAX_ATTEMPTS = 5;
5389
- var searchNodeSchema = z35.union([
5390
- z35.object({
5391
- baseRefName: z35.string().min(1),
5392
- headRefOid: z35.string().min(1),
5393
- mergeable: z35.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
5394
- number: z35.number().int().positive(),
5395
- state: z35.string(),
5396
- url: z35.string().min(1)
5525
+ var searchNodeSchema = z36.union([
5526
+ z36.object({
5527
+ baseRefName: z36.string().min(1),
5528
+ headRefOid: z36.string().min(1),
5529
+ mergeable: z36.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
5530
+ number: z36.number().int().positive(),
5531
+ state: z36.string(),
5532
+ url: z36.string().min(1)
5397
5533
  }),
5398
- z35.object({}).strict()
5534
+ z36.object({}).strict()
5399
5535
  ]);
5400
- var searchResponseSchema = z35.object({
5401
- data: z35.object({
5402
- search: z35.object({
5403
- nodes: z35.array(searchNodeSchema.nullable()),
5404
- pageInfo: z35.object({
5405
- endCursor: z35.string().nullable(),
5406
- hasNextPage: z35.boolean()
5536
+ var searchResponseSchema = z36.object({
5537
+ data: z36.object({
5538
+ search: z36.object({
5539
+ nodes: z36.array(searchNodeSchema.nullable()),
5540
+ pageInfo: z36.object({
5541
+ endCursor: z36.string().nullable(),
5542
+ hasNextPage: z36.boolean()
5407
5543
  })
5408
5544
  })
5409
5545
  })
@@ -5476,6 +5612,139 @@ async function runGitHubConflictChecks(args) {
5476
5612
  }
5477
5613
  }
5478
5614
 
5615
+ // src/pull-request-outcomes/reconcile.ts
5616
+ import * as z37 from "zod";
5617
+ var RECONCILE_MS = 24 * 60 * 6e4;
5618
+ var REPOSITORY_LIMIT = 1;
5619
+ var PULL_REQUESTS_PER_QUERY = 100;
5620
+ var lifecycleSchema = z37.object({
5621
+ assignees: z37.object({
5622
+ nodes: z37.array(z37.object({ login: z37.string().min(1) }).nullable())
5623
+ }),
5624
+ // GraphQL omits the `[bot]` suffix that REST and webhooks give an app.
5625
+ author: z37.object({ __typename: z37.string(), login: z37.string().min(1) }).nullable(),
5626
+ closedAt: z37.string().nullable(),
5627
+ createdAt: z37.string(),
5628
+ databaseId: z37.number().int().positive(),
5629
+ headRefName: z37.string(),
5630
+ isDraft: z37.boolean(),
5631
+ merged: z37.boolean(),
5632
+ mergedAt: z37.string().nullable(),
5633
+ number: z37.number().int().positive(),
5634
+ state: z37.enum(["OPEN", "CLOSED", "MERGED"]),
5635
+ title: z37.string(),
5636
+ updatedAt: z37.string()
5637
+ });
5638
+ var lifecyclesResponseSchema = z37.object({
5639
+ data: z37.object({
5640
+ repository: z37.object({
5641
+ databaseId: z37.number().int().positive(),
5642
+ nameWithOwner: z37.string().min(1)
5643
+ }).catchall(lifecycleSchema.nullable())
5644
+ })
5645
+ });
5646
+ function closedWebhookBody(repository2, pullRequest) {
5647
+ const login2 = pullRequest.author?.login ?? "ghost";
5648
+ return {
5649
+ action: "closed",
5650
+ pull_request: {
5651
+ assignees: pullRequest.assignees.nodes.flatMap(
5652
+ (assignee) => assignee ? [{ login: assignee.login }] : []
5653
+ ),
5654
+ closed_at: pullRequest.closedAt,
5655
+ created_at: pullRequest.createdAt,
5656
+ draft: pullRequest.isDraft,
5657
+ head: { ref: pullRequest.headRefName },
5658
+ id: pullRequest.databaseId,
5659
+ merged: pullRequest.merged,
5660
+ merged_at: pullRequest.mergedAt,
5661
+ number: pullRequest.number,
5662
+ title: pullRequest.title,
5663
+ updated_at: pullRequest.updatedAt,
5664
+ user: {
5665
+ login: pullRequest.author?.__typename === "Bot" ? `${login2}[bot]` : login2
5666
+ }
5667
+ },
5668
+ repository: {
5669
+ full_name: repository2.nameWithOwner,
5670
+ id: repository2.databaseId
5671
+ }
5672
+ };
5673
+ }
5674
+ async function reconcileRepository(args, repositoryFullName, numbers) {
5675
+ for (let start = 0; start < numbers.length; start += PULL_REQUESTS_PER_QUERY) {
5676
+ const { databaseId, nameWithOwner, ...pullRequests } = lifecyclesResponseSchema.parse(
5677
+ await args.loadLifecycles({
5678
+ numbers: numbers.slice(start, start + PULL_REQUESTS_PER_QUERY),
5679
+ repositoryFullName
5680
+ })
5681
+ ).data.repository;
5682
+ for (const pullRequest of Object.values(pullRequests)) {
5683
+ if (!pullRequest || pullRequest.state === "OPEN") continue;
5684
+ const body = closedWebhookBody(
5685
+ { databaseId, nameWithOwner },
5686
+ pullRequest
5687
+ );
5688
+ const outcome = normalizeGitHubPullRequestOutcome({
5689
+ body,
5690
+ botEmail: args.botEmail
5691
+ });
5692
+ if (!outcome) continue;
5693
+ const events = await withGitHubPullRequestPeople({
5694
+ body,
5695
+ deliveryId: "reconcile",
5696
+ events: gitHubPullRequestTerminalEvents(body),
5697
+ hasMatch: args.events.hasMatch,
5698
+ load: async (target) => await loadGitHubPullRequestPeople({
5699
+ logins: target.logins,
5700
+ loadPage: await args.loadCommitPages(target)
5701
+ }),
5702
+ log: args.log
5703
+ });
5704
+ for (const event of events) {
5705
+ await args.events.publish({ ...event, objectType: "code_change" });
5706
+ }
5707
+ await applyGitHubPullRequestOutcome({
5708
+ annotations: args.annotations,
5709
+ codeChanges: args.codeChanges,
5710
+ db: args.db,
5711
+ log: args.log,
5712
+ outcome
5713
+ });
5714
+ }
5715
+ }
5716
+ }
5717
+ async function reconcileGitHubPullRequests(args) {
5718
+ const numbersByRepository = /* @__PURE__ */ new Map();
5719
+ for (const row of await listGitHubStaleOpenPullRequests(
5720
+ args.db,
5721
+ new Date(args.nowMs - RECONCILE_MS)
5722
+ )) {
5723
+ const numbers = numbersByRepository.get(row.repositoryFullName) ?? [];
5724
+ numbers.push(row.number);
5725
+ numbersByRepository.set(row.repositoryFullName, numbers);
5726
+ }
5727
+ let reconciled = 0;
5728
+ for (const [repositoryFullName, numbers] of numbersByRepository) {
5729
+ if (reconciled >= REPOSITORY_LIMIT) break;
5730
+ const claimed = await args.state.setIfNotExists(
5731
+ `pull-request-reconcile:${repositoryFullName}`,
5732
+ args.nowMs,
5733
+ RECONCILE_MS
5734
+ );
5735
+ if (!claimed) continue;
5736
+ reconciled += 1;
5737
+ try {
5738
+ await reconcileRepository(args, repositoryFullName, numbers);
5739
+ } catch (error) {
5740
+ args.log.error("GitHub pull request reconcile failed", {
5741
+ errorType: error instanceof Error ? error.name : "UnknownError",
5742
+ repository: repositoryFullName
5743
+ });
5744
+ }
5745
+ }
5746
+ }
5747
+
5479
5748
  // src/events/declarations.ts
5480
5749
  var NEEDS_REPO = { anyOf: ["repo"] };
5481
5750
  function gitHubEventDeclarations(pullRequestGuidance) {
@@ -5500,30 +5769,30 @@ function gitHubResourceUrl(input) {
5500
5769
  if (input.resourceType === "repository") {
5501
5770
  return `https://github.com/${input.identifier}`;
5502
5771
  }
5503
- const [repo, number27] = input.identifier.split("#");
5504
- if (!repo || !number27) return void 0;
5772
+ const [repo, number29] = input.identifier.split("#");
5773
+ if (!repo || !number29) return void 0;
5505
5774
  if (input.resourceType === "pull_request") {
5506
- return `https://github.com/${repo}/pull/${number27}`;
5775
+ return `https://github.com/${repo}/pull/${number29}`;
5507
5776
  }
5508
5777
  if (input.resourceType === "issue") {
5509
- return `https://github.com/${repo}/issues/${number27}`;
5778
+ return `https://github.com/${repo}/issues/${number29}`;
5510
5779
  }
5511
5780
  return void 0;
5512
5781
  }
5513
5782
 
5514
5783
  // src/pull-request-outcomes/commit-composition.ts
5515
- import * as z36 from "zod";
5516
- var canonicalCommitSchema = z36.object({
5517
- authorEmail: z36.string().nullable(),
5518
- authorLogin: z36.string().nullable()
5784
+ import * as z38 from "zod";
5785
+ var canonicalCommitSchema = z38.object({
5786
+ authorEmail: z38.string().nullable(),
5787
+ authorLogin: z38.string().nullable()
5519
5788
  }).strict();
5520
- var providerCommitSchema = z36.object({
5521
- author: z36.object({ login: z36.string() }).passthrough().nullable(),
5522
- commit: z36.object({
5523
- author: z36.object({ email: z36.string() }).passthrough().nullable()
5789
+ var providerCommitSchema = z38.object({
5790
+ author: z38.object({ login: z38.string() }).passthrough().nullable(),
5791
+ commit: z38.object({
5792
+ author: z38.object({ email: z38.string() }).passthrough().nullable()
5524
5793
  }).passthrough()
5525
5794
  }).passthrough();
5526
- var commitPageSchema2 = z36.array(providerCommitSchema).transform(
5795
+ var commitPageSchema2 = z38.array(providerCommitSchema).transform(
5527
5796
  (commits) => commits.map(
5528
5797
  (commit) => canonicalCommitSchema.parse({
5529
5798
  authorEmail: commit.commit.author?.email ?? null,
@@ -6030,8 +6299,8 @@ function linkifyLine(line) {
6030
6299
  if (isReferenceBoundary(index2 === 0 ? void 0 : line[index2 - 1])) {
6031
6300
  const match = GITHUB_ISSUE_REFERENCE_PATTERN.exec(line.slice(index2));
6032
6301
  if (match) {
6033
- const [reference, owner, repository2, number27] = match;
6034
- output += `[${reference}](https://github.com/${owner}/${repository2}/issues/${number27})`;
6302
+ const [reference, owner, repository2, number29] = match;
6303
+ output += `[${reference}](https://github.com/${owner}/${repository2}/issues/${number29})`;
6035
6304
  index2 += reference.length;
6036
6305
  continue;
6037
6306
  }
@@ -6173,9 +6442,9 @@ function parseGitHubReferences(text2, config) {
6173
6442
  }
6174
6443
  return [...references.values()];
6175
6444
  }
6176
- function objectTitle(kind, object37) {
6177
- if (!isRecord(object37)) return void 0;
6178
- const raw = kind === "commit" ? isRecord(object37.commit) && typeof object37.commit.message === "string" ? object37.commit.message.split("\n")[0] : void 0 : typeof object37.title === "string" ? object37.title : void 0;
6445
+ function objectTitle(kind, object39) {
6446
+ if (!isRecord(object39)) return void 0;
6447
+ const raw = kind === "commit" ? isRecord(object39.commit) && typeof object39.commit.message === "string" ? object39.commit.message.split("\n")[0] : void 0 : typeof object39.title === "string" ? object39.title : void 0;
6179
6448
  return raw?.replace(/\s+/g, " ").trim() || void 0;
6180
6449
  }
6181
6450
  async function loadGitHubConversationTitleContext(args) {
@@ -6454,9 +6723,9 @@ import {
6454
6723
  } from "@sentry/junior-plugin-api";
6455
6724
 
6456
6725
  // src/default-branch.ts
6457
- import * as z37 from "zod";
6726
+ import * as z39 from "zod";
6458
6727
  var DEFAULT_BRANCH_TTL_MS = 10 * 60 * 1e3;
6459
- var repositorySchema2 = z37.object({ default_branch: z37.string().min(1) });
6728
+ var repositorySchema3 = z39.object({ default_branch: z39.string().min(1) });
6460
6729
  async function loadDefaultBranch(env, cache, repository2) {
6461
6730
  const { owner, name } = repository2;
6462
6731
  return await cache.getOrLoad(
@@ -6467,7 +6736,7 @@ async function loadDefaultBranch(env, cache, repository2) {
6467
6736
  permissions: { metadata: "read" },
6468
6737
  repositories: [name]
6469
6738
  });
6470
- const response = repositorySchema2.parse(
6739
+ const response = repositorySchema3.parse(
6471
6740
  await githubRequest(
6472
6741
  "https://api.github.com",
6473
6742
  `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`,
@@ -6571,86 +6840,17 @@ function githubUserReadReason(method, upstreamUrl) {
6571
6840
  }
6572
6841
  return upstreamUrl.pathname.toLowerCase() === "/user" ? "github.user-read" : void 0;
6573
6842
  }
6574
- function parseGitHubGraphqlOperation(bodyText) {
6575
- const parsed = parseGitHubGraphqlRequest(bodyText);
6576
- if (!parsed) {
6577
- return void 0;
6578
- }
6579
- const { normalized, operationName } = parsed;
6580
- if (operationName) {
6581
- const namedOperation = normalized.match(
6582
- new RegExp(
6583
- `\\b(query|mutation|subscription)\\s+${escapeRegExp2(operationName)}\\b`
6584
- )
6585
- )?.[1];
6586
- return namedOperation ? graphqlOperationAccess(namedOperation) : void 0;
6587
- }
6588
- const operation = normalized.match(/\b(query|mutation|subscription)\b/)?.[1];
6589
- const operationAccess = graphqlOperationAccess(operation);
6590
- if (operationAccess) {
6591
- return operationAccess;
6592
- }
6593
- if (normalized.startsWith("{")) {
6594
- return "read";
6595
- }
6596
- return void 0;
6843
+ function githubGraphqlOperation(graphql) {
6844
+ return graphql?.kind === "operation" ? graphql.operation : void 0;
6597
6845
  }
6598
- function parseGitHubGraphqlRequest(bodyText) {
6599
- if (typeof bodyText !== "string" || bodyText.trim().length === 0) {
6600
- return void 0;
6601
- }
6602
- let parsed;
6603
- try {
6604
- parsed = JSON.parse(bodyText);
6605
- } catch {
6606
- return void 0;
6607
- }
6608
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6609
- return void 0;
6610
- }
6611
- const query = parsed.query;
6612
- if (typeof query !== "string") {
6613
- return void 0;
6614
- }
6615
- const operationName = typeof parsed.operationName === "string" ? parsed.operationName.trim() : void 0;
6616
- const normalized = maskGraphqlStringLiterals(
6617
- query.replace(/^\s*#[^\n\r]*(?:\r?\n|$)/gm, "")
6618
- ).trim();
6619
- return {
6620
- normalized,
6621
- ...operationName ? { operationName } : void 0
6622
- };
6623
- }
6624
- function escapeRegExp2(value) {
6625
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6626
- }
6627
- function graphqlOperationAccess(operation) {
6628
- if (operation === "mutation" || operation === "subscription") {
6629
- return "write";
6630
- }
6631
- if (operation === "query") {
6632
- return "read";
6633
- }
6634
- return void 0;
6635
- }
6636
- function maskGraphqlStringLiterals(query) {
6637
- return query.replace(
6638
- /"""[\s\S]*?"""|"(?:\\.|[^"\\])*"/g,
6639
- (match) => " ".repeat(match.length)
6640
- );
6641
- }
6642
- function githubGraphqlAccess(method, upstreamUrl, bodyText) {
6846
+ function githubGraphqlAccess(method, upstreamUrl, graphql) {
6643
6847
  if (!isGitHubGraphqlUrl(upstreamUrl)) {
6644
6848
  return void 0;
6645
6849
  }
6646
6850
  if (HTTP_READ_METHODS.has(method)) {
6647
6851
  return "read";
6648
6852
  }
6649
- const operation = parseGitHubGraphqlOperation(bodyText);
6650
- if (operation) {
6651
- return operation;
6652
- }
6653
- return "write";
6853
+ return githubGraphqlOperation(graphql)?.type === "query" ? "read" : "write";
6654
6854
  }
6655
6855
  function githubGraphqlPermissionDeniedMessage(bodyText) {
6656
6856
  let parsed;
@@ -6740,8 +6940,10 @@ var ISSUE_PATH = /^\/repos\/[^/]+\/[^/]+\/issues\/\d+$/;
6740
6940
  var ISSUE_READ_DENIAL = `Use github_getIssue to read a GitHub issue, not gh issue view or gh api. Read comments with gh api repos/OWNER/REPO/issues/NUMBER/comments. ${CREATE_TOOL_ROUTING_GUIDANCE}`;
6741
6941
  function isGitHubIssueRead(input) {
6742
6942
  if (isGitHubGraphqlUrl(input.upstreamUrl)) {
6743
- const parsed = parseGitHubGraphqlRequest(input.bodyText);
6744
- return input.method === "POST" && parsed !== void 0 && /\b(?:issue|issueOrPullRequest)\s*\(/.test(parsed.normalized);
6943
+ const operation = input.method === "POST" ? githubGraphqlOperation(input.graphql) : void 0;
6944
+ return operation?.fields.some(
6945
+ (field) => (field.name === "issue" || field.name === "issueOrPullRequest") && field.arguments.length > 0
6946
+ ) ?? false;
6745
6947
  }
6746
6948
  return isGitHubApiUrl(input.upstreamUrl) && HTTP_READ_METHODS.has(input.method) && ISSUE_PATH.test(input.upstreamUrl.pathname.toLowerCase());
6747
6949
  }
@@ -6870,32 +7072,29 @@ var HOST_GRAPHQL_MUTATIONS = [
6870
7072
  operationPrefix: "github.pull.review-reaction.update:"
6871
7073
  }
6872
7074
  ];
6873
- function hostGraphqlMutationRepository(operation, method, upstreamUrl, bodyText) {
7075
+ function hostGraphqlMutationRepository(operation, method, upstreamUrl, graphql) {
6874
7076
  if (method !== "POST" || !isGitHubGraphqlUrl(upstreamUrl) || !operation) {
6875
7077
  return void 0;
6876
7078
  }
6877
- const parsed = parseGitHubGraphqlRequest(bodyText);
7079
+ const parsed = githubGraphqlOperation(graphql);
6878
7080
  const mutation = HOST_GRAPHQL_MUTATIONS.find(
6879
- (candidate) => operation.startsWith(candidate.operationPrefix) && parsed?.operationName === candidate.operationName && new RegExp(`\\bmutation\\s+${candidate.operationName}\\b`).test(
6880
- parsed.normalized
6881
- ) && new RegExp(`\\b${candidate.field}\\b`).test(parsed.normalized)
7081
+ (candidate) => operation.startsWith(candidate.operationPrefix) && parsed?.type === "mutation" && parsed.name === candidate.operationName && parsed.rootFields.length === 1 && parsed.rootFields[0] === candidate.field
6882
7082
  );
6883
7083
  if (!mutation) return void 0;
6884
7084
  const repository2 = operation.slice(mutation.operationPrefix.length);
6885
7085
  return /^[^/]+\/[^/]+$/.test(repository2) ? repository2 : void 0;
6886
7086
  }
6887
- function isGitHubGraphqlMutation(method, upstreamUrl, bodyText, field) {
7087
+ function isGitHubGraphqlMutation(method, upstreamUrl, graphql, field) {
6888
7088
  if (method !== "POST" || !isGitHubGraphqlUrl(upstreamUrl)) return false;
6889
- const parsed = parseGitHubGraphqlRequest(bodyText);
6890
- if (!parsed || !new RegExp(`\\b${field}\\b`).test(parsed.normalized)) {
6891
- return false;
6892
- }
6893
- if (!parsed.operationName) return /\bmutation\b/.test(parsed.normalized);
6894
- return new RegExp(
6895
- `\\bmutation\\s+${escapeRegExp2(parsed.operationName)}\\b`
6896
- ).test(parsed.normalized);
7089
+ const parsed = githubGraphqlOperation(graphql);
7090
+ return parsed?.type === "mutation" && parsed.rootFields.includes(field);
6897
7091
  }
6898
7092
  function applyGitHubEgressPolicy(input) {
7093
+ if (isGitHubGraphqlUrl(input.upstreamUrl) && input.graphql?.kind === "unreadable" && input.graphql.reason === "too-large") {
7094
+ throw new EgressPolicyDenied3(
7095
+ "GitHub GraphQL request body is too large to inspect before issuing credentials."
7096
+ );
7097
+ }
6899
7098
  const reactionWrite = isGitHubApiUrl(input.upstreamUrl) && (input.method === "POST" || input.method === "DELETE") && PULL_REQUEST_COMMENT_REACTIONS_PATH.test(
6900
7099
  input.upstreamUrl.pathname.toLowerCase()
6901
7100
  );
@@ -6922,7 +7121,7 @@ function applyGitHubEgressPolicy(input) {
6922
7121
  (candidate) => candidate.method === input.method && isGitHubApiUrl(input.upstreamUrl) && candidate.restPath.test(pathname) || isGitHubGraphqlMutation(
6923
7122
  input.method,
6924
7123
  input.upstreamUrl,
6925
- input.bodyText,
7124
+ input.graphql,
6926
7125
  candidate.graphqlField
6927
7126
  )
6928
7127
  );
@@ -6965,6 +7164,7 @@ async function selectGitHubGrant(ctx, env, upstreamUrl) {
6965
7164
  const method = ctx.request.method.toUpperCase();
6966
7165
  applyGitHubEgressPolicy({
6967
7166
  ...ctx.request.bodyText !== void 0 ? { bodyText: ctx.request.bodyText } : void 0,
7167
+ ...ctx.request.graphql ? { graphql: ctx.request.graphql } : void 0,
6968
7168
  method,
6969
7169
  ...ctx.request.operation ? { operation: ctx.request.operation } : void 0,
6970
7170
  upstreamUrl
@@ -7019,7 +7219,7 @@ async function selectGitHubGrant(ctx, env, upstreamUrl) {
7019
7219
  ctx.request.operation,
7020
7220
  method,
7021
7221
  upstreamUrl,
7022
- ctx.request.bodyText
7222
+ ctx.request.graphql
7023
7223
  );
7024
7224
  if (hostMutationRepository) {
7025
7225
  return {
@@ -7035,7 +7235,7 @@ async function selectGitHubGrant(ctx, env, upstreamUrl) {
7035
7235
  const graphqlAccess = githubGraphqlAccess(
7036
7236
  method,
7037
7237
  upstreamUrl,
7038
- ctx.request.bodyText
7238
+ ctx.request.graphql
7039
7239
  );
7040
7240
  if (graphqlAccess) {
7041
7241
  if (graphqlAccess === "write") {
@@ -7218,8 +7418,10 @@ function githubPlugin(options = {}) {
7218
7418
  return linkifyGitHubReferences(text2);
7219
7419
  },
7220
7420
  async heartbeat(ctx) {
7421
+ const db = ctx.db;
7422
+ const installationEnv = { appIdEnv, installationIdEnv, privateKeyEnv };
7221
7423
  await runGitHubConflictChecks({
7222
- db: ctx.db,
7424
+ db,
7223
7425
  events: ctx.events,
7224
7426
  log: ctx.log,
7225
7427
  now: new Date(ctx.nowMs),
@@ -7228,13 +7430,25 @@ function githubPlugin(options = {}) {
7228
7430
  if (!login2) {
7229
7431
  throw new Error(`${botEmailEnv} is not a GitHub bot address`);
7230
7432
  }
7231
- return await searchOpenPullRequestMergeability(
7232
- { appIdEnv, installationIdEnv, privateKeyEnv },
7233
- { ...input, author: `app/${login2.replace(/\[bot\]$/, "")}` }
7234
- );
7433
+ return await searchOpenPullRequestMergeability(installationEnv, {
7434
+ ...input,
7435
+ author: `app/${login2.replace(/\[bot\]$/, "")}`
7436
+ });
7235
7437
  },
7236
7438
  state: ctx.state
7237
7439
  });
7440
+ await reconcileGitHubPullRequests({
7441
+ annotations: ctx.annotations,
7442
+ botEmail: readEnv(botEmailEnv),
7443
+ codeChanges: ctx.codeChanges,
7444
+ db,
7445
+ events: ctx.events,
7446
+ loadCommitPages: async (target) => await loadPullRequestCommitPages(installationEnv, target),
7447
+ loadLifecycles: async (input) => await loadPullRequestLifecycles(installationEnv, input),
7448
+ log: ctx.log,
7449
+ nowMs: ctx.nowMs,
7450
+ state: ctx.state
7451
+ });
7238
7452
  },
7239
7453
  async unfinishedWork(ctx) {
7240
7454
  const db = ctx.db;
@@ -7299,7 +7513,9 @@ function githubPlugin(options = {}) {
7299
7513
  return createGitHubTools(
7300
7514
  ctx,
7301
7515
  readEnv(botEmailEnv),
7302
- options.pullRequestEvents?.subscribeAfterCreate
7516
+ gitHubPullRequestSubscription(
7517
+ options.pullRequestEvents?.subscribeAfterCreate
7518
+ )
7303
7519
  );
7304
7520
  },
7305
7521
  workspacePrepare: prepareWorkspace,