@sentry/junior-github 0.320.0 → 0.322.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.
@@ -1,5 +1,5 @@
1
1
  import * as z from "zod";
2
- import { PluginToolInputError, eventMatchFieldsSchema, mergeEventMatchFields } from "@sentry/junior-plugin-api";
2
+ import { PluginToolInputError, eventMatchFieldsSchema, mergeEventMatchFields, untilAborted } from "@sentry/junior-plugin-api";
3
3
  import { lexer } from "marked";
4
4
  import pLimit from "p-limit";
5
5
  import { createPrivateKey, createSign } from "node:crypto";
@@ -1060,12 +1060,16 @@ function readInstallationPermissions(installation) {
1060
1060
  return readGrantPermissions(parsed.data.permissions);
1061
1061
  }
1062
1062
  // src/installation-tokens.ts
1063
+ /**
1064
+ * Reuse of GitHub App installation tokens. One webhook burst for a pull
1065
+ * request reads it several times, and each read used to mint its own token.
1066
+ */
1063
1067
  /** A token this close to its expiry is minted again. */
1064
1068
  const REUSE_BUFFER_MS = 3e5;
1065
1069
  /**
1066
1070
  * Return the token of the same permissions and repositories while it has
1067
1071
  * time left, or mint one. Concurrent callers share one mint. A failed mint
1068
- * is not kept.
1072
+ * is not kept. `signal` ends only this caller's wait.
1069
1073
  */
1070
1074
  async function reuseInstallationToken(tokens, scope, mint) {
1071
1075
  const key = JSON.stringify([
@@ -1074,16 +1078,14 @@ async function reuseInstallationToken(tokens, scope, mint) {
1074
1078
  scope.repositoryIds ?? null
1075
1079
  ]);
1076
1080
  const pending = tokens.get(key);
1077
- const reused = pending && await pending.catch(() => void 0);
1081
+ const reused = pending && await untilAborted(pending.catch(() => void 0), scope.signal);
1078
1082
  if (reused && reused.expiresAtMs - REUSE_BUFFER_MS > Date.now()) return reused;
1079
1083
  const minted = mint();
1080
1084
  tokens.set(key, minted);
1081
- try {
1082
- return await minted;
1083
- } catch (error) {
1085
+ minted.catch(() => {
1084
1086
  if (tokens.get(key) === minted) tokens.delete(key);
1085
- throw error;
1086
- }
1087
+ });
1088
+ return await untilAborted(minted, scope.signal);
1087
1089
  }
1088
1090
  // src/credential-support.ts
1089
1091
  /**
@@ -1229,7 +1231,8 @@ async function githubRequest(apiBase, path, params) {
1229
1231
  "X-GitHub-Api-Version": "2022-11-28",
1230
1232
  ...params.body ? { "Content-Type": "application/json" } : void 0
1231
1233
  },
1232
- ...params.body ? { body: JSON.stringify(params.body) } : void 0
1234
+ ...params.body ? { body: JSON.stringify(params.body) } : void 0,
1235
+ ...params.signal ? { signal: params.signal } : void 0
1233
1236
  });
1234
1237
  const response = method === "GET" && params.responses ? await params.responses(url, send) : await send({});
1235
1238
  const text = await response.text();
@@ -1553,7 +1556,10 @@ async function issueUserCredential(ctx, options) {
1553
1556
  */
1554
1557
  async function issueInstallationToken(options) {
1555
1558
  if (!options.tokens || options.loadPermissions) return await mintInstallationToken(options);
1556
- return await reuseInstallationToken(options.tokens, options, () => mintInstallationToken(options));
1559
+ return await reuseInstallationToken(options.tokens, options, () => mintInstallationToken({
1560
+ ...options,
1561
+ signal: void 0
1562
+ }));
1557
1563
  }
1558
1564
  async function mintInstallationToken(options) {
1559
1565
  const appId = requireEnv(options.appIdEnv);
@@ -1574,6 +1580,7 @@ async function mintInstallationToken(options) {
1574
1580
  };
1575
1581
  const parsedToken = parseInstallationTokenResponse(await githubRequest("https://api.github.com", `/app/installations/${installationId}/access_tokens`, {
1576
1582
  method: "POST",
1583
+ signal: options.signal,
1577
1584
  token: appJwt,
1578
1585
  body
1579
1586
  }));
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRepositoryFromUrl, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubMessageSchema, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as definedValues, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as pullRequestTargets, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as logFailOpenFailure, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as githubRequest, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-DDjNmMZq.js";
1
+ import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRepositoryFromUrl, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubMessageSchema, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as definedValues, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as pullRequestTargets, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as logFailOpenFailure, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as githubRequest, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-D0hD78c5.js";
2
2
  import * as z from "zod";
3
3
  import { RE2JS } from "re2js";
4
4
  import { parse } from "yaml";
5
- import { EgressAuthRequired, EgressPolicyDenied, OBJECT_FACTS_MAX_BYTES, PluginInboxItemOwnerError, PluginToolInputError, decodeObjectImageRef, defineJuniorPlugin, definePluginTool, enforceEgressPolicy, mergeEventMatchFields, objectFactsBytes, parseShellCommands, pluginToolOutputSchema, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
5
+ import { CACHE_LOAD_TIMEOUT_MS, EgressAuthRequired, EgressPolicyDenied, OBJECT_FACTS_MAX_BYTES, PluginInboxItemOwnerError, PluginToolInputError, decodeObjectImageRef, defineJuniorPlugin, definePluginTool, enforceEgressPolicy, mergeEventMatchFields, objectFactsBytes, parseShellCommands, pluginToolOutputSchema, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
6
6
  import { lexer, walkTokens } from "marked";
7
7
  import { parseFragment } from "parse5";
8
8
  import pLimit from "p-limit";
9
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";
10
+ import { and, asc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql } from "drizzle-orm";
11
11
  import { integer, jsonb, pgTable, primaryKey, text, timestamp as timestamp$1, uniqueIndex } from "drizzle-orm/pg-core";
12
12
  import { Type } from "@sinclair/typebox";
13
13
  import { Value } from "@sinclair/typebox/value";
@@ -74,6 +74,7 @@ const githubAccountLinks = {
74
74
  host: "github.com",
75
75
  pathPattern: "/*"
76
76
  }],
77
+ cacheOnlyReads: true,
77
78
  canView: async () => true,
78
79
  objectTypes: ["person"],
79
80
  async resolve(ctx, url) {
@@ -92,6 +93,8 @@ const GITHUB_INBOX_SUBJECTS = {
92
93
  mergeConflict: "merge_conflict",
93
94
  pullRequest: "pull_request"
94
95
  };
96
+ /** The action of a merge conflict item that resumes the fixes. */
97
+ const GITHUB_CONFLICT_RESUME = "resume";
95
98
  /**
96
99
  * Name the ask on a Junior pull request from its live card. Once it is
97
100
  * approved, GitHub reports that it can merge, and it is no draft, the ask
@@ -137,6 +140,11 @@ const githubInboxSubjectKinds = [
137
140
  owner: pullRequestOwner
138
141
  },
139
142
  {
143
+ actions: [{
144
+ icon: "wrench",
145
+ id: GITHUB_CONFLICT_RESUME,
146
+ label: "Keep fixing"
147
+ }],
140
148
  codeChange: true,
141
149
  kind: GITHUB_INBOX_SUBJECTS.mergeConflict,
142
150
  label: "Merge conflict",
@@ -495,6 +503,8 @@ const githubCheckCountsSchema = z.object({
495
503
  const githubPullRequestFieldsSchema = z.object({
496
504
  ...objectFields,
497
505
  additions: count.optional(),
506
+ approved_by: z.array(person$1).optional(),
507
+ assignees: z.array(person$1).optional(),
498
508
  base: z.object({ ref: z.string() }).optional(),
499
509
  changed_files: count.optional(),
500
510
  checks: z.union([githubCheckCountsSchema, z.literal("pending")]).optional(),
@@ -574,20 +584,77 @@ function githubObjectCacheKey(collection, repo, number) {
574
584
  return `${collection}:${repo}#${number}`.toLowerCase();
575
585
  }
576
586
  /**
577
- * Clear a conflict that the pull request entry still knows for `headSha`,
578
- * after a read that is not the entry's own, such as a webhook or heartbeat
579
- * merge conflict check, finds it mergeable. Otherwise the next push marks
580
- * the fixed conflict again from the entry (`webhooks/object-cache.ts`).
587
+ * Write the merge state that a read which is not the entry's own, such as
588
+ * a webhook or heartbeat merge conflict check, finds for `headSha`. It
589
+ * changes only a known merge state of that head commit: a pending one waits
590
+ * for its patch. Otherwise the next push marks a fixed conflict again from
591
+ * the entry (`webhooks/object-cache.ts`), and a new conflict shows late.
581
592
  */
582
- async function clearGitHubCachedConflict(cache, ref, headSha) {
583
- await cache.update(githubObjectCacheKey("pulls", ref.repositoryFullName, ref.number), (current) => current?.mergeable === false && current.head?.sha === headSha ? {
593
+ async function writeGitHubCachedMergeable(cache, ref, read) {
594
+ await cache.update(githubObjectCacheKey("pulls", ref.repositoryFullName, ref.number), (current) => current?.mergeable === !read.mergeable && current.head?.sha === read.headSha ? {
584
595
  ...GITHUB_PULL_REQUEST_CACHE,
585
596
  value: {
586
597
  ...current,
587
- mergeable: true
598
+ mergeable: read.mergeable
588
599
  }
589
600
  } : void 0);
590
601
  }
602
+ /**
603
+ * Store the fields of a full pull request read, such as a card query, in
604
+ * its entry, unless the entry is newer. Then clear a review decision that a
605
+ * review webhook during the read made stale. Returns whether the entry
606
+ * took the read and whether it changed.
607
+ */
608
+ async function storeGitHubPullRequestFields(cache, key, fields, startedAtMs) {
609
+ let stored = false;
610
+ let changed = false;
611
+ await cache.update(key, (current) => {
612
+ if (isOlderGitHubObject(current, fields)) return void 0;
613
+ stored = true;
614
+ const entry = githubPullRequestEntry({
615
+ ...current,
616
+ ...fields
617
+ });
618
+ changed = JSON.stringify(current) !== JSON.stringify(entry.value);
619
+ return entry;
620
+ });
621
+ if (stored) await clearGitHubReviewAfterRead(cache, key, {
622
+ review: fields.review,
623
+ startedAtMs
624
+ });
625
+ return {
626
+ changed,
627
+ stored
628
+ };
629
+ }
630
+ /**
631
+ * Write the review state that another read of GitHub found, such as the
632
+ * next-action read, into an entry of the same head commit that is not
633
+ * newer than the read. An unset `review` keeps the entry's decision.
634
+ * Returns whether the entry changed.
635
+ */
636
+ async function writeGitHubPullRequestReviewState(cache, key, read) {
637
+ let changed = false;
638
+ await cache.update(key, (current) => {
639
+ if (!current || current.head?.sha !== read.headSha || isOlderGitHubObject(current, { updated_at: read.updatedAt })) return;
640
+ const value = {
641
+ ...current,
642
+ draft: read.draft,
643
+ requested_reviewers: read.requestedReviewers.map((login) => ({ login })),
644
+ ...read.review !== void 0 && { review: read.review }
645
+ };
646
+ changed = JSON.stringify(current) !== JSON.stringify(value);
647
+ return changed ? {
648
+ ...GITHUB_PULL_REQUEST_CACHE,
649
+ value
650
+ } : void 0;
651
+ });
652
+ if (changed) await clearGitHubReviewAfterRead(cache, key, {
653
+ review: read.review,
654
+ startedAtMs: read.startedAtMs
655
+ });
656
+ return changed;
657
+ }
591
658
  /** Whether `next` is older than `current`, so it must not replace it. */
592
659
  function isOlderGitHubObject(current, next) {
593
660
  return Boolean(current?.updated_at && next.updated_at && Date.parse(next.updated_at) < Date.parse(current.updated_at));
@@ -655,6 +722,7 @@ const responseSchema$1 = z.object({
655
722
  body: z.string().nullable().optional(),
656
723
  user: person.nullable().optional(),
657
724
  requested_reviewers: z.array(person).optional(),
725
+ approved_by: z.array(person).optional(),
658
726
  assignees: z.array(person).optional(),
659
727
  labels: z.array(z.union([z.string(), z.object({ name: z.string() })])).optional(),
660
728
  head: z.object({ ref: z.string() }).optional(),
@@ -680,6 +748,7 @@ const short = (value) => {
680
748
  const text = value?.trim();
681
749
  return text ? text.length > 64 ? `${text.slice(0, 63)}…` : text : void 0;
682
750
  };
751
+ const logins = (people) => people?.slice(0, 5).map((user) => short(user.login)).filter(Boolean);
683
752
  /** Remove Junior's footers and HTML comments from a GitHub body. */
684
753
  function visibleBody(body) {
685
754
  let text = (body ?? "").replace(/<!-- junior-(session-footer|request-attribution):start -->[\s\S]*?<!-- junior-\1:end -->/g, "");
@@ -767,7 +836,9 @@ function githubObjectFacts(type, response) {
767
836
  facts: type === "code_change" ? withGitHubPreviewImages({
768
837
  type,
769
838
  author: short(data.user?.login),
770
- reviewers: data.requested_reviewers?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
839
+ reviewers: logins(data.requested_reviewers),
840
+ approvers: logins(data.approved_by),
841
+ assignees: logins(data.assignees),
771
842
  review: data.review ?? void 0,
772
843
  sourceBranch: short(data.head?.ref),
773
844
  targetBranch: short(data.base?.ref),
@@ -778,7 +849,7 @@ function githubObjectFacts(type, response) {
778
849
  deletions: data.deletions
779
850
  }, githubPreviewImageUrls(data.body)) : {
780
851
  type,
781
- assignees: data.assignees?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
852
+ assignees: logins(data.assignees),
782
853
  labels: data.labels?.slice(0, 5).map((label) => short(typeof label === "string" ? label : label.name)).filter(Boolean)
783
854
  }
784
855
  };
@@ -1023,14 +1094,19 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
1023
1094
  baseRefName
1024
1095
  baseRef { associatedPullRequests(states: [OPEN]) { totalCount } }
1025
1096
  commits(last: 1) { nodes { commit { committedDate } } }
1097
+ headRefOid
1026
1098
  isDraft
1027
1099
  isInMergeQueue
1028
1100
  mergeStateStatus
1101
+ reviewDecision
1029
1102
  state
1030
1103
  title
1104
+ updatedAt
1031
1105
  url
1032
1106
  reviewRequests(first: 100) {
1033
- nodes { requestedReviewer { __typename ... on User { login } } }
1107
+ nodes {
1108
+ requestedReviewer { __typename ... on User { login } ... on Bot { login } }
1109
+ }
1034
1110
  }
1035
1111
  reviews(last: 100) {
1036
1112
  pageInfo { hasPreviousPage startCursor }
@@ -1252,6 +1328,7 @@ const PULL_REQUEST_CARD = githubGraphql(`
1252
1328
  }
1253
1329
 
1254
1330
  fragment Card on PullRequest {
1331
+ databaseId
1255
1332
  url
1256
1333
  number
1257
1334
  state
@@ -1268,6 +1345,7 @@ const PULL_REQUEST_CARD = githubGraphql(`
1268
1345
  additions
1269
1346
  deletions
1270
1347
  changedFiles
1348
+ assignees(first: 5) { nodes { login } }
1271
1349
  reviewRequests(first: 5) {
1272
1350
  nodes {
1273
1351
  requestedReviewer {
@@ -1278,7 +1356,7 @@ const PULL_REQUEST_CARD = githubGraphql(`
1278
1356
  }
1279
1357
  reviewDecision
1280
1358
  latestOpinionatedReviews(first: 5, writersOnly: true) {
1281
- nodes { state }
1359
+ nodes { state author { login } }
1282
1360
  }
1283
1361
  commits(last: 1) {
1284
1362
  nodes {
@@ -1305,6 +1383,18 @@ const PULL_REQUEST_HEAD_FACT = githubGraphql(`
1305
1383
  updatedAt
1306
1384
  headRefOid
1307
1385
  mergeable
1386
+ reviewRequests(first: 5) {
1387
+ nodes {
1388
+ requestedReviewer {
1389
+ ... on User { login }
1390
+ ... on Bot { login }
1391
+ }
1392
+ }
1393
+ }
1394
+ reviewDecision
1395
+ latestOpinionatedReviews(first: 5, writersOnly: true) {
1396
+ nodes { state author { login } }
1397
+ }
1308
1398
  commits(last: 1) {
1309
1399
  nodes {
1310
1400
  commit {
@@ -1362,9 +1452,9 @@ function pullRequestCards(count) {
1362
1452
  return aliasedPullRequests$1(PULL_REQUEST_CARD, count);
1363
1453
  }
1364
1454
  /**
1365
- * Return the query that reads only the merge state and check counts of
1366
- * `count` pull requests by repository and number, for the patch after a
1367
- * push. It has the aliases and variables of `pullRequestCards`.
1455
+ * Return the query that reads the merge state, check counts, and review
1456
+ * state of `count` pull requests by repository and number, for the patch.
1457
+ * It has the aliases and variables of `pullRequestCards`.
1368
1458
  */
1369
1459
  function pullRequestHeadFacts(count) {
1370
1460
  return aliasedPullRequests$1(PULL_REQUEST_HEAD_FACT, count);
@@ -1426,20 +1516,33 @@ const stateCount = z.object({
1426
1516
  });
1427
1517
  const rollupSchema = z.object({ contexts: z.object({ checkRunCountsByState: z.array(stateCount).nullable().optional() }) }).nullable();
1428
1518
  const commitsSchema = z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: rollupSchema }) }).nullable()).nullable() });
1519
+ const reviewDecisionSchema = z.enum([
1520
+ "APPROVED",
1521
+ "CHANGES_REQUESTED",
1522
+ "REVIEW_REQUIRED"
1523
+ ]).nullish();
1429
1524
  /** One pull request of `pullRequestHeadFacts`. */
1430
1525
  const pullRequestHeadFactsNodeSchema = z.object({
1431
1526
  commits: commitsSchema,
1527
+ databaseId: z.number().int().positive().nullish(),
1432
1528
  headRefOid: z.string(),
1529
+ latestOpinionatedReviews: z.object({ nodes: z.array(z.object({
1530
+ author: z.object({ login: z.string() }).nullish(),
1531
+ state: z.string()
1532
+ }).nullable()) }).nullish(),
1433
1533
  mergeable: z.enum([
1434
1534
  "CONFLICTING",
1435
1535
  "MERGEABLE",
1436
1536
  "UNKNOWN"
1437
1537
  ]),
1538
+ reviewDecision: reviewDecisionSchema,
1539
+ reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({ login: z.string().optional() }).nullable() }).nullable()).nullable() }).nullable(),
1438
1540
  updatedAt: z.string()
1439
1541
  });
1440
1542
  /** One pull request of `pullRequestCards`. */
1441
1543
  const pullRequestCardNodeSchema = pullRequestHeadFactsNodeSchema.extend({
1442
1544
  additions: z.number().int().nonnegative(),
1545
+ assignees: z.object({ nodes: z.array(z.object({ login: z.string() }).nullable()).nullable() }),
1443
1546
  author: z.object({ login: z.string() }).nullable(),
1444
1547
  baseRefName: z.string(),
1445
1548
  body: z.string(),
@@ -1449,13 +1552,6 @@ const pullRequestCardNodeSchema = pullRequestHeadFactsNodeSchema.extend({
1449
1552
  isDraft: z.boolean(),
1450
1553
  merged: z.boolean(),
1451
1554
  number: z.number().int().positive(),
1452
- reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({ login: z.string().optional() }).nullable() }).nullable()).nullable() }).nullable(),
1453
- reviewDecision: z.enum([
1454
- "APPROVED",
1455
- "CHANGES_REQUESTED",
1456
- "REVIEW_REQUIRED"
1457
- ]).nullish(),
1458
- latestOpinionatedReviews: z.object({ nodes: z.array(z.object({ state: z.string() }).nullable()) }).nullish(),
1459
1555
  state: z.enum([
1460
1556
  "CLOSED",
1461
1557
  "MERGED",
@@ -1464,19 +1560,40 @@ const pullRequestCardNodeSchema = pullRequestHeadFactsNodeSchema.extend({
1464
1560
  title: z.string(),
1465
1561
  url: z.string()
1466
1562
  });
1563
+ /** GitHub's review decision as the cache entry keeps it, or undefined. */
1564
+ function githubReviewDecision(decision) {
1565
+ if (decision === "APPROVED") return "approved";
1566
+ if (decision === "CHANGES_REQUESTED") return "changes_requested";
1567
+ return decision === "REVIEW_REQUIRED" ? "required" : void 0;
1568
+ }
1467
1569
  /**
1468
1570
  * Return GitHub's review decision. A repository that requires no review has
1469
1571
  * none, so the latest review of each writer decides: approved when one
1470
- * approves and none asks for changes.
1572
+ * approves and none asks for changes. `null` when there is none, so a read
1573
+ * replaces a decision that GitHub dropped, such as a dismissed review, and
1574
+ * marks the review read.
1471
1575
  */
1472
- function pullRequestReview(node) {
1473
- if (node.reviewDecision === "APPROVED") return "approved";
1474
- if (node.reviewDecision === "CHANGES_REQUESTED") return "changes_requested";
1475
- if (node.reviewDecision === "REVIEW_REQUIRED") return "required";
1576
+ function githubPullRequestReview(node) {
1577
+ const decision = githubReviewDecision(node.reviewDecision);
1578
+ if (decision) return decision;
1476
1579
  const states = (node.latestOpinionatedReviews?.nodes ?? []).map((review) => review?.state);
1477
1580
  if (states.includes("CHANGES_REQUESTED")) return "changes_requested";
1478
1581
  return states.includes("APPROVED") ? "approved" : null;
1479
1582
  }
1583
+ /** The logins of the reviewers whose review GitHub requests. */
1584
+ function githubRequestedReviewers(node) {
1585
+ return (node.reviewRequests?.nodes ?? []).flatMap((request) => {
1586
+ const login = request?.requestedReviewer?.login;
1587
+ return login ? [{ login }] : [];
1588
+ });
1589
+ }
1590
+ /** The logins of the writers whose latest review approves. */
1591
+ function githubApprovers(node) {
1592
+ return (node.latestOpinionatedReviews?.nodes ?? []).flatMap((review) => {
1593
+ const login = review?.author?.login;
1594
+ return review?.state === "APPROVED" && login ? [{ login }] : [];
1595
+ });
1596
+ }
1480
1597
  const PASSED_CHECK_RUNS = /* @__PURE__ */ new Set([
1481
1598
  "NEUTRAL",
1482
1599
  "SKIPPED",
@@ -1510,6 +1627,8 @@ function githubMergeable(value) {
1510
1627
  function githubPullRequestFieldsFromNode(node) {
1511
1628
  return {
1512
1629
  additions: node.additions,
1630
+ approved_by: githubApprovers(node),
1631
+ assignees: (node.assignees.nodes ?? []).flatMap((user) => user ? [{ login: user.login }] : []),
1513
1632
  base: { ref: node.baseRefName },
1514
1633
  body: node.body,
1515
1634
  changed_files: node.changedFiles,
@@ -1524,11 +1643,8 @@ function githubPullRequestFieldsFromNode(node) {
1524
1643
  mergeable: githubMergeable(node.mergeable),
1525
1644
  merged: node.merged,
1526
1645
  number: node.number,
1527
- requested_reviewers: (node.reviewRequests?.nodes ?? []).flatMap((request) => {
1528
- const login = request?.requestedReviewer?.login;
1529
- return login ? [{ login }] : [];
1530
- }),
1531
- review: pullRequestReview(node),
1646
+ requested_reviewers: githubRequestedReviewers(node),
1647
+ review: githubPullRequestReview(node),
1532
1648
  state: node.state === "OPEN" ? "open" : "closed",
1533
1649
  title: node.title,
1534
1650
  updated_at: node.updatedAt,
@@ -1584,7 +1700,7 @@ function cacheKey(ref) {
1584
1700
  }
1585
1701
  function needsReview(entry) {
1586
1702
  const fields = githubPullRequestFieldsSchema.safeParse(entry);
1587
- return fields.success && fields.data.state === "open" && fields.data.review === void 0;
1703
+ return fields.success && (fields.data.approved_by === void 0 || fields.data.state === "open" && fields.data.review === void 0);
1588
1704
  }
1589
1705
  async function missingRefs(ctx, refs) {
1590
1706
  const missing = await pLimit(PREFETCH_CONCURRENCY).map(refs, async (ref) => {
@@ -1594,21 +1710,6 @@ async function missingRefs(ctx, refs) {
1594
1710
  });
1595
1711
  return refs.filter((_, index) => missing[index]);
1596
1712
  }
1597
- async function storeCard(ctx, key, node, startedAtMs) {
1598
- const fields = githubPullRequestFieldsFromNode(node);
1599
- let stored = false;
1600
- await ctx.cache.update(key, (current) => {
1601
- stored = !isOlderGitHubObject(current, fields);
1602
- return stored ? githubPullRequestEntry({
1603
- ...current,
1604
- ...fields
1605
- }) : void 0;
1606
- });
1607
- if (stored) await clearGitHubReviewAfterRead(ctx.cache, key, {
1608
- review: fields.review,
1609
- startedAtMs
1610
- });
1611
- }
1612
1713
  async function loadChunk(ctx, refs, deadlineMs) {
1613
1714
  const startedAtMs = Date.now();
1614
1715
  const leftMs = deadlineMs - startedAtMs;
@@ -1627,7 +1728,7 @@ async function loadChunk(ctx, refs, deadlineMs) {
1627
1728
  const nodes = aliasedPullRequests(response.body, refs.length, pullRequestCardNodeSchema);
1628
1729
  await pLimit(PREFETCH_CONCURRENCY).map(refs, async (ref, index) => {
1629
1730
  const node = nodes[index];
1630
- if (node) await storeCard(ctx, cacheKey(ref), node, startedAtMs);
1731
+ if (node) await storeGitHubPullRequestFields(ctx.cache, cacheKey(ref), githubPullRequestFieldsFromNode(node), startedAtMs);
1631
1732
  });
1632
1733
  }
1633
1734
  async function loadInHalves(args) {
@@ -1753,9 +1854,9 @@ function releaseConfigKey(link) {
1753
1854
  }
1754
1855
  /**
1755
1856
  * Read the text of a repository's `.github/release.yml` with the App, or
1756
- * an empty text when it has none. A failed read is not cached. A card whose
1757
- * page read ran out of time reads only the cache, and a miss rejects with
1758
- * `OUT_OF_TIME`.
1857
+ * an empty text when it has none. A failed read is not cached. A
1858
+ * cache-only read, and a card whose page read ran out of time, read only
1859
+ * the cache, and a miss rejects with `OUT_OF_TIME`.
1759
1860
  */
1760
1861
  async function readReleaseConfig(ctx, link) {
1761
1862
  const load = async () => {
@@ -1775,7 +1876,12 @@ async function readReleaseConfig(ctx, link) {
1775
1876
  ttlMs: RELEASE_CONFIG_TTL_MS
1776
1877
  };
1777
1878
  };
1778
- return await ctx.cache.getOrLoad(releaseConfigKey(link), ctx.prefetchOutcome === "out_of_time" ? () => Promise.reject(OUT_OF_TIME) : load);
1879
+ if (ctx.cacheOnly || ctx.prefetchOutcome === "out_of_time") {
1880
+ const cached = await ctx.cache.get(releaseConfigKey(link));
1881
+ if (cached === void 0) throw OUT_OF_TIME;
1882
+ return cached;
1883
+ }
1884
+ return await ctx.cache.getOrLoad(releaseConfigKey(link), load);
1779
1885
  }
1780
1886
  /**
1781
1887
  * The change types of a repository. The defaults when the read fails, and
@@ -1815,11 +1921,8 @@ async function readFields(ctx, link, schema, entry) {
1815
1921
  if (!response.ok) throw new Error(`GitHub ${link.kind} lookup failed with HTTP ${response.status}`);
1816
1922
  return entry(schema.parse(response.body));
1817
1923
  };
1818
- if (collection === "pulls" && ctx.prefetchOutcome === "out_of_time") {
1819
- const stale = await ctx.cache.getOrLoad(key, () => Promise.reject(OUT_OF_TIME)).catch((error) => {
1820
- if (error === OUT_OF_TIME) return void 0;
1821
- throw error;
1822
- });
1924
+ if (ctx.cacheOnly || collection === "pulls" && ctx.prefetchOutcome === "out_of_time") {
1925
+ const stale = await ctx.cache.get(key, { stale: true });
1823
1926
  return schema.nullable().safeParse(stale).data ?? null;
1824
1927
  }
1825
1928
  const cached = schema.nullable().safeParse(await ctx.cache.getOrLoad(key, load));
@@ -1836,7 +1939,10 @@ async function readObject(ctx, link) {
1836
1939
  ...GITHUB_ISSUE_CACHE,
1837
1940
  value
1838
1941
  }));
1839
- if (!issue) return null;
1942
+ if (!issue) return ctx.cacheOnly ? await readObject(ctx, {
1943
+ ...link,
1944
+ kind: "pull_request"
1945
+ }) : null;
1840
1946
  return issue.pull_request === void 0 ? issueCard(link, issue) : await readObject(ctx, {
1841
1947
  ...link,
1842
1948
  kind: "pull_request"
@@ -1844,7 +1950,9 @@ async function readObject(ctx, link) {
1844
1950
  }
1845
1951
  async function canViewLink(ctx, url) {
1846
1952
  const link = parseLink(url);
1847
- if (!link || !await viewerCanSeeRepository(ctx, link)) return false;
1953
+ if (!link) return false;
1954
+ if (ctx.cacheOnly) return true;
1955
+ if (!await viewerCanSeeRepository(ctx, link)) return false;
1848
1956
  const card = await readObject(ctx, link);
1849
1957
  if (!card) return true;
1850
1958
  const source = card.url ? htmlUrlLink(card.url) : void 0;
@@ -1863,6 +1971,7 @@ async function resolveLink(ctx, url) {
1863
1971
  * A pull request at its issue URL shows the pull request card.
1864
1972
  */
1865
1973
  const githubIssueLinks = {
1974
+ cacheOnlyReads: true,
1866
1975
  canView: canViewLink,
1867
1976
  filters: [{
1868
1977
  host: "github.com",
@@ -1897,6 +2006,7 @@ async function prefetchLinks(ctx, urls) {
1897
2006
  }
1898
2007
  /** GitHub pull request links, such as `https://github.com/owner/repo/pull/12`. */
1899
2008
  const githubPullRequestLinks = {
2009
+ cacheOnlyReads: true,
1900
2010
  canView: canViewLink,
1901
2011
  filters: [{
1902
2012
  host: "github.com",
@@ -2221,15 +2331,11 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
2221
2331
  /** When the current check started. */
2222
2332
  readySyncAt: timestamp$1("ready_sync_at", { withTimezone: true }),
2223
2333
  /**
2224
- * When a person last chose Resume on the merge conflict item.
2225
- * It counts as activity by a person, so the fix count starts again.
2334
+ * Unused: the merge conflict item history holds the Resumes and asks. A
2335
+ * migration drops it once no release reads it.
2226
2336
  */
2227
2337
  conflictFixesResumedAt: timestamp$1("conflict_fixes_resumed_at", { withTimezone: true }),
2228
- /**
2229
- * When Junior last asked the requester to resume a merge conflict fix
2230
- * that did not land. It asks once after each Resume, so a Dismiss ends
2231
- * the asks on the pull request.
2232
- */
2338
+ /** Unused, like `conflictFixesResumedAt`. */
2233
2339
  conflictFixAskedAt: timestamp$1("conflict_fix_asked_at", { withTimezone: true }),
2234
2340
  /**
2235
2341
  * The latest merge conflict fixes that Junior started, oldest first.
@@ -2332,6 +2438,14 @@ async function listGitHubPullRequestOpeners(db, input) {
2332
2438
  return openers;
2333
2439
  }
2334
2440
  /**
2441
+ * Find the Conversation that opened a pull request, by GitHub's id of the
2442
+ * pull request. Unlike the name, the id holds after a repository rename.
2443
+ */
2444
+ async function findGitHubPullRequestConversation(db, pullRequestId) {
2445
+ const [row] = await db.select({ conversationId: table.conversationId }).from(table).where(and(eq(table.pullRequestId, pullRequestId), isNotNull(table.conversationId))).limit(1);
2446
+ return row?.conversationId ?? void 0;
2447
+ }
2448
+ /**
2335
2449
  * Save GitHub's id of the pull request on its opener's row, when the row
2336
2450
  * has none yet, such as a row from before the create saved the id. The row
2337
2451
  * maps the id to the Conversation that owns the pull request's Inbox items,
@@ -2879,7 +2993,7 @@ const gitHubIssueOutputSchema = pluginToolOutputSchema.merge(gitHubIssueDataSche
2879
2993
  * a person started gets it: no one can answer the item in other runs.
2880
2994
  */
2881
2995
  function implementIssueNote(issue) {
2882
- 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.`;
2996
+ 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 askUserQuestion: question "Start a Thread to implement ${issue}?", options "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.`;
2883
2997
  }
2884
2998
  async function gitHubIssueToolResult(ctx, input, result) {
2885
2999
  const repo = parseRepo$1(input.repo);
@@ -5678,8 +5792,6 @@ const ACTIVE_MS = 2 * DAY_MS;
5678
5792
  const FIX_INTERVAL_MS = DAY_MS;
5679
5793
  /** Fixes in a row, with no activity by a person, before Junior waits. */
5680
5794
  const MAX_FIXES = 3;
5681
- /** The choice of the merge conflict item that resumes the fixes. */
5682
- const GITHUB_CONFLICT_RESUME = "Resume";
5683
5795
  const actorSchema$1 = z.object({ __typename: z.string() }).nullable();
5684
5796
  const timelineItemSchema = z.union([
5685
5797
  z.object({
@@ -5762,30 +5874,49 @@ function parseGitHubConflictHistory(response) {
5762
5874
  function withGitHubConflictFix(fixes, fix) {
5763
5875
  return [...fixes.filter(({ headSha }) => headSha !== fix.headSha), fix].slice(-3);
5764
5876
  }
5877
+ const RESUMING_MS = 3e5;
5878
+ /**
5879
+ * Read the asks from the item history of one pull request, newest first.
5880
+ * A Resume counts only when it started a fix, so one that started none,
5881
+ * such as on a draft, lets the next conflict ask again.
5882
+ */
5883
+ function gitHubConflictAsks(items, fixes, nowMs) {
5884
+ const [latest] = items;
5885
+ const holds = latest?.status === "open" || latest?.status === "dismissed";
5886
+ const resuming = latest?.action === "resume" && nowMs - (latest.closedAtMs ?? 0) < RESUMING_MS && !fixes.some(({ itemId }) => itemId === latest.id);
5887
+ const fix = [...fixes].reverse().find(({ itemId }) => itemId);
5888
+ const resumed = items.some((item) => item.id === fix?.itemId && item.action === "resume");
5889
+ return fix?.itemId && resumed ? {
5890
+ holds,
5891
+ resume: {
5892
+ atMs: fix.atMs,
5893
+ itemId: fix.itemId
5894
+ },
5895
+ resuming
5896
+ } : {
5897
+ holds,
5898
+ resuming
5899
+ };
5900
+ }
5765
5901
  /** Decide what a conflict on one open Junior pull request does. */
5766
5902
  function gitHubConflictAction(input) {
5767
- const { askedAtMs, fixes, nowMs, resumedAtMs } = input;
5903
+ const { asks, fixes, nowMs } = input;
5768
5904
  const { approved } = input.history;
5769
- const activeAtMs = Math.max(input.history.activeAtMs, resumedAtMs ?? 0);
5905
+ const resumedAtMs = asks.resume?.atMs ?? 0;
5906
+ const activeAtMs = Math.max(input.history.activeAtMs, resumedAtMs);
5770
5907
  if (nowMs - activeAtMs > ACTIVE_MS && !approved) return "skip";
5771
- const resuming = resumedAtMs === activeAtMs && fixes.every(({ atMs }) => atMs < resumedAtMs);
5772
- const started = resuming ? resumedAtMs : fixes.find(({ headSha }) => headSha === input.headSha)?.atMs;
5773
- if (started !== void 0) {
5774
- if (nowMs - started >= FIX_INTERVAL_MS) return askedAtMs !== void 0 && askedAtMs > (resumedAtMs ?? 0) ? "skip" : "ask";
5775
- return resuming || started === resumedAtMs ? "skip" : "retry";
5908
+ const started = fixes.find(({ headSha }) => headSha === input.headSha);
5909
+ if (started) {
5910
+ if (nowMs - started.atMs >= FIX_INTERVAL_MS) return asks.holds ? "skip" : "ask";
5911
+ return started.itemId === void 0 ? "retry" : "skip";
5776
5912
  }
5777
5913
  if (fixes.filter(({ atMs }) => atMs >= activeAtMs).length >= MAX_FIXES) return "skip";
5778
- const fixedAtMs = Math.max(resumedAtMs ?? 0, ...fixes.map(({ atMs }) => atMs));
5914
+ const fixedAtMs = Math.max(resumedAtMs, ...fixes.map(({ atMs }) => atMs));
5779
5915
  return !approved && nowMs - fixedAtMs < FIX_INTERVAL_MS ? "skip" : "fix";
5780
5916
  }
5781
5917
  /** Ask the requester to resume a fix that did not land. */
5782
5918
  async function addUnlandedItem(args) {
5783
- const { conflict, ref } = args;
5784
- const opener = (await listGitHubPullRequestOpeners(args.db, {
5785
- numbers: [ref.number],
5786
- repositoryFullName: ref.repositoryFullName
5787
- })).get(ref.number);
5788
- if (!opener?.conversationId) return;
5919
+ const { conflict, opener, ref } = args;
5789
5920
  if (!opener.pullRequestId) await recordGitHubPullRequestOpenerId(args.db, {
5790
5921
  conversationId: opener.conversationId,
5791
5922
  number: ref.number,
@@ -5795,8 +5926,7 @@ async function addUnlandedItem(args) {
5795
5926
  await args.inboxItems.forConversation(opener.conversationId).upsert({
5796
5927
  askedIdentityIds: [opener.identityId],
5797
5928
  assigneeIdentityIds: [opener.identityId],
5798
- 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.`,
5799
- choices: [{ label: GITHUB_CONFLICT_RESUME }],
5929
+ body: `#${ref.number} conflicts with \`${conflict.baseBranch}\`, and the last fix did not land. Keep fixing tries again. Dismiss stops these asks for this pull request.`,
5800
5930
  subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, args.pullRequestId),
5801
5931
  title: `Merge conflict · #${ref.number}`
5802
5932
  });
@@ -5813,20 +5943,23 @@ async function applyGitHubConflictPolicy(args) {
5813
5943
  if (change?.state !== "open") return args.events;
5814
5944
  const t = juniorGitHubPullRequests;
5815
5945
  const pullRequest = eq(t.pullRequestId, change.providerId);
5816
- const [row] = await args.db.select({
5817
- askedAt: t.conflictFixAskedAt,
5818
- fixes: t.conflictFixes,
5819
- resumedAt: t.conflictFixesResumedAt
5820
- }).from(t).where(pullRequest).limit(1);
5946
+ const [row] = await args.db.select({ fixes: t.conflictFixes }).from(t).where(pullRequest).limit(1);
5821
5947
  if (!row) return args.events;
5948
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
5949
+ numbers: [args.ref.number],
5950
+ repositoryFullName: args.ref.repositoryFullName
5951
+ })).get(args.ref.number);
5952
+ const conversationId = opener?.conversationId ?? await findGitHubPullRequestConversation(args.db, change.providerId);
5953
+ const items = conversationId ? await args.inboxItems.forConversation(conversationId).history(pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, change.providerId)) : [];
5822
5954
  const nowMs = args.now.getTime();
5955
+ const asks = gitHubConflictAsks(items, row.fixes, nowMs);
5956
+ if (asks.resuming) return [];
5823
5957
  const action = gitHubConflictAction({
5824
- askedAtMs: row.askedAt?.getTime(),
5958
+ asks,
5825
5959
  fixes: row.fixes,
5826
5960
  headSha: args.conflict.headSha,
5827
5961
  history: parseGitHubConflictHistory(await args.loadHistory(args.ref)),
5828
- nowMs,
5829
- resumedAtMs: row.resumedAt?.getTime()
5962
+ nowMs
5830
5963
  });
5831
5964
  if (action === "skip") return [];
5832
5965
  if (action === "retry") return args.events;
@@ -5837,12 +5970,16 @@ async function applyGitHubConflictPolicy(args) {
5837
5970
  }) }).where(pullRequest);
5838
5971
  return args.events;
5839
5972
  }
5973
+ if (!opener?.conversationId) return [];
5840
5974
  try {
5841
5975
  await addUnlandedItem({
5842
5976
  ...args,
5977
+ opener: {
5978
+ ...opener,
5979
+ conversationId: opener.conversationId
5980
+ },
5843
5981
  pullRequestId: change.providerId
5844
5982
  });
5845
- await args.db.update(t).set({ conflictFixAskedAt: args.now }).where(pullRequest);
5846
5983
  } catch (error) {
5847
5984
  logFailOpenFailure(args.log, "GitHub merge conflict item failed", error, {
5848
5985
  number: args.ref.number,
@@ -5891,11 +6028,11 @@ async function closeGitHubConflictItems(args) {
5891
6028
  const limit = pLimit(ITEM_CLOSE_CONCURRENCY);
5892
6029
  const close = async (number, conversationId, pullRequestId) => {
5893
6030
  try {
5894
- if (await args.inboxItems.forConversation(conversationId).close({
6031
+ await args.inboxItems.forConversation(conversationId).close({
5895
6032
  subject: pullRequestSubject(GITHUB_INBOX_SUBJECTS.mergeConflict, pullRequestId),
5896
6033
  reason: args.reason,
5897
6034
  status: args.status
5898
- })) await args.db.update(juniorGitHubPullRequests).set({ conflictFixAskedAt: null }).where(eq(juniorGitHubPullRequests.pullRequestId, pullRequestId));
6035
+ });
5899
6036
  } catch (error) {
5900
6037
  logFailOpenFailure(args.log, "GitHub merge conflict item close failed", error, {
5901
6038
  number,
@@ -6175,6 +6312,26 @@ async function loadPullRequestHeadFacts(env, refs) {
6175
6312
  token: token.token
6176
6313
  });
6177
6314
  }
6315
+ /**
6316
+ * Read the cards of pull requests by repository and number, in one aliased
6317
+ * query, with a read-only token.
6318
+ */
6319
+ async function loadPullRequestCards(env, refs) {
6320
+ const token = await issueInstallationToken({
6321
+ ...env,
6322
+ permissions: {
6323
+ checks: "read",
6324
+ pull_requests: "read"
6325
+ }
6326
+ });
6327
+ return await githubGraphqlRequest({
6328
+ body: {
6329
+ ...pullRequestCards(refs.length),
6330
+ variables: pullRequestVariables(refs)
6331
+ },
6332
+ token: token.token
6333
+ });
6334
+ }
6178
6335
  /** Read the merge conflict history of one pull request, with a read-only token. */
6179
6336
  async function loadPullRequestConflictHistory(env, pullRequest) {
6180
6337
  const { owner, name } = splitRepository(pullRequest.repositoryFullName, "pull request conflict history");
@@ -6286,13 +6443,16 @@ const REPOSITORY_ROLE_TTL_MS = 6e5;
6286
6443
  async function loadRepositoryPermission(env, cache, target) {
6287
6444
  const { owner, name } = splitRepository(target.repositoryFullName, "repository role");
6288
6445
  return await cache.getOrLoad(`repository-permission:${owner}/${name}:${target.login}`.toLowerCase(), async () => {
6446
+ const signal = AbortSignal.timeout(CACHE_LOAD_TIMEOUT_MS);
6289
6447
  const token = await issueInstallationToken({
6290
6448
  ...env,
6291
6449
  permissions: { metadata: "read" },
6292
- repositories: [name]
6450
+ repositories: [name],
6451
+ signal
6293
6452
  });
6294
6453
  const response = repositoryPermissionSchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/collaborators/${encodeURIComponent(target.login)}/permission`, {
6295
6454
  responses: env.responses,
6455
+ signal,
6296
6456
  token: token.token
6297
6457
  }));
6298
6458
  return {
@@ -6346,9 +6506,15 @@ const nextActionSchema = z.object({ data: z.object({ repository: z.object({
6346
6506
  baseRef: z.object({ associatedPullRequests: z.object({ totalCount: z.number() }) }).nullable(),
6347
6507
  baseRefName: z.string(),
6348
6508
  commits: z.object({ nodes: nodesSchema(z.object({ commit: z.object({ committedDate: timestampSchema$1 }) })) }),
6509
+ headRefOid: z.string(),
6349
6510
  isDraft: z.boolean(),
6350
6511
  isInMergeQueue: z.boolean(),
6351
6512
  mergeStateStatus: z.string(),
6513
+ reviewDecision: z.enum([
6514
+ "APPROVED",
6515
+ "CHANGES_REQUESTED",
6516
+ "REVIEW_REQUIRED"
6517
+ ]).nullish(),
6352
6518
  reviewRequests: z.object({ nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })) }),
6353
6519
  reviews: reviewsSchema,
6354
6520
  state: z.enum([
@@ -6375,6 +6541,7 @@ const nextActionSchema = z.object({ data: z.object({ repository: z.object({
6375
6541
  })
6376
6542
  ])) }),
6377
6543
  title: z.string(),
6544
+ updatedAt: timestampSchema$1,
6378
6545
  url: z.string().url()
6379
6546
  })
6380
6547
  }) }) });
@@ -6456,14 +6623,18 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
6456
6623
  baseOpen: pull.baseRefName !== repository.defaultBranchRef?.name && (pull.baseRef?.associatedPullRequests.totalCount ?? 0) > 0,
6457
6624
  draft: pull.isDraft,
6458
6625
  ...headCommittedAt ? { headCommittedAt: new Date(headCommittedAt) } : void 0,
6626
+ headSha: pull.headRefOid,
6459
6627
  inMergeQueue: pull.isInMergeQueue,
6460
6628
  ...mergeableState ? { mergeableState } : void 0,
6461
6629
  requesterApproved: false,
6462
6630
  requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" && request.requestedReviewer.login ? [request.requestedReviewer.login] : []),
6631
+ ...pull.reviewDecision ? { reviewDecision: pull.reviewDecision } : void 0,
6463
6632
  reviewPending: pull.reviewRequests.nodes.length > 0,
6633
+ reviewRequestLogins: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.login ? [request.requestedReviewer.login] : []),
6464
6634
  reviewedBy: [],
6465
6635
  state: pull.state === "MERGED" ? "merged" : pull.state === "OPEN" ? "open" : "closed",
6466
6636
  title: pull.title,
6637
+ updatedAt: pull.updatedAt,
6467
6638
  url: pull.url
6468
6639
  };
6469
6640
  const latest = /* @__PURE__ */ new Map();
@@ -6642,6 +6813,26 @@ async function askReason(state, target, args) {
6642
6813
  reason: asked.reason ?? "handled"
6643
6814
  } : void 0;
6644
6815
  }
6816
+ function cardReview(state) {
6817
+ const decision = githubReviewDecision(state.reviewDecision);
6818
+ if (decision || state.state !== "open" || state.draft) return decision;
6819
+ if (state.reviewOutcome === "changesRequested") return "changes_requested";
6820
+ return state.reviewOutcome === "approved" ? "approved" : null;
6821
+ }
6822
+ async function cacheReviewState(args, target, pullRequestId, state, startedAtMs) {
6823
+ const review = cardReview(state);
6824
+ if (await writeGitHubPullRequestReviewState(args.cache, githubObjectCacheKey("pulls", target.repositoryFullName, target.number), {
6825
+ draft: state.draft,
6826
+ headSha: state.headSha,
6827
+ requestedReviewers: state.reviewRequestLogins,
6828
+ ...review !== void 0 && { review },
6829
+ startedAtMs,
6830
+ updatedAt: state.updatedAt
6831
+ })) await args.objectChanged({
6832
+ id: pullRequestId,
6833
+ kind: GITHUB_INBOX_SUBJECTS.pullRequest
6834
+ });
6835
+ }
6645
6836
  /** Read one Junior pull request from GitHub and change its items. */
6646
6837
  async function syncOne(args, target) {
6647
6838
  const opener = (await listGitHubPullRequestOpeners(args.db, {
@@ -6673,7 +6864,9 @@ async function syncOne(args, target) {
6673
6864
  let failure;
6674
6865
  let askedRequester = false;
6675
6866
  const check = async (previous) => {
6867
+ const startedAtMs = Date.now();
6676
6868
  const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
6869
+ await cacheReviewState(args, target, pullRequestId, state, startedAtMs);
6677
6870
  const activity = latestActivity(state.activity, requesterLogin);
6678
6871
  const asked = await askHeldReview(args, target, state, requesterLogin);
6679
6872
  const ask = await askReason(args.state, target, {
@@ -6848,6 +7041,7 @@ function startedTaskSyncContext(ctx, options) {
6848
7041
  loadGitHubLogin: async (identityId) => linkedGitHubLogin((await ctx.users.readIdentity(identityId))?.user),
6849
7042
  log: ctx.log,
6850
7043
  inboxItems: ctx.inboxItems,
7044
+ objectChanged: async (subject) => await ctx.annotations.objectChanged(subject),
6851
7045
  state: ctx.state
6852
7046
  };
6853
7047
  }
@@ -7020,7 +7214,6 @@ async function startGitHubPullRequestPatch(args) {
7020
7214
  }
7021
7215
  });
7022
7216
  }
7023
- const headFactsNodeSchema = pullRequestHeadFactsNodeSchema.extend({ databaseId: z.number().int().positive().nullish() });
7024
7217
  async function writeHeadFacts(cache, key, node, last) {
7025
7218
  const mergeable = githubMergeable(node.mergeable);
7026
7219
  let outcome = "done";
@@ -7041,10 +7234,13 @@ async function writeHeadFacts(cache, key, node, last) {
7041
7234
  written = true;
7042
7235
  const value = {
7043
7236
  ...current,
7237
+ approved_by: githubApprovers(node),
7044
7238
  checks: githubCheckCounts(node.commits),
7045
- mergeable: mergeable ?? current.mergeable
7239
+ mergeable: mergeable ?? current.mergeable,
7240
+ requested_reviewers: githubRequestedReviewers(node),
7241
+ review: githubPullRequestReview(node)
7046
7242
  };
7047
- changed = JSON.stringify([current.checks, current.mergeable]) !== JSON.stringify([value.checks, value.mergeable]);
7243
+ changed = JSON.stringify(current) !== JSON.stringify(value);
7048
7244
  return {
7049
7245
  ...computing && last ? GITHUB_PULL_REQUEST_PENDING_CACHE : GITHUB_PULL_REQUEST_CACHE,
7050
7246
  value
@@ -7083,33 +7279,55 @@ async function expirePending(cache, key) {
7083
7279
  value: current
7084
7280
  } : void 0);
7085
7281
  }
7282
+ async function storeCard(ctx, ref, loadCards) {
7283
+ const startedAtMs = Date.now();
7284
+ const [node] = aliasedPullRequests(await loadCards([ref]), 1, pullRequestCardNodeSchema);
7285
+ if (!node) return;
7286
+ const { changed, stored } = await storeGitHubPullRequestFields(ctx.cache, ctx.payload.key, githubPullRequestFieldsFromNode(node), startedAtMs);
7287
+ if (stored && node.state === "OPEN") await observeMergeState(ctx, ref, node);
7288
+ if (node.databaseId && changed) await ctx.annotations.objectChanged({
7289
+ id: String(node.databaseId),
7290
+ kind: GITHUB_INBOX_SUBJECTS.pullRequest
7291
+ });
7292
+ }
7086
7293
  /**
7087
- * Read the merge state and checks of one pull request and write them into
7088
- * its entry. While the read is not final, the task throws, and the queue
7089
- * delivers it again with backoff. On the last delivery, a merge state
7090
- * that GitHub still computes stays pending only briefly, so the next read
7091
- * asks GitHub. A pull request missing from the answer, of another head
7092
- * commit, or whose query fails on the last delivery, leaves its pending
7093
- * fields fresh only briefly too. A change calls `objectChanged`.
7294
+ * Read the merge state, checks, and review state of one pull request into
7295
+ * its entry, or its whole card when it has none. While the read is not
7296
+ * final, the task throws, and the queue delivers it again with backoff. On
7297
+ * the last delivery, a merge state that GitHub still computes stays pending
7298
+ * only briefly, so the next read asks GitHub. A pull request missing from
7299
+ * the answer, of another head commit, or whose query fails on the last
7300
+ * delivery, leaves its pending fields fresh only briefly too.
7094
7301
  */
7095
- function githubPullRequestPatchTask(loadHeadFacts) {
7302
+ function githubPullRequestPatchTask(loaders) {
7096
7303
  return {
7097
7304
  payload: payloadSchema$4,
7098
7305
  async run(ctx) {
7099
7306
  const { key, sha } = ctx.payload;
7100
7307
  const ref = pullRequestRefFromCacheKey(key);
7101
7308
  if (!ref) throw new Error(`GitHub patch key ${key} names no pull request`);
7102
- const cached = await ctx.cache.get(key);
7309
+ const cached = await ctx.cache.get(key, { stale: true });
7310
+ if (cached === void 0) {
7311
+ await storeCard(ctx, ref, loaders.loadCards);
7312
+ return;
7313
+ }
7103
7314
  if (cached && cached.head?.sha !== sha) return;
7315
+ const startedAtMs = Date.now();
7104
7316
  let node;
7105
7317
  try {
7106
- [node] = aliasedPullRequests(await loadHeadFacts([ref]), 1, headFactsNodeSchema);
7318
+ [node] = aliasedPullRequests(await loaders.loadHeadFacts([ref]), 1, pullRequestHeadFactsNodeSchema);
7107
7319
  } catch (error) {
7108
7320
  if (ctx.lastDelivery) await expirePending(ctx.cache, key);
7109
7321
  throw error;
7110
7322
  }
7111
7323
  const write = node ? await writeHeadFacts(ctx.cache, key, node, ctx.lastDelivery) : void 0;
7112
- if (node && write?.written) await observeMergeState(ctx, ref, node);
7324
+ if (node && write?.written) {
7325
+ await clearGitHubReviewAfterRead(ctx.cache, key, {
7326
+ review: githubPullRequestReview(node),
7327
+ startedAtMs
7328
+ });
7329
+ await observeMergeState(ctx, ref, node);
7330
+ }
7113
7331
  if (node?.databaseId && write?.changed) await ctx.annotations.objectChanged({
7114
7332
  id: String(node.databaseId),
7115
7333
  kind: GITHUB_INBOX_SUBJECTS.pullRequest
@@ -7134,7 +7352,10 @@ const pullRequestEventSchema = z.object({
7134
7352
  });
7135
7353
  const pullRequestReviewEventSchema = z.object({
7136
7354
  action: z.string().optional(),
7137
- pull_request: z.object({ number: z.number().int().positive() }),
7355
+ pull_request: z.object({
7356
+ head: z.object({ sha: z.string().min(1) }).optional(),
7357
+ number: z.number().int().positive()
7358
+ }),
7138
7359
  repository: repositorySchema$2
7139
7360
  });
7140
7361
  const REVIEW_ACTIONS = {
@@ -7204,7 +7425,7 @@ async function refreshPullRequest(args, event) {
7204
7425
  repositoryFullName: repository.full_name
7205
7426
  });
7206
7427
  const sha = payload.head?.sha;
7207
- if (patch && sha) await startGitHubPullRequestPatch({
7428
+ if (sha && (patch || reviewChanged)) await startGitHubPullRequestPatch({
7208
7429
  key,
7209
7430
  nowMs: args.nowMs,
7210
7431
  sha,
@@ -7216,6 +7437,10 @@ async function refreshChecks(args, pulls, sha) {
7216
7437
  let patch = false;
7217
7438
  let changed = false;
7218
7439
  await args.cache.update(key, (current) => {
7440
+ if (current === void 0) {
7441
+ patch = true;
7442
+ return;
7443
+ }
7219
7444
  if (current?.state !== "open" || current.head?.sha !== sha) return void 0;
7220
7445
  patch = true;
7221
7446
  changed = current.checks !== "pending";
@@ -7255,9 +7480,9 @@ function checkEventTarget(body, eventName) {
7255
7480
  /**
7256
7481
  * Write the issue or pull request of an `issues` or `pull_request` webhook
7257
7482
  * into its cache entry, so the next card read needs no GitHub call. A
7258
- * webhook that can change the review decision clears it. A check webhook
7259
- * marks its pull requests' checks pending, which gets a patch
7260
- * (`pull-request-patches.ts`). A write that changes an entry calls
7483
+ * review webhook clears the review decision, and a check webhook marks the
7484
+ * checks pending. Both get a patch that reads them again, or stores a whole
7485
+ * card (`pull-request-patches.ts`). A write that changes an entry calls
7261
7486
  * `objectChanged`.
7262
7487
  */
7263
7488
  async function refreshGitHubObjectCache(args) {
@@ -7273,7 +7498,9 @@ async function refreshGitHubObjectCache(args) {
7273
7498
  const key = githubObjectCacheKey("pulls", event.data.repository.full_name, event.data.pull_request.number);
7274
7499
  await markGitHubReviewCleared(args.cache, key);
7275
7500
  let changed = false;
7501
+ let sha = event.data.pull_request.head?.sha;
7276
7502
  await args.cache.update(key, (current) => {
7503
+ sha ??= current?.head?.sha;
7277
7504
  if (current?.review === void 0) return void 0;
7278
7505
  changed = true;
7279
7506
  return {
@@ -7283,6 +7510,12 @@ async function refreshGitHubObjectCache(args) {
7283
7510
  });
7284
7511
  const subject = webhookSubject(args.body, "pull_request");
7285
7512
  if (changed && subject) await args.objectChanged(subject);
7513
+ if (sha) await startGitHubPullRequestPatch({
7514
+ key,
7515
+ nowMs: args.nowMs,
7516
+ sha,
7517
+ tasks: args.tasks
7518
+ });
7286
7519
  return;
7287
7520
  }
7288
7521
  if (args.eventName === "issues") {
@@ -7761,7 +7994,10 @@ async function loadGitHubMergeConflictEvents(args) {
7761
7994
  const loaded = deliveredPullRequest(args.pullRequestPayload, ref) ?? gitHubPullRequestMergeSchema.parse(await loadPullRequest(ref));
7762
7995
  if (loaded.state !== "open") return [];
7763
7996
  if (loaded.mergeable === true) {
7764
- await clearGitHubCachedConflict(args.cache, ref, loaded.head.sha);
7997
+ await writeGitHubCachedMergeable(args.cache, ref, {
7998
+ headSha: loaded.head.sha,
7999
+ mergeable: true
8000
+ });
7765
8001
  await publishGitHubConflictResolved({
7766
8002
  events: args.publisher,
7767
8003
  headSha: loaded.head.sha,
@@ -8573,6 +8809,7 @@ function createGitHubWebhookRoute(args) {
8573
8809
  loadGitHubLogin: args.loadGitHubLogin,
8574
8810
  log: args.log,
8575
8811
  inboxItems: args.inboxItems,
8812
+ objectChanged: async (subject) => await args.annotations.objectChanged(subject),
8576
8813
  state: args.state,
8577
8814
  targets: pullRequestActionTargets(eventName, body),
8578
8815
  tasks: args.tasks
@@ -8654,9 +8891,12 @@ async function checkRepository(args, repositoryFullName) {
8654
8891
  repositoryFullName
8655
8892
  };
8656
8893
  if (node.mergeable === "UNKNOWN") unknown = true;
8894
+ else await writeGitHubCachedMergeable(args.cache, ref, {
8895
+ headSha: node.headRefOid,
8896
+ mergeable: node.mergeable === "MERGEABLE"
8897
+ });
8657
8898
  if (node.mergeable === "MERGEABLE") {
8658
8899
  mergeable.push(node.number);
8659
- await clearGitHubCachedConflict(args.cache, ref, node.headRefOid);
8660
8900
  await publishGitHubConflictResolved({
8661
8901
  events: args.events,
8662
8902
  headSha: node.headRefOid,
@@ -8728,13 +8968,6 @@ async function runGitHubConflictChecks(args) {
8728
8968
  }
8729
8969
  // src/merge-conflict-checks/resume.ts
8730
8970
  /**
8731
- * Let the conflict policy ask again about one pull request, after a Resume
8732
- * that could not start a fix.
8733
- */
8734
- async function allowGitHubConflictAsk(db, pullRequestId) {
8735
- await db.update(juniorGitHubPullRequests).set({ conflictFixAskedAt: null }).where(eq(juniorGitHubPullRequests.pullRequestId, pullRequestId));
8736
- }
8737
- /**
8738
8971
  * Resume merge conflict fixes of one open Junior pull request, and start a
8739
8972
  * fix when it is not a draft and GitHub does not say that it can merge.
8740
8973
  * Safe to repeat for one item: the event key names the item, so a retry publishes no second fix.
@@ -8742,22 +8975,10 @@ async function allowGitHubConflictAsk(db, pullRequestId) {
8742
8975
  async function resumeGitHubConflictFixes(args) {
8743
8976
  const t = juniorGitHubPullRequests;
8744
8977
  const pullRequest = eq(t.pullRequestId, args.pullRequestId);
8745
- const [row] = await args.db.select({
8746
- fixes: t.conflictFixes,
8747
- resumedAt: t.conflictFixesResumedAt
8748
- }).from(t).where(pullRequest);
8978
+ const [row] = await args.db.select({ fixes: t.conflictFixes }).from(t).where(pullRequest);
8749
8979
  if (!row) return;
8750
- const resumedAt = new Date(args.nowMs);
8751
- await args.db.update(t).set({ conflictFixesResumedAt: resumedAt }).where(pullRequest);
8752
- const undo = () => args.db.update(t).set({
8753
- conflictFixAskedAt: null,
8754
- conflictFixesResumedAt: row.resumedAt
8755
- }).where(and(pullRequest, eq(t.conflictFixesResumedAt, resumedAt)));
8756
8980
  const loaded = gitHubPullRequestMergeSchema.parse(await args.loadPullRequest(args.ref));
8757
- if (loaded.state !== "open" || loaded.mergeable === true || loaded.draft === true) {
8758
- await undo();
8759
- return;
8760
- }
8981
+ if (loaded.state !== "open" || loaded.mergeable === true || loaded.draft === true) return;
8761
8982
  const events = gitHubMergeConflictEvents({
8762
8983
  ...args.ref,
8763
8984
  conflict: {
@@ -8781,15 +9002,11 @@ async function resumeGitHubConflictFixes(args) {
8781
9002
  ...gitHubPullRequestCreateWatch(args.subscription, { draft: false }),
8782
9003
  resource
8783
9004
  });
8784
- try {
8785
- for (const event of events) await args.events.publish(event);
8786
- } catch (error) {
8787
- await undo();
8788
- throw error;
8789
- }
9005
+ for (const event of events) await args.events.publish(event);
8790
9006
  await args.db.update(t).set({ conflictFixes: withGitHubConflictFix(row.fixes, {
8791
9007
  atMs: args.nowMs,
8792
- headSha: loaded.head.sha
9008
+ headSha: loaded.head.sha,
9009
+ itemId: args.itemId
8793
9010
  }) }).where(pullRequest);
8794
9011
  }
8795
9012
  // src/pull-request-outcomes/reconcile.ts
@@ -10769,6 +10986,13 @@ function assertGitHubPullRequestApprovalDenied(input) {
10769
10986
  if (isEventsPath && event === void 0) throw new EgressPolicyDenied("GitHub pull request review submissions must include a parseable non-APPROVE event so the no-approve policy can be enforced.");
10770
10987
  }
10771
10988
  // src/default-branch.ts
10989
+ /**
10990
+ * Default branch lookup for the Git push policy.
10991
+ *
10992
+ * The egress grant hook decides whether a push may leave the sandbox, so it
10993
+ * cannot read GitHub through host egress. This file calls GitHub directly,
10994
+ * with a metadata-only installation token.
10995
+ */
10772
10996
  const DEFAULT_BRANCH_TTL_MS = 6e5;
10773
10997
  const repositorySchema = z.object({ default_branch: z.string().min(1) });
10774
10998
  /**
@@ -10778,13 +11002,18 @@ const repositorySchema = z.object({ default_branch: z.string().min(1) });
10778
11002
  async function loadDefaultBranch(env, cache, repository) {
10779
11003
  const { owner, name } = repository;
10780
11004
  return await cache.getOrLoad(`default-branch:${owner}/${name}`.toLowerCase(), async () => {
11005
+ const signal = AbortSignal.timeout(CACHE_LOAD_TIMEOUT_MS);
10781
11006
  const token = await issueInstallationToken({
10782
11007
  ...env,
10783
11008
  permissions: { metadata: "read" },
10784
- repositories: [name]
11009
+ repositories: [name],
11010
+ signal
10785
11011
  });
10786
11012
  return {
10787
- value: repositorySchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { token: token.token })).default_branch,
11013
+ value: repositorySchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, {
11014
+ signal,
11015
+ token: token.token
11016
+ })).default_branch,
10788
11017
  ttlMs: DEFAULT_BRANCH_TTL_MS
10789
11018
  };
10790
11019
  });
@@ -11270,11 +11499,18 @@ function githubPlugin(options = {}) {
11270
11499
  }
11271
11500
  }),
11272
11501
  [GITHUB_PULL_REQUEST_OUTCOME_TASK]: githubPullRequestOutcomeTask,
11273
- [GITHUB_PULL_REQUEST_PATCH_TASK]: githubPullRequestPatchTask(async (refs) => await loadPullRequestHeadFacts({
11274
- appIdEnv,
11275
- installationIdEnv,
11276
- privateKeyEnv
11277
- }, refs)),
11502
+ [GITHUB_PULL_REQUEST_PATCH_TASK]: githubPullRequestPatchTask({
11503
+ loadCards: async (refs) => await loadPullRequestCards({
11504
+ appIdEnv,
11505
+ installationIdEnv,
11506
+ privateKeyEnv
11507
+ }, refs),
11508
+ loadHeadFacts: async (refs) => await loadPullRequestHeadFacts({
11509
+ appIdEnv,
11510
+ installationIdEnv,
11511
+ privateKeyEnv
11512
+ }, refs)
11513
+ }),
11278
11514
  [GITHUB_PULL_REQUEST_REQUESTER_BACKFILL_TASK]: githubPullRequestRequesterBackfillTask,
11279
11515
  [GITHUB_REPOSITORY_NAME_REPAIR_TASK]: githubRepositoryNameRepairTask(async () => await loadRepositoryFullNames({
11280
11516
  appIdEnv,
@@ -11430,8 +11666,8 @@ function githubPlugin(options = {}) {
11430
11666
  privateKeyEnv
11431
11667
  });
11432
11668
  },
11433
- async inboxItemAnswered(ctx) {
11434
- if (ctx.subject.kind !== GITHUB_INBOX_SUBJECTS.mergeConflict || ctx.choice !== "Resume") return;
11669
+ async inboxItemAction(ctx) {
11670
+ if (ctx.subject.kind !== GITHUB_INBOX_SUBJECTS.mergeConflict || ctx.action !== "resume") return;
11435
11671
  const db = gitHubDbSchema.parse(ctx.db);
11436
11672
  const pullRequestId = ctx.subject.id;
11437
11673
  const [change] = await wasGitHubPullRequestOpenedIn(db, {
@@ -11443,7 +11679,6 @@ function githubPlugin(options = {}) {
11443
11679
  conversationId: ctx.conversationId,
11444
11680
  pullRequestId
11445
11681
  });
11446
- await allowGitHubConflictAsk(db, pullRequestId);
11447
11682
  return;
11448
11683
  }
11449
11684
  const installationEnv = {
package/dist/testing.js CHANGED
@@ -1 +1 @@
1
- export { n as normalizeGitHubEvents } from "./events-DDjNmMZq.js";
1
+ export { n as normalizeGitHubEvents } from "./events-D0hD78c5.js";
@@ -0,0 +1,31 @@
1
+ -- The merge conflict policy now reads Resumes from the item history, and a
2
+ -- fix that a Resume started names its item. Name the item on the fix of
3
+ -- each saved Resume: the fix that started at `conflict_fixes_resumed_at`,
4
+ -- and the latest item of the pull request that a Resume closed by then.
5
+ -- junior:bounded-backfill: only the Junior pull requests with a saved Resume, one row each, written once.
6
+ UPDATE junior_github_pull_requests AS pull_request
7
+ SET conflict_fixes = coalesce((
8
+ SELECT jsonb_agg(
9
+ CASE
10
+ WHEN (fixes.fix ->> 'atMs')::numeric = round(extract(epoch FROM pull_request.conflict_fixes_resumed_at) * 1000)
11
+ THEN fixes.fix || jsonb_build_object('itemId', resumed.item_id)
12
+ ELSE fixes.fix
13
+ END
14
+ ORDER BY fixes.position
15
+ )
16
+ FROM jsonb_array_elements(pull_request.conflict_fixes) WITH ORDINALITY AS fixes(fix, position)
17
+ ), '[]'::jsonb)
18
+ FROM (
19
+ SELECT DISTINCT ON (item.subject_id)
20
+ item.subject_id,
21
+ item.id AS item_id
22
+ FROM junior_inbox_items AS item
23
+ JOIN junior_github_pull_requests AS saved
24
+ ON saved.pull_request_id = item.subject_id
25
+ WHERE item.subject_kind = 'github:merge_conflict'
26
+ AND item.status = 'done'
27
+ AND item.answer -> 'values' -> 'choice' ->> 0 = 'Resume'
28
+ AND item.closed_at <= saved.conflict_fixes_resumed_at
29
+ ORDER BY item.subject_id, item.closed_at DESC
30
+ ) AS resumed
31
+ WHERE resumed.subject_id = pull_request.pull_request_id;
@@ -0,0 +1,9 @@
1
+ {
2
+ "type": "diff",
3
+ "version": "10",
4
+ "dialect": "postgres",
5
+ "id": "b74bb294-a5c9-441b-8877-c46225d6c5e3",
6
+ "prevIds": ["6daad623-cf70-43e4-8a43-233b09fb3607"],
7
+ "footprints": [],
8
+ "deltas": []
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/junior-github",
3
- "version": "0.320.0",
3
+ "version": "0.322.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "dependencies": {
31
31
  "@0no-co/graphql.web": "^1.3.4",
32
- "@sentry/junior-plugin-api": "0.320.0",
32
+ "@sentry/junior-plugin-api": "0.322.0",
33
33
  "@sinclair/typebox": "^0.34.49",
34
34
  "drizzle-orm": "1.0.0-rc.6",
35
35
  "ignore": "^7.0.5",