@sentry/junior-github 0.316.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
@@ -2,17 +2,17 @@ import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MAT
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(`
@@ -810,9 +1051,11 @@ const PULL_REQUEST_REQUIRED_CHECKS = githubGraphql(`
810
1051
  /**
811
1052
  * Read what decides whether a reviewer's change request is ready for their
812
1053
  * review again: whether GitHub asks them, when GitHub last asked people for
813
- * a review, their latest 20 reviews with the reactors of each body and
814
- * comment, the checks of the head
815
- * commit, and the branch protection's required checks of the base branch.
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.
816
1059
  */
817
1060
  const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
818
1061
  query PullRequestReviewAgain($owner: String!, $name: String!, $number: Int!, $reviewer: String!) {
@@ -831,18 +1074,11 @@ const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
831
1074
  }
832
1075
  }
833
1076
  }
834
- reviews(last: 20, author: $reviewer, states: [APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED]) {
835
- nodes {
836
- databaseId
837
- state
838
- submittedAt
839
- body
840
- ...FeedbackReactors
841
- comments(first: 100) {
842
- totalCount
843
- nodes { databaseId ...FeedbackReactors }
844
- }
845
- }
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 }
846
1082
  }
847
1083
  commits(last: 1) {
848
1084
  nodes {
@@ -864,6 +1100,18 @@ const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
864
1100
  }
865
1101
  }
866
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
+
867
1115
  fragment FeedbackReactors on Reactable {
868
1116
  reactionGroups {
869
1117
  content
@@ -928,7 +1176,7 @@ function pullRequestLifecycles(count) {
928
1176
  value: `n${index}`
929
1177
  }
930
1178
  });
931
- return operation(visit(parse(PULL_REQUEST_LIFECYCLE.query), {
1179
+ return operation(visit(parse$1(PULL_REQUEST_LIFECYCLE.query), {
932
1180
  OperationDefinition: (node) => ({
933
1181
  ...node,
934
1182
  variableDefinitions: node.variableDefinitions?.flatMap((definition) => definition.variable.name.value === "number" ? indexes.map((index) => ({
@@ -984,6 +1232,10 @@ const PULL_REQUEST_CARD = githubGraphql(`
984
1232
  }
985
1233
  }
986
1234
  }
1235
+ reviewDecision
1236
+ latestOpinionatedReviews(first: 5, writersOnly: true) {
1237
+ nodes { state }
1238
+ }
987
1239
  commits(last: 1) {
988
1240
  nodes {
989
1241
  commit {
@@ -1022,7 +1274,7 @@ const PULL_REQUEST_HEAD_FACT = githubGraphql(`
1022
1274
  }
1023
1275
  `);
1024
1276
  function aliasedPullRequests$1(single, count) {
1025
- const document = parse(single.query);
1277
+ const document = parse$1(single.query);
1026
1278
  const indexes = Array.from({ length: count }, (_, index) => index);
1027
1279
  const indexed = (variable, index) => ({
1028
1280
  ...variable,
@@ -1153,6 +1405,12 @@ const pullRequestCardNodeSchema = pullRequestHeadFactsNodeSchema.extend({
1153
1405
  merged: z.boolean(),
1154
1406
  number: z.number().int().positive(),
1155
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(),
1156
1414
  state: z.enum([
1157
1415
  "CLOSED",
1158
1416
  "MERGED",
@@ -1161,6 +1419,19 @@ const pullRequestCardNodeSchema = pullRequestHeadFactsNodeSchema.extend({
1161
1419
  title: z.string(),
1162
1420
  url: z.string()
1163
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
+ }
1164
1435
  const PASSED_CHECK_RUNS = /* @__PURE__ */ new Set([
1165
1436
  "NEUTRAL",
1166
1437
  "SKIPPED",
@@ -1212,6 +1483,7 @@ function githubPullRequestFieldsFromNode(node) {
1212
1483
  const login = request?.requestedReviewer?.login;
1213
1484
  return login ? [{ login }] : [];
1214
1485
  }),
1486
+ review: pullRequestReview(node),
1215
1487
  state: node.state === "OPEN" ? "open" : "closed",
1216
1488
  title: node.title,
1217
1489
  updated_at: node.updatedAt,
@@ -1265,22 +1537,36 @@ const PAGE_BUDGET_MS = 2e4;
1265
1537
  function cacheKey(ref) {
1266
1538
  return githubObjectCacheKey("pulls", `${ref.owner}/${ref.name}`, ref.number);
1267
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
+ }
1268
1544
  async function missingRefs(ctx, refs) {
1269
1545
  const missing = await pLimit(PREFETCH_CONCURRENCY).map(refs, async (ref) => {
1270
- 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;
1271
1548
  return await viewerCanSeeRepository(ctx, ref);
1272
1549
  });
1273
1550
  return refs.filter((_, index) => missing[index]);
1274
1551
  }
1275
- async function storeCard(ctx, key, node) {
1552
+ async function storeCard(ctx, key, node, startedAtMs) {
1276
1553
  const fields = githubPullRequestFieldsFromNode(node);
1277
- await ctx.cache.update(key, (current) => isOlderGitHubObject(current, fields) ? void 0 : githubPullRequestEntry({
1278
- ...current,
1279
- ...fields
1280
- }));
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
+ });
1281
1566
  }
1282
1567
  async function loadChunk(ctx, refs, deadlineMs) {
1283
- const leftMs = deadlineMs - Date.now();
1568
+ const startedAtMs = Date.now();
1569
+ const leftMs = deadlineMs - startedAtMs;
1284
1570
  if (leftMs <= 0) throw new Error("The page has no time left for cards");
1285
1571
  const response = await githubApi(ctx.egress, {
1286
1572
  body: {
@@ -1296,7 +1582,7 @@ async function loadChunk(ctx, refs, deadlineMs) {
1296
1582
  const nodes = aliasedPullRequests(response.body, refs.length, pullRequestCardNodeSchema);
1297
1583
  await pLimit(PREFETCH_CONCURRENCY).map(refs, async (ref, index) => {
1298
1584
  const node = nodes[index];
1299
- if (node) await storeCard(ctx, cacheKey(ref), node);
1585
+ if (node) await storeCard(ctx, cacheKey(ref), node, startedAtMs);
1300
1586
  });
1301
1587
  }
1302
1588
  async function loadInHalves(args) {
@@ -1345,6 +1631,11 @@ async function prefetchGitHubPullRequests(ctx, refs) {
1345
1631
  return outOfTime;
1346
1632
  }
1347
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
+ });
1348
1639
  const OWNER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
1349
1640
  const REPO_PATTERN = /^[\w.-]{1,100}$/;
1350
1641
  const NUMBER_PATTERN = /^[1-9]\d{0,9}$/;
@@ -1379,9 +1670,25 @@ function issueCard(link, issue) {
1379
1670
  status: issue.state
1380
1671
  });
1381
1672
  }
1382
- 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;
1383
1689
  return githubObjectAnnotation({
1384
- ...githubObjectFacts("code_change", pull),
1690
+ ...card,
1691
+ ...titleParts && card.facts?.type === "code_change" ? { facts: withTitleParts(card.facts, titleParts) } : void 0,
1385
1692
  repo: repoRef(pull.html_url, link),
1386
1693
  number: pull.number,
1387
1694
  title: pull.title,
@@ -1390,6 +1697,52 @@ function pullRequestCard(link, pull) {
1390
1697
  status: pull.merged ? "merged" : pull.state === "open" && pull.draft ? "draft" : pull.state
1391
1698
  });
1392
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
+ }
1393
1746
  /**
1394
1747
  * Read the object fields through the cache, or with the App. Nothing for a
1395
1748
  * missing or deleted object.
@@ -1426,7 +1779,7 @@ async function readFields(ctx, link, schema, entry) {
1426
1779
  async function readObject(ctx, link) {
1427
1780
  if (link.kind === "pull_request") {
1428
1781
  const pull = await readFields(ctx, link, githubPullRequestFieldsSchema, githubPullRequestEntry);
1429
- return pull && pullRequestCard(link, pull);
1782
+ return pull && pullRequestCard(link, pull, await readCategories(ctx, htmlUrlLink(pull.html_url) ?? link));
1430
1783
  }
1431
1784
  const issue = await readFields(ctx, link, githubIssueFieldsSchema, (value) => ({
1432
1785
  ...GITHUB_ISSUE_CACHE,
@@ -1837,13 +2190,19 @@ const table = pgTable("junior_github_pull_request_requesters", {
1837
2190
  identityId: text("identity_id").notNull(),
1838
2191
  /** The Conversation where the person asked Junior to open the pull request. */
1839
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"),
1840
2199
  createdAt: timestamp$1("created_at", { withTimezone: true }).notNull(),
1841
2200
  updatedAt: timestamp$1("updated_at", { withTimezone: true }).notNull()
1842
2201
  }, (table) => [primaryKey({ columns: [
1843
2202
  table.repositoryFullName,
1844
2203
  table.number,
1845
2204
  table.identityId
1846
- ] })]);
2205
+ ] }), uniqueIndex("junior_github_pull_request_requesters_opener_id_uidx").on(table.pullRequestId).where(sql`${table.conversationId} is not null`)]);
1847
2206
  /**
1848
2207
  * Save the person who asked Junior to open a pull request, after GitHub
1849
2208
  * opens it.
@@ -1855,11 +2214,13 @@ const table = pgTable("junior_github_pull_request_requesters", {
1855
2214
  */
1856
2215
  async function recordGitHubPullRequestOpener(db, input) {
1857
2216
  const repositoryFullName = input.repositoryFullName.toLowerCase();
2217
+ const pullRequestId = input.pullRequestId ?? null;
1858
2218
  await db.insert(table).values({
1859
2219
  conversationId: input.conversationId,
1860
2220
  createdAt: input.createdAt,
1861
2221
  identityId: input.identityId,
1862
2222
  number: input.number,
2223
+ pullRequestId,
1863
2224
  repositoryFullName,
1864
2225
  updatedAt: /* @__PURE__ */ new Date()
1865
2226
  }).onConflictDoUpdate({
@@ -1870,7 +2231,8 @@ async function recordGitHubPullRequestOpener(db, input) {
1870
2231
  ],
1871
2232
  set: {
1872
2233
  conversationId: input.conversationId,
1873
- createdAt: input.createdAt
2234
+ createdAt: input.createdAt,
2235
+ ...pullRequestId ? { pullRequestId } : void 0
1874
2236
  }
1875
2237
  });
1876
2238
  await db.delete(table).where(and(eq(table.repositoryFullName, repositoryFullName), eq(table.number, input.number), lt(table.createdAt, input.createdAt)));
@@ -1907,11 +2269,32 @@ async function listGitHubPullRequestOpeners(db, input) {
1907
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));
1908
2270
  for (const row of rows) if (!openers.has(row.number)) openers.set(row.number, {
1909
2271
  identityId: row.identityId,
1910
- ...row.conversationId ? { conversationId: row.conversationId } : void 0
2272
+ ...row.conversationId ? { conversationId: row.conversationId } : void 0,
2273
+ ...row.pullRequestId ? { pullRequestId: row.pullRequestId } : void 0
1911
2274
  });
1912
2275
  return openers;
1913
2276
  }
1914
2277
  /**
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
+ /**
1915
2298
  * Load every requester of each pull request: the person who asked Junior to
1916
2299
  * open it and each person who asked Junior to update it.
1917
2300
  */
@@ -1960,21 +2343,23 @@ const requiredChecksSchema = z.object({
1960
2343
  }) }).nullable() }) })) })
1961
2344
  });
1962
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
+ });
1963
2356
  const reviewAgainSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: requiredChecksSchema.extend({
1964
2357
  reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({
1965
2358
  __typename: z.string(),
1966
2359
  login: z.string().optional()
1967
2360
  }).nullable() }).nullable()) }),
1968
- reviews: z.object({ nodes: z.array(reactorsSchema.extend({
1969
- body: z.string(),
1970
- comments: z.object({
1971
- nodes: z.array(reactorsSchema.extend({ databaseId: z.number().nullable() }).nullable()),
1972
- totalCount: z.number()
1973
- }),
1974
- databaseId: z.number().nullable(),
1975
- state: z.string(),
1976
- submittedAt: z.string().nullable()
1977
- }).nullable()) }),
2361
+ decision: z.object({ nodes: z.array(feedbackReviewSchema.nullable()) }),
2362
+ reviews: z.object({ nodes: z.array(feedbackReviewSchema.nullable()) }),
1978
2363
  timelineItems: z.object({ nodes: z.array(z.object({
1979
2364
  createdAt: z.string().optional(),
1980
2365
  requestedReviewer: z.object({ login: z.string().optional() }).nullable().optional()
@@ -2014,7 +2399,6 @@ function requiredChecksPass(required, contexts, incomplete) {
2014
2399
  }
2015
2400
  return true;
2016
2401
  }
2017
- const REVIEWS_READ = 20;
2018
2402
  /**
2019
2403
  * Return the reviews whose comments Junior must mark before it asks again,
2020
2404
  * oldest first, or undefined when there is no feedback to answer. The
@@ -2024,20 +2408,21 @@ const REVIEWS_READ = 20;
2024
2408
  * comment-only reviews after a later ask count, so a comment on an
2025
2409
  * approved pull request does not ask again. For others, a comment-only
2026
2410
  * review is left out, so a reply to Junior does not hide their change
2027
- * request. A full page of comment-only reviews can hide older reviews,
2028
- * which count as open.
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.
2029
2415
  */
2030
- async function feedbackReviews(reviews, askedAt, commentsCount) {
2031
- let decidedIndex = reviews.length - 1;
2032
- while (decidedIndex >= 0 && reviews[decidedIndex]?.state === "COMMENTED") decidedIndex -= 1;
2033
- const decided = reviews[decidedIndex];
2416
+ async function feedbackReviews(decided, comments, askedAt, commentsCount) {
2034
2417
  const decidedAt = decided?.state === "APPROVED" || decided?.state === "DISMISSED" ? Date.parse(decided.submittedAt ?? "") : void 0;
2035
- const comments = reviews.slice(decidedIndex + 1).filter((review) => decidedAt === void 0 || askedAt > decidedAt && Date.parse(review.submittedAt ?? "") > askedAt);
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
+ });
2036
2424
  const changeRequest = decided?.state === "CHANGES_REQUESTED";
2037
- if (comments.length > 0 && await commentsCount()) {
2038
- if (decided === void 0 && reviews.length >= REVIEWS_READ) return;
2039
- return changeRequest ? [decided, ...comments] : comments;
2040
- }
2425
+ if (feedback.length > 0 && await commentsCount()) return changeRequest ? [decided, ...feedback] : feedback;
2041
2426
  return changeRequest ? [decided] : void 0;
2042
2427
  }
2043
2428
  /**
@@ -2064,7 +2449,7 @@ async function readReviewAgainReadiness(read, target) {
2064
2449
  const lower = reviewer.toLowerCase();
2065
2450
  if (pull.reviewRequests.nodes.some((request) => request?.requestedReviewer?.login?.toLowerCase() === lower)) return "none";
2066
2451
  const askedAt = Math.max(Number.NEGATIVE_INFINITY, ...pull.timelineItems.nodes.flatMap((item) => item?.createdAt && item.requestedReviewer?.login?.toLowerCase() === lower ? [Date.parse(item.createdAt)] : []));
2067
- const reviews = await feedbackReviews(pull.reviews.nodes.filter((review) => review !== null), askedAt, async () => await target.isRequester?.() ?? false);
2452
+ const reviews = await feedbackReviews(pull.decision.nodes[0] ?? void 0, pull.reviews.nodes.filter((review) => review !== null), askedAt, async () => await target.isRequester?.() ?? false);
2068
2453
  if (!reviews) return "none";
2069
2454
  const { marked } = target;
2070
2455
  const justMarked = (id, kind) => marked?.kind === kind && marked.id === id;
@@ -2140,27 +2525,26 @@ async function dropHeldGitHubReviewAsk(state, target, reviewer) {
2140
2525
  await state.delete(heldAskKey(target));
2141
2526
  }
2142
2527
  const ASKED_TTL_MS = 36e5;
2528
+ const SHOWN_TTL_MS = 2592e6;
2143
2529
  const askedSchema = z.object({
2144
2530
  at: z.iso.datetime(),
2145
2531
  reason: z.enum(["handled", "question"]).optional(),
2146
- reviewer: z.string().min(1)
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()
2147
2535
  });
2148
2536
  function askedKey(target) {
2149
2537
  return `pull-request-review-asked:${target.repositoryFullName.toLowerCase()}#${target.number}`;
2150
2538
  }
2151
2539
  /** Record that a Junior tool asked `reviewer` on one pull request. */
2152
2540
  async function markGitHubReviewAsked(state, target, asked) {
2153
- await state.set(askedKey(target), askedSchema.parse(asked), ASKED_TTL_MS);
2541
+ await state.set(askedKey(target), askedSchema.parse(asked), asked.shown ? SHOWN_TTL_MS : ASKED_TTL_MS);
2154
2542
  }
2155
2543
  /** Return the review that a Junior tool asked for on one pull request. */
2156
2544
  async function readGitHubReviewAsked(state, target) {
2157
2545
  const saved = askedSchema.safeParse(await state.get(askedKey(target)));
2158
2546
  return saved.success ? saved.data : void 0;
2159
2547
  }
2160
- /** Drop the record of a review that a Junior tool asked for. */
2161
- async function dropGitHubReviewAsked(state, target) {
2162
- await state.delete(askedKey(target));
2163
- }
2164
2548
  // src/tools/comment-on-pull-request.ts
2165
2549
  const inputSchema$12 = z.object({
2166
2550
  repo: z.string().describe("Repository in \"owner/name\" format."),
@@ -2437,7 +2821,7 @@ const gitHubIssueOutputSchema = pluginToolOutputSchema.merge(gitHubIssueDataSche
2437
2821
  * a person started gets it: no one can answer the item in other runs.
2438
2822
  */
2439
2823
  function implementIssueNote(issue) {
2440
- 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.`;
2441
2825
  }
2442
2826
  async function gitHubIssueToolResult(ctx, input, result) {
2443
2827
  const repo = parseRepo$1(input.repo);
@@ -3045,6 +3429,8 @@ const createPullRequestStateSchema = Type.Union([Type.Object({
3045
3429
  createdAtMs: Type.Number(),
3046
3430
  input: Type.Optional(createPullRequestInputSchema),
3047
3431
  number: Type.Number(),
3432
+ /** GitHub's id of the pull request, for its opener's row. */
3433
+ pullRequestId: Type.Optional(Type.String()),
3048
3434
  facts: Type.Optional(Type.Unknown()),
3049
3435
  sourceUpdatedAt: Type.Optional(Type.String()),
3050
3436
  description: Type.Optional(Type.String({ maxLength: 4e3 })),
@@ -3138,6 +3524,7 @@ async function createGitHubPullRequest(ctx, request) {
3138
3524
  number: pullRequest.number,
3139
3525
  url: pullRequest.html_url
3140
3526
  },
3527
+ ...typeof pullRequest.id === "number" ? { pullRequestId: String(pullRequest.id) } : void 0,
3141
3528
  ...stackTarget.success ? { stackTarget: stackTarget.data } : void 0
3142
3529
  };
3143
3530
  }
@@ -3155,6 +3542,7 @@ async function recordOpener(ctx, input, state, requester) {
3155
3542
  createdAt: new Date(state.createdAtMs),
3156
3543
  identityId,
3157
3544
  number: state.number,
3545
+ pullRequestId: state.pullRequestId,
3158
3546
  repositoryFullName: repo.ref
3159
3547
  });
3160
3548
  await syncGitHubPullRequestRequesters({
@@ -3389,9 +3777,10 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
3389
3777
  };
3390
3778
  await ctx.state.set(key, pendingState, GITHUB_PULL_REQUEST_CREATE_IDEMPOTENCY_TTL_MS);
3391
3779
  let result;
3780
+ let pullRequestId;
3392
3781
  let stackTarget;
3393
3782
  try {
3394
- ({result, stackTarget} = await createGitHubPullRequest(ctx, request));
3783
+ ({pullRequestId, result, stackTarget} = await createGitHubPullRequest(ctx, request));
3395
3784
  } catch (error) {
3396
3785
  if (isEgressAuthRequired(error) || isDefinitiveGitHubPullRequestCreateRejection(error)) await ctx.state.delete(key);
3397
3786
  throw error;
@@ -3400,6 +3789,7 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
3400
3789
  ...pendingState,
3401
3790
  status: "completed",
3402
3791
  number: result.number,
3792
+ ...pullRequestId === void 0 ? void 0 : { pullRequestId },
3403
3793
  url: result.url,
3404
3794
  facts: result.facts,
3405
3795
  ...result.sourceUpdatedAt === void 0 ? void 0 : { sourceUpdatedAt: result.sourceUpdatedAt },
@@ -4396,7 +4786,7 @@ const inputSchema$2 = z.object({
4396
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."),
4397
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."),
4398
4788
  pull_request: z.number().int().positive().describe("Pull request number that the comment is on. Use the exact value from the event."),
4399
- 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.")
4400
4790
  }).strict();
4401
4791
  const outputSchema$2 = pluginToolOutputSchema.extend({
4402
4792
  target: z.literal("updatePullRequestFeedback"),
@@ -4926,223 +5316,103 @@ function createGitHubTools(botEmail, pullRequestSubscription, experimental = {})
4926
5316
  getIssue: gitHubGetIssueTool,
4927
5317
  getPullRequest: gitHubGetPullRequestTool,
4928
5318
  getRelease: gitHubGetReleaseTool,
4929
- getRepository: gitHubGetRepositoryTool,
4930
- getStatus: gitHubGetStatusTool,
4931
- resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(botEmail),
4932
- submitPullRequestReview: gitHubSubmitPullRequestReviewTool,
4933
- updateIssue: gitHubUpdateIssueTool,
4934
- updateIssueComment: createGitHubUpdateIssueCommentTool(botEmail),
4935
- updatePullRequest: createGitHubUpdatePullRequestTool(descriptionChecks),
4936
- updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(botEmail)
4937
- }),
4938
- createPullRequest: createGitHubPullRequestTool(pullRequestSubscription, descriptionChecks)
4939
- };
4940
- }
4941
- // src/code-change-titles/parse.ts
4942
- function nativePattern(source) {
4943
- const regex = new RegExp(source, "i");
4944
- return (title) => {
4945
- const match = regex.exec(title);
4946
- return match ? {
4947
- scope: match.groups?.["scope"],
4948
- type: match.groups?.["type"]
4949
- } : void 0;
4950
- };
4951
- }
4952
- function defaultCategory(title, sources) {
4953
- return {
4954
- custom: false,
4955
- patterns: sources.map(nativePattern),
4956
- title
4957
- };
4958
- }
4959
- /** Craft's `DEFAULT_RELEASE_CONFIG` categories, in match order. */
4960
- const DEFAULT_CODE_CHANGE_CATEGORIES = [
4961
- defaultCategory("Breaking Changes", [String.raw`^(?<type>\w+(?:\((?<scope>[^)]+)\))?!:\s*)`]),
4962
- defaultCategory("Security", [String.raw`^(?<type>security(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
4963
- defaultCategory("New Features", [String.raw`^(?<type>feat(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
4964
- defaultCategory("Bug Fixes", [String.raw`^(?<type>fix(?:\((?<scope>[^)]+)\))?!?:\s*)`, String.raw`^Revert "`]),
4965
- defaultCategory("Documentation", [String.raw`^(?<type>docs?(?:\((?<scope>[^)]+)\))?!?:\s*)`]),
4966
- defaultCategory("Internal Changes", [String.raw`^(?<type>(?:build|refactor|meta|chore|ci|ref|perf|tests?|style)(?:\((?<scope>[^)]+)\))?!?:\s*)`])
4967
- ];
4968
- const TYPE_WORDS = {
4969
- build: "Build",
4970
- chore: "Chore",
4971
- ci: "CI",
4972
- doc: "Docs",
4973
- docs: "Docs",
4974
- feat: "Feature",
4975
- fix: "Fix",
4976
- meta: "Meta",
4977
- perf: "Perf",
4978
- ref: "Refactor",
4979
- refactor: "Refactor",
4980
- revert: "Revert",
4981
- security: "Security",
4982
- style: "Style",
4983
- test: "Test",
4984
- tests: "Test"
4985
- };
4986
- const BREAKING = /^\w+(?:\([^)]+\))?!:/;
4987
- const REVERT = /^Revert "/i;
4988
- const PULL_REQUEST_SUFFIX = /\s*\(#\d+\)$/;
4989
- /** GitHub titles are at most 256 characters, so this bounds regex work. */
4990
- const MAX_TITLE_LENGTH = 256;
4991
- function capitalize(text) {
4992
- return text.charAt(0).toUpperCase() + text.slice(1);
4993
- }
4994
- /** A custom category title as one word pill, without emoji or padding. */
4995
- function categoryWord(title) {
4996
- const word = title.replace(/[\p{Extended_Pictographic}\u{FE0F}\u{200D}]/gu, "").trim();
4997
- return word && !/^breaking\b/i.test(word) ? word : void 0;
4998
- }
4999
- function typeWord(category, token, title) {
5000
- const known = token ? TYPE_WORDS[token.toLowerCase()] : void 0;
5001
- if (known) return known;
5002
- if (!token && REVERT.test(title)) return "Revert";
5003
- return category.custom ? categoryWord(category.title) : void 0;
5004
- }
5005
- function firstMatch(title, categories) {
5006
- for (const category of categories) for (const pattern of category.patterns) {
5007
- const match = pattern(title);
5008
- if (match) return {
5009
- category,
5010
- match
5011
- };
5012
- }
5013
- }
5014
- /**
5015
- * Return the title parts of a pull request title, or undefined when the
5016
- * title has no conventional prefix and no breaking marker. The first
5017
- * matching category wins, as in Craft.
5018
- */
5019
- function parseCodeChangeTitle(title, categories = DEFAULT_CODE_CHANGE_CATEGORIES) {
5020
- const bounded = title.slice(0, MAX_TITLE_LENGTH);
5021
- const breaking = BREAKING.test(bounded);
5022
- const found = firstMatch(bounded, categories) ?? (breaking ? firstMatch(bounded, DEFAULT_CODE_CHANGE_CATEGORIES.slice(0, 1)) : void 0);
5023
- if (!found) return void 0;
5024
- const prefix = found.match.type;
5025
- const token = prefix ? /^\w+/.exec(prefix)?.[0] : void 0;
5026
- const rest = (prefix !== void 0 && bounded.startsWith(prefix) ? title.slice(prefix.length) : title).replace(PULL_REQUEST_SUFFIX, "").trim();
5027
- const type = typeWord(found.category, token, bounded);
5028
- const scope = found.match.scope?.trim();
5029
- return {
5030
- text: rest ? capitalize(rest) : title,
5031
- ...type ? { type } : void 0,
5032
- ...scope ? { scope } : void 0,
5033
- ...breaking ? { breaking: true } : void 0
5319
+ getRepository: gitHubGetRepositoryTool,
5320
+ getStatus: gitHubGetStatusTool,
5321
+ resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(botEmail),
5322
+ submitPullRequestReview: gitHubSubmitPullRequestReviewTool,
5323
+ updateIssue: gitHubUpdateIssueTool,
5324
+ updateIssueComment: createGitHubUpdateIssueCommentTool(botEmail),
5325
+ updatePullRequest: createGitHubUpdatePullRequestTool(descriptionChecks),
5326
+ updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(botEmail)
5327
+ }),
5328
+ createPullRequest: createGitHubPullRequestTool(pullRequestSubscription, descriptionChecks)
5034
5329
  };
5035
5330
  }
5036
- // src/code-change-titles/release-config.ts
5037
- /**
5038
- * A repository's changelog categories from `.github/release.yml`, the file
5039
- * that GitHub release notes and Craft read. Craft adds `commit_patterns` to
5040
- * each category. When the file has categories with patterns, they replace
5041
- * the default categories, as in Craft.
5042
- */
5043
- const MAX_CONFIG_LENGTH = 65536;
5044
- const MAX_CATEGORIES = 30;
5045
- const MAX_PATTERNS = 10;
5046
- const MAX_PATTERN_LENGTH = 200;
5047
- const releaseConfigSchema = z.object({ changelog: z.object({ categories: z.array(z.object({
5048
- commit_patterns: z.array(z.string()).optional(),
5049
- title: z.string().min(1)
5050
- })).optional() }).optional() });
5051
- function compilePattern(source) {
5052
- if (source.length > MAX_PATTERN_LENGTH) return void 0;
5053
- let regex;
5054
- try {
5055
- regex = RE2JS.compile(source, RE2JS.CASE_INSENSITIVE);
5056
- } catch {
5057
- return;
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"
5058
5341
  }
5059
- if (regex.matcher("").find()) return void 0;
5060
- const groups = regex.namedGroups();
5061
- return (title) => {
5062
- const match = regex.matcher(title);
5063
- if (!match.find()) return void 0;
5342
+ };
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
+ };
5064
5354
  return {
5065
- scope: "scope" in groups ? match.group("scope") ?? void 0 : void 0,
5066
- type: "type" in groups ? match.group("type") ?? void 0 : void 0
5355
+ reason: "The pull request is no longer ready to merge.",
5356
+ status: "dismissed"
5067
5357
  };
5068
- };
5069
- }
5070
- /**
5071
- * Return the changelog categories of a `.github/release.yml` text. A file
5072
- * with no usable `commit_patterns`, or one that does not parse, gives the
5073
- * default categories.
5074
- */
5075
- function parseReleaseCategories(text) {
5076
- if (text.length > MAX_CONFIG_LENGTH) return DEFAULT_CODE_CHANGE_CATEGORIES;
5077
- let raw;
5078
- try {
5079
- raw = parse$1(text, { maxAliasCount: 100 });
5080
- } catch {
5081
- return DEFAULT_CODE_CHANGE_CATEGORIES;
5082
5358
  }
5083
- const config = releaseConfigSchema.safeParse(raw);
5084
- if (!config.success) return DEFAULT_CODE_CHANGE_CATEGORIES;
5085
- const categories = (config.data.changelog?.categories ?? []).slice(0, MAX_CATEGORIES).map((category) => ({
5086
- custom: true,
5087
- patterns: (category.commit_patterns ?? []).slice(0, MAX_PATTERNS).map(compilePattern).filter((pattern) => pattern !== void 0),
5088
- title: category.title
5089
- })).filter((category) => category.patterns.length > 0);
5090
- return categories.length > 0 ? categories : DEFAULT_CODE_CHANGE_CATEGORIES;
5359
+ return {
5360
+ reason: "The review request ended.",
5361
+ status: "done"
5362
+ };
5091
5363
  }
5092
- // src/webhooks/title-parts.ts
5093
- /** A repository without the file costs at most one read in this time. */
5094
- const MISSING_TTL_MS = 36e5;
5095
- const contentsSchema = z.object({
5096
- content: z.string(),
5097
- encoding: z.literal("base64")
5098
- });
5099
- function missingKey(repositoryFullName) {
5100
- return `github-release-config-missing:${repositoryFullName.toLowerCase()}`;
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;
5101
5378
  }
5102
5379
  /**
5103
- * Read a repository's changelog categories from GitHub with a read-only
5104
- * token. The file is read with its ETag, and a missing file is remembered
5105
- * for an hour in `env.responses`.
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.
5106
5384
  */
5107
- async function loadReleaseCategories(env, repositoryFullName) {
5108
- const [owner, name] = repositoryFullName.split("/");
5109
- if (!owner || !name) return DEFAULT_CODE_CHANGE_CATEGORIES;
5110
- const state = env.responses;
5111
- if (await state?.get(missingKey(repositoryFullName)).catch(() => void 0)) return DEFAULT_CODE_CHANGE_CATEGORIES;
5112
- const token = await issueInstallationToken({
5113
- ...env,
5114
- permissions: { contents: "read" },
5115
- repositories: [name]
5116
- });
5117
- let response;
5118
- try {
5119
- response = await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/contents/.github/release.yml`, {
5120
- responses: state,
5121
- token: token.token
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]
5122
5392
  });
5123
- } catch (error) {
5124
- if (!(error instanceof GitHubRequestError) || error.status !== 404) throw error;
5125
- await state?.set(missingKey(repositoryFullName), true, MISSING_TTL_MS).catch(() => void 0);
5126
- return DEFAULT_CODE_CHANGE_CATEGORIES;
5393
+ return;
5127
5394
  }
5128
- const file = contentsSchema.safeParse(response);
5129
- if (!file.success) return DEFAULT_CODE_CHANGE_CATEGORIES;
5130
- return parseReleaseCategories(Buffer.from(file.data.content, "base64").toString("utf8"));
5131
- }
5132
- /**
5133
- * Return the title parts of a pull request title with its repository's
5134
- * changelog categories. Title parts are optional, so a failed read of the
5135
- * categories is logged, and the default categories apply.
5136
- */
5137
- async function loadGitHubTitleParts(env, input, log) {
5138
- let categories;
5139
- try {
5140
- categories = await loadReleaseCategories(env, input.repositoryFullName);
5141
- } catch (error) {
5142
- logFailOpenFailure(log, "GitHub release config read failed", error, { repository: input.repositoryFullName });
5143
- categories = DEFAULT_CODE_CHANGE_CATEGORIES;
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;
5144
5404
  }
5145
- return parseCodeChangeTitle(input.title, categories);
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
+ });
5146
5416
  }
5147
5417
  // src/webhooks/pull-request-next-action.ts
5148
5418
  /** Whether two GitHub logins name the same account. */
@@ -5202,7 +5472,7 @@ function timeOf(at) {
5202
5472
  */
5203
5473
  function nextAction(state, requester, saved) {
5204
5474
  if (state.state !== "open") return {};
5205
- const canMerge = !state.draft && !state.autoMerge && !state.reviewPending && !requester.feedback;
5475
+ const canMerge = requester.mergeAccess && !state.draft && !state.autoMerge && !state.reviewPending && !requester.feedback;
5206
5476
  if (canMerge && state.mergeableState === "clean" && state.reviewOutcome !== "changesRequested") return { action: "merge" };
5207
5477
  if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5208
5478
  const review = state.draft ? "review_draft" : "review";
@@ -5428,43 +5698,26 @@ function gitHubConflictAction(input) {
5428
5698
  const fixedAtMs = Math.max(resumedAtMs ?? 0, ...fixes.map(({ atMs }) => atMs));
5429
5699
  return !approved && nowMs - fixedAtMs < FIX_INTERVAL_MS ? "skip" : "fix";
5430
5700
  }
5431
- const ITEM_KEY_PREFIX = "merge-conflict:";
5432
- /** The dedupe key of the merge conflict item of one pull request. */
5433
- function gitHubConflictItemKey(ref) {
5434
- return `${ITEM_KEY_PREFIX}${ref.repositoryFullName.toLowerCase()}#${ref.number}`;
5435
- }
5436
- /** Read the pull request of a merge conflict item's dedupe key. */
5437
- function parseGitHubConflictItemKey(dedupeKey) {
5438
- const match = /^([^/#\s]+\/[^/#\s]+)#(\d+)$/.exec(dedupeKey.startsWith(ITEM_KEY_PREFIX) ? dedupeKey.slice(15) : "");
5439
- return match ? {
5440
- number: Number(match[2]),
5441
- repositoryFullName: match[1]
5442
- } : void 0;
5443
- }
5444
5701
  /** Ask the requester to resume a fix that did not land. */
5445
5702
  async function addUnlandedItem(args) {
5446
- const { conflict, ref, title } = args;
5703
+ const { conflict, ref } = args;
5447
5704
  const opener = (await listGitHubPullRequestOpeners(args.db, {
5448
5705
  numbers: [ref.number],
5449
5706
  repositoryFullName: ref.repositoryFullName
5450
5707
  })).get(ref.number);
5451
5708
  if (!opener?.conversationId) return;
5452
- const url = conflict.url ?? `https://github.com/${ref.repositoryFullName}/pull/${ref.number}`;
5453
- const titleParts = title ? await args.loadTitleParts?.({
5454
- repositoryFullName: ref.repositoryFullName,
5455
- title
5456
- }) : 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
+ });
5457
5715
  await args.inboxItems.forConversation(opener.conversationId).upsert({
5716
+ askedIdentityIds: [opener.identityId],
5458
5717
  assigneeIdentityIds: [opener.identityId],
5459
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.`,
5460
5719
  choices: [{ label: GITHUB_CONFLICT_RESUME }],
5461
- dedupeKey: gitHubConflictItemKey(ref),
5462
- subject: {
5463
- id: url,
5464
- title: title ? `${title} (#${ref.number})` : url,
5465
- ...titleParts ? { titleParts } : void 0,
5466
- url
5467
- },
5720
+ subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, args.pullRequestId),
5468
5721
  title: `Merge conflict · #${ref.number}`
5469
5722
  });
5470
5723
  }
@@ -5505,7 +5758,10 @@ async function applyGitHubConflictPolicy(args) {
5505
5758
  return args.events;
5506
5759
  }
5507
5760
  try {
5508
- await addUnlandedItem(args);
5761
+ await addUnlandedItem({
5762
+ ...args,
5763
+ pullRequestId: change.providerId
5764
+ });
5509
5765
  await args.db.update(t).set({ conflictFixAskedAt: args.now }).where(pullRequest);
5510
5766
  } catch (error) {
5511
5767
  logFailOpenFailure(args.log, "GitHub merge conflict item failed", error, {
@@ -5529,7 +5785,7 @@ async function closeGitHubConflictItem(args) {
5529
5785
  })).get(ref.number);
5530
5786
  if (!opener?.conversationId) return;
5531
5787
  await args.inboxItems.forConversation(opener.conversationId).close({
5532
- dedupeKey: gitHubConflictItemKey(ref),
5788
+ subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, args.pullRequestId),
5533
5789
  reason: args.reason,
5534
5790
  status: args.status
5535
5791
  });
@@ -5553,18 +5809,13 @@ async function closeGitHubConflictItems(args) {
5553
5809
  } })]);
5554
5810
  const pullRequestIds = new Map(changes.map((change) => [change.number, change.providerId]));
5555
5811
  const limit = pLimit(ITEM_CLOSE_CONCURRENCY);
5556
- const close = async (number, conversationId) => {
5812
+ const close = async (number, conversationId, pullRequestId) => {
5557
5813
  try {
5558
- const closed = await args.inboxItems.forConversation(conversationId).close({
5559
- dedupeKey: gitHubConflictItemKey({
5560
- number,
5561
- repositoryFullName
5562
- }),
5814
+ if (await args.inboxItems.forConversation(conversationId).close({
5815
+ subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, pullRequestId),
5563
5816
  reason: args.reason,
5564
5817
  status: args.status
5565
- });
5566
- const pullRequestId = pullRequestIds.get(number);
5567
- 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));
5568
5819
  } catch (error) {
5569
5820
  logFailOpenFailure(args.log, "GitHub merge conflict item close failed", error, {
5570
5821
  number,
@@ -5572,55 +5823,28 @@ async function closeGitHubConflictItems(args) {
5572
5823
  });
5573
5824
  }
5574
5825
  };
5575
- 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
+ }));
5576
5830
  }
5577
- // src/webhooks/pull-request-action-text.ts
5578
- /** Why an item closes when its pull request is no longer open. */
5579
- const ENDED_REASONS = {
5580
- closed: {
5581
- reason: "The pull request closed without merging.",
5582
- status: "dismissed"
5583
- },
5584
- merged: {
5585
- reason: "The pull request merged.",
5586
- status: "done"
5587
- }
5588
- };
5589
- /** Why an item closes, when its pull request is no longer open. */
5590
- function endedReason(state) {
5591
- return state === "open" ? void 0 : ENDED_REASONS[state];
5592
- }
5593
- /** Why the item of a pull request whose next action ended closes. */
5594
- function closeReason(state, previous) {
5595
- const ended = endedReason(state.state);
5596
- if (ended) return ended;
5597
- if (previous !== "merge") return {
5598
- reason: "The review request ended.",
5599
- status: "done"
5600
- };
5601
- if (state.autoMerge) return {
5602
- reason: "Auto-merge is on.",
5603
- status: "dismissed"
5604
- };
5605
- return {
5606
- reason: "The pull request is no longer ready to merge.",
5607
- status: "dismissed"
5608
- };
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()}`;
5609
5836
  }
5610
- /** The item text that says why Junior asked for the review again. */
5611
- const REVIEW_AGAIN_TEXT = {
5612
- checks: "Checks now pass, and every comment is handled.",
5613
- handled: "Every comment on your review is handled.",
5614
- question: "A comment asks you a question."
5615
- };
5616
- /** The item text for a pull request's next action. */
5617
- function actionText(action, number, reason, state) {
5618
- 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.`;
5619
- const asked = reason ? REVIEW_AGAIN_TEXT[reason] : void 0;
5620
- if (action === "review") return asked ?? `GitHub asks you to review #${number}.`;
5621
- if (action === "mark_ready") return `You approved #${number}. Mark it ready for review.`;
5622
- const step = `#${number} is a draft. Review it, then mark it ready for review.`;
5623
- return asked ? `${asked} ${step}` : step;
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)));
5624
5848
  }
5625
5849
  // src/webhooks/graphql-request.ts
5626
5850
  /**
@@ -5920,13 +6144,13 @@ const repositoryPermissionSchema = z.object({
5920
6144
  });
5921
6145
  const REPOSITORY_ROLE_TTL_MS = 6e5;
5922
6146
  /**
5923
- * Read one user's role on a repository, with a metadata-only token. GitHub
5924
- * returns "none" for accounts without access, such as most bots. Roles are
5925
- * 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.
5926
6150
  */
5927
- async function loadRepositoryRole(env, cache, target) {
6151
+ async function loadRepositoryPermission(env, cache, target) {
5928
6152
  const { owner, name } = splitRepository(target.repositoryFullName, "repository role");
5929
- 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 () => {
5930
6154
  const token = await issueInstallationToken({
5931
6155
  ...env,
5932
6156
  permissions: { metadata: "read" },
@@ -5937,11 +6161,26 @@ async function loadRepositoryRole(env, cache, target) {
5937
6161
  token: token.token
5938
6162
  }));
5939
6163
  return {
5940
- value: response.role_name?.trim() || response.permission,
6164
+ value: {
6165
+ permission: response.permission,
6166
+ role: response.role_name?.trim() || response.permission
6167
+ },
5941
6168
  ttlMs: REPOSITORY_ROLE_TTL_MS
5942
6169
  };
5943
6170
  });
5944
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
+ }
5945
6184
  const timestampSchema$1 = z.iso.datetime({ offset: true });
5946
6185
  function nodesSchema(node) {
5947
6186
  return z.array(node.nullable()).transform((items) => items.filter((item) => item !== null));
@@ -6118,30 +6357,12 @@ const ACTION_EVENTS = {
6118
6357
  ]),
6119
6358
  pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
6120
6359
  };
6121
- /**
6122
- * Keys of the two items that came before the one item per pull request.
6123
- * Each check closes them, so no old item stays open next to the new one.
6124
- * Remove them when no item from before is open.
6125
- */
6126
- const LEGACY_DEDUPE_PREFIXES = ["pull-request-ready:", "pull-request-review-requested:"];
6127
- function itemName(target) {
6128
- return `${target.repositoryFullName}#${target.number}`.toLowerCase();
6129
- }
6130
- function actionDedupeKey(target) {
6131
- return `pull-request-action:${itemName(target)}`;
6132
- }
6133
- async function closeLegacyItems(items, name) {
6134
- await Promise.all(LEGACY_DEDUPE_PREFIXES.map((prefix) => items.close({
6135
- dedupeKey: `${prefix}${name}`,
6136
- reason: "One item now shows the next action.",
6137
- status: "dismissed"
6138
- })));
6139
- }
6140
6360
  const repositorySchema$3 = z.object({ full_name: z.string().min(1) });
6141
6361
  const pullRequestWebhookSchema = z.object({
6142
6362
  action: z.string(),
6143
6363
  pull_request: z.object({ number: z.number().int().positive() }),
6144
- repository: repositorySchema$3
6364
+ repository: repositorySchema$3,
6365
+ requested_reviewer: z.object({ login: z.string().min(1) }).nullish()
6145
6366
  });
6146
6367
  const commentWebhookSchema = z.object({
6147
6368
  action: z.literal("created"),
@@ -6171,37 +6392,19 @@ function pullRequestActionTargets(eventName, body) {
6171
6392
  const actions = ACTION_EVENTS[eventName];
6172
6393
  const parsed = pullRequestWebhookSchema.safeParse(body);
6173
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;
6174
6396
  return [{
6175
6397
  number: parsed.data.pull_request.number,
6176
- repositoryFullName: parsed.data.repository.full_name
6398
+ repositoryFullName: parsed.data.repository.full_name,
6399
+ ...reviewer ? { reviewRequested: reviewer } : void 0
6177
6400
  }];
6178
6401
  }
6179
- async function showAction(items, args) {
6180
- const { action, number, state } = args;
6181
- if (action) await items.upsert({
6182
- assigneeIdentityIds: [args.identityId],
6183
- body: `${actionText(action, number, args.reason, state)}\n\n${state.url}`,
6184
- dedupeKey: args.dedupeKey,
6185
- subject: {
6186
- id: state.url,
6187
- title: `${state.title} (#${number})`,
6188
- ...args.titleParts ? { titleParts: args.titleParts } : void 0,
6189
- url: state.url
6190
- },
6191
- title: action === "merge" ? `Ready to merge · #${number}` : `Review requested · #${number}`,
6192
- waitsOnAssignees: true
6193
- });
6194
- else if (args.previous) await items.close({
6195
- dedupeKey: args.dedupeKey,
6196
- ...closeReason(state, args.previous)
6197
- });
6198
- }
6199
6402
  /**
6200
- * Return the closes of the next-action item and the merge conflict notice
6201
- * of a pull request that merged or closed, with the conversation that owns
6202
- * them. Undefined when no person asked Junior for the pull request. The
6203
- * outcome write saves them in one batch with that conversation's chip, so no
6204
- * 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.
6205
6408
  */
6206
6409
  async function endedGitHubPullRequestItemChanges(args) {
6207
6410
  const { target } = args;
@@ -6213,9 +6416,9 @@ async function endedGitHubPullRequestItemChanges(args) {
6213
6416
  const reason = ENDED_REASONS[args.state];
6214
6417
  return {
6215
6418
  conversationId,
6216
- inboxItems: [actionDedupeKey(target), gitHubConflictItemKey(target)].map((dedupeKey) => ({
6419
+ inboxItems: [GITHUB_INBOX_SUBJECTS.pullRequest, GITHUB_INBOX_SUBJECTS.mergeConflict].map((kind) => ({
6217
6420
  close: {
6218
- dedupeKey,
6421
+ subject: pullRequestSubject(kind, target.pullRequestId),
6219
6422
  ...reason
6220
6423
  },
6221
6424
  conversationId
@@ -6286,10 +6489,14 @@ async function askHeldReview(args, target, state, requesterLogin) {
6286
6489
  * wrote when it asked them, if they have not acted since.
6287
6490
  */
6288
6491
  async function askReason(state, target, args) {
6289
- 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;
6290
6493
  const asked = await readGitHubReviewAsked(state, target);
6291
- return asked && sameLogin(asked.reviewer, args.requesterLogin) && timeOf(args.requesterAt) <= Date.parse(asked.at) ? asked.reason ?? "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;
6292
6498
  }
6499
+ /** Read one Junior pull request from GitHub and change its items. */
6293
6500
  async function syncOne(args, target) {
6294
6501
  const opener = (await listGitHubPullRequestOpeners(args.db, {
6295
6502
  numbers: [target.number],
@@ -6297,12 +6504,17 @@ async function syncOne(args, target) {
6297
6504
  })).get(target.number);
6298
6505
  if (!opener?.conversationId) return;
6299
6506
  const items = args.inboxItems.forConversation(opener.conversationId);
6300
- const name = itemName(target);
6301
- const dedupeKey = actionDedupeKey(target);
6302
6507
  const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
6303
6508
  if (target.commentBy !== void 0 && !sameLogin(target.commentBy, requesterLogin)) return;
6304
6509
  const pullRequestId = (await findGitHubPullRequest(args.codeChanges, target))?.providerId;
6305
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);
6306
6518
  const claim = await claimGitHubPullRequestReadySync(args.db, pullRequestId, {
6307
6519
  now: /* @__PURE__ */ new Date(),
6308
6520
  staleMs: READY_SYNC_STALE_MS
@@ -6318,17 +6530,28 @@ async function syncOne(args, target) {
6318
6530
  const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
6319
6531
  const activity = latestActivity(state.activity, requesterLogin);
6320
6532
  const asked = await askHeldReview(args, target, state, requesterLogin);
6321
- const reason = await askReason(args.state, target, {
6533
+ const ask = await askReason(args.state, target, {
6322
6534
  asked,
6323
6535
  requesterAt: activity.requesterAt,
6324
6536
  requesterLogin
6325
6537
  });
6326
- const next = nextAction(state, {
6538
+ const reason = ask?.reason;
6539
+ const requester = {
6327
6540
  actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt),
6328
6541
  askedAgain: asked !== void 0 && reason !== void 0,
6329
6542
  feedback: requesterFeedback(state, activity),
6330
6543
  login: requesterLogin
6544
+ };
6545
+ const decide = (mergeAccess) => nextAction(state, {
6546
+ ...requester,
6547
+ mergeAccess
6331
6548
  }, previous);
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;
6332
6555
  if (!askedRequester && requesterLogin && next !== void 0 && next.action === void 0 && inLimbo(state, activity, requesterLogin) && (args.askAfterRequesterActed || activity.actedAt === void 0)) {
6333
6556
  const [owner = "", name = ""] = target.repositoryFullName.split("/");
6334
6557
  if (await readGitHubRequiredChecksPass(await loadReviewAgainReader(args.env, target.repositoryFullName), {
@@ -6341,28 +6564,40 @@ async function syncOne(args, target) {
6341
6564
  }
6342
6565
  }
6343
6566
  const showsAsk = next?.action === "review" || next?.action === "review_draft";
6344
- const changed = next !== void 0 && (next.action !== previous || reason === "question" && showsAsk);
6345
- if (changed) await showAction(items, {
6346
- action: next.action,
6347
- dedupeKey,
6348
- identityId: opener.identityId,
6349
- number: target.number,
6350
- previous,
6351
- reason,
6352
- state,
6353
- titleParts: next.action ? await loadGitHubTitleParts(args.env, {
6354
- repositoryFullName: target.repositoryFullName,
6355
- title: state.title
6356
- }, args.log) : void 0
6357
- });
6358
- await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
6359
- dedupeKey: gitHubConflictItemKey(target),
6360
- ...endedReason(state.state) ?? {
6361
- reason: "The pull request no longer has merge conflicts.",
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,
6362
6594
  status: "done"
6363
- }
6364
- }) : void 0]);
6365
- if (changed && showsAsk && (reason === "handled" || reason === "question")) await dropGitHubReviewAsked(args.state, target);
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
+ });
6366
6601
  if (!changed) return previous;
6367
6602
  await setGitHubPullRequestNextAction(args.db, pullRequestId, next.action);
6368
6603
  return next.action;
@@ -6408,7 +6643,7 @@ async function retryAfterFailure(env, target, error) {
6408
6643
  return error instanceof GitHubRequestError && error.status >= 500 ? {} : void 0;
6409
6644
  }
6410
6645
  /**
6411
- * Add, change, or close the next-action item of each Junior pull request that
6646
+ * Add, change, or close the item of each Junior pull request that
6412
6647
  * a webhook delivery can change. The item is optional, so a failure does not
6413
6648
  * fail the delivery. A failure that GitHub causes for a while starts a task
6414
6649
  * that syncs the pull request again, when `tasks` is given. Other failures
@@ -6444,7 +6679,7 @@ async function startSyncTask(tasks, target, retry, restarts) {
6444
6679
  const startsAt = Date.now() + (retry.delaySeconds ?? 0) * 1e3;
6445
6680
  await tasks.start({
6446
6681
  ...retry,
6447
- key: `pull-request-action-sync:${itemName(target)}:${Math.floor(startsAt / 6e4)}:${restarts}`,
6682
+ key: `pull-request-action-sync:${`${target.repositoryFullName}#${target.number}`.toLowerCase()}:${Math.floor(startsAt / 6e4)}:${restarts}`,
6448
6683
  name: GITHUB_PULL_REQUEST_ACTION_SYNC_TASK,
6449
6684
  payload: {
6450
6685
  number: target.number,
@@ -6457,6 +6692,7 @@ async function startSyncTask(tasks, target, retry, restarts) {
6457
6692
  function startedTaskSyncContext(ctx, options) {
6458
6693
  return {
6459
6694
  botEmail: options.botEmail,
6695
+ cache: ctx.cache,
6460
6696
  codeChanges: ctx.codeChanges,
6461
6697
  db: gitHubDbSchema.parse(ctx.db),
6462
6698
  env: {
@@ -6464,6 +6700,7 @@ function startedTaskSyncContext(ctx, options) {
6464
6700
  responses: ctx.state,
6465
6701
  tokens: /* @__PURE__ */ new Map()
6466
6702
  },
6703
+ findLinkedIdentityIds: async (logins) => await ctx.users.findLinkedIdentityIds(logins),
6467
6704
  loadGitHubLogin: async (identityId) => linkedGitHubLogin((await ctx.users.readIdentity(identityId))?.user),
6468
6705
  log: ctx.log,
6469
6706
  inboxItems: ctx.inboxItems,
@@ -6762,9 +6999,19 @@ const issueEventSchema = z.object({
6762
6999
  repository: repositorySchema$2
6763
7000
  });
6764
7001
  const pullRequestEventSchema = z.object({
7002
+ action: z.string().optional(),
6765
7003
  pull_request: githubPullRequestFieldsSchema,
6766
7004
  repository: repositorySchema$2
6767
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
+ };
6768
7015
  const checkPullRequestsSchema = z.array(z.object({ number: z.number().int().positive() }));
6769
7016
  const checkSuiteEventSchema = z.object({
6770
7017
  check_suite: z.object({
@@ -6785,18 +7032,24 @@ function goneKey(key) {
6785
7032
  return `gone:${key}`;
6786
7033
  }
6787
7034
  async function refreshPullRequest(args, event) {
6788
- const { pull_request: payload, repository } = event;
7035
+ const { action = "", pull_request: payload, repository } = event;
7036
+ const reviewChanged = REVIEW_ACTIONS.pull_request.has(action);
6789
7037
  const key = githubObjectCacheKey("pulls", repository.full_name, payload.number);
6790
7038
  let patch = false;
6791
7039
  let conflicted = false;
7040
+ if (reviewChanged) await markGitHubReviewCleared(args.cache, key);
6792
7041
  await args.cache.update(key, (current) => {
6793
7042
  const merged = mergeGitHubPullRequest(current, payload);
6794
7043
  patch = merged?.patch ?? false;
6795
7044
  conflicted = merged?.fields.state === "open" && (payload.mergeable === false || patch && current?.mergeable === false);
6796
- return merged && {
7045
+ if (merged) return {
6797
7046
  ...GITHUB_PULL_REQUEST_CACHE,
6798
- value: merged.fields
7047
+ value: reviewChanged ? withoutGitHubReview(merged.fields) : merged.fields
6799
7048
  };
7049
+ return reviewChanged && current?.review !== void 0 ? {
7050
+ ...GITHUB_PULL_REQUEST_CACHE,
7051
+ value: withoutGitHubReview(current)
7052
+ } : void 0;
6800
7053
  });
6801
7054
  if (conflicted) await markGitHubConflict(args.state, {
6802
7055
  number: payload.number,
@@ -6845,7 +7098,8 @@ function checkEventTarget(body, eventName) {
6845
7098
  /**
6846
7099
  * Write the issue or pull request of an `issues` or `pull_request` webhook
6847
7100
  * into its cache entry, so the next card read shows it without a GitHub
6848
- * 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
6849
7103
  * of its pull requests pending. Merge state and checks that turn pending
6850
7104
  * get a patch (`pull-request-patches.ts`).
6851
7105
  */
@@ -6855,6 +7109,18 @@ async function refreshGitHubObjectCache(args) {
6855
7109
  if (event.success) await refreshPullRequest(args, event.data);
6856
7110
  return;
6857
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
+ }
6858
7124
  if (args.eventName === "issues") {
6859
7125
  const event = issueEventSchema.safeParse(args.body);
6860
7126
  if (!event.success) return;
@@ -7238,8 +7504,7 @@ const gitHubPullRequestMergeSchema = z.object({
7238
7504
  html_url: z.string().min(1).optional(),
7239
7505
  mergeable: z.boolean().nullable().optional(),
7240
7506
  mergeable_state: z.string().optional(),
7241
- state: z.string(),
7242
- title: z.string().optional()
7507
+ state: z.string()
7243
7508
  });
7244
7509
  /**
7245
7510
  * Build the `pull_request.merge_conflict` copies for one pull request. With
@@ -7339,12 +7604,10 @@ async function loadGitHubMergeConflictEvents(args) {
7339
7604
  conflict
7340
7605
  }),
7341
7606
  loadHistory: loadConflictHistory,
7342
- loadTitleParts: args.loadTitleParts,
7343
7607
  log: args.log,
7344
7608
  now: /* @__PURE__ */ new Date(),
7345
7609
  ref,
7346
- inboxItems: args.inboxItems,
7347
- ...loaded.title ? { title: loaded.title } : void 0
7610
+ inboxItems: args.inboxItems
7348
7611
  });
7349
7612
  } catch (error) {
7350
7613
  logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
@@ -8056,7 +8319,6 @@ function createGitHubWebhookRoute(args) {
8056
8319
  events,
8057
8320
  hasMatch,
8058
8321
  loadConflictHistory: args.loadPullRequestConflictHistory,
8059
- loadTitleParts: args.loadTitleParts,
8060
8322
  loadPullRequest: args.loadPullRequest,
8061
8323
  log: args.log,
8062
8324
  pullRequestPayload: eventName === "pull_request" ? body : void 0,
@@ -8075,12 +8337,24 @@ function createGitHubWebhookRoute(args) {
8075
8337
  responses: args.state,
8076
8338
  tokens: args.tokens
8077
8339
  };
8340
+ await requestGitHubReviewersWhenReady({
8341
+ body,
8342
+ db: args.db,
8343
+ deliveryId,
8344
+ env,
8345
+ eventName,
8346
+ loadGitHubLogin: args.loadGitHubLogin,
8347
+ log: args.log,
8348
+ state: args.state
8349
+ });
8078
8350
  await syncGitHubPullRequestActions({
8079
8351
  botEmail,
8352
+ cache: args.cache,
8080
8353
  codeChanges: args.codeChanges,
8081
8354
  db: args.db,
8082
8355
  deliveryId,
8083
8356
  env,
8357
+ findLinkedIdentityIds: args.findLinkedIdentityIds,
8084
8358
  loadGitHubLogin: args.loadGitHubLogin,
8085
8359
  log: args.log,
8086
8360
  inboxItems: args.inboxItems,
@@ -8088,16 +8362,6 @@ function createGitHubWebhookRoute(args) {
8088
8362
  targets: pullRequestActionTargets(eventName, body),
8089
8363
  tasks: args.tasks
8090
8364
  });
8091
- await requestGitHubReviewersWhenReady({
8092
- body,
8093
- db: args.db,
8094
- deliveryId,
8095
- env,
8096
- eventName,
8097
- loadGitHubLogin: args.loadGitHubLogin,
8098
- log: args.log,
8099
- state: args.state
8100
- });
8101
8365
  if (!pullRequestOutcome && !closedIssue && !pullRequestConversations && events.length === 0) return new Response("Ignored", { status: 202 });
8102
8366
  return new Response("Accepted", { status: 202 });
8103
8367
  }
@@ -8129,7 +8393,6 @@ const searchNodeSchema = z.union([z.object({
8129
8393
  ]),
8130
8394
  number: z.number().int().positive(),
8131
8395
  state: z.string(),
8132
- title: z.string(),
8133
8396
  url: z.string().min(1)
8134
8397
  }), z.object({}).strict()]);
8135
8398
  const searchResponseSchema = z.object({ data: z.object({ search: z.object({
@@ -8154,12 +8417,10 @@ async function checkConflict(args, input) {
8154
8417
  draft: input.draft,
8155
8418
  events,
8156
8419
  loadHistory: args.loadHistory,
8157
- loadTitleParts: args.loadTitleParts,
8158
8420
  log: args.log,
8159
8421
  now: args.now,
8160
8422
  ref: input.ref,
8161
- inboxItems: args.inboxItems,
8162
- title: input.title
8423
+ inboxItems: args.inboxItems
8163
8424
  })) await args.events.publish(event);
8164
8425
  }
8165
8426
  async function checkRepository(args, repositoryFullName) {
@@ -8197,8 +8458,7 @@ async function checkRepository(args, repositoryFullName) {
8197
8458
  url: node.url
8198
8459
  },
8199
8460
  draft: node.isDraft,
8200
- ref,
8201
- title: node.title
8461
+ ref
8202
8462
  });
8203
8463
  }
8204
8464
  await closeGitHubConflictItems({
@@ -8253,15 +8513,20 @@ async function runGitHubConflictChecks(args) {
8253
8513
  }
8254
8514
  // src/merge-conflict-checks/resume.ts
8255
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
+ /**
8256
8523
  * Resume merge conflict fixes of one open Junior pull request, and start a
8257
8524
  * fix when it is not a draft and GitHub does not say that it can merge.
8258
8525
  * Safe to repeat for one item: the event key names the item, so a retry publishes no second fix.
8259
8526
  */
8260
8527
  async function resumeGitHubConflictFixes(args) {
8261
- const change = await findGitHubPullRequest(args.codeChanges, args.ref);
8262
- if (change?.state !== "open") return;
8263
8528
  const t = juniorGitHubPullRequests;
8264
- const pullRequest = eq(t.pullRequestId, change.providerId);
8529
+ const pullRequest = eq(t.pullRequestId, args.pullRequestId);
8265
8530
  const [row] = await args.db.select({
8266
8531
  fixes: t.conflictFixes,
8267
8532
  resumedAt: t.conflictFixesResumedAt
@@ -8435,6 +8700,7 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
8435
8700
  });
8436
8701
  await closeGitHubConflictItem({
8437
8702
  db: args.db,
8703
+ pullRequestId: String(pullRequest.databaseId),
8438
8704
  ref: {
8439
8705
  number: pullRequest.number,
8440
8706
  repositoryFullName: nameWithOwner
@@ -8730,7 +8996,8 @@ const githubPullRequestRequesterBackfillTask = {
8730
8996
  };
8731
8997
  // src/pull-request-action-backfill.ts
8732
8998
  const GITHUB_PULL_REQUEST_ACTION_BACKFILL_TASK = "backfillPullRequestActions";
8733
- const VERSION = "v1";
8999
+ const VERSION = "v2";
9000
+ const ASK_AFTER_REQUESTER_ACTED = false;
8734
9001
  const CURSOR_KEY = `pull-request-action-backfill:${VERSION}:cursor`;
8735
9002
  const DONE_KEY = `pull-request-action-backfill:${VERSION}:done`;
8736
9003
  const RERUNS_KEY = `pull-request-action-backfill:${VERSION}:reruns`;
@@ -8768,7 +9035,7 @@ function githubPullRequestActionBackfillTask(args) {
8768
9035
  id: Number(change.providerId)
8769
9036
  })).filter(({ id }) => id > after).sort((a, b) => a.id - b.id).slice(0, PAGE_SIZE);
8770
9037
  const busy = await syncGitHubPullRequestActions({
8771
- askAfterRequesterActed: true,
9038
+ askAfterRequesterActed: ASK_AFTER_REQUESTER_ACTED,
8772
9039
  ...startedTaskSyncContext(ctx, {
8773
9040
  botEmail: args.botEmail(),
8774
9041
  env: args.env
@@ -9340,24 +9607,25 @@ function readSpans(text) {
9340
9607
  */
9341
9608
  function namedRepositories(text, spans, configuredOwner) {
9342
9609
  const named = [];
9343
- const add = (offset, owner, name) => {
9610
+ const add = (offset, owner, name, issue) => {
9344
9611
  if (owner && name) named.push({
9345
9612
  offset,
9346
9613
  repository: {
9347
9614
  owner,
9348
9615
  name
9349
- }
9616
+ },
9617
+ issue
9350
9618
  });
9351
9619
  };
9352
9620
  for (const span of spans) {
9353
9621
  if (span.url) {
9354
- 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"]);
9355
9623
  continue;
9356
9624
  }
9357
9625
  const source = text.slice(span.start, span.end);
9358
9626
  for (const { groups, index } of source.matchAll(TEXT_REFERENCE_PATTERN)) {
9359
9627
  const offset = span.start + index;
9360
- add(offset, groups?.["issueOwner"], groups?.["issueRepo"]);
9628
+ add(offset, groups?.["issueOwner"], groups?.["issueRepo"], groups?.["issue"]);
9361
9629
  add(offset, groups?.["commitOwner"], groups?.["commitRepo"]);
9362
9630
  }
9363
9631
  if (!configuredOwner) continue;
@@ -9366,15 +9634,22 @@ function namedRepositories(text, spans, configuredOwner) {
9366
9634
  return named.sort((left, right) => left.offset - right.offset);
9367
9635
  }
9368
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
+ }
9369
9642
  /**
9370
- * Pick the repository of a bare reference at `offset`: the one repository
9371
- * that the text names, else the last one named before the reference when
9372
- * 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.
9373
9648
  */
9374
- function repositoryAt(named, configured, offset) {
9649
+ function repositoryAt(named, configured, offset, issue) {
9375
9650
  if (named.length === 0) return configured;
9376
- const first = named[0].repository;
9377
- 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;
9378
9653
  let nearest;
9379
9654
  for (const entry of named) {
9380
9655
  if (entry.offset >= offset) break;
@@ -9402,7 +9677,7 @@ function linkifyTextReferences(text, start, context) {
9402
9677
  if (known) return known;
9403
9678
  return context.linkProfiles ? `[${reference}](https://github.com/${login})` : reference;
9404
9679
  }
9405
- 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;
9406
9681
  if (!repository) return reference;
9407
9682
  const { owner, name } = repository;
9408
9683
  if (groups["bareIssue"]) {
@@ -9424,11 +9699,12 @@ function linkifyTextReferences(text, start, context) {
9424
9699
  * discussion, and commit URLs always become links. `#123`, `GH-123`,
9425
9700
  * `user@sha`, and full SHAs need a repository: the one that the text names,
9426
9701
  * also as a plain `owner/repo` of the configured owner. When it names
9427
- * several, the last one named before the reference wins. When it names
9428
- * none, the `repo` config value is used. Their link labels name the
9429
- * repository. `@login` becomes the
9430
- * `mention` of the known person with that GitHub login. Other logins become
9431
- * 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.
9432
9708
  * Chat `@name` words are often people who are not GitHub accounts. Set
9433
9709
  * `bareUrls` to keep bare URLs, where the place shows them as cards.
9434
9710
  */
@@ -9440,7 +9716,7 @@ function linkifyGitHubReferences(text, options = {}) {
9440
9716
  const context = {
9441
9717
  linkProfiles: options.githubText === true || named.length > 0,
9442
9718
  mention: options.mention ?? (() => void 0),
9443
- repositoryAt: (offset) => repositoryAt(named, configured, offset)
9719
+ repositoryAt: (offset, issue) => repositoryAt(named, configured, offset, issue)
9444
9720
  };
9445
9721
  let result = "";
9446
9722
  let cursor = 0;
@@ -10334,7 +10610,7 @@ function applyGitHubEgressPolicy(input) {
10334
10610
  denialMessage: toolOnlyWrite.denialMessage
10335
10611
  });
10336
10612
  if (isGitHubIssueRead(input)) enforceEgressPolicy({
10337
- allowed: input.operation === "github.issue.get",
10613
+ allowed: input.operation === "github.issue.get" || input.operation === "github.objects.cards.get",
10338
10614
  denialMessage: ISSUE_READ_DENIAL
10339
10615
  });
10340
10616
  assertGitHubPullRequestApprovalDenied({
@@ -10457,6 +10733,7 @@ function githubPlugin(options = {}) {
10457
10733
  repository: (name) => `https://github.com/${name}`
10458
10734
  },
10459
10735
  images: githubImageSource,
10736
+ inboxSubjects: githubInboxSubjectKinds,
10460
10737
  objectLinks: [
10461
10738
  githubAccountLinks,
10462
10739
  githubIssueLinks,
@@ -10634,21 +10911,37 @@ function githubPlugin(options = {}) {
10634
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." }];
10635
10912
  },
10636
10913
  async inboxItemAnswered(ctx) {
10637
- const ref = parseGitHubConflictItemKey(ctx.dedupeKey);
10638
- 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
+ }
10639
10929
  const installationEnv = {
10640
10930
  appIdEnv,
10641
10931
  installationIdEnv,
10642
10932
  privateKeyEnv
10643
10933
  };
10644
10934
  await resumeGitHubConflictFixes({
10645
- codeChanges: ctx.codeChanges,
10646
- db: gitHubDbSchema.parse(ctx.db),
10935
+ db,
10647
10936
  events: ctx.events,
10648
10937
  itemId: ctx.itemId,
10649
10938
  loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
10650
10939
  nowMs: ctx.nowMs,
10651
- ref,
10940
+ pullRequestId,
10941
+ ref: {
10942
+ number: change.number,
10943
+ repositoryFullName: change.repository.name
10944
+ },
10652
10945
  subscription: gitHubPullRequestSubscription(options.pullRequestEvents?.subscribeAfterCreate),
10653
10946
  watches: ctx.watches
10654
10947
  });
@@ -10666,10 +10959,6 @@ function githubPlugin(options = {}) {
10666
10959
  db,
10667
10960
  events: ctx.events,
10668
10961
  loadHistory: async (ref) => await loadPullRequestConflictHistory(installationEnv, ref),
10669
- loadTitleParts: async (input) => await loadGitHubTitleParts({
10670
- ...installationEnv,
10671
- responses: ctx.state
10672
- }, input, ctx.log),
10673
10962
  log: ctx.log,
10674
10963
  now: new Date(ctx.nowMs),
10675
10964
  inboxItems: ctx.inboxItems,
@@ -10739,10 +11028,10 @@ function githubPlugin(options = {}) {
10739
11028
  installationIdEnv,
10740
11029
  loadRepositoryRole: async (target) => await loadRepositoryRole(installationEnv, ctx.cache, target),
10741
11030
  loadGitHubLogin: async (identityId) => linkedGitHubLogin((await ctx.users.readIdentity(identityId))?.user),
11031
+ findLinkedIdentityIds: async (logins) => await ctx.users.findLinkedIdentityIds(logins),
10742
11032
  loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
10743
11033
  loadPullRequestConflictHistory: async (pullRequest) => await loadPullRequestConflictHistory(installationEnv, pullRequest),
10744
11034
  loadPullRequestCommitPages: async (pullRequest) => await loadPullRequestCommitPages(installationEnv, pullRequest),
10745
- loadTitleParts: async (input) => await loadGitHubTitleParts(installationEnv, input, ctx.log),
10746
11035
  log: ctx.log,
10747
11036
  markFeedbackReviewing: async (target) => await markPullRequestFeedbackReviewing(installationEnv, target),
10748
11037
  privateKeyEnv,