@sentry/junior-github 0.301.0 → 0.302.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.
Files changed (48) hide show
  1. package/dist/{chunk-YUF5P5I7.js → chunk-6SOJ5TN6.js} +142 -31
  2. package/dist/clone-command.d.ts +2 -0
  3. package/dist/db/schema.d.ts +23 -14
  4. package/dist/draft-readiness.d.ts +31 -0
  5. package/dist/events/pull-request.d.ts +1 -1
  6. package/dist/events/repository.d.ts +1 -1
  7. package/dist/graphql-documents.d.ts +13 -0
  8. package/dist/hooks-path-command.d.ts +5 -0
  9. package/dist/index.js +2060 -1699
  10. package/dist/merge-conflict-checks/heartbeat.d.ts +9 -5
  11. package/dist/merge-conflict-checks/policy.d.ts +74 -0
  12. package/dist/pull-request-outcomes/reconcile.d.ts +2 -1
  13. package/dist/pull-request-outcomes/store.d.ts +15 -10
  14. package/dist/testing.js +1 -1
  15. package/dist/tool-support/github-text.d.ts +2 -2
  16. package/dist/tools/clone-repository.d.ts +89 -7
  17. package/dist/tools/comment-on-issue.d.ts +87 -3
  18. package/dist/tools/comment-on-pull-request.d.ts +87 -3
  19. package/dist/tools/create-issue.d.ts +86 -4
  20. package/dist/tools/create-pull-request.d.ts +88 -6
  21. package/dist/tools/get-deployment.d.ts +90 -8
  22. package/dist/tools/get-issue.d.ts +98 -16
  23. package/dist/tools/get-pull-request.d.ts +112 -9
  24. package/dist/tools/get-release.d.ts +90 -8
  25. package/dist/tools/get-repository.d.ts +90 -8
  26. package/dist/tools/get-status.d.ts +87 -5
  27. package/dist/tools/react-to-issue.d.ts +87 -3
  28. package/dist/tools/resolve-pull-request-review-thread.d.ts +87 -5
  29. package/dist/tools/submit-pull-request-review.d.ts +87 -3
  30. package/dist/tools/update-issue-comment.d.ts +87 -3
  31. package/dist/tools/update-issue.d.ts +106 -24
  32. package/dist/tools/update-pull-request-feedback.d.ts +87 -5
  33. package/dist/tools/update-pull-request.d.ts +109 -26
  34. package/dist/tools.d.ts +3 -3
  35. package/dist/webhooks/check-suite.d.ts +30 -3
  36. package/dist/webhooks/handler.d.ts +2 -0
  37. package/dist/webhooks/installation-requests.d.ts +8 -1
  38. package/dist/webhooks/merge-conflict.d.ts +7 -2
  39. package/dist/webhooks/pull-request-action.d.ts +37 -0
  40. package/migrations/0012_pull_request_next_action.sql +5 -0
  41. package/migrations/meta/0012_snapshot.json +434 -0
  42. package/migrations/meta/_journal.json +7 -0
  43. package/package.json +3 -2
  44. package/skills/github-code/SKILL.md +1 -1
  45. package/skills/github-code/SPEC.md +2 -2
  46. package/skills/github-code/references/workflow.md +1 -1
  47. package/dist/webhooks/pull-request-ready.d.ts +0 -31
  48. package/dist/webhooks/pull-request-review-request.d.ts +0 -32
package/dist/index.js CHANGED
@@ -62,8 +62,9 @@ import {
62
62
  readEnv,
63
63
  readGrantPermissions,
64
64
  requireEnv,
65
- resolveUserAccount
66
- } from "./chunk-YUF5P5I7.js";
65
+ resolveUserAccount,
66
+ wantsCheckSuitePassed
67
+ } from "./chunk-6SOJ5TN6.js";
67
68
 
68
69
  // src/account-links.ts
69
70
  var GITHUB_LOGIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
@@ -97,16 +98,16 @@ var NON_ACCOUNT_PATHS = /* @__PURE__ */ new Set([
97
98
  "topics",
98
99
  "trending"
99
100
  ]);
100
- function githubAccountCard(login2) {
101
+ function githubAccountCard(login) {
101
102
  return {
102
103
  kind: "object",
103
104
  objectType: "person",
104
- key: `github:${login2.toLowerCase()}`,
105
- label: `@${login2}`,
106
- title: login2,
107
- url: `https://github.com/${login2}`,
105
+ key: `github:${login.toLowerCase()}`,
106
+ label: `@${login}`,
107
+ title: login,
108
+ url: `https://github.com/${login}`,
108
109
  displayType: "GitHub account",
109
- facts: { type: "person", githubHandle: login2 }
110
+ facts: { type: "person", githubHandle: login }
110
111
  };
111
112
  }
112
113
  var githubAccountLinks = {
@@ -115,11 +116,11 @@ var githubAccountLinks = {
115
116
  canView: async () => true,
116
117
  objectType: "person",
117
118
  async resolve(ctx, url) {
118
- const login2 = url.pathname.split("/")[1] ?? "";
119
- if (!GITHUB_LOGIN_PATTERN.test(login2) || NON_ACCOUNT_PATHS.has(login2.toLowerCase())) {
119
+ const login = url.pathname.split("/")[1] ?? "";
120
+ if (!GITHUB_LOGIN_PATTERN.test(login) || NON_ACCOUNT_PATHS.has(login.toLowerCase())) {
120
121
  return void 0;
121
122
  }
122
- return await ctx.findPerson({ provider: "github", handle: login2 }) ?? githubAccountCard(login2);
123
+ return await ctx.findPerson({ provider: "github", handle: login }) ?? githubAccountCard(login);
123
124
  }
124
125
  };
125
126
 
@@ -228,8 +229,8 @@ var GITHUB_REQUEST_ATTRIBUTION_END = "<!-- junior-request-attribution:end -->";
228
229
  var SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
229
230
  var GITHUB_LOGIN_PATTERN2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
230
231
  function parseGitHubLogin(value) {
231
- const login2 = value?.trim().replace(/^@/, "");
232
- return login2 && GITHUB_LOGIN_PATTERN2.test(login2) ? login2 : void 0;
232
+ const login = value?.trim().replace(/^@/, "");
233
+ return login && GITHUB_LOGIN_PATTERN2.test(login) ? login : void 0;
233
234
  }
234
235
  function linkedGitHubLogin(user) {
235
236
  return parseGitHubLogin(
@@ -269,9 +270,9 @@ function requesterLabel(args) {
269
270
  if (!actor || actor.platform === "system") {
270
271
  return void 0;
271
272
  }
272
- const login2 = linkedGitHubLogin(user);
273
- if (login2) {
274
- return `@${login2}`;
273
+ const login = linkedGitHubLogin(user);
274
+ if (login) {
275
+ return `@${login}`;
275
276
  }
276
277
  const userId = actor.userId;
277
278
  const display = cleanDisplayValue(user?.displayName, userId) ?? cleanDisplayValue(identity?.displayName, userId) ?? cleanDisplayValue(identity?.handle, userId) ?? cleanDisplayValue(actor.fullName, userId) ?? cleanDisplayValue(actor.userName, userId);
@@ -386,44 +387,42 @@ var outputSchema = pluginToolOutputSchema.extend({
386
387
  content: z2.enum(REACTION_CONTENTS),
387
388
  reaction_id: z2.number()
388
389
  });
389
- function createGitHubReactToIssueTool(egress) {
390
- return definePluginTool({
391
- annotations: {
392
- destructiveHint: false,
393
- // GitHub returns the existing reaction when the bot already added it.
394
- idempotentHint: true,
395
- openWorldHint: true,
396
- readOnlyHint: false
397
- },
398
- description: "React with an emoji to a GitHub issue or pull request itself, for example to show that you started work on it. Reacting again with the same content changes nothing.",
399
- inputSchema,
400
- outputSchema,
401
- async execute(input) {
402
- const repo = parseRepo(input.repo);
403
- const response = await githubApi(egress, {
404
- operation: "github.issue.reaction.create",
405
- method: "POST",
406
- path: `${repoPath(repo)}/issues/${input.number}/reactions`,
407
- body: { content: input.content }
408
- });
409
- if (!response.ok) {
410
- const message = `GitHub issue reaction failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`;
411
- if (response.status === 404 || response.status === 422) {
412
- throw new PluginToolInputError2(message);
413
- }
414
- throw new Error(message);
390
+ var gitHubReactToIssueTool = definePluginTool({
391
+ annotations: {
392
+ destructiveHint: false,
393
+ // GitHub returns the existing reaction when the bot already added it.
394
+ idempotentHint: true,
395
+ openWorldHint: true,
396
+ readOnlyHint: false
397
+ },
398
+ description: "React with an emoji to a GitHub issue or pull request itself, for example to show that you started work on it. Reacting again with the same content changes nothing.",
399
+ inputSchema,
400
+ outputSchema,
401
+ async execute(input, _options, { egress }) {
402
+ const repo = parseRepo(input.repo);
403
+ const response = await githubApi(egress, {
404
+ operation: "github.issue.reaction.create",
405
+ method: "POST",
406
+ path: `${repoPath(repo)}/issues/${input.number}/reactions`,
407
+ body: { content: input.content }
408
+ });
409
+ if (!response.ok) {
410
+ const message = `GitHub issue reaction failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`;
411
+ if (response.status === 404 || response.status === 422) {
412
+ throw new PluginToolInputError2(message);
415
413
  }
416
- const reaction = z2.object({ id: z2.number() }).parse(response.body);
417
- return {
418
- target: "reactToIssue",
419
- repo: repo.ref,
420
- number: input.number,
421
- content: input.content,
422
- reaction_id: reaction.id
423
- };
414
+ throw new Error(message);
424
415
  }
425
- });
426
- }
416
+ const reaction = z2.object({ id: z2.number() }).parse(response.body);
417
+ return {
418
+ target: "reactToIssue",
419
+ repo: repo.ref,
420
+ number: input.number,
421
+ content: input.content,
422
+ reaction_id: reaction.id
423
+ };
424
+ }
425
+ });
427
426
 
428
427
  // src/tools/clone-repository.ts
429
428
  import {
@@ -522,117 +521,113 @@ async function removePartialClone(ctx, path) {
522
521
  });
523
522
  }
524
523
  }
525
- function createGitHubCloneRepositoryTool(ctx) {
526
- return definePluginTool2({
527
- annotations: {
528
- // Remote GitHub effect is contents-read only. Sandbox checkout creation is
529
- // the same class of ephemeral local materialization as webFetch artifacts,
530
- // so this stays a read-only inspection tool rather than a mutating write.
531
- destructiveHint: false,
532
- idempotentHint: false,
533
- openWorldHint: true,
534
- readOnlyHint: true
535
- },
536
- description: "Clone a GitHub repository into the sandbox as an ad-hoc checkout. The destination must not already exist. In the default Sandbox, a matching Workspace is a tool input error: call switchWorkspace instead, or opt in to an intentional ad-hoc checkout. Inside a Workspace, the clone proceeds and the result notes matching Workspaces.",
537
- describeProposal(input) {
538
- const directory = typeof input.directory === "string" && input.directory.length > 0 ? input.directory : void 0;
539
- const adHoc = input.allow_ad_hoc === true ? " as an intentional ad-hoc checkout" : "";
540
- return directory ? `Shallow-clone ${input.repo} into the local sandbox at ${directory}${adHoc} for inspection (no GitHub mutation).` : `Shallow-clone ${input.repo} into the local sandbox${adHoc} for inspection (no GitHub mutation).`;
541
- },
542
- executionMode: "sequential",
543
- inputSchema: inputSchema2,
544
- outputSchema: outputSchema2,
545
- async execute(input, options) {
546
- const repo = parseRepo2(input.repo);
547
- const repoId = `${repo.owner}/${repo.name}`;
548
- let workspaces = [];
549
- let active;
550
- try {
551
- [workspaces, active] = await Promise.all([
552
- ctx.workspaces.findByRepository({
553
- provider: "github",
554
- repo: repoId
555
- }),
556
- ctx.workspaces.active()
557
- ]);
558
- } catch (error) {
559
- ctx.log.error("github.clone.workspaces_lookup.failed", {
560
- repo: repoId,
561
- error: error instanceof Error ? error.message : String(error)
562
- });
563
- }
564
- if (workspaces.length > 0 && !active && input.allow_ad_hoc !== true) {
565
- throw workspaceRequiredError(repoId, workspaces);
566
- }
567
- const otherWorkspaces = workspaces.filter(
568
- (name) => name !== active?.name
524
+ var gitHubCloneRepositoryTool = definePluginTool2({
525
+ annotations: {
526
+ // Remote GitHub effect is contents-read only. Sandbox checkout creation is
527
+ // the same class of ephemeral local materialization as webFetch artifacts,
528
+ // so this stays a read-only inspection tool rather than a mutating write.
529
+ destructiveHint: false,
530
+ idempotentHint: false,
531
+ openWorldHint: true,
532
+ readOnlyHint: true
533
+ },
534
+ description: "Clone a GitHub repository into the sandbox as an ad-hoc checkout. The destination must not already exist. In the default Sandbox, a matching Workspace is a tool input error: call switchWorkspace instead, or opt in to an intentional ad-hoc checkout. Inside a Workspace, the clone proceeds and the result notes matching Workspaces.",
535
+ describeProposal(input) {
536
+ const directory = typeof input.directory === "string" && input.directory.length > 0 ? input.directory : void 0;
537
+ const adHoc = input.allow_ad_hoc === true ? " as an intentional ad-hoc checkout" : "";
538
+ return directory ? `Shallow-clone ${input.repo} into the local sandbox at ${directory}${adHoc} for inspection (no GitHub mutation).` : `Shallow-clone ${input.repo} into the local sandbox${adHoc} for inspection (no GitHub mutation).`;
539
+ },
540
+ executionMode: "sequential",
541
+ inputSchema: inputSchema2,
542
+ outputSchema: outputSchema2,
543
+ async execute(input, options, ctx) {
544
+ const repo = parseRepo2(input.repo);
545
+ const repoId = `${repo.owner}/${repo.name}`;
546
+ let workspaces = [];
547
+ let active;
548
+ try {
549
+ [workspaces, active] = await Promise.all([
550
+ ctx.workspaces.findByRepository({
551
+ provider: "github",
552
+ repo: repoId
553
+ }),
554
+ ctx.workspaces.active()
555
+ ]);
556
+ } catch (error) {
557
+ ctx.log.error("github.clone.workspaces_lookup.failed", {
558
+ repo: repoId,
559
+ error: error instanceof Error ? error.message : String(error)
560
+ });
561
+ }
562
+ if (workspaces.length > 0 && !active && input.allow_ad_hoc !== true) {
563
+ throw workspaceRequiredError(repoId, workspaces);
564
+ }
565
+ const otherWorkspaces = workspaces.filter((name) => name !== active?.name);
566
+ const note = active && otherWorkspaces.length > 0 ? workspaceAvailableNote(repoId, active, otherWorkspaces) : void 0;
567
+ const directory = input.directory ?? defaultDirectory(repo.name);
568
+ const rootSegment = directory.split("/")[0] ?? directory;
569
+ if (isReservedSandboxDirectory(rootSegment)) {
570
+ throw new PluginToolInputError3(
571
+ `Directory conflicts with a reserved sandbox path: ${directory}`
569
572
  );
570
- const note = active && otherWorkspaces.length > 0 ? workspaceAvailableNote(repoId, active, otherWorkspaces) : void 0;
571
- const directory = input.directory ?? defaultDirectory(repo.name);
572
- const rootSegment = directory.split("/")[0] ?? directory;
573
- if (isReservedSandboxDirectory(rootSegment)) {
574
- throw new PluginToolInputError3(
575
- `Directory conflicts with a reserved sandbox path: ${directory}`
576
- );
577
- }
578
- const path = `${ctx.sandbox.root}/${directory}`;
579
- const parentDirectory = directory.includes("/") ? directory.slice(0, directory.lastIndexOf("/")) : void 0;
580
- if (parentDirectory) {
581
- const mkdir = await ctx.sandbox.run({
582
- cmd: "mkdir",
583
- args: ["-p", "--", `${ctx.sandbox.root}/${parentDirectory}`],
584
- cwd: ctx.sandbox.root,
585
- signal: commandSignal(options.signal, 3e4)
586
- });
587
- if (mkdir.exitCode !== 0) {
588
- throw new PluginToolInputError3(
589
- `Failed to create clone parent directory: ${parentDirectory}`
590
- );
591
- }
592
- }
593
- const exists = await ctx.sandbox.run({
594
- cmd: "bash",
595
- args: ["-c", `test -e "$1"`, "bash", path],
573
+ }
574
+ const path = `${ctx.sandbox.root}/${directory}`;
575
+ const parentDirectory = directory.includes("/") ? directory.slice(0, directory.lastIndexOf("/")) : void 0;
576
+ if (parentDirectory) {
577
+ const mkdir = await ctx.sandbox.run({
578
+ cmd: "mkdir",
579
+ args: ["-p", "--", `${ctx.sandbox.root}/${parentDirectory}`],
596
580
  cwd: ctx.sandbox.root,
597
581
  signal: commandSignal(options.signal, 3e4)
598
582
  });
599
- if (exists.exitCode === 0) {
600
- throw new PluginToolInputError3(`destination already exists: ${path}`);
601
- }
602
- let clone;
603
- try {
604
- clone = await ctx.sandbox.run({
605
- cmd: "git",
606
- args: [
607
- "clone",
608
- "--quiet",
609
- "--depth=1",
610
- "--",
611
- `https://github.com/${repo.owner}/${repo.name}.git`,
612
- directory
613
- ],
614
- cwd: ctx.sandbox.root,
615
- signal: commandSignal(options.signal, 2 * 6e4)
616
- });
617
- } catch (error) {
618
- await removePartialClone(ctx, path);
619
- throw error;
620
- }
621
- if (clone.exitCode !== 0) {
622
- await removePartialClone(ctx, path);
583
+ if (mkdir.exitCode !== 0) {
623
584
  throw new PluginToolInputError3(
624
- `GitHub repository clone failed: ${clone.stderr.trim() || `exit ${clone.exitCode}`}`
585
+ `Failed to create clone parent directory: ${parentDirectory}`
625
586
  );
626
587
  }
627
- return {
628
- target: "cloneRepository",
629
- repo: repoId,
630
- path,
631
- ...note ? { note } : void 0
632
- };
633
588
  }
634
- });
635
- }
589
+ const exists = await ctx.sandbox.run({
590
+ cmd: "bash",
591
+ args: ["-c", `test -e "$1"`, "bash", path],
592
+ cwd: ctx.sandbox.root,
593
+ signal: commandSignal(options.signal, 3e4)
594
+ });
595
+ if (exists.exitCode === 0) {
596
+ throw new PluginToolInputError3(`destination already exists: ${path}`);
597
+ }
598
+ let clone;
599
+ try {
600
+ clone = await ctx.sandbox.run({
601
+ cmd: "git",
602
+ args: [
603
+ "clone",
604
+ "--quiet",
605
+ "--depth=1",
606
+ "--",
607
+ `https://github.com/${repo.owner}/${repo.name}.git`,
608
+ directory
609
+ ],
610
+ cwd: ctx.sandbox.root,
611
+ signal: commandSignal(options.signal, 2 * 6e4)
612
+ });
613
+ } catch (error) {
614
+ await removePartialClone(ctx, path);
615
+ throw error;
616
+ }
617
+ if (clone.exitCode !== 0) {
618
+ await removePartialClone(ctx, path);
619
+ throw new PluginToolInputError3(
620
+ `GitHub repository clone failed: ${clone.stderr.trim() || `exit ${clone.exitCode}`}`
621
+ );
622
+ }
623
+ return {
624
+ target: "cloneRepository",
625
+ repo: repoId,
626
+ path,
627
+ ...note ? { note } : void 0
628
+ };
629
+ }
630
+ });
636
631
 
637
632
  // src/tools/comment-on-issue.ts
638
633
  import {
@@ -653,43 +648,41 @@ var outputSchema3 = pluginToolOutputSchema3.extend({
653
648
  comment_id: z4.number(),
654
649
  url: z4.string()
655
650
  });
656
- function createGitHubCommentOnIssueTool(egress) {
657
- return definePluginTool3({
658
- annotations: {
659
- destructiveHint: false,
660
- idempotentHint: false,
661
- openWorldHint: true,
662
- readOnlyHint: false
663
- },
664
- description: "Post a comment on a GitHub issue. Returns the comment id and URL.",
665
- inputSchema: inputSchema3,
666
- outputSchema: outputSchema3,
667
- async execute(input) {
668
- const repo = parseRepo(input.repo);
669
- const response = await githubApi(egress, {
670
- operation: "github.issue.comment.create",
671
- method: "POST",
672
- path: `${repoPath(repo)}/issues/${input.number}/comments`,
673
- body: { body: input.body }
674
- });
675
- if (!response.ok) {
676
- const message = `GitHub issue comment failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`;
677
- if (response.status === 404 || response.status === 422) {
678
- throw new PluginToolInputError4(message);
679
- }
680
- throw new Error(message);
651
+ var gitHubCommentOnIssueTool = definePluginTool3({
652
+ annotations: {
653
+ destructiveHint: false,
654
+ idempotentHint: false,
655
+ openWorldHint: true,
656
+ readOnlyHint: false
657
+ },
658
+ description: "Post a comment on a GitHub issue. Returns the comment id and URL.",
659
+ inputSchema: inputSchema3,
660
+ outputSchema: outputSchema3,
661
+ async execute(input, _options, { egress }) {
662
+ const repo = parseRepo(input.repo);
663
+ const response = await githubApi(egress, {
664
+ operation: "github.issue.comment.create",
665
+ method: "POST",
666
+ path: `${repoPath(repo)}/issues/${input.number}/comments`,
667
+ body: { body: input.body }
668
+ });
669
+ if (!response.ok) {
670
+ const message = `GitHub issue comment failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`;
671
+ if (response.status === 404 || response.status === 422) {
672
+ throw new PluginToolInputError4(message);
681
673
  }
682
- const comment = z4.object({ id: z4.number(), html_url: z4.string() }).parse(response.body);
683
- return {
684
- target: "commentOnIssue",
685
- repo: repo.ref,
686
- number: input.number,
687
- comment_id: comment.id,
688
- url: comment.html_url
689
- };
674
+ throw new Error(message);
690
675
  }
691
- });
692
- }
676
+ const comment = z4.object({ id: z4.number(), html_url: z4.string() }).parse(response.body);
677
+ return {
678
+ target: "commentOnIssue",
679
+ repo: repo.ref,
680
+ number: input.number,
681
+ comment_id: comment.id,
682
+ url: comment.html_url
683
+ };
684
+ }
685
+ });
693
686
 
694
687
  // src/tools/comment-on-pull-request.ts
695
688
  import {
@@ -726,46 +719,44 @@ async function threadRootId(egress, prefix, commentId) {
726
719
  const comment = z5.object({ in_reply_to_id: z5.number().nullish() }).parse(response.body);
727
720
  return comment.in_reply_to_id ?? commentId;
728
721
  }
729
- function createGitHubCommentOnPullRequestTool(egress) {
730
- return definePluginTool4({
731
- annotations: {
732
- destructiveHint: false,
733
- idempotentHint: false,
734
- openWorldHint: true,
735
- readOnlyHint: false
736
- },
737
- description: "Post a conversation comment on a GitHub pull request, or reply in an inline review thread. For issues, use github_commentOnIssue. Use it to answer a question asked in a pull request review or comment. Returns the comment id and URL.",
738
- inputSchema: inputSchema4,
739
- outputSchema: outputSchema4,
740
- async execute(input) {
741
- const repo = parseRepo(input.repo);
742
- const prefix = repoPath(repo);
743
- 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`;
744
- const response = await githubApi(egress, {
745
- operation: "github.pull.comment.create",
746
- method: "POST",
747
- path,
748
- body: { body: input.body }
749
- });
750
- if (!response.ok) {
751
- const message = `GitHub pull request comment failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`;
752
- if (response.status === 404 || response.status === 422) {
753
- throw new PluginToolInputError5(message);
754
- }
755
- throw new Error(message);
722
+ var gitHubCommentOnPullRequestTool = definePluginTool4({
723
+ annotations: {
724
+ destructiveHint: false,
725
+ idempotentHint: false,
726
+ openWorldHint: true,
727
+ readOnlyHint: false
728
+ },
729
+ description: "Post a conversation comment on a GitHub pull request, or reply in an inline review thread. For issues, use github_commentOnIssue. Use it to answer a question asked in a pull request review or comment. Returns the comment id and URL.",
730
+ inputSchema: inputSchema4,
731
+ outputSchema: outputSchema4,
732
+ async execute(input, _options, { egress }) {
733
+ const repo = parseRepo(input.repo);
734
+ const prefix = repoPath(repo);
735
+ 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`;
736
+ const response = await githubApi(egress, {
737
+ operation: "github.pull.comment.create",
738
+ method: "POST",
739
+ path,
740
+ body: { body: input.body }
741
+ });
742
+ if (!response.ok) {
743
+ const message = `GitHub pull request comment failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`;
744
+ if (response.status === 404 || response.status === 422) {
745
+ throw new PluginToolInputError5(message);
756
746
  }
757
- const comment = z5.object({ id: z5.number(), html_url: z5.string() }).parse(response.body);
758
- return {
759
- target: "commentOnPullRequest",
760
- repo: repo.ref,
761
- number: input.number,
762
- comment_id: comment.id,
763
- reply: { text: input.body, url: comment.html_url },
764
- url: comment.html_url
765
- };
747
+ throw new Error(message);
766
748
  }
767
- });
768
- }
749
+ const comment = z5.object({ id: z5.number(), html_url: z5.string() }).parse(response.body);
750
+ return {
751
+ target: "commentOnPullRequest",
752
+ repo: repo.ref,
753
+ number: input.number,
754
+ comment_id: comment.id,
755
+ reply: { text: input.body, url: comment.html_url },
756
+ url: comment.html_url
757
+ };
758
+ }
759
+ });
769
760
 
770
761
  // src/object-facts.ts
771
762
  import {
@@ -1309,97 +1300,92 @@ async function createGitHubIssue(ctx, request) {
1309
1300
  url: issue.html_url
1310
1301
  };
1311
1302
  }
1312
- function createGitHubIssueTool(ctx) {
1313
- return definePluginTool5({
1314
- annotations: {
1315
- destructiveHint: false,
1316
- idempotentHint: true,
1317
- openWorldHint: true,
1318
- readOnlyHint: false
1319
- },
1320
- description: "Create a GitHub issue with a runtime-owned conversation footer. Use this instead of shelling out to gh issue create when creating issues.",
1321
- inputSchema: createIssueToolInputSchema,
1322
- outputSchema: gitHubIssueOutputSchema,
1323
- async execute(input, options) {
1324
- const parsedInput = parseCreateIssueInput(input);
1325
- const conversationId = nonEmptyString2(
1326
- ctx.conversationId,
1327
- "conversationId"
1328
- );
1329
- const toolCallId = nonEmptyString2(options?.toolCallId, "toolCallId");
1330
- const key = `createIssue:${conversationId}:${toolCallId}`;
1331
- return await ctx.state.withLock(
1332
- `${key}:lock`,
1333
- GITHUB_ISSUE_CREATE_LOCK_TTL_MS,
1334
- async () => {
1335
- const state = createIssueState(await ctx.state.get(key));
1336
- if (state?.status === "completed") {
1337
- const completedInput = state.input ?? parsedInput;
1338
- const completedResult = {
1339
- facts: state.facts === void 0 ? void 0 : objectFactsSchema.parse(state.facts),
1340
- sourceUpdatedAt: state.sourceUpdatedAt,
1341
- description: state.description,
1342
- number: state.number,
1343
- url: state.url
1344
- };
1345
- return gitHubIssueToolResult(
1346
- completedInput,
1347
- completedResult,
1348
- ctx.events.canSubscribe
1303
+ var gitHubIssueTool = definePluginTool5({
1304
+ annotations: {
1305
+ destructiveHint: false,
1306
+ idempotentHint: true,
1307
+ openWorldHint: true,
1308
+ readOnlyHint: false
1309
+ },
1310
+ description: "Create a GitHub issue with a runtime-owned conversation footer. Use this instead of shelling out to gh issue create when creating issues.",
1311
+ inputSchema: createIssueToolInputSchema,
1312
+ outputSchema: gitHubIssueOutputSchema,
1313
+ async execute(input, options, ctx) {
1314
+ const parsedInput = parseCreateIssueInput(input);
1315
+ const conversationId = nonEmptyString2(ctx.conversationId, "conversationId");
1316
+ const toolCallId = nonEmptyString2(options?.toolCallId, "toolCallId");
1317
+ const key = `createIssue:${conversationId}:${toolCallId}`;
1318
+ return await ctx.state.withLock(
1319
+ `${key}:lock`,
1320
+ GITHUB_ISSUE_CREATE_LOCK_TTL_MS,
1321
+ async () => {
1322
+ const state = createIssueState(await ctx.state.get(key));
1323
+ if (state?.status === "completed") {
1324
+ const completedInput = state.input ?? parsedInput;
1325
+ const completedResult = {
1326
+ facts: state.facts === void 0 ? void 0 : objectFactsSchema.parse(state.facts),
1327
+ sourceUpdatedAt: state.sourceUpdatedAt,
1328
+ description: state.description,
1329
+ number: state.number,
1330
+ url: state.url
1331
+ };
1332
+ return gitHubIssueToolResult(
1333
+ completedInput,
1334
+ completedResult,
1335
+ ctx.events.canSubscribe
1336
+ );
1337
+ }
1338
+ if (state?.status === "pending") {
1339
+ throw new Error(
1340
+ "GitHub issue creation for this tool call has an uncertain pending result; refusing to create a duplicate issue."
1341
+ );
1342
+ }
1343
+ const request = await createGitHubIssueRequest(
1344
+ conversationId,
1345
+ parsedInput,
1346
+ ctx,
1347
+ ctx.conversationLink?.url
1348
+ );
1349
+ const pendingState = {
1350
+ status: "pending",
1351
+ createdAtMs: Date.now(),
1352
+ input: parsedInput
1353
+ };
1354
+ await ctx.state.set(
1355
+ key,
1356
+ pendingState,
1357
+ GITHUB_ISSUE_CREATE_IDEMPOTENCY_TTL_MS
1358
+ );
1359
+ try {
1360
+ const result = await createGitHubIssue(ctx, request);
1361
+ Object.assign(pendingState, { status: "completed", ...result });
1362
+ try {
1363
+ await ctx.state.set(
1364
+ key,
1365
+ pendingState,
1366
+ GITHUB_ISSUE_CREATE_IDEMPOTENCY_TTL_MS
1349
1367
  );
1350
- }
1351
- if (state?.status === "pending") {
1368
+ } catch (error) {
1352
1369
  throw new Error(
1353
- "GitHub issue creation for this tool call has an uncertain pending result; refusing to create a duplicate issue."
1370
+ "GitHub issue was created, but the runtime could not persist the completed issue state.",
1371
+ { cause: error }
1354
1372
  );
1355
1373
  }
1356
- const request = await createGitHubIssueRequest(
1357
- conversationId,
1374
+ return gitHubIssueToolResult(
1358
1375
  parsedInput,
1359
- ctx,
1360
- ctx.conversationLink?.url
1361
- );
1362
- const pendingState = {
1363
- status: "pending",
1364
- createdAtMs: Date.now(),
1365
- input: parsedInput
1366
- };
1367
- await ctx.state.set(
1368
- key,
1369
- pendingState,
1370
- GITHUB_ISSUE_CREATE_IDEMPOTENCY_TTL_MS
1376
+ result,
1377
+ ctx.events.canSubscribe
1371
1378
  );
1372
- try {
1373
- const result = await createGitHubIssue(ctx, request);
1374
- Object.assign(pendingState, { status: "completed", ...result });
1375
- try {
1376
- await ctx.state.set(
1377
- key,
1378
- pendingState,
1379
- GITHUB_ISSUE_CREATE_IDEMPOTENCY_TTL_MS
1380
- );
1381
- } catch (error) {
1382
- throw new Error(
1383
- "GitHub issue was created, but the runtime could not persist the completed issue state.",
1384
- { cause: error }
1385
- );
1386
- }
1387
- return gitHubIssueToolResult(
1388
- parsedInput,
1389
- result,
1390
- ctx.events.canSubscribe
1391
- );
1392
- } catch (error) {
1393
- if (isEgressAuthRequired(error) || isDefinitiveGitHubIssueCreateRejection(error)) {
1394
- await ctx.state.delete(key);
1395
- }
1396
- throw error;
1379
+ } catch (error) {
1380
+ if (isEgressAuthRequired(error) || isDefinitiveGitHubIssueCreateRejection(error)) {
1381
+ await ctx.state.delete(key);
1397
1382
  }
1383
+ throw error;
1398
1384
  }
1399
- );
1400
- }
1401
- });
1402
- }
1385
+ }
1386
+ );
1387
+ }
1388
+ });
1403
1389
 
1404
1390
  // src/tools/get-deployment.ts
1405
1391
  import {
@@ -1480,84 +1466,82 @@ function throwLookupError(target, status, body) {
1480
1466
  }
1481
1467
  throw new Error(message);
1482
1468
  }
1483
- function createGitHubGetDeploymentTool(ctx) {
1484
- return definePluginTool6({
1485
- annotations: {
1486
- destructiveHint: false,
1487
- idempotentHint: true,
1488
- openWorldHint: true,
1489
- readOnlyHint: true
1490
- },
1491
- description: "Get the latest GitHub deployment and status for an exact repository and full commit SHA, optionally limited to one environment. The result remains subscribable when no deployment exists yet, so use it before waiting for a deployment outcome.",
1492
- inputSchema: inputSchema5,
1493
- outputSchema: outputSchema5,
1494
- async execute(input) {
1495
- const repo = parseRepo(input.repo);
1496
- const commitSha = input.commit_sha.toLowerCase();
1497
- const deploymentsQuery = new URLSearchParams({ sha: commitSha });
1498
- if (input.environment) {
1499
- deploymentsQuery.set("environment", input.environment);
1500
- }
1501
- deploymentsQuery.set("per_page", "1");
1502
- const deployments = await githubApi(ctx.egress, {
1503
- operation: "github.deployment.list",
1504
- path: `${repoPath(repo)}/deployments?${deploymentsQuery}`
1469
+ var gitHubGetDeploymentTool = definePluginTool6({
1470
+ annotations: {
1471
+ destructiveHint: false,
1472
+ idempotentHint: true,
1473
+ openWorldHint: true,
1474
+ readOnlyHint: true
1475
+ },
1476
+ description: "Get the latest GitHub deployment and status for an exact repository and full commit SHA, optionally limited to one environment. The result remains subscribable when no deployment exists yet, so use it before waiting for a deployment outcome.",
1477
+ inputSchema: inputSchema5,
1478
+ outputSchema: outputSchema5,
1479
+ async execute(input, _options, ctx) {
1480
+ const repo = parseRepo(input.repo);
1481
+ const commitSha = input.commit_sha.toLowerCase();
1482
+ const deploymentsQuery = new URLSearchParams({ sha: commitSha });
1483
+ if (input.environment) {
1484
+ deploymentsQuery.set("environment", input.environment);
1485
+ }
1486
+ deploymentsQuery.set("per_page", "1");
1487
+ const deployments = await githubApi(ctx.egress, {
1488
+ operation: "github.deployment.list",
1489
+ path: `${repoPath(repo)}/deployments?${deploymentsQuery}`
1490
+ });
1491
+ if (!deployments.ok) {
1492
+ throwLookupError("deployment", deployments.status, deployments.body);
1493
+ }
1494
+ const providerDeployment = z8.array(providerDeploymentSchema).parse(deployments.body)[0];
1495
+ let deployment = null;
1496
+ if (providerDeployment) {
1497
+ const statuses = await githubApi(ctx.egress, {
1498
+ operation: "github.deployment-status.list",
1499
+ path: `${repoPath(repo)}/deployments/${providerDeployment.id}/statuses?per_page=1`
1505
1500
  });
1506
- if (!deployments.ok) {
1507
- throwLookupError("deployment", deployments.status, deployments.body);
1508
- }
1509
- const providerDeployment = z8.array(providerDeploymentSchema).parse(deployments.body)[0];
1510
- let deployment = null;
1511
- if (providerDeployment) {
1512
- const statuses = await githubApi(ctx.egress, {
1513
- operation: "github.deployment-status.list",
1514
- path: `${repoPath(repo)}/deployments/${providerDeployment.id}/statuses?per_page=1`
1515
- });
1516
- if (!statuses.ok) {
1517
- throwLookupError("deployment status", statuses.status, statuses.body);
1518
- }
1519
- const providerStatus = z8.array(providerStatusSchema).parse(statuses.body)[0];
1520
- deployment = {
1521
- created_at: providerDeployment.created_at,
1522
- creator: providerDeployment.creator?.login ?? null,
1523
- description: providerDeployment.description,
1524
- environment: providerDeployment.environment,
1525
- id: providerDeployment.id,
1526
- latest_status: providerStatus ? {
1527
- created_at: providerStatus.created_at,
1528
- creator: providerStatus.creator?.login ?? null,
1529
- description: providerStatus.description ?? null,
1530
- environment_url: providerStatus.environment_url ?? null,
1531
- id: providerStatus.id,
1532
- log_url: providerStatus.log_url ?? null,
1533
- state: providerStatus.state
1534
- } : null,
1535
- ref: providerDeployment.ref,
1536
- sha: providerDeployment.sha.toLowerCase(),
1537
- updated_at: providerDeployment.updated_at,
1538
- url: `https://github.com/${repo.ref}/deployments`
1539
- };
1501
+ if (!statuses.ok) {
1502
+ throwLookupError("deployment status", statuses.status, statuses.body);
1540
1503
  }
1541
- const subscribable = gitHubDeploymentSourceSubscribable({
1542
- canSubscribe: ctx.events.canSubscribe,
1543
- commitSha,
1544
- environment: input.environment,
1545
- repo: repo.ref
1546
- });
1547
- const data = {
1548
- commit_sha: commitSha,
1549
- deployment,
1550
- environment: input.environment ?? null,
1551
- repo: repo.ref,
1552
- ...subscribable ? { subscribable } : void 0
1553
- };
1554
- return {
1555
- target: "getDeployment",
1556
- ...data
1504
+ const providerStatus = z8.array(providerStatusSchema).parse(statuses.body)[0];
1505
+ deployment = {
1506
+ created_at: providerDeployment.created_at,
1507
+ creator: providerDeployment.creator?.login ?? null,
1508
+ description: providerDeployment.description,
1509
+ environment: providerDeployment.environment,
1510
+ id: providerDeployment.id,
1511
+ latest_status: providerStatus ? {
1512
+ created_at: providerStatus.created_at,
1513
+ creator: providerStatus.creator?.login ?? null,
1514
+ description: providerStatus.description ?? null,
1515
+ environment_url: providerStatus.environment_url ?? null,
1516
+ id: providerStatus.id,
1517
+ log_url: providerStatus.log_url ?? null,
1518
+ state: providerStatus.state
1519
+ } : null,
1520
+ ref: providerDeployment.ref,
1521
+ sha: providerDeployment.sha.toLowerCase(),
1522
+ updated_at: providerDeployment.updated_at,
1523
+ url: `https://github.com/${repo.ref}/deployments`
1557
1524
  };
1558
1525
  }
1559
- });
1560
- }
1526
+ const subscribable = gitHubDeploymentSourceSubscribable({
1527
+ canSubscribe: ctx.events.canSubscribe,
1528
+ commitSha,
1529
+ environment: input.environment,
1530
+ repo: repo.ref
1531
+ });
1532
+ const data = {
1533
+ commit_sha: commitSha,
1534
+ deployment,
1535
+ environment: input.environment ?? null,
1536
+ repo: repo.ref,
1537
+ ...subscribable ? { subscribable } : void 0
1538
+ };
1539
+ return {
1540
+ target: "getDeployment",
1541
+ ...data
1542
+ };
1543
+ }
1544
+ });
1561
1545
 
1562
1546
  // src/tools/get-issue.ts
1563
1547
  import {
@@ -1589,7 +1573,7 @@ var outputSchema6 = pluginToolOutputSchema7.merge(
1589
1573
  issueSchema.extend({ target: z9.literal("getIssue") })
1590
1574
  );
1591
1575
  var providerIssueSchema = z9.object({
1592
- assignees: z9.array(z9.object({ login: z9.string() })).nullish().transform((assignees) => assignees?.map(({ login: login2 }) => login2) ?? []),
1576
+ assignees: z9.array(z9.object({ login: z9.string() })).nullish().transform((assignees) => assignees?.map(({ login }) => login) ?? []),
1593
1577
  body: z9.string().nullable().optional().default(null),
1594
1578
  comments: z9.number().optional().default(0),
1595
1579
  html_url: z9.string(),
@@ -1600,71 +1584,69 @@ var providerIssueSchema = z9.object({
1600
1584
  title: z9.string(),
1601
1585
  user: z9.object({ login: z9.string() }).nullish()
1602
1586
  });
1603
- function createGitHubGetIssueTool(ctx) {
1604
- return definePluginTool7({
1605
- annotations: {
1606
- destructiveHint: false,
1607
- idempotentHint: true,
1608
- openWorldHint: true,
1609
- readOnlyHint: true
1610
- },
1611
- description: "Get a GitHub issue. Read its comments with gh api repos/OWNER/REPO/issues/NUMBER/comments.",
1612
- inputSchema: inputSchema6,
1613
- outputSchema: outputSchema6,
1614
- async execute(input) {
1615
- const repo = parseRepo(input.repo);
1616
- const [response, requester] = await Promise.all([
1617
- githubApi(ctx.egress, {
1618
- followRedirects: true,
1619
- operation: "github.issue.get",
1620
- path: `${repoPath(repo)}/issues/${input.number}`
1621
- }),
1622
- resolveGitHubRequester(ctx)
1623
- ]);
1624
- if (!response.ok) {
1625
- const message = `GitHub issue lookup failed with HTTP ${response.status}`;
1626
- if (response.status === 404) {
1627
- throw new PluginToolInputError9(message);
1628
- }
1629
- throw new Error(message);
1630
- }
1631
- const issue = providerIssueSchema.parse(response.body);
1632
- const repoRef = issueRepoRef(issue.repository_url) ?? repo.ref;
1633
- const login2 = linkedGitHubLogin(requester?.user)?.toLowerCase();
1634
- const needsClaim = login2 !== void 0 && issue.state === "open" && !issue.assignees.some((assignee) => assignee.toLowerCase() === login2);
1635
- const subscribable = gitHubIssueSubscribable({
1636
- canSubscribe: ctx.events.canSubscribe,
1637
- number: issue.number,
1638
- repo: repoRef
1639
- });
1640
- return {
1641
- objectAnnotations: [
1642
- githubObjectAnnotation({
1643
- ...githubObjectFacts("task", response.body),
1644
- repo: repoRef,
1645
- number: issue.number,
1646
- title: issue.title,
1647
- url: issue.html_url,
1648
- objectType: "task",
1649
- status: issue.state
1650
- })
1651
- ],
1652
- target: "getIssue",
1653
- assignees: issue.assignees,
1654
- ...issue.user ? { author: issue.user.login } : void 0,
1655
- body: issue.body,
1656
- comments: issue.comments,
1657
- labels: issue.labels,
1658
- ...needsClaim ? { note: CLAIM_NOTE } : void 0,
1659
- number: issue.number,
1660
- state: issue.state,
1661
- ...subscribable ? { subscribable } : void 0,
1662
- title: issue.title,
1663
- url: issue.html_url
1664
- };
1587
+ var gitHubGetIssueTool = definePluginTool7({
1588
+ annotations: {
1589
+ destructiveHint: false,
1590
+ idempotentHint: true,
1591
+ openWorldHint: true,
1592
+ readOnlyHint: true
1593
+ },
1594
+ description: "Get a GitHub issue. Read its comments with gh api repos/OWNER/REPO/issues/NUMBER/comments.",
1595
+ inputSchema: inputSchema6,
1596
+ outputSchema: outputSchema6,
1597
+ async execute(input, _options, ctx) {
1598
+ const repo = parseRepo(input.repo);
1599
+ const [response, requester] = await Promise.all([
1600
+ githubApi(ctx.egress, {
1601
+ followRedirects: true,
1602
+ operation: "github.issue.get",
1603
+ path: `${repoPath(repo)}/issues/${input.number}`
1604
+ }),
1605
+ resolveGitHubRequester(ctx)
1606
+ ]);
1607
+ if (!response.ok) {
1608
+ const message = `GitHub issue lookup failed with HTTP ${response.status}`;
1609
+ if (response.status === 404) {
1610
+ throw new PluginToolInputError9(message);
1611
+ }
1612
+ throw new Error(message);
1665
1613
  }
1666
- });
1667
- }
1614
+ const issue = providerIssueSchema.parse(response.body);
1615
+ const repoRef = issueRepoRef(issue.repository_url) ?? repo.ref;
1616
+ const login = linkedGitHubLogin(requester?.user)?.toLowerCase();
1617
+ const needsClaim = login !== void 0 && issue.state === "open" && !issue.assignees.some((assignee) => assignee.toLowerCase() === login);
1618
+ const subscribable = gitHubIssueSubscribable({
1619
+ canSubscribe: ctx.events.canSubscribe,
1620
+ number: issue.number,
1621
+ repo: repoRef
1622
+ });
1623
+ return {
1624
+ objectAnnotations: [
1625
+ githubObjectAnnotation({
1626
+ ...githubObjectFacts("task", response.body),
1627
+ repo: repoRef,
1628
+ number: issue.number,
1629
+ title: issue.title,
1630
+ url: issue.html_url,
1631
+ objectType: "task",
1632
+ status: issue.state
1633
+ })
1634
+ ],
1635
+ target: "getIssue",
1636
+ assignees: issue.assignees,
1637
+ ...issue.user ? { author: issue.user.login } : void 0,
1638
+ body: issue.body,
1639
+ comments: issue.comments,
1640
+ labels: issue.labels,
1641
+ ...needsClaim ? { note: CLAIM_NOTE } : void 0,
1642
+ number: issue.number,
1643
+ state: issue.state,
1644
+ ...subscribable ? { subscribable } : void 0,
1645
+ title: issue.title,
1646
+ url: issue.html_url
1647
+ };
1648
+ }
1649
+ });
1668
1650
  function issueRepoRef(repositoryUrl) {
1669
1651
  const url = repositoryUrl ? URL.parse(repositoryUrl) : null;
1670
1652
  if (url?.origin !== "https://api.github.com" || url.search || url.hash) {
@@ -1775,13 +1757,13 @@ var juniorGitHubPullRequests = pgTable(
1775
1757
  closedAt: timestamp("closed_at", { withTimezone: true }),
1776
1758
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
1777
1759
  /**
1778
- * When Junior saw the pull request become ready to merge and added its
1779
- * review desk notice. Null when it is not ready.
1760
+ * The requester's next action that Junior last derived from GitHub, and
1761
+ * shows on the review desk. Null when no action waits on them.
1780
1762
  */
1781
- readyToMergeAt: timestamp("ready_to_merge_at", { withTimezone: true }),
1763
+ nextAction: text("next_action").$type(),
1782
1764
  /**
1783
- * Webhooks that asked to check whether the pull request is ready to
1784
- * merge. The check runs again when this changes during a check.
1765
+ * Webhooks that asked to check the next action. The check runs again
1766
+ * when this changes during a check.
1785
1767
  */
1786
1768
  readySyncRequests: integer("ready_sync_requests").notNull().default(0),
1787
1769
  /**
@@ -2280,11 +2262,11 @@ async function assignPullRequestRequester(ctx, input, result, requester) {
2280
2262
  }
2281
2263
  function namedReviewers(input) {
2282
2264
  return input.reviewers?.map((value) => {
2283
- const login2 = parseGitHubLogin(value);
2284
- if (!login2) {
2265
+ const login = parseGitHubLogin(value);
2266
+ if (!login) {
2285
2267
  throw new PluginToolInputError11(`Invalid GitHub reviewer login: ${value}`);
2286
2268
  }
2287
- return login2;
2269
+ return login;
2288
2270
  });
2289
2271
  }
2290
2272
  async function saveNamedDraftReviewers(ctx, input, number33) {
@@ -2407,7 +2389,7 @@ async function gitHubPullRequestStructuredResult(ctx, input, result, subscriptio
2407
2389
  };
2408
2390
  }
2409
2391
  }
2410
- function createGitHubPullRequestTool(ctx, subscriptionConfig, descriptionDecider) {
2392
+ function createGitHubPullRequestTool(subscriptionConfig, descriptionChecks = false) {
2411
2393
  return definePluginTool8({
2412
2394
  annotations: {
2413
2395
  destructiveHint: false,
@@ -2419,7 +2401,7 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig, descriptionDecider
2419
2401
  exposure: "direct",
2420
2402
  inputSchema: createPullRequestToolInputSchema,
2421
2403
  outputSchema: gitHubPullRequestOutputSchema,
2422
- async execute(input, options) {
2404
+ async execute(input, options, ctx) {
2423
2405
  const parsedInput = parseCreatePullRequestInput(input);
2424
2406
  namedReviewers(parsedInput);
2425
2407
  const conversationId = nonEmptyString3(
@@ -2459,9 +2441,9 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig, descriptionDecider
2459
2441
  "GitHub pull request creation for this tool call has an uncertain pending result; refusing to create a duplicate pull request."
2460
2442
  );
2461
2443
  }
2462
- if (descriptionDecider) {
2444
+ if (descriptionChecks) {
2463
2445
  await checkPullRequestDescription(
2464
- descriptionDecider,
2446
+ ctx.decider,
2465
2447
  parsedInput.body ?? ""
2466
2448
  );
2467
2449
  }
@@ -2539,14 +2521,9 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig, descriptionDecider
2539
2521
  });
2540
2522
  }
2541
2523
 
2542
- // src/tools/get-pull-request.ts
2543
- import {
2544
- definePluginTool as definePluginTool9,
2545
- PluginToolInputError as PluginToolInputError12,
2546
- pluginToolOutputSchema as pluginToolOutputSchema9
2547
- } from "@sentry/junior-plugin-api";
2524
+ // src/draft-readiness.ts
2525
+ import ignore from "ignore";
2548
2526
  import * as z14 from "zod";
2549
- import { subscribableResourceSchema as subscribableResourceSchema5 } from "@sentry/junior-plugin-api";
2550
2527
 
2551
2528
  // src/graphql-documents.ts
2552
2529
  import {
@@ -2665,12 +2642,61 @@ var PULL_REQUEST_CHECKS = githubGraphql(`
2665
2642
  }
2666
2643
  }
2667
2644
  `);
2645
+ var PULL_REQUEST_DRAFT_READINESS = githubGraphql(`
2646
+ query PullRequestDraftReadiness(
2647
+ $owner: String!
2648
+ $name: String!
2649
+ $number: Int!
2650
+ $githubExpression: String!
2651
+ $rootExpression: String!
2652
+ $docsExpression: String!
2653
+ $agentsExpression: String!
2654
+ $after: String
2655
+ ) {
2656
+ repository(owner: $owner, name: $name) {
2657
+ github: object(expression: $githubExpression) { ... on Blob { text } }
2658
+ root: object(expression: $rootExpression) { ... on Blob { text } }
2659
+ docs: object(expression: $docsExpression) { ... on Blob { text } }
2660
+ agents: object(expression: $agentsExpression) { ... on Blob { text } }
2661
+ pullRequest(number: $number) {
2662
+ files(first: 100, after: $after) {
2663
+ pageInfo { hasNextPage endCursor }
2664
+ nodes { path }
2665
+ }
2666
+ }
2667
+ }
2668
+ }
2669
+ `);
2668
2670
  var OPEN_PULL_REQUEST_MERGEABILITY = githubGraphql(`
2669
2671
  query OpenPullRequestMergeability($query: String!, $after: String) {
2670
2672
  search(query: $query, type: ISSUE, first: 100, after: $after) {
2671
2673
  pageInfo { hasNextPage endCursor }
2672
2674
  nodes {
2673
- ... on PullRequest { number state mergeable headRefOid baseRefName url }
2675
+ ... on PullRequest { number state isDraft mergeable headRefOid baseRefName title url }
2676
+ }
2677
+ }
2678
+ }
2679
+ `);
2680
+ var PULL_REQUEST_CONFLICT_HISTORY = githubGraphql(`
2681
+ query PullRequestConflictHistory($owner: String!, $name: String!, $number: Int!) {
2682
+ repository(owner: $owner, name: $name) {
2683
+ pullRequest(number: $number) {
2684
+ createdAt
2685
+ reviewDecision
2686
+ pushes: timelineItems(last: 100, itemTypes: [PULL_REQUEST_COMMIT, HEAD_REF_FORCE_PUSHED_EVENT]) {
2687
+ nodes {
2688
+ __typename
2689
+ ... on PullRequestCommit { commit { committedDate parents { totalCount } author { user { login } } } }
2690
+ ... on HeadRefForcePushedEvent { createdAt actor { __typename } }
2691
+ }
2692
+ }
2693
+ discussion: timelineItems(last: 50, itemTypes: [PULL_REQUEST_REVIEW, ISSUE_COMMENT]) {
2694
+ nodes {
2695
+ __typename
2696
+ ... on PullRequestReview { submittedAt author { __typename } }
2697
+ ... on IssueComment { createdAt author { __typename } }
2698
+ }
2699
+ }
2674
2700
  }
2675
2701
  }
2676
2702
  }
@@ -2734,84 +2760,213 @@ function pullRequestLifecycles(count) {
2734
2760
  );
2735
2761
  }
2736
2762
 
2763
+ // src/draft-readiness.ts
2764
+ function parseCodeOwners(text2) {
2765
+ const rules = [];
2766
+ for (const line of text2.split(/\r?\n/)) {
2767
+ const [pattern, ...tokens] = line.trim().split(/\s+/);
2768
+ if (!pattern || pattern.startsWith("#")) continue;
2769
+ const comment = tokens.findIndex((token) => token.startsWith("#"));
2770
+ const matcher = ignore().add(pattern);
2771
+ rules.push({
2772
+ matches: (path) => matcher.ignores(path),
2773
+ owners: comment === -1 ? tokens : tokens.slice(0, comment)
2774
+ });
2775
+ }
2776
+ return rules;
2777
+ }
2778
+ function codeOwnersOf(rules, paths) {
2779
+ const owners = /* @__PURE__ */ new Set();
2780
+ for (const path of paths) {
2781
+ let last;
2782
+ for (const rule of rules) if (rule.matches(path)) last = rule;
2783
+ for (const owner of last?.owners ?? []) owners.add(owner);
2784
+ }
2785
+ return [...owners].sort();
2786
+ }
2787
+ var CODE_OWNERS_PATHS = {
2788
+ githubExpression: ".github/CODEOWNERS",
2789
+ rootExpression: "CODEOWNERS",
2790
+ docsExpression: "docs/CODEOWNERS"
2791
+ };
2792
+ var blobSchema = z14.object({ text: z14.string().nullish() }).nullable();
2793
+ var responseSchema2 = z14.object({
2794
+ data: z14.object({
2795
+ repository: z14.object({
2796
+ github: blobSchema,
2797
+ root: blobSchema,
2798
+ docs: blobSchema,
2799
+ agents: blobSchema,
2800
+ pullRequest: z14.object({
2801
+ files: z14.object({
2802
+ nodes: z14.array(z14.object({ path: z14.string() })),
2803
+ pageInfo: z14.object({
2804
+ endCursor: z14.string().nullable(),
2805
+ hasNextPage: z14.boolean()
2806
+ })
2807
+ }).nullable()
2808
+ })
2809
+ })
2810
+ })
2811
+ });
2812
+ async function readDraftReadiness(egress, repo, pullRequest) {
2813
+ const expressions = Object.fromEntries(
2814
+ Object.entries({ ...CODE_OWNERS_PATHS, agentsExpression: "AGENTS.md" }).map(
2815
+ ([key, path]) => [key, `${pullRequest.base}:${path}`]
2816
+ )
2817
+ );
2818
+ const paths = [];
2819
+ let codeOwners;
2820
+ let agentsMd;
2821
+ let after = null;
2822
+ do {
2823
+ const response = await githubApi(egress, {
2824
+ operation: "github.pull.draft_readiness.get",
2825
+ method: "POST",
2826
+ path: "/graphql",
2827
+ body: {
2828
+ ...PULL_REQUEST_DRAFT_READINESS,
2829
+ variables: {
2830
+ ...expressions,
2831
+ after,
2832
+ name: repo.name,
2833
+ number: pullRequest.number,
2834
+ owner: repo.owner
2835
+ }
2836
+ }
2837
+ });
2838
+ if (!response.ok) {
2839
+ throw new Error(
2840
+ `GitHub pull request code owners lookup failed with HTTP ${response.status}`
2841
+ );
2842
+ }
2843
+ const repository2 = responseSchema2.parse(response.body).data.repository;
2844
+ codeOwners ??= repository2.github?.text ?? repository2.root?.text ?? repository2.docs?.text ?? void 0;
2845
+ agentsMd ??= repository2.agents?.text ?? void 0;
2846
+ const files = repository2.pullRequest.files;
2847
+ if (!files) {
2848
+ if (codeOwners) {
2849
+ throw new Error(
2850
+ "GitHub did not list the changed files of the pull request"
2851
+ );
2852
+ }
2853
+ break;
2854
+ }
2855
+ paths.push(...files.nodes.map((file) => file.path));
2856
+ after = files.pageInfo.hasNextPage ? files.pageInfo.endCursor : null;
2857
+ } while (after);
2858
+ return {
2859
+ ...agentsMd ? { agentsMd } : void 0,
2860
+ codeOwners: codeOwners ? codeOwnersOf(parseCodeOwners(codeOwners), paths) : []
2861
+ };
2862
+ }
2863
+
2737
2864
  // src/tools/get-pull-request.ts
2738
- var commitShaSchema2 = z14.string().regex(/^[0-9a-f]{40}$/i);
2739
- var inputSchema7 = z14.object({
2740
- repo: z14.string().describe('Repository in "owner/name" format.'),
2741
- number: z14.number().int().positive().describe("Pull request number.")
2865
+ import {
2866
+ definePluginTool as definePluginTool9,
2867
+ PluginToolInputError as PluginToolInputError12,
2868
+ pluginToolOutputSchema as pluginToolOutputSchema9
2869
+ } from "@sentry/junior-plugin-api";
2870
+ import * as z15 from "zod";
2871
+ import { subscribableResourceSchema as subscribableResourceSchema5 } from "@sentry/junior-plugin-api";
2872
+ var commitShaSchema2 = z15.string().regex(/^[0-9a-f]{40}$/i);
2873
+ var RELATED_CONVERSATIONS_MAX = 10;
2874
+ var SUMMARY_MAX_LENGTH = 300;
2875
+ var inputSchema7 = z15.object({
2876
+ repo: z15.string().describe('Repository in "owner/name" format.'),
2877
+ number: z15.number().int().positive().describe("Pull request number.")
2742
2878
  }).strict();
2743
- var checksSchema = z14.object({
2744
- required: z14.enum(["passing", "failing", "pending", "not_reported"]).describe(
2879
+ var checksSchema = z15.object({
2880
+ required: z15.enum(["passing", "failing", "pending", "not_reported"]).describe(
2745
2881
  "State of the required checks on the head commit. not_reported means no required check has reported yet; it does not mean that none are required."
2746
2882
  ),
2747
- failing: z14.array(z14.string()).describe("Required checks that failed."),
2748
- pending: z14.array(z14.string()).describe("Required checks that have not finished."),
2749
- passing: z14.array(z14.string()).describe("Required checks that passed."),
2750
- incomplete: z14.literal(true).optional().describe(
2883
+ failing: z15.array(z15.string()).describe("Required checks that failed."),
2884
+ pending: z15.array(z15.string()).describe("Required checks that have not finished."),
2885
+ passing: z15.array(z15.string()).describe("Required checks that passed."),
2886
+ incomplete: z15.literal(true).optional().describe(
2751
2887
  "Set when the head commit has more than 100 checks, so some required checks are not listed."
2752
2888
  ),
2753
- merge_state: z14.string().describe(
2889
+ merge_state: z15.string().describe(
2754
2890
  "GitHub mergeStateStatus, such as CLEAN, BLOCKED, BEHIND, DIRTY, UNSTABLE, DRAFT, or UNKNOWN. BLOCKED while the listed required checks pass means a required check that has not started, a review, or another rule blocks the merge."
2755
2891
  ),
2756
- review_decision: z14.string().nullable().describe(
2892
+ review_decision: z15.string().nullable().describe(
2757
2893
  "GitHub reviewDecision: APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED, or null when no review is required."
2758
2894
  ),
2759
- auto_merge: z14.boolean().describe("true when auto-merge is on for the pull request.")
2895
+ auto_merge: z15.boolean().describe("true when auto-merge is on for the pull request.")
2760
2896
  });
2761
- var pullRequestSchema = z14.object({
2762
- base: z14.string(),
2897
+ var relatedConversationSchema = z15.object({
2898
+ conversation_id: z15.string(),
2899
+ root_conversation_id: z15.string().optional().describe("Root of a child agent."),
2900
+ status: z15.enum(["pending", "running", "paused", "idle"]).describe(
2901
+ "What its agent does now. pending: waiting to run. running or paused: working. idle: waits for a message."
2902
+ ),
2903
+ title: z15.string().optional(),
2904
+ summary: z15.string().optional().describe("Summary from the latest Brief."),
2905
+ updated_at: z15.string().describe("Time of the latest activity.")
2906
+ });
2907
+ var pullRequestSchema = z15.object({
2908
+ base: z15.string(),
2909
+ agents_md: z15.string().optional().describe(
2910
+ "Draft only: the root AGENTS.md of the base branch, when it has one."
2911
+ ),
2763
2912
  checks: checksSchema,
2764
- draft: z14.boolean(),
2765
- head: z14.string(),
2913
+ code_owners: z15.array(z15.string()).optional().describe(
2914
+ "Draft only: the CODEOWNERS owners of the changed files. GitHub asks them to review when the pull request is marked ready for review."
2915
+ ),
2916
+ draft: z15.boolean(),
2917
+ head: z15.string(),
2766
2918
  head_sha: commitShaSchema2,
2767
- merged: z14.boolean(),
2768
- number: z14.number(),
2769
- state: z14.string(),
2919
+ merged: z15.boolean(),
2920
+ number: z15.number(),
2921
+ related_conversations: z15.array(relatedConversationSchema).optional().describe(
2922
+ "Other conversations that touched this pull request, working ones first. While one is working, do not push to or comment on the pull request; first messageAgent its root (root_conversation_id, else conversation_id)."
2923
+ ),
2924
+ state: z15.string(),
2770
2925
  subscribable: subscribableResourceSchema5.optional(),
2771
- title: z14.string(),
2772
- url: z14.string()
2926
+ title: z15.string(),
2927
+ url: z15.string()
2773
2928
  });
2774
2929
  var outputSchema7 = pluginToolOutputSchema9.merge(
2775
2930
  pullRequestSchema.extend({
2776
- target: z14.literal("getPullRequest")
2931
+ target: z15.literal("getPullRequest")
2777
2932
  })
2778
2933
  );
2779
- var checkContextSchema = z14.union([
2780
- z14.object({
2781
- __typename: z14.literal("CheckRun"),
2782
- conclusion: z14.string().nullable(),
2783
- isRequired: z14.boolean(),
2784
- name: z14.string(),
2785
- status: z14.string()
2934
+ var checkContextSchema = z15.union([
2935
+ z15.object({
2936
+ __typename: z15.literal("CheckRun"),
2937
+ conclusion: z15.string().nullable(),
2938
+ isRequired: z15.boolean(),
2939
+ name: z15.string(),
2940
+ status: z15.string()
2786
2941
  }),
2787
- z14.object({
2788
- __typename: z14.literal("StatusContext"),
2789
- context: z14.string(),
2790
- isRequired: z14.boolean(),
2791
- state: z14.string()
2942
+ z15.object({
2943
+ __typename: z15.literal("StatusContext"),
2944
+ context: z15.string(),
2945
+ isRequired: z15.boolean(),
2946
+ state: z15.string()
2792
2947
  })
2793
2948
  ]);
2794
- var checksResponseSchema = z14.object({
2795
- data: z14.object({
2796
- repository: z14.object({
2797
- pullRequest: z14.object({
2798
- autoMergeRequest: z14.object({}).passthrough().nullable(),
2799
- commits: z14.object({
2800
- nodes: z14.array(
2801
- z14.object({
2802
- commit: z14.object({
2803
- statusCheckRollup: z14.object({
2804
- contexts: z14.object({
2805
- nodes: z14.array(checkContextSchema),
2806
- pageInfo: z14.object({ hasNextPage: z14.boolean() })
2949
+ var checksResponseSchema = z15.object({
2950
+ data: z15.object({
2951
+ repository: z15.object({
2952
+ pullRequest: z15.object({
2953
+ autoMergeRequest: z15.object({}).passthrough().nullable(),
2954
+ commits: z15.object({
2955
+ nodes: z15.array(
2956
+ z15.object({
2957
+ commit: z15.object({
2958
+ statusCheckRollup: z15.object({
2959
+ contexts: z15.object({
2960
+ nodes: z15.array(checkContextSchema),
2961
+ pageInfo: z15.object({ hasNextPage: z15.boolean() })
2807
2962
  })
2808
2963
  }).nullable()
2809
2964
  })
2810
2965
  })
2811
2966
  )
2812
2967
  }),
2813
- mergeStateStatus: z14.string(),
2814
- reviewDecision: z14.string().nullable()
2968
+ mergeStateStatus: z15.string(),
2969
+ reviewDecision: z15.string().nullable()
2815
2970
  })
2816
2971
  })
2817
2972
  })
@@ -2858,81 +3013,102 @@ async function readPullRequestChecks(egress, repo, number33) {
2858
3013
  auto_merge: pullRequest.autoMergeRequest !== null
2859
3014
  };
2860
3015
  }
2861
- function createGitHubGetPullRequestTool(ctx) {
2862
- return definePluginTool9({
2863
- annotations: {
2864
- destructiveHint: false,
2865
- idempotentHint: true,
2866
- openWorldHint: true,
2867
- readOnlyHint: true
2868
- },
2869
- description: "Get a GitHub pull request with its required checks and merge state. Use this when an existing PR may need event monitoring; the result includes a subscribable hint when GitHub webhooks are configured.",
2870
- inputSchema: inputSchema7,
2871
- outputSchema: outputSchema7,
2872
- async execute(input) {
2873
- const repo = parseRepo(input.repo);
2874
- const response = await githubApi(ctx.egress, {
2875
- operation: "github.pull.get",
2876
- path: `${repoPath(repo)}/pulls/${input.number}`
2877
- });
2878
- if (!response.ok) {
2879
- const message = `GitHub pull request lookup failed with HTTP ${response.status}`;
2880
- if (response.status === 404) {
2881
- throw new PluginToolInputError12(message);
2882
- }
2883
- throw new Error(message);
3016
+ function truncate(text2, maxLength) {
3017
+ return text2.length > maxLength ? `${text2.slice(0, maxLength)}\u2026` : text2;
3018
+ }
3019
+ async function readRelatedConversations(conversations, annotation) {
3020
+ if (!conversations) return [];
3021
+ const matches = await conversations.search({
3022
+ annotation,
3023
+ limit: RELATED_CONVERSATIONS_MAX
3024
+ });
3025
+ return matches.map((match) => ({
3026
+ conversation_id: match.conversationId,
3027
+ ...match.rootConversationId ? { root_conversation_id: match.rootConversationId } : void 0,
3028
+ status: match.status,
3029
+ ...match.title ? { title: match.title } : void 0,
3030
+ ...match.summary ? { summary: truncate(match.summary, SUMMARY_MAX_LENGTH) } : void 0,
3031
+ updated_at: match.updatedAt
3032
+ }));
3033
+ }
3034
+ var gitHubGetPullRequestTool = definePluginTool9({
3035
+ annotations: {
3036
+ destructiveHint: false,
3037
+ idempotentHint: true,
3038
+ openWorldHint: true,
3039
+ readOnlyHint: true
3040
+ },
3041
+ description: "Get a GitHub pull request with its required checks, merge state, and other conversations that touched it, and for a draft, what to check before marking it ready. Use this when an existing PR may need event monitoring; the result includes a subscribable hint when GitHub webhooks are configured.",
3042
+ inputSchema: inputSchema7,
3043
+ outputSchema: outputSchema7,
3044
+ async execute(input, _options, ctx) {
3045
+ const repo = parseRepo(input.repo);
3046
+ const response = await githubApi(ctx.egress, {
3047
+ operation: "github.pull.get",
3048
+ path: `${repoPath(repo)}/pulls/${input.number}`
3049
+ });
3050
+ if (!response.ok) {
3051
+ const message = `GitHub pull request lookup failed with HTTP ${response.status}`;
3052
+ if (response.status === 404) {
3053
+ throw new PluginToolInputError12(message);
2884
3054
  }
2885
- const providerResult = z14.object({
2886
- base: z14.object({ ref: z14.string() }),
2887
- draft: z14.boolean(),
2888
- head: z14.object({ ref: z14.string(), sha: commitShaSchema2 }),
2889
- html_url: z14.string(),
2890
- merged: z14.boolean().optional().default(false),
2891
- number: z14.number(),
2892
- state: z14.string(),
2893
- title: z14.string()
2894
- }).parse(response.body);
2895
- const checks = await readPullRequestChecks(
2896
- ctx.egress,
2897
- repo,
2898
- providerResult.number
2899
- );
2900
- const subscribable = gitHubPullRequestSubscribable({
2901
- canSubscribe: ctx.events.canSubscribe,
2902
- number: providerResult.number,
2903
- repo: repo.ref
2904
- });
2905
- const data = {
2906
- base: providerResult.base.ref,
2907
- checks,
2908
- draft: providerResult.draft,
2909
- head: providerResult.head.ref,
2910
- head_sha: providerResult.head.sha.toLowerCase(),
2911
- merged: providerResult.merged,
2912
- number: providerResult.number,
2913
- state: providerResult.state,
2914
- ...subscribable ? { subscribable } : void 0,
2915
- title: providerResult.title,
2916
- url: providerResult.html_url
2917
- };
2918
- return {
2919
- objectAnnotations: [
2920
- githubObjectAnnotation({
2921
- repo: repo.ref,
2922
- number: data.number,
2923
- title: data.title,
2924
- url: data.url,
2925
- objectType: "code_change",
2926
- status: data.merged ? "merged" : data.state === "open" && data.draft ? "draft" : data.state,
2927
- ...githubObjectFacts("code_change", response.body)
2928
- })
2929
- ],
2930
- target: "getPullRequest",
2931
- ...data
2932
- };
3055
+ throw new Error(message);
2933
3056
  }
2934
- });
2935
- }
3057
+ const providerResult = z15.object({
3058
+ base: z15.object({ ref: z15.string() }),
3059
+ draft: z15.boolean(),
3060
+ head: z15.object({ ref: z15.string(), sha: commitShaSchema2 }),
3061
+ html_url: z15.string(),
3062
+ merged: z15.boolean().optional().default(false),
3063
+ number: z15.number(),
3064
+ state: z15.string(),
3065
+ title: z15.string()
3066
+ }).parse(response.body);
3067
+ const annotation = githubObjectAnnotation({
3068
+ repo: repo.ref,
3069
+ number: providerResult.number,
3070
+ title: providerResult.title,
3071
+ url: providerResult.html_url,
3072
+ objectType: "code_change",
3073
+ status: providerResult.merged ? "merged" : providerResult.state === "open" && providerResult.draft ? "draft" : providerResult.state,
3074
+ ...githubObjectFacts("code_change", response.body)
3075
+ });
3076
+ const [checks, relatedConversations] = await Promise.all([
3077
+ readPullRequestChecks(ctx.egress, repo, providerResult.number),
3078
+ readRelatedConversations(ctx.conversations, annotation.key)
3079
+ ]);
3080
+ const readiness = providerResult.draft && providerResult.state === "open" ? await readDraftReadiness(ctx.egress, repo, {
3081
+ base: providerResult.base.ref,
3082
+ number: providerResult.number
3083
+ }) : void 0;
3084
+ const subscribable = gitHubPullRequestSubscribable({
3085
+ canSubscribe: ctx.events.canSubscribe,
3086
+ number: providerResult.number,
3087
+ repo: repo.ref
3088
+ });
3089
+ const data = {
3090
+ base: providerResult.base.ref,
3091
+ ...readiness?.agentsMd ? { agents_md: readiness.agentsMd } : void 0,
3092
+ checks,
3093
+ ...readiness ? { code_owners: readiness.codeOwners } : void 0,
3094
+ draft: providerResult.draft,
3095
+ head: providerResult.head.ref,
3096
+ head_sha: providerResult.head.sha.toLowerCase(),
3097
+ merged: providerResult.merged,
3098
+ number: providerResult.number,
3099
+ ...relatedConversations.length > 0 ? { related_conversations: relatedConversations } : void 0,
3100
+ state: providerResult.state,
3101
+ ...subscribable ? { subscribable } : void 0,
3102
+ title: providerResult.title,
3103
+ url: providerResult.html_url
3104
+ };
3105
+ return {
3106
+ objectAnnotations: [annotation],
3107
+ target: "getPullRequest",
3108
+ ...data
3109
+ };
3110
+ }
3111
+ });
2936
3112
 
2937
3113
  // src/tools/get-release.ts
2938
3114
  import {
@@ -2940,45 +3116,45 @@ import {
2940
3116
  pluginToolOutputSchema as pluginToolOutputSchema10,
2941
3117
  subscribableResourceSchema as subscribableResourceSchema6
2942
3118
  } from "@sentry/junior-plugin-api";
2943
- import * as z15 from "zod";
2944
- var inputSchema8 = z15.object({
2945
- repo: z15.string().describe('Repository in "owner/name" format.'),
2946
- tag: z15.string().trim().min(1).describe(
3119
+ import * as z16 from "zod";
3120
+ var inputSchema8 = z16.object({
3121
+ repo: z16.string().describe('Repository in "owner/name" format.'),
3122
+ tag: z16.string().trim().min(1).describe(
2947
3123
  "Optional release tag name. Omit to inspect and watch every published release in the repository."
2948
3124
  ).optional()
2949
3125
  }).strict();
2950
- var releaseSchema = z15.object({
2951
- created_at: z15.string(),
2952
- draft: z15.boolean(),
2953
- html_url: z15.string(),
2954
- id: z15.number(),
2955
- name: z15.string().nullable(),
2956
- prerelease: z15.boolean(),
2957
- published_at: z15.string().nullable(),
2958
- tag_name: z15.string(),
2959
- target_commitish: z15.string()
3126
+ var releaseSchema = z16.object({
3127
+ created_at: z16.string(),
3128
+ draft: z16.boolean(),
3129
+ html_url: z16.string(),
3130
+ id: z16.number(),
3131
+ name: z16.string().nullable(),
3132
+ prerelease: z16.boolean(),
3133
+ published_at: z16.string().nullable(),
3134
+ tag_name: z16.string(),
3135
+ target_commitish: z16.string()
2960
3136
  }).strict();
2961
- var releaseSourceSchema = z15.object({
3137
+ var releaseSourceSchema = z16.object({
2962
3138
  release: releaseSchema.nullable(),
2963
- repo: z15.string(),
3139
+ repo: z16.string(),
2964
3140
  subscribable: subscribableResourceSchema6.optional(),
2965
- tag: z15.string().nullable()
3141
+ tag: z16.string().nullable()
2966
3142
  }).strict();
2967
3143
  var outputSchema8 = pluginToolOutputSchema10.merge(
2968
3144
  releaseSourceSchema.extend({
2969
- target: z15.literal("getRelease")
3145
+ target: z16.literal("getRelease")
2970
3146
  })
2971
3147
  );
2972
- var providerReleaseSchema = z15.object({
2973
- created_at: z15.string(),
2974
- draft: z15.boolean(),
2975
- html_url: z15.string(),
2976
- id: z15.number(),
2977
- name: z15.string().nullable(),
2978
- prerelease: z15.boolean(),
2979
- published_at: z15.string().nullable(),
2980
- tag_name: z15.string(),
2981
- target_commitish: z15.string()
3148
+ var providerReleaseSchema = z16.object({
3149
+ created_at: z16.string(),
3150
+ draft: z16.boolean(),
3151
+ html_url: z16.string(),
3152
+ id: z16.number(),
3153
+ name: z16.string().nullable(),
3154
+ prerelease: z16.boolean(),
3155
+ published_at: z16.string().nullable(),
3156
+ tag_name: z16.string(),
3157
+ target_commitish: z16.string()
2982
3158
  }).passthrough();
2983
3159
  function mapRelease(providerRelease) {
2984
3160
  return {
@@ -2993,66 +3169,64 @@ function mapRelease(providerRelease) {
2993
3169
  target_commitish: providerRelease.target_commitish
2994
3170
  };
2995
3171
  }
2996
- function createGitHubGetReleaseTool(ctx) {
2997
- return definePluginTool10({
2998
- annotations: {
2999
- destructiveHint: false,
3000
- idempotentHint: true,
3001
- openWorldHint: true,
3002
- readOnlyHint: true
3003
- },
3004
- description: "Get a GitHub release for an exact repository, optionally limited to one tag. The result remains subscribable when no release exists yet, so use it before waiting for a published release. Omit the tag to watch every published release in the repository.",
3005
- inputSchema: inputSchema8,
3006
- outputSchema: outputSchema8,
3007
- async execute(input) {
3008
- const repo = parseRepo(input.repo);
3009
- const tag = input.tag?.trim() || void 0;
3010
- let release = null;
3011
- if (tag) {
3012
- const response = await githubApi(ctx.egress, {
3013
- operation: "github.release.get",
3014
- path: `${repoPath(repo)}/releases/tags/${encodeURIComponent(tag)}`
3015
- });
3016
- if (response.ok) {
3017
- release = mapRelease(providerReleaseSchema.parse(response.body));
3018
- } else if (response.status !== 404) {
3019
- throw new Error(
3020
- `GitHub release lookup failed with HTTP ${response.status}`
3021
- );
3022
- }
3023
- } else {
3024
- const response = await githubApi(ctx.egress, {
3025
- operation: "github.release.latest",
3026
- path: `${repoPath(repo)}/releases/latest`
3027
- });
3028
- if (response.ok) {
3029
- release = mapRelease(providerReleaseSchema.parse(response.body));
3030
- } else if (response.status === 404) {
3031
- release = null;
3032
- } else {
3033
- throw new Error(
3034
- `GitHub release lookup failed with HTTP ${response.status}`
3035
- );
3036
- }
3172
+ var gitHubGetReleaseTool = definePluginTool10({
3173
+ annotations: {
3174
+ destructiveHint: false,
3175
+ idempotentHint: true,
3176
+ openWorldHint: true,
3177
+ readOnlyHint: true
3178
+ },
3179
+ description: "Get a GitHub release for an exact repository, optionally limited to one tag. The result remains subscribable when no release exists yet, so use it before waiting for a published release. Omit the tag to watch every published release in the repository.",
3180
+ inputSchema: inputSchema8,
3181
+ outputSchema: outputSchema8,
3182
+ async execute(input, _options, ctx) {
3183
+ const repo = parseRepo(input.repo);
3184
+ const tag = input.tag?.trim() || void 0;
3185
+ let release = null;
3186
+ if (tag) {
3187
+ const response = await githubApi(ctx.egress, {
3188
+ operation: "github.release.get",
3189
+ path: `${repoPath(repo)}/releases/tags/${encodeURIComponent(tag)}`
3190
+ });
3191
+ if (response.ok) {
3192
+ release = mapRelease(providerReleaseSchema.parse(response.body));
3193
+ } else if (response.status !== 404) {
3194
+ throw new Error(
3195
+ `GitHub release lookup failed with HTTP ${response.status}`
3196
+ );
3037
3197
  }
3038
- const subscribable = gitHubReleaseSourceSubscribable({
3039
- canSubscribe: ctx.events.canSubscribe,
3040
- repo: repo.ref,
3041
- tag
3198
+ } else {
3199
+ const response = await githubApi(ctx.egress, {
3200
+ operation: "github.release.latest",
3201
+ path: `${repoPath(repo)}/releases/latest`
3042
3202
  });
3043
- const data = {
3044
- release,
3045
- repo: repo.ref,
3046
- tag: tag ?? null,
3047
- ...subscribable ? { subscribable } : void 0
3048
- };
3049
- return {
3050
- target: "getRelease",
3051
- ...data
3052
- };
3203
+ if (response.ok) {
3204
+ release = mapRelease(providerReleaseSchema.parse(response.body));
3205
+ } else if (response.status === 404) {
3206
+ release = null;
3207
+ } else {
3208
+ throw new Error(
3209
+ `GitHub release lookup failed with HTTP ${response.status}`
3210
+ );
3211
+ }
3053
3212
  }
3054
- });
3055
- }
3213
+ const subscribable = gitHubReleaseSourceSubscribable({
3214
+ canSubscribe: ctx.events.canSubscribe,
3215
+ repo: repo.ref,
3216
+ tag
3217
+ });
3218
+ const data = {
3219
+ release,
3220
+ repo: repo.ref,
3221
+ tag: tag ?? null,
3222
+ ...subscribable ? { subscribable } : void 0
3223
+ };
3224
+ return {
3225
+ target: "getRelease",
3226
+ ...data
3227
+ };
3228
+ }
3229
+ });
3056
3230
 
3057
3231
  // src/tools/get-repository.ts
3058
3232
  import {
@@ -3061,95 +3235,93 @@ import {
3061
3235
  pluginToolOutputSchema as pluginToolOutputSchema11,
3062
3236
  subscribableResourceSchema as subscribableResourceSchema7
3063
3237
  } from "@sentry/junior-plugin-api";
3064
- import * as z16 from "zod";
3065
- var inputSchema9 = z16.object({
3066
- repo: z16.string().describe('Repository in "owner/name" format.')
3238
+ import * as z17 from "zod";
3239
+ var inputSchema9 = z17.object({
3240
+ repo: z17.string().describe('Repository in "owner/name" format.')
3067
3241
  }).strict();
3068
- var repositorySchema = z16.object({
3069
- default_branch: z16.string(),
3070
- description: z16.string().nullable(),
3071
- full_name: z16.string(),
3072
- private: z16.boolean(),
3242
+ var repositorySchema = z17.object({
3243
+ default_branch: z17.string(),
3244
+ description: z17.string().nullable(),
3245
+ full_name: z17.string(),
3246
+ private: z17.boolean(),
3073
3247
  subscribable: subscribableResourceSchema7.optional(),
3074
- url: z16.string()
3248
+ url: z17.string()
3075
3249
  });
3076
3250
  var outputSchema9 = pluginToolOutputSchema11.merge(
3077
3251
  repositorySchema.extend({
3078
- target: z16.literal("getRepository")
3252
+ target: z17.literal("getRepository")
3079
3253
  })
3080
3254
  );
3081
- function createGitHubGetRepositoryTool(ctx) {
3082
- return definePluginTool11({
3083
- annotations: {
3084
- destructiveHint: false,
3085
- idempotentHint: true,
3086
- openWorldHint: true,
3087
- readOnlyHint: true
3088
- },
3089
- description: "Get a GitHub repository. Use this when repository-wide issue activity may need event monitoring; the result includes a subscribable hint when GitHub webhooks are configured.",
3090
- inputSchema: inputSchema9,
3091
- outputSchema: outputSchema9,
3092
- async execute(input) {
3093
- const repo = parseRepo(input.repo);
3094
- const response = await githubApi(ctx.egress, {
3095
- operation: "github.repository.get",
3096
- path: repoPath(repo)
3097
- });
3098
- if (!response.ok) {
3099
- throw new PluginToolInputError13(
3100
- `GitHub repository lookup failed with HTTP ${response.status}`
3101
- );
3102
- }
3103
- const providerResult = z16.object({
3104
- default_branch: z16.string(),
3105
- description: z16.string().nullable(),
3106
- full_name: z16.string(),
3107
- html_url: z16.string(),
3108
- private: z16.boolean()
3109
- }).parse(response.body);
3110
- const subscribable = gitHubRepositorySubscribable({
3111
- canSubscribe: ctx.events.canSubscribe,
3112
- repo: providerResult.full_name
3113
- });
3114
- const data = {
3115
- default_branch: providerResult.default_branch,
3116
- description: providerResult.description,
3117
- full_name: providerResult.full_name,
3118
- private: providerResult.private,
3119
- ...subscribable ? { subscribable } : void 0,
3120
- url: providerResult.html_url
3121
- };
3122
- return {
3123
- target: "getRepository",
3124
- ...data
3125
- };
3255
+ var gitHubGetRepositoryTool = definePluginTool11({
3256
+ annotations: {
3257
+ destructiveHint: false,
3258
+ idempotentHint: true,
3259
+ openWorldHint: true,
3260
+ readOnlyHint: true
3261
+ },
3262
+ description: "Get a GitHub repository. Use this when repository-wide issue activity may need event monitoring; the result includes a subscribable hint when GitHub webhooks are configured.",
3263
+ inputSchema: inputSchema9,
3264
+ outputSchema: outputSchema9,
3265
+ async execute(input, _options, ctx) {
3266
+ const repo = parseRepo(input.repo);
3267
+ const response = await githubApi(ctx.egress, {
3268
+ operation: "github.repository.get",
3269
+ path: repoPath(repo)
3270
+ });
3271
+ if (!response.ok) {
3272
+ throw new PluginToolInputError13(
3273
+ `GitHub repository lookup failed with HTTP ${response.status}`
3274
+ );
3126
3275
  }
3127
- });
3128
- }
3276
+ const providerResult = z17.object({
3277
+ default_branch: z17.string(),
3278
+ description: z17.string().nullable(),
3279
+ full_name: z17.string(),
3280
+ html_url: z17.string(),
3281
+ private: z17.boolean()
3282
+ }).parse(response.body);
3283
+ const subscribable = gitHubRepositorySubscribable({
3284
+ canSubscribe: ctx.events.canSubscribe,
3285
+ repo: providerResult.full_name
3286
+ });
3287
+ const data = {
3288
+ default_branch: providerResult.default_branch,
3289
+ description: providerResult.description,
3290
+ full_name: providerResult.full_name,
3291
+ private: providerResult.private,
3292
+ ...subscribable ? { subscribable } : void 0,
3293
+ url: providerResult.html_url
3294
+ };
3295
+ return {
3296
+ target: "getRepository",
3297
+ ...data
3298
+ };
3299
+ }
3300
+ });
3129
3301
 
3130
3302
  // src/tools/get-status.ts
3131
3303
  import {
3132
3304
  definePluginTool as definePluginTool12,
3133
3305
  pluginToolOutputSchema as pluginToolOutputSchema12
3134
3306
  } from "@sentry/junior-plugin-api";
3135
- import * as z18 from "zod";
3307
+ import * as z19 from "zod";
3136
3308
 
3137
3309
  // src/github-status.ts
3138
- import * as z17 from "zod";
3310
+ import * as z18 from "zod";
3139
3311
  var GITHUB_STATUS_INCIDENTS_URL = "https://www.githubstatus.com/api/v2/incidents.json";
3140
3312
  var GITHUB_STATUS_TTL_MS = 60 * 1e3;
3141
3313
  var GITHUB_STATUS_TIMEOUT_MS = 5e3;
3142
- var incidentsResponseSchema = z17.object({
3143
- incidents: z17.array(
3144
- z17.object({
3145
- components: z17.array(z17.object({ name: z17.string() })).default([]),
3146
- created_at: z17.string(),
3147
- impact: z17.string(),
3148
- name: z17.string(),
3149
- resolved_at: z17.string().nullable(),
3150
- shortlink: z17.string(),
3151
- started_at: z17.string().nullable().optional(),
3152
- status: z17.string()
3314
+ var incidentsResponseSchema = z18.object({
3315
+ incidents: z18.array(
3316
+ z18.object({
3317
+ components: z18.array(z18.object({ name: z18.string() })).default([]),
3318
+ created_at: z18.string(),
3319
+ impact: z18.string(),
3320
+ name: z18.string(),
3321
+ resolved_at: z18.string().nullable(),
3322
+ shortlink: z18.string(),
3323
+ started_at: z18.string().nullable().optional(),
3324
+ status: z18.string()
3153
3325
  })
3154
3326
  )
3155
3327
  });
@@ -3191,50 +3363,48 @@ async function loadGitHubStatusIncidents(cache, withinMs) {
3191
3363
 
3192
3364
  // src/tools/get-status.ts
3193
3365
  var RECENT_INCIDENT_MS = 24 * 60 * 60 * 1e3;
3194
- var inputSchema10 = z18.object({}).strict();
3195
- var incidentSchema = z18.object({
3196
- components: z18.array(z18.string()),
3197
- impact: z18.string(),
3198
- name: z18.string(),
3199
- resolved_at: z18.string().optional(),
3200
- started_at: z18.string(),
3201
- status: z18.string(),
3202
- url: z18.string()
3366
+ var inputSchema10 = z19.object({}).strict();
3367
+ var incidentSchema = z19.object({
3368
+ components: z19.array(z19.string()),
3369
+ impact: z19.string(),
3370
+ name: z19.string(),
3371
+ resolved_at: z19.string().optional(),
3372
+ started_at: z19.string(),
3373
+ status: z19.string(),
3374
+ url: z19.string()
3203
3375
  });
3204
3376
  var outputSchema10 = pluginToolOutputSchema12.extend({
3205
- target: z18.literal("getStatus"),
3206
- incidents: z18.array(incidentSchema)
3377
+ target: z19.literal("getStatus"),
3378
+ incidents: z19.array(incidentSchema)
3379
+ });
3380
+ var gitHubGetStatusTool = definePluginTool12({
3381
+ annotations: {
3382
+ destructiveHint: false,
3383
+ idempotentHint: true,
3384
+ openWorldHint: true,
3385
+ readOnlyHint: true
3386
+ },
3387
+ description: "List GitHub incidents from githubstatus.com that are open or were resolved in the last 24 hours, with their affected components. Use when a GitHub request fails with a 5xx, a timeout, or a dropped connection, or when checks stay queued or fail with no cause in the logs.",
3388
+ inputSchema: inputSchema10,
3389
+ outputSchema: outputSchema10,
3390
+ async execute(_input, _options, ctx) {
3391
+ const incidents = await loadGitHubStatusIncidents(
3392
+ ctx.cache,
3393
+ RECENT_INCIDENT_MS
3394
+ );
3395
+ return {
3396
+ target: "getStatus",
3397
+ incidents: incidents.map(({ resolvedAt, startedAt, ...incident }) => {
3398
+ const result = {
3399
+ ...incident,
3400
+ started_at: startedAt
3401
+ };
3402
+ if (resolvedAt) result.resolved_at = resolvedAt;
3403
+ return result;
3404
+ })
3405
+ };
3406
+ }
3207
3407
  });
3208
- function createGitHubGetStatusTool(ctx) {
3209
- return definePluginTool12({
3210
- annotations: {
3211
- destructiveHint: false,
3212
- idempotentHint: true,
3213
- openWorldHint: true,
3214
- readOnlyHint: true
3215
- },
3216
- description: "List GitHub incidents from githubstatus.com that are open or were resolved in the last 24 hours, with their affected components. Use when a GitHub request fails with a 5xx, a timeout, or a dropped connection, or when checks stay queued or fail with no cause in the logs.",
3217
- inputSchema: inputSchema10,
3218
- outputSchema: outputSchema10,
3219
- async execute() {
3220
- const incidents = await loadGitHubStatusIncidents(
3221
- ctx.cache,
3222
- RECENT_INCIDENT_MS
3223
- );
3224
- return {
3225
- target: "getStatus",
3226
- incidents: incidents.map(({ resolvedAt, startedAt, ...incident }) => {
3227
- const result = {
3228
- ...incident,
3229
- started_at: startedAt
3230
- };
3231
- if (resolvedAt) result.resolved_at = resolvedAt;
3232
- return result;
3233
- })
3234
- };
3235
- }
3236
- });
3237
- }
3238
3408
 
3239
3409
  // src/tools/update-issue.ts
3240
3410
  import {
@@ -3243,163 +3413,161 @@ import {
3243
3413
  pluginToolOutputSchema as pluginToolOutputSchema13,
3244
3414
  subscribableResourceSchema as subscribableResourceSchema8
3245
3415
  } from "@sentry/junior-plugin-api";
3246
- import * as z19 from "zod";
3247
- var inputSchema11 = z19.object({
3248
- repo: z19.string().describe('Repository in "owner/name" format.'),
3249
- number: z19.number().int().positive().describe("Issue number."),
3250
- title: z19.string().trim().min(1).optional().describe("Replacement issue title."),
3251
- body: z19.string().optional().describe(
3416
+ import * as z20 from "zod";
3417
+ var inputSchema11 = z20.object({
3418
+ repo: z20.string().describe('Repository in "owner/name" format.'),
3419
+ number: z20.number().int().positive().describe("Issue number."),
3420
+ title: z20.string().trim().min(1).optional().describe("Replacement issue title."),
3421
+ body: z20.string().optional().describe(
3252
3422
  "Replacement issue body. The runtime appends requester attribution and the conversation footer."
3253
3423
  ),
3254
- state: z19.enum(["open", "closed"]).optional().describe("Replacement issue state."),
3255
- assign_requester: z19.boolean().optional().describe(
3424
+ state: z20.enum(["open", "closed"]).optional().describe("Replacement issue state."),
3425
+ assign_requester: z20.boolean().optional().describe(
3256
3426
  "Set true to add the requester's linked GitHub account as an assignee. Other assignees stay."
3257
3427
  )
3258
3428
  }).strict().refine(
3259
3429
  ({ title, body, state, assign_requester }) => title !== void 0 || body !== void 0 || state !== void 0 || assign_requester === true,
3260
3430
  { message: "At least one issue field must be provided." }
3261
3431
  );
3262
- var issueSchema2 = z19.object({
3263
- assignees: z19.array(z19.string()),
3264
- body: z19.string().nullable(),
3265
- number: z19.number(),
3266
- state: z19.string(),
3432
+ var issueSchema2 = z20.object({
3433
+ assignees: z20.array(z20.string()),
3434
+ body: z20.string().nullable(),
3435
+ number: z20.number(),
3436
+ state: z20.string(),
3267
3437
  subscribable: subscribableResourceSchema8.optional(),
3268
- title: z19.string(),
3269
- url: z19.string()
3438
+ title: z20.string(),
3439
+ url: z20.string()
3270
3440
  });
3271
3441
  var outputSchema11 = pluginToolOutputSchema13.merge(
3272
3442
  issueSchema2.extend({
3273
- target: z19.literal("updateIssue")
3443
+ target: z20.literal("updateIssue")
3274
3444
  })
3275
3445
  );
3276
- var providerIssueSchema2 = z19.object({
3277
- assignees: z19.array(z19.object({ login: z19.string() })).nullish().transform((assignees) => assignees?.map(({ login: login2 }) => login2) ?? []),
3278
- body: z19.string().nullable().optional().default(null),
3279
- html_url: z19.string(),
3280
- number: z19.number(),
3281
- state: z19.string(),
3282
- title: z19.string()
3446
+ var providerIssueSchema2 = z20.object({
3447
+ assignees: z20.array(z20.object({ login: z20.string() })).nullish().transform((assignees) => assignees?.map(({ login }) => login) ?? []),
3448
+ body: z20.string().nullable().optional().default(null),
3449
+ html_url: z20.string(),
3450
+ number: z20.number(),
3451
+ state: z20.string(),
3452
+ title: z20.string()
3283
3453
  });
3284
3454
  function nonEmptyString4(value, name) {
3285
3455
  if (!value?.trim()) throw new PluginToolInputError14(`${name} is required`);
3286
3456
  return value.trim();
3287
3457
  }
3288
- function createGitHubUpdateIssueTool(ctx) {
3289
- return definePluginTool13({
3290
- annotations: {
3291
- destructiveHint: true,
3292
- idempotentHint: true,
3293
- openWorldHint: true,
3294
- readOnlyHint: false
3295
- },
3296
- description: "Update an existing GitHub issue's title, body, or open/closed state, or assign it to the requester. Use this instead of raw GitHub API calls when changing issue metadata.",
3297
- inputSchema: inputSchema11,
3298
- outputSchema: outputSchema11,
3299
- async execute(input) {
3300
- const parsedInput = inputSchema11.safeParse(input);
3301
- if (!parsedInput.success) {
3302
- throw new PluginToolInputError14("Invalid GitHub updateIssue input.", {
3303
- cause: parsedInput.error
3304
- });
3305
- }
3306
- const update = parsedInput.data;
3307
- const repo = parseRepo(update.repo);
3308
- const requester = update.body !== void 0 || update.assign_requester ? await resolveGitHubRequester(ctx) : void 0;
3309
- const assignee = update.assign_requester ? linkedGitHubLogin(requester?.user) : void 0;
3310
- if (update.assign_requester && !assignee) {
3311
- throw new PluginToolInputError14(
3312
- "The requester has no linked GitHub account, so Junior cannot assign the issue to them."
3458
+ var gitHubUpdateIssueTool = definePluginTool13({
3459
+ annotations: {
3460
+ destructiveHint: true,
3461
+ idempotentHint: true,
3462
+ openWorldHint: true,
3463
+ readOnlyHint: false
3464
+ },
3465
+ description: "Update an existing GitHub issue's title, body, or open/closed state, or assign it to the requester. Use this instead of raw GitHub API calls when changing issue metadata.",
3466
+ inputSchema: inputSchema11,
3467
+ outputSchema: outputSchema11,
3468
+ async execute(input, _options, ctx) {
3469
+ const parsedInput = inputSchema11.safeParse(input);
3470
+ if (!parsedInput.success) {
3471
+ throw new PluginToolInputError14("Invalid GitHub updateIssue input.", {
3472
+ cause: parsedInput.error
3473
+ });
3474
+ }
3475
+ const update = parsedInput.data;
3476
+ const repo = parseRepo(update.repo);
3477
+ const requester = update.body !== void 0 || update.assign_requester ? await resolveGitHubRequester(ctx) : void 0;
3478
+ const assignee = update.assign_requester ? linkedGitHubLogin(requester?.user) : void 0;
3479
+ if (update.assign_requester && !assignee) {
3480
+ throw new PluginToolInputError14(
3481
+ "The requester has no linked GitHub account, so Junior cannot assign the issue to them."
3482
+ );
3483
+ }
3484
+ const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
3485
+ operation: "github.issue.get",
3486
+ path: `${repoPath(repo)}/issues/${update.number}`
3487
+ }) : void 0;
3488
+ const payload = {
3489
+ ...update.title !== void 0 ? { title: update.title } : void 0,
3490
+ ...update.body !== void 0 ? {
3491
+ body: appendGitHubFooter(
3492
+ appendGitHubRequesterAttribution(
3493
+ update.body,
3494
+ ctx,
3495
+ requester,
3496
+ currentBody
3497
+ ),
3498
+ nonEmptyString4(ctx.conversationId, "conversationId"),
3499
+ ctx.conversationLink?.url
3500
+ )
3501
+ } : void 0,
3502
+ ...update.state !== void 0 ? { state: update.state } : void 0
3503
+ };
3504
+ let parsed;
3505
+ if (Object.keys(payload).length > 0) {
3506
+ const response = await githubApi(ctx.egress, {
3507
+ operation: "github.issue.update",
3508
+ method: "PATCH",
3509
+ path: `${repoPath(repo)}/issues/${update.number}`,
3510
+ body: payload
3511
+ });
3512
+ parsed = response.body;
3513
+ if (!response.ok) {
3514
+ throw new Error(
3515
+ `GitHub issue update failed with HTTP ${response.status}: ${githubErrorMessage(parsed)}`
3313
3516
  );
3314
3517
  }
3315
- const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
3316
- operation: "github.issue.get",
3317
- path: `${repoPath(repo)}/issues/${update.number}`
3318
- }) : void 0;
3319
- const payload = {
3320
- ...update.title !== void 0 ? { title: update.title } : void 0,
3321
- ...update.body !== void 0 ? {
3322
- body: appendGitHubFooter(
3323
- appendGitHubRequesterAttribution(
3324
- update.body,
3325
- ctx,
3326
- requester,
3327
- currentBody
3328
- ),
3329
- nonEmptyString4(ctx.conversationId, "conversationId"),
3330
- ctx.conversationLink?.url
3331
- )
3332
- } : void 0,
3333
- ...update.state !== void 0 ? { state: update.state } : void 0
3334
- };
3335
- let parsed;
3336
- if (Object.keys(payload).length > 0) {
3337
- const response = await githubApi(ctx.egress, {
3338
- operation: "github.issue.update",
3339
- method: "PATCH",
3340
- path: `${repoPath(repo)}/issues/${update.number}`,
3341
- body: payload
3342
- });
3343
- parsed = response.body;
3344
- if (!response.ok) {
3345
- throw new Error(
3346
- `GitHub issue update failed with HTTP ${response.status}: ${githubErrorMessage(parsed)}`
3347
- );
3348
- }
3349
- }
3350
- if (assignee) {
3351
- const response = await githubApi(ctx.egress, {
3352
- operation: "github.issue.assign",
3353
- method: "POST",
3354
- path: `${repoPath(repo)}/issues/${update.number}/assignees`,
3355
- body: { assignees: [assignee] }
3356
- });
3357
- parsed = response.body;
3358
- if (!response.ok) {
3359
- const message = `GitHub issue assignment failed with HTTP ${response.status}: ${githubErrorMessage(parsed)}`;
3360
- if (response.status === 404 || response.status === 422) {
3361
- throw new PluginToolInputError14(message);
3362
- }
3363
- throw new Error(message);
3518
+ }
3519
+ if (assignee) {
3520
+ const response = await githubApi(ctx.egress, {
3521
+ operation: "github.issue.assign",
3522
+ method: "POST",
3523
+ path: `${repoPath(repo)}/issues/${update.number}/assignees`,
3524
+ body: { assignees: [assignee] }
3525
+ });
3526
+ parsed = response.body;
3527
+ if (!response.ok) {
3528
+ const message = `GitHub issue assignment failed with HTTP ${response.status}: ${githubErrorMessage(parsed)}`;
3529
+ if (response.status === 404 || response.status === 422) {
3530
+ throw new PluginToolInputError14(message);
3364
3531
  }
3532
+ throw new Error(message);
3365
3533
  }
3366
- const providerResult = providerIssueSchema2.parse(parsed);
3367
- if (assignee && !providerResult.assignees.some(
3368
- (login2) => login2.toLowerCase() === assignee.toLowerCase()
3369
- )) {
3370
- throw new PluginToolInputError14(
3371
- `GitHub did not assign @${assignee} to the issue. They may not have access to ${repo.ref}.`
3372
- );
3373
- }
3374
- const subscribable = gitHubIssueSubscribable({
3375
- canSubscribe: ctx.events.canSubscribe,
3376
- number: providerResult.number,
3377
- repo: repo.ref
3378
- });
3379
- return {
3380
- objectAnnotations: [
3381
- githubObjectAnnotation({
3382
- ...githubObjectFacts("task", parsed),
3383
- repo: repo.ref,
3384
- number: providerResult.number,
3385
- title: providerResult.title,
3386
- url: providerResult.html_url,
3387
- objectType: "task",
3388
- status: providerResult.state
3389
- })
3390
- ],
3391
- target: "updateIssue",
3392
- assignees: providerResult.assignees,
3393
- body: providerResult.body,
3394
- number: providerResult.number,
3395
- state: providerResult.state,
3396
- ...subscribable ? { subscribable } : void 0,
3397
- title: providerResult.title,
3398
- url: providerResult.html_url
3399
- };
3400
3534
  }
3401
- });
3402
- }
3535
+ const providerResult = providerIssueSchema2.parse(parsed);
3536
+ if (assignee && !providerResult.assignees.some(
3537
+ (login) => login.toLowerCase() === assignee.toLowerCase()
3538
+ )) {
3539
+ throw new PluginToolInputError14(
3540
+ `GitHub did not assign @${assignee} to the issue. They may not have access to ${repo.ref}.`
3541
+ );
3542
+ }
3543
+ const subscribable = gitHubIssueSubscribable({
3544
+ canSubscribe: ctx.events.canSubscribe,
3545
+ number: providerResult.number,
3546
+ repo: repo.ref
3547
+ });
3548
+ return {
3549
+ objectAnnotations: [
3550
+ githubObjectAnnotation({
3551
+ ...githubObjectFacts("task", parsed),
3552
+ repo: repo.ref,
3553
+ number: providerResult.number,
3554
+ title: providerResult.title,
3555
+ url: providerResult.html_url,
3556
+ objectType: "task",
3557
+ status: providerResult.state
3558
+ })
3559
+ ],
3560
+ target: "updateIssue",
3561
+ assignees: providerResult.assignees,
3562
+ body: providerResult.body,
3563
+ number: providerResult.number,
3564
+ state: providerResult.state,
3565
+ ...subscribable ? { subscribable } : void 0,
3566
+ title: providerResult.title,
3567
+ url: providerResult.html_url
3568
+ };
3569
+ }
3570
+ });
3403
3571
 
3404
3572
  // src/tools/update-issue-comment.ts
3405
3573
  import {
@@ -3407,19 +3575,19 @@ import {
3407
3575
  PluginToolInputError as PluginToolInputError15,
3408
3576
  pluginToolOutputSchema as pluginToolOutputSchema14
3409
3577
  } from "@sentry/junior-plugin-api";
3410
- import * as z20 from "zod";
3411
- var inputSchema12 = z20.object({
3412
- repo: z20.string().describe('Repository in "owner/name" format.'),
3413
- comment_id: z20.number().int().positive().describe("Issue comment id, as returned by github_commentOnIssue."),
3414
- body: z20.string().trim().min(1).describe("Replacement comment text.")
3578
+ import * as z21 from "zod";
3579
+ var inputSchema12 = z21.object({
3580
+ repo: z21.string().describe('Repository in "owner/name" format.'),
3581
+ comment_id: z21.number().int().positive().describe("Issue comment id, as returned by github_commentOnIssue."),
3582
+ body: z21.string().trim().min(1).describe("Replacement comment text.")
3415
3583
  }).strict();
3416
3584
  var outputSchema12 = pluginToolOutputSchema14.extend({
3417
- target: z20.literal("updateIssueComment"),
3418
- repo: z20.string(),
3419
- comment_id: z20.number(),
3420
- url: z20.string()
3585
+ target: z21.literal("updateIssueComment"),
3586
+ repo: z21.string(),
3587
+ comment_id: z21.number(),
3588
+ url: z21.string()
3421
3589
  });
3422
- function createGitHubUpdateIssueCommentTool(egress, botEmail) {
3590
+ function createGitHubUpdateIssueCommentTool(botEmail) {
3423
3591
  return definePluginTool14({
3424
3592
  annotations: {
3425
3593
  destructiveHint: true,
@@ -3430,7 +3598,7 @@ function createGitHubUpdateIssueCommentTool(egress, botEmail) {
3430
3598
  description: "Replace the text of a GitHub issue or pull request conversation comment that you posted, for example to update a progress comment. Only works on your own comments.",
3431
3599
  inputSchema: inputSchema12,
3432
3600
  outputSchema: outputSchema12,
3433
- async execute(input) {
3601
+ async execute(input, _options, { egress }) {
3434
3602
  const repo = parseRepo(input.repo);
3435
3603
  const botUserId = botUserIdFromEmail(botEmail);
3436
3604
  if (botUserId === void 0) {
@@ -3446,7 +3614,7 @@ function createGitHubUpdateIssueCommentTool(egress, botEmail) {
3446
3614
  if (lookup.status === 404) throw new PluginToolInputError15(message);
3447
3615
  throw new Error(message);
3448
3616
  }
3449
- const author = z20.object({ user: z20.object({ id: z20.number() }).nullable() }).safeParse(lookup.body);
3617
+ const author = z21.object({ user: z21.object({ id: z21.number() }).nullable() }).safeParse(lookup.body);
3450
3618
  if (!author.success || author.data.user?.id !== botUserId) {
3451
3619
  throw new PluginToolInputError15(
3452
3620
  "This bot can only edit issue comments it posted."
@@ -3465,7 +3633,7 @@ function createGitHubUpdateIssueCommentTool(egress, botEmail) {
3465
3633
  }
3466
3634
  throw new Error(message);
3467
3635
  }
3468
- const comment = z20.object({ id: z20.number(), html_url: z20.string() }).parse(response.body);
3636
+ const comment = z21.object({ id: z21.number(), html_url: z21.string() }).parse(response.body);
3469
3637
  return {
3470
3638
  target: "updateIssueComment",
3471
3639
  repo: repo.ref,
@@ -3482,42 +3650,42 @@ import {
3482
3650
  PluginToolInputError as PluginToolInputError16,
3483
3651
  pluginToolOutputSchema as pluginToolOutputSchema15
3484
3652
  } from "@sentry/junior-plugin-api";
3485
- import * as z21 from "zod";
3653
+ import * as z22 from "zod";
3486
3654
  import { subscribableResourceSchema as subscribableResourceSchema9 } from "@sentry/junior-plugin-api";
3487
- var inputSchema13 = z21.object({
3488
- repo: z21.string().describe('Repository in "owner/name" format.'),
3489
- number: z21.number().int().positive().describe("Pull request number."),
3490
- title: z21.string().trim().min(1).optional().describe("Replacement pull request title."),
3491
- body: z21.string().optional().describe(
3655
+ var inputSchema13 = z22.object({
3656
+ repo: z22.string().describe('Repository in "owner/name" format.'),
3657
+ number: z22.number().int().positive().describe("Pull request number."),
3658
+ title: z22.string().trim().min(1).optional().describe("Replacement pull request title."),
3659
+ body: z22.string().optional().describe(
3492
3660
  "Replacement pull request body. The runtime appends requester attribution and the conversation footer."
3493
3661
  ),
3494
- base: z21.string().trim().min(1).optional().describe("Replacement base branch."),
3495
- state: z21.enum(["open", "closed"]).optional().describe("Replacement pull request state."),
3496
- draft: z21.boolean().optional().describe(
3662
+ base: z22.string().trim().min(1).optional().describe("Replacement base branch."),
3663
+ state: z22.enum(["open", "closed"]).optional().describe("Replacement pull request state."),
3664
+ draft: z22.boolean().optional().describe(
3497
3665
  "Set false to mark a draft pull request ready for review, or true to convert it back to a draft."
3498
3666
  )
3499
3667
  }).strict().refine(
3500
3668
  ({ title, body, base, state, draft }) => title !== void 0 || body !== void 0 || base !== void 0 || state !== void 0 || draft !== void 0,
3501
3669
  { message: "At least one pull request field must be provided." }
3502
3670
  );
3503
- var draftMutationResponseSchema = z21.object({
3504
- data: z21.object({
3505
- result: z21.object({ pullRequest: z21.object({ isDraft: z21.boolean() }) })
3671
+ var draftMutationResponseSchema = z22.object({
3672
+ data: z22.object({
3673
+ result: z22.object({ pullRequest: z22.object({ isDraft: z22.boolean() }) })
3506
3674
  })
3507
3675
  });
3508
- var pullRequestSchema2 = z21.object({
3509
- base: z21.string(),
3510
- body: z21.string().nullable(),
3511
- draft: z21.boolean(),
3512
- number: z21.number(),
3513
- state: z21.string(),
3676
+ var pullRequestSchema2 = z22.object({
3677
+ base: z22.string(),
3678
+ body: z22.string().nullable(),
3679
+ draft: z22.boolean(),
3680
+ number: z22.number(),
3681
+ state: z22.string(),
3514
3682
  subscribable: subscribableResourceSchema9.optional(),
3515
- title: z21.string(),
3516
- url: z21.string()
3683
+ title: z22.string(),
3684
+ url: z22.string()
3517
3685
  });
3518
3686
  var outputSchema13 = pluginToolOutputSchema15.merge(
3519
3687
  pullRequestSchema2.extend({
3520
- target: z21.literal("updatePullRequest")
3688
+ target: z22.literal("updatePullRequest")
3521
3689
  })
3522
3690
  );
3523
3691
  function nonEmptyString5(value, name) {
@@ -3546,7 +3714,7 @@ async function setPullRequestDraft(input) {
3546
3714
  }
3547
3715
  return isDraft;
3548
3716
  }
3549
- function createGitHubUpdatePullRequestTool(ctx, descriptionDecider) {
3717
+ function createGitHubUpdatePullRequestTool(descriptionChecks = false) {
3550
3718
  return definePluginTool15({
3551
3719
  annotations: {
3552
3720
  destructiveHint: true,
@@ -3557,7 +3725,7 @@ function createGitHubUpdatePullRequestTool(ctx, descriptionDecider) {
3557
3725
  description: "Update an existing GitHub pull request's title, body, base branch, open/closed state, or draft state. Use this instead of raw GitHub API calls when changing PR metadata or marking a PR ready for review.",
3558
3726
  inputSchema: inputSchema13,
3559
3727
  outputSchema: outputSchema13,
3560
- async execute(input) {
3728
+ async execute(input, _options, ctx) {
3561
3729
  const parsedInput = inputSchema13.safeParse(input);
3562
3730
  if (!parsedInput.success) {
3563
3731
  throw new PluginToolInputError16(
@@ -3566,8 +3734,8 @@ function createGitHubUpdatePullRequestTool(ctx, descriptionDecider) {
3566
3734
  );
3567
3735
  }
3568
3736
  const update = parsedInput.data;
3569
- if (descriptionDecider && update.body !== void 0) {
3570
- await checkPullRequestDescription(descriptionDecider, update.body);
3737
+ if (descriptionChecks && update.body !== void 0) {
3738
+ await checkPullRequestDescription(ctx.decider, update.body);
3571
3739
  }
3572
3740
  const repo = parseRepo(update.repo);
3573
3741
  const requester = await resolveGitHubRequester(ctx);
@@ -3606,16 +3774,16 @@ function createGitHubUpdatePullRequestTool(ctx, descriptionDecider) {
3606
3774
  }
3607
3775
  throw new Error(message);
3608
3776
  }
3609
- const providerResult = z21.object({
3610
- base: z21.object({ ref: z21.string() }),
3611
- body: z21.string().nullable().optional().default(null),
3612
- draft: z21.boolean(),
3613
- html_url: z21.string(),
3614
- merged: z21.boolean(),
3615
- node_id: z21.string().optional(),
3616
- number: z21.number(),
3617
- state: z21.string(),
3618
- title: z21.string()
3777
+ const providerResult = z22.object({
3778
+ base: z22.object({ ref: z22.string() }),
3779
+ body: z22.string().nullable().optional().default(null),
3780
+ draft: z22.boolean(),
3781
+ html_url: z22.string(),
3782
+ merged: z22.boolean(),
3783
+ node_id: z22.string().optional(),
3784
+ number: z22.number(),
3785
+ state: z22.string(),
3786
+ title: z22.string()
3619
3787
  }).parse(parsed);
3620
3788
  if (update.draft !== void 0 && update.draft !== providerResult.draft) {
3621
3789
  if (!providerResult.node_id) {
@@ -3680,7 +3848,7 @@ import {
3680
3848
  PluginToolInputError as PluginToolInputError17,
3681
3849
  pluginToolOutputSchema as pluginToolOutputSchema16
3682
3850
  } from "@sentry/junior-plugin-api";
3683
- import * as z22 from "zod";
3851
+ import * as z23 from "zod";
3684
3852
  var STATUS_TO_REACTION_CONTENT = {
3685
3853
  reviewing: "eyes",
3686
3854
  addressed: "+1",
@@ -3700,26 +3868,26 @@ var REST_REACTION_CONTENT = new Map(
3700
3868
  rest
3701
3869
  ])
3702
3870
  );
3703
- var inputSchema14 = z22.object({
3704
- repo: z22.string().describe('Repository in "owner/name" format.'),
3705
- comment_kind: z22.enum(["conversation", "review", "review_body"]).describe(
3871
+ var inputSchema14 = z23.object({
3872
+ repo: z23.string().describe('Repository in "owner/name" format.'),
3873
+ comment_kind: z23.enum(["conversation", "review", "review_body"]).describe(
3706
3874
  'Comment kind: "conversation" for a pull request conversation comment, "review" for an inline review comment, "review_body" for the body of a submitted review. Use the exact value from the event.'
3707
3875
  ),
3708
- comment_id: z22.number().int().positive().describe(
3876
+ comment_id: z23.number().int().positive().describe(
3709
3877
  "GitHub comment id (conversation comment id, inline review comment id, or review id). Use the exact value from the event."
3710
3878
  ),
3711
- pull_request: z22.number().int().positive().describe(
3879
+ pull_request: z23.number().int().positive().describe(
3712
3880
  "Pull request number that the comment is on. Use the exact value from the event."
3713
3881
  ),
3714
- status: z22.enum(["addressed", "declined"]).describe(
3882
+ status: z23.enum(["addressed", "declined"]).describe(
3715
3883
  "Feedback outcome. Maps to a reaction: addressed -> +1, declined -> -1."
3716
3884
  )
3717
3885
  }).strict();
3718
3886
  var outputSchema14 = pluginToolOutputSchema16.extend({
3719
- target: z22.literal("updatePullRequestFeedback"),
3720
- repo: z22.string(),
3721
- comment_id: z22.number(),
3722
- status: z22.enum(["addressed", "declined"])
3887
+ target: z23.literal("updatePullRequestFeedback"),
3888
+ repo: z23.string(),
3889
+ comment_id: z23.number(),
3890
+ status: z23.enum(["addressed", "declined"])
3723
3891
  });
3724
3892
  function pullRequestCommentPath(input) {
3725
3893
  const segment = input.commentKind === "conversation" ? "issues" : "pulls";
@@ -3731,10 +3899,10 @@ function pullRequestCommentReactionsPath(input) {
3731
3899
  function pullRequestFeedbackReactionContent(status) {
3732
3900
  return STATUS_TO_REACTION_CONTENT[status];
3733
3901
  }
3734
- var reactionSchema = z22.object({
3735
- id: z22.number(),
3736
- content: z22.string(),
3737
- user: z22.object({ id: z22.number() }).nullable()
3902
+ var reactionSchema = z23.object({
3903
+ id: z23.number(),
3904
+ content: z23.string(),
3905
+ user: z23.object({ id: z23.number() }).nullable()
3738
3906
  });
3739
3907
  async function commentParentNumber(egress, input) {
3740
3908
  const commentResponse = await githubApi(egress, {
@@ -3747,9 +3915,9 @@ async function commentParentNumber(egress, input) {
3747
3915
  if (commentResponse.status === 404) throw new PluginToolInputError17(message);
3748
3916
  throw new Error(message);
3749
3917
  }
3750
- const comment = z22.object({
3751
- issue_url: z22.string().optional(),
3752
- pull_request_url: z22.string().optional()
3918
+ const comment = z23.object({
3919
+ issue_url: z23.string().optional(),
3920
+ pull_request_url: z23.string().optional()
3753
3921
  }).safeParse(commentPayload);
3754
3922
  const parentUrl = comment.success ? input.commentKind === "conversation" ? comment.data.issue_url : comment.data.pull_request_url : void 0;
3755
3923
  const number33 = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
@@ -3770,7 +3938,7 @@ async function assertBotAuthoredPullRequest(egress, input) {
3770
3938
  `GitHub pull request lookup failed with HTTP ${pullResponse.status}: ${githubErrorMessage(pullPayload)}`
3771
3939
  );
3772
3940
  }
3773
- const pull = z22.object({ user: z22.object({ id: z22.number() }).nullable() }).safeParse(pullPayload);
3941
+ const pull = z23.object({ user: z23.object({ id: z23.number() }).nullable() }).safeParse(pullPayload);
3774
3942
  if (!pullResponse.ok || !pull.success || pull.data.user?.id !== input.botUserId) {
3775
3943
  throw new PluginToolInputError17(
3776
3944
  "This bot can only set feedback status on comments on pull requests it authored."
@@ -3783,14 +3951,14 @@ function pullRequestReviewPath(input) {
3783
3951
  function graphqlReactionContent(content) {
3784
3952
  return GRAPHQL_REACTION_CONTENT[content] ?? content;
3785
3953
  }
3786
- var reviewReactionsSchema = z22.object({
3787
- data: z22.object({
3788
- node: z22.object({
3789
- reactionGroups: z22.array(
3790
- z22.object({
3791
- content: z22.string(),
3792
- reactors: z22.object({
3793
- nodes: z22.array(z22.object({ databaseId: z22.number().optional() }))
3954
+ var reviewReactionsSchema = z23.object({
3955
+ data: z23.object({
3956
+ node: z23.object({
3957
+ reactionGroups: z23.array(
3958
+ z23.object({
3959
+ content: z23.string(),
3960
+ reactors: z23.object({
3961
+ nodes: z23.array(z23.object({ databaseId: z23.number().optional() }))
3794
3962
  })
3795
3963
  })
3796
3964
  )
@@ -3810,7 +3978,7 @@ async function commentReactions(egress, input) {
3810
3978
  operation: "github.pull.comment-reaction.list",
3811
3979
  path: `${path}?per_page=100`
3812
3980
  }),
3813
- botReactions: (body) => z22.array(reactionSchema).parse(body).filter((reaction) => reaction.user?.id === input.botUserId),
3981
+ botReactions: (body) => z23.array(reactionSchema).parse(body).filter((reaction) => reaction.user?.id === input.botUserId),
3814
3982
  remove: (reaction) => githubApi(egress, {
3815
3983
  operation: "github.pull.comment-reaction.delete",
3816
3984
  method: "DELETE",
@@ -3834,7 +4002,7 @@ async function reviewBodyReactions(egress, input) {
3834
4002
  if (reviewResponse.status === 404) throw new PluginToolInputError17(message);
3835
4003
  throw new Error(message);
3836
4004
  }
3837
- const subjectId = z22.object({ node_id: z22.string().min(1) }).parse(reviewResponse.body).node_id;
4005
+ const subjectId = z23.object({ node_id: z23.string().min(1) }).parse(reviewResponse.body).node_id;
3838
4006
  const graphql = (operation2, document, variables) => githubApi(egress, {
3839
4007
  operation: operation2,
3840
4008
  method: "POST",
@@ -3867,7 +4035,7 @@ function failed(response) {
3867
4035
  const errors = response.body?.errors;
3868
4036
  return !response.ok || Array.isArray(errors) && errors.length > 0;
3869
4037
  }
3870
- function createGitHubUpdatePullRequestFeedbackTool(ctx, botEmail) {
4038
+ function createGitHubUpdatePullRequestFeedbackTool(botEmail) {
3871
4039
  return definePluginTool16({
3872
4040
  // No action review: the tool checks in code that the bot authored the pull
3873
4041
  // request, and it changes only the bot's own reaction, which is reversible.
@@ -3882,7 +4050,7 @@ function createGitHubUpdatePullRequestFeedbackTool(ctx, botEmail) {
3882
4050
  exposure: "direct",
3883
4051
  inputSchema: inputSchema14,
3884
4052
  outputSchema: outputSchema14,
3885
- async execute(input) {
4053
+ async execute(input, _options, ctx) {
3886
4054
  const parsedInput = inputSchema14.safeParse(input);
3887
4055
  if (!parsedInput.success) {
3888
4056
  throw new PluginToolInputError17(
@@ -3964,23 +4132,23 @@ import {
3964
4132
  PluginToolInputError as PluginToolInputError18,
3965
4133
  pluginToolOutputSchema as pluginToolOutputSchema17
3966
4134
  } from "@sentry/junior-plugin-api";
3967
- import * as z23 from "zod";
3968
- var inputSchema15 = z23.object({
3969
- repo: z23.string().describe(
4135
+ import * as z24 from "zod";
4136
+ var inputSchema15 = z24.object({
4137
+ repo: z24.string().describe(
3970
4138
  'Repository in "owner/name" format. Required because GraphQL has no repo path.'
3971
4139
  ),
3972
- thread_id: z23.string().trim().min(1).describe(
4140
+ thread_id: z24.string().trim().min(1).describe(
3973
4141
  "GitHub pull request review thread node ID (the `threadId` / `id` variable used by `gh api graphql` resolveReviewThread)."
3974
4142
  )
3975
4143
  }).strict();
3976
4144
  var outputSchema15 = pluginToolOutputSchema17.extend({
3977
- target: z23.literal("resolvePullRequestReviewThread"),
3978
- repo: z23.string(),
3979
- number: z23.number(),
3980
- thread_id: z23.string(),
3981
- resolved: z23.boolean()
4145
+ target: z24.literal("resolvePullRequestReviewThread"),
4146
+ repo: z24.string(),
4147
+ number: z24.number(),
4148
+ thread_id: z24.string(),
4149
+ resolved: z24.boolean()
3982
4150
  });
3983
- function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
4151
+ function createGitHubResolvePullRequestReviewThreadTool(botEmail) {
3984
4152
  return definePluginTool17({
3985
4153
  // No action review: the tool checks in code that the bot authored the pull
3986
4154
  // request, and it changes only the thread's resolved state, which is
@@ -3996,7 +4164,7 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3996
4164
  exposure: "direct",
3997
4165
  inputSchema: inputSchema15,
3998
4166
  outputSchema: outputSchema15,
3999
- async execute(input) {
4167
+ async execute(input, _options, ctx) {
4000
4168
  const parsedInput = inputSchema15.safeParse(input);
4001
4169
  if (!parsedInput.success) {
4002
4170
  throw new PluginToolInputError18(
@@ -4024,18 +4192,18 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
4024
4192
  `GitHub review thread lookup failed with HTTP ${lookupResponse.status}: ${githubErrorMessage(lookupPayload)}`
4025
4193
  );
4026
4194
  }
4027
- const threadNodeSchema = z23.object({
4028
- id: z23.string(),
4029
- isResolved: z23.boolean(),
4030
- pullRequest: z23.object({
4031
- author: z23.object({ databaseId: z23.number().optional() }).passthrough().nullable(),
4032
- number: z23.number(),
4033
- repository: z23.object({ nameWithOwner: z23.string() }).passthrough()
4195
+ const threadNodeSchema = z24.object({
4196
+ id: z24.string(),
4197
+ isResolved: z24.boolean(),
4198
+ pullRequest: z24.object({
4199
+ author: z24.object({ databaseId: z24.number().optional() }).passthrough().nullable(),
4200
+ number: z24.number(),
4201
+ repository: z24.object({ nameWithOwner: z24.string() }).passthrough()
4034
4202
  }).passthrough()
4035
4203
  }).passthrough();
4036
- const lookupResultSchema = z23.object({
4037
- data: z23.object({
4038
- node: z23.unknown().nullable().optional()
4204
+ const lookupResultSchema = z24.object({
4205
+ data: z24.object({
4206
+ node: z24.unknown().nullable().optional()
4039
4207
  }).passthrough()
4040
4208
  }).passthrough();
4041
4209
  const lookupResult = lookupResultSchema.safeParse(lookupPayload);
@@ -4076,10 +4244,10 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
4076
4244
  `GitHub review thread resolution failed with HTTP ${resolveResponse.status}: ${githubErrorMessage(resolvePayload)}`
4077
4245
  );
4078
4246
  }
4079
- const resolveResultSchema = z23.object({
4080
- data: z23.object({
4081
- resolveReviewThread: z23.object({
4082
- thread: z23.object({ id: z23.string(), isResolved: z23.boolean() }).passthrough()
4247
+ const resolveResultSchema = z24.object({
4248
+ data: z24.object({
4249
+ resolveReviewThread: z24.object({
4250
+ thread: z24.object({ id: z24.string(), isResolved: z24.boolean() }).passthrough()
4083
4251
  }).passthrough()
4084
4252
  }).passthrough()
4085
4253
  }).passthrough();
@@ -4111,32 +4279,32 @@ import {
4111
4279
  PluginToolInputError as PluginToolInputError19,
4112
4280
  pluginToolOutputSchema as pluginToolOutputSchema18
4113
4281
  } from "@sentry/junior-plugin-api";
4114
- import * as z24 from "zod";
4115
- var reviewCommentSchema = z24.object({
4116
- path: z24.string().trim().min(1).describe("File path in the pull request."),
4117
- body: z24.string().trim().min(1).describe("Inline review comment."),
4118
- line: z24.number().int().positive().describe("Line in the pull request diff."),
4119
- side: z24.enum(["LEFT", "RIGHT"]).describe("Side of the pull request diff."),
4120
- start_line: z24.number().int().positive().optional().describe("First line of a multi-line comment."),
4121
- start_side: z24.enum(["LEFT", "RIGHT"]).optional().describe("First side of a multi-line comment.")
4282
+ import * as z25 from "zod";
4283
+ var reviewCommentSchema = z25.object({
4284
+ path: z25.string().trim().min(1).describe("File path in the pull request."),
4285
+ body: z25.string().trim().min(1).describe("Inline review comment."),
4286
+ line: z25.number().int().positive().describe("Line in the pull request diff."),
4287
+ side: z25.enum(["LEFT", "RIGHT"]).describe("Side of the pull request diff."),
4288
+ start_line: z25.number().int().positive().optional().describe("First line of a multi-line comment."),
4289
+ start_side: z25.enum(["LEFT", "RIGHT"]).optional().describe("First side of a multi-line comment.")
4122
4290
  }).strict().refine(
4123
4291
  ({ start_line, start_side }) => start_line === void 0 === (start_side === void 0),
4124
4292
  { message: "start_line and start_side must be provided together." }
4125
4293
  );
4126
- var inputSchema16 = z24.object({
4127
- repo: z24.string().describe('Repository in "owner/name" format.'),
4128
- number: z24.number().int().positive().describe("Pull request number."),
4129
- event: z24.enum(["COMMENT", "REQUEST_CHANGES"]).describe("Review result. You cannot approve pull requests."),
4130
- body: z24.string().trim().min(1).describe("Review summary."),
4131
- comments: z24.array(reviewCommentSchema).optional().describe("Optional inline review comments.")
4294
+ var inputSchema16 = z25.object({
4295
+ repo: z25.string().describe('Repository in "owner/name" format.'),
4296
+ number: z25.number().int().positive().describe("Pull request number."),
4297
+ event: z25.enum(["COMMENT", "REQUEST_CHANGES"]).describe("Review result. You cannot approve pull requests."),
4298
+ body: z25.string().trim().min(1).describe("Review summary."),
4299
+ comments: z25.array(reviewCommentSchema).optional().describe("Optional inline review comments.")
4132
4300
  }).strict();
4133
4301
  var outputSchema16 = pluginToolOutputSchema18.extend({
4134
- target: z24.literal("submitPullRequestReview"),
4135
- repo: z24.string(),
4136
- number: z24.number(),
4137
- review_id: z24.number(),
4138
- state: z24.string(),
4139
- url: z24.string()
4302
+ target: z25.literal("submitPullRequestReview"),
4303
+ repo: z25.string(),
4304
+ number: z25.number(),
4305
+ review_id: z25.number(),
4306
+ state: z25.string(),
4307
+ url: z25.string()
4140
4308
  });
4141
4309
  function throwReviewError(status, body) {
4142
4310
  const message = `GitHub pull request review failed with HTTP ${status}: ${githubErrorMessage(body)}`;
@@ -4145,136 +4313,122 @@ function throwReviewError(status, body) {
4145
4313
  }
4146
4314
  throw new Error(message);
4147
4315
  }
4148
- function createGitHubSubmitPullRequestReviewTool(egress) {
4149
- return definePluginTool18({
4150
- annotations: {
4151
- destructiveHint: true,
4152
- idempotentHint: false,
4153
- openWorldHint: true,
4154
- readOnlyHint: false
4155
- },
4156
- description: "Submit a GitHub pull request review as a comment or change request. Use this instead of `gh pr review`, GraphQL, or direct REST calls. You cannot approve pull requests.",
4157
- inputSchema: inputSchema16,
4158
- outputSchema: outputSchema16,
4159
- async execute(review) {
4160
- const repo = parseRepo(review.repo);
4161
- const comments = review.comments?.map((comment) => ({
4162
- path: comment.path,
4163
- body: comment.body,
4164
- line: comment.line,
4165
- side: comment.side,
4166
- ...comment.start_line !== void 0 ? { start_line: comment.start_line } : void 0,
4167
- ...comment.start_side !== void 0 ? { start_side: comment.start_side } : void 0
4168
- }));
4169
- const response = await githubApi(egress, {
4170
- operation: "github.pull.review.create",
4171
- method: "POST",
4172
- path: `${repoPath(repo)}/pulls/${review.number}/reviews`,
4173
- body: {
4174
- body: review.body,
4175
- event: review.event,
4176
- ...comments ? { comments } : void 0
4177
- }
4178
- });
4179
- if (!response.ok) {
4180
- throwReviewError(response.status, response.body);
4316
+ var gitHubSubmitPullRequestReviewTool = definePluginTool18({
4317
+ annotations: {
4318
+ destructiveHint: true,
4319
+ idempotentHint: false,
4320
+ openWorldHint: true,
4321
+ readOnlyHint: false
4322
+ },
4323
+ description: "Submit a GitHub pull request review as a comment or change request. Use this instead of `gh pr review`, GraphQL, or direct REST calls. You cannot approve pull requests.",
4324
+ inputSchema: inputSchema16,
4325
+ outputSchema: outputSchema16,
4326
+ async execute(review, _options, { egress }) {
4327
+ const repo = parseRepo(review.repo);
4328
+ const comments = review.comments?.map((comment) => ({
4329
+ path: comment.path,
4330
+ body: comment.body,
4331
+ line: comment.line,
4332
+ side: comment.side,
4333
+ ...comment.start_line !== void 0 ? { start_line: comment.start_line } : void 0,
4334
+ ...comment.start_side !== void 0 ? { start_side: comment.start_side } : void 0
4335
+ }));
4336
+ const response = await githubApi(egress, {
4337
+ operation: "github.pull.review.create",
4338
+ method: "POST",
4339
+ path: `${repoPath(repo)}/pulls/${review.number}/reviews`,
4340
+ body: {
4341
+ body: review.body,
4342
+ event: review.event,
4343
+ ...comments ? { comments } : void 0
4181
4344
  }
4182
- const providerResult = z24.object({ id: z24.number(), html_url: z24.string(), state: z24.string() }).parse(response.body);
4183
- return {
4184
- target: "submitPullRequestReview",
4185
- repo: repo.ref,
4186
- number: review.number,
4187
- reply: { text: review.body, url: providerResult.html_url },
4188
- review_id: providerResult.id,
4189
- state: providerResult.state,
4190
- url: providerResult.html_url
4191
- };
4345
+ });
4346
+ if (!response.ok) {
4347
+ throwReviewError(response.status, response.body);
4192
4348
  }
4193
- });
4194
- }
4349
+ const providerResult = z25.object({ id: z25.number(), html_url: z25.string(), state: z25.string() }).parse(response.body);
4350
+ return {
4351
+ target: "submitPullRequestReview",
4352
+ repo: repo.ref,
4353
+ number: review.number,
4354
+ reply: { text: review.body, url: providerResult.html_url },
4355
+ review_id: providerResult.id,
4356
+ state: providerResult.state,
4357
+ url: providerResult.html_url
4358
+ };
4359
+ }
4360
+ });
4195
4361
 
4196
4362
  // src/tool-support/github-text.ts
4197
- function withGitHubText(tools, users) {
4363
+ function withGitHubText(tools) {
4198
4364
  return Object.fromEntries(
4199
4365
  Object.entries(tools).map(([name, tool]) => {
4200
4366
  const execute = tool.execute;
4201
4367
  if (!execute) return [name, tool];
4202
- const wrapped = Object.create(tool);
4203
- wrapped.execute = async (input, options) => await execute.call(
4204
- tool,
4205
- await users.replaceSlackMentions(input, "github"),
4206
- options
4207
- );
4368
+ const wrapped = {
4369
+ ...tool,
4370
+ execute: async (input, options, ctx) => await execute.call(
4371
+ tool,
4372
+ await ctx.users.replaceSlackMentions(input, "github"),
4373
+ options,
4374
+ ctx
4375
+ )
4376
+ };
4208
4377
  return [name, wrapped];
4209
4378
  })
4210
4379
  );
4211
4380
  }
4212
4381
 
4213
4382
  // src/tools.ts
4214
- function createGitHubTools(ctx, botEmail, pullRequestSubscription, experimental = {}) {
4215
- const descriptionDecider = experimental.pullRequestDescriptionChecks ? ctx.decider : void 0;
4216
- return withGitHubText(
4217
- {
4218
- reactToIssue: createGitHubReactToIssueTool(ctx.egress),
4219
- cloneRepository: createGitHubCloneRepositoryTool(ctx),
4220
- commentOnIssue: createGitHubCommentOnIssueTool(ctx.egress),
4221
- commentOnPullRequest: createGitHubCommentOnPullRequestTool(ctx.egress),
4222
- createIssue: createGitHubIssueTool(ctx),
4223
- createPullRequest: createGitHubPullRequestTool(
4224
- ctx,
4225
- pullRequestSubscription,
4226
- descriptionDecider
4227
- ),
4228
- getDeployment: createGitHubGetDeploymentTool(ctx),
4229
- getIssue: createGitHubGetIssueTool(ctx),
4230
- getPullRequest: createGitHubGetPullRequestTool(ctx),
4231
- getRelease: createGitHubGetReleaseTool(ctx),
4232
- getRepository: createGitHubGetRepositoryTool(ctx),
4233
- getStatus: createGitHubGetStatusTool(ctx),
4234
- resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail),
4235
- submitPullRequestReview: createGitHubSubmitPullRequestReviewTool(
4236
- ctx.egress
4237
- ),
4238
- updateIssue: createGitHubUpdateIssueTool(ctx),
4239
- updateIssueComment: createGitHubUpdateIssueCommentTool(
4240
- ctx.egress,
4241
- botEmail
4242
- ),
4243
- updatePullRequest: createGitHubUpdatePullRequestTool(
4244
- ctx,
4245
- descriptionDecider
4246
- ),
4247
- updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(
4248
- ctx,
4249
- botEmail
4250
- )
4251
- },
4252
- ctx.users
4253
- );
4383
+ function createGitHubTools(botEmail, pullRequestSubscription, experimental = {}) {
4384
+ const descriptionChecks = experimental.pullRequestDescriptionChecks ?? false;
4385
+ return withGitHubText({
4386
+ reactToIssue: gitHubReactToIssueTool,
4387
+ cloneRepository: gitHubCloneRepositoryTool,
4388
+ commentOnIssue: gitHubCommentOnIssueTool,
4389
+ commentOnPullRequest: gitHubCommentOnPullRequestTool,
4390
+ createIssue: gitHubIssueTool,
4391
+ createPullRequest: createGitHubPullRequestTool(
4392
+ pullRequestSubscription,
4393
+ descriptionChecks
4394
+ ),
4395
+ getDeployment: gitHubGetDeploymentTool,
4396
+ getIssue: gitHubGetIssueTool,
4397
+ getPullRequest: gitHubGetPullRequestTool,
4398
+ getRelease: gitHubGetReleaseTool,
4399
+ getRepository: gitHubGetRepositoryTool,
4400
+ getStatus: gitHubGetStatusTool,
4401
+ resolvePullRequestReviewThread: createGitHubResolvePullRequestReviewThreadTool(botEmail),
4402
+ submitPullRequestReview: gitHubSubmitPullRequestReviewTool,
4403
+ updateIssue: gitHubUpdateIssueTool,
4404
+ updateIssueComment: createGitHubUpdateIssueCommentTool(botEmail),
4405
+ updatePullRequest: createGitHubUpdatePullRequestTool(descriptionChecks),
4406
+ updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(botEmail)
4407
+ });
4254
4408
  }
4255
4409
 
4256
4410
  // src/webhooks/handler.ts
4257
4411
  import { createHmac, timingSafeEqual } from "crypto";
4258
- import * as z40 from "zod";
4412
+ import * as z41 from "zod";
4259
4413
 
4260
4414
  // src/issue-outcomes/store.ts
4261
4415
  import { and as and2, eq as eq2, lte, sql as sql2 } from "drizzle-orm";
4262
- import * as z25 from "zod";
4263
- var githubIssueOutcomeInputSchema = z25.object({
4264
- candidateOwned: z25.boolean(),
4265
- closedAt: z25.date().optional(),
4266
- issueId: z25.string().min(1),
4267
- number: z25.number().int().positive(),
4268
- openedAt: z25.date(),
4269
- repositoryFullName: z25.string().min(1),
4270
- repositoryId: z25.string().min(1),
4416
+ import * as z26 from "zod";
4417
+ var githubIssueOutcomeInputSchema = z26.object({
4418
+ candidateOwned: z26.boolean(),
4419
+ closedAt: z26.date().optional(),
4420
+ issueId: z26.string().min(1),
4421
+ number: z26.number().int().positive(),
4422
+ openedAt: z26.date(),
4423
+ repositoryFullName: z26.string().min(1),
4424
+ repositoryId: z26.string().min(1),
4271
4425
  state: githubIssueStateSchema,
4272
4426
  stateReason: githubIssueStateReasonSchema.optional(),
4273
- updatedAt: z25.date()
4427
+ updatedAt: z26.date()
4274
4428
  }).strict();
4275
- var githubIssueConversationsInputSchema = z25.object({
4276
- conversationIds: z25.array(z25.string().min(1)).min(1),
4277
- issueId: z25.string().min(1)
4429
+ var githubIssueConversationsInputSchema = z26.object({
4430
+ conversationIds: z26.array(z26.string().min(1)).min(1),
4431
+ issueId: z26.string().min(1)
4278
4432
  }).strict();
4279
4433
  function projectionValues(input) {
4280
4434
  return {
@@ -4338,35 +4492,35 @@ async function recordGitHubIssueConversations(db, input) {
4338
4492
 
4339
4493
  // src/pull-request-outcomes/store.ts
4340
4494
  import { and as and3, eq as eq3, lt as lt2, lte as lte2, ne, sql as sql3 } from "drizzle-orm";
4341
- import * as z26 from "zod";
4342
- var githubPullRequestOutcomeInputSchema = z26.object({
4343
- candidateOwned: z26.boolean(),
4344
- closedAt: z26.date().optional(),
4495
+ import * as z27 from "zod";
4496
+ var githubPullRequestOutcomeInputSchema = z27.object({
4497
+ candidateOwned: z27.boolean(),
4498
+ closedAt: z27.date().optional(),
4345
4499
  commitComposition: githubPullRequestCommitCompositionSchema.optional(),
4346
4500
  /** When omitted, the stored draft state does not change. */
4347
- draft: z26.boolean().optional(),
4348
- mergedAt: z26.date().optional(),
4349
- number: z26.number().int().positive(),
4350
- openedAt: z26.date(),
4351
- pullRequestId: z26.string().min(1),
4352
- repositoryFullName: z26.string().min(1),
4353
- repositoryId: z26.string().min(1),
4501
+ draft: z27.boolean().optional(),
4502
+ mergedAt: z27.date().optional(),
4503
+ number: z27.number().int().positive(),
4504
+ openedAt: z27.date(),
4505
+ pullRequestId: z27.string().min(1),
4506
+ repositoryFullName: z27.string().min(1),
4507
+ repositoryId: z27.string().min(1),
4354
4508
  state: githubPullRequestStateSchema,
4355
- title: z26.string().min(1).optional(),
4356
- updatedAt: z26.date()
4509
+ title: z27.string().min(1).optional(),
4510
+ updatedAt: z27.date()
4357
4511
  }).strict();
4358
- var githubPullRequestConversationsInputSchema = z26.object({
4359
- conversationIds: z26.array(z26.string().min(1)).min(1),
4360
- pullRequestId: z26.string().min(1)
4512
+ var githubPullRequestConversationsInputSchema = z27.object({
4513
+ conversationIds: z27.array(z27.string().min(1)).min(1),
4514
+ pullRequestId: z27.string().min(1)
4361
4515
  }).strict();
4362
- var githubPullRequestLinkedIssuesInputSchema = z26.object({
4363
- linkedIssues: z26.array(
4364
- z26.object({
4365
- number: z26.number().int().positive(),
4366
- repositoryFullName: z26.string().min(1)
4516
+ var githubPullRequestLinkedIssuesInputSchema = z27.object({
4517
+ linkedIssues: z27.array(
4518
+ z27.object({
4519
+ number: z27.number().int().positive(),
4520
+ repositoryFullName: z27.string().min(1)
4367
4521
  }).strict()
4368
4522
  ).min(1),
4369
- pullRequestId: z26.string().min(1)
4523
+ pullRequestId: z27.string().min(1)
4370
4524
  }).strict();
4371
4525
  function projectionValues2(input) {
4372
4526
  return {
@@ -4561,19 +4715,19 @@ async function claimGitHubPullRequestReadySync(db, target, options) {
4561
4715
  readySyncId: sql3`case when ${free} then ${t.readySyncRequests} + 1 else ${t.readySyncId} end`,
4562
4716
  readySyncAt: sql3`case when ${free} then ${options.now.toISOString()}::timestamptz else ${t.readySyncAt} end`
4563
4717
  }).where(pullRequestRow(target)).returning({
4718
+ action: t.nextAction,
4564
4719
  id: t.readySyncId,
4565
- readyToMergeAt: t.readyToMergeAt,
4566
4720
  requests: t.readySyncRequests
4567
4721
  });
4568
4722
  if (!row || row.id !== row.requests) return void 0;
4569
4723
  return {
4724
+ action: row.action ?? void 0,
4570
4725
  id: row.id,
4571
- ready: row.readyToMergeAt !== null,
4572
4726
  requests: row.requests
4573
4727
  };
4574
4728
  }
4575
- async function setGitHubPullRequestReadyToMerge(db, target) {
4576
- await db.update(juniorGitHubPullRequests).set({ readyToMergeAt: target.ready ? /* @__PURE__ */ new Date() : null }).where(pullRequestRow(target));
4729
+ async function setGitHubPullRequestNextAction(db, target) {
4730
+ await db.update(juniorGitHubPullRequests).set({ nextAction: target.action ?? null }).where(pullRequestRow(target));
4577
4731
  }
4578
4732
  async function releaseGitHubPullRequestReadySync(db, target, claim) {
4579
4733
  const t = juniorGitHubPullRequests;
@@ -4629,39 +4783,39 @@ async function applyGitHubPullRequestOutcome(args) {
4629
4783
  }
4630
4784
 
4631
4785
  // src/webhooks/issue-outcome.ts
4632
- import * as z27 from "zod";
4633
- var canonicalIssueOutcomeSchema = z27.object({
4634
- action: z27.enum(["opened", "closed", "reopened"]),
4635
- issue: z27.object({
4636
- body: z27.string().nullable().optional(),
4637
- closed_at: z27.string().nullable().optional(),
4638
- created_at: z27.string(),
4639
- id: z27.number().int().positive(),
4640
- number: z27.number().int().positive(),
4786
+ import * as z28 from "zod";
4787
+ var canonicalIssueOutcomeSchema = z28.object({
4788
+ action: z28.enum(["opened", "closed", "reopened"]),
4789
+ issue: z28.object({
4790
+ body: z28.string().nullable().optional(),
4791
+ closed_at: z28.string().nullable().optional(),
4792
+ created_at: z28.string(),
4793
+ id: z28.number().int().positive(),
4794
+ number: z28.number().int().positive(),
4641
4795
  state_reason: githubIssueStateReasonSchema.nullable().optional(),
4642
- updated_at: z27.string(),
4643
- user: z27.object({ login: z27.string().min(1) }).strict()
4796
+ updated_at: z28.string(),
4797
+ user: z28.object({ login: z28.string().min(1) }).strict()
4644
4798
  }).strict(),
4645
- repository: z27.object({
4646
- full_name: z27.string().min(1),
4647
- id: z27.number().int().positive()
4799
+ repository: z28.object({
4800
+ full_name: z28.string().min(1),
4801
+ id: z28.number().int().positive()
4648
4802
  }).strict()
4649
4803
  }).strict();
4650
- var issueOutcomeSchema = z27.object({
4651
- action: z27.enum(["opened", "closed", "reopened"]),
4652
- issue: z27.object({
4653
- body: z27.string().nullable().optional(),
4654
- closed_at: z27.string().nullable().optional(),
4655
- created_at: z27.string(),
4656
- id: z27.number().int().positive(),
4657
- number: z27.number().int().positive(),
4804
+ var issueOutcomeSchema = z28.object({
4805
+ action: z28.enum(["opened", "closed", "reopened"]),
4806
+ issue: z28.object({
4807
+ body: z28.string().nullable().optional(),
4808
+ closed_at: z28.string().nullable().optional(),
4809
+ created_at: z28.string(),
4810
+ id: z28.number().int().positive(),
4811
+ number: z28.number().int().positive(),
4658
4812
  state_reason: githubIssueStateReasonSchema.nullable().optional(),
4659
- updated_at: z27.string(),
4660
- user: z27.object({ login: z27.string().min(1) }).passthrough()
4813
+ updated_at: z28.string(),
4814
+ user: z28.object({ login: z28.string().min(1) }).passthrough()
4661
4815
  }).passthrough(),
4662
- repository: z27.object({
4663
- full_name: z27.string().min(1),
4664
- id: z27.number().int().positive()
4816
+ repository: z28.object({
4817
+ full_name: z28.string().min(1),
4818
+ id: z28.number().int().positive()
4665
4819
  }).passthrough()
4666
4820
  }).passthrough().transform(
4667
4821
  (provider) => canonicalIssueOutcomeSchema.parse({
@@ -4682,7 +4836,7 @@ var issueOutcomeSchema = z27.object({
4682
4836
  }
4683
4837
  })
4684
4838
  );
4685
- var issueLifecycleActionSchema = z27.object({ action: z27.string() }).passthrough();
4839
+ var issueLifecycleActionSchema = z28.object({ action: z28.string() }).passthrough();
4686
4840
  function timestamp2(value) {
4687
4841
  if (!value) return void 0;
4688
4842
  const parsed = new Date(value);
@@ -4726,21 +4880,21 @@ function normalizeGitHubIssueOutcome(args) {
4726
4880
  updatedAt
4727
4881
  };
4728
4882
  }
4729
- var canonicalIssueConversationSchema = z27.object({
4730
- issue: z27.object({
4731
- body: z27.string().nullable().optional(),
4732
- id: z27.number().int().positive(),
4733
- user: z27.object({ login: z27.string().min(1) }).strict()
4883
+ var canonicalIssueConversationSchema = z28.object({
4884
+ issue: z28.object({
4885
+ body: z28.string().nullable().optional(),
4886
+ id: z28.number().int().positive(),
4887
+ user: z28.object({ login: z28.string().min(1) }).strict()
4734
4888
  }).strict(),
4735
- sender: z27.object({ login: z27.string().min(1) }).strict().optional()
4889
+ sender: z28.object({ login: z28.string().min(1) }).strict().optional()
4736
4890
  }).strict();
4737
- var issueConversationSchema = z27.object({
4738
- issue: z27.object({
4739
- body: z27.string().nullable().optional(),
4740
- id: z27.number().int().positive(),
4741
- user: z27.object({ login: z27.string().min(1) }).passthrough()
4891
+ var issueConversationSchema = z28.object({
4892
+ issue: z28.object({
4893
+ body: z28.string().nullable().optional(),
4894
+ id: z28.number().int().positive(),
4895
+ user: z28.object({ login: z28.string().min(1) }).passthrough()
4742
4896
  }).passthrough(),
4743
- sender: z27.object({ login: z27.string().min(1) }).passthrough().optional()
4897
+ sender: z28.object({ login: z28.string().min(1) }).passthrough().optional()
4744
4898
  }).passthrough().transform(
4745
4899
  (provider) => canonicalIssueConversationSchema.parse({
4746
4900
  issue: {
@@ -4767,52 +4921,52 @@ function normalizeGitHubIssueConversations(args) {
4767
4921
  }
4768
4922
 
4769
4923
  // src/webhooks/pull-request-outcome.ts
4770
- import * as z28 from "zod";
4771
- var pullRequestLifecycleActionsSchema = z28.enum([
4924
+ import * as z29 from "zod";
4925
+ var pullRequestLifecycleActionsSchema = z29.enum([
4772
4926
  "opened",
4773
4927
  "closed",
4774
4928
  "reopened",
4775
4929
  "ready_for_review",
4776
4930
  "converted_to_draft"
4777
4931
  ]);
4778
- var canonicalPullRequestOutcomeSchema = z28.object({
4932
+ var canonicalPullRequestOutcomeSchema = z29.object({
4779
4933
  action: pullRequestLifecycleActionsSchema,
4780
- pull_request: z28.object({
4781
- body: z28.string().nullable().optional(),
4782
- closed_at: z28.string().nullable().optional(),
4783
- created_at: z28.string(),
4784
- draft: z28.boolean().optional(),
4785
- id: z28.number().int().positive(),
4786
- merged: z28.boolean(),
4787
- merged_at: z28.string().nullable().optional(),
4788
- number: z28.number().int().positive(),
4789
- title: z28.string().min(1).optional(),
4790
- updated_at: z28.string(),
4791
- user: z28.object({ login: z28.string().min(1) }).strict()
4934
+ pull_request: z29.object({
4935
+ body: z29.string().nullable().optional(),
4936
+ closed_at: z29.string().nullable().optional(),
4937
+ created_at: z29.string(),
4938
+ draft: z29.boolean().optional(),
4939
+ id: z29.number().int().positive(),
4940
+ merged: z29.boolean(),
4941
+ merged_at: z29.string().nullable().optional(),
4942
+ number: z29.number().int().positive(),
4943
+ title: z29.string().min(1).optional(),
4944
+ updated_at: z29.string(),
4945
+ user: z29.object({ login: z29.string().min(1) }).strict()
4792
4946
  }).strict(),
4793
- repository: z28.object({
4794
- full_name: z28.string().min(1),
4795
- id: z28.number().int().positive()
4947
+ repository: z29.object({
4948
+ full_name: z29.string().min(1),
4949
+ id: z29.number().int().positive()
4796
4950
  }).strict()
4797
4951
  }).strict();
4798
- var pullRequestOutcomeSchema = z28.object({
4952
+ var pullRequestOutcomeSchema = z29.object({
4799
4953
  action: pullRequestLifecycleActionsSchema,
4800
- pull_request: z28.object({
4801
- body: z28.string().nullable().optional(),
4802
- closed_at: z28.string().nullable().optional(),
4803
- created_at: z28.string(),
4804
- draft: z28.boolean().optional(),
4805
- id: z28.number().int().positive(),
4806
- merged: z28.boolean(),
4807
- merged_at: z28.string().nullable().optional(),
4808
- number: z28.number().int().positive(),
4809
- title: z28.string().min(1).optional(),
4810
- updated_at: z28.string(),
4811
- user: z28.object({ login: z28.string().min(1) }).passthrough()
4954
+ pull_request: z29.object({
4955
+ body: z29.string().nullable().optional(),
4956
+ closed_at: z29.string().nullable().optional(),
4957
+ created_at: z29.string(),
4958
+ draft: z29.boolean().optional(),
4959
+ id: z29.number().int().positive(),
4960
+ merged: z29.boolean(),
4961
+ merged_at: z29.string().nullable().optional(),
4962
+ number: z29.number().int().positive(),
4963
+ title: z29.string().min(1).optional(),
4964
+ updated_at: z29.string(),
4965
+ user: z29.object({ login: z29.string().min(1) }).passthrough()
4812
4966
  }).passthrough(),
4813
- repository: z28.object({
4814
- full_name: z28.string().min(1),
4815
- id: z28.number().int().positive()
4967
+ repository: z29.object({
4968
+ full_name: z29.string().min(1),
4969
+ id: z29.number().int().positive()
4816
4970
  }).passthrough()
4817
4971
  }).passthrough().transform(
4818
4972
  (provider) => canonicalPullRequestOutcomeSchema.parse({
@@ -4836,24 +4990,24 @@ var pullRequestOutcomeSchema = z28.object({
4836
4990
  }
4837
4991
  })
4838
4992
  );
4839
- var pullRequestLifecycleActionSchema = z28.object({ action: z28.string() }).passthrough();
4840
- var canonicalPullRequestConversationSchema = z28.object({
4841
- pull_request: z28.object({
4842
- body: z28.string().nullable().optional(),
4843
- id: z28.number().int().positive(),
4844
- user: z28.object({ login: z28.string().min(1) }).strict()
4993
+ var pullRequestLifecycleActionSchema = z29.object({ action: z29.string() }).passthrough();
4994
+ var canonicalPullRequestConversationSchema = z29.object({
4995
+ pull_request: z29.object({
4996
+ body: z29.string().nullable().optional(),
4997
+ id: z29.number().int().positive(),
4998
+ user: z29.object({ login: z29.string().min(1) }).strict()
4845
4999
  }).strict(),
4846
- repository: z28.object({ full_name: z28.string().min(1) }).strict(),
4847
- sender: z28.object({ login: z28.string().min(1) }).strict()
5000
+ repository: z29.object({ full_name: z29.string().min(1) }).strict(),
5001
+ sender: z29.object({ login: z29.string().min(1) }).strict()
4848
5002
  }).strict();
4849
- var pullRequestConversationSchema = z28.object({
4850
- pull_request: z28.object({
4851
- body: z28.string().nullable().optional(),
4852
- id: z28.number().int().positive(),
4853
- user: z28.object({ login: z28.string().min(1) }).passthrough()
5003
+ var pullRequestConversationSchema = z29.object({
5004
+ pull_request: z29.object({
5005
+ body: z29.string().nullable().optional(),
5006
+ id: z29.number().int().positive(),
5007
+ user: z29.object({ login: z29.string().min(1) }).passthrough()
4854
5008
  }).passthrough(),
4855
- repository: z28.object({ full_name: z28.string().min(1) }).passthrough(),
4856
- sender: z28.object({ login: z28.string().min(1) }).passthrough()
5009
+ repository: z29.object({ full_name: z29.string().min(1) }).passthrough(),
5010
+ sender: z29.object({ login: z29.string().min(1) }).passthrough()
4857
5011
  }).passthrough().transform(
4858
5012
  (provider) => canonicalPullRequestConversationSchema.parse({
4859
5013
  pull_request: {
@@ -4940,17 +5094,17 @@ function normalizeGitHubPullRequestLinkedIssues(args) {
4940
5094
  }
4941
5095
 
4942
5096
  // src/webhooks/pull-request-activity.ts
4943
- import * as z29 from "zod";
4944
- var timestampSchema = z29.iso.datetime({ offset: true });
4945
- var numberSchema = z29.number().int().positive();
4946
- var repositorySchema2 = z29.object({ id: numberSchema });
4947
- var senderSchema = z29.object({ type: z29.string() });
5097
+ import * as z30 from "zod";
5098
+ var timestampSchema = z30.iso.datetime({ offset: true });
5099
+ var numberSchema = z30.number().int().positive();
5100
+ var repositorySchema2 = z30.object({ id: numberSchema });
5101
+ var senderSchema = z30.object({ type: z30.string() });
4948
5102
  var activitySchemas = {
4949
- issue_comment: z29.object({
4950
- action: z29.literal("created"),
4951
- comment: z29.object({ created_at: timestampSchema }),
5103
+ issue_comment: z30.object({
5104
+ action: z30.literal("created"),
5105
+ comment: z30.object({ created_at: timestampSchema }),
4952
5106
  // Only comments on a pull request carry `issue.pull_request`.
4953
- issue: z29.object({ number: numberSchema, pull_request: z29.object({}) }),
5107
+ issue: z30.object({ number: numberSchema, pull_request: z30.object({}) }),
4954
5108
  repository: repositorySchema2,
4955
5109
  sender: senderSchema
4956
5110
  }).transform((event) => ({
@@ -4959,9 +5113,9 @@ var activitySchemas = {
4959
5113
  repositoryProviderId: String(event.repository.id),
4960
5114
  senderType: event.sender.type
4961
5115
  })),
4962
- pull_request: z29.object({
4963
- action: z29.literal("synchronize"),
4964
- pull_request: z29.object({
5116
+ pull_request: z30.object({
5117
+ action: z30.literal("synchronize"),
5118
+ pull_request: z30.object({
4965
5119
  number: numberSchema,
4966
5120
  updated_at: timestampSchema
4967
5121
  }),
@@ -4973,11 +5127,11 @@ var activitySchemas = {
4973
5127
  repositoryProviderId: String(event.repository.id),
4974
5128
  senderType: event.sender.type
4975
5129
  })),
4976
- pull_request_review: z29.object({
4977
- action: z29.literal("submitted"),
4978
- pull_request: z29.object({ number: numberSchema }),
5130
+ pull_request_review: z30.object({
5131
+ action: z30.literal("submitted"),
5132
+ pull_request: z30.object({ number: numberSchema }),
4979
5133
  repository: repositorySchema2,
4980
- review: z29.object({ submitted_at: timestampSchema }),
5134
+ review: z30.object({ submitted_at: timestampSchema }),
4981
5135
  sender: senderSchema
4982
5136
  }).transform((event) => ({
4983
5137
  at: new Date(event.review.submitted_at),
@@ -4985,10 +5139,10 @@ var activitySchemas = {
4985
5139
  repositoryProviderId: String(event.repository.id),
4986
5140
  senderType: event.sender.type
4987
5141
  })),
4988
- pull_request_review_comment: z29.object({
4989
- action: z29.literal("created"),
4990
- comment: z29.object({ created_at: timestampSchema }),
4991
- pull_request: z29.object({ number: numberSchema }),
5142
+ pull_request_review_comment: z30.object({
5143
+ action: z30.literal("created"),
5144
+ comment: z30.object({ created_at: timestampSchema }),
5145
+ pull_request: z30.object({ number: numberSchema }),
4992
5146
  repository: repositorySchema2,
4993
5147
  sender: senderSchema
4994
5148
  }).transform((event) => ({
@@ -5007,16 +5161,16 @@ function normalizeGitHubPullRequestActivity(input) {
5007
5161
  }
5008
5162
 
5009
5163
  // src/webhooks/pull-request-preview.ts
5010
- import * as z30 from "zod";
5011
- var previewWebhookSchema = z30.object({
5012
- action: z30.enum(["opened", "edited", "synchronize", "ready_for_review"]),
5013
- pull_request: z30.object({
5014
- body: z30.string().nullable().optional(),
5015
- id: z30.number().int().positive(),
5016
- number: z30.number().int().positive(),
5017
- updated_at: z30.iso.datetime({ offset: true })
5164
+ import * as z31 from "zod";
5165
+ var previewWebhookSchema = z31.object({
5166
+ action: z31.enum(["opened", "edited", "synchronize", "ready_for_review"]),
5167
+ pull_request: z31.object({
5168
+ body: z31.string().nullable().optional(),
5169
+ id: z31.number().int().positive(),
5170
+ number: z31.number().int().positive(),
5171
+ updated_at: z31.iso.datetime({ offset: true })
5018
5172
  }),
5019
- repository: z30.object({ full_name: z30.string().min(1) })
5173
+ repository: z31.object({ full_name: z31.string().min(1) })
5020
5174
  });
5021
5175
  async function refreshGitHubPullRequestPreview(args) {
5022
5176
  const parsed = previewWebhookSchema.safeParse(args.body);
@@ -5070,20 +5224,221 @@ async function refreshGitHubPullRequestPreview(args) {
5070
5224
  }
5071
5225
 
5072
5226
  // src/webhooks/merge-conflict.ts
5073
- import * as z31 from "zod";
5227
+ import * as z33 from "zod";
5228
+
5229
+ // src/merge-conflict-checks/policy.ts
5230
+ import { and as and4, eq as eq4 } from "drizzle-orm";
5231
+ import * as z32 from "zod";
5232
+ var DAY_MS = 24 * 60 * 6e4;
5233
+ var ACTIVE_MS = 2 * DAY_MS;
5234
+ var IDLE_MS = 3 * DAY_MS;
5235
+ var FIX_INTERVAL_MS = DAY_MS;
5236
+ var MAX_FIXES = 3;
5237
+ var actorSchema = z32.object({ __typename: z32.string() }).nullable();
5238
+ var timelineItemSchema = z32.union([
5239
+ z32.object({
5240
+ __typename: z32.literal("PullRequestCommit"),
5241
+ commit: z32.object({
5242
+ author: z32.object({ user: z32.object({ login: z32.string() }).nullable() }).nullable(),
5243
+ committedDate: z32.string(),
5244
+ parents: z32.object({ totalCount: z32.number() })
5245
+ })
5246
+ }),
5247
+ z32.object({
5248
+ __typename: z32.literal("PullRequestReview"),
5249
+ author: actorSchema,
5250
+ submittedAt: z32.string().nullable()
5251
+ }),
5252
+ z32.object({
5253
+ __typename: z32.literal("IssueComment"),
5254
+ author: actorSchema,
5255
+ createdAt: z32.string()
5256
+ }),
5257
+ z32.object({
5258
+ __typename: z32.literal("HeadRefForcePushedEvent"),
5259
+ actor: actorSchema,
5260
+ createdAt: z32.string()
5261
+ })
5262
+ ]);
5263
+ var historyResponseSchema = z32.object({
5264
+ data: z32.object({
5265
+ repository: z32.object({
5266
+ pullRequest: z32.object({
5267
+ createdAt: z32.string(),
5268
+ discussion: z32.object({
5269
+ nodes: z32.array(timelineItemSchema.nullable())
5270
+ }),
5271
+ pushes: z32.object({
5272
+ nodes: z32.array(timelineItemSchema.nullable())
5273
+ }),
5274
+ reviewDecision: z32.string().nullable()
5275
+ })
5276
+ })
5277
+ })
5278
+ });
5279
+ function parseGitHubConflictHistory(response) {
5280
+ const pullRequest = historyResponseSchema.parse(response).data.repository.pullRequest;
5281
+ let activeAtMs = Date.parse(pullRequest.createdAt);
5282
+ let fixedAtMs;
5283
+ let fixes = 0;
5284
+ const record = (bot, fix, at) => {
5285
+ if (!at) return;
5286
+ const atMs = Date.parse(at);
5287
+ if (!bot) {
5288
+ activeAtMs = Math.max(activeAtMs, atMs);
5289
+ } else if (fix) {
5290
+ fixes += 1;
5291
+ fixedAtMs = Math.max(fixedAtMs ?? 0, atMs);
5292
+ }
5293
+ };
5294
+ for (const item of [
5295
+ ...pullRequest.pushes.nodes,
5296
+ ...pullRequest.discussion.nodes
5297
+ ]) {
5298
+ if (!item) continue;
5299
+ switch (item.__typename) {
5300
+ case "PullRequestCommit": {
5301
+ const login = item.commit.author?.user?.login;
5302
+ record(
5303
+ login?.endsWith("[bot]") === true,
5304
+ item.commit.parents.totalCount > 1,
5305
+ item.commit.committedDate
5306
+ );
5307
+ break;
5308
+ }
5309
+ case "HeadRefForcePushedEvent":
5310
+ record(item.actor?.__typename === "Bot", true, item.createdAt);
5311
+ break;
5312
+ case "PullRequestReview":
5313
+ record(item.author?.__typename === "Bot", false, item.submittedAt);
5314
+ break;
5315
+ case "IssueComment":
5316
+ record(item.author?.__typename === "Bot", false, item.createdAt);
5317
+ break;
5318
+ }
5319
+ }
5320
+ return {
5321
+ activeAtMs,
5322
+ approved: pullRequest.reviewDecision === "APPROVED",
5323
+ fixes,
5324
+ ...fixedAtMs === void 0 ? void 0 : { fixedAtMs }
5325
+ };
5326
+ }
5327
+ function gitHubConflictAction(history, nowMs) {
5328
+ const { approved, fixedAtMs } = history;
5329
+ const idleMs = nowMs - history.activeAtMs;
5330
+ if (idleMs > IDLE_MS && !approved) return "skip";
5331
+ if ((idleMs <= ACTIVE_MS || approved) && history.fixes < MAX_FIXES) {
5332
+ return !approved && fixedAtMs !== void 0 && nowMs - fixedAtMs < FIX_INTERVAL_MS ? "skip" : "fix";
5333
+ }
5334
+ return "notice";
5335
+ }
5336
+ function gitHubConflictNoticeKey(ref) {
5337
+ return `merge-conflict:${ref.repositoryFullName.toLowerCase()}#${ref.number}`;
5338
+ }
5339
+ async function addNotice(args, fixes) {
5340
+ const { conflict, ref, title } = args;
5341
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
5342
+ numbers: [ref.number],
5343
+ repositoryFullName: ref.repositoryFullName
5344
+ })).get(ref.number);
5345
+ if (!opener?.conversationId) return;
5346
+ const url = conflict.url ?? `https://github.com/${ref.repositoryFullName}/pull/${ref.number}`;
5347
+ const name = title ? `**${title}**` : "This pull request";
5348
+ const reason = fixes >= MAX_FIXES ? `Junior already fixed conflicts ${fixes} times` : "nobody worked on it in the last 2 days";
5349
+ await args.reviewItems.forConversation(opener.conversationId).upsert({
5350
+ assigneeIdentityIds: [opener.identityId],
5351
+ body: `${name} has merge conflicts with \`${conflict.baseBranch}\`. Junior stopped fixing them on its own, because ${reason}. If they are still there, ask Junior in this thread to fix them: ${url}`,
5352
+ dedupeKey: gitHubConflictNoticeKey(ref),
5353
+ subject: {
5354
+ id: url,
5355
+ title: title ? `${title} (#${ref.number})` : url,
5356
+ url
5357
+ },
5358
+ title: `Merge conflict \xB7 #${ref.number}`
5359
+ });
5360
+ }
5361
+ async function applyGitHubConflictPolicy(args) {
5362
+ if (args.draft) return [];
5363
+ const t = juniorGitHubPullRequests;
5364
+ const [row] = await args.db.select({ pullRequestId: t.pullRequestId }).from(t).where(and4(pullRequestRow(args.ref), eq4(t.state, "open"))).limit(1);
5365
+ if (!row) return args.events;
5366
+ const history = parseGitHubConflictHistory(await args.loadHistory(args.ref));
5367
+ const action = gitHubConflictAction(history, args.now.getTime());
5368
+ if (action === "fix") return args.events;
5369
+ if (action === "notice") {
5370
+ try {
5371
+ await addNotice(args, history.fixes);
5372
+ } catch (error) {
5373
+ logFailOpenFailure(
5374
+ args.log,
5375
+ "GitHub merge conflict notice failed",
5376
+ error,
5377
+ {
5378
+ number: args.ref.number,
5379
+ repository: args.ref.repositoryFullName
5380
+ }
5381
+ );
5382
+ }
5383
+ }
5384
+ return [];
5385
+ }
5386
+ var GITHUB_CONFLICT_GONE_REASON = "The pull request no longer has merge conflicts.";
5387
+ async function closeGitHubConflictNotice(args) {
5388
+ const { ref } = args;
5389
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
5390
+ numbers: [ref.number],
5391
+ repositoryFullName: ref.repositoryFullName
5392
+ })).get(ref.number);
5393
+ if (!opener?.conversationId) return;
5394
+ await args.reviewItems.forConversation(opener.conversationId).close({
5395
+ dedupeKey: gitHubConflictNoticeKey(ref),
5396
+ reason: args.reason,
5397
+ status: args.status
5398
+ });
5399
+ }
5400
+ async function closeGitHubConflictNotices(args) {
5401
+ if (args.numbers.length === 0) return;
5402
+ const { repositoryFullName } = args;
5403
+ const openers = await listGitHubPullRequestOpeners(args.db, {
5404
+ numbers: args.numbers,
5405
+ repositoryFullName
5406
+ });
5407
+ for (const [number33, opener] of openers) {
5408
+ if (!opener.conversationId) continue;
5409
+ try {
5410
+ await args.reviewItems.forConversation(opener.conversationId).close({
5411
+ dedupeKey: gitHubConflictNoticeKey({ number: number33, repositoryFullName }),
5412
+ reason: args.reason,
5413
+ status: args.status
5414
+ });
5415
+ } catch (error) {
5416
+ logFailOpenFailure(
5417
+ args.log,
5418
+ "GitHub merge conflict notice close failed",
5419
+ error,
5420
+ { number: number33, repository: repositoryFullName }
5421
+ );
5422
+ }
5423
+ }
5424
+ }
5425
+
5426
+ // src/webhooks/merge-conflict.ts
5074
5427
  var EVENT_TYPE = "pull_request.merge_conflict";
5075
5428
  var CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set([
5076
5429
  "pull_request.closed_unmerged",
5077
5430
  "pull_request.merged"
5078
5431
  ]);
5079
- var pullRequestSchema3 = z31.object({
5080
- base: z31.object({ ref: z31.string().min(1) }),
5081
- number: z31.number().int().positive().optional(),
5082
- head: z31.object({ sha: z31.string().min(1) }),
5083
- html_url: z31.string().min(1).optional(),
5084
- mergeable: z31.boolean().nullable().optional(),
5085
- mergeable_state: z31.string().optional(),
5086
- state: z31.string()
5432
+ var pullRequestSchema3 = z33.object({
5433
+ base: z33.object({ ref: z33.string().min(1) }),
5434
+ draft: z33.boolean().optional(),
5435
+ number: z33.number().int().positive().optional(),
5436
+ head: z33.object({ sha: z33.string().min(1) }),
5437
+ html_url: z33.string().min(1).optional(),
5438
+ mergeable: z33.boolean().nullable().optional(),
5439
+ mergeable_state: z33.string().optional(),
5440
+ state: z33.string(),
5441
+ title: z33.string().optional()
5087
5442
  });
5088
5443
  function gitHubMergeConflictEvents(input) {
5089
5444
  const { conflict } = input;
@@ -5117,13 +5472,13 @@ function pullRequestRefs(events) {
5117
5472
  return [...refs.values()];
5118
5473
  }
5119
5474
  function deliveredPullRequest(payload, ref) {
5120
- const parsed = z31.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
5475
+ const parsed = z33.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
5121
5476
  const pullRequest = parsed.success ? parsed.data.pull_request : void 0;
5122
5477
  return pullRequest?.number === ref.number && typeof pullRequest.mergeable === "boolean" ? pullRequest : void 0;
5123
5478
  }
5124
5479
  async function loadGitHubMergeConflictEvents(args) {
5125
- const { hasMatch, loadPullRequest: loadPullRequest2 } = args;
5126
- if (!hasMatch || !loadPullRequest2) return [];
5480
+ const { hasMatch, loadConflictHistory, loadPullRequest: loadPullRequest2 } = args;
5481
+ if (!hasMatch || !loadPullRequest2 || !loadConflictHistory) return [];
5127
5482
  const conflicts = [];
5128
5483
  for (const ref of pullRequestRefs(args.events)) {
5129
5484
  if (!await hasMatch(gitHubMergeConflictEvents(ref))) continue;
@@ -5132,14 +5487,23 @@ async function loadGitHubMergeConflictEvents(args) {
5132
5487
  if (loaded.state !== "open" || loaded.mergeable !== false || loaded.mergeable_state !== "dirty") {
5133
5488
  continue;
5134
5489
  }
5490
+ const conflict = {
5491
+ baseBranch: loaded.base.ref,
5492
+ headSha: loaded.head.sha,
5493
+ ...loaded.html_url ? { url: loaded.html_url } : void 0
5494
+ };
5135
5495
  conflicts.push(
5136
- ...gitHubMergeConflictEvents({
5137
- ...ref,
5138
- conflict: {
5139
- baseBranch: loaded.base.ref,
5140
- headSha: loaded.head.sha,
5141
- ...loaded.html_url ? { url: loaded.html_url } : void 0
5142
- }
5496
+ ...await applyGitHubConflictPolicy({
5497
+ conflict,
5498
+ db: args.db,
5499
+ draft: loaded.draft === true,
5500
+ events: gitHubMergeConflictEvents({ ...ref, conflict }),
5501
+ loadHistory: loadConflictHistory,
5502
+ log: args.log,
5503
+ now: /* @__PURE__ */ new Date(),
5504
+ ref,
5505
+ reviewItems: args.reviewItems,
5506
+ ...loaded.title ? { title: loaded.title } : void 0
5143
5507
  })
5144
5508
  );
5145
5509
  } catch (error) {
@@ -5159,16 +5523,16 @@ async function loadGitHubMergeConflictEvents(args) {
5159
5523
  }
5160
5524
 
5161
5525
  // src/merge-conflict-checks/webhooks.ts
5162
- import * as z33 from "zod";
5526
+ import * as z35 from "zod";
5163
5527
 
5164
5528
  // src/merge-conflict-checks/store.ts
5165
- import { and as and4, eq as eq4 } from "drizzle-orm";
5166
- import * as z32 from "zod";
5529
+ import { and as and5, eq as eq5 } from "drizzle-orm";
5530
+ import * as z34 from "zod";
5167
5531
  var CHECK_TTL_MS = 30 * 6e4;
5168
- var repeatSchema = z32.object({
5532
+ var repeatSchema = z34.object({
5169
5533
  /** Checks since the last push that ended with an unknown answer. */
5170
- attempts: z32.number().int().positive(),
5171
- dueAtMs: z32.number()
5534
+ attempts: z34.number().int().positive(),
5535
+ dueAtMs: z34.number()
5172
5536
  });
5173
5537
  function pushKey(repositoryFullName) {
5174
5538
  return `merge-conflict-check:push:${repositoryFullName}`;
@@ -5179,9 +5543,9 @@ function repeatKey(repositoryFullName) {
5179
5543
  async function listGitHubRepositoriesWithOpenPullRequests(db, repositoryFullName) {
5180
5544
  const t = juniorGitHubPullRequests;
5181
5545
  const rows = await db.selectDistinct({ repositoryFullName: t.repositoryFullName }).from(t).where(
5182
- and4(
5183
- eq4(t.state, "open"),
5184
- repositoryFullName ? eq4(t.repositoryFullName, repositoryFullName) : void 0
5546
+ and5(
5547
+ eq5(t.state, "open"),
5548
+ repositoryFullName ? eq5(t.repositoryFullName, repositoryFullName) : void 0
5185
5549
  )
5186
5550
  ).orderBy(t.repositoryFullName);
5187
5551
  return rows.map((row) => row.repositoryFullName);
@@ -5236,12 +5600,12 @@ async function settleGitHubConflictCheck(state, check, retryAtMs) {
5236
5600
 
5237
5601
  // src/merge-conflict-checks/webhooks.ts
5238
5602
  var CONFLICT_CHECK_DELAY_MS = 2 * 6e4;
5239
- var pushSchema = z33.object({
5240
- deleted: z33.boolean().optional(),
5241
- ref: z33.string(),
5242
- repository: z33.object({
5243
- default_branch: z33.string().min(1),
5244
- full_name: z33.string().min(1)
5603
+ var pushSchema = z35.object({
5604
+ deleted: z35.boolean().optional(),
5605
+ ref: z35.string(),
5606
+ repository: z35.object({
5607
+ default_branch: z35.string().min(1),
5608
+ full_name: z35.string().min(1)
5245
5609
  })
5246
5610
  });
5247
5611
  async function scheduleGitHubPushConflictCheck(args) {
@@ -5257,11 +5621,11 @@ async function scheduleGitHubPushConflictCheck(args) {
5257
5621
  });
5258
5622
  }
5259
5623
 
5260
- // src/webhooks/pull-request-ready.ts
5261
- import * as z35 from "zod";
5624
+ // src/webhooks/pull-request-action.ts
5625
+ import * as z37 from "zod";
5262
5626
 
5263
5627
  // src/webhooks/installation-requests.ts
5264
- import * as z34 from "zod";
5628
+ import * as z36 from "zod";
5265
5629
  function splitRepository(fullName, label) {
5266
5630
  const [owner, name, ...extra] = fullName.split("/");
5267
5631
  if (!owner || !name || extra.length > 0) {
@@ -5322,7 +5686,7 @@ async function loadPullRequestLifecycles(env, input) {
5322
5686
  }
5323
5687
  throw error;
5324
5688
  }
5325
- const repository2 = z34.object({ full_name: z34.string().min(1) }).parse(
5689
+ const repository2 = z36.object({ full_name: z36.string().min(1) }).parse(
5326
5690
  await githubRequest(
5327
5691
  "https://api.github.com",
5328
5692
  `/repositories/${input.repositoryId}`,
@@ -5370,6 +5734,25 @@ async function searchOpenPullRequestMergeability(env, input) {
5370
5734
  token: token.token
5371
5735
  });
5372
5736
  }
5737
+ async function loadPullRequestConflictHistory(env, pullRequest) {
5738
+ const { owner, name } = splitRepository(
5739
+ pullRequest.repositoryFullName,
5740
+ "pull request conflict history"
5741
+ );
5742
+ const token = await issueInstallationToken({
5743
+ ...env,
5744
+ permissions: { pull_requests: "read" },
5745
+ repositories: [name]
5746
+ });
5747
+ return await githubRequest("https://api.github.com", "/graphql", {
5748
+ body: {
5749
+ ...PULL_REQUEST_CONFLICT_HISTORY,
5750
+ variables: { name, number: pullRequest.number, owner }
5751
+ },
5752
+ method: "POST",
5753
+ token: token.token
5754
+ });
5755
+ }
5373
5756
  async function requestPullRequestReviewers2(env, input) {
5374
5757
  const { owner, name } = splitRepository(
5375
5758
  input.repositoryFullName,
@@ -5398,7 +5781,7 @@ async function markPullRequestFeedbackReviewing(env, target) {
5398
5781
  });
5399
5782
  const content = pullRequestFeedbackReactionContent("reviewing");
5400
5783
  if (target.commentKind === "review_body") {
5401
- const review = z34.object({ node_id: z34.string().min(1) }).parse(
5784
+ const review = z36.object({ node_id: z36.string().min(1) }).parse(
5402
5785
  await githubRequest(
5403
5786
  "https://api.github.com",
5404
5787
  pullRequestReviewPath({
@@ -5410,7 +5793,7 @@ async function markPullRequestFeedbackReviewing(env, target) {
5410
5793
  { token: token.token }
5411
5794
  )
5412
5795
  );
5413
- const result = z34.object({ errors: z34.array(z34.unknown()).optional() }).parse(
5796
+ const result = z36.object({ errors: z36.array(z36.unknown()).optional() }).parse(
5414
5797
  await githubRequest("https://api.github.com", "/graphql", {
5415
5798
  body: {
5416
5799
  ...ADD_REVIEW_REACTION,
@@ -5445,9 +5828,9 @@ async function markPullRequestFeedbackReviewing(env, target) {
5445
5828
  }
5446
5829
  );
5447
5830
  }
5448
- var repositoryPermissionSchema = z34.object({
5449
- permission: z34.string().min(1),
5450
- role_name: z34.string().optional()
5831
+ var repositoryPermissionSchema = z36.object({
5832
+ permission: z36.string().min(1),
5833
+ role_name: z36.string().optional()
5451
5834
  });
5452
5835
  var REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1e3;
5453
5836
  async function loadRepositoryRole(env, cache, target) {
@@ -5477,19 +5860,21 @@ async function loadRepositoryRole(env, cache, target) {
5477
5860
  }
5478
5861
  );
5479
5862
  }
5480
- var pullRequestSchema4 = z34.object({
5481
- auto_merge: z34.object({}).nullable().optional(),
5482
- draft: z34.boolean().optional(),
5483
- html_url: z34.string().url(),
5484
- mergeable_state: z34.string().nullable().optional(),
5485
- merged: z34.boolean(),
5486
- state: z34.enum(["open", "closed"]),
5487
- title: z34.string()
5863
+ var pullRequestSchema4 = z36.object({
5864
+ auto_merge: z36.object({}).nullable().optional(),
5865
+ draft: z36.boolean().optional(),
5866
+ html_url: z36.string().url(),
5867
+ mergeable_state: z36.string().nullable().optional(),
5868
+ merged: z36.boolean(),
5869
+ // The people whose review is still requested. Teams are listed apart.
5870
+ requested_reviewers: z36.array(z36.object({ login: z36.string().min(1) })).optional(),
5871
+ state: z36.enum(["open", "closed"]),
5872
+ title: z36.string()
5488
5873
  });
5489
- var reviewsSchema = z34.array(
5490
- z34.object({
5491
- state: z34.string(),
5492
- user: z34.object({ login: z34.string() }).nullable()
5874
+ var reviewsSchema = z36.array(
5875
+ z36.object({
5876
+ state: z36.string(),
5877
+ user: z36.object({ login: z36.string() }).nullable()
5493
5878
  })
5494
5879
  );
5495
5880
  async function loadPullRequestMergeState(env, pullRequest) {
@@ -5515,6 +5900,9 @@ async function loadPullRequestMergeState(env, pullRequest) {
5515
5900
  autoMerge: Boolean(pull.auto_merge),
5516
5901
  draft: pull.draft === true,
5517
5902
  ...mergeableState ? { mergeableState } : void 0,
5903
+ requestedReviewers: (pull.requested_reviewers ?? []).map(
5904
+ (reviewer) => reviewer.login
5905
+ ),
5518
5906
  state: pull.merged ? "merged" : pull.state,
5519
5907
  title: pull.title,
5520
5908
  url: pull.html_url
@@ -5543,9 +5931,9 @@ async function loadPullRequestMergeState(env, pullRequest) {
5543
5931
  return state;
5544
5932
  }
5545
5933
 
5546
- // src/webhooks/pull-request-ready.ts
5934
+ // src/webhooks/pull-request-action.ts
5547
5935
  var READY_SYNC_STALE_MS = 6e4;
5548
- var READY_ACTIONS = {
5936
+ var ACTION_EVENTS = {
5549
5937
  pull_request: /* @__PURE__ */ new Set([
5550
5938
  "auto_merge_disabled",
5551
5939
  "auto_merge_enabled",
@@ -5553,18 +5941,33 @@ var READY_ACTIONS = {
5553
5941
  "converted_to_draft",
5554
5942
  "ready_for_review",
5555
5943
  "reopened",
5944
+ "review_request_removed",
5945
+ "review_requested",
5556
5946
  "synchronize"
5557
5947
  ]),
5558
5948
  pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
5559
5949
  };
5560
- var pullRequestWebhookSchema = z35.object({
5561
- action: z35.string(),
5562
- pull_request: z35.object({ number: z35.number().int().positive() }),
5563
- repository: z35.object({ full_name: z35.string().min(1) })
5950
+ var LEGACY_DEDUPE_PREFIXES = [
5951
+ "pull-request-ready:",
5952
+ "pull-request-review-requested:"
5953
+ ];
5954
+ async function closeLegacyItems(items, name) {
5955
+ for (const prefix of LEGACY_DEDUPE_PREFIXES) {
5956
+ await items.close({
5957
+ dedupeKey: `${prefix}${name}`,
5958
+ reason: "One item now shows the next action.",
5959
+ status: "dismissed"
5960
+ });
5961
+ }
5962
+ }
5963
+ var pullRequestWebhookSchema = z37.object({
5964
+ action: z37.string(),
5965
+ pull_request: z37.object({ number: z37.number().int().positive() }),
5966
+ repository: z37.object({ full_name: z37.string().min(1) })
5564
5967
  });
5565
- function pullRequestReadyTargets(eventName, body) {
5968
+ function pullRequestActionTargets(eventName, body) {
5566
5969
  if (eventName === "check_suite") return checkSuitePullRequests(body);
5567
- const actions = READY_ACTIONS[eventName];
5970
+ const actions = ACTION_EVENTS[eventName];
5568
5971
  const parsed = pullRequestWebhookSchema.safeParse(body);
5569
5972
  if (!actions || !parsed.success || !actions.has(parsed.data.action)) {
5570
5973
  return [];
@@ -5576,7 +5979,23 @@ function pullRequestReadyTargets(eventName, body) {
5576
5979
  }
5577
5980
  ];
5578
5981
  }
5579
- function closeReason(state) {
5982
+ function nextAction(state, requesterLogin, saved) {
5983
+ if (state.state !== "open") return {};
5984
+ const canMerge = !state.draft && !state.autoMerge;
5985
+ if (canMerge && state.mergeableState === "clean" && state.approved) {
5986
+ return { action: "merge" };
5987
+ }
5988
+ if (canMerge && !state.mergeableState && saved === "merge") return void 0;
5989
+ const login = requesterLogin?.toLowerCase();
5990
+ if (login && state.requestedReviewers.some(
5991
+ (reviewer) => reviewer.toLowerCase() === login
5992
+ )) {
5993
+ return { action: "review" };
5994
+ }
5995
+ if (canMerge && !state.mergeableState) return void 0;
5996
+ return {};
5997
+ }
5998
+ function endedReason(state) {
5580
5999
  if (state.state === "merged") {
5581
6000
  return { reason: "The pull request merged.", status: "done" };
5582
6001
  }
@@ -5586,6 +6005,14 @@ function closeReason(state) {
5586
6005
  status: "dismissed"
5587
6006
  };
5588
6007
  }
6008
+ return void 0;
6009
+ }
6010
+ function closeReason(state, previous) {
6011
+ const ended = endedReason(state);
6012
+ if (ended) return ended;
6013
+ if (previous === "review") {
6014
+ return { reason: "The review request ended.", status: "done" };
6015
+ }
5589
6016
  if (state.autoMerge) {
5590
6017
  return { reason: "Auto-merge is on.", status: "dismissed" };
5591
6018
  }
@@ -5594,6 +6021,29 @@ function closeReason(state) {
5594
6021
  status: "dismissed"
5595
6022
  };
5596
6023
  }
6024
+ async function showAction(items, args) {
6025
+ const { action, number: number33, state } = args;
6026
+ if (action) {
6027
+ await items.upsert({
6028
+ assigneeIdentityIds: [args.identityId],
6029
+ body: action === "merge" ? `**${state.title}** is approved, and GitHub says that it can merge: ${state.url}` : `GitHub asks you to review **${state.title}**: ${state.url}`,
6030
+ dedupeKey: args.dedupeKey,
6031
+ // The number stays visible where a view shows only the subject.
6032
+ subject: {
6033
+ id: state.url,
6034
+ title: `${state.title} (#${number33})`,
6035
+ url: state.url
6036
+ },
6037
+ title: action === "merge" ? `Ready to merge \xB7 #${number33}` : `Review requested \xB7 #${number33}`,
6038
+ waitsOnAssignees: true
6039
+ });
6040
+ } else if (args.previous) {
6041
+ await items.close({
6042
+ dedupeKey: args.dedupeKey,
6043
+ ...closeReason(state, args.previous)
6044
+ });
6045
+ }
6046
+ }
5597
6047
  async function syncOne(args, target) {
5598
6048
  const opener = (await listGitHubPullRequestOpeners(args.db, {
5599
6049
  numbers: [target.number],
@@ -5601,42 +6051,49 @@ async function syncOne(args, target) {
5601
6051
  })).get(target.number);
5602
6052
  if (!opener?.conversationId) return;
5603
6053
  const items = args.reviewItems.forConversation(opener.conversationId);
5604
- const name = `${target.repositoryFullName}#${target.number}`;
5605
- const dedupeKey = `pull-request-ready:${name.toLowerCase()}`;
6054
+ const name = `${target.repositoryFullName}#${target.number}`.toLowerCase();
6055
+ const dedupeKey = `pull-request-action:${name}`;
6056
+ const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
5606
6057
  const claim = await claimGitHubPullRequestReadySync(args.db, target, {
5607
6058
  now: /* @__PURE__ */ new Date(),
5608
6059
  staleMs: READY_SYNC_STALE_MS
5609
6060
  });
5610
6061
  if (!claim) return;
5611
6062
  const { id } = claim;
5612
- let saved = claim.ready;
6063
+ let saved = claim.action;
5613
6064
  let requests = claim.requests;
5614
6065
  let failure;
5615
6066
  while (requests !== void 0) {
5616
6067
  try {
5617
6068
  const state = await loadPullRequestMergeState(args.env, target);
5618
- const open = state.state === "open" && !state.draft;
5619
- const ready = open && !state.autoMerge && state.mergeableState === "clean" && state.approved;
5620
- if ((!open || state.autoMerge || state.mergeableState) && ready !== saved) {
5621
- if (ready) {
5622
- await items.upsert({
5623
- assigneeIdentityIds: [opener.identityId],
5624
- body: `**${state.title}** is approved, and GitHub says that it can merge: ${state.url}`,
5625
- dedupeKey,
5626
- // The number stays visible where a view shows only the subject.
5627
- subject: {
5628
- id: state.url,
5629
- title: `${state.title} (#${target.number})`,
5630
- url: state.url
5631
- },
5632
- title: `Ready to merge \xB7 #${target.number}`,
5633
- waitsOnAssignees: true
5634
- });
5635
- } else {
5636
- await items.close({ dedupeKey, ...closeReason(state) });
5637
- }
5638
- await setGitHubPullRequestReadyToMerge(args.db, { ...target, ready });
5639
- saved = ready;
6069
+ const next = nextAction(state, requesterLogin, saved);
6070
+ const changed = next !== void 0 && next.action !== saved;
6071
+ if (changed) {
6072
+ await showAction(items, {
6073
+ action: next.action,
6074
+ dedupeKey,
6075
+ identityId: opener.identityId,
6076
+ number: target.number,
6077
+ previous: saved,
6078
+ state
6079
+ });
6080
+ }
6081
+ await closeLegacyItems(items, name);
6082
+ if (state.state !== "open" || state.mergeableState && state.mergeableState !== "dirty") {
6083
+ await items.close({
6084
+ dedupeKey: gitHubConflictNoticeKey(target),
6085
+ ...endedReason(state) ?? {
6086
+ reason: GITHUB_CONFLICT_GONE_REASON,
6087
+ status: "done"
6088
+ }
6089
+ });
6090
+ }
6091
+ if (changed) {
6092
+ await setGitHubPullRequestNextAction(args.db, {
6093
+ ...target,
6094
+ action: next.action
6095
+ });
6096
+ saved = next.action;
5640
6097
  }
5641
6098
  } catch (error) {
5642
6099
  failure ??= error;
@@ -5648,31 +6105,26 @@ async function syncOne(args, target) {
5648
6105
  }
5649
6106
  if (failure !== void 0) throw failure;
5650
6107
  }
5651
- async function syncGitHubPullRequestReadyNotices(args) {
6108
+ async function syncGitHubPullRequestActions(args) {
5652
6109
  for (const target of args.targets) {
5653
6110
  try {
5654
6111
  await syncOne(args, target);
5655
6112
  } catch (error) {
5656
- logFailOpenFailure(
5657
- args.log,
5658
- "GitHub pull request ready notice failed",
5659
- error,
5660
- {
5661
- deliveryId: args.deliveryId,
5662
- number: target.number,
5663
- repository: target.repositoryFullName
5664
- }
5665
- );
6113
+ logFailOpenFailure(args.log, "GitHub pull request action failed", error, {
6114
+ deliveryId: args.deliveryId,
6115
+ number: target.number,
6116
+ repository: target.repositoryFullName
6117
+ });
5666
6118
  }
5667
6119
  }
5668
6120
  }
5669
6121
 
5670
6122
  // src/webhooks/pull-request-ready-reviewers.ts
5671
- import * as z36 from "zod";
5672
- var readyForReviewSchema = z36.object({
5673
- action: z36.literal("ready_for_review"),
5674
- pull_request: z36.object({ number: z36.number().int().positive() }),
5675
- repository: z36.object({ full_name: z36.string().min(1) })
6123
+ import * as z38 from "zod";
6124
+ var readyForReviewSchema = z38.object({
6125
+ action: z38.literal("ready_for_review"),
6126
+ pull_request: z38.object({ number: z38.number().int().positive() }),
6127
+ repository: z38.object({ full_name: z38.string().min(1) })
5676
6128
  });
5677
6129
  async function requestGitHubReviewersWhenReady(args) {
5678
6130
  if (args.eventName !== "pull_request") return;
@@ -5703,163 +6155,8 @@ async function requestGitHubReviewersWhenReady(args) {
5703
6155
  }
5704
6156
  }
5705
6157
 
5706
- // src/webhooks/pull-request-review-request.ts
5707
- import * as z37 from "zod";
5708
- var login = z37.object({ login: z37.string().min(1) });
5709
- var pullRequestEventSchema = z37.object({
5710
- action: z37.enum([
5711
- "closed",
5712
- "reopened",
5713
- "review_request_removed",
5714
- "review_requested"
5715
- ]),
5716
- pull_request: z37.object({
5717
- html_url: z37.string().url(),
5718
- merged: z37.boolean().optional(),
5719
- number: z37.number().int().positive(),
5720
- // The people whose review is still requested. Teams are listed apart.
5721
- requested_reviewers: z37.array(login).optional(),
5722
- title: z37.string()
5723
- }),
5724
- repository: z37.object({ full_name: z37.string().min(1) }),
5725
- // A team request has `requested_team` instead.
5726
- requested_reviewer: login.optional()
5727
- });
5728
- var reviewEventSchema = z37.object({
5729
- action: z37.literal("submitted"),
5730
- pull_request: z37.object({ number: z37.number().int().positive() }),
5731
- repository: z37.object({ full_name: z37.string().min(1) }),
5732
- review: z37.object({ user: login })
5733
- });
5734
- function reviewRequestChange(eventName, body) {
5735
- if (eventName === "pull_request_review") {
5736
- const parsed2 = reviewEventSchema.safeParse(body);
5737
- if (!parsed2.success) return void 0;
5738
- return {
5739
- change: {
5740
- kind: "ended",
5741
- reason: "The requester reviewed the pull request.",
5742
- reviewer: parsed2.data.review.user.login,
5743
- status: "done"
5744
- },
5745
- number: parsed2.data.pull_request.number,
5746
- repository: parsed2.data.repository.full_name
5747
- };
5748
- }
5749
- if (eventName !== "pull_request") return void 0;
5750
- const parsed = pullRequestEventSchema.safeParse(body);
5751
- if (!parsed.success) return void 0;
5752
- const { action, pull_request: pull } = parsed.data;
5753
- const reviewer = parsed.data.requested_reviewer?.login;
5754
- const target = {
5755
- number: pull.number,
5756
- repository: parsed.data.repository.full_name
5757
- };
5758
- if (action === "reopened") {
5759
- const reviewers = (pull.requested_reviewers ?? []).map(
5760
- (person2) => person2.login
5761
- );
5762
- if (reviewers.length === 0) return void 0;
5763
- return {
5764
- ...target,
5765
- change: {
5766
- kind: "requested",
5767
- reviewers,
5768
- title: pull.title,
5769
- url: pull.html_url
5770
- }
5771
- };
5772
- }
5773
- if (action !== "closed" && !reviewer) {
5774
- return void 0;
5775
- }
5776
- if (action === "review_requested" && reviewer) {
5777
- return {
5778
- ...target,
5779
- change: {
5780
- kind: "requested",
5781
- reviewers: [reviewer],
5782
- title: pull.title,
5783
- url: pull.html_url
5784
- }
5785
- };
5786
- }
5787
- if (action === "review_request_removed") {
5788
- return {
5789
- ...target,
5790
- change: {
5791
- kind: "ended",
5792
- reason: "The review request was removed.",
5793
- reviewer,
5794
- status: "dismissed"
5795
- }
5796
- };
5797
- }
5798
- return {
5799
- ...target,
5800
- change: pull.merged ? { kind: "ended", reason: "The pull request merged.", status: "done" } : {
5801
- kind: "ended",
5802
- reason: "The pull request closed without merging.",
5803
- status: "dismissed"
5804
- }
5805
- };
5806
- }
5807
- function sameLogin(left, right) {
5808
- return left.toLowerCase() === right.toLowerCase();
5809
- }
5810
- async function syncGitHubPullRequestReviewRequest(args) {
5811
- const parsed = reviewRequestChange(args.eventName, args.body);
5812
- if (!parsed) return;
5813
- const { change, number: number33, repository: repository2 } = parsed;
5814
- try {
5815
- const opener = (await listGitHubPullRequestOpeners(args.db, {
5816
- numbers: [number33],
5817
- repositoryFullName: repository2
5818
- })).get(number33);
5819
- if (!opener?.conversationId) return;
5820
- const name = `${repository2}#${number33}`;
5821
- const dedupeKey = `pull-request-review-requested:${name.toLowerCase()}`;
5822
- const items = args.reviewItems.forConversation(opener.conversationId);
5823
- const reviewers = change.kind === "requested" ? change.reviewers : change.reviewer === void 0 ? void 0 : [change.reviewer];
5824
- if (reviewers !== void 0) {
5825
- const requesterLogin = await args.loadGitHubLogin?.(opener.identityId);
5826
- if (!requesterLogin || !reviewers.some((reviewer) => sameLogin(reviewer, requesterLogin))) {
5827
- return;
5828
- }
5829
- }
5830
- if (change.kind === "ended") {
5831
- await items.close({
5832
- dedupeKey,
5833
- reason: change.reason,
5834
- status: change.status
5835
- });
5836
- return;
5837
- }
5838
- await items.upsert({
5839
- assigneeIdentityIds: [opener.identityId],
5840
- body: `GitHub asks you to review **${change.title}**: ${change.url}`,
5841
- dedupeKey,
5842
- // The number stays visible where a view shows only the subject title.
5843
- subject: {
5844
- id: change.url,
5845
- title: `${change.title} (#${number33})`,
5846
- url: change.url
5847
- },
5848
- title: `Review requested \xB7 #${number33}`,
5849
- waitsOnAssignees: true
5850
- });
5851
- } catch (error) {
5852
- args.log?.error("GitHub pull request review request failed", {
5853
- deliveryId: args.deliveryId,
5854
- errorType: error instanceof Error ? error.name : "UnknownError",
5855
- number: number33,
5856
- repository: repository2
5857
- });
5858
- }
5859
- }
5860
-
5861
6158
  // src/webhooks/pull-request-match-data.ts
5862
- import * as z38 from "zod";
6159
+ import * as z39 from "zod";
5863
6160
  var LOOKUPS_BY_MATCH_KEY = {
5864
6161
  authors: ["authors"],
5865
6162
  openerEmail: ["opener"],
@@ -5867,16 +6164,16 @@ var LOOKUPS_BY_MATCH_KEY = {
5867
6164
  openerUsername: ["opener"]
5868
6165
  };
5869
6166
  var ALL_LOOKUPS = ["authors", "opener", "openerRole"];
5870
- var lookupDataSchema = z38.object({
5871
- authors: z38.array(z38.string().min(1)).min(1).optional(),
5872
- openerRole: z38.string().min(1).optional(),
5873
- openerUsername: z38.string().min(1).optional()
6167
+ var lookupDataSchema = z39.object({
6168
+ authors: z39.array(z39.string().min(1)).min(1).optional(),
6169
+ openerRole: z39.string().min(1).optional(),
6170
+ openerUsername: z39.string().min(1).optional()
5874
6171
  }).strict();
5875
6172
  function lookupData(input) {
5876
6173
  return lookupDataSchema.parse(definedValues(input));
5877
6174
  }
5878
- var webhookSchema = z38.object({
5879
- repository: z38.object({ full_name: z38.string().min(1) })
6175
+ var webhookSchema = z39.object({
6176
+ repository: z39.object({ full_name: z39.string().min(1) })
5880
6177
  });
5881
6178
  function pullRequestNumbers(events) {
5882
6179
  const numbers = /* @__PURE__ */ new Map();
@@ -5919,7 +6216,7 @@ async function withJuniorOpeners(context, events) {
5919
6216
  const number33 = botNumber(event);
5920
6217
  if (number33 === void 0) return event;
5921
6218
  const identityId = openers.get(number33)?.identityId;
5922
- const login2 = identityId ? logins.get(identityId) : void 0;
6219
+ const login = identityId ? logins.get(identityId) : void 0;
5923
6220
  const {
5924
6221
  openerEmail: _email,
5925
6222
  openerUsername: _login,
@@ -5927,7 +6224,7 @@ async function withJuniorOpeners(context, events) {
5927
6224
  } = event.data ?? {};
5928
6225
  return {
5929
6226
  ...event,
5930
- data: { ...data, ...lookupData({ openerUsername: login2 || void 0 }) }
6227
+ data: { ...data, ...lookupData({ openerUsername: login || void 0 }) }
5931
6228
  };
5932
6229
  });
5933
6230
  }
@@ -5942,11 +6239,11 @@ async function withRolesAndAuthors(context, events, lookups) {
5942
6239
  events.map(async (event) => {
5943
6240
  const number33 = context.numbers.get(event.eventKey);
5944
6241
  if (number33 === void 0) return event;
5945
- const login2 = event.data?.openerUsername;
5946
- if (loadRole && typeof login2 === "string" && !roles.has(login2)) {
6242
+ const login = event.data?.openerUsername;
6243
+ if (loadRole && typeof login === "string" && !roles.has(login)) {
5947
6244
  roles.set(
5948
- login2,
5949
- loadRole({ login: login2, repositoryFullName }).catch(
6245
+ login,
6246
+ loadRole({ login, repositoryFullName }).catch(
5950
6247
  (error) => logFailure(context, "role", error)
5951
6248
  )
5952
6249
  );
@@ -5959,7 +6256,7 @@ async function withRolesAndAuthors(context, events, lookups) {
5959
6256
  )
5960
6257
  );
5961
6258
  }
5962
- const role = loadRole && typeof login2 === "string" ? await roles.get(login2) : void 0;
6259
+ const role = loadRole && typeof login === "string" ? await roles.get(login) : void 0;
5963
6260
  const logins = loadAuthors ? await authors.get(number33) : void 0;
5964
6261
  if (!role && !logins?.length) return event;
5965
6262
  return {
@@ -6017,7 +6314,7 @@ async function withGitHubPullRequestMatchData(args) {
6017
6314
  }
6018
6315
 
6019
6316
  // src/webhooks/pull-request-people.ts
6020
- import * as z39 from "zod";
6317
+ import * as z40 from "zod";
6021
6318
  var PEOPLE_EVENTS = /* @__PURE__ */ new Set([
6022
6319
  "pull_request.review.approved",
6023
6320
  "pull_request.merged"
@@ -6027,18 +6324,18 @@ var PAGE_SIZE = 100;
6027
6324
  var MAX_PAGES = 3;
6028
6325
  var CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
6029
6326
  var GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
6030
- var webhookSchema2 = z39.object({
6031
- pull_request: z39.object({
6032
- assignees: z39.array(z39.object({ login: z39.string().min(1) })).nullish(),
6033
- number: z39.number(),
6034
- user: z39.object({ login: z39.string().min(1) }).nullish()
6327
+ var webhookSchema2 = z40.object({
6328
+ pull_request: z40.object({
6329
+ assignees: z40.array(z40.object({ login: z40.string().min(1) })).nullish(),
6330
+ number: z40.number(),
6331
+ user: z40.object({ login: z40.string().min(1) }).nullish()
6035
6332
  }),
6036
- repository: z39.object({ full_name: z39.string().min(1) })
6333
+ repository: z40.object({ full_name: z40.string().min(1) })
6037
6334
  });
6038
- var commitPageSchema = z39.array(
6039
- z39.object({
6040
- author: z39.object({ login: z39.string().min(1) }).nullish(),
6041
- commit: z39.object({ message: z39.string() })
6335
+ var commitPageSchema = z40.array(
6336
+ z40.object({
6337
+ author: z40.object({ login: z40.string().min(1) }).nullish(),
6338
+ commit: z40.object({ message: z40.string() })
6042
6339
  })
6043
6340
  );
6044
6341
  function shareCommitPages(load) {
@@ -6079,15 +6376,15 @@ function noreplyLogin(email) {
6079
6376
  }
6080
6377
  async function loadGitHubPullRequestPeople(args) {
6081
6378
  const people = /* @__PURE__ */ new Map();
6082
- const addLogin = (login2) => {
6083
- if (/\[bot\]$/i.test(login2)) return;
6084
- const key = `github:${login2.toLowerCase()}`;
6379
+ const addLogin = (login) => {
6380
+ if (/\[bot\]$/i.test(login)) return;
6381
+ const key = `github:${login.toLowerCase()}`;
6085
6382
  if (!people.has(key))
6086
- people.set(key, { provider: "github", handle: login2 });
6383
+ people.set(key, { provider: "github", handle: login });
6087
6384
  };
6088
6385
  const addEmail = (value) => {
6089
- const login2 = noreplyLogin(value);
6090
- if (login2) return addLogin(login2);
6386
+ const login = noreplyLogin(value);
6387
+ if (login) return addLogin(login);
6091
6388
  const email = value.toLowerCase();
6092
6389
  if (!people.has(`email:${email}`)) {
6093
6390
  people.set(`email:${email}`, { email });
@@ -6102,9 +6399,9 @@ async function loadGitHubPullRequestPeople(args) {
6102
6399
  }
6103
6400
  async function loadGitHubPullRequestAuthors(args) {
6104
6401
  const authors = /* @__PURE__ */ new Map();
6105
- const add = (login2) => {
6106
- if (login2 && !authors.has(login2.toLowerCase())) {
6107
- authors.set(login2.toLowerCase(), login2);
6402
+ const add = (login) => {
6403
+ if (login && !authors.has(login.toLowerCase())) {
6404
+ authors.set(login.toLowerCase(), login);
6108
6405
  }
6109
6406
  };
6110
6407
  await forEachCommit(args.loadPage, (commit) => {
@@ -6180,11 +6477,11 @@ function webhookInstallationId(body) {
6180
6477
  }
6181
6478
  return parseInstallationId(installation.id);
6182
6479
  }
6183
- var feedbackTargetSchema = z40.object({
6184
- commentId: z40.number(),
6185
- commentKind: z40.enum(["conversation", "review", "review_body"]),
6186
- pullRequest: z40.number(),
6187
- repo: z40.string().min(1)
6480
+ var feedbackTargetSchema = z41.object({
6481
+ commentId: z41.number(),
6482
+ commentKind: z41.enum(["conversation", "review", "review_body"]),
6483
+ pullRequest: z41.number(),
6484
+ repo: z41.string().min(1)
6188
6485
  });
6189
6486
  function pullRequestFeedbackTarget(events) {
6190
6487
  for (const event of events) {
@@ -6322,6 +6619,12 @@ function createGitHubWebhookRoute(args) {
6322
6619
  appIdEnv: args.appIdEnv,
6323
6620
  body,
6324
6621
  installationIdEnv: args.installationIdEnv,
6622
+ loadCheckSuites: await wantsCheckSuitePassed({
6623
+ body,
6624
+ deliveryId,
6625
+ hasMatch: args.events.hasMatch,
6626
+ neededMatchKeys: args.events.neededMatchKeys
6627
+ }),
6325
6628
  ...args.loadGitHubIncidents ? { loadGitHubIncidents: args.loadGitHubIncidents } : void 0,
6326
6629
  loadPullRequestFacts: needsCheckSuitePullRequestFacts(checkSuiteMatchKeys),
6327
6630
  log: args.log,
@@ -6380,12 +6683,15 @@ function createGitHubWebhookRoute(args) {
6380
6683
  }
6381
6684
  events.push(
6382
6685
  ...await loadGitHubMergeConflictEvents({
6686
+ db: args.db,
6383
6687
  deliveryId,
6384
6688
  events,
6385
6689
  hasMatch,
6690
+ loadConflictHistory: args.loadPullRequestConflictHistory,
6386
6691
  loadPullRequest: args.loadPullRequest,
6387
6692
  log: args.log,
6388
- pullRequestPayload: eventName === "pull_request" ? body : void 0
6693
+ pullRequestPayload: eventName === "pull_request" ? body : void 0,
6694
+ reviewItems: args.reviewItems
6389
6695
  })
6390
6696
  );
6391
6697
  for (const event of events) {
@@ -6394,7 +6700,7 @@ function createGitHubWebhookRoute(args) {
6394
6700
  objectType: event.eventType.startsWith("pull_request.") ? "code_change" : event.eventType.startsWith("issue.") ? "task" : event.eventType.startsWith("deployment.") ? "deployment" : "item"
6395
6701
  });
6396
6702
  }
6397
- await syncGitHubPullRequestReadyNotices({
6703
+ await syncGitHubPullRequestActions({
6398
6704
  db: args.db,
6399
6705
  deliveryId,
6400
6706
  env: {
@@ -6402,9 +6708,10 @@ function createGitHubWebhookRoute(args) {
6402
6708
  installationIdEnv: args.installationIdEnv,
6403
6709
  privateKeyEnv: args.privateKeyEnv
6404
6710
  },
6711
+ loadGitHubLogin: args.loadGitHubLogin,
6405
6712
  log: args.log,
6406
6713
  reviewItems: args.reviewItems,
6407
- targets: pullRequestReadyTargets(eventName, body)
6714
+ targets: pullRequestActionTargets(eventName, body)
6408
6715
  });
6409
6716
  await requestGitHubReviewersWhenReady({
6410
6717
  body,
@@ -6420,15 +6727,6 @@ function createGitHubWebhookRoute(args) {
6420
6727
  log: args.log,
6421
6728
  state: args.state
6422
6729
  });
6423
- await syncGitHubPullRequestReviewRequest({
6424
- body,
6425
- db: args.db,
6426
- deliveryId,
6427
- eventName,
6428
- loadGitHubLogin: args.loadGitHubLogin,
6429
- log: args.log,
6430
- reviewItems: args.reviewItems
6431
- });
6432
6730
  if (!pullRequestOutcome && !issueOutcome && !recordedIssueConversations && !recordedPullRequestConversations && !recordedPullRequestLinkedIssues && events.length === 0) {
6433
6731
  return new Response("Ignored", { status: 202 });
6434
6732
  }
@@ -6438,30 +6736,32 @@ function createGitHubWebhookRoute(args) {
6438
6736
  }
6439
6737
 
6440
6738
  // src/merge-conflict-checks/heartbeat.ts
6441
- import * as z41 from "zod";
6739
+ import * as z42 from "zod";
6442
6740
  var CHECK_LIMIT = 10;
6443
6741
  var MAX_PAGES2 = 5;
6444
6742
  var CLAIM_MS = 5 * 6e4;
6445
6743
  var UNKNOWN_RETRY_MS = 6e4;
6446
6744
  var MAX_ATTEMPTS = 5;
6447
- var searchNodeSchema = z41.union([
6448
- z41.object({
6449
- baseRefName: z41.string().min(1),
6450
- headRefOid: z41.string().min(1),
6451
- mergeable: z41.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
6452
- number: z41.number().int().positive(),
6453
- state: z41.string(),
6454
- url: z41.string().min(1)
6745
+ var searchNodeSchema = z42.union([
6746
+ z42.object({
6747
+ baseRefName: z42.string().min(1),
6748
+ headRefOid: z42.string().min(1),
6749
+ isDraft: z42.boolean(),
6750
+ mergeable: z42.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
6751
+ number: z42.number().int().positive(),
6752
+ state: z42.string(),
6753
+ title: z42.string(),
6754
+ url: z42.string().min(1)
6455
6755
  }),
6456
- z41.object({}).strict()
6756
+ z42.object({}).strict()
6457
6757
  ]);
6458
- var searchResponseSchema = z41.object({
6459
- data: z41.object({
6460
- search: z41.object({
6461
- nodes: z41.array(searchNodeSchema.nullable()),
6462
- pageInfo: z41.object({
6463
- endCursor: z41.string().nullable(),
6464
- hasNextPage: z41.boolean()
6758
+ var searchResponseSchema = z42.object({
6759
+ data: z42.object({
6760
+ search: z42.object({
6761
+ nodes: z42.array(searchNodeSchema.nullable()),
6762
+ pageInfo: z42.object({
6763
+ endCursor: z42.string().nullable(),
6764
+ hasNextPage: z42.boolean()
6465
6765
  })
6466
6766
  })
6467
6767
  })
@@ -6473,22 +6773,44 @@ async function checkRepository(args, repositoryFullName) {
6473
6773
  const { search } = searchResponseSchema.parse(
6474
6774
  await args.search({ after, repositoryFullName })
6475
6775
  ).data;
6776
+ const mergeable = [];
6476
6777
  for (const node of search.nodes) {
6477
6778
  if (!node || !("number" in node) || node.state !== "OPEN") continue;
6478
6779
  if (node.mergeable === "UNKNOWN") unknown3 = true;
6780
+ if (node.mergeable === "MERGEABLE") mergeable.push(node.number);
6479
6781
  if (node.mergeable !== "CONFLICTING") continue;
6480
- const events = gitHubMergeConflictEvents({
6481
- conflict: {
6482
- baseBranch: node.baseRefName,
6483
- headSha: node.headRefOid,
6484
- url: node.url
6485
- },
6486
- number: node.number,
6487
- repositoryFullName
6488
- });
6782
+ const ref = { number: node.number, repositoryFullName };
6783
+ const conflict = {
6784
+ baseBranch: node.baseRefName,
6785
+ headSha: node.headRefOid,
6786
+ url: node.url
6787
+ };
6788
+ const events = gitHubMergeConflictEvents({ ...ref, conflict });
6489
6789
  if (!await args.events.hasMatch?.(events)) continue;
6490
- for (const event of events) await args.events.publish(event);
6790
+ for (const event of await applyGitHubConflictPolicy({
6791
+ conflict,
6792
+ db: args.db,
6793
+ draft: node.isDraft,
6794
+ events,
6795
+ loadHistory: args.loadHistory,
6796
+ log: args.log,
6797
+ now: args.now,
6798
+ ref,
6799
+ reviewItems: args.reviewItems,
6800
+ title: node.title
6801
+ })) {
6802
+ await args.events.publish(event);
6803
+ }
6491
6804
  }
6805
+ await closeGitHubConflictNotices({
6806
+ db: args.db,
6807
+ log: args.log,
6808
+ numbers: mergeable,
6809
+ reason: GITHUB_CONFLICT_GONE_REASON,
6810
+ repositoryFullName,
6811
+ reviewItems: args.reviewItems,
6812
+ status: "done"
6813
+ });
6492
6814
  if (!search.pageInfo.hasNextPage || !search.pageInfo.endCursor) break;
6493
6815
  after = search.pageInfo.endCursor;
6494
6816
  }
@@ -6535,38 +6857,38 @@ async function runGitHubConflictChecks(args) {
6535
6857
  }
6536
6858
 
6537
6859
  // src/pull-request-outcomes/reconcile.ts
6538
- import * as z42 from "zod";
6860
+ import * as z43 from "zod";
6539
6861
  var RECONCILE_MS = 24 * 60 * 6e4;
6540
6862
  var REPOSITORY_LIMIT = 1;
6541
6863
  var PULL_REQUESTS_PER_QUERY = 100;
6542
- var lifecycleSchema = z42.object({
6543
- assignees: z42.object({
6544
- nodes: z42.array(z42.object({ login: z42.string().min(1) }).nullable())
6864
+ var lifecycleSchema = z43.object({
6865
+ assignees: z43.object({
6866
+ nodes: z43.array(z43.object({ login: z43.string().min(1) }).nullable())
6545
6867
  }),
6546
6868
  // GraphQL omits the `[bot]` suffix that REST and webhooks give an app.
6547
- author: z42.object({ __typename: z42.string(), login: z42.string().min(1) }).nullable(),
6548
- closedAt: z42.string().nullable(),
6549
- createdAt: z42.string(),
6550
- databaseId: z42.number().int().positive(),
6551
- headRefName: z42.string(),
6552
- isDraft: z42.boolean(),
6553
- merged: z42.boolean(),
6554
- mergedAt: z42.string().nullable(),
6555
- number: z42.number().int().positive(),
6556
- state: z42.enum(["OPEN", "CLOSED", "MERGED"]),
6557
- title: z42.string(),
6558
- updatedAt: z42.string()
6869
+ author: z43.object({ __typename: z43.string(), login: z43.string().min(1) }).nullable(),
6870
+ closedAt: z43.string().nullable(),
6871
+ createdAt: z43.string(),
6872
+ databaseId: z43.number().int().positive(),
6873
+ headRefName: z43.string(),
6874
+ isDraft: z43.boolean(),
6875
+ merged: z43.boolean(),
6876
+ mergedAt: z43.string().nullable(),
6877
+ number: z43.number().int().positive(),
6878
+ state: z43.enum(["OPEN", "CLOSED", "MERGED"]),
6879
+ title: z43.string(),
6880
+ updatedAt: z43.string()
6559
6881
  });
6560
- var lifecyclesResponseSchema = z42.object({
6561
- data: z42.object({
6562
- repository: z42.object({
6563
- databaseId: z42.number().int().positive(),
6564
- nameWithOwner: z42.string().min(1)
6882
+ var lifecyclesResponseSchema = z43.object({
6883
+ data: z43.object({
6884
+ repository: z43.object({
6885
+ databaseId: z43.number().int().positive(),
6886
+ nameWithOwner: z43.string().min(1)
6565
6887
  }).catchall(lifecycleSchema.nullable())
6566
6888
  })
6567
6889
  });
6568
6890
  function webhookBody(action, repository2, pullRequest) {
6569
- const login2 = pullRequest.author?.login ?? "ghost";
6891
+ const login = pullRequest.author?.login ?? "ghost";
6570
6892
  return {
6571
6893
  action,
6572
6894
  pull_request: {
@@ -6584,7 +6906,7 @@ function webhookBody(action, repository2, pullRequest) {
6584
6906
  title: pullRequest.title,
6585
6907
  updated_at: pullRequest.updatedAt,
6586
6908
  user: {
6587
- login: pullRequest.author?.__typename === "Bot" ? `${login2}[bot]` : login2
6909
+ login: pullRequest.author?.__typename === "Bot" ? `${login}[bot]` : login
6588
6910
  }
6589
6911
  },
6590
6912
  repository: {
@@ -6674,6 +6996,15 @@ async function reconcileRepository(args, repositoryId, drafts) {
6674
6996
  for (const event of events) {
6675
6997
  await args.events.publish({ ...event, objectType: "code_change" });
6676
6998
  }
6999
+ await closeGitHubConflictNotice({
7000
+ db: args.db,
7001
+ ref: { number: pullRequest.number, repositoryFullName: nameWithOwner },
7002
+ reviewItems: args.reviewItems,
7003
+ ...pullRequest.merged ? { reason: "The pull request merged.", status: "done" } : {
7004
+ reason: "The pull request closed without merging.",
7005
+ status: "dismissed"
7006
+ }
7007
+ });
6677
7008
  await applyGitHubPullRequestOutcome({
6678
7009
  annotations: args.annotations,
6679
7010
  codeChanges: args.codeChanges,
@@ -6764,18 +7095,18 @@ function gitHubResourceUrl(input) {
6764
7095
  }
6765
7096
 
6766
7097
  // src/pull-request-outcomes/commit-composition.ts
6767
- import * as z43 from "zod";
6768
- var canonicalCommitSchema = z43.object({
6769
- authorEmail: z43.string().nullable(),
6770
- authorLogin: z43.string().nullable()
7098
+ import * as z44 from "zod";
7099
+ var canonicalCommitSchema = z44.object({
7100
+ authorEmail: z44.string().nullable(),
7101
+ authorLogin: z44.string().nullable()
6771
7102
  }).strict();
6772
- var providerCommitSchema = z43.object({
6773
- author: z43.object({ login: z43.string() }).passthrough().nullable(),
6774
- commit: z43.object({
6775
- author: z43.object({ email: z43.string() }).passthrough().nullable()
7103
+ var providerCommitSchema = z44.object({
7104
+ author: z44.object({ login: z44.string() }).passthrough().nullable(),
7105
+ commit: z44.object({
7106
+ author: z44.object({ email: z44.string() }).passthrough().nullable()
6776
7107
  }).passthrough()
6777
7108
  }).passthrough();
6778
- var commitPageSchema2 = z43.array(providerCommitSchema).transform(
7109
+ var commitPageSchema2 = z44.array(providerCommitSchema).transform(
6779
7110
  (commits) => commits.map(
6780
7111
  (commit) => canonicalCommitSchema.parse({
6781
7112
  authorEmail: commit.commit.author?.email ?? null,
@@ -6818,10 +7149,10 @@ async function classifyGitHubPullRequestCommitComposition(args) {
6818
7149
  import {
6819
7150
  decodeObjectImageRef
6820
7151
  } from "@sentry/junior-plugin-api";
6821
- import * as z44 from "zod";
7152
+ import * as z45 from "zod";
6822
7153
  var OBJECT_KEY = /^([\w.-]+)\/([\w.-]+)#\d+$/;
6823
7154
  var ACCESS_TTL_MS = 10 * 60 * 1e3;
6824
- var permissionSchema = z44.object({ permission: z44.string().min(1) });
7155
+ var permissionSchema = z45.object({ permission: z45.string().min(1) });
6825
7156
  var AccessReadFailed = class extends Error {
6826
7157
  status;
6827
7158
  constructor(status) {
@@ -6829,9 +7160,9 @@ var AccessReadFailed = class extends Error {
6829
7160
  this.status = status;
6830
7161
  }
6831
7162
  };
6832
- async function canSeeRepository(ctx, repository2, login2) {
7163
+ async function canSeeRepository(ctx, repository2, login) {
6833
7164
  try {
6834
- return await readRepositoryAccess(ctx, repository2, login2);
7165
+ return await readRepositoryAccess(ctx, repository2, login);
6835
7166
  } catch (error) {
6836
7167
  if (!(error instanceof AccessReadFailed)) throw error;
6837
7168
  ctx.log.warn("github.image_access.read_failed", {
@@ -6840,13 +7171,13 @@ async function canSeeRepository(ctx, repository2, login2) {
6840
7171
  return false;
6841
7172
  }
6842
7173
  }
6843
- async function readRepositoryAccess(ctx, repository2, login2) {
7174
+ async function readRepositoryAccess(ctx, repository2, login) {
6844
7175
  return await ctx.cache.getOrLoad(
6845
- `image-access:${repository2.owner}/${repository2.name}:${login2}`.toLowerCase(),
7176
+ `image-access:${repository2.owner}/${repository2.name}:${login}`.toLowerCase(),
6846
7177
  async () => {
6847
7178
  const response = await githubApi(ctx.egress, {
6848
7179
  operation: "github.repository.collaborator-permission.get",
6849
- path: `${repoPath(repository2)}/collaborators/${encodeURIComponent(login2)}/permission`
7180
+ path: `${repoPath(repository2)}/collaborators/${encodeURIComponent(login)}/permission`
6850
7181
  });
6851
7182
  if (!response.ok && response.status !== 404) {
6852
7183
  throw new AccessReadFailed(response.status);
@@ -6865,10 +7196,10 @@ var githubImageSource = {
6865
7196
  const key = image && OBJECT_KEY.exec(image.key);
6866
7197
  if (!image || !key || !URL.canParse(image.url)) return void 0;
6867
7198
  const kind = githubImageKind(new URL(image.url));
6868
- const login2 = linkedGitHubLogin(ctx.viewer);
6869
- if (!kind || !login2) return void 0;
7199
+ const login = linkedGitHubLogin(ctx.viewer);
7200
+ if (!kind || !login) return void 0;
6870
7201
  const repository2 = { name: key[2], owner: key[1] };
6871
- if (!await canSeeRepository(ctx, repository2, login2)) return void 0;
7202
+ if (!await canSeeRepository(ctx, repository2, login)) return void 0;
6872
7203
  return kind === "artifact" ? { url: image.url } : {
6873
7204
  url: image.url,
6874
7205
  location: () => githubAttachmentLocation(ctx.egress, image.url)
@@ -6911,15 +7242,15 @@ function githubNoreplyEmail(user) {
6911
7242
  if (identity.provider !== "github") {
6912
7243
  continue;
6913
7244
  }
6914
- const login2 = cleanIdentityPart(identity.handle);
7245
+ const login = cleanIdentityPart(identity.handle);
6915
7246
  const userId = cleanIdentityPart(identity.providerSubjectId);
6916
- if (!login2 || login2.toLowerCase().endsWith("[bot]")) {
7247
+ if (!login || login.toLowerCase().endsWith("[bot]")) {
6917
7248
  continue;
6918
7249
  }
6919
7250
  if (/^[1-9]\d*$/.test(userId)) {
6920
- return `${userId}+${login2}@users.noreply.github.com`;
7251
+ return `${userId}+${login}@users.noreply.github.com`;
6921
7252
  }
6922
- return `${login2}@users.noreply.github.com`;
7253
+ return `${login}@users.noreply.github.com`;
6923
7254
  }
6924
7255
  return void 0;
6925
7256
  }
@@ -7361,11 +7692,11 @@ function linkifyTextReferences(text2, context) {
7361
7692
  return `[${label}](${commitUrl(groups.commitOwner, groups.commitRepo, groups.commit)})`;
7362
7693
  }
7363
7694
  if (groups.mention) {
7364
- const login2 = groups.mention;
7365
- if (NON_ACCOUNT_MENTIONS.has(login2.toLowerCase())) return reference;
7366
- const known = context.mention(login2);
7695
+ const login = groups.mention;
7696
+ if (NON_ACCOUNT_MENTIONS.has(login.toLowerCase())) return reference;
7697
+ const known = context.mention(login);
7367
7698
  if (known) return known;
7368
- return context.linkProfiles ? `[${reference}](https://github.com/${login2})` : reference;
7699
+ return context.linkProfiles ? `[${reference}](https://github.com/${login})` : reference;
7369
7700
  }
7370
7701
  if (!repository2) {
7371
7702
  return reference;
@@ -7511,9 +7842,9 @@ function parseGitHubReferences(text2, config) {
7511
7842
  }
7512
7843
  return [...references.values()];
7513
7844
  }
7514
- function objectTitle(kind, object44) {
7515
- if (!isRecord(object44)) return void 0;
7516
- const raw = kind === "commit" ? isRecord(object44.commit) && typeof object44.commit.message === "string" ? object44.commit.message.split("\n")[0] : void 0 : typeof object44.title === "string" ? object44.title : void 0;
7845
+ function objectTitle(kind, object45) {
7846
+ if (!isRecord(object45)) return void 0;
7847
+ const raw = kind === "commit" ? isRecord(object45.commit) && typeof object45.commit.message === "string" ? object45.commit.message.split("\n")[0] : void 0 : typeof object45.title === "string" ? object45.title : void 0;
7517
7848
  return raw?.replace(/\s+/g, " ").trim() || void 0;
7518
7849
  }
7519
7850
  async function loadGitHubConversationTitleContext(args) {
@@ -7697,7 +8028,7 @@ async function prepareWorkspace(ctx) {
7697
8028
  // src/clone-command.ts
7698
8029
  import { parseShellCommands } from "@sentry/junior-plugin-api";
7699
8030
  var CLONE_REDIRECT_MESSAGE = "Use github_cloneRepository to clone GitHub repositories, not git clone or gh repo clone. It checks for a matching Workspace first.";
7700
- var GIT_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-C", "-c"]);
8031
+ var GIT_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-C", "-c", "--config-env"]);
7701
8032
  function githubCloneCommandRedirect(command) {
7702
8033
  return parseShellCommands(command).some(isGitHubClone) ? CLONE_REDIRECT_MESSAGE : void 0;
7703
8034
  }
@@ -7726,6 +8057,29 @@ function isGitHubRemote(arg) {
7726
8057
  }
7727
8058
  }
7728
8059
 
8060
+ // src/hooks-path-command.ts
8061
+ import { parseShellCommands as parseShellCommands2 } from "@sentry/junior-plugin-api";
8062
+ var HOOKS_PATH_REDIRECT_MESSAGE = "Do not override core.hooksPath. Junior's Git hooks set commit attribution. To skip the repository's pre-commit and commit-msg hooks, use `git commit --no-verify`.";
8063
+ function gitHooksPathOverrideRedirect(command) {
8064
+ return parseShellCommands2(command).some(overridesHooksPath) ? HOOKS_PATH_REDIRECT_MESSAGE : void 0;
8065
+ }
8066
+ function overridesHooksPath([program, ...args]) {
8067
+ if (program !== "git") {
8068
+ return false;
8069
+ }
8070
+ for (let index2 = 0; args[index2]?.startsWith("-"); index2 += 1) {
8071
+ const option = args[index2];
8072
+ const value = option.startsWith("--config-env=") ? option.slice("--config-env=".length) : option === "-c" || option === "--config-env" ? args[index2 + 1] : void 0;
8073
+ if (value?.toLowerCase().startsWith("core.hookspath=")) {
8074
+ return true;
8075
+ }
8076
+ if (GIT_OPTIONS_WITH_VALUE.has(option)) {
8077
+ index2 += 1;
8078
+ }
8079
+ }
8080
+ return false;
8081
+ }
8082
+
7729
8083
  // src/egress-policy.ts
7730
8084
  import {
7731
8085
  EgressPolicyDenied as EgressPolicyDenied3,
@@ -7792,9 +8146,9 @@ import {
7792
8146
  } from "@sentry/junior-plugin-api";
7793
8147
 
7794
8148
  // src/default-branch.ts
7795
- import * as z45 from "zod";
8149
+ import * as z46 from "zod";
7796
8150
  var DEFAULT_BRANCH_TTL_MS = 10 * 60 * 1e3;
7797
- var repositorySchema3 = z45.object({ default_branch: z45.string().min(1) });
8151
+ var repositorySchema3 = z46.object({ default_branch: z46.string().min(1) });
7798
8152
  async function loadDefaultBranch(env, cache, repository2) {
7799
8153
  const { owner, name } = repository2;
7800
8154
  return await cache.getOrLoad(
@@ -8525,7 +8879,7 @@ function githubPlugin(options = {}) {
8525
8879
  bareUrls: platform === "web",
8526
8880
  config,
8527
8881
  githubText: provider === "github",
8528
- mention: (login2) => mention({ provider: "github", handle: login2 })
8882
+ mention: (login) => mention({ provider: "github", handle: login })
8529
8883
  });
8530
8884
  },
8531
8885
  systemPrompt() {
@@ -8541,16 +8895,18 @@ function githubPlugin(options = {}) {
8541
8895
  await runGitHubConflictChecks({
8542
8896
  db,
8543
8897
  events: ctx.events,
8898
+ loadHistory: async (ref) => await loadPullRequestConflictHistory(installationEnv, ref),
8544
8899
  log: ctx.log,
8545
8900
  now: new Date(ctx.nowMs),
8901
+ reviewItems: ctx.reviewItems,
8546
8902
  search: async (input) => {
8547
- const login2 = botLoginFromEmail(requireEnv(botEmailEnv));
8548
- if (!login2) {
8903
+ const login = botLoginFromEmail(requireEnv(botEmailEnv));
8904
+ if (!login) {
8549
8905
  throw new Error(`${botEmailEnv} is not a GitHub bot address`);
8550
8906
  }
8551
8907
  return await searchOpenPullRequestMergeability(installationEnv, {
8552
8908
  ...input,
8553
- author: `app/${login2.replace(/\[bot\]$/, "")}`
8909
+ author: `app/${login.replace(/\[bot\]$/, "")}`
8554
8910
  });
8555
8911
  },
8556
8912
  state: ctx.state
@@ -8565,6 +8921,7 @@ function githubPlugin(options = {}) {
8565
8921
  loadLifecycles: async (input) => await loadPullRequestLifecycles(installationEnv, input),
8566
8922
  log: ctx.log,
8567
8923
  nowMs: ctx.nowMs,
8924
+ reviewItems: ctx.reviewItems,
8568
8925
  state: ctx.state
8569
8926
  });
8570
8927
  },
@@ -8616,6 +8973,10 @@ function githubPlugin(options = {}) {
8616
8973
  (await ctx.users.readIdentity(identityId))?.user
8617
8974
  ),
8618
8975
  loadPullRequest: async (pullRequest) => await loadPullRequest(installationEnv, pullRequest),
8976
+ loadPullRequestConflictHistory: async (pullRequest) => await loadPullRequestConflictHistory(
8977
+ installationEnv,
8978
+ pullRequest
8979
+ ),
8619
8980
  loadPullRequestCommitPages: async (pullRequest) => await loadPullRequestCommitPages(installationEnv, pullRequest),
8620
8981
  log: ctx.log,
8621
8982
  markFeedbackReviewing: async (target) => await markPullRequestFeedbackReviewing(installationEnv, target),
@@ -8627,9 +8988,8 @@ function githubPlugin(options = {}) {
8627
8988
  })
8628
8989
  ];
8629
8990
  },
8630
- tools(ctx) {
8991
+ tools() {
8631
8992
  return createGitHubTools(
8632
- ctx,
8633
8993
  readEnv(botEmailEnv),
8634
8994
  gitHubPullRequestSubscription(
8635
8995
  options.pullRequestEvents?.subscribeAfterCreate
@@ -8643,9 +9003,10 @@ function githubPlugin(options = {}) {
8643
9003
  if (ctx.tool.name !== "bash") {
8644
9004
  return;
8645
9005
  }
8646
- const cloneRedirect = typeof ctx.tool.input.command === "string" ? githubCloneCommandRedirect(ctx.tool.input.command) : void 0;
8647
- if (cloneRedirect) {
8648
- ctx.decision.redirect(cloneRedirect);
9006
+ const command = ctx.tool.input.command;
9007
+ const commandRedirect = typeof command === "string" ? githubCloneCommandRedirect(command) || gitHooksPathOverrideRedirect(command) : void 0;
9008
+ if (commandRedirect) {
9009
+ ctx.decision.redirect(commandRedirect);
8649
9010
  return;
8650
9011
  }
8651
9012
  const botName = requireEnv(botNameEnv);