@sentry/junior-github 0.306.0 → 0.307.1

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.
@@ -2,6 +2,7 @@ import * as z from "zod";
2
2
  import { PluginToolInputError, eventMatchFieldsSchema, mergeEventMatchFields } from "@sentry/junior-plugin-api";
3
3
  import { lexer } from "marked";
4
4
  import { createPrivateKey, createSign } from "node:crypto";
5
+ import pLimit from "p-limit";
5
6
  // src/tool-support/github-api.ts
6
7
  const GITHUB_API_BASE = "https://api.github.com";
7
8
  const MAX_REDIRECTS = 3;
@@ -1646,6 +1647,10 @@ function logFailOpenFailure(log, message, error, metadata) {
1646
1647
  log?.error(message, attributes);
1647
1648
  }
1648
1649
  // src/webhooks/check-suite.ts
1650
+ /**
1651
+ * GitHub check suite events.
1652
+ */
1653
+ const PULL_REQUEST_LOAD_CONCURRENCY = 5;
1649
1654
  /** Match keys that need a pull request API load on check suite events. */
1650
1655
  const CHECK_SUITE_PULL_REQUEST_MATCH_KEYS = /* @__PURE__ */ new Set([
1651
1656
  "isDraft",
@@ -2106,7 +2111,8 @@ async function loadCheckSuiteFacts(args) {
2106
2111
  privateKeyEnv: args.privateKeyEnv,
2107
2112
  repositories: [target.repoName]
2108
2113
  });
2109
- const loaded = await Promise.all(target.pullRequestNumbers.map(async (number) => {
2114
+ const limit = pLimit(PULL_REQUEST_LOAD_CONCURRENCY);
2115
+ const loaded = await Promise.all(target.pullRequestNumbers.map((number) => limit(async () => {
2110
2116
  try {
2111
2117
  const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, { token: token.token }));
2112
2118
  return loadedFacts ? [number, loadedFacts] : void 0;
@@ -2117,7 +2123,7 @@ async function loadCheckSuiteFacts(args) {
2117
2123
  });
2118
2124
  return;
2119
2125
  }
2120
- }));
2126
+ })));
2121
2127
  const pullRequestFactsByNumber = {};
2122
2128
  for (const entry of loaded) {
2123
2129
  if (!entry) continue;
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 githubRequest, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubRepositoryFromUrl, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as logFailOpenFailure, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as definedValues, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as pullRequestTargets, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as isRecord, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-VdBpoUV7.js";
1
+ import { $ as GITHUB_DEPLOYMENT_EVENTS, A as requireEnv, B as GITHUB_RELEASE_MATCH_FIELDS, C as githubRequest, Ct as githubErrorMessage$1, D as listVerifiedUserEmails, E as issueInstallationToken, F as GITHUB_REPOSITORY_EVENTS, G as GITHUB_PULL_REQUEST_IDENTIFIER, H as GITHUB_RELEASE_SUGGESTED_EVENTS, I as GITHUB_REPOSITORY_IDENTIFIER, J as gitHubPullRequestCreateWatch, K as GITHUB_PULL_REQUEST_MATCH_FIELDS, L as GITHUB_REPOSITORY_SUGGESTED_EVENTS, M as botLoginFromEmail, N as botUserIdFromEmail, O as normalizeScopeList, P as isBotLogin, Q as gitHubPullRequestSubscription, R as gitHubRepositorySubscribable, S as githubRepositoryFromUrl, St as githubAttachmentLocation, T as issueGitHubCredential, Tt as repoPath, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, _t as readGitHubBody, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, bt as startedByPerson, c as logFailOpenFailure, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as normalizePermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, ft as readGrantPermissions, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, gt as parseGitHubLogin, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, ht as linkedGitHubLogin, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as definedValues, lt as watchGitHubIssue, m as GITHUB_AUTH_TOKEN_ENV, mt as assertGitHubPullRequestRequester, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, pt as appendGitHubRequesterAttribution, q as GITHUB_PULL_REQUEST_SUGGESTED_EVENTS, r as checkSuitePullRequests, rt as gitHubDeploymentSourceSubscribable, s as wantsCheckSuitePassed, st as GITHUB_ISSUE_SUGGESTED_EVENTS, t as gitHubPullRequestTerminalEvents, tt as GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER, u as pullRequestTargets, ut as gitHubRepoDataSchema, v as GitHubRequestError, vt as requesterPerson, w as isRecord, wt as parseRepo$1, x as createPermissionCache, xt as githubApi, y as HTTP_READ_METHODS, yt as resolveGitHubRequester, z as GITHUB_RELEASE_EVENTS } from "./events-CAZiit9g.js";
2
2
  import * as z from "zod";
3
3
  import { EgressAuthRequired, EgressPolicyDenied, OBJECT_FACTS_MAX_BYTES, PluginToolInputError, decodeObjectImageRef, defineJuniorPlugin, definePluginTool, enforceEgressPolicy, mergeEventMatchFields, objectFactsBytes, objectFactsMatchType, objectFactsSchema, parseShellCommands, pluginToolOutputSchema, subscribableResourceSchema, watchResultSchema } from "@sentry/junior-plugin-api";
4
4
  import { lexer, walkTokens } from "marked";
@@ -10,6 +10,7 @@ import { boolean, index, integer, pgTable, primaryKey, text, timestamp as timest
10
10
  import ignore from "ignore";
11
11
  import { Kind, parse, print, visit } from "@0no-co/graphql.web";
12
12
  import { createHmac, timingSafeEqual } from "node:crypto";
13
+ import pLimit from "p-limit";
13
14
  import { fromMarkdown } from "mdast-util-from-markdown";
14
15
  import { gfmFromMarkdown } from "mdast-util-gfm";
15
16
  import { gfm } from "micromark-extension-gfm";
@@ -215,7 +216,7 @@ function htmlImageSources(html) {
215
216
  const src = node.attrs.find((attr) => attr.name === "src")?.value;
216
217
  if (src) sources.push(src);
217
218
  }
218
- if ("childNodes" in node) node.childNodes.forEach(visit);
219
+ if ("childNodes" in node) for (const child of node.childNodes) visit(child);
219
220
  if ("content" in node) visit(node.content);
220
221
  };
221
222
  visit(parseFragment(html));
@@ -1055,7 +1056,7 @@ const gitHubIssueTool = definePluginTool({
1055
1056
  const parsedInput = parseCreateIssueInput(input);
1056
1057
  const conversationId = nonEmptyString$3(ctx.conversationId, "conversationId");
1057
1058
  const key = `createIssue:${conversationId}:${nonEmptyString$3(options?.toolCallId, "toolCallId")}`;
1058
- return await ctx.state.withLock(`${key}:lock`, GITHUB_ISSUE_CREATE_LOCK_TTL_MS, async () => {
1059
+ const attempt = await ctx.state.withLock(`${key}:lock`, GITHUB_ISSUE_CREATE_LOCK_TTL_MS, async () => {
1059
1060
  const state = createIssueState(await ctx.state.get(key));
1060
1061
  if (state?.status === "completed") return await gitHubIssueToolResult(ctx, state.input ?? parsedInput, {
1061
1062
  facts: state.facts === void 0 ? void 0 : objectFactsSchema.parse(state.facts),
@@ -1089,6 +1090,8 @@ const gitHubIssueTool = definePluginTool({
1089
1090
  throw error;
1090
1091
  }
1091
1092
  });
1093
+ if (!attempt.acquired) throw new Error("GitHub issue creation for this tool call is already running; refusing to create a duplicate issue.");
1094
+ return attempt.value;
1092
1095
  }
1093
1096
  });
1094
1097
  // src/tools/get-deployment.ts
@@ -1938,7 +1941,7 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
1938
1941
  namedReviewers(parsedInput);
1939
1942
  const conversationId = nonEmptyString$2(ctx.conversationId, "conversationId");
1940
1943
  const key = `createPullRequest:${conversationId}:${nonEmptyString$2(options?.toolCallId, "toolCallId")}`;
1941
- return await ctx.state.withLock(`${key}:lock`, GITHUB_PULL_REQUEST_CREATE_LOCK_TTL_MS, async () => {
1944
+ const attempt = await ctx.state.withLock(`${key}:lock`, GITHUB_PULL_REQUEST_CREATE_LOCK_TTL_MS, async () => {
1942
1945
  const state = createPullRequestState(await ctx.state.get(key));
1943
1946
  if (state?.status === "completed") {
1944
1947
  const completedInput = state.input ?? parsedInput;
@@ -1999,6 +2002,8 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
1999
2002
  const stack = stackTarget ? await stackGitHubPullRequest(ctx, stackTarget) : void 0;
2000
2003
  return await gitHubPullRequestStructuredResult(ctx, parsedInput, result, subscriptionConfig, stack);
2001
2004
  });
2005
+ if (!attempt.acquired) throw new Error("GitHub pull request creation for this tool call is already running; refusing to create a duplicate pull request.");
2006
+ return attempt.value;
2002
2007
  }
2003
2008
  });
2004
2009
  }
@@ -3331,11 +3336,8 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3331
3336
  const listPayload = listResponse.body;
3332
3337
  if (failed(listResponse)) throw new Error(`GitHub reaction lookup failed with HTTP ${listResponse.status}: ${githubErrorMessage$1(listPayload)}`);
3333
3338
  const botReactions = reactions.botReactions(listPayload).filter((reaction) => FEEDBACK_REACTION_CONTENTS.has(reaction.content));
3334
- for (const stale of botReactions) {
3335
- if (stale.content === targetContent) continue;
3336
- const deleteResponse = await reactions.remove(stale);
3337
- if (failed(deleteResponse) && deleteResponse.status !== 404) throw new Error(`GitHub reaction removal failed with HTTP ${deleteResponse.status}: ${githubErrorMessage$1(deleteResponse.body)}`);
3338
- }
3339
+ const deleteResponses = await Promise.all(botReactions.filter((stale) => stale.content !== targetContent).map((stale) => reactions.remove(stale)));
3340
+ for (const deleteResponse of deleteResponses) if (failed(deleteResponse) && deleteResponse.status !== 404) throw new Error(`GitHub reaction removal failed with HTTP ${deleteResponse.status}: ${githubErrorMessage$1(deleteResponse.body)}`);
3339
3341
  if (!botReactions.some((reaction) => reaction.content === targetContent)) {
3340
3342
  const createResponse = await reactions.add(targetContent);
3341
3343
  const createPayload = createResponse.body;
@@ -4266,6 +4268,7 @@ function normalizeGitHubPullRequestActivity(input) {
4266
4268
  return senderType === "Bot" ? void 0 : activity;
4267
4269
  }
4268
4270
  // src/webhooks/pull-request-preview.ts
4271
+ const ANNOTATION_UPDATE_CONCURRENCY = 8;
4269
4272
  const previewWebhookSchema = z.object({
4270
4273
  action: z.enum([
4271
4274
  "opened",
@@ -4294,7 +4297,8 @@ async function refreshGitHubPullRequestPreview(args) {
4294
4297
  const key = `${repository.full_name.toLowerCase()}#${pullRequest.number}`;
4295
4298
  const previewImageUrls = githubPreviewImageUrls(pullRequest.body);
4296
4299
  const updatedAt = Date.parse(pullRequest.updated_at);
4297
- const results = await Promise.allSettled(conversationIds.map(async (conversationId) => {
4300
+ const limit = pLimit(ANNOTATION_UPDATE_CONCURRENCY);
4301
+ const results = await Promise.allSettled(conversationIds.map((conversationId) => limit(async () => {
4298
4302
  const store = args.annotations.forConversation(conversationId);
4299
4303
  const current = (await store.list()).find((annotation) => annotation.key === key);
4300
4304
  if (current?.kind !== "object" || current.facts?.type !== "code_change") return;
@@ -4308,7 +4312,7 @@ async function refreshGitHubPullRequestPreview(args) {
4308
4312
  facts: next,
4309
4313
  sourceUpdatedAt: pullRequest.updated_at
4310
4314
  });
4311
- }));
4315
+ })));
4312
4316
  for (const result of results) {
4313
4317
  if (result.status === "fulfilled") continue;
4314
4318
  args.log?.error("GitHub pull request preview update failed", {
@@ -4319,6 +4323,7 @@ async function refreshGitHubPullRequestPreview(args) {
4319
4323
  }
4320
4324
  }
4321
4325
  // src/merge-conflict-checks/policy.ts
4326
+ const NOTICE_CLOSE_CONCURRENCY = 8;
4322
4327
  const DAY_MS = 864e5;
4323
4328
  /** Time after activity by a person in which Junior fixes conflicts. */
4324
4329
  const ACTIVE_MS = 2 * DAY_MS;
@@ -4491,10 +4496,10 @@ async function closeGitHubConflictNotices(args) {
4491
4496
  numbers: args.numbers,
4492
4497
  repositoryFullName
4493
4498
  });
4494
- for (const [number, opener] of openers) {
4495
- if (!opener.conversationId) continue;
4499
+ const limit = pLimit(NOTICE_CLOSE_CONCURRENCY);
4500
+ const close = async (number, conversationId) => {
4496
4501
  try {
4497
- await args.reviewItems.forConversation(opener.conversationId).close({
4502
+ await args.reviewItems.forConversation(conversationId).close({
4498
4503
  dedupeKey: gitHubConflictNoticeKey({
4499
4504
  number,
4500
4505
  repositoryFullName
@@ -4508,9 +4513,11 @@ async function closeGitHubConflictNotices(args) {
4508
4513
  repository: repositoryFullName
4509
4514
  });
4510
4515
  }
4511
- }
4516
+ };
4517
+ await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
4512
4518
  }
4513
4519
  // src/webhooks/merge-conflict.ts
4520
+ const PULL_REQUEST_CHECK_CONCURRENCY = 5;
4514
4521
  const EVENT_TYPE = "pull_request.merge_conflict";
4515
4522
  /** Events after which the pull request cannot get a conflict. */
4516
4523
  const CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set(["pull_request.closed_unmerged", "pull_request.merged"]);
@@ -4587,18 +4594,17 @@ function deliveredPullRequest(payload, ref) {
4587
4594
  async function loadGitHubMergeConflictEvents(args) {
4588
4595
  const { hasMatch, loadConflictHistory, loadPullRequest } = args;
4589
4596
  if (!hasMatch || !loadPullRequest || !loadConflictHistory) return [];
4590
- const conflicts = [];
4591
- for (const ref of pullRequestRefs(args.events)) {
4592
- if (!await hasMatch(gitHubMergeConflictEvents(ref))) continue;
4597
+ const check = async (ref) => {
4598
+ if (!await hasMatch(gitHubMergeConflictEvents(ref))) return [];
4593
4599
  try {
4594
4600
  const loaded = deliveredPullRequest(args.pullRequestPayload, ref) ?? pullRequestSchema$1.parse(await loadPullRequest(ref));
4595
- if (loaded.state !== "open" || loaded.mergeable !== false || loaded.mergeable_state !== "dirty") continue;
4601
+ if (loaded.state !== "open" || loaded.mergeable !== false || loaded.mergeable_state !== "dirty") return [];
4596
4602
  const conflict = {
4597
4603
  baseBranch: loaded.base.ref,
4598
4604
  headSha: loaded.head.sha,
4599
4605
  ...loaded.html_url ? { url: loaded.html_url } : void 0
4600
4606
  };
4601
- conflicts.push(...await applyGitHubConflictPolicy({
4607
+ return await applyGitHubConflictPolicy({
4602
4608
  conflict,
4603
4609
  db: args.db,
4604
4610
  draft: loaded.draft === true,
@@ -4612,16 +4618,18 @@ async function loadGitHubMergeConflictEvents(args) {
4612
4618
  ref,
4613
4619
  reviewItems: args.reviewItems,
4614
4620
  ...loaded.title ? { title: loaded.title } : void 0
4615
- }));
4621
+ });
4616
4622
  } catch (error) {
4617
4623
  logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
4618
4624
  deliveryId: args.deliveryId,
4619
4625
  pullRequest: ref.number,
4620
4626
  repository: ref.repositoryFullName
4621
4627
  });
4628
+ return [];
4622
4629
  }
4623
- }
4624
- return conflicts;
4630
+ };
4631
+ const limit = pLimit(PULL_REQUEST_CHECK_CONCURRENCY);
4632
+ return (await Promise.all(pullRequestRefs(args.events).map((ref) => limit(() => check(ref))))).flat();
4625
4633
  }
4626
4634
  // src/merge-conflict-checks/store.ts
4627
4635
  /** A key that waits longer than this was lost and expires. */
@@ -4970,6 +4978,7 @@ async function loadPullRequestMergeState(env, pullRequest) {
4970
4978
  return state;
4971
4979
  }
4972
4980
  // src/webhooks/pull-request-action.ts
4981
+ const PULL_REQUEST_SYNC_CONCURRENCY = 5;
4973
4982
  /**
4974
4983
  * A check normally takes a few seconds. After this time, a check that
4975
4984
  * stopped without its release no longer blocks new checks.
@@ -4997,11 +5006,11 @@ const ACTION_EVENTS = {
4997
5006
  */
4998
5007
  const LEGACY_DEDUPE_PREFIXES = ["pull-request-ready:", "pull-request-review-requested:"];
4999
5008
  async function closeLegacyItems(items, name) {
5000
- for (const prefix of LEGACY_DEDUPE_PREFIXES) await items.close({
5009
+ await Promise.all(LEGACY_DEDUPE_PREFIXES.map((prefix) => items.close({
5001
5010
  dedupeKey: `${prefix}${name}`,
5002
5011
  reason: "One item now shows the next action.",
5003
5012
  status: "dismissed"
5004
- });
5013
+ })));
5005
5014
  }
5006
5015
  const pullRequestWebhookSchema = z.object({
5007
5016
  action: z.string(),
@@ -5064,7 +5073,7 @@ async function showAction(items, args) {
5064
5073
  const { action, number, state } = args;
5065
5074
  if (action) await items.upsert({
5066
5075
  assigneeIdentityIds: [args.identityId],
5067
- body: action === "merge" ? `**${state.title}** (#${number}) is approved, and GitHub says that it can merge: ${state.url}` : `GitHub asks you to review **${state.title}** (#${number}): ${state.url}`,
5076
+ body: action === "merge" ? `#${number} is approved, and GitHub says that it can merge.\n\n${state.url}` : `GitHub asks you to review #${number}.\n\n${state.url}`,
5068
5077
  dedupeKey: args.dedupeKey,
5069
5078
  subject: {
5070
5079
  id: state.url,
@@ -5098,34 +5107,35 @@ async function syncOne(args, target) {
5098
5107
  let saved = claim.action;
5099
5108
  let requests = claim.requests;
5100
5109
  let failure;
5110
+ const check = async (previous) => {
5111
+ const state = await loadPullRequestMergeState(args.env, target);
5112
+ const next = nextAction(state, requesterLogin, previous);
5113
+ const changed = next !== void 0 && next.action !== previous;
5114
+ if (changed) await showAction(items, {
5115
+ action: next.action,
5116
+ dedupeKey,
5117
+ identityId: opener.identityId,
5118
+ number: target.number,
5119
+ previous,
5120
+ state
5121
+ });
5122
+ await Promise.all([closeLegacyItems(items, name), state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty" ? items.close({
5123
+ dedupeKey: gitHubConflictNoticeKey(target),
5124
+ ...endedReason(state) ?? {
5125
+ reason: "The pull request no longer has merge conflicts.",
5126
+ status: "done"
5127
+ }
5128
+ }) : void 0]);
5129
+ if (!changed) return previous;
5130
+ await setGitHubPullRequestNextAction(args.db, {
5131
+ ...target,
5132
+ action: next.action
5133
+ });
5134
+ return next.action;
5135
+ };
5101
5136
  while (requests !== void 0) {
5102
5137
  try {
5103
- const state = await loadPullRequestMergeState(args.env, target);
5104
- const next = nextAction(state, requesterLogin, saved);
5105
- const changed = next !== void 0 && next.action !== saved;
5106
- if (changed) await showAction(items, {
5107
- action: next.action,
5108
- dedupeKey,
5109
- identityId: opener.identityId,
5110
- number: target.number,
5111
- previous: saved,
5112
- state
5113
- });
5114
- await closeLegacyItems(items, name);
5115
- if (state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty") await items.close({
5116
- dedupeKey: gitHubConflictNoticeKey(target),
5117
- ...endedReason(state) ?? {
5118
- reason: "The pull request no longer has merge conflicts.",
5119
- status: "done"
5120
- }
5121
- });
5122
- if (changed) {
5123
- await setGitHubPullRequestNextAction(args.db, {
5124
- ...target,
5125
- action: next.action
5126
- });
5127
- saved = next.action;
5128
- }
5138
+ saved = await check(saved);
5129
5139
  } catch (error) {
5130
5140
  failure ??= error;
5131
5141
  }
@@ -5142,15 +5152,18 @@ async function syncOne(args, target) {
5142
5152
  * and does not fail the delivery.
5143
5153
  */
5144
5154
  async function syncGitHubPullRequestActions(args) {
5145
- for (const target of args.targets) try {
5146
- await syncOne(args, target);
5147
- } catch (error) {
5148
- logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
5149
- deliveryId: args.deliveryId,
5150
- number: target.number,
5151
- repository: target.repositoryFullName
5152
- });
5153
- }
5155
+ const limit = pLimit(PULL_REQUEST_SYNC_CONCURRENCY);
5156
+ await Promise.all(args.targets.map((target) => limit(async () => {
5157
+ try {
5158
+ await syncOne(args, target);
5159
+ } catch (error) {
5160
+ logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
5161
+ deliveryId: args.deliveryId,
5162
+ number: target.number,
5163
+ repository: target.repositoryFullName
5164
+ });
5165
+ }
5166
+ })));
5154
5167
  }
5155
5168
  // src/webhooks/pull-request-ready-reviewers.ts
5156
5169
  const readyForReviewSchema = z.object({
@@ -5195,6 +5208,7 @@ async function requestGitHubReviewersWhenReady(args) {
5195
5208
  }
5196
5209
  }
5197
5210
  // src/webhooks/pull-request-match-data.ts
5211
+ const LOGIN_LOAD_CONCURRENCY = 5;
5198
5212
  /** The lookups that each match key needs. */
5199
5213
  const LOOKUPS_BY_MATCH_KEY = {
5200
5214
  authors: ["authors"],
@@ -5263,11 +5277,14 @@ async function withJuniorOpeners(context, events) {
5263
5277
  repositoryFullName: context.repositoryFullName
5264
5278
  });
5265
5279
  const logins = /* @__PURE__ */ new Map();
5266
- for (const identityId of new Set([...openers.values()].map((opener) => opener.identityId))) try {
5267
- logins.set(identityId, await context.loadGitHubLogin?.(identityId));
5268
- } catch (error) {
5269
- logFailure(context, "opener", error);
5270
- }
5280
+ const limit = pLimit(LOGIN_LOAD_CONCURRENCY);
5281
+ await Promise.all([...new Set([...openers.values()].map((opener) => opener.identityId))].map((identityId) => limit(async () => {
5282
+ try {
5283
+ logins.set(identityId, await context.loadGitHubLogin?.(identityId));
5284
+ } catch (error) {
5285
+ logFailure(context, "opener", error);
5286
+ }
5287
+ })));
5271
5288
  return events.map((event) => {
5272
5289
  const number = botNumber(event);
5273
5290
  if (number === void 0) return event;
@@ -5446,10 +5463,10 @@ async function loadGitHubPullRequestPeople(args) {
5446
5463
  const email = value.toLowerCase();
5447
5464
  if (!people.has(`email:${email}`)) people.set(`email:${email}`, { email });
5448
5465
  };
5449
- args.logins.forEach(addLogin);
5466
+ for (const login of args.logins) addLogin(login);
5450
5467
  await forEachCommit(args.loadPage, (commit) => {
5451
5468
  if (commit.login) addLogin(commit.login);
5452
- commit.coAuthorEmails.forEach(addEmail);
5469
+ for (const email of commit.coAuthorEmails) addEmail(email);
5453
5470
  });
5454
5471
  return [...people.values()].slice(0, MAX_PEOPLE);
5455
5472
  }
@@ -5467,7 +5484,7 @@ async function loadGitHubPullRequestAuthors(args) {
5467
5484
  };
5468
5485
  await forEachCommit(args.loadPage, (commit) => {
5469
5486
  add(commit.login);
5470
- commit.coAuthorEmails.forEach((email) => add(noreplyLogin(email)));
5487
+ for (const email of commit.coAuthorEmails) add(noreplyLogin(email));
5471
5488
  });
5472
5489
  return [...authors.values()].slice(0, MAX_PEOPLE);
5473
5490
  }
@@ -5808,6 +5825,26 @@ const searchResponseSchema = z.object({ data: z.object({ search: z.object({
5808
5825
  })
5809
5826
  }) }) });
5810
5827
  /** Return whether any open pull request still has an unknown answer. */
5828
+ /** Apply the conflict policy to one pull request and publish its events. */
5829
+ async function checkConflict(args, input) {
5830
+ const events = gitHubMergeConflictEvents({
5831
+ ...input.ref,
5832
+ conflict: input.conflict
5833
+ });
5834
+ if (!await args.events.hasMatch?.(events)) return;
5835
+ for (const event of await applyGitHubConflictPolicy({
5836
+ conflict: input.conflict,
5837
+ db: args.db,
5838
+ draft: input.draft,
5839
+ events,
5840
+ loadHistory: args.loadHistory,
5841
+ log: args.log,
5842
+ now: args.now,
5843
+ ref: input.ref,
5844
+ reviewItems: args.reviewItems,
5845
+ title: input.title
5846
+ })) await args.events.publish(event);
5847
+ }
5811
5848
  async function checkRepository(args, repositoryFullName) {
5812
5849
  let unknown = false;
5813
5850
  let after;
@@ -5826,28 +5863,16 @@ async function checkRepository(args, repositoryFullName) {
5826
5863
  number: node.number,
5827
5864
  repositoryFullName
5828
5865
  };
5829
- const conflict = {
5830
- baseBranch: node.baseRefName,
5831
- headSha: node.headRefOid,
5832
- url: node.url
5833
- };
5834
- const events = gitHubMergeConflictEvents({
5835
- ...ref,
5836
- conflict
5837
- });
5838
- if (!await args.events.hasMatch?.(events)) continue;
5839
- for (const event of await applyGitHubConflictPolicy({
5840
- conflict,
5841
- db: args.db,
5866
+ await checkConflict(args, {
5867
+ conflict: {
5868
+ baseBranch: node.baseRefName,
5869
+ headSha: node.headRefOid,
5870
+ url: node.url
5871
+ },
5842
5872
  draft: node.isDraft,
5843
- events,
5844
- loadHistory: args.loadHistory,
5845
- log: args.log,
5846
- now: args.now,
5847
5873
  ref,
5848
- reviewItems: args.reviewItems,
5849
5874
  title: node.title
5850
- })) await args.events.publish(event);
5875
+ });
5851
5876
  }
5852
5877
  await closeGitHubConflictNotices({
5853
5878
  db: args.db,
@@ -5987,76 +6012,83 @@ async function reconcileRepository(args, repositoryId, drafts) {
5987
6012
  })).data.repository;
5988
6013
  for (const pullRequest of Object.values(pullRequests)) {
5989
6014
  if (!pullRequest) continue;
5990
- if (pullRequest.state === "OPEN") {
5991
- if (pullRequest.isDraft !== drafts.get(pullRequest.number)) {
5992
- await reconcileDraft(args, {
5993
- databaseId,
5994
- nameWithOwner
5995
- }, pullRequest);
5996
- continue;
5997
- }
5998
- await args.codeChanges.record(githubCodeChange({
5999
- candidateOwned: false,
6000
- draft: pullRequest.isDraft,
6001
- number: pullRequest.number,
6002
- openedAt: new Date(pullRequest.createdAt),
6003
- pullRequestId: String(pullRequest.databaseId),
6004
- repositoryFullName: nameWithOwner,
6005
- repositoryId: String(databaseId),
6006
- state: "open",
6007
- title: pullRequest.title,
6008
- updatedAt: new Date(pullRequest.updatedAt)
6009
- }, []));
6010
- continue;
6011
- }
6012
- const body = webhookBody("closed", {
6015
+ await reconcilePullRequest(args, {
6016
+ databaseId,
6017
+ nameWithOwner
6018
+ }, pullRequest, drafts);
6019
+ }
6020
+ }
6021
+ }
6022
+ /** Write the GitHub state of one stored pull request. */
6023
+ async function reconcilePullRequest(args, { databaseId, nameWithOwner }, pullRequest, drafts) {
6024
+ if (pullRequest.state === "OPEN") {
6025
+ if (pullRequest.isDraft !== drafts.get(pullRequest.number)) {
6026
+ await reconcileDraft(args, {
6013
6027
  databaseId,
6014
6028
  nameWithOwner
6015
6029
  }, pullRequest);
6016
- const outcome = normalizeGitHubPullRequestOutcome({
6017
- body,
6018
- botEmail: args.botEmail
6019
- });
6020
- if (!outcome) continue;
6021
- const events = await withGitHubPullRequestPeople({
6022
- body,
6023
- deliveryId: "reconcile",
6024
- events: gitHubPullRequestTerminalEvents(body),
6025
- hasMatch: args.events.hasMatch,
6026
- load: async (target) => await loadGitHubPullRequestPeople({
6027
- logins: target.logins,
6028
- loadPage: await args.loadCommitPages(target)
6029
- }),
6030
- log: args.log
6031
- });
6032
- for (const event of events) await args.events.publish({
6033
- ...event,
6034
- objectType: "code_change"
6035
- });
6036
- await closeGitHubConflictNotice({
6037
- db: args.db,
6038
- ref: {
6039
- number: pullRequest.number,
6040
- repositoryFullName: nameWithOwner
6041
- },
6042
- reviewItems: args.reviewItems,
6043
- ...pullRequest.merged ? {
6044
- reason: "The pull request merged.",
6045
- status: "done"
6046
- } : {
6047
- reason: "The pull request closed without merging.",
6048
- status: "dismissed"
6049
- }
6050
- });
6051
- await applyGitHubPullRequestOutcome({
6052
- annotations: args.annotations,
6053
- codeChanges: args.codeChanges,
6054
- db: args.db,
6055
- log: args.log,
6056
- outcome
6057
- });
6030
+ return;
6058
6031
  }
6032
+ await args.codeChanges.record(githubCodeChange({
6033
+ candidateOwned: false,
6034
+ draft: pullRequest.isDraft,
6035
+ number: pullRequest.number,
6036
+ openedAt: new Date(pullRequest.createdAt),
6037
+ pullRequestId: String(pullRequest.databaseId),
6038
+ repositoryFullName: nameWithOwner,
6039
+ repositoryId: String(databaseId),
6040
+ state: "open",
6041
+ title: pullRequest.title,
6042
+ updatedAt: new Date(pullRequest.updatedAt)
6043
+ }, []));
6044
+ return;
6059
6045
  }
6046
+ const body = webhookBody("closed", {
6047
+ databaseId,
6048
+ nameWithOwner
6049
+ }, pullRequest);
6050
+ const outcome = normalizeGitHubPullRequestOutcome({
6051
+ body,
6052
+ botEmail: args.botEmail
6053
+ });
6054
+ if (!outcome) return;
6055
+ const events = await withGitHubPullRequestPeople({
6056
+ body,
6057
+ deliveryId: "reconcile",
6058
+ events: gitHubPullRequestTerminalEvents(body),
6059
+ hasMatch: args.events.hasMatch,
6060
+ load: async (target) => await loadGitHubPullRequestPeople({
6061
+ logins: target.logins,
6062
+ loadPage: await args.loadCommitPages(target)
6063
+ }),
6064
+ log: args.log
6065
+ });
6066
+ for (const event of events) await args.events.publish({
6067
+ ...event,
6068
+ objectType: "code_change"
6069
+ });
6070
+ await closeGitHubConflictNotice({
6071
+ db: args.db,
6072
+ ref: {
6073
+ number: pullRequest.number,
6074
+ repositoryFullName: nameWithOwner
6075
+ },
6076
+ reviewItems: args.reviewItems,
6077
+ ...pullRequest.merged ? {
6078
+ reason: "The pull request merged.",
6079
+ status: "done"
6080
+ } : {
6081
+ reason: "The pull request closed without merging.",
6082
+ status: "dismissed"
6083
+ }
6084
+ });
6085
+ await applyGitHubPullRequestOutcome({
6086
+ annotations: args.annotations,
6087
+ codeChanges: args.codeChanges,
6088
+ db: args.db,
6089
+ log: args.log,
6090
+ outcome
6091
+ });
6060
6092
  }
6061
6093
  /**
6062
6094
  * Reconcile the next repository that has open Junior pull requests and was
@@ -6753,6 +6785,7 @@ function linkifyGitHubReferences(text, options = {}) {
6753
6785
  return result + text.slice(cursor);
6754
6786
  }
6755
6787
  // src/conversation-title-context.ts
6788
+ const REFERENCE_LOAD_CONCURRENCY = 5;
6756
6789
  const MAX_REFERENCES = 3;
6757
6790
  const TITLE_MAX_LENGTH = 160;
6758
6791
  const OWNER = String.raw`([A-Za-z0-9][A-Za-z0-9-]*)`;
@@ -6865,7 +6898,8 @@ function objectTitle(kind, object) {
6865
6898
  * References that `loadObject` cannot read are left out.
6866
6899
  */
6867
6900
  async function loadGitHubConversationTitleContext(args) {
6868
- return (await Promise.all(parseGitHubReferences(args.text, args.config).map(async (reference) => {
6901
+ const limit = pLimit(REFERENCE_LOAD_CONCURRENCY);
6902
+ return (await Promise.all(parseGitHubReferences(args.text, args.config).map((reference) => limit(async () => {
6869
6903
  try {
6870
6904
  const title = objectTitle(reference.kind, await args.loadObject(reference));
6871
6905
  if (!title) return void 0;
@@ -6877,7 +6911,7 @@ async function loadGitHubConversationTitleContext(args) {
6877
6911
  });
6878
6912
  return;
6879
6913
  }
6880
- }))).filter((line) => Boolean(line));
6914
+ })))).filter((line) => Boolean(line));
6881
6915
  }
6882
6916
  // src/workspace-prepare.ts
6883
6917
  /** Clone missing GitHub repositories or refresh existing Workspace checkouts. */
@@ -6900,160 +6934,165 @@ async function prepareWorkspace(ctx) {
6900
6934
  if (paths.has(key)) throw new Error(`Workspace checkout path collision: ${entry.path}`);
6901
6935
  paths.add(key);
6902
6936
  }
6903
- const gitEnv = {
6904
- GIT_CONFIG_GLOBAL: "/dev/null",
6905
- GIT_CONFIG_NOSYSTEM: "1"
6906
- };
6907
6937
  const finalize = [];
6908
- for (const { owner, name, path, repo } of repos) {
6909
- const parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : void 0;
6910
- if (parent) {
6911
- const mkdir = await ctx.sandbox.run({
6912
- cmd: "mkdir",
6913
- args: [
6914
- "-p",
6915
- "--",
6916
- parent
6917
- ],
6918
- cwd: ctx.sandbox.root
6919
- });
6920
- if (mkdir.exitCode !== 0) throw new Error(`GitHub workspace checkout parent failed for ${repo}: ${mkdir.stderr.trim() || `exit ${mkdir.exitCode}`}`);
6921
- }
6922
- const cloneUrl = `https://github.com/${owner}/${name}.git`;
6923
- const worktree = await ctx.sandbox.run({
6924
- cmd: "git",
6925
- args: [
6926
- "-C",
6927
- path,
6928
- "rev-parse",
6929
- "--is-inside-work-tree"
6930
- ],
6931
- cwd: ctx.sandbox.root,
6932
- env: gitEnv
6933
- });
6934
- const branch = worktree.exitCode === 0 ? await ctx.sandbox.run({
6935
- cmd: "git",
6936
- args: [
6937
- "-C",
6938
- path,
6939
- "symbolic-ref",
6940
- "--quiet",
6941
- "--short",
6942
- "HEAD"
6943
- ],
6944
- cwd: ctx.sandbox.root,
6945
- env: gitEnv
6946
- }) : void 0;
6947
- const branchName = branch?.stdout.trim();
6948
- const detachedHead = worktree.exitCode === 0 && !branchName ? await ctx.sandbox.run({
6949
- cmd: "git",
6950
- args: [
6951
- "-C",
6952
- path,
6953
- "rev-parse",
6954
- "--verify",
6955
- "HEAD^{commit}"
6956
- ],
6957
- cwd: ctx.sandbox.root,
6958
- env: gitEnv
6959
- }) : void 0;
6960
- const detachedSha = detachedHead?.stdout.trim();
6961
- const validDetachedHead = Boolean(detachedHead?.exitCode === 0 && detachedSha && /^[0-9a-f]{40,64}$/.test(detachedSha));
6962
- const upstreamRef = (branch?.exitCode === 0 && branchName ? await ctx.sandbox.run({
6963
- cmd: "git",
6964
- args: [
6965
- "-C",
6966
- path,
6967
- "rev-parse",
6968
- "--symbolic-full-name",
6969
- "@{upstream}"
6970
- ],
6971
- cwd: ctx.sandbox.root,
6972
- env: gitEnv
6973
- }) : void 0)?.stdout.trim();
6974
- const upstreamPrefix = "refs/remotes/origin/";
6975
- const upstreamBranch = upstreamRef?.startsWith(upstreamPrefix) ? upstreamRef.slice(20) : void 0;
6976
- if (worktree.exitCode === 0 && (branchName || validDetachedHead)) {
6977
- const target = upstreamBranch ? `${upstreamPrefix}${upstreamBranch}` : "HEAD";
6978
- if (upstreamBranch) {
6979
- const result = await ctx.sandbox.run({
6980
- cmd: "git",
6981
- args: [
6982
- "-c",
6983
- "credential.helper=",
6984
- "-C",
6985
- path,
6986
- "fetch",
6987
- "--quiet",
6988
- "--no-tags",
6989
- "--no-recurse-submodules",
6990
- cloneUrl,
6991
- `+refs/heads/${upstreamBranch}:${target}`
6992
- ],
6993
- cwd: ctx.sandbox.root,
6994
- env: gitEnv
6995
- });
6996
- if (result.exitCode !== 0) throw new Error(`GitHub workspace refresh failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
6997
- }
6998
- finalize.push({
6999
- path,
7000
- repo,
7001
- target
7002
- });
7003
- continue;
7004
- }
7005
- const cleanup = await ctx.sandbox.run({
7006
- cmd: "rm",
6938
+ for (const entry of repos) finalize.push(await prepareCheckout(ctx, entry));
6939
+ return async () => {
6940
+ for (const checkout of finalize) await refreshCheckout(ctx, checkout);
6941
+ };
6942
+ }
6943
+ const GIT_ENV = {
6944
+ GIT_CONFIG_GLOBAL: "/dev/null",
6945
+ GIT_CONFIG_NOSYSTEM: "1"
6946
+ };
6947
+ /** Clone one repository, or find the target that refreshes its checkout. */
6948
+ async function prepareCheckout(ctx, { owner, name, path, repo }) {
6949
+ const parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : void 0;
6950
+ if (parent) {
6951
+ const mkdir = await ctx.sandbox.run({
6952
+ cmd: "mkdir",
7007
6953
  args: [
7008
- "-rf",
6954
+ "-p",
7009
6955
  "--",
7010
- path
6956
+ parent
7011
6957
  ],
7012
6958
  cwd: ctx.sandbox.root
7013
6959
  });
7014
- if (cleanup.exitCode !== 0) throw new Error(`GitHub workspace checkout cleanup failed for ${repo}: ${cleanup.stderr.trim() || `exit ${cleanup.exitCode}`}`);
7015
- const result = await ctx.sandbox.run({
7016
- cmd: "git",
7017
- args: [
7018
- "clone",
7019
- "--quiet",
7020
- "--",
7021
- cloneUrl,
7022
- path
7023
- ],
7024
- cwd: ctx.sandbox.root,
7025
- env: gitEnv
7026
- });
7027
- if (result.exitCode !== 0) throw new Error(`GitHub workspace clone failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
7028
- finalize.push({
7029
- path,
7030
- repo,
7031
- target: "HEAD"
7032
- });
6960
+ if (mkdir.exitCode !== 0) throw new Error(`GitHub workspace checkout parent failed for ${repo}: ${mkdir.stderr.trim() || `exit ${mkdir.exitCode}`}`);
7033
6961
  }
7034
- return async () => {
7035
- for (const { path, repo, target } of finalize) for (const args of [[
6962
+ const cloneUrl = `https://github.com/${owner}/${name}.git`;
6963
+ const worktree = await ctx.sandbox.run({
6964
+ cmd: "git",
6965
+ args: [
7036
6966
  "-C",
7037
6967
  path,
7038
- "reset",
7039
- "--hard",
7040
- target
7041
- ], [
6968
+ "rev-parse",
6969
+ "--is-inside-work-tree"
6970
+ ],
6971
+ cwd: ctx.sandbox.root,
6972
+ env: GIT_ENV
6973
+ });
6974
+ const branch = worktree.exitCode === 0 ? await ctx.sandbox.run({
6975
+ cmd: "git",
6976
+ args: [
7042
6977
  "-C",
7043
6978
  path,
7044
- "clean",
7045
- "-fd"
7046
- ]]) {
6979
+ "symbolic-ref",
6980
+ "--quiet",
6981
+ "--short",
6982
+ "HEAD"
6983
+ ],
6984
+ cwd: ctx.sandbox.root,
6985
+ env: GIT_ENV
6986
+ }) : void 0;
6987
+ const branchName = branch?.stdout.trim();
6988
+ const detachedHead = worktree.exitCode === 0 && !branchName ? await ctx.sandbox.run({
6989
+ cmd: "git",
6990
+ args: [
6991
+ "-C",
6992
+ path,
6993
+ "rev-parse",
6994
+ "--verify",
6995
+ "HEAD^{commit}"
6996
+ ],
6997
+ cwd: ctx.sandbox.root,
6998
+ env: GIT_ENV
6999
+ }) : void 0;
7000
+ const detachedSha = detachedHead?.stdout.trim();
7001
+ const validDetachedHead = Boolean(detachedHead?.exitCode === 0 && detachedSha && /^[0-9a-f]{40,64}$/.test(detachedSha));
7002
+ const upstreamRef = (branch?.exitCode === 0 && branchName ? await ctx.sandbox.run({
7003
+ cmd: "git",
7004
+ args: [
7005
+ "-C",
7006
+ path,
7007
+ "rev-parse",
7008
+ "--symbolic-full-name",
7009
+ "@{upstream}"
7010
+ ],
7011
+ cwd: ctx.sandbox.root,
7012
+ env: GIT_ENV
7013
+ }) : void 0)?.stdout.trim();
7014
+ const upstreamPrefix = "refs/remotes/origin/";
7015
+ const upstreamBranch = upstreamRef?.startsWith(upstreamPrefix) ? upstreamRef.slice(20) : void 0;
7016
+ if (worktree.exitCode === 0 && (branchName || validDetachedHead)) {
7017
+ const target = upstreamBranch ? `${upstreamPrefix}${upstreamBranch}` : "HEAD";
7018
+ if (upstreamBranch) {
7047
7019
  const result = await ctx.sandbox.run({
7048
7020
  cmd: "git",
7049
- args,
7021
+ args: [
7022
+ "-c",
7023
+ "credential.helper=",
7024
+ "-C",
7025
+ path,
7026
+ "fetch",
7027
+ "--quiet",
7028
+ "--no-tags",
7029
+ "--no-recurse-submodules",
7030
+ cloneUrl,
7031
+ `+refs/heads/${upstreamBranch}:${target}`
7032
+ ],
7050
7033
  cwd: ctx.sandbox.root,
7051
- env: gitEnv
7034
+ env: GIT_ENV
7052
7035
  });
7053
7036
  if (result.exitCode !== 0) throw new Error(`GitHub workspace refresh failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
7054
7037
  }
7038
+ return {
7039
+ path,
7040
+ repo,
7041
+ target
7042
+ };
7043
+ }
7044
+ const cleanup = await ctx.sandbox.run({
7045
+ cmd: "rm",
7046
+ args: [
7047
+ "-rf",
7048
+ "--",
7049
+ path
7050
+ ],
7051
+ cwd: ctx.sandbox.root
7052
+ });
7053
+ if (cleanup.exitCode !== 0) throw new Error(`GitHub workspace checkout cleanup failed for ${repo}: ${cleanup.stderr.trim() || `exit ${cleanup.exitCode}`}`);
7054
+ const result = await ctx.sandbox.run({
7055
+ cmd: "git",
7056
+ args: [
7057
+ "clone",
7058
+ "--quiet",
7059
+ "--",
7060
+ cloneUrl,
7061
+ path
7062
+ ],
7063
+ cwd: ctx.sandbox.root,
7064
+ env: GIT_ENV
7065
+ });
7066
+ if (result.exitCode !== 0) throw new Error(`GitHub workspace clone failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
7067
+ return {
7068
+ path,
7069
+ repo,
7070
+ target: "HEAD"
7055
7071
  };
7056
7072
  }
7073
+ /** Reset one checkout to its target and remove untracked files. */
7074
+ async function refreshCheckout(ctx, { path, repo, target }) {
7075
+ for (const args of [[
7076
+ "-C",
7077
+ path,
7078
+ "reset",
7079
+ "--hard",
7080
+ target
7081
+ ], [
7082
+ "-C",
7083
+ path,
7084
+ "clean",
7085
+ "-fd"
7086
+ ]]) {
7087
+ const result = await ctx.sandbox.run({
7088
+ cmd: "git",
7089
+ args,
7090
+ cwd: ctx.sandbox.root,
7091
+ env: GIT_ENV
7092
+ });
7093
+ if (result.exitCode !== 0) throw new Error(`GitHub workspace refresh failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
7094
+ }
7095
+ }
7057
7096
  // src/clone-command.ts
7058
7097
  /**
7059
7098
  * Best-effort detection of GitHub clones typed into the bash tool.
@@ -7657,6 +7696,7 @@ function githubPlugin(options = {}) {
7657
7696
  "github.com",
7658
7697
  "uploads.github.com"
7659
7698
  ],
7699
+ toolsSendNoCredential: true,
7660
7700
  envVars: {
7661
7701
  [appIdEnv]: {},
7662
7702
  [privateKeyEnv]: {},
package/dist/testing.js CHANGED
@@ -1 +1 @@
1
- export { n as normalizeGitHubEvents } from "./events-VdBpoUV7.js";
1
+ export { n as normalizeGitHubEvents } from "./events-CAZiit9g.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/junior-github",
3
- "version": "0.306.0",
3
+ "version": "0.307.1",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "dependencies": {
31
31
  "@0no-co/graphql.web": "^1.3.4",
32
- "@sentry/junior-plugin-api": "0.306.0",
32
+ "@sentry/junior-plugin-api": "0.307.1",
33
33
  "@sinclair/typebox": "^0.34.49",
34
34
  "drizzle-orm": "^0.45.4",
35
35
  "ignore": "^7.0.5",
@@ -37,6 +37,7 @@
37
37
  "mdast-util-from-markdown": "^2.1.0",
38
38
  "mdast-util-gfm": "^3.1.0",
39
39
  "micromark-extension-gfm": "^3.0.0",
40
+ "p-limit": "^7.3.1",
40
41
  "parse5": "^7.3.0",
41
42
  "zod": "^4.6.7"
42
43
  },