@sentry/junior-github 0.296.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",
@@ -2085,7 +2112,7 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2085
2112
  parsedInput,
2086
2113
  ctx,
2087
2114
  requester,
2088
- ctx.slack?.conversationLink?.url
2115
+ ctx.conversationLink?.url
2089
2116
  );
2090
2117
  const pendingState = {
2091
2118
  status: "pending",
@@ -2639,7 +2666,7 @@ function createGitHubUpdateIssueTool(ctx) {
2639
2666
  currentBody
2640
2667
  ),
2641
2668
  nonEmptyString4(ctx.conversationId, "conversationId"),
2642
- ctx.slack?.conversationLink?.url
2669
+ ctx.conversationLink?.url
2643
2670
  )
2644
2671
  } : void 0,
2645
2672
  ...update.state !== void 0 ? { state: update.state } : void 0
@@ -2829,7 +2856,7 @@ function createGitHubUpdatePullRequestTool(ctx) {
2829
2856
  currentBody
2830
2857
  ),
2831
2858
  nonEmptyString5(ctx.conversationId, "conversationId"),
2832
- ctx.slack?.conversationLink?.url
2859
+ ctx.conversationLink?.url
2833
2860
  )
2834
2861
  } : void 0,
2835
2862
  ...update.base !== void 0 ? { base: update.base } : void 0,
@@ -2991,17 +3018,17 @@ async function commentParentNumber(egress, input) {
2991
3018
  pull_request_url: z19.string().optional()
2992
3019
  }).safeParse(commentPayload);
2993
3020
  const parentUrl = comment.success ? input.commentKind === "conversation" ? comment.data.issue_url : comment.data.pull_request_url : void 0;
2994
- const number27 = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
2995
- if (!number27) {
3021
+ const number29 = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
3022
+ if (!number29) {
2996
3023
  throw new Error("GitHub comment did not name its issue or pull request.");
2997
3024
  }
2998
- return number27;
3025
+ return number29;
2999
3026
  }
3000
3027
  async function assertBotAuthoredPullRequest(egress, input) {
3001
- const { number: number27 } = input;
3028
+ const { number: number29 } = input;
3002
3029
  const pullResponse = await githubApi(egress, {
3003
3030
  operation: "github.pull.get",
3004
- path: `${repoPath(input)}/pulls/${number27}`
3031
+ path: `${repoPath(input)}/pulls/${number29}`
3005
3032
  });
3006
3033
  const pullPayload = pullResponse.body;
3007
3034
  if (!pullResponse.ok && pullResponse.status !== 404) {
@@ -3507,7 +3534,7 @@ function createGitHubTools(ctx, botEmail, pullRequestSubscription) {
3507
3534
 
3508
3535
  // src/webhooks/handler.ts
3509
3536
  import { createHmac, timingSafeEqual } from "crypto";
3510
- import * as z34 from "zod";
3537
+ import * as z35 from "zod";
3511
3538
 
3512
3539
  // src/issue-outcomes/store.ts
3513
3540
  import { and as and2, eq as eq2, lte, sql as sql2 } from "drizzle-orm";
@@ -3589,7 +3616,7 @@ async function recordGitHubIssueConversations(db, input) {
3589
3616
  }
3590
3617
 
3591
3618
  // src/pull-request-outcomes/store.ts
3592
- 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";
3593
3620
  import * as z23 from "zod";
3594
3621
  var githubPullRequestOutcomeInputSchema = z23.object({
3595
3622
  candidateOwned: z23.boolean(),
@@ -3726,6 +3753,10 @@ async function listGitHubFinishedWork(db, conversationIds) {
3726
3753
  })
3727
3754
  );
3728
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
+ }
3729
3760
  async function listGitHubAssignedWork(db, conversationIds) {
3730
3761
  if (conversationIds.length === 0) return [];
3731
3762
  const values = sql3.join(
@@ -3820,6 +3851,49 @@ async function releaseGitHubPullRequestReadySync(db, target, claim) {
3820
3851
  return row?.requests;
3821
3852
  }
3822
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
+
3823
3897
  // src/webhooks/issue-outcome.ts
3824
3898
  import * as z24 from "zod";
3825
3899
  var canonicalIssueOutcomeSchema = z24.object({
@@ -4074,11 +4148,9 @@ function normalizeGitHubPullRequestOutcome(args) {
4074
4148
  );
4075
4149
  const candidateOwned = hasOwnershipMarker && (parsed.action === "opened" || parsed.action === "closed");
4076
4150
  const state = parsed.action !== "closed" ? "open" : pullRequest.merged ? "merged" : "closed_unmerged";
4077
- const closedAt = timestamp3(pullRequest.closed_at);
4078
- const mergedAt = timestamp3(pullRequest.merged_at);
4079
- if (parsed.action === "closed" && (pullRequest.merged ? !mergedAt : !closedAt)) {
4080
- throw new Error("GitHub pull request terminal timestamp is invalid");
4081
- }
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);
4082
4154
  return {
4083
4155
  candidateOwned,
4084
4156
  closedAt,
@@ -4121,21 +4193,88 @@ function normalizeGitHubPullRequestLinkedIssues(args) {
4121
4193
  } : void 0;
4122
4194
  }
4123
4195
 
4124
- // src/webhooks/merge-conflict.ts
4196
+ // src/webhooks/pull-request-activity.ts
4125
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";
4126
4265
  var EVENT_TYPE = "pull_request.merge_conflict";
4127
4266
  var CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set([
4128
4267
  "pull_request.closed_unmerged",
4129
4268
  "pull_request.merged"
4130
4269
  ]);
4131
- var pullRequestSchema3 = z26.object({
4132
- base: z26.object({ ref: z26.string().min(1) }),
4133
- number: z26.number().int().positive().optional(),
4134
- head: z26.object({ sha: z26.string().min(1) }),
4135
- html_url: z26.string().min(1).optional(),
4136
- mergeable: z26.boolean().nullable().optional(),
4137
- mergeable_state: z26.string().optional(),
4138
- 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()
4139
4278
  });
4140
4279
  function gitHubMergeConflictEvents(input) {
4141
4280
  const { conflict } = input;
@@ -4169,7 +4308,7 @@ function pullRequestRefs(events) {
4169
4308
  return [...refs.values()];
4170
4309
  }
4171
4310
  function deliveredPullRequest(payload, ref) {
4172
- const parsed = z26.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
4311
+ const parsed = z27.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
4173
4312
  const pullRequest = parsed.success ? parsed.data.pull_request : void 0;
4174
4313
  return pullRequest?.number === ref.number && typeof pullRequest.mergeable === "boolean" ? pullRequest : void 0;
4175
4314
  }
@@ -4207,16 +4346,16 @@ async function loadGitHubMergeConflictEvents(args) {
4207
4346
  }
4208
4347
 
4209
4348
  // src/merge-conflict-checks/webhooks.ts
4210
- import * as z28 from "zod";
4349
+ import * as z29 from "zod";
4211
4350
 
4212
4351
  // src/merge-conflict-checks/store.ts
4213
4352
  import { and as and4, eq as eq4 } from "drizzle-orm";
4214
- import * as z27 from "zod";
4353
+ import * as z28 from "zod";
4215
4354
  var CHECK_TTL_MS = 30 * 6e4;
4216
- var repeatSchema = z27.object({
4355
+ var repeatSchema = z28.object({
4217
4356
  /** Checks since the last push that ended with an unknown answer. */
4218
- attempts: z27.number().int().positive(),
4219
- dueAtMs: z27.number()
4357
+ attempts: z28.number().int().positive(),
4358
+ dueAtMs: z28.number()
4220
4359
  });
4221
4360
  function pushKey(repositoryFullName) {
4222
4361
  return `merge-conflict-check:push:${repositoryFullName}`;
@@ -4284,12 +4423,12 @@ async function settleGitHubConflictCheck(state, check, retryAtMs) {
4284
4423
 
4285
4424
  // src/merge-conflict-checks/webhooks.ts
4286
4425
  var CONFLICT_CHECK_DELAY_MS = 2 * 6e4;
4287
- var pushSchema = z28.object({
4288
- deleted: z28.boolean().optional(),
4289
- ref: z28.string(),
4290
- repository: z28.object({
4291
- default_branch: z28.string().min(1),
4292
- 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)
4293
4432
  })
4294
4433
  });
4295
4434
  async function scheduleGitHubPushConflictCheck(args) {
@@ -4306,10 +4445,10 @@ async function scheduleGitHubPushConflictCheck(args) {
4306
4445
  }
4307
4446
 
4308
4447
  // src/webhooks/pull-request-ready.ts
4309
- import * as z30 from "zod";
4448
+ import * as z31 from "zod";
4310
4449
 
4311
4450
  // src/webhooks/installation-requests.ts
4312
- import * as z29 from "zod";
4451
+ import * as z30 from "zod";
4313
4452
  function splitRepository(fullName, label) {
4314
4453
  const [owner, name, ...extra] = fullName.split("/");
4315
4454
  if (!owner || !name || extra.length > 0) {
@@ -4349,6 +4488,35 @@ async function loadPullRequest(env, pullRequest) {
4349
4488
  { token: token.token }
4350
4489
  );
4351
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
+ }
4352
4520
  async function searchOpenPullRequestMergeability(env, input) {
4353
4521
  const { name } = splitRepository(
4354
4522
  input.repositoryFullName,
@@ -4379,7 +4547,7 @@ async function markPullRequestFeedbackReviewing(env, target) {
4379
4547
  });
4380
4548
  const content = pullRequestFeedbackReactionContent("reviewing");
4381
4549
  if (target.commentKind === "review_body") {
4382
- const review = z29.object({ node_id: z29.string().min(1) }).parse(
4550
+ const review = z30.object({ node_id: z30.string().min(1) }).parse(
4383
4551
  await githubRequest(
4384
4552
  "https://api.github.com",
4385
4553
  pullRequestReviewPath({
@@ -4391,7 +4559,7 @@ async function markPullRequestFeedbackReviewing(env, target) {
4391
4559
  { token: token.token }
4392
4560
  )
4393
4561
  );
4394
- const result = z29.object({ errors: z29.array(z29.unknown()).optional() }).parse(
4562
+ const result = z30.object({ errors: z30.array(z30.unknown()).optional() }).parse(
4395
4563
  await githubRequest("https://api.github.com", "/graphql", {
4396
4564
  body: {
4397
4565
  operationName: "AddReviewReaction",
@@ -4427,9 +4595,9 @@ async function markPullRequestFeedbackReviewing(env, target) {
4427
4595
  }
4428
4596
  );
4429
4597
  }
4430
- var repositoryPermissionSchema = z29.object({
4431
- permission: z29.string().min(1),
4432
- role_name: z29.string().optional()
4598
+ var repositoryPermissionSchema = z30.object({
4599
+ permission: z30.string().min(1),
4600
+ role_name: z30.string().optional()
4433
4601
  });
4434
4602
  var REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1e3;
4435
4603
  async function loadRepositoryRole(env, cache, target) {
@@ -4459,19 +4627,19 @@ async function loadRepositoryRole(env, cache, target) {
4459
4627
  }
4460
4628
  );
4461
4629
  }
4462
- var pullRequestSchema4 = z29.object({
4463
- auto_merge: z29.object({}).nullable().optional(),
4464
- draft: z29.boolean().optional(),
4465
- html_url: z29.string().url(),
4466
- mergeable_state: z29.string().nullable().optional(),
4467
- merged: z29.boolean(),
4468
- state: z29.enum(["open", "closed"]),
4469
- 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()
4470
4638
  });
4471
- var reviewsSchema = z29.array(
4472
- z29.object({
4473
- state: z29.string(),
4474
- 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()
4475
4643
  })
4476
4644
  );
4477
4645
  async function loadPullRequestMergeState(env, pullRequest) {
@@ -4539,10 +4707,10 @@ var READY_ACTIONS = {
4539
4707
  ]),
4540
4708
  pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
4541
4709
  };
4542
- var pullRequestWebhookSchema = z30.object({
4543
- action: z30.string(),
4544
- pull_request: z30.object({ number: z30.number().int().positive() }),
4545
- 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) })
4546
4714
  });
4547
4715
  function pullRequestReadyTargets(eventName, body) {
4548
4716
  if (eventName === "check_suite") return checkSuitePullRequests(body);
@@ -4641,32 +4809,32 @@ async function syncGitHubPullRequestReadyNotices(args) {
4641
4809
  }
4642
4810
 
4643
4811
  // src/webhooks/pull-request-review-request.ts
4644
- import * as z31 from "zod";
4645
- var login = z31.object({ login: z31.string().min(1) });
4646
- var pullRequestEventSchema = z31.object({
4647
- 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([
4648
4816
  "closed",
4649
4817
  "reopened",
4650
4818
  "review_request_removed",
4651
4819
  "review_requested"
4652
4820
  ]),
4653
- pull_request: z31.object({
4654
- html_url: z31.string().url(),
4655
- merged: z31.boolean().optional(),
4656
- 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(),
4657
4825
  // The people whose review is still requested. Teams are listed apart.
4658
- requested_reviewers: z31.array(login).optional(),
4659
- title: z31.string()
4826
+ requested_reviewers: z32.array(login).optional(),
4827
+ title: z32.string()
4660
4828
  }),
4661
- repository: z31.object({ full_name: z31.string().min(1) }),
4829
+ repository: z32.object({ full_name: z32.string().min(1) }),
4662
4830
  // A team request has `requested_team` instead.
4663
4831
  requested_reviewer: login.optional()
4664
4832
  });
4665
- var reviewEventSchema = z31.object({
4666
- action: z31.literal("submitted"),
4667
- pull_request: z31.object({ number: z31.number().int().positive() }),
4668
- repository: z31.object({ full_name: z31.string().min(1) }),
4669
- 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 })
4670
4838
  });
4671
4839
  function reviewRequestChange(eventName, body) {
4672
4840
  if (eventName === "pull_request_review") {
@@ -4747,14 +4915,14 @@ function sameLogin(left, right) {
4747
4915
  async function syncGitHubPullRequestReviewRequest(args) {
4748
4916
  const parsed = reviewRequestChange(args.eventName, args.body);
4749
4917
  if (!parsed) return;
4750
- const { change, number: number27, repository: repository2 } = parsed;
4918
+ const { change, number: number29, repository: repository2 } = parsed;
4751
4919
  try {
4752
4920
  const opener = (await listGitHubPullRequestOpeners(args.db, {
4753
- numbers: [number27],
4921
+ numbers: [number29],
4754
4922
  repositoryFullName: repository2
4755
- })).get(number27);
4923
+ })).get(number29);
4756
4924
  if (!opener?.conversationId) return;
4757
- const name = `${repository2}#${number27}`;
4925
+ const name = `${repository2}#${number29}`;
4758
4926
  const dedupeKey = `pull-request-review-requested:${name.toLowerCase()}`;
4759
4927
  const items = args.reviewItems.forConversation(opener.conversationId);
4760
4928
  const reviewers = change.kind === "requested" ? change.reviewers : change.reviewer === void 0 ? void 0 : [change.reviewer];
@@ -4777,21 +4945,21 @@ async function syncGitHubPullRequestReviewRequest(args) {
4777
4945
  body: `GitHub asks you to review **${change.title}**: ${change.url}`,
4778
4946
  dedupeKey,
4779
4947
  subject: { id: change.url, title: name, url: change.url },
4780
- title: `Review requested \xB7 #${number27}`,
4948
+ title: `Review requested \xB7 #${number29}`,
4781
4949
  waitsOnAssignees: true
4782
4950
  });
4783
4951
  } catch (error) {
4784
4952
  args.log?.error("GitHub pull request review request failed", {
4785
4953
  deliveryId: args.deliveryId,
4786
4954
  errorType: error instanceof Error ? error.name : "UnknownError",
4787
- number: number27,
4955
+ number: number29,
4788
4956
  repository: repository2
4789
4957
  });
4790
4958
  }
4791
4959
  }
4792
4960
 
4793
4961
  // src/webhooks/pull-request-match-data.ts
4794
- import * as z32 from "zod";
4962
+ import * as z33 from "zod";
4795
4963
  var LOOKUPS_BY_MATCH_KEY = {
4796
4964
  authors: ["authors"],
4797
4965
  openerEmail: ["opener"],
@@ -4799,22 +4967,22 @@ var LOOKUPS_BY_MATCH_KEY = {
4799
4967
  openerUsername: ["opener"]
4800
4968
  };
4801
4969
  var ALL_LOOKUPS = ["authors", "opener", "openerRole"];
4802
- var lookupDataSchema = z32.object({
4803
- authors: z32.array(z32.string().min(1)).min(1).optional(),
4804
- openerRole: z32.string().min(1).optional(),
4805
- 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()
4806
4974
  }).strict();
4807
4975
  function lookupData(input) {
4808
4976
  return lookupDataSchema.parse(definedValues(input));
4809
4977
  }
4810
- var webhookSchema = z32.object({
4811
- repository: z32.object({ full_name: z32.string().min(1) })
4978
+ var webhookSchema = z33.object({
4979
+ repository: z33.object({ full_name: z33.string().min(1) })
4812
4980
  });
4813
4981
  function pullRequestNumbers(events) {
4814
4982
  const numbers = /* @__PURE__ */ new Map();
4815
4983
  for (const event of events) {
4816
- const number27 = event.data?.pullRequest;
4817
- 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);
4818
4986
  }
4819
4987
  return numbers;
4820
4988
  }
@@ -4828,8 +4996,8 @@ function logFailure(context, lookup, error) {
4828
4996
  }
4829
4997
  async function withJuniorOpeners(context, events) {
4830
4998
  const botNumber = (event) => {
4831
- const number27 = context.numbers.get(event.eventKey);
4832
- 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;
4833
5001
  };
4834
5002
  const numbers = events.flatMap((event) => botNumber(event) ?? []);
4835
5003
  if (numbers.length === 0) return events;
@@ -4848,9 +5016,9 @@ async function withJuniorOpeners(context, events) {
4848
5016
  }
4849
5017
  }
4850
5018
  return events.map((event) => {
4851
- const number27 = botNumber(event);
4852
- if (number27 === void 0) return event;
4853
- 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;
4854
5022
  const login2 = identityId ? logins.get(identityId) : void 0;
4855
5023
  const {
4856
5024
  openerEmail: _email,
@@ -4872,8 +5040,8 @@ async function withRolesAndAuthors(context, events, lookups) {
4872
5040
  if (!loadRole && !loadAuthors) return events;
4873
5041
  return await Promise.all(
4874
5042
  events.map(async (event) => {
4875
- const number27 = context.numbers.get(event.eventKey);
4876
- if (number27 === void 0) return event;
5043
+ const number29 = context.numbers.get(event.eventKey);
5044
+ if (number29 === void 0) return event;
4877
5045
  const login2 = event.data?.openerUsername;
4878
5046
  if (loadRole && typeof login2 === "string" && !roles.has(login2)) {
4879
5047
  roles.set(
@@ -4883,16 +5051,16 @@ async function withRolesAndAuthors(context, events, lookups) {
4883
5051
  )
4884
5052
  );
4885
5053
  }
4886
- if (loadAuthors && !authors.has(number27)) {
5054
+ if (loadAuthors && !authors.has(number29)) {
4887
5055
  authors.set(
4888
- number27,
4889
- loadAuthors({ number: number27, repositoryFullName }).catch(
5056
+ number29,
5057
+ loadAuthors({ number: number29, repositoryFullName }).catch(
4890
5058
  (error) => logFailure(context, "authors", error)
4891
5059
  )
4892
5060
  );
4893
5061
  }
4894
5062
  const role = loadRole && typeof login2 === "string" ? await roles.get(login2) : void 0;
4895
- const logins = loadAuthors ? await authors.get(number27) : void 0;
5063
+ const logins = loadAuthors ? await authors.get(number29) : void 0;
4896
5064
  if (!role && !logins?.length) return event;
4897
5065
  return {
4898
5066
  ...event,
@@ -4949,7 +5117,7 @@ async function withGitHubPullRequestMatchData(args) {
4949
5117
  }
4950
5118
 
4951
5119
  // src/webhooks/pull-request-people.ts
4952
- import * as z33 from "zod";
5120
+ import * as z34 from "zod";
4953
5121
  var PEOPLE_EVENTS = /* @__PURE__ */ new Set([
4954
5122
  "pull_request.review.approved",
4955
5123
  "pull_request.merged"
@@ -4959,18 +5127,18 @@ var PAGE_SIZE = 100;
4959
5127
  var MAX_PAGES = 3;
4960
5128
  var CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
4961
5129
  var GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
4962
- var webhookSchema2 = z33.object({
4963
- pull_request: z33.object({
4964
- assignees: z33.array(z33.object({ login: z33.string().min(1) })).nullish(),
4965
- number: z33.number(),
4966
- 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()
4967
5135
  }),
4968
- repository: z33.object({ full_name: z33.string().min(1) })
5136
+ repository: z34.object({ full_name: z34.string().min(1) })
4969
5137
  });
4970
- var commitPageSchema = z33.array(
4971
- z33.object({
4972
- author: z33.object({ login: z33.string().min(1) }).nullish(),
4973
- 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() })
4974
5142
  })
4975
5143
  );
4976
5144
  function shareCommitPages(load) {
@@ -5112,11 +5280,11 @@ function webhookInstallationId(body) {
5112
5280
  }
5113
5281
  return parseInstallationId(installation.id);
5114
5282
  }
5115
- var feedbackTargetSchema = z34.object({
5116
- commentId: z34.number(),
5117
- commentKind: z34.enum(["conversation", "review", "review_body"]),
5118
- pullRequest: z34.number(),
5119
- 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)
5120
5288
  });
5121
5289
  function pullRequestFeedbackTarget(events) {
5122
5290
  for (const event of events) {
@@ -5126,25 +5294,6 @@ function pullRequestFeedbackTarget(events) {
5126
5294
  }
5127
5295
  return void 0;
5128
5296
  }
5129
- function githubCodeChange(outcome, conversationIds) {
5130
- return {
5131
- closedAt: outcome.closedAt,
5132
- conversationIds,
5133
- mergedAt: outcome.mergedAt,
5134
- number: outcome.number,
5135
- openedAt: outcome.openedAt,
5136
- providerId: outcome.pullRequestId,
5137
- repository: {
5138
- name: outcome.repositoryFullName,
5139
- providerId: outcome.repositoryId,
5140
- url: `https://github.com/${outcome.repositoryFullName}`
5141
- },
5142
- state: outcome.state === "closed_unmerged" ? "closed" : outcome.state,
5143
- title: outcome.title,
5144
- updatedAt: outcome.updatedAt,
5145
- url: `https://github.com/${outcome.repositoryFullName}/pull/${outcome.number}`
5146
- };
5147
- }
5148
5297
  function createGitHubWebhookRoute(args) {
5149
5298
  return {
5150
5299
  method: "POST",
@@ -5188,34 +5337,13 @@ function createGitHubWebhookRoute(args) {
5188
5337
  const pullRequestConversations = eventName === "pull_request" ? normalizeGitHubPullRequestConversations({ body, botEmail }) : void 0;
5189
5338
  const pullRequestLinkedIssues = eventName === "pull_request" ? normalizeGitHubPullRequestLinkedIssues({ body, botEmail }) : void 0;
5190
5339
  if (pullRequestOutcome) {
5191
- const recordedOutcome = await recordGitHubPullRequestOutcome(
5192
- args.db,
5193
- pullRequestOutcome
5194
- );
5195
- if (recordedOutcome.applied) {
5196
- await args.codeChanges.record(
5197
- githubCodeChange(
5198
- pullRequestOutcome,
5199
- recordedOutcome.conversationIds
5200
- )
5201
- );
5202
- }
5203
- if (recordedOutcome.applied && pullRequestOutcome.state !== "open") {
5204
- const status = pullRequestOutcome.state === "merged" ? "merged" : "closed";
5205
- await Promise.all(
5206
- recordedOutcome.conversationIds.map(
5207
- (conversationId) => updateGitHubAnnotation(
5208
- args.annotations.forConversation(conversationId),
5209
- {
5210
- repo: pullRequestOutcome.repositoryFullName,
5211
- number: pullRequestOutcome.number,
5212
- objectType: "code_change",
5213
- status
5214
- }
5215
- )
5216
- )
5217
- );
5218
- }
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
+ });
5219
5347
  if (recordedOutcome.applied && !recordedOutcome.commitComposition && pullRequestOutcome.state === "merged" && args.classifyPullRequestCommits) {
5220
5348
  let commitComposition;
5221
5349
  try {
@@ -5245,19 +5373,17 @@ function createGitHubWebhookRoute(args) {
5245
5373
  issueOutcome
5246
5374
  );
5247
5375
  if (recordedOutcome.applied && issueOutcome.state === "closed") {
5248
- await Promise.all(
5249
- recordedOutcome.conversationIds.map(
5250
- (conversationId) => updateGitHubAnnotation(
5251
- args.annotations.forConversation(conversationId),
5252
- {
5253
- repo: issueOutcome.repositoryFullName,
5254
- number: issueOutcome.number,
5255
- objectType: "task",
5256
- status: "closed"
5257
- }
5258
- )
5259
- )
5260
- );
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
+ });
5261
5387
  }
5262
5388
  }
5263
5389
  const recordedIssueConversations = issueConversations ? await recordGitHubIssueConversations(args.db, issueConversations) : false;
@@ -5271,6 +5397,13 @@ function createGitHubWebhookRoute(args) {
5271
5397
  providerId: pullRequestConversations.pullRequestId
5272
5398
  });
5273
5399
  }
5400
+ const pullRequestActivity = normalizeGitHubPullRequestActivity({
5401
+ body,
5402
+ eventName
5403
+ });
5404
+ if (pullRequestActivity) {
5405
+ await args.codeChanges.recordActivity(pullRequestActivity);
5406
+ }
5274
5407
  const recordedPullRequestLinkedIssues = pullRequestLinkedIssues ? await recordGitHubPullRequestLinkedIssues(
5275
5408
  args.db,
5276
5409
  pullRequestLinkedIssues
@@ -5383,30 +5516,30 @@ function createGitHubWebhookRoute(args) {
5383
5516
  }
5384
5517
 
5385
5518
  // src/merge-conflict-checks/heartbeat.ts
5386
- import * as z35 from "zod";
5519
+ import * as z36 from "zod";
5387
5520
  var CHECK_LIMIT = 10;
5388
5521
  var MAX_PAGES2 = 5;
5389
5522
  var CLAIM_MS = 5 * 6e4;
5390
5523
  var UNKNOWN_RETRY_MS = 6e4;
5391
5524
  var MAX_ATTEMPTS = 5;
5392
- var searchNodeSchema = z35.union([
5393
- z35.object({
5394
- baseRefName: z35.string().min(1),
5395
- headRefOid: z35.string().min(1),
5396
- mergeable: z35.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
5397
- number: z35.number().int().positive(),
5398
- state: z35.string(),
5399
- 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)
5400
5533
  }),
5401
- z35.object({}).strict()
5534
+ z36.object({}).strict()
5402
5535
  ]);
5403
- var searchResponseSchema = z35.object({
5404
- data: z35.object({
5405
- search: z35.object({
5406
- nodes: z35.array(searchNodeSchema.nullable()),
5407
- pageInfo: z35.object({
5408
- endCursor: z35.string().nullable(),
5409
- 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()
5410
5543
  })
5411
5544
  })
5412
5545
  })
@@ -5479,6 +5612,139 @@ async function runGitHubConflictChecks(args) {
5479
5612
  }
5480
5613
  }
5481
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
+
5482
5748
  // src/events/declarations.ts
5483
5749
  var NEEDS_REPO = { anyOf: ["repo"] };
5484
5750
  function gitHubEventDeclarations(pullRequestGuidance) {
@@ -5503,30 +5769,30 @@ function gitHubResourceUrl(input) {
5503
5769
  if (input.resourceType === "repository") {
5504
5770
  return `https://github.com/${input.identifier}`;
5505
5771
  }
5506
- const [repo, number27] = input.identifier.split("#");
5507
- if (!repo || !number27) return void 0;
5772
+ const [repo, number29] = input.identifier.split("#");
5773
+ if (!repo || !number29) return void 0;
5508
5774
  if (input.resourceType === "pull_request") {
5509
- return `https://github.com/${repo}/pull/${number27}`;
5775
+ return `https://github.com/${repo}/pull/${number29}`;
5510
5776
  }
5511
5777
  if (input.resourceType === "issue") {
5512
- return `https://github.com/${repo}/issues/${number27}`;
5778
+ return `https://github.com/${repo}/issues/${number29}`;
5513
5779
  }
5514
5780
  return void 0;
5515
5781
  }
5516
5782
 
5517
5783
  // src/pull-request-outcomes/commit-composition.ts
5518
- import * as z36 from "zod";
5519
- var canonicalCommitSchema = z36.object({
5520
- authorEmail: z36.string().nullable(),
5521
- 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()
5522
5788
  }).strict();
5523
- var providerCommitSchema = z36.object({
5524
- author: z36.object({ login: z36.string() }).passthrough().nullable(),
5525
- commit: z36.object({
5526
- 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()
5527
5793
  }).passthrough()
5528
5794
  }).passthrough();
5529
- var commitPageSchema2 = z36.array(providerCommitSchema).transform(
5795
+ var commitPageSchema2 = z38.array(providerCommitSchema).transform(
5530
5796
  (commits) => commits.map(
5531
5797
  (commit) => canonicalCommitSchema.parse({
5532
5798
  authorEmail: commit.commit.author?.email ?? null,
@@ -6033,8 +6299,8 @@ function linkifyLine(line) {
6033
6299
  if (isReferenceBoundary(index2 === 0 ? void 0 : line[index2 - 1])) {
6034
6300
  const match = GITHUB_ISSUE_REFERENCE_PATTERN.exec(line.slice(index2));
6035
6301
  if (match) {
6036
- const [reference, owner, repository2, number27] = match;
6037
- 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})`;
6038
6304
  index2 += reference.length;
6039
6305
  continue;
6040
6306
  }
@@ -6176,9 +6442,9 @@ function parseGitHubReferences(text2, config) {
6176
6442
  }
6177
6443
  return [...references.values()];
6178
6444
  }
6179
- function objectTitle(kind, object37) {
6180
- if (!isRecord(object37)) return void 0;
6181
- 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;
6182
6448
  return raw?.replace(/\s+/g, " ").trim() || void 0;
6183
6449
  }
6184
6450
  async function loadGitHubConversationTitleContext(args) {
@@ -6457,9 +6723,9 @@ import {
6457
6723
  } from "@sentry/junior-plugin-api";
6458
6724
 
6459
6725
  // src/default-branch.ts
6460
- import * as z37 from "zod";
6726
+ import * as z39 from "zod";
6461
6727
  var DEFAULT_BRANCH_TTL_MS = 10 * 60 * 1e3;
6462
- var repositorySchema2 = z37.object({ default_branch: z37.string().min(1) });
6728
+ var repositorySchema3 = z39.object({ default_branch: z39.string().min(1) });
6463
6729
  async function loadDefaultBranch(env, cache, repository2) {
6464
6730
  const { owner, name } = repository2;
6465
6731
  return await cache.getOrLoad(
@@ -6470,7 +6736,7 @@ async function loadDefaultBranch(env, cache, repository2) {
6470
6736
  permissions: { metadata: "read" },
6471
6737
  repositories: [name]
6472
6738
  });
6473
- const response = repositorySchema2.parse(
6739
+ const response = repositorySchema3.parse(
6474
6740
  await githubRequest(
6475
6741
  "https://api.github.com",
6476
6742
  `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`,
@@ -7152,8 +7418,10 @@ function githubPlugin(options = {}) {
7152
7418
  return linkifyGitHubReferences(text2);
7153
7419
  },
7154
7420
  async heartbeat(ctx) {
7421
+ const db = ctx.db;
7422
+ const installationEnv = { appIdEnv, installationIdEnv, privateKeyEnv };
7155
7423
  await runGitHubConflictChecks({
7156
- db: ctx.db,
7424
+ db,
7157
7425
  events: ctx.events,
7158
7426
  log: ctx.log,
7159
7427
  now: new Date(ctx.nowMs),
@@ -7162,13 +7430,25 @@ function githubPlugin(options = {}) {
7162
7430
  if (!login2) {
7163
7431
  throw new Error(`${botEmailEnv} is not a GitHub bot address`);
7164
7432
  }
7165
- return await searchOpenPullRequestMergeability(
7166
- { appIdEnv, installationIdEnv, privateKeyEnv },
7167
- { ...input, author: `app/${login2.replace(/\[bot\]$/, "")}` }
7168
- );
7433
+ return await searchOpenPullRequestMergeability(installationEnv, {
7434
+ ...input,
7435
+ author: `app/${login2.replace(/\[bot\]$/, "")}`
7436
+ });
7169
7437
  },
7170
7438
  state: ctx.state
7171
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
+ });
7172
7452
  },
7173
7453
  async unfinishedWork(ctx) {
7174
7454
  const db = ctx.db;
@@ -7233,7 +7513,9 @@ function githubPlugin(options = {}) {
7233
7513
  return createGitHubTools(
7234
7514
  ctx,
7235
7515
  readEnv(botEmailEnv),
7236
- options.pullRequestEvents?.subscribeAfterCreate
7516
+ gitHubPullRequestSubscription(
7517
+ options.pullRequestEvents?.subscribeAfterCreate
7518
+ )
7237
7519
  );
7238
7520
  },
7239
7521
  workspacePrepare: prepareWorkspace,