@sentry/junior-github 0.315.0 → 0.317.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,18 +1,18 @@
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-D3Qnj4yY.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-BoMOs5Rd.js";
2
2
  import * as z from "zod";
3
3
  import pLimit from "p-limit";
4
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";
5
+ import { RE2JS } from "re2js";
6
+ import { parse } from "yaml";
5
7
  import { lexer, walkTokens } from "marked";
6
8
  import { parseFragment } from "parse5";
7
- import { Kind, parse, print, visit } from "@0no-co/graphql.web";
8
- import { and, asc, eq, gt, inArray, lt, lte, or, sql } from "drizzle-orm";
9
- import { integer, jsonb, pgTable, primaryKey, text, timestamp as timestamp$1 } from "drizzle-orm/pg-core";
9
+ import { Kind, parse as parse$1, print, visit } from "@0no-co/graphql.web";
10
+ import { and, asc, eq, gt, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
11
+ import { integer, jsonb, pgTable, primaryKey, text, timestamp as timestamp$1, uniqueIndex } from "drizzle-orm/pg-core";
10
12
  import { Type } from "@sinclair/typebox";
11
13
  import { Value } from "@sinclair/typebox/value";
12
14
  import ignore from "ignore";
13
15
  import { createHmac, timingSafeEqual } from "node:crypto";
14
- import { RE2JS } from "re2js";
15
- import { parse as parse$1 } from "yaml";
16
16
  import { fromMarkdown } from "mdast-util-from-markdown";
17
17
  import { gfmFromMarkdown } from "mdast-util-gfm";
18
18
  import { gfm } from "micromark-extension-gfm";
@@ -85,6 +85,48 @@ const githubAccountLinks = {
85
85
  }) ?? githubAccountCard(login);
86
86
  }
87
87
  };
88
+ // src/inbox-subjects.ts
89
+ /** The subject kinds of GitHub Inbox items. */
90
+ const GITHUB_INBOX_SUBJECTS = {
91
+ mergeConflict: "merge_conflict",
92
+ pullRequest: "pull_request"
93
+ };
94
+ /**
95
+ * Name the ask on a Junior pull request from its live card. Once it is
96
+ * approved, GitHub reports that it can merge, and it is no draft, the ask
97
+ * is the merge for every viewer, also a reviewer whose review GitHub still
98
+ * requests. Before that, it is the review. A conflict has its own item.
99
+ */
100
+ function pullRequestAsk(object) {
101
+ const facts = object.facts;
102
+ if (facts?.type !== "code_change") return void 0;
103
+ return facts.review === "approved" && facts.mergeable === true && object.status !== "draft" ? "Ready to merge" : "Review requested";
104
+ }
105
+ const pullRequestOwner = {
106
+ conversationId: "conversation_id",
107
+ subjectId: "pull_request_id",
108
+ table: "junior_github_pull_request_requesters"
109
+ };
110
+ /** The registered kinds and labels, for the plugin registration. */
111
+ const githubInboxSubjectKinds = [{
112
+ ask: pullRequestAsk,
113
+ codeChange: true,
114
+ kind: GITHUB_INBOX_SUBJECTS.pullRequest,
115
+ label: "Pull request",
116
+ owner: pullRequestOwner
117
+ }, {
118
+ codeChange: true,
119
+ kind: GITHUB_INBOX_SUBJECTS.mergeConflict,
120
+ label: "Merge conflict",
121
+ owner: pullRequestOwner
122
+ }];
123
+ /** The subject of an Inbox item about one pull request. */
124
+ function pullRequestSubject(kind, pullRequestId) {
125
+ return {
126
+ id: pullRequestId,
127
+ kind
128
+ };
129
+ }
88
130
  // src/annotations.ts
89
131
  function githubObjectType(annotation) {
90
132
  if (annotation.objectType === "task" || annotation.objectType === "code_change") return annotation.objectType;
@@ -207,6 +249,157 @@ async function githubAnnotationChange(args) {
207
249
  upsert: githubStatusAnnotation(await args.annotations.forConversation(args.conversationId).list(), args.update)
208
250
  };
209
251
  }
252
+ // src/code-change-titles/parse.ts
253
+ function nativePattern(source) {
254
+ const regex = new RegExp(source, "i");
255
+ return (title) => {
256
+ const match = regex.exec(title);
257
+ return match ? {
258
+ scope: match.groups?.["scope"],
259
+ type: match.groups?.["type"]
260
+ } : void 0;
261
+ };
262
+ }
263
+ function defaultCategory(title, sources) {
264
+ return {
265
+ custom: false,
266
+ patterns: sources.map(nativePattern),
267
+ title
268
+ };
269
+ }
270
+ /** Craft's `DEFAULT_RELEASE_CONFIG` categories, in match order. */
271
+ const DEFAULT_CODE_CHANGE_CATEGORIES = [
272
+ defaultCategory("Breaking Changes", [String.raw`^(?<type>\w+(?:\((?<scope>[^)]+)\))?!:\s*)`]),
273
+ defaultCategory("Security", [String.raw`^(?<type>security(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
274
+ defaultCategory("New Features", [String.raw`^(?<type>feat(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
275
+ defaultCategory("Bug Fixes", [String.raw`^(?<type>fix(?:\((?<scope>[^)]+)\))?!?:\s*)`, String.raw`^Revert "`]),
276
+ defaultCategory("Documentation", [String.raw`^(?<type>docs?(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
277
+ defaultCategory("Internal Changes", [String.raw`^(?<type>(?:build|refactor|meta|chore|ci|ref|perf|tests?|style)(?:\((?<scope>[^)]+)\))?!?:\s*)`])
278
+ ];
279
+ const TYPE_WORDS = {
280
+ build: "Build",
281
+ chore: "Chore",
282
+ ci: "CI",
283
+ doc: "Docs",
284
+ docs: "Docs",
285
+ feat: "Feature",
286
+ fix: "Fix",
287
+ meta: "Meta",
288
+ perf: "Perf",
289
+ ref: "Refactor",
290
+ refactor: "Refactor",
291
+ revert: "Revert",
292
+ security: "Security",
293
+ style: "Style",
294
+ test: "Test",
295
+ tests: "Test"
296
+ };
297
+ const BREAKING = /^\w+(?:\([^)]+\))?!:/;
298
+ const REVERT = /^Revert "/i;
299
+ const PULL_REQUEST_SUFFIX = /\s*\(#\d+\)$/;
300
+ /** GitHub titles are at most 256 characters, so this bounds regex work. */
301
+ const MAX_TITLE_LENGTH = 256;
302
+ function capitalize(text) {
303
+ return text.charAt(0).toUpperCase() + text.slice(1);
304
+ }
305
+ /** A custom category title as one word pill, without emoji or padding. */
306
+ function categoryWord(title) {
307
+ const word = title.replace(/[\p{Extended_Pictographic}\u{FE0F}\u{200D}]/gu, "").trim();
308
+ return word && !/^breaking\b/i.test(word) ? word : void 0;
309
+ }
310
+ function typeWord(category, token, title) {
311
+ const known = token ? TYPE_WORDS[token.toLowerCase()] : void 0;
312
+ if (known) return known;
313
+ if (!token && REVERT.test(title)) return "Revert";
314
+ return category.custom ? categoryWord(category.title) : void 0;
315
+ }
316
+ function firstMatch(title, categories) {
317
+ for (const category of categories) for (const pattern of category.patterns) {
318
+ const match = pattern(title);
319
+ if (match) return {
320
+ category,
321
+ match
322
+ };
323
+ }
324
+ }
325
+ /**
326
+ * Return the title parts of a pull request title, or undefined when the
327
+ * title has no conventional prefix and no breaking marker. The first
328
+ * matching category wins, as in Craft.
329
+ */
330
+ function parseCodeChangeTitle(title, categories = DEFAULT_CODE_CHANGE_CATEGORIES) {
331
+ const bounded = title.slice(0, MAX_TITLE_LENGTH);
332
+ const breaking = BREAKING.test(bounded);
333
+ const found = firstMatch(bounded, categories) ?? (breaking ? firstMatch(bounded, DEFAULT_CODE_CHANGE_CATEGORIES.slice(0, 1)) : void 0);
334
+ if (!found) return void 0;
335
+ const prefix = found.match.type;
336
+ const token = prefix ? /^\w+/.exec(prefix)?.[0] : void 0;
337
+ const rest = (prefix !== void 0 && bounded.startsWith(prefix) ? title.slice(prefix.length) : title).replace(PULL_REQUEST_SUFFIX, "").trim();
338
+ const type = typeWord(found.category, token, bounded);
339
+ const scope = found.match.scope?.trim();
340
+ return {
341
+ text: rest ? capitalize(rest) : title,
342
+ ...type ? { type } : void 0,
343
+ ...scope ? { scope } : void 0,
344
+ ...breaking ? { breaking: true } : void 0
345
+ };
346
+ }
347
+ // src/code-change-titles/release-config.ts
348
+ /**
349
+ * A repository's changelog categories from `.github/release.yml`, the file
350
+ * that GitHub release notes and Craft read. Craft adds `commit_patterns` to
351
+ * each category. When the file has categories with patterns, they replace
352
+ * the default categories, as in Craft.
353
+ */
354
+ const MAX_CONFIG_LENGTH = 65536;
355
+ const MAX_CATEGORIES = 30;
356
+ const MAX_PATTERNS = 10;
357
+ const MAX_PATTERN_LENGTH = 200;
358
+ const releaseConfigSchema = z.object({ changelog: z.object({ categories: z.array(z.object({
359
+ commit_patterns: z.array(z.string()).optional(),
360
+ title: z.string().min(1)
361
+ })).optional() }).optional() });
362
+ function compilePattern(source) {
363
+ if (source.length > MAX_PATTERN_LENGTH) return void 0;
364
+ let regex;
365
+ try {
366
+ regex = RE2JS.compile(source, RE2JS.CASE_INSENSITIVE);
367
+ } catch {
368
+ return;
369
+ }
370
+ if (regex.matcher("").find()) return void 0;
371
+ const groups = regex.namedGroups();
372
+ return (title) => {
373
+ const match = regex.matcher(title);
374
+ if (!match.find()) return void 0;
375
+ return {
376
+ scope: "scope" in groups ? match.group("scope") ?? void 0 : void 0,
377
+ type: "type" in groups ? match.group("type") ?? void 0 : void 0
378
+ };
379
+ };
380
+ }
381
+ /**
382
+ * Return the changelog categories of a `.github/release.yml` text. A file
383
+ * with no usable `commit_patterns`, or one that does not parse, gives the
384
+ * default categories.
385
+ */
386
+ function parseReleaseCategories(text) {
387
+ if (text.length > MAX_CONFIG_LENGTH) return DEFAULT_CODE_CHANGE_CATEGORIES;
388
+ let raw;
389
+ try {
390
+ raw = parse(text, { maxAliasCount: 100 });
391
+ } catch {
392
+ return DEFAULT_CODE_CHANGE_CATEGORIES;
393
+ }
394
+ const config = releaseConfigSchema.safeParse(raw);
395
+ if (!config.success) return DEFAULT_CODE_CHANGE_CATEGORIES;
396
+ const categories = (config.data.changelog?.categories ?? []).slice(0, MAX_CATEGORIES).map((category) => ({
397
+ custom: true,
398
+ patterns: (category.commit_patterns ?? []).slice(0, MAX_PATTERNS).map(compilePattern).filter((pattern) => pattern !== void 0),
399
+ title: category.title
400
+ })).filter((category) => category.patterns.length > 0);
401
+ return categories.length > 0 ? categories : DEFAULT_CODE_CHANGE_CATEGORIES;
402
+ }
210
403
  // src/object-cache.ts
211
404
  const ISSUE_CACHE_TTL_MS = 6e4;
212
405
  /**
@@ -281,8 +474,50 @@ const githubPullRequestFieldsSchema = z.object({
281
474
  }).optional(),
282
475
  mergeable: z.union([z.boolean(), z.literal("pending")]).nullable().optional(),
283
476
  merged: z.boolean().optional(),
284
- requested_reviewers: z.array(person$1).optional()
477
+ requested_reviewers: z.array(person$1).optional(),
478
+ review: z.enum([
479
+ "approved",
480
+ "changes_requested",
481
+ "required"
482
+ ]).nullable().optional()
285
483
  });
484
+ /** The pull request fields without GitHub's review decision. */
485
+ function withoutGitHubReview(fields) {
486
+ const { review: _, ...rest } = fields;
487
+ return rest;
488
+ }
489
+ const REVIEW_CLEARED_TTL_MS = 6e4;
490
+ function reviewClearedKey(key) {
491
+ return `review-cleared:${key}`;
492
+ }
493
+ /**
494
+ * Record that a review webhook cleared the review decision of a pull
495
+ * request entry. Call it before the entry write, so a card read that
496
+ * GitHub answered before the change does not store the old decision
497
+ * (`clearGitHubReviewAfterRead`).
498
+ */
499
+ async function markGitHubReviewCleared(cache, key) {
500
+ await cache.update(reviewClearedKey(key), () => ({
501
+ ttlMs: REVIEW_CLEARED_TTL_MS,
502
+ value: Date.now()
503
+ }));
504
+ }
505
+ /**
506
+ * Clear the review decision `review` that a card read started at
507
+ * `startedAtMs` stored, when a review webhook came since. The read writes
508
+ * first and checks after, so a webhook either comes before the check, which
509
+ * clears the decision here, or clears it itself after the write. A
510
+ * different decision is from a later read, so it stays.
511
+ */
512
+ async function clearGitHubReviewAfterRead(cache, key, read) {
513
+ if (read.review === void 0) return;
514
+ const clearedAt = await cache.get(reviewClearedKey(key));
515
+ if (clearedAt === void 0 || clearedAt < read.startedAtMs) return;
516
+ await cache.update(key, (current) => !current || current.review !== read.review ? void 0 : {
517
+ ...GITHUB_PULL_REQUEST_CACHE,
518
+ value: withoutGitHubReview(current)
519
+ });
520
+ }
286
521
  /**
287
522
  * The cache entry of pull request fields read from GitHub. An open pull
288
523
  * request whose merge state GitHub still computes shows pending, briefly.
@@ -398,6 +633,11 @@ const responseSchema$1 = z.object({
398
633
  failed: z.number(),
399
634
  pending: z.number()
400
635
  }), z.literal("pending")]).optional(),
636
+ review: z.enum([
637
+ "approved",
638
+ "changes_requested",
639
+ "required"
640
+ ]).nullable().optional(),
401
641
  state: z.string().optional(),
402
642
  changed_files: z.number().int().nonnegative().optional(),
403
643
  additions: z.number().int().nonnegative().optional(),
@@ -496,6 +736,7 @@ function githubObjectFacts(type, response) {
496
736
  type,
497
737
  author: short(data.user?.login),
498
738
  reviewers: data.requested_reviewers?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
739
+ review: data.review ?? void 0,
499
740
  sourceBranch: short(data.head?.ref),
500
741
  targetBranch: short(data.base?.ref),
501
742
  mergeable: data.state === "open" ? data.mergeable ?? void 0 : void 0,
@@ -527,7 +768,7 @@ function operation(document) {
527
768
  };
528
769
  }
529
770
  function githubGraphql(source) {
530
- return operation(parse(source));
771
+ return operation(parse$1(source));
531
772
  }
532
773
  /** Add one reaction to a review body. */
533
774
  const ADD_REVIEW_REACTION = githubGraphql(`
@@ -668,6 +909,24 @@ const PULL_REQUEST_DRAFT_READINESS = githubGraphql(`
668
909
  }
669
910
  }
670
911
  `);
912
+ /**
913
+ * Read whether GitHub asks one person to review a pull request, and their
914
+ * latest 20 submitted reviews. A pending review is not submitted.
915
+ */
916
+ const PULL_REQUEST_REVIEWER = githubGraphql(`
917
+ query PullRequestReviewer($owner: String!, $name: String!, $number: Int!, $login: String!) {
918
+ repository(owner: $owner, name: $name) {
919
+ pullRequest(number: $number) {
920
+ reviewRequests(first: 100) {
921
+ nodes { requestedReviewer { __typename ... on User { login } } }
922
+ }
923
+ reviews(last: 20, author: $login, states: [APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED]) {
924
+ nodes { state }
925
+ }
926
+ }
927
+ }
928
+ }
929
+ `);
671
930
  /** Read one page of a pull request search, with mergeability. */
672
931
  const OPEN_PULL_REQUEST_MERGEABILITY = githubGraphql(`
673
932
  query OpenPullRequestMergeability($query: String!, $after: String) {
@@ -720,6 +979,7 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
720
979
  repository(owner: $owner, name: $name) {
721
980
  pullRequest(number: $number) {
722
981
  autoMergeRequest { enabledAt }
982
+ commits(last: 1) { nodes { commit { committedDate } } }
723
983
  isDraft
724
984
  mergeStateStatus
725
985
  state
@@ -732,7 +992,7 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
732
992
  pageInfo { hasPreviousPage startCursor }
733
993
  nodes { ...NextActionReview }
734
994
  }
735
- timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT]) {
995
+ timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT, REVIEW_REQUEST_REMOVED_EVENT]) {
736
996
  nodes {
737
997
  __typename
738
998
  ... on IssueComment { createdAt author { __typename login } }
@@ -740,6 +1000,11 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
740
1000
  createdAt
741
1001
  requestedReviewer { __typename ... on User { login } }
742
1002
  }
1003
+ ... on ReviewRequestRemovedEvent {
1004
+ createdAt
1005
+ actor { __typename login }
1006
+ requestedReviewer { __typename ... on User { login } }
1007
+ }
743
1008
  }
744
1009
  }
745
1010
  }
@@ -753,10 +1018,44 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
753
1018
  }
754
1019
  `);
755
1020
  /**
1021
+ * Read whether the required checks of a pull request's head commit pass:
1022
+ * the checks of the head commit and the branch protection's required checks
1023
+ * of the base branch. `PULL_REQUEST_REVIEW_AGAIN` reads the same fields.
1024
+ */
1025
+ const PULL_REQUEST_REQUIRED_CHECKS = githubGraphql(`
1026
+ query PullRequestRequiredChecks($owner: String!, $name: String!, $number: Int!) {
1027
+ repository(owner: $owner, name: $name) {
1028
+ pullRequest(number: $number) {
1029
+ baseRefName
1030
+ baseRef { refUpdateRule { requiredStatusCheckContexts } }
1031
+ commits(last: 1) {
1032
+ nodes {
1033
+ commit {
1034
+ statusCheckRollup {
1035
+ contexts(first: 100) {
1036
+ pageInfo { hasNextPage }
1037
+ nodes {
1038
+ __typename
1039
+ ... on CheckRun { name status conclusion }
1040
+ ... on StatusContext { context state }
1041
+ }
1042
+ }
1043
+ }
1044
+ }
1045
+ }
1046
+ }
1047
+ }
1048
+ }
1049
+ }
1050
+ `);
1051
+ /**
756
1052
  * Read what decides whether a reviewer's change request is ready for their
757
- * review again: whether GitHub asks them, their latest review with the
758
- * reactors of its body and each of its comments, the checks of the head
759
- * commit, and the branch protection's required checks of the base branch.
1053
+ * review again: whether GitHub asks them, when GitHub last asked people for
1054
+ * a review, their latest approval or change request and their latest 20
1055
+ * comment-only reviews with the reactors of each body and comment, the
1056
+ * checks of the head commit, and the branch protection's required checks
1057
+ * of the base branch. The decision is read on its own, so a long
1058
+ * discussion does not push it out of view.
760
1059
  */
761
1060
  const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
762
1061
  query PullRequestReviewAgain($owner: String!, $name: String!, $number: Int!, $reviewer: String!) {
@@ -767,18 +1066,20 @@ const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
767
1066
  reviewRequests(first: 100) {
768
1067
  nodes { requestedReviewer { __typename ... on User { login } } }
769
1068
  }
770
- reviews(last: 1, author: $reviewer, states: [APPROVED, CHANGES_REQUESTED, DISMISSED]) {
1069
+ timelineItems(last: 100, itemTypes: [REVIEW_REQUESTED_EVENT]) {
771
1070
  nodes {
772
- databaseId
773
- state
774
- body
775
- ...FeedbackReactors
776
- comments(first: 100) {
777
- totalCount
778
- nodes { databaseId ...FeedbackReactors }
1071
+ ... on ReviewRequestedEvent {
1072
+ createdAt
1073
+ requestedReviewer { __typename ... on User { login } }
779
1074
  }
780
1075
  }
781
1076
  }
1077
+ decision: reviews(last: 1, author: $reviewer, states: [APPROVED, CHANGES_REQUESTED, DISMISSED]) {
1078
+ nodes { ...FeedbackReview }
1079
+ }
1080
+ reviews(last: 20, author: $reviewer, states: [COMMENTED]) {
1081
+ nodes { ...FeedbackReview }
1082
+ }
782
1083
  commits(last: 1) {
783
1084
  nodes {
784
1085
  commit {
@@ -799,6 +1100,18 @@ const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
799
1100
  }
800
1101
  }
801
1102
 
1103
+ fragment FeedbackReview on PullRequestReview {
1104
+ databaseId
1105
+ state
1106
+ submittedAt
1107
+ body
1108
+ ...FeedbackReactors
1109
+ comments(first: 100) {
1110
+ totalCount
1111
+ nodes { databaseId ...FeedbackReactors }
1112
+ }
1113
+ }
1114
+
802
1115
  fragment FeedbackReactors on Reactable {
803
1116
  reactionGroups {
804
1117
  content
@@ -863,7 +1176,7 @@ function pullRequestLifecycles(count) {
863
1176
  value: `n${index}`
864
1177
  }
865
1178
  });
866
- return operation(visit(parse(PULL_REQUEST_LIFECYCLE.query), {
1179
+ return operation(visit(parse$1(PULL_REQUEST_LIFECYCLE.query), {
867
1180
  OperationDefinition: (node) => ({
868
1181
  ...node,
869
1182
  variableDefinitions: node.variableDefinitions?.flatMap((definition) => definition.variable.name.value === "number" ? indexes.map((index) => ({
@@ -919,6 +1232,10 @@ const PULL_REQUEST_CARD = githubGraphql(`
919
1232
  }
920
1233
  }
921
1234
  }
1235
+ reviewDecision
1236
+ latestOpinionatedReviews(first: 5, writersOnly: true) {
1237
+ nodes { state }
1238
+ }
922
1239
  commits(last: 1) {
923
1240
  nodes {
924
1241
  commit {
@@ -957,7 +1274,7 @@ const PULL_REQUEST_HEAD_FACT = githubGraphql(`
957
1274
  }
958
1275
  `);
959
1276
  function aliasedPullRequests$1(single, count) {
960
- const document = parse(single.query);
1277
+ const document = parse$1(single.query);
961
1278
  const indexes = Array.from({ length: count }, (_, index) => index);
962
1279
  const indexed = (variable, index) => ({
963
1280
  ...variable,
@@ -1088,6 +1405,12 @@ const pullRequestCardNodeSchema = pullRequestHeadFactsNodeSchema.extend({
1088
1405
  merged: z.boolean(),
1089
1406
  number: z.number().int().positive(),
1090
1407
  reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({ login: z.string().optional() }).nullable() }).nullable()).nullable() }).nullable(),
1408
+ reviewDecision: z.enum([
1409
+ "APPROVED",
1410
+ "CHANGES_REQUESTED",
1411
+ "REVIEW_REQUIRED"
1412
+ ]).nullish(),
1413
+ latestOpinionatedReviews: z.object({ nodes: z.array(z.object({ state: z.string() }).nullable()) }).nullish(),
1091
1414
  state: z.enum([
1092
1415
  "CLOSED",
1093
1416
  "MERGED",
@@ -1096,6 +1419,19 @@ const pullRequestCardNodeSchema = pullRequestHeadFactsNodeSchema.extend({
1096
1419
  title: z.string(),
1097
1420
  url: z.string()
1098
1421
  });
1422
+ /**
1423
+ * Return GitHub's review decision. A repository that requires no review has
1424
+ * none, so the latest review of each writer decides: approved when one
1425
+ * approves and none asks for changes.
1426
+ */
1427
+ function pullRequestReview(node) {
1428
+ if (node.reviewDecision === "APPROVED") return "approved";
1429
+ if (node.reviewDecision === "CHANGES_REQUESTED") return "changes_requested";
1430
+ if (node.reviewDecision === "REVIEW_REQUIRED") return "required";
1431
+ const states = (node.latestOpinionatedReviews?.nodes ?? []).map((review) => review?.state);
1432
+ if (states.includes("CHANGES_REQUESTED")) return "changes_requested";
1433
+ return states.includes("APPROVED") ? "approved" : null;
1434
+ }
1099
1435
  const PASSED_CHECK_RUNS = /* @__PURE__ */ new Set([
1100
1436
  "NEUTRAL",
1101
1437
  "SKIPPED",
@@ -1147,6 +1483,7 @@ function githubPullRequestFieldsFromNode(node) {
1147
1483
  const login = request?.requestedReviewer?.login;
1148
1484
  return login ? [{ login }] : [];
1149
1485
  }),
1486
+ review: pullRequestReview(node),
1150
1487
  state: node.state === "OPEN" ? "open" : "closed",
1151
1488
  title: node.title,
1152
1489
  updated_at: node.updatedAt,
@@ -1200,22 +1537,36 @@ const PAGE_BUDGET_MS = 2e4;
1200
1537
  function cacheKey(ref) {
1201
1538
  return githubObjectCacheKey("pulls", `${ref.owner}/${ref.name}`, ref.number);
1202
1539
  }
1540
+ function needsReview(entry) {
1541
+ const fields = githubPullRequestFieldsSchema.safeParse(entry);
1542
+ return fields.success && fields.data.state === "open" && fields.data.review === void 0;
1543
+ }
1203
1544
  async function missingRefs(ctx, refs) {
1204
1545
  const missing = await pLimit(PREFETCH_CONCURRENCY).map(refs, async (ref) => {
1205
- if (await ctx.cache.get(cacheKey(ref)) !== void 0) return false;
1546
+ const entry = await ctx.cache.get(cacheKey(ref));
1547
+ if (entry !== void 0 && !needsReview(entry)) return false;
1206
1548
  return await viewerCanSeeRepository(ctx, ref);
1207
1549
  });
1208
1550
  return refs.filter((_, index) => missing[index]);
1209
1551
  }
1210
- async function storeCard(ctx, key, node) {
1552
+ async function storeCard(ctx, key, node, startedAtMs) {
1211
1553
  const fields = githubPullRequestFieldsFromNode(node);
1212
- await ctx.cache.update(key, (current) => isOlderGitHubObject(current, fields) ? void 0 : githubPullRequestEntry({
1213
- ...current,
1214
- ...fields
1215
- }));
1554
+ let stored = false;
1555
+ await ctx.cache.update(key, (current) => {
1556
+ stored = !isOlderGitHubObject(current, fields);
1557
+ return stored ? githubPullRequestEntry({
1558
+ ...current,
1559
+ ...fields
1560
+ }) : void 0;
1561
+ });
1562
+ if (stored) await clearGitHubReviewAfterRead(ctx.cache, key, {
1563
+ review: fields.review,
1564
+ startedAtMs
1565
+ });
1216
1566
  }
1217
1567
  async function loadChunk(ctx, refs, deadlineMs) {
1218
- const leftMs = deadlineMs - Date.now();
1568
+ const startedAtMs = Date.now();
1569
+ const leftMs = deadlineMs - startedAtMs;
1219
1570
  if (leftMs <= 0) throw new Error("The page has no time left for cards");
1220
1571
  const response = await githubApi(ctx.egress, {
1221
1572
  body: {
@@ -1231,7 +1582,7 @@ async function loadChunk(ctx, refs, deadlineMs) {
1231
1582
  const nodes = aliasedPullRequests(response.body, refs.length, pullRequestCardNodeSchema);
1232
1583
  await pLimit(PREFETCH_CONCURRENCY).map(refs, async (ref, index) => {
1233
1584
  const node = nodes[index];
1234
- if (node) await storeCard(ctx, cacheKey(ref), node);
1585
+ if (node) await storeCard(ctx, cacheKey(ref), node, startedAtMs);
1235
1586
  });
1236
1587
  }
1237
1588
  async function loadInHalves(args) {
@@ -1280,6 +1631,11 @@ async function prefetchGitHubPullRequests(ctx, refs) {
1280
1631
  return outOfTime;
1281
1632
  }
1282
1633
  // src/issue-links.ts
1634
+ const RELEASE_CONFIG_TTL_MS = 36e5;
1635
+ const contentsSchema = z.object({
1636
+ content: z.string(),
1637
+ encoding: z.literal("base64")
1638
+ });
1283
1639
  const OWNER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
1284
1640
  const REPO_PATTERN = /^[\w.-]{1,100}$/;
1285
1641
  const NUMBER_PATTERN = /^[1-9]\d{0,9}$/;
@@ -1314,9 +1670,25 @@ function issueCard(link, issue) {
1314
1670
  status: issue.state
1315
1671
  });
1316
1672
  }
1317
- function pullRequestCard(link, pull) {
1673
+ const TITLE_PART_MAX_LENGTH = 160;
1674
+ /**
1675
+ * Add the title parts to code change facts. The preview images are packed
1676
+ * again after them, so the facts stay in the 4 KiB limit.
1677
+ */
1678
+ function withTitleParts(facts, titleParts) {
1679
+ const { previewImageUrls = [], ...rest } = facts;
1680
+ return withGitHubPreviewImages({
1681
+ ...rest,
1682
+ titleParts
1683
+ }, previewImageUrls);
1684
+ }
1685
+ function pullRequestCard(link, pull, categories) {
1686
+ const card = githubObjectFacts("code_change", pull);
1687
+ const parsed = categories && parseCodeChangeTitle(pull.title, categories);
1688
+ const titleParts = parsed && (parsed.scope?.length ?? 0) <= TITLE_PART_MAX_LENGTH && (parsed.type?.length ?? 0) <= TITLE_PART_MAX_LENGTH ? parsed : void 0;
1318
1689
  return githubObjectAnnotation({
1319
- ...githubObjectFacts("code_change", pull),
1690
+ ...card,
1691
+ ...titleParts && card.facts?.type === "code_change" ? { facts: withTitleParts(card.facts, titleParts) } : void 0,
1320
1692
  repo: repoRef(pull.html_url, link),
1321
1693
  number: pull.number,
1322
1694
  title: pull.title,
@@ -1325,6 +1697,52 @@ function pullRequestCard(link, pull) {
1325
1697
  status: pull.merged ? "merged" : pull.state === "open" && pull.draft ? "draft" : pull.state
1326
1698
  });
1327
1699
  }
1700
+ function releaseConfigKey(link) {
1701
+ return `release-config:${link.owner}/${link.name}`.toLowerCase();
1702
+ }
1703
+ /**
1704
+ * Read the text of a repository's `.github/release.yml` with the App, or
1705
+ * an empty text when it has none. A failed read is not cached. A card whose
1706
+ * page read ran out of time reads only the cache, and a miss rejects with
1707
+ * `OUT_OF_TIME`.
1708
+ */
1709
+ async function readReleaseConfig(ctx, link) {
1710
+ const load = async () => {
1711
+ const response = await githubApi(ctx.egress, {
1712
+ apiVersion: "2022-11-28",
1713
+ operation: "github.repository.release-config.get",
1714
+ path: `${repoPath(link)}/contents/.github/release.yml`
1715
+ });
1716
+ if (response.status === 404) return {
1717
+ value: "",
1718
+ ttlMs: RELEASE_CONFIG_TTL_MS
1719
+ };
1720
+ const file = contentsSchema.safeParse(response.body);
1721
+ if (!response.ok || !file.success) throw new Error(`GitHub release config read failed with HTTP ${response.status}`);
1722
+ return {
1723
+ value: Buffer.from(file.data.content, "base64").toString("utf8"),
1724
+ ttlMs: RELEASE_CONFIG_TTL_MS
1725
+ };
1726
+ };
1727
+ return await ctx.cache.getOrLoad(releaseConfigKey(link), ctx.prefetchOutcome === "out_of_time" ? () => Promise.reject(OUT_OF_TIME) : load);
1728
+ }
1729
+ /**
1730
+ * The change types of a repository. The defaults when the read fails, and
1731
+ * none when the page read ran out of time before the cache held them.
1732
+ */
1733
+ async function readCategories(ctx, link) {
1734
+ try {
1735
+ const text = await readReleaseConfig(ctx, link);
1736
+ return text ? parseReleaseCategories(text) : DEFAULT_CODE_CHANGE_CATEGORIES;
1737
+ } catch (error) {
1738
+ if (error === OUT_OF_TIME) return void 0;
1739
+ ctx.log.warn("GitHub release config read failed", {
1740
+ error: error instanceof Error ? error.message : String(error),
1741
+ repository: `${link.owner}/${link.name}`
1742
+ });
1743
+ return DEFAULT_CODE_CHANGE_CATEGORIES;
1744
+ }
1745
+ }
1328
1746
  /**
1329
1747
  * Read the object fields through the cache, or with the App. Nothing for a
1330
1748
  * missing or deleted object.
@@ -1361,7 +1779,7 @@ async function readFields(ctx, link, schema, entry) {
1361
1779
  async function readObject(ctx, link) {
1362
1780
  if (link.kind === "pull_request") {
1363
1781
  const pull = await readFields(ctx, link, githubPullRequestFieldsSchema, githubPullRequestEntry);
1364
- return pull && pullRequestCard(link, pull);
1782
+ return pull && pullRequestCard(link, pull, await readCategories(ctx, htmlUrlLink(pull.html_url) ?? link));
1365
1783
  }
1366
1784
  const issue = await readFields(ctx, link, githubIssueFieldsSchema, (value) => ({
1367
1785
  ...GITHUB_ISSUE_CACHE,
@@ -1772,13 +2190,19 @@ const table = pgTable("junior_github_pull_request_requesters", {
1772
2190
  identityId: text("identity_id").notNull(),
1773
2191
  /** The Conversation where the person asked Junior to open the pull request. */
1774
2192
  conversationId: text("conversation_id"),
2193
+ /**
2194
+ * GitHub's id of the pull request (`databaseId`), the id of its Inbox
2195
+ * items. Set on the opener's row, so a Resume finds its pull request
2196
+ * without a name, also after a rename.
2197
+ */
2198
+ pullRequestId: text("pull_request_id"),
1775
2199
  createdAt: timestamp$1("created_at", { withTimezone: true }).notNull(),
1776
2200
  updatedAt: timestamp$1("updated_at", { withTimezone: true }).notNull()
1777
2201
  }, (table) => [primaryKey({ columns: [
1778
2202
  table.repositoryFullName,
1779
2203
  table.number,
1780
2204
  table.identityId
1781
- ] })]);
2205
+ ] }), uniqueIndex("junior_github_pull_request_requesters_opener_id_uidx").on(table.pullRequestId).where(sql`${table.conversationId} is not null`)]);
1782
2206
  /**
1783
2207
  * Save the person who asked Junior to open a pull request, after GitHub
1784
2208
  * opens it.
@@ -1790,11 +2214,13 @@ const table = pgTable("junior_github_pull_request_requesters", {
1790
2214
  */
1791
2215
  async function recordGitHubPullRequestOpener(db, input) {
1792
2216
  const repositoryFullName = input.repositoryFullName.toLowerCase();
2217
+ const pullRequestId = input.pullRequestId ?? null;
1793
2218
  await db.insert(table).values({
1794
2219
  conversationId: input.conversationId,
1795
2220
  createdAt: input.createdAt,
1796
2221
  identityId: input.identityId,
1797
2222
  number: input.number,
2223
+ pullRequestId,
1798
2224
  repositoryFullName,
1799
2225
  updatedAt: /* @__PURE__ */ new Date()
1800
2226
  }).onConflictDoUpdate({
@@ -1805,7 +2231,8 @@ async function recordGitHubPullRequestOpener(db, input) {
1805
2231
  ],
1806
2232
  set: {
1807
2233
  conversationId: input.conversationId,
1808
- createdAt: input.createdAt
2234
+ createdAt: input.createdAt,
2235
+ ...pullRequestId ? { pullRequestId } : void 0
1809
2236
  }
1810
2237
  });
1811
2238
  await db.delete(table).where(and(eq(table.repositoryFullName, repositoryFullName), eq(table.number, input.number), lt(table.createdAt, input.createdAt)));
@@ -1842,34 +2269,281 @@ async function listGitHubPullRequestOpeners(db, input) {
1842
2269
  const rows = await db.select().from(table).where(and(eq(table.repositoryFullName, input.repositoryFullName.toLowerCase()), inArray(table.number, [...new Set(input.numbers)]))).orderBy(asc(table.createdAt));
1843
2270
  for (const row of rows) if (!openers.has(row.number)) openers.set(row.number, {
1844
2271
  identityId: row.identityId,
1845
- ...row.conversationId ? { conversationId: row.conversationId } : void 0
2272
+ ...row.conversationId ? { conversationId: row.conversationId } : void 0,
2273
+ ...row.pullRequestId ? { pullRequestId: row.pullRequestId } : void 0
1846
2274
  });
1847
2275
  return openers;
1848
2276
  }
1849
2277
  /**
1850
- * Load every requester of each pull request: the person who asked Junior to
1851
- * open it and each person who asked Junior to update it.
2278
+ * Save GitHub's id of the pull request on its opener's row, when the row
2279
+ * has none yet, such as a row from before the create saved the id. The row
2280
+ * maps the id to the Conversation that owns the pull request's Inbox items,
2281
+ * so an item needs it before it is added.
2282
+ */
2283
+ async function recordGitHubPullRequestOpenerId(db, input) {
2284
+ await db.update(table).set({
2285
+ pullRequestId: input.pullRequestId,
2286
+ updatedAt: /* @__PURE__ */ new Date()
2287
+ }).where(and(eq(table.repositoryFullName, input.repositoryFullName.toLowerCase()), eq(table.number, input.number), eq(table.conversationId, input.conversationId), isNull(table.pullRequestId)));
2288
+ }
2289
+ /**
2290
+ * Whether a person asked Junior to open a pull request in one Conversation,
2291
+ * by GitHub's id of the pull request.
2292
+ */
2293
+ async function wasGitHubPullRequestOpenedIn(db, input) {
2294
+ const [row] = await db.select({ number: table.number }).from(table).where(and(eq(table.conversationId, input.conversationId), eq(table.pullRequestId, input.pullRequestId))).limit(1);
2295
+ return row !== void 0;
2296
+ }
2297
+ /**
2298
+ * Load every requester of each pull request: the person who asked Junior to
2299
+ * open it and each person who asked Junior to update it.
2300
+ */
2301
+ async function listGitHubPullRequestRequesters(db, input) {
2302
+ const requesters = /* @__PURE__ */ new Map();
2303
+ if (input.numbers.length === 0) return requesters;
2304
+ const rows = await db.select({
2305
+ identityId: table.identityId,
2306
+ number: table.number
2307
+ }).from(table).where(and(eq(table.repositoryFullName, input.repositoryFullName.toLowerCase()), inArray(table.number, [...new Set(input.numbers)])));
2308
+ for (const row of rows) requesters.set(row.number, [...requesters.get(row.number) ?? [], row.identityId]);
2309
+ return requesters;
2310
+ }
2311
+ /**
2312
+ * Load the next pull requests that have saved requesters, after `after`, in
2313
+ * the order of their repository name and number.
2314
+ */
2315
+ async function listGitHubPullRequestsWithRequesters(db, input) {
2316
+ const { after } = input;
2317
+ return await db.selectDistinct({
2318
+ number: table.number,
2319
+ repositoryFullName: table.repositoryFullName
2320
+ }).from(table).where(after ? or(gt(table.repositoryFullName, after.repositoryFullName), and(eq(table.repositoryFullName, after.repositoryFullName), gt(table.number, after.number))) : void 0).orderBy(asc(table.repositoryFullName), asc(table.number)).limit(input.limit);
2321
+ }
2322
+ // src/pull-request-review-again.ts
2323
+ const reactorsSchema = z.object({ reactionGroups: z.array(z.object({
2324
+ content: z.string(),
2325
+ reactors: z.object({ nodes: z.array(z.object({ databaseId: z.number().optional() }).nullable()) })
2326
+ })) });
2327
+ const checkContextSchema$1 = z.discriminatedUnion("__typename", [z.object({
2328
+ __typename: z.literal("CheckRun"),
2329
+ conclusion: z.string().nullable(),
2330
+ name: z.string(),
2331
+ status: z.string()
2332
+ }), z.object({
2333
+ __typename: z.literal("StatusContext"),
2334
+ context: z.string(),
2335
+ state: z.string()
2336
+ })]);
2337
+ const requiredChecksSchema = z.object({
2338
+ baseRef: z.object({ refUpdateRule: z.object({ requiredStatusCheckContexts: z.array(z.string().nullable()).nullable() }).nullable() }).nullable(),
2339
+ baseRefName: z.string().min(1),
2340
+ commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ contexts: z.object({
2341
+ nodes: z.array(checkContextSchema$1.nullable()),
2342
+ pageInfo: z.object({ hasNextPage: z.boolean() })
2343
+ }) }).nullable() }) })) })
2344
+ });
2345
+ const requiredChecksReadSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: requiredChecksSchema }) }) });
2346
+ const feedbackReviewSchema = reactorsSchema.extend({
2347
+ body: z.string(),
2348
+ comments: z.object({
2349
+ nodes: z.array(reactorsSchema.extend({ databaseId: z.number().nullable() }).nullable()),
2350
+ totalCount: z.number()
2351
+ }),
2352
+ databaseId: z.number().nullable(),
2353
+ state: z.string(),
2354
+ submittedAt: z.string().nullable()
2355
+ });
2356
+ const reviewAgainSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: requiredChecksSchema.extend({
2357
+ reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({
2358
+ __typename: z.string(),
2359
+ login: z.string().optional()
2360
+ }).nullable() }).nullable()) }),
2361
+ decision: z.object({ nodes: z.array(feedbackReviewSchema.nullable()) }),
2362
+ reviews: z.object({ nodes: z.array(feedbackReviewSchema.nullable()) }),
2363
+ timelineItems: z.object({ nodes: z.array(z.object({
2364
+ createdAt: z.string().optional(),
2365
+ requestedReviewer: z.object({ login: z.string().optional() }).nullable().optional()
2366
+ }).nullable()) })
2367
+ }) }) }) });
2368
+ const branchRulesSchema = z.array(z.object({
2369
+ parameters: z.object({ required_status_checks: z.array(z.object({ context: z.string() })).optional() }).optional(),
2370
+ type: z.string()
2371
+ }));
2372
+ const MARKED_CONTENTS = /* @__PURE__ */ new Set(["THUMBS_DOWN", "THUMBS_UP"]);
2373
+ const PASSING_CONCLUSIONS = /* @__PURE__ */ new Set([
2374
+ "NEUTRAL",
2375
+ "SKIPPED",
2376
+ "SUCCESS"
2377
+ ]);
2378
+ /** Return whether one check run or commit status passes, fails, or waits. */
2379
+ function checkContextState(context) {
2380
+ if (context.__typename === "CheckRun") {
2381
+ if (context.status !== "COMPLETED") return "pending";
2382
+ return PASSING_CONCLUSIONS.has(context.conclusion ?? "") ? "passing" : "failing";
2383
+ }
2384
+ if (context.state === "SUCCESS") return "passing";
2385
+ return context.state === "PENDING" || context.state === "EXPECTED" ? "pending" : "failing";
2386
+ }
2387
+ function markedBy(reactable, botUserId) {
2388
+ return reactable.reactionGroups.some((group) => MARKED_CONTENTS.has(group.content) && group.reactors.nodes.some((reactor) => reactor?.databaseId === botUserId));
2389
+ }
2390
+ /**
2391
+ * Return whether every required check passes. A required check that has
2392
+ * not reported yet waits, so the ask does not go out before CI starts.
2393
+ */
2394
+ function requiredChecksPass(required, contexts, incomplete) {
2395
+ for (const name of required) {
2396
+ const states = contexts.filter((context) => (context.__typename === "CheckRun" ? context.name : context.context) === name).map(checkContextState);
2397
+ if (states.length === 0 && incomplete) return false;
2398
+ if (states.length === 0 || states.some((state) => state !== "passing")) return false;
2399
+ }
2400
+ return true;
2401
+ }
2402
+ /**
2403
+ * Return the reviews whose comments Junior must mark before it asks again,
2404
+ * oldest first, or undefined when there is no feedback to answer. The
2405
+ * feedback is the reviewer's latest change request. For the requester
2406
+ * (`commentsCount`), it also takes their comment-only reviews after their
2407
+ * latest approval or change request. After an approval, only the
2408
+ * comment-only reviews after a later ask count, so a comment on an
2409
+ * approved pull request does not ask again. For others, a comment-only
2410
+ * review is left out, so a reply to Junior does not hide their change
2411
+ * request. `decided` is read on its own, so a long discussion does not
2412
+ * hide an approval. A long discussion can push older comments out of
2413
+ * `comments`. Junior answers each comment as it comes, so it asks once the
2414
+ * comments it reads are marked, and the discussion does not stall.
2415
+ */
2416
+ async function feedbackReviews(decided, comments, askedAt, commentsCount) {
2417
+ const decidedAt = decided?.state === "APPROVED" || decided?.state === "DISMISSED" ? Date.parse(decided.submittedAt ?? "") : void 0;
2418
+ const since = Date.parse(decided?.submittedAt ?? "");
2419
+ const feedback = comments.filter((review) => {
2420
+ const at = Date.parse(review.submittedAt ?? "");
2421
+ if (decided && !(at > since)) return false;
2422
+ return decidedAt === void 0 || askedAt > decidedAt && at > askedAt;
2423
+ });
2424
+ const changeRequest = decided?.state === "CHANGES_REQUESTED";
2425
+ if (feedback.length > 0 && await commentsCount()) return changeRequest ? [decided, ...feedback] : feedback;
2426
+ return changeRequest ? [decided] : void 0;
2427
+ }
2428
+ /**
2429
+ * Read whether `reviewer`'s latest change request on a pull request is
2430
+ * ready for their review again. The comments of a change request are its
2431
+ * inline comments and its body. An empty body counts only when the review
2432
+ * has no inline comments.
2433
+ */
2434
+ async function readReviewAgainReadiness(read, target) {
2435
+ const { name, number, owner, reviewer } = target;
2436
+ const pull = reviewAgainSchema.parse(await read({
2437
+ body: {
2438
+ ...PULL_REQUEST_REVIEW_AGAIN,
2439
+ variables: {
2440
+ name,
2441
+ number,
2442
+ owner,
2443
+ reviewer
2444
+ }
2445
+ },
2446
+ operation: "github.pull.review-again.get",
2447
+ path: "/graphql"
2448
+ })).data.repository.pullRequest;
2449
+ const lower = reviewer.toLowerCase();
2450
+ if (pull.reviewRequests.nodes.some((request) => request?.requestedReviewer?.login?.toLowerCase() === lower)) return "none";
2451
+ const askedAt = Math.max(Number.NEGATIVE_INFINITY, ...pull.timelineItems.nodes.flatMap((item) => item?.createdAt && item.requestedReviewer?.login?.toLowerCase() === lower ? [Date.parse(item.createdAt)] : []));
2452
+ const reviews = await feedbackReviews(pull.decision.nodes[0] ?? void 0, pull.reviews.nodes.filter((review) => review !== null), askedAt, async () => await target.isRequester?.() ?? false);
2453
+ if (!reviews) return "none";
2454
+ const { marked } = target;
2455
+ const justMarked = (id, kind) => marked?.kind === kind && marked.id === id;
2456
+ for (const review of reviews) {
2457
+ const comments = review.comments.nodes.filter((comment) => comment !== null);
2458
+ if (comments.length < review.comments.totalCount) return "none";
2459
+ const bodyMarked = justMarked(review.databaseId, "review_body") || markedBy(review, target.botUserId);
2460
+ if ((review.body.trim() !== "" || comments.length === 0) && !bodyMarked) return "none";
2461
+ if (!comments.every((comment) => justMarked(comment.databaseId, "review") || markedBy(comment, target.botUserId))) return "none";
2462
+ }
2463
+ return await readRequiredChecksPass(read, target, pull) ? "ready" : "checks";
2464
+ }
2465
+ async function readRequiredChecksPass(read, target, pull) {
2466
+ const { name, owner } = target;
2467
+ const rules = branchRulesSchema.parse(await read({
2468
+ operation: "github.repo.branch-rules.get",
2469
+ path: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/rules/branches/${encodeURIComponent(pull.baseRefName)}?per_page=100`
2470
+ }));
2471
+ const required = /* @__PURE__ */ new Set([...(pull.baseRef?.refUpdateRule?.requiredStatusCheckContexts ?? []).filter((context) => Boolean(context)), ...rules.flatMap((rule) => rule.type === "required_status_checks" ? (rule.parameters?.required_status_checks ?? []).map((check) => check.context) : [])]);
2472
+ const rollup = pull.commits.nodes[0]?.commit.statusCheckRollup;
2473
+ return requiredChecksPass(required, (rollup?.contexts.nodes ?? []).filter((context) => context !== null), rollup?.contexts.pageInfo.hasNextPage ?? false);
2474
+ }
2475
+ /**
2476
+ * Read whether every required check of a pull request's head commit
2477
+ * passes, so an ask for a review does not go out before CI is green.
1852
2478
  */
1853
- async function listGitHubPullRequestRequesters(db, input) {
1854
- const requesters = /* @__PURE__ */ new Map();
1855
- if (input.numbers.length === 0) return requesters;
1856
- const rows = await db.select({
1857
- identityId: table.identityId,
1858
- number: table.number
1859
- }).from(table).where(and(eq(table.repositoryFullName, input.repositoryFullName.toLowerCase()), inArray(table.number, [...new Set(input.numbers)])));
1860
- for (const row of rows) requesters.set(row.number, [...requesters.get(row.number) ?? [], row.identityId]);
1861
- return requesters;
2479
+ async function readGitHubRequiredChecksPass(read, target) {
2480
+ const { name, number, owner } = target;
2481
+ const pull = requiredChecksReadSchema.parse(await read({
2482
+ body: {
2483
+ ...PULL_REQUEST_REQUIRED_CHECKS,
2484
+ variables: {
2485
+ name,
2486
+ number,
2487
+ owner
2488
+ }
2489
+ },
2490
+ operation: "github.pull.required-checks.get",
2491
+ path: "/graphql"
2492
+ })).data.repository.pullRequest;
2493
+ return await readRequiredChecksPass(read, target, pull);
2494
+ }
2495
+ const HELD_ASK_TTL_MS = 2592e5;
2496
+ const heldAskSchema = z.object({
2497
+ at: z.iso.datetime(),
2498
+ reason: z.enum(["checks", "handled"]),
2499
+ reviewer: z.string().min(1),
2500
+ marked: z.object({
2501
+ id: z.number(),
2502
+ kind: z.enum(["review", "review_body"])
2503
+ }).optional()
2504
+ });
2505
+ function heldAskKey(target) {
2506
+ return `pull-request-review-again:${target.repositoryFullName.toLowerCase()}#${target.number}`;
2507
+ }
2508
+ /** Save the review ask that waits for the checks of one pull request. */
2509
+ async function holdGitHubReviewAsk(state, target, ask) {
2510
+ await state.set(heldAskKey(target), heldAskSchema.parse(ask), HELD_ASK_TTL_MS);
2511
+ }
2512
+ /** Return the review ask that waits for the checks of one pull request. */
2513
+ async function readHeldGitHubReviewAsk(state, target) {
2514
+ const saved = heldAskSchema.safeParse(await state.get(heldAskKey(target)));
2515
+ return saved.success ? saved.data : void 0;
1862
2516
  }
1863
2517
  /**
1864
- * Load the next pull requests that have saved requesters, after `after`, in
1865
- * the order of their repository name and number.
2518
+ * Drop the held review ask of one pull request. With `reviewer`, drop it
2519
+ * only when it is for that reviewer.
1866
2520
  */
1867
- async function listGitHubPullRequestsWithRequesters(db, input) {
1868
- const { after } = input;
1869
- return await db.selectDistinct({
1870
- number: table.number,
1871
- repositoryFullName: table.repositoryFullName
1872
- }).from(table).where(after ? or(gt(table.repositoryFullName, after.repositoryFullName), and(eq(table.repositoryFullName, after.repositoryFullName), gt(table.number, after.number))) : void 0).orderBy(asc(table.repositoryFullName), asc(table.number)).limit(input.limit);
2521
+ async function dropHeldGitHubReviewAsk(state, target, reviewer) {
2522
+ if (reviewer !== void 0) {
2523
+ if ((await readHeldGitHubReviewAsk(state, target))?.reviewer.toLowerCase() !== reviewer.toLowerCase()) return;
2524
+ }
2525
+ await state.delete(heldAskKey(target));
2526
+ }
2527
+ const ASKED_TTL_MS = 36e5;
2528
+ const SHOWN_TTL_MS = 2592e6;
2529
+ const askedSchema = z.object({
2530
+ at: z.iso.datetime(),
2531
+ reason: z.enum(["handled", "question"]).optional(),
2532
+ reviewer: z.string().min(1),
2533
+ /** The item shows the ask, so a later sync does not push it again. */
2534
+ shown: z.boolean().optional()
2535
+ });
2536
+ function askedKey(target) {
2537
+ return `pull-request-review-asked:${target.repositoryFullName.toLowerCase()}#${target.number}`;
2538
+ }
2539
+ /** Record that a Junior tool asked `reviewer` on one pull request. */
2540
+ async function markGitHubReviewAsked(state, target, asked) {
2541
+ await state.set(askedKey(target), askedSchema.parse(asked), asked.shown ? SHOWN_TTL_MS : ASKED_TTL_MS);
2542
+ }
2543
+ /** Return the review that a Junior tool asked for on one pull request. */
2544
+ async function readGitHubReviewAsked(state, target) {
2545
+ const saved = askedSchema.safeParse(await state.get(askedKey(target)));
2546
+ return saved.success ? saved.data : void 0;
1873
2547
  }
1874
2548
  // src/tools/comment-on-pull-request.ts
1875
2549
  const inputSchema$12 = z.object({
@@ -1922,12 +2596,23 @@ async function askRequester(ctx, target) {
1922
2596
  }).then((openers) => openers.get(target.number)), ctx.resolveWorkOwner().then(requesterPerson)]);
1923
2597
  const login = opener?.conversationId && owner?.identity?.id === opener.identityId ? linkedGitHubLogin(owner.user) : void 0;
1924
2598
  if (!login) return false;
1925
- const response = await githubApi(ctx.egress, {
2599
+ await markGitHubReviewAsked(ctx.state, {
2600
+ number: target.number,
2601
+ repositoryFullName: target.repo
2602
+ }, {
2603
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2604
+ reason: "question",
2605
+ reviewer: login
2606
+ });
2607
+ const path = `${target.prefix}/pulls/${target.number}/requested_reviewers`;
2608
+ const removed = await isRequested$1(ctx, path, login) && (await githubApi(ctx.egress, {
1926
2609
  operation: "github.pull.request_reviewers",
1927
- method: "POST",
1928
- path: `${target.prefix}/pulls/${target.number}/requested_reviewers`,
2610
+ method: "DELETE",
2611
+ path,
1929
2612
  body: { reviewers: [login] }
1930
- });
2613
+ })).ok;
2614
+ let response = await requestReviewer$1(ctx, path, login);
2615
+ if (removed && isTransient(response.status)) response = await requestReviewer$1(ctx, path, login);
1931
2616
  if (response.ok) return true;
1932
2617
  ctx.log.warn("github.pull_request.request_reviewers_after_question.rejected", {
1933
2618
  ...fields,
@@ -1941,6 +2626,29 @@ async function askRequester(ctx, target) {
1941
2626
  }
1942
2627
  return false;
1943
2628
  }
2629
+ function requestReviewer$1(ctx, path, login) {
2630
+ return githubApi(ctx.egress, {
2631
+ operation: "github.pull.request_reviewers",
2632
+ method: "POST",
2633
+ path,
2634
+ body: { reviewers: [login] }
2635
+ });
2636
+ }
2637
+ function isTransient(status) {
2638
+ return status === 429 || status >= 500;
2639
+ }
2640
+ /** Whether GitHub asks `login` for a review of the pull request now. */
2641
+ async function isRequested$1(ctx, path, login) {
2642
+ const response = await githubApi(ctx.egress, {
2643
+ operation: "github.pull.request_reviewers",
2644
+ method: "GET",
2645
+ path
2646
+ });
2647
+ if (!response.ok) return false;
2648
+ const parsed = z.object({ users: z.array(z.object({ login: z.string() })) }).safeParse(response.body);
2649
+ const lower = login.toLowerCase();
2650
+ return parsed.success && parsed.data.users.some((user) => user.login.toLowerCase() === lower);
2651
+ }
1944
2652
  /**
1945
2653
  * Post a pull request comment as the App bot, or reply in an inline review
1946
2654
  * thread. GitHub keeps conversation comments under the issues endpoint and
@@ -2113,7 +2821,7 @@ const gitHubIssueOutputSchema = pluginToolOutputSchema.merge(gitHubIssueDataSche
2113
2821
  * a person started gets it: no one can answer the item in other runs.
2114
2822
  */
2115
2823
  function implementIssueNote(issue) {
2116
- 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 startAgent, kind thread, and this brief: read ${issue} with github_getIssue, follow the github-code workflow, and open a pull request that references it.`;
2824
+ 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". 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 startAgent, kind thread, and this brief: read ${issue} with github_getIssue, follow the github-code workflow, and open a pull request that references it.`;
2117
2825
  }
2118
2826
  async function gitHubIssueToolResult(ctx, input, result) {
2119
2827
  const repo = parseRepo$1(input.repo);
@@ -2721,6 +3429,8 @@ const createPullRequestStateSchema = Type.Union([Type.Object({
2721
3429
  createdAtMs: Type.Number(),
2722
3430
  input: Type.Optional(createPullRequestInputSchema),
2723
3431
  number: Type.Number(),
3432
+ /** GitHub's id of the pull request, for its opener's row. */
3433
+ pullRequestId: Type.Optional(Type.String()),
2724
3434
  facts: Type.Optional(Type.Unknown()),
2725
3435
  sourceUpdatedAt: Type.Optional(Type.String()),
2726
3436
  description: Type.Optional(Type.String({ maxLength: 4e3 })),
@@ -2814,6 +3524,7 @@ async function createGitHubPullRequest(ctx, request) {
2814
3524
  number: pullRequest.number,
2815
3525
  url: pullRequest.html_url
2816
3526
  },
3527
+ ...typeof pullRequest.id === "number" ? { pullRequestId: String(pullRequest.id) } : void 0,
2817
3528
  ...stackTarget.success ? { stackTarget: stackTarget.data } : void 0
2818
3529
  };
2819
3530
  }
@@ -2831,6 +3542,7 @@ async function recordOpener(ctx, input, state, requester) {
2831
3542
  createdAt: new Date(state.createdAtMs),
2832
3543
  identityId,
2833
3544
  number: state.number,
3545
+ pullRequestId: state.pullRequestId,
2834
3546
  repositoryFullName: repo.ref
2835
3547
  });
2836
3548
  await syncGitHubPullRequestRequesters({
@@ -3065,9 +3777,10 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
3065
3777
  };
3066
3778
  await ctx.state.set(key, pendingState, GITHUB_PULL_REQUEST_CREATE_IDEMPOTENCY_TTL_MS);
3067
3779
  let result;
3780
+ let pullRequestId;
3068
3781
  let stackTarget;
3069
3782
  try {
3070
- ({result, stackTarget} = await createGitHubPullRequest(ctx, request));
3783
+ ({pullRequestId, result, stackTarget} = await createGitHubPullRequest(ctx, request));
3071
3784
  } catch (error) {
3072
3785
  if (isEgressAuthRequired(error) || isDefinitiveGitHubPullRequestCreateRejection(error)) await ctx.state.delete(key);
3073
3786
  throw error;
@@ -3076,6 +3789,7 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
3076
3789
  ...pendingState,
3077
3790
  status: "completed",
3078
3791
  number: result.number,
3792
+ ...pullRequestId === void 0 ? void 0 : { pullRequestId },
3079
3793
  url: result.url,
3080
3794
  facts: result.facts,
3081
3795
  ...result.sourceUpdatedAt === void 0 ? void 0 : { sourceUpdatedAt: result.sourceUpdatedAt },
@@ -3191,169 +3905,6 @@ async function readDraftReadiness(egress, repo, pullRequest) {
3191
3905
  codeOwners: codeOwners ? codeOwnersOf(parseCodeOwners(codeOwners), paths) : []
3192
3906
  };
3193
3907
  }
3194
- // src/pull-request-review-again.ts
3195
- const reactorsSchema = z.object({ reactionGroups: z.array(z.object({
3196
- content: z.string(),
3197
- reactors: z.object({ nodes: z.array(z.object({ databaseId: z.number().optional() }).nullable()) })
3198
- })) });
3199
- const checkContextSchema$1 = z.discriminatedUnion("__typename", [z.object({
3200
- __typename: z.literal("CheckRun"),
3201
- conclusion: z.string().nullable(),
3202
- name: z.string(),
3203
- status: z.string()
3204
- }), z.object({
3205
- __typename: z.literal("StatusContext"),
3206
- context: z.string(),
3207
- state: z.string()
3208
- })]);
3209
- const reviewAgainSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
3210
- baseRef: z.object({ refUpdateRule: z.object({ requiredStatusCheckContexts: z.array(z.string().nullable()).nullable() }).nullable() }).nullable(),
3211
- baseRefName: z.string().min(1),
3212
- commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ contexts: z.object({
3213
- nodes: z.array(checkContextSchema$1.nullable()),
3214
- pageInfo: z.object({ hasNextPage: z.boolean() })
3215
- }) }).nullable() }) })) }),
3216
- reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({
3217
- __typename: z.string(),
3218
- login: z.string().optional()
3219
- }).nullable() }).nullable()) }),
3220
- reviews: z.object({ nodes: z.array(reactorsSchema.extend({
3221
- body: z.string(),
3222
- comments: z.object({
3223
- nodes: z.array(reactorsSchema.extend({ databaseId: z.number().nullable() }).nullable()),
3224
- totalCount: z.number()
3225
- }),
3226
- databaseId: z.number().nullable(),
3227
- state: z.string()
3228
- }).nullable()) })
3229
- }) }) }) });
3230
- const branchRulesSchema = z.array(z.object({
3231
- parameters: z.object({ required_status_checks: z.array(z.object({ context: z.string() })).optional() }).optional(),
3232
- type: z.string()
3233
- }));
3234
- const MARKED_CONTENTS = /* @__PURE__ */ new Set(["THUMBS_DOWN", "THUMBS_UP"]);
3235
- const PASSING_CONCLUSIONS = /* @__PURE__ */ new Set([
3236
- "NEUTRAL",
3237
- "SKIPPED",
3238
- "SUCCESS"
3239
- ]);
3240
- /** Return whether one check run or commit status passes, fails, or waits. */
3241
- function checkContextState(context) {
3242
- if (context.__typename === "CheckRun") {
3243
- if (context.status !== "COMPLETED") return "pending";
3244
- return PASSING_CONCLUSIONS.has(context.conclusion ?? "") ? "passing" : "failing";
3245
- }
3246
- if (context.state === "SUCCESS") return "passing";
3247
- return context.state === "PENDING" || context.state === "EXPECTED" ? "pending" : "failing";
3248
- }
3249
- function markedBy(reactable, botUserId) {
3250
- return reactable.reactionGroups.some((group) => MARKED_CONTENTS.has(group.content) && group.reactors.nodes.some((reactor) => reactor?.databaseId === botUserId));
3251
- }
3252
- /**
3253
- * Return whether every required check passes. A required check that has
3254
- * not reported yet waits, so the ask does not go out before CI starts.
3255
- */
3256
- function requiredChecksPass(required, contexts, incomplete) {
3257
- for (const name of required) {
3258
- const states = contexts.filter((context) => (context.__typename === "CheckRun" ? context.name : context.context) === name).map(checkContextState);
3259
- if (states.length === 0 && incomplete) return false;
3260
- if (states.length === 0 || states.some((state) => state !== "passing")) return false;
3261
- }
3262
- return true;
3263
- }
3264
- /**
3265
- * Read whether `reviewer`'s latest change request on a pull request is
3266
- * ready for their review again. The comments of a change request are its
3267
- * inline comments and its body. An empty body counts only when the review
3268
- * has no inline comments.
3269
- */
3270
- async function readReviewAgainReadiness(read, target) {
3271
- const { name, number, owner, reviewer } = target;
3272
- const pull = reviewAgainSchema.parse(await read({
3273
- body: {
3274
- ...PULL_REQUEST_REVIEW_AGAIN,
3275
- variables: {
3276
- name,
3277
- number,
3278
- owner,
3279
- reviewer
3280
- }
3281
- },
3282
- operation: "github.pull.review-again.get",
3283
- path: "/graphql"
3284
- })).data.repository.pullRequest;
3285
- const lower = reviewer.toLowerCase();
3286
- const requested = pull.reviewRequests.nodes.some((request) => request?.requestedReviewer?.login?.toLowerCase() === lower);
3287
- const review = pull.reviews.nodes[0];
3288
- if (requested || review?.state !== "CHANGES_REQUESTED") return "none";
3289
- const comments = review.comments.nodes.filter((comment) => comment !== null);
3290
- if (comments.length < review.comments.totalCount) return "none";
3291
- const { marked } = target;
3292
- const justMarked = (id, kind) => marked?.kind === kind && marked.id === id;
3293
- const bodyMarked = justMarked(review.databaseId, "review_body") || markedBy(review, target.botUserId);
3294
- if ((review.body.trim() !== "" || comments.length === 0) && !bodyMarked) return "none";
3295
- if (!comments.every((comment) => justMarked(comment.databaseId, "review") || markedBy(comment, target.botUserId))) return "none";
3296
- const rules = branchRulesSchema.parse(await read({
3297
- operation: "github.repo.branch-rules.get",
3298
- path: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/rules/branches/${encodeURIComponent(pull.baseRefName)}?per_page=100`
3299
- }));
3300
- const required = /* @__PURE__ */ new Set([...(pull.baseRef?.refUpdateRule?.requiredStatusCheckContexts ?? []).filter((context) => Boolean(context)), ...rules.flatMap((rule) => rule.type === "required_status_checks" ? (rule.parameters?.required_status_checks ?? []).map((check) => check.context) : [])]);
3301
- const rollup = pull.commits.nodes[0]?.commit.statusCheckRollup;
3302
- return requiredChecksPass(required, (rollup?.contexts.nodes ?? []).filter((context) => context !== null), rollup?.contexts.pageInfo.hasNextPage ?? false) ? "ready" : "checks";
3303
- }
3304
- const HELD_ASK_TTL_MS = 2592e5;
3305
- const heldAskSchema = z.object({
3306
- at: z.iso.datetime(),
3307
- reason: z.enum(["checks", "handled"]),
3308
- reviewer: z.string().min(1),
3309
- marked: z.object({
3310
- id: z.number(),
3311
- kind: z.enum(["review", "review_body"])
3312
- }).optional()
3313
- });
3314
- function heldAskKey(target) {
3315
- return `pull-request-review-again:${target.repositoryFullName.toLowerCase()}#${target.number}`;
3316
- }
3317
- /** Save the review ask that waits for the checks of one pull request. */
3318
- async function holdGitHubReviewAsk(state, target, ask) {
3319
- await state.set(heldAskKey(target), heldAskSchema.parse(ask), HELD_ASK_TTL_MS);
3320
- }
3321
- /** Return the review ask that waits for the checks of one pull request. */
3322
- async function readHeldGitHubReviewAsk(state, target) {
3323
- const saved = heldAskSchema.safeParse(await state.get(heldAskKey(target)));
3324
- return saved.success ? saved.data : void 0;
3325
- }
3326
- /**
3327
- * Drop the held review ask of one pull request. With `reviewer`, drop it
3328
- * only when it is for that reviewer.
3329
- */
3330
- async function dropHeldGitHubReviewAsk(state, target, reviewer) {
3331
- if (reviewer !== void 0) {
3332
- if ((await readHeldGitHubReviewAsk(state, target))?.reviewer.toLowerCase() !== reviewer.toLowerCase()) return;
3333
- }
3334
- await state.delete(heldAskKey(target));
3335
- }
3336
- const ASKED_TTL_MS = 36e5;
3337
- const askedSchema = z.object({
3338
- at: z.iso.datetime(),
3339
- reviewer: z.string().min(1)
3340
- });
3341
- function askedKey(target) {
3342
- return `pull-request-review-asked:${target.repositoryFullName.toLowerCase()}#${target.number}`;
3343
- }
3344
- /** Record that the feedback tool asked `reviewer` again on one pull request. */
3345
- async function markGitHubReviewAsked(state, target, asked) {
3346
- await state.set(askedKey(target), askedSchema.parse(asked), ASKED_TTL_MS);
3347
- }
3348
- /** Return the review that the feedback tool asked for on one pull request. */
3349
- async function readGitHubReviewAsked(state, target) {
3350
- const saved = askedSchema.safeParse(await state.get(askedKey(target)));
3351
- return saved.success ? saved.data : void 0;
3352
- }
3353
- /** Drop the record of a review that the feedback tool asked for. */
3354
- async function dropGitHubReviewAsked(state, target) {
3355
- await state.delete(askedKey(target));
3356
- }
3357
3908
  // src/tools/get-pull-request.ts
3358
3909
  const commitShaSchema = z.string().regex(/^[0-9a-f]{40}$/i);
3359
3910
  const RELATED_CONVERSATIONS_MAX = 10;
@@ -3969,8 +4520,9 @@ const inputSchema$3 = z.object({
3969
4520
  body: z.string().optional().describe(`Replacement pull request body. ${PULL_REQUEST_BODY_RULES}`),
3970
4521
  base: z.string().trim().min(1).optional().describe("Replacement base branch."),
3971
4522
  state: z.enum(["open", "closed"]).optional().describe("Replacement pull request state."),
3972
- 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.")
3973
- }).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." });
4523
+ 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."),
4524
+ request_review: z.literal(true).optional().describe("Set true to ask only the person who asked for the pull request to review it on GitHub. A draft stays a draft, so nobody else is asked. A person who has reviewed it is not asked again, unless their latest approval or change request was dismissed.")
4525
+ }).strict().refine(({ title, body, base, state, draft, request_review }) => title !== void 0 || body !== void 0 || base !== void 0 || state !== void 0 || draft !== void 0 || request_review !== void 0, { message: "At least one pull request field must be provided." });
3974
4526
  const draftMutationResponseSchema = z.object({ data: z.object({ result: z.object({ pullRequest: z.object({ isDraft: z.boolean() }) }) }) });
3975
4527
  const pullRequestSchema = z.object({
3976
4528
  base: z.string(),
@@ -3982,7 +4534,10 @@ const pullRequestSchema = z.object({
3982
4534
  title: z.string(),
3983
4535
  url: z.string()
3984
4536
  });
3985
- const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema.extend({ target: z.literal("updatePullRequest") }));
4537
+ const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema.extend({
4538
+ review_requested: z.boolean().optional().describe("With request_review: true when GitHub asks the person for a review, false when they have reviewed it and their latest approval or change request was not dismissed."),
4539
+ target: z.literal("updatePullRequest")
4540
+ }));
3986
4541
  function nonEmptyString(value, name) {
3987
4542
  if (!value?.trim()) throw new PluginToolInputError(`${name} is missing in this Turn, so the GitHub footer cannot be added. No change to the call can fix this.`);
3988
4543
  return value.trim();
@@ -4004,6 +4559,65 @@ async function setPullRequestDraft(input) {
4004
4559
  if (!response.ok || isDraft !== input.draft) throw new Error(`GitHub pull request draft update failed with HTTP ${response.status}: ${githubErrorMessage$1(payload)}`);
4005
4560
  return isDraft;
4006
4561
  }
4562
+ const reviewerSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4563
+ reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({ login: z.string().optional() }).nullable() })) }),
4564
+ reviews: z.object({ nodes: z.array(z.object({ state: z.string() })) })
4565
+ }) }) }) });
4566
+ /**
4567
+ * Ask the requester to review a pull request on GitHub, and return true when
4568
+ * GitHub asks them after the call.
4569
+ *
4570
+ * Junior keeps a draft for its requester when marking it ready would ask the
4571
+ * code owners. A review request asks only the person it names, and the Inbox
4572
+ * item follows from it (`webhooks/pull-request-action.ts`). A person whom
4573
+ * GitHub already asks is not asked again. Nor is a person who has reviewed
4574
+ * it, and the result is false: after a change request or a comment-only
4575
+ * review, only the review-again flow asks, and an approved draft's item says
4576
+ * to mark it ready. An approval stands when a comment follows it. A person
4577
+ * with no review yet is asked. So is one whose latest approval or change
4578
+ * request was dismissed, also with comments since: a dismissal resets their
4579
+ * decision, so those comments wait for a new ask
4580
+ * (`webhooks/pull-request-next-action.ts`).
4581
+ */
4582
+ async function requestRequesterReview(egress, repo, number, login) {
4583
+ const read = await githubApi(egress, {
4584
+ operation: "github.pull.reviewer.get",
4585
+ method: "POST",
4586
+ path: "/graphql",
4587
+ body: {
4588
+ ...PULL_REQUEST_REVIEWER,
4589
+ variables: {
4590
+ login,
4591
+ name: repo.name,
4592
+ number,
4593
+ owner: repo.owner
4594
+ }
4595
+ }
4596
+ });
4597
+ const parsed = reviewerSchema.safeParse(read.body);
4598
+ if (!read.ok || !parsed.success) {
4599
+ const message = `GitHub pull request reviewer lookup failed with HTTP ${read.status}: ${githubErrorMessage$1(read.body)}`;
4600
+ throw new Error(message);
4601
+ }
4602
+ const { pullRequest } = parsed.data.data.repository;
4603
+ const lower = login.toLowerCase();
4604
+ if (pullRequest.reviewRequests.nodes.some((node) => node.requestedReviewer?.login?.toLowerCase() === lower)) return true;
4605
+ const states = pullRequest.reviews.nodes.map((review) => review.state);
4606
+ const decided = [...states].reverse().find((state) => state !== "COMMENTED");
4607
+ if (decided ? decided !== "DISMISSED" : states.length > 0) return false;
4608
+ const response = await githubApi(egress, {
4609
+ operation: "github.pull.request_reviewers",
4610
+ method: "POST",
4611
+ path: `${repoPath(repo)}/pulls/${number}/requested_reviewers`,
4612
+ body: { reviewers: [login] }
4613
+ });
4614
+ if (!response.ok) {
4615
+ const message = `GitHub review request for ${login} failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`;
4616
+ if (response.status === 422) throw new PluginToolInputError(`${message}. Do not retry: tell them in the thread where they asked.`);
4617
+ throw new Error(message);
4618
+ }
4619
+ return true;
4620
+ }
4007
4621
  /** Update mutable PR metadata while preserving runtime-owned body attribution. */
4008
4622
  function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4009
4623
  return definePluginTool({
@@ -4023,6 +4637,8 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4023
4637
  if (descriptionChecks && update.body !== void 0) await checkPullRequestDescription(ctx.decider, update.body);
4024
4638
  const repo = parseRepo$1(update.repo);
4025
4639
  const requester = await resolveGitHubRequester(ctx);
4640
+ const reviewerLogin = update.request_review ? linkedGitHubLogin(requesterPerson(requester)?.user) : void 0;
4641
+ if (update.request_review && !reviewerLogin) throw new PluginToolInputError("The person who asked for this pull request has no linked GitHub account, so GitHub cannot ask for their review. Do not retry: tell them in the thread where they asked.");
4026
4642
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
4027
4643
  operation: "github.pull.get",
4028
4644
  path: `${repoPath(repo)}/pulls/${update.pull_request}`
@@ -4083,6 +4699,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4083
4699
  repositoryFullName: repo.ref
4084
4700
  });
4085
4701
  }
4702
+ const reviewRequested = reviewerLogin ? await requestRequesterReview(ctx.egress, repo, providerResult.number, reviewerLogin) : void 0;
4086
4703
  const subscribable = gitHubPullRequestSubscribable({
4087
4704
  canSubscribe: ctx.events.canSubscribe,
4088
4705
  number: providerResult.number,
@@ -4111,6 +4728,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
4111
4728
  objectType: "code_change",
4112
4729
  status: providerResult.merged ? "merged" : providerResult.state === "open" && providerResult.draft ? "draft" : providerResult.state
4113
4730
  })],
4731
+ ...reviewRequested !== void 0 ? { review_requested: reviewRequested } : void 0,
4114
4732
  target: "updatePullRequest",
4115
4733
  ...data
4116
4734
  };
@@ -4168,7 +4786,7 @@ const inputSchema$2 = z.object({
4168
4786
  ]).describe("Comment kind: \"conversation\" for a pull request conversation comment, \"review\" for an inline review comment, \"review_body\" for the body of a submitted review. Use the exact value from the event."),
4169
4787
  comment_id: z.number().int().positive().describe("GitHub comment id (conversation comment id, inline review comment id, or review id). Use the exact value from the event."),
4170
4788
  pull_request: z.number().int().positive().describe("Pull request number that the comment is on. Use the exact value from the event."),
4171
- status: z.enum(["addressed", "declined"]).describe("Feedback outcome. \"addressed\" (+1): you made the change or answered the question. \"declined\" (-1): you do not make the change now, such as when you push back, defer it, or leave the decision to the author.")
4789
+ status: z.enum(["addressed", "declined"]).describe("Feedback outcome. \"addressed\" (+1): you made the change, answered it, or agree and wait on the reviewer to confirm or choose. \"declined\" (-1), which reviewers read as disagreement: you push back or defer the change to later work.")
4172
4790
  }).strict();
4173
4791
  const outputSchema$2 = pluginToolOutputSchema.extend({
4174
4792
  target: z.literal("updatePullRequestFeedback"),
@@ -4296,8 +4914,22 @@ async function reviewBodyReactions(egress, input) {
4296
4914
  };
4297
4915
  }
4298
4916
  /**
4917
+ * Whether `reviewer` is the person who asked Junior for the pull request.
4918
+ * Only the opener row of a pull request that Junior opened has a
4919
+ * Conversation, and only that person's own work knows their linked GitHub
4920
+ * login, as when Junior asks them a question.
4921
+ */
4922
+ async function reviewerIsRequester(ctx, input) {
4923
+ const [opener, owner] = await Promise.all([listGitHubPullRequestOpeners(gitHubDbSchema.parse(ctx.db), {
4924
+ numbers: [input.pullRequest],
4925
+ repositoryFullName: `${input.owner}/${input.name}`
4926
+ }).then((openers) => openers.get(input.pullRequest)), ctx.resolveWorkOwner().then(requesterPerson)]);
4927
+ return (opener?.conversationId && owner?.identity?.id === opener.identityId ? linkedGitHubLogin(owner.user) : void 0)?.toLowerCase() === input.reviewer.toLowerCase();
4928
+ }
4929
+ /**
4299
4930
  * Ask the reviewer to review again when every comment of their latest
4300
- * change request is marked and the required checks pass. GitHub stops
4931
+ * change request is marked and the required checks pass. For the requester,
4932
+ * their comment-only reviews count as a change request. GitHub stops
4301
4933
  * asking a reviewer once they review, so the fixed pull request would not
4302
4934
  * wait on them. While the checks have not passed, the ask is held, and the
4303
4935
  * check suite webhook asks when they pass. The ask is optional, so a failure
@@ -4322,6 +4954,7 @@ async function askForReviewAgain(ctx, input) {
4322
4954
  return response.body;
4323
4955
  }, {
4324
4956
  ...input,
4957
+ isRequester: async () => await reviewerIsRequester(ctx, input),
4325
4958
  number: input.pullRequest
4326
4959
  });
4327
4960
  if (readiness === "none") return;
@@ -4401,7 +5034,7 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
4401
5034
  openWorldHint: true,
4402
5035
  readOnlyHint: false
4403
5036
  },
4404
- description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after you act on or reply to the feedback. Replaces only your prior status reaction on that comment. When every comment of the author's latest change request is marked and the required checks pass, asks the author to review again. Only works on pull requests the bot authored.",
5037
+ description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after you act on or reply to the feedback. Replaces only your prior status reaction on that comment. When every comment of the author's latest change request, or of the requester's latest comment-only reviews, is marked and the required checks pass, asks the author to review again. Only works on pull requests the bot authored.",
4405
5038
  exposure: "direct",
4406
5039
  inputSchema: inputSchema$2,
4407
5040
  outputSchema: outputSchema$2,
@@ -4695,211 +5328,177 @@ function createGitHubTools(botEmail, pullRequestSubscription, experimental = {})
4695
5328
  createPullRequest: createGitHubPullRequestTool(pullRequestSubscription, descriptionChecks)
4696
5329
  };
4697
5330
  }
4698
- // src/code-change-titles/parse.ts
4699
- function nativePattern(source) {
4700
- const regex = new RegExp(source, "i");
4701
- return (title) => {
4702
- const match = regex.exec(title);
4703
- return match ? {
4704
- scope: match.groups?.["scope"],
4705
- type: match.groups?.["type"]
4706
- } : void 0;
4707
- };
4708
- }
4709
- function defaultCategory(title, sources) {
4710
- return {
4711
- custom: false,
4712
- patterns: sources.map(nativePattern),
4713
- title
4714
- };
4715
- }
4716
- /** Craft's `DEFAULT_RELEASE_CONFIG` categories, in match order. */
4717
- const DEFAULT_CODE_CHANGE_CATEGORIES = [
4718
- defaultCategory("Breaking Changes", [String.raw`^(?<type>\w+(?:\((?<scope>[^)]+)\))?!:\s*)`]),
4719
- defaultCategory("Security", [String.raw`^(?<type>security(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
4720
- defaultCategory("New Features", [String.raw`^(?<type>feat(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
4721
- defaultCategory("Bug Fixes", [String.raw`^(?<type>fix(?:\((?<scope>[^)]+)\))?!?:\s*)`, String.raw`^Revert "`]),
4722
- defaultCategory("Documentation", [String.raw`^(?<type>docs?(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
4723
- defaultCategory("Internal Changes", [String.raw`^(?<type>(?:build|refactor|meta|chore|ci|ref|perf|tests?|style)(?:\((?<scope>[^)]+)\))?!?:\s*)`])
4724
- ];
4725
- const TYPE_WORDS = {
4726
- build: "Build",
4727
- chore: "Chore",
4728
- ci: "CI",
4729
- doc: "Docs",
4730
- docs: "Docs",
4731
- feat: "Feature",
4732
- fix: "Fix",
4733
- meta: "Meta",
4734
- perf: "Perf",
4735
- ref: "Refactor",
4736
- refactor: "Refactor",
4737
- revert: "Revert",
4738
- security: "Security",
4739
- style: "Style",
4740
- test: "Test",
4741
- tests: "Test"
5331
+ // src/webhooks/pull-request-item.ts
5332
+ /** Why the item closes when its pull request is no longer open. */
5333
+ const ENDED_REASONS = {
5334
+ closed: {
5335
+ reason: "The pull request closed without merging.",
5336
+ status: "dismissed"
5337
+ },
5338
+ merged: {
5339
+ reason: "The pull request merged.",
5340
+ status: "done"
5341
+ }
4742
5342
  };
4743
- const BREAKING = /^\w+(?:\([^)]+\))?!:/;
4744
- const REVERT = /^Revert "/i;
4745
- const PULL_REQUEST_SUFFIX = /\s*\(#\d+\)$/;
4746
- /** GitHub titles are at most 256 characters, so this bounds regex work. */
4747
- const MAX_TITLE_LENGTH = 256;
4748
- function capitalize(text) {
4749
- return text.charAt(0).toUpperCase() + text.slice(1);
4750
- }
4751
- /** A custom category title as one word pill, without emoji or padding. */
4752
- function categoryWord(title) {
4753
- const word = title.replace(/[\p{Extended_Pictographic}\u{FE0F}\u{200D}]/gu, "").trim();
4754
- return word && !/^breaking\b/i.test(word) ? word : void 0;
4755
- }
4756
- function typeWord(category, token, title) {
4757
- const known = token ? TYPE_WORDS[token.toLowerCase()] : void 0;
4758
- if (known) return known;
4759
- if (!token && REVERT.test(title)) return "Revert";
4760
- return category.custom ? categoryWord(category.title) : void 0;
4761
- }
4762
- function firstMatch(title, categories) {
4763
- for (const category of categories) for (const pattern of category.patterns) {
4764
- const match = pattern(title);
4765
- if (match) return {
4766
- category,
4767
- match
5343
+ /** Why the item closes when nobody on it has an ask now. */
5344
+ function closeReason(state, previous, mergeAccess) {
5345
+ if (previous === "merge") {
5346
+ if (state.autoMerge) return {
5347
+ reason: "Auto-merge is on.",
5348
+ status: "dismissed"
5349
+ };
5350
+ if (mergeAccess === false) return {
5351
+ reason: "Only a person with write access can merge it.",
5352
+ status: "dismissed"
5353
+ };
5354
+ return {
5355
+ reason: "The pull request is no longer ready to merge.",
5356
+ status: "dismissed"
4768
5357
  };
4769
5358
  }
4770
- }
4771
- /**
4772
- * Return the title parts of a pull request title, or undefined when the
4773
- * title has no conventional prefix and no breaking marker. The first
4774
- * matching category wins, as in Craft.
4775
- */
4776
- function parseCodeChangeTitle(title, categories = DEFAULT_CODE_CHANGE_CATEGORIES) {
4777
- const bounded = title.slice(0, MAX_TITLE_LENGTH);
4778
- const breaking = BREAKING.test(bounded);
4779
- const found = firstMatch(bounded, categories) ?? (breaking ? firstMatch(bounded, DEFAULT_CODE_CHANGE_CATEGORIES.slice(0, 1)) : void 0);
4780
- if (!found) return void 0;
4781
- const prefix = found.match.type;
4782
- const token = prefix ? /^\w+/.exec(prefix)?.[0] : void 0;
4783
- const rest = (prefix !== void 0 && bounded.startsWith(prefix) ? title.slice(prefix.length) : title).replace(PULL_REQUEST_SUFFIX, "").trim();
4784
- const type = typeWord(found.category, token, bounded);
4785
- const scope = found.match.scope?.trim();
4786
5359
  return {
4787
- text: rest ? capitalize(rest) : title,
4788
- ...type ? { type } : void 0,
4789
- ...scope ? { scope } : void 0,
4790
- ...breaking ? { breaking: true } : void 0
5360
+ reason: "The review request ended.",
5361
+ status: "done"
4791
5362
  };
4792
5363
  }
4793
- // src/code-change-titles/release-config.ts
4794
- /**
4795
- * A repository's changelog categories from `.github/release.yml`, the file
4796
- * that GitHub release notes and Craft read. Craft adds `commit_patterns` to
4797
- * each category. When the file has categories with patterns, they replace
4798
- * the default categories, as in Craft.
4799
- */
4800
- const MAX_CONFIG_LENGTH = 65536;
4801
- const MAX_CATEGORIES = 30;
4802
- const MAX_PATTERNS = 10;
4803
- const MAX_PATTERN_LENGTH = 200;
4804
- const releaseConfigSchema = z.object({ changelog: z.object({ categories: z.array(z.object({
4805
- commit_patterns: z.array(z.string()).optional(),
4806
- title: z.string().min(1)
4807
- })).optional() }).optional() });
4808
- function compilePattern(source) {
4809
- if (source.length > MAX_PATTERN_LENGTH) return void 0;
4810
- let regex;
4811
- try {
4812
- regex = RE2JS.compile(source, RE2JS.CASE_INSENSITIVE);
4813
- } catch {
5364
+ /** The item text that says why Junior asked for the review again. */
5365
+ const REVIEW_AGAIN_TEXT = {
5366
+ checks: "Checks now pass, and every comment is handled.",
5367
+ handled: "Every comment on your review is handled.",
5368
+ question: "A comment asks you a question."
5369
+ };
5370
+ /** The item text that gives the requester their action. */
5371
+ function requesterText(action, number, reason, state) {
5372
+ if (action === "merge") return state.reviewOutcome === "approved" ? `#${number} is approved, and GitHub says that it can merge.` : `GitHub says that #${number} can merge with no review. Review it, then merge it.`;
5373
+ const asked = reason ? REVIEW_AGAIN_TEXT[reason] : void 0;
5374
+ if (action === "review") return asked ?? `GitHub asks you to review #${number}.`;
5375
+ if (action === "mark_ready") return `You approved #${number}. Mark it ready for review.`;
5376
+ const step = `#${number} is a draft. Review it, then mark it ready for review.`;
5377
+ return asked ? `${asked} ${step}` : step;
5378
+ }
5379
+ /**
5380
+ * Add, change, or close the item of one pull request from what GitHub says
5381
+ * now. Only the people that this event gives an ask join the item and get a
5382
+ * push: the requester when their action changes, and a reviewer when GitHub
5383
+ * requests their review.
5384
+ */
5385
+ async function showPullRequestItem(items, args) {
5386
+ const { action, number, state } = args;
5387
+ const subject = pullRequestSubject(GITHUB_INBOX_SUBJECTS.pullRequest, args.pullRequestId);
5388
+ if (state.state !== "open") {
5389
+ await items.close({
5390
+ subject,
5391
+ ...ENDED_REASONS[state.state]
5392
+ });
4814
5393
  return;
4815
5394
  }
4816
- if (regex.matcher("").find()) return void 0;
4817
- const groups = regex.namedGroups();
4818
- return (title) => {
4819
- const match = regex.matcher(title);
4820
- if (!match.find()) return void 0;
4821
- return {
4822
- scope: "scope" in groups ? match.group("scope") ?? void 0 : void 0,
4823
- type: "type" in groups ? match.group("type") ?? void 0 : void 0
4824
- };
4825
- };
5395
+ const requesterAsks = action !== void 0;
5396
+ const reviewers = args.reviewerIdentityIds.filter((identityId) => identityId !== args.requester.identityId);
5397
+ const assignees = [...requesterAsks ? [args.requester.identityId] : [], ...reviewers];
5398
+ if (assignees.length === 0) {
5399
+ await items.close({
5400
+ subject,
5401
+ ...closeReason(state, args.previous, args.mergeAccess)
5402
+ });
5403
+ return;
5404
+ }
5405
+ const review = `GitHub asks you to review #${number}.`;
5406
+ const requesterLine = action && requesterText(action, number, args.reason, state);
5407
+ const lines = [...requesterLine ? [requesterLine] : [], ...reviewers.length > 0 && requesterLine !== review ? [review] : []];
5408
+ await items.upsert({
5409
+ askedIdentityIds: [...requesterAsks && args.requester.asked ? [args.requester.identityId] : [], ...args.askedReviewerIdentityIds.filter((identityId) => reviewers.includes(identityId))],
5410
+ assigneeIdentityIds: assignees,
5411
+ body: `${lines.join("\n\n")}\n\n${state.url}`,
5412
+ subject,
5413
+ title: `${action === "merge" ? "Ready to merge" : "Review requested"} · #${number}`,
5414
+ waitsOnAssignees: true
5415
+ });
4826
5416
  }
4827
- /**
4828
- * Return the changelog categories of a `.github/release.yml` text. A file
4829
- * with no usable `commit_patterns`, or one that does not parse, gives the
4830
- * default categories.
4831
- */
4832
- function parseReleaseCategories(text) {
4833
- if (text.length > MAX_CONFIG_LENGTH) return DEFAULT_CODE_CHANGE_CATEGORIES;
4834
- let raw;
4835
- try {
4836
- raw = parse$1(text, { maxAliasCount: 100 });
4837
- } catch {
4838
- return DEFAULT_CODE_CHANGE_CATEGORIES;
5417
+ // src/webhooks/pull-request-next-action.ts
5418
+ /** Whether two GitHub logins name the same account. */
5419
+ function sameLogin(a, b) {
5420
+ return b !== void 0 && a.toLowerCase() === b.toLowerCase();
5421
+ }
5422
+ /** Read the requester's latest activity from a pull request's activity. */
5423
+ function latestActivity(activity, requesterLogin) {
5424
+ const latest = {};
5425
+ const keep = (key, at) => {
5426
+ const saved = latest[key];
5427
+ if (!saved || at > saved) latest[key] = at;
5428
+ };
5429
+ for (const entry of activity) {
5430
+ if (!sameLogin(entry.login, requesterLogin)) continue;
5431
+ if (entry.kind === "reviewRequest") keep("askedAt", entry.at);
5432
+ else if (entry.kind === "reviewRequestRemoved") keep("removedAt", entry.at);
5433
+ else {
5434
+ keep("requesterAt", entry.at);
5435
+ if (entry.review !== "COMMENTED") keep("actedAt", entry.at);
5436
+ const review = entry.review && {
5437
+ at: entry.at,
5438
+ state: entry.review
5439
+ };
5440
+ if (review && (!latest.review || review.at > latest.review.at)) latest.review = review;
5441
+ if (review && review.state !== "COMMENTED" && (!latest.decided || review.at > latest.decided.at)) latest.decided = review;
5442
+ }
4839
5443
  }
4840
- const config = releaseConfigSchema.safeParse(raw);
4841
- if (!config.success) return DEFAULT_CODE_CHANGE_CATEGORIES;
4842
- const categories = (config.data.changelog?.categories ?? []).slice(0, MAX_CATEGORIES).map((category) => ({
4843
- custom: true,
4844
- patterns: (category.commit_patterns ?? []).slice(0, MAX_PATTERNS).map(compilePattern).filter((pattern) => pattern !== void 0),
4845
- title: category.title
4846
- })).filter((category) => category.patterns.length > 0);
4847
- return categories.length > 0 ? categories : DEFAULT_CODE_CHANGE_CATEGORIES;
5444
+ return latest;
4848
5445
  }
4849
- // src/webhooks/title-parts.ts
4850
- /** A repository without the file costs at most one read in this time. */
4851
- const MISSING_TTL_MS = 36e5;
4852
- const contentsSchema = z.object({
4853
- content: z.string(),
4854
- encoding: z.literal("base64")
4855
- });
4856
- function missingKey(repositoryFullName) {
4857
- return `github-release-config-missing:${repositoryFullName.toLowerCase()}`;
5446
+ /**
5447
+ * Whether the requester's latest review waits for Junior's answer: a change
5448
+ * request, or a comment-only review, which Junior handles like a change
5449
+ * request. After the requester approves, only a comment-only review after
5450
+ * a later ask counts, so a comment on an approved pull request leaves it
5451
+ * ready to merge. A dismissed review, such as an approval that a push
5452
+ * reset, works the same way: a comment since it waits for a new ask, so a
5453
+ * ready pull request is in limbo and Junior asks. A draft cannot merge, so
5454
+ * it is left out.
5455
+ */
5456
+ function requesterFeedback(state, activity) {
5457
+ const { decided, review } = activity;
5458
+ if (state.draft || !review) return false;
5459
+ if (review.state === "CHANGES_REQUESTED") return true;
5460
+ if (review.state !== "COMMENTED") return false;
5461
+ if (decided?.state !== "APPROVED" && decided?.state !== "DISMISSED") return true;
5462
+ const askedAt = timeOf(activity.askedAt);
5463
+ return askedAt > decided.at.getTime() && review.at.getTime() > askedAt;
5464
+ }
5465
+ /** A time in milliseconds. A missing time is older than every time. */
5466
+ function timeOf(at) {
5467
+ return at ? at.getTime() : Number.NEGATIVE_INFINITY;
4858
5468
  }
4859
5469
  /**
4860
- * Read a repository's changelog categories from GitHub with a read-only
4861
- * token. The file is read with its ETag, and a missing file is remembered
4862
- * for an hour in `env.responses`.
5470
+ * Derive the requester's next action. Return undefined when it cannot be
5471
+ * known yet, so a later event decides.
4863
5472
  */
4864
- async function loadReleaseCategories(env, repositoryFullName) {
4865
- const [owner, name] = repositoryFullName.split("/");
4866
- if (!owner || !name) return DEFAULT_CODE_CHANGE_CATEGORIES;
4867
- const state = env.responses;
4868
- if (await state?.get(missingKey(repositoryFullName)).catch(() => void 0)) return DEFAULT_CODE_CHANGE_CATEGORIES;
4869
- const token = await issueInstallationToken({
4870
- ...env,
4871
- permissions: { contents: "read" },
4872
- repositories: [name]
4873
- });
4874
- let response;
4875
- try {
4876
- response = await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/contents/.github/release.yml`, {
4877
- responses: state,
4878
- token: token.token
4879
- });
4880
- } catch (error) {
4881
- if (!(error instanceof GitHubRequestError) || error.status !== 404) throw error;
4882
- await state?.set(missingKey(repositoryFullName), true, MISSING_TTL_MS).catch(() => void 0);
4883
- return DEFAULT_CODE_CHANGE_CATEGORIES;
4884
- }
4885
- const file = contentsSchema.safeParse(response);
4886
- if (!file.success) return DEFAULT_CODE_CHANGE_CATEGORIES;
4887
- return parseReleaseCategories(Buffer.from(file.data.content, "base64").toString("utf8"));
5473
+ function nextAction(state, requester, saved) {
5474
+ if (state.state !== "open") return {};
5475
+ const canMerge = requester.mergeAccess && !state.draft && !state.autoMerge && !state.reviewPending && !requester.feedback;
5476
+ if (canMerge && state.mergeableState === "clean" && state.reviewOutcome !== "changesRequested") return { action: "merge" };
5477
+ if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5478
+ const review = state.draft ? "review_draft" : "review";
5479
+ if (requester.askedAgain) return { action: review };
5480
+ if (isRequested(state, requester.login) && (!requester.actedLast || !requester.feedback)) return { action: review };
5481
+ if (state.draft && state.requesterApproved) return { action: "mark_ready" };
5482
+ if (canMerge && !state.mergeableState) return void 0;
5483
+ return {};
5484
+ }
5485
+ function isRequested(state, login) {
5486
+ const lower = login?.toLowerCase();
5487
+ return state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === lower);
4888
5488
  }
4889
5489
  /**
4890
- * Return the title parts of a pull request title with its repository's
4891
- * changelog categories. Title parts are optional, so a failed read of the
4892
- * categories is logged, and the default categories apply.
5490
+ * Whether a pull request whose action is none is in limbo: it waits on
5491
+ * nobody, so Junior asks for the requester's review on GitHub. It is open,
5492
+ * not a draft, and auto-merge is off. GitHub does not ask the requester
5493
+ * for a review, and the requester's feedback does not wait for Junior. The
5494
+ * requester has not reviewed since the last push, other than a comment-only
5495
+ * review. No reviewer approved it, so it does not wait only on others, and
5496
+ * no reviewer requests changes, so Junior does not act next. Junior does
5497
+ * not ask when the requester removed their own review request and no one
5498
+ * asked them since.
4893
5499
  */
4894
- async function loadGitHubTitleParts(env, input, log) {
4895
- let categories;
4896
- try {
4897
- categories = await loadReleaseCategories(env, input.repositoryFullName);
4898
- } catch (error) {
4899
- logFailOpenFailure(log, "GitHub release config read failed", error, { repository: input.repositoryFullName });
4900
- categories = DEFAULT_CODE_CHANGE_CATEGORIES;
4901
- }
4902
- return parseCodeChangeTitle(input.title, categories);
5500
+ function inLimbo(state, activity, login) {
5501
+ return state.state === "open" && !state.draft && !state.autoMerge && !isRequested(state, login) && !requesterFeedback(state, activity) && timeOf(activity.removedAt) <= timeOf(activity.askedAt) && timeOf(activity.actedAt) <= timeOf(state.headCommittedAt) && state.reviewOutcome === void 0;
4903
5502
  }
4904
5503
  // src/pull-request-outcomes/store.ts
4905
5504
  /** One pull request lifecycle outcome, as the webhook and reconcile read it. */
@@ -4959,9 +5558,10 @@ async function findGitHubPullRequest(codeChanges, ref) {
4959
5558
  /**
4960
5559
  * Ask to check the next action of a Junior pull request, and claim the check
4961
5560
  * when no other webhook runs one. A claim older than `staleMs` is free.
4962
- * Return the claim and the saved action, or undefined when another webhook
4963
- * runs the check or Junior does not own the pull request. The webhook that
4964
- * runs the check sees the new request in `releaseGitHubPullRequestReadySync`.
5561
+ * Return the claim and the saved action, `held` when another webhook runs
5562
+ * the check, or undefined when Junior does not own the pull request. The
5563
+ * webhook that runs the check sees the new request in
5564
+ * `releaseGitHubPullRequestReadySync`.
4965
5565
  */
4966
5566
  async function claimGitHubPullRequestReadySync(db, pullRequestId, options) {
4967
5567
  const t = juniorGitHubPullRequests;
@@ -4976,7 +5576,8 @@ async function claimGitHubPullRequestReadySync(db, pullRequestId, options) {
4976
5576
  id: t.readySyncId,
4977
5577
  requests: t.readySyncRequests
4978
5578
  });
4979
- if (!row || row.id !== row.requests) return void 0;
5579
+ if (!row) return void 0;
5580
+ if (row.id !== row.requests) return "held";
4980
5581
  return {
4981
5582
  action: row.action ?? void 0,
4982
5583
  id: row.id,
@@ -5097,43 +5698,26 @@ function gitHubConflictAction(input) {
5097
5698
  const fixedAtMs = Math.max(resumedAtMs ?? 0, ...fixes.map(({ atMs }) => atMs));
5098
5699
  return !approved && nowMs - fixedAtMs < FIX_INTERVAL_MS ? "skip" : "fix";
5099
5700
  }
5100
- const ITEM_KEY_PREFIX = "merge-conflict:";
5101
- /** The dedupe key of the merge conflict item of one pull request. */
5102
- function gitHubConflictItemKey(ref) {
5103
- return `${ITEM_KEY_PREFIX}${ref.repositoryFullName.toLowerCase()}#${ref.number}`;
5104
- }
5105
- /** Read the pull request of a merge conflict item's dedupe key. */
5106
- function parseGitHubConflictItemKey(dedupeKey) {
5107
- const match = /^([^/#\s]+\/[^/#\s]+)#(\d+)$/.exec(dedupeKey.startsWith(ITEM_KEY_PREFIX) ? dedupeKey.slice(15) : "");
5108
- return match ? {
5109
- number: Number(match[2]),
5110
- repositoryFullName: match[1]
5111
- } : void 0;
5112
- }
5113
5701
  /** Ask the requester to resume a fix that did not land. */
5114
5702
  async function addUnlandedItem(args) {
5115
- const { conflict, ref, title } = args;
5703
+ const { conflict, ref } = args;
5116
5704
  const opener = (await listGitHubPullRequestOpeners(args.db, {
5117
5705
  numbers: [ref.number],
5118
5706
  repositoryFullName: ref.repositoryFullName
5119
5707
  })).get(ref.number);
5120
5708
  if (!opener?.conversationId) return;
5121
- const url = conflict.url ?? `https://github.com/${ref.repositoryFullName}/pull/${ref.number}`;
5122
- const titleParts = title ? await args.loadTitleParts?.({
5123
- repositoryFullName: ref.repositoryFullName,
5124
- title
5125
- }) : void 0;
5709
+ if (!opener.pullRequestId) await recordGitHubPullRequestOpenerId(args.db, {
5710
+ conversationId: opener.conversationId,
5711
+ number: ref.number,
5712
+ pullRequestId: args.pullRequestId,
5713
+ repositoryFullName: ref.repositoryFullName
5714
+ });
5126
5715
  await args.inboxItems.forConversation(opener.conversationId).upsert({
5716
+ askedIdentityIds: [opener.identityId],
5127
5717
  assigneeIdentityIds: [opener.identityId],
5128
5718
  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.`,
5129
5719
  choices: [{ label: GITHUB_CONFLICT_RESUME }],
5130
- dedupeKey: gitHubConflictItemKey(ref),
5131
- subject: {
5132
- id: url,
5133
- title: title ? `${title} (#${ref.number})` : url,
5134
- ...titleParts ? { titleParts } : void 0,
5135
- url
5136
- },
5720
+ subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, args.pullRequestId),
5137
5721
  title: `Merge conflict · #${ref.number}`
5138
5722
  });
5139
5723
  }
@@ -5174,7 +5758,10 @@ async function applyGitHubConflictPolicy(args) {
5174
5758
  return args.events;
5175
5759
  }
5176
5760
  try {
5177
- await addUnlandedItem(args);
5761
+ await addUnlandedItem({
5762
+ ...args,
5763
+ pullRequestId: change.providerId
5764
+ });
5178
5765
  await args.db.update(t).set({ conflictFixAskedAt: args.now }).where(pullRequest);
5179
5766
  } catch (error) {
5180
5767
  logFailOpenFailure(args.log, "GitHub merge conflict item failed", error, {
@@ -5198,7 +5785,7 @@ async function closeGitHubConflictItem(args) {
5198
5785
  })).get(ref.number);
5199
5786
  if (!opener?.conversationId) return;
5200
5787
  await args.inboxItems.forConversation(opener.conversationId).close({
5201
- dedupeKey: gitHubConflictItemKey(ref),
5788
+ subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, args.pullRequestId),
5202
5789
  reason: args.reason,
5203
5790
  status: args.status
5204
5791
  });
@@ -5222,18 +5809,13 @@ async function closeGitHubConflictItems(args) {
5222
5809
  } })]);
5223
5810
  const pullRequestIds = new Map(changes.map((change) => [change.number, change.providerId]));
5224
5811
  const limit = pLimit(ITEM_CLOSE_CONCURRENCY);
5225
- const close = async (number, conversationId) => {
5812
+ const close = async (number, conversationId, pullRequestId) => {
5226
5813
  try {
5227
- const closed = await args.inboxItems.forConversation(conversationId).close({
5228
- dedupeKey: gitHubConflictItemKey({
5229
- number,
5230
- repositoryFullName
5231
- }),
5814
+ if (await args.inboxItems.forConversation(conversationId).close({
5815
+ subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, pullRequestId),
5232
5816
  reason: args.reason,
5233
5817
  status: args.status
5234
- });
5235
- const pullRequestId = pullRequestIds.get(number);
5236
- if (closed && pullRequestId) await args.db.update(juniorGitHubPullRequests).set({ conflictFixAskedAt: null }).where(eq(juniorGitHubPullRequests.pullRequestId, pullRequestId));
5818
+ })) await args.db.update(juniorGitHubPullRequests).set({ conflictFixAskedAt: null }).where(eq(juniorGitHubPullRequests.pullRequestId, pullRequestId));
5237
5819
  } catch (error) {
5238
5820
  logFailOpenFailure(args.log, "GitHub merge conflict item close failed", error, {
5239
5821
  number,
@@ -5241,7 +5823,28 @@ async function closeGitHubConflictItems(args) {
5241
5823
  });
5242
5824
  }
5243
5825
  };
5244
- await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
5826
+ await Promise.all([...openers].flatMap(([number, { conversationId }]) => {
5827
+ const pullRequestId = pullRequestIds.get(number);
5828
+ return conversationId && pullRequestId ? [limit(() => close(number, conversationId, pullRequestId))] : [];
5829
+ }));
5830
+ }
5831
+ // src/webhooks/review-requests.ts
5832
+ const REQUESTED_TTL_MS = 36e5;
5833
+ const STATE_CALLS = 5;
5834
+ function requestedKey(target, login) {
5835
+ return `pull-request-review-requested:${target.repositoryFullName.toLowerCase()}#${target.number}:${login.toLowerCase()}`;
5836
+ }
5837
+ /** Save a review request until a check of its pull request asks the reviewer. */
5838
+ async function markGitHubReviewRequested(state, target, login) {
5839
+ await state.set(requestedKey(target, login), true, REQUESTED_TTL_MS);
5840
+ }
5841
+ /** Return the lowercase logins among `logins` that have a saved request. */
5842
+ async function readGitHubReviewRequested(state, target, logins) {
5843
+ return (await pLimit(STATE_CALLS).map(logins, async (login) => await state.get(requestedKey(target, login)) === true ? [login.toLowerCase()] : [])).flat();
5844
+ }
5845
+ /** Drop the saved requests of reviewers that a check asked. */
5846
+ async function dropGitHubReviewRequested(state, target, logins) {
5847
+ await pLimit(STATE_CALLS).map(logins, async (login) => await state.delete(requestedKey(target, login)));
5245
5848
  }
5246
5849
  // src/webhooks/graphql-request.ts
5247
5850
  /**
@@ -5252,9 +5855,12 @@ async function closeGitHubConflictItems(args) {
5252
5855
  * HTTP 200, such as when the installation is rate limited.
5253
5856
  */
5254
5857
  var GitHubGraphqlError = class extends Error {
5255
- constructor(message) {
5858
+ /** GitHub's error types, such as `RATE_LIMIT`. GitHub's own failures have none. */
5859
+ types;
5860
+ constructor(message, types) {
5256
5861
  super(message);
5257
5862
  this.name = "GitHubGraphqlError";
5863
+ this.types = types;
5258
5864
  }
5259
5865
  };
5260
5866
  const graphqlFailureSchema = z.object({
@@ -5275,7 +5881,7 @@ async function githubGraphqlRequest(params) {
5275
5881
  method: "POST"
5276
5882
  });
5277
5883
  const failure = graphqlFailureSchema.safeParse(response);
5278
- if (failure.success) throw new GitHubGraphqlError(failure.data.errors.map((error) => error.type ? `${error.type}: ${error.message}` : error.message).join("; "));
5884
+ if (failure.success) throw new GitHubGraphqlError(failure.data.errors.map((error) => error.type ? `${error.type}: ${error.message}` : error.message).join("; "), failure.data.errors.flatMap((error) => error.type ? [error.type] : []));
5279
5885
  return response;
5280
5886
  }
5281
5887
  // src/webhooks/installation-requests.ts
@@ -5319,6 +5925,22 @@ async function loadPullRequest(env, pullRequest) {
5319
5925
  token: token.token
5320
5926
  });
5321
5927
  }
5928
+ const rateLimitSchema = z.object({ resources: z.object({ graphql: z.object({ reset: z.number().int() }) }) });
5929
+ /**
5930
+ * Read when the installation's GraphQL rate limit resets, with the same
5931
+ * read-only token as the pull request reads. GitHub does not count this
5932
+ * read against the rate limit.
5933
+ */
5934
+ async function loadGraphqlRateLimitReset(env, repositoryFullName) {
5935
+ const { name } = splitRepository(repositoryFullName, "rate limit");
5936
+ const token = await issueInstallationToken({
5937
+ ...env,
5938
+ permissions: { pull_requests: "read" },
5939
+ repositories: [name]
5940
+ });
5941
+ const response = rateLimitSchema.parse(await githubRequest("https://api.github.com", "/rate_limit", { token: token.token }));
5942
+ return /* @__PURE__ */ new Date(response.resources.graphql.reset * 1e3);
5943
+ }
5322
5944
  /**
5323
5945
  * Return a reader of repository full names by repository id, with one
5324
5946
  * metadata-only token for every repository of the installation. The reader
@@ -5522,13 +6144,13 @@ const repositoryPermissionSchema = z.object({
5522
6144
  });
5523
6145
  const REPOSITORY_ROLE_TTL_MS = 6e5;
5524
6146
  /**
5525
- * Read one user's role on a repository, with a metadata-only token. GitHub
5526
- * returns "none" for accounts without access, such as most bots. Roles are
5527
- * cached for ten minutes.
6147
+ * Read one user's access to a repository, with a metadata-only token.
6148
+ * GitHub returns "none" for accounts without access, such as most bots. It
6149
+ * is cached for ten minutes.
5528
6150
  */
5529
- async function loadRepositoryRole(env, cache, target) {
6151
+ async function loadRepositoryPermission(env, cache, target) {
5530
6152
  const { owner, name } = splitRepository(target.repositoryFullName, "repository role");
5531
- return await cache.getOrLoad(`repository-role:${owner}/${name}:${target.login}`.toLowerCase(), async () => {
6153
+ return await cache.getOrLoad(`repository-permission:${owner}/${name}:${target.login}`.toLowerCase(), async () => {
5532
6154
  const token = await issueInstallationToken({
5533
6155
  ...env,
5534
6156
  permissions: { metadata: "read" },
@@ -5539,11 +6161,26 @@ async function loadRepositoryRole(env, cache, target) {
5539
6161
  token: token.token
5540
6162
  }));
5541
6163
  return {
5542
- value: response.role_name?.trim() || response.permission,
6164
+ value: {
6165
+ permission: response.permission,
6166
+ role: response.role_name?.trim() || response.permission
6167
+ },
5543
6168
  ttlMs: REPOSITORY_ROLE_TTL_MS
5544
6169
  };
5545
6170
  });
5546
6171
  }
6172
+ /** Read one user's role on a repository, such as "maintain" or "none". */
6173
+ async function loadRepositoryRole(env, cache, target) {
6174
+ return (await loadRepositoryPermission(env, cache, target)).role;
6175
+ }
6176
+ /**
6177
+ * Whether one user can merge pull requests on a repository: their base role
6178
+ * is write or admin. Maintain and custom roles map to one of these.
6179
+ */
6180
+ async function loadRepositoryMergeAccess(env, cache, target) {
6181
+ const { permission } = await loadRepositoryPermission(env, cache, target);
6182
+ return permission === "admin" || permission === "write";
6183
+ }
5547
6184
  const timestampSchema$1 = z.iso.datetime({ offset: true });
5548
6185
  function nodesSchema(node) {
5549
6186
  return z.array(node.nullable()).transform((items) => items.filter((item) => item !== null));
@@ -5569,6 +6206,7 @@ const userLoginSchema = z.object({
5569
6206
  }).nullable();
5570
6207
  const nextActionSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
5571
6208
  autoMergeRequest: z.object({}).nullable(),
6209
+ commits: z.object({ nodes: nodesSchema(z.object({ commit: z.object({ committedDate: timestampSchema$1 }) })) }),
5572
6210
  isDraft: z.boolean(),
5573
6211
  mergeStateStatus: z.string(),
5574
6212
  reviewRequests: z.object({ nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })) }),
@@ -5578,15 +6216,24 @@ const nextActionSchema = z.object({ data: z.object({ repository: z.object({ pull
5578
6216
  "MERGED",
5579
6217
  "OPEN"
5580
6218
  ]),
5581
- timelineItems: z.object({ nodes: nodesSchema(z.discriminatedUnion("__typename", [z.object({
5582
- __typename: z.literal("IssueComment"),
5583
- author: actorSchema,
5584
- createdAt: timestampSchema$1
5585
- }), z.object({
5586
- __typename: z.literal("ReviewRequestedEvent"),
5587
- createdAt: timestampSchema$1,
5588
- requestedReviewer: userLoginSchema
5589
- })])) }),
6219
+ timelineItems: z.object({ nodes: nodesSchema(z.discriminatedUnion("__typename", [
6220
+ z.object({
6221
+ __typename: z.literal("IssueComment"),
6222
+ author: actorSchema,
6223
+ createdAt: timestampSchema$1
6224
+ }),
6225
+ z.object({
6226
+ __typename: z.literal("ReviewRequestedEvent"),
6227
+ createdAt: timestampSchema$1,
6228
+ requestedReviewer: userLoginSchema
6229
+ }),
6230
+ z.object({
6231
+ __typename: z.literal("ReviewRequestRemovedEvent"),
6232
+ actor: actorSchema,
6233
+ createdAt: timestampSchema$1,
6234
+ requestedReviewer: userLoginSchema
6235
+ })
6236
+ ])) }),
5590
6237
  title: z.string(),
5591
6238
  url: z.string().url()
5592
6239
  }) }) }) });
@@ -5648,18 +6295,26 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
5648
6295
  kind: "reviewRequest",
5649
6296
  login: item.requestedReviewer.login
5650
6297
  });
6298
+ else if (item.__typename === "ReviewRequestRemovedEvent" && item.requestedReviewer?.login && item.actor && restLogin(item.actor).toLowerCase() === item.requestedReviewer.login.toLowerCase()) activity.push({
6299
+ at: new Date(item.createdAt),
6300
+ kind: "reviewRequestRemoved",
6301
+ login: item.requestedReviewer.login
6302
+ });
5651
6303
  for (const review of reviews) if (review.author && review.submittedAt) activity.push({
5652
6304
  at: new Date(review.submittedAt),
5653
6305
  kind: "author",
5654
- login: restLogin(review.author)
6306
+ login: restLogin(review.author),
6307
+ review: review.state
5655
6308
  });
5656
6309
  const mergeableState = unknown(pull.mergeStateStatus) ? void 0 : pull.mergeStateStatus.toLowerCase();
6310
+ const headCommittedAt = pull.commits.nodes[0]?.commit.committedDate;
5657
6311
  const state = {
5658
6312
  activity,
5659
6313
  autoMerge: Boolean(pull.autoMergeRequest),
5660
- changesRequested: false,
5661
6314
  draft: pull.isDraft,
6315
+ ...headCommittedAt ? { headCommittedAt: new Date(headCommittedAt) } : void 0,
5662
6316
  ...mergeableState ? { mergeableState } : void 0,
6317
+ requesterApproved: false,
5663
6318
  requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" && request.requestedReviewer.login ? [request.requestedReviewer.login] : []),
5664
6319
  reviewPending: pull.reviewRequests.nodes.length > 0,
5665
6320
  reviewedBy: [],
@@ -5667,19 +6322,17 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
5667
6322
  title: pull.title,
5668
6323
  url: pull.url
5669
6324
  };
5670
- if (!open) return state;
5671
6325
  const latest = /* @__PURE__ */ new Map();
5672
6326
  for (const review of reviews) if (review.author && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.author.login.toLowerCase(), review);
6327
+ const login = requesterLogin?.toLowerCase();
6328
+ state.requesterApproved = (login ? latest.get(login) : void 0)?.state === "APPROVED";
6329
+ if (!open) return state;
5673
6330
  const latestSubmitted = /* @__PURE__ */ new Map();
5674
6331
  for (const review of reviews) if (review.author && review.submittedAt && review.state !== "PENDING") latestSubmitted.set(review.author.login.toLowerCase(), review.state);
5675
6332
  state.reviewedBy = [...latestSubmitted].flatMap(([login, reviewState]) => reviewState === "DISMISSED" ? [] : [login]);
5676
6333
  const reviewStates = [...latest.values()].map((review) => review.state);
5677
- if (!state.autoMerge && state.mergeableState === "clean") {
5678
- if (reviewStates.includes("CHANGES_REQUESTED")) state.reviewOutcome = "changesRequested";
5679
- else if (reviewStates.includes("APPROVED")) state.reviewOutcome = "approved";
5680
- }
5681
- const login = requesterLogin?.toLowerCase();
5682
- state.changesRequested = (login ? latest.get(login) : void 0)?.state === "CHANGES_REQUESTED";
6334
+ if (reviewStates.includes("CHANGES_REQUESTED")) state.reviewOutcome = "changesRequested";
6335
+ else if (reviewStates.includes("APPROVED")) state.reviewOutcome = "approved";
5683
6336
  return state;
5684
6337
  }
5685
6338
  // src/webhooks/pull-request-action.ts
@@ -5704,30 +6357,12 @@ const ACTION_EVENTS = {
5704
6357
  ]),
5705
6358
  pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
5706
6359
  };
5707
- /**
5708
- * Keys of the two items that came before the one item per pull request.
5709
- * Each check closes them, so no old item stays open next to the new one.
5710
- * Remove them when no item from before is open.
5711
- */
5712
- const LEGACY_DEDUPE_PREFIXES = ["pull-request-ready:", "pull-request-review-requested:"];
5713
- function itemName(target) {
5714
- return `${target.repositoryFullName}#${target.number}`.toLowerCase();
5715
- }
5716
- function actionDedupeKey(target) {
5717
- return `pull-request-action:${itemName(target)}`;
5718
- }
5719
- async function closeLegacyItems(items, name) {
5720
- await Promise.all(LEGACY_DEDUPE_PREFIXES.map((prefix) => items.close({
5721
- dedupeKey: `${prefix}${name}`,
5722
- reason: "One item now shows the next action.",
5723
- status: "dismissed"
5724
- })));
5725
- }
5726
6360
  const repositorySchema$3 = z.object({ full_name: z.string().min(1) });
5727
6361
  const pullRequestWebhookSchema = z.object({
5728
6362
  action: z.string(),
5729
6363
  pull_request: z.object({ number: z.number().int().positive() }),
5730
- repository: repositorySchema$3
6364
+ repository: repositorySchema$3,
6365
+ requested_reviewer: z.object({ login: z.string().min(1) }).nullish()
5731
6366
  });
5732
6367
  const commentWebhookSchema = z.object({
5733
6368
  action: z.literal("created"),
@@ -5757,110 +6392,19 @@ function pullRequestActionTargets(eventName, body) {
5757
6392
  const actions = ACTION_EVENTS[eventName];
5758
6393
  const parsed = pullRequestWebhookSchema.safeParse(body);
5759
6394
  if (!actions || !parsed.success || !actions.has(parsed.data.action)) return [];
6395
+ const reviewer = parsed.data.action === "review_requested" ? parsed.data.requested_reviewer?.login : void 0;
5760
6396
  return [{
5761
6397
  number: parsed.data.pull_request.number,
5762
- repositoryFullName: parsed.data.repository.full_name
6398
+ repositoryFullName: parsed.data.repository.full_name,
6399
+ ...reviewer ? { reviewRequested: reviewer } : void 0
5763
6400
  }];
5764
6401
  }
5765
- function sameLogin(a, b) {
5766
- return b !== void 0 && a.toLowerCase() === b.toLowerCase();
5767
- }
5768
- function latestActivity(activity, requesterLogin) {
5769
- const latest = {};
5770
- for (const entry of activity) {
5771
- if (!sameLogin(entry.login, requesterLogin)) continue;
5772
- const key = entry.kind === "reviewRequest" ? "askedAt" : "requesterAt";
5773
- const saved = latest[key];
5774
- if (!saved || entry.at > saved) latest[key] = entry.at;
5775
- }
5776
- return latest;
5777
- }
5778
- function timeOf(at) {
5779
- return at ? at.getTime() : Number.NEGATIVE_INFINITY;
5780
- }
5781
- /**
5782
- * Derive the requester's next action. Return undefined when it cannot be
5783
- * known yet, so a later event decides.
5784
- */
5785
- function nextAction(state, requester, saved) {
5786
- if (state.state !== "open") return {};
5787
- const canMerge = !state.draft && !state.autoMerge && !state.reviewPending;
5788
- if (canMerge && state.mergeableState === "clean" && state.reviewOutcome !== "changesRequested") return { action: "merge" };
5789
- if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5790
- if (requester.askedAgain) return { action: "review" };
5791
- if (isRequested(state, requester.login) && (!requester.actedLast || !state.changesRequested)) return { action: "review" };
5792
- if (canMerge && !state.mergeableState) return void 0;
5793
- return {};
5794
- }
5795
- function isRequested(state, login) {
5796
- const lower = login?.toLowerCase();
5797
- return state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === lower);
5798
- }
5799
- /** Why an item closes when its pull request is no longer open. */
5800
- const ENDED_REASONS = {
5801
- closed: {
5802
- reason: "The pull request closed without merging.",
5803
- status: "dismissed"
5804
- },
5805
- merged: {
5806
- reason: "The pull request merged.",
5807
- status: "done"
5808
- }
5809
- };
5810
- function endedReason(state) {
5811
- return state === "open" ? void 0 : ENDED_REASONS[state];
5812
- }
5813
- function closeReason(state, previous) {
5814
- const ended = endedReason(state.state);
5815
- if (ended) return ended;
5816
- if (previous === "review") return {
5817
- reason: "The review request ended.",
5818
- status: "done"
5819
- };
5820
- if (state.autoMerge) return {
5821
- reason: "Auto-merge is on.",
5822
- status: "dismissed"
5823
- };
5824
- return {
5825
- reason: "The pull request is no longer ready to merge.",
5826
- status: "dismissed"
5827
- };
5828
- }
5829
- /** The item text that says why Junior asked for the review again. */
5830
- const REVIEW_AGAIN_TEXT = {
5831
- checks: "Checks now pass, and every comment is handled.",
5832
- handled: "Every comment on your change request is handled."
5833
- };
5834
- function actionText(action, number, reason, state) {
5835
- if (action === "review") return reason ? REVIEW_AGAIN_TEXT[reason] : `GitHub asks you to review #${number}.`;
5836
- return state.reviewOutcome === "approved" ? `#${number} is approved, and GitHub says that it can merge.` : `GitHub says that #${number} can merge with no review. Review it, then merge it.`;
5837
- }
5838
- async function showAction(items, args) {
5839
- const { action, number, state } = args;
5840
- if (action) await items.upsert({
5841
- assigneeIdentityIds: [args.identityId],
5842
- body: `${actionText(action, number, args.reason, state)}\n\n${state.url}`,
5843
- dedupeKey: args.dedupeKey,
5844
- subject: {
5845
- id: state.url,
5846
- title: `${state.title} (#${number})`,
5847
- ...args.titleParts ? { titleParts: args.titleParts } : void 0,
5848
- url: state.url
5849
- },
5850
- title: action === "merge" ? `Ready to merge · #${number}` : `Review requested · #${number}`,
5851
- waitsOnAssignees: true
5852
- });
5853
- else if (args.previous) await items.close({
5854
- dedupeKey: args.dedupeKey,
5855
- ...closeReason(state, args.previous)
5856
- });
5857
- }
5858
6402
  /**
5859
- * Return the closes of the next-action item and the merge conflict notice
5860
- * of a pull request that merged or closed, with the conversation that owns
5861
- * them. Undefined when no person asked Junior for the pull request. The
5862
- * outcome write saves them in one batch with that conversation's chip, so no
5863
- * reader sees an ended pull request next to its open item.
6403
+ * Return the close of the item of a pull request that merged or closed,
6404
+ * with the conversation that owns it. Undefined when no person asked Junior
6405
+ * for the pull request. The outcome write saves it in one batch with that
6406
+ * conversation's chip, so no reader sees an ended pull request next to its
6407
+ * open item.
5864
6408
  */
5865
6409
  async function endedGitHubPullRequestItemChanges(args) {
5866
6410
  const { target } = args;
@@ -5872,9 +6416,9 @@ async function endedGitHubPullRequestItemChanges(args) {
5872
6416
  const reason = ENDED_REASONS[args.state];
5873
6417
  return {
5874
6418
  conversationId,
5875
- inboxItems: [actionDedupeKey(target), gitHubConflictItemKey(target)].map((dedupeKey) => ({
6419
+ inboxItems: [GITHUB_INBOX_SUBJECTS.pullRequest, GITHUB_INBOX_SUBJECTS.mergeConflict].map((kind) => ({
5876
6420
  close: {
5877
- dedupeKey,
6421
+ subject: pullRequestSubject(kind, target.pullRequestId),
5878
6422
  ...reason
5879
6423
  },
5880
6424
  conversationId
@@ -5909,7 +6453,7 @@ async function requestReviewAgain(args, target, login) {
5909
6453
  * reviewer commented or reviewed since, or when their change request is no
5910
6454
  * longer ready.
5911
6455
  */
5912
- async function askHeldReview(args, target, state) {
6456
+ async function askHeldReview(args, target, state, requesterLogin) {
5913
6457
  const held = await readHeldGitHubReviewAsk(args.state, target);
5914
6458
  if (!held) return void 0;
5915
6459
  const heldAt = new Date(held.at);
@@ -5922,6 +6466,7 @@ async function askHeldReview(args, target, state) {
5922
6466
  const [owner = "", name = ""] = target.repositoryFullName.split("/");
5923
6467
  const readiness = await readReviewAgainReadiness(await loadReviewAgainReader(args.env, target.repositoryFullName), {
5924
6468
  botUserId,
6469
+ isRequester: async () => sameLogin(held.reviewer, requesterLogin),
5925
6470
  marked: held.marked,
5926
6471
  name,
5927
6472
  number: target.number,
@@ -5939,15 +6484,19 @@ async function askHeldReview(args, target, state) {
5939
6484
  await dropHeldGitHubReviewAsk(args.state, target);
5940
6485
  }
5941
6486
  /**
5942
- * Return why Junior asked the requester again, if it did: the reason of the
5943
- * held ask that this sync released, or `handled` when the feedback tool
5944
- * asked them and they have not acted since.
6487
+ * Return why Junior asked the requester, if it did: the reason of the held
6488
+ * ask that this sync released, or the reason of the mark that a Junior tool
6489
+ * wrote when it asked them, if they have not acted since.
5945
6490
  */
5946
6491
  async function askReason(state, target, args) {
5947
- if (args.asked !== void 0) return sameLogin(args.asked.reviewer, args.requesterLogin) ? args.asked.reason : void 0;
6492
+ if (args.asked !== void 0) return sameLogin(args.asked.reviewer, args.requesterLogin) ? { reason: args.asked.reason } : void 0;
5948
6493
  const asked = await readGitHubReviewAsked(state, target);
5949
- return asked && sameLogin(asked.reviewer, args.requesterLogin) && timeOf(args.requesterAt) <= Date.parse(asked.at) ? "handled" : void 0;
6494
+ return asked && sameLogin(asked.reviewer, args.requesterLogin) && timeOf(args.requesterAt) <= Date.parse(asked.at) ? {
6495
+ mark: asked,
6496
+ reason: asked.reason ?? "handled"
6497
+ } : void 0;
5950
6498
  }
6499
+ /** Read one Junior pull request from GitHub and change its items. */
5951
6500
  async function syncOne(args, target) {
5952
6501
  const opener = (await listGitHubPullRequestOpeners(args.db, {
5953
6502
  numbers: [target.number],
@@ -5955,57 +6504,100 @@ async function syncOne(args, target) {
5955
6504
  })).get(target.number);
5956
6505
  if (!opener?.conversationId) return;
5957
6506
  const items = args.inboxItems.forConversation(opener.conversationId);
5958
- const name = itemName(target);
5959
- const dedupeKey = actionDedupeKey(target);
5960
6507
  const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
5961
6508
  if (target.commentBy !== void 0 && !sameLogin(target.commentBy, requesterLogin)) return;
5962
6509
  const pullRequestId = (await findGitHubPullRequest(args.codeChanges, target))?.providerId;
5963
6510
  if (!pullRequestId) return;
6511
+ if (!opener.pullRequestId) await recordGitHubPullRequestOpenerId(args.db, {
6512
+ conversationId: opener.conversationId,
6513
+ number: target.number,
6514
+ pullRequestId,
6515
+ repositoryFullName: target.repositoryFullName
6516
+ });
6517
+ if (target.reviewRequested) await markGitHubReviewRequested(args.state, target, target.reviewRequested);
5964
6518
  const claim = await claimGitHubPullRequestReadySync(args.db, pullRequestId, {
5965
6519
  now: /* @__PURE__ */ new Date(),
5966
6520
  staleMs: READY_SYNC_STALE_MS
5967
6521
  });
6522
+ if (claim === "held") return "busy";
5968
6523
  if (!claim) return;
5969
6524
  const { id } = claim;
5970
6525
  let saved = claim.action;
5971
6526
  let requests = claim.requests;
5972
6527
  let failure;
6528
+ let askedRequester = false;
5973
6529
  const check = async (previous) => {
5974
6530
  const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
5975
6531
  const activity = latestActivity(state.activity, requesterLogin);
5976
- const asked = await askHeldReview(args, target, state);
5977
- const reason = await askReason(args.state, target, {
6532
+ const asked = await askHeldReview(args, target, state, requesterLogin);
6533
+ const ask = await askReason(args.state, target, {
5978
6534
  asked,
5979
6535
  requesterAt: activity.requesterAt,
5980
6536
  requesterLogin
5981
6537
  });
5982
- const next = nextAction(state, {
6538
+ const reason = ask?.reason;
6539
+ const requester = {
5983
6540
  actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt),
5984
6541
  askedAgain: asked !== void 0 && reason !== void 0,
6542
+ feedback: requesterFeedback(state, activity),
5985
6543
  login: requesterLogin
6544
+ };
6545
+ const decide = (mergeAccess) => nextAction(state, {
6546
+ ...requester,
6547
+ mergeAccess
5986
6548
  }, previous);
5987
- const changed = next !== void 0 && next.action !== previous;
5988
- if (changed) await showAction(items, {
5989
- action: next.action,
5990
- dedupeKey,
5991
- identityId: opener.identityId,
5992
- number: target.number,
5993
- previous,
5994
- reason,
5995
- state,
5996
- titleParts: next.action ? await loadGitHubTitleParts(args.env, {
5997
- repositoryFullName: target.repositoryFullName,
5998
- title: state.title
5999
- }, args.log) : void 0
6000
- });
6001
- await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
6002
- dedupeKey: gitHubConflictItemKey(target),
6003
- ...endedReason(state.state) ?? {
6004
- reason: "The pull request no longer has merge conflicts.",
6005
- status: "done"
6549
+ const withAccess = decide(true);
6550
+ const mergeAccess = withAccess?.action === "merge" || previous === "merge" ? requesterLogin !== void 0 && await loadRepositoryMergeAccess(args.env, args.cache, {
6551
+ login: requesterLogin,
6552
+ repositoryFullName: target.repositoryFullName
6553
+ }) : void 0;
6554
+ const next = mergeAccess === false ? decide(false) : withAccess;
6555
+ if (!askedRequester && requesterLogin && next !== void 0 && next.action === void 0 && inLimbo(state, activity, requesterLogin) && (args.askAfterRequesterActed || activity.actedAt === void 0)) {
6556
+ const [owner = "", name = ""] = target.repositoryFullName.split("/");
6557
+ if (await readGitHubRequiredChecksPass(await loadReviewAgainReader(args.env, target.repositoryFullName), {
6558
+ name,
6559
+ number: target.number,
6560
+ owner
6561
+ })) {
6562
+ askedRequester = true;
6563
+ if (await requestReviewAgain(args, target, requesterLogin)) return await check(previous);
6006
6564
  }
6007
- }) : void 0]);
6008
- if (changed && next.action === "review" && reason === "handled") await dropGitHubReviewAsked(args.state, target);
6565
+ }
6566
+ const showsAsk = next?.action === "review" || next?.action === "review_draft";
6567
+ const changed = next !== void 0 && (next.action !== previous || reason === "question" && showsAsk && !ask?.mark?.shown);
6568
+ const action = next === void 0 ? previous : next.action;
6569
+ if (next !== void 0 || previous === void 0) {
6570
+ const reviewers = state.requestedReviewers.filter((login) => !sameLogin(login, requesterLogin));
6571
+ const newlyRequested = await readGitHubReviewRequested(args.state, target, reviewers);
6572
+ const linked = await args.findLinkedIdentityIds(reviewers);
6573
+ await showPullRequestItem(items, {
6574
+ action,
6575
+ mergeAccess,
6576
+ askedReviewerIdentityIds: newlyRequested.flatMap((login) => linked.get(login) ?? []),
6577
+ number: target.number,
6578
+ previous,
6579
+ pullRequestId,
6580
+ reason,
6581
+ requester: {
6582
+ asked: changed && next.action !== void 0,
6583
+ identityId: opener.identityId
6584
+ },
6585
+ reviewerIdentityIds: reviewers.flatMap((login) => linked.get(login.toLowerCase()) ?? []),
6586
+ state
6587
+ });
6588
+ await dropGitHubReviewRequested(args.state, target, newlyRequested);
6589
+ }
6590
+ if (state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty") await items.close({
6591
+ subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, pullRequestId),
6592
+ ...state.state === "open" ? {
6593
+ reason: GITHUB_CONFLICT_GONE_REASON,
6594
+ status: "done"
6595
+ } : ENDED_REASONS[state.state]
6596
+ });
6597
+ if (changed && showsAsk && ask?.mark && !ask.mark.shown) await markGitHubReviewAsked(args.state, target, {
6598
+ ...ask.mark,
6599
+ shown: true
6600
+ });
6009
6601
  if (!changed) return previous;
6010
6602
  await setGitHubPullRequestNextAction(args.db, pullRequestId, next.action);
6011
6603
  return next.action;
@@ -6023,23 +6615,128 @@ async function syncOne(args, target) {
6023
6615
  }
6024
6616
  if (failure !== void 0) throw failure;
6025
6617
  }
6618
+ /** The task that syncs one pull request again after a webhook's sync failed. */
6619
+ const GITHUB_PULL_REQUEST_ACTION_SYNC_TASK = "syncPullRequestAction";
6620
+ const syncTaskPayloadSchema = z.object({
6621
+ number: z.number().int().positive(),
6622
+ repositoryFullName: z.string().min(1),
6623
+ /** Tasks that ran before this one and hit the rate limit again. */
6624
+ restarts: z.number().int().nonnegative()
6625
+ }).strict();
6626
+ const MAX_SYNC_TASK_RESTARTS = 3;
6627
+ const RATE_LIMIT_RESET_MARGIN_SECONDS = 5;
6628
+ const MAX_SYNC_TASK_DELAY_SECONDS = 3300;
6629
+ /**
6630
+ * Return when to sync again after a failure that GitHub causes for a
6631
+ * while: after the GraphQL rate limit resets, or after the task backoff
6632
+ * for a GitHub outage. Return undefined for other failures, which a retry
6633
+ * cannot fix.
6634
+ */
6635
+ async function retryAfterFailure(env, target, error) {
6636
+ if (error instanceof GitHubGraphqlError) {
6637
+ if (!error.types.some((type) => type === "RATE_LIMIT" || type === "RATE_LIMITED")) return error.types.length === 0 ? {} : void 0;
6638
+ const reset = await loadGraphqlRateLimitReset(env, target.repositoryFullName).catch(() => void 0);
6639
+ if (!reset) return {};
6640
+ const seconds = Math.ceil((reset.getTime() - Date.now()) / 1e3);
6641
+ return { delaySeconds: Math.min(Math.max(seconds, 0) + RATE_LIMIT_RESET_MARGIN_SECONDS, MAX_SYNC_TASK_DELAY_SECONDS) };
6642
+ }
6643
+ return error instanceof GitHubRequestError && error.status >= 500 ? {} : void 0;
6644
+ }
6026
6645
  /**
6027
- * Add, change, or close the next-action item of each Junior pull request that
6028
- * a webhook delivery can change. The item is optional, so a failure is logged
6029
- * and does not fail the delivery.
6646
+ * Add, change, or close the item of each Junior pull request that
6647
+ * a webhook delivery can change. The item is optional, so a failure does not
6648
+ * fail the delivery. A failure that GitHub causes for a while starts a task
6649
+ * that syncs the pull request again, when `tasks` is given. Other failures
6650
+ * are logged. Return the pull requests that another webhook was checking.
6651
+ * That webhook checks them again, but without `askAfterRequesterActed`.
6030
6652
  */
6031
6653
  async function syncGitHubPullRequestActions(args) {
6654
+ const busy = [];
6032
6655
  await pLimit(PULL_REQUEST_SYNC_CONCURRENCY).map(args.targets, async (target) => {
6033
6656
  try {
6034
- await syncOne(args, target);
6657
+ if (await syncOne(args, target) === "busy") busy.push(target);
6035
6658
  } catch (error) {
6036
- logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
6659
+ const metadata = {
6037
6660
  deliveryId: args.deliveryId,
6038
6661
  number: target.number,
6039
6662
  repository: target.repositoryFullName
6663
+ };
6664
+ const retry = args.tasks ? await retryAfterFailure(args.env, target, error) : void 0;
6665
+ if (!args.tasks || !retry) {
6666
+ logFailOpenFailure(args.log, "GitHub pull request action failed", error, metadata);
6667
+ return;
6668
+ }
6669
+ args.log?.warn("GitHub pull request action failed; retrying in a task", {
6670
+ ...metadata,
6671
+ errorType: error instanceof Error ? error.name : "UnknownError"
6040
6672
  });
6673
+ await startSyncTask(args.tasks, target, retry, 0);
6041
6674
  }
6042
6675
  });
6676
+ return busy;
6677
+ }
6678
+ async function startSyncTask(tasks, target, retry, restarts) {
6679
+ const startsAt = Date.now() + (retry.delaySeconds ?? 0) * 1e3;
6680
+ await tasks.start({
6681
+ ...retry,
6682
+ key: `pull-request-action-sync:${`${target.repositoryFullName}#${target.number}`.toLowerCase()}:${Math.floor(startsAt / 6e4)}:${restarts}`,
6683
+ name: GITHUB_PULL_REQUEST_ACTION_SYNC_TASK,
6684
+ payload: {
6685
+ number: target.number,
6686
+ repositoryFullName: target.repositoryFullName,
6687
+ restarts
6688
+ }
6689
+ });
6690
+ }
6691
+ /** The sync context of a started task, with fresh installation tokens. */
6692
+ function startedTaskSyncContext(ctx, options) {
6693
+ return {
6694
+ botEmail: options.botEmail,
6695
+ cache: ctx.cache,
6696
+ codeChanges: ctx.codeChanges,
6697
+ db: gitHubDbSchema.parse(ctx.db),
6698
+ env: {
6699
+ ...options.env,
6700
+ responses: ctx.state,
6701
+ tokens: /* @__PURE__ */ new Map()
6702
+ },
6703
+ findLinkedIdentityIds: async (logins) => await ctx.users.findLinkedIdentityIds(logins),
6704
+ loadGitHubLogin: async (identityId) => linkedGitHubLogin((await ctx.users.readIdentity(identityId))?.user),
6705
+ log: ctx.log,
6706
+ inboxItems: ctx.inboxItems,
6707
+ state: ctx.state
6708
+ };
6709
+ }
6710
+ /**
6711
+ * Sync the next action of one pull request again. A rate limit starts a new
6712
+ * task that waits for the reset: the queue rejects a task message an hour
6713
+ * after it starts, so the backoff of this one can end before the reset.
6714
+ * Other failures throw, so the task queue runs it again after its backoff,
6715
+ * a bounded number of times.
6716
+ */
6717
+ function githubPullRequestActionSyncTask(options) {
6718
+ return {
6719
+ payload: syncTaskPayloadSchema,
6720
+ async run(ctx) {
6721
+ const context = startedTaskSyncContext(ctx, {
6722
+ botEmail: options.botEmail(),
6723
+ env: options.env
6724
+ });
6725
+ const { restarts } = ctx.payload;
6726
+ try {
6727
+ await syncOne(context, ctx.payload);
6728
+ } catch (error) {
6729
+ const retry = await retryAfterFailure(context.env, ctx.payload, error);
6730
+ if (retry?.delaySeconds === void 0 || restarts >= MAX_SYNC_TASK_RESTARTS) throw error;
6731
+ ctx.log.warn("GitHub pull request action sync task hit the rate limit", {
6732
+ number: ctx.payload.number,
6733
+ repository: ctx.payload.repositoryFullName,
6734
+ restarts
6735
+ });
6736
+ await startSyncTask(ctx.tasks, ctx.payload, retry, restarts + 1);
6737
+ }
6738
+ }
6739
+ };
6043
6740
  }
6044
6741
  // src/pull-request-outcomes/apply.ts
6045
6742
  /**
@@ -6169,7 +6866,7 @@ async function publishGitHubConflictResolved(args) {
6169
6866
  // src/pull-request-patches.ts
6170
6867
  const GITHUB_PULL_REQUEST_PATCH_TASK = "patchPullRequest";
6171
6868
  const PATCH_DELAY_SECONDS = 5;
6172
- const payloadSchema$2 = z.object({
6869
+ const payloadSchema$3 = z.object({
6173
6870
  /** Cache entry `pulls:owner/repo#N`. */
6174
6871
  key: z.string().min(1),
6175
6872
  /** Head commit of the event. */
@@ -6272,7 +6969,7 @@ async function expirePending(cache, key) {
6272
6969
  */
6273
6970
  function githubPullRequestPatchTask(loadHeadFacts) {
6274
6971
  return {
6275
- payload: payloadSchema$2,
6972
+ payload: payloadSchema$3,
6276
6973
  async run(ctx) {
6277
6974
  const { key, sha } = ctx.payload;
6278
6975
  const ref = pullRequestRefFromCacheKey(key);
@@ -6302,9 +6999,19 @@ const issueEventSchema = z.object({
6302
6999
  repository: repositorySchema$2
6303
7000
  });
6304
7001
  const pullRequestEventSchema = z.object({
7002
+ action: z.string().optional(),
6305
7003
  pull_request: githubPullRequestFieldsSchema,
6306
7004
  repository: repositorySchema$2
6307
7005
  });
7006
+ const pullRequestReviewEventSchema = z.object({
7007
+ action: z.string().optional(),
7008
+ pull_request: z.object({ number: z.number().int().positive() }),
7009
+ repository: repositorySchema$2
7010
+ });
7011
+ const REVIEW_ACTIONS = {
7012
+ pull_request: /* @__PURE__ */ new Set(["review_requested", "review_request_removed"]),
7013
+ pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
7014
+ };
6308
7015
  const checkPullRequestsSchema = z.array(z.object({ number: z.number().int().positive() }));
6309
7016
  const checkSuiteEventSchema = z.object({
6310
7017
  check_suite: z.object({
@@ -6325,18 +7032,24 @@ function goneKey(key) {
6325
7032
  return `gone:${key}`;
6326
7033
  }
6327
7034
  async function refreshPullRequest(args, event) {
6328
- const { pull_request: payload, repository } = event;
7035
+ const { action = "", pull_request: payload, repository } = event;
7036
+ const reviewChanged = REVIEW_ACTIONS.pull_request.has(action);
6329
7037
  const key = githubObjectCacheKey("pulls", repository.full_name, payload.number);
6330
7038
  let patch = false;
6331
7039
  let conflicted = false;
7040
+ if (reviewChanged) await markGitHubReviewCleared(args.cache, key);
6332
7041
  await args.cache.update(key, (current) => {
6333
7042
  const merged = mergeGitHubPullRequest(current, payload);
6334
7043
  patch = merged?.patch ?? false;
6335
7044
  conflicted = merged?.fields.state === "open" && (payload.mergeable === false || patch && current?.mergeable === false);
6336
- return merged && {
7045
+ if (merged) return {
6337
7046
  ...GITHUB_PULL_REQUEST_CACHE,
6338
- value: merged.fields
7047
+ value: reviewChanged ? withoutGitHubReview(merged.fields) : merged.fields
6339
7048
  };
7049
+ return reviewChanged && current?.review !== void 0 ? {
7050
+ ...GITHUB_PULL_REQUEST_CACHE,
7051
+ value: withoutGitHubReview(current)
7052
+ } : void 0;
6340
7053
  });
6341
7054
  if (conflicted) await markGitHubConflict(args.state, {
6342
7055
  number: payload.number,
@@ -6385,7 +7098,8 @@ function checkEventTarget(body, eventName) {
6385
7098
  /**
6386
7099
  * Write the issue or pull request of an `issues` or `pull_request` webhook
6387
7100
  * into its cache entry, so the next card read shows it without a GitHub
6388
- * call. A `check_suite` or `check_run` webhook marks the checks
7101
+ * call. A webhook that can change the review decision clears it, so the
7102
+ * next page read asks GitHub. A `check_suite` or `check_run` webhook marks the checks
6389
7103
  * of its pull requests pending. Merge state and checks that turn pending
6390
7104
  * get a patch (`pull-request-patches.ts`).
6391
7105
  */
@@ -6395,6 +7109,18 @@ async function refreshGitHubObjectCache(args) {
6395
7109
  if (event.success) await refreshPullRequest(args, event.data);
6396
7110
  return;
6397
7111
  }
7112
+ if (args.eventName === "pull_request_review") {
7113
+ const event = pullRequestReviewEventSchema.safeParse(args.body);
7114
+ if (!event.success) return;
7115
+ if (!REVIEW_ACTIONS.pull_request_review.has(event.data.action ?? "")) return;
7116
+ const key = githubObjectCacheKey("pulls", event.data.repository.full_name, event.data.pull_request.number);
7117
+ await markGitHubReviewCleared(args.cache, key);
7118
+ await args.cache.update(key, (current) => current?.review === void 0 ? void 0 : {
7119
+ ...GITHUB_PULL_REQUEST_CACHE,
7120
+ value: withoutGitHubReview(current)
7121
+ });
7122
+ return;
7123
+ }
6398
7124
  if (args.eventName === "issues") {
6399
7125
  const event = issueEventSchema.safeParse(args.body);
6400
7126
  if (!event.success) return;
@@ -6778,8 +7504,7 @@ const gitHubPullRequestMergeSchema = z.object({
6778
7504
  html_url: z.string().min(1).optional(),
6779
7505
  mergeable: z.boolean().nullable().optional(),
6780
7506
  mergeable_state: z.string().optional(),
6781
- state: z.string(),
6782
- title: z.string().optional()
7507
+ state: z.string()
6783
7508
  });
6784
7509
  /**
6785
7510
  * Build the `pull_request.merge_conflict` copies for one pull request. With
@@ -6879,12 +7604,10 @@ async function loadGitHubMergeConflictEvents(args) {
6879
7604
  conflict
6880
7605
  }),
6881
7606
  loadHistory: loadConflictHistory,
6882
- loadTitleParts: args.loadTitleParts,
6883
7607
  log: args.log,
6884
7608
  now: /* @__PURE__ */ new Date(),
6885
7609
  ref,
6886
- inboxItems: args.inboxItems,
6887
- ...loaded.title ? { title: loaded.title } : void 0
7610
+ inboxItems: args.inboxItems
6888
7611
  });
6889
7612
  } catch (error) {
6890
7613
  logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
@@ -7218,7 +7941,7 @@ async function withGitHubPullRequestMatchData(args) {
7218
7941
  /** Pull request outcomes that the people involved need to hear about. */
7219
7942
  const PEOPLE_EVENTS = /* @__PURE__ */ new Set(["pull_request.review.approved", "pull_request.merged"]);
7220
7943
  const MAX_PEOPLE = 20;
7221
- const PAGE_SIZE$2 = 100;
7944
+ const PAGE_SIZE$3 = 100;
7222
7945
  const MAX_PAGES$2 = 3;
7223
7946
  const CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
7224
7947
  const GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
@@ -7263,12 +7986,12 @@ function shareCommitPages(load) {
7263
7986
  */
7264
7987
  async function forEachCommit(loadPage, visit) {
7265
7988
  for (let page = 1; page <= MAX_PAGES$2; page += 1) {
7266
- const commits = commitPageSchema$1.parse(await loadPage(page, PAGE_SIZE$2));
7989
+ const commits = commitPageSchema$1.parse(await loadPage(page, PAGE_SIZE$3));
7267
7990
  for (const commit of commits) visit({
7268
7991
  coAuthorEmails: [...commit.commit.message.matchAll(CO_AUTHOR_TRAILER)].map((match) => match[1]),
7269
7992
  ...commit.author ? { login: commit.author.login } : void 0
7270
7993
  });
7271
- if (commits.length < PAGE_SIZE$2) break;
7994
+ if (commits.length < PAGE_SIZE$3) break;
7272
7995
  }
7273
7996
  }
7274
7997
  /** The GitHub login in a noreply email such as `1+octocat@users.noreply.github.com`. */
@@ -7596,7 +8319,6 @@ function createGitHubWebhookRoute(args) {
7596
8319
  events,
7597
8320
  hasMatch,
7598
8321
  loadConflictHistory: args.loadPullRequestConflictHistory,
7599
- loadTitleParts: args.loadTitleParts,
7600
8322
  loadPullRequest: args.loadPullRequest,
7601
8323
  log: args.log,
7602
8324
  pullRequestPayload: eventName === "pull_request" ? body : void 0,
@@ -7615,27 +8337,30 @@ function createGitHubWebhookRoute(args) {
7615
8337
  responses: args.state,
7616
8338
  tokens: args.tokens
7617
8339
  };
7618
- await syncGitHubPullRequestActions({
7619
- botEmail,
7620
- codeChanges: args.codeChanges,
8340
+ await requestGitHubReviewersWhenReady({
8341
+ body,
7621
8342
  db: args.db,
7622
8343
  deliveryId,
7623
8344
  env,
8345
+ eventName,
7624
8346
  loadGitHubLogin: args.loadGitHubLogin,
7625
8347
  log: args.log,
7626
- inboxItems: args.inboxItems,
7627
- state: args.state,
7628
- targets: pullRequestActionTargets(eventName, body)
8348
+ state: args.state
7629
8349
  });
7630
- await requestGitHubReviewersWhenReady({
7631
- body,
8350
+ await syncGitHubPullRequestActions({
8351
+ botEmail,
8352
+ cache: args.cache,
8353
+ codeChanges: args.codeChanges,
7632
8354
  db: args.db,
7633
8355
  deliveryId,
7634
8356
  env,
7635
- eventName,
8357
+ findLinkedIdentityIds: args.findLinkedIdentityIds,
7636
8358
  loadGitHubLogin: args.loadGitHubLogin,
7637
8359
  log: args.log,
7638
- state: args.state
8360
+ inboxItems: args.inboxItems,
8361
+ state: args.state,
8362
+ targets: pullRequestActionTargets(eventName, body),
8363
+ tasks: args.tasks
7639
8364
  });
7640
8365
  if (!pullRequestOutcome && !closedIssue && !pullRequestConversations && events.length === 0) return new Response("Ignored", { status: 202 });
7641
8366
  return new Response("Accepted", { status: 202 });
@@ -7668,7 +8393,6 @@ const searchNodeSchema = z.union([z.object({
7668
8393
  ]),
7669
8394
  number: z.number().int().positive(),
7670
8395
  state: z.string(),
7671
- title: z.string(),
7672
8396
  url: z.string().min(1)
7673
8397
  }), z.object({}).strict()]);
7674
8398
  const searchResponseSchema = z.object({ data: z.object({ search: z.object({
@@ -7693,12 +8417,10 @@ async function checkConflict(args, input) {
7693
8417
  draft: input.draft,
7694
8418
  events,
7695
8419
  loadHistory: args.loadHistory,
7696
- loadTitleParts: args.loadTitleParts,
7697
8420
  log: args.log,
7698
8421
  now: args.now,
7699
8422
  ref: input.ref,
7700
- inboxItems: args.inboxItems,
7701
- title: input.title
8423
+ inboxItems: args.inboxItems
7702
8424
  })) await args.events.publish(event);
7703
8425
  }
7704
8426
  async function checkRepository(args, repositoryFullName) {
@@ -7736,8 +8458,7 @@ async function checkRepository(args, repositoryFullName) {
7736
8458
  url: node.url
7737
8459
  },
7738
8460
  draft: node.isDraft,
7739
- ref,
7740
- title: node.title
8461
+ ref
7741
8462
  });
7742
8463
  }
7743
8464
  await closeGitHubConflictItems({
@@ -7792,15 +8513,20 @@ async function runGitHubConflictChecks(args) {
7792
8513
  }
7793
8514
  // src/merge-conflict-checks/resume.ts
7794
8515
  /**
8516
+ * Let the conflict policy ask again about one pull request, after a Resume
8517
+ * that could not start a fix.
8518
+ */
8519
+ async function allowGitHubConflictAsk(db, pullRequestId) {
8520
+ await db.update(juniorGitHubPullRequests).set({ conflictFixAskedAt: null }).where(eq(juniorGitHubPullRequests.pullRequestId, pullRequestId));
8521
+ }
8522
+ /**
7795
8523
  * Resume merge conflict fixes of one open Junior pull request, and start a
7796
8524
  * fix when it is not a draft and GitHub does not say that it can merge.
7797
8525
  * Safe to repeat for one item: the event key names the item, so a retry publishes no second fix.
7798
8526
  */
7799
8527
  async function resumeGitHubConflictFixes(args) {
7800
- const change = await findGitHubPullRequest(args.codeChanges, args.ref);
7801
- if (change?.state !== "open") return;
7802
8528
  const t = juniorGitHubPullRequests;
7803
- const pullRequest = eq(t.pullRequestId, change.providerId);
8529
+ const pullRequest = eq(t.pullRequestId, args.pullRequestId);
7804
8530
  const [row] = await args.db.select({
7805
8531
  fixes: t.conflictFixes,
7806
8532
  resumedAt: t.conflictFixesResumedAt
@@ -7974,6 +8700,7 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
7974
8700
  });
7975
8701
  await closeGitHubConflictItem({
7976
8702
  db: args.db,
8703
+ pullRequestId: String(pullRequest.databaseId),
7977
8704
  ref: {
7978
8705
  number: pullRequest.number,
7979
8706
  repositoryFullName: nameWithOwner
@@ -8143,7 +8870,7 @@ const commitPageSchema = z.array(providerCommitSchema).transform((commits) => co
8143
8870
  authorEmail: commit.commit.author?.email ?? null,
8144
8871
  authorLogin: commit.author?.login ?? null
8145
8872
  })));
8146
- const PAGE_SIZE$1 = 100;
8873
+ const PAGE_SIZE$2 = 100;
8147
8874
  const MAX_PAGES = 3;
8148
8875
  const MAX_LISTED_COMMITS = 250;
8149
8876
  /** Classify whether every Git author in a PR commit list is Junior's bot. */
@@ -8153,7 +8880,7 @@ async function classifyGitHubPullRequestCommitComposition(args) {
8153
8880
  let foundCommit = false;
8154
8881
  let inspectedCommits = 0;
8155
8882
  for (let page = 1; page <= MAX_PAGES; page += 1) {
8156
- const commits = commitPageSchema.parse(await args.loadPage(page, PAGE_SIZE$1));
8883
+ const commits = commitPageSchema.parse(await args.loadPage(page, PAGE_SIZE$2));
8157
8884
  inspectedCommits += commits.length;
8158
8885
  for (const commit of commits) {
8159
8886
  foundCommit = true;
@@ -8161,7 +8888,7 @@ async function classifyGitHubPullRequestCommitComposition(args) {
8161
8888
  if (!isBotLogin(commit.authorLogin, botEmail) && authorEmail !== botEmail) return "mixed";
8162
8889
  }
8163
8890
  if (inspectedCommits >= MAX_LISTED_COMMITS) return void 0;
8164
- if (commits.length < PAGE_SIZE$1) break;
8891
+ if (commits.length < PAGE_SIZE$2) break;
8165
8892
  if (page === MAX_PAGES) return void 0;
8166
8893
  }
8167
8894
  return foundCommit ? "junior_only" : void 0;
@@ -8178,13 +8905,13 @@ async function classifyGitHubPullRequestCommitComposition(args) {
8178
8905
  * records the names that changed.
8179
8906
  */
8180
8907
  const GITHUB_REPOSITORY_NAME_REPAIR_TASK = "repairRepositoryNames";
8181
- const DONE_KEY$1 = "repository-name-repair:done";
8908
+ const DONE_KEY$2 = "repository-name-repair:done";
8182
8909
  /** GitHub reads at once. */
8183
8910
  const READ_CONCURRENCY = 4;
8184
- const payloadSchema$1 = z.object({}).strict();
8911
+ const payloadSchema$2 = z.object({}).strict();
8185
8912
  /** Start the repair until one run finishes. */
8186
8913
  async function startGitHubRepositoryNameRepair(args) {
8187
- if (await args.state.get(DONE_KEY$1)) return;
8914
+ if (await args.state.get(DONE_KEY$2)) return;
8188
8915
  await args.tasks.start({
8189
8916
  key: "repository-name-repair",
8190
8917
  name: GITHUB_REPOSITORY_NAME_REPAIR_TASK,
@@ -8198,9 +8925,9 @@ async function startGitHubRepositoryNameRepair(args) {
8198
8925
  */
8199
8926
  function githubRepositoryNameRepairTask(loadFullNames) {
8200
8927
  return {
8201
- payload: payloadSchema$1,
8928
+ payload: payloadSchema$2,
8202
8929
  async run(ctx) {
8203
- if (await ctx.state.get(DONE_KEY$1)) return;
8930
+ if (await ctx.state.get(DONE_KEY$2)) return;
8204
8931
  const stored = /* @__PURE__ */ new Map();
8205
8932
  for (const change of await ctx.codeChanges.list({})) stored.set(change.repository.providerId, change.repository.name);
8206
8933
  if (stored.size > 0) {
@@ -8220,21 +8947,21 @@ function githubRepositoryNameRepairTask(loadFullNames) {
8220
8947
  }
8221
8948
  });
8222
8949
  }
8223
- await ctx.state.set(DONE_KEY$1, true);
8950
+ await ctx.state.set(DONE_KEY$2, true);
8224
8951
  }
8225
8952
  };
8226
8953
  }
8227
8954
  // src/pull-request-requesters/backfill.ts
8228
8955
  const GITHUB_PULL_REQUEST_REQUESTER_BACKFILL_TASK = "backfillPullRequestRequesters";
8229
- const CURSOR_KEY = "pull-request-requester-backfill:cursor";
8230
- const DONE_KEY = "pull-request-requester-backfill:done";
8956
+ const CURSOR_KEY$1 = "pull-request-requester-backfill:cursor";
8957
+ const DONE_KEY$1 = "pull-request-requester-backfill:done";
8231
8958
  /** Pull requests per task run. Each needs a few small database writes. */
8232
- const PAGE_SIZE = 200;
8233
- const payloadSchema = z.object({}).strict();
8959
+ const PAGE_SIZE$1 = 200;
8960
+ const payloadSchema$1 = z.object({}).strict();
8234
8961
  /** Start the next page of the backfill until the last page is done. */
8235
8962
  async function startGitHubPullRequestRequesterBackfill(args) {
8236
- if (await args.state.get(DONE_KEY)) return;
8237
- const after = await args.state.get(CURSOR_KEY);
8963
+ if (await args.state.get(DONE_KEY$1)) return;
8964
+ const after = await args.state.get(CURSOR_KEY$1);
8238
8965
  await args.tasks.start({
8239
8966
  key: `pull-request-requester-backfill:${after ? `${after.repositoryFullName}#${after.number}` : "start"}`,
8240
8967
  name: GITHUB_PULL_REQUEST_REQUESTER_BACKFILL_TASK,
@@ -8246,13 +8973,13 @@ async function startGitHubPullRequestRequesterBackfill(args) {
8246
8973
  * code changes, in the order of repository name and number.
8247
8974
  */
8248
8975
  const githubPullRequestRequesterBackfillTask = {
8249
- payload: payloadSchema,
8976
+ payload: payloadSchema$1,
8250
8977
  async run(ctx) {
8251
- if (await ctx.state.get(DONE_KEY)) return;
8978
+ if (await ctx.state.get(DONE_KEY$1)) return;
8252
8979
  const db = gitHubDbSchema.parse(ctx.db);
8253
8980
  const page = await listGitHubPullRequestsWithRequesters(db, {
8254
- after: await ctx.state.get(CURSOR_KEY),
8255
- limit: PAGE_SIZE
8981
+ after: await ctx.state.get(CURSOR_KEY$1),
8982
+ limit: PAGE_SIZE$1
8256
8983
  });
8257
8984
  const numbers = /* @__PURE__ */ new Map();
8258
8985
  for (const ref of page) numbers.set(ref.repositoryFullName, [...numbers.get(ref.repositoryFullName) ?? [], ref.number]);
@@ -8263,10 +8990,69 @@ const githubPullRequestRequesterBackfillTask = {
8263
8990
  repositoryFullName
8264
8991
  });
8265
8992
  const last = page.at(-1);
8266
- if (!last || page.length < PAGE_SIZE) await ctx.state.set(DONE_KEY, true);
8267
- else await ctx.state.set(CURSOR_KEY, last);
8993
+ if (!last || page.length < PAGE_SIZE$1) await ctx.state.set(DONE_KEY$1, true);
8994
+ else await ctx.state.set(CURSOR_KEY$1, last);
8268
8995
  }
8269
8996
  };
8997
+ // src/pull-request-action-backfill.ts
8998
+ const GITHUB_PULL_REQUEST_ACTION_BACKFILL_TASK = "backfillPullRequestActions";
8999
+ const VERSION = "v2";
9000
+ const ASK_AFTER_REQUESTER_ACTED = false;
9001
+ const CURSOR_KEY = `pull-request-action-backfill:${VERSION}:cursor`;
9002
+ const DONE_KEY = `pull-request-action-backfill:${VERSION}:done`;
9003
+ const RERUNS_KEY = `pull-request-action-backfill:${VERSION}:reruns`;
9004
+ /**
9005
+ * Pull requests per task run. Most need no GitHub read, because no person
9006
+ * asked for them. The others read GitHub a few times each, five at once, so
9007
+ * one run stays well inside the function time and the hourly rate limit.
9008
+ */
9009
+ const PAGE_SIZE = 50;
9010
+ const payloadSchema = z.object({}).strict();
9011
+ /** Start the next page of the backfill until the last page is done. */
9012
+ async function startGitHubPullRequestActionBackfill(args) {
9013
+ if (await args.state.get(DONE_KEY)) return;
9014
+ const after = await args.state.get(CURSOR_KEY);
9015
+ const reruns = await args.state.get(RERUNS_KEY);
9016
+ await args.tasks.start({
9017
+ key: `pull-request-action-backfill:${VERSION}:${after ?? 0}:${reruns ?? 0}`,
9018
+ name: GITHUB_PULL_REQUEST_ACTION_BACKFILL_TASK,
9019
+ payload: {}
9020
+ });
9021
+ }
9022
+ /**
9023
+ * Sync the next action of the next page of open Junior pull requests, in
9024
+ * the order of their GitHub ids. A failure for one pull request is logged
9025
+ * and skips it.
9026
+ */
9027
+ function githubPullRequestActionBackfillTask(args) {
9028
+ return {
9029
+ payload: payloadSchema,
9030
+ async run(ctx) {
9031
+ if (await ctx.state.get(DONE_KEY)) return;
9032
+ const after = await ctx.state.get(CURSOR_KEY) ?? 0;
9033
+ const page = (await ctx.codeChanges.list({ state: "open" })).map((change) => ({
9034
+ change,
9035
+ id: Number(change.providerId)
9036
+ })).filter(({ id }) => id > after).sort((a, b) => a.id - b.id).slice(0, PAGE_SIZE);
9037
+ const busy = await syncGitHubPullRequestActions({
9038
+ askAfterRequesterActed: ASK_AFTER_REQUESTER_ACTED,
9039
+ ...startedTaskSyncContext(ctx, {
9040
+ botEmail: args.botEmail(),
9041
+ env: args.env
9042
+ }),
9043
+ deliveryId: `pull-request-action-backfill:${VERSION}`,
9044
+ targets: page.map(({ change }) => ({
9045
+ number: change.number,
9046
+ repositoryFullName: change.repository.name
9047
+ }))
9048
+ });
9049
+ const last = page.at(-1);
9050
+ if (busy.length > 0) await ctx.state.set(RERUNS_KEY, (await ctx.state.get(RERUNS_KEY) ?? 0) + 1);
9051
+ else if (!last || page.length < PAGE_SIZE) await ctx.state.set(DONE_KEY, true);
9052
+ else await ctx.state.set(CURSOR_KEY, last.id);
9053
+ }
9054
+ };
9055
+ }
8270
9056
  // src/images.ts
8271
9057
  /**
8272
9058
  * Description images of GitHub objects, served through the Junior image
@@ -8821,24 +9607,25 @@ function readSpans(text) {
8821
9607
  */
8822
9608
  function namedRepositories(text, spans, configuredOwner) {
8823
9609
  const named = [];
8824
- const add = (offset, owner, name) => {
9610
+ const add = (offset, owner, name, issue) => {
8825
9611
  if (owner && name) named.push({
8826
9612
  offset,
8827
9613
  repository: {
8828
9614
  owner,
8829
9615
  name
8830
- }
9616
+ },
9617
+ issue
8831
9618
  });
8832
9619
  };
8833
9620
  for (const span of spans) {
8834
9621
  if (span.url) {
8835
- for (const { groups } of span.url.matchAll(GITHUB_LINKED_URL_PATTERN)) add(span.start, groups?.["owner"], groups?.["repo"]);
9622
+ for (const { groups } of span.url.matchAll(GITHUB_LINKED_URL_PATTERN)) add(span.start, groups?.["owner"], groups?.["repo"], groups?.["issue"]);
8836
9623
  continue;
8837
9624
  }
8838
9625
  const source = text.slice(span.start, span.end);
8839
9626
  for (const { groups, index } of source.matchAll(TEXT_REFERENCE_PATTERN)) {
8840
9627
  const offset = span.start + index;
8841
- add(offset, groups?.["issueOwner"], groups?.["issueRepo"]);
9628
+ add(offset, groups?.["issueOwner"], groups?.["issueRepo"], groups?.["issue"]);
8842
9629
  add(offset, groups?.["commitOwner"], groups?.["commitRepo"]);
8843
9630
  }
8844
9631
  if (!configuredOwner) continue;
@@ -8847,15 +9634,22 @@ function namedRepositories(text, spans, configuredOwner) {
8847
9634
  return named.sort((left, right) => left.offset - right.offset);
8848
9635
  }
8849
9636
  const repositoryKey = ({ owner, name }) => `${owner}/${name}`.toLowerCase();
9637
+ /** Return the one repository of all entries, or none when they differ. */
9638
+ function onlyRepository(named) {
9639
+ const first = named[0]?.repository;
9640
+ return first && named.every(({ repository }) => repositoryKey(repository) === repositoryKey(first)) ? first : void 0;
9641
+ }
8850
9642
  /**
8851
- * Pick the repository of a bare reference at `offset`: the one repository
8852
- * that the text names, else the last one named before the reference when
8853
- * the text names several, else the configured one when it names none.
9643
+ * Pick the repository of a bare reference at `offset`. A bare issue number
9644
+ * that the text also qualifies, such as `#905` after `owner/repo#905`, gets
9645
+ * that repository. Else it gets the one repository that the text names,
9646
+ * else the last one named before the reference when the text names
9647
+ * several, else the configured one when it names none.
8854
9648
  */
8855
- function repositoryAt(named, configured, offset) {
9649
+ function repositoryAt(named, configured, offset, issue) {
8856
9650
  if (named.length === 0) return configured;
8857
- const first = named[0].repository;
8858
- if (named.every(({ repository }) => repositoryKey(repository) === repositoryKey(first))) return first;
9651
+ const only = (issue ? onlyRepository(named.filter((entry) => entry.issue === issue)) : void 0) ?? onlyRepository(named);
9652
+ if (only) return only;
8859
9653
  let nearest;
8860
9654
  for (const entry of named) {
8861
9655
  if (entry.offset >= offset) break;
@@ -8883,7 +9677,7 @@ function linkifyTextReferences(text, start, context) {
8883
9677
  if (known) return known;
8884
9678
  return context.linkProfiles ? `[${reference}](https://github.com/${login})` : reference;
8885
9679
  }
8886
- const repository = typeof index === "number" ? context.repositoryAt(start + index) : void 0;
9680
+ const repository = typeof index === "number" ? context.repositoryAt(start + index, groups["bareIssue"]) : void 0;
8887
9681
  if (!repository) return reference;
8888
9682
  const { owner, name } = repository;
8889
9683
  if (groups["bareIssue"]) {
@@ -8905,11 +9699,12 @@ function linkifyTextReferences(text, start, context) {
8905
9699
  * discussion, and commit URLs always become links. `#123`, `GH-123`,
8906
9700
  * `user@sha`, and full SHAs need a repository: the one that the text names,
8907
9701
  * also as a plain `owner/repo` of the configured owner. When it names
8908
- * several, the last one named before the reference wins. When it names
8909
- * none, the `repo` config value is used. Their link labels name the
8910
- * repository. `@login` becomes the
8911
- * `mention` of the known person with that GitHub login. Other logins become
8912
- * GitHub profile links when the text is GitHub text, or names a repository.
9702
+ * several, a qualified reference with the same issue number wins, else
9703
+ * the last one named before the reference. When it names none, the `repo`
9704
+ * config value is used. Their link labels name the repository. `@login`
9705
+ * becomes the `mention` of the known person with that GitHub login. Other
9706
+ * logins become GitHub profile links when the text is GitHub text, or names
9707
+ * a repository.
8913
9708
  * Chat `@name` words are often people who are not GitHub accounts. Set
8914
9709
  * `bareUrls` to keep bare URLs, where the place shows them as cards.
8915
9710
  */
@@ -8921,7 +9716,7 @@ function linkifyGitHubReferences(text, options = {}) {
8921
9716
  const context = {
8922
9717
  linkProfiles: options.githubText === true || named.length > 0,
8923
9718
  mention: options.mention ?? (() => void 0),
8924
- repositoryAt: (offset) => repositoryAt(named, configured, offset)
9719
+ repositoryAt: (offset, issue) => repositoryAt(named, configured, offset, issue)
8925
9720
  };
8926
9721
  let result = "";
8927
9722
  let cursor = 0;
@@ -9321,6 +10116,136 @@ function overridesHooksPath([program, ...args]) {
9321
10116
  }
9322
10117
  return false;
9323
10118
  }
10119
+ // src/graphql-budget.ts
10120
+ /**
10121
+ * Hourly GitHub GraphQL budgets for Sandbox requests.
10122
+ *
10123
+ * The App installation has one hourly GraphQL points budget for all of
10124
+ * Junior. Each Conversation's Sandbox gets a share of it, and Sandbox
10125
+ * requests stop while the installation has only the host reserve left, so
10126
+ * host calls such as the PR next-action syncs keep working.
10127
+ *
10128
+ * Spend comes from GitHub's own rate limit headers on each response, not
10129
+ * from a prediction. A response's cost is the rise in `x-ratelimit-used`
10130
+ * since the last response that Junior saw. Spend that Junior does not see,
10131
+ * such as a webhook call that does not go through egress, counts toward the
10132
+ * next Sandbox response, so a Conversation can be charged more than its own
10133
+ * queries cost, never less.
10134
+ *
10135
+ * Spend is known only when a response comes back, so each Conversation may
10136
+ * have only a few Sandbox GraphQL requests in flight. Without that limit,
10137
+ * parallel copies of a costly query all pass the check before any of them
10138
+ * is charged.
10139
+ *
10140
+ * Counts live in the plugin cache, which every instance shares. A lost
10141
+ * entry only resets a count, which lets more requests through, never fewer.
10142
+ */
10143
+ /** Points that one Conversation's Sandbox may spend in one clock hour. */
10144
+ const GITHUB_SANDBOX_GRAPHQL_CONVERSATION_BUDGET = 2e3;
10145
+ /** Installation points that Sandbox requests leave for host calls. */
10146
+ const GITHUB_GRAPHQL_HOST_RESERVE = 2e3;
10147
+ /** Sandbox GraphQL requests that one Conversation may have in flight. */
10148
+ const GITHUB_SANDBOX_GRAPHQL_IN_FLIGHT_LIMIT = 2;
10149
+ /**
10150
+ * How long a request holds its in-flight slot when no response frees it,
10151
+ * such as when the upstream fetch fails. GitHub stops a GraphQL query after
10152
+ * 10 seconds.
10153
+ */
10154
+ const IN_FLIGHT_SLOT_MS = 6e4;
10155
+ const HOUR_MS = 36e5;
10156
+ const RATE_LIMIT_CACHE_KEY = "graphql-rate-limit";
10157
+ function resetText(resetAtMs, nowMs) {
10158
+ return `${new Date(resetAtMs).toISOString().slice(11, 16)} UTC (in ${Math.max(1, Math.ceil((resetAtMs - nowMs) / 6e4))} min)`;
10159
+ }
10160
+ function conversationKey(conversationId, hourStartMs) {
10161
+ return `graphql-budget:${conversationId}:${hourStartMs}`;
10162
+ }
10163
+ function inFlightKey(conversationId) {
10164
+ return `graphql-in-flight:${conversationId}`;
10165
+ }
10166
+ function heldSlots(starts, nowMs) {
10167
+ return (starts ?? []).filter((start) => nowMs - start < IN_FLIGHT_SLOT_MS);
10168
+ }
10169
+ async function takeInFlightSlot(ctx, conversationId, nowMs) {
10170
+ let taken = false;
10171
+ await ctx.cache.update(inFlightKey(conversationId), (current) => {
10172
+ const held = heldSlots(current, nowMs);
10173
+ if (held.length >= GITHUB_SANDBOX_GRAPHQL_IN_FLIGHT_LIMIT) return {
10174
+ ttlMs: IN_FLIGHT_SLOT_MS,
10175
+ value: held
10176
+ };
10177
+ taken = true;
10178
+ return {
10179
+ ttlMs: IN_FLIGHT_SLOT_MS,
10180
+ value: [...held, nowMs]
10181
+ };
10182
+ });
10183
+ if (taken) return;
10184
+ throw new EgressPolicyDenied(`GitHub GraphQL request denied: this Conversation already has ${GITHUB_SANDBOX_GRAPHQL_IN_FLIGHT_LIMIT} Sandbox GraphQL requests in flight. Wait for them to finish, and send GraphQL requests one after another, not in parallel.`);
10185
+ }
10186
+ function spendsSandboxBudget(request) {
10187
+ return !request.operation && !request.withoutCredential;
10188
+ }
10189
+ /**
10190
+ * Deny a Sandbox GitHub GraphQL request when its Conversation has spent its
10191
+ * hourly budget, or when the installation has only the host reserve left.
10192
+ */
10193
+ async function assertGitHubSandboxGraphqlBudgetLeft(ctx) {
10194
+ if (!spendsSandboxBudget(ctx.request)) return;
10195
+ const nowMs = Date.now();
10196
+ const rateLimit = await ctx.cache.get(RATE_LIMIT_CACHE_KEY);
10197
+ if (rateLimit && rateLimit.resetAtMs > nowMs && rateLimit.remaining <= GITHUB_GRAPHQL_HOST_RESERVE) throw new EgressPolicyDenied(`GitHub GraphQL request denied: the App installation has ${rateLimit.remaining} GraphQL points left this hour, and Sandbox requests leave ${GITHUB_GRAPHQL_HOST_RESERVE} for host calls. It resets at ${resetText(rateLimit.resetAtMs, nowMs)}. Use REST endpoints such as \`gh api repos/{owner}/{repo}/pulls/{number}\` until then. Do not retry GraphQL before the reset.`);
10198
+ const { conversationId } = ctx.request;
10199
+ if (!conversationId) return;
10200
+ const hourStartMs = nowMs - nowMs % HOUR_MS;
10201
+ const spent = await ctx.cache.get(conversationKey(conversationId, hourStartMs)) ?? 0;
10202
+ if (spent < GITHUB_SANDBOX_GRAPHQL_CONVERSATION_BUDGET) {
10203
+ await takeInFlightSlot(ctx, conversationId, nowMs);
10204
+ return;
10205
+ }
10206
+ throw new EgressPolicyDenied(`GitHub GraphQL request denied: this Conversation has used ${spent} of its ${GITHUB_SANDBOX_GRAPHQL_CONVERSATION_BUDGET} Sandbox GraphQL points for this hour. The budget resets at ${resetText(hourStartMs + HOUR_MS, nowMs)}. Use REST endpoints such as \`gh api repos/{owner}/{repo}/pulls/{number}\` until then.`);
10207
+ }
10208
+ /**
10209
+ * Keep the installation's GraphQL rate limit from a GraphQL response's
10210
+ * headers. When the response answers a Sandbox request, free its in-flight
10211
+ * slot and charge what it cost to its Conversation's hourly budget.
10212
+ */
10213
+ async function recordGitHubGraphqlSpend(ctx) {
10214
+ const nowMs = Date.now();
10215
+ const { conversationId } = ctx.request;
10216
+ const sandboxConversationId = conversationId && spendsSandboxBudget(ctx.request) ? conversationId : void 0;
10217
+ if (sandboxConversationId && ctx.response.status !== 403) await ctx.cache.update(inFlightKey(sandboxConversationId), (current) => ({
10218
+ ttlMs: IN_FLIGHT_SLOT_MS,
10219
+ value: heldSlots(current, nowMs).slice(1)
10220
+ }));
10221
+ if (!ctx.grant.name.startsWith("installation-")) return;
10222
+ const { headers } = ctx.response;
10223
+ if (headers.get("x-ratelimit-resource") !== "graphql") return;
10224
+ const remaining = Number(headers.get("x-ratelimit-remaining"));
10225
+ const used = Number(headers.get("x-ratelimit-used"));
10226
+ const resetAtMs = Number(headers.get("x-ratelimit-reset")) * 1e3;
10227
+ if (!Number.isInteger(remaining) || !Number.isInteger(used) || !(resetAtMs > nowMs)) return;
10228
+ let cost = 0;
10229
+ await ctx.cache.update(RATE_LIMIT_CACHE_KEY, (current) => {
10230
+ const sameWindow = current?.resetAtMs === resetAtMs;
10231
+ if (sameWindow && used <= current.used) return;
10232
+ cost = sameWindow ? used - current.used : 1;
10233
+ return {
10234
+ ttlMs: resetAtMs - nowMs,
10235
+ value: {
10236
+ remaining,
10237
+ resetAtMs,
10238
+ used
10239
+ }
10240
+ };
10241
+ });
10242
+ if (!sandboxConversationId || cost === 0) return;
10243
+ const hourStartMs = nowMs - nowMs % HOUR_MS;
10244
+ await ctx.cache.update(conversationKey(sandboxConversationId, hourStartMs), (spent = 0) => ({
10245
+ ttlMs: hourStartMs + HOUR_MS - nowMs,
10246
+ value: spent + cost
10247
+ }));
10248
+ }
9324
10249
  // src/pull-request-review-policy.ts
9325
10250
  /**
9326
10251
  * Deterministic pull request review policy enforced before credential grant.
@@ -9439,6 +10364,7 @@ function githubSmartHttpAccess(upstreamUrl) {
9439
10364
  if (pathname.endsWith("/git-receive-pack") || service === "git-receive-pack") return "write";
9440
10365
  if (pathname.endsWith("/git-upload-pack") || service === "git-upload-pack") return "read";
9441
10366
  }
10367
+ /** Whether a URL is GitHub's GraphQL endpoint. */
9442
10368
  function isGitHubGraphqlUrl(upstreamUrl) {
9443
10369
  return upstreamUrl.hostname.toLowerCase() === "api.github.com" && upstreamUrl.pathname.toLowerCase().endsWith("/graphql");
9444
10370
  }
@@ -9684,7 +10610,7 @@ function applyGitHubEgressPolicy(input) {
9684
10610
  denialMessage: toolOnlyWrite.denialMessage
9685
10611
  });
9686
10612
  if (isGitHubIssueRead(input)) enforceEgressPolicy({
9687
- allowed: input.operation === "github.issue.get",
10613
+ allowed: input.operation === "github.issue.get" || input.operation === "github.objects.cards.get",
9688
10614
  denialMessage: ISSUE_READ_DENIAL
9689
10615
  });
9690
10616
  assertGitHubPullRequestApprovalDenied({
@@ -9720,6 +10646,7 @@ function requireRepositoryTarget(upstreamUrl) {
9720
10646
  async function githubGrantForEgress(ctx, env) {
9721
10647
  const upstreamUrl = new URL(ctx.request.url);
9722
10648
  const grant = await selectGitHubGrant(ctx, env, upstreamUrl);
10649
+ if (isGitHubGraphqlUrl(upstreamUrl)) await assertGitHubSandboxGraphqlBudgetLeft(ctx);
9723
10650
  const repository = githubRepositoryFromUrl(upstreamUrl);
9724
10651
  return repository ? {
9725
10652
  ...grant,
@@ -9806,12 +10733,29 @@ function githubPlugin(options = {}) {
9806
10733
  repository: (name) => `https://github.com/${name}`
9807
10734
  },
9808
10735
  images: githubImageSource,
10736
+ inboxSubjects: githubInboxSubjectKinds,
9809
10737
  objectLinks: [
9810
10738
  githubAccountLinks,
9811
10739
  githubIssueLinks,
9812
10740
  githubPullRequestLinks
9813
10741
  ],
9814
10742
  tasks: {
10743
+ [GITHUB_PULL_REQUEST_ACTION_BACKFILL_TASK]: githubPullRequestActionBackfillTask({
10744
+ botEmail: () => readEnv(botEmailEnv),
10745
+ env: {
10746
+ appIdEnv,
10747
+ installationIdEnv,
10748
+ privateKeyEnv
10749
+ }
10750
+ }),
10751
+ [GITHUB_PULL_REQUEST_ACTION_SYNC_TASK]: githubPullRequestActionSyncTask({
10752
+ botEmail: () => readEnv(botEmailEnv),
10753
+ env: {
10754
+ appIdEnv,
10755
+ installationIdEnv,
10756
+ privateKeyEnv
10757
+ }
10758
+ }),
9815
10759
  [GITHUB_PULL_REQUEST_OUTCOME_TASK]: githubPullRequestOutcomeTask,
9816
10760
  [GITHUB_PULL_REQUEST_PATCH_TASK]: githubPullRequestPatchTask(async (refs) => await loadPullRequestHeadFacts({
9817
10761
  appIdEnv,
@@ -9967,21 +10911,37 @@ function githubPlugin(options = {}) {
9967
10911
  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." }];
9968
10912
  },
9969
10913
  async inboxItemAnswered(ctx) {
9970
- const ref = parseGitHubConflictItemKey(ctx.dedupeKey);
9971
- if (!ref || ctx.choice !== "Resume") return;
10914
+ if (ctx.subject.kind !== GITHUB_INBOX_SUBJECTS.mergeConflict || ctx.choice !== "Resume") return;
10915
+ const db = gitHubDbSchema.parse(ctx.db);
10916
+ const pullRequestId = ctx.subject.id;
10917
+ const [change] = await wasGitHubPullRequestOpenedIn(db, {
10918
+ conversationId: ctx.conversationId,
10919
+ pullRequestId
10920
+ }) ? await ctx.codeChanges.list({ providerIds: [pullRequestId] }) : [];
10921
+ if (!change) {
10922
+ ctx.log.warn("GitHub merge conflict Resume found no pull request", {
10923
+ conversationId: ctx.conversationId,
10924
+ pullRequestId
10925
+ });
10926
+ await allowGitHubConflictAsk(db, pullRequestId);
10927
+ return;
10928
+ }
9972
10929
  const installationEnv = {
9973
10930
  appIdEnv,
9974
10931
  installationIdEnv,
9975
10932
  privateKeyEnv
9976
10933
  };
9977
10934
  await resumeGitHubConflictFixes({
9978
- codeChanges: ctx.codeChanges,
9979
- db: gitHubDbSchema.parse(ctx.db),
10935
+ db,
9980
10936
  events: ctx.events,
9981
10937
  itemId: ctx.itemId,
9982
10938
  loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
9983
10939
  nowMs: ctx.nowMs,
9984
- ref,
10940
+ pullRequestId,
10941
+ ref: {
10942
+ number: change.number,
10943
+ repositoryFullName: change.repository.name
10944
+ },
9985
10945
  subscription: gitHubPullRequestSubscription(options.pullRequestEvents?.subscribeAfterCreate),
9986
10946
  watches: ctx.watches
9987
10947
  });
@@ -9999,10 +10959,6 @@ function githubPlugin(options = {}) {
9999
10959
  db,
10000
10960
  events: ctx.events,
10001
10961
  loadHistory: async (ref) => await loadPullRequestConflictHistory(installationEnv, ref),
10002
- loadTitleParts: async (input) => await loadGitHubTitleParts({
10003
- ...installationEnv,
10004
- responses: ctx.state
10005
- }, input, ctx.log),
10006
10962
  log: ctx.log,
10007
10963
  now: new Date(ctx.nowMs),
10008
10964
  inboxItems: ctx.inboxItems,
@@ -10038,6 +10994,10 @@ function githubPlugin(options = {}) {
10038
10994
  state: ctx.state,
10039
10995
  tasks: ctx.tasks
10040
10996
  });
10997
+ await startGitHubPullRequestActionBackfill({
10998
+ state: ctx.state,
10999
+ tasks: ctx.tasks
11000
+ });
10041
11001
  },
10042
11002
  async unfinishedWork(ctx) {
10043
11003
  return await listGitHubConversationWork(ctx.codeChanges, ctx.conversationIds);
@@ -10068,10 +11028,10 @@ function githubPlugin(options = {}) {
10068
11028
  installationIdEnv,
10069
11029
  loadRepositoryRole: async (target) => await loadRepositoryRole(installationEnv, ctx.cache, target),
10070
11030
  loadGitHubLogin: async (identityId) => linkedGitHubLogin((await ctx.users.readIdentity(identityId))?.user),
11031
+ findLinkedIdentityIds: async (logins) => await ctx.users.findLinkedIdentityIds(logins),
10071
11032
  loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
10072
11033
  loadPullRequestConflictHistory: async (pullRequest) => await loadPullRequestConflictHistory(installationEnv, pullRequest),
10073
11034
  loadPullRequestCommitPages: async (pullRequest) => await loadPullRequestCommitPages(installationEnv, pullRequest),
10074
- loadTitleParts: async (input) => await loadGitHubTitleParts(installationEnv, input, ctx.log),
10075
11035
  log: ctx.log,
10076
11036
  markFeedbackReviewing: async (target) => await markPullRequestFeedbackReviewing(installationEnv, target),
10077
11037
  privateKeyEnv,
@@ -10126,6 +11086,7 @@ function githubPlugin(options = {}) {
10126
11086
  });
10127
11087
  },
10128
11088
  async onEgressResponse(ctx) {
11089
+ if (isGitHubGraphqlUrl(new URL(ctx.request.url))) await recordGitHubGraphqlSpend(ctx);
10129
11090
  if (ctx.response.status === 403) ctx.log.warn("github.egress.upstream_forbidden", {
10130
11091
  "app.github.accepted_permissions": ctx.response.headers.get("x-accepted-github-permissions") ?? void 0,
10131
11092
  "app.github.sso": ctx.response.headers.get("x-github-sso") ?? void 0