@sentry/junior-github 0.310.0 → 0.312.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,16 +1,18 @@
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-mAaCafvx.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 { 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";
14
+ import { RE2JS } from "re2js";
15
+ import { parse as parse$1 } from "yaml";
14
16
  import { fromMarkdown } from "mdast-util-from-markdown";
15
17
  import { gfmFromMarkdown } from "mdast-util-gfm";
16
18
  import { gfm } from "micromark-extension-gfm";
@@ -109,8 +111,16 @@ function githubSidebarAnnotations(annotations) {
109
111
  };
110
112
  if (annotation.kind === "object") {
111
113
  sidebar.title = annotation.title;
112
- const image = annotation.facts?.type === "code_change" ? annotation.facts.previewImageUrls?.[0] : void 0;
113
- if (image) sidebar.imageUrl = image;
114
+ if (annotation.facts?.type === "code_change") {
115
+ const { additions, changedFiles, deletions, previewImageUrls } = annotation.facts;
116
+ const image = previewImageUrls?.[0];
117
+ if (image) sidebar.imageUrl = image;
118
+ if (additions !== void 0 || deletions !== void 0 || changedFiles !== void 0) sidebar.size = {
119
+ additions,
120
+ changedFiles,
121
+ deletions
122
+ };
123
+ }
114
124
  }
115
125
  if (annotation.url) sidebar.url = annotation.url;
116
126
  return [{
@@ -190,6 +200,7 @@ const responseSchema$1 = z.object({
190
200
  head: z.object({ ref: z.string() }).optional(),
191
201
  base: z.object({ ref: z.string() }).optional(),
192
202
  mergeable: z.boolean().nullable().optional(),
203
+ state: z.string().optional(),
193
204
  changed_files: z.number().int().nonnegative().optional(),
194
205
  additions: z.number().int().nonnegative().optional(),
195
206
  deletions: z.number().int().nonnegative().optional(),
@@ -289,7 +300,7 @@ function githubObjectFacts(type, response) {
289
300
  reviewers: data.requested_reviewers?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
290
301
  sourceBranch: short(data.head?.ref),
291
302
  targetBranch: short(data.base?.ref),
292
- mergeable: data.mergeable ?? void 0,
303
+ mergeable: data.state === "open" ? data.mergeable ?? void 0 : void 0,
293
304
  changedFiles: data.changed_files,
294
305
  additions: data.additions,
295
306
  deletions: data.deletions
@@ -352,7 +363,7 @@ const objectSchema = z.object({
352
363
  title: z.string()
353
364
  });
354
365
  const issueSchema$2 = objectSchema.extend({ pull_request: z.unknown().optional() });
355
- const pullRequestSchema$4 = objectSchema.extend({
366
+ const pullRequestSchema$2 = objectSchema.extend({
356
367
  draft: z.boolean().optional(),
357
368
  merged: z.boolean().optional()
358
369
  });
@@ -388,7 +399,7 @@ function issueCard(link, body) {
388
399
  });
389
400
  }
390
401
  function pullRequestCard(link, body) {
391
- const pull = pullRequestSchema$4.parse(body);
402
+ const pull = pullRequestSchema$2.parse(body);
392
403
  return githubObjectAnnotation({
393
404
  ...githubObjectFacts("code_change", body),
394
405
  repo: repoRef(pull.html_url, link),
@@ -478,7 +489,7 @@ const REACTION_CONTENTS = [
478
489
  ];
479
490
  const inputSchema$15 = z.object({
480
491
  repo: z.string().describe("Repository in \"owner/name\" format."),
481
- number: z.number().int().positive().describe("Issue or pull request number."),
492
+ issue: z.number().int().positive().describe("Issue or pull request number."),
482
493
  content: z.enum(REACTION_CONTENTS).describe("Reaction to add.")
483
494
  }).strict();
484
495
  const outputSchema$15 = pluginToolOutputSchema.extend({
@@ -504,7 +515,7 @@ const gitHubReactToIssueTool = definePluginTool({
504
515
  const response = await githubApi(egress, {
505
516
  operation: "github.issue.reaction.create",
506
517
  method: "POST",
507
- path: `${repoPath(repo)}/issues/${input.number}/reactions`,
518
+ path: `${repoPath(repo)}/issues/${input.issue}/reactions`,
508
519
  body: { content: input.content }
509
520
  });
510
521
  if (!response.ok) {
@@ -516,7 +527,7 @@ const gitHubReactToIssueTool = definePluginTool({
516
527
  return {
517
528
  target: "reactToIssue",
518
529
  repo: repo.ref,
519
- number: input.number,
530
+ number: input.issue,
520
531
  content: input.content,
521
532
  reaction_id: reaction.id
522
533
  };
@@ -693,7 +704,7 @@ const gitHubCloneRepositoryTool = definePluginTool({
693
704
  // src/tools/comment-on-issue.ts
694
705
  const inputSchema$13 = z.object({
695
706
  repo: z.string().describe("Repository in \"owner/name\" format."),
696
- number: z.number().int().positive().describe("Issue number."),
707
+ issue: z.number().int().positive().describe("Issue number."),
697
708
  body: z.string().trim().min(1).describe("Comment text.")
698
709
  }).strict();
699
710
  const outputSchema$13 = pluginToolOutputSchema.extend({
@@ -719,7 +730,7 @@ const gitHubCommentOnIssueTool = definePluginTool({
719
730
  const response = await githubApi(egress, {
720
731
  operation: "github.issue.comment.create",
721
732
  method: "POST",
722
- path: `${repoPath(repo)}/issues/${input.number}/comments`,
733
+ path: `${repoPath(repo)}/issues/${input.issue}/comments`,
723
734
  body: { body: input.body }
724
735
  });
725
736
  if (!response.ok) {
@@ -734,7 +745,7 @@ const gitHubCommentOnIssueTool = definePluginTool({
734
745
  return {
735
746
  target: "commentOnIssue",
736
747
  repo: repo.ref,
737
- number: input.number,
748
+ number: input.issue,
738
749
  comment_id: comment.id,
739
750
  url: comment.html_url
740
751
  };
@@ -743,7 +754,7 @@ const gitHubCommentOnIssueTool = definePluginTool({
743
754
  // src/tools/comment-on-pull-request.ts
744
755
  const inputSchema$12 = z.object({
745
756
  repo: z.string().describe("Repository in \"owner/name\" format."),
746
- number: z.number().int().positive().describe("Pull request number."),
757
+ pull_request: z.number().int().positive().describe("Pull request number."),
747
758
  body: z.string().trim().min(1).describe("Comment text."),
748
759
  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
760
  }).strict();
@@ -788,7 +799,7 @@ const gitHubCommentOnPullRequestTool = definePluginTool({
788
799
  async execute(input, _options, { egress }) {
789
800
  const repo = parseRepo$1(input.repo);
790
801
  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`;
802
+ 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
803
  const response = await githubApi(egress, {
793
804
  operation: "github.pull.comment.create",
794
805
  method: "POST",
@@ -807,7 +818,7 @@ const gitHubCommentOnPullRequestTool = definePluginTool({
807
818
  return {
808
819
  target: "commentOnPullRequest",
809
820
  repo: repo.ref,
810
- number: input.number,
821
+ number: input.pull_request,
811
822
  comment_id: comment.id,
812
823
  reply: {
813
824
  text: input.body,
@@ -817,7 +828,7 @@ const gitHubCommentOnPullRequestTool = definePluginTool({
817
828
  };
818
829
  }
819
830
  });
820
- // src/tools/footer.ts
831
+ // src/conversation-footer.ts
821
832
  const GITHUB_SESSION_FOOTER_START = "<!-- junior-session-footer:start -->";
822
833
  const GITHUB_SESSION_FOOTER_END = "<!-- junior-session-footer:end -->";
823
834
  const GITHUB_CONVERSATION_ID_MARKER = "junior-conversation-id:";
@@ -945,11 +956,11 @@ const gitHubIssueDataSchema = z.object({
945
956
  const gitHubIssueOutputSchema = pluginToolOutputSchema.merge(gitHubIssueDataSchema.extend({ target: z.literal("createIssue") }));
946
957
  /**
947
958
  * Next step after an issue is created. Whether Junior does the work is the
948
- * requester's decision, so the note asks for a Review item. Only a Turn that
959
+ * requester's decision, so the note asks for an Inbox item. Only a Turn that
949
960
  * a person started gets it: no one can answer the item in other runs.
950
961
  */
951
962
  function implementIssueNote(issue) {
952
- return `Unless the requester already asked you to fix ${issue}, ask whether to: the choice is theirs, even if they asked only for the issue. Use addReviewItem: question "Start a Thread to implement ${issue}?", choices "Start thread" (recommended) and "Not now", dedupe_key "github-issue-implement:${issue}". If they asked for the fix, start the Thread now. Skip both for issues owned by another team and for security, feedback, or tracking reports. Start the Thread with spawnAgent, kind thread, and this brief: read ${issue} with github_getIssue, follow the github-code workflow, and open a pull request that references it.`;
963
+ return `Unless the requester already asked you to fix ${issue}, ask whether to: the choice is theirs, even if they asked only for the issue. Use addInboxItem: question "Start a Thread to implement ${issue}?", choices "Start thread" (recommended) and "Not now", dedupe_key "github-issue-implement:${issue}". If they asked for the fix, start the Thread now. Skip both for issues owned by another team and for security, feedback, or tracking reports. Start the Thread with spawnAgent, kind thread, and this brief: read ${issue} with github_getIssue, follow the github-code workflow, and open a pull request that references it.`;
953
964
  }
954
965
  async function gitHubIssueToolResult(ctx, input, result) {
955
966
  const repo = parseRepo$1(input.repo);
@@ -1230,7 +1241,7 @@ const gitHubGetDeploymentTool = definePluginTool({
1230
1241
  const CLAIM_NOTE = "If you start work on this issue, first claim it with github_updateIssue and assign_requester: true.";
1231
1242
  const inputSchema$10 = z.object({
1232
1243
  repo: z.string().describe("Repository in \"owner/name\" format."),
1233
- number: z.number().int().positive().describe("Issue number.")
1244
+ issue: z.number().int().positive().describe("Issue number.")
1234
1245
  }).strict();
1235
1246
  const issueSchema$1 = z.object({
1236
1247
  assignees: z.array(z.string()),
@@ -1277,7 +1288,7 @@ const gitHubGetIssueTool = definePluginTool({
1277
1288
  const [response, requester] = await Promise.all([githubApi(ctx.egress, {
1278
1289
  followRedirects: true,
1279
1290
  operation: "github.issue.get",
1280
- path: `${repoPath(repo)}/issues/${input.number}`
1291
+ path: `${repoPath(repo)}/issues/${input.issue}`
1281
1292
  }), resolveGitHubRequester(ctx)]);
1282
1293
  if (!response.ok) {
1283
1294
  const message = `GitHub issue lookup failed with HTTP ${response.status}`;
@@ -1370,15 +1381,17 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1370
1381
  state: text("state").$type().notNull(),
1371
1382
  commitComposition: text("commit_composition").$type(),
1372
1383
  conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
1373
- /** The daily reconcile compares this with GitHub. */
1374
- draft: boolean("draft").notNull().default(false),
1375
1384
  openedAt: timestamp$2("opened_at", { withTimezone: true }).notNull(),
1376
- mergedAt: timestamp$2("merged_at", { withTimezone: true }),
1377
- closedAt: timestamp$2("closed_at", { withTimezone: true }),
1385
+ /**
1386
+ * When the pull request merged or closed. Null while it is open. The
1387
+ * finished work of a Conversation needs this time for every pull
1388
+ * request of every candidate, so it is stored and not read from GitHub.
1389
+ */
1390
+ finishedAt: timestamp$2("finished_at", { withTimezone: true }),
1378
1391
  updatedAt: timestamp$2("updated_at", { withTimezone: true }).notNull(),
1379
1392
  /**
1380
1393
  * 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.
1394
+ * shows in the Inbox. Null when no action waits on them.
1382
1395
  */
1383
1396
  nextAction: text("next_action").$type(),
1384
1397
  /**
@@ -1391,11 +1404,26 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1391
1404
  */
1392
1405
  readySyncId: integer("ready_sync_id"),
1393
1406
  /** When the current check started. */
1394
- readySyncAt: timestamp$2("ready_sync_at", { withTimezone: true })
1407
+ readySyncAt: timestamp$2("ready_sync_at", { withTimezone: true }),
1408
+ /**
1409
+ * When a person last chose Resume on the merge conflict item.
1410
+ * It counts as activity by a person, so the fix count starts again.
1411
+ */
1412
+ conflictFixesResumedAt: timestamp$2("conflict_fixes_resumed_at", { withTimezone: true }),
1413
+ /**
1414
+ * When Junior last asked the requester to resume a merge conflict fix
1415
+ * that did not land. It asks once after each Resume, so a Dismiss ends
1416
+ * the asks on the pull request.
1417
+ */
1418
+ conflictFixAskedAt: timestamp$2("conflict_fix_asked_at", { withTimezone: true }),
1419
+ /**
1420
+ * The latest merge conflict fixes that Junior started, oldest first.
1421
+ * Only these count as fixes, so a merge or force push for work that a
1422
+ * person asked for does not.
1423
+ */
1424
+ conflictFixes: jsonb("conflict_fixes").$type().notNull().default([])
1395
1425
  }, (table) => [
1396
1426
  index("junior_github_pull_requests_opened_at_idx").on(table.openedAt),
1397
- index("junior_github_pull_requests_merged_at_idx").on(table.mergedAt),
1398
- index("junior_github_pull_requests_closed_at_idx").on(table.closedAt),
1399
1427
  index("junior_github_pull_requests_open_idx").on(table.pullRequestId).where(sql`${table.state} = 'open'`),
1400
1428
  index("junior_github_pull_requests_unmerged_conversations_idx").using("gin", table.conversationIds).where(sql`${table.state} <> 'merged'`)
1401
1429
  ]);
@@ -1492,7 +1520,7 @@ async function listGitHubPullRequestOpeners(db, input) {
1492
1520
  });
1493
1521
  return openers;
1494
1522
  }
1495
- // src/tools/stack-pull-request.ts
1523
+ // src/tool-support/stack-pull-request.ts
1496
1524
  /** Longest chain of base branches to walk down to the trunk. */
1497
1525
  const MAX_STACK_DEPTH = 10;
1498
1526
  const GITHUB_STACKS_API_VERSION = "2026-03-10";
@@ -1656,7 +1684,8 @@ var GitHubPullRequestCreateRejectedError = class extends Error {
1656
1684
  }
1657
1685
  };
1658
1686
  const BODY_DESCRIPTION = `Pull request body. ${PULL_REQUEST_BODY_RULES}`;
1659
- const REVIEWERS_DESCRIPTION = "GitHub logins to ask for a review. Set this only when the person names who should review. Without it, the tool asks the requester's linked GitHub account. A draft gets the request when it becomes ready for review.";
1687
+ const REVIEWERS_DESCRIPTION = "People to ask for a review: GitHub logins, emails, Slack mentions, or names. A person maps to their linked GitHub login. Set it only when the person names a reviewer. Without it, the tool asks the requester. A draft is asked once ready.";
1688
+ const ASSIGNEES_DESCRIPTION = "People to assign: GitHub logins, emails, Slack mentions, or names. A person maps to their linked GitHub login. Set this only when the person or instruction names who to assign. Without it, the tool assigns the requester's linked GitHub account.";
1660
1689
  const createPullRequestInputSchema = Type.Object({
1661
1690
  repo: Type.String({ description: "Repository in \"owner/name\" format." }),
1662
1691
  title: Type.String({ description: "Pull request title." }),
@@ -1667,6 +1696,10 @@ const createPullRequestInputSchema = Type.Object({
1667
1696
  reviewers: Type.Optional(Type.Array(Type.String(), {
1668
1697
  description: REVIEWERS_DESCRIPTION,
1669
1698
  minItems: 1
1699
+ })),
1700
+ assignees: Type.Optional(Type.Array(Type.String(), {
1701
+ description: ASSIGNEES_DESCRIPTION,
1702
+ minItems: 1
1670
1703
  }))
1671
1704
  }, { additionalProperties: false });
1672
1705
  const createPullRequestToolInputSchema = z.object({
@@ -1676,7 +1709,8 @@ const createPullRequestToolInputSchema = z.object({
1676
1709
  base: z.string().describe("Base branch."),
1677
1710
  body: z.string().describe(BODY_DESCRIPTION).optional(),
1678
1711
  draft: z.boolean().describe("Whether to open the pull request as a draft.").optional(),
1679
- reviewers: z.array(z.string()).min(1).describe(REVIEWERS_DESCRIPTION).optional()
1712
+ reviewers: z.array(z.string()).min(1).describe(REVIEWERS_DESCRIPTION).optional(),
1713
+ assignees: z.array(z.string()).min(1).describe(ASSIGNEES_DESCRIPTION).optional()
1680
1714
  }).strict();
1681
1715
  const createPullRequestStateSchema = Type.Union([Type.Object({
1682
1716
  createdAtMs: Type.Number(),
@@ -1790,17 +1824,21 @@ async function recordOpener(ctx, input, state, requester) {
1790
1824
  repositoryFullName: repo.ref
1791
1825
  });
1792
1826
  }
1793
- /** Assignment is optional: provider failures must not fail PR creation. */
1794
- async function assignPullRequestRequester(ctx, input, result, requester) {
1795
- const assignee = linkedGitHubLogin(requesterPerson(requester)?.user);
1796
- if (!assignee) return;
1827
+ /**
1828
+ * Assign the named assignees, or else the requester. Assignment is optional:
1829
+ * provider failures must not fail PR creation.
1830
+ */
1831
+ async function assignPullRequest(ctx, input, result, requester) {
1832
+ const requesterLogin = linkedGitHubLogin(requesterPerson(requester)?.user);
1833
+ const assignees = namedLogins(input.assignees, "assignee") ?? (requesterLogin ? [requesterLogin] : []);
1834
+ if (assignees.length === 0) return;
1797
1835
  try {
1798
1836
  const repo = parseRepo$1(input.repo);
1799
1837
  const response = await githubApi(ctx.egress, {
1800
1838
  operation: "github.pull.assign",
1801
1839
  method: "POST",
1802
1840
  path: `${repoPath(repo)}/issues/${result.number}/assignees`,
1803
- body: { assignees: [assignee] }
1841
+ body: { assignees }
1804
1842
  });
1805
1843
  if (!response.ok) ctx.log.warn("github.pull_request.assign_after_create.rejected", {
1806
1844
  number: result.number,
@@ -1815,11 +1853,36 @@ async function assignPullRequestRequester(ctx, input, result, requester) {
1815
1853
  });
1816
1854
  }
1817
1855
  }
1818
- /** Return the logins of the named reviewers. */
1819
- function namedReviewers(input) {
1820
- return input.reviewers?.map((value) => {
1856
+ /**
1857
+ * Replace each named assignee or reviewer that is not a GitHub login, such as
1858
+ * an email, a Slack mention, or a name, with the linked GitHub login of the
1859
+ * person it names. Reject a value that no linked account verifies, before
1860
+ * GitHub opens the pull request.
1861
+ */
1862
+ async function resolveNamedPeople(ctx, people) {
1863
+ const [assignees, reviewers] = await Promise.all([resolveLogins(ctx, people.assignees, "assignee"), resolveLogins(ctx, people.reviewers, "reviewer")]);
1864
+ return {
1865
+ ...assignees ? { assignees } : void 0,
1866
+ ...reviewers ? { reviewers } : void 0
1867
+ };
1868
+ }
1869
+ const PERSON_LOOKUP_CONCURRENCY = 4;
1870
+ async function resolveLogins(ctx, values, role) {
1871
+ if (!values) return void 0;
1872
+ return await pLimit(PERSON_LOOKUP_CONCURRENCY).map(values, async (value) => {
1821
1873
  const login = parseGitHubLogin(value);
1822
- if (!login) throw new PluginToolInputError(`Invalid GitHub reviewer login: ${value}`);
1874
+ if (login) return login;
1875
+ const lookup = await ctx.users.findLinkedHandle(value, "github");
1876
+ const linked = lookup.status === "found" ? parseGitHubLogin(lookup.handle) : void 0;
1877
+ if (linked) return linked;
1878
+ throw new PluginToolInputError(lookup.status === "ambiguous" ? `More than one person matches ${role} ${value}. Name one person.` : lookup.status === "unlinked" ? `${role} ${value} has no linked GitHub account. Pass their GitHub login.` : `No person matches ${role} ${value}. Pass a GitHub login.`);
1879
+ });
1880
+ }
1881
+ /** Return the logins of named reviewers or assignees. */
1882
+ function namedLogins(values, role) {
1883
+ return values?.map((value) => {
1884
+ const login = parseGitHubLogin(value);
1885
+ if (!login) throw new PluginToolInputError(`Invalid GitHub ${role} login: ${value}`);
1823
1886
  return login;
1824
1887
  });
1825
1888
  }
@@ -1828,7 +1891,7 @@ function namedReviewers(input) {
1828
1891
  * them. With nothing saved, that webhook asks the requester.
1829
1892
  */
1830
1893
  async function saveNamedDraftReviewers(ctx, input, number) {
1831
- const named = namedReviewers(input);
1894
+ const named = namedLogins(input.reviewers, "reviewer");
1832
1895
  if (!input.draft || !named) return;
1833
1896
  await saveGitHubDraftReviewers(ctx.state, {
1834
1897
  number,
@@ -1841,7 +1904,7 @@ async function saveNamedDraftReviewers(ctx, input, number) {
1841
1904
  * optional: provider failures must not fail PR creation.
1842
1905
  */
1843
1906
  async function requestPullRequestReviewers$1(ctx, input, result, requester) {
1844
- const named = namedReviewers(input);
1907
+ const named = namedLogins(input.reviewers, "reviewer");
1845
1908
  const repo = parseRepo$1(input.repo);
1846
1909
  try {
1847
1910
  if (input.draft) {
@@ -1939,13 +2002,20 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
1939
2002
  openWorldHint: true,
1940
2003
  readOnlyHint: false
1941
2004
  },
1942
- description: "Create a GitHub pull request with a runtime-owned conversation footer. It assigns the pull request to the requester's linked GitHub account and asks for a review when available. Use this instead of shelling out to gh pr create when creating pull requests.",
2005
+ description: "Create a GitHub pull request with a runtime-owned conversation footer. By default it assigns the pull request to the requester's linked GitHub account and asks for a review when available. Use this instead of shelling out to gh pr create when creating pull requests.",
1943
2006
  exposure: "direct",
1944
2007
  inputSchema: createPullRequestToolInputSchema,
1945
2008
  outputSchema: gitHubPullRequestOutputSchema,
1946
2009
  async execute(input, options, ctx) {
1947
- const parsedInput = parseCreatePullRequestInput(input);
1948
- namedReviewers(parsedInput);
2010
+ const { assignees, reviewers, ...text } = input;
2011
+ const [githubText, people] = await Promise.all([ctx.users.replaceSlackMentions(text, "github"), resolveNamedPeople(ctx, {
2012
+ assignees,
2013
+ reviewers
2014
+ })]);
2015
+ const parsedInput = parseCreatePullRequestInput({
2016
+ ...githubText,
2017
+ ...people
2018
+ });
1949
2019
  const conversationId = nonEmptyString$2(ctx.conversationId, "conversationId");
1950
2020
  const key = `createPullRequest:${conversationId}:${nonEmptyString$2(options?.toolCallId, "toolCallId")}`;
1951
2021
  const attempt = await ctx.state.withLock(`${key}:lock`, GITHUB_PULL_REQUEST_CREATE_LOCK_TTL_MS, async () => {
@@ -2004,7 +2074,7 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
2004
2074
  conversationId,
2005
2075
  identityId
2006
2076
  });
2007
- await assignPullRequestRequester(ctx, parsedInput, result, requester);
2077
+ await assignPullRequest(ctx, parsedInput, result, requester);
2008
2078
  await requestPullRequestReviewers$1(ctx, parsedInput, result, requester);
2009
2079
  const stack = stackTarget ? await stackGitHubPullRequest(ctx, stackTarget) : void 0;
2010
2080
  return await gitHubPullRequestStructuredResult(ctx, parsedInput, result, subscriptionConfig, stack);
@@ -2187,7 +2257,7 @@ const OPEN_PULL_REQUEST_MERGEABILITY = githubGraphql(`
2187
2257
  * Read what decides a merge conflict fix on one pull request: the review
2188
2258
  * decision, when it opened, and its latest pushes, reviews, and comments.
2189
2259
  * Pushes have their own window, so comments, which anyone can add, cannot
2190
- * push Junior's earlier fixes out of it.
2260
+ * push a person's latest push out of it.
2191
2261
  */
2192
2262
  const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2193
2263
  query PullRequestConflictHistory($owner: String!, $name: String!, $number: Int!) {
@@ -2198,7 +2268,7 @@ const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2198
2268
  pushes: timelineItems(last: 100, itemTypes: [PULL_REQUEST_COMMIT, HEAD_REF_FORCE_PUSHED_EVENT]) {
2199
2269
  nodes {
2200
2270
  __typename
2201
- ... on PullRequestCommit { commit { committedDate parents { totalCount } author { user { login } } } }
2271
+ ... on PullRequestCommit { commit { committedDate author { user { login } } } }
2202
2272
  ... on HeadRefForcePushedEvent { createdAt actor { __typename } }
2203
2273
  }
2204
2274
  }
@@ -2213,6 +2283,72 @@ const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2213
2283
  }
2214
2284
  }
2215
2285
  `);
2286
+ /**
2287
+ * Read what decides the requester's next action on one pull request: its
2288
+ * state, merge state, review requests, latest reviews, head commit, and
2289
+ * latest comments and review requests. A review comment reply is a review,
2290
+ * so `reviews` holds it too.
2291
+ */
2292
+ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
2293
+ query PullRequestNextAction($owner: String!, $name: String!, $number: Int!) {
2294
+ repository(owner: $owner, name: $name) {
2295
+ pullRequest(number: $number) {
2296
+ autoMergeRequest { enabledAt }
2297
+ headRefOid
2298
+ isDraft
2299
+ mergeStateStatus
2300
+ state
2301
+ title
2302
+ url
2303
+ reviewRequests(first: 100) {
2304
+ nodes { requestedReviewer { __typename ... on User { login } } }
2305
+ }
2306
+ reviews(last: 100) {
2307
+ pageInfo { hasPreviousPage startCursor }
2308
+ nodes { ...NextActionReview }
2309
+ }
2310
+ commits(last: 1) { nodes { commit { committedDate } } }
2311
+ timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT]) {
2312
+ nodes {
2313
+ __typename
2314
+ ... on IssueComment { createdAt author { __typename login } }
2315
+ ... on ReviewRequestedEvent {
2316
+ createdAt
2317
+ requestedReviewer { __typename ... on User { login } }
2318
+ }
2319
+ }
2320
+ }
2321
+ }
2322
+ }
2323
+ }
2324
+
2325
+ fragment NextActionReview on PullRequestReview {
2326
+ state
2327
+ submittedAt
2328
+ author { __typename login }
2329
+ commit { oid }
2330
+ }
2331
+ `);
2332
+ /** Read the page of a pull request's reviews before `before`. */
2333
+ const PULL_REQUEST_REVIEWS_BEFORE = githubGraphql(`
2334
+ query PullRequestReviewsBefore($owner: String!, $name: String!, $number: Int!, $before: String!) {
2335
+ repository(owner: $owner, name: $name) {
2336
+ pullRequest(number: $number) {
2337
+ reviews(last: 100, before: $before) {
2338
+ pageInfo { hasPreviousPage startCursor }
2339
+ nodes { ...NextActionReview }
2340
+ }
2341
+ }
2342
+ }
2343
+ }
2344
+
2345
+ fragment NextActionReview on PullRequestReview {
2346
+ state
2347
+ submittedAt
2348
+ author { __typename login }
2349
+ commit { oid }
2350
+ }
2351
+ `);
2216
2352
  const PULL_REQUEST_LIFECYCLE = githubGraphql(`
2217
2353
  query PullRequestLifecycles($owner: String!, $name: String!, $number: Int!) {
2218
2354
  repository(owner: $owner, name: $name) {
@@ -2372,7 +2508,7 @@ const RELATED_CONVERSATIONS_MAX = 10;
2372
2508
  const SUMMARY_MAX_LENGTH = 300;
2373
2509
  const inputSchema$9 = z.object({
2374
2510
  repo: z.string().describe("Repository in \"owner/name\" format."),
2375
- number: z.number().int().positive().describe("Pull request number.")
2511
+ pull_request: z.number().int().positive().describe("Pull request number.")
2376
2512
  }).strict();
2377
2513
  const checksSchema = z.object({
2378
2514
  required: z.enum([
@@ -2402,7 +2538,7 @@ const relatedConversationSchema = z.object({
2402
2538
  summary: z.string().optional().describe("Summary from the latest Brief."),
2403
2539
  updated_at: z.string().describe("Time of the latest activity.")
2404
2540
  });
2405
- const pullRequestSchema$3 = z.object({
2541
+ const pullRequestSchema$1 = z.object({
2406
2542
  base: z.string(),
2407
2543
  agents_md: z.string().optional().describe("Draft only: the root AGENTS.md of the base branch, when it has one."),
2408
2544
  checks: checksSchema,
@@ -2418,7 +2554,7 @@ const pullRequestSchema$3 = z.object({
2418
2554
  title: z.string(),
2419
2555
  url: z.string()
2420
2556
  });
2421
- const outputSchema$9 = pluginToolOutputSchema.merge(pullRequestSchema$3.extend({ target: z.literal("getPullRequest") }));
2557
+ const outputSchema$9 = pluginToolOutputSchema.merge(pullRequestSchema$1.extend({ target: z.literal("getPullRequest") }));
2422
2558
  const checkContextSchema = z.union([z.object({
2423
2559
  __typename: z.literal("CheckRun"),
2424
2560
  conclusion: z.string().nullable(),
@@ -2525,7 +2661,7 @@ const gitHubGetPullRequestTool = definePluginTool({
2525
2661
  const repo = parseRepo$1(input.repo);
2526
2662
  const response = await githubApi(ctx.egress, {
2527
2663
  operation: "github.pull.get",
2528
- path: `${repoPath(repo)}/pulls/${input.number}`
2664
+ path: `${repoPath(repo)}/pulls/${input.pull_request}`
2529
2665
  });
2530
2666
  if (!response.ok) {
2531
2667
  const message = `GitHub pull request lookup failed with HTTP ${response.status}`;
@@ -2668,7 +2804,7 @@ const gitHubGetReleaseTool = definePluginTool({
2668
2804
  });
2669
2805
  // src/tools/get-repository.ts
2670
2806
  const inputSchema$7 = z.object({ repo: z.string().describe("Repository in \"owner/name\" format.") }).strict();
2671
- const repositorySchema$2 = z.object({
2807
+ const repositorySchema$3 = z.object({
2672
2808
  default_branch: z.string(),
2673
2809
  description: z.string().nullable(),
2674
2810
  full_name: z.string(),
@@ -2676,7 +2812,7 @@ const repositorySchema$2 = z.object({
2676
2812
  subscribable: subscribableResourceSchema.optional(),
2677
2813
  url: z.string()
2678
2814
  });
2679
- const outputSchema$7 = pluginToolOutputSchema.merge(repositorySchema$2.extend({ target: z.literal("getRepository") }));
2815
+ const outputSchema$7 = pluginToolOutputSchema.merge(repositorySchema$3.extend({ target: z.literal("getRepository") }));
2680
2816
  /** Read one repository and expose its stable subscription identity. */
2681
2817
  const gitHubGetRepositoryTool = definePluginTool({
2682
2818
  annotations: {
@@ -2806,7 +2942,7 @@ const gitHubGetStatusTool = definePluginTool({
2806
2942
  // src/tools/update-issue.ts
2807
2943
  const inputSchema$5 = z.object({
2808
2944
  repo: z.string().describe("Repository in \"owner/name\" format."),
2809
- number: z.number().int().positive().describe("Issue number."),
2945
+ issue: z.number().int().positive().describe("Issue number."),
2810
2946
  title: z.string().trim().min(1).optional().describe("Replacement issue title."),
2811
2947
  body: z.string().optional().describe("Replacement issue body. The runtime appends requester attribution and the conversation footer."),
2812
2948
  state: z.enum(["open", "closed"]).optional().describe("Replacement issue state."),
@@ -2856,7 +2992,7 @@ const gitHubUpdateIssueTool = definePluginTool({
2856
2992
  if (update.assign_requester && !assignee) throw new PluginToolInputError("The requester has no linked GitHub account, so the issue cannot be assigned to them.");
2857
2993
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
2858
2994
  operation: "github.issue.get",
2859
- path: `${repoPath(repo)}/issues/${update.number}`
2995
+ path: `${repoPath(repo)}/issues/${update.issue}`
2860
2996
  }) : void 0;
2861
2997
  const payload = {
2862
2998
  ...update.title !== void 0 ? { title: update.title } : void 0,
@@ -2868,7 +3004,7 @@ const gitHubUpdateIssueTool = definePluginTool({
2868
3004
  const response = await githubApi(ctx.egress, {
2869
3005
  operation: "github.issue.update",
2870
3006
  method: "PATCH",
2871
- path: `${repoPath(repo)}/issues/${update.number}`,
3007
+ path: `${repoPath(repo)}/issues/${update.issue}`,
2872
3008
  body: payload
2873
3009
  });
2874
3010
  parsed = response.body;
@@ -2878,7 +3014,7 @@ const gitHubUpdateIssueTool = definePluginTool({
2878
3014
  const response = await githubApi(ctx.egress, {
2879
3015
  operation: "github.issue.assign",
2880
3016
  method: "POST",
2881
- path: `${repoPath(repo)}/issues/${update.number}/assignees`,
3017
+ path: `${repoPath(repo)}/issues/${update.issue}/assignees`,
2882
3018
  body: { assignees: [assignee] }
2883
3019
  });
2884
3020
  parsed = response.body;
@@ -2939,7 +3075,7 @@ function createGitHubUpdateIssueCommentTool(botEmail) {
2939
3075
  openWorldHint: true,
2940
3076
  readOnlyHint: false
2941
3077
  },
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.",
3078
+ 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
3079
  inputSchema: inputSchema$4,
2944
3080
  outputSchema: outputSchema$4,
2945
3081
  async execute(input, _options, { egress }) {
@@ -2985,7 +3121,7 @@ function createGitHubUpdateIssueCommentTool(botEmail) {
2985
3121
  // src/tools/update-pull-request.ts
2986
3122
  const inputSchema$3 = z.object({
2987
3123
  repo: z.string().describe("Repository in \"owner/name\" format."),
2988
- number: z.number().int().positive().describe("Pull request number."),
3124
+ pull_request: z.number().int().positive().describe("Pull request number."),
2989
3125
  title: z.string().trim().min(1).optional().describe("Replacement pull request title."),
2990
3126
  body: z.string().optional().describe(`Replacement pull request body. ${PULL_REQUEST_BODY_RULES}`),
2991
3127
  base: z.string().trim().min(1).optional().describe("Replacement base branch."),
@@ -2993,7 +3129,7 @@ const inputSchema$3 = z.object({
2993
3129
  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
3130
  }).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
3131
  const draftMutationResponseSchema = z.object({ data: z.object({ result: z.object({ pullRequest: z.object({ isDraft: z.boolean() }) }) }) });
2996
- const pullRequestSchema$2 = z.object({
3132
+ const pullRequestSchema = z.object({
2997
3133
  base: z.string(),
2998
3134
  body: z.string().nullable(),
2999
3135
  draft: z.boolean(),
@@ -3003,7 +3139,7 @@ const pullRequestSchema$2 = z.object({
3003
3139
  title: z.string(),
3004
3140
  url: z.string()
3005
3141
  });
3006
- const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema$2.extend({ target: z.literal("updatePullRequest") }));
3142
+ const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema.extend({ target: z.literal("updatePullRequest") }));
3007
3143
  function nonEmptyString(value, name) {
3008
3144
  if (!value?.trim()) throw new PluginToolInputError(`${name} is required`);
3009
3145
  return value.trim();
@@ -3046,7 +3182,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3046
3182
  const requester = await resolveGitHubRequester(ctx);
3047
3183
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
3048
3184
  operation: "github.pull.get",
3049
- path: `${repoPath(repo)}/pulls/${update.number}`
3185
+ path: `${repoPath(repo)}/pulls/${update.pull_request}`
3050
3186
  }) : void 0;
3051
3187
  const payload = {
3052
3188
  ...update.title !== void 0 ? { title: update.title } : void 0,
@@ -3057,7 +3193,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3057
3193
  const hasRestUpdate = Object.keys(payload).length > 0;
3058
3194
  const response = await githubApi(ctx.egress, {
3059
3195
  operation: hasRestUpdate ? "github.pull.update" : "github.pull.get",
3060
- path: `${repoPath(repo)}/pulls/${update.number}`,
3196
+ path: `${repoPath(repo)}/pulls/${update.pull_request}`,
3061
3197
  ...hasRestUpdate ? {
3062
3198
  method: "PATCH",
3063
3199
  body: payload
@@ -3129,9 +3265,50 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3129
3265
  }
3130
3266
  });
3131
3267
  }
3268
+ // src/pull-request-feedback.ts
3269
+ /**
3270
+ * GitHub has reactions but no feedback state. `updatePullRequestFeedback` maps
3271
+ * each state to a reaction and keeps at most one state reaction that Junior
3272
+ * owns. It does not change reactions from other users.
3273
+ */
3274
+ const STATUS_TO_REACTION_CONTENT = {
3275
+ reviewing: "eyes",
3276
+ addressed: "+1",
3277
+ declined: "-1"
3278
+ };
3279
+ /** Every reaction that marks a feedback state. */
3280
+ const FEEDBACK_REACTION_CONTENTS = new Set(Object.values(STATUS_TO_REACTION_CONTENT));
3281
+ const GRAPHQL_REACTION_CONTENT = {
3282
+ eyes: "EYES",
3283
+ "+1": "THUMBS_UP",
3284
+ "-1": "THUMBS_DOWN"
3285
+ };
3286
+ /** REST name of each GraphQL reaction content. */
3287
+ const REST_REACTION_CONTENT = new Map(Object.entries(GRAPHQL_REACTION_CONTENT).map(([rest, graphql]) => [graphql, rest]));
3288
+ /** Build the GitHub API path for one pull request comment. */
3289
+ function pullRequestCommentPath(input) {
3290
+ const segment = input.commentKind === "conversation" ? "issues" : "pulls";
3291
+ return `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.name)}/${segment}/comments/${input.commentId}`;
3292
+ }
3293
+ /** Build the GitHub API path for one pull request comment's reactions. */
3294
+ function pullRequestCommentReactionsPath(input) {
3295
+ return `${pullRequestCommentPath(input)}/reactions`;
3296
+ }
3297
+ /** Return the GitHub reaction for one feedback state. */
3298
+ function pullRequestFeedbackReactionContent(status) {
3299
+ return STATUS_TO_REACTION_CONTENT[status];
3300
+ }
3301
+ /** Build the GitHub API path for one pull request review. */
3302
+ function pullRequestReviewPath(input) {
3303
+ return `${repoPath(input)}/pulls/${input.pullRequest}/reviews/${input.reviewId}`;
3304
+ }
3305
+ /** Return the GraphQL name of one REST reaction content. */
3306
+ function graphqlReactionContent(content) {
3307
+ return GRAPHQL_REACTION_CONTENT[content] ?? content;
3308
+ }
3132
3309
  // src/pull-request-reviews.ts
3133
3310
  const REVIEWS_PAGE_SIZE = 100;
3134
- const reviewsSchema = z.array(z.object({
3311
+ const reviewsSchema$1 = z.array(z.object({
3135
3312
  commit_id: z.string().nullable().optional(),
3136
3313
  state: z.string(),
3137
3314
  user: z.object({ login: z.string() }).nullable()
@@ -3145,29 +3322,12 @@ const reviewsSchema = z.array(z.object({
3145
3322
  async function loadLatestReviews(readPage) {
3146
3323
  const latest = /* @__PURE__ */ new Map();
3147
3324
  for (let page = 1;; page++) {
3148
- const batch = reviewsSchema.parse(await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`));
3325
+ const batch = reviewsSchema$1.parse(await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`));
3149
3326
  for (const review of batch) if (review.user && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.user.login.toLowerCase(), review);
3150
3327
  if (batch.length < REVIEWS_PAGE_SIZE) return latest;
3151
3328
  }
3152
3329
  }
3153
3330
  // src/tools/update-pull-request-feedback.ts
3154
- /**
3155
- * GitHub has reactions but no feedback state. This tool maps each state to a
3156
- * reaction and keeps at most one state reaction that Junior owns. It does not
3157
- * change reactions from other users.
3158
- */
3159
- const STATUS_TO_REACTION_CONTENT = {
3160
- reviewing: "eyes",
3161
- addressed: "+1",
3162
- declined: "-1"
3163
- };
3164
- const FEEDBACK_REACTION_CONTENTS = new Set(Object.values(STATUS_TO_REACTION_CONTENT));
3165
- const GRAPHQL_REACTION_CONTENT = {
3166
- eyes: "EYES",
3167
- "+1": "THUMBS_UP",
3168
- "-1": "THUMBS_DOWN"
3169
- };
3170
- const REST_REACTION_CONTENT = new Map(Object.entries(GRAPHQL_REACTION_CONTENT).map(([rest, graphql]) => [graphql, rest]));
3171
3331
  const inputSchema$2 = z.object({
3172
3332
  repo: z.string().describe("Repository in \"owner/name\" format."),
3173
3333
  comment_kind: z.enum([
@@ -3185,18 +3345,6 @@ const outputSchema$2 = pluginToolOutputSchema.extend({
3185
3345
  comment_id: z.number(),
3186
3346
  status: z.enum(["addressed", "declined"])
3187
3347
  });
3188
- function pullRequestCommentPath(input) {
3189
- const segment = input.commentKind === "conversation" ? "issues" : "pulls";
3190
- return `/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.name)}/${segment}/comments/${input.commentId}`;
3191
- }
3192
- /** Build the GitHub API path for one pull request comment's reactions. */
3193
- function pullRequestCommentReactionsPath(input) {
3194
- return `${pullRequestCommentPath(input)}/reactions`;
3195
- }
3196
- /** Return the GitHub reaction for one feedback state. */
3197
- function pullRequestFeedbackReactionContent(status) {
3198
- return STATUS_TO_REACTION_CONTENT[status];
3199
- }
3200
3348
  const reactionSchema = z.object({
3201
3349
  id: z.number(),
3202
3350
  content: z.string(),
@@ -3241,14 +3389,6 @@ async function assertBotAuthoredPullRequest(egress, input) {
3241
3389
  const pull = z.object({ user: z.object({ id: z.number() }).nullable() }).safeParse(pullPayload);
3242
3390
  if (!pullResponse.ok || !pull.success || pull.data.user?.id !== input.botUserId) throw new PluginToolInputError("This bot can only set feedback status on comments on pull requests it authored.");
3243
3391
  }
3244
- /** Build the GitHub API path for one pull request review. */
3245
- function pullRequestReviewPath(input) {
3246
- return `${repoPath(input)}/pulls/${input.pullRequest}/reviews/${input.reviewId}`;
3247
- }
3248
- /** Return the GraphQL name of one REST reaction content. */
3249
- function graphqlReactionContent(content) {
3250
- return GRAPHQL_REACTION_CONTENT[content] ?? content;
3251
- }
3252
3392
  const reviewReactionsSchema = z.object({ data: z.object({ node: z.object({ reactionGroups: z.array(z.object({
3253
3393
  content: z.string(),
3254
3394
  reactors: z.object({ nodes: z.array(z.object({ databaseId: z.number().optional() })) })
@@ -3327,7 +3467,7 @@ async function reviewBodyReactions(egress, input) {
3327
3467
  * approved since then is not asked. The request is optional, so a failure is
3328
3468
  * logged and does not fail the tool.
3329
3469
  */
3330
- async function requestReviewAgain(ctx, input) {
3470
+ async function requestReviewAgain$1(ctx, input) {
3331
3471
  const fields = {
3332
3472
  number: input.pullRequest,
3333
3473
  repo: `${input.owner}/${input.name}`
@@ -3425,7 +3565,7 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3425
3565
  const createPayload = createResponse.body;
3426
3566
  if (failed(createResponse)) throw new Error(`GitHub reaction creation failed with HTTP ${createResponse.status}: ${githubErrorMessage$1(createPayload)}`);
3427
3567
  }
3428
- if (status === "addressed" && reactions.changesRequestedBy) await requestReviewAgain(ctx, {
3568
+ if (status === "addressed" && reactions.changesRequestedBy) await requestReviewAgain$1(ctx, {
3429
3569
  owner: repo.owner,
3430
3570
  name: repo.name,
3431
3571
  pullRequest,
@@ -3558,7 +3698,7 @@ const reviewCommentSchema = z.object({
3558
3698
  }).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
3699
  const inputSchema = z.object({
3560
3700
  repo: z.string().describe("Repository in \"owner/name\" format."),
3561
- number: z.number().int().positive().describe("Pull request number."),
3701
+ pull_request: z.number().int().positive().describe("Pull request number."),
3562
3702
  event: z.enum(["COMMENT", "REQUEST_CHANGES"]).describe("Review result. You cannot approve pull requests."),
3563
3703
  body: z.string().trim().min(1).describe("Review summary."),
3564
3704
  comments: z.array(reviewCommentSchema).optional().describe("Optional inline review comments.")
@@ -3600,7 +3740,7 @@ const gitHubSubmitPullRequestReviewTool = definePluginTool({
3600
3740
  const response = await githubApi(egress, {
3601
3741
  operation: "github.pull.review.create",
3602
3742
  method: "POST",
3603
- path: `${repoPath(repo)}/pulls/${review.number}/reviews`,
3743
+ path: `${repoPath(repo)}/pulls/${review.pull_request}/reviews`,
3604
3744
  body: {
3605
3745
  body: review.body,
3606
3746
  event: review.event,
@@ -3616,7 +3756,7 @@ const gitHubSubmitPullRequestReviewTool = definePluginTool({
3616
3756
  return {
3617
3757
  target: "submitPullRequestReview",
3618
3758
  repo: repo.ref,
3619
- number: review.number,
3759
+ number: review.pull_request,
3620
3760
  reply: {
3621
3761
  text: review.body,
3622
3762
  url: providerResult.html_url
@@ -3648,26 +3788,28 @@ function withGitHubText(tools) {
3648
3788
  /** The GitHub plugin's tools for one deployment configuration. */
3649
3789
  function createGitHubTools(botEmail, pullRequestSubscription, experimental = {}) {
3650
3790
  const descriptionChecks = experimental.pullRequestDescriptionChecks ?? false;
3651
- return withGitHubText({
3652
- reactToIssue: gitHubReactToIssueTool,
3653
- cloneRepository: gitHubCloneRepositoryTool,
3654
- commentOnIssue: gitHubCommentOnIssueTool,
3655
- commentOnPullRequest: gitHubCommentOnPullRequestTool,
3656
- createIssue: gitHubIssueTool,
3657
- createPullRequest: createGitHubPullRequestTool(pullRequestSubscription, descriptionChecks),
3658
- getDeployment: gitHubGetDeploymentTool,
3659
- getIssue: gitHubGetIssueTool,
3660
- getPullRequest: gitHubGetPullRequestTool,
3661
- getRelease: gitHubGetReleaseTool,
3662
- getRepository: gitHubGetRepositoryTool,
3663
- getStatus: gitHubGetStatusTool,
3664
- resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(botEmail),
3665
- submitPullRequestReview: gitHubSubmitPullRequestReviewTool,
3666
- updateIssue: gitHubUpdateIssueTool,
3667
- updateIssueComment: createGitHubUpdateIssueCommentTool(botEmail),
3668
- updatePullRequest: createGitHubUpdatePullRequestTool(descriptionChecks),
3669
- updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(botEmail)
3670
- });
3791
+ return {
3792
+ ...withGitHubText({
3793
+ reactToIssue: gitHubReactToIssueTool,
3794
+ cloneRepository: gitHubCloneRepositoryTool,
3795
+ commentOnIssue: gitHubCommentOnIssueTool,
3796
+ commentOnPullRequest: gitHubCommentOnPullRequestTool,
3797
+ createIssue: gitHubIssueTool,
3798
+ getDeployment: gitHubGetDeploymentTool,
3799
+ getIssue: gitHubGetIssueTool,
3800
+ getPullRequest: gitHubGetPullRequestTool,
3801
+ getRelease: gitHubGetReleaseTool,
3802
+ getRepository: gitHubGetRepositoryTool,
3803
+ getStatus: gitHubGetStatusTool,
3804
+ resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(botEmail),
3805
+ submitPullRequestReview: gitHubSubmitPullRequestReviewTool,
3806
+ updateIssue: gitHubUpdateIssueTool,
3807
+ updateIssueComment: createGitHubUpdateIssueCommentTool(botEmail),
3808
+ updatePullRequest: createGitHubUpdatePullRequestTool(descriptionChecks),
3809
+ updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(botEmail)
3810
+ }),
3811
+ createPullRequest: createGitHubPullRequestTool(pullRequestSubscription, descriptionChecks)
3812
+ };
3671
3813
  }
3672
3814
  // src/issue-outcomes/store.ts
3673
3815
  const githubIssueOutcomeInputSchema = z.object({
@@ -3742,12 +3884,221 @@ async function recordGitHubIssueConversations(db, input) {
3742
3884
  ORDER BY value
3743
3885
  )` }).where(eq(juniorGitHubIssues.issueId, association.issueId)).returning({ issueId: juniorGitHubIssues.issueId })).length > 0;
3744
3886
  }
3887
+ // src/code-change-titles/parse.ts
3888
+ function nativePattern(source) {
3889
+ const regex = new RegExp(source, "i");
3890
+ return (title) => {
3891
+ const match = regex.exec(title);
3892
+ return match ? {
3893
+ scope: match.groups?.["scope"],
3894
+ type: match.groups?.["type"]
3895
+ } : void 0;
3896
+ };
3897
+ }
3898
+ function defaultCategory(title, sources) {
3899
+ return {
3900
+ custom: false,
3901
+ patterns: sources.map(nativePattern),
3902
+ title
3903
+ };
3904
+ }
3905
+ /** Craft's `DEFAULT_RELEASE_CONFIG` categories, in match order. */
3906
+ const DEFAULT_CODE_CHANGE_CATEGORIES = [
3907
+ defaultCategory("Breaking Changes", [String.raw`^(?<type>\w+(?:\((?<scope>[^)]+)\))?!:\s*)`]),
3908
+ defaultCategory("Security", [String.raw`^(?<type>security(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
3909
+ defaultCategory("New Features", [String.raw`^(?<type>feat(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
3910
+ defaultCategory("Bug Fixes", [String.raw`^(?<type>fix(?:\((?<scope>[^)]+)\))?!?:\s*)`, String.raw`^Revert "`]),
3911
+ defaultCategory("Documentation", [String.raw`^(?<type>docs?(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
3912
+ defaultCategory("Internal Changes", [String.raw`^(?<type>(?:build|refactor|meta|chore|ci|ref|perf|tests?|style)(?:\((?<scope>[^)]+)\))?!?:\s*)`])
3913
+ ];
3914
+ const TYPE_WORDS = {
3915
+ build: "Build",
3916
+ chore: "Chore",
3917
+ ci: "CI",
3918
+ doc: "Docs",
3919
+ docs: "Docs",
3920
+ feat: "Feature",
3921
+ fix: "Fix",
3922
+ meta: "Meta",
3923
+ perf: "Perf",
3924
+ ref: "Refactor",
3925
+ refactor: "Refactor",
3926
+ revert: "Revert",
3927
+ security: "Security",
3928
+ style: "Style",
3929
+ test: "Test",
3930
+ tests: "Test"
3931
+ };
3932
+ const BREAKING = /^\w+(?:\([^)]+\))?!:/;
3933
+ const REVERT = /^Revert "/i;
3934
+ const PULL_REQUEST_SUFFIX = /\s*\(#\d+\)$/;
3935
+ /** GitHub titles are at most 256 characters, so this bounds regex work. */
3936
+ const MAX_TITLE_LENGTH = 256;
3937
+ function capitalize(text) {
3938
+ return text.charAt(0).toUpperCase() + text.slice(1);
3939
+ }
3940
+ /** A custom category title as one word pill, without emoji or padding. */
3941
+ function categoryWord(title) {
3942
+ const word = title.replace(/[\p{Extended_Pictographic}\u{FE0F}\u{200D}]/gu, "").trim();
3943
+ return word && !/^breaking\b/i.test(word) ? word : void 0;
3944
+ }
3945
+ function typeWord(category, token, title) {
3946
+ const known = token ? TYPE_WORDS[token.toLowerCase()] : void 0;
3947
+ if (known) return known;
3948
+ if (!token && REVERT.test(title)) return "Revert";
3949
+ return category.custom ? categoryWord(category.title) : void 0;
3950
+ }
3951
+ function firstMatch(title, categories) {
3952
+ for (const category of categories) for (const pattern of category.patterns) {
3953
+ const match = pattern(title);
3954
+ if (match) return {
3955
+ category,
3956
+ match
3957
+ };
3958
+ }
3959
+ }
3960
+ /**
3961
+ * Return the title parts of a pull request title, or undefined when the
3962
+ * title has no conventional prefix and no breaking marker. The first
3963
+ * matching category wins, as in Craft.
3964
+ */
3965
+ function parseCodeChangeTitle(title, categories = DEFAULT_CODE_CHANGE_CATEGORIES) {
3966
+ const bounded = title.slice(0, MAX_TITLE_LENGTH);
3967
+ const breaking = BREAKING.test(bounded);
3968
+ const found = firstMatch(bounded, categories) ?? (breaking ? firstMatch(bounded, DEFAULT_CODE_CHANGE_CATEGORIES.slice(0, 1)) : void 0);
3969
+ if (!found) return void 0;
3970
+ const prefix = found.match.type;
3971
+ const token = prefix ? /^\w+/.exec(prefix)?.[0] : void 0;
3972
+ const rest = (prefix !== void 0 && bounded.startsWith(prefix) ? title.slice(prefix.length) : title).replace(PULL_REQUEST_SUFFIX, "").trim();
3973
+ const type = typeWord(found.category, token, bounded);
3974
+ const scope = found.match.scope?.trim();
3975
+ return {
3976
+ text: rest ? capitalize(rest) : title,
3977
+ ...type ? { type } : void 0,
3978
+ ...scope ? { scope } : void 0,
3979
+ ...breaking ? { breaking: true } : void 0
3980
+ };
3981
+ }
3982
+ // src/code-change-titles/release-config.ts
3983
+ /**
3984
+ * A repository's changelog categories from `.github/release.yml`, the file
3985
+ * that GitHub release notes and Craft read. Craft adds `commit_patterns` to
3986
+ * each category. When the file has categories with patterns, they replace
3987
+ * the default categories, as in Craft.
3988
+ */
3989
+ const MAX_CONFIG_LENGTH = 65536;
3990
+ const MAX_CATEGORIES = 30;
3991
+ const MAX_PATTERNS = 10;
3992
+ const MAX_PATTERN_LENGTH = 200;
3993
+ const releaseConfigSchema = z.object({ changelog: z.object({ categories: z.array(z.object({
3994
+ commit_patterns: z.array(z.string()).optional(),
3995
+ title: z.string().min(1)
3996
+ })).optional() }).optional() });
3997
+ function compilePattern(source) {
3998
+ if (source.length > MAX_PATTERN_LENGTH) return void 0;
3999
+ let regex;
4000
+ try {
4001
+ regex = RE2JS.compile(source, RE2JS.CASE_INSENSITIVE);
4002
+ } catch {
4003
+ return;
4004
+ }
4005
+ if (regex.matcher("").find()) return void 0;
4006
+ const groups = regex.namedGroups();
4007
+ return (title) => {
4008
+ const match = regex.matcher(title);
4009
+ if (!match.find()) return void 0;
4010
+ return {
4011
+ scope: "scope" in groups ? match.group("scope") ?? void 0 : void 0,
4012
+ type: "type" in groups ? match.group("type") ?? void 0 : void 0
4013
+ };
4014
+ };
4015
+ }
4016
+ /**
4017
+ * Return the changelog categories of a `.github/release.yml` text. A file
4018
+ * with no usable `commit_patterns`, or one that does not parse, gives the
4019
+ * default categories.
4020
+ */
4021
+ function parseReleaseCategories(text) {
4022
+ if (text.length > MAX_CONFIG_LENGTH) return DEFAULT_CODE_CHANGE_CATEGORIES;
4023
+ let raw;
4024
+ try {
4025
+ raw = parse$1(text, { maxAliasCount: 100 });
4026
+ } catch {
4027
+ return DEFAULT_CODE_CHANGE_CATEGORIES;
4028
+ }
4029
+ const config = releaseConfigSchema.safeParse(raw);
4030
+ if (!config.success) return DEFAULT_CODE_CHANGE_CATEGORIES;
4031
+ const categories = (config.data.changelog?.categories ?? []).slice(0, MAX_CATEGORIES).map((category) => ({
4032
+ custom: true,
4033
+ patterns: (category.commit_patterns ?? []).slice(0, MAX_PATTERNS).map(compilePattern).filter((pattern) => pattern !== void 0),
4034
+ title: category.title
4035
+ })).filter((category) => category.patterns.length > 0);
4036
+ return categories.length > 0 ? categories : DEFAULT_CODE_CHANGE_CATEGORIES;
4037
+ }
4038
+ // src/webhooks/title-parts.ts
4039
+ /** A repository without the file costs at most one read in this time. */
4040
+ const MISSING_TTL_MS = 36e5;
4041
+ const contentsSchema = z.object({
4042
+ content: z.string(),
4043
+ encoding: z.literal("base64")
4044
+ });
4045
+ function missingKey(repositoryFullName) {
4046
+ return `github-release-config-missing:${repositoryFullName.toLowerCase()}`;
4047
+ }
4048
+ /**
4049
+ * Read a repository's changelog categories from GitHub with a read-only
4050
+ * token. The file is read with its ETag, and a missing file is remembered
4051
+ * for an hour in `env.responses`.
4052
+ */
4053
+ async function loadReleaseCategories(env, repositoryFullName) {
4054
+ const [owner, name] = repositoryFullName.split("/");
4055
+ if (!owner || !name) return DEFAULT_CODE_CHANGE_CATEGORIES;
4056
+ const state = env.responses;
4057
+ if (await state?.get(missingKey(repositoryFullName)).catch(() => void 0)) return DEFAULT_CODE_CHANGE_CATEGORIES;
4058
+ const token = await issueInstallationToken({
4059
+ ...env,
4060
+ permissions: { contents: "read" },
4061
+ repositories: [name]
4062
+ });
4063
+ let response;
4064
+ try {
4065
+ response = await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/contents/.github/release.yml`, {
4066
+ responses: state,
4067
+ token: token.token
4068
+ });
4069
+ } catch (error) {
4070
+ if (!(error instanceof GitHubRequestError) || error.status !== 404) throw error;
4071
+ await state?.set(missingKey(repositoryFullName), true, MISSING_TTL_MS).catch(() => void 0);
4072
+ return DEFAULT_CODE_CHANGE_CATEGORIES;
4073
+ }
4074
+ const file = contentsSchema.safeParse(response);
4075
+ if (!file.success) return DEFAULT_CODE_CHANGE_CATEGORIES;
4076
+ return parseReleaseCategories(Buffer.from(file.data.content, "base64").toString("utf8"));
4077
+ }
4078
+ /**
4079
+ * Return the title parts of a pull request title with its repository's
4080
+ * changelog categories. Title parts are optional, so a failed read of the
4081
+ * categories is logged, and the default categories apply.
4082
+ */
4083
+ async function loadGitHubTitleParts(env, input, log) {
4084
+ let categories;
4085
+ try {
4086
+ categories = await loadReleaseCategories(env, input.repositoryFullName);
4087
+ } catch (error) {
4088
+ logFailOpenFailure(log, "GitHub release config read failed", error, { repository: input.repositoryFullName });
4089
+ categories = DEFAULT_CODE_CHANGE_CATEGORIES;
4090
+ }
4091
+ return parseCodeChangeTitle(input.title, categories);
4092
+ }
3745
4093
  // src/pull-request-outcomes/store.ts
3746
4094
  const githubPullRequestOutcomeInputSchema = z.object({
3747
4095
  candidateOwned: z.boolean(),
3748
4096
  closedAt: z.date().optional(),
3749
4097
  commitComposition: githubPullRequestCommitCompositionSchema.optional(),
3750
- /** When omitted, the stored draft state does not change. */
4098
+ /**
4099
+ * Written to Junior's code index only. When omitted, the stored draft
4100
+ * state does not change.
4101
+ */
3751
4102
  draft: z.boolean().optional(),
3752
4103
  mergedAt: z.date().optional(),
3753
4104
  number: z.number().int().positive(),
@@ -3755,6 +4106,8 @@ const githubPullRequestOutcomeInputSchema = z.object({
3755
4106
  pullRequestId: z.string().min(1),
3756
4107
  repositoryFullName: z.string().min(1),
3757
4108
  repositoryId: z.string().min(1),
4109
+ /** Written to Junior's code index only, not to the GitHub row. */
4110
+ size: codeChangeSizeSchema.optional(),
3758
4111
  state: githubPullRequestStateSchema,
3759
4112
  title: z.string().min(1).optional(),
3760
4113
  updatedAt: z.date()
@@ -3773,10 +4126,8 @@ const githubPullRequestLinkedIssuesInputSchema = z.object({
3773
4126
  /** Select mutable lifecycle fields while excluding transient ownership inputs. */
3774
4127
  function projectionValues(input) {
3775
4128
  return {
3776
- closedAt: input.closedAt ?? null,
3777
4129
  ...input.commitComposition ? { commitComposition: input.commitComposition } : void 0,
3778
- ...input.draft !== void 0 ? { draft: input.draft } : void 0,
3779
- mergedAt: input.mergedAt ?? null,
4130
+ finishedAt: input.mergedAt ?? input.closedAt ?? null,
3780
4131
  number: input.number,
3781
4132
  openedAt: input.openedAt,
3782
4133
  repositoryFullName: input.repositoryFullName,
@@ -3842,14 +4193,13 @@ async function listGitHubFinishedWork(db, conversationIds) {
3842
4193
  if (conversationIds.length === 0) return {};
3843
4194
  const values = sql.join(conversationIds.map((id) => sql`${id}`), sql`, `);
3844
4195
  const rows = await db.select({
3845
- closedAt: juniorGitHubPullRequests.closedAt,
3846
4196
  conversationIds: juniorGitHubPullRequests.conversationIds,
3847
- mergedAt: juniorGitHubPullRequests.mergedAt
4197
+ finishedAt: juniorGitHubPullRequests.finishedAt
3848
4198
  }).from(juniorGitHubPullRequests).where(and(ne(juniorGitHubPullRequests.state, "open"), sql`${juniorGitHubPullRequests.conversationIds} && ARRAY[${values}]::text[]`));
3849
4199
  const candidates = new Set(conversationIds);
3850
4200
  const finishedAtById = /* @__PURE__ */ new Map();
3851
4201
  for (const row of rows) {
3852
- const finishedAt = row.mergedAt ?? row.closedAt;
4202
+ const { finishedAt } = row;
3853
4203
  if (!finishedAt) continue;
3854
4204
  for (const conversationId of row.conversationIds) {
3855
4205
  if (!candidates.has(conversationId)) continue;
@@ -3870,7 +4220,6 @@ async function listGitHubFinishedWork(db, conversationIds) {
3870
4220
  async function listGitHubStaleOpenPullRequests(db, before) {
3871
4221
  const t = juniorGitHubPullRequests;
3872
4222
  return await db.select({
3873
- draft: t.draft,
3874
4223
  number: t.number,
3875
4224
  repositoryFullName: t.repositoryFullName,
3876
4225
  repositoryId: t.repositoryId
@@ -3964,1299 +4313,1625 @@ async function releaseGitHubPullRequestReadySync(db, target, claim) {
3964
4313
  const [row] = await db.select({ requests: t.readySyncRequests }).from(t).where(claimed);
3965
4314
  return row?.requests;
3966
4315
  }
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) {
4316
+ // src/merge-conflict-checks/policy.ts
4317
+ const ITEM_CLOSE_CONCURRENCY = 8;
4318
+ const DAY_MS = 864e5;
4319
+ /** Time after activity by a person in which Junior fixes conflicts. */
4320
+ const ACTIVE_MS = 2 * DAY_MS;
4321
+ /** Shortest time between two fixes of one pull request. */
4322
+ const FIX_INTERVAL_MS = DAY_MS;
4323
+ /** Fixes in a row, with no activity by a person, before Junior waits. */
4324
+ const MAX_FIXES = 3;
4325
+ /** The choice of the merge conflict item that resumes the fixes. */
4326
+ const GITHUB_CONFLICT_RESUME = "Resume";
4327
+ const actorSchema$1 = z.object({ __typename: z.string() }).nullable();
4328
+ const timelineItemSchema = z.union([
4329
+ z.object({
4330
+ __typename: z.literal("PullRequestCommit"),
4331
+ commit: z.object({
4332
+ author: z.object({ user: z.object({ login: z.string() }).nullable() }).nullable(),
4333
+ committedDate: z.string()
4334
+ })
4335
+ }),
4336
+ z.object({
4337
+ __typename: z.literal("PullRequestReview"),
4338
+ author: actorSchema$1,
4339
+ submittedAt: z.string().nullable()
4340
+ }),
4341
+ z.object({
4342
+ __typename: z.literal("IssueComment"),
4343
+ author: actorSchema$1,
4344
+ createdAt: z.string()
4345
+ }),
4346
+ z.object({
4347
+ __typename: z.literal("HeadRefForcePushedEvent"),
4348
+ actor: actorSchema$1,
4349
+ createdAt: z.string()
4350
+ })
4351
+ ]);
4352
+ const historyResponseSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4353
+ createdAt: z.string(),
4354
+ discussion: z.object({ nodes: z.array(timelineItemSchema.nullable()) }),
4355
+ pushes: z.object({ nodes: z.array(timelineItemSchema.nullable()) }),
4356
+ reviewDecision: z.string().nullable()
4357
+ }) }) }) });
4358
+ /**
4359
+ * Read the history from GitHub's answer. A deleted account has no author,
4360
+ * and counts as a person. Activity by a bot is not activity.
4361
+ */
4362
+ function parseGitHubConflictHistory(response) {
4363
+ const pullRequest = historyResponseSchema.parse(response).data.repository.pullRequest;
4364
+ let activeAtMs = Date.parse(pullRequest.createdAt);
4365
+ const record = (bot, at) => {
4366
+ if (!bot && at) activeAtMs = Math.max(activeAtMs, Date.parse(at));
4367
+ };
4368
+ for (const item of [...pullRequest.pushes.nodes, ...pullRequest.discussion.nodes]) {
4369
+ if (!item) continue;
4370
+ switch (item.__typename) {
4371
+ case "PullRequestCommit":
4372
+ record(item.commit.author?.user?.login?.endsWith("[bot]") === true, item.commit.committedDate);
4373
+ break;
4374
+ case "HeadRefForcePushedEvent":
4375
+ record(item.actor?.__typename === "Bot", item.createdAt);
4376
+ break;
4377
+ case "PullRequestReview":
4378
+ record(item.author?.__typename === "Bot", item.submittedAt);
4379
+ break;
4380
+ case "IssueComment": record(item.author?.__typename === "Bot", item.createdAt);
4381
+ }
4382
+ }
3970
4383
  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}`
4384
+ activeAtMs,
4385
+ approved: pullRequest.reviewDecision === "APPROVED"
3987
4386
  };
3988
4387
  }
3989
4388
  /**
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.
4389
+ * Add a fix that Junior started to the stored fixes. A second fix of one
4390
+ * head commit replaces the first. Only the latest `MAX_FIXES` matter.
3993
4391
  */
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"
4008
- }
4392
+ function withGitHubConflictFix(fixes, fix) {
4393
+ return [...fixes.filter(({ headSha }) => headSha !== fix.headSha), fix].slice(-3);
4394
+ }
4395
+ /** Decide what a conflict on one open Junior pull request does. */
4396
+ function gitHubConflictAction(input) {
4397
+ const { askedAtMs, fixes, nowMs, resumedAtMs } = input;
4398
+ const { approved } = input.history;
4399
+ const activeAtMs = Math.max(input.history.activeAtMs, resumedAtMs ?? 0);
4400
+ if (nowMs - activeAtMs > ACTIVE_MS && !approved) return "skip";
4401
+ const resuming = resumedAtMs === activeAtMs && fixes.every(({ atMs }) => atMs < resumedAtMs);
4402
+ const started = resuming ? resumedAtMs : fixes.find(({ headSha }) => headSha === input.headSha)?.atMs;
4403
+ if (started !== void 0) {
4404
+ if (nowMs - started >= FIX_INTERVAL_MS) return askedAtMs !== void 0 && askedAtMs > (resumedAtMs ?? 0) ? "skip" : "ask";
4405
+ return resuming || started === resumedAtMs ? "skip" : "retry";
4406
+ }
4407
+ if (fixes.filter(({ atMs }) => atMs >= activeAtMs).length >= MAX_FIXES) return "skip";
4408
+ const fixedAtMs = Math.max(resumedAtMs ?? 0, ...fixes.map(({ atMs }) => atMs));
4409
+ return !approved && nowMs - fixedAtMs < FIX_INTERVAL_MS ? "skip" : "fix";
4410
+ }
4411
+ const ITEM_KEY_PREFIX = "merge-conflict:";
4412
+ /** The dedupe key of the merge conflict item of one pull request. */
4413
+ function gitHubConflictItemKey(ref) {
4414
+ return `${ITEM_KEY_PREFIX}${ref.repositoryFullName.toLowerCase()}#${ref.number}`;
4415
+ }
4416
+ /** Read the pull request of a merge conflict item's dedupe key. */
4417
+ function parseGitHubConflictItemKey(dedupeKey) {
4418
+ const match = /^([^/#\s]+\/[^/#\s]+)#(\d+)$/.exec(dedupeKey.startsWith(ITEM_KEY_PREFIX) ? dedupeKey.slice(15) : "");
4419
+ return match ? {
4420
+ number: Number(match[2]),
4421
+ repositoryFullName: match[1]
4422
+ } : void 0;
4423
+ }
4424
+ /** Ask the requester to resume a fix that did not land. */
4425
+ async function addUnlandedItem(args) {
4426
+ const { conflict, ref, title } = args;
4427
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
4428
+ numbers: [ref.number],
4429
+ repositoryFullName: ref.repositoryFullName
4430
+ })).get(ref.number);
4431
+ if (!opener?.conversationId) return;
4432
+ const url = conflict.url ?? `https://github.com/${ref.repositoryFullName}/pull/${ref.number}`;
4433
+ const titleParts = title ? await args.loadTitleParts?.({
4434
+ repositoryFullName: ref.repositoryFullName,
4435
+ title
4436
+ }) : void 0;
4437
+ await args.inboxItems.forConversation(opener.conversationId).upsert({
4438
+ assigneeIdentityIds: [opener.identityId],
4439
+ 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.`,
4440
+ choices: [{ label: GITHUB_CONFLICT_RESUME }],
4441
+ dedupeKey: gitHubConflictItemKey(ref),
4442
+ subject: {
4443
+ id: url,
4444
+ title: title ? `${title} (#${ref.number})` : url,
4445
+ ...titleParts ? { titleParts } : void 0,
4446
+ url
4447
+ },
4448
+ title: `Merge conflict · #${ref.number}`
4009
4449
  });
4010
- return recorded;
4011
4450
  }
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
4451
+ /**
4452
+ * Return the merge conflict events to publish for one conflicted pull
4453
+ * request that a Watch or event automation wants. A fix returns `events`.
4454
+ * An ask adds the Inbox item and returns no events. The item is optional,
4455
+ * so a failure is logged, and the next check tries again.
4456
+ */
4457
+ async function applyGitHubConflictPolicy(args) {
4458
+ if (args.draft) return [];
4459
+ const t = juniorGitHubPullRequests;
4460
+ const [row] = await args.db.select({
4461
+ askedAt: t.conflictFixAskedAt,
4462
+ fixes: t.conflictFixes,
4463
+ resumedAt: t.conflictFixesResumedAt
4464
+ }).from(t).where(and(pullRequestRow(args.ref), eq(t.state, "open"))).limit(1);
4465
+ if (!row) return args.events;
4466
+ const nowMs = args.now.getTime();
4467
+ const action = gitHubConflictAction({
4468
+ askedAtMs: row.askedAt?.getTime(),
4469
+ fixes: row.fixes,
4470
+ headSha: args.conflict.headSha,
4471
+ history: parseGitHubConflictHistory(await args.loadHistory(args.ref)),
4472
+ nowMs,
4473
+ resumedAtMs: row.resumedAt?.getTime()
4474
+ });
4475
+ if (action === "skip") return [];
4476
+ if (action === "retry") return args.events;
4477
+ if (action === "fix") {
4478
+ await args.db.update(t).set({ conflictFixes: withGitHubConflictFix(row.fixes, {
4479
+ atMs: nowMs,
4480
+ headSha: args.conflict.headSha
4481
+ }) }).where(pullRequestRow(args.ref));
4482
+ return args.events;
4069
4483
  }
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;
4484
+ try {
4485
+ await addUnlandedItem(args);
4486
+ await args.db.update(t).set({ conflictFixAskedAt: args.now }).where(pullRequestRow(args.ref));
4487
+ } catch (error) {
4488
+ logFailOpenFailure(args.log, "GitHub merge conflict item failed", error, {
4489
+ number: args.ref.number,
4490
+ repository: args.ref.repositoryFullName
4491
+ });
4492
+ }
4493
+ return [];
4077
4494
  }
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");
4495
+ /** Why a merge conflict item closes when GitHub reports no conflict. */
4496
+ const GITHUB_CONFLICT_GONE_REASON = "The pull request no longer has merge conflicts.";
4497
+ /**
4498
+ * Close the merge conflict item of one Junior pull request. Throws
4499
+ * when the Inbox fails, so a caller with no later check can try again.
4500
+ */
4501
+ async function closeGitHubConflictItem(args) {
4502
+ const { ref } = args;
4503
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
4504
+ numbers: [ref.number],
4505
+ repositoryFullName: ref.repositoryFullName
4506
+ })).get(ref.number);
4507
+ if (!opener?.conversationId) return;
4508
+ await args.inboxItems.forConversation(opener.conversationId).close({
4509
+ dedupeKey: gitHubConflictItemKey(ref),
4510
+ reason: args.reason,
4511
+ status: args.status
4512
+ });
4513
+ }
4514
+ /**
4515
+ * Close the merge conflict items of some Junior pull requests, such
4516
+ * as ones that GitHub reports as mergeable. An item is optional, so a failed
4517
+ * close is logged, and the next check closes it again. When an open item
4518
+ * closes, the ask was not dismissed, so a later fix that does not land asks
4519
+ * again.
4520
+ */
4521
+ async function closeGitHubConflictItems(args) {
4522
+ if (args.numbers.length === 0) return;
4523
+ const { repositoryFullName } = args;
4524
+ const openers = await listGitHubPullRequestOpeners(args.db, {
4525
+ numbers: args.numbers,
4526
+ repositoryFullName
4527
+ });
4528
+ const limit = pLimit(ITEM_CLOSE_CONCURRENCY);
4529
+ const close = async (number, conversationId) => {
4530
+ try {
4531
+ if (await args.inboxItems.forConversation(conversationId).close({
4532
+ dedupeKey: gitHubConflictItemKey({
4533
+ number,
4534
+ repositoryFullName
4535
+ }),
4536
+ reason: args.reason,
4537
+ status: args.status
4538
+ })) await args.db.update(juniorGitHubPullRequests).set({ conflictFixAskedAt: null }).where(pullRequestRow({
4539
+ number,
4540
+ repositoryFullName
4541
+ }));
4542
+ } catch (error) {
4543
+ logFailOpenFailure(args.log, "GitHub merge conflict item close failed", error, {
4544
+ number,
4545
+ repository: repositoryFullName
4546
+ });
4547
+ }
4548
+ };
4549
+ await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
4550
+ }
4551
+ // src/webhooks/installation-requests.ts
4552
+ /**
4553
+ * GitHub requests that webhook handling makes with installation tokens.
4554
+ *
4555
+ * A webhook delivery has no Turn and no egress context, so these requests
4556
+ * call GitHub directly. Other plugin code must use host egress.
4557
+ */
4558
+ function splitRepository(fullName, label) {
4559
+ const [owner, name, ...extra] = fullName.split("/");
4560
+ if (!owner || !name || extra.length > 0) throw new Error(`GitHub ${label} received an invalid repository name`);
4095
4561
  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
4562
+ owner,
4563
+ name
4106
4564
  };
4107
4565
  }
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)
4142
- } : void 0;
4566
+ /** Return a reader for pages of a pull request's commits, with a read-only token. */
4567
+ async function loadPullRequestCommitPages(env, pullRequest) {
4568
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request commits");
4569
+ const token = await issueInstallationToken({
4570
+ ...env,
4571
+ permissions: { pull_requests: "read" },
4572
+ repositories: [name]
4573
+ });
4574
+ return async (page, perPage) => await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}/commits?per_page=${perPage}&page=${page}`, {
4575
+ responses: env.responses,
4576
+ token: token.token
4577
+ });
4143
4578
  }
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
4579
+ /** Read one pull request, with a read-only token. */
4580
+ async function loadPullRequest(env, pullRequest) {
4581
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request");
4582
+ const token = await issueInstallationToken({
4583
+ ...env,
4584
+ permissions: { pull_requests: "read" },
4585
+ repositories: [name]
4586
+ });
4587
+ return await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}`, {
4588
+ responses: env.responses,
4589
+ token: token.token
4590
+ });
4591
+ }
4592
+ /** GitHub cannot reach a repository: it is gone, or the installation lost it. */
4593
+ var GitHubRepositoryUnreachableError = class extends Error {
4594
+ constructor(repositoryId) {
4595
+ super(`GitHub repository ${repositoryId} is not reachable`);
4596
+ this.name = "GitHubRepositoryUnreachableError";
4209
4597
  }
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;
4598
+ };
4599
+ const UNREACHABLE_REPOSITORY_MESSAGE = /does not exist or is not accessible/i;
4600
+ /**
4601
+ * Read the lifecycle of some pull requests of one repository in one GraphQL
4602
+ * query, with a read-only token. Each pull request has the alias `pr<index>`.
4603
+ * The repository is found by its id, because a rename changes its name.
4604
+ */
4605
+ async function loadPullRequestLifecycles(env, input) {
4606
+ let token;
4607
+ try {
4608
+ token = await issueInstallationToken({
4609
+ ...env,
4610
+ permissions: { pull_requests: "read" },
4611
+ repositoryIds: [input.repositoryId]
4612
+ });
4613
+ } catch (error) {
4614
+ if (error instanceof GitHubRequestError && error.status === 422 && UNREACHABLE_REPOSITORY_MESSAGE.test(error.message)) throw new GitHubRepositoryUnreachableError(input.repositoryId);
4615
+ throw error;
4616
+ }
4617
+ 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");
4618
+ return await githubRequest("https://api.github.com", "/graphql", {
4619
+ body: {
4620
+ ...pullRequestLifecycles(input.numbers.length),
4621
+ variables: {
4622
+ name,
4623
+ owner,
4624
+ ...Object.fromEntries(input.numbers.map((number, index) => [`n${index}`, number]))
4625
+ }
4626
+ },
4627
+ method: "POST",
4628
+ token: token.token
4629
+ });
4243
4630
  }
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);
4259
- 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
4272
- };
4631
+ /**
4632
+ * Read one page of a repository's open pull requests by one author, with
4633
+ * their mergeability, through GraphQL search and a read-only token.
4634
+ */
4635
+ async function searchOpenPullRequestMergeability(env, input) {
4636
+ const { name } = splitRepository(input.repositoryFullName, "pull request mergeability");
4637
+ const token = await issueInstallationToken({
4638
+ ...env,
4639
+ permissions: { pull_requests: "read" },
4640
+ repositories: [name]
4641
+ });
4642
+ return await githubRequest("https://api.github.com", "/graphql", {
4643
+ body: {
4644
+ ...OPEN_PULL_REQUEST_MERGEABILITY,
4645
+ variables: {
4646
+ after: input.after ?? null,
4647
+ query: `repo:${input.repositoryFullName} is:pr is:open author:${input.author}`
4648
+ }
4649
+ },
4650
+ method: "POST",
4651
+ token: token.token
4652
+ });
4273
4653
  }
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;
4654
+ /** Read the merge conflict history of one pull request, with a read-only token. */
4655
+ async function loadPullRequestConflictHistory(env, pullRequest) {
4656
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request conflict history");
4657
+ const token = await issueInstallationToken({
4658
+ ...env,
4659
+ permissions: { pull_requests: "read" },
4660
+ repositories: [name]
4661
+ });
4662
+ return await githubRequest("https://api.github.com", "/graphql", {
4663
+ body: {
4664
+ ...PULL_REQUEST_CONFLICT_HISTORY,
4665
+ variables: {
4666
+ name,
4667
+ number: pullRequest.number,
4668
+ owner
4669
+ }
4670
+ },
4671
+ method: "POST",
4672
+ token: token.token
4673
+ });
4284
4674
  }
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;
4675
+ /** Ask people to review one pull request, with a pull request write token. */
4676
+ async function requestPullRequestReviewers(env, input) {
4677
+ const { owner, name } = splitRepository(input.repositoryFullName, "pull request review request");
4678
+ const token = await issueInstallationToken({
4679
+ ...env,
4680
+ permissions: { pull_requests: "write" },
4681
+ repositories: [name]
4682
+ });
4683
+ await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${input.number}/requested_reviewers`, {
4684
+ body: { reviewers: input.reviewers },
4685
+ method: "POST",
4686
+ token: token.token
4687
+ });
4295
4688
  }
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
- }))
4355
- };
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;
4689
+ /** Add the "reviewing" reaction to one pull request comment or review body. */
4690
+ async function markPullRequestFeedbackReviewing(env, target) {
4691
+ const { owner, name } = splitRepository(target.repo, "pull request feedback");
4692
+ const token = await issueInstallationToken({
4693
+ ...env,
4694
+ repositories: [name]
4695
+ });
4696
+ const content = pullRequestFeedbackReactionContent("reviewing");
4697
+ if (target.commentKind === "review_body") {
4698
+ const review = z.object({ node_id: z.string().min(1) }).parse(await githubRequest("https://api.github.com", pullRequestReviewPath({
4699
+ owner,
4700
+ name,
4701
+ pullRequest: target.pullRequest,
4702
+ reviewId: target.commentId
4703
+ }), { token: token.token }));
4704
+ const result = z.object({ errors: z.array(z.unknown()).optional() }).parse(await githubRequest("https://api.github.com", "/graphql", {
4705
+ body: {
4706
+ ...ADD_REVIEW_REACTION,
4707
+ variables: {
4708
+ content: graphqlReactionContent(content),
4709
+ subjectId: review.node_id
4710
+ }
4711
+ },
4712
+ method: "POST",
4713
+ token: token.token
4714
+ }));
4715
+ if (result.errors?.length) throw new Error(`GitHub review reaction failed: ${githubErrorMessage$1(result)}`);
4716
+ return;
4717
+ }
4718
+ await githubRequest("https://api.github.com", pullRequestCommentReactionsPath({
4719
+ owner,
4720
+ name,
4721
+ commentKind: target.commentKind,
4722
+ commentId: target.commentId
4723
+ }), {
4724
+ body: { content },
4725
+ method: "POST",
4726
+ token: token.token
4727
+ });
4362
4728
  }
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) })
4729
+ const repositoryPermissionSchema = z.object({
4730
+ permission: z.string().min(1),
4731
+ role_name: z.string().optional()
4378
4732
  });
4733
+ const REPOSITORY_ROLE_TTL_MS = 6e5;
4379
4734
  /**
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.
4735
+ * Read one user's role on a repository, with a metadata-only token. GitHub
4736
+ * returns "none" for accounts without access, such as most bots. Roles are
4737
+ * cached for ten minutes.
4382
4738
  */
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
4739
+ async function loadRepositoryRole(env, cache, target) {
4740
+ const { owner, name } = splitRepository(target.repositoryFullName, "repository role");
4741
+ return await cache.getOrLoad(`repository-role:${owner}/${name}:${target.login}`.toLowerCase(), async () => {
4742
+ const token = await issueInstallationToken({
4743
+ ...env,
4744
+ permissions: { metadata: "read" },
4745
+ repositories: [name]
4414
4746
  });
4415
- }
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
- })
4747
+ const response = repositoryPermissionSchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/collaborators/${encodeURIComponent(target.login)}/permission`, {
4748
+ responses: env.responses,
4749
+ token: token.token
4750
+ }));
4751
+ return {
4752
+ value: response.role_name?.trim() || response.permission,
4753
+ ttlMs: REPOSITORY_ROLE_TTL_MS
4754
+ };
4755
+ });
4756
+ }
4757
+ const timestampSchema$1 = z.iso.datetime({ offset: true });
4758
+ function nodesSchema(node) {
4759
+ return z.array(node.nullable()).transform((items) => items.filter((item) => item !== null));
4760
+ }
4761
+ const actorSchema = z.object({
4762
+ __typename: z.string(),
4763
+ login: z.string().min(1)
4764
+ }).nullable();
4765
+ const reviewsSchema = z.object({
4766
+ pageInfo: z.object({
4767
+ hasPreviousPage: z.boolean(),
4768
+ startCursor: z.string().nullable()
4437
4769
  }),
4438
- z.object({
4439
- __typename: z.literal("PullRequestReview"),
4770
+ nodes: nodesSchema(z.object({
4440
4771
  author: actorSchema,
4441
- submittedAt: z.string().nullable()
4442
- }),
4443
- z.object({
4772
+ commit: z.object({ oid: z.string().min(1) }).nullable(),
4773
+ state: z.string(),
4774
+ submittedAt: timestampSchema$1.nullable()
4775
+ }))
4776
+ });
4777
+ const userLoginSchema = z.object({
4778
+ __typename: z.string(),
4779
+ login: z.string().min(1).optional()
4780
+ }).nullable();
4781
+ const nextActionSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4782
+ autoMergeRequest: z.object({}).nullable(),
4783
+ commits: z.object({ nodes: nodesSchema(z.object({ commit: z.object({ committedDate: timestampSchema$1 }) })) }),
4784
+ headRefOid: z.string().min(1),
4785
+ isDraft: z.boolean(),
4786
+ mergeStateStatus: z.string(),
4787
+ reviewRequests: z.object({ nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })) }),
4788
+ reviews: reviewsSchema,
4789
+ state: z.enum([
4790
+ "CLOSED",
4791
+ "MERGED",
4792
+ "OPEN"
4793
+ ]),
4794
+ timelineItems: z.object({ nodes: nodesSchema(z.discriminatedUnion("__typename", [z.object({
4444
4795
  __typename: z.literal("IssueComment"),
4445
4796
  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()
4797
+ createdAt: timestampSchema$1
4798
+ }), z.object({
4799
+ __typename: z.literal("ReviewRequestedEvent"),
4800
+ createdAt: timestampSchema$1,
4801
+ requestedReviewer: userLoginSchema
4802
+ })])) }),
4803
+ title: z.string(),
4804
+ url: z.string().url()
4459
4805
  }) }) }) });
4806
+ const reviewsPageSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ reviews: reviewsSchema }) }) }) });
4807
+ function restLogin(actor) {
4808
+ return actor.__typename === "Bot" ? `${actor.login}[bot]` : actor.login;
4809
+ }
4460
4810
  /**
4461
- * Read the history from GitHub's answer. A deleted account has no author,
4462
- * and counts as a person.
4811
+ * Read whether a pull request is ready to merge, whether the requester
4812
+ * changed their review, and who acted on it last, with a read-only token
4813
+ * and one GraphQL query. GitHub computes the merge state after a change,
4814
+ * so an unknown state is read once more. A pull request with more than 100
4815
+ * reviews reads the older pages too. Each reviewer counts by their latest
4816
+ * approval, change request, or dismissal. Comments do not change the
4817
+ * result.
4463
4818
  */
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
- }
4819
+ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4820
+ const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request merge state");
4821
+ const token = await issueInstallationToken({
4822
+ ...env,
4823
+ permissions: { pull_requests: "read" },
4824
+ repositories: [name]
4825
+ });
4826
+ const variables = {
4827
+ name,
4828
+ number: pullRequest.number,
4829
+ owner
4477
4830
  };
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;
4831
+ const query = async (document, extra) => await githubRequest("https://api.github.com", "/graphql", {
4832
+ body: {
4833
+ ...document,
4834
+ variables: {
4835
+ ...variables,
4836
+ ...extra
4485
4837
  }
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
4838
  },
4533
- title: `Merge conflict · #${ref.number}`
4839
+ method: "POST",
4840
+ token: token.token
4841
+ });
4842
+ const readPull = async () => nextActionSchema.parse(await query(PULL_REQUEST_NEXT_ACTION)).data.repository.pullRequest;
4843
+ let pull = await readPull();
4844
+ const open = pull.state === "OPEN" && !pull.isDraft;
4845
+ const unknown = (status) => status === "UNKNOWN";
4846
+ if (open && !pull.autoMergeRequest && unknown(pull.mergeStateStatus)) pull = await readPull();
4847
+ const reviews = [...pull.reviews.nodes];
4848
+ let page = pull.reviews.pageInfo;
4849
+ while (open && page.hasPreviousPage && page.startCursor) {
4850
+ const older = reviewsPageSchema.parse(await query(PULL_REQUEST_REVIEWS_BEFORE, { before: page.startCursor })).data.repository.pullRequest.reviews;
4851
+ reviews.unshift(...older.nodes);
4852
+ page = older.pageInfo;
4853
+ }
4854
+ const activity = [];
4855
+ const head = pull.commits.nodes.at(-1);
4856
+ if (head) activity.push({
4857
+ at: new Date(head.commit.committedDate),
4858
+ kind: "push",
4859
+ login: ""
4860
+ });
4861
+ for (const item of pull.timelineItems.nodes) if (item.__typename === "IssueComment" && item.author) activity.push({
4862
+ at: new Date(item.createdAt),
4863
+ kind: "author",
4864
+ login: restLogin(item.author)
4865
+ });
4866
+ else if (item.__typename === "ReviewRequestedEvent" && item.requestedReviewer?.login) activity.push({
4867
+ at: new Date(item.createdAt),
4868
+ kind: "reviewRequest",
4869
+ login: item.requestedReviewer.login
4870
+ });
4871
+ for (const review of reviews) if (review.author && review.submittedAt) activity.push({
4872
+ at: new Date(review.submittedAt),
4873
+ kind: "author",
4874
+ login: restLogin(review.author)
4534
4875
  });
4876
+ const mergeableState = unknown(pull.mergeStateStatus) ? void 0 : pull.mergeStateStatus.toLowerCase();
4877
+ const state = {
4878
+ activity,
4879
+ approved: false,
4880
+ autoMerge: Boolean(pull.autoMergeRequest),
4881
+ draft: pull.isDraft,
4882
+ headSha: pull.headRefOid,
4883
+ ...mergeableState ? { mergeableState } : void 0,
4884
+ requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" && request.requestedReviewer.login ? [request.requestedReviewer.login] : []),
4885
+ state: pull.state === "MERGED" ? "merged" : pull.state === "OPEN" ? "open" : "closed",
4886
+ title: pull.title,
4887
+ url: pull.url
4888
+ };
4889
+ if (!open) return state;
4890
+ const latest = /* @__PURE__ */ new Map();
4891
+ for (const review of reviews) if (review.author && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.author.login.toLowerCase(), review);
4892
+ const reviewStates = [...latest.values()].map((review) => review.state);
4893
+ if (!state.autoMerge && state.mergeableState === "clean") state.approved = reviewStates.includes("APPROVED") && !reviewStates.includes("CHANGES_REQUESTED");
4894
+ const login = requesterLogin?.toLowerCase();
4895
+ const requesterReview = login ? latest.get(login) : void 0;
4896
+ if (requesterReview?.state === "CHANGES_REQUESTED" && requesterReview.commit) {
4897
+ state.changesRequestedCommit = requesterReview.commit.oid;
4898
+ if (requesterReview.submittedAt) state.changesRequestedAt = new Date(requesterReview.submittedAt);
4899
+ }
4900
+ return state;
4535
4901
  }
4902
+ // src/webhooks/pull-request-action.ts
4903
+ const PULL_REQUEST_SYNC_CONCURRENCY = 5;
4536
4904
  /**
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.
4905
+ * A check normally takes a few seconds. After this time, a check that
4906
+ * stopped without its release no longer blocks new checks.
4541
4907
  */
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
- });
4908
+ const READY_SYNC_STALE_MS = 6e4;
4909
+ /** Webhook actions that can change the next action of a pull request. */
4910
+ const ACTION_EVENTS = {
4911
+ pull_request: /* @__PURE__ */ new Set([
4912
+ "auto_merge_disabled",
4913
+ "auto_merge_enabled",
4914
+ "closed",
4915
+ "converted_to_draft",
4916
+ "ready_for_review",
4917
+ "reopened",
4918
+ "review_request_removed",
4919
+ "review_requested",
4920
+ "synchronize"
4921
+ ]),
4922
+ pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
4923
+ };
4924
+ /**
4925
+ * Keys of the two items that came before the one item per pull request.
4926
+ * Each check closes them, so no old item stays open next to the new one.
4927
+ * Remove them when no item from before is open.
4928
+ */
4929
+ const LEGACY_DEDUPE_PREFIXES = ["pull-request-ready:", "pull-request-review-requested:"];
4930
+ function itemName(target) {
4931
+ return `${target.repositoryFullName}#${target.number}`.toLowerCase();
4932
+ }
4933
+ function actionDedupeKey(target) {
4934
+ return `pull-request-action:${itemName(target)}`;
4935
+ }
4936
+ async function closeLegacyItems(items, name) {
4937
+ await Promise.all(LEGACY_DEDUPE_PREFIXES.map((prefix) => items.close({
4938
+ dedupeKey: `${prefix}${name}`,
4939
+ reason: "One item now shows the next action.",
4940
+ status: "dismissed"
4941
+ })));
4942
+ }
4943
+ const repositorySchema$2 = z.object({ full_name: z.string().min(1) });
4944
+ const pullRequestWebhookSchema = z.object({
4945
+ action: z.string(),
4946
+ pull_request: z.object({ number: z.number().int().positive() }),
4947
+ repository: repositorySchema$2
4948
+ });
4949
+ const commentWebhookSchema = z.object({
4950
+ action: z.literal("created"),
4951
+ comment: z.object({ user: z.object({ login: z.string().min(1) }).nullable() }),
4952
+ issue: z.object({
4953
+ number: z.number().int().positive(),
4954
+ pull_request: z.object({})
4955
+ }).optional(),
4956
+ pull_request: z.object({ number: z.number().int().positive() }).optional(),
4957
+ repository: repositorySchema$2
4958
+ });
4959
+ /** Return the pull requests whose next action one webhook delivery can change. */
4960
+ function pullRequestActionTargets(eventName, body) {
4961
+ if (eventName === "check_suite") return checkSuitePullRequests(body);
4962
+ if (eventName === "issue_comment" || eventName === "pull_request_review_comment") {
4963
+ const parsed = commentWebhookSchema.safeParse(body);
4964
+ if (!parsed.success) return [];
4965
+ const { comment, repository } = parsed.data;
4966
+ const number = (parsed.data.issue ?? parsed.data.pull_request)?.number;
4967
+ if (number === void 0 || !comment.user) return [];
4968
+ return [{
4969
+ commentBy: comment.user.login,
4970
+ number,
4971
+ repositoryFullName: repository.full_name
4972
+ }];
4557
4973
  }
4558
- return [];
4974
+ const actions = ACTION_EVENTS[eventName];
4975
+ const parsed = pullRequestWebhookSchema.safeParse(body);
4976
+ if (!actions || !parsed.success || !actions.has(parsed.data.action)) return [];
4977
+ return [{
4978
+ number: parsed.data.pull_request.number,
4979
+ repositoryFullName: parsed.data.repository.full_name
4980
+ }];
4559
4981
  }
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
4982
  /**
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.
4983
+ * Who did one thing on a pull request. A push counts as Junior's, as new
4984
+ * commits do. A request for the requester's review hands the pull request
4985
+ * to them, so it counts as Junior's too.
4565
4986
  */
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
4577
- });
4987
+ function actor(activity, requesterLogin, botEmail) {
4988
+ const byRequester = requesterLogin !== void 0 && activity.login.toLowerCase() === requesterLogin.toLowerCase();
4989
+ switch (activity.kind) {
4990
+ case "push": return "junior";
4991
+ case "reviewRequest": return byRequester ? "junior" : void 0;
4992
+ case "author":
4993
+ if (isBotLogin(activity.login, botEmail)) return "junior";
4994
+ return byRequester ? "requester" : void 0;
4995
+ }
4996
+ }
4997
+ function latestActivity(activity, requesterLogin, botEmail) {
4998
+ const latest = {};
4999
+ for (const entry of activity) {
5000
+ const by = actor(entry, requesterLogin, botEmail);
5001
+ if (!by) continue;
5002
+ const key = by === "junior" ? "juniorAt" : "requesterAt";
5003
+ const saved = latest[key];
5004
+ if (!saved || entry.at > saved) latest[key] = entry.at;
5005
+ }
5006
+ return latest;
5007
+ }
5008
+ function timeOf(at) {
5009
+ return at ? at.getTime() : Number.NEGATIVE_INFINITY;
4578
5010
  }
4579
5011
  /**
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.
5012
+ * Return why the requester's review is wanted again after their change
5013
+ * request, or undefined while Junior acts next.
4583
5014
  */
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
4590
- });
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))] : []));
5015
+ function reviewAgainReason(state, activity) {
5016
+ if (!state.changesRequestedCommit) return void 0;
5017
+ const newCommits = state.changesRequestedCommit !== state.headSha;
5018
+ const changesRequestedAt = timeOf(state.changesRequestedAt);
5019
+ const requesterAt = Math.max(timeOf(activity.requesterAt), changesRequestedAt);
5020
+ if (timeOf(activity.juniorAt) > requesterAt) return newCommits ? "commits" : "reply";
5021
+ return newCommits && !(timeOf(activity.requesterAt) > changesRequestedAt) ? "commits" : void 0;
4610
5022
  }
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
5023
  /**
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.
5024
+ * Derive the requester's next action. Return undefined when it cannot be
5025
+ * known yet, so a later event decides.
4632
5026
  */
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
5027
+ function nextAction(state, requester, saved) {
5028
+ if (state.state !== "open") return {};
5029
+ const canMerge = !state.draft && !state.autoMerge;
5030
+ if (canMerge && state.mergeableState === "clean" && state.approved) return { action: "merge" };
5031
+ if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5032
+ const requested = isRequested(state, requester.login);
5033
+ if (requested && !requester.actedLast) return { action: "review" };
5034
+ const reason = reviewAgainReason(state, requester.activity);
5035
+ if (reason) return {
5036
+ action: "review",
5037
+ reason
5038
+ };
5039
+ if (requested && !state.changesRequestedCommit) return { action: "review" };
5040
+ if (canMerge && !state.mergeableState) return void 0;
5041
+ return {};
5042
+ }
5043
+ function isRequested(state, login) {
5044
+ const lower = login?.toLowerCase();
5045
+ return state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === lower);
5046
+ }
5047
+ const REVIEW_AGAIN_TEXT = {
5048
+ commits: (number) => `#${number} has new commits since you requested changes.`,
5049
+ reply: (number) => `#${number} has a reply since you requested changes.`
5050
+ };
5051
+ /** Why an item closes when its pull request is no longer open. */
5052
+ const ENDED_REASONS = {
5053
+ closed: {
5054
+ reason: "The pull request closed without merging.",
5055
+ status: "dismissed"
5056
+ },
5057
+ merged: {
5058
+ reason: "The pull request merged.",
5059
+ status: "done"
5060
+ }
5061
+ };
5062
+ function endedReason(state) {
5063
+ return state === "open" ? void 0 : ENDED_REASONS[state];
5064
+ }
5065
+ function closeReason(state, previous) {
5066
+ const ended = endedReason(state.state);
5067
+ if (ended) return ended;
5068
+ if (previous === "review") return {
5069
+ reason: "The review request ended.",
5070
+ status: "done"
5071
+ };
5072
+ if (state.autoMerge) return {
5073
+ reason: "Auto-merge is on.",
5074
+ status: "dismissed"
5075
+ };
5076
+ return {
5077
+ reason: "The pull request is no longer ready to merge.",
5078
+ status: "dismissed"
5079
+ };
5080
+ }
5081
+ async function showAction(items, args) {
5082
+ const { action, number, state } = args;
5083
+ if (action) await items.upsert({
5084
+ assigneeIdentityIds: [args.identityId],
5085
+ 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}`,
5086
+ dedupeKey: args.dedupeKey,
5087
+ subject: {
5088
+ id: state.url,
5089
+ title: `${state.title} (#${number})`,
5090
+ ...args.titleParts ? { titleParts: args.titleParts } : void 0,
5091
+ url: state.url
5092
+ },
5093
+ title: action === "merge" ? `Ready to merge · #${number}` : `Review requested · #${number}`,
5094
+ waitsOnAssignees: true
5095
+ });
5096
+ else if (args.previous) await items.close({
5097
+ dedupeKey: args.dedupeKey,
5098
+ ...closeReason(state, args.previous)
4639
5099
  });
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
5100
  }
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
5101
+ /**
5102
+ * Close the next-action item and the merge conflict notice of a pull request
5103
+ * that merged or closed. The outcome write calls this before it marks the
5104
+ * chips, so no reader sees an ended pull request next to its open item. The
5105
+ * items are optional, so a failure is logged. In a webhook, the next-action
5106
+ * sync after it closes the item again.
5107
+ */
5108
+ async function closeEndedGitHubPullRequestItems(args) {
5109
+ const { target } = args;
5110
+ try {
5111
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
5112
+ numbers: [target.number],
5113
+ repositoryFullName: target.repositoryFullName
5114
+ })).get(target.number);
5115
+ if (!opener?.conversationId) return;
5116
+ const items = args.inboxItems.forConversation(opener.conversationId);
5117
+ const reason = ENDED_REASONS[args.state];
5118
+ await Promise.all([items.close({
5119
+ dedupeKey: actionDedupeKey(target),
5120
+ ...reason
5121
+ }), items.close({
5122
+ dedupeKey: gitHubConflictItemKey(target),
5123
+ ...reason
5124
+ })]);
5125
+ } catch (error) {
5126
+ logFailOpenFailure(args.log, "GitHub ended pull request item close failed", error, {
5127
+ number: target.number,
5128
+ repository: target.repositoryFullName
4663
5129
  });
4664
5130
  }
4665
- return [...refs.values()];
4666
5131
  }
4667
5132
  /**
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.
5133
+ * Ask for the requester's review on GitHub, so GitHub notifies them. The
5134
+ * item already asks, so a failure is logged and the item stays.
4671
5135
  */
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;
5136
+ async function requestReviewAgain(args, target, login) {
5137
+ try {
5138
+ await requestPullRequestReviewers(args.env, {
5139
+ ...target,
5140
+ reviewers: [login]
5141
+ });
5142
+ } catch (error) {
5143
+ logFailOpenFailure(args.log, "GitHub review request again failed", error, {
5144
+ number: target.number,
5145
+ repository: target.repositoryFullName
5146
+ });
5147
+ }
5148
+ }
5149
+ async function syncOne(args, target) {
5150
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
5151
+ numbers: [target.number],
5152
+ repositoryFullName: target.repositoryFullName
5153
+ })).get(target.number);
5154
+ if (!opener?.conversationId) return;
5155
+ const items = args.inboxItems.forConversation(opener.conversationId);
5156
+ const name = itemName(target);
5157
+ const dedupeKey = actionDedupeKey(target);
5158
+ const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
5159
+ if (target.commentBy !== void 0 && !actor({
5160
+ kind: "author",
5161
+ login: target.commentBy
5162
+ }, requesterLogin, args.botEmail)) return;
5163
+ const claim = await claimGitHubPullRequestReadySync(args.db, target, {
5164
+ now: /* @__PURE__ */ new Date(),
5165
+ staleMs: READY_SYNC_STALE_MS
5166
+ });
5167
+ if (!claim) return;
5168
+ const { id } = claim;
5169
+ let saved = claim.action;
5170
+ let requests = claim.requests;
5171
+ let failure;
5172
+ const check = async (previous) => {
5173
+ const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
5174
+ const activity = latestActivity(state.activity, requesterLogin, args.botEmail);
5175
+ const next = nextAction(state, {
5176
+ activity,
5177
+ actedLast: timeOf(activity.requesterAt) > timeOf(activity.juniorAt),
5178
+ login: requesterLogin
5179
+ }, previous);
5180
+ const changed = next !== void 0 && next.action !== previous;
5181
+ if (changed) {
5182
+ await showAction(items, {
5183
+ action: next.action,
5184
+ dedupeKey,
5185
+ identityId: opener.identityId,
5186
+ number: target.number,
5187
+ previous,
5188
+ reason: next.reason,
5189
+ state,
5190
+ titleParts: next.action ? await loadGitHubTitleParts(args.env, {
5191
+ repositoryFullName: target.repositoryFullName,
5192
+ title: state.title
5193
+ }, args.log) : void 0
5194
+ });
5195
+ if (next.reason && requesterLogin && !isRequested(state, requesterLogin)) await requestReviewAgain(args, target, requesterLogin);
5196
+ }
5197
+ await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
5198
+ dedupeKey: gitHubConflictItemKey(target),
5199
+ ...endedReason(state.state) ?? {
5200
+ reason: "The pull request no longer has merge conflicts.",
5201
+ status: "done"
5202
+ }
5203
+ }) : void 0]);
5204
+ if (!changed) return previous;
5205
+ await setGitHubPullRequestNextAction(args.db, {
5206
+ ...target,
5207
+ action: next.action
5208
+ });
5209
+ return next.action;
5210
+ };
5211
+ while (requests !== void 0) {
5212
+ try {
5213
+ saved = await check(saved);
5214
+ } catch (error) {
5215
+ failure ??= error;
5216
+ }
5217
+ requests = await releaseGitHubPullRequestReadySync(args.db, target, {
5218
+ id,
5219
+ requests
5220
+ });
5221
+ }
5222
+ if (failure !== void 0) throw failure;
4676
5223
  }
4677
5224
  /**
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.
5225
+ * Add, change, or close the next-action item of each Junior pull request that
5226
+ * a webhook delivery can change. The item is optional, so a failure is logged
5227
+ * and does not fail the delivery.
4685
5228
  */
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 [];
5229
+ async function syncGitHubPullRequestActions(args) {
5230
+ await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map(args.targets, async (target) => {
4691
5231
  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
- });
5232
+ await syncOne(args, target);
4714
5233
  } catch (error) {
4715
- logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
5234
+ logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
4716
5235
  deliveryId: args.deliveryId,
4717
- pullRequest: ref.number,
4718
- repository: ref.repositoryFullName
5236
+ number: target.number,
5237
+ repository: target.repositoryFullName
4719
5238
  });
4720
- return [];
4721
5239
  }
5240
+ });
5241
+ }
5242
+ // src/pull-request-outcomes/apply.ts
5243
+ /** Write a pull request outcome as a code change in Junior's code index. */
5244
+ function githubCodeChange(outcome, conversationIds) {
5245
+ return {
5246
+ closedAt: outcome.closedAt,
5247
+ conversationIds,
5248
+ draft: outcome.draft,
5249
+ mergedAt: outcome.mergedAt,
5250
+ number: outcome.number,
5251
+ openedAt: outcome.openedAt,
5252
+ providerId: outcome.pullRequestId,
5253
+ repository: {
5254
+ name: outcome.repositoryFullName,
5255
+ providerId: outcome.repositoryId,
5256
+ url: `https://github.com/${outcome.repositoryFullName}`
5257
+ },
5258
+ size: outcome.size,
5259
+ state: outcome.state === "closed_unmerged" ? "closed" : outcome.state,
5260
+ title: outcome.title,
5261
+ updatedAt: outcome.updatedAt,
5262
+ url: `https://github.com/${outcome.repositoryFullName}/pull/${outcome.number}`
4722
5263
  };
4723
- return (await pLimit(PULL_REQUEST_CHECK_CONCURRENCY).map(pullRequestRefs(args.events), (ref) => check(ref))).flat();
4724
5264
  }
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
5265
  /**
4729
- * The heartbeat's own record of a running or repeated check. Only the
4730
- * heartbeat writes it, so it needs no lock.
5266
+ * Record one pull request outcome. When the stored row changes, update the
5267
+ * code index, and mark the chip of each linked conversation merged or closed.
5268
+ * A merged or closed pull request closes its Inbox items first, so no
5269
+ * reader sees a merged chip next to an open item. A failed chip or item is
5270
+ * logged, so it does not stop the work after it.
4731
5271
  */
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()
4736
- });
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);
5272
+ async function applyGitHubPullRequestOutcome(args) {
5273
+ const { outcome } = args;
5274
+ const recorded = await recordGitHubPullRequestOutcome(args.db, outcome);
5275
+ if (!recorded.applied) return recorded;
5276
+ await args.codeChanges.record(githubCodeChange(outcome, recorded.conversationIds));
5277
+ if (outcome.state !== "open") {
5278
+ const state = outcome.state === "merged" ? "merged" : "closed";
5279
+ await closeEndedGitHubPullRequestItems({
5280
+ db: args.db,
5281
+ log: args.log,
5282
+ inboxItems: args.inboxItems,
5283
+ state,
5284
+ target: outcome
5285
+ });
5286
+ await updateGitHubAnnotations({
5287
+ annotations: args.annotations,
5288
+ conversationIds: recorded.conversationIds,
5289
+ log: args.log,
5290
+ update: {
5291
+ repo: outcome.repositoryFullName,
5292
+ number: outcome.number,
5293
+ objectType: "code_change",
5294
+ status: state
5295
+ }
5296
+ });
5297
+ }
5298
+ return recorded;
4747
5299
  }
4748
- /**
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.
4752
- */
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;
5300
+ // src/webhooks/issue-outcome.ts
5301
+ const canonicalIssueOutcomeSchema = z.object({
5302
+ action: z.enum([
5303
+ "opened",
5304
+ "closed",
5305
+ "reopened"
5306
+ ]),
5307
+ issue: z.object({
5308
+ body: z.string().nullable().optional(),
5309
+ closed_at: z.string().nullable().optional(),
5310
+ created_at: z.string(),
5311
+ id: z.number().int().positive(),
5312
+ number: z.number().int().positive(),
5313
+ state_reason: githubIssueStateReasonSchema.nullable().optional(),
5314
+ updated_at: z.string(),
5315
+ user: z.object({ login: z.string().min(1) }).strict()
5316
+ }).strict(),
5317
+ repository: z.object({
5318
+ full_name: z.string().min(1),
5319
+ id: z.number().int().positive()
5320
+ }).strict()
5321
+ }).strict();
5322
+ const issueOutcomeSchema = z.object({
5323
+ action: z.enum([
5324
+ "opened",
5325
+ "closed",
5326
+ "reopened"
5327
+ ]),
5328
+ issue: z.object({
5329
+ body: z.string().nullable().optional(),
5330
+ closed_at: z.string().nullable().optional(),
5331
+ created_at: z.string(),
5332
+ id: z.number().int().positive(),
5333
+ number: z.number().int().positive(),
5334
+ state_reason: githubIssueStateReasonSchema.nullable().optional(),
5335
+ updated_at: z.string(),
5336
+ user: z.object({ login: z.string().min(1) }).passthrough()
5337
+ }).passthrough(),
5338
+ repository: z.object({
5339
+ full_name: z.string().min(1),
5340
+ id: z.number().int().positive()
5341
+ }).passthrough()
5342
+ }).passthrough().transform((provider) => canonicalIssueOutcomeSchema.parse({
5343
+ action: provider.action,
5344
+ issue: {
5345
+ body: provider.issue.body,
5346
+ closed_at: provider.issue.closed_at,
5347
+ created_at: provider.issue.created_at,
5348
+ id: provider.issue.id,
5349
+ number: provider.issue.number,
5350
+ state_reason: provider.issue.state_reason,
5351
+ updated_at: provider.issue.updated_at,
5352
+ user: { login: provider.issue.user.login }
5353
+ },
5354
+ repository: {
5355
+ full_name: provider.repository.full_name,
5356
+ id: provider.repository.id
5357
+ }
5358
+ }));
5359
+ const issueLifecycleActionSchema = z.object({ action: z.string() }).passthrough();
5360
+ /** Parse a provider timestamp, rejecting missing or invalid lifecycle values. */
5361
+ function timestamp$1(value) {
5362
+ if (!value) return void 0;
5363
+ const parsed = new Date(value);
5364
+ return Number.isFinite(parsed.getTime()) ? parsed : void 0;
4757
5365
  }
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));
5366
+ /** Normalize only the fields required for the Junior-owned issue projection. */
5367
+ function normalizeGitHubIssueOutcome(args) {
5368
+ const lifecycle = issueLifecycleActionSchema.safeParse(args.body);
5369
+ if (!lifecycle.success || ![
5370
+ "opened",
5371
+ "closed",
5372
+ "reopened"
5373
+ ].includes(lifecycle.data.action)) return;
5374
+ const parsed = issueOutcomeSchema.parse(args.body);
5375
+ const issue = parsed.issue;
5376
+ const openedAt = timestamp$1(issue.created_at);
5377
+ const updatedAt = timestamp$1(issue.updated_at);
5378
+ if (!openedAt || !updatedAt) throw new Error("GitHub issue lifecycle timestamps are invalid");
5379
+ 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");
5380
+ const candidateOwned = Boolean(isBotLogin(issue.user.login, args.botEmail) && issue.body?.includes("<!-- junior-session-footer:start -->")) && (parsed.action === "opened" || parsed.action === "closed");
5381
+ const closedAt = timestamp$1(issue.closed_at);
5382
+ if (parsed.action === "closed" && !closedAt) throw new Error("GitHub issue terminal timestamp is invalid");
4776
5383
  return {
4777
- attempts,
4778
- repositoryFullName: args.repositoryFullName
5384
+ candidateOwned,
5385
+ closedAt,
5386
+ issueId: String(issue.id),
5387
+ number: issue.number,
5388
+ openedAt,
5389
+ repositoryFullName: parsed.repository.full_name,
5390
+ repositoryId: String(parsed.repository.id),
5391
+ state: parsed.action === "closed" ? "closed" : "open",
5392
+ stateReason: parsed.action === "closed" ? issue.state_reason ?? void 0 : void 0,
5393
+ updatedAt
4779
5394
  };
4780
5395
  }
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;
4786
- }
4787
- await state.set(repeatKey(check.repositoryFullName), {
4788
- attempts: check.attempts,
4789
- dueAtMs: retryAtMs
4790
- }, CHECK_TTL_MS);
5396
+ const canonicalIssueConversationSchema = z.object({
5397
+ issue: z.object({
5398
+ body: z.string().nullable().optional(),
5399
+ id: z.number().int().positive(),
5400
+ user: z.object({ login: z.string().min(1) }).strict()
5401
+ }).strict(),
5402
+ sender: z.object({ login: z.string().min(1) }).strict().optional()
5403
+ }).strict();
5404
+ const issueConversationSchema = z.object({
5405
+ issue: z.object({
5406
+ body: z.string().nullable().optional(),
5407
+ id: z.number().int().positive(),
5408
+ user: z.object({ login: z.string().min(1) }).passthrough()
5409
+ }).passthrough(),
5410
+ sender: z.object({ login: z.string().min(1) }).passthrough().optional()
5411
+ }).passthrough().transform((provider) => canonicalIssueConversationSchema.parse({
5412
+ issue: {
5413
+ body: provider.issue.body,
5414
+ id: provider.issue.id,
5415
+ user: { login: provider.issue.user.login }
5416
+ },
5417
+ ...provider.sender ? { sender: { login: provider.sender.login } } : void 0
5418
+ }));
5419
+ /** Normalize native conversation ids written to a Junior-owned issue by its bot. */
5420
+ function normalizeGitHubIssueConversations(args) {
5421
+ const parsed = issueConversationSchema.safeParse(args.body);
5422
+ if (!parsed.success) return void 0;
5423
+ if (!isBotLogin(parsed.data.issue.user.login, args.botEmail)) return;
5424
+ const sender = parsed.data.sender;
5425
+ if (sender && !isBotLogin(sender.login, args.botEmail)) return void 0;
5426
+ const conversationIds = githubConversationIds(parsed.data.issue.body);
5427
+ return conversationIds.length > 0 ? {
5428
+ conversationIds,
5429
+ issueId: String(parsed.data.issue.id)
5430
+ } : void 0;
4791
5431
  }
4792
- // src/merge-conflict-checks/webhooks.ts
4793
- /**
4794
- * Time from a push to its check. GitHub calculates mergeability after a
4795
- * push, and pushes in this time share one check.
4796
- */
4797
- const CONFLICT_CHECK_DELAY_MS = 12e4;
4798
- const pushSchema = z.object({
4799
- deleted: z.boolean().optional(),
4800
- ref: z.string(),
5432
+ // src/webhooks/pull-request-outcome.ts
5433
+ const count = z.number().int().nonnegative();
5434
+ const pullRequestLifecycleActionsSchema = z.enum([
5435
+ "opened",
5436
+ "closed",
5437
+ "reopened",
5438
+ "ready_for_review",
5439
+ "converted_to_draft",
5440
+ "synchronize"
5441
+ ]);
5442
+ const canonicalPullRequestOutcomeSchema = z.object({
5443
+ action: pullRequestLifecycleActionsSchema,
5444
+ pull_request: z.object({
5445
+ additions: count.optional(),
5446
+ body: z.string().nullable().optional(),
5447
+ changed_files: count.optional(),
5448
+ closed_at: z.string().nullable().optional(),
5449
+ created_at: z.string(),
5450
+ deletions: count.optional(),
5451
+ draft: z.boolean().optional(),
5452
+ id: z.number().int().positive(),
5453
+ merged: z.boolean(),
5454
+ merged_at: z.string().nullable().optional(),
5455
+ number: z.number().int().positive(),
5456
+ title: z.string().min(1).optional(),
5457
+ updated_at: z.string(),
5458
+ user: z.object({ login: z.string().min(1) }).strict()
5459
+ }).strict(),
4801
5460
  repository: z.object({
4802
- default_branch: z.string().min(1),
4803
- full_name: z.string().min(1)
4804
- })
4805
- });
4806
- /**
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.
4810
- */
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
- });
5461
+ full_name: z.string().min(1),
5462
+ id: z.number().int().positive()
5463
+ }).strict()
5464
+ }).strict();
5465
+ const pullRequestOutcomeSchema = z.object({
5466
+ action: pullRequestLifecycleActionsSchema,
5467
+ pull_request: z.object({
5468
+ additions: count.optional(),
5469
+ body: z.string().nullable().optional(),
5470
+ changed_files: count.optional(),
5471
+ closed_at: z.string().nullable().optional(),
5472
+ created_at: z.string(),
5473
+ deletions: count.optional(),
5474
+ draft: z.boolean().optional(),
5475
+ id: z.number().int().positive(),
5476
+ merged: z.boolean(),
5477
+ merged_at: z.string().nullable().optional(),
5478
+ number: z.number().int().positive(),
5479
+ title: z.string().min(1).optional(),
5480
+ updated_at: z.string(),
5481
+ user: z.object({ login: z.string().min(1) }).passthrough()
5482
+ }).passthrough(),
5483
+ repository: z.object({
5484
+ full_name: z.string().min(1),
5485
+ id: z.number().int().positive()
5486
+ }).passthrough()
5487
+ }).passthrough().transform((provider) => canonicalPullRequestOutcomeSchema.parse({
5488
+ action: provider.action,
5489
+ pull_request: {
5490
+ additions: provider.pull_request.additions,
5491
+ body: provider.pull_request.body,
5492
+ changed_files: provider.pull_request.changed_files,
5493
+ closed_at: provider.pull_request.closed_at,
5494
+ created_at: provider.pull_request.created_at,
5495
+ deletions: provider.pull_request.deletions,
5496
+ draft: provider.pull_request.draft,
5497
+ id: provider.pull_request.id,
5498
+ merged: provider.pull_request.merged,
5499
+ merged_at: provider.pull_request.merged_at,
5500
+ number: provider.pull_request.number,
5501
+ title: provider.pull_request.title,
5502
+ updated_at: provider.pull_request.updated_at,
5503
+ user: { login: provider.pull_request.user.login }
5504
+ },
5505
+ repository: {
5506
+ full_name: provider.repository.full_name,
5507
+ id: provider.repository.id
5508
+ }
5509
+ }));
5510
+ const pullRequestLifecycleActionSchema = z.object({ action: z.string() }).passthrough();
5511
+ const canonicalPullRequestConversationSchema = z.object({
5512
+ pull_request: z.object({
5513
+ body: z.string().nullable().optional(),
5514
+ id: z.number().int().positive(),
5515
+ user: z.object({ login: z.string().min(1) }).strict()
5516
+ }).strict(),
5517
+ repository: z.object({ full_name: z.string().min(1) }).strict(),
5518
+ sender: z.object({ login: z.string().min(1) }).strict()
5519
+ }).strict();
5520
+ const pullRequestConversationSchema = z.object({
5521
+ pull_request: z.object({
5522
+ body: z.string().nullable().optional(),
5523
+ id: z.number().int().positive(),
5524
+ user: z.object({ login: z.string().min(1) }).passthrough()
5525
+ }).passthrough(),
5526
+ repository: z.object({ full_name: z.string().min(1) }).passthrough(),
5527
+ sender: z.object({ login: z.string().min(1) }).passthrough()
5528
+ }).passthrough().transform((provider) => canonicalPullRequestConversationSchema.parse({
5529
+ pull_request: {
5530
+ body: provider.pull_request.body,
5531
+ id: provider.pull_request.id,
5532
+ user: { login: provider.pull_request.user.login }
5533
+ },
5534
+ repository: { full_name: provider.repository.full_name },
5535
+ sender: { login: provider.sender.login }
5536
+ }));
5537
+ /** Parse a provider timestamp. A missing or invalid value is undefined. */
5538
+ function timestamp(value) {
5539
+ if (!value) return void 0;
5540
+ const parsed = new Date(value);
5541
+ return Number.isFinite(parsed.getTime()) ? parsed : void 0;
4820
5542
  }
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`);
5543
+ /** The size of a pull request payload. Undefined when it counts nothing. */
5544
+ function githubPullRequestSize(pullRequest) {
5545
+ const size = {};
5546
+ if (pullRequest.additions !== void 0) size.additions = pullRequest.additions;
5547
+ if (pullRequest.deletions !== void 0) size.deletions = pullRequest.deletions;
5548
+ if (pullRequest.changed_files !== void 0) size.changedFiles = pullRequest.changed_files;
5549
+ return Object.keys(size).length > 0 ? size : void 0;
5550
+ }
5551
+ /** Normalize only the fields required for the Junior-owned PR projection. */
5552
+ function normalizeGitHubPullRequestOutcome(args) {
5553
+ const lifecycle = pullRequestLifecycleActionSchema.safeParse(args.body);
5554
+ if (!lifecycle.success || !pullRequestLifecycleActionsSchema.safeParse(lifecycle.data.action).success) return;
5555
+ const parsed = pullRequestOutcomeSchema.parse(args.body);
5556
+ const pullRequest = parsed.pull_request;
5557
+ if (parsed.action === "synchronize" && (pullRequest.merged || pullRequest.closed_at)) return;
5558
+ const openedAt = timestamp(pullRequest.created_at);
5559
+ const updatedAt = timestamp(pullRequest.updated_at);
5560
+ if (!openedAt || !updatedAt) throw new Error("GitHub pull request lifecycle timestamps are invalid");
5561
+ 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");
5562
+ 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");
5563
+ const state = parsed.action !== "closed" ? "open" : pullRequest.merged ? "merged" : "closed_unmerged";
5564
+ const closed = parsed.action === "closed";
5565
+ const closedAt = timestamp(pullRequest.closed_at) ?? (closed ? updatedAt : void 0);
5566
+ const mergedAt = timestamp(pullRequest.merged_at) ?? (closed && pullRequest.merged ? updatedAt : void 0);
4825
5567
  return {
4826
- owner,
4827
- name
5568
+ candidateOwned,
5569
+ closedAt,
5570
+ draft: closed ? void 0 : pullRequest.draft,
5571
+ mergedAt,
5572
+ number: pullRequest.number,
5573
+ openedAt,
5574
+ pullRequestId: String(pullRequest.id),
5575
+ repositoryFullName: parsed.repository.full_name,
5576
+ repositoryId: String(parsed.repository.id),
5577
+ size: githubPullRequestSize(pullRequest),
5578
+ state,
5579
+ title: pullRequest.title,
5580
+ updatedAt
4828
5581
  };
4829
5582
  }
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]
4837
- });
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 });
5583
+ /** Normalize native conversation ids written to a Junior-owned PR by its bot. */
5584
+ function normalizeGitHubPullRequestConversations(args) {
5585
+ const parsed = pullRequestConversationSchema.safeParse(args.body);
5586
+ if (!parsed.success) return void 0;
5587
+ if (!isBotLogin(parsed.data.pull_request.user.login, args.botEmail) || !isBotLogin(parsed.data.sender.login, args.botEmail)) return;
5588
+ const conversationIds = githubConversationIds(parsed.data.pull_request.body);
5589
+ return conversationIds.length > 0 ? {
5590
+ conversationIds,
5591
+ pullRequestId: String(parsed.data.pull_request.id)
5592
+ } : void 0;
4839
5593
  }
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]
4847
- });
4848
- return await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${pullRequest.number}`, { token: token.token });
5594
+ /** Normalize linked issues written into a Junior-owned PR body by its bot. */
5595
+ function normalizeGitHubPullRequestLinkedIssues(args) {
5596
+ const parsed = pullRequestConversationSchema.safeParse(args.body);
5597
+ if (!parsed.success) return void 0;
5598
+ if (!isBotLogin(parsed.data.pull_request.user.login, args.botEmail) || !isBotLogin(parsed.data.sender.login, args.botEmail)) return;
5599
+ const linkedIssues = githubLinkedIssues(parsed.data.pull_request.body, parsed.data.repository.full_name);
5600
+ return linkedIssues.length > 0 ? {
5601
+ linkedIssues,
5602
+ pullRequestId: String(parsed.data.pull_request.id)
5603
+ } : void 0;
4849
5604
  }
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";
4855
- }
5605
+ // src/webhooks/pull-request-activity.ts
5606
+ const timestampSchema = z.iso.datetime({ offset: true });
5607
+ const numberSchema = z.number().int().positive();
5608
+ const repositorySchema$1 = z.object({ id: numberSchema });
5609
+ const senderSchema = z.object({ type: z.string() });
5610
+ const activitySchemas = {
5611
+ issue_comment: z.object({
5612
+ action: z.literal("created"),
5613
+ comment: z.object({ created_at: timestampSchema }),
5614
+ issue: z.object({
5615
+ number: numberSchema,
5616
+ pull_request: z.object({})
5617
+ }),
5618
+ repository: repositorySchema$1,
5619
+ sender: senderSchema
5620
+ }).transform((event) => ({
5621
+ at: new Date(event.comment.created_at),
5622
+ number: event.issue.number,
5623
+ repositoryProviderId: String(event.repository.id),
5624
+ senderType: event.sender.type
5625
+ })),
5626
+ pull_request: z.object({
5627
+ action: z.literal("synchronize"),
5628
+ pull_request: z.object({
5629
+ number: numberSchema,
5630
+ updated_at: timestampSchema
5631
+ }),
5632
+ repository: repositorySchema$1,
5633
+ sender: senderSchema
5634
+ }).transform((event) => ({
5635
+ at: new Date(event.pull_request.updated_at),
5636
+ number: event.pull_request.number,
5637
+ repositoryProviderId: String(event.repository.id),
5638
+ senderType: event.sender.type
5639
+ })),
5640
+ pull_request_review: z.object({
5641
+ action: z.literal("submitted"),
5642
+ pull_request: z.object({ number: numberSchema }),
5643
+ repository: repositorySchema$1,
5644
+ review: z.object({ submitted_at: timestampSchema }),
5645
+ sender: senderSchema
5646
+ }).transform((event) => ({
5647
+ at: new Date(event.review.submitted_at),
5648
+ number: event.pull_request.number,
5649
+ repositoryProviderId: String(event.repository.id),
5650
+ senderType: event.sender.type
5651
+ })),
5652
+ pull_request_review_comment: z.object({
5653
+ action: z.literal("created"),
5654
+ comment: z.object({ created_at: timestampSchema }),
5655
+ pull_request: z.object({ number: numberSchema }),
5656
+ repository: repositorySchema$1,
5657
+ sender: senderSchema
5658
+ }).transform((event) => ({
5659
+ at: new Date(event.comment.created_at),
5660
+ number: event.pull_request.number,
5661
+ repositoryProviderId: String(event.repository.id),
5662
+ senderType: event.sender.type
5663
+ }))
4856
5664
  };
4857
- const UNREACHABLE_REPOSITORY_MESSAGE = /does not exist or is not accessible/i;
4858
- /**
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.
4862
- */
4863
- async function loadPullRequestLifecycles(env, input) {
4864
- let token;
4865
- try {
4866
- token = await issueInstallationToken({
4867
- ...env,
4868
- permissions: { pull_requests: "read" },
4869
- repositoryIds: [input.repositoryId]
4870
- });
4871
- } catch (error) {
4872
- if (error instanceof GitHubRequestError && error.status === 422 && UNREACHABLE_REPOSITORY_MESSAGE.test(error.message)) throw new GitHubRepositoryUnreachableError(input.repositoryId);
4873
- throw error;
4874
- }
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
4887
- });
4888
- }
4889
- /**
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.
4892
- */
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]
4899
- });
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
- }
4907
- },
4908
- method: "POST",
4909
- token: token.token
4910
- });
4911
- }
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
4927
- }
4928
- },
4929
- method: "POST",
4930
- token: token.token
4931
- });
4932
- }
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
- });
4946
- }
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;
4975
- }
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
- });
5665
+ /** Read a person's pull request activity from a webhook, if it has any. */
5666
+ function normalizeGitHubPullRequestActivity(input) {
5667
+ const parsed = (Object.hasOwn(activitySchemas, input.eventName) ? activitySchemas[input.eventName] : void 0)?.safeParse(input.body);
5668
+ if (!parsed?.success) return void 0;
5669
+ const { senderType, ...activity } = parsed.data;
5670
+ return senderType === "Bot" ? void 0 : activity;
4986
5671
  }
4987
- const repositoryPermissionSchema = z.object({
4988
- permission: z.string().min(1),
4989
- role_name: z.string().optional()
5672
+ // src/webhooks/pull-request-preview.ts
5673
+ const previewWebhookSchema = z.object({
5674
+ action: z.enum([
5675
+ "opened",
5676
+ "edited",
5677
+ "synchronize",
5678
+ "ready_for_review"
5679
+ ]),
5680
+ pull_request: z.object({
5681
+ body: z.string().nullable().optional(),
5682
+ id: z.number().int().positive(),
5683
+ number: z.number().int().positive(),
5684
+ updated_at: z.iso.datetime({ offset: true })
5685
+ }),
5686
+ repository: z.object({ full_name: z.string().min(1) })
4990
5687
  });
4991
- const REPOSITORY_ROLE_TTL_MS = 6e5;
4992
5688
  /**
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.
5689
+ * Set or clear the preview image fact on each chip of a Junior pull request
5690
+ * from the webhook body. One failed conversation does not stop the others.
4996
5691
  */
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]
5692
+ async function refreshGitHubPullRequestPreview(args) {
5693
+ const parsed = previewWebhookSchema.safeParse(args.body);
5694
+ if (!parsed.success) return;
5695
+ const { pull_request: pullRequest, repository } = parsed.data;
5696
+ const conversationIds = await readGitHubPullRequestConversationIds(args.db, String(pullRequest.id));
5697
+ if (conversationIds.length === 0) return;
5698
+ const key = `${repository.full_name.toLowerCase()}#${pullRequest.number}`;
5699
+ const previewImageUrls = githubPreviewImageUrls(pullRequest.body);
5700
+ const updatedAt = Date.parse(pullRequest.updated_at);
5701
+ const limit = pLimit(8);
5702
+ const results = await Promise.allSettled(conversationIds.map((conversationId) => limit(async () => {
5703
+ const store = args.annotations.forConversation(conversationId);
5704
+ const current = (await store.list()).find((annotation) => annotation.key === key);
5705
+ if (current?.kind !== "object" || current.facts?.type !== "code_change") return;
5706
+ const storedAt = current.sourceUpdatedAt ? Date.parse(current.sourceUpdatedAt) : void 0;
5707
+ if (storedAt !== void 0 && storedAt > updatedAt) return;
5708
+ const { plugin: _plugin, createdAt: _createdAt, updatedAt: _updatedAt, facts: { previewImageUrls: previous, ...facts }, ...annotation } = current;
5709
+ const next = withGitHubPreviewImages(facts, previewImageUrls);
5710
+ if (previous?.join("\n") === next.previewImageUrls?.join("\n") && storedAt === updatedAt) return;
5711
+ await store.upsert({
5712
+ ...annotation,
5713
+ facts: next,
5714
+ sourceUpdatedAt: pullRequest.updated_at
5004
5715
  });
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
- });
5716
+ })));
5717
+ for (const result of results) {
5718
+ if (result.status === "fulfilled") continue;
5719
+ args.log?.error("GitHub pull request preview update failed", {
5720
+ errorType: result.reason instanceof Error ? result.reason.name : "UnknownError",
5721
+ number: pullRequest.number,
5722
+ repository: repository.full_name
5723
+ });
5724
+ }
5011
5725
  }
5012
- const pullRequestSchema = z.object({
5013
- auto_merge: z.object({}).nullable().optional(),
5726
+ // src/webhooks/merge-conflict.ts
5727
+ const PULL_REQUEST_CHECK_CONCURRENCY = 5;
5728
+ const EVENT_TYPE = "pull_request.merge_conflict";
5729
+ /** Events after which the pull request cannot get a conflict. */
5730
+ const CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set(["pull_request.closed_unmerged", "pull_request.merged"]);
5731
+ /** The pull request fields that tell if it has a conflict. */
5732
+ const gitHubPullRequestMergeSchema = z.object({
5733
+ base: z.object({ ref: z.string().min(1) }),
5014
5734
  draft: z.boolean().optional(),
5735
+ number: z.number().int().positive().optional(),
5015
5736
  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()
5022
- });
5023
- /**
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.
5031
- */
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]
5038
- });
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;
5069
- }
5070
- // src/webhooks/pull-request-action.ts
5071
- const PULL_REQUEST_SYNC_CONCURRENCY = 5;
5072
- /**
5073
- * A check normally takes a few seconds. After this time, a check that
5074
- * stopped without its release no longer blocks new checks.
5075
- */
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
- };
5092
- /**
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.
5096
- */
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) })
5737
+ html_url: z.string().min(1).optional(),
5738
+ mergeable: z.boolean().nullable().optional(),
5739
+ mergeable_state: z.string().optional(),
5740
+ state: z.string(),
5741
+ title: z.string().optional()
5109
5742
  });
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
- }];
5120
- }
5121
5743
  /**
5122
- * Derive the requester's next action. Return undefined when it cannot be
5123
- * known yet, so a later event decides.
5744
+ * Build the `pull_request.merge_conflict` copies for one pull request. With
5745
+ * no conflict, the copies have only the values that filters can match. The
5746
+ * event key names the head commit, so each head commit publishes once.
5124
5747
  */
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 {};
5138
- }
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
- };
5149
- }
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
- };
5165
- }
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
- });
5184
- }
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
5748
+ function gitHubMergeConflictEvents(input) {
5749
+ const { conflict } = input;
5750
+ const repo = gitHubRepoDataSchema.parse(input.repositoryFullName);
5751
+ const resource = gitHubPullRequestResource({
5752
+ number: input.number,
5753
+ repo
5198
5754
  });
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;
5230
- };
5231
- while (requests !== void 0) {
5232
- try {
5233
- saved = await check(saved);
5234
- } catch (error) {
5235
- failure ??= error;
5755
+ return pullRequestTargets({
5756
+ eventKey: `github:merge-conflict:${resource.identifier}${conflict ? `:${conflict.headSha}` : ""}`,
5757
+ eventType: EVENT_TYPE,
5758
+ identifier: resource.identifier,
5759
+ objectType: "code_change",
5760
+ occurredAtMs: Date.now(),
5761
+ trustedSummary: `${resource.label} has merge conflicts${conflict ? ` with ${conflict.baseBranch}` : ""}.`,
5762
+ data: {
5763
+ repo,
5764
+ pullRequest: input.number,
5765
+ ...conflict
5236
5766
  }
5237
- requests = await releaseGitHubPullRequestReadySync(args.db, target, {
5238
- id,
5239
- requests
5767
+ }, repo);
5768
+ }
5769
+ /** Open pull requests that the delivered events are about. */
5770
+ function pullRequestRefs(events) {
5771
+ const refs = /* @__PURE__ */ new Map();
5772
+ for (const event of events) {
5773
+ const { pullRequest, repo } = event.data ?? {};
5774
+ if (!event.eventType.startsWith("pull_request.") || CLOSED_EVENT_TYPES.has(event.eventType) || typeof pullRequest !== "number" || typeof repo !== "string") continue;
5775
+ refs.set(`${repo}#${pullRequest}`, {
5776
+ number: pullRequest,
5777
+ repositoryFullName: repo
5240
5778
  });
5241
5779
  }
5242
- if (failure !== void 0) throw failure;
5780
+ return [...refs.values()];
5243
5781
  }
5244
5782
  /**
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.
5783
+ * Return the pull request from a `pull_request` webhook payload when it is
5784
+ * `ref` and GitHub already knows its mergeability. Other webhooks, such as
5785
+ * reviews, comments, and check results, do not send mergeability.
5248
5786
  */
5249
- async function syncGitHubPullRequestActions(args) {
5250
- await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map(args.targets, async (target) => {
5787
+ function deliveredPullRequest(payload, ref) {
5788
+ const parsed = z.object({ pull_request: gitHubPullRequestMergeSchema }).safeParse(payload);
5789
+ const pullRequest = parsed.success ? parsed.data.pull_request : void 0;
5790
+ return pullRequest?.number === ref.number && typeof pullRequest.mergeable === "boolean" ? pullRequest : void 0;
5791
+ }
5792
+ /**
5793
+ * Return `pull_request.merge_conflict` events for the open pull requests that
5794
+ * these events are about, when a Watch or event automation wants them and
5795
+ * GitHub reports a conflict. A `pull_request` webhook payload gives the
5796
+ * mergeability when GitHub knows it. Otherwise the check reads the pull
5797
+ * request, which also makes GitHub calculate its mergeability. When GitHub
5798
+ * does not know it yet, a later event reads it again. The policy in
5799
+ * `merge-conflict-checks/policy.ts` decides if a conflict publishes.
5800
+ */
5801
+ async function loadGitHubMergeConflictEvents(args) {
5802
+ const { hasMatch, loadConflictHistory, loadPullRequest } = args;
5803
+ if (!hasMatch || !loadPullRequest || !loadConflictHistory) return [];
5804
+ const check = async (ref) => {
5805
+ if (!await hasMatch(gitHubMergeConflictEvents(ref))) return [];
5251
5806
  try {
5252
- await syncOne(args, target);
5807
+ const loaded = deliveredPullRequest(args.pullRequestPayload, ref) ?? gitHubPullRequestMergeSchema.parse(await loadPullRequest(ref));
5808
+ if (loaded.state !== "open" || loaded.mergeable !== false || loaded.mergeable_state !== "dirty") return [];
5809
+ const conflict = {
5810
+ baseBranch: loaded.base.ref,
5811
+ headSha: loaded.head.sha,
5812
+ ...loaded.html_url ? { url: loaded.html_url } : void 0
5813
+ };
5814
+ return await applyGitHubConflictPolicy({
5815
+ conflict,
5816
+ db: args.db,
5817
+ draft: loaded.draft === true,
5818
+ events: gitHubMergeConflictEvents({
5819
+ ...ref,
5820
+ conflict
5821
+ }),
5822
+ loadHistory: loadConflictHistory,
5823
+ loadTitleParts: args.loadTitleParts,
5824
+ log: args.log,
5825
+ now: /* @__PURE__ */ new Date(),
5826
+ ref,
5827
+ inboxItems: args.inboxItems,
5828
+ ...loaded.title ? { title: loaded.title } : void 0
5829
+ });
5253
5830
  } catch (error) {
5254
- logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
5831
+ logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
5255
5832
  deliveryId: args.deliveryId,
5256
- number: target.number,
5257
- repository: target.repositoryFullName
5833
+ pullRequest: ref.number,
5834
+ repository: ref.repositoryFullName
5258
5835
  });
5836
+ return [];
5259
5837
  }
5838
+ };
5839
+ return (await pLimit(PULL_REQUEST_CHECK_CONCURRENCY).map(pullRequestRefs(args.events), (ref) => check(ref))).flat();
5840
+ }
5841
+ // src/merge-conflict-checks/store.ts
5842
+ /** A key that waits longer than this was lost and expires. */
5843
+ const CHECK_TTL_MS = 18e5;
5844
+ /**
5845
+ * The heartbeat's own record of a running or repeated check. Only the
5846
+ * heartbeat writes it, so it needs no lock.
5847
+ */
5848
+ const repeatSchema = z.object({
5849
+ /** Checks since the last push that ended with an unknown answer. */
5850
+ attempts: z.number().int().positive(),
5851
+ dueAtMs: z.number()
5852
+ });
5853
+ function pushKey(repositoryFullName) {
5854
+ return `merge-conflict-check:push:${repositoryFullName}`;
5855
+ }
5856
+ function repeatKey(repositoryFullName) {
5857
+ return `merge-conflict-check:repeat:${repositoryFullName}`;
5858
+ }
5859
+ /** Return the repositories that have open Junior pull requests. */
5860
+ async function listGitHubRepositoriesWithOpenPullRequests(db, repositoryFullName) {
5861
+ const t = juniorGitHubPullRequests;
5862
+ 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);
5863
+ }
5864
+ /**
5865
+ * Add a check at `dueAtMs` for a repository with open Junior pull requests.
5866
+ * A check that already waits keeps its earlier time, so pushes that keep
5867
+ * coming do not delay it. Return whether a check waits.
5868
+ */
5869
+ async function scheduleGitHubConflictCheck(args) {
5870
+ if ((await listGitHubRepositoriesWithOpenPullRequests(args.db, args.repositoryFullName)).length === 0) return false;
5871
+ await args.state.setIfNotExists(pushKey(args.repositoryFullName), args.dueAtMs, CHECK_TTL_MS);
5872
+ return true;
5873
+ }
5874
+ /**
5875
+ * Claim the due check of a repository. The claim removes the push key
5876
+ * before the check reads GitHub, so the read includes every push that the
5877
+ * key held, and a later push adds a new key. A repeat at `claimedUntilMs`
5878
+ * runs the check again when it stops without an end.
5879
+ */
5880
+ async function claimGitHubConflictCheck(args) {
5881
+ const pushDueAtMs = await args.state.get(pushKey(args.repositoryFullName));
5882
+ const repeat = repeatSchema.safeParse(await args.state.get(repeatKey(args.repositoryFullName)));
5883
+ let attempts;
5884
+ if (typeof pushDueAtMs === "number" && pushDueAtMs <= args.nowMs) attempts = 1;
5885
+ else if (repeat.success && repeat.data.dueAtMs <= args.nowMs) attempts = repeat.data.attempts + 1;
5886
+ else return;
5887
+ await args.state.set(repeatKey(args.repositoryFullName), {
5888
+ attempts,
5889
+ dueAtMs: args.claimedUntilMs
5890
+ }, CHECK_TTL_MS);
5891
+ if (attempts === 1) await args.state.delete(pushKey(args.repositoryFullName));
5892
+ return {
5893
+ attempts,
5894
+ repositoryFullName: args.repositoryFullName
5895
+ };
5896
+ }
5897
+ /** End a claimed check, or repeat it at `retryAtMs`. */
5898
+ async function settleGitHubConflictCheck(state, check, retryAtMs) {
5899
+ if (retryAtMs === void 0) {
5900
+ await state.delete(repeatKey(check.repositoryFullName));
5901
+ return;
5902
+ }
5903
+ await state.set(repeatKey(check.repositoryFullName), {
5904
+ attempts: check.attempts,
5905
+ dueAtMs: retryAtMs
5906
+ }, CHECK_TTL_MS);
5907
+ }
5908
+ // src/merge-conflict-checks/webhooks.ts
5909
+ /**
5910
+ * Time from a push to its check. GitHub calculates mergeability after a
5911
+ * push, and pushes in this time share one check.
5912
+ */
5913
+ const CONFLICT_CHECK_DELAY_MS = 12e4;
5914
+ const pushSchema = z.object({
5915
+ deleted: z.boolean().optional(),
5916
+ ref: z.string(),
5917
+ repository: z.object({
5918
+ default_branch: z.string().min(1),
5919
+ full_name: z.string().min(1)
5920
+ })
5921
+ });
5922
+ /**
5923
+ * Schedule a check after a push to a repository's default branch. Stacked
5924
+ * pull requests do not need this, because Junior restacks them when it
5925
+ * pushes the branch below. Return whether a check waits.
5926
+ */
5927
+ async function scheduleGitHubPushConflictCheck(args) {
5928
+ const parsed = pushSchema.safeParse(args.body);
5929
+ if (!parsed.success || parsed.data.deleted || parsed.data.ref !== `refs/heads/${parsed.data.repository.default_branch}`) return false;
5930
+ return await scheduleGitHubConflictCheck({
5931
+ db: args.db,
5932
+ dueAtMs: args.now.getTime() + CONFLICT_CHECK_DELAY_MS,
5933
+ repositoryFullName: parsed.data.repository.full_name,
5934
+ state: args.state
5260
5935
  });
5261
5936
  }
5262
5937
  // src/webhooks/pull-request-ready-reviewers.ts
@@ -5718,7 +6393,8 @@ function createGitHubWebhookRoute(args) {
5718
6393
  codeChanges: args.codeChanges,
5719
6394
  db: args.db,
5720
6395
  log: args.log,
5721
- outcome: pullRequestOutcome
6396
+ outcome: pullRequestOutcome,
6397
+ inboxItems: args.inboxItems
5722
6398
  });
5723
6399
  if (recordedOutcome.applied && !recordedOutcome.commitComposition && pullRequestOutcome.state === "merged" && args.classifyPullRequestCommits) {
5724
6400
  let commitComposition;
@@ -5788,7 +6464,9 @@ function createGitHubWebhookRoute(args) {
5788
6464
  ...args.loadGitHubIncidents ? { loadGitHubIncidents: args.loadGitHubIncidents } : void 0,
5789
6465
  loadPullRequestFacts: needsCheckSuitePullRequestFacts(checkSuiteMatchKeys),
5790
6466
  log: args.log,
5791
- privateKeyEnv: args.privateKeyEnv
6467
+ privateKeyEnv: args.privateKeyEnv,
6468
+ responses: args.state,
6469
+ tokens: args.tokens
5792
6470
  }) : void 0;
5793
6471
  const hasMatch = args.events.hasMatch;
5794
6472
  const commitPages = args.loadPullRequestCommitPages ? shareCommitPages(args.loadPullRequestCommitPages) : void 0;
@@ -5840,37 +6518,38 @@ function createGitHubWebhookRoute(args) {
5840
6518
  events,
5841
6519
  hasMatch,
5842
6520
  loadConflictHistory: args.loadPullRequestConflictHistory,
6521
+ loadTitleParts: args.loadTitleParts,
5843
6522
  loadPullRequest: args.loadPullRequest,
5844
6523
  log: args.log,
5845
6524
  pullRequestPayload: eventName === "pull_request" ? body : void 0,
5846
- reviewItems: args.reviewItems
6525
+ inboxItems: args.inboxItems
5847
6526
  }));
5848
6527
  for (const event of events) await args.events.publish({
5849
6528
  ...event,
5850
6529
  objectType: event.eventType.startsWith("pull_request.") ? "code_change" : event.eventType.startsWith("issue.") ? "task" : event.eventType.startsWith("deployment.") ? "deployment" : "item"
5851
6530
  });
6531
+ const env = {
6532
+ appIdEnv: args.appIdEnv,
6533
+ installationIdEnv: args.installationIdEnv,
6534
+ privateKeyEnv: args.privateKeyEnv,
6535
+ responses: args.state,
6536
+ tokens: args.tokens
6537
+ };
5852
6538
  await syncGitHubPullRequestActions({
6539
+ botEmail,
5853
6540
  db: args.db,
5854
6541
  deliveryId,
5855
- env: {
5856
- appIdEnv: args.appIdEnv,
5857
- installationIdEnv: args.installationIdEnv,
5858
- privateKeyEnv: args.privateKeyEnv
5859
- },
6542
+ env,
5860
6543
  loadGitHubLogin: args.loadGitHubLogin,
5861
6544
  log: args.log,
5862
- reviewItems: args.reviewItems,
6545
+ inboxItems: args.inboxItems,
5863
6546
  targets: pullRequestActionTargets(eventName, body)
5864
6547
  });
5865
6548
  await requestGitHubReviewersWhenReady({
5866
6549
  body,
5867
6550
  db: args.db,
5868
6551
  deliveryId,
5869
- env: {
5870
- appIdEnv: args.appIdEnv,
5871
- installationIdEnv: args.installationIdEnv,
5872
- privateKeyEnv: args.privateKeyEnv
5873
- },
6552
+ env,
5874
6553
  eventName,
5875
6554
  loadGitHubLogin: args.loadGitHubLogin,
5876
6555
  log: args.log,
@@ -5931,10 +6610,11 @@ async function checkConflict(args, input) {
5931
6610
  draft: input.draft,
5932
6611
  events,
5933
6612
  loadHistory: args.loadHistory,
6613
+ loadTitleParts: args.loadTitleParts,
5934
6614
  log: args.log,
5935
6615
  now: args.now,
5936
6616
  ref: input.ref,
5937
- reviewItems: args.reviewItems,
6617
+ inboxItems: args.inboxItems,
5938
6618
  title: input.title
5939
6619
  })) await args.events.publish(event);
5940
6620
  }
@@ -5967,13 +6647,13 @@ async function checkRepository(args, repositoryFullName) {
5967
6647
  title: node.title
5968
6648
  });
5969
6649
  }
5970
- await closeGitHubConflictNotices({
6650
+ await closeGitHubConflictItems({
5971
6651
  db: args.db,
5972
6652
  log: args.log,
5973
6653
  numbers: mergeable,
5974
6654
  reason: GITHUB_CONFLICT_GONE_REASON,
5975
6655
  repositoryFullName,
5976
- reviewItems: args.reviewItems,
6656
+ inboxItems: args.inboxItems,
5977
6657
  status: "done"
5978
6658
  });
5979
6659
  if (!search.pageInfo.hasNextPage || !search.pageInfo.endCursor) break;
@@ -6016,6 +6696,64 @@ async function runGitHubConflictChecks(args) {
6016
6696
  await runCheck(args, check);
6017
6697
  }
6018
6698
  }
6699
+ // src/merge-conflict-checks/resume.ts
6700
+ /**
6701
+ * Resume merge conflict fixes of one open Junior pull request, and start a
6702
+ * fix when it is not a draft and GitHub does not say that it can merge.
6703
+ * Safe to repeat for one item: the event key names the item, so a retry publishes no second fix.
6704
+ */
6705
+ async function resumeGitHubConflictFixes(args) {
6706
+ const t = juniorGitHubPullRequests;
6707
+ const [row] = await args.db.select({
6708
+ fixes: t.conflictFixes,
6709
+ resumedAt: t.conflictFixesResumedAt
6710
+ }).from(t).where(and(pullRequestRow(args.ref), eq(t.state, "open")));
6711
+ if (!row) return;
6712
+ const resumedAt = new Date(args.nowMs);
6713
+ 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;
6714
+ const undo = () => args.db.update(t).set({
6715
+ conflictFixAskedAt: null,
6716
+ conflictFixesResumedAt: row.resumedAt
6717
+ }).where(and(pullRequestRow(args.ref), eq(t.conflictFixesResumedAt, resumedAt)));
6718
+ const loaded = gitHubPullRequestMergeSchema.parse(await args.loadPullRequest(args.ref));
6719
+ if (loaded.state !== "open" || loaded.mergeable === true || loaded.draft === true) {
6720
+ await undo();
6721
+ return;
6722
+ }
6723
+ const events = gitHubMergeConflictEvents({
6724
+ ...args.ref,
6725
+ conflict: {
6726
+ baseBranch: loaded.base.ref,
6727
+ headSha: loaded.head.sha,
6728
+ ...loaded.html_url ? { url: loaded.html_url } : void 0
6729
+ }
6730
+ }).map((event) => ({
6731
+ ...event,
6732
+ eventKey: `${event.eventKey}:resume:${args.itemId}`
6733
+ }));
6734
+ const resource = gitHubPullRequestSubscribable({
6735
+ canSubscribe: args.watches.canSubscribe,
6736
+ number: args.ref.number,
6737
+ repo: args.ref.repositoryFullName
6738
+ });
6739
+ if (args.subscription && resource && !await args.watches.watching({
6740
+ eventType: "pull_request.merge_conflict",
6741
+ identifier: resource.identifier
6742
+ })) await args.watches.subscribe({
6743
+ ...gitHubPullRequestCreateWatch(args.subscription, { draft: false }),
6744
+ resource
6745
+ });
6746
+ try {
6747
+ for (const event of events) await args.events.publish(event);
6748
+ } catch (error) {
6749
+ await undo();
6750
+ throw error;
6751
+ }
6752
+ await args.db.update(t).set({ conflictFixes: withGitHubConflictFix(row.fixes, {
6753
+ atMs: args.nowMs,
6754
+ headSha: loaded.head.sha
6755
+ }) }).where(pullRequestRow(args.ref));
6756
+ }
6019
6757
  // src/pull-request-outcomes/reconcile.ts
6020
6758
  /**
6021
6759
  * Time between the reconciles of one repository. A row with a newer
@@ -6056,11 +6794,11 @@ const lifecyclesResponseSchema = z.object({ data: z.object({ repository: z.objec
6056
6794
  databaseId: z.number().int().positive(),
6057
6795
  nameWithOwner: z.string().min(1)
6058
6796
  }).catchall(lifecycleSchema.nullable()) }) });
6059
- /** Write a GraphQL lifecycle as the body of a webhook with `action`. */
6060
- function webhookBody(action, repository, pullRequest) {
6797
+ /** Write a GraphQL lifecycle as the body of a `closed` webhook. */
6798
+ function closedWebhookBody(repository, pullRequest) {
6061
6799
  const login = pullRequest.author?.login ?? "ghost";
6062
6800
  return {
6063
- action,
6801
+ action: "closed",
6064
6802
  pull_request: {
6065
6803
  assignees: pullRequest.assignees.nodes.flatMap((assignee) => assignee ? [{ login: assignee.login }] : []),
6066
6804
  closed_at: pullRequest.closedAt,
@@ -6081,23 +6819,7 @@ function webhookBody(action, repository, pullRequest) {
6081
6819
  }
6082
6820
  };
6083
6821
  }
6084
- /** Write a changed draft state of an open pull request. */
6085
- async function reconcileDraft(args, repository, pullRequest) {
6086
- const outcome = normalizeGitHubPullRequestOutcome({
6087
- body: webhookBody(pullRequest.isDraft ? "converted_to_draft" : "ready_for_review", repository, pullRequest),
6088
- botEmail: args.botEmail
6089
- });
6090
- if (!outcome) return;
6091
- await applyGitHubPullRequestOutcome({
6092
- annotations: args.annotations,
6093
- codeChanges: args.codeChanges,
6094
- db: args.db,
6095
- log: args.log,
6096
- outcome
6097
- });
6098
- }
6099
- async function reconcileRepository(args, repositoryId, drafts) {
6100
- const numbers = [...drafts.keys()];
6822
+ async function reconcileRepository(args, repositoryId, numbers) {
6101
6823
  for (let start = 0; start < numbers.length; start += PULL_REQUESTS_PER_QUERY) {
6102
6824
  const { databaseId, nameWithOwner, ...pullRequests } = lifecyclesResponseSchema.parse(await args.loadLifecycles({
6103
6825
  numbers: numbers.slice(start, start + PULL_REQUESTS_PER_QUERY),
@@ -6108,20 +6830,13 @@ async function reconcileRepository(args, repositoryId, drafts) {
6108
6830
  await reconcilePullRequest(args, {
6109
6831
  databaseId,
6110
6832
  nameWithOwner
6111
- }, pullRequest, drafts);
6833
+ }, pullRequest);
6112
6834
  }
6113
6835
  }
6114
6836
  }
6115
6837
  /** Write the GitHub state of one stored pull request. */
6116
- async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullRequest, drafts) {
6838
+ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullRequest) {
6117
6839
  if (pullRequest.state === "OPEN") {
6118
- if (pullRequest.isDraft !== drafts.get(pullRequest.number)) {
6119
- await reconcileDraft(args, {
6120
- databaseId,
6121
- nameWithOwner
6122
- }, pullRequest);
6123
- return;
6124
- }
6125
6840
  await args.codeChanges.record(githubCodeChange({
6126
6841
  candidateOwned: false,
6127
6842
  draft: pullRequest.isDraft,
@@ -6136,7 +6851,7 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
6136
6851
  }, []));
6137
6852
  return;
6138
6853
  }
6139
- const body = webhookBody("closed", {
6854
+ const body = closedWebhookBody({
6140
6855
  databaseId,
6141
6856
  nameWithOwner
6142
6857
  }, pullRequest);
@@ -6160,13 +6875,13 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
6160
6875
  ...event,
6161
6876
  objectType: "code_change"
6162
6877
  });
6163
- await closeGitHubConflictNotice({
6878
+ await closeGitHubConflictItem({
6164
6879
  db: args.db,
6165
6880
  ref: {
6166
6881
  number: pullRequest.number,
6167
6882
  repositoryFullName: nameWithOwner
6168
6883
  },
6169
- reviewItems: args.reviewItems,
6884
+ inboxItems: args.inboxItems,
6170
6885
  ...pullRequest.merged ? {
6171
6886
  reason: "The pull request merged.",
6172
6887
  status: "done"
@@ -6180,7 +6895,8 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
6180
6895
  codeChanges: args.codeChanges,
6181
6896
  db: args.db,
6182
6897
  log: args.log,
6183
- outcome
6898
+ outcome,
6899
+ inboxItems: args.inboxItems
6184
6900
  });
6185
6901
  }
6186
6902
  /**
@@ -6191,19 +6907,19 @@ async function reconcileGitHubPullRequests(args) {
6191
6907
  const repositories = /* @__PURE__ */ new Map();
6192
6908
  for (const row of await listGitHubStaleOpenPullRequests(args.db, /* @__PURE__ */ new Date(args.nowMs - RECONCILE_MS))) {
6193
6909
  const repository = repositories.get(row.repositoryId) ?? {
6194
- drafts: /* @__PURE__ */ new Map(),
6195
- name: row.repositoryFullName
6910
+ name: row.repositoryFullName,
6911
+ numbers: []
6196
6912
  };
6197
- repository.drafts.set(row.number, row.draft);
6913
+ repository.numbers.push(row.number);
6198
6914
  repositories.set(row.repositoryId, repository);
6199
6915
  }
6200
6916
  let reconciled = 0;
6201
- for (const [repositoryId, { drafts, name: repositoryFullName }] of repositories) {
6917
+ for (const [repositoryId, { name: repositoryFullName, numbers }] of repositories) {
6202
6918
  if (reconciled >= REPOSITORY_LIMIT) break;
6203
6919
  if (!await args.state.setIfNotExists(`pull-request-reconcile:${repositoryId}`, args.nowMs, RECONCILE_MS)) continue;
6204
6920
  reconciled += 1;
6205
6921
  try {
6206
- await reconcileRepository(args, Number(repositoryId), drafts);
6922
+ await reconcileRepository(args, Number(repositoryId), numbers);
6207
6923
  } catch (error) {
6208
6924
  if (error instanceof GitHubRepositoryUnreachableError) args.log.warn("GitHub pull request reconcile skipped a repository", {
6209
6925
  repository: repositoryFullName,
@@ -6218,6 +6934,27 @@ async function reconcileGitHubPullRequests(args) {
6218
6934
  }
6219
6935
  // src/events/declarations.ts
6220
6936
  const NEEDS_REPO = { anyOf: ["repo"] };
6937
+ /** How each Event reads after the name of its pull request or issue. */
6938
+ const GITHUB_EVENT_PHRASES = {
6939
+ "issue.closed": "is closed",
6940
+ "issue.comment.created": "gets a new comment",
6941
+ "issue.opened": "is opened",
6942
+ "issue.reopened": "is reopened",
6943
+ "issue.updated": "is edited",
6944
+ "pull_request.checks.failed": "fails its checks",
6945
+ "pull_request.checks.passed": "passes its checks",
6946
+ "pull_request.checks.recovered": "passes its checks again",
6947
+ "pull_request.closed_unmerged": "is closed without merging",
6948
+ "pull_request.comment.created": "gets a new comment",
6949
+ "pull_request.merge_conflict": "gets a merge conflict",
6950
+ "pull_request.merged": "is merged",
6951
+ "pull_request.opened": "is opened",
6952
+ "pull_request.ready_for_review": "is ready for review",
6953
+ "pull_request.review.approved": "is approved",
6954
+ "pull_request.review.changes_requested": "gets changes requested",
6955
+ "pull_request.review.commented": "gets a review comment",
6956
+ "pull_request.review_comment.created": "gets an inline review comment"
6957
+ };
6221
6958
  /**
6222
6959
  * Declare the reach and guidance of every GitHub event.
6223
6960
  *
@@ -6236,9 +6973,16 @@ const NEEDS_REPO = { anyOf: ["repo"] };
6236
6973
  function gitHubEventDeclarations(pullRequestGuidance) {
6237
6974
  const declarations = {};
6238
6975
  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 };
6976
+ for (const eventType of GITHUB_RELEASE_EVENTS) declarations[eventType] = { reach: NEEDS_REPO };
6977
+ for (const eventType of GITHUB_ISSUE_EVENTS) declarations[eventType] = {
6978
+ phrase: GITHUB_EVENT_PHRASES[eventType],
6979
+ reach: NEEDS_REPO
6980
+ };
6240
6981
  for (const eventType of GITHUB_PULL_REQUEST_EVENTS) {
6241
- const declaration = { reach: NEEDS_REPO };
6982
+ const declaration = {
6983
+ phrase: GITHUB_EVENT_PHRASES[eventType],
6984
+ reach: NEEDS_REPO
6985
+ };
6242
6986
  const guidance = pullRequestGuidance[eventType];
6243
6987
  if (guidance) declaration.guidance = guidance;
6244
6988
  declarations[eventType] = declaration;
@@ -6254,6 +6998,36 @@ function gitHubResourceUrl(input) {
6254
6998
  if (input.resourceType === "pull_request") return `https://github.com/${repo}/pull/${number}`;
6255
6999
  if (input.resourceType === "issue") return `https://github.com/${repo}/issues/${number}`;
6256
7000
  }
7001
+ const RESOURCE_PAGES = /* @__PURE__ */ new Map([["issues", "issue"], ["pull", "pull_request"]]);
7002
+ /**
7003
+ * Name the watched resource of one github.com page: a repository, or a pull
7004
+ * request or issue and its subpages, such as `/pull/12/files`.
7005
+ */
7006
+ function gitHubUrlResource(url) {
7007
+ let parsed;
7008
+ try {
7009
+ parsed = new URL(url);
7010
+ } catch {
7011
+ return;
7012
+ }
7013
+ if (parsed.protocol !== "https:" || parsed.hostname !== "github.com") return;
7014
+ const [owner, repo, page, number] = parsed.pathname.split("/").filter(Boolean);
7015
+ if (!owner || !repo) return void 0;
7016
+ const repository = `${owner}/${repo}`.toLowerCase();
7017
+ if (!page) return {
7018
+ identifier: repository,
7019
+ resourceType: "repository"
7020
+ };
7021
+ const resourceType = RESOURCE_PAGES.get(page);
7022
+ if (!resourceType || !number || !/^\d+$/.test(number)) return void 0;
7023
+ return {
7024
+ identifier: `${repository}#${number}`,
7025
+ resourceType
7026
+ };
7027
+ }
7028
+ // src/db/database.ts
7029
+ /** Parse the shared database of a plugin context as the GitHub database. */
7030
+ const gitHubDbSchema = z.custom((value) => typeof value === "object" && value !== null && "select" in value && "update" in value, "Expected a Drizzle Postgres database");
6257
7031
  // src/pull-request-outcomes/commit-composition.ts
6258
7032
  const canonicalCommitSchema = z.object({
6259
7033
  authorEmail: z.string().nullable(),
@@ -6755,6 +7529,7 @@ const REPO$1 = "[A-Za-z0-9._-]+";
6755
7529
  const SHA$1 = "[0-9a-f]{7,40}";
6756
7530
  const START = "(?<![\\w.\\-/@&<\\\\])";
6757
7531
  const END = "(?![\\w-])";
7532
+ const PROSE_REPOSITORY_PATTERN = new RegExp(`(?<![\\w.\\-/@&<\\\\:])(?<owner>${LOGIN})\\/(?<repo>[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)(?<!\\.git)(?![\\w/-])`, "g");
6758
7533
  const TEXT_REFERENCE_PATTERN = new RegExp([
6759
7534
  `${START}(?<issueOwner>${LOGIN})\\/(?<issueRepo>${REPO$1})#(?<issue>\\d+)${END}`,
6760
7535
  `${START}(?<commitOwner>${LOGIN})\\/(?<commitRepo>${REPO$1})@(?<commit>${SHA$1})${END}`,
@@ -6799,26 +7574,53 @@ function readSpans(text) {
6799
7574
  return spans;
6800
7575
  }
6801
7576
  /**
6802
- * Return the distinct repositories that the text names in qualified
6803
- * references or GitHub issue, pull request, and commit URLs.
7577
+ * Return the repositories that the text names, in source order: qualified
7578
+ * references, GitHub issue, pull request, and commit URLs, and prose that
7579
+ * names a repository of the configured owner.
6804
7580
  */
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
7581
+ function namedRepositories(text, spans, configuredOwner) {
7582
+ const named = [];
7583
+ const add = (offset, owner, name) => {
7584
+ if (owner && name) named.push({
7585
+ offset,
7586
+ repository: {
7587
+ owner,
7588
+ name
7589
+ }
6811
7590
  });
6812
7591
  };
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 {
7592
+ for (const span of spans) {
7593
+ if (span.url) {
7594
+ for (const { groups } of span.url.matchAll(GITHUB_LINKED_URL_PATTERN)) add(span.start, groups?.["owner"], groups?.["repo"]);
7595
+ continue;
7596
+ }
6815
7597
  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"]);
7598
+ for (const { groups, index } of source.matchAll(TEXT_REFERENCE_PATTERN)) {
7599
+ const offset = span.start + index;
7600
+ add(offset, groups?.["issueOwner"], groups?.["issueRepo"]);
7601
+ add(offset, groups?.["commitOwner"], groups?.["commitRepo"]);
6819
7602
  }
7603
+ if (!configuredOwner) continue;
7604
+ for (const { groups, index } of source.matchAll(PROSE_REPOSITORY_PATTERN)) if (groups?.["owner"]?.toLowerCase() === configuredOwner.toLowerCase()) add(span.start + index, groups["owner"], groups["repo"]);
7605
+ }
7606
+ return named.sort((left, right) => left.offset - right.offset);
7607
+ }
7608
+ const repositoryKey = ({ owner, name }) => `${owner}/${name}`.toLowerCase();
7609
+ /**
7610
+ * Pick the repository of a bare reference at `offset`: the one repository
7611
+ * that the text names, else the last one named before the reference when
7612
+ * the text names several, else the configured one when it names none.
7613
+ */
7614
+ function repositoryAt(named, configured, offset) {
7615
+ if (named.length === 0) return configured;
7616
+ const first = named[0].repository;
7617
+ if (named.every(({ repository }) => repositoryKey(repository) === repositoryKey(first))) return first;
7618
+ let nearest;
7619
+ for (const entry of named) {
7620
+ if (entry.offset >= offset) break;
7621
+ nearest = entry.repository;
6820
7622
  }
6821
- return [...repositories.values()];
7623
+ return nearest;
6822
7624
  }
6823
7625
  const issueUrl = (owner, name, issue) => `https://github.com/${owner}/${name}/issues/${issue}`;
6824
7626
  const commitUrl = (owner, name, sha) => `https://github.com/${owner}/${name}/commit/${sha}`;
@@ -6827,10 +7629,10 @@ function linkifyUrl(url) {
6827
7629
  if (!groups?.["owner"] || !groups["repo"]) return url;
6828
7630
  return `[${groups["issue"] ? `${groups["owner"]}/${groups["repo"]}#${groups["issue"]}` : `${groups["owner"]}/${groups["repo"]}@${groups["commit"].slice(0, 7)}`}](${url})`;
6829
7631
  }
6830
- function linkifyTextReferences(text, context) {
6831
- const { repository } = context;
7632
+ function linkifyTextReferences(text, start, context) {
6832
7633
  return text.replace(TEXT_REFERENCE_PATTERN, (reference, ...args) => {
6833
7634
  const groups = args.at(-1);
7635
+ const index = args.at(-3);
6834
7636
  if (groups["issue"]) return `[${reference}](${issueUrl(groups["issueOwner"], groups["issueRepo"], groups["issue"])})`;
6835
7637
  if (groups["commit"]) return `[${`${groups["commitOwner"]}/${groups["commitRepo"]}@${groups["commit"].slice(0, 7)}`}](${commitUrl(groups["commitOwner"], groups["commitRepo"], groups["commit"])})`;
6836
7638
  if (groups["mention"]) {
@@ -6840,11 +7642,19 @@ function linkifyTextReferences(text, context) {
6840
7642
  if (known) return known;
6841
7643
  return context.linkProfiles ? `[${reference}](https://github.com/${login})` : reference;
6842
7644
  }
7645
+ const repository = typeof index === "number" ? context.repositoryAt(start + index) : void 0;
6843
7646
  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"])})`;
7647
+ const { owner, name } = repository;
7648
+ if (groups["bareIssue"]) {
7649
+ const issue = groups["bareIssue"];
7650
+ return `[${owner}/${name}#${issue}](${issueUrl(owner, name, issue)})`;
7651
+ }
7652
+ if (groups["userCommit"]) {
7653
+ const sha = groups["userCommit"];
7654
+ return `[${groups["user"]}/${name}@${sha.slice(0, 7)}](${commitUrl(groups["user"], name, sha)})`;
7655
+ }
6846
7656
  const sha = groups["bareCommit"];
6847
- return `[${sha.slice(0, 7)}](${commitUrl(repository.owner, repository.name, sha)})`;
7657
+ return `[${owner}/${name}@${sha.slice(0, 7)}](${commitUrl(owner, name, sha)})`;
6848
7658
  });
6849
7659
  }
6850
7660
  /**
@@ -6853,26 +7663,31 @@ function linkifyTextReferences(text, context) {
6853
7663
  * `owner/repo#123`, `owner/repo@sha`, and GitHub issue, pull request,
6854
7664
  * discussion, and commit URLs always become links. `#123`, `GH-123`,
6855
7665
  * `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
7666
+ * also as a plain `owner/repo` of the configured owner. When it names
7667
+ * several, the last one named before the reference wins. When it names
7668
+ * none, the `repo` config value is used. Their link labels name the
7669
+ * repository. `@login` becomes the
6857
7670
  * `mention` of the known person with that GitHub login. Other logins become
6858
7671
  * GitHub profile links when the text is GitHub text, or names a repository.
6859
7672
  * Chat `@name` words are often people who are not GitHub accounts. Set
6860
7673
  * `bareUrls` to keep bare URLs, where the place shows them as cards.
6861
7674
  */
6862
7675
  function linkifyGitHubReferences(text, options = {}) {
7676
+ const config = options.config ?? {};
7677
+ const configured = configuredRepository(config);
6863
7678
  const spans = readSpans(text);
6864
- const named = namedRepositories(text, spans);
7679
+ const named = namedRepositories(text, spans, configured?.owner ?? config["org"]?.trim());
6865
7680
  const context = {
6866
7681
  linkProfiles: options.githubText === true || named.length > 0,
6867
7682
  mention: options.mention ?? (() => void 0),
6868
- repository: named.length === 0 ? configuredRepository(options.config ?? {}) : named.length === 1 ? named[0] : void 0
7683
+ repositoryAt: (offset) => repositoryAt(named, configured, offset)
6869
7684
  };
6870
7685
  let result = "";
6871
7686
  let cursor = 0;
6872
7687
  for (const span of spans) {
6873
7688
  const source = text.slice(span.start, span.end);
6874
7689
  result += text.slice(cursor, span.start);
6875
- result += span.kind === "text" ? linkifyTextReferences(source, context) : span.kind === "url" && !options.bareUrls ? linkifyUrl(source) : source;
7690
+ result += span.kind === "text" ? linkifyTextReferences(source, span.start, context) : span.kind === "url" && !options.bareUrls ? linkifyUrl(source) : source;
6876
7691
  cursor = span.end;
6877
7692
  }
6878
7693
  return result + text.slice(cursor);
@@ -6980,10 +7795,19 @@ function parseGitHubReferences(text, config) {
6980
7795
  }
6981
7796
  return [...references.values()];
6982
7797
  }
7798
+ const commitResponseSchema = z.object({ commit: z.object({ message: z.string() }) });
7799
+ const titledResponseSchema = z.object({ title: z.string() });
6983
7800
  /** Read the display title of an issue, pull request, or commit response. */
6984
7801
  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;
7802
+ let raw;
7803
+ if (kind === "commit") {
7804
+ const parsed = commitResponseSchema.safeParse(object);
7805
+ raw = parsed.success ? parsed.data.commit.message.split("\n")[0] : void 0;
7806
+ } else {
7807
+ const parsed = titledResponseSchema.safeParse(object);
7808
+ raw = parsed.success ? parsed.data.title : void 0;
7809
+ }
7810
+ return raw?.replace(/\s+/g, " ").trim() || void 0;
6987
7811
  }
6988
7812
  /**
6989
7813
  * Describe GitHub issues, pull requests, and commits that message text
@@ -7277,7 +8101,7 @@ function assertGitHubPullRequestApprovalDenied(input) {
7277
8101
  } catch {
7278
8102
  throw new EgressPolicyDenied("GitHub pull request review requests must use JSON bodies so the no-approve policy can be enforced.");
7279
8103
  }
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.");
8104
+ 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
8105
  let event;
7282
8106
  if ("event" in body) {
7283
8107
  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 +8223,11 @@ function githubGraphqlAccess(method, upstreamUrl, graphql) {
7399
8223
  if (HTTP_READ_METHODS.has(method)) return "read";
7400
8224
  return githubGraphqlOperation(graphql)?.type === "query" ? "read" : "write";
7401
8225
  }
8226
+ const githubGraphqlErrorsSchema = z.object({ errors: z.array(z.unknown()) });
8227
+ const githubGraphqlErrorSchema = z.object({
8228
+ message: z.string(),
8229
+ type: z.unknown().optional()
8230
+ });
7402
8231
  function githubGraphqlPermissionDeniedMessage(bodyText) {
7403
8232
  let parsed;
7404
8233
  try {
@@ -7406,11 +8235,13 @@ function githubGraphqlPermissionDeniedMessage(bodyText) {
7406
8235
  } catch {
7407
8236
  return;
7408
8237
  }
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}`;
8238
+ const body = githubGraphqlErrorsSchema.safeParse(parsed);
8239
+ if (!body.success) return;
8240
+ for (const entry of body.data.errors) {
8241
+ const error = githubGraphqlErrorSchema.safeParse(entry);
8242
+ if (!error.success) continue;
8243
+ const message = error.data.message;
8244
+ 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
8245
  if (/\bResource not accessible by integration\b/.test(message)) return `GitHub GraphQL denied access: ${message}`;
7415
8246
  }
7416
8247
  }
@@ -7432,8 +8263,8 @@ const GITHUB_ACCEPTED_PERMISSIONS_PATTERN = /^[a-z_]+=[a-z]+(?:\s*[,;]\s*[a-z_]+
7432
8263
  function githubErrorMessage(bodyText) {
7433
8264
  if (!bodyText) return;
7434
8265
  try {
7435
- const parsed = JSON.parse(bodyText);
7436
- return isRecord(parsed) && typeof parsed["message"] === "string" ? parsed["message"].trim() : void 0;
8266
+ const parsed = githubMessageSchema.safeParse(JSON.parse(bodyText));
8267
+ return parsed.success ? parsed.data.message.trim() : void 0;
7437
8268
  } catch {
7438
8269
  return;
7439
8270
  }
@@ -7776,6 +8607,7 @@ function githubPlugin(options = {}) {
7776
8607
  events: gitHubEventDeclarations(gitHubPullRequestEventGuidance(options.pullRequestEvents?.guidance)),
7777
8608
  isEnabled: () => Boolean(readEnv("GITHUB_WEBHOOK_SECRET")),
7778
8609
  normalizeIdentifier: (identifier) => identifier.toLowerCase(),
8610
+ resourceForUrl: gitHubUrlResource,
7779
8611
  resourceUrl: gitHubResourceUrl
7780
8612
  },
7781
8613
  manifest: {
@@ -7875,8 +8707,27 @@ function githubPlugin(options = {}) {
7875
8707
  systemPrompt() {
7876
8708
  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
8709
  },
8710
+ async inboxItemAnswered(ctx) {
8711
+ const ref = parseGitHubConflictItemKey(ctx.dedupeKey);
8712
+ if (!ref || ctx.choice !== "Resume") return;
8713
+ const installationEnv = {
8714
+ appIdEnv,
8715
+ installationIdEnv,
8716
+ privateKeyEnv
8717
+ };
8718
+ await resumeGitHubConflictFixes({
8719
+ db: gitHubDbSchema.parse(ctx.db),
8720
+ events: ctx.events,
8721
+ itemId: ctx.itemId,
8722
+ loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
8723
+ nowMs: ctx.nowMs,
8724
+ ref,
8725
+ subscription: gitHubPullRequestSubscription(options.pullRequestEvents?.subscribeAfterCreate),
8726
+ watches: ctx.watches
8727
+ });
8728
+ },
7878
8729
  async heartbeat(ctx) {
7879
- const db = ctx.db;
8730
+ const db = gitHubDbSchema.parse(ctx.db);
7880
8731
  const installationEnv = {
7881
8732
  appIdEnv,
7882
8733
  installationIdEnv,
@@ -7886,9 +8737,13 @@ function githubPlugin(options = {}) {
7886
8737
  db,
7887
8738
  events: ctx.events,
7888
8739
  loadHistory: async (ref) => await loadPullRequestConflictHistory(installationEnv, ref),
8740
+ loadTitleParts: async (input) => await loadGitHubTitleParts({
8741
+ ...installationEnv,
8742
+ responses: ctx.state
8743
+ }, input, ctx.log),
7889
8744
  log: ctx.log,
7890
8745
  now: new Date(ctx.nowMs),
7891
- reviewItems: ctx.reviewItems,
8746
+ inboxItems: ctx.inboxItems,
7892
8747
  search: async (input) => {
7893
8748
  const login = botLoginFromEmail(requireEnv(botEmailEnv));
7894
8749
  if (!login) throw new Error(`${botEmailEnv} is not a GitHub bot address`);
@@ -7909,12 +8764,12 @@ function githubPlugin(options = {}) {
7909
8764
  loadLifecycles: async (input) => await loadPullRequestLifecycles(installationEnv, input),
7910
8765
  log: ctx.log,
7911
8766
  nowMs: ctx.nowMs,
7912
- reviewItems: ctx.reviewItems,
8767
+ inboxItems: ctx.inboxItems,
7913
8768
  state: ctx.state
7914
8769
  });
7915
8770
  },
7916
8771
  async unfinishedWork(ctx) {
7917
- const db = ctx.db;
8772
+ const db = gitHubDbSchema.parse(ctx.db);
7918
8773
  const [conversationIds, assignedConversationIds, finishedWorkAtByConversationId] = await Promise.all([
7919
8774
  listGitHubUnfinishedWork(db, ctx.conversationIds),
7920
8775
  listGitHubAssignedWork(db, ctx.conversationIds),
@@ -7930,7 +8785,9 @@ function githubPlugin(options = {}) {
7930
8785
  const installationEnv = {
7931
8786
  appIdEnv,
7932
8787
  installationIdEnv,
7933
- privateKeyEnv
8788
+ privateKeyEnv,
8789
+ responses: ctx.state,
8790
+ tokens: /* @__PURE__ */ new Map()
7934
8791
  };
7935
8792
  return [createGitHubWebhookRoute({
7936
8793
  annotations: ctx.annotations,
@@ -7942,7 +8799,7 @@ function githubPlugin(options = {}) {
7942
8799
  loadPage: await loadPullRequestCommitPages(installationEnv, pullRequest)
7943
8800
  }),
7944
8801
  codeChanges: ctx.codeChanges,
7945
- db: ctx.db,
8802
+ db: gitHubDbSchema.parse(ctx.db),
7946
8803
  installationId: () => readEnv(installationIdEnv),
7947
8804
  loadGitHubIncidents: async () => await loadGitHubStatusIncidents(ctx.cache, CHECK_SUITE_INCIDENT_WINDOW_MS),
7948
8805
  installationIdEnv,
@@ -7951,12 +8808,14 @@ function githubPlugin(options = {}) {
7951
8808
  loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
7952
8809
  loadPullRequestConflictHistory: async (pullRequest) => await loadPullRequestConflictHistory(installationEnv, pullRequest),
7953
8810
  loadPullRequestCommitPages: async (pullRequest) => await loadPullRequestCommitPages(installationEnv, pullRequest),
8811
+ loadTitleParts: async (input) => await loadGitHubTitleParts(installationEnv, input, ctx.log),
7954
8812
  log: ctx.log,
7955
8813
  markFeedbackReviewing: async (target) => await markPullRequestFeedbackReviewing(installationEnv, target),
7956
8814
  privateKeyEnv,
7957
8815
  events: ctx.events,
7958
- reviewItems: ctx.reviewItems,
8816
+ inboxItems: ctx.inboxItems,
7959
8817
  state: ctx.state,
8818
+ tokens: installationEnv.tokens,
7960
8819
  webhookSecret: () => readEnv("GITHUB_WEBHOOK_SECRET")
7961
8820
  })];
7962
8821
  },