@sentry/junior-github 0.310.0 → 0.311.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRequest, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubRepositoryFromUrl, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as logFailOpenFailure, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as definedValues, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as pullRequestTargets, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as isRecord, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-D5Zs75yy.js";
1
+ import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRepositoryFromUrl, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubMessageSchema, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as definedValues, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as pullRequestTargets, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as logFailOpenFailure, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as githubRequest, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-BxioaScB.js";
2
2
  import * as z from "zod";
3
3
  import pLimit from "p-limit";
4
- import { EgressAuthRequired, EgressPolicyDenied, OBJECT_FACTS_MAX_BYTES, PluginToolInputError, decodeObjectImageRef, defineJuniorPlugin, definePluginTool, enforceEgressPolicy, mergeEventMatchFields, objectFactsBytes, objectFactsMatchType, objectFactsSchema, parseShellCommands, pluginToolOutputSchema, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
4
+ import { EgressAuthRequired, EgressPolicyDenied, OBJECT_FACTS_MAX_BYTES, PluginToolInputError, codeChangeSizeSchema, decodeObjectImageRef, defineJuniorPlugin, definePluginTool, enforceEgressPolicy, mergeEventMatchFields, objectFactsBytes, objectFactsMatchType, objectFactsSchema, parseShellCommands, pluginToolOutputSchema, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
5
5
  import { lexer, walkTokens } from "marked";
6
6
  import { parseFragment } from "parse5";
7
7
  import { Type } from "@sinclair/typebox";
8
8
  import { Value } from "@sinclair/typebox/value";
9
9
  import { and, asc, eq, inArray, lt, lte, ne, sql } from "drizzle-orm";
10
- import { boolean, index, integer, pgTable, primaryKey, text, timestamp as timestamp$2 } from "drizzle-orm/pg-core";
10
+ import { boolean, index, integer, jsonb, pgTable, primaryKey, text, timestamp as timestamp$2 } from "drizzle-orm/pg-core";
11
11
  import ignore from "ignore";
12
12
  import { Kind, parse, print, visit } from "@0no-co/graphql.web";
13
13
  import { createHmac, timingSafeEqual } from "node:crypto";
@@ -109,8 +109,16 @@ function githubSidebarAnnotations(annotations) {
109
109
  };
110
110
  if (annotation.kind === "object") {
111
111
  sidebar.title = annotation.title;
112
- const image = annotation.facts?.type === "code_change" ? annotation.facts.previewImageUrls?.[0] : void 0;
113
- if (image) sidebar.imageUrl = image;
112
+ if (annotation.facts?.type === "code_change") {
113
+ const { additions, changedFiles, deletions, previewImageUrls } = annotation.facts;
114
+ const image = previewImageUrls?.[0];
115
+ if (image) sidebar.imageUrl = image;
116
+ if (additions !== void 0 || deletions !== void 0 || changedFiles !== void 0) sidebar.size = {
117
+ additions,
118
+ changedFiles,
119
+ deletions
120
+ };
121
+ }
114
122
  }
115
123
  if (annotation.url) sidebar.url = annotation.url;
116
124
  return [{
@@ -190,6 +198,7 @@ const responseSchema$1 = z.object({
190
198
  head: z.object({ ref: z.string() }).optional(),
191
199
  base: z.object({ ref: z.string() }).optional(),
192
200
  mergeable: z.boolean().nullable().optional(),
201
+ state: z.string().optional(),
193
202
  changed_files: z.number().int().nonnegative().optional(),
194
203
  additions: z.number().int().nonnegative().optional(),
195
204
  deletions: z.number().int().nonnegative().optional(),
@@ -289,7 +298,7 @@ function githubObjectFacts(type, response) {
289
298
  reviewers: data.requested_reviewers?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
290
299
  sourceBranch: short(data.head?.ref),
291
300
  targetBranch: short(data.base?.ref),
292
- mergeable: data.mergeable ?? void 0,
301
+ mergeable: data.state === "open" ? data.mergeable ?? void 0 : void 0,
293
302
  changedFiles: data.changed_files,
294
303
  additions: data.additions,
295
304
  deletions: data.deletions
@@ -352,7 +361,7 @@ const objectSchema = z.object({
352
361
  title: z.string()
353
362
  });
354
363
  const issueSchema$2 = objectSchema.extend({ pull_request: z.unknown().optional() });
355
- const pullRequestSchema$4 = objectSchema.extend({
364
+ const pullRequestSchema$2 = objectSchema.extend({
356
365
  draft: z.boolean().optional(),
357
366
  merged: z.boolean().optional()
358
367
  });
@@ -388,7 +397,7 @@ function issueCard(link, body) {
388
397
  });
389
398
  }
390
399
  function pullRequestCard(link, body) {
391
- const pull = pullRequestSchema$4.parse(body);
400
+ const pull = pullRequestSchema$2.parse(body);
392
401
  return githubObjectAnnotation({
393
402
  ...githubObjectFacts("code_change", body),
394
403
  repo: repoRef(pull.html_url, link),
@@ -478,7 +487,7 @@ const REACTION_CONTENTS = [
478
487
  ];
479
488
  const inputSchema$15 = z.object({
480
489
  repo: z.string().describe("Repository in \"owner/name\" format."),
481
- number: z.number().int().positive().describe("Issue or pull request number."),
490
+ issue: z.number().int().positive().describe("Issue or pull request number."),
482
491
  content: z.enum(REACTION_CONTENTS).describe("Reaction to add.")
483
492
  }).strict();
484
493
  const outputSchema$15 = pluginToolOutputSchema.extend({
@@ -504,7 +513,7 @@ const gitHubReactToIssueTool = definePluginTool({
504
513
  const response = await githubApi(egress, {
505
514
  operation: "github.issue.reaction.create",
506
515
  method: "POST",
507
- path: `${repoPath(repo)}/issues/${input.number}/reactions`,
516
+ path: `${repoPath(repo)}/issues/${input.issue}/reactions`,
508
517
  body: { content: input.content }
509
518
  });
510
519
  if (!response.ok) {
@@ -516,7 +525,7 @@ const gitHubReactToIssueTool = definePluginTool({
516
525
  return {
517
526
  target: "reactToIssue",
518
527
  repo: repo.ref,
519
- number: input.number,
528
+ number: input.issue,
520
529
  content: input.content,
521
530
  reaction_id: reaction.id
522
531
  };
@@ -693,7 +702,7 @@ const gitHubCloneRepositoryTool = definePluginTool({
693
702
  // src/tools/comment-on-issue.ts
694
703
  const inputSchema$13 = z.object({
695
704
  repo: z.string().describe("Repository in \"owner/name\" format."),
696
- number: z.number().int().positive().describe("Issue number."),
705
+ issue: z.number().int().positive().describe("Issue number."),
697
706
  body: z.string().trim().min(1).describe("Comment text.")
698
707
  }).strict();
699
708
  const outputSchema$13 = pluginToolOutputSchema.extend({
@@ -719,7 +728,7 @@ const gitHubCommentOnIssueTool = definePluginTool({
719
728
  const response = await githubApi(egress, {
720
729
  operation: "github.issue.comment.create",
721
730
  method: "POST",
722
- path: `${repoPath(repo)}/issues/${input.number}/comments`,
731
+ path: `${repoPath(repo)}/issues/${input.issue}/comments`,
723
732
  body: { body: input.body }
724
733
  });
725
734
  if (!response.ok) {
@@ -734,7 +743,7 @@ const gitHubCommentOnIssueTool = definePluginTool({
734
743
  return {
735
744
  target: "commentOnIssue",
736
745
  repo: repo.ref,
737
- number: input.number,
746
+ number: input.issue,
738
747
  comment_id: comment.id,
739
748
  url: comment.html_url
740
749
  };
@@ -743,7 +752,7 @@ const gitHubCommentOnIssueTool = definePluginTool({
743
752
  // src/tools/comment-on-pull-request.ts
744
753
  const inputSchema$12 = z.object({
745
754
  repo: z.string().describe("Repository in \"owner/name\" format."),
746
- number: z.number().int().positive().describe("Pull request number."),
755
+ pull_request: z.number().int().positive().describe("Pull request number."),
747
756
  body: z.string().trim().min(1).describe("Comment text."),
748
757
  in_reply_to: z.number().int().positive().optional().describe("Inline review comment id. Set it to reply in that comment's thread. Omit it to comment on the pull request.")
749
758
  }).strict();
@@ -788,7 +797,7 @@ const gitHubCommentOnPullRequestTool = definePluginTool({
788
797
  async execute(input, _options, { egress }) {
789
798
  const repo = parseRepo$1(input.repo);
790
799
  const prefix = repoPath(repo);
791
- const path = input.in_reply_to === void 0 ? `${prefix}/issues/${input.number}/comments` : `${prefix}/pulls/${input.number}/comments/${await threadRootId(egress, prefix, input.in_reply_to)}/replies`;
800
+ const path = input.in_reply_to === void 0 ? `${prefix}/issues/${input.pull_request}/comments` : `${prefix}/pulls/${input.pull_request}/comments/${await threadRootId(egress, prefix, input.in_reply_to)}/replies`;
792
801
  const response = await githubApi(egress, {
793
802
  operation: "github.pull.comment.create",
794
803
  method: "POST",
@@ -807,7 +816,7 @@ const gitHubCommentOnPullRequestTool = definePluginTool({
807
816
  return {
808
817
  target: "commentOnPullRequest",
809
818
  repo: repo.ref,
810
- number: input.number,
819
+ number: input.pull_request,
811
820
  comment_id: comment.id,
812
821
  reply: {
813
822
  text: input.body,
@@ -1230,7 +1239,7 @@ const gitHubGetDeploymentTool = definePluginTool({
1230
1239
  const CLAIM_NOTE = "If you start work on this issue, first claim it with github_updateIssue and assign_requester: true.";
1231
1240
  const inputSchema$10 = z.object({
1232
1241
  repo: z.string().describe("Repository in \"owner/name\" format."),
1233
- number: z.number().int().positive().describe("Issue number.")
1242
+ issue: z.number().int().positive().describe("Issue number.")
1234
1243
  }).strict();
1235
1244
  const issueSchema$1 = z.object({
1236
1245
  assignees: z.array(z.string()),
@@ -1277,7 +1286,7 @@ const gitHubGetIssueTool = definePluginTool({
1277
1286
  const [response, requester] = await Promise.all([githubApi(ctx.egress, {
1278
1287
  followRedirects: true,
1279
1288
  operation: "github.issue.get",
1280
- path: `${repoPath(repo)}/issues/${input.number}`
1289
+ path: `${repoPath(repo)}/issues/${input.issue}`
1281
1290
  }), resolveGitHubRequester(ctx)]);
1282
1291
  if (!response.ok) {
1283
1292
  const message = `GitHub issue lookup failed with HTTP ${response.status}`;
@@ -1378,7 +1387,7 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1378
1387
  updatedAt: timestamp$2("updated_at", { withTimezone: true }).notNull(),
1379
1388
  /**
1380
1389
  * The requester's next action that Junior last derived from GitHub, and
1381
- * shows on the review desk. Null when no action waits on them.
1390
+ * shows in the Inbox. Null when no action waits on them.
1382
1391
  */
1383
1392
  nextAction: text("next_action").$type(),
1384
1393
  /**
@@ -1391,7 +1400,24 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1391
1400
  */
1392
1401
  readySyncId: integer("ready_sync_id"),
1393
1402
  /** When the current check started. */
1394
- readySyncAt: timestamp$2("ready_sync_at", { withTimezone: true })
1403
+ readySyncAt: timestamp$2("ready_sync_at", { withTimezone: true }),
1404
+ /**
1405
+ * When a person last chose Resume on the merge conflict item.
1406
+ * It counts as activity by a person, so the fix count starts again.
1407
+ */
1408
+ conflictFixesResumedAt: timestamp$2("conflict_fixes_resumed_at", { withTimezone: true }),
1409
+ /**
1410
+ * When Junior last asked the requester to resume a merge conflict fix
1411
+ * that did not land. It asks once after each Resume, so a Dismiss ends
1412
+ * the asks on the pull request.
1413
+ */
1414
+ conflictFixAskedAt: timestamp$2("conflict_fix_asked_at", { withTimezone: true }),
1415
+ /**
1416
+ * The latest merge conflict fixes that Junior started, oldest first.
1417
+ * Only these count as fixes, so a merge or force push for work that a
1418
+ * person asked for does not.
1419
+ */
1420
+ conflictFixes: jsonb("conflict_fixes").$type().notNull().default([])
1395
1421
  }, (table) => [
1396
1422
  index("junior_github_pull_requests_opened_at_idx").on(table.openedAt),
1397
1423
  index("junior_github_pull_requests_merged_at_idx").on(table.mergedAt),
@@ -2187,7 +2213,7 @@ const OPEN_PULL_REQUEST_MERGEABILITY = githubGraphql(`
2187
2213
  * Read what decides a merge conflict fix on one pull request: the review
2188
2214
  * decision, when it opened, and its latest pushes, reviews, and comments.
2189
2215
  * Pushes have their own window, so comments, which anyone can add, cannot
2190
- * push Junior's earlier fixes out of it.
2216
+ * push a person's latest push out of it.
2191
2217
  */
2192
2218
  const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2193
2219
  query PullRequestConflictHistory($owner: String!, $name: String!, $number: Int!) {
@@ -2198,7 +2224,7 @@ const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2198
2224
  pushes: timelineItems(last: 100, itemTypes: [PULL_REQUEST_COMMIT, HEAD_REF_FORCE_PUSHED_EVENT]) {
2199
2225
  nodes {
2200
2226
  __typename
2201
- ... on PullRequestCommit { commit { committedDate parents { totalCount } author { user { login } } } }
2227
+ ... on PullRequestCommit { commit { committedDate author { user { login } } } }
2202
2228
  ... on HeadRefForcePushedEvent { createdAt actor { __typename } }
2203
2229
  }
2204
2230
  }
@@ -2213,6 +2239,72 @@ const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2213
2239
  }
2214
2240
  }
2215
2241
  `);
2242
+ /**
2243
+ * Read what decides the requester's next action on one pull request: its
2244
+ * state, merge state, review requests, latest reviews, head commit, and
2245
+ * latest comments and review requests. A review comment reply is a review,
2246
+ * so `reviews` holds it too.
2247
+ */
2248
+ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
2249
+ query PullRequestNextAction($owner: String!, $name: String!, $number: Int!) {
2250
+ repository(owner: $owner, name: $name) {
2251
+ pullRequest(number: $number) {
2252
+ autoMergeRequest { enabledAt }
2253
+ headRefOid
2254
+ isDraft
2255
+ mergeStateStatus
2256
+ state
2257
+ title
2258
+ url
2259
+ reviewRequests(first: 100) {
2260
+ nodes { requestedReviewer { __typename ... on User { login } } }
2261
+ }
2262
+ reviews(last: 100) {
2263
+ pageInfo { hasPreviousPage startCursor }
2264
+ nodes { ...NextActionReview }
2265
+ }
2266
+ commits(last: 1) { nodes { commit { committedDate } } }
2267
+ timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT]) {
2268
+ nodes {
2269
+ __typename
2270
+ ... on IssueComment { createdAt author { __typename login } }
2271
+ ... on ReviewRequestedEvent {
2272
+ createdAt
2273
+ requestedReviewer { __typename ... on User { login } }
2274
+ }
2275
+ }
2276
+ }
2277
+ }
2278
+ }
2279
+ }
2280
+
2281
+ fragment NextActionReview on PullRequestReview {
2282
+ state
2283
+ submittedAt
2284
+ author { __typename login }
2285
+ commit { oid }
2286
+ }
2287
+ `);
2288
+ /** Read the page of a pull request's reviews before `before`. */
2289
+ const PULL_REQUEST_REVIEWS_BEFORE = githubGraphql(`
2290
+ query PullRequestReviewsBefore($owner: String!, $name: String!, $number: Int!, $before: String!) {
2291
+ repository(owner: $owner, name: $name) {
2292
+ pullRequest(number: $number) {
2293
+ reviews(last: 100, before: $before) {
2294
+ pageInfo { hasPreviousPage startCursor }
2295
+ nodes { ...NextActionReview }
2296
+ }
2297
+ }
2298
+ }
2299
+ }
2300
+
2301
+ fragment NextActionReview on PullRequestReview {
2302
+ state
2303
+ submittedAt
2304
+ author { __typename login }
2305
+ commit { oid }
2306
+ }
2307
+ `);
2216
2308
  const PULL_REQUEST_LIFECYCLE = githubGraphql(`
2217
2309
  query PullRequestLifecycles($owner: String!, $name: String!, $number: Int!) {
2218
2310
  repository(owner: $owner, name: $name) {
@@ -2372,7 +2464,7 @@ const RELATED_CONVERSATIONS_MAX = 10;
2372
2464
  const SUMMARY_MAX_LENGTH = 300;
2373
2465
  const inputSchema$9 = z.object({
2374
2466
  repo: z.string().describe("Repository in \"owner/name\" format."),
2375
- number: z.number().int().positive().describe("Pull request number.")
2467
+ pull_request: z.number().int().positive().describe("Pull request number.")
2376
2468
  }).strict();
2377
2469
  const checksSchema = z.object({
2378
2470
  required: z.enum([
@@ -2402,7 +2494,7 @@ const relatedConversationSchema = z.object({
2402
2494
  summary: z.string().optional().describe("Summary from the latest Brief."),
2403
2495
  updated_at: z.string().describe("Time of the latest activity.")
2404
2496
  });
2405
- const pullRequestSchema$3 = z.object({
2497
+ const pullRequestSchema$1 = z.object({
2406
2498
  base: z.string(),
2407
2499
  agents_md: z.string().optional().describe("Draft only: the root AGENTS.md of the base branch, when it has one."),
2408
2500
  checks: checksSchema,
@@ -2418,7 +2510,7 @@ const pullRequestSchema$3 = z.object({
2418
2510
  title: z.string(),
2419
2511
  url: z.string()
2420
2512
  });
2421
- const outputSchema$9 = pluginToolOutputSchema.merge(pullRequestSchema$3.extend({ target: z.literal("getPullRequest") }));
2513
+ const outputSchema$9 = pluginToolOutputSchema.merge(pullRequestSchema$1.extend({ target: z.literal("getPullRequest") }));
2422
2514
  const checkContextSchema = z.union([z.object({
2423
2515
  __typename: z.literal("CheckRun"),
2424
2516
  conclusion: z.string().nullable(),
@@ -2525,7 +2617,7 @@ const gitHubGetPullRequestTool = definePluginTool({
2525
2617
  const repo = parseRepo$1(input.repo);
2526
2618
  const response = await githubApi(ctx.egress, {
2527
2619
  operation: "github.pull.get",
2528
- path: `${repoPath(repo)}/pulls/${input.number}`
2620
+ path: `${repoPath(repo)}/pulls/${input.pull_request}`
2529
2621
  });
2530
2622
  if (!response.ok) {
2531
2623
  const message = `GitHub pull request lookup failed with HTTP ${response.status}`;
@@ -2668,7 +2760,7 @@ const gitHubGetReleaseTool = definePluginTool({
2668
2760
  });
2669
2761
  // src/tools/get-repository.ts
2670
2762
  const inputSchema$7 = z.object({ repo: z.string().describe("Repository in \"owner/name\" format.") }).strict();
2671
- const repositorySchema$2 = z.object({
2763
+ const repositorySchema$3 = z.object({
2672
2764
  default_branch: z.string(),
2673
2765
  description: z.string().nullable(),
2674
2766
  full_name: z.string(),
@@ -2676,7 +2768,7 @@ const repositorySchema$2 = z.object({
2676
2768
  subscribable: subscribableResourceSchema.optional(),
2677
2769
  url: z.string()
2678
2770
  });
2679
- const outputSchema$7 = pluginToolOutputSchema.merge(repositorySchema$2.extend({ target: z.literal("getRepository") }));
2771
+ const outputSchema$7 = pluginToolOutputSchema.merge(repositorySchema$3.extend({ target: z.literal("getRepository") }));
2680
2772
  /** Read one repository and expose its stable subscription identity. */
2681
2773
  const gitHubGetRepositoryTool = definePluginTool({
2682
2774
  annotations: {
@@ -2806,7 +2898,7 @@ const gitHubGetStatusTool = definePluginTool({
2806
2898
  // src/tools/update-issue.ts
2807
2899
  const inputSchema$5 = z.object({
2808
2900
  repo: z.string().describe("Repository in \"owner/name\" format."),
2809
- number: z.number().int().positive().describe("Issue number."),
2901
+ issue: z.number().int().positive().describe("Issue number."),
2810
2902
  title: z.string().trim().min(1).optional().describe("Replacement issue title."),
2811
2903
  body: z.string().optional().describe("Replacement issue body. The runtime appends requester attribution and the conversation footer."),
2812
2904
  state: z.enum(["open", "closed"]).optional().describe("Replacement issue state."),
@@ -2856,7 +2948,7 @@ const gitHubUpdateIssueTool = definePluginTool({
2856
2948
  if (update.assign_requester && !assignee) throw new PluginToolInputError("The requester has no linked GitHub account, so the issue cannot be assigned to them.");
2857
2949
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
2858
2950
  operation: "github.issue.get",
2859
- path: `${repoPath(repo)}/issues/${update.number}`
2951
+ path: `${repoPath(repo)}/issues/${update.issue}`
2860
2952
  }) : void 0;
2861
2953
  const payload = {
2862
2954
  ...update.title !== void 0 ? { title: update.title } : void 0,
@@ -2868,7 +2960,7 @@ const gitHubUpdateIssueTool = definePluginTool({
2868
2960
  const response = await githubApi(ctx.egress, {
2869
2961
  operation: "github.issue.update",
2870
2962
  method: "PATCH",
2871
- path: `${repoPath(repo)}/issues/${update.number}`,
2963
+ path: `${repoPath(repo)}/issues/${update.issue}`,
2872
2964
  body: payload
2873
2965
  });
2874
2966
  parsed = response.body;
@@ -2878,7 +2970,7 @@ const gitHubUpdateIssueTool = definePluginTool({
2878
2970
  const response = await githubApi(ctx.egress, {
2879
2971
  operation: "github.issue.assign",
2880
2972
  method: "POST",
2881
- path: `${repoPath(repo)}/issues/${update.number}/assignees`,
2973
+ path: `${repoPath(repo)}/issues/${update.issue}/assignees`,
2882
2974
  body: { assignees: [assignee] }
2883
2975
  });
2884
2976
  parsed = response.body;
@@ -2939,7 +3031,7 @@ function createGitHubUpdateIssueCommentTool(botEmail) {
2939
3031
  openWorldHint: true,
2940
3032
  readOnlyHint: false
2941
3033
  },
2942
- description: "Replace the text of a GitHub issue or pull request conversation comment that you posted, for example to update a progress comment. Only works on your own comments.",
3034
+ description: "Edit the text of a GitHub issue or pull request conversation comment that you posted, for example to update a progress comment. Only works on your own comments.",
2943
3035
  inputSchema: inputSchema$4,
2944
3036
  outputSchema: outputSchema$4,
2945
3037
  async execute(input, _options, { egress }) {
@@ -2985,7 +3077,7 @@ function createGitHubUpdateIssueCommentTool(botEmail) {
2985
3077
  // src/tools/update-pull-request.ts
2986
3078
  const inputSchema$3 = z.object({
2987
3079
  repo: z.string().describe("Repository in \"owner/name\" format."),
2988
- number: z.number().int().positive().describe("Pull request number."),
3080
+ pull_request: z.number().int().positive().describe("Pull request number."),
2989
3081
  title: z.string().trim().min(1).optional().describe("Replacement pull request title."),
2990
3082
  body: z.string().optional().describe(`Replacement pull request body. ${PULL_REQUEST_BODY_RULES}`),
2991
3083
  base: z.string().trim().min(1).optional().describe("Replacement base branch."),
@@ -2993,7 +3085,7 @@ const inputSchema$3 = z.object({
2993
3085
  draft: z.boolean().optional().describe("Set false to mark a draft pull request ready for review, or true to convert it back to a draft.")
2994
3086
  }).strict().refine(({ title, body, base, state, draft }) => title !== void 0 || body !== void 0 || base !== void 0 || state !== void 0 || draft !== void 0, { message: "At least one pull request field must be provided." });
2995
3087
  const draftMutationResponseSchema = z.object({ data: z.object({ result: z.object({ pullRequest: z.object({ isDraft: z.boolean() }) }) }) });
2996
- const pullRequestSchema$2 = z.object({
3088
+ const pullRequestSchema = z.object({
2997
3089
  base: z.string(),
2998
3090
  body: z.string().nullable(),
2999
3091
  draft: z.boolean(),
@@ -3003,7 +3095,7 @@ const pullRequestSchema$2 = z.object({
3003
3095
  title: z.string(),
3004
3096
  url: z.string()
3005
3097
  });
3006
- const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema$2.extend({ target: z.literal("updatePullRequest") }));
3098
+ const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema.extend({ target: z.literal("updatePullRequest") }));
3007
3099
  function nonEmptyString(value, name) {
3008
3100
  if (!value?.trim()) throw new PluginToolInputError(`${name} is required`);
3009
3101
  return value.trim();
@@ -3046,7 +3138,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3046
3138
  const requester = await resolveGitHubRequester(ctx);
3047
3139
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
3048
3140
  operation: "github.pull.get",
3049
- path: `${repoPath(repo)}/pulls/${update.number}`
3141
+ path: `${repoPath(repo)}/pulls/${update.pull_request}`
3050
3142
  }) : void 0;
3051
3143
  const payload = {
3052
3144
  ...update.title !== void 0 ? { title: update.title } : void 0,
@@ -3057,7 +3149,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3057
3149
  const hasRestUpdate = Object.keys(payload).length > 0;
3058
3150
  const response = await githubApi(ctx.egress, {
3059
3151
  operation: hasRestUpdate ? "github.pull.update" : "github.pull.get",
3060
- path: `${repoPath(repo)}/pulls/${update.number}`,
3152
+ path: `${repoPath(repo)}/pulls/${update.pull_request}`,
3061
3153
  ...hasRestUpdate ? {
3062
3154
  method: "PATCH",
3063
3155
  body: payload
@@ -3131,7 +3223,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3131
3223
  }
3132
3224
  // src/pull-request-reviews.ts
3133
3225
  const REVIEWS_PAGE_SIZE = 100;
3134
- const reviewsSchema = z.array(z.object({
3226
+ const reviewsSchema$1 = z.array(z.object({
3135
3227
  commit_id: z.string().nullable().optional(),
3136
3228
  state: z.string(),
3137
3229
  user: z.object({ login: z.string() }).nullable()
@@ -3145,7 +3237,7 @@ const reviewsSchema = z.array(z.object({
3145
3237
  async function loadLatestReviews(readPage) {
3146
3238
  const latest = /* @__PURE__ */ new Map();
3147
3239
  for (let page = 1;; page++) {
3148
- const batch = reviewsSchema.parse(await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`));
3240
+ const batch = reviewsSchema$1.parse(await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`));
3149
3241
  for (const review of batch) if (review.user && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.user.login.toLowerCase(), review);
3150
3242
  if (batch.length < REVIEWS_PAGE_SIZE) return latest;
3151
3243
  }
@@ -3327,7 +3419,7 @@ async function reviewBodyReactions(egress, input) {
3327
3419
  * approved since then is not asked. The request is optional, so a failure is
3328
3420
  * logged and does not fail the tool.
3329
3421
  */
3330
- async function requestReviewAgain(ctx, input) {
3422
+ async function requestReviewAgain$1(ctx, input) {
3331
3423
  const fields = {
3332
3424
  number: input.pullRequest,
3333
3425
  repo: `${input.owner}/${input.name}`
@@ -3425,7 +3517,7 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3425
3517
  const createPayload = createResponse.body;
3426
3518
  if (failed(createResponse)) throw new Error(`GitHub reaction creation failed with HTTP ${createResponse.status}: ${githubErrorMessage$1(createPayload)}`);
3427
3519
  }
3428
- if (status === "addressed" && reactions.changesRequestedBy) await requestReviewAgain(ctx, {
3520
+ if (status === "addressed" && reactions.changesRequestedBy) await requestReviewAgain$1(ctx, {
3429
3521
  owner: repo.owner,
3430
3522
  name: repo.name,
3431
3523
  pullRequest,
@@ -3558,7 +3650,7 @@ const reviewCommentSchema = z.object({
3558
3650
  }).strict().refine(({ start_line, start_side }) => start_line === void 0 === (start_side === void 0), { message: "start_line and start_side must be provided together." });
3559
3651
  const inputSchema = z.object({
3560
3652
  repo: z.string().describe("Repository in \"owner/name\" format."),
3561
- number: z.number().int().positive().describe("Pull request number."),
3653
+ pull_request: z.number().int().positive().describe("Pull request number."),
3562
3654
  event: z.enum(["COMMENT", "REQUEST_CHANGES"]).describe("Review result. You cannot approve pull requests."),
3563
3655
  body: z.string().trim().min(1).describe("Review summary."),
3564
3656
  comments: z.array(reviewCommentSchema).optional().describe("Optional inline review comments.")
@@ -3600,7 +3692,7 @@ const gitHubSubmitPullRequestReviewTool = definePluginTool({
3600
3692
  const response = await githubApi(egress, {
3601
3693
  operation: "github.pull.review.create",
3602
3694
  method: "POST",
3603
- path: `${repoPath(repo)}/pulls/${review.number}/reviews`,
3695
+ path: `${repoPath(repo)}/pulls/${review.pull_request}/reviews`,
3604
3696
  body: {
3605
3697
  body: review.body,
3606
3698
  event: review.event,
@@ -3616,7 +3708,7 @@ const gitHubSubmitPullRequestReviewTool = definePluginTool({
3616
3708
  return {
3617
3709
  target: "submitPullRequestReview",
3618
3710
  repo: repo.ref,
3619
- number: review.number,
3711
+ number: review.pull_request,
3620
3712
  reply: {
3621
3713
  text: review.body,
3622
3714
  url: providerResult.html_url
@@ -3755,6 +3847,8 @@ const githubPullRequestOutcomeInputSchema = z.object({
3755
3847
  pullRequestId: z.string().min(1),
3756
3848
  repositoryFullName: z.string().min(1),
3757
3849
  repositoryId: z.string().min(1),
3850
+ /** Written to Junior's code index only, not to the GitHub row. */
3851
+ size: codeChangeSizeSchema.optional(),
3758
3852
  state: githubPullRequestStateSchema,
3759
3853
  title: z.string().min(1).optional(),
3760
3854
  updatedAt: z.date()
@@ -3964,1299 +4058,1594 @@ async function releaseGitHubPullRequestReadySync(db, target, claim) {
3964
4058
  const [row] = await db.select({ requests: t.readySyncRequests }).from(t).where(claimed);
3965
4059
  return row?.requests;
3966
4060
  }
3967
- // src/pull-request-outcomes/apply.ts
3968
- /** Write a pull request outcome as a code change in Junior's code index. */
3969
- function githubCodeChange(outcome, conversationIds) {
3970
- return {
3971
- closedAt: outcome.closedAt,
3972
- conversationIds,
3973
- draft: outcome.draft,
3974
- mergedAt: outcome.mergedAt,
3975
- number: outcome.number,
3976
- openedAt: outcome.openedAt,
3977
- providerId: outcome.pullRequestId,
3978
- repository: {
3979
- name: outcome.repositoryFullName,
3980
- providerId: outcome.repositoryId,
3981
- url: `https://github.com/${outcome.repositoryFullName}`
3982
- },
3983
- state: outcome.state === "closed_unmerged" ? "closed" : outcome.state,
3984
- title: outcome.title,
3985
- updatedAt: outcome.updatedAt,
3986
- url: `https://github.com/${outcome.repositoryFullName}/pull/${outcome.number}`
3987
- };
3988
- }
4061
+ // src/merge-conflict-checks/policy.ts
4062
+ const ITEM_CLOSE_CONCURRENCY = 8;
4063
+ const DAY_MS = 864e5;
4064
+ /** Time after activity by a person in which Junior fixes conflicts. */
4065
+ const ACTIVE_MS = 2 * DAY_MS;
4066
+ /** Shortest time between two fixes of one pull request. */
4067
+ const FIX_INTERVAL_MS = DAY_MS;
4068
+ /** Fixes in a row, with no activity by a person, before Junior waits. */
4069
+ const MAX_FIXES = 3;
4070
+ /** The choice of the merge conflict item that resumes the fixes. */
4071
+ const GITHUB_CONFLICT_RESUME = "Resume";
4072
+ const actorSchema$1 = z.object({ __typename: z.string() }).nullable();
4073
+ const timelineItemSchema = z.union([
4074
+ z.object({
4075
+ __typename: z.literal("PullRequestCommit"),
4076
+ commit: z.object({
4077
+ author: z.object({ user: z.object({ login: z.string() }).nullable() }).nullable(),
4078
+ committedDate: z.string()
4079
+ })
4080
+ }),
4081
+ z.object({
4082
+ __typename: z.literal("PullRequestReview"),
4083
+ author: actorSchema$1,
4084
+ submittedAt: z.string().nullable()
4085
+ }),
4086
+ z.object({
4087
+ __typename: z.literal("IssueComment"),
4088
+ author: actorSchema$1,
4089
+ createdAt: z.string()
4090
+ }),
4091
+ z.object({
4092
+ __typename: z.literal("HeadRefForcePushedEvent"),
4093
+ actor: actorSchema$1,
4094
+ createdAt: z.string()
4095
+ })
4096
+ ]);
4097
+ const historyResponseSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4098
+ createdAt: z.string(),
4099
+ discussion: z.object({ nodes: z.array(timelineItemSchema.nullable()) }),
4100
+ pushes: z.object({ nodes: z.array(timelineItemSchema.nullable()) }),
4101
+ reviewDecision: z.string().nullable()
4102
+ }) }) }) });
3989
4103
  /**
3990
- * Record one pull request outcome. When the stored row changes, update the
3991
- * code index, and mark the chip of each linked conversation merged or closed.
3992
- * A failed chip is logged, so it does not stop the work after it.
4104
+ * Read the history from GitHub's answer. A deleted account has no author,
4105
+ * and counts as a person. Activity by a bot is not activity.
3993
4106
  */
3994
- async function applyGitHubPullRequestOutcome(args) {
3995
- const { outcome } = args;
3996
- const recorded = await recordGitHubPullRequestOutcome(args.db, outcome);
3997
- if (!recorded.applied) return recorded;
3998
- await args.codeChanges.record(githubCodeChange(outcome, recorded.conversationIds));
3999
- if (outcome.state !== "open") await updateGitHubAnnotations({
4000
- annotations: args.annotations,
4001
- conversationIds: recorded.conversationIds,
4002
- log: args.log,
4003
- update: {
4004
- repo: outcome.repositoryFullName,
4005
- number: outcome.number,
4006
- objectType: "code_change",
4007
- status: outcome.state === "merged" ? "merged" : "closed"
4107
+ function parseGitHubConflictHistory(response) {
4108
+ const pullRequest = historyResponseSchema.parse(response).data.repository.pullRequest;
4109
+ let activeAtMs = Date.parse(pullRequest.createdAt);
4110
+ const record = (bot, at) => {
4111
+ if (!bot && at) activeAtMs = Math.max(activeAtMs, Date.parse(at));
4112
+ };
4113
+ for (const item of [...pullRequest.pushes.nodes, ...pullRequest.discussion.nodes]) {
4114
+ if (!item) continue;
4115
+ switch (item.__typename) {
4116
+ case "PullRequestCommit":
4117
+ record(item.commit.author?.user?.login?.endsWith("[bot]") === true, item.commit.committedDate);
4118
+ break;
4119
+ case "HeadRefForcePushedEvent":
4120
+ record(item.actor?.__typename === "Bot", item.createdAt);
4121
+ break;
4122
+ case "PullRequestReview":
4123
+ record(item.author?.__typename === "Bot", item.submittedAt);
4124
+ break;
4125
+ case "IssueComment": record(item.author?.__typename === "Bot", item.createdAt);
4008
4126
  }
4009
- });
4010
- return recorded;
4011
- }
4012
- // src/webhooks/issue-outcome.ts
4013
- const canonicalIssueOutcomeSchema = z.object({
4014
- action: z.enum([
4015
- "opened",
4016
- "closed",
4017
- "reopened"
4018
- ]),
4019
- issue: z.object({
4020
- body: z.string().nullable().optional(),
4021
- closed_at: z.string().nullable().optional(),
4022
- created_at: z.string(),
4023
- id: z.number().int().positive(),
4024
- number: z.number().int().positive(),
4025
- state_reason: githubIssueStateReasonSchema.nullable().optional(),
4026
- updated_at: z.string(),
4027
- user: z.object({ login: z.string().min(1) }).strict()
4028
- }).strict(),
4029
- repository: z.object({
4030
- full_name: z.string().min(1),
4031
- id: z.number().int().positive()
4032
- }).strict()
4033
- }).strict();
4034
- const issueOutcomeSchema = z.object({
4035
- action: z.enum([
4036
- "opened",
4037
- "closed",
4038
- "reopened"
4039
- ]),
4040
- issue: z.object({
4041
- body: z.string().nullable().optional(),
4042
- closed_at: z.string().nullable().optional(),
4043
- created_at: z.string(),
4044
- id: z.number().int().positive(),
4045
- number: z.number().int().positive(),
4046
- state_reason: githubIssueStateReasonSchema.nullable().optional(),
4047
- updated_at: z.string(),
4048
- user: z.object({ login: z.string().min(1) }).passthrough()
4049
- }).passthrough(),
4050
- repository: z.object({
4051
- full_name: z.string().min(1),
4052
- id: z.number().int().positive()
4053
- }).passthrough()
4054
- }).passthrough().transform((provider) => canonicalIssueOutcomeSchema.parse({
4055
- action: provider.action,
4056
- issue: {
4057
- body: provider.issue.body,
4058
- closed_at: provider.issue.closed_at,
4059
- created_at: provider.issue.created_at,
4060
- id: provider.issue.id,
4061
- number: provider.issue.number,
4062
- state_reason: provider.issue.state_reason,
4063
- updated_at: provider.issue.updated_at,
4064
- user: { login: provider.issue.user.login }
4065
- },
4066
- repository: {
4067
- full_name: provider.repository.full_name,
4068
- id: provider.repository.id
4069
4127
  }
4070
- }));
4071
- const issueLifecycleActionSchema = z.object({ action: z.string() }).passthrough();
4072
- /** Parse a provider timestamp, rejecting missing or invalid lifecycle values. */
4073
- function timestamp$1(value) {
4074
- if (!value) return void 0;
4075
- const parsed = new Date(value);
4076
- return Number.isFinite(parsed.getTime()) ? parsed : void 0;
4077
- }
4078
- /** Normalize only the fields required for the Junior-owned issue projection. */
4079
- function normalizeGitHubIssueOutcome(args) {
4080
- const lifecycle = issueLifecycleActionSchema.safeParse(args.body);
4081
- if (!lifecycle.success || ![
4082
- "opened",
4083
- "closed",
4084
- "reopened"
4085
- ].includes(lifecycle.data.action)) return;
4086
- const parsed = issueOutcomeSchema.parse(args.body);
4087
- const issue = parsed.issue;
4088
- const openedAt = timestamp$1(issue.created_at);
4089
- const updatedAt = timestamp$1(issue.updated_at);
4090
- if (!openedAt || !updatedAt) throw new Error("GitHub issue lifecycle timestamps are invalid");
4091
- if (parsed.action === "opened" && !botLoginFromEmail(args.botEmail)) throw new Error("The configured GitHub App bot email must encode a [bot] login in GitHub's noreply format to classify issue ownership");
4092
- const candidateOwned = Boolean(isBotLogin(issue.user.login, args.botEmail) && issue.body?.includes("<!-- junior-session-footer:start -->")) && (parsed.action === "opened" || parsed.action === "closed");
4093
- const closedAt = timestamp$1(issue.closed_at);
4094
- if (parsed.action === "closed" && !closedAt) throw new Error("GitHub issue terminal timestamp is invalid");
4095
4128
  return {
4096
- candidateOwned,
4097
- closedAt,
4098
- issueId: String(issue.id),
4099
- number: issue.number,
4100
- openedAt,
4101
- repositoryFullName: parsed.repository.full_name,
4102
- repositoryId: String(parsed.repository.id),
4103
- state: parsed.action === "closed" ? "closed" : "open",
4104
- stateReason: parsed.action === "closed" ? issue.state_reason ?? void 0 : void 0,
4105
- updatedAt
4129
+ activeAtMs,
4130
+ approved: pullRequest.reviewDecision === "APPROVED"
4106
4131
  };
4107
4132
  }
4108
- const canonicalIssueConversationSchema = z.object({
4109
- issue: z.object({
4110
- body: z.string().nullable().optional(),
4111
- id: z.number().int().positive(),
4112
- user: z.object({ login: z.string().min(1) }).strict()
4113
- }).strict(),
4114
- sender: z.object({ login: z.string().min(1) }).strict().optional()
4115
- }).strict();
4116
- const issueConversationSchema = z.object({
4117
- issue: z.object({
4118
- body: z.string().nullable().optional(),
4119
- id: z.number().int().positive(),
4120
- user: z.object({ login: z.string().min(1) }).passthrough()
4121
- }).passthrough(),
4122
- sender: z.object({ login: z.string().min(1) }).passthrough().optional()
4123
- }).passthrough().transform((provider) => canonicalIssueConversationSchema.parse({
4124
- issue: {
4125
- body: provider.issue.body,
4126
- id: provider.issue.id,
4127
- user: { login: provider.issue.user.login }
4128
- },
4129
- ...provider.sender ? { sender: { login: provider.sender.login } } : void 0
4130
- }));
4131
- /** Normalize native conversation ids written to a Junior-owned issue by its bot. */
4132
- function normalizeGitHubIssueConversations(args) {
4133
- const parsed = issueConversationSchema.safeParse(args.body);
4134
- if (!parsed.success) return void 0;
4135
- if (!isBotLogin(parsed.data.issue.user.login, args.botEmail)) return;
4136
- const sender = parsed.data.sender;
4137
- if (sender && !isBotLogin(sender.login, args.botEmail)) return void 0;
4138
- const conversationIds = githubConversationIds(parsed.data.issue.body);
4139
- return conversationIds.length > 0 ? {
4140
- conversationIds,
4141
- issueId: String(parsed.data.issue.id)
4133
+ /**
4134
+ * Add a fix that Junior started to the stored fixes. A second fix of one
4135
+ * head commit replaces the first. Only the latest `MAX_FIXES` matter.
4136
+ */
4137
+ function withGitHubConflictFix(fixes, fix) {
4138
+ return [...fixes.filter(({ headSha }) => headSha !== fix.headSha), fix].slice(-3);
4139
+ }
4140
+ /** Decide what a conflict on one open Junior pull request does. */
4141
+ function gitHubConflictAction(input) {
4142
+ const { askedAtMs, fixes, nowMs, resumedAtMs } = input;
4143
+ const { approved } = input.history;
4144
+ const activeAtMs = Math.max(input.history.activeAtMs, resumedAtMs ?? 0);
4145
+ if (nowMs - activeAtMs > ACTIVE_MS && !approved) return "skip";
4146
+ const resuming = resumedAtMs === activeAtMs && fixes.every(({ atMs }) => atMs < resumedAtMs);
4147
+ const started = resuming ? resumedAtMs : fixes.find(({ headSha }) => headSha === input.headSha)?.atMs;
4148
+ if (started !== void 0) {
4149
+ if (nowMs - started >= FIX_INTERVAL_MS) return askedAtMs !== void 0 && askedAtMs > (resumedAtMs ?? 0) ? "skip" : "ask";
4150
+ return resuming || started === resumedAtMs ? "skip" : "retry";
4151
+ }
4152
+ if (fixes.filter(({ atMs }) => atMs >= activeAtMs).length >= MAX_FIXES) return "skip";
4153
+ const fixedAtMs = Math.max(resumedAtMs ?? 0, ...fixes.map(({ atMs }) => atMs));
4154
+ return !approved && nowMs - fixedAtMs < FIX_INTERVAL_MS ? "skip" : "fix";
4155
+ }
4156
+ const ITEM_KEY_PREFIX = "merge-conflict:";
4157
+ /** The dedupe key of the merge conflict item of one pull request. */
4158
+ function gitHubConflictItemKey(ref) {
4159
+ return `${ITEM_KEY_PREFIX}${ref.repositoryFullName.toLowerCase()}#${ref.number}`;
4160
+ }
4161
+ /** Read the pull request of a merge conflict item's dedupe key. */
4162
+ function parseGitHubConflictItemKey(dedupeKey) {
4163
+ const match = /^([^/#\s]+\/[^/#\s]+)#(\d+)$/.exec(dedupeKey.startsWith(ITEM_KEY_PREFIX) ? dedupeKey.slice(15) : "");
4164
+ return match ? {
4165
+ number: Number(match[2]),
4166
+ repositoryFullName: match[1]
4142
4167
  } : void 0;
4143
4168
  }
4144
- // src/webhooks/pull-request-outcome.ts
4145
- const pullRequestLifecycleActionsSchema = z.enum([
4146
- "opened",
4147
- "closed",
4148
- "reopened",
4149
- "ready_for_review",
4150
- "converted_to_draft"
4151
- ]);
4152
- const canonicalPullRequestOutcomeSchema = z.object({
4153
- action: pullRequestLifecycleActionsSchema,
4154
- pull_request: z.object({
4155
- body: z.string().nullable().optional(),
4156
- closed_at: z.string().nullable().optional(),
4157
- created_at: z.string(),
4158
- draft: z.boolean().optional(),
4159
- id: z.number().int().positive(),
4160
- merged: z.boolean(),
4161
- merged_at: z.string().nullable().optional(),
4162
- number: z.number().int().positive(),
4163
- title: z.string().min(1).optional(),
4164
- updated_at: z.string(),
4165
- user: z.object({ login: z.string().min(1) }).strict()
4166
- }).strict(),
4167
- repository: z.object({
4168
- full_name: z.string().min(1),
4169
- id: z.number().int().positive()
4170
- }).strict()
4171
- }).strict();
4172
- const pullRequestOutcomeSchema = z.object({
4173
- action: pullRequestLifecycleActionsSchema,
4174
- pull_request: z.object({
4175
- body: z.string().nullable().optional(),
4176
- closed_at: z.string().nullable().optional(),
4177
- created_at: z.string(),
4178
- draft: z.boolean().optional(),
4179
- id: z.number().int().positive(),
4180
- merged: z.boolean(),
4181
- merged_at: z.string().nullable().optional(),
4182
- number: z.number().int().positive(),
4183
- title: z.string().min(1).optional(),
4184
- updated_at: z.string(),
4185
- user: z.object({ login: z.string().min(1) }).passthrough()
4186
- }).passthrough(),
4187
- repository: z.object({
4188
- full_name: z.string().min(1),
4189
- id: z.number().int().positive()
4190
- }).passthrough()
4191
- }).passthrough().transform((provider) => canonicalPullRequestOutcomeSchema.parse({
4192
- action: provider.action,
4193
- pull_request: {
4194
- body: provider.pull_request.body,
4195
- closed_at: provider.pull_request.closed_at,
4196
- created_at: provider.pull_request.created_at,
4197
- draft: provider.pull_request.draft,
4198
- id: provider.pull_request.id,
4199
- merged: provider.pull_request.merged,
4200
- merged_at: provider.pull_request.merged_at,
4201
- number: provider.pull_request.number,
4202
- title: provider.pull_request.title,
4203
- updated_at: provider.pull_request.updated_at,
4204
- user: { login: provider.pull_request.user.login }
4205
- },
4206
- repository: {
4207
- full_name: provider.repository.full_name,
4208
- id: provider.repository.id
4169
+ /** Ask the requester to resume a fix that did not land. */
4170
+ async function addUnlandedItem(args) {
4171
+ const { conflict, ref, title } = args;
4172
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
4173
+ numbers: [ref.number],
4174
+ repositoryFullName: ref.repositoryFullName
4175
+ })).get(ref.number);
4176
+ if (!opener?.conversationId) return;
4177
+ const url = conflict.url ?? `https://github.com/${ref.repositoryFullName}/pull/${ref.number}`;
4178
+ await args.reviewItems.forConversation(opener.conversationId).upsert({
4179
+ assigneeIdentityIds: [opener.identityId],
4180
+ body: `#${ref.number} conflicts with \`${conflict.baseBranch}\`, and the last fix did not land. Resume tries again. Dismiss stops these asks for this pull request.`,
4181
+ choices: [{ label: GITHUB_CONFLICT_RESUME }],
4182
+ dedupeKey: gitHubConflictItemKey(ref),
4183
+ subject: {
4184
+ id: url,
4185
+ title: title ? `${title} (#${ref.number})` : url,
4186
+ url
4187
+ },
4188
+ title: `Merge conflict · #${ref.number}`
4189
+ });
4190
+ }
4191
+ /**
4192
+ * Return the merge conflict events to publish for one conflicted pull
4193
+ * request that a Watch or event automation wants. A fix returns `events`.
4194
+ * An ask adds the Review item and returns no events. The item is optional,
4195
+ * so a failure is logged, and the next check tries again.
4196
+ */
4197
+ async function applyGitHubConflictPolicy(args) {
4198
+ if (args.draft) return [];
4199
+ const t = juniorGitHubPullRequests;
4200
+ const [row] = await args.db.select({
4201
+ askedAt: t.conflictFixAskedAt,
4202
+ fixes: t.conflictFixes,
4203
+ resumedAt: t.conflictFixesResumedAt
4204
+ }).from(t).where(and(pullRequestRow(args.ref), eq(t.state, "open"))).limit(1);
4205
+ if (!row) return args.events;
4206
+ const nowMs = args.now.getTime();
4207
+ const action = gitHubConflictAction({
4208
+ askedAtMs: row.askedAt?.getTime(),
4209
+ fixes: row.fixes,
4210
+ headSha: args.conflict.headSha,
4211
+ history: parseGitHubConflictHistory(await args.loadHistory(args.ref)),
4212
+ nowMs,
4213
+ resumedAtMs: row.resumedAt?.getTime()
4214
+ });
4215
+ if (action === "skip") return [];
4216
+ if (action === "retry") return args.events;
4217
+ if (action === "fix") {
4218
+ await args.db.update(t).set({ conflictFixes: withGitHubConflictFix(row.fixes, {
4219
+ atMs: nowMs,
4220
+ headSha: args.conflict.headSha
4221
+ }) }).where(pullRequestRow(args.ref));
4222
+ return args.events;
4209
4223
  }
4210
- }));
4211
- const pullRequestLifecycleActionSchema = z.object({ action: z.string() }).passthrough();
4212
- const canonicalPullRequestConversationSchema = z.object({
4213
- pull_request: z.object({
4214
- body: z.string().nullable().optional(),
4215
- id: z.number().int().positive(),
4216
- user: z.object({ login: z.string().min(1) }).strict()
4217
- }).strict(),
4218
- repository: z.object({ full_name: z.string().min(1) }).strict(),
4219
- sender: z.object({ login: z.string().min(1) }).strict()
4220
- }).strict();
4221
- const pullRequestConversationSchema = z.object({
4222
- pull_request: z.object({
4223
- body: z.string().nullable().optional(),
4224
- id: z.number().int().positive(),
4225
- user: z.object({ login: z.string().min(1) }).passthrough()
4226
- }).passthrough(),
4227
- repository: z.object({ full_name: z.string().min(1) }).passthrough(),
4228
- sender: z.object({ login: z.string().min(1) }).passthrough()
4229
- }).passthrough().transform((provider) => canonicalPullRequestConversationSchema.parse({
4230
- pull_request: {
4231
- body: provider.pull_request.body,
4232
- id: provider.pull_request.id,
4233
- user: { login: provider.pull_request.user.login }
4234
- },
4235
- repository: { full_name: provider.repository.full_name },
4236
- sender: { login: provider.sender.login }
4237
- }));
4238
- /** Parse a provider timestamp. A missing or invalid value is undefined. */
4239
- function timestamp(value) {
4240
- if (!value) return void 0;
4241
- const parsed = new Date(value);
4242
- return Number.isFinite(parsed.getTime()) ? parsed : void 0;
4224
+ try {
4225
+ await addUnlandedItem(args);
4226
+ await args.db.update(t).set({ conflictFixAskedAt: args.now }).where(pullRequestRow(args.ref));
4227
+ } catch (error) {
4228
+ logFailOpenFailure(args.log, "GitHub merge conflict item failed", error, {
4229
+ number: args.ref.number,
4230
+ repository: args.ref.repositoryFullName
4231
+ });
4232
+ }
4233
+ return [];
4243
4234
  }
4244
- /** Normalize only the fields required for the Junior-owned PR projection. */
4245
- function normalizeGitHubPullRequestOutcome(args) {
4246
- const lifecycle = pullRequestLifecycleActionSchema.safeParse(args.body);
4247
- if (!lifecycle.success || !pullRequestLifecycleActionsSchema.safeParse(lifecycle.data.action).success) return;
4248
- const parsed = pullRequestOutcomeSchema.parse(args.body);
4249
- const pullRequest = parsed.pull_request;
4250
- const openedAt = timestamp(pullRequest.created_at);
4251
- const updatedAt = timestamp(pullRequest.updated_at);
4252
- if (!openedAt || !updatedAt) throw new Error("GitHub pull request lifecycle timestamps are invalid");
4253
- if (parsed.action === "opened" && !botLoginFromEmail(args.botEmail)) throw new Error("The configured GitHub App bot email must encode a [bot] login in GitHub's noreply format to classify pull request ownership");
4254
- const candidateOwned = Boolean(isBotLogin(pullRequest.user.login, args.botEmail) && pullRequest.body?.includes("<!-- junior-session-footer:start -->")) && (parsed.action === "opened" || parsed.action === "closed");
4255
- const state = parsed.action !== "closed" ? "open" : pullRequest.merged ? "merged" : "closed_unmerged";
4256
- const closed = parsed.action === "closed";
4257
- const closedAt = timestamp(pullRequest.closed_at) ?? (closed ? updatedAt : void 0);
4258
- const mergedAt = timestamp(pullRequest.merged_at) ?? (closed && pullRequest.merged ? updatedAt : void 0);
4235
+ /** Why a merge conflict item closes when GitHub reports no conflict. */
4236
+ const GITHUB_CONFLICT_GONE_REASON = "The pull request no longer has merge conflicts.";
4237
+ /**
4238
+ * Close the merge conflict item of one Junior pull request. Throws
4239
+ * when the Inbox fails, so a caller with no later check can try again.
4240
+ */
4241
+ async function closeGitHubConflictItem(args) {
4242
+ const { ref } = args;
4243
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
4244
+ numbers: [ref.number],
4245
+ repositoryFullName: ref.repositoryFullName
4246
+ })).get(ref.number);
4247
+ if (!opener?.conversationId) return;
4248
+ await args.reviewItems.forConversation(opener.conversationId).close({
4249
+ dedupeKey: gitHubConflictItemKey(ref),
4250
+ reason: args.reason,
4251
+ status: args.status
4252
+ });
4253
+ }
4254
+ /**
4255
+ * Close the merge conflict items of some Junior pull requests, such
4256
+ * as ones that GitHub reports as mergeable. An item is optional, so a failed
4257
+ * close is logged, and the next check closes it again.
4258
+ */
4259
+ async function closeGitHubConflictItems(args) {
4260
+ if (args.numbers.length === 0) return;
4261
+ const { repositoryFullName } = args;
4262
+ const openers = await listGitHubPullRequestOpeners(args.db, {
4263
+ numbers: args.numbers,
4264
+ repositoryFullName
4265
+ });
4266
+ const limit = pLimit(ITEM_CLOSE_CONCURRENCY);
4267
+ const close = async (number, conversationId) => {
4268
+ try {
4269
+ await args.reviewItems.forConversation(conversationId).close({
4270
+ dedupeKey: gitHubConflictItemKey({
4271
+ number,
4272
+ repositoryFullName
4273
+ }),
4274
+ reason: args.reason,
4275
+ status: args.status
4276
+ });
4277
+ } catch (error) {
4278
+ logFailOpenFailure(args.log, "GitHub merge conflict item close failed", error, {
4279
+ number,
4280
+ repository: repositoryFullName
4281
+ });
4282
+ }
4283
+ };
4284
+ await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
4285
+ }
4286
+ // src/webhooks/installation-requests.ts
4287
+ function splitRepository(fullName, label) {
4288
+ const [owner, name, ...extra] = fullName.split("/");
4289
+ if (!owner || !name || extra.length > 0) throw new Error(`GitHub ${label} received an invalid repository name`);
4259
4290
  return {
4260
- candidateOwned,
4261
- closedAt,
4262
- draft: closed ? void 0 : pullRequest.draft,
4263
- mergedAt,
4264
- number: pullRequest.number,
4265
- openedAt,
4266
- pullRequestId: String(pullRequest.id),
4267
- repositoryFullName: parsed.repository.full_name,
4268
- repositoryId: String(parsed.repository.id),
4269
- state,
4270
- title: pullRequest.title,
4271
- updatedAt
4291
+ owner,
4292
+ name
4272
4293
  };
4273
4294
  }
4274
- /** Normalize native conversation ids written to a Junior-owned PR by its bot. */
4275
- function normalizeGitHubPullRequestConversations(args) {
4276
- const parsed = pullRequestConversationSchema.safeParse(args.body);
4277
- if (!parsed.success) return void 0;
4278
- if (!isBotLogin(parsed.data.pull_request.user.login, args.botEmail) || !isBotLogin(parsed.data.sender.login, args.botEmail)) return;
4279
- const conversationIds = githubConversationIds(parsed.data.pull_request.body);
4280
- return conversationIds.length > 0 ? {
4281
- conversationIds,
4282
- pullRequestId: String(parsed.data.pull_request.id)
4283
- } : void 0;
4295
+ /** Return a reader for pages of a pull request's commits, with a read-only token. */
4296
+ async function loadPullRequestCommitPages(env, pullRequest) {
4297
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request commits");
4298
+ const token = await issueInstallationToken({
4299
+ ...env,
4300
+ permissions: { pull_requests: "read" },
4301
+ repositories: [name]
4302
+ });
4303
+ return async (page, perPage) => await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}/commits?per_page=${perPage}&page=${page}`, { token: token.token });
4284
4304
  }
4285
- /** Normalize linked issues written into a Junior-owned PR body by its bot. */
4286
- function normalizeGitHubPullRequestLinkedIssues(args) {
4287
- const parsed = pullRequestConversationSchema.safeParse(args.body);
4288
- if (!parsed.success) return void 0;
4289
- if (!isBotLogin(parsed.data.pull_request.user.login, args.botEmail) || !isBotLogin(parsed.data.sender.login, args.botEmail)) return;
4290
- const linkedIssues = githubLinkedIssues(parsed.data.pull_request.body, parsed.data.repository.full_name);
4291
- return linkedIssues.length > 0 ? {
4292
- linkedIssues,
4293
- pullRequestId: String(parsed.data.pull_request.id)
4294
- } : void 0;
4305
+ /** Read one pull request, with a read-only token. */
4306
+ async function loadPullRequest(env, pullRequest) {
4307
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request");
4308
+ const token = await issueInstallationToken({
4309
+ ...env,
4310
+ permissions: { pull_requests: "read" },
4311
+ repositories: [name]
4312
+ });
4313
+ return await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}`, { token: token.token });
4295
4314
  }
4296
- // src/webhooks/pull-request-activity.ts
4297
- const timestampSchema = z.iso.datetime({ offset: true });
4298
- const numberSchema = z.number().int().positive();
4299
- const repositorySchema$1 = z.object({ id: numberSchema });
4300
- const senderSchema = z.object({ type: z.string() });
4301
- const activitySchemas = {
4302
- issue_comment: z.object({
4303
- action: z.literal("created"),
4304
- comment: z.object({ created_at: timestampSchema }),
4305
- issue: z.object({
4306
- number: numberSchema,
4307
- pull_request: z.object({})
4308
- }),
4309
- repository: repositorySchema$1,
4310
- sender: senderSchema
4311
- }).transform((event) => ({
4312
- at: new Date(event.comment.created_at),
4313
- number: event.issue.number,
4314
- repositoryProviderId: String(event.repository.id),
4315
- senderType: event.sender.type
4316
- })),
4317
- pull_request: z.object({
4318
- action: z.literal("synchronize"),
4319
- pull_request: z.object({
4320
- number: numberSchema,
4321
- updated_at: timestampSchema
4322
- }),
4323
- repository: repositorySchema$1,
4324
- sender: senderSchema
4325
- }).transform((event) => ({
4326
- at: new Date(event.pull_request.updated_at),
4327
- number: event.pull_request.number,
4328
- repositoryProviderId: String(event.repository.id),
4329
- senderType: event.sender.type
4330
- })),
4331
- pull_request_review: z.object({
4332
- action: z.literal("submitted"),
4333
- pull_request: z.object({ number: numberSchema }),
4334
- repository: repositorySchema$1,
4335
- review: z.object({ submitted_at: timestampSchema }),
4336
- sender: senderSchema
4337
- }).transform((event) => ({
4338
- at: new Date(event.review.submitted_at),
4339
- number: event.pull_request.number,
4340
- repositoryProviderId: String(event.repository.id),
4341
- senderType: event.sender.type
4342
- })),
4343
- pull_request_review_comment: z.object({
4344
- action: z.literal("created"),
4345
- comment: z.object({ created_at: timestampSchema }),
4346
- pull_request: z.object({ number: numberSchema }),
4347
- repository: repositorySchema$1,
4348
- sender: senderSchema
4349
- }).transform((event) => ({
4350
- at: new Date(event.comment.created_at),
4351
- number: event.pull_request.number,
4352
- repositoryProviderId: String(event.repository.id),
4353
- senderType: event.sender.type
4354
- }))
4315
+ /** GitHub cannot reach a repository: it is gone, or the installation lost it. */
4316
+ var GitHubRepositoryUnreachableError = class extends Error {
4317
+ constructor(repositoryId) {
4318
+ super(`GitHub repository ${repositoryId} is not reachable`);
4319
+ this.name = "GitHubRepositoryUnreachableError";
4320
+ }
4355
4321
  };
4356
- /** Read a person's pull request activity from a webhook, if it has any. */
4357
- function normalizeGitHubPullRequestActivity(input) {
4358
- const parsed = (Object.hasOwn(activitySchemas, input.eventName) ? activitySchemas[input.eventName] : void 0)?.safeParse(input.body);
4359
- if (!parsed?.success) return void 0;
4360
- const { senderType, ...activity } = parsed.data;
4361
- return senderType === "Bot" ? void 0 : activity;
4362
- }
4363
- // src/webhooks/pull-request-preview.ts
4364
- const previewWebhookSchema = z.object({
4365
- action: z.enum([
4366
- "opened",
4367
- "edited",
4368
- "synchronize",
4369
- "ready_for_review"
4370
- ]),
4371
- pull_request: z.object({
4372
- body: z.string().nullable().optional(),
4373
- id: z.number().int().positive(),
4374
- number: z.number().int().positive(),
4375
- updated_at: z.iso.datetime({ offset: true })
4376
- }),
4377
- repository: z.object({ full_name: z.string().min(1) })
4378
- });
4322
+ const UNREACHABLE_REPOSITORY_MESSAGE = /does not exist or is not accessible/i;
4379
4323
  /**
4380
- * Set or clear the preview image fact on each chip of a Junior pull request
4381
- * from the webhook body. One failed conversation does not stop the others.
4324
+ * Read the lifecycle of some pull requests of one repository in one GraphQL
4325
+ * query, with a read-only token. Each pull request has the alias `pr<index>`.
4326
+ * The repository is found by its id, because a rename changes its name.
4382
4327
  */
4383
- async function refreshGitHubPullRequestPreview(args) {
4384
- const parsed = previewWebhookSchema.safeParse(args.body);
4385
- if (!parsed.success) return;
4386
- const { pull_request: pullRequest, repository } = parsed.data;
4387
- const conversationIds = await readGitHubPullRequestConversationIds(args.db, String(pullRequest.id));
4388
- if (conversationIds.length === 0) return;
4389
- const key = `${repository.full_name.toLowerCase()}#${pullRequest.number}`;
4390
- const previewImageUrls = githubPreviewImageUrls(pullRequest.body);
4391
- const updatedAt = Date.parse(pullRequest.updated_at);
4392
- const limit = pLimit(8);
4393
- const results = await Promise.allSettled(conversationIds.map((conversationId) => limit(async () => {
4394
- const store = args.annotations.forConversation(conversationId);
4395
- const current = (await store.list()).find((annotation) => annotation.key === key);
4396
- if (current?.kind !== "object" || current.facts?.type !== "code_change") return;
4397
- const storedAt = current.sourceUpdatedAt ? Date.parse(current.sourceUpdatedAt) : void 0;
4398
- if (storedAt !== void 0 && storedAt > updatedAt) return;
4399
- const { plugin: _plugin, createdAt: _createdAt, updatedAt: _updatedAt, facts: { previewImageUrls: previous, ...facts }, ...annotation } = current;
4400
- const next = withGitHubPreviewImages(facts, previewImageUrls);
4401
- if (previous?.join("\n") === next.previewImageUrls?.join("\n") && storedAt === updatedAt) return;
4402
- await store.upsert({
4403
- ...annotation,
4404
- facts: next,
4405
- sourceUpdatedAt: pullRequest.updated_at
4406
- });
4407
- })));
4408
- for (const result of results) {
4409
- if (result.status === "fulfilled") continue;
4410
- args.log?.error("GitHub pull request preview update failed", {
4411
- errorType: result.reason instanceof Error ? result.reason.name : "UnknownError",
4412
- number: pullRequest.number,
4413
- repository: repository.full_name
4328
+ async function loadPullRequestLifecycles(env, input) {
4329
+ let token;
4330
+ try {
4331
+ token = await issueInstallationToken({
4332
+ ...env,
4333
+ permissions: { pull_requests: "read" },
4334
+ repositoryIds: [input.repositoryId]
4414
4335
  });
4336
+ } catch (error) {
4337
+ if (error instanceof GitHubRequestError && error.status === 422 && UNREACHABLE_REPOSITORY_MESSAGE.test(error.message)) throw new GitHubRepositoryUnreachableError(input.repositoryId);
4338
+ throw error;
4415
4339
  }
4416
- }
4417
- // src/merge-conflict-checks/policy.ts
4418
- const NOTICE_CLOSE_CONCURRENCY = 8;
4419
- const DAY_MS = 864e5;
4420
- /** Time after activity by a person in which Junior fixes conflicts. */
4421
- const ACTIVE_MS = 2 * DAY_MS;
4422
- /** Time after activity by a person after which conflicts do nothing. */
4423
- const IDLE_MS = 3 * DAY_MS;
4424
- /** Shortest time between two fixes of one pull request. */
4425
- const FIX_INTERVAL_MS = DAY_MS;
4426
- /** Fixes of one pull request before Junior only adds the notice. */
4427
- const MAX_FIXES = 3;
4428
- const actorSchema = z.object({ __typename: z.string() }).nullable();
4429
- const timelineItemSchema = z.union([
4430
- z.object({
4431
- __typename: z.literal("PullRequestCommit"),
4432
- commit: z.object({
4433
- author: z.object({ user: z.object({ login: z.string() }).nullable() }).nullable(),
4434
- committedDate: z.string(),
4435
- parents: z.object({ totalCount: z.number() })
4436
- })
4437
- }),
4438
- z.object({
4439
- __typename: z.literal("PullRequestReview"),
4440
- author: actorSchema,
4441
- submittedAt: z.string().nullable()
4442
- }),
4443
- z.object({
4444
- __typename: z.literal("IssueComment"),
4445
- author: actorSchema,
4446
- createdAt: z.string()
4447
- }),
4448
- z.object({
4449
- __typename: z.literal("HeadRefForcePushedEvent"),
4450
- actor: actorSchema,
4451
- createdAt: z.string()
4452
- })
4453
- ]);
4454
- const historyResponseSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4455
- createdAt: z.string(),
4456
- discussion: z.object({ nodes: z.array(timelineItemSchema.nullable()) }),
4457
- pushes: z.object({ nodes: z.array(timelineItemSchema.nullable()) }),
4458
- reviewDecision: z.string().nullable()
4459
- }) }) }) });
4460
- /**
4461
- * Read the history from GitHub's answer. A deleted account has no author,
4462
- * and counts as a person.
4463
- */
4464
- function parseGitHubConflictHistory(response) {
4465
- const pullRequest = historyResponseSchema.parse(response).data.repository.pullRequest;
4466
- let activeAtMs = Date.parse(pullRequest.createdAt);
4467
- let fixedAtMs;
4468
- let fixes = 0;
4469
- const record = (bot, fix, at) => {
4470
- if (!at) return;
4471
- const atMs = Date.parse(at);
4472
- if (!bot) activeAtMs = Math.max(activeAtMs, atMs);
4473
- else if (fix) {
4474
- fixes += 1;
4475
- fixedAtMs = Math.max(fixedAtMs ?? 0, atMs);
4476
- }
4477
- };
4478
- for (const item of [...pullRequest.pushes.nodes, ...pullRequest.discussion.nodes]) {
4479
- if (!item) continue;
4480
- switch (item.__typename) {
4481
- case "PullRequestCommit": {
4482
- const login = item.commit.author?.user?.login;
4483
- record(login?.endsWith("[bot]") === true, item.commit.parents.totalCount > 1, item.commit.committedDate);
4484
- break;
4340
+ const { owner, name } = splitRepository(z.object({ full_name: z.string().min(1) }).parse(await githubRequest("https://api.github.com", `/repositories/${input.repositoryId}`, { token: token.token })).full_name, "pull request lifecycle");
4341
+ return await githubRequest("https://api.github.com", "/graphql", {
4342
+ body: {
4343
+ ...pullRequestLifecycles(input.numbers.length),
4344
+ variables: {
4345
+ name,
4346
+ owner,
4347
+ ...Object.fromEntries(input.numbers.map((number, index) => [`n${index}`, number]))
4485
4348
  }
4486
- case "HeadRefForcePushedEvent":
4487
- record(item.actor?.__typename === "Bot", true, item.createdAt);
4488
- break;
4489
- case "PullRequestReview":
4490
- record(item.author?.__typename === "Bot", false, item.submittedAt);
4491
- break;
4492
- case "IssueComment": record(item.author?.__typename === "Bot", false, item.createdAt);
4493
- }
4494
- }
4495
- return {
4496
- activeAtMs,
4497
- approved: pullRequest.reviewDecision === "APPROVED",
4498
- fixes,
4499
- ...fixedAtMs === void 0 ? void 0 : { fixedAtMs }
4500
- };
4501
- }
4502
- /** Decide what a conflict on one open Junior pull request does. */
4503
- function gitHubConflictAction(history, nowMs) {
4504
- const { approved, fixedAtMs } = history;
4505
- const idleMs = nowMs - history.activeAtMs;
4506
- if (idleMs > IDLE_MS && !approved) return "skip";
4507
- if ((idleMs <= ACTIVE_MS || approved) && history.fixes < MAX_FIXES) return !approved && fixedAtMs !== void 0 && nowMs - fixedAtMs < FIX_INTERVAL_MS ? "skip" : "fix";
4508
- return "notice";
4509
- }
4510
- /** The dedupe key of the merge conflict notice of one pull request. */
4511
- function gitHubConflictNoticeKey(ref) {
4512
- return `merge-conflict:${ref.repositoryFullName.toLowerCase()}#${ref.number}`;
4513
- }
4514
- async function addNotice(args, fixes) {
4515
- const { conflict, ref, title } = args;
4516
- const opener = (await listGitHubPullRequestOpeners(args.db, {
4517
- numbers: [ref.number],
4518
- repositoryFullName: ref.repositoryFullName
4519
- })).get(ref.number);
4520
- if (!opener?.conversationId) return;
4521
- const url = conflict.url ?? `https://github.com/${ref.repositoryFullName}/pull/${ref.number}`;
4522
- const name = title ? `**${title}**` : "This pull request";
4523
- const reason = fixes >= MAX_FIXES ? `conflicts were already fixed ${fixes} times` : "nobody worked on it in the last 2 days";
4524
- await args.reviewItems.forConversation(opener.conversationId).upsert({
4525
- assigneeIdentityIds: [opener.identityId],
4526
- body: `${name} has merge conflicts with \`${conflict.baseBranch}\`. Automatic fixes stopped, because ${reason}. If they are still there, ask in this thread to fix them: ${url}`,
4527
- dedupeKey: gitHubConflictNoticeKey(ref),
4528
- subject: {
4529
- id: url,
4530
- title: title ? `${title} (#${ref.number})` : url,
4531
- url
4532
4349
  },
4533
- title: `Merge conflict · #${ref.number}`
4350
+ method: "POST",
4351
+ token: token.token
4534
4352
  });
4535
4353
  }
4536
4354
  /**
4537
- * Return the merge conflict events to publish for one conflicted pull
4538
- * request that a Watch or event automation wants. A fix returns `events`.
4539
- * A notice goes to the review desk and returns no events. The notice is
4540
- * optional, so a failure is logged, and the next check tries again.
4541
- */
4542
- async function applyGitHubConflictPolicy(args) {
4543
- if (args.draft) return [];
4544
- const t = juniorGitHubPullRequests;
4545
- const [row] = await args.db.select({ pullRequestId: t.pullRequestId }).from(t).where(and(pullRequestRow(args.ref), eq(t.state, "open"))).limit(1);
4546
- if (!row) return args.events;
4547
- const history = parseGitHubConflictHistory(await args.loadHistory(args.ref));
4548
- const action = gitHubConflictAction(history, args.now.getTime());
4549
- if (action === "fix") return args.events;
4550
- if (action === "notice") try {
4551
- await addNotice(args, history.fixes);
4552
- } catch (error) {
4553
- logFailOpenFailure(args.log, "GitHub merge conflict notice failed", error, {
4554
- number: args.ref.number,
4555
- repository: args.ref.repositoryFullName
4556
- });
4557
- }
4558
- return [];
4559
- }
4560
- /** Why a merge conflict notice closes when GitHub reports no conflict. */
4561
- const GITHUB_CONFLICT_GONE_REASON = "The pull request no longer has merge conflicts.";
4562
- /**
4563
- * Close the merge conflict notice of one Junior pull request. Throws when
4564
- * the review desk fails, so a caller with no later check can try again.
4355
+ * Read one page of a repository's open pull requests by one author, with
4356
+ * their mergeability, through GraphQL search and a read-only token.
4565
4357
  */
4566
- async function closeGitHubConflictNotice(args) {
4567
- const { ref } = args;
4568
- const opener = (await listGitHubPullRequestOpeners(args.db, {
4569
- numbers: [ref.number],
4570
- repositoryFullName: ref.repositoryFullName
4571
- })).get(ref.number);
4572
- if (!opener?.conversationId) return;
4573
- await args.reviewItems.forConversation(opener.conversationId).close({
4574
- dedupeKey: gitHubConflictNoticeKey(ref),
4575
- reason: args.reason,
4576
- status: args.status
4358
+ async function searchOpenPullRequestMergeability(env, input) {
4359
+ const { name } = splitRepository(input.repositoryFullName, "pull request mergeability");
4360
+ const token = await issueInstallationToken({
4361
+ ...env,
4362
+ permissions: { pull_requests: "read" },
4363
+ repositories: [name]
4577
4364
  });
4578
- }
4579
- /**
4580
- * Close the merge conflict notices of some Junior pull requests, such as
4581
- * ones that GitHub reports as mergeable. A notice is optional, so a failed
4582
- * close is logged, and the next check closes it again.
4583
- */
4584
- async function closeGitHubConflictNotices(args) {
4585
- if (args.numbers.length === 0) return;
4586
- const { repositoryFullName } = args;
4587
- const openers = await listGitHubPullRequestOpeners(args.db, {
4588
- numbers: args.numbers,
4589
- repositoryFullName
4365
+ return await githubRequest("https://api.github.com", "/graphql", {
4366
+ body: {
4367
+ ...OPEN_PULL_REQUEST_MERGEABILITY,
4368
+ variables: {
4369
+ after: input.after ?? null,
4370
+ query: `repo:${input.repositoryFullName} is:pr is:open author:${input.author}`
4371
+ }
4372
+ },
4373
+ method: "POST",
4374
+ token: token.token
4590
4375
  });
4591
- const limit = pLimit(NOTICE_CLOSE_CONCURRENCY);
4592
- const close = async (number, conversationId) => {
4593
- try {
4594
- await args.reviewItems.forConversation(conversationId).close({
4595
- dedupeKey: gitHubConflictNoticeKey({
4596
- number,
4597
- repositoryFullName
4598
- }),
4599
- reason: args.reason,
4600
- status: args.status
4601
- });
4602
- } catch (error) {
4603
- logFailOpenFailure(args.log, "GitHub merge conflict notice close failed", error, {
4604
- number,
4605
- repository: repositoryFullName
4606
- });
4607
- }
4608
- };
4609
- await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
4610
4376
  }
4611
- // src/webhooks/merge-conflict.ts
4612
- const PULL_REQUEST_CHECK_CONCURRENCY = 5;
4613
- const EVENT_TYPE = "pull_request.merge_conflict";
4614
- /** Events after which the pull request cannot get a conflict. */
4615
- const CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set(["pull_request.closed_unmerged", "pull_request.merged"]);
4616
- /** The pull request fields that tell if it has a conflict. */
4617
- const pullRequestSchema$1 = z.object({
4618
- base: z.object({ ref: z.string().min(1) }),
4619
- draft: z.boolean().optional(),
4620
- number: z.number().int().positive().optional(),
4621
- head: z.object({ sha: z.string().min(1) }),
4622
- html_url: z.string().min(1).optional(),
4623
- mergeable: z.boolean().nullable().optional(),
4624
- mergeable_state: z.string().optional(),
4625
- state: z.string(),
4626
- title: z.string().optional()
4627
- });
4628
- /**
4629
- * Build the `pull_request.merge_conflict` copies for one pull request. With
4630
- * no conflict, the copies have only the values that filters can match. The
4631
- * event key names the head commit, so each head commit publishes once.
4632
- */
4633
- function gitHubMergeConflictEvents(input) {
4634
- const { conflict } = input;
4635
- const repo = gitHubRepoDataSchema.parse(input.repositoryFullName);
4636
- const resource = gitHubPullRequestResource({
4637
- number: input.number,
4638
- repo
4377
+ /** Read the merge conflict history of one pull request, with a read-only token. */
4378
+ async function loadPullRequestConflictHistory(env, pullRequest) {
4379
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request conflict history");
4380
+ const token = await issueInstallationToken({
4381
+ ...env,
4382
+ permissions: { pull_requests: "read" },
4383
+ repositories: [name]
4384
+ });
4385
+ return await githubRequest("https://api.github.com", "/graphql", {
4386
+ body: {
4387
+ ...PULL_REQUEST_CONFLICT_HISTORY,
4388
+ variables: {
4389
+ name,
4390
+ number: pullRequest.number,
4391
+ owner
4392
+ }
4393
+ },
4394
+ method: "POST",
4395
+ token: token.token
4639
4396
  });
4640
- return pullRequestTargets({
4641
- eventKey: `github:merge-conflict:${resource.identifier}${conflict ? `:${conflict.headSha}` : ""}`,
4642
- eventType: EVENT_TYPE,
4643
- identifier: resource.identifier,
4644
- objectType: "code_change",
4645
- occurredAtMs: Date.now(),
4646
- trustedSummary: `${resource.label} has merge conflicts${conflict ? ` with ${conflict.baseBranch}` : ""}.`,
4647
- data: {
4648
- repo,
4649
- pullRequest: input.number,
4650
- ...conflict
4651
- }
4652
- }, repo);
4653
4397
  }
4654
- /** Open pull requests that the delivered events are about. */
4655
- function pullRequestRefs(events) {
4656
- const refs = /* @__PURE__ */ new Map();
4657
- for (const event of events) {
4658
- const { pullRequest, repo } = event.data ?? {};
4659
- if (!event.eventType.startsWith("pull_request.") || CLOSED_EVENT_TYPES.has(event.eventType) || typeof pullRequest !== "number" || typeof repo !== "string") continue;
4660
- refs.set(`${repo}#${pullRequest}`, {
4661
- number: pullRequest,
4662
- repositoryFullName: repo
4663
- });
4398
+ /** Ask people to review one pull request, with a pull request write token. */
4399
+ async function requestPullRequestReviewers(env, input) {
4400
+ const { owner, name } = splitRepository(input.repositoryFullName, "pull request review request");
4401
+ const token = await issueInstallationToken({
4402
+ ...env,
4403
+ permissions: { pull_requests: "write" },
4404
+ repositories: [name]
4405
+ });
4406
+ await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${input.number}/requested_reviewers`, {
4407
+ body: { reviewers: input.reviewers },
4408
+ method: "POST",
4409
+ token: token.token
4410
+ });
4411
+ }
4412
+ /** Add the "reviewing" reaction to one pull request comment or review body. */
4413
+ async function markPullRequestFeedbackReviewing(env, target) {
4414
+ const { owner, name } = splitRepository(target.repo, "pull request feedback");
4415
+ const token = await issueInstallationToken({
4416
+ ...env,
4417
+ repositories: [name]
4418
+ });
4419
+ const content = pullRequestFeedbackReactionContent("reviewing");
4420
+ if (target.commentKind === "review_body") {
4421
+ const review = z.object({ node_id: z.string().min(1) }).parse(await githubRequest("https://api.github.com", pullRequestReviewPath({
4422
+ owner,
4423
+ name,
4424
+ pullRequest: target.pullRequest,
4425
+ reviewId: target.commentId
4426
+ }), { token: token.token }));
4427
+ const result = z.object({ errors: z.array(z.unknown()).optional() }).parse(await githubRequest("https://api.github.com", "/graphql", {
4428
+ body: {
4429
+ ...ADD_REVIEW_REACTION,
4430
+ variables: {
4431
+ content: graphqlReactionContent(content),
4432
+ subjectId: review.node_id
4433
+ }
4434
+ },
4435
+ method: "POST",
4436
+ token: token.token
4437
+ }));
4438
+ if (result.errors?.length) throw new Error(`GitHub review reaction failed: ${githubErrorMessage$1(result)}`);
4439
+ return;
4664
4440
  }
4665
- return [...refs.values()];
4441
+ await githubRequest("https://api.github.com", pullRequestCommentReactionsPath({
4442
+ owner,
4443
+ name,
4444
+ commentKind: target.commentKind,
4445
+ commentId: target.commentId
4446
+ }), {
4447
+ body: { content },
4448
+ method: "POST",
4449
+ token: token.token
4450
+ });
4666
4451
  }
4452
+ const repositoryPermissionSchema = z.object({
4453
+ permission: z.string().min(1),
4454
+ role_name: z.string().optional()
4455
+ });
4456
+ const REPOSITORY_ROLE_TTL_MS = 6e5;
4667
4457
  /**
4668
- * Return the pull request from a `pull_request` webhook payload when it is
4669
- * `ref` and GitHub already knows its mergeability. Other webhooks, such as
4670
- * reviews, comments, and check results, do not send mergeability.
4458
+ * Read one user's role on a repository, with a metadata-only token. GitHub
4459
+ * returns "none" for accounts without access, such as most bots. Roles are
4460
+ * cached for ten minutes.
4671
4461
  */
4672
- function deliveredPullRequest(payload, ref) {
4673
- const parsed = z.object({ pull_request: pullRequestSchema$1 }).safeParse(payload);
4674
- const pullRequest = parsed.success ? parsed.data.pull_request : void 0;
4675
- return pullRequest?.number === ref.number && typeof pullRequest.mergeable === "boolean" ? pullRequest : void 0;
4462
+ async function loadRepositoryRole(env, cache, target) {
4463
+ const { owner, name } = splitRepository(target.repositoryFullName, "repository role");
4464
+ return await cache.getOrLoad(`repository-role:${owner}/${name}:${target.login}`.toLowerCase(), async () => {
4465
+ const token = await issueInstallationToken({
4466
+ ...env,
4467
+ permissions: { metadata: "read" },
4468
+ repositories: [name]
4469
+ });
4470
+ const response = repositoryPermissionSchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/collaborators/${encodeURIComponent(target.login)}/permission`, { token: token.token }));
4471
+ return {
4472
+ value: response.role_name?.trim() || response.permission,
4473
+ ttlMs: REPOSITORY_ROLE_TTL_MS
4474
+ };
4475
+ });
4676
4476
  }
4677
- /**
4678
- * Return `pull_request.merge_conflict` events for the open pull requests that
4679
- * these events are about, when a Watch or event automation wants them and
4680
- * GitHub reports a conflict. A `pull_request` webhook payload gives the
4681
- * mergeability when GitHub knows it. Otherwise the check reads the pull
4682
- * request, which also makes GitHub calculate its mergeability. When GitHub
4683
- * does not know it yet, a later event reads it again. The policy in
4684
- * `merge-conflict-checks/policy.ts` decides if a conflict publishes.
4685
- */
4686
- async function loadGitHubMergeConflictEvents(args) {
4687
- const { hasMatch, loadConflictHistory, loadPullRequest } = args;
4688
- if (!hasMatch || !loadPullRequest || !loadConflictHistory) return [];
4689
- const check = async (ref) => {
4690
- if (!await hasMatch(gitHubMergeConflictEvents(ref))) return [];
4691
- try {
4692
- const loaded = deliveredPullRequest(args.pullRequestPayload, ref) ?? pullRequestSchema$1.parse(await loadPullRequest(ref));
4693
- if (loaded.state !== "open" || loaded.mergeable !== false || loaded.mergeable_state !== "dirty") return [];
4694
- const conflict = {
4695
- baseBranch: loaded.base.ref,
4696
- headSha: loaded.head.sha,
4697
- ...loaded.html_url ? { url: loaded.html_url } : void 0
4698
- };
4699
- return await applyGitHubConflictPolicy({
4700
- conflict,
4701
- db: args.db,
4702
- draft: loaded.draft === true,
4703
- events: gitHubMergeConflictEvents({
4704
- ...ref,
4705
- conflict
4706
- }),
4707
- loadHistory: loadConflictHistory,
4708
- log: args.log,
4709
- now: /* @__PURE__ */ new Date(),
4710
- ref,
4711
- reviewItems: args.reviewItems,
4712
- ...loaded.title ? { title: loaded.title } : void 0
4713
- });
4714
- } catch (error) {
4715
- logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
4716
- deliveryId: args.deliveryId,
4717
- pullRequest: ref.number,
4718
- repository: ref.repositoryFullName
4719
- });
4720
- return [];
4721
- }
4722
- };
4723
- return (await pLimit(PULL_REQUEST_CHECK_CONCURRENCY).map(pullRequestRefs(args.events), (ref) => check(ref))).flat();
4477
+ const timestampSchema$1 = z.iso.datetime({ offset: true });
4478
+ function nodesSchema(node) {
4479
+ return z.array(node.nullable()).transform((items) => items.filter((item) => item !== null));
4724
4480
  }
4725
- // src/merge-conflict-checks/store.ts
4726
- /** A key that waits longer than this was lost and expires. */
4727
- const CHECK_TTL_MS = 18e5;
4728
- /**
4729
- * The heartbeat's own record of a running or repeated check. Only the
4730
- * heartbeat writes it, so it needs no lock.
4731
- */
4732
- const repeatSchema = z.object({
4733
- /** Checks since the last push that ended with an unknown answer. */
4734
- attempts: z.number().int().positive(),
4735
- dueAtMs: z.number()
4481
+ const actorSchema = z.object({
4482
+ __typename: z.string(),
4483
+ login: z.string().min(1)
4484
+ }).nullable();
4485
+ const reviewsSchema = z.object({
4486
+ pageInfo: z.object({
4487
+ hasPreviousPage: z.boolean(),
4488
+ startCursor: z.string().nullable()
4489
+ }),
4490
+ nodes: nodesSchema(z.object({
4491
+ author: actorSchema,
4492
+ commit: z.object({ oid: z.string().min(1) }).nullable(),
4493
+ state: z.string(),
4494
+ submittedAt: timestampSchema$1.nullable()
4495
+ }))
4736
4496
  });
4737
- function pushKey(repositoryFullName) {
4738
- return `merge-conflict-check:push:${repositoryFullName}`;
4739
- }
4740
- function repeatKey(repositoryFullName) {
4741
- return `merge-conflict-check:repeat:${repositoryFullName}`;
4742
- }
4743
- /** Return the repositories that have open Junior pull requests. */
4744
- async function listGitHubRepositoriesWithOpenPullRequests(db, repositoryFullName) {
4745
- const t = juniorGitHubPullRequests;
4746
- return (await db.selectDistinct({ repositoryFullName: t.repositoryFullName }).from(t).where(and(eq(t.state, "open"), repositoryFullName ? eq(t.repositoryFullName, repositoryFullName) : void 0)).orderBy(t.repositoryFullName)).map((row) => row.repositoryFullName);
4497
+ const userLoginSchema = z.object({
4498
+ __typename: z.string(),
4499
+ login: z.string().min(1).optional()
4500
+ }).nullable();
4501
+ const nextActionSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4502
+ autoMergeRequest: z.object({}).nullable(),
4503
+ commits: z.object({ nodes: nodesSchema(z.object({ commit: z.object({ committedDate: timestampSchema$1 }) })) }),
4504
+ headRefOid: z.string().min(1),
4505
+ isDraft: z.boolean(),
4506
+ mergeStateStatus: z.string(),
4507
+ reviewRequests: z.object({ nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })) }),
4508
+ reviews: reviewsSchema,
4509
+ state: z.enum([
4510
+ "CLOSED",
4511
+ "MERGED",
4512
+ "OPEN"
4513
+ ]),
4514
+ timelineItems: z.object({ nodes: nodesSchema(z.discriminatedUnion("__typename", [z.object({
4515
+ __typename: z.literal("IssueComment"),
4516
+ author: actorSchema,
4517
+ createdAt: timestampSchema$1
4518
+ }), z.object({
4519
+ __typename: z.literal("ReviewRequestedEvent"),
4520
+ createdAt: timestampSchema$1,
4521
+ requestedReviewer: userLoginSchema
4522
+ })])) }),
4523
+ title: z.string(),
4524
+ url: z.string().url()
4525
+ }) }) }) });
4526
+ const reviewsPageSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ reviews: reviewsSchema }) }) }) });
4527
+ function restLogin(actor) {
4528
+ return actor.__typename === "Bot" ? `${actor.login}[bot]` : actor.login;
4747
4529
  }
4748
4530
  /**
4749
- * Add a check at `dueAtMs` for a repository with open Junior pull requests.
4750
- * A check that already waits keeps its earlier time, so pushes that keep
4751
- * coming do not delay it. Return whether a check waits.
4531
+ * Read whether a pull request is ready to merge, whether the requester
4532
+ * changed their review, and who acted on it last, with a read-only token
4533
+ * and one GraphQL query. GitHub computes the merge state after a change,
4534
+ * so an unknown state is read once more. A pull request with more than 100
4535
+ * reviews reads the older pages too. Each reviewer counts by their latest
4536
+ * approval, change request, or dismissal. Comments do not change the
4537
+ * result.
4752
4538
  */
4753
- async function scheduleGitHubConflictCheck(args) {
4754
- if ((await listGitHubRepositoriesWithOpenPullRequests(args.db, args.repositoryFullName)).length === 0) return false;
4755
- await args.state.setIfNotExists(pushKey(args.repositoryFullName), args.dueAtMs, CHECK_TTL_MS);
4756
- return true;
4757
- }
4758
- /**
4759
- * Claim the due check of a repository. The claim removes the push key
4760
- * before the check reads GitHub, so the read includes every push that the
4761
- * key held, and a later push adds a new key. A repeat at `claimedUntilMs`
4762
- * runs the check again when it stops without an end.
4763
- */
4764
- async function claimGitHubConflictCheck(args) {
4765
- const pushDueAtMs = await args.state.get(pushKey(args.repositoryFullName));
4766
- const repeat = repeatSchema.safeParse(await args.state.get(repeatKey(args.repositoryFullName)));
4767
- let attempts;
4768
- if (typeof pushDueAtMs === "number" && pushDueAtMs <= args.nowMs) attempts = 1;
4769
- else if (repeat.success && repeat.data.dueAtMs <= args.nowMs) attempts = repeat.data.attempts + 1;
4770
- else return;
4771
- await args.state.set(repeatKey(args.repositoryFullName), {
4772
- attempts,
4773
- dueAtMs: args.claimedUntilMs
4774
- }, CHECK_TTL_MS);
4775
- if (attempts === 1) await args.state.delete(pushKey(args.repositoryFullName));
4776
- return {
4777
- attempts,
4778
- repositoryFullName: args.repositoryFullName
4539
+ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4540
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request merge state");
4541
+ const token = await issueInstallationToken({
4542
+ ...env,
4543
+ permissions: { pull_requests: "read" },
4544
+ repositories: [name]
4545
+ });
4546
+ const variables = {
4547
+ name,
4548
+ number: pullRequest.number,
4549
+ owner
4779
4550
  };
4780
- }
4781
- /** End a claimed check, or repeat it at `retryAtMs`. */
4782
- async function settleGitHubConflictCheck(state, check, retryAtMs) {
4783
- if (retryAtMs === void 0) {
4784
- await state.delete(repeatKey(check.repositoryFullName));
4785
- return;
4551
+ const query = async (document, extra) => await githubRequest("https://api.github.com", "/graphql", {
4552
+ body: {
4553
+ ...document,
4554
+ variables: {
4555
+ ...variables,
4556
+ ...extra
4557
+ }
4558
+ },
4559
+ method: "POST",
4560
+ token: token.token
4561
+ });
4562
+ const readPull = async () => nextActionSchema.parse(await query(PULL_REQUEST_NEXT_ACTION)).data.repository.pullRequest;
4563
+ let pull = await readPull();
4564
+ const open = pull.state === "OPEN" && !pull.isDraft;
4565
+ const unknown = (status) => status === "UNKNOWN";
4566
+ if (open && !pull.autoMergeRequest && unknown(pull.mergeStateStatus)) pull = await readPull();
4567
+ const reviews = [...pull.reviews.nodes];
4568
+ let page = pull.reviews.pageInfo;
4569
+ while (open && page.hasPreviousPage && page.startCursor) {
4570
+ const older = reviewsPageSchema.parse(await query(PULL_REQUEST_REVIEWS_BEFORE, { before: page.startCursor })).data.repository.pullRequest.reviews;
4571
+ reviews.unshift(...older.nodes);
4572
+ page = older.pageInfo;
4786
4573
  }
4787
- await state.set(repeatKey(check.repositoryFullName), {
4788
- attempts: check.attempts,
4789
- dueAtMs: retryAtMs
4790
- }, CHECK_TTL_MS);
4574
+ const activity = [];
4575
+ const head = pull.commits.nodes.at(-1);
4576
+ if (head) activity.push({
4577
+ at: new Date(head.commit.committedDate),
4578
+ kind: "push",
4579
+ login: ""
4580
+ });
4581
+ for (const item of pull.timelineItems.nodes) if (item.__typename === "IssueComment" && item.author) activity.push({
4582
+ at: new Date(item.createdAt),
4583
+ kind: "author",
4584
+ login: restLogin(item.author)
4585
+ });
4586
+ else if (item.__typename === "ReviewRequestedEvent" && item.requestedReviewer?.login) activity.push({
4587
+ at: new Date(item.createdAt),
4588
+ kind: "reviewRequest",
4589
+ login: item.requestedReviewer.login
4590
+ });
4591
+ for (const review of reviews) if (review.author && review.submittedAt) activity.push({
4592
+ at: new Date(review.submittedAt),
4593
+ kind: "author",
4594
+ login: restLogin(review.author)
4595
+ });
4596
+ const mergeableState = unknown(pull.mergeStateStatus) ? void 0 : pull.mergeStateStatus.toLowerCase();
4597
+ const state = {
4598
+ activity,
4599
+ approved: false,
4600
+ autoMerge: Boolean(pull.autoMergeRequest),
4601
+ draft: pull.isDraft,
4602
+ headSha: pull.headRefOid,
4603
+ ...mergeableState ? { mergeableState } : void 0,
4604
+ requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" && request.requestedReviewer.login ? [request.requestedReviewer.login] : []),
4605
+ state: pull.state === "MERGED" ? "merged" : pull.state === "OPEN" ? "open" : "closed",
4606
+ title: pull.title,
4607
+ url: pull.url
4608
+ };
4609
+ if (!open) return state;
4610
+ const latest = /* @__PURE__ */ new Map();
4611
+ for (const review of reviews) if (review.author && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.author.login.toLowerCase(), review);
4612
+ const reviewStates = [...latest.values()].map((review) => review.state);
4613
+ if (!state.autoMerge && state.mergeableState === "clean") state.approved = reviewStates.includes("APPROVED") && !reviewStates.includes("CHANGES_REQUESTED");
4614
+ const login = requesterLogin?.toLowerCase();
4615
+ const requesterReview = login ? latest.get(login) : void 0;
4616
+ if (requesterReview?.state === "CHANGES_REQUESTED" && requesterReview.commit) {
4617
+ state.changesRequestedCommit = requesterReview.commit.oid;
4618
+ if (requesterReview.submittedAt) state.changesRequestedAt = new Date(requesterReview.submittedAt);
4619
+ }
4620
+ return state;
4791
4621
  }
4792
- // src/merge-conflict-checks/webhooks.ts
4622
+ // src/webhooks/pull-request-action.ts
4623
+ const PULL_REQUEST_SYNC_CONCURRENCY = 5;
4793
4624
  /**
4794
- * Time from a push to its check. GitHub calculates mergeability after a
4795
- * push, and pushes in this time share one check.
4625
+ * A check normally takes a few seconds. After this time, a check that
4626
+ * stopped without its release no longer blocks new checks.
4796
4627
  */
4797
- const CONFLICT_CHECK_DELAY_MS = 12e4;
4798
- const pushSchema = z.object({
4799
- deleted: z.boolean().optional(),
4800
- ref: z.string(),
4801
- repository: z.object({
4802
- default_branch: z.string().min(1),
4803
- full_name: z.string().min(1)
4804
- })
4628
+ const READY_SYNC_STALE_MS = 6e4;
4629
+ /** Webhook actions that can change the next action of a pull request. */
4630
+ const ACTION_EVENTS = {
4631
+ pull_request: /* @__PURE__ */ new Set([
4632
+ "auto_merge_disabled",
4633
+ "auto_merge_enabled",
4634
+ "closed",
4635
+ "converted_to_draft",
4636
+ "ready_for_review",
4637
+ "reopened",
4638
+ "review_request_removed",
4639
+ "review_requested",
4640
+ "synchronize"
4641
+ ]),
4642
+ pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
4643
+ };
4644
+ /**
4645
+ * Keys of the two items that came before the one item per pull request.
4646
+ * Each check closes them, so no old item stays open next to the new one.
4647
+ * Remove them when no item from before is open.
4648
+ */
4649
+ const LEGACY_DEDUPE_PREFIXES = ["pull-request-ready:", "pull-request-review-requested:"];
4650
+ function itemName(target) {
4651
+ return `${target.repositoryFullName}#${target.number}`.toLowerCase();
4652
+ }
4653
+ function actionDedupeKey(target) {
4654
+ return `pull-request-action:${itemName(target)}`;
4655
+ }
4656
+ async function closeLegacyItems(items, name) {
4657
+ await Promise.all(LEGACY_DEDUPE_PREFIXES.map((prefix) => items.close({
4658
+ dedupeKey: `${prefix}${name}`,
4659
+ reason: "One item now shows the next action.",
4660
+ status: "dismissed"
4661
+ })));
4662
+ }
4663
+ const repositorySchema$2 = z.object({ full_name: z.string().min(1) });
4664
+ const pullRequestWebhookSchema = z.object({
4665
+ action: z.string(),
4666
+ pull_request: z.object({ number: z.number().int().positive() }),
4667
+ repository: repositorySchema$2
4668
+ });
4669
+ const commentWebhookSchema = z.object({
4670
+ action: z.literal("created"),
4671
+ comment: z.object({ user: z.object({ login: z.string().min(1) }).nullable() }),
4672
+ issue: z.object({
4673
+ number: z.number().int().positive(),
4674
+ pull_request: z.object({})
4675
+ }).optional(),
4676
+ pull_request: z.object({ number: z.number().int().positive() }).optional(),
4677
+ repository: repositorySchema$2
4805
4678
  });
4679
+ /** Return the pull requests whose next action one webhook delivery can change. */
4680
+ function pullRequestActionTargets(eventName, body) {
4681
+ if (eventName === "check_suite") return checkSuitePullRequests(body);
4682
+ if (eventName === "issue_comment" || eventName === "pull_request_review_comment") {
4683
+ const parsed = commentWebhookSchema.safeParse(body);
4684
+ if (!parsed.success) return [];
4685
+ const { comment, repository } = parsed.data;
4686
+ const number = (parsed.data.issue ?? parsed.data.pull_request)?.number;
4687
+ if (number === void 0 || !comment.user) return [];
4688
+ return [{
4689
+ commentBy: comment.user.login,
4690
+ number,
4691
+ repositoryFullName: repository.full_name
4692
+ }];
4693
+ }
4694
+ const actions = ACTION_EVENTS[eventName];
4695
+ const parsed = pullRequestWebhookSchema.safeParse(body);
4696
+ if (!actions || !parsed.success || !actions.has(parsed.data.action)) return [];
4697
+ return [{
4698
+ number: parsed.data.pull_request.number,
4699
+ repositoryFullName: parsed.data.repository.full_name
4700
+ }];
4701
+ }
4806
4702
  /**
4807
- * Schedule a check after a push to a repository's default branch. Stacked
4808
- * pull requests do not need this, because Junior restacks them when it
4809
- * pushes the branch below. Return whether a check waits.
4703
+ * Who did one thing on a pull request. A push counts as Junior's, as new
4704
+ * commits do. A request for the requester's review hands the pull request
4705
+ * to them, so it counts as Junior's too.
4810
4706
  */
4811
- async function scheduleGitHubPushConflictCheck(args) {
4812
- const parsed = pushSchema.safeParse(args.body);
4813
- if (!parsed.success || parsed.data.deleted || parsed.data.ref !== `refs/heads/${parsed.data.repository.default_branch}`) return false;
4814
- return await scheduleGitHubConflictCheck({
4815
- db: args.db,
4816
- dueAtMs: args.now.getTime() + CONFLICT_CHECK_DELAY_MS,
4817
- repositoryFullName: parsed.data.repository.full_name,
4818
- state: args.state
4819
- });
4707
+ function actor(activity, requesterLogin, botEmail) {
4708
+ const byRequester = requesterLogin !== void 0 && activity.login.toLowerCase() === requesterLogin.toLowerCase();
4709
+ switch (activity.kind) {
4710
+ case "push": return "junior";
4711
+ case "reviewRequest": return byRequester ? "junior" : void 0;
4712
+ case "author":
4713
+ if (isBotLogin(activity.login, botEmail)) return "junior";
4714
+ return byRequester ? "requester" : void 0;
4715
+ }
4820
4716
  }
4821
- // src/webhooks/installation-requests.ts
4822
- function splitRepository(fullName, label) {
4823
- const [owner, name, ...extra] = fullName.split("/");
4824
- if (!owner || !name || extra.length > 0) throw new Error(`GitHub ${label} received an invalid repository name`);
4717
+ function latestActivity(activity, requesterLogin, botEmail) {
4718
+ const latest = {};
4719
+ for (const entry of activity) {
4720
+ const by = actor(entry, requesterLogin, botEmail);
4721
+ if (!by) continue;
4722
+ const key = by === "junior" ? "juniorAt" : "requesterAt";
4723
+ const saved = latest[key];
4724
+ if (!saved || entry.at > saved) latest[key] = entry.at;
4725
+ }
4726
+ return latest;
4727
+ }
4728
+ function timeOf(at) {
4729
+ return at ? at.getTime() : Number.NEGATIVE_INFINITY;
4730
+ }
4731
+ /**
4732
+ * Return why the requester's review is wanted again after their change
4733
+ * request, or undefined while Junior acts next.
4734
+ */
4735
+ function reviewAgainReason(state, activity) {
4736
+ if (!state.changesRequestedCommit) return void 0;
4737
+ const newCommits = state.changesRequestedCommit !== state.headSha;
4738
+ const changesRequestedAt = timeOf(state.changesRequestedAt);
4739
+ const requesterAt = Math.max(timeOf(activity.requesterAt), changesRequestedAt);
4740
+ if (timeOf(activity.juniorAt) > requesterAt) return newCommits ? "commits" : "reply";
4741
+ return newCommits && !(timeOf(activity.requesterAt) > changesRequestedAt) ? "commits" : void 0;
4742
+ }
4743
+ /**
4744
+ * Derive the requester's next action. Return undefined when it cannot be
4745
+ * known yet, so a later event decides.
4746
+ */
4747
+ function nextAction(state, requester, saved) {
4748
+ if (state.state !== "open") return {};
4749
+ const canMerge = !state.draft && !state.autoMerge;
4750
+ if (canMerge && state.mergeableState === "clean" && state.approved) return { action: "merge" };
4751
+ if (canMerge && !state.mergeableState && saved === "merge") return void 0;
4752
+ const requested = isRequested(state, requester.login);
4753
+ if (requested && !requester.actedLast) return { action: "review" };
4754
+ const reason = reviewAgainReason(state, requester.activity);
4755
+ if (reason) return {
4756
+ action: "review",
4757
+ reason
4758
+ };
4759
+ if (requested && !state.changesRequestedCommit) return { action: "review" };
4760
+ if (canMerge && !state.mergeableState) return void 0;
4761
+ return {};
4762
+ }
4763
+ function isRequested(state, login) {
4764
+ const lower = login?.toLowerCase();
4765
+ return state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === lower);
4766
+ }
4767
+ const REVIEW_AGAIN_TEXT = {
4768
+ commits: (number) => `#${number} has new commits since you requested changes.`,
4769
+ reply: (number) => `#${number} has a reply since you requested changes.`
4770
+ };
4771
+ /** Why an item closes when its pull request is no longer open. */
4772
+ const ENDED_REASONS = {
4773
+ closed: {
4774
+ reason: "The pull request closed without merging.",
4775
+ status: "dismissed"
4776
+ },
4777
+ merged: {
4778
+ reason: "The pull request merged.",
4779
+ status: "done"
4780
+ }
4781
+ };
4782
+ function endedReason(state) {
4783
+ return state === "open" ? void 0 : ENDED_REASONS[state];
4784
+ }
4785
+ function closeReason(state, previous) {
4786
+ const ended = endedReason(state.state);
4787
+ if (ended) return ended;
4788
+ if (previous === "review") return {
4789
+ reason: "The review request ended.",
4790
+ status: "done"
4791
+ };
4792
+ if (state.autoMerge) return {
4793
+ reason: "Auto-merge is on.",
4794
+ status: "dismissed"
4795
+ };
4825
4796
  return {
4826
- owner,
4827
- name
4797
+ reason: "The pull request is no longer ready to merge.",
4798
+ status: "dismissed"
4828
4799
  };
4829
4800
  }
4830
- /** Return a reader for pages of a pull request's commits, with a read-only token. */
4831
- async function loadPullRequestCommitPages(env, pullRequest) {
4832
- const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request commits");
4833
- const token = await issueInstallationToken({
4834
- ...env,
4835
- permissions: { pull_requests: "read" },
4836
- repositories: [name]
4801
+ async function showAction(items, args) {
4802
+ const { action, number, state } = args;
4803
+ if (action) await items.upsert({
4804
+ assigneeIdentityIds: [args.identityId],
4805
+ body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` : `${args.reason ? REVIEW_AGAIN_TEXT[args.reason](number) : `GitHub asks you to review #${number}.`}\n\n${state.url}`,
4806
+ dedupeKey: args.dedupeKey,
4807
+ subject: {
4808
+ id: state.url,
4809
+ title: `${state.title} (#${number})`,
4810
+ url: state.url
4811
+ },
4812
+ title: action === "merge" ? `Ready to merge · #${number}` : `Review requested · #${number}`,
4813
+ waitsOnAssignees: true
4837
4814
  });
4838
- return async (page, perPage) => await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}/commits?per_page=${perPage}&page=${page}`, { token: token.token });
4839
- }
4840
- /** Read one pull request, with a read-only token. */
4841
- async function loadPullRequest(env, pullRequest) {
4842
- const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request");
4843
- const token = await issueInstallationToken({
4844
- ...env,
4845
- permissions: { pull_requests: "read" },
4846
- repositories: [name]
4815
+ else if (args.previous) await items.close({
4816
+ dedupeKey: args.dedupeKey,
4817
+ ...closeReason(state, args.previous)
4847
4818
  });
4848
- return await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}`, { token: token.token });
4849
4819
  }
4850
- /** GitHub cannot reach a repository: it is gone, or the installation lost it. */
4851
- var GitHubRepositoryUnreachableError = class extends Error {
4852
- constructor(repositoryId) {
4853
- super(`GitHub repository ${repositoryId} is not reachable`);
4854
- this.name = "GitHubRepositoryUnreachableError";
4820
+ /**
4821
+ * Close the next-action item and the merge conflict notice of a pull request
4822
+ * that merged or closed. The outcome write calls this before it marks the
4823
+ * chips, so no reader sees an ended pull request next to its open item. The
4824
+ * items are optional, so a failure is logged. In a webhook, the next-action
4825
+ * sync after it closes the item again.
4826
+ */
4827
+ async function closeEndedGitHubPullRequestItems(args) {
4828
+ const { target } = args;
4829
+ try {
4830
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
4831
+ numbers: [target.number],
4832
+ repositoryFullName: target.repositoryFullName
4833
+ })).get(target.number);
4834
+ if (!opener?.conversationId) return;
4835
+ const items = args.reviewItems.forConversation(opener.conversationId);
4836
+ const reason = ENDED_REASONS[args.state];
4837
+ await Promise.all([items.close({
4838
+ dedupeKey: actionDedupeKey(target),
4839
+ ...reason
4840
+ }), items.close({
4841
+ dedupeKey: gitHubConflictItemKey(target),
4842
+ ...reason
4843
+ })]);
4844
+ } catch (error) {
4845
+ logFailOpenFailure(args.log, "GitHub ended pull request item close failed", error, {
4846
+ number: target.number,
4847
+ repository: target.repositoryFullName
4848
+ });
4855
4849
  }
4856
- };
4857
- const UNREACHABLE_REPOSITORY_MESSAGE = /does not exist or is not accessible/i;
4850
+ }
4858
4851
  /**
4859
- * Read the lifecycle of some pull requests of one repository in one GraphQL
4860
- * query, with a read-only token. Each pull request has the alias `pr<index>`.
4861
- * The repository is found by its id, because a rename changes its name.
4852
+ * Ask for the requester's review on GitHub, so GitHub notifies them. The
4853
+ * item already asks, so a failure is logged and the item stays.
4862
4854
  */
4863
- async function loadPullRequestLifecycles(env, input) {
4864
- let token;
4855
+ async function requestReviewAgain(args, target, login) {
4865
4856
  try {
4866
- token = await issueInstallationToken({
4867
- ...env,
4868
- permissions: { pull_requests: "read" },
4869
- repositoryIds: [input.repositoryId]
4857
+ await requestPullRequestReviewers(args.env, {
4858
+ ...target,
4859
+ reviewers: [login]
4870
4860
  });
4871
4861
  } catch (error) {
4872
- if (error instanceof GitHubRequestError && error.status === 422 && UNREACHABLE_REPOSITORY_MESSAGE.test(error.message)) throw new GitHubRepositoryUnreachableError(input.repositoryId);
4873
- throw error;
4862
+ logFailOpenFailure(args.log, "GitHub review request again failed", error, {
4863
+ number: target.number,
4864
+ repository: target.repositoryFullName
4865
+ });
4874
4866
  }
4875
- const { owner, name } = splitRepository(z.object({ full_name: z.string().min(1) }).parse(await githubRequest("https://api.github.com", `/repositories/${input.repositoryId}`, { token: token.token })).full_name, "pull request lifecycle");
4876
- return await githubRequest("https://api.github.com", "/graphql", {
4877
- body: {
4878
- ...pullRequestLifecycles(input.numbers.length),
4879
- variables: {
4880
- name,
4881
- owner,
4882
- ...Object.fromEntries(input.numbers.map((number, index) => [`n${index}`, number]))
4883
- }
4884
- },
4885
- method: "POST",
4886
- token: token.token
4867
+ }
4868
+ async function syncOne(args, target) {
4869
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
4870
+ numbers: [target.number],
4871
+ repositoryFullName: target.repositoryFullName
4872
+ })).get(target.number);
4873
+ if (!opener?.conversationId) return;
4874
+ const items = args.reviewItems.forConversation(opener.conversationId);
4875
+ const name = itemName(target);
4876
+ const dedupeKey = actionDedupeKey(target);
4877
+ const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
4878
+ if (target.commentBy !== void 0 && !actor({
4879
+ kind: "author",
4880
+ login: target.commentBy
4881
+ }, requesterLogin, args.botEmail)) return;
4882
+ const claim = await claimGitHubPullRequestReadySync(args.db, target, {
4883
+ now: /* @__PURE__ */ new Date(),
4884
+ staleMs: READY_SYNC_STALE_MS
4887
4885
  });
4886
+ if (!claim) return;
4887
+ const { id } = claim;
4888
+ let saved = claim.action;
4889
+ let requests = claim.requests;
4890
+ let failure;
4891
+ const check = async (previous) => {
4892
+ const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
4893
+ const activity = latestActivity(state.activity, requesterLogin, args.botEmail);
4894
+ const next = nextAction(state, {
4895
+ activity,
4896
+ actedLast: timeOf(activity.requesterAt) > timeOf(activity.juniorAt),
4897
+ login: requesterLogin
4898
+ }, previous);
4899
+ const changed = next !== void 0 && next.action !== previous;
4900
+ if (changed) {
4901
+ await showAction(items, {
4902
+ action: next.action,
4903
+ dedupeKey,
4904
+ identityId: opener.identityId,
4905
+ number: target.number,
4906
+ previous,
4907
+ reason: next.reason,
4908
+ state
4909
+ });
4910
+ if (next.reason && requesterLogin && !isRequested(state, requesterLogin)) await requestReviewAgain(args, target, requesterLogin);
4911
+ }
4912
+ await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
4913
+ dedupeKey: gitHubConflictItemKey(target),
4914
+ ...endedReason(state.state) ?? {
4915
+ reason: "The pull request no longer has merge conflicts.",
4916
+ status: "done"
4917
+ }
4918
+ }) : void 0]);
4919
+ if (!changed) return previous;
4920
+ await setGitHubPullRequestNextAction(args.db, {
4921
+ ...target,
4922
+ action: next.action
4923
+ });
4924
+ return next.action;
4925
+ };
4926
+ while (requests !== void 0) {
4927
+ try {
4928
+ saved = await check(saved);
4929
+ } catch (error) {
4930
+ failure ??= error;
4931
+ }
4932
+ requests = await releaseGitHubPullRequestReadySync(args.db, target, {
4933
+ id,
4934
+ requests
4935
+ });
4936
+ }
4937
+ if (failure !== void 0) throw failure;
4888
4938
  }
4889
4939
  /**
4890
- * Read one page of a repository's open pull requests by one author, with
4891
- * their mergeability, through GraphQL search and a read-only token.
4940
+ * Add, change, or close the next-action item of each Junior pull request that
4941
+ * a webhook delivery can change. The item is optional, so a failure is logged
4942
+ * and does not fail the delivery.
4892
4943
  */
4893
- async function searchOpenPullRequestMergeability(env, input) {
4894
- const { name } = splitRepository(input.repositoryFullName, "pull request mergeability");
4895
- const token = await issueInstallationToken({
4896
- ...env,
4897
- permissions: { pull_requests: "read" },
4898
- repositories: [name]
4944
+ async function syncGitHubPullRequestActions(args) {
4945
+ await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map(args.targets, async (target) => {
4946
+ try {
4947
+ await syncOne(args, target);
4948
+ } catch (error) {
4949
+ logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
4950
+ deliveryId: args.deliveryId,
4951
+ number: target.number,
4952
+ repository: target.repositoryFullName
4953
+ });
4954
+ }
4899
4955
  });
4900
- return await githubRequest("https://api.github.com", "/graphql", {
4901
- body: {
4902
- ...OPEN_PULL_REQUEST_MERGEABILITY,
4903
- variables: {
4904
- after: input.after ?? null,
4905
- query: `repo:${input.repositoryFullName} is:pr is:open author:${input.author}`
4906
- }
4956
+ }
4957
+ // src/pull-request-outcomes/apply.ts
4958
+ /** Write a pull request outcome as a code change in Junior's code index. */
4959
+ function githubCodeChange(outcome, conversationIds) {
4960
+ return {
4961
+ closedAt: outcome.closedAt,
4962
+ conversationIds,
4963
+ draft: outcome.draft,
4964
+ mergedAt: outcome.mergedAt,
4965
+ number: outcome.number,
4966
+ openedAt: outcome.openedAt,
4967
+ providerId: outcome.pullRequestId,
4968
+ repository: {
4969
+ name: outcome.repositoryFullName,
4970
+ providerId: outcome.repositoryId,
4971
+ url: `https://github.com/${outcome.repositoryFullName}`
4907
4972
  },
4908
- method: "POST",
4909
- token: token.token
4910
- });
4973
+ size: outcome.size,
4974
+ state: outcome.state === "closed_unmerged" ? "closed" : outcome.state,
4975
+ title: outcome.title,
4976
+ updatedAt: outcome.updatedAt,
4977
+ url: `https://github.com/${outcome.repositoryFullName}/pull/${outcome.number}`
4978
+ };
4911
4979
  }
4912
- /** Read the merge conflict history of one pull request, with a read-only token. */
4913
- async function loadPullRequestConflictHistory(env, pullRequest) {
4914
- const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request conflict history");
4915
- const token = await issueInstallationToken({
4916
- ...env,
4917
- permissions: { pull_requests: "read" },
4918
- repositories: [name]
4919
- });
4920
- return await githubRequest("https://api.github.com", "/graphql", {
4921
- body: {
4922
- ...PULL_REQUEST_CONFLICT_HISTORY,
4923
- variables: {
4924
- name,
4925
- number: pullRequest.number,
4926
- owner
4980
+ /**
4981
+ * Record one pull request outcome. When the stored row changes, update the
4982
+ * code index, and mark the chip of each linked conversation merged or closed.
4983
+ * A merged or closed pull request closes its Review items first, so no
4984
+ * reader sees a merged chip next to an open item. A failed chip or item is
4985
+ * logged, so it does not stop the work after it.
4986
+ */
4987
+ async function applyGitHubPullRequestOutcome(args) {
4988
+ const { outcome } = args;
4989
+ const recorded = await recordGitHubPullRequestOutcome(args.db, outcome);
4990
+ if (!recorded.applied) return recorded;
4991
+ await args.codeChanges.record(githubCodeChange(outcome, recorded.conversationIds));
4992
+ if (outcome.state !== "open") {
4993
+ const state = outcome.state === "merged" ? "merged" : "closed";
4994
+ await closeEndedGitHubPullRequestItems({
4995
+ db: args.db,
4996
+ log: args.log,
4997
+ reviewItems: args.reviewItems,
4998
+ state,
4999
+ target: outcome
5000
+ });
5001
+ await updateGitHubAnnotations({
5002
+ annotations: args.annotations,
5003
+ conversationIds: recorded.conversationIds,
5004
+ log: args.log,
5005
+ update: {
5006
+ repo: outcome.repositoryFullName,
5007
+ number: outcome.number,
5008
+ objectType: "code_change",
5009
+ status: state
4927
5010
  }
4928
- },
4929
- method: "POST",
4930
- token: token.token
4931
- });
5011
+ });
5012
+ }
5013
+ return recorded;
4932
5014
  }
4933
- /** Ask people to review one pull request, with a pull request write token. */
4934
- async function requestPullRequestReviewers(env, input) {
4935
- const { owner, name } = splitRepository(input.repositoryFullName, "pull request review request");
4936
- const token = await issueInstallationToken({
4937
- ...env,
4938
- permissions: { pull_requests: "write" },
4939
- repositories: [name]
4940
- });
4941
- await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${input.number}/requested_reviewers`, {
4942
- body: { reviewers: input.reviewers },
4943
- method: "POST",
4944
- token: token.token
4945
- });
5015
+ // src/webhooks/issue-outcome.ts
5016
+ const canonicalIssueOutcomeSchema = z.object({
5017
+ action: z.enum([
5018
+ "opened",
5019
+ "closed",
5020
+ "reopened"
5021
+ ]),
5022
+ issue: z.object({
5023
+ body: z.string().nullable().optional(),
5024
+ closed_at: z.string().nullable().optional(),
5025
+ created_at: z.string(),
5026
+ id: z.number().int().positive(),
5027
+ number: z.number().int().positive(),
5028
+ state_reason: githubIssueStateReasonSchema.nullable().optional(),
5029
+ updated_at: z.string(),
5030
+ user: z.object({ login: z.string().min(1) }).strict()
5031
+ }).strict(),
5032
+ repository: z.object({
5033
+ full_name: z.string().min(1),
5034
+ id: z.number().int().positive()
5035
+ }).strict()
5036
+ }).strict();
5037
+ const issueOutcomeSchema = z.object({
5038
+ action: z.enum([
5039
+ "opened",
5040
+ "closed",
5041
+ "reopened"
5042
+ ]),
5043
+ issue: z.object({
5044
+ body: z.string().nullable().optional(),
5045
+ closed_at: z.string().nullable().optional(),
5046
+ created_at: z.string(),
5047
+ id: z.number().int().positive(),
5048
+ number: z.number().int().positive(),
5049
+ state_reason: githubIssueStateReasonSchema.nullable().optional(),
5050
+ updated_at: z.string(),
5051
+ user: z.object({ login: z.string().min(1) }).passthrough()
5052
+ }).passthrough(),
5053
+ repository: z.object({
5054
+ full_name: z.string().min(1),
5055
+ id: z.number().int().positive()
5056
+ }).passthrough()
5057
+ }).passthrough().transform((provider) => canonicalIssueOutcomeSchema.parse({
5058
+ action: provider.action,
5059
+ issue: {
5060
+ body: provider.issue.body,
5061
+ closed_at: provider.issue.closed_at,
5062
+ created_at: provider.issue.created_at,
5063
+ id: provider.issue.id,
5064
+ number: provider.issue.number,
5065
+ state_reason: provider.issue.state_reason,
5066
+ updated_at: provider.issue.updated_at,
5067
+ user: { login: provider.issue.user.login }
5068
+ },
5069
+ repository: {
5070
+ full_name: provider.repository.full_name,
5071
+ id: provider.repository.id
5072
+ }
5073
+ }));
5074
+ const issueLifecycleActionSchema = z.object({ action: z.string() }).passthrough();
5075
+ /** Parse a provider timestamp, rejecting missing or invalid lifecycle values. */
5076
+ function timestamp$1(value) {
5077
+ if (!value) return void 0;
5078
+ const parsed = new Date(value);
5079
+ return Number.isFinite(parsed.getTime()) ? parsed : void 0;
4946
5080
  }
4947
- /** Add the "reviewing" reaction to one pull request comment or review body. */
4948
- async function markPullRequestFeedbackReviewing(env, target) {
4949
- const { owner, name } = splitRepository(target.repo, "pull request feedback");
4950
- const token = await issueInstallationToken({
4951
- ...env,
4952
- repositories: [name]
4953
- });
4954
- const content = pullRequestFeedbackReactionContent("reviewing");
4955
- if (target.commentKind === "review_body") {
4956
- const review = z.object({ node_id: z.string().min(1) }).parse(await githubRequest("https://api.github.com", pullRequestReviewPath({
4957
- owner,
4958
- name,
4959
- pullRequest: target.pullRequest,
4960
- reviewId: target.commentId
4961
- }), { token: token.token }));
4962
- const result = z.object({ errors: z.array(z.unknown()).optional() }).parse(await githubRequest("https://api.github.com", "/graphql", {
4963
- body: {
4964
- ...ADD_REVIEW_REACTION,
4965
- variables: {
4966
- content: graphqlReactionContent(content),
4967
- subjectId: review.node_id
4968
- }
4969
- },
4970
- method: "POST",
4971
- token: token.token
4972
- }));
4973
- if (result.errors?.length) throw new Error(`GitHub review reaction failed: ${githubErrorMessage$1(result)}`);
4974
- return;
5081
+ /** Normalize only the fields required for the Junior-owned issue projection. */
5082
+ function normalizeGitHubIssueOutcome(args) {
5083
+ const lifecycle = issueLifecycleActionSchema.safeParse(args.body);
5084
+ if (!lifecycle.success || ![
5085
+ "opened",
5086
+ "closed",
5087
+ "reopened"
5088
+ ].includes(lifecycle.data.action)) return;
5089
+ const parsed = issueOutcomeSchema.parse(args.body);
5090
+ const issue = parsed.issue;
5091
+ const openedAt = timestamp$1(issue.created_at);
5092
+ const updatedAt = timestamp$1(issue.updated_at);
5093
+ if (!openedAt || !updatedAt) throw new Error("GitHub issue lifecycle timestamps are invalid");
5094
+ if (parsed.action === "opened" && !botLoginFromEmail(args.botEmail)) throw new Error("The configured GitHub App bot email must encode a [bot] login in GitHub's noreply format to classify issue ownership");
5095
+ const candidateOwned = Boolean(isBotLogin(issue.user.login, args.botEmail) && issue.body?.includes("<!-- junior-session-footer:start -->")) && (parsed.action === "opened" || parsed.action === "closed");
5096
+ const closedAt = timestamp$1(issue.closed_at);
5097
+ if (parsed.action === "closed" && !closedAt) throw new Error("GitHub issue terminal timestamp is invalid");
5098
+ return {
5099
+ candidateOwned,
5100
+ closedAt,
5101
+ issueId: String(issue.id),
5102
+ number: issue.number,
5103
+ openedAt,
5104
+ repositoryFullName: parsed.repository.full_name,
5105
+ repositoryId: String(parsed.repository.id),
5106
+ state: parsed.action === "closed" ? "closed" : "open",
5107
+ stateReason: parsed.action === "closed" ? issue.state_reason ?? void 0 : void 0,
5108
+ updatedAt
5109
+ };
5110
+ }
5111
+ const canonicalIssueConversationSchema = z.object({
5112
+ issue: z.object({
5113
+ body: z.string().nullable().optional(),
5114
+ id: z.number().int().positive(),
5115
+ user: z.object({ login: z.string().min(1) }).strict()
5116
+ }).strict(),
5117
+ sender: z.object({ login: z.string().min(1) }).strict().optional()
5118
+ }).strict();
5119
+ const issueConversationSchema = z.object({
5120
+ issue: z.object({
5121
+ body: z.string().nullable().optional(),
5122
+ id: z.number().int().positive(),
5123
+ user: z.object({ login: z.string().min(1) }).passthrough()
5124
+ }).passthrough(),
5125
+ sender: z.object({ login: z.string().min(1) }).passthrough().optional()
5126
+ }).passthrough().transform((provider) => canonicalIssueConversationSchema.parse({
5127
+ issue: {
5128
+ body: provider.issue.body,
5129
+ id: provider.issue.id,
5130
+ user: { login: provider.issue.user.login }
5131
+ },
5132
+ ...provider.sender ? { sender: { login: provider.sender.login } } : void 0
5133
+ }));
5134
+ /** Normalize native conversation ids written to a Junior-owned issue by its bot. */
5135
+ function normalizeGitHubIssueConversations(args) {
5136
+ const parsed = issueConversationSchema.safeParse(args.body);
5137
+ if (!parsed.success) return void 0;
5138
+ if (!isBotLogin(parsed.data.issue.user.login, args.botEmail)) return;
5139
+ const sender = parsed.data.sender;
5140
+ if (sender && !isBotLogin(sender.login, args.botEmail)) return void 0;
5141
+ const conversationIds = githubConversationIds(parsed.data.issue.body);
5142
+ return conversationIds.length > 0 ? {
5143
+ conversationIds,
5144
+ issueId: String(parsed.data.issue.id)
5145
+ } : void 0;
5146
+ }
5147
+ // src/webhooks/pull-request-outcome.ts
5148
+ const count = z.number().int().nonnegative();
5149
+ const pullRequestLifecycleActionsSchema = z.enum([
5150
+ "opened",
5151
+ "closed",
5152
+ "reopened",
5153
+ "ready_for_review",
5154
+ "converted_to_draft",
5155
+ "synchronize"
5156
+ ]);
5157
+ const canonicalPullRequestOutcomeSchema = z.object({
5158
+ action: pullRequestLifecycleActionsSchema,
5159
+ pull_request: z.object({
5160
+ additions: count.optional(),
5161
+ body: z.string().nullable().optional(),
5162
+ changed_files: count.optional(),
5163
+ closed_at: z.string().nullable().optional(),
5164
+ created_at: z.string(),
5165
+ deletions: count.optional(),
5166
+ draft: z.boolean().optional(),
5167
+ id: z.number().int().positive(),
5168
+ merged: z.boolean(),
5169
+ merged_at: z.string().nullable().optional(),
5170
+ number: z.number().int().positive(),
5171
+ title: z.string().min(1).optional(),
5172
+ updated_at: z.string(),
5173
+ user: z.object({ login: z.string().min(1) }).strict()
5174
+ }).strict(),
5175
+ repository: z.object({
5176
+ full_name: z.string().min(1),
5177
+ id: z.number().int().positive()
5178
+ }).strict()
5179
+ }).strict();
5180
+ const pullRequestOutcomeSchema = z.object({
5181
+ action: pullRequestLifecycleActionsSchema,
5182
+ pull_request: z.object({
5183
+ additions: count.optional(),
5184
+ body: z.string().nullable().optional(),
5185
+ changed_files: count.optional(),
5186
+ closed_at: z.string().nullable().optional(),
5187
+ created_at: z.string(),
5188
+ deletions: count.optional(),
5189
+ draft: z.boolean().optional(),
5190
+ id: z.number().int().positive(),
5191
+ merged: z.boolean(),
5192
+ merged_at: z.string().nullable().optional(),
5193
+ number: z.number().int().positive(),
5194
+ title: z.string().min(1).optional(),
5195
+ updated_at: z.string(),
5196
+ user: z.object({ login: z.string().min(1) }).passthrough()
5197
+ }).passthrough(),
5198
+ repository: z.object({
5199
+ full_name: z.string().min(1),
5200
+ id: z.number().int().positive()
5201
+ }).passthrough()
5202
+ }).passthrough().transform((provider) => canonicalPullRequestOutcomeSchema.parse({
5203
+ action: provider.action,
5204
+ pull_request: {
5205
+ additions: provider.pull_request.additions,
5206
+ body: provider.pull_request.body,
5207
+ changed_files: provider.pull_request.changed_files,
5208
+ closed_at: provider.pull_request.closed_at,
5209
+ created_at: provider.pull_request.created_at,
5210
+ deletions: provider.pull_request.deletions,
5211
+ draft: provider.pull_request.draft,
5212
+ id: provider.pull_request.id,
5213
+ merged: provider.pull_request.merged,
5214
+ merged_at: provider.pull_request.merged_at,
5215
+ number: provider.pull_request.number,
5216
+ title: provider.pull_request.title,
5217
+ updated_at: provider.pull_request.updated_at,
5218
+ user: { login: provider.pull_request.user.login }
5219
+ },
5220
+ repository: {
5221
+ full_name: provider.repository.full_name,
5222
+ id: provider.repository.id
4975
5223
  }
4976
- await githubRequest("https://api.github.com", pullRequestCommentReactionsPath({
4977
- owner,
4978
- name,
4979
- commentKind: target.commentKind,
4980
- commentId: target.commentId
4981
- }), {
4982
- body: { content },
4983
- method: "POST",
4984
- token: token.token
4985
- });
5224
+ }));
5225
+ const pullRequestLifecycleActionSchema = z.object({ action: z.string() }).passthrough();
5226
+ const canonicalPullRequestConversationSchema = z.object({
5227
+ pull_request: z.object({
5228
+ body: z.string().nullable().optional(),
5229
+ id: z.number().int().positive(),
5230
+ user: z.object({ login: z.string().min(1) }).strict()
5231
+ }).strict(),
5232
+ repository: z.object({ full_name: z.string().min(1) }).strict(),
5233
+ sender: z.object({ login: z.string().min(1) }).strict()
5234
+ }).strict();
5235
+ const pullRequestConversationSchema = z.object({
5236
+ pull_request: z.object({
5237
+ body: z.string().nullable().optional(),
5238
+ id: z.number().int().positive(),
5239
+ user: z.object({ login: z.string().min(1) }).passthrough()
5240
+ }).passthrough(),
5241
+ repository: z.object({ full_name: z.string().min(1) }).passthrough(),
5242
+ sender: z.object({ login: z.string().min(1) }).passthrough()
5243
+ }).passthrough().transform((provider) => canonicalPullRequestConversationSchema.parse({
5244
+ pull_request: {
5245
+ body: provider.pull_request.body,
5246
+ id: provider.pull_request.id,
5247
+ user: { login: provider.pull_request.user.login }
5248
+ },
5249
+ repository: { full_name: provider.repository.full_name },
5250
+ sender: { login: provider.sender.login }
5251
+ }));
5252
+ /** Parse a provider timestamp. A missing or invalid value is undefined. */
5253
+ function timestamp(value) {
5254
+ if (!value) return void 0;
5255
+ const parsed = new Date(value);
5256
+ return Number.isFinite(parsed.getTime()) ? parsed : void 0;
5257
+ }
5258
+ /** The size of a pull request payload. Undefined when it counts nothing. */
5259
+ function githubPullRequestSize(pullRequest) {
5260
+ const size = {};
5261
+ if (pullRequest.additions !== void 0) size.additions = pullRequest.additions;
5262
+ if (pullRequest.deletions !== void 0) size.deletions = pullRequest.deletions;
5263
+ if (pullRequest.changed_files !== void 0) size.changedFiles = pullRequest.changed_files;
5264
+ return Object.keys(size).length > 0 ? size : void 0;
5265
+ }
5266
+ /** Normalize only the fields required for the Junior-owned PR projection. */
5267
+ function normalizeGitHubPullRequestOutcome(args) {
5268
+ const lifecycle = pullRequestLifecycleActionSchema.safeParse(args.body);
5269
+ if (!lifecycle.success || !pullRequestLifecycleActionsSchema.safeParse(lifecycle.data.action).success) return;
5270
+ const parsed = pullRequestOutcomeSchema.parse(args.body);
5271
+ const pullRequest = parsed.pull_request;
5272
+ if (parsed.action === "synchronize" && (pullRequest.merged || pullRequest.closed_at)) return;
5273
+ const openedAt = timestamp(pullRequest.created_at);
5274
+ const updatedAt = timestamp(pullRequest.updated_at);
5275
+ if (!openedAt || !updatedAt) throw new Error("GitHub pull request lifecycle timestamps are invalid");
5276
+ if (parsed.action === "opened" && !botLoginFromEmail(args.botEmail)) throw new Error("The configured GitHub App bot email must encode a [bot] login in GitHub's noreply format to classify pull request ownership");
5277
+ const candidateOwned = Boolean(isBotLogin(pullRequest.user.login, args.botEmail) && pullRequest.body?.includes("<!-- junior-session-footer:start -->")) && (parsed.action === "opened" || parsed.action === "closed" || parsed.action === "synchronize");
5278
+ const state = parsed.action !== "closed" ? "open" : pullRequest.merged ? "merged" : "closed_unmerged";
5279
+ const closed = parsed.action === "closed";
5280
+ const closedAt = timestamp(pullRequest.closed_at) ?? (closed ? updatedAt : void 0);
5281
+ const mergedAt = timestamp(pullRequest.merged_at) ?? (closed && pullRequest.merged ? updatedAt : void 0);
5282
+ return {
5283
+ candidateOwned,
5284
+ closedAt,
5285
+ draft: closed ? void 0 : pullRequest.draft,
5286
+ mergedAt,
5287
+ number: pullRequest.number,
5288
+ openedAt,
5289
+ pullRequestId: String(pullRequest.id),
5290
+ repositoryFullName: parsed.repository.full_name,
5291
+ repositoryId: String(parsed.repository.id),
5292
+ size: githubPullRequestSize(pullRequest),
5293
+ state,
5294
+ title: pullRequest.title,
5295
+ updatedAt
5296
+ };
5297
+ }
5298
+ /** Normalize native conversation ids written to a Junior-owned PR by its bot. */
5299
+ function normalizeGitHubPullRequestConversations(args) {
5300
+ const parsed = pullRequestConversationSchema.safeParse(args.body);
5301
+ if (!parsed.success) return void 0;
5302
+ if (!isBotLogin(parsed.data.pull_request.user.login, args.botEmail) || !isBotLogin(parsed.data.sender.login, args.botEmail)) return;
5303
+ const conversationIds = githubConversationIds(parsed.data.pull_request.body);
5304
+ return conversationIds.length > 0 ? {
5305
+ conversationIds,
5306
+ pullRequestId: String(parsed.data.pull_request.id)
5307
+ } : void 0;
5308
+ }
5309
+ /** Normalize linked issues written into a Junior-owned PR body by its bot. */
5310
+ function normalizeGitHubPullRequestLinkedIssues(args) {
5311
+ const parsed = pullRequestConversationSchema.safeParse(args.body);
5312
+ if (!parsed.success) return void 0;
5313
+ if (!isBotLogin(parsed.data.pull_request.user.login, args.botEmail) || !isBotLogin(parsed.data.sender.login, args.botEmail)) return;
5314
+ const linkedIssues = githubLinkedIssues(parsed.data.pull_request.body, parsed.data.repository.full_name);
5315
+ return linkedIssues.length > 0 ? {
5316
+ linkedIssues,
5317
+ pullRequestId: String(parsed.data.pull_request.id)
5318
+ } : void 0;
5319
+ }
5320
+ // src/webhooks/pull-request-activity.ts
5321
+ const timestampSchema = z.iso.datetime({ offset: true });
5322
+ const numberSchema = z.number().int().positive();
5323
+ const repositorySchema$1 = z.object({ id: numberSchema });
5324
+ const senderSchema = z.object({ type: z.string() });
5325
+ const activitySchemas = {
5326
+ issue_comment: z.object({
5327
+ action: z.literal("created"),
5328
+ comment: z.object({ created_at: timestampSchema }),
5329
+ issue: z.object({
5330
+ number: numberSchema,
5331
+ pull_request: z.object({})
5332
+ }),
5333
+ repository: repositorySchema$1,
5334
+ sender: senderSchema
5335
+ }).transform((event) => ({
5336
+ at: new Date(event.comment.created_at),
5337
+ number: event.issue.number,
5338
+ repositoryProviderId: String(event.repository.id),
5339
+ senderType: event.sender.type
5340
+ })),
5341
+ pull_request: z.object({
5342
+ action: z.literal("synchronize"),
5343
+ pull_request: z.object({
5344
+ number: numberSchema,
5345
+ updated_at: timestampSchema
5346
+ }),
5347
+ repository: repositorySchema$1,
5348
+ sender: senderSchema
5349
+ }).transform((event) => ({
5350
+ at: new Date(event.pull_request.updated_at),
5351
+ number: event.pull_request.number,
5352
+ repositoryProviderId: String(event.repository.id),
5353
+ senderType: event.sender.type
5354
+ })),
5355
+ pull_request_review: z.object({
5356
+ action: z.literal("submitted"),
5357
+ pull_request: z.object({ number: numberSchema }),
5358
+ repository: repositorySchema$1,
5359
+ review: z.object({ submitted_at: timestampSchema }),
5360
+ sender: senderSchema
5361
+ }).transform((event) => ({
5362
+ at: new Date(event.review.submitted_at),
5363
+ number: event.pull_request.number,
5364
+ repositoryProviderId: String(event.repository.id),
5365
+ senderType: event.sender.type
5366
+ })),
5367
+ pull_request_review_comment: z.object({
5368
+ action: z.literal("created"),
5369
+ comment: z.object({ created_at: timestampSchema }),
5370
+ pull_request: z.object({ number: numberSchema }),
5371
+ repository: repositorySchema$1,
5372
+ sender: senderSchema
5373
+ }).transform((event) => ({
5374
+ at: new Date(event.comment.created_at),
5375
+ number: event.pull_request.number,
5376
+ repositoryProviderId: String(event.repository.id),
5377
+ senderType: event.sender.type
5378
+ }))
5379
+ };
5380
+ /** Read a person's pull request activity from a webhook, if it has any. */
5381
+ function normalizeGitHubPullRequestActivity(input) {
5382
+ const parsed = (Object.hasOwn(activitySchemas, input.eventName) ? activitySchemas[input.eventName] : void 0)?.safeParse(input.body);
5383
+ if (!parsed?.success) return void 0;
5384
+ const { senderType, ...activity } = parsed.data;
5385
+ return senderType === "Bot" ? void 0 : activity;
4986
5386
  }
4987
- const repositoryPermissionSchema = z.object({
4988
- permission: z.string().min(1),
4989
- role_name: z.string().optional()
5387
+ // src/webhooks/pull-request-preview.ts
5388
+ const previewWebhookSchema = z.object({
5389
+ action: z.enum([
5390
+ "opened",
5391
+ "edited",
5392
+ "synchronize",
5393
+ "ready_for_review"
5394
+ ]),
5395
+ pull_request: z.object({
5396
+ body: z.string().nullable().optional(),
5397
+ id: z.number().int().positive(),
5398
+ number: z.number().int().positive(),
5399
+ updated_at: z.iso.datetime({ offset: true })
5400
+ }),
5401
+ repository: z.object({ full_name: z.string().min(1) })
4990
5402
  });
4991
- const REPOSITORY_ROLE_TTL_MS = 6e5;
4992
5403
  /**
4993
- * Read one user's role on a repository, with a metadata-only token. GitHub
4994
- * returns "none" for accounts without access, such as most bots. Roles are
4995
- * cached for ten minutes.
5404
+ * Set or clear the preview image fact on each chip of a Junior pull request
5405
+ * from the webhook body. One failed conversation does not stop the others.
4996
5406
  */
4997
- async function loadRepositoryRole(env, cache, target) {
4998
- const { owner, name } = splitRepository(target.repositoryFullName, "repository role");
4999
- return await cache.getOrLoad(`repository-role:${owner}/${name}:${target.login}`.toLowerCase(), async () => {
5000
- const token = await issueInstallationToken({
5001
- ...env,
5002
- permissions: { metadata: "read" },
5003
- repositories: [name]
5407
+ async function refreshGitHubPullRequestPreview(args) {
5408
+ const parsed = previewWebhookSchema.safeParse(args.body);
5409
+ if (!parsed.success) return;
5410
+ const { pull_request: pullRequest, repository } = parsed.data;
5411
+ const conversationIds = await readGitHubPullRequestConversationIds(args.db, String(pullRequest.id));
5412
+ if (conversationIds.length === 0) return;
5413
+ const key = `${repository.full_name.toLowerCase()}#${pullRequest.number}`;
5414
+ const previewImageUrls = githubPreviewImageUrls(pullRequest.body);
5415
+ const updatedAt = Date.parse(pullRequest.updated_at);
5416
+ const limit = pLimit(8);
5417
+ const results = await Promise.allSettled(conversationIds.map((conversationId) => limit(async () => {
5418
+ const store = args.annotations.forConversation(conversationId);
5419
+ const current = (await store.list()).find((annotation) => annotation.key === key);
5420
+ if (current?.kind !== "object" || current.facts?.type !== "code_change") return;
5421
+ const storedAt = current.sourceUpdatedAt ? Date.parse(current.sourceUpdatedAt) : void 0;
5422
+ if (storedAt !== void 0 && storedAt > updatedAt) return;
5423
+ const { plugin: _plugin, createdAt: _createdAt, updatedAt: _updatedAt, facts: { previewImageUrls: previous, ...facts }, ...annotation } = current;
5424
+ const next = withGitHubPreviewImages(facts, previewImageUrls);
5425
+ if (previous?.join("\n") === next.previewImageUrls?.join("\n") && storedAt === updatedAt) return;
5426
+ await store.upsert({
5427
+ ...annotation,
5428
+ facts: next,
5429
+ sourceUpdatedAt: pullRequest.updated_at
5004
5430
  });
5005
- const response = repositoryPermissionSchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/collaborators/${encodeURIComponent(target.login)}/permission`, { token: token.token }));
5006
- return {
5007
- value: response.role_name?.trim() || response.permission,
5008
- ttlMs: REPOSITORY_ROLE_TTL_MS
5009
- };
5010
- });
5431
+ })));
5432
+ for (const result of results) {
5433
+ if (result.status === "fulfilled") continue;
5434
+ args.log?.error("GitHub pull request preview update failed", {
5435
+ errorType: result.reason instanceof Error ? result.reason.name : "UnknownError",
5436
+ number: pullRequest.number,
5437
+ repository: repository.full_name
5438
+ });
5439
+ }
5011
5440
  }
5012
- const pullRequestSchema = z.object({
5013
- auto_merge: z.object({}).nullable().optional(),
5441
+ // src/webhooks/merge-conflict.ts
5442
+ const PULL_REQUEST_CHECK_CONCURRENCY = 5;
5443
+ const EVENT_TYPE = "pull_request.merge_conflict";
5444
+ /** Events after which the pull request cannot get a conflict. */
5445
+ const CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set(["pull_request.closed_unmerged", "pull_request.merged"]);
5446
+ /** The pull request fields that tell if it has a conflict. */
5447
+ const gitHubPullRequestMergeSchema = z.object({
5448
+ base: z.object({ ref: z.string().min(1) }),
5014
5449
  draft: z.boolean().optional(),
5450
+ number: z.number().int().positive().optional(),
5015
5451
  head: z.object({ sha: z.string().min(1) }),
5016
- html_url: z.string().url(),
5017
- mergeable_state: z.string().nullable().optional(),
5018
- merged: z.boolean(),
5019
- requested_reviewers: z.array(z.object({ login: z.string().min(1) })).optional(),
5020
- state: z.enum(["open", "closed"]),
5021
- title: z.string()
5452
+ html_url: z.string().min(1).optional(),
5453
+ mergeable: z.boolean().nullable().optional(),
5454
+ mergeable_state: z.string().optional(),
5455
+ state: z.string(),
5456
+ title: z.string().optional()
5022
5457
  });
5023
5458
  /**
5024
- * Read whether a pull request is ready to merge, and whether the requester
5025
- * changed their review, with a read-only token. GitHub computes
5026
- * `mergeable_state` after a change, so an unknown state is read once more.
5027
- * Reviews load for an open pull request that is not a draft, when it can
5028
- * merge cleanly or GitHub does not ask the requester for a review. Each
5029
- * reviewer counts by their latest approval, change request, or dismissal.
5030
- * Comments do not change the result.
5459
+ * Build the `pull_request.merge_conflict` copies for one pull request. With
5460
+ * no conflict, the copies have only the values that filters can match. The
5461
+ * event key names the head commit, so each head commit publishes once.
5031
5462
  */
5032
- async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
5033
- const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request merge state");
5034
- const token = await issueInstallationToken({
5035
- ...env,
5036
- permissions: { pull_requests: "read" },
5037
- repositories: [name]
5463
+ function gitHubMergeConflictEvents(input) {
5464
+ const { conflict } = input;
5465
+ const repo = gitHubRepoDataSchema.parse(input.repositoryFullName);
5466
+ const resource = gitHubPullRequestResource({
5467
+ number: input.number,
5468
+ repo
5038
5469
  });
5039
- const read = async (path) => await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}${path}`, { token: token.token });
5040
- const readPull = async () => {
5041
- const pull = pullRequestSchema.parse(await read(""));
5042
- const mergeableState = pull.mergeable_state && pull.mergeable_state !== "unknown" ? pull.mergeable_state : void 0;
5043
- return {
5044
- approved: false,
5045
- autoMerge: Boolean(pull.auto_merge),
5046
- draft: pull.draft === true,
5047
- headSha: pull.head.sha,
5048
- ...mergeableState ? { mergeableState } : void 0,
5049
- requestedReviewers: (pull.requested_reviewers ?? []).map((reviewer) => reviewer.login),
5050
- state: pull.merged ? "merged" : pull.state,
5051
- title: pull.title,
5052
- url: pull.html_url
5053
- };
5054
- };
5055
- let state = await readPull();
5056
- if (state.state !== "open" || state.draft) return state;
5057
- const canMerge = !state.autoMerge;
5058
- if (canMerge && !state.mergeableState) state = await readPull();
5059
- const login = requesterLogin?.toLowerCase();
5060
- const readsChanges = login !== void 0 && !state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === login);
5061
- const readsApproval = canMerge && state.mergeableState === "clean";
5062
- if (!readsApproval && !readsChanges) return state;
5063
- const latestReviews = await loadLatestReviews(async (query) => await read(`/reviews?${query}`));
5064
- const reviewStates = [...latestReviews.values()].map((review) => review.state);
5065
- if (readsApproval) state.approved = reviewStates.includes("APPROVED") && !reviewStates.includes("CHANGES_REQUESTED");
5066
- const requesterReview = login ? latestReviews.get(login) : void 0;
5067
- if (requesterReview?.state === "CHANGES_REQUESTED" && requesterReview.commit_id) state.changesRequestedCommit = requesterReview.commit_id;
5068
- return state;
5470
+ return pullRequestTargets({
5471
+ eventKey: `github:merge-conflict:${resource.identifier}${conflict ? `:${conflict.headSha}` : ""}`,
5472
+ eventType: EVENT_TYPE,
5473
+ identifier: resource.identifier,
5474
+ objectType: "code_change",
5475
+ occurredAtMs: Date.now(),
5476
+ trustedSummary: `${resource.label} has merge conflicts${conflict ? ` with ${conflict.baseBranch}` : ""}.`,
5477
+ data: {
5478
+ repo,
5479
+ pullRequest: input.number,
5480
+ ...conflict
5481
+ }
5482
+ }, repo);
5483
+ }
5484
+ /** Open pull requests that the delivered events are about. */
5485
+ function pullRequestRefs(events) {
5486
+ const refs = /* @__PURE__ */ new Map();
5487
+ for (const event of events) {
5488
+ const { pullRequest, repo } = event.data ?? {};
5489
+ if (!event.eventType.startsWith("pull_request.") || CLOSED_EVENT_TYPES.has(event.eventType) || typeof pullRequest !== "number" || typeof repo !== "string") continue;
5490
+ refs.set(`${repo}#${pullRequest}`, {
5491
+ number: pullRequest,
5492
+ repositoryFullName: repo
5493
+ });
5494
+ }
5495
+ return [...refs.values()];
5069
5496
  }
5070
- // src/webhooks/pull-request-action.ts
5071
- const PULL_REQUEST_SYNC_CONCURRENCY = 5;
5072
5497
  /**
5073
- * A check normally takes a few seconds. After this time, a check that
5074
- * stopped without its release no longer blocks new checks.
5498
+ * Return the pull request from a `pull_request` webhook payload when it is
5499
+ * `ref` and GitHub already knows its mergeability. Other webhooks, such as
5500
+ * reviews, comments, and check results, do not send mergeability.
5075
5501
  */
5076
- const READY_SYNC_STALE_MS = 6e4;
5077
- /** Webhook actions that can change the next action of a pull request. */
5078
- const ACTION_EVENTS = {
5079
- pull_request: /* @__PURE__ */ new Set([
5080
- "auto_merge_disabled",
5081
- "auto_merge_enabled",
5082
- "closed",
5083
- "converted_to_draft",
5084
- "ready_for_review",
5085
- "reopened",
5086
- "review_request_removed",
5087
- "review_requested",
5088
- "synchronize"
5089
- ]),
5090
- pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
5091
- };
5502
+ function deliveredPullRequest(payload, ref) {
5503
+ const parsed = z.object({ pull_request: gitHubPullRequestMergeSchema }).safeParse(payload);
5504
+ const pullRequest = parsed.success ? parsed.data.pull_request : void 0;
5505
+ return pullRequest?.number === ref.number && typeof pullRequest.mergeable === "boolean" ? pullRequest : void 0;
5506
+ }
5092
5507
  /**
5093
- * Keys of the two items that came before the one item per pull request.
5094
- * Each check closes them, so no old item stays open next to the new one.
5095
- * Remove them when no item from before is open.
5508
+ * Return `pull_request.merge_conflict` events for the open pull requests that
5509
+ * these events are about, when a Watch or event automation wants them and
5510
+ * GitHub reports a conflict. A `pull_request` webhook payload gives the
5511
+ * mergeability when GitHub knows it. Otherwise the check reads the pull
5512
+ * request, which also makes GitHub calculate its mergeability. When GitHub
5513
+ * does not know it yet, a later event reads it again. The policy in
5514
+ * `merge-conflict-checks/policy.ts` decides if a conflict publishes.
5096
5515
  */
5097
- const LEGACY_DEDUPE_PREFIXES = ["pull-request-ready:", "pull-request-review-requested:"];
5098
- async function closeLegacyItems(items, name) {
5099
- await Promise.all(LEGACY_DEDUPE_PREFIXES.map((prefix) => items.close({
5100
- dedupeKey: `${prefix}${name}`,
5101
- reason: "One item now shows the next action.",
5102
- status: "dismissed"
5103
- })));
5104
- }
5105
- const pullRequestWebhookSchema = z.object({
5106
- action: z.string(),
5107
- pull_request: z.object({ number: z.number().int().positive() }),
5108
- repository: z.object({ full_name: z.string().min(1) })
5109
- });
5110
- /** Return the pull requests whose next action one webhook delivery can change. */
5111
- function pullRequestActionTargets(eventName, body) {
5112
- if (eventName === "check_suite") return checkSuitePullRequests(body);
5113
- const actions = ACTION_EVENTS[eventName];
5114
- const parsed = pullRequestWebhookSchema.safeParse(body);
5115
- if (!actions || !parsed.success || !actions.has(parsed.data.action)) return [];
5116
- return [{
5117
- number: parsed.data.pull_request.number,
5118
- repositoryFullName: parsed.data.repository.full_name
5119
- }];
5516
+ async function loadGitHubMergeConflictEvents(args) {
5517
+ const { hasMatch, loadConflictHistory, loadPullRequest } = args;
5518
+ if (!hasMatch || !loadPullRequest || !loadConflictHistory) return [];
5519
+ const check = async (ref) => {
5520
+ if (!await hasMatch(gitHubMergeConflictEvents(ref))) return [];
5521
+ try {
5522
+ const loaded = deliveredPullRequest(args.pullRequestPayload, ref) ?? gitHubPullRequestMergeSchema.parse(await loadPullRequest(ref));
5523
+ if (loaded.state !== "open" || loaded.mergeable !== false || loaded.mergeable_state !== "dirty") return [];
5524
+ const conflict = {
5525
+ baseBranch: loaded.base.ref,
5526
+ headSha: loaded.head.sha,
5527
+ ...loaded.html_url ? { url: loaded.html_url } : void 0
5528
+ };
5529
+ return await applyGitHubConflictPolicy({
5530
+ conflict,
5531
+ db: args.db,
5532
+ draft: loaded.draft === true,
5533
+ events: gitHubMergeConflictEvents({
5534
+ ...ref,
5535
+ conflict
5536
+ }),
5537
+ loadHistory: loadConflictHistory,
5538
+ log: args.log,
5539
+ now: /* @__PURE__ */ new Date(),
5540
+ ref,
5541
+ reviewItems: args.reviewItems,
5542
+ ...loaded.title ? { title: loaded.title } : void 0
5543
+ });
5544
+ } catch (error) {
5545
+ logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
5546
+ deliveryId: args.deliveryId,
5547
+ pullRequest: ref.number,
5548
+ repository: ref.repositoryFullName
5549
+ });
5550
+ return [];
5551
+ }
5552
+ };
5553
+ return (await pLimit(PULL_REQUEST_CHECK_CONCURRENCY).map(pullRequestRefs(args.events), (ref) => check(ref))).flat();
5120
5554
  }
5555
+ // src/merge-conflict-checks/store.ts
5556
+ /** A key that waits longer than this was lost and expires. */
5557
+ const CHECK_TTL_MS = 18e5;
5121
5558
  /**
5122
- * Derive the requester's next action. Return undefined when it cannot be
5123
- * known yet, so a later event decides.
5559
+ * The heartbeat's own record of a running or repeated check. Only the
5560
+ * heartbeat writes it, so it needs no lock.
5124
5561
  */
5125
- function nextAction(state, requesterLogin, saved) {
5126
- if (state.state !== "open") return {};
5127
- const canMerge = !state.draft && !state.autoMerge;
5128
- if (canMerge && state.mergeableState === "clean" && state.approved) return { action: "merge" };
5129
- if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5130
- const login = requesterLogin?.toLowerCase();
5131
- if (login && state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === login)) return { action: "review" };
5132
- if (state.changesRequestedCommit && state.changesRequestedCommit !== state.headSha) return {
5133
- action: "review",
5134
- rereview: true
5135
- };
5136
- if (canMerge && !state.mergeableState) return void 0;
5137
- return {};
5562
+ const repeatSchema = z.object({
5563
+ /** Checks since the last push that ended with an unknown answer. */
5564
+ attempts: z.number().int().positive(),
5565
+ dueAtMs: z.number()
5566
+ });
5567
+ function pushKey(repositoryFullName) {
5568
+ return `merge-conflict-check:push:${repositoryFullName}`;
5138
5569
  }
5139
- /** Why an item closes when its pull request is no longer open. */
5140
- function endedReason(state) {
5141
- if (state.state === "merged") return {
5142
- reason: "The pull request merged.",
5143
- status: "done"
5144
- };
5145
- if (state.state === "closed") return {
5146
- reason: "The pull request closed without merging.",
5147
- status: "dismissed"
5148
- };
5570
+ function repeatKey(repositoryFullName) {
5571
+ return `merge-conflict-check:repeat:${repositoryFullName}`;
5149
5572
  }
5150
- function closeReason(state, previous) {
5151
- const ended = endedReason(state);
5152
- if (ended) return ended;
5153
- if (previous === "review") return {
5154
- reason: "The review request ended.",
5155
- status: "done"
5156
- };
5157
- if (state.autoMerge) return {
5158
- reason: "Auto-merge is on.",
5159
- status: "dismissed"
5160
- };
5161
- return {
5162
- reason: "The pull request is no longer ready to merge.",
5163
- status: "dismissed"
5164
- };
5573
+ /** Return the repositories that have open Junior pull requests. */
5574
+ async function listGitHubRepositoriesWithOpenPullRequests(db, repositoryFullName) {
5575
+ const t = juniorGitHubPullRequests;
5576
+ return (await db.selectDistinct({ repositoryFullName: t.repositoryFullName }).from(t).where(and(eq(t.state, "open"), repositoryFullName ? eq(t.repositoryFullName, repositoryFullName) : void 0)).orderBy(t.repositoryFullName)).map((row) => row.repositoryFullName);
5165
5577
  }
5166
- async function showAction(items, args) {
5167
- const { action, number, state } = args;
5168
- if (action) await items.upsert({
5169
- assigneeIdentityIds: [args.identityId],
5170
- body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` : args.rereview ? `#${number} has new commits since you requested changes.\n\n${state.url}` : `GitHub asks you to review #${number}.\n\n${state.url}`,
5171
- dedupeKey: args.dedupeKey,
5172
- subject: {
5173
- id: state.url,
5174
- title: `${state.title} (#${number})`,
5175
- url: state.url
5176
- },
5177
- title: action === "merge" ? `Ready to merge · #${number}` : `Review requested · #${number}`,
5178
- waitsOnAssignees: true
5179
- });
5180
- else if (args.previous) await items.close({
5181
- dedupeKey: args.dedupeKey,
5182
- ...closeReason(state, args.previous)
5183
- });
5578
+ /**
5579
+ * Add a check at `dueAtMs` for a repository with open Junior pull requests.
5580
+ * A check that already waits keeps its earlier time, so pushes that keep
5581
+ * coming do not delay it. Return whether a check waits.
5582
+ */
5583
+ async function scheduleGitHubConflictCheck(args) {
5584
+ if ((await listGitHubRepositoriesWithOpenPullRequests(args.db, args.repositoryFullName)).length === 0) return false;
5585
+ await args.state.setIfNotExists(pushKey(args.repositoryFullName), args.dueAtMs, CHECK_TTL_MS);
5586
+ return true;
5184
5587
  }
5185
- async function syncOne(args, target) {
5186
- const opener = (await listGitHubPullRequestOpeners(args.db, {
5187
- numbers: [target.number],
5188
- repositoryFullName: target.repositoryFullName
5189
- })).get(target.number);
5190
- if (!opener?.conversationId) return;
5191
- const items = args.reviewItems.forConversation(opener.conversationId);
5192
- const name = `${target.repositoryFullName}#${target.number}`.toLowerCase();
5193
- const dedupeKey = `pull-request-action:${name}`;
5194
- const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
5195
- const claim = await claimGitHubPullRequestReadySync(args.db, target, {
5196
- now: /* @__PURE__ */ new Date(),
5197
- staleMs: READY_SYNC_STALE_MS
5198
- });
5199
- if (!claim) return;
5200
- const { id } = claim;
5201
- let saved = claim.action;
5202
- let requests = claim.requests;
5203
- let failure;
5204
- const check = async (previous) => {
5205
- const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
5206
- const next = nextAction(state, requesterLogin, previous);
5207
- const changed = next !== void 0 && next.action !== previous;
5208
- if (changed) await showAction(items, {
5209
- action: next.action,
5210
- dedupeKey,
5211
- identityId: opener.identityId,
5212
- number: target.number,
5213
- previous,
5214
- rereview: next.rereview === true,
5215
- state
5216
- });
5217
- await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
5218
- dedupeKey: gitHubConflictNoticeKey(target),
5219
- ...endedReason(state) ?? {
5220
- reason: "The pull request no longer has merge conflicts.",
5221
- status: "done"
5222
- }
5223
- }) : void 0]);
5224
- if (!changed) return previous;
5225
- await setGitHubPullRequestNextAction(args.db, {
5226
- ...target,
5227
- action: next.action
5228
- });
5229
- return next.action;
5588
+ /**
5589
+ * Claim the due check of a repository. The claim removes the push key
5590
+ * before the check reads GitHub, so the read includes every push that the
5591
+ * key held, and a later push adds a new key. A repeat at `claimedUntilMs`
5592
+ * runs the check again when it stops without an end.
5593
+ */
5594
+ async function claimGitHubConflictCheck(args) {
5595
+ const pushDueAtMs = await args.state.get(pushKey(args.repositoryFullName));
5596
+ const repeat = repeatSchema.safeParse(await args.state.get(repeatKey(args.repositoryFullName)));
5597
+ let attempts;
5598
+ if (typeof pushDueAtMs === "number" && pushDueAtMs <= args.nowMs) attempts = 1;
5599
+ else if (repeat.success && repeat.data.dueAtMs <= args.nowMs) attempts = repeat.data.attempts + 1;
5600
+ else return;
5601
+ await args.state.set(repeatKey(args.repositoryFullName), {
5602
+ attempts,
5603
+ dueAtMs: args.claimedUntilMs
5604
+ }, CHECK_TTL_MS);
5605
+ if (attempts === 1) await args.state.delete(pushKey(args.repositoryFullName));
5606
+ return {
5607
+ attempts,
5608
+ repositoryFullName: args.repositoryFullName
5230
5609
  };
5231
- while (requests !== void 0) {
5232
- try {
5233
- saved = await check(saved);
5234
- } catch (error) {
5235
- failure ??= error;
5236
- }
5237
- requests = await releaseGitHubPullRequestReadySync(args.db, target, {
5238
- id,
5239
- requests
5240
- });
5610
+ }
5611
+ /** End a claimed check, or repeat it at `retryAtMs`. */
5612
+ async function settleGitHubConflictCheck(state, check, retryAtMs) {
5613
+ if (retryAtMs === void 0) {
5614
+ await state.delete(repeatKey(check.repositoryFullName));
5615
+ return;
5241
5616
  }
5242
- if (failure !== void 0) throw failure;
5617
+ await state.set(repeatKey(check.repositoryFullName), {
5618
+ attempts: check.attempts,
5619
+ dueAtMs: retryAtMs
5620
+ }, CHECK_TTL_MS);
5243
5621
  }
5622
+ // src/merge-conflict-checks/webhooks.ts
5244
5623
  /**
5245
- * Add, change, or close the next-action item of each Junior pull request that
5246
- * a webhook delivery can change. The item is optional, so a failure is logged
5247
- * and does not fail the delivery.
5624
+ * Time from a push to its check. GitHub calculates mergeability after a
5625
+ * push, and pushes in this time share one check.
5248
5626
  */
5249
- async function syncGitHubPullRequestActions(args) {
5250
- await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map(args.targets, async (target) => {
5251
- try {
5252
- await syncOne(args, target);
5253
- } catch (error) {
5254
- logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
5255
- deliveryId: args.deliveryId,
5256
- number: target.number,
5257
- repository: target.repositoryFullName
5258
- });
5259
- }
5627
+ const CONFLICT_CHECK_DELAY_MS = 12e4;
5628
+ const pushSchema = z.object({
5629
+ deleted: z.boolean().optional(),
5630
+ ref: z.string(),
5631
+ repository: z.object({
5632
+ default_branch: z.string().min(1),
5633
+ full_name: z.string().min(1)
5634
+ })
5635
+ });
5636
+ /**
5637
+ * Schedule a check after a push to a repository's default branch. Stacked
5638
+ * pull requests do not need this, because Junior restacks them when it
5639
+ * pushes the branch below. Return whether a check waits.
5640
+ */
5641
+ async function scheduleGitHubPushConflictCheck(args) {
5642
+ const parsed = pushSchema.safeParse(args.body);
5643
+ if (!parsed.success || parsed.data.deleted || parsed.data.ref !== `refs/heads/${parsed.data.repository.default_branch}`) return false;
5644
+ return await scheduleGitHubConflictCheck({
5645
+ db: args.db,
5646
+ dueAtMs: args.now.getTime() + CONFLICT_CHECK_DELAY_MS,
5647
+ repositoryFullName: parsed.data.repository.full_name,
5648
+ state: args.state
5260
5649
  });
5261
5650
  }
5262
5651
  // src/webhooks/pull-request-ready-reviewers.ts
@@ -5718,7 +6107,8 @@ function createGitHubWebhookRoute(args) {
5718
6107
  codeChanges: args.codeChanges,
5719
6108
  db: args.db,
5720
6109
  log: args.log,
5721
- outcome: pullRequestOutcome
6110
+ outcome: pullRequestOutcome,
6111
+ reviewItems: args.reviewItems
5722
6112
  });
5723
6113
  if (recordedOutcome.applied && !recordedOutcome.commitComposition && pullRequestOutcome.state === "merged" && args.classifyPullRequestCommits) {
5724
6114
  let commitComposition;
@@ -5850,6 +6240,7 @@ function createGitHubWebhookRoute(args) {
5850
6240
  objectType: event.eventType.startsWith("pull_request.") ? "code_change" : event.eventType.startsWith("issue.") ? "task" : event.eventType.startsWith("deployment.") ? "deployment" : "item"
5851
6241
  });
5852
6242
  await syncGitHubPullRequestActions({
6243
+ botEmail,
5853
6244
  db: args.db,
5854
6245
  deliveryId,
5855
6246
  env: {
@@ -5967,7 +6358,7 @@ async function checkRepository(args, repositoryFullName) {
5967
6358
  title: node.title
5968
6359
  });
5969
6360
  }
5970
- await closeGitHubConflictNotices({
6361
+ await closeGitHubConflictItems({
5971
6362
  db: args.db,
5972
6363
  log: args.log,
5973
6364
  numbers: mergeable,
@@ -6016,6 +6407,64 @@ async function runGitHubConflictChecks(args) {
6016
6407
  await runCheck(args, check);
6017
6408
  }
6018
6409
  }
6410
+ // src/merge-conflict-checks/resume.ts
6411
+ /**
6412
+ * Resume merge conflict fixes of one open Junior pull request, and start a
6413
+ * fix when it is not a draft and GitHub does not say that it can merge.
6414
+ * Safe to repeat for one item: the event key names the item, so a retry publishes no second fix.
6415
+ */
6416
+ async function resumeGitHubConflictFixes(args) {
6417
+ const t = juniorGitHubPullRequests;
6418
+ const [row] = await args.db.select({
6419
+ fixes: t.conflictFixes,
6420
+ resumedAt: t.conflictFixesResumedAt
6421
+ }).from(t).where(and(pullRequestRow(args.ref), eq(t.state, "open")));
6422
+ if (!row) return;
6423
+ const resumedAt = new Date(args.nowMs);
6424
+ if ((await args.db.update(t).set({ conflictFixesResumedAt: resumedAt }).where(and(pullRequestRow(args.ref), eq(t.state, "open"))).returning({ pullRequestId: t.pullRequestId })).length === 0) return;
6425
+ const undo = () => args.db.update(t).set({
6426
+ conflictFixAskedAt: null,
6427
+ conflictFixesResumedAt: row.resumedAt
6428
+ }).where(and(pullRequestRow(args.ref), eq(t.conflictFixesResumedAt, resumedAt)));
6429
+ const loaded = gitHubPullRequestMergeSchema.parse(await args.loadPullRequest(args.ref));
6430
+ if (loaded.state !== "open" || loaded.mergeable === true || loaded.draft === true) {
6431
+ await undo();
6432
+ return;
6433
+ }
6434
+ const events = gitHubMergeConflictEvents({
6435
+ ...args.ref,
6436
+ conflict: {
6437
+ baseBranch: loaded.base.ref,
6438
+ headSha: loaded.head.sha,
6439
+ ...loaded.html_url ? { url: loaded.html_url } : void 0
6440
+ }
6441
+ }).map((event) => ({
6442
+ ...event,
6443
+ eventKey: `${event.eventKey}:resume:${args.itemId}`
6444
+ }));
6445
+ const resource = gitHubPullRequestSubscribable({
6446
+ canSubscribe: args.watches.canSubscribe,
6447
+ number: args.ref.number,
6448
+ repo: args.ref.repositoryFullName
6449
+ });
6450
+ if (args.subscription && resource && !await args.watches.watching({
6451
+ eventType: "pull_request.merge_conflict",
6452
+ identifier: resource.identifier
6453
+ })) await args.watches.subscribe({
6454
+ ...gitHubPullRequestCreateWatch(args.subscription, { draft: false }),
6455
+ resource
6456
+ });
6457
+ try {
6458
+ for (const event of events) await args.events.publish(event);
6459
+ } catch (error) {
6460
+ await undo();
6461
+ throw error;
6462
+ }
6463
+ await args.db.update(t).set({ conflictFixes: withGitHubConflictFix(row.fixes, {
6464
+ atMs: args.nowMs,
6465
+ headSha: loaded.head.sha
6466
+ }) }).where(pullRequestRow(args.ref));
6467
+ }
6019
6468
  // src/pull-request-outcomes/reconcile.ts
6020
6469
  /**
6021
6470
  * Time between the reconciles of one repository. A row with a newer
@@ -6093,7 +6542,8 @@ async function reconcileDraft(args, repository, pullRequest) {
6093
6542
  codeChanges: args.codeChanges,
6094
6543
  db: args.db,
6095
6544
  log: args.log,
6096
- outcome
6545
+ outcome,
6546
+ reviewItems: args.reviewItems
6097
6547
  });
6098
6548
  }
6099
6549
  async function reconcileRepository(args, repositoryId, drafts) {
@@ -6160,7 +6610,7 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
6160
6610
  ...event,
6161
6611
  objectType: "code_change"
6162
6612
  });
6163
- await closeGitHubConflictNotice({
6613
+ await closeGitHubConflictItem({
6164
6614
  db: args.db,
6165
6615
  ref: {
6166
6616
  number: pullRequest.number,
@@ -6180,7 +6630,8 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
6180
6630
  codeChanges: args.codeChanges,
6181
6631
  db: args.db,
6182
6632
  log: args.log,
6183
- outcome
6633
+ outcome,
6634
+ reviewItems: args.reviewItems
6184
6635
  });
6185
6636
  }
6186
6637
  /**
@@ -6218,6 +6669,27 @@ async function reconcileGitHubPullRequests(args) {
6218
6669
  }
6219
6670
  // src/events/declarations.ts
6220
6671
  const NEEDS_REPO = { anyOf: ["repo"] };
6672
+ /** How each Event reads after the name of its pull request or issue. */
6673
+ const GITHUB_EVENT_PHRASES = {
6674
+ "issue.closed": "is closed",
6675
+ "issue.comment.created": "gets a new comment",
6676
+ "issue.opened": "is opened",
6677
+ "issue.reopened": "is reopened",
6678
+ "issue.updated": "is edited",
6679
+ "pull_request.checks.failed": "fails its checks",
6680
+ "pull_request.checks.passed": "passes its checks",
6681
+ "pull_request.checks.recovered": "passes its checks again",
6682
+ "pull_request.closed_unmerged": "is closed without merging",
6683
+ "pull_request.comment.created": "gets a new comment",
6684
+ "pull_request.merge_conflict": "gets a merge conflict",
6685
+ "pull_request.merged": "is merged",
6686
+ "pull_request.opened": "is opened",
6687
+ "pull_request.ready_for_review": "is ready for review",
6688
+ "pull_request.review.approved": "is approved",
6689
+ "pull_request.review.changes_requested": "gets changes requested",
6690
+ "pull_request.review.commented": "gets a review comment",
6691
+ "pull_request.review_comment.created": "gets an inline review comment"
6692
+ };
6221
6693
  /**
6222
6694
  * Declare the reach and guidance of every GitHub event.
6223
6695
  *
@@ -6236,9 +6708,16 @@ const NEEDS_REPO = { anyOf: ["repo"] };
6236
6708
  function gitHubEventDeclarations(pullRequestGuidance) {
6237
6709
  const declarations = {};
6238
6710
  for (const eventType of GITHUB_DEPLOYMENT_EVENTS) declarations[eventType] = { reach: "all" };
6239
- for (const eventType of [...GITHUB_RELEASE_EVENTS, ...GITHUB_ISSUE_EVENTS]) declarations[eventType] = { reach: NEEDS_REPO };
6711
+ for (const eventType of GITHUB_RELEASE_EVENTS) declarations[eventType] = { reach: NEEDS_REPO };
6712
+ for (const eventType of GITHUB_ISSUE_EVENTS) declarations[eventType] = {
6713
+ phrase: GITHUB_EVENT_PHRASES[eventType],
6714
+ reach: NEEDS_REPO
6715
+ };
6240
6716
  for (const eventType of GITHUB_PULL_REQUEST_EVENTS) {
6241
- const declaration = { reach: NEEDS_REPO };
6717
+ const declaration = {
6718
+ phrase: GITHUB_EVENT_PHRASES[eventType],
6719
+ reach: NEEDS_REPO
6720
+ };
6242
6721
  const guidance = pullRequestGuidance[eventType];
6243
6722
  if (guidance) declaration.guidance = guidance;
6244
6723
  declarations[eventType] = declaration;
@@ -6254,6 +6733,36 @@ function gitHubResourceUrl(input) {
6254
6733
  if (input.resourceType === "pull_request") return `https://github.com/${repo}/pull/${number}`;
6255
6734
  if (input.resourceType === "issue") return `https://github.com/${repo}/issues/${number}`;
6256
6735
  }
6736
+ const RESOURCE_PAGES = /* @__PURE__ */ new Map([["issues", "issue"], ["pull", "pull_request"]]);
6737
+ /**
6738
+ * Name the watched resource of one github.com page: a repository, or a pull
6739
+ * request or issue and its subpages, such as `/pull/12/files`.
6740
+ */
6741
+ function gitHubUrlResource(url) {
6742
+ let parsed;
6743
+ try {
6744
+ parsed = new URL(url);
6745
+ } catch {
6746
+ return;
6747
+ }
6748
+ if (parsed.protocol !== "https:" || parsed.hostname !== "github.com") return;
6749
+ const [owner, repo, page, number] = parsed.pathname.split("/").filter(Boolean);
6750
+ if (!owner || !repo) return void 0;
6751
+ const repository = `${owner}/${repo}`.toLowerCase();
6752
+ if (!page) return {
6753
+ identifier: repository,
6754
+ resourceType: "repository"
6755
+ };
6756
+ const resourceType = RESOURCE_PAGES.get(page);
6757
+ if (!resourceType || !number || !/^\d+$/.test(number)) return void 0;
6758
+ return {
6759
+ identifier: `${repository}#${number}`,
6760
+ resourceType
6761
+ };
6762
+ }
6763
+ // src/db/database.ts
6764
+ /** Parse the shared database of a plugin context as the GitHub database. */
6765
+ const gitHubDbSchema = z.custom((value) => typeof value === "object" && value !== null && "select" in value && "update" in value, "Expected a Drizzle Postgres database");
6257
6766
  // src/pull-request-outcomes/commit-composition.ts
6258
6767
  const canonicalCommitSchema = z.object({
6259
6768
  authorEmail: z.string().nullable(),
@@ -6755,6 +7264,7 @@ const REPO$1 = "[A-Za-z0-9._-]+";
6755
7264
  const SHA$1 = "[0-9a-f]{7,40}";
6756
7265
  const START = "(?<![\\w.\\-/@&<\\\\])";
6757
7266
  const END = "(?![\\w-])";
7267
+ const PROSE_REPOSITORY_PATTERN = new RegExp(`(?<![\\w.\\-/@&<\\\\:])(?<owner>${LOGIN})\\/(?<repo>[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)(?<!\\.git)(?![\\w/-])`, "g");
6758
7268
  const TEXT_REFERENCE_PATTERN = new RegExp([
6759
7269
  `${START}(?<issueOwner>${LOGIN})\\/(?<issueRepo>${REPO$1})#(?<issue>\\d+)${END}`,
6760
7270
  `${START}(?<commitOwner>${LOGIN})\\/(?<commitRepo>${REPO$1})@(?<commit>${SHA$1})${END}`,
@@ -6799,26 +7309,53 @@ function readSpans(text) {
6799
7309
  return spans;
6800
7310
  }
6801
7311
  /**
6802
- * Return the distinct repositories that the text names in qualified
6803
- * references or GitHub issue, pull request, and commit URLs.
7312
+ * Return the repositories that the text names, in source order: qualified
7313
+ * references, GitHub issue, pull request, and commit URLs, and prose that
7314
+ * names a repository of the configured owner.
6804
7315
  */
6805
- function namedRepositories(text, spans) {
6806
- const repositories = /* @__PURE__ */ new Map();
6807
- const add = (owner, name) => {
6808
- if (owner && name) repositories.set(`${owner}/${name}`.toLowerCase(), {
6809
- owner,
6810
- name
7316
+ function namedRepositories(text, spans, configuredOwner) {
7317
+ const named = [];
7318
+ const add = (offset, owner, name) => {
7319
+ if (owner && name) named.push({
7320
+ offset,
7321
+ repository: {
7322
+ owner,
7323
+ name
7324
+ }
6811
7325
  });
6812
7326
  };
6813
- for (const span of spans) if (span.url) for (const { groups } of span.url.matchAll(GITHUB_LINKED_URL_PATTERN)) add(groups?.["owner"], groups?.["repo"]);
6814
- else {
7327
+ for (const span of spans) {
7328
+ if (span.url) {
7329
+ for (const { groups } of span.url.matchAll(GITHUB_LINKED_URL_PATTERN)) add(span.start, groups?.["owner"], groups?.["repo"]);
7330
+ continue;
7331
+ }
6815
7332
  const source = text.slice(span.start, span.end);
6816
- for (const { groups } of source.matchAll(TEXT_REFERENCE_PATTERN)) {
6817
- add(groups?.["issueOwner"], groups?.["issueRepo"]);
6818
- add(groups?.["commitOwner"], groups?.["commitRepo"]);
7333
+ for (const { groups, index } of source.matchAll(TEXT_REFERENCE_PATTERN)) {
7334
+ const offset = span.start + index;
7335
+ add(offset, groups?.["issueOwner"], groups?.["issueRepo"]);
7336
+ add(offset, groups?.["commitOwner"], groups?.["commitRepo"]);
6819
7337
  }
7338
+ if (!configuredOwner) continue;
7339
+ for (const { groups, index } of source.matchAll(PROSE_REPOSITORY_PATTERN)) if (groups?.["owner"]?.toLowerCase() === configuredOwner.toLowerCase()) add(span.start + index, groups["owner"], groups["repo"]);
7340
+ }
7341
+ return named.sort((left, right) => left.offset - right.offset);
7342
+ }
7343
+ const repositoryKey = ({ owner, name }) => `${owner}/${name}`.toLowerCase();
7344
+ /**
7345
+ * Pick the repository of a bare reference at `offset`: the one repository
7346
+ * that the text names, else the last one named before the reference when
7347
+ * the text names several, else the configured one when it names none.
7348
+ */
7349
+ function repositoryAt(named, configured, offset) {
7350
+ if (named.length === 0) return configured;
7351
+ const first = named[0].repository;
7352
+ if (named.every(({ repository }) => repositoryKey(repository) === repositoryKey(first))) return first;
7353
+ let nearest;
7354
+ for (const entry of named) {
7355
+ if (entry.offset >= offset) break;
7356
+ nearest = entry.repository;
6820
7357
  }
6821
- return [...repositories.values()];
7358
+ return nearest;
6822
7359
  }
6823
7360
  const issueUrl = (owner, name, issue) => `https://github.com/${owner}/${name}/issues/${issue}`;
6824
7361
  const commitUrl = (owner, name, sha) => `https://github.com/${owner}/${name}/commit/${sha}`;
@@ -6827,10 +7364,10 @@ function linkifyUrl(url) {
6827
7364
  if (!groups?.["owner"] || !groups["repo"]) return url;
6828
7365
  return `[${groups["issue"] ? `${groups["owner"]}/${groups["repo"]}#${groups["issue"]}` : `${groups["owner"]}/${groups["repo"]}@${groups["commit"].slice(0, 7)}`}](${url})`;
6829
7366
  }
6830
- function linkifyTextReferences(text, context) {
6831
- const { repository } = context;
7367
+ function linkifyTextReferences(text, start, context) {
6832
7368
  return text.replace(TEXT_REFERENCE_PATTERN, (reference, ...args) => {
6833
7369
  const groups = args.at(-1);
7370
+ const index = args.at(-3);
6834
7371
  if (groups["issue"]) return `[${reference}](${issueUrl(groups["issueOwner"], groups["issueRepo"], groups["issue"])})`;
6835
7372
  if (groups["commit"]) return `[${`${groups["commitOwner"]}/${groups["commitRepo"]}@${groups["commit"].slice(0, 7)}`}](${commitUrl(groups["commitOwner"], groups["commitRepo"], groups["commit"])})`;
6836
7373
  if (groups["mention"]) {
@@ -6840,11 +7377,19 @@ function linkifyTextReferences(text, context) {
6840
7377
  if (known) return known;
6841
7378
  return context.linkProfiles ? `[${reference}](https://github.com/${login})` : reference;
6842
7379
  }
7380
+ const repository = typeof index === "number" ? context.repositoryAt(start + index) : void 0;
6843
7381
  if (!repository) return reference;
6844
- if (groups["bareIssue"]) return `[${reference}](${issueUrl(repository.owner, repository.name, groups["bareIssue"])})`;
6845
- if (groups["userCommit"]) return `[${`${groups["user"]}@${groups["userCommit"].slice(0, 7)}`}](${commitUrl(groups["user"], repository.name, groups["userCommit"])})`;
7382
+ const { owner, name } = repository;
7383
+ if (groups["bareIssue"]) {
7384
+ const issue = groups["bareIssue"];
7385
+ return `[${owner}/${name}#${issue}](${issueUrl(owner, name, issue)})`;
7386
+ }
7387
+ if (groups["userCommit"]) {
7388
+ const sha = groups["userCommit"];
7389
+ return `[${groups["user"]}/${name}@${sha.slice(0, 7)}](${commitUrl(groups["user"], name, sha)})`;
7390
+ }
6846
7391
  const sha = groups["bareCommit"];
6847
- return `[${sha.slice(0, 7)}](${commitUrl(repository.owner, repository.name, sha)})`;
7392
+ return `[${owner}/${name}@${sha.slice(0, 7)}](${commitUrl(owner, name, sha)})`;
6848
7393
  });
6849
7394
  }
6850
7395
  /**
@@ -6853,26 +7398,31 @@ function linkifyTextReferences(text, context) {
6853
7398
  * `owner/repo#123`, `owner/repo@sha`, and GitHub issue, pull request,
6854
7399
  * discussion, and commit URLs always become links. `#123`, `GH-123`,
6855
7400
  * `user@sha`, and full SHAs need a repository: the one that the text names,
6856
- * else the `repo` config value when the text names none. `@login` becomes the
7401
+ * also as a plain `owner/repo` of the configured owner. When it names
7402
+ * several, the last one named before the reference wins. When it names
7403
+ * none, the `repo` config value is used. Their link labels name the
7404
+ * repository. `@login` becomes the
6857
7405
  * `mention` of the known person with that GitHub login. Other logins become
6858
7406
  * GitHub profile links when the text is GitHub text, or names a repository.
6859
7407
  * Chat `@name` words are often people who are not GitHub accounts. Set
6860
7408
  * `bareUrls` to keep bare URLs, where the place shows them as cards.
6861
7409
  */
6862
7410
  function linkifyGitHubReferences(text, options = {}) {
7411
+ const config = options.config ?? {};
7412
+ const configured = configuredRepository(config);
6863
7413
  const spans = readSpans(text);
6864
- const named = namedRepositories(text, spans);
7414
+ const named = namedRepositories(text, spans, configured?.owner ?? config["org"]?.trim());
6865
7415
  const context = {
6866
7416
  linkProfiles: options.githubText === true || named.length > 0,
6867
7417
  mention: options.mention ?? (() => void 0),
6868
- repository: named.length === 0 ? configuredRepository(options.config ?? {}) : named.length === 1 ? named[0] : void 0
7418
+ repositoryAt: (offset) => repositoryAt(named, configured, offset)
6869
7419
  };
6870
7420
  let result = "";
6871
7421
  let cursor = 0;
6872
7422
  for (const span of spans) {
6873
7423
  const source = text.slice(span.start, span.end);
6874
7424
  result += text.slice(cursor, span.start);
6875
- result += span.kind === "text" ? linkifyTextReferences(source, context) : span.kind === "url" && !options.bareUrls ? linkifyUrl(source) : source;
7425
+ result += span.kind === "text" ? linkifyTextReferences(source, span.start, context) : span.kind === "url" && !options.bareUrls ? linkifyUrl(source) : source;
6876
7426
  cursor = span.end;
6877
7427
  }
6878
7428
  return result + text.slice(cursor);
@@ -6980,10 +7530,19 @@ function parseGitHubReferences(text, config) {
6980
7530
  }
6981
7531
  return [...references.values()];
6982
7532
  }
7533
+ const commitResponseSchema = z.object({ commit: z.object({ message: z.string() }) });
7534
+ const titledResponseSchema = z.object({ title: z.string() });
6983
7535
  /** Read the display title of an issue, pull request, or commit response. */
6984
7536
  function objectTitle(kind, object) {
6985
- if (!isRecord(object)) return void 0;
6986
- return (kind === "commit" ? isRecord(object["commit"]) && typeof object["commit"]["message"] === "string" ? object["commit"]["message"].split("\n")[0] : void 0 : typeof object["title"] === "string" ? object["title"] : void 0)?.replace(/\s+/g, " ").trim() || void 0;
7537
+ let raw;
7538
+ if (kind === "commit") {
7539
+ const parsed = commitResponseSchema.safeParse(object);
7540
+ raw = parsed.success ? parsed.data.commit.message.split("\n")[0] : void 0;
7541
+ } else {
7542
+ const parsed = titledResponseSchema.safeParse(object);
7543
+ raw = parsed.success ? parsed.data.title : void 0;
7544
+ }
7545
+ return raw?.replace(/\s+/g, " ").trim() || void 0;
6987
7546
  }
6988
7547
  /**
6989
7548
  * Describe GitHub issues, pull requests, and commits that message text
@@ -7277,7 +7836,7 @@ function assertGitHubPullRequestApprovalDenied(input) {
7277
7836
  } catch {
7278
7837
  throw new EgressPolicyDenied("GitHub pull request review requests must use JSON bodies so the no-approve policy can be enforced.");
7279
7838
  }
7280
- if (!isRecord(body)) throw new EgressPolicyDenied("GitHub pull request review requests must use JSON object bodies so the no-approve policy can be enforced.");
7839
+ if (typeof body !== "object" || body === null || Array.isArray(body)) throw new EgressPolicyDenied("GitHub pull request review requests must use JSON object bodies so the no-approve policy can be enforced.");
7281
7840
  let event;
7282
7841
  if ("event" in body) {
7283
7842
  if (typeof body["event"] !== "string" || body["event"].trim().length === 0) throw new EgressPolicyDenied("GitHub pull request review submissions must include a parseable non-APPROVE event so the no-approve policy can be enforced.");
@@ -7399,6 +7958,11 @@ function githubGraphqlAccess(method, upstreamUrl, graphql) {
7399
7958
  if (HTTP_READ_METHODS.has(method)) return "read";
7400
7959
  return githubGraphqlOperation(graphql)?.type === "query" ? "read" : "write";
7401
7960
  }
7961
+ const githubGraphqlErrorsSchema = z.object({ errors: z.array(z.unknown()) });
7962
+ const githubGraphqlErrorSchema = z.object({
7963
+ message: z.string(),
7964
+ type: z.unknown().optional()
7965
+ });
7402
7966
  function githubGraphqlPermissionDeniedMessage(bodyText) {
7403
7967
  let parsed;
7404
7968
  try {
@@ -7406,11 +7970,13 @@ function githubGraphqlPermissionDeniedMessage(bodyText) {
7406
7970
  } catch {
7407
7971
  return;
7408
7972
  }
7409
- if (!isRecord(parsed) || !Array.isArray(parsed["errors"])) return;
7410
- for (const error of parsed["errors"]) {
7411
- if (!isRecord(error) || typeof error["message"] !== "string") continue;
7412
- const message = error["message"];
7413
- if (error["type"] === "NOT_FOUND" && /\bCould not resolve to a Repository with the name\b/.test(message)) return `GitHub GraphQL could not access the repository: ${message}`;
7973
+ const body = githubGraphqlErrorsSchema.safeParse(parsed);
7974
+ if (!body.success) return;
7975
+ for (const entry of body.data.errors) {
7976
+ const error = githubGraphqlErrorSchema.safeParse(entry);
7977
+ if (!error.success) continue;
7978
+ const message = error.data.message;
7979
+ if (error.data.type === "NOT_FOUND" && /\bCould not resolve to a Repository with the name\b/.test(message)) return `GitHub GraphQL could not access the repository: ${message}`;
7414
7980
  if (/\bResource not accessible by integration\b/.test(message)) return `GitHub GraphQL denied access: ${message}`;
7415
7981
  }
7416
7982
  }
@@ -7432,8 +7998,8 @@ const GITHUB_ACCEPTED_PERMISSIONS_PATTERN = /^[a-z_]+=[a-z]+(?:\s*[,;]\s*[a-z_]+
7432
7998
  function githubErrorMessage(bodyText) {
7433
7999
  if (!bodyText) return;
7434
8000
  try {
7435
- const parsed = JSON.parse(bodyText);
7436
- return isRecord(parsed) && typeof parsed["message"] === "string" ? parsed["message"].trim() : void 0;
8001
+ const parsed = githubMessageSchema.safeParse(JSON.parse(bodyText));
8002
+ return parsed.success ? parsed.data.message.trim() : void 0;
7437
8003
  } catch {
7438
8004
  return;
7439
8005
  }
@@ -7776,6 +8342,7 @@ function githubPlugin(options = {}) {
7776
8342
  events: gitHubEventDeclarations(gitHubPullRequestEventGuidance(options.pullRequestEvents?.guidance)),
7777
8343
  isEnabled: () => Boolean(readEnv("GITHUB_WEBHOOK_SECRET")),
7778
8344
  normalizeIdentifier: (identifier) => identifier.toLowerCase(),
8345
+ resourceForUrl: gitHubUrlResource,
7779
8346
  resourceUrl: gitHubResourceUrl
7780
8347
  },
7781
8348
  manifest: {
@@ -7875,8 +8442,27 @@ function githubPlugin(options = {}) {
7875
8442
  systemPrompt() {
7876
8443
  return [{ text: "Write each GitHub issue, pull request, or commit reference with its repository, such as owner/repo#123 or owner/repo@abc1234, and not in code formatting. A bare #123, GH-123, or SHA is ambiguous when a conversation spans several repositories." }];
7877
8444
  },
8445
+ async reviewItemAnswered(ctx) {
8446
+ const ref = parseGitHubConflictItemKey(ctx.dedupeKey);
8447
+ if (!ref || ctx.choice !== "Resume") return;
8448
+ const installationEnv = {
8449
+ appIdEnv,
8450
+ installationIdEnv,
8451
+ privateKeyEnv
8452
+ };
8453
+ await resumeGitHubConflictFixes({
8454
+ db: gitHubDbSchema.parse(ctx.db),
8455
+ events: ctx.events,
8456
+ itemId: ctx.itemId,
8457
+ loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
8458
+ nowMs: ctx.nowMs,
8459
+ ref,
8460
+ subscription: gitHubPullRequestSubscription(options.pullRequestEvents?.subscribeAfterCreate),
8461
+ watches: ctx.watches
8462
+ });
8463
+ },
7878
8464
  async heartbeat(ctx) {
7879
- const db = ctx.db;
8465
+ const db = gitHubDbSchema.parse(ctx.db);
7880
8466
  const installationEnv = {
7881
8467
  appIdEnv,
7882
8468
  installationIdEnv,
@@ -7914,7 +8500,7 @@ function githubPlugin(options = {}) {
7914
8500
  });
7915
8501
  },
7916
8502
  async unfinishedWork(ctx) {
7917
- const db = ctx.db;
8503
+ const db = gitHubDbSchema.parse(ctx.db);
7918
8504
  const [conversationIds, assignedConversationIds, finishedWorkAtByConversationId] = await Promise.all([
7919
8505
  listGitHubUnfinishedWork(db, ctx.conversationIds),
7920
8506
  listGitHubAssignedWork(db, ctx.conversationIds),
@@ -7942,7 +8528,7 @@ function githubPlugin(options = {}) {
7942
8528
  loadPage: await loadPullRequestCommitPages(installationEnv, pullRequest)
7943
8529
  }),
7944
8530
  codeChanges: ctx.codeChanges,
7945
- db: ctx.db,
8531
+ db: gitHubDbSchema.parse(ctx.db),
7946
8532
  installationId: () => readEnv(installationIdEnv),
7947
8533
  loadGitHubIncidents: async () => await loadGitHubStatusIncidents(ctx.cache, CHECK_SUITE_INCIDENT_WINDOW_MS),
7948
8534
  installationIdEnv,