@sentry/junior-github 0.312.0 → 0.314.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRepositoryFromUrl, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubMessageSchema, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as definedValues, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as pullRequestTargets, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as logFailOpenFailure, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as githubRequest, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-mAaCafvx.js";
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-D51HE9X3.js";
2
2
  import * as z from "zod";
3
3
  import pLimit from "p-limit";
4
4
  import { EgressAuthRequired, EgressPolicyDenied, OBJECT_FACTS_MAX_BYTES, PluginToolInputError, codeChangeSizeSchema, decodeObjectImageRef, defineJuniorPlugin, definePluginTool, enforceEgressPolicy, mergeEventMatchFields, objectFactsBytes, objectFactsMatchType, objectFactsSchema, parseShellCommands, pluginToolOutputSchema, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
@@ -7,7 +7,7 @@ import { parseFragment } from "parse5";
7
7
  import { Type } from "@sinclair/typebox";
8
8
  import { Value } from "@sinclair/typebox/value";
9
9
  import { and, asc, eq, inArray, lt, lte, ne, sql } from "drizzle-orm";
10
- import { index, integer, jsonb, pgTable, primaryKey, text, timestamp as timestamp$2 } from "drizzle-orm/pg-core";
10
+ import { index, integer, jsonb, pgTable, primaryKey, text, timestamp as timestamp$1 } from "drizzle-orm/pg-core";
11
11
  import ignore from "ignore";
12
12
  import { Kind, parse, print, visit } from "@0no-co/graphql.web";
13
13
  import { createHmac, timingSafeEqual } from "node:crypto";
@@ -149,28 +149,42 @@ function githubObjectAnnotation(input) {
149
149
  sourceUpdatedAt: input.sourceUpdatedAt
150
150
  };
151
151
  }
152
- /** Refresh an existing object's status without selecting a card for delivery. */
153
- async function updateGitHubAnnotation(store, input) {
154
- const key = `${input.repo.toLowerCase()}#${input.number}`;
155
- const current = (await store.list()).find((annotation) => annotation.key === key);
152
+ /**
153
+ * Return the annotation that shows a new status of one object, from the
154
+ * stored annotations of a conversation. It keeps a saved object card and
155
+ * does not select a card for delivery.
156
+ */
157
+ function githubStatusAnnotation(annotations, input) {
158
+ const key = githubObjectKey(input.repo, input.number);
159
+ const current = annotations.find((annotation) => annotation.key === key);
156
160
  if (current?.kind === "object") {
157
161
  const { plugin: _plugin, createdAt: _createdAt, updatedAt: _updatedAt, facts, ...annotation } = current;
158
- await store.upsert({
162
+ return {
159
163
  ...annotation,
160
164
  ...facts && objectFactsMatchType(facts, input.objectType) ? { facts } : void 0,
161
165
  objectType: input.objectType,
162
166
  status: input.status
163
- });
164
- return;
167
+ };
165
168
  }
166
- await store.upsert({
169
+ return {
167
170
  kind: "resource_link",
168
171
  objectType: input.objectType,
169
172
  key,
170
173
  label: `${input.repo}#${input.number}`,
171
174
  url: `https://github.com/${input.repo}/${input.objectType === "code_change" ? "pull" : "issues"}/${input.number}`,
172
175
  status: input.status
173
- });
176
+ };
177
+ }
178
+ /**
179
+ * Refresh an existing object's status without selecting a card for delivery.
180
+ * With `existingOnly`, a conversation with no annotation for the object gets
181
+ * none.
182
+ */
183
+ async function updateGitHubAnnotation(store, input, existingOnly) {
184
+ const annotations = await store.list();
185
+ const key = githubObjectKey(input.repo, input.number);
186
+ if (existingOnly && !annotations.some((item) => item.key === key)) return;
187
+ await store.upsert(githubStatusAnnotation(annotations, input));
174
188
  }
175
189
  /**
176
190
  * Refresh the status of one object in each linked conversation. One failed
@@ -178,7 +192,7 @@ async function updateGitHubAnnotation(store, input) {
178
192
  */
179
193
  async function updateGitHubAnnotations(args) {
180
194
  const limit = pLimit(8);
181
- const results = await Promise.allSettled(args.conversationIds.map((conversationId) => limit(() => updateGitHubAnnotation(args.annotations.forConversation(conversationId), args.update))));
195
+ const results = await Promise.allSettled(args.conversationIds.map((conversationId) => limit(() => updateGitHubAnnotation(args.annotations.forConversation(conversationId), args.update, args.existingOnly ?? false))));
182
196
  for (const result of results) {
183
197
  if (result.status === "fulfilled") continue;
184
198
  args.log?.error("GitHub conversation annotation update failed", {
@@ -189,6 +203,16 @@ async function updateGitHubAnnotations(args) {
189
203
  });
190
204
  }
191
205
  }
206
+ /**
207
+ * Return the status change of one object for one conversation, to save in
208
+ * one batch with other changes.
209
+ */
210
+ async function githubAnnotationChange(args) {
211
+ return {
212
+ conversationId: args.conversationId,
213
+ upsert: githubStatusAnnotation(await args.annotations.forConversation(args.conversationId).list(), args.update)
214
+ };
215
+ }
192
216
  // src/object-facts.ts
193
217
  const person = z.object({ login: z.string() });
194
218
  const responseSchema$1 = z.object({
@@ -520,7 +544,7 @@ const gitHubReactToIssueTool = definePluginTool({
520
544
  });
521
545
  if (!response.ok) {
522
546
  const message = `GitHub issue reaction failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`;
523
- if (response.status === 404 || response.status === 422) throw new PluginToolInputError(message);
547
+ if (response.status === 404 || response.status === 422) throw new PluginToolInputError(`${message}. Check repo and issue, and fix any field that GitHub names.`);
524
548
  throw new Error(message);
525
549
  }
526
550
  const reaction = z.object({ id: z.number() }).parse(response.body);
@@ -644,7 +668,7 @@ const gitHubCloneRepositoryTool = definePluginTool({
644
668
  const otherWorkspaces = workspaces.filter((name) => name !== active?.name);
645
669
  const note = active && otherWorkspaces.length > 0 ? workspaceAvailableNote(repoId, active, otherWorkspaces) : void 0;
646
670
  const directory = input.directory ?? defaultDirectory(repo.name);
647
- if (isReservedSandboxDirectory(directory.split("/")[0] ?? directory)) throw new PluginToolInputError(`Directory conflicts with a reserved sandbox path: ${directory}`);
671
+ if (isReservedSandboxDirectory(directory.split("/")[0] ?? directory)) throw new PluginToolInputError(`directory ${directory} conflicts with a reserved sandbox path. Set directory to another path, or leave it out to use repos/${repo.name}.`);
648
672
  const path = `${ctx.sandbox.root}/${directory}`;
649
673
  const parentDirectory = directory.includes("/") ? directory.slice(0, directory.lastIndexOf("/")) : void 0;
650
674
  if (parentDirectory) {
@@ -657,7 +681,7 @@ const gitHubCloneRepositoryTool = definePluginTool({
657
681
  ],
658
682
  cwd: ctx.sandbox.root,
659
683
  signal: commandSignal(options.signal, 3e4)
660
- })).exitCode !== 0) throw new PluginToolInputError(`Failed to create clone parent directory: ${parentDirectory}`);
684
+ })).exitCode !== 0) throw new PluginToolInputError(`Could not create the parent directory ${parentDirectory}. Set directory to another path, or leave it out to use repos/${repo.name}.`);
661
685
  }
662
686
  if ((await ctx.sandbox.run({
663
687
  cmd: "bash",
@@ -669,7 +693,7 @@ const gitHubCloneRepositoryTool = definePluginTool({
669
693
  ],
670
694
  cwd: ctx.sandbox.root,
671
695
  signal: commandSignal(options.signal, 3e4)
672
- })).exitCode === 0) throw new PluginToolInputError(`destination already exists: ${path}`);
696
+ })).exitCode === 0) throw new PluginToolInputError(`${path} already exists. Use that checkout, or set directory to a new path.`);
673
697
  let clone;
674
698
  try {
675
699
  clone = await ctx.sandbox.run({
@@ -691,7 +715,7 @@ const gitHubCloneRepositoryTool = definePluginTool({
691
715
  }
692
716
  if (clone.exitCode !== 0) {
693
717
  await removePartialClone(ctx, path);
694
- throw new PluginToolInputError(`GitHub repository clone failed: ${clone.stderr.trim() || `exit ${clone.exitCode}`}`);
718
+ throw new PluginToolInputError(`GitHub repository clone failed: ${clone.stderr.trim() || `exit ${clone.exitCode}`}. Check that repo names a repository that exists.`);
695
719
  }
696
720
  return {
697
721
  target: "cloneRepository",
@@ -735,7 +759,7 @@ const gitHubCommentOnIssueTool = definePluginTool({
735
759
  });
736
760
  if (!response.ok) {
737
761
  const message = `GitHub issue comment failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`;
738
- if (response.status === 404 || response.status === 422) throw new PluginToolInputError(message);
762
+ if (response.status === 404 || response.status === 422) throw new PluginToolInputError(`${message}. Check repo and issue, and fix any field that GitHub names.`);
739
763
  throw new Error(message);
740
764
  }
741
765
  const comment = z.object({
@@ -776,7 +800,7 @@ async function threadRootId(egress, prefix, commentId) {
776
800
  });
777
801
  if (!response.ok) {
778
802
  const message = `GitHub review comment lookup failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`;
779
- if (response.status === 404) throw new PluginToolInputError(message);
803
+ if (response.status === 404) throw new PluginToolInputError(`${message}. Set in_reply_to to the id of a review comment in repo.`);
780
804
  throw new Error(message);
781
805
  }
782
806
  return z.object({ in_reply_to_id: z.number().nullish() }).parse(response.body).in_reply_to_id ?? commentId;
@@ -808,7 +832,7 @@ const gitHubCommentOnPullRequestTool = definePluginTool({
808
832
  });
809
833
  if (!response.ok) {
810
834
  const message = `GitHub pull request comment failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`;
811
- if (response.status === 404 || response.status === 422) throw new PluginToolInputError(message);
835
+ if (response.status === 404 || response.status === 422) throw new PluginToolInputError(`${message}. Check repo and pull_request, and fix any field that GitHub names.`);
812
836
  throw new Error(message);
813
837
  }
814
838
  const comment = z.object({
@@ -833,7 +857,7 @@ const GITHUB_SESSION_FOOTER_START = "<!-- junior-session-footer:start -->";
833
857
  const GITHUB_SESSION_FOOTER_END = "<!-- junior-session-footer:end -->";
834
858
  const GITHUB_CONVERSATION_ID_MARKER = "junior-conversation-id:";
835
859
  function nonEmptyString$4(value, name) {
836
- if (!value?.trim()) throw new PluginToolInputError(`${name} is required`);
860
+ if (!value?.trim()) throw new PluginToolInputError(`${name} is missing in this Turn, so the GitHub footer cannot be added. No change to the call can fix this.`);
837
861
  return value.trim();
838
862
  }
839
863
  function escapeRegExp(value) {
@@ -856,15 +880,19 @@ function sentryConversationUrl(conversationId) {
856
880
  const port = parsed.port ? `:${parsed.port}` : "";
857
881
  return `${parsed.protocol}//${parsed.hostname}${port}/organizations/${orgSlug}/${path}`;
858
882
  }
859
- /** Build the conversation session footer, preferring a host-provided dashboard link. */
860
- function githubConversationFooter(conversationId, dashboardUrl) {
883
+ /**
884
+ * Build the conversation session footer, preferring a host-provided dashboard
885
+ * link. `earlierConversationIds` keeps the markers of Conversations that wrote
886
+ * the body before, so the footer names every one of them.
887
+ */
888
+ function githubConversationFooter(conversationId, dashboardUrl, earlierConversationIds = []) {
861
889
  const id = nonEmptyString$4(conversationId, "conversationId");
862
890
  const normalizedDashboardUrl = dashboardUrl?.trim();
863
891
  const sentryUrl = sentryConversationUrl(id);
864
892
  const sessionLinks = normalizedDashboardUrl ? `[View Session](${normalizedDashboardUrl})${sentryUrl ? ` [[Sentry]](${sentryUrl})` : ""}` : sentryUrl ? `[View Session in Sentry](${sentryUrl})` : void 0;
865
893
  if (!sessionLinks) return;
866
- const conversationMarker = `<!-- ${GITHUB_CONVERSATION_ID_MARKER}${encodeURIComponent(id)} -->`;
867
- return `${GITHUB_SESSION_FOOTER_START}\n${conversationMarker}\n\n--\n\n${sessionLinks}\n\n${GITHUB_SESSION_FOOTER_END}`;
894
+ const markers = [.../* @__PURE__ */ new Set([id, ...earlierConversationIds])].map((markerId) => `<!-- ${GITHUB_CONVERSATION_ID_MARKER}${encodeURIComponent(markerId)} -->`).join("\n");
895
+ return `${GITHUB_SESSION_FOOTER_START}\n${markers}\n\n--\n\n${sessionLinks}\n\n${GITHUB_SESSION_FOOTER_END}`;
868
896
  }
869
897
  /** Read opaque native conversation ids from runtime-owned GitHub footers. */
870
898
  function githubConversationIds(body) {
@@ -880,30 +908,13 @@ function githubConversationIds(body) {
880
908
  }
881
909
  return [...ids];
882
910
  }
883
- /** Read same- and cross-repository issue references from a pull request body. */
884
- function githubLinkedIssues(body, repositoryFullName) {
885
- if (!body) return [];
886
- const references = /* @__PURE__ */ new Map();
887
- const add = (linkedRepository, rawNumber) => {
888
- const number = Number.parseInt(rawNumber, 10);
889
- if (!Number.isInteger(number) || number <= 0) return;
890
- const normalizedRepository = linkedRepository.toLowerCase();
891
- references.set(`${normalizedRepository}#${number}`, {
892
- number,
893
- repositoryFullName: linkedRepository
894
- });
895
- };
896
- for (const match of body.matchAll(/\b([\w.-]+\/[\w.-]+)#(\d+)\b/g)) add(match[1] ?? "", match[2] ?? "");
897
- for (const match of body.matchAll(/(?:^|[^\w/])#(\d+)\b/g)) add(repositoryFullName, match[1] ?? "");
898
- return [...references.values()].sort((left, right) => left.repositoryFullName.localeCompare(right.repositoryFullName) || left.number - right.number);
899
- }
900
911
  /**
901
912
  * Append (or replace an existing) conversation session footer to a GitHub body string.
902
913
  * Without a dashboard or Sentry link, returns the body unchanged (existing footer stripped).
903
914
  */
904
- function appendGitHubFooter(body, conversationId, dashboardUrl) {
905
- const footer = githubConversationFooter(conversationId, dashboardUrl);
915
+ function appendGitHubFooter(body, conversationId, dashboardUrl, currentBody) {
906
916
  const normalizedBody = body.trimEnd();
917
+ const footer = githubConversationFooter(conversationId, dashboardUrl, githubConversationIds(currentBody));
907
918
  const existingFooter = new RegExp(`${escapeRegExp(GITHUB_SESSION_FOOTER_START)}[\\s\\S]*?${escapeRegExp(GITHUB_SESSION_FOOTER_END)}`);
908
919
  if (existingFooter.test(normalizedBody)) return footer ? normalizedBody.replace(existingFooter, footer) : normalizedBody.replace(existingFooter, "").trimEnd();
909
920
  if (!footer) return normalizedBody;
@@ -995,11 +1006,15 @@ function parseCreateIssueInput(input) {
995
1006
  try {
996
1007
  return Value.Parse(createIssueInputSchema, input);
997
1008
  } catch (error) {
998
- throw new PluginToolInputError("Invalid GitHub createIssue input.", { cause: error });
1009
+ throw new PluginToolInputError("Invalid GitHub createIssue input. Check the arguments against the tool schema and call it again.", { cause: error });
999
1010
  }
1000
1011
  }
1001
1012
  function nonEmptyString$3(value, name) {
1002
- if (!value?.trim()) throw new PluginToolInputError(`${name} is required`);
1013
+ if (!value?.trim()) throw new PluginToolInputError(`${name} must not be empty. Set it and call the tool again.`);
1014
+ return value.trim();
1015
+ }
1016
+ function runtimeId$1(value, name) {
1017
+ if (!value?.trim()) throw new PluginToolInputError(`${name} is missing in this Turn. No change to the call can fix this.`);
1003
1018
  return value.trim();
1004
1019
  }
1005
1020
  function createIssueState(value) {
@@ -1066,8 +1081,8 @@ const gitHubIssueTool = definePluginTool({
1066
1081
  outputSchema: gitHubIssueOutputSchema,
1067
1082
  async execute(input, options, ctx) {
1068
1083
  const parsedInput = parseCreateIssueInput(input);
1069
- const conversationId = nonEmptyString$3(ctx.conversationId, "conversationId");
1070
- const key = `createIssue:${conversationId}:${nonEmptyString$3(options?.toolCallId, "toolCallId")}`;
1084
+ const conversationId = runtimeId$1(ctx.conversationId, "conversationId");
1085
+ const key = `createIssue:${conversationId}:${runtimeId$1(options?.toolCallId, "toolCallId")}`;
1071
1086
  const attempt = await ctx.state.withLock(`${key}:lock`, GITHUB_ISSUE_CREATE_LOCK_TTL_MS, async () => {
1072
1087
  const state = createIssueState(await ctx.state.get(key));
1073
1088
  if (state?.status === "completed") return await gitHubIssueToolResult(ctx, state.input ?? parsedInput, {
@@ -1166,7 +1181,7 @@ const providerStatusSchema = z.object({
1166
1181
  function throwLookupError(target, status, body) {
1167
1182
  const message = `GitHub ${target} lookup failed with HTTP ${status}`;
1168
1183
  const hasValidationErrors = body !== null && typeof body === "object" && !Array.isArray(body) && Array.isArray(body.errors) && body.errors.length > 0;
1169
- if (target === "deployment" && (status === 404 || status === 422 && hasValidationErrors)) throw new PluginToolInputError(message);
1184
+ if (target === "deployment" && (status === 404 || status === 422 && hasValidationErrors)) throw new PluginToolInputError(`${message}. Check repo and commit_sha, and that environment is a deployment environment of the repo.`);
1170
1185
  throw new Error(message);
1171
1186
  }
1172
1187
  /** Read deployment metadata and expose its stable subscription identity. */
@@ -1292,7 +1307,7 @@ const gitHubGetIssueTool = definePluginTool({
1292
1307
  }), resolveGitHubRequester(ctx)]);
1293
1308
  if (!response.ok) {
1294
1309
  const message = `GitHub issue lookup failed with HTTP ${response.status}`;
1295
- if (response.status === 404) throw new PluginToolInputError(message);
1310
+ if (response.status === 404) throw new PluginToolInputError(`${message}. Check repo and issue. If they are correct, the GitHub App cannot see the repository.`);
1296
1311
  throw new Error(message);
1297
1312
  }
1298
1313
  const issue = providerIssueSchema$1.parse(response.body);
@@ -1348,30 +1363,6 @@ const githubPullRequestStateSchema = z.enum([
1348
1363
  "open"
1349
1364
  ]);
1350
1365
  const githubPullRequestCommitCompositionSchema = z.enum(["junior_only", "mixed"]);
1351
- const githubIssueStateSchema = z.enum(["closed", "open"]);
1352
- const githubIssueStateReasonSchema = z.enum([
1353
- "completed",
1354
- "duplicate",
1355
- "not_planned",
1356
- "reopened"
1357
- ]);
1358
- /** Current provider projection for issues classified as Junior-owned. */
1359
- const juniorGitHubIssues = pgTable("junior_github_issues", {
1360
- issueId: text("issue_id").primaryKey(),
1361
- repositoryId: text("repository_id").notNull(),
1362
- repositoryFullName: text("repository_full_name").notNull(),
1363
- number: integer("number").notNull(),
1364
- state: text("state").$type().notNull(),
1365
- stateReason: text("state_reason").$type(),
1366
- conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
1367
- openedAt: timestamp$2("opened_at", { withTimezone: true }).notNull(),
1368
- closedAt: timestamp$2("closed_at", { withTimezone: true }),
1369
- updatedAt: timestamp$2("updated_at", { withTimezone: true }).notNull()
1370
- }, (table) => [
1371
- index("junior_github_issues_opened_at_idx").on(table.openedAt),
1372
- index("junior_github_issues_closed_at_idx").on(table.closedAt),
1373
- index("junior_github_issues_open_idx").on(table.issueId).where(sql`${table.state} = 'open'`)
1374
- ]);
1375
1366
  /** Current provider projection for pull requests classified as Junior-owned. */
1376
1367
  const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1377
1368
  pullRequestId: text("pull_request_id").primaryKey(),
@@ -1381,14 +1372,14 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1381
1372
  state: text("state").$type().notNull(),
1382
1373
  commitComposition: text("commit_composition").$type(),
1383
1374
  conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
1384
- openedAt: timestamp$2("opened_at", { withTimezone: true }).notNull(),
1375
+ openedAt: timestamp$1("opened_at", { withTimezone: true }).notNull(),
1385
1376
  /**
1386
1377
  * When the pull request merged or closed. Null while it is open. The
1387
1378
  * finished work of a Conversation needs this time for every pull
1388
1379
  * request of every candidate, so it is stored and not read from GitHub.
1389
1380
  */
1390
- finishedAt: timestamp$2("finished_at", { withTimezone: true }),
1391
- updatedAt: timestamp$2("updated_at", { withTimezone: true }).notNull(),
1381
+ finishedAt: timestamp$1("finished_at", { withTimezone: true }),
1382
+ updatedAt: timestamp$1("updated_at", { withTimezone: true }).notNull(),
1392
1383
  /**
1393
1384
  * The requester's next action that Junior last derived from GitHub, and
1394
1385
  * shows in the Inbox. Null when no action waits on them.
@@ -1404,18 +1395,18 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1404
1395
  */
1405
1396
  readySyncId: integer("ready_sync_id"),
1406
1397
  /** When the current check started. */
1407
- readySyncAt: timestamp$2("ready_sync_at", { withTimezone: true }),
1398
+ readySyncAt: timestamp$1("ready_sync_at", { withTimezone: true }),
1408
1399
  /**
1409
1400
  * When a person last chose Resume on the merge conflict item.
1410
1401
  * It counts as activity by a person, so the fix count starts again.
1411
1402
  */
1412
- conflictFixesResumedAt: timestamp$2("conflict_fixes_resumed_at", { withTimezone: true }),
1403
+ conflictFixesResumedAt: timestamp$1("conflict_fixes_resumed_at", { withTimezone: true }),
1413
1404
  /**
1414
1405
  * When Junior last asked the requester to resume a merge conflict fix
1415
1406
  * that did not land. It asks once after each Resume, so a Dismiss ends
1416
1407
  * the asks on the pull request.
1417
1408
  */
1418
- conflictFixAskedAt: timestamp$2("conflict_fix_asked_at", { withTimezone: true }),
1409
+ conflictFixAskedAt: timestamp$1("conflict_fix_asked_at", { withTimezone: true }),
1419
1410
  /**
1420
1411
  * The latest merge conflict fixes that Junior started, oldest first.
1421
1412
  * Only these count as fixes, so a merge or force push for work that a
@@ -1427,16 +1418,6 @@ const juniorGitHubPullRequests = pgTable("junior_github_pull_requests", {
1427
1418
  index("junior_github_pull_requests_open_idx").on(table.pullRequestId).where(sql`${table.state} = 'open'`),
1428
1419
  index("junior_github_pull_requests_unmerged_conversations_idx").using("gin", table.conversationIds).where(sql`${table.state} <> 'merged'`)
1429
1420
  ]);
1430
- /** Many-to-many links between tracked pull requests and tracked issues. */
1431
- const juniorGitHubPullRequestIssues = pgTable("junior_github_pull_request_issues", {
1432
- pullRequestId: text("pull_request_id").notNull().references(() => juniorGitHubPullRequests.pullRequestId, { onDelete: "cascade" }),
1433
- issueRepositoryFullName: text("issue_repository_full_name").notNull(),
1434
- issueNumber: integer("issue_number").notNull()
1435
- }, (table) => [primaryKey({ columns: [
1436
- table.pullRequestId,
1437
- table.issueRepositoryFullName,
1438
- table.issueNumber
1439
- ] })]);
1440
1421
  // src/pull-request-requesters/store.ts
1441
1422
  const table = pgTable("junior_github_pull_request_requesters", {
1442
1423
  /** Lowercase `owner/name`. */
@@ -1446,8 +1427,8 @@ const table = pgTable("junior_github_pull_request_requesters", {
1446
1427
  identityId: text("identity_id").notNull(),
1447
1428
  /** The Conversation where the person asked Junior to open the pull request. */
1448
1429
  conversationId: text("conversation_id"),
1449
- createdAt: timestamp$2("created_at", { withTimezone: true }).notNull(),
1450
- updatedAt: timestamp$2("updated_at", { withTimezone: true }).notNull()
1430
+ createdAt: timestamp$1("created_at", { withTimezone: true }).notNull(),
1431
+ updatedAt: timestamp$1("updated_at", { withTimezone: true }).notNull()
1451
1432
  }, (table) => [primaryKey({ columns: [
1452
1433
  table.repositoryFullName,
1453
1434
  table.number,
@@ -1741,11 +1722,15 @@ function parseCreatePullRequestInput(input) {
1741
1722
  try {
1742
1723
  return Value.Parse(createPullRequestInputSchema, input);
1743
1724
  } catch (error) {
1744
- throw new PluginToolInputError("Invalid GitHub createPullRequest input.", { cause: error });
1725
+ throw new PluginToolInputError("Invalid GitHub createPullRequest input. Check the arguments against the tool schema and call it again.", { cause: error });
1745
1726
  }
1746
1727
  }
1747
1728
  function nonEmptyString$2(value, name) {
1748
- if (!value?.trim()) throw new PluginToolInputError(`${name} is required`);
1729
+ if (!value?.trim()) throw new PluginToolInputError(`${name} must not be empty. Set it and call the tool again.`);
1730
+ return value.trim();
1731
+ }
1732
+ function runtimeId(value, name) {
1733
+ if (!value?.trim()) throw new PluginToolInputError(`${name} is missing in this Turn. No change to the call can fix this.`);
1749
1734
  return value.trim();
1750
1735
  }
1751
1736
  function createPullRequestState(value) {
@@ -1792,7 +1777,7 @@ async function createGitHubPullRequest(ctx, request) {
1792
1777
  const parsed = response.body;
1793
1778
  if (!response.ok) {
1794
1779
  const message = `GitHub pull request creation failed with HTTP ${response.status}: ${githubErrorMessage$1(parsed)}`;
1795
- if (response.status === 404 || response.status === 422) throw new PluginToolInputError(message);
1780
+ if (response.status === 404 || response.status === 422) throw new PluginToolInputError(`${message}. Check repo, head, and base, and fix any field that GitHub names.`);
1796
1781
  throw new GitHubPullRequestCreateRejectedError(message, response.status);
1797
1782
  }
1798
1783
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("GitHub pull request creation returned an invalid response.");
@@ -1882,7 +1867,7 @@ async function resolveLogins(ctx, values, role) {
1882
1867
  function namedLogins(values, role) {
1883
1868
  return values?.map((value) => {
1884
1869
  const login = parseGitHubLogin(value);
1885
- if (!login) throw new PluginToolInputError(`Invalid GitHub ${role} login: ${value}`);
1870
+ if (!login) throw new PluginToolInputError(`Invalid GitHub ${role} login: ${value}. Pass a GitHub login, such as octocat.`);
1886
1871
  return login;
1887
1872
  });
1888
1873
  }
@@ -2016,8 +2001,8 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
2016
2001
  ...githubText,
2017
2002
  ...people
2018
2003
  });
2019
- const conversationId = nonEmptyString$2(ctx.conversationId, "conversationId");
2020
- const key = `createPullRequest:${conversationId}:${nonEmptyString$2(options?.toolCallId, "toolCallId")}`;
2004
+ const conversationId = runtimeId(ctx.conversationId, "conversationId");
2005
+ const key = `createPullRequest:${conversationId}:${runtimeId(options?.toolCallId, "toolCallId")}`;
2021
2006
  const attempt = await ctx.state.withLock(`${key}:lock`, GITHUB_PULL_REQUEST_CREATE_LOCK_TTL_MS, async () => {
2022
2007
  const state = createPullRequestState(await ctx.state.get(key));
2023
2008
  if (state?.status === "completed") {
@@ -2285,16 +2270,15 @@ const PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2285
2270
  `);
2286
2271
  /**
2287
2272
  * Read what decides the requester's next action on one pull request: its
2288
- * state, merge state, review requests, latest reviews, head commit, and
2289
- * latest comments and review requests. A review comment reply is a review,
2290
- * so `reviews` holds it too.
2273
+ * state, merge state, review requests, latest reviews, and latest comments
2274
+ * and review requests. A review comment reply is a review, so `reviews`
2275
+ * holds it too.
2291
2276
  */
2292
2277
  const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
2293
2278
  query PullRequestNextAction($owner: String!, $name: String!, $number: Int!) {
2294
2279
  repository(owner: $owner, name: $name) {
2295
2280
  pullRequest(number: $number) {
2296
2281
  autoMergeRequest { enabledAt }
2297
- headRefOid
2298
2282
  isDraft
2299
2283
  mergeStateStatus
2300
2284
  state
@@ -2307,7 +2291,6 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
2307
2291
  pageInfo { hasPreviousPage startCursor }
2308
2292
  nodes { ...NextActionReview }
2309
2293
  }
2310
- commits(last: 1) { nodes { commit { committedDate } } }
2311
2294
  timelineItems(last: 100, itemTypes: [ISSUE_COMMENT, REVIEW_REQUESTED_EVENT]) {
2312
2295
  nodes {
2313
2296
  __typename
@@ -2326,7 +2309,60 @@ const PULL_REQUEST_NEXT_ACTION = githubGraphql(`
2326
2309
  state
2327
2310
  submittedAt
2328
2311
  author { __typename login }
2329
- commit { oid }
2312
+ }
2313
+ `);
2314
+ /**
2315
+ * Read what decides whether a reviewer's change request is ready for their
2316
+ * review again: whether GitHub asks them, their latest review with the
2317
+ * reactors of its body and each of its comments, the checks of the head
2318
+ * commit, and the branch protection's required checks of the base branch.
2319
+ */
2320
+ const PULL_REQUEST_REVIEW_AGAIN = githubGraphql(`
2321
+ query PullRequestReviewAgain($owner: String!, $name: String!, $number: Int!, $reviewer: String!) {
2322
+ repository(owner: $owner, name: $name) {
2323
+ pullRequest(number: $number) {
2324
+ baseRefName
2325
+ baseRef { refUpdateRule { requiredStatusCheckContexts } }
2326
+ reviewRequests(first: 100) {
2327
+ nodes { requestedReviewer { __typename ... on User { login } } }
2328
+ }
2329
+ reviews(last: 1, author: $reviewer, states: [APPROVED, CHANGES_REQUESTED, DISMISSED]) {
2330
+ nodes {
2331
+ databaseId
2332
+ state
2333
+ body
2334
+ ...FeedbackReactors
2335
+ comments(first: 100) {
2336
+ totalCount
2337
+ nodes { databaseId ...FeedbackReactors }
2338
+ }
2339
+ }
2340
+ }
2341
+ commits(last: 1) {
2342
+ nodes {
2343
+ commit {
2344
+ statusCheckRollup {
2345
+ contexts(first: 100) {
2346
+ pageInfo { hasNextPage }
2347
+ nodes {
2348
+ __typename
2349
+ ... on CheckRun { name status conclusion }
2350
+ ... on StatusContext { context state }
2351
+ }
2352
+ }
2353
+ }
2354
+ }
2355
+ }
2356
+ }
2357
+ }
2358
+ }
2359
+ }
2360
+
2361
+ fragment FeedbackReactors on Reactable {
2362
+ reactionGroups {
2363
+ content
2364
+ reactors(first: 100) { nodes { ... on Bot { databaseId } } }
2365
+ }
2330
2366
  }
2331
2367
  `);
2332
2368
  /** Read the page of a pull request's reviews before `before`. */
@@ -2346,7 +2382,6 @@ const PULL_REQUEST_REVIEWS_BEFORE = githubGraphql(`
2346
2382
  state
2347
2383
  submittedAt
2348
2384
  author { __typename login }
2349
- commit { oid }
2350
2385
  }
2351
2386
  `);
2352
2387
  const PULL_REQUEST_LIFECYCLE = githubGraphql(`
@@ -2502,6 +2537,169 @@ async function readDraftReadiness(egress, repo, pullRequest) {
2502
2537
  codeOwners: codeOwners ? codeOwnersOf(parseCodeOwners(codeOwners), paths) : []
2503
2538
  };
2504
2539
  }
2540
+ // src/pull-request-review-again.ts
2541
+ const reactorsSchema = z.object({ reactionGroups: z.array(z.object({
2542
+ content: z.string(),
2543
+ reactors: z.object({ nodes: z.array(z.object({ databaseId: z.number().optional() }).nullable()) })
2544
+ })) });
2545
+ const checkContextSchema$1 = z.discriminatedUnion("__typename", [z.object({
2546
+ __typename: z.literal("CheckRun"),
2547
+ conclusion: z.string().nullable(),
2548
+ name: z.string(),
2549
+ status: z.string()
2550
+ }), z.object({
2551
+ __typename: z.literal("StatusContext"),
2552
+ context: z.string(),
2553
+ state: z.string()
2554
+ })]);
2555
+ const reviewAgainSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
2556
+ baseRef: z.object({ refUpdateRule: z.object({ requiredStatusCheckContexts: z.array(z.string().nullable()).nullable() }).nullable() }).nullable(),
2557
+ baseRefName: z.string().min(1),
2558
+ commits: z.object({ nodes: z.array(z.object({ commit: z.object({ statusCheckRollup: z.object({ contexts: z.object({
2559
+ nodes: z.array(checkContextSchema$1.nullable()),
2560
+ pageInfo: z.object({ hasNextPage: z.boolean() })
2561
+ }) }).nullable() }) })) }),
2562
+ reviewRequests: z.object({ nodes: z.array(z.object({ requestedReviewer: z.object({
2563
+ __typename: z.string(),
2564
+ login: z.string().optional()
2565
+ }).nullable() }).nullable()) }),
2566
+ reviews: z.object({ nodes: z.array(reactorsSchema.extend({
2567
+ body: z.string(),
2568
+ comments: z.object({
2569
+ nodes: z.array(reactorsSchema.extend({ databaseId: z.number().nullable() }).nullable()),
2570
+ totalCount: z.number()
2571
+ }),
2572
+ databaseId: z.number().nullable(),
2573
+ state: z.string()
2574
+ }).nullable()) })
2575
+ }) }) }) });
2576
+ const branchRulesSchema = z.array(z.object({
2577
+ parameters: z.object({ required_status_checks: z.array(z.object({ context: z.string() })).optional() }).optional(),
2578
+ type: z.string()
2579
+ }));
2580
+ const MARKED_CONTENTS = /* @__PURE__ */ new Set(["THUMBS_DOWN", "THUMBS_UP"]);
2581
+ const PASSING_CONCLUSIONS = /* @__PURE__ */ new Set([
2582
+ "NEUTRAL",
2583
+ "SKIPPED",
2584
+ "SUCCESS"
2585
+ ]);
2586
+ /** Return whether one check run or commit status passes, fails, or waits. */
2587
+ function checkContextState(context) {
2588
+ if (context.__typename === "CheckRun") {
2589
+ if (context.status !== "COMPLETED") return "pending";
2590
+ return PASSING_CONCLUSIONS.has(context.conclusion ?? "") ? "passing" : "failing";
2591
+ }
2592
+ if (context.state === "SUCCESS") return "passing";
2593
+ return context.state === "PENDING" || context.state === "EXPECTED" ? "pending" : "failing";
2594
+ }
2595
+ function markedBy(reactable, botUserId) {
2596
+ return reactable.reactionGroups.some((group) => MARKED_CONTENTS.has(group.content) && group.reactors.nodes.some((reactor) => reactor?.databaseId === botUserId));
2597
+ }
2598
+ /**
2599
+ * Return whether every required check passes. A required check that has
2600
+ * not reported yet waits, so the ask does not go out before CI starts.
2601
+ */
2602
+ function requiredChecksPass(required, contexts, incomplete) {
2603
+ for (const name of required) {
2604
+ const states = contexts.filter((context) => (context.__typename === "CheckRun" ? context.name : context.context) === name).map(checkContextState);
2605
+ if (states.length === 0 && incomplete) return false;
2606
+ if (states.length === 0 || states.some((state) => state !== "passing")) return false;
2607
+ }
2608
+ return true;
2609
+ }
2610
+ /**
2611
+ * Read whether `reviewer`'s latest change request on a pull request is
2612
+ * ready for their review again. The comments of a change request are its
2613
+ * inline comments and its body. An empty body counts only when the review
2614
+ * has no inline comments.
2615
+ */
2616
+ async function readReviewAgainReadiness(read, target) {
2617
+ const { name, number, owner, reviewer } = target;
2618
+ const pull = reviewAgainSchema.parse(await read({
2619
+ body: {
2620
+ ...PULL_REQUEST_REVIEW_AGAIN,
2621
+ variables: {
2622
+ name,
2623
+ number,
2624
+ owner,
2625
+ reviewer
2626
+ }
2627
+ },
2628
+ operation: "github.pull.review-again.get",
2629
+ path: "/graphql"
2630
+ })).data.repository.pullRequest;
2631
+ const lower = reviewer.toLowerCase();
2632
+ const requested = pull.reviewRequests.nodes.some((request) => request?.requestedReviewer?.login?.toLowerCase() === lower);
2633
+ const review = pull.reviews.nodes[0];
2634
+ if (requested || review?.state !== "CHANGES_REQUESTED") return "none";
2635
+ const comments = review.comments.nodes.filter((comment) => comment !== null);
2636
+ if (comments.length < review.comments.totalCount) return "none";
2637
+ const { marked } = target;
2638
+ const justMarked = (id, kind) => marked?.kind === kind && marked.id === id;
2639
+ const bodyMarked = justMarked(review.databaseId, "review_body") || markedBy(review, target.botUserId);
2640
+ if ((review.body.trim() !== "" || comments.length === 0) && !bodyMarked) return "none";
2641
+ if (!comments.every((comment) => justMarked(comment.databaseId, "review") || markedBy(comment, target.botUserId))) return "none";
2642
+ const rules = branchRulesSchema.parse(await read({
2643
+ operation: "github.repo.branch-rules.get",
2644
+ path: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/rules/branches/${encodeURIComponent(pull.baseRefName)}?per_page=100`
2645
+ }));
2646
+ const required = /* @__PURE__ */ new Set([...(pull.baseRef?.refUpdateRule?.requiredStatusCheckContexts ?? []).filter((context) => Boolean(context)), ...rules.flatMap((rule) => rule.type === "required_status_checks" ? (rule.parameters?.required_status_checks ?? []).map((check) => check.context) : [])]);
2647
+ const rollup = pull.commits.nodes[0]?.commit.statusCheckRollup;
2648
+ return requiredChecksPass(required, (rollup?.contexts.nodes ?? []).filter((context) => context !== null), rollup?.contexts.pageInfo.hasNextPage ?? false) ? "ready" : "checks";
2649
+ }
2650
+ const HELD_ASK_TTL_MS = 2592e5;
2651
+ const heldAskSchema = z.object({
2652
+ at: z.iso.datetime(),
2653
+ reason: z.enum(["checks", "handled"]),
2654
+ reviewer: z.string().min(1),
2655
+ marked: z.object({
2656
+ id: z.number(),
2657
+ kind: z.enum(["review", "review_body"])
2658
+ }).optional()
2659
+ });
2660
+ function heldAskKey(target) {
2661
+ return `pull-request-review-again:${target.repositoryFullName.toLowerCase()}#${target.number}`;
2662
+ }
2663
+ /** Save the review ask that waits for the checks of one pull request. */
2664
+ async function holdGitHubReviewAsk(state, target, ask) {
2665
+ await state.set(heldAskKey(target), heldAskSchema.parse(ask), HELD_ASK_TTL_MS);
2666
+ }
2667
+ /** Return the review ask that waits for the checks of one pull request. */
2668
+ async function readHeldGitHubReviewAsk(state, target) {
2669
+ const saved = heldAskSchema.safeParse(await state.get(heldAskKey(target)));
2670
+ return saved.success ? saved.data : void 0;
2671
+ }
2672
+ /**
2673
+ * Drop the held review ask of one pull request. With `reviewer`, drop it
2674
+ * only when it is for that reviewer.
2675
+ */
2676
+ async function dropHeldGitHubReviewAsk(state, target, reviewer) {
2677
+ if (reviewer !== void 0) {
2678
+ if ((await readHeldGitHubReviewAsk(state, target))?.reviewer.toLowerCase() !== reviewer.toLowerCase()) return;
2679
+ }
2680
+ await state.delete(heldAskKey(target));
2681
+ }
2682
+ const ASKED_TTL_MS = 36e5;
2683
+ const askedSchema = z.object({
2684
+ at: z.iso.datetime(),
2685
+ reviewer: z.string().min(1)
2686
+ });
2687
+ function askedKey(target) {
2688
+ return `pull-request-review-asked:${target.repositoryFullName.toLowerCase()}#${target.number}`;
2689
+ }
2690
+ /** Record that the feedback tool asked `reviewer` again on one pull request. */
2691
+ async function markGitHubReviewAsked(state, target, asked) {
2692
+ await state.set(askedKey(target), askedSchema.parse(asked), ASKED_TTL_MS);
2693
+ }
2694
+ /** Return the review that the feedback tool asked for on one pull request. */
2695
+ async function readGitHubReviewAsked(state, target) {
2696
+ const saved = askedSchema.safeParse(await state.get(askedKey(target)));
2697
+ return saved.success ? saved.data : void 0;
2698
+ }
2699
+ /** Drop the record of a review that the feedback tool asked for. */
2700
+ async function dropGitHubReviewAsked(state, target) {
2701
+ await state.delete(askedKey(target));
2702
+ }
2505
2703
  // src/tools/get-pull-request.ts
2506
2704
  const commitShaSchema = z.string().regex(/^[0-9a-f]{40}$/i);
2507
2705
  const RELATED_CONVERSATIONS_MAX = 10;
@@ -2576,19 +2774,6 @@ const checksResponseSchema = z.object({ data: z.object({ repository: z.object({
2576
2774
  mergeStateStatus: z.string(),
2577
2775
  reviewDecision: z.string().nullable()
2578
2776
  }) }) }) });
2579
- const PASSING_CONCLUSIONS = /* @__PURE__ */ new Set([
2580
- "SUCCESS",
2581
- "NEUTRAL",
2582
- "SKIPPED"
2583
- ]);
2584
- function contextState(context) {
2585
- if (context.__typename === "CheckRun") {
2586
- if (context.status !== "COMPLETED") return "pending";
2587
- return PASSING_CONCLUSIONS.has(context.conclusion ?? "") ? "passing" : "failing";
2588
- }
2589
- if (context.state === "SUCCESS") return "passing";
2590
- return context.state === "PENDING" || context.state === "EXPECTED" ? "pending" : "failing";
2591
- }
2592
2777
  /** Read the required checks and merge state of one pull request. */
2593
2778
  async function readPullRequestChecks(egress, repo, number) {
2594
2779
  const response = await githubApi(egress, {
@@ -2614,7 +2799,7 @@ async function readPullRequestChecks(egress, repo, number) {
2614
2799
  };
2615
2800
  for (const context of rollup?.contexts.nodes ?? []) {
2616
2801
  if (!context.isRequired) continue;
2617
- checks[contextState(context)].push(context.__typename === "CheckRun" ? context.name : context.context);
2802
+ checks[checkContextState(context)].push(context.__typename === "CheckRun" ? context.name : context.context);
2618
2803
  }
2619
2804
  return {
2620
2805
  required: checks.failing.length > 0 ? "failing" : checks.pending.length > 0 ? "pending" : checks.passing.length > 0 ? "passing" : "not_reported",
@@ -2665,7 +2850,7 @@ const gitHubGetPullRequestTool = definePluginTool({
2665
2850
  });
2666
2851
  if (!response.ok) {
2667
2852
  const message = `GitHub pull request lookup failed with HTTP ${response.status}`;
2668
- if (response.status === 404) throw new PluginToolInputError(message);
2853
+ if (response.status === 404) throw new PluginToolInputError(`${message}. Check repo and pull_request. If they are correct, the GitHub App cannot see the repository.`);
2669
2854
  throw new Error(message);
2670
2855
  }
2671
2856
  const providerResult = z.object({
@@ -2718,7 +2903,7 @@ const inputSchema$8 = z.object({
2718
2903
  const releaseSchema = z.object({
2719
2904
  created_at: z.string(),
2720
2905
  draft: z.boolean(),
2721
- html_url: z.string(),
2906
+ url: z.string(),
2722
2907
  id: z.number(),
2723
2908
  name: z.string().nullable(),
2724
2909
  prerelease: z.boolean(),
@@ -2748,7 +2933,7 @@ function mapRelease(providerRelease) {
2748
2933
  return {
2749
2934
  created_at: providerRelease.created_at,
2750
2935
  draft: providerRelease.draft,
2751
- html_url: providerRelease.html_url,
2936
+ url: providerRelease.html_url,
2752
2937
  id: providerRelease.id,
2753
2938
  name: providerRelease.name,
2754
2939
  prerelease: providerRelease.prerelease,
@@ -2830,7 +3015,11 @@ const gitHubGetRepositoryTool = definePluginTool({
2830
3015
  operation: "github.repository.get",
2831
3016
  path: repoPath(repo)
2832
3017
  });
2833
- if (!response.ok) throw new PluginToolInputError(`GitHub repository lookup failed with HTTP ${response.status}`);
3018
+ if (!response.ok) {
3019
+ const message = `GitHub repository lookup failed with HTTP ${response.status}`;
3020
+ if (response.status === 404) throw new PluginToolInputError(`${message}. Check repo. If it is correct, the GitHub App cannot see the repository.`);
3021
+ throw new Error(message);
3022
+ }
2834
3023
  const providerResult = z.object({
2835
3024
  default_branch: z.string(),
2836
3025
  description: z.string().nullable(),
@@ -2968,7 +3157,7 @@ const providerIssueSchema = z.object({
2968
3157
  title: z.string()
2969
3158
  });
2970
3159
  function nonEmptyString$1(value, name) {
2971
- if (!value?.trim()) throw new PluginToolInputError(`${name} is required`);
3160
+ if (!value?.trim()) throw new PluginToolInputError(`${name} is missing in this Turn, so the GitHub footer cannot be added. No change to the call can fix this.`);
2972
3161
  return value.trim();
2973
3162
  }
2974
3163
  /** Update mutable issue metadata while preserving runtime-owned body attribution. */
@@ -2984,19 +3173,19 @@ const gitHubUpdateIssueTool = definePluginTool({
2984
3173
  outputSchema: outputSchema$5,
2985
3174
  async execute(input, _options, ctx) {
2986
3175
  const parsedInput = inputSchema$5.safeParse(input);
2987
- if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub updateIssue input.", { cause: parsedInput.error });
3176
+ if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub updateIssue input. Check the arguments against the tool schema and call it again.", { cause: parsedInput.error });
2988
3177
  const update = parsedInput.data;
2989
3178
  const repo = parseRepo$1(update.repo);
2990
3179
  const requester = update.body !== void 0 || update.assign_requester ? await resolveGitHubRequester(ctx) : void 0;
2991
3180
  const assignee = update.assign_requester ? linkedGitHubLogin(requesterPerson(requester)?.user) : void 0;
2992
- if (update.assign_requester && !assignee) throw new PluginToolInputError("The requester has no linked GitHub account, so the issue cannot be assigned to them.");
3181
+ if (update.assign_requester && !assignee) throw new PluginToolInputError("The requester has no linked GitHub account, so the issue cannot be assigned to them. Leave out assign_requester.");
2993
3182
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
2994
3183
  operation: "github.issue.get",
2995
3184
  path: `${repoPath(repo)}/issues/${update.issue}`
2996
3185
  }) : void 0;
2997
3186
  const payload = {
2998
3187
  ...update.title !== void 0 ? { title: update.title } : void 0,
2999
- ...update.body !== void 0 ? { body: appendGitHubFooter(appendGitHubRequesterAttribution(update.body, requester, currentBody), nonEmptyString$1(ctx.conversationId, "conversationId"), ctx.conversationLink?.url) } : void 0,
3188
+ ...update.body !== void 0 ? { body: appendGitHubFooter(appendGitHubRequesterAttribution(update.body, requester, currentBody), nonEmptyString$1(ctx.conversationId, "conversationId"), ctx.conversationLink?.url, currentBody) } : void 0,
3000
3189
  ...update.state !== void 0 ? { state: update.state } : void 0
3001
3190
  };
3002
3191
  let parsed;
@@ -3020,12 +3209,12 @@ const gitHubUpdateIssueTool = definePluginTool({
3020
3209
  parsed = response.body;
3021
3210
  if (!response.ok) {
3022
3211
  const message = `GitHub issue assignment failed with HTTP ${response.status}: ${githubErrorMessage$1(parsed)}`;
3023
- if (response.status === 404 || response.status === 422) throw new PluginToolInputError(message);
3212
+ if (response.status === 404 || response.status === 422) throw new PluginToolInputError(`${message}. Check repo and issue, and fix any field that GitHub names.`);
3024
3213
  throw new Error(message);
3025
3214
  }
3026
3215
  }
3027
3216
  const providerResult = providerIssueSchema.parse(parsed);
3028
- if (assignee && !providerResult.assignees.some((login) => login.toLowerCase() === assignee.toLowerCase())) throw new PluginToolInputError(`GitHub did not assign @${assignee} to the issue. They may not have access to ${repo.ref}.`);
3217
+ if (assignee && !providerResult.assignees.some((login) => login.toLowerCase() === assignee.toLowerCase())) throw new PluginToolInputError(`GitHub did not assign @${assignee} to the issue. They may not have access to ${repo.ref}. Continue without the assignment.`);
3029
3218
  const watch = await watchGitHubIssue(ctx, {
3030
3219
  number: providerResult.number,
3031
3220
  repo: repo.ref
@@ -3089,11 +3278,11 @@ function createGitHubUpdateIssueCommentTool(botEmail) {
3089
3278
  });
3090
3279
  if (!lookup.ok) {
3091
3280
  const message = `GitHub issue comment lookup failed with HTTP ${lookup.status}: ${githubErrorMessage$1(lookup.body)}`;
3092
- if (lookup.status === 404) throw new PluginToolInputError(message);
3281
+ if (lookup.status === 404) throw new PluginToolInputError(`${message}. Check repo and comment_id.`);
3093
3282
  throw new Error(message);
3094
3283
  }
3095
3284
  const author = z.object({ user: z.object({ id: z.number() }).nullable() }).safeParse(lookup.body);
3096
- if (!author.success || author.data.user?.id !== botUserId) throw new PluginToolInputError("This bot can only edit issue comments it posted.");
3285
+ if (!author.success || author.data.user?.id !== botUserId) throw new PluginToolInputError("This bot can only edit issue comments it posted. Post a new comment instead.");
3097
3286
  const response = await githubApi(egress, {
3098
3287
  operation: "github.issue.comment.update",
3099
3288
  method: "PATCH",
@@ -3102,7 +3291,7 @@ function createGitHubUpdateIssueCommentTool(botEmail) {
3102
3291
  });
3103
3292
  if (!response.ok) {
3104
3293
  const message = `GitHub issue comment update failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`;
3105
- if (response.status === 404 || response.status === 422) throw new PluginToolInputError(message);
3294
+ if (response.status === 404 || response.status === 422) throw new PluginToolInputError(`${message}. Check repo and comment_id, and fix any field that GitHub names.`);
3106
3295
  throw new Error(message);
3107
3296
  }
3108
3297
  const comment = z.object({
@@ -3141,7 +3330,7 @@ const pullRequestSchema = z.object({
3141
3330
  });
3142
3331
  const outputSchema$3 = pluginToolOutputSchema.merge(pullRequestSchema.extend({ target: z.literal("updatePullRequest") }));
3143
3332
  function nonEmptyString(value, name) {
3144
- if (!value?.trim()) throw new PluginToolInputError(`${name} is required`);
3333
+ if (!value?.trim()) throw new PluginToolInputError(`${name} is missing in this Turn, so the GitHub footer cannot be added. No change to the call can fix this.`);
3145
3334
  return value.trim();
3146
3335
  }
3147
3336
  /** Change draft state through GitHub GraphQL and return the confirmed value. */
@@ -3175,7 +3364,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3175
3364
  outputSchema: outputSchema$3,
3176
3365
  async execute(input, _options, ctx) {
3177
3366
  const parsedInput = inputSchema$3.safeParse(input);
3178
- if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub updatePullRequest input.", { cause: parsedInput.error });
3367
+ if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub updatePullRequest input. Check the arguments against the tool schema and call it again.", { cause: parsedInput.error });
3179
3368
  const update = parsedInput.data;
3180
3369
  if (descriptionChecks && update.body !== void 0) await checkPullRequestDescription(ctx.decider, update.body);
3181
3370
  const repo = parseRepo$1(update.repo);
@@ -3202,7 +3391,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3202
3391
  const parsed = response.body;
3203
3392
  if (!response.ok) {
3204
3393
  const message = `GitHub pull request update failed with HTTP ${response.status}: ${githubErrorMessage$1(parsed)}`;
3205
- if (response.status === 404 || response.status === 422) throw new PluginToolInputError(message);
3394
+ if (response.status === 404 || response.status === 422) throw new PluginToolInputError(`${message}. Check repo and pull_request, and fix any field that GitHub names.`);
3206
3395
  throw new Error(message);
3207
3396
  }
3208
3397
  const providerResult = z.object({
@@ -3306,27 +3495,6 @@ function pullRequestReviewPath(input) {
3306
3495
  function graphqlReactionContent(content) {
3307
3496
  return GRAPHQL_REACTION_CONTENT[content] ?? content;
3308
3497
  }
3309
- // src/pull-request-reviews.ts
3310
- const REVIEWS_PAGE_SIZE = 100;
3311
- const reviewsSchema$1 = z.array(z.object({
3312
- commit_id: z.string().nullable().optional(),
3313
- state: z.string(),
3314
- user: z.object({ login: z.string() }).nullable()
3315
- }));
3316
- /**
3317
- * Read every page of a pull request's reviews, and return the latest
3318
- * approval, change request, or dismissal of each reviewer by lowercase
3319
- * login. Comments do not count. `readPage` reads the reviews with the given
3320
- * query string.
3321
- */
3322
- async function loadLatestReviews(readPage) {
3323
- const latest = /* @__PURE__ */ new Map();
3324
- for (let page = 1;; page++) {
3325
- const batch = reviewsSchema$1.parse(await readPage(`per_page=${REVIEWS_PAGE_SIZE}&page=${page}`));
3326
- for (const review of batch) if (review.user && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.user.login.toLowerCase(), review);
3327
- if (batch.length < REVIEWS_PAGE_SIZE) return latest;
3328
- }
3329
- }
3330
3498
  // src/tools/update-pull-request-feedback.ts
3331
3499
  const inputSchema$2 = z.object({
3332
3500
  repo: z.string().describe("Repository in \"owner/name\" format."),
@@ -3351,10 +3519,11 @@ const reactionSchema = z.object({
3351
3519
  user: z.object({ id: z.number() }).nullable()
3352
3520
  });
3353
3521
  /**
3354
- * Return the issue or pull request number of one comment in `repo`. A
3355
- * conversation comment is an issue comment, so its issue can be a plain issue.
3522
+ * Return the issue or pull request number of one comment in `repo`, and its
3523
+ * author. A conversation comment is an issue comment, so its issue can be a
3524
+ * plain issue.
3356
3525
  */
3357
- async function commentParentNumber(egress, input) {
3526
+ async function readComment(egress, input) {
3358
3527
  const commentResponse = await githubApi(egress, {
3359
3528
  operation: "github.pull.comment.get",
3360
3529
  path: pullRequestCommentPath(input)
@@ -3362,17 +3531,22 @@ async function commentParentNumber(egress, input) {
3362
3531
  const commentPayload = commentResponse.body;
3363
3532
  if (!commentResponse.ok) {
3364
3533
  const message = `GitHub comment lookup failed with HTTP ${commentResponse.status}: ${githubErrorMessage$1(commentPayload)}`;
3365
- if (commentResponse.status === 404) throw new PluginToolInputError(message);
3534
+ if (commentResponse.status === 404) throw new PluginToolInputError(`${message}. Check repo, comment_id, and comment_kind.`);
3366
3535
  throw new Error(message);
3367
3536
  }
3368
3537
  const comment = z.object({
3369
3538
  issue_url: z.string().optional(),
3370
- pull_request_url: z.string().optional()
3539
+ pull_request_url: z.string().optional(),
3540
+ user: z.object({ login: z.string().min(1) }).nullable().optional()
3371
3541
  }).safeParse(commentPayload);
3372
3542
  const parentUrl = comment.success ? input.commentKind === "conversation" ? comment.data.issue_url : comment.data.pull_request_url : void 0;
3373
3543
  const number = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
3374
3544
  if (!number) throw new Error("GitHub comment did not name its issue or pull request.");
3375
- return number;
3545
+ const author = comment.success ? comment.data.user?.login : void 0;
3546
+ return {
3547
+ ...author ? { author } : void 0,
3548
+ number
3549
+ };
3376
3550
  }
3377
3551
  /**
3378
3552
  * Refuse feedback unless GitHub shows that `number` is a pull request in
@@ -3387,7 +3561,7 @@ async function assertBotAuthoredPullRequest(egress, input) {
3387
3561
  const pullPayload = pullResponse.body;
3388
3562
  if (!pullResponse.ok && pullResponse.status !== 404) throw new Error(`GitHub pull request lookup failed with HTTP ${pullResponse.status}: ${githubErrorMessage$1(pullPayload)}`);
3389
3563
  const pull = z.object({ user: z.object({ id: z.number() }).nullable() }).safeParse(pullPayload);
3390
- if (!pullResponse.ok || !pull.success || pull.data.user?.id !== input.botUserId) throw new PluginToolInputError("This bot can only set feedback status on comments on pull requests it authored.");
3564
+ if (!pullResponse.ok || !pull.success || pull.data.user?.id !== input.botUserId) throw new PluginToolInputError("This bot can only set feedback status on comments on pull requests it authored. Do not call this tool for this pull request.");
3391
3565
  }
3392
3566
  const reviewReactionsSchema = z.object({ data: z.object({ node: z.object({ reactionGroups: z.array(z.object({
3393
3567
  content: z.string(),
@@ -3395,9 +3569,11 @@ const reviewReactionsSchema = z.object({ data: z.object({ node: z.object({ react
3395
3569
  })) }) }) });
3396
3570
  /** Return the REST reactions of a comment that is on `pullRequest`. */
3397
3571
  async function commentReactions(egress, input) {
3398
- if (await commentParentNumber(egress, input) !== String(input.pullRequest)) throw new PluginToolInputError(`GitHub comment ${input.commentId} is not on pull request ${input.pullRequest}.`);
3572
+ const comment = await readComment(egress, input);
3573
+ if (comment.number !== String(input.pullRequest)) throw new PluginToolInputError(`GitHub comment ${input.commentId} is not on pull request ${input.pullRequest}. Set pull_request to the pull request that has the comment.`);
3399
3574
  const path = pullRequestCommentReactionsPath(input);
3400
3575
  return {
3576
+ ...comment.author ? { author: comment.author } : void 0,
3401
3577
  list: () => githubApi(egress, {
3402
3578
  operation: "github.pull.comment-reaction.list",
3403
3579
  path: `${path}?per_page=100`
@@ -3416,10 +3592,7 @@ async function commentReactions(egress, input) {
3416
3592
  })
3417
3593
  };
3418
3594
  }
3419
- /**
3420
- * Return the GraphQL reactions of a review on `pullRequest`, and the login of
3421
- * its author when the review requests changes.
3422
- */
3595
+ /** Return the GraphQL reactions of a review on `pullRequest`. */
3423
3596
  async function reviewBodyReactions(egress, input) {
3424
3597
  const reviewResponse = await githubApi(egress, {
3425
3598
  operation: "github.pull.review.get",
@@ -3427,12 +3600,11 @@ async function reviewBodyReactions(egress, input) {
3427
3600
  });
3428
3601
  if (!reviewResponse.ok) {
3429
3602
  const message = `GitHub review lookup failed with HTTP ${reviewResponse.status}: ${githubErrorMessage$1(reviewResponse.body)}`;
3430
- if (reviewResponse.status === 404) throw new PluginToolInputError(message);
3603
+ if (reviewResponse.status === 404) throw new PluginToolInputError(`${message}. Check repo, pull_request, and comment_id.`);
3431
3604
  throw new Error(message);
3432
3605
  }
3433
3606
  const review = z.object({
3434
3607
  node_id: z.string().min(1),
3435
- state: z.string().optional(),
3436
3608
  user: z.object({ login: z.string().min(1) }).nullable().optional()
3437
3609
  }).parse(reviewResponse.body);
3438
3610
  const subjectId = review.node_id;
@@ -3447,7 +3619,7 @@ async function reviewBodyReactions(egress, input) {
3447
3619
  });
3448
3620
  const update = `github.pull.review-reaction.update:${input.owner}/${input.name}`.toLowerCase();
3449
3621
  return {
3450
- ...review.state === "CHANGES_REQUESTED" && review.user ? { changesRequestedBy: review.user.login } : void 0,
3622
+ ...review.user ? { author: review.user.login } : void 0,
3451
3623
  list: () => graphql("github.pull.review-reaction.list", REVIEW_REACTIONS, { subjectId }),
3452
3624
  botReactions: (body) => reviewReactionsSchema.parse(body).data.node.reactionGroups.filter((group) => group.reactors.nodes.some((reactor) => reactor.databaseId === input.botUserId)).map((group) => ({ content: REST_REACTION_CONTENT.get(group.content) ?? group.content })),
3453
3625
  remove: (reaction) => graphql(update, REMOVE_REVIEW_REACTION, {
@@ -3461,41 +3633,83 @@ async function reviewBodyReactions(egress, input) {
3461
3633
  };
3462
3634
  }
3463
3635
  /**
3464
- * Ask the reviewer who requested changes to review again, while their latest
3465
- * review still requests changes. GitHub stops asking a reviewer once they
3466
- * review, so the fixed pull request would not wait on them. A reviewer who
3467
- * approved since then is not asked. The request is optional, so a failure is
3468
- * logged and does not fail the tool.
3636
+ * Ask the reviewer to review again when every comment of their latest
3637
+ * change request is marked and the required checks pass. GitHub stops
3638
+ * asking a reviewer once they review, so the fixed pull request would not
3639
+ * wait on them. While the checks have not passed, the ask is held, and the
3640
+ * check suite webhook asks when they pass. The ask is optional, so a failure
3641
+ * is logged and does not fail the tool.
3469
3642
  */
3470
- async function requestReviewAgain$1(ctx, input) {
3471
- const fields = {
3643
+ async function askForReviewAgain(ctx, input) {
3644
+ const target = {
3472
3645
  number: input.pullRequest,
3473
- repo: `${input.owner}/${input.name}`
3646
+ repositoryFullName: `${input.owner}/${input.name}`
3647
+ };
3648
+ const fields = {
3649
+ number: target.number,
3650
+ repo: target.repositoryFullName
3474
3651
  };
3475
3652
  try {
3476
- const pullPath = `${repoPath(input)}/pulls/${input.pullRequest}`;
3477
- let rejectedStatus;
3478
- const latest = await loadLatestReviews(async (query) => {
3479
- const page = await githubApi(ctx.egress, {
3480
- operation: "github.pull.review.list",
3481
- path: `${pullPath}/reviews?${query}`
3653
+ const readiness = await readReviewAgainReadiness(async (request) => {
3654
+ const response = await githubApi(ctx.egress, {
3655
+ ...request,
3656
+ ...request.body === void 0 ? void 0 : { method: "POST" }
3482
3657
  });
3483
- if (page.ok) return page.body;
3484
- rejectedStatus = page.status;
3485
- return [];
3658
+ if (!response.ok) throw new Error(`GitHub ${request.operation} failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`);
3659
+ return response.body;
3660
+ }, {
3661
+ ...input,
3662
+ number: input.pullRequest
3486
3663
  });
3487
- if (rejectedStatus === void 0 && latest.get(input.reviewer.toLowerCase())?.state === "CHANGES_REQUESTED") {
3488
- const response = await githubApi(ctx.egress, {
3489
- operation: "github.pull.request_reviewers",
3490
- method: "POST",
3491
- path: `${pullPath}/requested_reviewers`,
3492
- body: { reviewers: [input.reviewer] }
3664
+ if (readiness === "none") return;
3665
+ const at = (/* @__PURE__ */ new Date()).toISOString();
3666
+ if (readiness === "checks") {
3667
+ await holdGitHubReviewAsk(ctx.state, target, {
3668
+ at,
3669
+ ...input.marked ? { marked: input.marked } : void 0,
3670
+ reason: "checks",
3671
+ reviewer: input.reviewer
3493
3672
  });
3494
- if (!response.ok) rejectedStatus = response.status;
3673
+ return;
3674
+ }
3675
+ await markGitHubReviewAsked(ctx.state, target, {
3676
+ at,
3677
+ reviewer: input.reviewer
3678
+ });
3679
+ if (await requestReviewer(ctx, input)) {
3680
+ await dropHeldGitHubReviewAsk(ctx.state, target, input.reviewer);
3681
+ return;
3495
3682
  }
3496
- if (rejectedStatus !== void 0) ctx.log.warn("github.pull_request.request_reviewers_after_feedback.rejected", {
3683
+ await holdGitHubReviewAsk(ctx.state, target, {
3684
+ at,
3685
+ ...input.marked ? { marked: input.marked } : void 0,
3686
+ reason: "handled",
3687
+ reviewer: input.reviewer
3688
+ });
3689
+ } catch (error) {
3690
+ ctx.log.warn("github.pull_request.request_reviewers_after_feedback.failed", {
3497
3691
  ...fields,
3498
- status: rejectedStatus
3692
+ errorType: error instanceof Error ? error.name : "UnknownError"
3693
+ });
3694
+ }
3695
+ }
3696
+ /** Ask the reviewer on GitHub, and return whether GitHub took the request. */
3697
+ async function requestReviewer(ctx, input) {
3698
+ const fields = {
3699
+ number: input.pullRequest,
3700
+ repo: `${input.owner}/${input.name}`
3701
+ };
3702
+ try {
3703
+ const response = await githubApi(ctx.egress, {
3704
+ operation: "github.pull.request_reviewers",
3705
+ method: "POST",
3706
+ path: `${repoPath(input)}/pulls/${input.pullRequest}/requested_reviewers`,
3707
+ body: { reviewers: [input.reviewer] }
3708
+ });
3709
+ if (response.ok) return true;
3710
+ ctx.log.warn("github.pull_request.request_reviewers_after_feedback.rejected", {
3711
+ ...fields,
3712
+ status: response.status
3499
3713
  });
3500
3714
  } catch (error) {
3501
3715
  ctx.log.warn("github.pull_request.request_reviewers_after_feedback.failed", {
@@ -3503,6 +3717,7 @@ async function requestReviewAgain$1(ctx, input) {
3503
3717
  errorType: error instanceof Error ? error.name : "UnknownError"
3504
3718
  });
3505
3719
  }
3720
+ return false;
3506
3721
  }
3507
3722
  function failed(response) {
3508
3723
  const errors = response.body?.errors;
@@ -3511,7 +3726,8 @@ function failed(response) {
3511
3726
  /**
3512
3727
  * Set Junior's feedback reaction on a pull request comment or review body.
3513
3728
  * Replace only state reactions Junior previously added to the same comment.
3514
- * Addressed change requests ask their reviewer to review again.
3729
+ * When the comments of a change request are all marked, ask its reviewer to
3730
+ * review again.
3515
3731
  */
3516
3732
  function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3517
3733
  return definePluginTool({
@@ -3522,13 +3738,13 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3522
3738
  openWorldHint: true,
3523
3739
  readOnlyHint: false
3524
3740
  },
3525
- description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after acting on the feedback. Replaces only your prior status reaction on that comment. Addressed on a change request asks its reviewer to review again, unless they approved since. Only works on pull requests the bot authored.",
3741
+ description: "Set your outcome reaction on GitHub pull request feedback: addressed (+1) or declined (-1). Call it after acting on the feedback. Replaces only your prior status reaction on that comment. When every comment of the author's latest change request is marked and the required checks pass, asks the author to review again. Only works on pull requests the bot authored.",
3526
3742
  exposure: "direct",
3527
3743
  inputSchema: inputSchema$2,
3528
3744
  outputSchema: outputSchema$2,
3529
3745
  async execute(input, _options, ctx) {
3530
3746
  const parsedInput = inputSchema$2.safeParse(input);
3531
- if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub updatePullRequestFeedback input.", { cause: parsedInput.error });
3747
+ if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub updatePullRequestFeedback input. Check the arguments against the tool schema and call it again.", { cause: parsedInput.error });
3532
3748
  const { comment_id: commentId, comment_kind: commentKind, pull_request: pullRequest, status } = parsedInput.data;
3533
3749
  const repo = parseRepo$1(parsedInput.data.repo);
3534
3750
  const botUserId = botUserIdFromEmail(botEmail);
@@ -3565,11 +3781,16 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3565
3781
  const createPayload = createResponse.body;
3566
3782
  if (failed(createResponse)) throw new Error(`GitHub reaction creation failed with HTTP ${createResponse.status}: ${githubErrorMessage$1(createPayload)}`);
3567
3783
  }
3568
- if (status === "addressed" && reactions.changesRequestedBy) await requestReviewAgain$1(ctx, {
3569
- owner: repo.owner,
3784
+ if (reactions.author) await askForReviewAgain(ctx, {
3785
+ botUserId,
3570
3786
  name: repo.name,
3787
+ owner: repo.owner,
3788
+ ...commentKind === "conversation" ? void 0 : { marked: {
3789
+ id: commentId,
3790
+ kind: commentKind
3791
+ } },
3571
3792
  pullRequest,
3572
- reviewer: reactions.changesRequestedBy
3793
+ reviewer: reactions.author
3573
3794
  });
3574
3795
  return {
3575
3796
  target: "updatePullRequestFeedback",
@@ -3621,7 +3842,7 @@ function createGitHubResolvePullRequestReviewThreadTool(botEmail) {
3621
3842
  outputSchema: outputSchema$1,
3622
3843
  async execute(input, _options, ctx) {
3623
3844
  const parsedInput = inputSchema$1.safeParse(input);
3624
- if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub resolvePullRequestReviewThread input.", { cause: parsedInput.error });
3845
+ if (!parsedInput.success) throw new PluginToolInputError("Invalid GitHub resolvePullRequestReviewThread input. Check the arguments against the tool schema and call it again.", { cause: parsedInput.error });
3625
3846
  const repo = parseRepo$1(parsedInput.data.repo);
3626
3847
  const botUserId = botUserIdFromEmail(botEmail);
3627
3848
  if (botUserId === void 0) throw new Error("GitHub App bot identity is not configured.");
@@ -3648,10 +3869,10 @@ function createGitHubResolvePullRequestReviewThreadTool(botEmail) {
3648
3869
  const lookupResult = z.object({ data: z.object({ node: z.unknown().nullable().optional() }).passthrough() }).passthrough().safeParse(lookupPayload);
3649
3870
  const rawNode = lookupResult.success ? lookupResult.data.data.node : void 0;
3650
3871
  const parsedNode = rawNode == null ? void 0 : threadNodeSchema.safeParse(rawNode);
3651
- if (!parsedNode?.success) throw new PluginToolInputError("GitHub review thread was not found.");
3872
+ if (!parsedNode?.success) throw new PluginToolInputError("GitHub review thread was not found. Set thread_id to the node id of a review thread on a pull request in repo.");
3652
3873
  const thread = parsedNode.data;
3653
3874
  const pullRequest = thread.pullRequest;
3654
- if (!(pullRequest.repository.nameWithOwner.toLowerCase() === repo.ref.toLowerCase() && pullRequest.author?.databaseId === botUserId)) throw new PluginToolInputError("This bot can only resolve review threads on pull requests it authored.");
3875
+ if (!(pullRequest.repository.nameWithOwner.toLowerCase() === repo.ref.toLowerCase() && pullRequest.author?.databaseId === botUserId)) throw new PluginToolInputError("This bot can only resolve review threads on pull requests it authored. Leave this thread for a person to resolve.");
3655
3876
  if (thread.isResolved) return {
3656
3877
  target: "resolvePullRequestReviewThread",
3657
3878
  repo: repo.ref,
@@ -3713,7 +3934,7 @@ const outputSchema = pluginToolOutputSchema.extend({
3713
3934
  });
3714
3935
  function throwReviewError(status, body) {
3715
3936
  const message = `GitHub pull request review failed with HTTP ${status}: ${githubErrorMessage$1(body)}`;
3716
- if (status === 404 || status === 422) throw new PluginToolInputError(message);
3937
+ if (status === 404 || status === 422) throw new PluginToolInputError(`${message}. Check repo and pull_request, and fix any field that GitHub names.`);
3717
3938
  throw new Error(message);
3718
3939
  }
3719
3940
  /** Submit a comment or change-request review through GitHub's REST API. */
@@ -3811,79 +4032,6 @@ function createGitHubTools(botEmail, pullRequestSubscription, experimental = {})
3811
4032
  createPullRequest: createGitHubPullRequestTool(pullRequestSubscription, descriptionChecks)
3812
4033
  };
3813
4034
  }
3814
- // src/issue-outcomes/store.ts
3815
- const githubIssueOutcomeInputSchema = z.object({
3816
- candidateOwned: z.boolean(),
3817
- closedAt: z.date().optional(),
3818
- issueId: z.string().min(1),
3819
- number: z.number().int().positive(),
3820
- openedAt: z.date(),
3821
- repositoryFullName: z.string().min(1),
3822
- repositoryId: z.string().min(1),
3823
- state: githubIssueStateSchema,
3824
- stateReason: githubIssueStateReasonSchema.optional(),
3825
- updatedAt: z.date()
3826
- }).strict();
3827
- const githubIssueConversationsInputSchema = z.object({
3828
- conversationIds: z.array(z.string().min(1)).min(1),
3829
- issueId: z.string().min(1)
3830
- }).strict();
3831
- /** Select mutable issue lifecycle fields while excluding ownership evidence. */
3832
- function projectionValues$1(input) {
3833
- return {
3834
- closedAt: input.closedAt ?? null,
3835
- number: input.number,
3836
- openedAt: input.openedAt,
3837
- repositoryFullName: input.repositoryFullName,
3838
- repositoryId: input.repositoryId,
3839
- state: input.state,
3840
- stateReason: input.stateReason ?? null,
3841
- updatedAt: input.updatedAt
3842
- };
3843
- }
3844
- /**
3845
- * Record the newest lifecycle projection for one Junior-owned issue.
3846
- * Ownership-qualified opening or closing events insert; later events update
3847
- * existing rows, and older provider timestamps cannot regress them.
3848
- * Returns the written row state so follow-up annotation updates stay scoped to
3849
- * associated conversations.
3850
- */
3851
- async function recordGitHubIssueOutcome(db, input) {
3852
- const outcome = githubIssueOutcomeInputSchema.parse(input);
3853
- const values = projectionValues$1(outcome);
3854
- if (!outcome.candidateOwned) {
3855
- const updated = await db.update(juniorGitHubIssues).set(values).where(and(eq(juniorGitHubIssues.issueId, outcome.issueId), lte(juniorGitHubIssues.updatedAt, outcome.updatedAt))).returning({ conversationIds: juniorGitHubIssues.conversationIds });
3856
- return {
3857
- applied: updated.length > 0,
3858
- conversationIds: updated[0]?.conversationIds ?? []
3859
- };
3860
- }
3861
- const inserted = await db.insert(juniorGitHubIssues).values({
3862
- issueId: outcome.issueId,
3863
- ...values
3864
- }).onConflictDoUpdate({
3865
- target: juniorGitHubIssues.issueId,
3866
- set: values,
3867
- where: lte(juniorGitHubIssues.updatedAt, outcome.updatedAt)
3868
- }).returning({ conversationIds: juniorGitHubIssues.conversationIds });
3869
- return {
3870
- applied: inserted.length > 0,
3871
- conversationIds: inserted[0]?.conversationIds ?? []
3872
- };
3873
- }
3874
- /** Append native conversation ids to an existing Junior-owned issue projection. */
3875
- async function recordGitHubIssueConversations(db, input) {
3876
- const association = githubIssueConversationsInputSchema.parse(input);
3877
- const conversationIds = sql.join(association.conversationIds.map((id) => sql`${id}`), sql`, `);
3878
- return (await db.update(juniorGitHubIssues).set({ conversationIds: sql`ARRAY(
3879
- SELECT DISTINCT value
3880
- FROM unnest(
3881
- ${juniorGitHubIssues.conversationIds}
3882
- || ARRAY[${conversationIds}]::text[]
3883
- ) AS value
3884
- ORDER BY value
3885
- )` }).where(eq(juniorGitHubIssues.issueId, association.issueId)).returning({ issueId: juniorGitHubIssues.issueId })).length > 0;
3886
- }
3887
4035
  // src/code-change-titles/parse.ts
3888
4036
  function nativePattern(source) {
3889
4037
  const regex = new RegExp(source, "i");
@@ -4116,13 +4264,6 @@ const githubPullRequestConversationsInputSchema = z.object({
4116
4264
  conversationIds: z.array(z.string().min(1)).min(1),
4117
4265
  pullRequestId: z.string().min(1)
4118
4266
  }).strict();
4119
- const githubPullRequestLinkedIssuesInputSchema = z.object({
4120
- linkedIssues: z.array(z.object({
4121
- number: z.number().int().positive(),
4122
- repositoryFullName: z.string().min(1)
4123
- }).strict()).min(1),
4124
- pullRequestId: z.string().min(1)
4125
- }).strict();
4126
4267
  /** Select mutable lifecycle fields while excluding transient ownership inputs. */
4127
4268
  function projectionValues(input) {
4128
4269
  return {
@@ -4249,20 +4390,6 @@ async function recordGitHubPullRequestConversations(db, input) {
4249
4390
  ORDER BY value
4250
4391
  )` }).where(eq(juniorGitHubPullRequests.pullRequestId, association.pullRequestId)).returning({ pullRequestId: juniorGitHubPullRequests.pullRequestId })).length > 0;
4251
4392
  }
4252
- /** Link an existing Junior-owned PR to tracked issues across repositories. */
4253
- async function recordGitHubPullRequestLinkedIssues(db, input) {
4254
- const association = githubPullRequestLinkedIssuesInputSchema.parse(input);
4255
- const list = (values) => sql.join(values.map((value) => sql`${value}`), sql`, `);
4256
- const issues = sql`unnest(
4257
- ARRAY[${list(association.linkedIssues.map((issue) => issue.repositoryFullName))}]::text[],
4258
- ARRAY[${list(association.linkedIssues.map((issue) => issue.number))}]::integer[]
4259
- ) AS issue(repository_full_name, number)`;
4260
- return (await db.insert(juniorGitHubPullRequestIssues).select(db.select({
4261
- pullRequestId: juniorGitHubPullRequests.pullRequestId,
4262
- issueRepositoryFullName: sql`lower(issue.repository_full_name)`.as("issue_repository_full_name"),
4263
- issueNumber: sql`issue.number`.as("issue_number")
4264
- }).from(juniorGitHubPullRequests).crossJoin(issues).where(eq(juniorGitHubPullRequests.pullRequestId, association.pullRequestId))).onConflictDoNothing().returning({ issueNumber: juniorGitHubPullRequestIssues.issueNumber })).length > 0;
4265
- }
4266
4393
  /** Match one pull request row by repository name, in any case, and number. */
4267
4394
  function pullRequestRow(target) {
4268
4395
  return and(sql`lower(${juniorGitHubPullRequests.repositoryFullName}) = ${target.repositoryFullName.toLowerCase()}`, eq(juniorGitHubPullRequests.number, target.number));
@@ -4548,6 +4675,41 @@ async function closeGitHubConflictItems(args) {
4548
4675
  };
4549
4676
  await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
4550
4677
  }
4678
+ // src/webhooks/graphql-request.ts
4679
+ /**
4680
+ * GitHub GraphQL requests that fail on a response with errors and no data.
4681
+ */
4682
+ /**
4683
+ * A GitHub GraphQL response with errors and no data. GitHub sends it with
4684
+ * HTTP 200, such as when the installation is rate limited.
4685
+ */
4686
+ var GitHubGraphqlError = class extends Error {
4687
+ constructor(message) {
4688
+ super(message);
4689
+ this.name = "GitHubGraphqlError";
4690
+ }
4691
+ };
4692
+ const graphqlFailureSchema = z.object({
4693
+ data: z.null().optional(),
4694
+ errors: z.array(z.object({
4695
+ message: z.string(),
4696
+ type: z.string().optional()
4697
+ })).min(1)
4698
+ });
4699
+ /**
4700
+ * Send a GitHub GraphQL request. Throw `GitHubGraphqlError` when GitHub
4701
+ * returns errors and no data, so the caller does not read a missing result.
4702
+ * A response with partial data returns as usual.
4703
+ */
4704
+ async function githubGraphqlRequest(params) {
4705
+ const response = await githubRequest("https://api.github.com", "/graphql", {
4706
+ ...params,
4707
+ method: "POST"
4708
+ });
4709
+ const failure = graphqlFailureSchema.safeParse(response);
4710
+ if (failure.success) throw new GitHubGraphqlError(failure.data.errors.map((error) => error.type ? `${error.type}: ${error.message}` : error.message).join("; "));
4711
+ return response;
4712
+ }
4551
4713
  // src/webhooks/installation-requests.ts
4552
4714
  /**
4553
4715
  * GitHub requests that webhook handling makes with installation tokens.
@@ -4615,7 +4777,7 @@ async function loadPullRequestLifecycles(env, input) {
4615
4777
  throw error;
4616
4778
  }
4617
4779
  const { owner, name } = splitRepository(z.object({ full_name: z.string().min(1) }).parse(await githubRequest("https://api.github.com", `/repositories/${input.repositoryId}`, { token: token.token })).full_name, "pull request lifecycle");
4618
- return await githubRequest("https://api.github.com", "/graphql", {
4780
+ return await githubGraphqlRequest({
4619
4781
  body: {
4620
4782
  ...pullRequestLifecycles(input.numbers.length),
4621
4783
  variables: {
@@ -4624,7 +4786,6 @@ async function loadPullRequestLifecycles(env, input) {
4624
4786
  ...Object.fromEntries(input.numbers.map((number, index) => [`n${index}`, number]))
4625
4787
  }
4626
4788
  },
4627
- method: "POST",
4628
4789
  token: token.token
4629
4790
  });
4630
4791
  }
@@ -4639,7 +4800,7 @@ async function searchOpenPullRequestMergeability(env, input) {
4639
4800
  permissions: { pull_requests: "read" },
4640
4801
  repositories: [name]
4641
4802
  });
4642
- return await githubRequest("https://api.github.com", "/graphql", {
4803
+ return await githubGraphqlRequest({
4643
4804
  body: {
4644
4805
  ...OPEN_PULL_REQUEST_MERGEABILITY,
4645
4806
  variables: {
@@ -4647,7 +4808,6 @@ async function searchOpenPullRequestMergeability(env, input) {
4647
4808
  query: `repo:${input.repositoryFullName} is:pr is:open author:${input.author}`
4648
4809
  }
4649
4810
  },
4650
- method: "POST",
4651
4811
  token: token.token
4652
4812
  });
4653
4813
  }
@@ -4659,7 +4819,7 @@ async function loadPullRequestConflictHistory(env, pullRequest) {
4659
4819
  permissions: { pull_requests: "read" },
4660
4820
  repositories: [name]
4661
4821
  });
4662
- return await githubRequest("https://api.github.com", "/graphql", {
4822
+ return await githubGraphqlRequest({
4663
4823
  body: {
4664
4824
  ...PULL_REQUEST_CONFLICT_HISTORY,
4665
4825
  variables: {
@@ -4668,7 +4828,6 @@ async function loadPullRequestConflictHistory(env, pullRequest) {
4668
4828
  owner
4669
4829
  }
4670
4830
  },
4671
- method: "POST",
4672
4831
  token: token.token
4673
4832
  });
4674
4833
  }
@@ -4686,6 +4845,30 @@ async function requestPullRequestReviewers(env, input) {
4686
4845
  token: token.token
4687
4846
  });
4688
4847
  }
4848
+ /**
4849
+ * Return a read-only GitHub reader for one repository, for the review-again
4850
+ * check: GraphQL for the pull request, and REST for the branch rules.
4851
+ */
4852
+ async function loadReviewAgainReader(env, repositoryFullName) {
4853
+ const { name } = splitRepository(repositoryFullName, "review again");
4854
+ const token = await issueInstallationToken({
4855
+ ...env,
4856
+ permissions: {
4857
+ checks: "read",
4858
+ contents: "read",
4859
+ metadata: "read",
4860
+ pull_requests: "read"
4861
+ },
4862
+ repositories: [name]
4863
+ });
4864
+ return async (request) => await githubRequest("https://api.github.com", request.path, {
4865
+ ...request.body === void 0 ? { responses: env.responses } : {
4866
+ body: request.body,
4867
+ method: "POST"
4868
+ },
4869
+ token: token.token
4870
+ });
4871
+ }
4689
4872
  /** Add the "reviewing" reaction to one pull request comment or review body. */
4690
4873
  async function markPullRequestFeedbackReviewing(env, target) {
4691
4874
  const { owner, name } = splitRepository(target.repo, "pull request feedback");
@@ -4769,7 +4952,6 @@ const reviewsSchema = z.object({
4769
4952
  }),
4770
4953
  nodes: nodesSchema(z.object({
4771
4954
  author: actorSchema,
4772
- commit: z.object({ oid: z.string().min(1) }).nullable(),
4773
4955
  state: z.string(),
4774
4956
  submittedAt: timestampSchema$1.nullable()
4775
4957
  }))
@@ -4780,8 +4962,6 @@ const userLoginSchema = z.object({
4780
4962
  }).nullable();
4781
4963
  const nextActionSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({
4782
4964
  autoMergeRequest: z.object({}).nullable(),
4783
- commits: z.object({ nodes: nodesSchema(z.object({ commit: z.object({ committedDate: timestampSchema$1 }) })) }),
4784
- headRefOid: z.string().min(1),
4785
4965
  isDraft: z.boolean(),
4786
4966
  mergeStateStatus: z.string(),
4787
4967
  reviewRequests: z.object({ nodes: nodesSchema(z.object({ requestedReviewer: userLoginSchema })) }),
@@ -4828,7 +5008,7 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4828
5008
  number: pullRequest.number,
4829
5009
  owner
4830
5010
  };
4831
- const query = async (document, extra) => await githubRequest("https://api.github.com", "/graphql", {
5011
+ const query = async (document, extra) => await githubGraphqlRequest({
4832
5012
  body: {
4833
5013
  ...document,
4834
5014
  variables: {
@@ -4836,7 +5016,6 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4836
5016
  ...extra
4837
5017
  }
4838
5018
  },
4839
- method: "POST",
4840
5019
  token: token.token
4841
5020
  });
4842
5021
  const readPull = async () => nextActionSchema.parse(await query(PULL_REQUEST_NEXT_ACTION)).data.repository.pullRequest;
@@ -4852,12 +5031,6 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4852
5031
  page = older.pageInfo;
4853
5032
  }
4854
5033
  const activity = [];
4855
- const head = pull.commits.nodes.at(-1);
4856
- if (head) activity.push({
4857
- at: new Date(head.commit.committedDate),
4858
- kind: "push",
4859
- login: ""
4860
- });
4861
5034
  for (const item of pull.timelineItems.nodes) if (item.__typename === "IssueComment" && item.author) activity.push({
4862
5035
  at: new Date(item.createdAt),
4863
5036
  kind: "author",
@@ -4878,10 +5051,11 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4878
5051
  activity,
4879
5052
  approved: false,
4880
5053
  autoMerge: Boolean(pull.autoMergeRequest),
5054
+ changesRequested: false,
4881
5055
  draft: pull.isDraft,
4882
- headSha: pull.headRefOid,
4883
5056
  ...mergeableState ? { mergeableState } : void 0,
4884
5057
  requestedReviewers: pull.reviewRequests.nodes.flatMap((request) => request.requestedReviewer?.__typename === "User" && request.requestedReviewer.login ? [request.requestedReviewer.login] : []),
5058
+ reviewedBy: [],
4885
5059
  state: pull.state === "MERGED" ? "merged" : pull.state === "OPEN" ? "open" : "closed",
4886
5060
  title: pull.title,
4887
5061
  url: pull.url
@@ -4889,14 +5063,13 @@ async function loadPullRequestMergeState(env, pullRequest, requesterLogin) {
4889
5063
  if (!open) return state;
4890
5064
  const latest = /* @__PURE__ */ new Map();
4891
5065
  for (const review of reviews) if (review.author && review.state !== "COMMENTED" && review.state !== "PENDING") latest.set(review.author.login.toLowerCase(), review);
5066
+ const latestSubmitted = /* @__PURE__ */ new Map();
5067
+ for (const review of reviews) if (review.author && review.submittedAt && review.state !== "PENDING") latestSubmitted.set(review.author.login.toLowerCase(), review.state);
5068
+ state.reviewedBy = [...latestSubmitted].flatMap(([login, reviewState]) => reviewState === "DISMISSED" ? [] : [login]);
4892
5069
  const reviewStates = [...latest.values()].map((review) => review.state);
4893
5070
  if (!state.autoMerge && state.mergeableState === "clean") state.approved = reviewStates.includes("APPROVED") && !reviewStates.includes("CHANGES_REQUESTED");
4894
5071
  const login = requesterLogin?.toLowerCase();
4895
- const requesterReview = login ? latest.get(login) : void 0;
4896
- if (requesterReview?.state === "CHANGES_REQUESTED" && requesterReview.commit) {
4897
- state.changesRequestedCommit = requesterReview.commit.oid;
4898
- if (requesterReview.submittedAt) state.changesRequestedAt = new Date(requesterReview.submittedAt);
4899
- }
5072
+ state.changesRequested = (login ? latest.get(login) : void 0)?.state === "CHANGES_REQUESTED";
4900
5073
  return state;
4901
5074
  }
4902
5075
  // src/webhooks/pull-request-action.ts
@@ -4979,27 +5152,14 @@ function pullRequestActionTargets(eventName, body) {
4979
5152
  repositoryFullName: parsed.data.repository.full_name
4980
5153
  }];
4981
5154
  }
4982
- /**
4983
- * Who did one thing on a pull request. A push counts as Junior's, as new
4984
- * commits do. A request for the requester's review hands the pull request
4985
- * to them, so it counts as Junior's too.
4986
- */
4987
- function actor(activity, requesterLogin, botEmail) {
4988
- const byRequester = requesterLogin !== void 0 && activity.login.toLowerCase() === requesterLogin.toLowerCase();
4989
- switch (activity.kind) {
4990
- case "push": return "junior";
4991
- case "reviewRequest": return byRequester ? "junior" : void 0;
4992
- case "author":
4993
- if (isBotLogin(activity.login, botEmail)) return "junior";
4994
- return byRequester ? "requester" : void 0;
4995
- }
5155
+ function sameLogin(a, b) {
5156
+ return b !== void 0 && a.toLowerCase() === b.toLowerCase();
4996
5157
  }
4997
- function latestActivity(activity, requesterLogin, botEmail) {
5158
+ function latestActivity(activity, requesterLogin) {
4998
5159
  const latest = {};
4999
5160
  for (const entry of activity) {
5000
- const by = actor(entry, requesterLogin, botEmail);
5001
- if (!by) continue;
5002
- const key = by === "junior" ? "juniorAt" : "requesterAt";
5161
+ if (!sameLogin(entry.login, requesterLogin)) continue;
5162
+ const key = entry.kind === "reviewRequest" ? "askedAt" : "requesterAt";
5003
5163
  const saved = latest[key];
5004
5164
  if (!saved || entry.at > saved) latest[key] = entry.at;
5005
5165
  }
@@ -5009,18 +5169,6 @@ function timeOf(at) {
5009
5169
  return at ? at.getTime() : Number.NEGATIVE_INFINITY;
5010
5170
  }
5011
5171
  /**
5012
- * Return why the requester's review is wanted again after their change
5013
- * request, or undefined while Junior acts next.
5014
- */
5015
- function reviewAgainReason(state, activity) {
5016
- if (!state.changesRequestedCommit) return void 0;
5017
- const newCommits = state.changesRequestedCommit !== state.headSha;
5018
- const changesRequestedAt = timeOf(state.changesRequestedAt);
5019
- const requesterAt = Math.max(timeOf(activity.requesterAt), changesRequestedAt);
5020
- if (timeOf(activity.juniorAt) > requesterAt) return newCommits ? "commits" : "reply";
5021
- return newCommits && !(timeOf(activity.requesterAt) > changesRequestedAt) ? "commits" : void 0;
5022
- }
5023
- /**
5024
5172
  * Derive the requester's next action. Return undefined when it cannot be
5025
5173
  * known yet, so a later event decides.
5026
5174
  */
@@ -5029,14 +5177,8 @@ function nextAction(state, requester, saved) {
5029
5177
  const canMerge = !state.draft && !state.autoMerge;
5030
5178
  if (canMerge && state.mergeableState === "clean" && state.approved) return { action: "merge" };
5031
5179
  if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5032
- const requested = isRequested(state, requester.login);
5033
- if (requested && !requester.actedLast) return { action: "review" };
5034
- const reason = reviewAgainReason(state, requester.activity);
5035
- if (reason) return {
5036
- action: "review",
5037
- reason
5038
- };
5039
- if (requested && !state.changesRequestedCommit) return { action: "review" };
5180
+ if (requester.askedAgain) return { action: "review" };
5181
+ if (isRequested(state, requester.login) && (!requester.actedLast || !state.changesRequested)) return { action: "review" };
5040
5182
  if (canMerge && !state.mergeableState) return void 0;
5041
5183
  return {};
5042
5184
  }
@@ -5044,10 +5186,6 @@ function isRequested(state, login) {
5044
5186
  const lower = login?.toLowerCase();
5045
5187
  return state.requestedReviewers.some((reviewer) => reviewer.toLowerCase() === lower);
5046
5188
  }
5047
- const REVIEW_AGAIN_TEXT = {
5048
- commits: (number) => `#${number} has new commits since you requested changes.`,
5049
- reply: (number) => `#${number} has a reply since you requested changes.`
5050
- };
5051
5189
  /** Why an item closes when its pull request is no longer open. */
5052
5190
  const ENDED_REASONS = {
5053
5191
  closed: {
@@ -5078,11 +5216,16 @@ function closeReason(state, previous) {
5078
5216
  status: "dismissed"
5079
5217
  };
5080
5218
  }
5219
+ /** The item text that says why Junior asked for the review again. */
5220
+ const REVIEW_AGAIN_TEXT = {
5221
+ checks: "Checks now pass, and every comment is handled.",
5222
+ handled: "Every comment on your change request is handled."
5223
+ };
5081
5224
  async function showAction(items, args) {
5082
5225
  const { action, number, state } = args;
5083
5226
  if (action) await items.upsert({
5084
5227
  assigneeIdentityIds: [args.identityId],
5085
- body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` : `${args.reason ? REVIEW_AGAIN_TEXT[args.reason](number) : `GitHub asks you to review #${number}.`}\n\n${state.url}`,
5228
+ body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` : `${args.reason ? REVIEW_AGAIN_TEXT[args.reason] : `GitHub asks you to review #${number}.`}\n\n${state.url}`,
5086
5229
  dedupeKey: args.dedupeKey,
5087
5230
  subject: {
5088
5231
  id: state.url,
@@ -5099,39 +5242,35 @@ async function showAction(items, args) {
5099
5242
  });
5100
5243
  }
5101
5244
  /**
5102
- * Close the next-action item and the merge conflict notice of a pull request
5103
- * that merged or closed. The outcome write calls this before it marks the
5104
- * chips, so no reader sees an ended pull request next to its open item. The
5105
- * items are optional, so a failure is logged. In a webhook, the next-action
5106
- * sync after it closes the item again.
5245
+ * Return the closes of the next-action item and the merge conflict notice
5246
+ * of a pull request that merged or closed, with the conversation that owns
5247
+ * them. Undefined when no person asked Junior for the pull request. The
5248
+ * outcome write saves them in one batch with that conversation's chip, so no
5249
+ * reader sees an ended pull request next to its open item.
5107
5250
  */
5108
- async function closeEndedGitHubPullRequestItems(args) {
5251
+ async function endedGitHubPullRequestItemChanges(args) {
5109
5252
  const { target } = args;
5110
- try {
5111
- const opener = (await listGitHubPullRequestOpeners(args.db, {
5112
- numbers: [target.number],
5113
- repositoryFullName: target.repositoryFullName
5114
- })).get(target.number);
5115
- if (!opener?.conversationId) return;
5116
- const items = args.inboxItems.forConversation(opener.conversationId);
5117
- const reason = ENDED_REASONS[args.state];
5118
- await Promise.all([items.close({
5119
- dedupeKey: actionDedupeKey(target),
5120
- ...reason
5121
- }), items.close({
5122
- dedupeKey: gitHubConflictItemKey(target),
5123
- ...reason
5124
- })]);
5125
- } catch (error) {
5126
- logFailOpenFailure(args.log, "GitHub ended pull request item close failed", error, {
5127
- number: target.number,
5128
- repository: target.repositoryFullName
5129
- });
5130
- }
5253
+ const conversationId = (await listGitHubPullRequestOpeners(args.db, {
5254
+ numbers: [target.number],
5255
+ repositoryFullName: target.repositoryFullName
5256
+ })).get(target.number)?.conversationId;
5257
+ if (!conversationId) return void 0;
5258
+ const reason = ENDED_REASONS[args.state];
5259
+ return {
5260
+ conversationId,
5261
+ inboxItems: [actionDedupeKey(target), gitHubConflictItemKey(target)].map((dedupeKey) => ({
5262
+ close: {
5263
+ dedupeKey,
5264
+ ...reason
5265
+ },
5266
+ conversationId
5267
+ }))
5268
+ };
5131
5269
  }
5132
5270
  /**
5133
- * Ask for the requester's review on GitHub, so GitHub notifies them. The
5134
- * item already asks, so a failure is logged and the item stays.
5271
+ * Ask for a reviewer's review on GitHub, so GitHub notifies them, and return
5272
+ * whether GitHub took the request. The item already asks, so a failure is
5273
+ * logged and the item stays.
5135
5274
  */
5136
5275
  async function requestReviewAgain(args, target, login) {
5137
5276
  try {
@@ -5139,12 +5278,61 @@ async function requestReviewAgain(args, target, login) {
5139
5278
  ...target,
5140
5279
  reviewers: [login]
5141
5280
  });
5281
+ return true;
5142
5282
  } catch (error) {
5143
5283
  logFailOpenFailure(args.log, "GitHub review request again failed", error, {
5144
5284
  number: target.number,
5145
5285
  repository: target.repositoryFullName
5146
5286
  });
5287
+ return false;
5288
+ }
5289
+ }
5290
+ /**
5291
+ * Ask the reviewer of a held review ask again once the required checks
5292
+ * pass, and return their login and the reason. Keep the hold while the
5293
+ * checks have not passed, or while GitHub does not take the request, so a
5294
+ * later webhook asks again. Drop it when the pull request ended, when the
5295
+ * reviewer commented or reviewed since, or when their change request is no
5296
+ * longer ready.
5297
+ */
5298
+ async function askHeldReview(args, target, state) {
5299
+ const held = await readHeldGitHubReviewAsk(args.state, target);
5300
+ if (!held) return void 0;
5301
+ const heldAt = new Date(held.at);
5302
+ const botUserId = botUserIdFromEmail(args.botEmail);
5303
+ const actedSince = state.activity.some((entry) => entry.kind === "author" && sameLogin(entry.login, held.reviewer) && entry.at > heldAt);
5304
+ if (state.state !== "open" || actedSince || botUserId === void 0) {
5305
+ await dropHeldGitHubReviewAsk(args.state, target);
5306
+ return;
5307
+ }
5308
+ const [owner = "", name = ""] = target.repositoryFullName.split("/");
5309
+ const readiness = await readReviewAgainReadiness(await loadReviewAgainReader(args.env, target.repositoryFullName), {
5310
+ botUserId,
5311
+ marked: held.marked,
5312
+ name,
5313
+ number: target.number,
5314
+ owner,
5315
+ reviewer: held.reviewer
5316
+ });
5317
+ if (readiness === "checks") return void 0;
5318
+ if (readiness === "ready") {
5319
+ if (await requestReviewAgain(args, target, held.reviewer)) await dropHeldGitHubReviewAsk(args.state, target);
5320
+ return {
5321
+ reason: held.reason,
5322
+ reviewer: held.reviewer
5323
+ };
5147
5324
  }
5325
+ await dropHeldGitHubReviewAsk(args.state, target);
5326
+ }
5327
+ /**
5328
+ * Return why Junior asked the requester again, if it did: the reason of the
5329
+ * held ask that this sync released, or `handled` when the feedback tool
5330
+ * asked them and they have not acted since.
5331
+ */
5332
+ async function askReason(state, target, args) {
5333
+ if (args.asked !== void 0) return sameLogin(args.asked.reviewer, args.requesterLogin) ? args.asked.reason : void 0;
5334
+ const asked = await readGitHubReviewAsked(state, target);
5335
+ return asked && sameLogin(asked.reviewer, args.requesterLogin) && timeOf(args.requesterAt) <= Date.parse(asked.at) ? "handled" : void 0;
5148
5336
  }
5149
5337
  async function syncOne(args, target) {
5150
5338
  const opener = (await listGitHubPullRequestOpeners(args.db, {
@@ -5156,10 +5344,7 @@ async function syncOne(args, target) {
5156
5344
  const name = itemName(target);
5157
5345
  const dedupeKey = actionDedupeKey(target);
5158
5346
  const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
5159
- if (target.commentBy !== void 0 && !actor({
5160
- kind: "author",
5161
- login: target.commentBy
5162
- }, requesterLogin, args.botEmail)) return;
5347
+ if (target.commentBy !== void 0 && !sameLogin(target.commentBy, requesterLogin)) return;
5163
5348
  const claim = await claimGitHubPullRequestReadySync(args.db, target, {
5164
5349
  now: /* @__PURE__ */ new Date(),
5165
5350
  staleMs: READY_SYNC_STALE_MS
@@ -5171,29 +5356,32 @@ async function syncOne(args, target) {
5171
5356
  let failure;
5172
5357
  const check = async (previous) => {
5173
5358
  const state = await loadPullRequestMergeState(args.env, target, requesterLogin);
5174
- const activity = latestActivity(state.activity, requesterLogin, args.botEmail);
5359
+ const activity = latestActivity(state.activity, requesterLogin);
5360
+ const asked = await askHeldReview(args, target, state);
5361
+ const reason = await askReason(args.state, target, {
5362
+ asked,
5363
+ requesterAt: activity.requesterAt,
5364
+ requesterLogin
5365
+ });
5175
5366
  const next = nextAction(state, {
5176
- activity,
5177
- actedLast: timeOf(activity.requesterAt) > timeOf(activity.juniorAt),
5367
+ actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt),
5368
+ askedAgain: asked !== void 0 && reason !== void 0,
5178
5369
  login: requesterLogin
5179
5370
  }, previous);
5180
5371
  const changed = next !== void 0 && next.action !== previous;
5181
- if (changed) {
5182
- await showAction(items, {
5183
- action: next.action,
5184
- dedupeKey,
5185
- identityId: opener.identityId,
5186
- number: target.number,
5187
- previous,
5188
- reason: next.reason,
5189
- state,
5190
- titleParts: next.action ? await loadGitHubTitleParts(args.env, {
5191
- repositoryFullName: target.repositoryFullName,
5192
- title: state.title
5193
- }, args.log) : void 0
5194
- });
5195
- if (next.reason && requesterLogin && !isRequested(state, requesterLogin)) await requestReviewAgain(args, target, requesterLogin);
5196
- }
5372
+ if (changed) await showAction(items, {
5373
+ action: next.action,
5374
+ dedupeKey,
5375
+ identityId: opener.identityId,
5376
+ number: target.number,
5377
+ previous,
5378
+ reason,
5379
+ state,
5380
+ titleParts: next.action ? await loadGitHubTitleParts(args.env, {
5381
+ repositoryFullName: target.repositoryFullName,
5382
+ title: state.title
5383
+ }, args.log) : void 0
5384
+ });
5197
5385
  await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
5198
5386
  dedupeKey: gitHubConflictItemKey(target),
5199
5387
  ...endedReason(state.state) ?? {
@@ -5201,6 +5389,7 @@ async function syncOne(args, target) {
5201
5389
  status: "done"
5202
5390
  }
5203
5391
  }) : void 0]);
5392
+ if (changed && next.action === "review" && reason === "handled") await dropGitHubReviewAsked(args.state, target);
5204
5393
  if (!changed) return previous;
5205
5394
  await setGitHubPullRequestNextAction(args.db, {
5206
5395
  ...target,
@@ -5252,181 +5441,107 @@ function githubCodeChange(outcome, conversationIds) {
5252
5441
  providerId: outcome.pullRequestId,
5253
5442
  repository: {
5254
5443
  name: outcome.repositoryFullName,
5255
- providerId: outcome.repositoryId,
5256
- url: `https://github.com/${outcome.repositoryFullName}`
5444
+ providerId: outcome.repositoryId
5257
5445
  },
5258
5446
  size: outcome.size,
5259
5447
  state: outcome.state === "closed_unmerged" ? "closed" : outcome.state,
5260
5448
  title: outcome.title,
5261
- updatedAt: outcome.updatedAt,
5262
- url: `https://github.com/${outcome.repositoryFullName}/pull/${outcome.number}`
5449
+ updatedAt: outcome.updatedAt
5263
5450
  };
5264
5451
  }
5265
5452
  /**
5266
5453
  * Record one pull request outcome. When the stored row changes, update the
5267
- * code index, and mark the chip of each linked conversation merged or closed.
5268
- * A merged or closed pull request closes its Inbox items first, so no
5269
- * reader sees a merged chip next to an open item. A failed chip or item is
5270
- * logged, so it does not stop the work after it.
5454
+ * code index. A merged or closed pull request then marks the chip of the
5455
+ * conversation that asked for it and closes its Inbox items in one batch, so
5456
+ * no reader sees a merged chip next to an open item. Each other linked
5457
+ * conversation gets its chip in its own write, so a stale conversation id
5458
+ * breaks only its own chip. The chips and items are optional UI, so a
5459
+ * failed write is logged and does not stop the work after it.
5271
5460
  */
5272
5461
  async function applyGitHubPullRequestOutcome(args) {
5273
5462
  const { outcome } = args;
5463
+ const state = outcome.state === "open" ? void 0 : outcome.state === "merged" ? "merged" : "closed";
5464
+ const ended = state ? await endedGitHubPullRequestItemChanges({
5465
+ db: args.db,
5466
+ state,
5467
+ target: outcome
5468
+ }) : void 0;
5274
5469
  const recorded = await recordGitHubPullRequestOutcome(args.db, outcome);
5275
5470
  if (!recorded.applied) return recorded;
5276
5471
  await args.codeChanges.record(githubCodeChange(outcome, recorded.conversationIds));
5277
- if (outcome.state !== "open") {
5278
- const state = outcome.state === "merged" ? "merged" : "closed";
5279
- await closeEndedGitHubPullRequestItems({
5280
- db: args.db,
5281
- log: args.log,
5282
- inboxItems: args.inboxItems,
5283
- state,
5284
- target: outcome
5285
- });
5472
+ if (state) {
5473
+ const update = {
5474
+ repo: outcome.repositoryFullName,
5475
+ number: outcome.number,
5476
+ objectType: "code_change",
5477
+ status: state
5478
+ };
5479
+ if (ended) try {
5480
+ await args.conversationChanges.apply({
5481
+ annotations: recorded.conversationIds.includes(ended.conversationId) ? [await githubAnnotationChange({
5482
+ annotations: args.annotations,
5483
+ conversationId: ended.conversationId,
5484
+ update
5485
+ })] : [],
5486
+ inboxItems: ended.inboxItems
5487
+ });
5488
+ } catch (error) {
5489
+ logFailOpenFailure(args.log, "GitHub ended pull request change failed", error, {
5490
+ number: outcome.number,
5491
+ repository: outcome.repositoryFullName
5492
+ });
5493
+ }
5286
5494
  await updateGitHubAnnotations({
5287
5495
  annotations: args.annotations,
5288
- conversationIds: recorded.conversationIds,
5496
+ conversationIds: recorded.conversationIds.filter((id) => id !== ended?.conversationId),
5289
5497
  log: args.log,
5290
- update: {
5291
- repo: outcome.repositoryFullName,
5292
- number: outcome.number,
5293
- objectType: "code_change",
5294
- status: state
5295
- }
5498
+ update
5296
5499
  });
5297
5500
  }
5298
5501
  return recorded;
5299
5502
  }
5300
5503
  // src/webhooks/issue-outcome.ts
5301
- const canonicalIssueOutcomeSchema = z.object({
5302
- action: z.enum([
5303
- "opened",
5304
- "closed",
5305
- "reopened"
5306
- ]),
5504
+ const canonicalClosedIssueSchema = z.object({
5505
+ action: z.string(),
5307
5506
  issue: z.object({
5308
5507
  body: z.string().nullable().optional(),
5309
- closed_at: z.string().nullable().optional(),
5310
- created_at: z.string(),
5311
- id: z.number().int().positive(),
5312
5508
  number: z.number().int().positive(),
5313
- state_reason: githubIssueStateReasonSchema.nullable().optional(),
5314
- updated_at: z.string(),
5315
5509
  user: z.object({ login: z.string().min(1) }).strict()
5316
5510
  }).strict(),
5317
- repository: z.object({
5318
- full_name: z.string().min(1),
5319
- id: z.number().int().positive()
5320
- }).strict()
5511
+ repository: z.object({ full_name: z.string().min(1) }).strict()
5321
5512
  }).strict();
5322
- const issueOutcomeSchema = z.object({
5323
- action: z.enum([
5324
- "opened",
5325
- "closed",
5326
- "reopened"
5327
- ]),
5513
+ const closedIssueSchema = z.object({
5514
+ action: z.string(),
5328
5515
  issue: z.object({
5329
5516
  body: z.string().nullable().optional(),
5330
- closed_at: z.string().nullable().optional(),
5331
- created_at: z.string(),
5332
- id: z.number().int().positive(),
5333
5517
  number: z.number().int().positive(),
5334
- state_reason: githubIssueStateReasonSchema.nullable().optional(),
5335
- updated_at: z.string(),
5336
5518
  user: z.object({ login: z.string().min(1) }).passthrough()
5337
5519
  }).passthrough(),
5338
- repository: z.object({
5339
- full_name: z.string().min(1),
5340
- id: z.number().int().positive()
5341
- }).passthrough()
5342
- }).passthrough().transform((provider) => canonicalIssueOutcomeSchema.parse({
5520
+ repository: z.object({ full_name: z.string().min(1) }).passthrough()
5521
+ }).passthrough().transform((provider) => canonicalClosedIssueSchema.parse({
5343
5522
  action: provider.action,
5344
5523
  issue: {
5345
5524
  body: provider.issue.body,
5346
- closed_at: provider.issue.closed_at,
5347
- created_at: provider.issue.created_at,
5348
- id: provider.issue.id,
5349
5525
  number: provider.issue.number,
5350
- state_reason: provider.issue.state_reason,
5351
- updated_at: provider.issue.updated_at,
5352
5526
  user: { login: provider.issue.user.login }
5353
5527
  },
5354
- repository: {
5355
- full_name: provider.repository.full_name,
5356
- id: provider.repository.id
5357
- }
5528
+ repository: { full_name: provider.repository.full_name }
5358
5529
  }));
5359
- const issueLifecycleActionSchema = z.object({ action: z.string() }).passthrough();
5360
- /** Parse a provider timestamp, rejecting missing or invalid lifecycle values. */
5361
- function timestamp$1(value) {
5362
- if (!value) return void 0;
5363
- const parsed = new Date(value);
5364
- return Number.isFinite(parsed.getTime()) ? parsed : void 0;
5365
- }
5366
- /** Normalize only the fields required for the Junior-owned issue projection. */
5367
- function normalizeGitHubIssueOutcome(args) {
5368
- const lifecycle = issueLifecycleActionSchema.safeParse(args.body);
5369
- if (!lifecycle.success || ![
5370
- "opened",
5371
- "closed",
5372
- "reopened"
5373
- ].includes(lifecycle.data.action)) return;
5374
- const parsed = issueOutcomeSchema.parse(args.body);
5375
- const issue = parsed.issue;
5376
- const openedAt = timestamp$1(issue.created_at);
5377
- const updatedAt = timestamp$1(issue.updated_at);
5378
- if (!openedAt || !updatedAt) throw new Error("GitHub issue lifecycle timestamps are invalid");
5379
- if (parsed.action === "opened" && !botLoginFromEmail(args.botEmail)) throw new Error("The configured GitHub App bot email must encode a [bot] login in GitHub's noreply format to classify issue ownership");
5380
- const candidateOwned = Boolean(isBotLogin(issue.user.login, args.botEmail) && issue.body?.includes("<!-- junior-session-footer:start -->")) && (parsed.action === "opened" || parsed.action === "closed");
5381
- const closedAt = timestamp$1(issue.closed_at);
5382
- if (parsed.action === "closed" && !closedAt) throw new Error("GitHub issue terminal timestamp is invalid");
5383
- return {
5384
- candidateOwned,
5385
- closedAt,
5386
- issueId: String(issue.id),
5387
- number: issue.number,
5388
- openedAt,
5389
- repositoryFullName: parsed.repository.full_name,
5390
- repositoryId: String(parsed.repository.id),
5391
- state: parsed.action === "closed" ? "closed" : "open",
5392
- stateReason: parsed.action === "closed" ? issue.state_reason ?? void 0 : void 0,
5393
- updatedAt
5394
- };
5395
- }
5396
- const canonicalIssueConversationSchema = z.object({
5397
- issue: z.object({
5398
- body: z.string().nullable().optional(),
5399
- id: z.number().int().positive(),
5400
- user: z.object({ login: z.string().min(1) }).strict()
5401
- }).strict(),
5402
- sender: z.object({ login: z.string().min(1) }).strict().optional()
5403
- }).strict();
5404
- const issueConversationSchema = z.object({
5405
- issue: z.object({
5406
- body: z.string().nullable().optional(),
5407
- id: z.number().int().positive(),
5408
- user: z.object({ login: z.string().min(1) }).passthrough()
5409
- }).passthrough(),
5410
- sender: z.object({ login: z.string().min(1) }).passthrough().optional()
5411
- }).passthrough().transform((provider) => canonicalIssueConversationSchema.parse({
5412
- issue: {
5413
- body: provider.issue.body,
5414
- id: provider.issue.id,
5415
- user: { login: provider.issue.user.login }
5416
- },
5417
- ...provider.sender ? { sender: { login: provider.sender.login } } : void 0
5418
- }));
5419
- /** Normalize native conversation ids written to a Junior-owned issue by its bot. */
5420
- function normalizeGitHubIssueConversations(args) {
5421
- const parsed = issueConversationSchema.safeParse(args.body);
5422
- if (!parsed.success) return void 0;
5423
- if (!isBotLogin(parsed.data.issue.user.login, args.botEmail)) return;
5424
- const sender = parsed.data.sender;
5425
- if (sender && !isBotLogin(sender.login, args.botEmail)) return void 0;
5426
- const conversationIds = githubConversationIds(parsed.data.issue.body);
5530
+ /**
5531
+ * Read a closed Junior issue from an `issues` webhook: the issue, and the
5532
+ * Conversations that its bot-written footer names. Undefined for any other
5533
+ * action or issue.
5534
+ */
5535
+ function normalizeGitHubClosedIssue(args) {
5536
+ const parsed = closedIssueSchema.safeParse(args.body);
5537
+ if (!parsed.success || parsed.data.action !== "closed") return void 0;
5538
+ const { issue, repository } = parsed.data;
5539
+ if (!isBotLogin(issue.user.login, args.botEmail)) return void 0;
5540
+ const conversationIds = githubConversationIds(issue.body);
5427
5541
  return conversationIds.length > 0 ? {
5428
5542
  conversationIds,
5429
- issueId: String(parsed.data.issue.id)
5543
+ number: issue.number,
5544
+ repositoryFullName: repository.full_name
5430
5545
  } : void 0;
5431
5546
  }
5432
5547
  // src/webhooks/pull-request-outcome.ts
@@ -5591,17 +5706,6 @@ function normalizeGitHubPullRequestConversations(args) {
5591
5706
  pullRequestId: String(parsed.data.pull_request.id)
5592
5707
  } : void 0;
5593
5708
  }
5594
- /** Normalize linked issues written into a Junior-owned PR body by its bot. */
5595
- function normalizeGitHubPullRequestLinkedIssues(args) {
5596
- const parsed = pullRequestConversationSchema.safeParse(args.body);
5597
- if (!parsed.success) return void 0;
5598
- if (!isBotLogin(parsed.data.pull_request.user.login, args.botEmail) || !isBotLogin(parsed.data.sender.login, args.botEmail)) return;
5599
- const linkedIssues = githubLinkedIssues(parsed.data.pull_request.body, parsed.data.repository.full_name);
5600
- return linkedIssues.length > 0 ? {
5601
- linkedIssues,
5602
- pullRequestId: String(parsed.data.pull_request.id)
5603
- } : void 0;
5604
- }
5605
5709
  // src/webhooks/pull-request-activity.ts
5606
5710
  const timestampSchema = z.iso.datetime({ offset: true });
5607
5711
  const numberSchema = z.number().int().positive();
@@ -5961,7 +6065,10 @@ async function requestGitHubReviewersWhenReady(args) {
5961
6065
  if (!opener?.conversationId) return;
5962
6066
  const named = await readGitHubDraftReviewers(args.state, target);
5963
6067
  const requester = named ? void 0 : await args.loadGitHubLogin?.(opener.identityId);
5964
- const reviewers = named ?? (requester ? [requester] : []);
6068
+ const candidates = named ?? (requester ? [requester] : []);
6069
+ if (candidates.length === 0) return;
6070
+ const { reviewedBy } = await loadPullRequestMergeState(args.env, target, void 0);
6071
+ const reviewers = candidates.filter((login) => !reviewedBy.includes(login.toLowerCase()));
5965
6072
  if (reviewers.length === 0) return;
5966
6073
  await requestPullRequestReviewers(args.env, {
5967
6074
  ...target,
@@ -6371,11 +6478,7 @@ function createGitHubWebhookRoute(args) {
6371
6478
  body,
6372
6479
  botEmail
6373
6480
  }) : void 0;
6374
- const issueOutcome = eventName === "issues" ? normalizeGitHubIssueOutcome({
6375
- body,
6376
- botEmail
6377
- }) : void 0;
6378
- const issueConversations = eventName === "issues" ? normalizeGitHubIssueConversations({
6481
+ const closedIssue = eventName === "issues" ? normalizeGitHubClosedIssue({
6379
6482
  body,
6380
6483
  botEmail
6381
6484
  }) : void 0;
@@ -6383,18 +6486,14 @@ function createGitHubWebhookRoute(args) {
6383
6486
  body,
6384
6487
  botEmail
6385
6488
  }) : void 0;
6386
- const pullRequestLinkedIssues = eventName === "pull_request" ? normalizeGitHubPullRequestLinkedIssues({
6387
- body,
6388
- botEmail
6389
- }) : void 0;
6390
6489
  if (pullRequestOutcome) {
6391
6490
  const recordedOutcome = await applyGitHubPullRequestOutcome({
6392
6491
  annotations: args.annotations,
6393
6492
  codeChanges: args.codeChanges,
6493
+ conversationChanges: args.conversationChanges,
6394
6494
  db: args.db,
6395
6495
  log: args.log,
6396
- outcome: pullRequestOutcome,
6397
- inboxItems: args.inboxItems
6496
+ outcome: pullRequestOutcome
6398
6497
  });
6399
6498
  if (recordedOutcome.applied && !recordedOutcome.commitComposition && pullRequestOutcome.state === "merged" && args.classifyPullRequestCommits) {
6400
6499
  let commitComposition;
@@ -6417,21 +6516,18 @@ function createGitHubWebhookRoute(args) {
6417
6516
  });
6418
6517
  }
6419
6518
  }
6420
- if (issueOutcome) {
6421
- const recordedOutcome = await recordGitHubIssueOutcome(args.db, issueOutcome);
6422
- if (recordedOutcome.applied && issueOutcome.state === "closed") await updateGitHubAnnotations({
6423
- annotations: args.annotations,
6424
- conversationIds: recordedOutcome.conversationIds,
6425
- log: args.log,
6426
- update: {
6427
- repo: issueOutcome.repositoryFullName,
6428
- number: issueOutcome.number,
6429
- objectType: "task",
6430
- status: "closed"
6431
- }
6432
- });
6433
- }
6434
- const recordedIssueConversations = issueConversations ? await recordGitHubIssueConversations(args.db, issueConversations) : false;
6519
+ if (closedIssue) await updateGitHubAnnotations({
6520
+ annotations: args.annotations,
6521
+ conversationIds: closedIssue.conversationIds,
6522
+ existingOnly: true,
6523
+ log: args.log,
6524
+ update: {
6525
+ repo: closedIssue.repositoryFullName,
6526
+ number: closedIssue.number,
6527
+ objectType: "task",
6528
+ status: "closed"
6529
+ }
6530
+ });
6435
6531
  const recordedPullRequestConversations = pullRequestConversations ? await recordGitHubPullRequestConversations(args.db, pullRequestConversations) : false;
6436
6532
  if (recordedPullRequestConversations && pullRequestConversations) await args.codeChanges.associateConversations({
6437
6533
  conversationIds: pullRequestConversations.conversationIds,
@@ -6448,7 +6544,6 @@ function createGitHubWebhookRoute(args) {
6448
6544
  eventName
6449
6545
  });
6450
6546
  if (pullRequestActivity) await args.codeChanges.recordActivity(pullRequestActivity);
6451
- const recordedPullRequestLinkedIssues = pullRequestLinkedIssues ? await recordGitHubPullRequestLinkedIssues(args.db, pullRequestLinkedIssues) : false;
6452
6547
  const checkSuitePublishTargets = eventName === "check_suite" ? parseCheckSuitePublishTargets(body) : void 0;
6453
6548
  const checkSuiteMatchKeys = checkSuitePublishTargets && args.events.neededMatchKeys ? await args.events.neededMatchKeys(checkSuitePublishTargets) : [];
6454
6549
  const checkSuiteFacts = eventName === "check_suite" ? await loadCheckSuiteFacts({
@@ -6543,6 +6638,7 @@ function createGitHubWebhookRoute(args) {
6543
6638
  loadGitHubLogin: args.loadGitHubLogin,
6544
6639
  log: args.log,
6545
6640
  inboxItems: args.inboxItems,
6641
+ state: args.state,
6546
6642
  targets: pullRequestActionTargets(eventName, body)
6547
6643
  });
6548
6644
  await requestGitHubReviewersWhenReady({
@@ -6555,7 +6651,7 @@ function createGitHubWebhookRoute(args) {
6555
6651
  log: args.log,
6556
6652
  state: args.state
6557
6653
  });
6558
- if (!pullRequestOutcome && !issueOutcome && !recordedIssueConversations && !recordedPullRequestConversations && !recordedPullRequestLinkedIssues && events.length === 0) return new Response("Ignored", { status: 202 });
6654
+ if (!pullRequestOutcome && !closedIssue && !recordedPullRequestConversations && events.length === 0) return new Response("Ignored", { status: 202 });
6559
6655
  return new Response("Accepted", { status: 202 });
6560
6656
  }
6561
6657
  };
@@ -6670,7 +6766,7 @@ async function runCheck(args, check) {
6670
6766
  attempts: check.attempts,
6671
6767
  errorType: error instanceof Error ? error.name : "UnknownError",
6672
6768
  repository: check.repositoryFullName
6673
- });
6769
+ }, error);
6674
6770
  if (check.attempts >= MAX_ATTEMPTS) await settleGitHubConflictCheck(args.state, check);
6675
6771
  return;
6676
6772
  }
@@ -6893,10 +6989,10 @@ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullReq
6893
6989
  await applyGitHubPullRequestOutcome({
6894
6990
  annotations: args.annotations,
6895
6991
  codeChanges: args.codeChanges,
6992
+ conversationChanges: args.conversationChanges,
6896
6993
  db: args.db,
6897
6994
  log: args.log,
6898
- outcome,
6899
- inboxItems: args.inboxItems
6995
+ outcome
6900
6996
  });
6901
6997
  }
6902
6998
  /**
@@ -6928,7 +7024,7 @@ async function reconcileGitHubPullRequests(args) {
6928
7024
  else args.log.error("GitHub pull request reconcile failed", {
6929
7025
  errorType: error instanceof Error ? error.name : "UnknownError",
6930
7026
  repository: repositoryFullName
6931
- });
7027
+ }, error);
6932
7028
  }
6933
7029
  }
6934
7030
  }
@@ -8560,6 +8656,10 @@ function githubPlugin(options = {}) {
8560
8656
  const userScope = userScopes.length ? userScopes.join(" ") : void 0;
8561
8657
  return defineJuniorPlugin({
8562
8658
  packageName: "@sentry/junior-github",
8659
+ codeLinks: {
8660
+ change: ({ number, repository }) => `https://github.com/${repository}/pull/${number}`,
8661
+ repository: (name) => `https://github.com/${name}`
8662
+ },
8563
8663
  images: githubImageSource,
8564
8664
  objectLinks: [
8565
8665
  githubAccountLinks,
@@ -8758,6 +8858,7 @@ function githubPlugin(options = {}) {
8758
8858
  annotations: ctx.annotations,
8759
8859
  botEmail: readEnv(botEmailEnv),
8760
8860
  codeChanges: ctx.codeChanges,
8861
+ conversationChanges: ctx.conversationChanges,
8761
8862
  db,
8762
8863
  events: ctx.events,
8763
8864
  loadCommitPages: async (target) => await loadPullRequestCommitPages(installationEnv, target),
@@ -8799,6 +8900,7 @@ function githubPlugin(options = {}) {
8799
8900
  loadPage: await loadPullRequestCommitPages(installationEnv, pullRequest)
8800
8901
  }),
8801
8902
  codeChanges: ctx.codeChanges,
8903
+ conversationChanges: ctx.conversationChanges,
8802
8904
  db: gitHubDbSchema.parse(ctx.db),
8803
8905
  installationId: () => readEnv(installationIdEnv),
8804
8906
  loadGitHubIncidents: async () => await loadGitHubStatusIncidents(ctx.cache, CHECK_SUITE_INCIDENT_WINDOW_MS),