@sentry/junior-github 0.305.0 → 0.307.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 githubRequest, 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, T as issueGitHubCredential, U as gitHubReleaseSourceSubscribable, V as GITHUB_RELEASE_SOURCE_IDENTIFIER, W as GITHUB_PULL_REQUEST_EVENTS, X as gitHubPullRequestResource, Y as gitHubPullRequestEventGuidance, Z as gitHubPullRequestSubscribable, a as needsCheckSuitePullRequestFacts, at as GITHUB_ISSUE_IDENTIFIER, b as USER_WRITE_REQUIREMENTS, c as logFailOpenFailure, ct as gitHubIssueSubscribable, d as CREATE_TOOL_ROUTING_GUIDANCE, dt as readGrantPermissions, et as GITHUB_DEPLOYMENT_MATCH_FIELDS, g as GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES, h as GITHUB_AUTH_TOKEN_PLACEHOLDER, i as loadCheckSuiteFacts, it as GITHUB_ISSUE_EVENTS, j as resolveUserAccount, k as readEnv, l as definedValues, lt as gitHubRepoDataSchema, m as GITHUB_AUTH_TOKEN_ENV, n as normalizeGitHubEvents, nt as GITHUB_DEPLOYMENT_SUGGESTED_EVENTS, o as parseCheckSuitePublishTargets, ot as GITHUB_ISSUE_MATCH_FIELDS, 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 normalizePermissions, v as GitHubRequestError, w as isRecord$1, x as createPermissionCache, y as HTTP_READ_METHODS, z as GITHUB_RELEASE_EVENTS } from "./events-DGd7UVVs.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,11 +10,12 @@ 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";
16
17
  // src/account-links.ts
17
- const GITHUB_LOGIN_PATTERN$1 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
18
+ const GITHUB_LOGIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
18
19
  const NON_ACCOUNT_PATHS = /* @__PURE__ */ new Set([
19
20
  "about",
20
21
  "apps",
@@ -75,7 +76,7 @@ const githubAccountLinks = {
75
76
  objectTypes: ["person"],
76
77
  async resolve(ctx, url) {
77
78
  const login = url.pathname.split("/")[1] ?? "";
78
- if (!GITHUB_LOGIN_PATTERN$1.test(login) || NON_ACCOUNT_PATHS.has(login.toLowerCase())) return;
79
+ if (!GITHUB_LOGIN_PATTERN.test(login) || NON_ACCOUNT_PATHS.has(login.toLowerCase())) return;
79
80
  return await ctx.findPerson({
80
81
  provider: "github",
81
82
  handle: login
@@ -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));
@@ -298,265 +299,6 @@ function githubObjectFacts(type, response) {
298
299
  }
299
300
  };
300
301
  }
301
- // src/tool-support/github-api.ts
302
- const GITHUB_API_BASE = "https://api.github.com";
303
- const MAX_REDIRECTS = 3;
304
- const REDIRECT_STATUSES = /* @__PURE__ */ new Set([
305
- 301,
306
- 302,
307
- 307,
308
- 308
309
- ]);
310
- /**
311
- * Send one GitHub API request through host egress.
312
- *
313
- * Egress injects credentials, so tools never see a token. `operation` names
314
- * the provider action for grant selection and diagnostics. Callers own the
315
- * error mapping, because the status that means bad input differs per route.
316
- * `followRedirects` follows GET redirects on the GitHub API host. Set it only
317
- * when the caller reads the object identity from the response, because the
318
- * redirect target can be in another repository.
319
- */
320
- async function githubApi(egress, input) {
321
- const headers = {
322
- Accept: "application/vnd.github+json",
323
- "X-GitHub-Api-Version": input.apiVersion ?? "2022-11-28"
324
- };
325
- if (input.body !== void 0) headers["Content-Type"] = "application/json";
326
- const method = input.method ?? "GET";
327
- let url = `${GITHUB_API_BASE}${input.path}`;
328
- let response;
329
- const follow = input.followRedirects === true && method === "GET";
330
- for (let hop = 0;; hop++) {
331
- response = await egress.fetch({
332
- provider: "github",
333
- operation: input.operation,
334
- request: new Request(url, {
335
- method,
336
- headers,
337
- signal: input.signal ?? null,
338
- ...input.body !== void 0 ? { body: JSON.stringify(input.body) } : void 0
339
- })
340
- });
341
- const next = follow ? redirectTarget(response, url) : void 0;
342
- if (!next || hop >= MAX_REDIRECTS) break;
343
- await response.body?.cancel();
344
- url = next;
345
- }
346
- return {
347
- body: await readBody(response),
348
- ok: response.ok,
349
- status: response.status
350
- };
351
- }
352
- function redirectTarget(response, from) {
353
- if (!REDIRECT_STATUSES.has(response.status)) return void 0;
354
- const location = response.headers.get("location");
355
- if (!location) return void 0;
356
- const target = new URL(location, from);
357
- return target.origin === GITHUB_API_BASE ? target.href : void 0;
358
- }
359
- /**
360
- * Return where a `github.com` attachment URL redirects, through host
361
- * egress. GitHub signs that address for a short time, so it needs no
362
- * credential. Egress does not follow the redirect, so the credential never
363
- * reaches the image host.
364
- */
365
- async function githubAttachmentLocation(egress, url) {
366
- const response = await egress.fetch({
367
- provider: "github",
368
- operation: "github.attachment.get",
369
- request: new Request(url, { redirect: "manual" })
370
- });
371
- await response.body?.cancel();
372
- const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
373
- return location ? new URL(location, url).href : void 0;
374
- }
375
- async function readBody(response) {
376
- const text = await response.text();
377
- if (!text) return void 0;
378
- try {
379
- return JSON.parse(text);
380
- } catch {
381
- return text;
382
- }
383
- }
384
- /** Return the `/repos/{owner}/{name}` API path prefix for a parsed repo. */
385
- function repoPath(repo) {
386
- return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
387
- }
388
- /** Parse a model-supplied `owner/name` repository reference. */
389
- function parseRepo$1(value) {
390
- const parts = value.split("/").map((part) => part.trim());
391
- if (parts.length !== 2 || !parts[0] || !parts[1]) throw new PluginToolInputError("repo must use \"owner/name\" format");
392
- return {
393
- owner: parts[0],
394
- name: parts[1],
395
- ref: `${parts[0]}/${parts[1]}`
396
- };
397
- }
398
- /**
399
- * Return a readable error from a GitHub REST or GraphQL error body.
400
- *
401
- * REST validation errors list the failed fields in `errors`, and GraphQL puts
402
- * every message in `errors`. Both details help the model fix its input.
403
- */
404
- function githubErrorMessage$1(body) {
405
- if (typeof body === "string" && body.trim()) return body.trim();
406
- if (!isRecord(body)) return "GitHub request failed";
407
- const errors = Array.isArray(body["errors"]) ? body["errors"].filter(isRecord) : [];
408
- if (typeof body["message"] === "string" && body["message"].trim()) {
409
- const details = errors.map((error) => [
410
- "resource",
411
- "field",
412
- "code",
413
- "message"
414
- ].map((name) => {
415
- const value = error[name];
416
- return typeof value === "string" && value.trim() ? `${name}=${value.trim()}` : void 0;
417
- }).filter(Boolean).join(" ")).filter(Boolean).join("; ");
418
- const message = body["message"].trim();
419
- return details ? `${message}: ${details}` : message;
420
- }
421
- const graphqlMessages = errors.map((error) => error["message"]).filter((message) => typeof message === "string" && message.trim());
422
- return graphqlMessages.length ? graphqlMessages.join("; ") : "GitHub request failed";
423
- }
424
- function isRecord(value) {
425
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
426
- }
427
- // src/tool-support/attribution.ts
428
- const GITHUB_REQUEST_ATTRIBUTION_START = "<!-- junior-request-attribution:start -->";
429
- const GITHUB_REQUEST_ATTRIBUTION_END = "<!-- junior-request-attribution:end -->";
430
- const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
431
- const GITHUB_LOGIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
432
- /** Return a GitHub login without a leading `@`, when it is a valid login. */
433
- function parseGitHubLogin(value) {
434
- const login = value?.trim().replace(/^@/, "");
435
- return login && GITHUB_LOGIN_PATTERN.test(login) ? login : void 0;
436
- }
437
- /**
438
- * Return the GitHub login linked to a user, when it is a valid login.
439
- *
440
- * Attribution mentions, PR assignment, and review requests use this login so
441
- * the requester gets GitHub notifications for the issue or pull request.
442
- */
443
- function linkedGitHubLogin(user) {
444
- return parseGitHubLogin(user?.identities.find((identity) => identity.provider === "github")?.handle);
445
- }
446
- /**
447
- * Match host actor display cleaning: drop blanks, unknown, the actor id, and
448
- * Slack user-id shaped values so attribution never publishes a raw subject id.
449
- */
450
- function cleanDisplayValue(value, userId) {
451
- const cleaned = value?.replace(/[\r\n<>]/g, " ").trim();
452
- if (!cleaned) return;
453
- if (cleaned.toLowerCase() === "unknown") return;
454
- if (userId && cleaned === userId) return;
455
- if (SLACK_USER_ID_DISPLAY_PATTERN.test(cleaned)) return;
456
- return cleaned;
457
- }
458
- /** Name the Automation run that made this write. */
459
- function automationLabel(source, automationUrl) {
460
- if (source?.kind !== "event_automation" && source?.kind !== "scheduled_automation" || !source.automationId) return;
461
- const automation = `automation \`${source.automationId}\``;
462
- const label = automationUrl ? `[${automation}](${automationUrl})` : automation;
463
- return source.automationRunId ? `${label} · Run ID \`${source.automationRunId}\`` : label;
464
- }
465
- /**
466
- * Resolve the requester display label through the host identity path first.
467
- *
468
- * Automation runs use the automation label. Other system actors get no label
469
- * because their names are internal. For people, prefer a linked GitHub login
470
- * as an `@` mention so GitHub subscribes the requester. Otherwise use the
471
- * linked user name, then the stored identity name/handle, then the
472
- * already-hydrated actor profile. Never publish a raw actor id.
473
- */
474
- function requesterLabel(args) {
475
- const { actor, identity, user } = args;
476
- const automation = automationLabel(args.source, args.automationUrl);
477
- if (automation) return automation;
478
- if (!actor || actor.platform === "system") return;
479
- const login = linkedGitHubLogin(user);
480
- if (login) return `@${login}`;
481
- const userId = actor.userId;
482
- const display = cleanDisplayValue(user?.displayName, userId) ?? cleanDisplayValue(identity?.displayName, userId) ?? cleanDisplayValue(identity?.handle, userId) ?? cleanDisplayValue(actor.fullName, userId) ?? cleanDisplayValue(actor.userName, userId);
483
- return display ? `**${display.replaceAll("*", "\\*")}**` : void 0;
484
- }
485
- /**
486
- * Recover the ordered list of prior requester labels from an existing
487
- * attribution block, including the legacy `Requested by` and `via A, via B`
488
- * wordings, so a new requester can be appended instead of replacing them.
489
- */
490
- function parseExistingLabels(blockContents) {
491
- const trimmed = blockContents.trim().replace(/\.$/, "");
492
- if (!trimmed) return [];
493
- return trimmed.replace(/^(?:Requested by|via)\s+/i, "").split(/,\s*(?=\*\*|@|\[?automation `|Junior system actor `|via\s)/i).map((entry) => entry.trim().replace(/^via\s+/i, "")).filter(Boolean);
494
- }
495
- /** Render the attribution block wire format parsed by `parseExistingLabels`. */
496
- function formatAttributionBlock(labels) {
497
- return `${GITHUB_REQUEST_ATTRIBUTION_START}\nvia ${labels.join(", ")}.\n${GITHUB_REQUEST_ATTRIBUTION_END}`;
498
- }
499
- const ATTRIBUTION_BLOCK = new RegExp(`${GITHUB_REQUEST_ATTRIBUTION_START}([\\s\\S]*?)${GITHUB_REQUEST_ATTRIBUTION_END}`);
500
- function blockLabels(body) {
501
- const contents = body?.match(ATTRIBUTION_BLOCK)?.[1];
502
- return contents === void 0 ? [] : parseExistingLabels(contents);
503
- }
504
- /**
505
- * Merge requesters from the body on GitHub, the new body, and the current
506
- * Actor, in that order and without duplicates.
507
- */
508
- function applyAttribution(body, label, currentBody) {
509
- const normalizedBody = body.trimEnd();
510
- const labels = [.../* @__PURE__ */ new Set([
511
- ...blockLabels(currentBody),
512
- ...blockLabels(normalizedBody),
513
- ...label ? [label] : []
514
- ])];
515
- const attribution = labels.length ? formatAttributionBlock(labels) : void 0;
516
- if (ATTRIBUTION_BLOCK.test(normalizedBody)) return attribution ? normalizedBody.replace(ATTRIBUTION_BLOCK, attribution) : normalizedBody.replace(ATTRIBUTION_BLOCK, "").trimEnd();
517
- if (!attribution) return normalizedBody;
518
- return normalizedBody ? `${normalizedBody}\n\n${attribution}` : attribution;
519
- }
520
- /**
521
- * Read the body that is on GitHub now, so an update keeps its requesters.
522
- * The model sees descriptions with the attribution block removed.
523
- */
524
- async function readGitHubBody(egress, input) {
525
- const response = await githubApi(egress, input);
526
- if (!response.ok) throw new Error(`GitHub read before update failed with HTTP ${response.status}: ${githubErrorMessage$1(response.body)}`);
527
- return z.object({ body: z.string().nullable().optional() }).parse(response.body).body ?? void 0;
528
- }
529
- /**
530
- * Look up the current Actor once for one GitHub write. The attribution block,
531
- * the saved pull request requester, and the assignee all use this one result.
532
- *
533
- * System actors have no requester. The lookup is best effort: a failure is
534
- * logged and gives no requester, so it never blocks the write.
535
- */
536
- async function resolveGitHubRequester(ctx) {
537
- if (!ctx.actor || ctx.actor.platform === "system") return void 0;
538
- try {
539
- return await ctx.users.resolveActor();
540
- } catch (error) {
541
- ctx.log.warn("github.requester.resolve_actor.failed", { "exception.message": error instanceof Error ? error.message : String(error) });
542
- return;
543
- }
544
- }
545
- /**
546
- * Append or replace runtime-owned requester attribution in a GitHub body.
547
- * Pass `currentBody` on updates so requesters already on GitHub are kept.
548
- * With no stored requester, the label falls back to the already-hydrated
549
- * actor profile.
550
- */
551
- function appendGitHubRequesterAttribution(body, ctx, requester, currentBody) {
552
- return applyAttribution(body, requesterLabel({
553
- actor: ctx.actor,
554
- automationUrl: ctx.automationLink?.url,
555
- identity: requester?.identity,
556
- source: ctx.source,
557
- user: requester?.user
558
- }), currentBody);
559
- }
560
302
  // src/repository-access.ts
561
303
  const ACCESS_TTL_MS = 6e5;
562
304
  const permissionSchema = z.object({ permission: z.string().min(1) });
@@ -1045,10 +787,11 @@ const gitHubCommentOnPullRequestTool = definePluginTool({
1045
787
  async execute(input, _options, { egress }) {
1046
788
  const repo = parseRepo$1(input.repo);
1047
789
  const prefix = repoPath(repo);
790
+ const path = input.in_reply_to === void 0 ? `${prefix}/issues/${input.number}/comments` : `${prefix}/pulls/${input.number}/comments/${await threadRootId(egress, prefix, input.in_reply_to)}/replies`;
1048
791
  const response = await githubApi(egress, {
1049
792
  operation: "github.pull.comment.create",
1050
793
  method: "POST",
1051
- path: input.in_reply_to === void 0 ? `${prefix}/issues/${input.number}/comments` : `${prefix}/pulls/${input.number}/comments/${await threadRootId(egress, prefix, input.in_reply_to)}/replies`,
794
+ path,
1052
795
  body: { body: input.body }
1053
796
  });
1054
797
  if (!response.ok) {
@@ -1192,22 +935,33 @@ const createIssueStateSchema = Type.Union([Type.Object({
1192
935
  status: Type.Literal("pending")
1193
936
  }, { additionalProperties: false })]);
1194
937
  const gitHubIssueDataSchema = z.object({
938
+ note: z.string().optional(),
1195
939
  number: z.number(),
1196
940
  subscribable: subscribableResourceSchema.optional(),
941
+ subscription: watchResultSchema.optional(),
1197
942
  url: z.string()
1198
943
  });
1199
944
  const gitHubIssueOutputSchema = pluginToolOutputSchema.merge(gitHubIssueDataSchema.extend({ target: z.literal("createIssue") }));
1200
- function gitHubIssueToolResult(input, result, canSubscribe) {
945
+ /**
946
+ * Next step after an issue is created. Whether Junior does the work is the
947
+ * requester's decision, so the note asks for a Review item. Only a Turn that
948
+ * a person started gets it: no one can answer the item in other runs.
949
+ */
950
+ function implementIssueNote(issue) {
951
+ return `Unless the requester already asked you to fix ${issue}, ask whether to: the choice is theirs, even if they asked only for the issue. Use addReviewItem: question "Start a Thread to implement ${issue}?", choices "Start thread" (recommended) and "Not now", dedupe_key "github-issue-implement:${issue}". If they asked for the fix, start the Thread now. Skip both for issues owned by another team and for security, feedback, or tracking reports. Start the Thread with spawnAgent, kind thread, and this brief: read ${issue} with github_getIssue, follow the github-code workflow, and open a pull request that references it.`;
952
+ }
953
+ async function gitHubIssueToolResult(ctx, input, result) {
1201
954
  const repo = parseRepo$1(input.repo);
1202
- const subscribable = gitHubIssueSubscribable({
1203
- canSubscribe,
955
+ const repoName = `${repo.owner}/${repo.name}`;
956
+ const watch = await watchGitHubIssue(ctx, {
1204
957
  number: result.number,
1205
- repo: `${repo.owner}/${repo.name}`
958
+ repo: repoName
1206
959
  });
1207
960
  const data = {
961
+ ...startedByPerson(ctx) ? { note: implementIssueNote(`${repoName}#${result.number}`) } : void 0,
1208
962
  number: result.number,
1209
963
  url: result.url,
1210
- ...subscribable ? { subscribable } : void 0
964
+ ...watch
1211
965
  };
1212
966
  return {
1213
967
  objectAnnotations: [githubObjectAnnotation({
@@ -1262,7 +1016,7 @@ async function createGitHubIssueRequest(conversationId, input, ctx, dashboardUrl
1262
1016
  const labels = input.labels?.map((label) => nonEmptyString$3(label, "labels entry"));
1263
1017
  const payload = {
1264
1018
  title: nonEmptyString$3(input.title, "title"),
1265
- body: appendGitHubFooter(appendGitHubRequesterAttribution(input.body ?? "", ctx, await resolveGitHubRequester(ctx)), conversationId, dashboardUrl),
1019
+ body: appendGitHubFooter(appendGitHubRequesterAttribution(input.body ?? "", await resolveGitHubRequester(ctx)), conversationId, dashboardUrl),
1266
1020
  ...labels?.length ? { labels } : void 0
1267
1021
  };
1268
1022
  return {
@@ -1302,15 +1056,15 @@ const gitHubIssueTool = definePluginTool({
1302
1056
  const parsedInput = parseCreateIssueInput(input);
1303
1057
  const conversationId = nonEmptyString$3(ctx.conversationId, "conversationId");
1304
1058
  const key = `createIssue:${conversationId}:${nonEmptyString$3(options?.toolCallId, "toolCallId")}`;
1305
- 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 () => {
1306
1060
  const state = createIssueState(await ctx.state.get(key));
1307
- if (state?.status === "completed") return gitHubIssueToolResult(state.input ?? parsedInput, {
1061
+ if (state?.status === "completed") return await gitHubIssueToolResult(ctx, state.input ?? parsedInput, {
1308
1062
  facts: state.facts === void 0 ? void 0 : objectFactsSchema.parse(state.facts),
1309
1063
  sourceUpdatedAt: state.sourceUpdatedAt,
1310
1064
  description: state.description,
1311
1065
  number: state.number,
1312
1066
  url: state.url
1313
- }, ctx.events.canSubscribe);
1067
+ });
1314
1068
  if (state?.status === "pending") throw new Error("GitHub issue creation for this tool call has an uncertain pending result; refusing to create a duplicate issue.");
1315
1069
  const request = await createGitHubIssueRequest(conversationId, parsedInput, ctx, ctx.conversationLink?.url);
1316
1070
  const pendingState = {
@@ -1330,12 +1084,14 @@ const gitHubIssueTool = definePluginTool({
1330
1084
  } catch (error) {
1331
1085
  throw new Error("GitHub issue was created, but the runtime could not persist the completed issue state.", { cause: error });
1332
1086
  }
1333
- return gitHubIssueToolResult(parsedInput, result, ctx.events.canSubscribe);
1087
+ return await gitHubIssueToolResult(ctx, parsedInput, result);
1334
1088
  } catch (error) {
1335
1089
  if (isEgressAuthRequired$1(error) || isDefinitiveGitHubIssueCreateRejection(error)) await ctx.state.delete(key);
1336
1090
  throw error;
1337
1091
  }
1338
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;
1339
1095
  }
1340
1096
  });
1341
1097
  // src/tools/get-deployment.ts
@@ -1529,7 +1285,7 @@ const gitHubGetIssueTool = definePluginTool({
1529
1285
  }
1530
1286
  const issue = providerIssueSchema$1.parse(response.body);
1531
1287
  const repoRef = issueRepoRef(issue.repository_url) ?? repo.ref;
1532
- const login = linkedGitHubLogin(requester?.user)?.toLowerCase();
1288
+ const login = linkedGitHubLogin(requesterPerson(requester)?.user)?.toLowerCase();
1533
1289
  const needsClaim = login !== void 0 && issue.state === "open" && !issue.assignees.some((assignee) => assignee.toLowerCase() === login);
1534
1290
  const subscribable = gitHubIssueSubscribable({
1535
1291
  canSubscribe: ctx.events.canSubscribe,
@@ -1972,13 +1728,13 @@ function isDefinitiveGitHubPullRequestCreateRejection(error) {
1972
1728
  ].includes(error.status);
1973
1729
  }
1974
1730
  /** Build the GitHub REST create-PR request after the runtime owns body/footer shaping. */
1975
- function createGitHubPullRequestRequest(conversationId, input, ctx, requester, dashboardUrl) {
1731
+ function createGitHubPullRequestRequest(conversationId, input, requester, dashboardUrl) {
1976
1732
  const repo = parseRepo$1(input.repo);
1977
1733
  const payload = {
1978
1734
  title: nonEmptyString$2(input.title, "title"),
1979
1735
  head: nonEmptyString$2(input.head, "head"),
1980
1736
  base: nonEmptyString$2(input.base, "base"),
1981
- body: appendGitHubFooter(appendGitHubRequesterAttribution(input.body ?? "", ctx, requester), conversationId, dashboardUrl),
1737
+ body: appendGitHubFooter(appendGitHubRequesterAttribution(input.body ?? "", requester), conversationId, dashboardUrl),
1982
1738
  ...input.draft !== void 0 ? { draft: input.draft } : void 0
1983
1739
  };
1984
1740
  return {
@@ -2029,7 +1785,7 @@ async function recordOpener(ctx, input, state, requester) {
2029
1785
  }
2030
1786
  /** Assignment is optional: provider failures must not fail PR creation. */
2031
1787
  async function assignPullRequestRequester(ctx, input, result, requester) {
2032
- const assignee = linkedGitHubLogin(requester?.user);
1788
+ const assignee = linkedGitHubLogin(requesterPerson(requester)?.user);
2033
1789
  if (!assignee) return;
2034
1790
  try {
2035
1791
  const repo = parseRepo$1(input.repo);
@@ -2085,7 +1841,7 @@ async function requestPullRequestReviewers$1(ctx, input, result, requester) {
2085
1841
  await saveNamedDraftReviewers(ctx, input, result.number);
2086
1842
  return;
2087
1843
  }
2088
- const requesterLogin = linkedGitHubLogin(requester?.user);
1844
+ const requesterLogin = linkedGitHubLogin(requesterPerson(requester)?.user);
2089
1845
  const reviewers = named ?? (requesterLogin ? [requesterLogin] : []);
2090
1846
  if (reviewers.length === 0) return;
2091
1847
  const response = await githubApi(ctx.egress, {
@@ -2149,7 +1905,7 @@ async function gitHubPullRequestStructuredResult(ctx, input, result, subscriptio
2149
1905
  return {
2150
1906
  objectAnnotations,
2151
1907
  target: "createPullRequest",
2152
- ...gitHubPullRequestToolResult(input, result, ctx.events.canSubscribe, watch.events),
1908
+ ...gitHubPullRequestToolResult(input, result, ctx.events.canSubscribe, subscription.events),
2153
1909
  ...stack ? { stack } : void 0,
2154
1910
  subscription
2155
1911
  };
@@ -2185,13 +1941,14 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
2185
1941
  namedReviewers(parsedInput);
2186
1942
  const conversationId = nonEmptyString$2(ctx.conversationId, "conversationId");
2187
1943
  const key = `createPullRequest:${conversationId}:${nonEmptyString$2(options?.toolCallId, "toolCallId")}`;
2188
- 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 () => {
2189
1945
  const state = createPullRequestState(await ctx.state.get(key));
2190
1946
  if (state?.status === "completed") {
2191
1947
  const completedInput = state.input ?? parsedInput;
1948
+ const requester = await resolveGitHubRequester(ctx);
2192
1949
  await recordOpener(ctx, completedInput, state, {
2193
1950
  conversationId,
2194
- identityId: (await resolveGitHubRequester(ctx))?.identity?.id
1951
+ identityId: requesterPerson(requester)?.identity?.id
2195
1952
  });
2196
1953
  await saveNamedDraftReviewers(ctx, completedInput, state.number);
2197
1954
  return await gitHubPullRequestStructuredResult(ctx, completedInput, {
@@ -2203,10 +1960,11 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
2203
1960
  }, subscriptionConfig);
2204
1961
  }
2205
1962
  if (state?.status === "pending") throw new Error("GitHub pull request creation for this tool call has an uncertain pending result; refusing to create a duplicate pull request.");
2206
- if (descriptionChecks) await checkPullRequestDescription(ctx.decider, parsedInput.body ?? "");
2207
1963
  const requester = await resolveGitHubRequester(ctx);
2208
- const identityId = requester?.identity?.id;
2209
- const request = createGitHubPullRequestRequest(conversationId, parsedInput, ctx, requester, ctx.conversationLink?.url);
1964
+ assertGitHubPullRequestRequester(requester);
1965
+ if (descriptionChecks) await checkPullRequestDescription(ctx.decider, parsedInput.body ?? "");
1966
+ const identityId = requesterPerson(requester)?.identity?.id;
1967
+ const request = createGitHubPullRequestRequest(conversationId, parsedInput, requester, ctx.conversationLink?.url);
2210
1968
  const pendingState = {
2211
1969
  status: "pending",
2212
1970
  createdAtMs: Date.now(),
@@ -2244,6 +2002,8 @@ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = fal
2244
2002
  const stack = stackTarget ? await stackGitHubPullRequest(ctx, stackTarget) : void 0;
2245
2003
  return await gitHubPullRequestStructuredResult(ctx, parsedInput, result, subscriptionConfig, stack);
2246
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;
2247
2007
  }
2248
2008
  });
2249
2009
  }
@@ -3051,6 +2811,7 @@ const issueSchema = z.object({
3051
2811
  number: z.number(),
3052
2812
  state: z.string(),
3053
2813
  subscribable: subscribableResourceSchema.optional(),
2814
+ subscription: watchResultSchema.optional(),
3054
2815
  title: z.string(),
3055
2816
  url: z.string()
3056
2817
  });
@@ -3084,7 +2845,7 @@ const gitHubUpdateIssueTool = definePluginTool({
3084
2845
  const update = parsedInput.data;
3085
2846
  const repo = parseRepo$1(update.repo);
3086
2847
  const requester = update.body !== void 0 || update.assign_requester ? await resolveGitHubRequester(ctx) : void 0;
3087
- const assignee = update.assign_requester ? linkedGitHubLogin(requester?.user) : void 0;
2848
+ const assignee = update.assign_requester ? linkedGitHubLogin(requesterPerson(requester)?.user) : void 0;
3088
2849
  if (update.assign_requester && !assignee) throw new PluginToolInputError("The requester has no linked GitHub account, so the issue cannot be assigned to them.");
3089
2850
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
3090
2851
  operation: "github.issue.get",
@@ -3092,7 +2853,7 @@ const gitHubUpdateIssueTool = definePluginTool({
3092
2853
  }) : void 0;
3093
2854
  const payload = {
3094
2855
  ...update.title !== void 0 ? { title: update.title } : void 0,
3095
- ...update.body !== void 0 ? { body: appendGitHubFooter(appendGitHubRequesterAttribution(update.body, ctx, requester, currentBody), nonEmptyString$1(ctx.conversationId, "conversationId"), ctx.conversationLink?.url) } : void 0,
2856
+ ...update.body !== void 0 ? { body: appendGitHubFooter(appendGitHubRequesterAttribution(update.body, requester, currentBody), nonEmptyString$1(ctx.conversationId, "conversationId"), ctx.conversationLink?.url) } : void 0,
3096
2857
  ...update.state !== void 0 ? { state: update.state } : void 0
3097
2858
  };
3098
2859
  let parsed;
@@ -3122,8 +2883,7 @@ const gitHubUpdateIssueTool = definePluginTool({
3122
2883
  }
3123
2884
  const providerResult = providerIssueSchema.parse(parsed);
3124
2885
  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}.`);
3125
- const subscribable = gitHubIssueSubscribable({
3126
- canSubscribe: ctx.events.canSubscribe,
2886
+ const watch = await watchGitHubIssue(ctx, {
3127
2887
  number: providerResult.number,
3128
2888
  repo: repo.ref
3129
2889
  });
@@ -3142,7 +2902,7 @@ const gitHubUpdateIssueTool = definePluginTool({
3142
2902
  body: providerResult.body,
3143
2903
  number: providerResult.number,
3144
2904
  state: providerResult.state,
3145
- ...subscribable ? { subscribable } : void 0,
2905
+ ...watch,
3146
2906
  title: providerResult.title,
3147
2907
  url: providerResult.html_url
3148
2908
  };
@@ -3283,7 +3043,7 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3283
3043
  }) : void 0;
3284
3044
  const payload = {
3285
3045
  ...update.title !== void 0 ? { title: update.title } : void 0,
3286
- ...update.body !== void 0 ? { body: appendGitHubFooter(appendGitHubRequesterAttribution(update.body, ctx, requester, currentBody), nonEmptyString(ctx.conversationId, "conversationId"), ctx.conversationLink?.url) } : void 0,
3046
+ ...update.body !== void 0 ? { body: appendGitHubFooter(appendGitHubRequesterAttribution(update.body, requester, currentBody), nonEmptyString(ctx.conversationId, "conversationId"), ctx.conversationLink?.url) } : void 0,
3287
3047
  ...update.base !== void 0 ? { base: update.base } : void 0,
3288
3048
  ...update.state !== void 0 ? { state: update.state } : void 0
3289
3049
  };
@@ -3322,8 +3082,9 @@ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3322
3082
  repo: repo.ref
3323
3083
  });
3324
3084
  }
3325
- if (requester?.identity) await recordGitHubPullRequestRequester(ctx.db, {
3326
- identityId: requester.identity.id,
3085
+ const identity = requesterPerson(requester)?.identity;
3086
+ if (identity) await recordGitHubPullRequestRequester(ctx.db, {
3087
+ identityId: identity.id,
3327
3088
  number: providerResult.number,
3328
3089
  repositoryFullName: repo.ref
3329
3090
  });
@@ -3575,11 +3336,8 @@ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3575
3336
  const listPayload = listResponse.body;
3576
3337
  if (failed(listResponse)) throw new Error(`GitHub reaction lookup failed with HTTP ${listResponse.status}: ${githubErrorMessage$1(listPayload)}`);
3577
3338
  const botReactions = reactions.botReactions(listPayload).filter((reaction) => FEEDBACK_REACTION_CONTENTS.has(reaction.content));
3578
- for (const stale of botReactions) {
3579
- if (stale.content === targetContent) continue;
3580
- const deleteResponse = await reactions.remove(stale);
3581
- if (failed(deleteResponse) && deleteResponse.status !== 404) throw new Error(`GitHub reaction removal failed with HTTP ${deleteResponse.status}: ${githubErrorMessage$1(deleteResponse.body)}`);
3582
- }
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)}`);
3583
3341
  if (!botReactions.some((reaction) => reaction.content === targetContent)) {
3584
3342
  const createResponse = await reactions.add(targetContent);
3585
3343
  const createPayload = createResponse.body;
@@ -4510,6 +4268,7 @@ function normalizeGitHubPullRequestActivity(input) {
4510
4268
  return senderType === "Bot" ? void 0 : activity;
4511
4269
  }
4512
4270
  // src/webhooks/pull-request-preview.ts
4271
+ const ANNOTATION_UPDATE_CONCURRENCY = 8;
4513
4272
  const previewWebhookSchema = z.object({
4514
4273
  action: z.enum([
4515
4274
  "opened",
@@ -4538,7 +4297,8 @@ async function refreshGitHubPullRequestPreview(args) {
4538
4297
  const key = `${repository.full_name.toLowerCase()}#${pullRequest.number}`;
4539
4298
  const previewImageUrls = githubPreviewImageUrls(pullRequest.body);
4540
4299
  const updatedAt = Date.parse(pullRequest.updated_at);
4541
- 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 () => {
4542
4302
  const store = args.annotations.forConversation(conversationId);
4543
4303
  const current = (await store.list()).find((annotation) => annotation.key === key);
4544
4304
  if (current?.kind !== "object" || current.facts?.type !== "code_change") return;
@@ -4552,7 +4312,7 @@ async function refreshGitHubPullRequestPreview(args) {
4552
4312
  facts: next,
4553
4313
  sourceUpdatedAt: pullRequest.updated_at
4554
4314
  });
4555
- }));
4315
+ })));
4556
4316
  for (const result of results) {
4557
4317
  if (result.status === "fulfilled") continue;
4558
4318
  args.log?.error("GitHub pull request preview update failed", {
@@ -4563,6 +4323,7 @@ async function refreshGitHubPullRequestPreview(args) {
4563
4323
  }
4564
4324
  }
4565
4325
  // src/merge-conflict-checks/policy.ts
4326
+ const NOTICE_CLOSE_CONCURRENCY = 8;
4566
4327
  const DAY_MS = 864e5;
4567
4328
  /** Time after activity by a person in which Junior fixes conflicts. */
4568
4329
  const ACTIVE_MS = 2 * DAY_MS;
@@ -4735,10 +4496,10 @@ async function closeGitHubConflictNotices(args) {
4735
4496
  numbers: args.numbers,
4736
4497
  repositoryFullName
4737
4498
  });
4738
- for (const [number, opener] of openers) {
4739
- if (!opener.conversationId) continue;
4499
+ const limit = pLimit(NOTICE_CLOSE_CONCURRENCY);
4500
+ const close = async (number, conversationId) => {
4740
4501
  try {
4741
- await args.reviewItems.forConversation(opener.conversationId).close({
4502
+ await args.reviewItems.forConversation(conversationId).close({
4742
4503
  dedupeKey: gitHubConflictNoticeKey({
4743
4504
  number,
4744
4505
  repositoryFullName
@@ -4752,9 +4513,11 @@ async function closeGitHubConflictNotices(args) {
4752
4513
  repository: repositoryFullName
4753
4514
  });
4754
4515
  }
4755
- }
4516
+ };
4517
+ await Promise.all([...openers].flatMap(([number, { conversationId }]) => conversationId ? [limit(() => close(number, conversationId))] : []));
4756
4518
  }
4757
4519
  // src/webhooks/merge-conflict.ts
4520
+ const PULL_REQUEST_CHECK_CONCURRENCY = 5;
4758
4521
  const EVENT_TYPE = "pull_request.merge_conflict";
4759
4522
  /** Events after which the pull request cannot get a conflict. */
4760
4523
  const CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set(["pull_request.closed_unmerged", "pull_request.merged"]);
@@ -4831,18 +4594,17 @@ function deliveredPullRequest(payload, ref) {
4831
4594
  async function loadGitHubMergeConflictEvents(args) {
4832
4595
  const { hasMatch, loadConflictHistory, loadPullRequest } = args;
4833
4596
  if (!hasMatch || !loadPullRequest || !loadConflictHistory) return [];
4834
- const conflicts = [];
4835
- for (const ref of pullRequestRefs(args.events)) {
4836
- if (!await hasMatch(gitHubMergeConflictEvents(ref))) continue;
4597
+ const check = async (ref) => {
4598
+ if (!await hasMatch(gitHubMergeConflictEvents(ref))) return [];
4837
4599
  try {
4838
4600
  const loaded = deliveredPullRequest(args.pullRequestPayload, ref) ?? pullRequestSchema$1.parse(await loadPullRequest(ref));
4839
- 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 [];
4840
4602
  const conflict = {
4841
4603
  baseBranch: loaded.base.ref,
4842
4604
  headSha: loaded.head.sha,
4843
4605
  ...loaded.html_url ? { url: loaded.html_url } : void 0
4844
4606
  };
4845
- conflicts.push(...await applyGitHubConflictPolicy({
4607
+ return await applyGitHubConflictPolicy({
4846
4608
  conflict,
4847
4609
  db: args.db,
4848
4610
  draft: loaded.draft === true,
@@ -4856,16 +4618,18 @@ async function loadGitHubMergeConflictEvents(args) {
4856
4618
  ref,
4857
4619
  reviewItems: args.reviewItems,
4858
4620
  ...loaded.title ? { title: loaded.title } : void 0
4859
- }));
4621
+ });
4860
4622
  } catch (error) {
4861
4623
  logFailOpenFailure(args.log, "GitHub pull request merge conflict check failed", error, {
4862
4624
  deliveryId: args.deliveryId,
4863
4625
  pullRequest: ref.number,
4864
4626
  repository: ref.repositoryFullName
4865
4627
  });
4628
+ return [];
4866
4629
  }
4867
- }
4868
- 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();
4869
4633
  }
4870
4634
  // src/merge-conflict-checks/store.ts
4871
4635
  /** A key that waits longer than this was lost and expires. */
@@ -5214,6 +4978,7 @@ async function loadPullRequestMergeState(env, pullRequest) {
5214
4978
  return state;
5215
4979
  }
5216
4980
  // src/webhooks/pull-request-action.ts
4981
+ const PULL_REQUEST_SYNC_CONCURRENCY = 5;
5217
4982
  /**
5218
4983
  * A check normally takes a few seconds. After this time, a check that
5219
4984
  * stopped without its release no longer blocks new checks.
@@ -5241,11 +5006,11 @@ const ACTION_EVENTS = {
5241
5006
  */
5242
5007
  const LEGACY_DEDUPE_PREFIXES = ["pull-request-ready:", "pull-request-review-requested:"];
5243
5008
  async function closeLegacyItems(items, name) {
5244
- for (const prefix of LEGACY_DEDUPE_PREFIXES) await items.close({
5009
+ await Promise.all(LEGACY_DEDUPE_PREFIXES.map((prefix) => items.close({
5245
5010
  dedupeKey: `${prefix}${name}`,
5246
5011
  reason: "One item now shows the next action.",
5247
5012
  status: "dismissed"
5248
- });
5013
+ })));
5249
5014
  }
5250
5015
  const pullRequestWebhookSchema = z.object({
5251
5016
  action: z.string(),
@@ -5308,7 +5073,7 @@ async function showAction(items, args) {
5308
5073
  const { action, number, state } = args;
5309
5074
  if (action) await items.upsert({
5310
5075
  assigneeIdentityIds: [args.identityId],
5311
- 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}`,
5312
5077
  dedupeKey: args.dedupeKey,
5313
5078
  subject: {
5314
5079
  id: state.url,
@@ -5342,34 +5107,35 @@ async function syncOne(args, target) {
5342
5107
  let saved = claim.action;
5343
5108
  let requests = claim.requests;
5344
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
+ };
5345
5136
  while (requests !== void 0) {
5346
5137
  try {
5347
- const state = await loadPullRequestMergeState(args.env, target);
5348
- const next = nextAction(state, requesterLogin, saved);
5349
- const changed = next !== void 0 && next.action !== saved;
5350
- if (changed) await showAction(items, {
5351
- action: next.action,
5352
- dedupeKey,
5353
- identityId: opener.identityId,
5354
- number: target.number,
5355
- previous: saved,
5356
- state
5357
- });
5358
- await closeLegacyItems(items, name);
5359
- if (state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty") await items.close({
5360
- dedupeKey: gitHubConflictNoticeKey(target),
5361
- ...endedReason(state) ?? {
5362
- reason: "The pull request no longer has merge conflicts.",
5363
- status: "done"
5364
- }
5365
- });
5366
- if (changed) {
5367
- await setGitHubPullRequestNextAction(args.db, {
5368
- ...target,
5369
- action: next.action
5370
- });
5371
- saved = next.action;
5372
- }
5138
+ saved = await check(saved);
5373
5139
  } catch (error) {
5374
5140
  failure ??= error;
5375
5141
  }
@@ -5386,15 +5152,18 @@ async function syncOne(args, target) {
5386
5152
  * and does not fail the delivery.
5387
5153
  */
5388
5154
  async function syncGitHubPullRequestActions(args) {
5389
- for (const target of args.targets) try {
5390
- await syncOne(args, target);
5391
- } catch (error) {
5392
- logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
5393
- deliveryId: args.deliveryId,
5394
- number: target.number,
5395
- repository: target.repositoryFullName
5396
- });
5397
- }
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
+ })));
5398
5167
  }
5399
5168
  // src/webhooks/pull-request-ready-reviewers.ts
5400
5169
  const readyForReviewSchema = z.object({
@@ -5439,6 +5208,7 @@ async function requestGitHubReviewersWhenReady(args) {
5439
5208
  }
5440
5209
  }
5441
5210
  // src/webhooks/pull-request-match-data.ts
5211
+ const LOGIN_LOAD_CONCURRENCY = 5;
5442
5212
  /** The lookups that each match key needs. */
5443
5213
  const LOOKUPS_BY_MATCH_KEY = {
5444
5214
  authors: ["authors"],
@@ -5507,11 +5277,14 @@ async function withJuniorOpeners(context, events) {
5507
5277
  repositoryFullName: context.repositoryFullName
5508
5278
  });
5509
5279
  const logins = /* @__PURE__ */ new Map();
5510
- for (const identityId of new Set([...openers.values()].map((opener) => opener.identityId))) try {
5511
- logins.set(identityId, await context.loadGitHubLogin?.(identityId));
5512
- } catch (error) {
5513
- logFailure(context, "opener", error);
5514
- }
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
+ })));
5515
5288
  return events.map((event) => {
5516
5289
  const number = botNumber(event);
5517
5290
  if (number === void 0) return event;
@@ -5690,10 +5463,10 @@ async function loadGitHubPullRequestPeople(args) {
5690
5463
  const email = value.toLowerCase();
5691
5464
  if (!people.has(`email:${email}`)) people.set(`email:${email}`, { email });
5692
5465
  };
5693
- args.logins.forEach(addLogin);
5466
+ for (const login of args.logins) addLogin(login);
5694
5467
  await forEachCommit(args.loadPage, (commit) => {
5695
5468
  if (commit.login) addLogin(commit.login);
5696
- commit.coAuthorEmails.forEach(addEmail);
5469
+ for (const email of commit.coAuthorEmails) addEmail(email);
5697
5470
  });
5698
5471
  return [...people.values()].slice(0, MAX_PEOPLE);
5699
5472
  }
@@ -5711,7 +5484,7 @@ async function loadGitHubPullRequestAuthors(args) {
5711
5484
  };
5712
5485
  await forEachCommit(args.loadPage, (commit) => {
5713
5486
  add(commit.login);
5714
- commit.coAuthorEmails.forEach((email) => add(noreplyLogin(email)));
5487
+ for (const email of commit.coAuthorEmails) add(noreplyLogin(email));
5715
5488
  });
5716
5489
  return [...authors.values()].slice(0, MAX_PEOPLE);
5717
5490
  }
@@ -5939,7 +5712,8 @@ function createGitHubWebhookRoute(args) {
5939
5712
  botEmail,
5940
5713
  ...checkSuiteFacts ? { checkSuiteFacts } : void 0,
5941
5714
  deliveryId,
5942
- eventName
5715
+ eventName,
5716
+ ...args.trustedAuthors ? { trustedAuthors: args.trustedAuthors } : void 0
5943
5717
  }),
5944
5718
  hasMatch,
5945
5719
  ...commitPages ? { loadAuthors: async (target) => await loadGitHubPullRequestAuthors({ loadPage: commitPages(target) }) } : void 0,
@@ -6051,6 +5825,26 @@ const searchResponseSchema = z.object({ data: z.object({ search: z.object({
6051
5825
  })
6052
5826
  }) }) });
6053
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
+ }
6054
5848
  async function checkRepository(args, repositoryFullName) {
6055
5849
  let unknown = false;
6056
5850
  let after;
@@ -6069,28 +5863,16 @@ async function checkRepository(args, repositoryFullName) {
6069
5863
  number: node.number,
6070
5864
  repositoryFullName
6071
5865
  };
6072
- const conflict = {
6073
- baseBranch: node.baseRefName,
6074
- headSha: node.headRefOid,
6075
- url: node.url
6076
- };
6077
- const events = gitHubMergeConflictEvents({
6078
- ...ref,
6079
- conflict
6080
- });
6081
- if (!await args.events.hasMatch?.(events)) continue;
6082
- for (const event of await applyGitHubConflictPolicy({
6083
- conflict,
6084
- db: args.db,
5866
+ await checkConflict(args, {
5867
+ conflict: {
5868
+ baseBranch: node.baseRefName,
5869
+ headSha: node.headRefOid,
5870
+ url: node.url
5871
+ },
6085
5872
  draft: node.isDraft,
6086
- events,
6087
- loadHistory: args.loadHistory,
6088
- log: args.log,
6089
- now: args.now,
6090
5873
  ref,
6091
- reviewItems: args.reviewItems,
6092
5874
  title: node.title
6093
- })) await args.events.publish(event);
5875
+ });
6094
5876
  }
6095
5877
  await closeGitHubConflictNotices({
6096
5878
  db: args.db,
@@ -6230,76 +6012,83 @@ async function reconcileRepository(args, repositoryId, drafts) {
6230
6012
  })).data.repository;
6231
6013
  for (const pullRequest of Object.values(pullRequests)) {
6232
6014
  if (!pullRequest) continue;
6233
- if (pullRequest.state === "OPEN") {
6234
- if (pullRequest.isDraft !== drafts.get(pullRequest.number)) {
6235
- await reconcileDraft(args, {
6236
- databaseId,
6237
- nameWithOwner
6238
- }, pullRequest);
6239
- continue;
6240
- }
6241
- await args.codeChanges.record(githubCodeChange({
6242
- candidateOwned: false,
6243
- draft: pullRequest.isDraft,
6244
- number: pullRequest.number,
6245
- openedAt: new Date(pullRequest.createdAt),
6246
- pullRequestId: String(pullRequest.databaseId),
6247
- repositoryFullName: nameWithOwner,
6248
- repositoryId: String(databaseId),
6249
- state: "open",
6250
- title: pullRequest.title,
6251
- updatedAt: new Date(pullRequest.updatedAt)
6252
- }, []));
6253
- continue;
6254
- }
6255
- 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, {
6256
6027
  databaseId,
6257
6028
  nameWithOwner
6258
6029
  }, pullRequest);
6259
- const outcome = normalizeGitHubPullRequestOutcome({
6260
- body,
6261
- botEmail: args.botEmail
6262
- });
6263
- if (!outcome) continue;
6264
- const events = await withGitHubPullRequestPeople({
6265
- body,
6266
- deliveryId: "reconcile",
6267
- events: gitHubPullRequestTerminalEvents(body),
6268
- hasMatch: args.events.hasMatch,
6269
- load: async (target) => await loadGitHubPullRequestPeople({
6270
- logins: target.logins,
6271
- loadPage: await args.loadCommitPages(target)
6272
- }),
6273
- log: args.log
6274
- });
6275
- for (const event of events) await args.events.publish({
6276
- ...event,
6277
- objectType: "code_change"
6278
- });
6279
- await closeGitHubConflictNotice({
6280
- db: args.db,
6281
- ref: {
6282
- number: pullRequest.number,
6283
- repositoryFullName: nameWithOwner
6284
- },
6285
- reviewItems: args.reviewItems,
6286
- ...pullRequest.merged ? {
6287
- reason: "The pull request merged.",
6288
- status: "done"
6289
- } : {
6290
- reason: "The pull request closed without merging.",
6291
- status: "dismissed"
6292
- }
6293
- });
6294
- await applyGitHubPullRequestOutcome({
6295
- annotations: args.annotations,
6296
- codeChanges: args.codeChanges,
6297
- db: args.db,
6298
- log: args.log,
6299
- outcome
6300
- });
6030
+ return;
6301
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;
6302
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
+ });
6303
6092
  }
6304
6093
  /**
6305
6094
  * Reconcile the next repository that has open Junior pull requests and was
@@ -6996,6 +6785,7 @@ function linkifyGitHubReferences(text, options = {}) {
6996
6785
  return result + text.slice(cursor);
6997
6786
  }
6998
6787
  // src/conversation-title-context.ts
6788
+ const REFERENCE_LOAD_CONCURRENCY = 5;
6999
6789
  const MAX_REFERENCES = 3;
7000
6790
  const TITLE_MAX_LENGTH = 160;
7001
6791
  const OWNER = String.raw`([A-Za-z0-9][A-Za-z0-9-]*)`;
@@ -7099,8 +6889,8 @@ function parseGitHubReferences(text, config) {
7099
6889
  }
7100
6890
  /** Read the display title of an issue, pull request, or commit response. */
7101
6891
  function objectTitle(kind, object) {
7102
- if (!isRecord$1(object)) return void 0;
7103
- return (kind === "commit" ? isRecord$1(object["commit"]) && typeof object["commit"]["message"] === "string" ? object["commit"]["message"].split("\n")[0] : void 0 : typeof object["title"] === "string" ? object["title"] : void 0)?.replace(/\s+/g, " ").trim() || void 0;
6892
+ if (!isRecord(object)) return void 0;
6893
+ return (kind === "commit" ? isRecord(object["commit"]) && typeof object["commit"]["message"] === "string" ? object["commit"]["message"].split("\n")[0] : void 0 : typeof object["title"] === "string" ? object["title"] : void 0)?.replace(/\s+/g, " ").trim() || void 0;
7104
6894
  }
7105
6895
  /**
7106
6896
  * Describe GitHub issues, pull requests, and commits that message text
@@ -7108,7 +6898,8 @@ function objectTitle(kind, object) {
7108
6898
  * References that `loadObject` cannot read are left out.
7109
6899
  */
7110
6900
  async function loadGitHubConversationTitleContext(args) {
7111
- 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 () => {
7112
6903
  try {
7113
6904
  const title = objectTitle(reference.kind, await args.loadObject(reference));
7114
6905
  if (!title) return void 0;
@@ -7120,7 +6911,7 @@ async function loadGitHubConversationTitleContext(args) {
7120
6911
  });
7121
6912
  return;
7122
6913
  }
7123
- }))).filter((line) => Boolean(line));
6914
+ })))).filter((line) => Boolean(line));
7124
6915
  }
7125
6916
  // src/workspace-prepare.ts
7126
6917
  /** Clone missing GitHub repositories or refresh existing Workspace checkouts. */
@@ -7143,160 +6934,165 @@ async function prepareWorkspace(ctx) {
7143
6934
  if (paths.has(key)) throw new Error(`Workspace checkout path collision: ${entry.path}`);
7144
6935
  paths.add(key);
7145
6936
  }
7146
- const gitEnv = {
7147
- GIT_CONFIG_GLOBAL: "/dev/null",
7148
- GIT_CONFIG_NOSYSTEM: "1"
7149
- };
7150
6937
  const finalize = [];
7151
- for (const { owner, name, path, repo } of repos) {
7152
- const parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : void 0;
7153
- if (parent) {
7154
- const mkdir = await ctx.sandbox.run({
7155
- cmd: "mkdir",
7156
- args: [
7157
- "-p",
7158
- "--",
7159
- parent
7160
- ],
7161
- cwd: ctx.sandbox.root
7162
- });
7163
- if (mkdir.exitCode !== 0) throw new Error(`GitHub workspace checkout parent failed for ${repo}: ${mkdir.stderr.trim() || `exit ${mkdir.exitCode}`}`);
7164
- }
7165
- const cloneUrl = `https://github.com/${owner}/${name}.git`;
7166
- const worktree = await ctx.sandbox.run({
7167
- cmd: "git",
7168
- args: [
7169
- "-C",
7170
- path,
7171
- "rev-parse",
7172
- "--is-inside-work-tree"
7173
- ],
7174
- cwd: ctx.sandbox.root,
7175
- env: gitEnv
7176
- });
7177
- const branch = worktree.exitCode === 0 ? await ctx.sandbox.run({
7178
- cmd: "git",
7179
- args: [
7180
- "-C",
7181
- path,
7182
- "symbolic-ref",
7183
- "--quiet",
7184
- "--short",
7185
- "HEAD"
7186
- ],
7187
- cwd: ctx.sandbox.root,
7188
- env: gitEnv
7189
- }) : void 0;
7190
- const branchName = branch?.stdout.trim();
7191
- const detachedHead = worktree.exitCode === 0 && !branchName ? await ctx.sandbox.run({
7192
- cmd: "git",
7193
- args: [
7194
- "-C",
7195
- path,
7196
- "rev-parse",
7197
- "--verify",
7198
- "HEAD^{commit}"
7199
- ],
7200
- cwd: ctx.sandbox.root,
7201
- env: gitEnv
7202
- }) : void 0;
7203
- const detachedSha = detachedHead?.stdout.trim();
7204
- const validDetachedHead = Boolean(detachedHead?.exitCode === 0 && detachedSha && /^[0-9a-f]{40,64}$/.test(detachedSha));
7205
- const upstreamRef = (branch?.exitCode === 0 && branchName ? await ctx.sandbox.run({
7206
- cmd: "git",
7207
- args: [
7208
- "-C",
7209
- path,
7210
- "rev-parse",
7211
- "--symbolic-full-name",
7212
- "@{upstream}"
7213
- ],
7214
- cwd: ctx.sandbox.root,
7215
- env: gitEnv
7216
- }) : void 0)?.stdout.trim();
7217
- const upstreamPrefix = "refs/remotes/origin/";
7218
- const upstreamBranch = upstreamRef?.startsWith(upstreamPrefix) ? upstreamRef.slice(20) : void 0;
7219
- if (worktree.exitCode === 0 && (branchName || validDetachedHead)) {
7220
- const target = upstreamBranch ? `${upstreamPrefix}${upstreamBranch}` : "HEAD";
7221
- if (upstreamBranch) {
7222
- const result = await ctx.sandbox.run({
7223
- cmd: "git",
7224
- args: [
7225
- "-c",
7226
- "credential.helper=",
7227
- "-C",
7228
- path,
7229
- "fetch",
7230
- "--quiet",
7231
- "--no-tags",
7232
- "--no-recurse-submodules",
7233
- cloneUrl,
7234
- `+refs/heads/${upstreamBranch}:${target}`
7235
- ],
7236
- cwd: ctx.sandbox.root,
7237
- env: gitEnv
7238
- });
7239
- if (result.exitCode !== 0) throw new Error(`GitHub workspace refresh failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
7240
- }
7241
- finalize.push({
7242
- path,
7243
- repo,
7244
- target
7245
- });
7246
- continue;
7247
- }
7248
- const cleanup = await ctx.sandbox.run({
7249
- 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",
7250
6953
  args: [
7251
- "-rf",
6954
+ "-p",
7252
6955
  "--",
7253
- path
6956
+ parent
7254
6957
  ],
7255
6958
  cwd: ctx.sandbox.root
7256
6959
  });
7257
- if (cleanup.exitCode !== 0) throw new Error(`GitHub workspace checkout cleanup failed for ${repo}: ${cleanup.stderr.trim() || `exit ${cleanup.exitCode}`}`);
7258
- const result = await ctx.sandbox.run({
7259
- cmd: "git",
7260
- args: [
7261
- "clone",
7262
- "--quiet",
7263
- "--",
7264
- cloneUrl,
7265
- path
7266
- ],
7267
- cwd: ctx.sandbox.root,
7268
- env: gitEnv
7269
- });
7270
- if (result.exitCode !== 0) throw new Error(`GitHub workspace clone failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
7271
- finalize.push({
7272
- path,
7273
- repo,
7274
- target: "HEAD"
7275
- });
6960
+ if (mkdir.exitCode !== 0) throw new Error(`GitHub workspace checkout parent failed for ${repo}: ${mkdir.stderr.trim() || `exit ${mkdir.exitCode}`}`);
7276
6961
  }
7277
- return async () => {
7278
- 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: [
7279
6966
  "-C",
7280
6967
  path,
7281
- "reset",
7282
- "--hard",
7283
- target
7284
- ], [
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: [
6977
+ "-C",
6978
+ path,
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: [
7285
7005
  "-C",
7286
7006
  path,
7287
- "clean",
7288
- "-fd"
7289
- ]]) {
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) {
7290
7019
  const result = await ctx.sandbox.run({
7291
7020
  cmd: "git",
7292
- 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
+ ],
7293
7033
  cwd: ctx.sandbox.root,
7294
- env: gitEnv
7034
+ env: GIT_ENV
7295
7035
  });
7296
7036
  if (result.exitCode !== 0) throw new Error(`GitHub workspace refresh failed for ${repo}: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
7297
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"
7298
7071
  };
7299
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
+ }
7300
7096
  // src/clone-command.ts
7301
7097
  /**
7302
7098
  * Best-effort detection of GitHub clones typed into the bash tool.
@@ -7389,7 +7185,7 @@ function assertGitHubPullRequestApprovalDenied(input) {
7389
7185
  } catch {
7390
7186
  throw new EgressPolicyDenied("GitHub pull request review requests must use JSON bodies so the no-approve policy can be enforced.");
7391
7187
  }
7392
- if (!isRecord$1(body)) throw new EgressPolicyDenied("GitHub pull request review requests must use JSON object bodies so the no-approve policy can be enforced.");
7188
+ if (!isRecord(body)) throw new EgressPolicyDenied("GitHub pull request review requests must use JSON object bodies so the no-approve policy can be enforced.");
7393
7189
  let event;
7394
7190
  if ("event" in body) {
7395
7191
  if (typeof body["event"] !== "string" || body["event"].trim().length === 0) throw new EgressPolicyDenied("GitHub pull request review submissions must include a parseable non-APPROVE event so the no-approve policy can be enforced.");
@@ -7518,9 +7314,9 @@ function githubGraphqlPermissionDeniedMessage(bodyText) {
7518
7314
  } catch {
7519
7315
  return;
7520
7316
  }
7521
- if (!isRecord$1(parsed) || !Array.isArray(parsed["errors"])) return;
7317
+ if (!isRecord(parsed) || !Array.isArray(parsed["errors"])) return;
7522
7318
  for (const error of parsed["errors"]) {
7523
- if (!isRecord$1(error) || typeof error["message"] !== "string") continue;
7319
+ if (!isRecord(error) || typeof error["message"] !== "string") continue;
7524
7320
  const message = error["message"];
7525
7321
  if (error["type"] === "NOT_FOUND" && /\bCould not resolve to a Repository with the name\b/.test(message)) return `GitHub GraphQL could not access the repository: ${message}`;
7526
7322
  if (/\bResource not accessible by integration\b/.test(message)) return `GitHub GraphQL denied access: ${message}`;
@@ -7545,7 +7341,7 @@ function githubErrorMessage(bodyText) {
7545
7341
  if (!bodyText) return;
7546
7342
  try {
7547
7343
  const parsed = JSON.parse(bodyText);
7548
- return isRecord$1(parsed) && typeof parsed["message"] === "string" ? parsed["message"].trim() : void 0;
7344
+ return isRecord(parsed) && typeof parsed["message"] === "string" ? parsed["message"].trim() : void 0;
7549
7345
  } catch {
7550
7346
  return;
7551
7347
  }
@@ -7900,6 +7696,7 @@ function githubPlugin(options = {}) {
7900
7696
  "github.com",
7901
7697
  "uploads.github.com"
7902
7698
  ],
7699
+ toolsSendNoCredential: true,
7903
7700
  envVars: {
7904
7701
  [appIdEnv]: {},
7905
7702
  [privateKeyEnv]: {},
@@ -8047,6 +7844,7 @@ function githubPlugin(options = {}) {
8047
7844
  annotations: ctx.annotations,
8048
7845
  appIdEnv,
8049
7846
  botEmail: () => readEnv(botEmailEnv),
7847
+ ...options.trustedAuthors ? { trustedAuthors: options.trustedAuthors } : void 0,
8050
7848
  classifyPullRequestCommits: async (pullRequest) => await classifyGitHubPullRequestCommitComposition({
8051
7849
  botEmail: requireEnv(botEmailEnv),
8052
7850
  loadPage: await loadPullRequestCommitPages(installationEnv, pullRequest)