@sentry/junior-github 0.298.0 → 0.299.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 (49) hide show
  1. package/dist/{chunk-OK6BNAGC.js → chunk-O74CQGTZ.js} +50 -20
  2. package/dist/credential-support.d.ts +7 -0
  3. package/dist/db/schema.d.ts +34 -0
  4. package/dist/events/pull-request.d.ts +8 -2
  5. package/dist/graphql-documents.d.ts +31 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +1510 -771
  8. package/dist/object-facts.d.ts +16 -1
  9. package/dist/plugin.d.ts +3 -0
  10. package/dist/pull-request-outcomes/apply.d.ts +3 -1
  11. package/dist/pull-request-outcomes/reconcile.d.ts +10 -5
  12. package/dist/pull-request-outcomes/store.d.ts +5 -0
  13. package/dist/pull-request-requesters/draft-reviewers.d.ts +15 -0
  14. package/dist/testing.js +1 -1
  15. package/dist/tool-support/attribution.d.ts +4 -2
  16. package/dist/tool-support/pull-request-description.d.ts +8 -0
  17. package/dist/tools/clone-repository.d.ts +34 -2
  18. package/dist/tools/comment-on-issue.d.ts +34 -2
  19. package/dist/tools/comment-on-pull-request.d.ts +34 -2
  20. package/dist/tools/create-issue.d.ts +34 -2
  21. package/dist/tools/create-pull-request.d.ts +39 -4
  22. package/dist/tools/get-deployment.d.ts +34 -2
  23. package/dist/tools/get-issue.d.ts +34 -2
  24. package/dist/tools/get-pull-request.d.ts +54 -2
  25. package/dist/tools/get-release.d.ts +34 -2
  26. package/dist/tools/get-repository.d.ts +34 -2
  27. package/dist/tools/get-status.d.ts +34 -2
  28. package/dist/tools/react-to-issue.d.ts +34 -2
  29. package/dist/tools/resolve-pull-request-review-thread.d.ts +34 -2
  30. package/dist/tools/submit-pull-request-review.d.ts +34 -2
  31. package/dist/tools/update-issue-comment.d.ts +34 -2
  32. package/dist/tools/update-issue.d.ts +34 -2
  33. package/dist/tools/update-pull-request-feedback.d.ts +34 -4
  34. package/dist/tools/update-pull-request.d.ts +38 -4
  35. package/dist/tools.d.ts +10 -1
  36. package/dist/webhooks/check-suite.d.ts +2 -4
  37. package/dist/webhooks/fail-open-log.d.ts +10 -0
  38. package/dist/webhooks/handler.d.ts +1 -1
  39. package/dist/webhooks/installation-requests.d.ts +12 -1
  40. package/dist/webhooks/merge-conflict.d.ts +1 -1
  41. package/dist/webhooks/pull-request-preview.d.ts +12 -0
  42. package/dist/webhooks/pull-request-ready-reviewers.d.ts +25 -0
  43. package/dist/webhooks/pull-request-ready.d.ts +1 -1
  44. package/migrations/0011_pull_request_draft.sql +1 -0
  45. package/migrations/meta/0011_snapshot.json +434 -0
  46. package/migrations/meta/_journal.json +7 -0
  47. package/package.json +5 -2
  48. package/skills/github-code/SKILL.md +1 -1
  49. package/skills/github-code/SPEC.md +1 -1
package/dist/index.js CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  GITHUB_REPOSITORY_EVENTS,
26
26
  GITHUB_REPOSITORY_IDENTIFIER,
27
27
  GITHUB_REPOSITORY_SUGGESTED_EVENTS,
28
+ GitHubRequestError,
28
29
  HTTP_READ_METHODS,
29
30
  USER_WRITE_REQUIREMENTS,
30
31
  botLoginFromEmail,
@@ -51,6 +52,7 @@ import {
51
52
  issueInstallationToken,
52
53
  listVerifiedUserEmails,
53
54
  loadCheckSuiteFacts,
55
+ logFailOpenFailure,
54
56
  needsCheckSuitePullRequestFacts,
55
57
  normalizeGitHubEvents,
56
58
  normalizePermissions,
@@ -61,7 +63,7 @@ import {
61
63
  readGrantPermissions,
62
64
  requireEnv,
63
65
  resolveUserAccount
64
- } from "./chunk-OK6BNAGC.js";
66
+ } from "./chunk-O74CQGTZ.js";
65
67
 
66
68
  // src/tool-support/attribution.ts
67
69
  import * as z from "zod";
@@ -157,10 +159,15 @@ var GITHUB_REQUEST_ATTRIBUTION_START = "<!-- junior-request-attribution:start --
157
159
  var GITHUB_REQUEST_ATTRIBUTION_END = "<!-- junior-request-attribution:end -->";
158
160
  var SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
159
161
  var GITHUB_LOGIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
160
- function linkedGitHubLogin(user) {
161
- const login2 = user?.identities.find((identity) => identity.provider === "github")?.handle?.trim().replace(/^@/, "");
162
+ function parseGitHubLogin(value) {
163
+ const login2 = value?.trim().replace(/^@/, "");
162
164
  return login2 && GITHUB_LOGIN_PATTERN.test(login2) ? login2 : void 0;
163
165
  }
166
+ function linkedGitHubLogin(user) {
167
+ return parseGitHubLogin(
168
+ user?.identities.find((identity) => identity.provider === "github")?.handle
169
+ );
170
+ }
164
171
  function cleanDisplayValue(value, userId) {
165
172
  const cleaned = value?.replace(/[\r\n<>]/g, " ").trim();
166
173
  if (!cleaned) {
@@ -693,6 +700,12 @@ function createGitHubCommentOnPullRequestTool(egress) {
693
700
  }
694
701
 
695
702
  // src/object-facts.ts
703
+ import {
704
+ OBJECT_FACTS_MAX_BYTES,
705
+ objectFactsBytes
706
+ } from "@sentry/junior-plugin-api";
707
+ import { lexer, walkTokens } from "marked";
708
+ import { parseFragment } from "parse5";
696
709
  import * as z6 from "zod";
697
710
  var person = z6.object({ login: z6.string() });
698
711
  var responseSchema = z6.object({
@@ -713,7 +726,7 @@ var short = (value) => {
713
726
  const text2 = value?.trim();
714
727
  return text2 ? text2.length > 64 ? `${text2.slice(0, 63)}\u2026` : text2 : void 0;
715
728
  };
716
- function description(body) {
729
+ function visibleBody(body) {
717
730
  let text2 = (body ?? "").replace(
718
731
  /<!-- junior-(session-footer|request-attribution):start -->[\s\S]*?<!-- junior-\1:end -->/g,
719
732
  ""
@@ -721,26 +734,80 @@ function description(body) {
721
734
  while (text2.includes("<!--")) {
722
735
  text2 = text2.replace(/<!--[\s\S]*?(?:-->|$)/g, "");
723
736
  }
724
- text2 = text2.trim();
737
+ return text2.trim();
738
+ }
739
+ function description(body) {
740
+ const text2 = visibleBody(body);
725
741
  if (!text2) return void 0;
726
742
  return text2.length > 4e3 ? `${text2.slice(0, 3999)}\u2026` : text2;
727
743
  }
744
+ function htmlImageSources(html) {
745
+ const sources = [];
746
+ const visit2 = (node) => {
747
+ if ("tagName" in node && node.tagName === "img") {
748
+ const src = node.attrs.find((attr) => attr.name === "src")?.value;
749
+ if (src) sources.push(src);
750
+ }
751
+ if ("childNodes" in node) node.childNodes.forEach(visit2);
752
+ if ("content" in node) visit2(node.content);
753
+ };
754
+ visit2(parseFragment(html));
755
+ return sources;
756
+ }
757
+ function publicArtifactUrl(value) {
758
+ const baseUrl = process.env.JUNIOR_BASE_URL?.trim().replace(/\/+$/, "");
759
+ if (!baseUrl) return void 0;
760
+ let url;
761
+ let prefix;
762
+ try {
763
+ url = new URL(value);
764
+ prefix = new URL(`${baseUrl}/public/artifacts/`);
765
+ } catch {
766
+ return void 0;
767
+ }
768
+ return (url.protocol === "https:" || url.protocol === "http:") && url.origin === prefix.origin && url.pathname.length > prefix.pathname.length && url.pathname.startsWith(prefix.pathname) && !url.username && !url.password && url.href.length <= 512 ? url.href : void 0;
769
+ }
770
+ function githubPreviewImageUrls(body) {
771
+ const sources = [];
772
+ walkTokens(lexer(visibleBody(body), { gfm: true }), (token) => {
773
+ if (token.type === "image") sources.push(token.href);
774
+ if (token.type === "html") sources.push(...htmlImageSources(token.raw));
775
+ });
776
+ return [
777
+ ...new Set(
778
+ sources.map(publicArtifactUrl).filter((url) => url !== void 0)
779
+ )
780
+ ];
781
+ }
782
+ function withGitHubPreviewImages(facts, urls) {
783
+ let bytes = objectFactsBytes(facts) + ',"previewImageUrls":[]'.length;
784
+ const previewImageUrls = [];
785
+ for (const url of urls) {
786
+ bytes += JSON.stringify(url).length + (previewImageUrls.length ? 1 : 0);
787
+ if (bytes > OBJECT_FACTS_MAX_BYTES) break;
788
+ previewImageUrls.push(url);
789
+ }
790
+ return previewImageUrls.length > 0 ? { ...facts, previewImageUrls } : facts;
791
+ }
728
792
  function githubObjectFacts(type, response) {
729
793
  const data = responseSchema.parse(response);
730
794
  const result = {
731
795
  sourceUpdatedAt: data.updated_at,
732
796
  description: description(data.body),
733
- facts: type === "code_change" ? {
734
- type,
735
- author: short(data.user?.login),
736
- reviewers: data.requested_reviewers?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
737
- sourceBranch: short(data.head?.ref),
738
- targetBranch: short(data.base?.ref),
739
- mergeable: data.mergeable ?? void 0,
740
- changedFiles: data.changed_files,
741
- additions: data.additions,
742
- deletions: data.deletions
743
- } : {
797
+ facts: type === "code_change" ? withGitHubPreviewImages(
798
+ {
799
+ type,
800
+ author: short(data.user?.login),
801
+ reviewers: data.requested_reviewers?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
802
+ sourceBranch: short(data.head?.ref),
803
+ targetBranch: short(data.base?.ref),
804
+ mergeable: data.mergeable ?? void 0,
805
+ changedFiles: data.changed_files,
806
+ additions: data.additions,
807
+ deletions: data.deletions
808
+ },
809
+ githubPreviewImageUrls(data.body)
810
+ ) : {
744
811
  type,
745
812
  assignees: data.assignees?.slice(0, 5).map((user) => short(user.login)).filter(Boolean),
746
813
  labels: data.labels?.slice(0, 5).map(
@@ -949,11 +1016,11 @@ function githubLinkedIssues(body, repositoryFullName) {
949
1016
  if (!body) return [];
950
1017
  const references = /* @__PURE__ */ new Map();
951
1018
  const add = (linkedRepository, rawNumber) => {
952
- const number31 = Number.parseInt(rawNumber, 10);
953
- if (!Number.isInteger(number31) || number31 <= 0) return;
1019
+ const number33 = Number.parseInt(rawNumber, 10);
1020
+ if (!Number.isInteger(number33) || number33 <= 0) return;
954
1021
  const normalizedRepository = linkedRepository.toLowerCase();
955
- references.set(`${normalizedRepository}#${number31}`, {
956
- number: number31,
1022
+ references.set(`${normalizedRepository}#${number33}`, {
1023
+ number: number33,
957
1024
  repositoryFullName: linkedRepository
958
1025
  });
959
1026
  };
@@ -1537,14 +1604,33 @@ import {
1537
1604
  objectFactsSchema as objectFactsSchema2,
1538
1605
  definePluginTool as definePluginTool8,
1539
1606
  EgressAuthRequired as EgressAuthRequired2,
1540
- PluginToolInputError as PluginToolInputError10,
1607
+ PluginToolInputError as PluginToolInputError11,
1541
1608
  pluginToolOutputSchema as pluginToolOutputSchema8,
1542
1609
  watchResultSchema,
1543
1610
  subscribableResourceSchema as subscribableResourceSchema4
1544
1611
  } from "@sentry/junior-plugin-api";
1545
1612
  import { Type as Type2 } from "@sinclair/typebox";
1546
1613
  import { Value as Value2 } from "@sinclair/typebox/value";
1547
- import * as z12 from "zod";
1614
+ import * as z13 from "zod";
1615
+
1616
+ // src/pull-request-requesters/draft-reviewers.ts
1617
+ import * as z10 from "zod";
1618
+ var DRAFT_REVIEWERS_TTL_MS = 14 * 24 * 60 * 60 * 1e3;
1619
+ var reviewersSchema = z10.array(z10.string().min(1)).min(1);
1620
+ function draftReviewersKey(target) {
1621
+ return `pull-request-draft-reviewers:${target.repositoryFullName.toLowerCase()}#${target.number}`;
1622
+ }
1623
+ async function saveGitHubDraftReviewers(state, target, reviewers) {
1624
+ await state.set(
1625
+ draftReviewersKey(target),
1626
+ reviewersSchema.parse(reviewers),
1627
+ DRAFT_REVIEWERS_TTL_MS
1628
+ );
1629
+ }
1630
+ async function readGitHubDraftReviewers(state, target) {
1631
+ const saved = await state.get(draftReviewersKey(target));
1632
+ return saved === void 0 ? void 0 : reviewersSchema.parse(saved);
1633
+ }
1548
1634
 
1549
1635
  // src/pull-request-requesters/store.ts
1550
1636
  import { and, asc, eq, inArray, lt } from "drizzle-orm";
@@ -1552,6 +1638,7 @@ import { and, asc, eq, inArray, lt } from "drizzle-orm";
1552
1638
  // src/db/schema.ts
1553
1639
  import { sql } from "drizzle-orm";
1554
1640
  import {
1641
+ boolean as boolean3,
1555
1642
  index,
1556
1643
  integer,
1557
1644
  pgTable,
@@ -1559,18 +1646,18 @@ import {
1559
1646
  text,
1560
1647
  timestamp
1561
1648
  } from "drizzle-orm/pg-core";
1562
- import * as z10 from "zod";
1563
- var githubPullRequestStateSchema = z10.enum([
1649
+ import * as z11 from "zod";
1650
+ var githubPullRequestStateSchema = z11.enum([
1564
1651
  "closed_unmerged",
1565
1652
  "merged",
1566
1653
  "open"
1567
1654
  ]);
1568
- var githubPullRequestCommitCompositionSchema = z10.enum([
1655
+ var githubPullRequestCommitCompositionSchema = z11.enum([
1569
1656
  "junior_only",
1570
1657
  "mixed"
1571
1658
  ]);
1572
- var githubIssueStateSchema = z10.enum(["closed", "open"]);
1573
- var githubIssueStateReasonSchema = z10.enum([
1659
+ var githubIssueStateSchema = z11.enum(["closed", "open"]);
1660
+ var githubIssueStateReasonSchema = z11.enum([
1574
1661
  "completed",
1575
1662
  "duplicate",
1576
1663
  "not_planned",
@@ -1606,6 +1693,8 @@ var juniorGitHubPullRequests = pgTable(
1606
1693
  state: text("state").$type().notNull(),
1607
1694
  commitComposition: text("commit_composition").$type(),
1608
1695
  conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
1696
+ /** The daily reconcile compares this with GitHub. */
1697
+ draft: boolean3("draft").notNull().default(false),
1609
1698
  openedAt: timestamp("opened_at", { withTimezone: true }).notNull(),
1610
1699
  mergedAt: timestamp("merged_at", { withTimezone: true }),
1611
1700
  closedAt: timestamp("closed_at", { withTimezone: true }),
@@ -1731,32 +1820,32 @@ async function listGitHubPullRequestOpeners(db, input) {
1731
1820
  }
1732
1821
 
1733
1822
  // src/tools/stack-pull-request.ts
1734
- import * as z11 from "zod";
1823
+ import * as z12 from "zod";
1735
1824
  var MAX_STACK_DEPTH = 10;
1736
1825
  var GITHUB_STACKS_API_VERSION = "2026-03-10";
1737
- var stackTargetSchema = z11.object({
1738
- number: z11.number().int().positive(),
1739
- head: z11.object({
1740
- ref: z11.string().min(1),
1741
- repo: z11.object({ full_name: z11.string().min(1) }).nullable()
1826
+ var stackTargetSchema = z12.object({
1827
+ number: z12.number().int().positive(),
1828
+ head: z12.object({
1829
+ ref: z12.string().min(1),
1830
+ repo: z12.object({ full_name: z12.string().min(1) }).nullable()
1742
1831
  }),
1743
- base: z11.object({
1744
- ref: z11.string().min(1),
1745
- repo: z11.object({
1746
- default_branch: z11.string().min(1),
1747
- full_name: z11.string().min(1)
1832
+ base: z12.object({
1833
+ ref: z12.string().min(1),
1834
+ repo: z12.object({
1835
+ default_branch: z12.string().min(1),
1836
+ full_name: z12.string().min(1)
1748
1837
  })
1749
1838
  })
1750
1839
  });
1751
- var openPullRequestsSchema = z11.array(
1752
- z11.object({
1753
- number: z11.number().int().positive(),
1754
- base: z11.object({ ref: z11.string().min(1) })
1840
+ var openPullRequestsSchema = z12.array(
1841
+ z12.object({
1842
+ number: z12.number().int().positive(),
1843
+ base: z12.object({ ref: z12.string().min(1) })
1755
1844
  })
1756
1845
  );
1757
- var stackSchema = z11.object({
1758
- number: z11.number().int().positive(),
1759
- pull_requests: z11.array(z11.object({ number: z11.number().int().positive() }))
1846
+ var stackSchema = z12.object({
1847
+ number: z12.number().int().positive(),
1848
+ pull_requests: z12.array(z12.object({ number: z12.number().int().positive() }))
1760
1849
  });
1761
1850
  async function stackGitHubPullRequest(ctx, target) {
1762
1851
  const repo = target.base.repo.full_name;
@@ -1766,17 +1855,17 @@ async function stackGitHubPullRequest(ctx, target) {
1766
1855
  }
1767
1856
  const [owner, name] = repo.split("/");
1768
1857
  const api = repoPath({ owner, name });
1769
- const github = async (operation, path, schema, body) => {
1858
+ const github = async (operation2, path, schema, body) => {
1770
1859
  const response = await githubApi(ctx.egress, {
1771
1860
  apiVersion: GITHUB_STACKS_API_VERSION,
1772
- operation,
1861
+ operation: operation2,
1773
1862
  path,
1774
1863
  ...body === void 0 ? void 0 : { method: "POST", body }
1775
1864
  });
1776
1865
  if (!response.ok) {
1777
1866
  ctx.log.warn("github.pull_request.stack_after_create.rejected", {
1778
1867
  number: target.number,
1779
- operation,
1868
+ operation: operation2,
1780
1869
  repo,
1781
1870
  status: response.status
1782
1871
  });
@@ -1804,7 +1893,7 @@ async function stackGitHubPullRequest(ctx, target) {
1804
1893
  const stacks = await github(
1805
1894
  "github.stack.read",
1806
1895
  `${api}/stacks?pull_request=${parent.number}`,
1807
- z11.array(stackSchema)
1896
+ z12.array(stackSchema)
1808
1897
  );
1809
1898
  if (!stacks) return void 0;
1810
1899
  const stack = stacks[0];
@@ -1841,6 +1930,59 @@ async function stackGitHubPullRequest(ctx, target) {
1841
1930
  }
1842
1931
  }
1843
1932
 
1933
+ // src/tool-support/pull-request-description.ts
1934
+ import {
1935
+ PluginToolInputError as PluginToolInputError10
1936
+ } from "@sentry/junior-plugin-api";
1937
+ var MISSING_REASON_FIX = "Say why the change is needed.";
1938
+ var DESCRIPTION_CHECKS = [
1939
+ {
1940
+ question: "Does the description report how tests, lint, typecheck, or CI went when the author ran them, passing or failing, locally or in CI, or describe a test plan or test coverage, including what has no tests? Text about what the product does with such commands does not count.",
1941
+ fix: "Remove check results, test plans, test coverage notes, and commands. Reviewers see checks on the pull request."
1942
+ },
1943
+ {
1944
+ question: "Does the description narrate the author's own work session, such as what the author investigated, approaches or names the author tried first and dropped, or how many runs the author looked at? Old behavior compared with new behavior does not count.",
1945
+ fix: "Remove the work log. Describe the change as it is now."
1946
+ },
1947
+ {
1948
+ question: "Does the description mention the request for this pull request, such as who asked for it or a chat message about it? A product feature that involves Slack or chat does not count.",
1949
+ fix: "Remove the conversation. The runtime adds who asked."
1950
+ },
1951
+ {
1952
+ question: "Does the description leave out why the change is needed or what problem it fixes?",
1953
+ fix: MISSING_REASON_FIX
1954
+ }
1955
+ ];
1956
+ async function pullRequestDescriptionFixes(decider, body) {
1957
+ if (!body.trim()) {
1958
+ return [MISSING_REASON_FIX];
1959
+ }
1960
+ const answers = await Promise.all(
1961
+ DESCRIPTION_CHECKS.map(
1962
+ ({ question }) => decider.decide({
1963
+ criteria: { no: "No.", yes: "Yes." },
1964
+ instructions: `Judge this GitHub pull request description. ${question}`,
1965
+ state: body
1966
+ })
1967
+ )
1968
+ );
1969
+ return DESCRIPTION_CHECKS.filter(
1970
+ (_, index2) => answers[index2].choice === "yes"
1971
+ ).map(({ fix }) => fix);
1972
+ }
1973
+ async function checkPullRequestDescription(decider, body) {
1974
+ const fixes = await pullRequestDescriptionFixes(decider, body);
1975
+ if (fixes.length > 0) {
1976
+ throw new PluginToolInputError10(
1977
+ [
1978
+ "Pull request description rejected. Fix it and call the tool again:",
1979
+ ...fixes.map((fix) => `- ${fix}`),
1980
+ "Write for a reviewer with no context: what changes and why, whether anything breaks and what to do, linked issues, and open questions. Keep it short."
1981
+ ].join("\n")
1982
+ );
1983
+ }
1984
+ }
1985
+
1844
1986
  // src/tools/create-pull-request.ts
1845
1987
  var GITHUB_PULL_REQUEST_CREATE_IDEMPOTENCY_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1846
1988
  var GITHUB_PULL_REQUEST_CREATE_LOCK_TTL_MS = 6e4;
@@ -1852,6 +1994,7 @@ var GitHubPullRequestCreateRejectedError = class extends Error {
1852
1994
  this.status = status;
1853
1995
  }
1854
1996
  };
1997
+ var REVIEWERS_DESCRIPTION = "GitHub logins to ask for a review. Set this only when the person names who should review. Without it, Junior asks the requester's linked GitHub account. A draft gets the request when it becomes ready for review.";
1855
1998
  var createPullRequestInputSchema = Type2.Object(
1856
1999
  {
1857
2000
  repo: Type2.String({
@@ -1875,19 +2018,26 @@ var createPullRequestInputSchema = Type2.Object(
1875
2018
  Type2.Boolean({
1876
2019
  description: "Whether to open the pull request as a draft."
1877
2020
  })
2021
+ ),
2022
+ reviewers: Type2.Optional(
2023
+ Type2.Array(Type2.String(), {
2024
+ description: REVIEWERS_DESCRIPTION,
2025
+ minItems: 1
2026
+ })
1878
2027
  )
1879
2028
  },
1880
2029
  { additionalProperties: false }
1881
2030
  );
1882
- var createPullRequestToolInputSchema = z12.object({
1883
- repo: z12.string().describe('Repository in "owner/name" format.'),
1884
- title: z12.string().describe("Pull request title."),
1885
- head: z12.string().describe("Head branch or owner:branch ref."),
1886
- base: z12.string().describe("Base branch."),
1887
- body: z12.string().describe(
2031
+ var createPullRequestToolInputSchema = z13.object({
2032
+ repo: z13.string().describe('Repository in "owner/name" format.'),
2033
+ title: z13.string().describe("Pull request title."),
2034
+ head: z13.string().describe("Head branch or owner:branch ref."),
2035
+ base: z13.string().describe("Base branch."),
2036
+ body: z13.string().describe(
1888
2037
  "Pull request body. The runtime appends the conversation footer."
1889
2038
  ).optional(),
1890
- draft: z12.boolean().describe("Whether to open the pull request as a draft.").optional()
2039
+ draft: z13.boolean().describe("Whether to open the pull request as a draft.").optional(),
2040
+ reviewers: z13.array(z13.string()).min(1).describe(REVIEWERS_DESCRIPTION).optional()
1891
2041
  }).strict();
1892
2042
  var createPullRequestStateSchema = Type2.Union([
1893
2043
  Type2.Object(
@@ -1912,30 +2062,30 @@ var createPullRequestStateSchema = Type2.Union([
1912
2062
  { additionalProperties: false }
1913
2063
  )
1914
2064
  ]);
1915
- var gitHubPullRequestDataSchema = z12.object({
1916
- number: z12.number(),
1917
- url: z12.string(),
1918
- stack: z12.object({ number: z12.number(), pull_requests: z12.array(z12.number()) }).optional(),
2065
+ var gitHubPullRequestDataSchema = z13.object({
2066
+ number: z13.number(),
2067
+ url: z13.string(),
2068
+ stack: z13.object({ number: z13.number(), pull_requests: z13.array(z13.number()) }).optional(),
1919
2069
  subscribable: subscribableResourceSchema4.optional(),
1920
2070
  subscription: watchResultSchema.optional()
1921
2071
  });
1922
2072
  var gitHubPullRequestOutputSchema = pluginToolOutputSchema8.merge(
1923
2073
  gitHubPullRequestDataSchema.extend({
1924
- target: z12.literal("createPullRequest")
2074
+ target: z13.literal("createPullRequest")
1925
2075
  })
1926
2076
  );
1927
2077
  function parseCreatePullRequestInput(input) {
1928
2078
  try {
1929
2079
  return Value2.Parse(createPullRequestInputSchema, input);
1930
2080
  } catch (error) {
1931
- throw new PluginToolInputError10("Invalid GitHub createPullRequest input.", {
2081
+ throw new PluginToolInputError11("Invalid GitHub createPullRequest input.", {
1932
2082
  cause: error
1933
2083
  });
1934
2084
  }
1935
2085
  }
1936
2086
  function nonEmptyString3(value, name) {
1937
2087
  if (!value?.trim()) {
1938
- throw new PluginToolInputError10(`${name} is required`);
2088
+ throw new PluginToolInputError11(`${name} is required`);
1939
2089
  }
1940
2090
  return value.trim();
1941
2091
  }
@@ -1955,10 +2105,13 @@ function isEgressAuthRequired2(error) {
1955
2105
  return error instanceof EgressAuthRequired2 || error instanceof Error && error.name === "EgressAuthRequired";
1956
2106
  }
1957
2107
  function isDefinitiveGitHubPullRequestCreateRejection(error) {
2108
+ if (error instanceof PluginToolInputError11) {
2109
+ return true;
2110
+ }
1958
2111
  if (!(error instanceof GitHubPullRequestCreateRejectedError)) {
1959
2112
  return false;
1960
2113
  }
1961
- return [400, 401, 404, 410, 422].includes(error.status);
2114
+ return [400, 401, 410].includes(error.status);
1962
2115
  }
1963
2116
  function createGitHubPullRequestRequest(conversationId, input, ctx, requester, dashboardUrl) {
1964
2117
  const repo = parseRepo(input.repo);
@@ -1983,12 +2136,13 @@ async function createGitHubPullRequest(ctx, request) {
1983
2136
  });
1984
2137
  const parsed = response.body;
1985
2138
  if (!response.ok) {
1986
- throw new GitHubPullRequestCreateRejectedError(
1987
- `GitHub pull request creation failed with HTTP ${response.status}: ${githubErrorMessage(
1988
- parsed
1989
- )}`,
1990
- response.status
1991
- );
2139
+ const message = `GitHub pull request creation failed with HTTP ${response.status}: ${githubErrorMessage(
2140
+ parsed
2141
+ )}`;
2142
+ if (response.status === 404 || response.status === 422) {
2143
+ throw new PluginToolInputError11(message);
2144
+ }
2145
+ throw new GitHubPullRequestCreateRejectedError(message, response.status);
1992
2146
  }
1993
2147
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1994
2148
  throw new Error(
@@ -2049,6 +2203,59 @@ async function assignPullRequestRequester(ctx, input, result, requester) {
2049
2203
  });
2050
2204
  }
2051
2205
  }
2206
+ function namedReviewers(input) {
2207
+ return input.reviewers?.map((value) => {
2208
+ const login2 = parseGitHubLogin(value);
2209
+ if (!login2) {
2210
+ throw new PluginToolInputError11(`Invalid GitHub reviewer login: ${value}`);
2211
+ }
2212
+ return login2;
2213
+ });
2214
+ }
2215
+ async function saveNamedDraftReviewers(ctx, input, number33) {
2216
+ const named = namedReviewers(input);
2217
+ if (!input.draft || !named) return;
2218
+ await saveGitHubDraftReviewers(
2219
+ ctx.state,
2220
+ { number: number33, repositoryFullName: parseRepo(input.repo).ref },
2221
+ named
2222
+ );
2223
+ }
2224
+ async function requestPullRequestReviewers(ctx, input, result, requester) {
2225
+ const named = namedReviewers(input);
2226
+ const repo = parseRepo(input.repo);
2227
+ try {
2228
+ if (input.draft) {
2229
+ await saveNamedDraftReviewers(ctx, input, result.number);
2230
+ return;
2231
+ }
2232
+ const requesterLogin = linkedGitHubLogin(requester?.user);
2233
+ const reviewers = named ?? (requesterLogin ? [requesterLogin] : []);
2234
+ if (reviewers.length === 0) return;
2235
+ const response = await githubApi(ctx.egress, {
2236
+ operation: "github.pull.request_reviewers",
2237
+ method: "POST",
2238
+ path: `${repoPath(repo)}/pulls/${result.number}/requested_reviewers`,
2239
+ body: { reviewers }
2240
+ });
2241
+ if (!response.ok) {
2242
+ ctx.log.warn(
2243
+ "github.pull_request.request_reviewers_after_create.rejected",
2244
+ {
2245
+ number: result.number,
2246
+ repo: input.repo,
2247
+ status: response.status
2248
+ }
2249
+ );
2250
+ }
2251
+ } catch (error) {
2252
+ ctx.log.warn("github.pull_request.request_reviewers_after_create.failed", {
2253
+ error: error instanceof Error ? error.message : String(error),
2254
+ number: result.number,
2255
+ repo: input.repo
2256
+ });
2257
+ }
2258
+ }
2052
2259
  function gitHubPullRequestToolResult(input, result, canSubscribe, omitSuggestedEvents) {
2053
2260
  const repo = parseRepo(input.repo);
2054
2261
  const subscribable = gitHubPullRequestSubscribable({
@@ -2090,7 +2297,9 @@ async function gitHubPullRequestStructuredResult(ctx, input, result, subscriptio
2090
2297
  ...stack ? { stack } : void 0
2091
2298
  };
2092
2299
  }
2093
- const watch = gitHubPullRequestCreateWatch(subscriptionConfig);
2300
+ const watch = gitHubPullRequestCreateWatch(subscriptionConfig, {
2301
+ draft: input.draft === true
2302
+ });
2094
2303
  try {
2095
2304
  const subscription = await ctx.events.subscribe({
2096
2305
  ...watch,
@@ -2123,7 +2332,7 @@ async function gitHubPullRequestStructuredResult(ctx, input, result, subscriptio
2123
2332
  };
2124
2333
  }
2125
2334
  }
2126
- function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2335
+ function createGitHubPullRequestTool(ctx, subscriptionConfig, descriptionDecider) {
2127
2336
  return definePluginTool8({
2128
2337
  annotations: {
2129
2338
  destructiveHint: false,
@@ -2131,12 +2340,13 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2131
2340
  openWorldHint: true,
2132
2341
  readOnlyHint: false
2133
2342
  },
2134
- description: "Create a GitHub pull request with a runtime-owned conversation footer and assign it to the requester's linked GitHub account when available. Use this instead of shelling out to gh pr create when creating pull requests.",
2343
+ description: "Create a GitHub pull request with a runtime-owned conversation footer. It assigns the pull request to the requester's linked GitHub account and asks for a review when available. Use this instead of shelling out to gh pr create when creating pull requests.",
2135
2344
  exposure: "direct",
2136
2345
  inputSchema: createPullRequestToolInputSchema,
2137
2346
  outputSchema: gitHubPullRequestOutputSchema,
2138
2347
  async execute(input, options) {
2139
2348
  const parsedInput = parseCreatePullRequestInput(input);
2349
+ namedReviewers(parsedInput);
2140
2350
  const conversationId = nonEmptyString3(
2141
2351
  ctx.conversationId,
2142
2352
  "conversationId"
@@ -2154,6 +2364,7 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2154
2364
  conversationId,
2155
2365
  identityId: (await resolveGitHubRequester(ctx))?.identity?.id
2156
2366
  });
2367
+ await saveNamedDraftReviewers(ctx, completedInput, state.number);
2157
2368
  const completedResult = {
2158
2369
  facts: state.facts === void 0 ? void 0 : objectFactsSchema2.parse(state.facts),
2159
2370
  sourceUpdatedAt: state.sourceUpdatedAt,
@@ -2173,6 +2384,12 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2173
2384
  "GitHub pull request creation for this tool call has an uncertain pending result; refusing to create a duplicate pull request."
2174
2385
  );
2175
2386
  }
2387
+ if (descriptionDecider) {
2388
+ await checkPullRequestDescription(
2389
+ descriptionDecider,
2390
+ parsedInput.body ?? ""
2391
+ );
2392
+ }
2176
2393
  const requester = await resolveGitHubRequester(ctx);
2177
2394
  const identityId = requester?.identity?.id;
2178
2395
  const request = createGitHubPullRequestRequest(
@@ -2227,6 +2444,12 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2227
2444
  identityId
2228
2445
  });
2229
2446
  await assignPullRequestRequester(ctx, parsedInput, result, requester);
2447
+ await requestPullRequestReviewers(
2448
+ ctx,
2449
+ parsedInput,
2450
+ result,
2451
+ requester
2452
+ );
2230
2453
  const stack = stackTarget ? await stackGitHubPullRequest(ctx, stackTarget) : void 0;
2231
2454
  return await gitHubPullRequestStructuredResult(
2232
2455
  ctx,
@@ -2244,33 +2467,322 @@ function createGitHubPullRequestTool(ctx, subscriptionConfig) {
2244
2467
  // src/tools/get-pull-request.ts
2245
2468
  import {
2246
2469
  definePluginTool as definePluginTool9,
2247
- PluginToolInputError as PluginToolInputError11,
2470
+ PluginToolInputError as PluginToolInputError12,
2248
2471
  pluginToolOutputSchema as pluginToolOutputSchema9
2249
2472
  } from "@sentry/junior-plugin-api";
2250
- import * as z13 from "zod";
2473
+ import * as z14 from "zod";
2251
2474
  import { subscribableResourceSchema as subscribableResourceSchema5 } from "@sentry/junior-plugin-api";
2252
- var commitShaSchema2 = z13.string().regex(/^[0-9a-f]{40}$/i);
2253
- var inputSchema7 = z13.object({
2254
- repo: z13.string().describe('Repository in "owner/name" format.'),
2255
- number: z13.number().int().positive().describe("Pull request number.")
2475
+
2476
+ // src/graphql-documents.ts
2477
+ import {
2478
+ Kind,
2479
+ parse,
2480
+ print,
2481
+ visit
2482
+ } from "@0no-co/graphql.web";
2483
+ function operation(document) {
2484
+ const [definition] = document.definitions;
2485
+ if (definition?.kind !== Kind.OPERATION_DEFINITION || !definition.name) {
2486
+ throw new Error(
2487
+ "GitHub GraphQL document must start with a named operation"
2488
+ );
2489
+ }
2490
+ return { operationName: definition.name.value, query: print(document) };
2491
+ }
2492
+ function githubGraphql(source) {
2493
+ return operation(parse(source));
2494
+ }
2495
+ var ADD_REVIEW_REACTION = githubGraphql(`
2496
+ mutation AddReviewReaction($subjectId: ID!, $content: ReactionContent!) {
2497
+ addReaction(input: { subjectId: $subjectId, content: $content }) {
2498
+ reaction { content }
2499
+ }
2500
+ }
2501
+ `);
2502
+ var REMOVE_REVIEW_REACTION = githubGraphql(`
2503
+ mutation RemoveReviewReaction($subjectId: ID!, $content: ReactionContent!) {
2504
+ removeReaction(input: { subjectId: $subjectId, content: $content }) {
2505
+ reaction { content }
2506
+ }
2507
+ }
2508
+ `);
2509
+ var REVIEW_REACTIONS = githubGraphql(`
2510
+ query ReviewReactions($subjectId: ID!) {
2511
+ node(id: $subjectId) {
2512
+ ... on PullRequestReview {
2513
+ reactionGroups {
2514
+ content
2515
+ reactors(first: 100) { nodes { ... on Bot { databaseId } } }
2516
+ }
2517
+ }
2518
+ }
2519
+ }
2520
+ `);
2521
+ var MARK_PULL_REQUEST_READY_FOR_REVIEW = githubGraphql(`
2522
+ mutation MarkPullRequestReadyForReview($id: ID!) {
2523
+ result: markPullRequestReadyForReview(input: { pullRequestId: $id }) {
2524
+ pullRequest { isDraft }
2525
+ }
2526
+ }
2527
+ `);
2528
+ var CONVERT_PULL_REQUEST_TO_DRAFT = githubGraphql(`
2529
+ mutation ConvertPullRequestToDraft($id: ID!) {
2530
+ result: convertPullRequestToDraft(input: { pullRequestId: $id }) {
2531
+ pullRequest { isDraft }
2532
+ }
2533
+ }
2534
+ `);
2535
+ var REVIEW_THREAD_OWNERSHIP = githubGraphql(`
2536
+ query ReviewThreadOwnership($threadId: ID!) {
2537
+ node(id: $threadId) {
2538
+ ... on PullRequestReviewThread {
2539
+ id
2540
+ isResolved
2541
+ pullRequest {
2542
+ number
2543
+ repository { nameWithOwner }
2544
+ author { ... on Bot { databaseId } }
2545
+ }
2546
+ }
2547
+ }
2548
+ }
2549
+ `);
2550
+ var RESOLVE_REVIEW_THREAD = githubGraphql(`
2551
+ mutation ResolveReviewThread($threadId: ID!) {
2552
+ resolveReviewThread(input: { threadId: $threadId }) {
2553
+ thread { id isResolved }
2554
+ }
2555
+ }
2556
+ `);
2557
+ var PULL_REQUEST_CHECKS = githubGraphql(`
2558
+ query PullRequestChecks($owner: String!, $name: String!, $number: Int!) {
2559
+ repository(owner: $owner, name: $name) {
2560
+ pullRequest(number: $number) {
2561
+ mergeStateStatus
2562
+ reviewDecision
2563
+ autoMergeRequest { enabledAt }
2564
+ commits(last: 1) {
2565
+ nodes {
2566
+ commit {
2567
+ statusCheckRollup {
2568
+ contexts(first: 100) {
2569
+ pageInfo { hasNextPage }
2570
+ nodes {
2571
+ __typename
2572
+ ... on CheckRun {
2573
+ name
2574
+ status
2575
+ conclusion
2576
+ isRequired(pullRequestNumber: $number)
2577
+ }
2578
+ ... on StatusContext {
2579
+ context
2580
+ state
2581
+ isRequired(pullRequestNumber: $number)
2582
+ }
2583
+ }
2584
+ }
2585
+ }
2586
+ }
2587
+ }
2588
+ }
2589
+ }
2590
+ }
2591
+ }
2592
+ `);
2593
+ var OPEN_PULL_REQUEST_MERGEABILITY = githubGraphql(`
2594
+ query OpenPullRequestMergeability($query: String!, $after: String) {
2595
+ search(query: $query, type: ISSUE, first: 100, after: $after) {
2596
+ pageInfo { hasNextPage endCursor }
2597
+ nodes {
2598
+ ... on PullRequest { number state mergeable headRefOid baseRefName url }
2599
+ }
2600
+ }
2601
+ }
2602
+ `);
2603
+ var PULL_REQUEST_LIFECYCLE = githubGraphql(`
2604
+ query PullRequestLifecycles($owner: String!, $name: String!, $number: Int!) {
2605
+ repository(owner: $owner, name: $name) {
2606
+ databaseId
2607
+ nameWithOwner
2608
+ pullRequest(number: $number) { ...Lifecycle }
2609
+ }
2610
+ }
2611
+
2612
+ fragment Lifecycle on PullRequest {
2613
+ assignees(first: 20) { nodes { login } }
2614
+ author { __typename login }
2615
+ closedAt
2616
+ createdAt
2617
+ databaseId
2618
+ headRefName
2619
+ isDraft
2620
+ merged
2621
+ mergedAt
2622
+ number
2623
+ state
2624
+ title
2625
+ updatedAt
2626
+ }
2627
+ `);
2628
+ function pullRequestLifecycles(count) {
2629
+ const indexes = Array.from({ length: count }, (_, index2) => index2);
2630
+ const variable = (index2) => ({
2631
+ kind: Kind.VARIABLE,
2632
+ name: { kind: Kind.NAME, value: `n${index2}` }
2633
+ });
2634
+ return operation(
2635
+ visit(parse(PULL_REQUEST_LIFECYCLE.query), {
2636
+ OperationDefinition: (node) => ({
2637
+ ...node,
2638
+ variableDefinitions: node.variableDefinitions?.flatMap(
2639
+ (definition) => definition.variable.name.value === "number" ? indexes.map((index2) => ({
2640
+ ...definition,
2641
+ variable: variable(index2)
2642
+ })) : [definition]
2643
+ )
2644
+ }),
2645
+ SelectionSet: (node) => ({
2646
+ ...node,
2647
+ selections: node.selections.flatMap(
2648
+ (selection) => selection.kind === Kind.FIELD && selection.name.value === "pullRequest" ? indexes.map((index2) => ({
2649
+ ...selection,
2650
+ alias: { kind: Kind.NAME, value: `pr${index2}` },
2651
+ arguments: selection.arguments?.map((argument) => ({
2652
+ ...argument,
2653
+ value: variable(index2)
2654
+ }))
2655
+ })) : [selection]
2656
+ )
2657
+ })
2658
+ })
2659
+ );
2660
+ }
2661
+
2662
+ // src/tools/get-pull-request.ts
2663
+ var commitShaSchema2 = z14.string().regex(/^[0-9a-f]{40}$/i);
2664
+ var inputSchema7 = z14.object({
2665
+ repo: z14.string().describe('Repository in "owner/name" format.'),
2666
+ number: z14.number().int().positive().describe("Pull request number.")
2256
2667
  }).strict();
2257
- var pullRequestSchema = z13.object({
2258
- base: z13.string(),
2259
- draft: z13.boolean(),
2260
- head: z13.string(),
2668
+ var checksSchema = z14.object({
2669
+ required: z14.enum(["passing", "failing", "pending", "not_reported"]).describe(
2670
+ "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."
2671
+ ),
2672
+ failing: z14.array(z14.string()).describe("Required checks that failed."),
2673
+ pending: z14.array(z14.string()).describe("Required checks that have not finished."),
2674
+ passing: z14.array(z14.string()).describe("Required checks that passed."),
2675
+ incomplete: z14.literal(true).optional().describe(
2676
+ "Set when the head commit has more than 100 checks, so some required checks are not listed."
2677
+ ),
2678
+ merge_state: z14.string().describe(
2679
+ "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."
2680
+ ),
2681
+ review_decision: z14.string().nullable().describe(
2682
+ "GitHub reviewDecision: APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED, or null when no review is required."
2683
+ ),
2684
+ auto_merge: z14.boolean().describe("true when auto-merge is on for the pull request.")
2685
+ });
2686
+ var pullRequestSchema = z14.object({
2687
+ base: z14.string(),
2688
+ checks: checksSchema,
2689
+ draft: z14.boolean(),
2690
+ head: z14.string(),
2261
2691
  head_sha: commitShaSchema2,
2262
- merged: z13.boolean(),
2263
- number: z13.number(),
2264
- state: z13.string(),
2692
+ merged: z14.boolean(),
2693
+ number: z14.number(),
2694
+ state: z14.string(),
2265
2695
  subscribable: subscribableResourceSchema5.optional(),
2266
- title: z13.string(),
2267
- url: z13.string()
2696
+ title: z14.string(),
2697
+ url: z14.string()
2268
2698
  });
2269
2699
  var outputSchema7 = pluginToolOutputSchema9.merge(
2270
2700
  pullRequestSchema.extend({
2271
- target: z13.literal("getPullRequest")
2701
+ target: z14.literal("getPullRequest")
2272
2702
  })
2273
2703
  );
2704
+ var checkContextSchema = z14.union([
2705
+ z14.object({
2706
+ __typename: z14.literal("CheckRun"),
2707
+ conclusion: z14.string().nullable(),
2708
+ isRequired: z14.boolean(),
2709
+ name: z14.string(),
2710
+ status: z14.string()
2711
+ }),
2712
+ z14.object({
2713
+ __typename: z14.literal("StatusContext"),
2714
+ context: z14.string(),
2715
+ isRequired: z14.boolean(),
2716
+ state: z14.string()
2717
+ })
2718
+ ]);
2719
+ var checksResponseSchema = z14.object({
2720
+ data: z14.object({
2721
+ repository: z14.object({
2722
+ pullRequest: z14.object({
2723
+ autoMergeRequest: z14.object({}).passthrough().nullable(),
2724
+ commits: z14.object({
2725
+ nodes: z14.array(
2726
+ z14.object({
2727
+ commit: z14.object({
2728
+ statusCheckRollup: z14.object({
2729
+ contexts: z14.object({
2730
+ nodes: z14.array(checkContextSchema),
2731
+ pageInfo: z14.object({ hasNextPage: z14.boolean() })
2732
+ })
2733
+ }).nullable()
2734
+ })
2735
+ })
2736
+ )
2737
+ }),
2738
+ mergeStateStatus: z14.string(),
2739
+ reviewDecision: z14.string().nullable()
2740
+ })
2741
+ })
2742
+ })
2743
+ });
2744
+ var PASSING_CONCLUSIONS = /* @__PURE__ */ new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
2745
+ function contextState(context) {
2746
+ if (context.__typename === "CheckRun") {
2747
+ if (context.status !== "COMPLETED") return "pending";
2748
+ return PASSING_CONCLUSIONS.has(context.conclusion ?? "") ? "passing" : "failing";
2749
+ }
2750
+ if (context.state === "SUCCESS") return "passing";
2751
+ return context.state === "PENDING" || context.state === "EXPECTED" ? "pending" : "failing";
2752
+ }
2753
+ async function readPullRequestChecks(egress, repo, number33) {
2754
+ const response = await githubApi(egress, {
2755
+ operation: "github.pull.checks.get",
2756
+ method: "POST",
2757
+ path: "/graphql",
2758
+ body: {
2759
+ ...PULL_REQUEST_CHECKS,
2760
+ variables: { name: repo.name, number: number33, owner: repo.owner }
2761
+ }
2762
+ });
2763
+ if (!response.ok) {
2764
+ throw new Error(
2765
+ `GitHub pull request checks lookup failed with HTTP ${response.status}`
2766
+ );
2767
+ }
2768
+ const pullRequest = checksResponseSchema.parse(response.body).data.repository.pullRequest;
2769
+ const rollup = pullRequest.commits.nodes[0]?.commit.statusCheckRollup;
2770
+ const checks = { failing: [], pending: [], passing: [] };
2771
+ for (const context of rollup?.contexts.nodes ?? []) {
2772
+ if (!context.isRequired) continue;
2773
+ checks[contextState(context)].push(
2774
+ context.__typename === "CheckRun" ? context.name : context.context
2775
+ );
2776
+ }
2777
+ return {
2778
+ required: checks.failing.length > 0 ? "failing" : checks.pending.length > 0 ? "pending" : checks.passing.length > 0 ? "passing" : "not_reported",
2779
+ ...checks,
2780
+ ...rollup?.contexts.pageInfo.hasNextPage ? { incomplete: true } : void 0,
2781
+ merge_state: pullRequest.mergeStateStatus,
2782
+ review_decision: pullRequest.reviewDecision,
2783
+ auto_merge: pullRequest.autoMergeRequest !== null
2784
+ };
2785
+ }
2274
2786
  function createGitHubGetPullRequestTool(ctx) {
2275
2787
  return definePluginTool9({
2276
2788
  annotations: {
@@ -2279,7 +2791,7 @@ function createGitHubGetPullRequestTool(ctx) {
2279
2791
  openWorldHint: true,
2280
2792
  readOnlyHint: true
2281
2793
  },
2282
- description: "Get a GitHub pull request. Use this when an existing PR may need event monitoring; the result includes a subscribable hint when GitHub webhooks are configured.",
2794
+ 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.",
2283
2795
  inputSchema: inputSchema7,
2284
2796
  outputSchema: outputSchema7,
2285
2797
  async execute(input) {
@@ -2291,20 +2803,25 @@ function createGitHubGetPullRequestTool(ctx) {
2291
2803
  if (!response.ok) {
2292
2804
  const message = `GitHub pull request lookup failed with HTTP ${response.status}`;
2293
2805
  if (response.status === 404) {
2294
- throw new PluginToolInputError11(message);
2806
+ throw new PluginToolInputError12(message);
2295
2807
  }
2296
2808
  throw new Error(message);
2297
2809
  }
2298
- const providerResult = z13.object({
2299
- base: z13.object({ ref: z13.string() }),
2300
- draft: z13.boolean(),
2301
- head: z13.object({ ref: z13.string(), sha: commitShaSchema2 }),
2302
- html_url: z13.string(),
2303
- merged: z13.boolean().optional().default(false),
2304
- number: z13.number(),
2305
- state: z13.string(),
2306
- title: z13.string()
2810
+ const providerResult = z14.object({
2811
+ base: z14.object({ ref: z14.string() }),
2812
+ draft: z14.boolean(),
2813
+ head: z14.object({ ref: z14.string(), sha: commitShaSchema2 }),
2814
+ html_url: z14.string(),
2815
+ merged: z14.boolean().optional().default(false),
2816
+ number: z14.number(),
2817
+ state: z14.string(),
2818
+ title: z14.string()
2307
2819
  }).parse(response.body);
2820
+ const checks = await readPullRequestChecks(
2821
+ ctx.egress,
2822
+ repo,
2823
+ providerResult.number
2824
+ );
2308
2825
  const subscribable = gitHubPullRequestSubscribable({
2309
2826
  canSubscribe: ctx.events.canSubscribe,
2310
2827
  number: providerResult.number,
@@ -2312,6 +2829,7 @@ function createGitHubGetPullRequestTool(ctx) {
2312
2829
  });
2313
2830
  const data = {
2314
2831
  base: providerResult.base.ref,
2832
+ checks,
2315
2833
  draft: providerResult.draft,
2316
2834
  head: providerResult.head.ref,
2317
2835
  head_sha: providerResult.head.sha.toLowerCase(),
@@ -2347,45 +2865,45 @@ import {
2347
2865
  pluginToolOutputSchema as pluginToolOutputSchema10,
2348
2866
  subscribableResourceSchema as subscribableResourceSchema6
2349
2867
  } from "@sentry/junior-plugin-api";
2350
- import * as z14 from "zod";
2351
- var inputSchema8 = z14.object({
2352
- repo: z14.string().describe('Repository in "owner/name" format.'),
2353
- tag: z14.string().trim().min(1).describe(
2868
+ import * as z15 from "zod";
2869
+ var inputSchema8 = z15.object({
2870
+ repo: z15.string().describe('Repository in "owner/name" format.'),
2871
+ tag: z15.string().trim().min(1).describe(
2354
2872
  "Optional release tag name. Omit to inspect and watch every published release in the repository."
2355
2873
  ).optional()
2356
2874
  }).strict();
2357
- var releaseSchema = z14.object({
2358
- created_at: z14.string(),
2359
- draft: z14.boolean(),
2360
- html_url: z14.string(),
2361
- id: z14.number(),
2362
- name: z14.string().nullable(),
2363
- prerelease: z14.boolean(),
2364
- published_at: z14.string().nullable(),
2365
- tag_name: z14.string(),
2366
- target_commitish: z14.string()
2875
+ var releaseSchema = z15.object({
2876
+ created_at: z15.string(),
2877
+ draft: z15.boolean(),
2878
+ html_url: z15.string(),
2879
+ id: z15.number(),
2880
+ name: z15.string().nullable(),
2881
+ prerelease: z15.boolean(),
2882
+ published_at: z15.string().nullable(),
2883
+ tag_name: z15.string(),
2884
+ target_commitish: z15.string()
2367
2885
  }).strict();
2368
- var releaseSourceSchema = z14.object({
2886
+ var releaseSourceSchema = z15.object({
2369
2887
  release: releaseSchema.nullable(),
2370
- repo: z14.string(),
2888
+ repo: z15.string(),
2371
2889
  subscribable: subscribableResourceSchema6.optional(),
2372
- tag: z14.string().nullable()
2890
+ tag: z15.string().nullable()
2373
2891
  }).strict();
2374
2892
  var outputSchema8 = pluginToolOutputSchema10.merge(
2375
2893
  releaseSourceSchema.extend({
2376
- target: z14.literal("getRelease")
2894
+ target: z15.literal("getRelease")
2377
2895
  })
2378
2896
  );
2379
- var providerReleaseSchema = z14.object({
2380
- created_at: z14.string(),
2381
- draft: z14.boolean(),
2382
- html_url: z14.string(),
2383
- id: z14.number(),
2384
- name: z14.string().nullable(),
2385
- prerelease: z14.boolean(),
2386
- published_at: z14.string().nullable(),
2387
- tag_name: z14.string(),
2388
- target_commitish: z14.string()
2897
+ var providerReleaseSchema = z15.object({
2898
+ created_at: z15.string(),
2899
+ draft: z15.boolean(),
2900
+ html_url: z15.string(),
2901
+ id: z15.number(),
2902
+ name: z15.string().nullable(),
2903
+ prerelease: z15.boolean(),
2904
+ published_at: z15.string().nullable(),
2905
+ tag_name: z15.string(),
2906
+ target_commitish: z15.string()
2389
2907
  }).passthrough();
2390
2908
  function mapRelease(providerRelease) {
2391
2909
  return {
@@ -2464,25 +2982,25 @@ function createGitHubGetReleaseTool(ctx) {
2464
2982
  // src/tools/get-repository.ts
2465
2983
  import {
2466
2984
  definePluginTool as definePluginTool11,
2467
- PluginToolInputError as PluginToolInputError12,
2985
+ PluginToolInputError as PluginToolInputError13,
2468
2986
  pluginToolOutputSchema as pluginToolOutputSchema11,
2469
2987
  subscribableResourceSchema as subscribableResourceSchema7
2470
2988
  } from "@sentry/junior-plugin-api";
2471
- import * as z15 from "zod";
2472
- var inputSchema9 = z15.object({
2473
- repo: z15.string().describe('Repository in "owner/name" format.')
2989
+ import * as z16 from "zod";
2990
+ var inputSchema9 = z16.object({
2991
+ repo: z16.string().describe('Repository in "owner/name" format.')
2474
2992
  }).strict();
2475
- var repositorySchema = z15.object({
2476
- default_branch: z15.string(),
2477
- description: z15.string().nullable(),
2478
- full_name: z15.string(),
2479
- private: z15.boolean(),
2993
+ var repositorySchema = z16.object({
2994
+ default_branch: z16.string(),
2995
+ description: z16.string().nullable(),
2996
+ full_name: z16.string(),
2997
+ private: z16.boolean(),
2480
2998
  subscribable: subscribableResourceSchema7.optional(),
2481
- url: z15.string()
2999
+ url: z16.string()
2482
3000
  });
2483
3001
  var outputSchema9 = pluginToolOutputSchema11.merge(
2484
3002
  repositorySchema.extend({
2485
- target: z15.literal("getRepository")
3003
+ target: z16.literal("getRepository")
2486
3004
  })
2487
3005
  );
2488
3006
  function createGitHubGetRepositoryTool(ctx) {
@@ -2503,16 +3021,16 @@ function createGitHubGetRepositoryTool(ctx) {
2503
3021
  path: repoPath(repo)
2504
3022
  });
2505
3023
  if (!response.ok) {
2506
- throw new PluginToolInputError12(
3024
+ throw new PluginToolInputError13(
2507
3025
  `GitHub repository lookup failed with HTTP ${response.status}`
2508
3026
  );
2509
3027
  }
2510
- const providerResult = z15.object({
2511
- default_branch: z15.string(),
2512
- description: z15.string().nullable(),
2513
- full_name: z15.string(),
2514
- html_url: z15.string(),
2515
- private: z15.boolean()
3028
+ const providerResult = z16.object({
3029
+ default_branch: z16.string(),
3030
+ description: z16.string().nullable(),
3031
+ full_name: z16.string(),
3032
+ html_url: z16.string(),
3033
+ private: z16.boolean()
2516
3034
  }).parse(response.body);
2517
3035
  const subscribable = gitHubRepositorySubscribable({
2518
3036
  canSubscribe: ctx.events.canSubscribe,
@@ -2539,24 +3057,24 @@ import {
2539
3057
  definePluginTool as definePluginTool12,
2540
3058
  pluginToolOutputSchema as pluginToolOutputSchema12
2541
3059
  } from "@sentry/junior-plugin-api";
2542
- import * as z17 from "zod";
3060
+ import * as z18 from "zod";
2543
3061
 
2544
3062
  // src/github-status.ts
2545
- import * as z16 from "zod";
3063
+ import * as z17 from "zod";
2546
3064
  var GITHUB_STATUS_INCIDENTS_URL = "https://www.githubstatus.com/api/v2/incidents.json";
2547
3065
  var GITHUB_STATUS_TTL_MS = 60 * 1e3;
2548
3066
  var GITHUB_STATUS_TIMEOUT_MS = 5e3;
2549
- var incidentsResponseSchema = z16.object({
2550
- incidents: z16.array(
2551
- z16.object({
2552
- components: z16.array(z16.object({ name: z16.string() })).default([]),
2553
- created_at: z16.string(),
2554
- impact: z16.string(),
2555
- name: z16.string(),
2556
- resolved_at: z16.string().nullable(),
2557
- shortlink: z16.string(),
2558
- started_at: z16.string().nullable().optional(),
2559
- status: z16.string()
3067
+ var incidentsResponseSchema = z17.object({
3068
+ incidents: z17.array(
3069
+ z17.object({
3070
+ components: z17.array(z17.object({ name: z17.string() })).default([]),
3071
+ created_at: z17.string(),
3072
+ impact: z17.string(),
3073
+ name: z17.string(),
3074
+ resolved_at: z17.string().nullable(),
3075
+ shortlink: z17.string(),
3076
+ started_at: z17.string().nullable().optional(),
3077
+ status: z17.string()
2560
3078
  })
2561
3079
  )
2562
3080
  });
@@ -2598,19 +3116,19 @@ async function loadGitHubStatusIncidents(cache, withinMs) {
2598
3116
 
2599
3117
  // src/tools/get-status.ts
2600
3118
  var RECENT_INCIDENT_MS = 24 * 60 * 60 * 1e3;
2601
- var inputSchema10 = z17.object({}).strict();
2602
- var incidentSchema = z17.object({
2603
- components: z17.array(z17.string()),
2604
- impact: z17.string(),
2605
- name: z17.string(),
2606
- resolved_at: z17.string().optional(),
2607
- started_at: z17.string(),
2608
- status: z17.string(),
2609
- url: z17.string()
3119
+ var inputSchema10 = z18.object({}).strict();
3120
+ var incidentSchema = z18.object({
3121
+ components: z18.array(z18.string()),
3122
+ impact: z18.string(),
3123
+ name: z18.string(),
3124
+ resolved_at: z18.string().optional(),
3125
+ started_at: z18.string(),
3126
+ status: z18.string(),
3127
+ url: z18.string()
2610
3128
  });
2611
3129
  var outputSchema10 = pluginToolOutputSchema12.extend({
2612
- target: z17.literal("getStatus"),
2613
- incidents: z17.array(incidentSchema)
3130
+ target: z18.literal("getStatus"),
3131
+ incidents: z18.array(incidentSchema)
2614
3132
  });
2615
3133
  function createGitHubGetStatusTool(ctx) {
2616
3134
  return definePluginTool12({
@@ -2646,50 +3164,50 @@ function createGitHubGetStatusTool(ctx) {
2646
3164
  // src/tools/update-issue.ts
2647
3165
  import {
2648
3166
  definePluginTool as definePluginTool13,
2649
- PluginToolInputError as PluginToolInputError13,
3167
+ PluginToolInputError as PluginToolInputError14,
2650
3168
  pluginToolOutputSchema as pluginToolOutputSchema13,
2651
3169
  subscribableResourceSchema as subscribableResourceSchema8
2652
3170
  } from "@sentry/junior-plugin-api";
2653
- import * as z18 from "zod";
2654
- var inputSchema11 = z18.object({
2655
- repo: z18.string().describe('Repository in "owner/name" format.'),
2656
- number: z18.number().int().positive().describe("Issue number."),
2657
- title: z18.string().trim().min(1).optional().describe("Replacement issue title."),
2658
- body: z18.string().optional().describe(
3171
+ import * as z19 from "zod";
3172
+ var inputSchema11 = z19.object({
3173
+ repo: z19.string().describe('Repository in "owner/name" format.'),
3174
+ number: z19.number().int().positive().describe("Issue number."),
3175
+ title: z19.string().trim().min(1).optional().describe("Replacement issue title."),
3176
+ body: z19.string().optional().describe(
2659
3177
  "Replacement issue body. The runtime appends requester attribution and the conversation footer."
2660
3178
  ),
2661
- state: z18.enum(["open", "closed"]).optional().describe("Replacement issue state."),
2662
- assign_requester: z18.boolean().optional().describe(
3179
+ state: z19.enum(["open", "closed"]).optional().describe("Replacement issue state."),
3180
+ assign_requester: z19.boolean().optional().describe(
2663
3181
  "Set true to add the requester's linked GitHub account as an assignee. Other assignees stay."
2664
3182
  )
2665
3183
  }).strict().refine(
2666
3184
  ({ title, body, state, assign_requester }) => title !== void 0 || body !== void 0 || state !== void 0 || assign_requester === true,
2667
3185
  { message: "At least one issue field must be provided." }
2668
3186
  );
2669
- var issueSchema2 = z18.object({
2670
- assignees: z18.array(z18.string()),
2671
- body: z18.string().nullable(),
2672
- number: z18.number(),
2673
- state: z18.string(),
3187
+ var issueSchema2 = z19.object({
3188
+ assignees: z19.array(z19.string()),
3189
+ body: z19.string().nullable(),
3190
+ number: z19.number(),
3191
+ state: z19.string(),
2674
3192
  subscribable: subscribableResourceSchema8.optional(),
2675
- title: z18.string(),
2676
- url: z18.string()
3193
+ title: z19.string(),
3194
+ url: z19.string()
2677
3195
  });
2678
3196
  var outputSchema11 = pluginToolOutputSchema13.merge(
2679
3197
  issueSchema2.extend({
2680
- target: z18.literal("updateIssue")
3198
+ target: z19.literal("updateIssue")
2681
3199
  })
2682
3200
  );
2683
- var providerIssueSchema2 = z18.object({
2684
- assignees: z18.array(z18.object({ login: z18.string() })).nullish().transform((assignees) => assignees?.map(({ login: login2 }) => login2) ?? []),
2685
- body: z18.string().nullable().optional().default(null),
2686
- html_url: z18.string(),
2687
- number: z18.number(),
2688
- state: z18.string(),
2689
- title: z18.string()
3201
+ var providerIssueSchema2 = z19.object({
3202
+ assignees: z19.array(z19.object({ login: z19.string() })).nullish().transform((assignees) => assignees?.map(({ login: login2 }) => login2) ?? []),
3203
+ body: z19.string().nullable().optional().default(null),
3204
+ html_url: z19.string(),
3205
+ number: z19.number(),
3206
+ state: z19.string(),
3207
+ title: z19.string()
2690
3208
  });
2691
3209
  function nonEmptyString4(value, name) {
2692
- if (!value?.trim()) throw new PluginToolInputError13(`${name} is required`);
3210
+ if (!value?.trim()) throw new PluginToolInputError14(`${name} is required`);
2693
3211
  return value.trim();
2694
3212
  }
2695
3213
  function createGitHubUpdateIssueTool(ctx) {
@@ -2706,7 +3224,7 @@ function createGitHubUpdateIssueTool(ctx) {
2706
3224
  async execute(input) {
2707
3225
  const parsedInput = inputSchema11.safeParse(input);
2708
3226
  if (!parsedInput.success) {
2709
- throw new PluginToolInputError13("Invalid GitHub updateIssue input.", {
3227
+ throw new PluginToolInputError14("Invalid GitHub updateIssue input.", {
2710
3228
  cause: parsedInput.error
2711
3229
  });
2712
3230
  }
@@ -2715,7 +3233,7 @@ function createGitHubUpdateIssueTool(ctx) {
2715
3233
  const requester = update.body !== void 0 || update.assign_requester ? await resolveGitHubRequester(ctx) : void 0;
2716
3234
  const assignee = update.assign_requester ? linkedGitHubLogin(requester?.user) : void 0;
2717
3235
  if (update.assign_requester && !assignee) {
2718
- throw new PluginToolInputError13(
3236
+ throw new PluginToolInputError14(
2719
3237
  "The requester has no linked GitHub account, so Junior cannot assign the issue to them."
2720
3238
  );
2721
3239
  }
@@ -2765,7 +3283,7 @@ function createGitHubUpdateIssueTool(ctx) {
2765
3283
  if (!response.ok) {
2766
3284
  const message = `GitHub issue assignment failed with HTTP ${response.status}: ${githubErrorMessage(parsed)}`;
2767
3285
  if (response.status === 404 || response.status === 422) {
2768
- throw new PluginToolInputError13(message);
3286
+ throw new PluginToolInputError14(message);
2769
3287
  }
2770
3288
  throw new Error(message);
2771
3289
  }
@@ -2774,7 +3292,7 @@ function createGitHubUpdateIssueTool(ctx) {
2774
3292
  if (assignee && !providerResult.assignees.some(
2775
3293
  (login2) => login2.toLowerCase() === assignee.toLowerCase()
2776
3294
  )) {
2777
- throw new PluginToolInputError13(
3295
+ throw new PluginToolInputError14(
2778
3296
  `GitHub did not assign @${assignee} to the issue. They may not have access to ${repo.ref}.`
2779
3297
  );
2780
3298
  }
@@ -2811,20 +3329,20 @@ function createGitHubUpdateIssueTool(ctx) {
2811
3329
  // src/tools/update-issue-comment.ts
2812
3330
  import {
2813
3331
  definePluginTool as definePluginTool14,
2814
- PluginToolInputError as PluginToolInputError14,
3332
+ PluginToolInputError as PluginToolInputError15,
2815
3333
  pluginToolOutputSchema as pluginToolOutputSchema14
2816
3334
  } from "@sentry/junior-plugin-api";
2817
- import * as z19 from "zod";
2818
- var inputSchema12 = z19.object({
2819
- repo: z19.string().describe('Repository in "owner/name" format.'),
2820
- comment_id: z19.number().int().positive().describe("Issue comment id, as returned by github_commentOnIssue."),
2821
- body: z19.string().trim().min(1).describe("Replacement comment text.")
3335
+ import * as z20 from "zod";
3336
+ var inputSchema12 = z20.object({
3337
+ repo: z20.string().describe('Repository in "owner/name" format.'),
3338
+ comment_id: z20.number().int().positive().describe("Issue comment id, as returned by github_commentOnIssue."),
3339
+ body: z20.string().trim().min(1).describe("Replacement comment text.")
2822
3340
  }).strict();
2823
3341
  var outputSchema12 = pluginToolOutputSchema14.extend({
2824
- target: z19.literal("updateIssueComment"),
2825
- repo: z19.string(),
2826
- comment_id: z19.number(),
2827
- url: z19.string()
3342
+ target: z20.literal("updateIssueComment"),
3343
+ repo: z20.string(),
3344
+ comment_id: z20.number(),
3345
+ url: z20.string()
2828
3346
  });
2829
3347
  function createGitHubUpdateIssueCommentTool(egress, botEmail) {
2830
3348
  return definePluginTool14({
@@ -2850,12 +3368,12 @@ function createGitHubUpdateIssueCommentTool(egress, botEmail) {
2850
3368
  });
2851
3369
  if (!lookup.ok) {
2852
3370
  const message = `GitHub issue comment lookup failed with HTTP ${lookup.status}: ${githubErrorMessage(lookup.body)}`;
2853
- if (lookup.status === 404) throw new PluginToolInputError14(message);
3371
+ if (lookup.status === 404) throw new PluginToolInputError15(message);
2854
3372
  throw new Error(message);
2855
3373
  }
2856
- const author = z19.object({ user: z19.object({ id: z19.number() }).nullable() }).safeParse(lookup.body);
3374
+ const author = z20.object({ user: z20.object({ id: z20.number() }).nullable() }).safeParse(lookup.body);
2857
3375
  if (!author.success || author.data.user?.id !== botUserId) {
2858
- throw new PluginToolInputError14(
3376
+ throw new PluginToolInputError15(
2859
3377
  "This bot can only edit issue comments it posted."
2860
3378
  );
2861
3379
  }
@@ -2868,11 +3386,11 @@ function createGitHubUpdateIssueCommentTool(egress, botEmail) {
2868
3386
  if (!response.ok) {
2869
3387
  const message = `GitHub issue comment update failed with HTTP ${response.status}: ${githubErrorMessage(response.body)}`;
2870
3388
  if (response.status === 404 || response.status === 422) {
2871
- throw new PluginToolInputError14(message);
3389
+ throw new PluginToolInputError15(message);
2872
3390
  }
2873
3391
  throw new Error(message);
2874
3392
  }
2875
- const comment = z19.object({ id: z19.number(), html_url: z19.string() }).parse(response.body);
3393
+ const comment = z20.object({ id: z20.number(), html_url: z20.string() }).parse(response.body);
2876
3394
  return {
2877
3395
  target: "updateIssueComment",
2878
3396
  repo: repo.ref,
@@ -2886,70 +3404,61 @@ function createGitHubUpdateIssueCommentTool(egress, botEmail) {
2886
3404
  // src/tools/update-pull-request.ts
2887
3405
  import {
2888
3406
  definePluginTool as definePluginTool15,
2889
- PluginToolInputError as PluginToolInputError15,
3407
+ PluginToolInputError as PluginToolInputError16,
2890
3408
  pluginToolOutputSchema as pluginToolOutputSchema15
2891
3409
  } from "@sentry/junior-plugin-api";
2892
- import * as z20 from "zod";
3410
+ import * as z21 from "zod";
2893
3411
  import { subscribableResourceSchema as subscribableResourceSchema9 } from "@sentry/junior-plugin-api";
2894
- var inputSchema13 = z20.object({
2895
- repo: z20.string().describe('Repository in "owner/name" format.'),
2896
- number: z20.number().int().positive().describe("Pull request number."),
2897
- title: z20.string().trim().min(1).optional().describe("Replacement pull request title."),
2898
- body: z20.string().optional().describe(
3412
+ var inputSchema13 = z21.object({
3413
+ repo: z21.string().describe('Repository in "owner/name" format.'),
3414
+ number: z21.number().int().positive().describe("Pull request number."),
3415
+ title: z21.string().trim().min(1).optional().describe("Replacement pull request title."),
3416
+ body: z21.string().optional().describe(
2899
3417
  "Replacement pull request body. The runtime appends requester attribution and the conversation footer."
2900
3418
  ),
2901
- base: z20.string().trim().min(1).optional().describe("Replacement base branch."),
2902
- state: z20.enum(["open", "closed"]).optional().describe("Replacement pull request state."),
2903
- draft: z20.boolean().optional().describe(
3419
+ base: z21.string().trim().min(1).optional().describe("Replacement base branch."),
3420
+ state: z21.enum(["open", "closed"]).optional().describe("Replacement pull request state."),
3421
+ draft: z21.boolean().optional().describe(
2904
3422
  "Set false to mark a draft pull request ready for review, or true to convert it back to a draft."
2905
3423
  )
2906
3424
  }).strict().refine(
2907
3425
  ({ title, body, base, state, draft }) => title !== void 0 || body !== void 0 || base !== void 0 || state !== void 0 || draft !== void 0,
2908
3426
  { message: "At least one pull request field must be provided." }
2909
3427
  );
2910
- var MARK_READY_FOR_REVIEW = {
2911
- operationName: "MarkPullRequestReadyForReview",
2912
- query: "mutation MarkPullRequestReadyForReview($id: ID!) { result: markPullRequestReadyForReview(input: {pullRequestId: $id}) { pullRequest { isDraft } } }"
2913
- };
2914
- var CONVERT_TO_DRAFT = {
2915
- operationName: "ConvertPullRequestToDraft",
2916
- query: "mutation ConvertPullRequestToDraft($id: ID!) { result: convertPullRequestToDraft(input: {pullRequestId: $id}) { pullRequest { isDraft } } }"
2917
- };
2918
- var draftMutationResponseSchema = z20.object({
2919
- data: z20.object({
2920
- result: z20.object({ pullRequest: z20.object({ isDraft: z20.boolean() }) })
3428
+ var draftMutationResponseSchema = z21.object({
3429
+ data: z21.object({
3430
+ result: z21.object({ pullRequest: z21.object({ isDraft: z21.boolean() }) })
2921
3431
  })
2922
3432
  });
2923
- var pullRequestSchema2 = z20.object({
2924
- base: z20.string(),
2925
- body: z20.string().nullable(),
2926
- draft: z20.boolean(),
2927
- number: z20.number(),
2928
- state: z20.string(),
3433
+ var pullRequestSchema2 = z21.object({
3434
+ base: z21.string(),
3435
+ body: z21.string().nullable(),
3436
+ draft: z21.boolean(),
3437
+ number: z21.number(),
3438
+ state: z21.string(),
2929
3439
  subscribable: subscribableResourceSchema9.optional(),
2930
- title: z20.string(),
2931
- url: z20.string()
3440
+ title: z21.string(),
3441
+ url: z21.string()
2932
3442
  });
2933
3443
  var outputSchema13 = pluginToolOutputSchema15.merge(
2934
3444
  pullRequestSchema2.extend({
2935
- target: z20.literal("updatePullRequest")
3445
+ target: z21.literal("updatePullRequest")
2936
3446
  })
2937
3447
  );
2938
3448
  function nonEmptyString5(value, name) {
2939
3449
  if (!value?.trim()) {
2940
- throw new PluginToolInputError15(`${name} is required`);
3450
+ throw new PluginToolInputError16(`${name} is required`);
2941
3451
  }
2942
3452
  return value.trim();
2943
3453
  }
2944
3454
  async function setPullRequestDraft(input) {
2945
- const mutation = input.draft ? CONVERT_TO_DRAFT : MARK_READY_FOR_REVIEW;
3455
+ const mutation = input.draft ? CONVERT_PULL_REQUEST_TO_DRAFT : MARK_PULL_REQUEST_READY_FOR_REVIEW;
2946
3456
  const response = await githubApi(input.egress, {
2947
3457
  operation: `github.pull.draft.update:${input.repo.toLowerCase()}`,
2948
3458
  method: "POST",
2949
3459
  path: "/graphql",
2950
3460
  body: {
2951
- operationName: mutation.operationName,
2952
- query: mutation.query,
3461
+ ...mutation,
2953
3462
  variables: { id: input.nodeId }
2954
3463
  }
2955
3464
  });
@@ -2962,7 +3471,7 @@ async function setPullRequestDraft(input) {
2962
3471
  }
2963
3472
  return isDraft;
2964
3473
  }
2965
- function createGitHubUpdatePullRequestTool(ctx) {
3474
+ function createGitHubUpdatePullRequestTool(ctx, descriptionDecider) {
2966
3475
  return definePluginTool15({
2967
3476
  annotations: {
2968
3477
  destructiveHint: true,
@@ -2976,12 +3485,15 @@ function createGitHubUpdatePullRequestTool(ctx) {
2976
3485
  async execute(input) {
2977
3486
  const parsedInput = inputSchema13.safeParse(input);
2978
3487
  if (!parsedInput.success) {
2979
- throw new PluginToolInputError15(
3488
+ throw new PluginToolInputError16(
2980
3489
  "Invalid GitHub updatePullRequest input.",
2981
3490
  { cause: parsedInput.error }
2982
3491
  );
2983
3492
  }
2984
3493
  const update = parsedInput.data;
3494
+ if (descriptionDecider && update.body !== void 0) {
3495
+ await checkPullRequestDescription(descriptionDecider, update.body);
3496
+ }
2985
3497
  const repo = parseRepo(update.repo);
2986
3498
  const requester = await resolveGitHubRequester(ctx);
2987
3499
  const currentBody = update.body !== void 0 ? await readGitHubBody(ctx.egress, {
@@ -3013,20 +3525,22 @@ function createGitHubUpdatePullRequestTool(ctx) {
3013
3525
  });
3014
3526
  const parsed = response.body;
3015
3527
  if (!response.ok) {
3016
- throw new Error(
3017
- `GitHub pull request update failed with HTTP ${response.status}: ${githubErrorMessage(parsed)}`
3018
- );
3528
+ const message = `GitHub pull request update failed with HTTP ${response.status}: ${githubErrorMessage(parsed)}`;
3529
+ if (response.status === 404 || response.status === 422) {
3530
+ throw new PluginToolInputError16(message);
3531
+ }
3532
+ throw new Error(message);
3019
3533
  }
3020
- const providerResult = z20.object({
3021
- base: z20.object({ ref: z20.string() }),
3022
- body: z20.string().nullable().optional().default(null),
3023
- draft: z20.boolean(),
3024
- html_url: z20.string(),
3025
- merged: z20.boolean(),
3026
- node_id: z20.string().optional(),
3027
- number: z20.number(),
3028
- state: z20.string(),
3029
- title: z20.string()
3534
+ const providerResult = z21.object({
3535
+ base: z21.object({ ref: z21.string() }),
3536
+ body: z21.string().nullable().optional().default(null),
3537
+ draft: z21.boolean(),
3538
+ html_url: z21.string(),
3539
+ merged: z21.boolean(),
3540
+ node_id: z21.string().optional(),
3541
+ number: z21.number(),
3542
+ state: z21.string(),
3543
+ title: z21.string()
3030
3544
  }).parse(parsed);
3031
3545
  if (update.draft !== void 0 && update.draft !== providerResult.draft) {
3032
3546
  if (!providerResult.node_id) {
@@ -3088,10 +3602,10 @@ function createGitHubUpdatePullRequestTool(ctx) {
3088
3602
  // src/tools/update-pull-request-feedback.ts
3089
3603
  import {
3090
3604
  definePluginTool as definePluginTool16,
3091
- PluginToolInputError as PluginToolInputError16,
3605
+ PluginToolInputError as PluginToolInputError17,
3092
3606
  pluginToolOutputSchema as pluginToolOutputSchema16
3093
3607
  } from "@sentry/junior-plugin-api";
3094
- import * as z21 from "zod";
3608
+ import * as z22 from "zod";
3095
3609
  var STATUS_TO_REACTION_CONTENT = {
3096
3610
  reviewing: "eyes",
3097
3611
  addressed: "+1",
@@ -3111,24 +3625,24 @@ var REST_REACTION_CONTENT = new Map(
3111
3625
  rest
3112
3626
  ])
3113
3627
  );
3114
- var inputSchema14 = z21.object({
3115
- repo: z21.string().describe('Repository in "owner/name" format.'),
3116
- comment_kind: z21.enum(["conversation", "review", "review_body"]).describe(
3628
+ var inputSchema14 = z22.object({
3629
+ repo: z22.string().describe('Repository in "owner/name" format.'),
3630
+ comment_kind: z22.enum(["conversation", "review", "review_body"]).describe(
3117
3631
  'Comment kind: "conversation" for a pull request conversation comment, "review" for an inline review comment, "review_body" for the body of a submitted review.'
3118
3632
  ),
3119
- comment_id: z21.number().int().positive().describe(
3633
+ comment_id: z22.number().int().positive().describe(
3120
3634
  "GitHub comment id (conversation comment id, inline review comment id, or review id)."
3121
3635
  ),
3122
- pull_request: z21.number().int().positive().describe("Pull request number that the comment is on."),
3123
- status: z21.enum(["addressed", "declined"]).describe(
3636
+ pull_request: z22.number().int().positive().describe("Pull request number that the comment is on."),
3637
+ status: z22.enum(["addressed", "declined"]).describe(
3124
3638
  "Feedback outcome. Maps to a reaction: addressed -> +1, declined -> -1."
3125
3639
  )
3126
3640
  }).strict();
3127
3641
  var outputSchema14 = pluginToolOutputSchema16.extend({
3128
- target: z21.literal("updatePullRequestFeedback"),
3129
- repo: z21.string(),
3130
- comment_id: z21.number(),
3131
- status: z21.enum(["addressed", "declined"])
3642
+ target: z22.literal("updatePullRequestFeedback"),
3643
+ repo: z22.string(),
3644
+ comment_id: z22.number(),
3645
+ status: z22.enum(["addressed", "declined"])
3132
3646
  });
3133
3647
  function pullRequestCommentPath(input) {
3134
3648
  const segment = input.commentKind === "conversation" ? "issues" : "pulls";
@@ -3140,10 +3654,10 @@ function pullRequestCommentReactionsPath(input) {
3140
3654
  function pullRequestFeedbackReactionContent(status) {
3141
3655
  return STATUS_TO_REACTION_CONTENT[status];
3142
3656
  }
3143
- var reactionSchema = z21.object({
3144
- id: z21.number(),
3145
- content: z21.string(),
3146
- user: z21.object({ id: z21.number() }).nullable()
3657
+ var reactionSchema = z22.object({
3658
+ id: z22.number(),
3659
+ content: z22.string(),
3660
+ user: z22.object({ id: z22.number() }).nullable()
3147
3661
  });
3148
3662
  async function commentParentNumber(egress, input) {
3149
3663
  const commentResponse = await githubApi(egress, {
@@ -3153,25 +3667,25 @@ async function commentParentNumber(egress, input) {
3153
3667
  const commentPayload = commentResponse.body;
3154
3668
  if (!commentResponse.ok) {
3155
3669
  const message = `GitHub comment lookup failed with HTTP ${commentResponse.status}: ${githubErrorMessage(commentPayload)}`;
3156
- if (commentResponse.status === 404) throw new PluginToolInputError16(message);
3670
+ if (commentResponse.status === 404) throw new PluginToolInputError17(message);
3157
3671
  throw new Error(message);
3158
3672
  }
3159
- const comment = z21.object({
3160
- issue_url: z21.string().optional(),
3161
- pull_request_url: z21.string().optional()
3673
+ const comment = z22.object({
3674
+ issue_url: z22.string().optional(),
3675
+ pull_request_url: z22.string().optional()
3162
3676
  }).safeParse(commentPayload);
3163
3677
  const parentUrl = comment.success ? input.commentKind === "conversation" ? comment.data.issue_url : comment.data.pull_request_url : void 0;
3164
- const number31 = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
3165
- if (!number31) {
3678
+ const number33 = /\/(?:issues|pulls)\/(\d+)$/.exec(parentUrl ?? "")?.[1];
3679
+ if (!number33) {
3166
3680
  throw new Error("GitHub comment did not name its issue or pull request.");
3167
3681
  }
3168
- return number31;
3682
+ return number33;
3169
3683
  }
3170
3684
  async function assertBotAuthoredPullRequest(egress, input) {
3171
- const { number: number31 } = input;
3685
+ const { number: number33 } = input;
3172
3686
  const pullResponse = await githubApi(egress, {
3173
3687
  operation: "github.pull.get",
3174
- path: `${repoPath(input)}/pulls/${number31}`
3688
+ path: `${repoPath(input)}/pulls/${number33}`
3175
3689
  });
3176
3690
  const pullPayload = pullResponse.body;
3177
3691
  if (!pullResponse.ok && pullResponse.status !== 404) {
@@ -3179,9 +3693,9 @@ async function assertBotAuthoredPullRequest(egress, input) {
3179
3693
  `GitHub pull request lookup failed with HTTP ${pullResponse.status}: ${githubErrorMessage(pullPayload)}`
3180
3694
  );
3181
3695
  }
3182
- const pull = z21.object({ user: z21.object({ id: z21.number() }).nullable() }).safeParse(pullPayload);
3696
+ const pull = z22.object({ user: z22.object({ id: z22.number() }).nullable() }).safeParse(pullPayload);
3183
3697
  if (!pullResponse.ok || !pull.success || pull.data.user?.id !== input.botUserId) {
3184
- throw new PluginToolInputError16(
3698
+ throw new PluginToolInputError17(
3185
3699
  "This bot can only set feedback status on comments on pull requests it authored."
3186
3700
  );
3187
3701
  }
@@ -3192,34 +3706,14 @@ function pullRequestReviewPath(input) {
3192
3706
  function graphqlReactionContent(content) {
3193
3707
  return GRAPHQL_REACTION_CONTENT[content] ?? content;
3194
3708
  }
3195
- var ADD_REVIEW_REACTION_MUTATION = `mutation AddReviewReaction($subjectId: ID!, $content: ReactionContent!) {
3196
- addReaction(input: {subjectId: $subjectId, content: $content}) {
3197
- reaction { content }
3198
- }
3199
- }`;
3200
- var REMOVE_REVIEW_REACTION_MUTATION = `mutation RemoveReviewReaction($subjectId: ID!, $content: ReactionContent!) {
3201
- removeReaction(input: {subjectId: $subjectId, content: $content}) {
3202
- reaction { content }
3203
- }
3204
- }`;
3205
- var REVIEW_REACTIONS_QUERY = `query ReviewReactions($subjectId: ID!) {
3206
- node(id: $subjectId) {
3207
- ... on PullRequestReview {
3208
- reactionGroups {
3209
- content
3210
- reactors(first: 100) { nodes { ... on Bot { databaseId } } }
3211
- }
3212
- }
3213
- }
3214
- }`;
3215
- var reviewReactionsSchema = z21.object({
3216
- data: z21.object({
3217
- node: z21.object({
3218
- reactionGroups: z21.array(
3219
- z21.object({
3220
- content: z21.string(),
3221
- reactors: z21.object({
3222
- nodes: z21.array(z21.object({ databaseId: z21.number().optional() }))
3709
+ var reviewReactionsSchema = z22.object({
3710
+ data: z22.object({
3711
+ node: z22.object({
3712
+ reactionGroups: z22.array(
3713
+ z22.object({
3714
+ content: z22.string(),
3715
+ reactors: z22.object({
3716
+ nodes: z22.array(z22.object({ databaseId: z22.number().optional() }))
3223
3717
  })
3224
3718
  })
3225
3719
  )
@@ -3229,7 +3723,7 @@ var reviewReactionsSchema = z21.object({
3229
3723
  async function commentReactions(egress, input) {
3230
3724
  const parentNumber = await commentParentNumber(egress, input);
3231
3725
  if (parentNumber !== String(input.pullRequest)) {
3232
- throw new PluginToolInputError16(
3726
+ throw new PluginToolInputError17(
3233
3727
  `GitHub comment ${input.commentId} is not on pull request ${input.pullRequest}.`
3234
3728
  );
3235
3729
  }
@@ -3239,7 +3733,7 @@ async function commentReactions(egress, input) {
3239
3733
  operation: "github.pull.comment-reaction.list",
3240
3734
  path: `${path}?per_page=100`
3241
3735
  }),
3242
- botReactions: (body) => z21.array(reactionSchema).parse(body).filter((reaction) => reaction.user?.id === input.botUserId),
3736
+ botReactions: (body) => z22.array(reactionSchema).parse(body).filter((reaction) => reaction.user?.id === input.botUserId),
3243
3737
  remove: (reaction) => githubApi(egress, {
3244
3738
  operation: "github.pull.comment-reaction.delete",
3245
3739
  method: "DELETE",
@@ -3260,24 +3754,21 @@ async function reviewBodyReactions(egress, input) {
3260
3754
  });
3261
3755
  if (!reviewResponse.ok) {
3262
3756
  const message = `GitHub review lookup failed with HTTP ${reviewResponse.status}: ${githubErrorMessage(reviewResponse.body)}`;
3263
- if (reviewResponse.status === 404) throw new PluginToolInputError16(message);
3757
+ if (reviewResponse.status === 404) throw new PluginToolInputError17(message);
3264
3758
  throw new Error(message);
3265
3759
  }
3266
- const subjectId = z21.object({ node_id: z21.string().min(1) }).parse(reviewResponse.body).node_id;
3267
- const graphql = (operation, operationName, query, variables) => githubApi(egress, {
3268
- operation,
3760
+ const subjectId = z22.object({ node_id: z22.string().min(1) }).parse(reviewResponse.body).node_id;
3761
+ const graphql = (operation2, document, variables) => githubApi(egress, {
3762
+ operation: operation2,
3269
3763
  method: "POST",
3270
3764
  path: "/graphql",
3271
- body: { operationName, query, variables }
3765
+ body: { ...document, variables }
3272
3766
  });
3273
3767
  const update = `github.pull.review-reaction.update:${input.owner}/${input.name}`.toLowerCase();
3274
3768
  return {
3275
- list: () => graphql(
3276
- "github.pull.review-reaction.list",
3277
- "ReviewReactions",
3278
- REVIEW_REACTIONS_QUERY,
3279
- { subjectId }
3280
- ),
3769
+ list: () => graphql("github.pull.review-reaction.list", REVIEW_REACTIONS, {
3770
+ subjectId
3771
+ }),
3281
3772
  botReactions: (body) => reviewReactionsSchema.parse(body).data.node.reactionGroups.filter(
3282
3773
  (group) => group.reactors.nodes.some(
3283
3774
  (reactor) => reactor.databaseId === input.botUserId
@@ -3285,11 +3776,11 @@ async function reviewBodyReactions(egress, input) {
3285
3776
  ).map((group) => ({
3286
3777
  content: REST_REACTION_CONTENT.get(group.content) ?? group.content
3287
3778
  })),
3288
- remove: (reaction) => graphql(update, "RemoveReviewReaction", REMOVE_REVIEW_REACTION_MUTATION, {
3779
+ remove: (reaction) => graphql(update, REMOVE_REVIEW_REACTION, {
3289
3780
  subjectId,
3290
3781
  content: graphqlReactionContent(reaction.content)
3291
3782
  }),
3292
- add: (content) => graphql(update, "AddReviewReaction", ADD_REVIEW_REACTION_MUTATION, {
3783
+ add: (content) => graphql(update, ADD_REVIEW_REACTION, {
3293
3784
  subjectId,
3294
3785
  content: graphqlReactionContent(content)
3295
3786
  })
@@ -3317,7 +3808,7 @@ function createGitHubUpdatePullRequestFeedbackTool(ctx, botEmail) {
3317
3808
  async execute(input) {
3318
3809
  const parsedInput = inputSchema14.safeParse(input);
3319
3810
  if (!parsedInput.success) {
3320
- throw new PluginToolInputError16(
3811
+ throw new PluginToolInputError17(
3321
3812
  "Invalid GitHub updatePullRequestFeedback input.",
3322
3813
  { cause: parsedInput.error }
3323
3814
  );
@@ -3393,24 +3884,24 @@ function createGitHubUpdatePullRequestFeedbackTool(ctx, botEmail) {
3393
3884
  // src/tools/resolve-pull-request-review-thread.ts
3394
3885
  import {
3395
3886
  definePluginTool as definePluginTool17,
3396
- PluginToolInputError as PluginToolInputError17,
3887
+ PluginToolInputError as PluginToolInputError18,
3397
3888
  pluginToolOutputSchema as pluginToolOutputSchema17
3398
3889
  } from "@sentry/junior-plugin-api";
3399
- import * as z22 from "zod";
3400
- var inputSchema15 = z22.object({
3401
- repo: z22.string().describe(
3890
+ import * as z23 from "zod";
3891
+ var inputSchema15 = z23.object({
3892
+ repo: z23.string().describe(
3402
3893
  'Repository in "owner/name" format. Required because GraphQL has no repo path.'
3403
3894
  ),
3404
- thread_id: z22.string().trim().min(1).describe(
3895
+ thread_id: z23.string().trim().min(1).describe(
3405
3896
  "GitHub pull request review thread node ID (the `threadId` / `id` variable used by `gh api graphql` resolveReviewThread)."
3406
3897
  )
3407
3898
  }).strict();
3408
3899
  var outputSchema15 = pluginToolOutputSchema17.extend({
3409
- target: z22.literal("resolvePullRequestReviewThread"),
3410
- repo: z22.string(),
3411
- number: z22.number(),
3412
- thread_id: z22.string(),
3413
- resolved: z22.boolean()
3900
+ target: z23.literal("resolvePullRequestReviewThread"),
3901
+ repo: z23.string(),
3902
+ number: z23.number(),
3903
+ thread_id: z23.string(),
3904
+ resolved: z23.boolean()
3414
3905
  });
3415
3906
  function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3416
3907
  return definePluginTool17({
@@ -3431,7 +3922,7 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3431
3922
  async execute(input) {
3432
3923
  const parsedInput = inputSchema15.safeParse(input);
3433
3924
  if (!parsedInput.success) {
3434
- throw new PluginToolInputError17(
3925
+ throw new PluginToolInputError18(
3435
3926
  "Invalid GitHub resolvePullRequestReviewThread input.",
3436
3927
  { cause: parsedInput.error }
3437
3928
  );
@@ -3441,26 +3932,12 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3441
3932
  if (botUserId === void 0) {
3442
3933
  throw new Error("GitHub App bot identity is not configured.");
3443
3934
  }
3444
- const query = `query ReviewThreadOwnership($threadId: ID!) {
3445
- node(id: $threadId) {
3446
- ... on PullRequestReviewThread {
3447
- id
3448
- isResolved
3449
- pullRequest {
3450
- number
3451
- repository { nameWithOwner }
3452
- author { ... on Bot { databaseId } }
3453
- }
3454
- }
3455
- }
3456
- }`;
3457
3935
  const lookupResponse = await githubApi(ctx.egress, {
3458
3936
  operation: "github.pull.review-thread.get",
3459
3937
  method: "POST",
3460
3938
  path: "/graphql",
3461
3939
  body: {
3462
- operationName: "ReviewThreadOwnership",
3463
- query,
3940
+ ...REVIEW_THREAD_OWNERSHIP,
3464
3941
  variables: { threadId: parsedInput.data.thread_id }
3465
3942
  }
3466
3943
  });
@@ -3470,31 +3947,31 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3470
3947
  `GitHub review thread lookup failed with HTTP ${lookupResponse.status}: ${githubErrorMessage(lookupPayload)}`
3471
3948
  );
3472
3949
  }
3473
- const threadNodeSchema = z22.object({
3474
- id: z22.string(),
3475
- isResolved: z22.boolean(),
3476
- pullRequest: z22.object({
3477
- author: z22.object({ databaseId: z22.number().optional() }).passthrough().nullable(),
3478
- number: z22.number(),
3479
- repository: z22.object({ nameWithOwner: z22.string() }).passthrough()
3950
+ const threadNodeSchema = z23.object({
3951
+ id: z23.string(),
3952
+ isResolved: z23.boolean(),
3953
+ pullRequest: z23.object({
3954
+ author: z23.object({ databaseId: z23.number().optional() }).passthrough().nullable(),
3955
+ number: z23.number(),
3956
+ repository: z23.object({ nameWithOwner: z23.string() }).passthrough()
3480
3957
  }).passthrough()
3481
3958
  }).passthrough();
3482
- const lookupResultSchema = z22.object({
3483
- data: z22.object({
3484
- node: z22.unknown().nullable().optional()
3959
+ const lookupResultSchema = z23.object({
3960
+ data: z23.object({
3961
+ node: z23.unknown().nullable().optional()
3485
3962
  }).passthrough()
3486
3963
  }).passthrough();
3487
3964
  const lookupResult = lookupResultSchema.safeParse(lookupPayload);
3488
3965
  const rawNode = lookupResult.success ? lookupResult.data.data.node : void 0;
3489
3966
  const parsedNode = rawNode == null ? void 0 : threadNodeSchema.safeParse(rawNode);
3490
3967
  if (!parsedNode?.success) {
3491
- throw new PluginToolInputError17("GitHub review thread was not found.");
3968
+ throw new PluginToolInputError18("GitHub review thread was not found.");
3492
3969
  }
3493
3970
  const thread = parsedNode.data;
3494
3971
  const pullRequest = thread.pullRequest;
3495
3972
  const ownsPullRequest = pullRequest.repository.nameWithOwner.toLowerCase() === repo.ref.toLowerCase() && pullRequest.author?.databaseId === botUserId;
3496
3973
  if (!ownsPullRequest) {
3497
- throw new PluginToolInputError17(
3974
+ throw new PluginToolInputError18(
3498
3975
  "This bot can only resolve review threads on pull requests it authored."
3499
3976
  );
3500
3977
  }
@@ -3507,18 +3984,12 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3507
3984
  resolved: true
3508
3985
  };
3509
3986
  }
3510
- const mutation = `mutation ResolveReviewThread($threadId: ID!) {
3511
- resolveReviewThread(input: {threadId: $threadId}) {
3512
- thread { id isResolved }
3513
- }
3514
- }`;
3515
3987
  const resolveResponse = await githubApi(ctx.egress, {
3516
3988
  operation: `github.pull.review-thread.resolve:${repo.ref.toLowerCase()}`,
3517
3989
  method: "POST",
3518
3990
  path: "/graphql",
3519
3991
  body: {
3520
- operationName: "ResolveReviewThread",
3521
- query: mutation,
3992
+ ...RESOLVE_REVIEW_THREAD,
3522
3993
  variables: { threadId: thread.id }
3523
3994
  }
3524
3995
  });
@@ -3528,10 +3999,10 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3528
3999
  `GitHub review thread resolution failed with HTTP ${resolveResponse.status}: ${githubErrorMessage(resolvePayload)}`
3529
4000
  );
3530
4001
  }
3531
- const resolveResultSchema = z22.object({
3532
- data: z22.object({
3533
- resolveReviewThread: z22.object({
3534
- thread: z22.object({ id: z22.string(), isResolved: z22.boolean() }).passthrough()
4002
+ const resolveResultSchema = z23.object({
4003
+ data: z23.object({
4004
+ resolveReviewThread: z23.object({
4005
+ thread: z23.object({ id: z23.string(), isResolved: z23.boolean() }).passthrough()
3535
4006
  }).passthrough()
3536
4007
  }).passthrough()
3537
4008
  }).passthrough();
@@ -3560,40 +4031,40 @@ function createGitHubResolvePullRequestReviewThreadTool(ctx, botEmail) {
3560
4031
  // src/tools/submit-pull-request-review.ts
3561
4032
  import {
3562
4033
  definePluginTool as definePluginTool18,
3563
- PluginToolInputError as PluginToolInputError18,
4034
+ PluginToolInputError as PluginToolInputError19,
3564
4035
  pluginToolOutputSchema as pluginToolOutputSchema18
3565
4036
  } from "@sentry/junior-plugin-api";
3566
- import * as z23 from "zod";
3567
- var reviewCommentSchema = z23.object({
3568
- path: z23.string().trim().min(1).describe("File path in the pull request."),
3569
- body: z23.string().trim().min(1).describe("Inline review comment."),
3570
- line: z23.number().int().positive().describe("Line in the pull request diff."),
3571
- side: z23.enum(["LEFT", "RIGHT"]).describe("Side of the pull request diff."),
3572
- start_line: z23.number().int().positive().optional().describe("First line of a multi-line comment."),
3573
- start_side: z23.enum(["LEFT", "RIGHT"]).optional().describe("First side of a multi-line comment.")
4037
+ import * as z24 from "zod";
4038
+ var reviewCommentSchema = z24.object({
4039
+ path: z24.string().trim().min(1).describe("File path in the pull request."),
4040
+ body: z24.string().trim().min(1).describe("Inline review comment."),
4041
+ line: z24.number().int().positive().describe("Line in the pull request diff."),
4042
+ side: z24.enum(["LEFT", "RIGHT"]).describe("Side of the pull request diff."),
4043
+ start_line: z24.number().int().positive().optional().describe("First line of a multi-line comment."),
4044
+ start_side: z24.enum(["LEFT", "RIGHT"]).optional().describe("First side of a multi-line comment.")
3574
4045
  }).strict().refine(
3575
4046
  ({ start_line, start_side }) => start_line === void 0 === (start_side === void 0),
3576
4047
  { message: "start_line and start_side must be provided together." }
3577
4048
  );
3578
- var inputSchema16 = z23.object({
3579
- repo: z23.string().describe('Repository in "owner/name" format.'),
3580
- number: z23.number().int().positive().describe("Pull request number."),
3581
- event: z23.enum(["COMMENT", "REQUEST_CHANGES"]).describe("Review result. You cannot approve pull requests."),
3582
- body: z23.string().trim().min(1).describe("Review summary."),
3583
- comments: z23.array(reviewCommentSchema).optional().describe("Optional inline review comments.")
4049
+ var inputSchema16 = z24.object({
4050
+ repo: z24.string().describe('Repository in "owner/name" format.'),
4051
+ number: z24.number().int().positive().describe("Pull request number."),
4052
+ event: z24.enum(["COMMENT", "REQUEST_CHANGES"]).describe("Review result. You cannot approve pull requests."),
4053
+ body: z24.string().trim().min(1).describe("Review summary."),
4054
+ comments: z24.array(reviewCommentSchema).optional().describe("Optional inline review comments.")
3584
4055
  }).strict();
3585
4056
  var outputSchema16 = pluginToolOutputSchema18.extend({
3586
- target: z23.literal("submitPullRequestReview"),
3587
- repo: z23.string(),
3588
- number: z23.number(),
3589
- review_id: z23.number(),
3590
- state: z23.string(),
3591
- url: z23.string()
4057
+ target: z24.literal("submitPullRequestReview"),
4058
+ repo: z24.string(),
4059
+ number: z24.number(),
4060
+ review_id: z24.number(),
4061
+ state: z24.string(),
4062
+ url: z24.string()
3592
4063
  });
3593
4064
  function throwReviewError(status, body) {
3594
4065
  const message = `GitHub pull request review failed with HTTP ${status}: ${githubErrorMessage(body)}`;
3595
4066
  if (status === 404 || status === 422) {
3596
- throw new PluginToolInputError18(message);
4067
+ throw new PluginToolInputError19(message);
3597
4068
  }
3598
4069
  throw new Error(message);
3599
4070
  }
@@ -3631,7 +4102,7 @@ function createGitHubSubmitPullRequestReviewTool(egress) {
3631
4102
  if (!response.ok) {
3632
4103
  throwReviewError(response.status, response.body);
3633
4104
  }
3634
- const providerResult = z23.object({ id: z23.number(), html_url: z23.string(), state: z23.string() }).parse(response.body);
4105
+ const providerResult = z24.object({ id: z24.number(), html_url: z24.string(), state: z24.string() }).parse(response.body);
3635
4106
  return {
3636
4107
  target: "submitPullRequestReview",
3637
4108
  repo: repo.ref,
@@ -3646,7 +4117,8 @@ function createGitHubSubmitPullRequestReviewTool(egress) {
3646
4117
  }
3647
4118
 
3648
4119
  // src/tools.ts
3649
- function createGitHubTools(ctx, botEmail, pullRequestSubscription) {
4120
+ function createGitHubTools(ctx, botEmail, pullRequestSubscription, experimental = {}) {
4121
+ const descriptionDecider = experimental.pullRequestDescriptionChecks ? ctx.decider : void 0;
3650
4122
  return {
3651
4123
  reactToIssue: createGitHubReactToIssueTool(ctx.egress),
3652
4124
  cloneRepository: createGitHubCloneRepositoryTool(ctx),
@@ -3655,7 +4127,8 @@ function createGitHubTools(ctx, botEmail, pullRequestSubscription) {
3655
4127
  createIssue: createGitHubIssueTool(ctx),
3656
4128
  createPullRequest: createGitHubPullRequestTool(
3657
4129
  ctx,
3658
- pullRequestSubscription
4130
+ pullRequestSubscription,
4131
+ descriptionDecider
3659
4132
  ),
3660
4133
  getDeployment: createGitHubGetDeploymentTool(ctx),
3661
4134
  getIssue: createGitHubGetIssueTool(ctx),
@@ -3672,7 +4145,10 @@ function createGitHubTools(ctx, botEmail, pullRequestSubscription) {
3672
4145
  ctx.egress,
3673
4146
  botEmail
3674
4147
  ),
3675
- updatePullRequest: createGitHubUpdatePullRequestTool(ctx),
4148
+ updatePullRequest: createGitHubUpdatePullRequestTool(
4149
+ ctx,
4150
+ descriptionDecider
4151
+ ),
3676
4152
  updatePullRequestFeedback: createGitHubUpdatePullRequestFeedbackTool(
3677
4153
  ctx,
3678
4154
  botEmail
@@ -3682,26 +4158,26 @@ function createGitHubTools(ctx, botEmail, pullRequestSubscription) {
3682
4158
 
3683
4159
  // src/webhooks/handler.ts
3684
4160
  import { createHmac, timingSafeEqual } from "crypto";
3685
- import * as z37 from "zod";
4161
+ import * as z40 from "zod";
3686
4162
 
3687
4163
  // src/issue-outcomes/store.ts
3688
4164
  import { and as and2, eq as eq2, lte, sql as sql2 } from "drizzle-orm";
3689
- import * as z24 from "zod";
3690
- var githubIssueOutcomeInputSchema = z24.object({
3691
- candidateOwned: z24.boolean(),
3692
- closedAt: z24.date().optional(),
3693
- issueId: z24.string().min(1),
3694
- number: z24.number().int().positive(),
3695
- openedAt: z24.date(),
3696
- repositoryFullName: z24.string().min(1),
3697
- repositoryId: z24.string().min(1),
4165
+ import * as z25 from "zod";
4166
+ var githubIssueOutcomeInputSchema = z25.object({
4167
+ candidateOwned: z25.boolean(),
4168
+ closedAt: z25.date().optional(),
4169
+ issueId: z25.string().min(1),
4170
+ number: z25.number().int().positive(),
4171
+ openedAt: z25.date(),
4172
+ repositoryFullName: z25.string().min(1),
4173
+ repositoryId: z25.string().min(1),
3698
4174
  state: githubIssueStateSchema,
3699
4175
  stateReason: githubIssueStateReasonSchema.optional(),
3700
- updatedAt: z24.date()
4176
+ updatedAt: z25.date()
3701
4177
  }).strict();
3702
- var githubIssueConversationsInputSchema = z24.object({
3703
- conversationIds: z24.array(z24.string().min(1)).min(1),
3704
- issueId: z24.string().min(1)
4178
+ var githubIssueConversationsInputSchema = z25.object({
4179
+ conversationIds: z25.array(z25.string().min(1)).min(1),
4180
+ issueId: z25.string().min(1)
3705
4181
  }).strict();
3706
4182
  function projectionValues(input) {
3707
4183
  return {
@@ -3765,38 +4241,41 @@ async function recordGitHubIssueConversations(db, input) {
3765
4241
 
3766
4242
  // src/pull-request-outcomes/store.ts
3767
4243
  import { and as and3, eq as eq3, lt as lt2, lte as lte2, ne, sql as sql3 } from "drizzle-orm";
3768
- import * as z25 from "zod";
3769
- var githubPullRequestOutcomeInputSchema = z25.object({
3770
- candidateOwned: z25.boolean(),
3771
- closedAt: z25.date().optional(),
4244
+ import * as z26 from "zod";
4245
+ var githubPullRequestOutcomeInputSchema = z26.object({
4246
+ candidateOwned: z26.boolean(),
4247
+ closedAt: z26.date().optional(),
3772
4248
  commitComposition: githubPullRequestCommitCompositionSchema.optional(),
3773
- mergedAt: z25.date().optional(),
3774
- number: z25.number().int().positive(),
3775
- openedAt: z25.date(),
3776
- pullRequestId: z25.string().min(1),
3777
- repositoryFullName: z25.string().min(1),
3778
- repositoryId: z25.string().min(1),
4249
+ /** When omitted, the stored draft state does not change. */
4250
+ draft: z26.boolean().optional(),
4251
+ mergedAt: z26.date().optional(),
4252
+ number: z26.number().int().positive(),
4253
+ openedAt: z26.date(),
4254
+ pullRequestId: z26.string().min(1),
4255
+ repositoryFullName: z26.string().min(1),
4256
+ repositoryId: z26.string().min(1),
3779
4257
  state: githubPullRequestStateSchema,
3780
- title: z25.string().min(1).optional(),
3781
- updatedAt: z25.date()
4258
+ title: z26.string().min(1).optional(),
4259
+ updatedAt: z26.date()
3782
4260
  }).strict();
3783
- var githubPullRequestConversationsInputSchema = z25.object({
3784
- conversationIds: z25.array(z25.string().min(1)).min(1),
3785
- pullRequestId: z25.string().min(1)
4261
+ var githubPullRequestConversationsInputSchema = z26.object({
4262
+ conversationIds: z26.array(z26.string().min(1)).min(1),
4263
+ pullRequestId: z26.string().min(1)
3786
4264
  }).strict();
3787
- var githubPullRequestLinkedIssuesInputSchema = z25.object({
3788
- linkedIssues: z25.array(
3789
- z25.object({
3790
- number: z25.number().int().positive(),
3791
- repositoryFullName: z25.string().min(1)
4265
+ var githubPullRequestLinkedIssuesInputSchema = z26.object({
4266
+ linkedIssues: z26.array(
4267
+ z26.object({
4268
+ number: z26.number().int().positive(),
4269
+ repositoryFullName: z26.string().min(1)
3792
4270
  }).strict()
3793
4271
  ).min(1),
3794
- pullRequestId: z25.string().min(1)
4272
+ pullRequestId: z26.string().min(1)
3795
4273
  }).strict();
3796
4274
  function projectionValues2(input) {
3797
4275
  return {
3798
4276
  closedAt: input.closedAt ?? null,
3799
4277
  ...input.commitComposition ? { commitComposition: input.commitComposition } : void 0,
4278
+ ...input.draft !== void 0 ? { draft: input.draft } : void 0,
3800
4279
  mergedAt: input.mergedAt ?? null,
3801
4280
  number: input.number,
3802
4281
  openedAt: input.openedAt,
@@ -3903,7 +4382,12 @@ async function listGitHubFinishedWork(db, conversationIds) {
3903
4382
  }
3904
4383
  async function listGitHubStaleOpenPullRequests(db, before) {
3905
4384
  const t = juniorGitHubPullRequests;
3906
- return await db.select({ number: t.number, repositoryFullName: t.repositoryFullName }).from(t).where(and3(eq3(t.state, "open"), lt2(t.updatedAt, before))).orderBy(t.updatedAt);
4385
+ return await db.select({
4386
+ draft: t.draft,
4387
+ number: t.number,
4388
+ repositoryFullName: t.repositoryFullName,
4389
+ repositoryId: t.repositoryId
4390
+ }).from(t).where(and3(eq3(t.state, "open"), lt2(t.updatedAt, before))).orderBy(t.updatedAt);
3907
4391
  }
3908
4392
  async function listGitHubAssignedWork(db, conversationIds) {
3909
4393
  if (conversationIds.length === 0) return [];
@@ -3916,6 +4400,10 @@ async function listGitHubAssignedWork(db, conversationIds) {
3916
4400
  );
3917
4401
  return conversationIdsForPullRequests(rows, conversationIds);
3918
4402
  }
4403
+ async function readGitHubPullRequestConversationIds(db, pullRequestId) {
4404
+ const [row] = await db.select({ conversationIds: juniorGitHubPullRequests.conversationIds }).from(juniorGitHubPullRequests).where(eq3(juniorGitHubPullRequests.pullRequestId, pullRequestId)).limit(1);
4405
+ return row?.conversationIds ?? [];
4406
+ }
3919
4407
  async function recordGitHubPullRequestConversations(db, input) {
3920
4408
  const association = githubPullRequestConversationsInputSchema.parse(input);
3921
4409
  const conversationIds = sql3.join(
@@ -4004,6 +4492,7 @@ function githubCodeChange(outcome, conversationIds) {
4004
4492
  return {
4005
4493
  closedAt: outcome.closedAt,
4006
4494
  conversationIds,
4495
+ draft: outcome.draft,
4007
4496
  mergedAt: outcome.mergedAt,
4008
4497
  number: outcome.number,
4009
4498
  openedAt: outcome.openedAt,
@@ -4043,39 +4532,39 @@ async function applyGitHubPullRequestOutcome(args) {
4043
4532
  }
4044
4533
 
4045
4534
  // src/webhooks/issue-outcome.ts
4046
- import * as z26 from "zod";
4047
- var canonicalIssueOutcomeSchema = z26.object({
4048
- action: z26.enum(["opened", "closed", "reopened"]),
4049
- issue: z26.object({
4050
- body: z26.string().nullable().optional(),
4051
- closed_at: z26.string().nullable().optional(),
4052
- created_at: z26.string(),
4053
- id: z26.number().int().positive(),
4054
- number: z26.number().int().positive(),
4535
+ import * as z27 from "zod";
4536
+ var canonicalIssueOutcomeSchema = z27.object({
4537
+ action: z27.enum(["opened", "closed", "reopened"]),
4538
+ issue: z27.object({
4539
+ body: z27.string().nullable().optional(),
4540
+ closed_at: z27.string().nullable().optional(),
4541
+ created_at: z27.string(),
4542
+ id: z27.number().int().positive(),
4543
+ number: z27.number().int().positive(),
4055
4544
  state_reason: githubIssueStateReasonSchema.nullable().optional(),
4056
- updated_at: z26.string(),
4057
- user: z26.object({ login: z26.string().min(1) }).strict()
4545
+ updated_at: z27.string(),
4546
+ user: z27.object({ login: z27.string().min(1) }).strict()
4058
4547
  }).strict(),
4059
- repository: z26.object({
4060
- full_name: z26.string().min(1),
4061
- id: z26.number().int().positive()
4548
+ repository: z27.object({
4549
+ full_name: z27.string().min(1),
4550
+ id: z27.number().int().positive()
4062
4551
  }).strict()
4063
4552
  }).strict();
4064
- var issueOutcomeSchema = z26.object({
4065
- action: z26.enum(["opened", "closed", "reopened"]),
4066
- issue: z26.object({
4067
- body: z26.string().nullable().optional(),
4068
- closed_at: z26.string().nullable().optional(),
4069
- created_at: z26.string(),
4070
- id: z26.number().int().positive(),
4071
- number: z26.number().int().positive(),
4553
+ var issueOutcomeSchema = z27.object({
4554
+ action: z27.enum(["opened", "closed", "reopened"]),
4555
+ issue: z27.object({
4556
+ body: z27.string().nullable().optional(),
4557
+ closed_at: z27.string().nullable().optional(),
4558
+ created_at: z27.string(),
4559
+ id: z27.number().int().positive(),
4560
+ number: z27.number().int().positive(),
4072
4561
  state_reason: githubIssueStateReasonSchema.nullable().optional(),
4073
- updated_at: z26.string(),
4074
- user: z26.object({ login: z26.string().min(1) }).passthrough()
4562
+ updated_at: z27.string(),
4563
+ user: z27.object({ login: z27.string().min(1) }).passthrough()
4075
4564
  }).passthrough(),
4076
- repository: z26.object({
4077
- full_name: z26.string().min(1),
4078
- id: z26.number().int().positive()
4565
+ repository: z27.object({
4566
+ full_name: z27.string().min(1),
4567
+ id: z27.number().int().positive()
4079
4568
  }).passthrough()
4080
4569
  }).passthrough().transform(
4081
4570
  (provider) => canonicalIssueOutcomeSchema.parse({
@@ -4096,7 +4585,7 @@ var issueOutcomeSchema = z26.object({
4096
4585
  }
4097
4586
  })
4098
4587
  );
4099
- var issueLifecycleActionSchema = z26.object({ action: z26.string() }).passthrough();
4588
+ var issueLifecycleActionSchema = z27.object({ action: z27.string() }).passthrough();
4100
4589
  function timestamp2(value) {
4101
4590
  if (!value) return void 0;
4102
4591
  const parsed = new Date(value);
@@ -4140,21 +4629,21 @@ function normalizeGitHubIssueOutcome(args) {
4140
4629
  updatedAt
4141
4630
  };
4142
4631
  }
4143
- var canonicalIssueConversationSchema = z26.object({
4144
- issue: z26.object({
4145
- body: z26.string().nullable().optional(),
4146
- id: z26.number().int().positive(),
4147
- user: z26.object({ login: z26.string().min(1) }).strict()
4632
+ var canonicalIssueConversationSchema = z27.object({
4633
+ issue: z27.object({
4634
+ body: z27.string().nullable().optional(),
4635
+ id: z27.number().int().positive(),
4636
+ user: z27.object({ login: z27.string().min(1) }).strict()
4148
4637
  }).strict(),
4149
- sender: z26.object({ login: z26.string().min(1) }).strict().optional()
4638
+ sender: z27.object({ login: z27.string().min(1) }).strict().optional()
4150
4639
  }).strict();
4151
- var issueConversationSchema = z26.object({
4152
- issue: z26.object({
4153
- body: z26.string().nullable().optional(),
4154
- id: z26.number().int().positive(),
4155
- user: z26.object({ login: z26.string().min(1) }).passthrough()
4640
+ var issueConversationSchema = z27.object({
4641
+ issue: z27.object({
4642
+ body: z27.string().nullable().optional(),
4643
+ id: z27.number().int().positive(),
4644
+ user: z27.object({ login: z27.string().min(1) }).passthrough()
4156
4645
  }).passthrough(),
4157
- sender: z26.object({ login: z26.string().min(1) }).passthrough().optional()
4646
+ sender: z27.object({ login: z27.string().min(1) }).passthrough().optional()
4158
4647
  }).passthrough().transform(
4159
4648
  (provider) => canonicalIssueConversationSchema.parse({
4160
4649
  issue: {
@@ -4181,43 +4670,52 @@ function normalizeGitHubIssueConversations(args) {
4181
4670
  }
4182
4671
 
4183
4672
  // src/webhooks/pull-request-outcome.ts
4184
- import * as z27 from "zod";
4185
- var canonicalPullRequestOutcomeSchema = z27.object({
4186
- action: z27.enum(["opened", "closed", "reopened"]),
4187
- pull_request: z27.object({
4188
- body: z27.string().nullable().optional(),
4189
- closed_at: z27.string().nullable().optional(),
4190
- created_at: z27.string(),
4191
- id: z27.number().int().positive(),
4192
- merged: z27.boolean(),
4193
- merged_at: z27.string().nullable().optional(),
4194
- number: z27.number().int().positive(),
4195
- title: z27.string().min(1).optional(),
4196
- updated_at: z27.string(),
4197
- user: z27.object({ login: z27.string().min(1) }).strict()
4673
+ import * as z28 from "zod";
4674
+ var pullRequestLifecycleActionsSchema = z28.enum([
4675
+ "opened",
4676
+ "closed",
4677
+ "reopened",
4678
+ "ready_for_review",
4679
+ "converted_to_draft"
4680
+ ]);
4681
+ var canonicalPullRequestOutcomeSchema = z28.object({
4682
+ action: pullRequestLifecycleActionsSchema,
4683
+ pull_request: z28.object({
4684
+ body: z28.string().nullable().optional(),
4685
+ closed_at: z28.string().nullable().optional(),
4686
+ created_at: z28.string(),
4687
+ draft: z28.boolean().optional(),
4688
+ id: z28.number().int().positive(),
4689
+ merged: z28.boolean(),
4690
+ merged_at: z28.string().nullable().optional(),
4691
+ number: z28.number().int().positive(),
4692
+ title: z28.string().min(1).optional(),
4693
+ updated_at: z28.string(),
4694
+ user: z28.object({ login: z28.string().min(1) }).strict()
4198
4695
  }).strict(),
4199
- repository: z27.object({
4200
- full_name: z27.string().min(1),
4201
- id: z27.number().int().positive()
4696
+ repository: z28.object({
4697
+ full_name: z28.string().min(1),
4698
+ id: z28.number().int().positive()
4202
4699
  }).strict()
4203
4700
  }).strict();
4204
- var pullRequestOutcomeSchema = z27.object({
4205
- action: z27.enum(["opened", "closed", "reopened"]),
4206
- pull_request: z27.object({
4207
- body: z27.string().nullable().optional(),
4208
- closed_at: z27.string().nullable().optional(),
4209
- created_at: z27.string(),
4210
- id: z27.number().int().positive(),
4211
- merged: z27.boolean(),
4212
- merged_at: z27.string().nullable().optional(),
4213
- number: z27.number().int().positive(),
4214
- title: z27.string().min(1).optional(),
4215
- updated_at: z27.string(),
4216
- user: z27.object({ login: z27.string().min(1) }).passthrough()
4701
+ var pullRequestOutcomeSchema = z28.object({
4702
+ action: pullRequestLifecycleActionsSchema,
4703
+ pull_request: z28.object({
4704
+ body: z28.string().nullable().optional(),
4705
+ closed_at: z28.string().nullable().optional(),
4706
+ created_at: z28.string(),
4707
+ draft: z28.boolean().optional(),
4708
+ id: z28.number().int().positive(),
4709
+ merged: z28.boolean(),
4710
+ merged_at: z28.string().nullable().optional(),
4711
+ number: z28.number().int().positive(),
4712
+ title: z28.string().min(1).optional(),
4713
+ updated_at: z28.string(),
4714
+ user: z28.object({ login: z28.string().min(1) }).passthrough()
4217
4715
  }).passthrough(),
4218
- repository: z27.object({
4219
- full_name: z27.string().min(1),
4220
- id: z27.number().int().positive()
4716
+ repository: z28.object({
4717
+ full_name: z28.string().min(1),
4718
+ id: z28.number().int().positive()
4221
4719
  }).passthrough()
4222
4720
  }).passthrough().transform(
4223
4721
  (provider) => canonicalPullRequestOutcomeSchema.parse({
@@ -4226,6 +4724,7 @@ var pullRequestOutcomeSchema = z27.object({
4226
4724
  body: provider.pull_request.body,
4227
4725
  closed_at: provider.pull_request.closed_at,
4228
4726
  created_at: provider.pull_request.created_at,
4727
+ draft: provider.pull_request.draft,
4229
4728
  id: provider.pull_request.id,
4230
4729
  merged: provider.pull_request.merged,
4231
4730
  merged_at: provider.pull_request.merged_at,
@@ -4240,24 +4739,24 @@ var pullRequestOutcomeSchema = z27.object({
4240
4739
  }
4241
4740
  })
4242
4741
  );
4243
- var pullRequestLifecycleActionSchema = z27.object({ action: z27.string() }).passthrough();
4244
- var canonicalPullRequestConversationSchema = z27.object({
4245
- pull_request: z27.object({
4246
- body: z27.string().nullable().optional(),
4247
- id: z27.number().int().positive(),
4248
- user: z27.object({ login: z27.string().min(1) }).strict()
4742
+ var pullRequestLifecycleActionSchema = z28.object({ action: z28.string() }).passthrough();
4743
+ var canonicalPullRequestConversationSchema = z28.object({
4744
+ pull_request: z28.object({
4745
+ body: z28.string().nullable().optional(),
4746
+ id: z28.number().int().positive(),
4747
+ user: z28.object({ login: z28.string().min(1) }).strict()
4249
4748
  }).strict(),
4250
- repository: z27.object({ full_name: z27.string().min(1) }).strict(),
4251
- sender: z27.object({ login: z27.string().min(1) }).strict()
4749
+ repository: z28.object({ full_name: z28.string().min(1) }).strict(),
4750
+ sender: z28.object({ login: z28.string().min(1) }).strict()
4252
4751
  }).strict();
4253
- var pullRequestConversationSchema = z27.object({
4254
- pull_request: z27.object({
4255
- body: z27.string().nullable().optional(),
4256
- id: z27.number().int().positive(),
4257
- user: z27.object({ login: z27.string().min(1) }).passthrough()
4752
+ var pullRequestConversationSchema = z28.object({
4753
+ pull_request: z28.object({
4754
+ body: z28.string().nullable().optional(),
4755
+ id: z28.number().int().positive(),
4756
+ user: z28.object({ login: z28.string().min(1) }).passthrough()
4258
4757
  }).passthrough(),
4259
- repository: z27.object({ full_name: z27.string().min(1) }).passthrough(),
4260
- sender: z27.object({ login: z27.string().min(1) }).passthrough()
4758
+ repository: z28.object({ full_name: z28.string().min(1) }).passthrough(),
4759
+ sender: z28.object({ login: z28.string().min(1) }).passthrough()
4261
4760
  }).passthrough().transform(
4262
4761
  (provider) => canonicalPullRequestConversationSchema.parse({
4263
4762
  pull_request: {
@@ -4276,7 +4775,7 @@ function timestamp3(value) {
4276
4775
  }
4277
4776
  function normalizeGitHubPullRequestOutcome(args) {
4278
4777
  const lifecycle = pullRequestLifecycleActionSchema.safeParse(args.body);
4279
- if (!lifecycle.success || !["opened", "closed", "reopened"].includes(lifecycle.data.action)) {
4778
+ if (!lifecycle.success || !pullRequestLifecycleActionsSchema.safeParse(lifecycle.data.action).success) {
4280
4779
  return void 0;
4281
4780
  }
4282
4781
  const parsed = pullRequestOutcomeSchema.parse(args.body);
@@ -4302,6 +4801,8 @@ function normalizeGitHubPullRequestOutcome(args) {
4302
4801
  return {
4303
4802
  candidateOwned,
4304
4803
  closedAt,
4804
+ // A close keeps the stored draft state.
4805
+ draft: closed ? void 0 : pullRequest.draft,
4305
4806
  mergedAt,
4306
4807
  number: pullRequest.number,
4307
4808
  openedAt,
@@ -4342,17 +4843,17 @@ function normalizeGitHubPullRequestLinkedIssues(args) {
4342
4843
  }
4343
4844
 
4344
4845
  // src/webhooks/pull-request-activity.ts
4345
- import * as z28 from "zod";
4346
- var timestampSchema = z28.iso.datetime({ offset: true });
4347
- var numberSchema = z28.number().int().positive();
4348
- var repositorySchema2 = z28.object({ id: numberSchema });
4349
- var senderSchema = z28.object({ type: z28.string() });
4846
+ import * as z29 from "zod";
4847
+ var timestampSchema = z29.iso.datetime({ offset: true });
4848
+ var numberSchema = z29.number().int().positive();
4849
+ var repositorySchema2 = z29.object({ id: numberSchema });
4850
+ var senderSchema = z29.object({ type: z29.string() });
4350
4851
  var activitySchemas = {
4351
- issue_comment: z28.object({
4352
- action: z28.literal("created"),
4353
- comment: z28.object({ created_at: timestampSchema }),
4852
+ issue_comment: z29.object({
4853
+ action: z29.literal("created"),
4854
+ comment: z29.object({ created_at: timestampSchema }),
4354
4855
  // Only comments on a pull request carry `issue.pull_request`.
4355
- issue: z28.object({ number: numberSchema, pull_request: z28.object({}) }),
4856
+ issue: z29.object({ number: numberSchema, pull_request: z29.object({}) }),
4356
4857
  repository: repositorySchema2,
4357
4858
  sender: senderSchema
4358
4859
  }).transform((event) => ({
@@ -4361,9 +4862,9 @@ var activitySchemas = {
4361
4862
  repositoryProviderId: String(event.repository.id),
4362
4863
  senderType: event.sender.type
4363
4864
  })),
4364
- pull_request: z28.object({
4365
- action: z28.literal("synchronize"),
4366
- pull_request: z28.object({
4865
+ pull_request: z29.object({
4866
+ action: z29.literal("synchronize"),
4867
+ pull_request: z29.object({
4367
4868
  number: numberSchema,
4368
4869
  updated_at: timestampSchema
4369
4870
  }),
@@ -4375,11 +4876,11 @@ var activitySchemas = {
4375
4876
  repositoryProviderId: String(event.repository.id),
4376
4877
  senderType: event.sender.type
4377
4878
  })),
4378
- pull_request_review: z28.object({
4379
- action: z28.literal("submitted"),
4380
- pull_request: z28.object({ number: numberSchema }),
4879
+ pull_request_review: z29.object({
4880
+ action: z29.literal("submitted"),
4881
+ pull_request: z29.object({ number: numberSchema }),
4381
4882
  repository: repositorySchema2,
4382
- review: z28.object({ submitted_at: timestampSchema }),
4883
+ review: z29.object({ submitted_at: timestampSchema }),
4383
4884
  sender: senderSchema
4384
4885
  }).transform((event) => ({
4385
4886
  at: new Date(event.review.submitted_at),
@@ -4387,10 +4888,10 @@ var activitySchemas = {
4387
4888
  repositoryProviderId: String(event.repository.id),
4388
4889
  senderType: event.sender.type
4389
4890
  })),
4390
- pull_request_review_comment: z28.object({
4391
- action: z28.literal("created"),
4392
- comment: z28.object({ created_at: timestampSchema }),
4393
- pull_request: z28.object({ number: numberSchema }),
4891
+ pull_request_review_comment: z29.object({
4892
+ action: z29.literal("created"),
4893
+ comment: z29.object({ created_at: timestampSchema }),
4894
+ pull_request: z29.object({ number: numberSchema }),
4394
4895
  repository: repositorySchema2,
4395
4896
  sender: senderSchema
4396
4897
  }).transform((event) => ({
@@ -4408,21 +4909,84 @@ function normalizeGitHubPullRequestActivity(input) {
4408
4909
  return senderType === "Bot" ? void 0 : activity;
4409
4910
  }
4410
4911
 
4912
+ // src/webhooks/pull-request-preview.ts
4913
+ import * as z30 from "zod";
4914
+ var previewWebhookSchema = z30.object({
4915
+ action: z30.enum(["opened", "edited", "synchronize", "ready_for_review"]),
4916
+ pull_request: z30.object({
4917
+ body: z30.string().nullable().optional(),
4918
+ id: z30.number().int().positive(),
4919
+ number: z30.number().int().positive(),
4920
+ updated_at: z30.iso.datetime({ offset: true })
4921
+ }),
4922
+ repository: z30.object({ full_name: z30.string().min(1) })
4923
+ });
4924
+ async function refreshGitHubPullRequestPreview(args) {
4925
+ const parsed = previewWebhookSchema.safeParse(args.body);
4926
+ if (!parsed.success) return;
4927
+ const { pull_request: pullRequest, repository: repository2 } = parsed.data;
4928
+ const conversationIds = await readGitHubPullRequestConversationIds(
4929
+ args.db,
4930
+ String(pullRequest.id)
4931
+ );
4932
+ if (conversationIds.length === 0) return;
4933
+ const key = `${repository2.full_name.toLowerCase()}#${pullRequest.number}`;
4934
+ const previewImageUrls = githubPreviewImageUrls(pullRequest.body);
4935
+ const updatedAt = Date.parse(pullRequest.updated_at);
4936
+ const results = await Promise.allSettled(
4937
+ conversationIds.map(async (conversationId) => {
4938
+ const store = args.annotations.forConversation(conversationId);
4939
+ const current = (await store.list()).find(
4940
+ (annotation2) => annotation2.key === key
4941
+ );
4942
+ if (current?.kind !== "object" || current.facts?.type !== "code_change") {
4943
+ return;
4944
+ }
4945
+ const storedAt = current.sourceUpdatedAt ? Date.parse(current.sourceUpdatedAt) : void 0;
4946
+ if (storedAt !== void 0 && storedAt > updatedAt) return;
4947
+ const {
4948
+ plugin: _plugin,
4949
+ createdAt: _createdAt,
4950
+ updatedAt: _updatedAt,
4951
+ facts: { previewImageUrls: previous, ...facts },
4952
+ ...annotation
4953
+ } = current;
4954
+ const next = withGitHubPreviewImages(facts, previewImageUrls);
4955
+ if (previous?.join("\n") === next.previewImageUrls?.join("\n") && storedAt === updatedAt) {
4956
+ return;
4957
+ }
4958
+ await store.upsert({
4959
+ ...annotation,
4960
+ facts: next,
4961
+ sourceUpdatedAt: pullRequest.updated_at
4962
+ });
4963
+ })
4964
+ );
4965
+ for (const result of results) {
4966
+ if (result.status === "fulfilled") continue;
4967
+ args.log?.error("GitHub pull request preview update failed", {
4968
+ errorType: result.reason instanceof Error ? result.reason.name : "UnknownError",
4969
+ number: pullRequest.number,
4970
+ repository: repository2.full_name
4971
+ });
4972
+ }
4973
+ }
4974
+
4411
4975
  // src/webhooks/merge-conflict.ts
4412
- import * as z29 from "zod";
4976
+ import * as z31 from "zod";
4413
4977
  var EVENT_TYPE = "pull_request.merge_conflict";
4414
4978
  var CLOSED_EVENT_TYPES = /* @__PURE__ */ new Set([
4415
4979
  "pull_request.closed_unmerged",
4416
4980
  "pull_request.merged"
4417
4981
  ]);
4418
- var pullRequestSchema3 = z29.object({
4419
- base: z29.object({ ref: z29.string().min(1) }),
4420
- number: z29.number().int().positive().optional(),
4421
- head: z29.object({ sha: z29.string().min(1) }),
4422
- html_url: z29.string().min(1).optional(),
4423
- mergeable: z29.boolean().nullable().optional(),
4424
- mergeable_state: z29.string().optional(),
4425
- state: z29.string()
4982
+ var pullRequestSchema3 = z31.object({
4983
+ base: z31.object({ ref: z31.string().min(1) }),
4984
+ number: z31.number().int().positive().optional(),
4985
+ head: z31.object({ sha: z31.string().min(1) }),
4986
+ html_url: z31.string().min(1).optional(),
4987
+ mergeable: z31.boolean().nullable().optional(),
4988
+ mergeable_state: z31.string().optional(),
4989
+ state: z31.string()
4426
4990
  });
4427
4991
  function gitHubMergeConflictEvents(input) {
4428
4992
  const { conflict } = input;
@@ -4456,7 +5020,7 @@ function pullRequestRefs(events) {
4456
5020
  return [...refs.values()];
4457
5021
  }
4458
5022
  function deliveredPullRequest(payload, ref) {
4459
- const parsed = z29.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
5023
+ const parsed = z31.object({ pull_request: pullRequestSchema3 }).safeParse(payload);
4460
5024
  const pullRequest = parsed.success ? parsed.data.pull_request : void 0;
4461
5025
  return pullRequest?.number === ref.number && typeof pullRequest.mergeable === "boolean" ? pullRequest : void 0;
4462
5026
  }
@@ -4482,28 +5046,32 @@ async function loadGitHubMergeConflictEvents(args) {
4482
5046
  })
4483
5047
  );
4484
5048
  } catch (error) {
4485
- args.log?.error("GitHub pull request merge conflict check failed", {
4486
- deliveryId: args.deliveryId,
4487
- errorType: error instanceof Error ? error.name : "UnknownError",
4488
- pullRequest: ref.number,
4489
- repository: ref.repositoryFullName
4490
- });
5049
+ logFailOpenFailure(
5050
+ args.log,
5051
+ "GitHub pull request merge conflict check failed",
5052
+ error,
5053
+ {
5054
+ deliveryId: args.deliveryId,
5055
+ pullRequest: ref.number,
5056
+ repository: ref.repositoryFullName
5057
+ }
5058
+ );
4491
5059
  }
4492
5060
  }
4493
5061
  return conflicts;
4494
5062
  }
4495
5063
 
4496
5064
  // src/merge-conflict-checks/webhooks.ts
4497
- import * as z31 from "zod";
5065
+ import * as z33 from "zod";
4498
5066
 
4499
5067
  // src/merge-conflict-checks/store.ts
4500
5068
  import { and as and4, eq as eq4 } from "drizzle-orm";
4501
- import * as z30 from "zod";
5069
+ import * as z32 from "zod";
4502
5070
  var CHECK_TTL_MS = 30 * 6e4;
4503
- var repeatSchema = z30.object({
5071
+ var repeatSchema = z32.object({
4504
5072
  /** Checks since the last push that ended with an unknown answer. */
4505
- attempts: z30.number().int().positive(),
4506
- dueAtMs: z30.number()
5073
+ attempts: z32.number().int().positive(),
5074
+ dueAtMs: z32.number()
4507
5075
  });
4508
5076
  function pushKey(repositoryFullName) {
4509
5077
  return `merge-conflict-check:push:${repositoryFullName}`;
@@ -4571,12 +5139,12 @@ async function settleGitHubConflictCheck(state, check, retryAtMs) {
4571
5139
 
4572
5140
  // src/merge-conflict-checks/webhooks.ts
4573
5141
  var CONFLICT_CHECK_DELAY_MS = 2 * 6e4;
4574
- var pushSchema = z31.object({
4575
- deleted: z31.boolean().optional(),
4576
- ref: z31.string(),
4577
- repository: z31.object({
4578
- default_branch: z31.string().min(1),
4579
- full_name: z31.string().min(1)
5142
+ var pushSchema = z33.object({
5143
+ deleted: z33.boolean().optional(),
5144
+ ref: z33.string(),
5145
+ repository: z33.object({
5146
+ default_branch: z33.string().min(1),
5147
+ full_name: z33.string().min(1)
4580
5148
  })
4581
5149
  });
4582
5150
  async function scheduleGitHubPushConflictCheck(args) {
@@ -4593,10 +5161,10 @@ async function scheduleGitHubPushConflictCheck(args) {
4593
5161
  }
4594
5162
 
4595
5163
  // src/webhooks/pull-request-ready.ts
4596
- import * as z33 from "zod";
5164
+ import * as z35 from "zod";
4597
5165
 
4598
5166
  // src/webhooks/installation-requests.ts
4599
- import * as z32 from "zod";
5167
+ import * as z34 from "zod";
4600
5168
  function splitRepository(fullName, label) {
4601
5169
  const [owner, name, ...extra] = fullName.split("/");
4602
5170
  if (!owner || !name || extra.length > 0) {
@@ -4636,28 +5204,46 @@ async function loadPullRequest(env, pullRequest) {
4636
5204
  { token: token.token }
4637
5205
  );
4638
5206
  }
5207
+ var GitHubRepositoryUnreachableError = class extends Error {
5208
+ constructor(repositoryId) {
5209
+ super(`GitHub repository ${repositoryId} is not reachable`);
5210
+ this.name = "GitHubRepositoryUnreachableError";
5211
+ }
5212
+ };
5213
+ var UNREACHABLE_REPOSITORY_MESSAGE = /does not exist or is not accessible/i;
4639
5214
  async function loadPullRequestLifecycles(env, input) {
5215
+ let token;
5216
+ try {
5217
+ token = await issueInstallationToken({
5218
+ ...env,
5219
+ permissions: { pull_requests: "read" },
5220
+ repositoryIds: [input.repositoryId]
5221
+ });
5222
+ } catch (error) {
5223
+ if (error instanceof GitHubRequestError && error.status === 422 && UNREACHABLE_REPOSITORY_MESSAGE.test(error.message)) {
5224
+ throw new GitHubRepositoryUnreachableError(input.repositoryId);
5225
+ }
5226
+ throw error;
5227
+ }
5228
+ const repository2 = z34.object({ full_name: z34.string().min(1) }).parse(
5229
+ await githubRequest(
5230
+ "https://api.github.com",
5231
+ `/repositories/${input.repositoryId}`,
5232
+ { token: token.token }
5233
+ )
5234
+ );
4640
5235
  const { owner, name } = splitRepository(
4641
- input.repositoryFullName,
5236
+ repository2.full_name,
4642
5237
  "pull request lifecycle"
4643
5238
  );
4644
- const token = await issueInstallationToken({
4645
- ...env,
4646
- permissions: { pull_requests: "read" },
4647
- repositories: [name]
4648
- });
4649
- const variables = input.numbers.map((_, index2) => `$n${index2}: Int!`);
4650
- const pullRequests = input.numbers.map(
4651
- (_, index2) => `pr${index2}: pullRequest(number: $n${index2}) { ...lifecycle }`
4652
- );
4653
5239
  return await githubRequest("https://api.github.com", "/graphql", {
4654
5240
  body: {
4655
- query: `query($owner: String!, $name: String!, ${variables.join(", ")}) { repository(owner: $owner, name: $name) { databaseId nameWithOwner ${pullRequests.join(" ")} } } fragment lifecycle on PullRequest { assignees(first: 20) { nodes { login } } author { __typename login } closedAt createdAt databaseId headRefName isDraft merged mergedAt number state title updatedAt }`,
5241
+ ...pullRequestLifecycles(input.numbers.length),
4656
5242
  variables: {
4657
5243
  name,
4658
5244
  owner,
4659
5245
  ...Object.fromEntries(
4660
- input.numbers.map((number31, index2) => [`n${index2}`, number31])
5246
+ input.numbers.map((number33, index2) => [`n${index2}`, number33])
4661
5247
  )
4662
5248
  }
4663
5249
  },
@@ -4677,7 +5263,7 @@ async function searchOpenPullRequestMergeability(env, input) {
4677
5263
  });
4678
5264
  return await githubRequest("https://api.github.com", "/graphql", {
4679
5265
  body: {
4680
- query: "query($query: String!, $after: String) { search(query: $query, type: ISSUE, first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { ... on PullRequest { number state mergeable headRefOid baseRefName url } } } }",
5266
+ ...OPEN_PULL_REQUEST_MERGEABILITY,
4681
5267
  variables: {
4682
5268
  after: input.after ?? null,
4683
5269
  query: `repo:${input.repositoryFullName} is:pr is:open author:${input.author}`
@@ -4687,6 +5273,26 @@ async function searchOpenPullRequestMergeability(env, input) {
4687
5273
  token: token.token
4688
5274
  });
4689
5275
  }
5276
+ async function requestPullRequestReviewers2(env, input) {
5277
+ const { owner, name } = splitRepository(
5278
+ input.repositoryFullName,
5279
+ "pull request review request"
5280
+ );
5281
+ const token = await issueInstallationToken({
5282
+ ...env,
5283
+ permissions: { pull_requests: "write" },
5284
+ repositories: [name]
5285
+ });
5286
+ await githubRequest(
5287
+ "https://api.github.com",
5288
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${input.number}/requested_reviewers`,
5289
+ {
5290
+ body: { reviewers: input.reviewers },
5291
+ method: "POST",
5292
+ token: token.token
5293
+ }
5294
+ );
5295
+ }
4690
5296
  async function markPullRequestFeedbackReviewing(env, target) {
4691
5297
  const { owner, name } = splitRepository(target.repo, "pull request feedback");
4692
5298
  const token = await issueInstallationToken({
@@ -4695,7 +5301,7 @@ async function markPullRequestFeedbackReviewing(env, target) {
4695
5301
  });
4696
5302
  const content = pullRequestFeedbackReactionContent("reviewing");
4697
5303
  if (target.commentKind === "review_body") {
4698
- const review = z32.object({ node_id: z32.string().min(1) }).parse(
5304
+ const review = z34.object({ node_id: z34.string().min(1) }).parse(
4699
5305
  await githubRequest(
4700
5306
  "https://api.github.com",
4701
5307
  pullRequestReviewPath({
@@ -4707,11 +5313,10 @@ async function markPullRequestFeedbackReviewing(env, target) {
4707
5313
  { token: token.token }
4708
5314
  )
4709
5315
  );
4710
- const result = z32.object({ errors: z32.array(z32.unknown()).optional() }).parse(
5316
+ const result = z34.object({ errors: z34.array(z34.unknown()).optional() }).parse(
4711
5317
  await githubRequest("https://api.github.com", "/graphql", {
4712
5318
  body: {
4713
- operationName: "AddReviewReaction",
4714
- query: ADD_REVIEW_REACTION_MUTATION,
5319
+ ...ADD_REVIEW_REACTION,
4715
5320
  variables: {
4716
5321
  content: graphqlReactionContent(content),
4717
5322
  subjectId: review.node_id
@@ -4743,9 +5348,9 @@ async function markPullRequestFeedbackReviewing(env, target) {
4743
5348
  }
4744
5349
  );
4745
5350
  }
4746
- var repositoryPermissionSchema = z32.object({
4747
- permission: z32.string().min(1),
4748
- role_name: z32.string().optional()
5351
+ var repositoryPermissionSchema = z34.object({
5352
+ permission: z34.string().min(1),
5353
+ role_name: z34.string().optional()
4749
5354
  });
4750
5355
  var REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1e3;
4751
5356
  async function loadRepositoryRole(env, cache, target) {
@@ -4775,19 +5380,19 @@ async function loadRepositoryRole(env, cache, target) {
4775
5380
  }
4776
5381
  );
4777
5382
  }
4778
- var pullRequestSchema4 = z32.object({
4779
- auto_merge: z32.object({}).nullable().optional(),
4780
- draft: z32.boolean().optional(),
4781
- html_url: z32.string().url(),
4782
- mergeable_state: z32.string().nullable().optional(),
4783
- merged: z32.boolean(),
4784
- state: z32.enum(["open", "closed"]),
4785
- title: z32.string()
5383
+ var pullRequestSchema4 = z34.object({
5384
+ auto_merge: z34.object({}).nullable().optional(),
5385
+ draft: z34.boolean().optional(),
5386
+ html_url: z34.string().url(),
5387
+ mergeable_state: z34.string().nullable().optional(),
5388
+ merged: z34.boolean(),
5389
+ state: z34.enum(["open", "closed"]),
5390
+ title: z34.string()
4786
5391
  });
4787
- var reviewsSchema = z32.array(
4788
- z32.object({
4789
- state: z32.string(),
4790
- user: z32.object({ login: z32.string() }).nullable()
5392
+ var reviewsSchema = z34.array(
5393
+ z34.object({
5394
+ state: z34.string(),
5395
+ user: z34.object({ login: z34.string() }).nullable()
4791
5396
  })
4792
5397
  );
4793
5398
  async function loadPullRequestMergeState(env, pullRequest) {
@@ -4855,10 +5460,10 @@ var READY_ACTIONS = {
4855
5460
  ]),
4856
5461
  pull_request_review: /* @__PURE__ */ new Set(["dismissed", "submitted"])
4857
5462
  };
4858
- var pullRequestWebhookSchema = z33.object({
4859
- action: z33.string(),
4860
- pull_request: z33.object({ number: z33.number().int().positive() }),
4861
- repository: z33.object({ full_name: z33.string().min(1) })
5463
+ var pullRequestWebhookSchema = z35.object({
5464
+ action: z35.string(),
5465
+ pull_request: z35.object({ number: z35.number().int().positive() }),
5466
+ repository: z35.object({ full_name: z35.string().min(1) })
4862
5467
  });
4863
5468
  function pullRequestReadyTargets(eventName, body) {
4864
5469
  if (eventName === "check_suite") return checkSuitePullRequests(body);
@@ -4921,7 +5526,12 @@ async function syncOne(args, target) {
4921
5526
  assigneeIdentityIds: [opener.identityId],
4922
5527
  body: `**${state.title}** is approved, and GitHub says that it can merge: ${state.url}`,
4923
5528
  dedupeKey,
4924
- subject: { id: state.url, title: name, url: state.url },
5529
+ // The number stays visible where a view shows only the subject.
5530
+ subject: {
5531
+ id: state.url,
5532
+ title: `${state.title} (#${target.number})`,
5533
+ url: state.url
5534
+ },
4925
5535
  title: `Ready to merge \xB7 #${target.number}`,
4926
5536
  waitsOnAssignees: true
4927
5537
  });
@@ -4946,43 +5556,83 @@ async function syncGitHubPullRequestReadyNotices(args) {
4946
5556
  try {
4947
5557
  await syncOne(args, target);
4948
5558
  } catch (error) {
4949
- args.log?.error("GitHub pull request ready notice failed", {
4950
- deliveryId: args.deliveryId,
4951
- errorType: error instanceof Error ? error.name : "UnknownError",
4952
- number: target.number,
4953
- repository: target.repositoryFullName
4954
- });
5559
+ logFailOpenFailure(
5560
+ args.log,
5561
+ "GitHub pull request ready notice failed",
5562
+ error,
5563
+ {
5564
+ deliveryId: args.deliveryId,
5565
+ number: target.number,
5566
+ repository: target.repositoryFullName
5567
+ }
5568
+ );
4955
5569
  }
4956
5570
  }
4957
5571
  }
4958
5572
 
5573
+ // src/webhooks/pull-request-ready-reviewers.ts
5574
+ import * as z36 from "zod";
5575
+ var readyForReviewSchema = z36.object({
5576
+ action: z36.literal("ready_for_review"),
5577
+ pull_request: z36.object({ number: z36.number().int().positive() }),
5578
+ repository: z36.object({ full_name: z36.string().min(1) })
5579
+ });
5580
+ async function requestGitHubReviewersWhenReady(args) {
5581
+ if (args.eventName !== "pull_request") return;
5582
+ const parsed = readyForReviewSchema.safeParse(args.body);
5583
+ if (!parsed.success) return;
5584
+ const target = {
5585
+ number: parsed.data.pull_request.number,
5586
+ repositoryFullName: parsed.data.repository.full_name
5587
+ };
5588
+ try {
5589
+ const opener = (await listGitHubPullRequestOpeners(args.db, {
5590
+ numbers: [target.number],
5591
+ repositoryFullName: target.repositoryFullName
5592
+ })).get(target.number);
5593
+ if (!opener?.conversationId) return;
5594
+ const named = await readGitHubDraftReviewers(args.state, target);
5595
+ const requester = named ? void 0 : await args.loadGitHubLogin?.(opener.identityId);
5596
+ const reviewers = named ?? (requester ? [requester] : []);
5597
+ if (reviewers.length === 0) return;
5598
+ await requestPullRequestReviewers2(args.env, { ...target, reviewers });
5599
+ } catch (error) {
5600
+ args.log?.warn("GitHub pull request review request failed", {
5601
+ deliveryId: args.deliveryId,
5602
+ errorType: error instanceof Error ? error.name : "UnknownError",
5603
+ number: target.number,
5604
+ repository: target.repositoryFullName
5605
+ });
5606
+ }
5607
+ }
5608
+
4959
5609
  // src/webhooks/pull-request-review-request.ts
4960
- import * as z34 from "zod";
4961
- var login = z34.object({ login: z34.string().min(1) });
4962
- var pullRequestEventSchema = z34.object({
4963
- action: z34.enum([
5610
+ import * as z37 from "zod";
5611
+ var login = z37.object({ login: z37.string().min(1) });
5612
+ var pullRequestEventSchema = z37.object({
5613
+ action: z37.enum([
4964
5614
  "closed",
4965
5615
  "reopened",
4966
5616
  "review_request_removed",
4967
5617
  "review_requested"
4968
5618
  ]),
4969
- pull_request: z34.object({
4970
- html_url: z34.string().url(),
4971
- merged: z34.boolean().optional(),
4972
- number: z34.number().int().positive(),
5619
+ pull_request: z37.object({
5620
+ html_url: z37.string().url(),
5621
+ merged: z37.boolean().optional(),
5622
+ number: z37.number().int().positive(),
4973
5623
  // The people whose review is still requested. Teams are listed apart.
4974
- requested_reviewers: z34.array(login).optional(),
4975
- title: z34.string()
5624
+ requested_reviewers: z37.array(login).optional(),
5625
+ title: z37.string()
4976
5626
  }),
4977
- repository: z34.object({ full_name: z34.string().min(1) }),
5627
+ repository: z37.object({ full_name: z37.string().min(1) }),
4978
5628
  // A team request has `requested_team` instead.
4979
5629
  requested_reviewer: login.optional()
4980
5630
  });
4981
- var reviewEventSchema = z34.object({
4982
- action: z34.literal("submitted"),
4983
- pull_request: z34.object({ number: z34.number().int().positive() }),
4984
- repository: z34.object({ full_name: z34.string().min(1) }),
4985
- review: z34.object({ user: login })
5631
+ var reviewEventSchema = z37.object({
5632
+ action: z37.literal("submitted"),
5633
+ pull_request: z37.object({ number: z37.number().int().positive() }),
5634
+ repository: z37.object({ full_name: z37.string().min(1) }),
5635
+ review: z37.object({ user: login })
4986
5636
  });
4987
5637
  function reviewRequestChange(eventName, body) {
4988
5638
  if (eventName === "pull_request_review") {
@@ -5063,14 +5713,14 @@ function sameLogin(left, right) {
5063
5713
  async function syncGitHubPullRequestReviewRequest(args) {
5064
5714
  const parsed = reviewRequestChange(args.eventName, args.body);
5065
5715
  if (!parsed) return;
5066
- const { change, number: number31, repository: repository2 } = parsed;
5716
+ const { change, number: number33, repository: repository2 } = parsed;
5067
5717
  try {
5068
5718
  const opener = (await listGitHubPullRequestOpeners(args.db, {
5069
- numbers: [number31],
5719
+ numbers: [number33],
5070
5720
  repositoryFullName: repository2
5071
- })).get(number31);
5721
+ })).get(number33);
5072
5722
  if (!opener?.conversationId) return;
5073
- const name = `${repository2}#${number31}`;
5723
+ const name = `${repository2}#${number33}`;
5074
5724
  const dedupeKey = `pull-request-review-requested:${name.toLowerCase()}`;
5075
5725
  const items = args.reviewItems.forConversation(opener.conversationId);
5076
5726
  const reviewers = change.kind === "requested" ? change.reviewers : change.reviewer === void 0 ? void 0 : [change.reviewer];
@@ -5092,22 +5742,27 @@ async function syncGitHubPullRequestReviewRequest(args) {
5092
5742
  assigneeIdentityIds: [opener.identityId],
5093
5743
  body: `GitHub asks you to review **${change.title}**: ${change.url}`,
5094
5744
  dedupeKey,
5095
- subject: { id: change.url, title: name, url: change.url },
5096
- title: `Review requested \xB7 #${number31}`,
5745
+ // The number stays visible where a view shows only the subject title.
5746
+ subject: {
5747
+ id: change.url,
5748
+ title: `${change.title} (#${number33})`,
5749
+ url: change.url
5750
+ },
5751
+ title: `Review requested \xB7 #${number33}`,
5097
5752
  waitsOnAssignees: true
5098
5753
  });
5099
5754
  } catch (error) {
5100
5755
  args.log?.error("GitHub pull request review request failed", {
5101
5756
  deliveryId: args.deliveryId,
5102
5757
  errorType: error instanceof Error ? error.name : "UnknownError",
5103
- number: number31,
5758
+ number: number33,
5104
5759
  repository: repository2
5105
5760
  });
5106
5761
  }
5107
5762
  }
5108
5763
 
5109
5764
  // src/webhooks/pull-request-match-data.ts
5110
- import * as z35 from "zod";
5765
+ import * as z38 from "zod";
5111
5766
  var LOOKUPS_BY_MATCH_KEY = {
5112
5767
  authors: ["authors"],
5113
5768
  openerEmail: ["opener"],
@@ -5115,22 +5770,22 @@ var LOOKUPS_BY_MATCH_KEY = {
5115
5770
  openerUsername: ["opener"]
5116
5771
  };
5117
5772
  var ALL_LOOKUPS = ["authors", "opener", "openerRole"];
5118
- var lookupDataSchema = z35.object({
5119
- authors: z35.array(z35.string().min(1)).min(1).optional(),
5120
- openerRole: z35.string().min(1).optional(),
5121
- openerUsername: z35.string().min(1).optional()
5773
+ var lookupDataSchema = z38.object({
5774
+ authors: z38.array(z38.string().min(1)).min(1).optional(),
5775
+ openerRole: z38.string().min(1).optional(),
5776
+ openerUsername: z38.string().min(1).optional()
5122
5777
  }).strict();
5123
5778
  function lookupData(input) {
5124
5779
  return lookupDataSchema.parse(definedValues(input));
5125
5780
  }
5126
- var webhookSchema = z35.object({
5127
- repository: z35.object({ full_name: z35.string().min(1) })
5781
+ var webhookSchema = z38.object({
5782
+ repository: z38.object({ full_name: z38.string().min(1) })
5128
5783
  });
5129
5784
  function pullRequestNumbers(events) {
5130
5785
  const numbers = /* @__PURE__ */ new Map();
5131
5786
  for (const event of events) {
5132
- const number31 = event.data?.pullRequest;
5133
- if (typeof number31 === "number") numbers.set(event.eventKey, number31);
5787
+ const number33 = event.data?.pullRequest;
5788
+ if (typeof number33 === "number") numbers.set(event.eventKey, number33);
5134
5789
  }
5135
5790
  return numbers;
5136
5791
  }
@@ -5144,8 +5799,8 @@ function logFailure(context, lookup, error) {
5144
5799
  }
5145
5800
  async function withJuniorOpeners(context, events) {
5146
5801
  const botNumber = (event) => {
5147
- const number31 = context.numbers.get(event.eventKey);
5148
- return number31 !== void 0 && isBotLogin(event.data?.openerUsername, context.botEmail) ? number31 : void 0;
5802
+ const number33 = context.numbers.get(event.eventKey);
5803
+ return number33 !== void 0 && isBotLogin(event.data?.openerUsername, context.botEmail) ? number33 : void 0;
5149
5804
  };
5150
5805
  const numbers = events.flatMap((event) => botNumber(event) ?? []);
5151
5806
  if (numbers.length === 0) return events;
@@ -5164,9 +5819,9 @@ async function withJuniorOpeners(context, events) {
5164
5819
  }
5165
5820
  }
5166
5821
  return events.map((event) => {
5167
- const number31 = botNumber(event);
5168
- if (number31 === void 0) return event;
5169
- const identityId = openers.get(number31)?.identityId;
5822
+ const number33 = botNumber(event);
5823
+ if (number33 === void 0) return event;
5824
+ const identityId = openers.get(number33)?.identityId;
5170
5825
  const login2 = identityId ? logins.get(identityId) : void 0;
5171
5826
  const {
5172
5827
  openerEmail: _email,
@@ -5188,8 +5843,8 @@ async function withRolesAndAuthors(context, events, lookups) {
5188
5843
  if (!loadRole && !loadAuthors) return events;
5189
5844
  return await Promise.all(
5190
5845
  events.map(async (event) => {
5191
- const number31 = context.numbers.get(event.eventKey);
5192
- if (number31 === void 0) return event;
5846
+ const number33 = context.numbers.get(event.eventKey);
5847
+ if (number33 === void 0) return event;
5193
5848
  const login2 = event.data?.openerUsername;
5194
5849
  if (loadRole && typeof login2 === "string" && !roles.has(login2)) {
5195
5850
  roles.set(
@@ -5199,16 +5854,16 @@ async function withRolesAndAuthors(context, events, lookups) {
5199
5854
  )
5200
5855
  );
5201
5856
  }
5202
- if (loadAuthors && !authors.has(number31)) {
5857
+ if (loadAuthors && !authors.has(number33)) {
5203
5858
  authors.set(
5204
- number31,
5205
- loadAuthors({ number: number31, repositoryFullName }).catch(
5859
+ number33,
5860
+ loadAuthors({ number: number33, repositoryFullName }).catch(
5206
5861
  (error) => logFailure(context, "authors", error)
5207
5862
  )
5208
5863
  );
5209
5864
  }
5210
5865
  const role = loadRole && typeof login2 === "string" ? await roles.get(login2) : void 0;
5211
- const logins = loadAuthors ? await authors.get(number31) : void 0;
5866
+ const logins = loadAuthors ? await authors.get(number33) : void 0;
5212
5867
  if (!role && !logins?.length) return event;
5213
5868
  return {
5214
5869
  ...event,
@@ -5265,7 +5920,7 @@ async function withGitHubPullRequestMatchData(args) {
5265
5920
  }
5266
5921
 
5267
5922
  // src/webhooks/pull-request-people.ts
5268
- import * as z36 from "zod";
5923
+ import * as z39 from "zod";
5269
5924
  var PEOPLE_EVENTS = /* @__PURE__ */ new Set([
5270
5925
  "pull_request.review.approved",
5271
5926
  "pull_request.merged"
@@ -5275,18 +5930,18 @@ var PAGE_SIZE = 100;
5275
5930
  var MAX_PAGES = 3;
5276
5931
  var CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
5277
5932
  var GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
5278
- var webhookSchema2 = z36.object({
5279
- pull_request: z36.object({
5280
- assignees: z36.array(z36.object({ login: z36.string().min(1) })).nullish(),
5281
- number: z36.number(),
5282
- user: z36.object({ login: z36.string().min(1) }).nullish()
5933
+ var webhookSchema2 = z39.object({
5934
+ pull_request: z39.object({
5935
+ assignees: z39.array(z39.object({ login: z39.string().min(1) })).nullish(),
5936
+ number: z39.number(),
5937
+ user: z39.object({ login: z39.string().min(1) }).nullish()
5283
5938
  }),
5284
- repository: z36.object({ full_name: z36.string().min(1) })
5939
+ repository: z39.object({ full_name: z39.string().min(1) })
5285
5940
  });
5286
- var commitPageSchema = z36.array(
5287
- z36.object({
5288
- author: z36.object({ login: z36.string().min(1) }).nullish(),
5289
- commit: z36.object({ message: z36.string() })
5941
+ var commitPageSchema = z39.array(
5942
+ z39.object({
5943
+ author: z39.object({ login: z39.string().min(1) }).nullish(),
5944
+ commit: z39.object({ message: z39.string() })
5290
5945
  })
5291
5946
  );
5292
5947
  function shareCommitPages(load) {
@@ -5308,11 +5963,11 @@ function shareCommitPages(load) {
5308
5963
  return await result;
5309
5964
  };
5310
5965
  }
5311
- async function forEachCommit(loadPage, visit) {
5966
+ async function forEachCommit(loadPage, visit2) {
5312
5967
  for (let page = 1; page <= MAX_PAGES; page += 1) {
5313
5968
  const commits = commitPageSchema.parse(await loadPage(page, PAGE_SIZE));
5314
5969
  for (const commit of commits) {
5315
- visit({
5970
+ visit2({
5316
5971
  coAuthorEmails: [
5317
5972
  ...commit.commit.message.matchAll(CO_AUTHOR_TRAILER)
5318
5973
  ].map((match) => match[1]),
@@ -5428,11 +6083,11 @@ function webhookInstallationId(body) {
5428
6083
  }
5429
6084
  return parseInstallationId(installation.id);
5430
6085
  }
5431
- var feedbackTargetSchema = z37.object({
5432
- commentId: z37.number(),
5433
- commentKind: z37.enum(["conversation", "review", "review_body"]),
5434
- pullRequest: z37.number(),
5435
- repo: z37.string().min(1)
6086
+ var feedbackTargetSchema = z40.object({
6087
+ commentId: z40.number(),
6088
+ commentKind: z40.enum(["conversation", "review", "review_body"]),
6089
+ pullRequest: z40.number(),
6090
+ repo: z40.string().min(1)
5436
6091
  });
5437
6092
  function pullRequestFeedbackTarget(events) {
5438
6093
  for (const event of events) {
@@ -5545,6 +6200,14 @@ function createGitHubWebhookRoute(args) {
5545
6200
  providerId: pullRequestConversations.pullRequestId
5546
6201
  });
5547
6202
  }
6203
+ if (eventName === "pull_request") {
6204
+ await refreshGitHubPullRequestPreview({
6205
+ annotations: args.annotations,
6206
+ body,
6207
+ db: args.db,
6208
+ log: args.log
6209
+ });
6210
+ }
5548
6211
  const pullRequestActivity = normalizeGitHubPullRequestActivity({
5549
6212
  body,
5550
6213
  eventName
@@ -5646,6 +6309,20 @@ function createGitHubWebhookRoute(args) {
5646
6309
  reviewItems: args.reviewItems,
5647
6310
  targets: pullRequestReadyTargets(eventName, body)
5648
6311
  });
6312
+ await requestGitHubReviewersWhenReady({
6313
+ body,
6314
+ db: args.db,
6315
+ deliveryId,
6316
+ env: {
6317
+ appIdEnv: args.appIdEnv,
6318
+ installationIdEnv: args.installationIdEnv,
6319
+ privateKeyEnv: args.privateKeyEnv
6320
+ },
6321
+ eventName,
6322
+ loadGitHubLogin: args.loadGitHubLogin,
6323
+ log: args.log,
6324
+ state: args.state
6325
+ });
5649
6326
  await syncGitHubPullRequestReviewRequest({
5650
6327
  body,
5651
6328
  db: args.db,
@@ -5664,30 +6341,30 @@ function createGitHubWebhookRoute(args) {
5664
6341
  }
5665
6342
 
5666
6343
  // src/merge-conflict-checks/heartbeat.ts
5667
- import * as z38 from "zod";
6344
+ import * as z41 from "zod";
5668
6345
  var CHECK_LIMIT = 10;
5669
6346
  var MAX_PAGES2 = 5;
5670
6347
  var CLAIM_MS = 5 * 6e4;
5671
6348
  var UNKNOWN_RETRY_MS = 6e4;
5672
6349
  var MAX_ATTEMPTS = 5;
5673
- var searchNodeSchema = z38.union([
5674
- z38.object({
5675
- baseRefName: z38.string().min(1),
5676
- headRefOid: z38.string().min(1),
5677
- mergeable: z38.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
5678
- number: z38.number().int().positive(),
5679
- state: z38.string(),
5680
- url: z38.string().min(1)
6350
+ var searchNodeSchema = z41.union([
6351
+ z41.object({
6352
+ baseRefName: z41.string().min(1),
6353
+ headRefOid: z41.string().min(1),
6354
+ mergeable: z41.enum(["CONFLICTING", "MERGEABLE", "UNKNOWN"]),
6355
+ number: z41.number().int().positive(),
6356
+ state: z41.string(),
6357
+ url: z41.string().min(1)
5681
6358
  }),
5682
- z38.object({}).strict()
6359
+ z41.object({}).strict()
5683
6360
  ]);
5684
- var searchResponseSchema = z38.object({
5685
- data: z38.object({
5686
- search: z38.object({
5687
- nodes: z38.array(searchNodeSchema.nullable()),
5688
- pageInfo: z38.object({
5689
- endCursor: z38.string().nullable(),
5690
- hasNextPage: z38.boolean()
6361
+ var searchResponseSchema = z41.object({
6362
+ data: z41.object({
6363
+ search: z41.object({
6364
+ nodes: z41.array(searchNodeSchema.nullable()),
6365
+ pageInfo: z41.object({
6366
+ endCursor: z41.string().nullable(),
6367
+ hasNextPage: z41.boolean()
5691
6368
  })
5692
6369
  })
5693
6370
  })
@@ -5761,40 +6438,40 @@ async function runGitHubConflictChecks(args) {
5761
6438
  }
5762
6439
 
5763
6440
  // src/pull-request-outcomes/reconcile.ts
5764
- import * as z39 from "zod";
6441
+ import * as z42 from "zod";
5765
6442
  var RECONCILE_MS = 24 * 60 * 6e4;
5766
6443
  var REPOSITORY_LIMIT = 1;
5767
6444
  var PULL_REQUESTS_PER_QUERY = 100;
5768
- var lifecycleSchema = z39.object({
5769
- assignees: z39.object({
5770
- nodes: z39.array(z39.object({ login: z39.string().min(1) }).nullable())
6445
+ var lifecycleSchema = z42.object({
6446
+ assignees: z42.object({
6447
+ nodes: z42.array(z42.object({ login: z42.string().min(1) }).nullable())
5771
6448
  }),
5772
6449
  // GraphQL omits the `[bot]` suffix that REST and webhooks give an app.
5773
- author: z39.object({ __typename: z39.string(), login: z39.string().min(1) }).nullable(),
5774
- closedAt: z39.string().nullable(),
5775
- createdAt: z39.string(),
5776
- databaseId: z39.number().int().positive(),
5777
- headRefName: z39.string(),
5778
- isDraft: z39.boolean(),
5779
- merged: z39.boolean(),
5780
- mergedAt: z39.string().nullable(),
5781
- number: z39.number().int().positive(),
5782
- state: z39.enum(["OPEN", "CLOSED", "MERGED"]),
5783
- title: z39.string(),
5784
- updatedAt: z39.string()
6450
+ author: z42.object({ __typename: z42.string(), login: z42.string().min(1) }).nullable(),
6451
+ closedAt: z42.string().nullable(),
6452
+ createdAt: z42.string(),
6453
+ databaseId: z42.number().int().positive(),
6454
+ headRefName: z42.string(),
6455
+ isDraft: z42.boolean(),
6456
+ merged: z42.boolean(),
6457
+ mergedAt: z42.string().nullable(),
6458
+ number: z42.number().int().positive(),
6459
+ state: z42.enum(["OPEN", "CLOSED", "MERGED"]),
6460
+ title: z42.string(),
6461
+ updatedAt: z42.string()
5785
6462
  });
5786
- var lifecyclesResponseSchema = z39.object({
5787
- data: z39.object({
5788
- repository: z39.object({
5789
- databaseId: z39.number().int().positive(),
5790
- nameWithOwner: z39.string().min(1)
6463
+ var lifecyclesResponseSchema = z42.object({
6464
+ data: z42.object({
6465
+ repository: z42.object({
6466
+ databaseId: z42.number().int().positive(),
6467
+ nameWithOwner: z42.string().min(1)
5791
6468
  }).catchall(lifecycleSchema.nullable())
5792
6469
  })
5793
6470
  });
5794
- function closedWebhookBody(repository2, pullRequest) {
6471
+ function webhookBody(action, repository2, pullRequest) {
5795
6472
  const login2 = pullRequest.author?.login ?? "ghost";
5796
6473
  return {
5797
- action: "closed",
6474
+ action,
5798
6475
  pull_request: {
5799
6476
  assignees: pullRequest.assignees.nodes.flatMap(
5800
6477
  (assignee) => assignee ? [{ login: assignee.login }] : []
@@ -5819,17 +6496,65 @@ function closedWebhookBody(repository2, pullRequest) {
5819
6496
  }
5820
6497
  };
5821
6498
  }
5822
- async function reconcileRepository(args, repositoryFullName, numbers) {
6499
+ async function reconcileDraft(args, repository2, pullRequest) {
6500
+ const outcome = normalizeGitHubPullRequestOutcome({
6501
+ body: webhookBody(
6502
+ pullRequest.isDraft ? "converted_to_draft" : "ready_for_review",
6503
+ repository2,
6504
+ pullRequest
6505
+ ),
6506
+ botEmail: args.botEmail
6507
+ });
6508
+ if (!outcome) return;
6509
+ await applyGitHubPullRequestOutcome({
6510
+ annotations: args.annotations,
6511
+ codeChanges: args.codeChanges,
6512
+ db: args.db,
6513
+ log: args.log,
6514
+ outcome
6515
+ });
6516
+ }
6517
+ async function reconcileRepository(args, repositoryId, drafts) {
6518
+ const numbers = [...drafts.keys()];
5823
6519
  for (let start = 0; start < numbers.length; start += PULL_REQUESTS_PER_QUERY) {
5824
6520
  const { databaseId, nameWithOwner, ...pullRequests } = lifecyclesResponseSchema.parse(
5825
6521
  await args.loadLifecycles({
5826
6522
  numbers: numbers.slice(start, start + PULL_REQUESTS_PER_QUERY),
5827
- repositoryFullName
6523
+ repositoryId
5828
6524
  })
5829
6525
  ).data.repository;
5830
6526
  for (const pullRequest of Object.values(pullRequests)) {
5831
- if (!pullRequest || pullRequest.state === "OPEN") continue;
5832
- const body = closedWebhookBody(
6527
+ if (!pullRequest) continue;
6528
+ if (pullRequest.state === "OPEN") {
6529
+ if (pullRequest.isDraft !== drafts.get(pullRequest.number)) {
6530
+ await reconcileDraft(
6531
+ args,
6532
+ { databaseId, nameWithOwner },
6533
+ pullRequest
6534
+ );
6535
+ continue;
6536
+ }
6537
+ await args.codeChanges.record(
6538
+ githubCodeChange(
6539
+ {
6540
+ candidateOwned: false,
6541
+ draft: pullRequest.isDraft,
6542
+ number: pullRequest.number,
6543
+ openedAt: new Date(pullRequest.createdAt),
6544
+ pullRequestId: String(pullRequest.databaseId),
6545
+ repositoryFullName: nameWithOwner,
6546
+ repositoryId: String(databaseId),
6547
+ state: "open",
6548
+ title: pullRequest.title,
6549
+ updatedAt: new Date(pullRequest.updatedAt)
6550
+ },
6551
+ []
6552
+ )
6553
+ );
6554
+ continue;
6555
+ }
6556
+ const body = webhookBody(
6557
+ "closed",
5833
6558
  { databaseId, nameWithOwner },
5834
6559
  pullRequest
5835
6560
  );
@@ -5863,32 +6588,45 @@ async function reconcileRepository(args, repositoryFullName, numbers) {
5863
6588
  }
5864
6589
  }
5865
6590
  async function reconcileGitHubPullRequests(args) {
5866
- const numbersByRepository = /* @__PURE__ */ new Map();
6591
+ const repositories = /* @__PURE__ */ new Map();
5867
6592
  for (const row of await listGitHubStaleOpenPullRequests(
5868
6593
  args.db,
5869
6594
  new Date(args.nowMs - RECONCILE_MS)
5870
6595
  )) {
5871
- const numbers = numbersByRepository.get(row.repositoryFullName) ?? [];
5872
- numbers.push(row.number);
5873
- numbersByRepository.set(row.repositoryFullName, numbers);
6596
+ const repository2 = repositories.get(row.repositoryId) ?? {
6597
+ drafts: /* @__PURE__ */ new Map(),
6598
+ name: row.repositoryFullName
6599
+ };
6600
+ repository2.drafts.set(row.number, row.draft);
6601
+ repositories.set(row.repositoryId, repository2);
5874
6602
  }
5875
6603
  let reconciled = 0;
5876
- for (const [repositoryFullName, numbers] of numbersByRepository) {
6604
+ for (const [
6605
+ repositoryId,
6606
+ { drafts, name: repositoryFullName }
6607
+ ] of repositories) {
5877
6608
  if (reconciled >= REPOSITORY_LIMIT) break;
5878
6609
  const claimed = await args.state.setIfNotExists(
5879
- `pull-request-reconcile:${repositoryFullName}`,
6610
+ `pull-request-reconcile:${repositoryId}`,
5880
6611
  args.nowMs,
5881
6612
  RECONCILE_MS
5882
6613
  );
5883
6614
  if (!claimed) continue;
5884
6615
  reconciled += 1;
5885
6616
  try {
5886
- await reconcileRepository(args, repositoryFullName, numbers);
6617
+ await reconcileRepository(args, Number(repositoryId), drafts);
5887
6618
  } catch (error) {
5888
- args.log.error("GitHub pull request reconcile failed", {
5889
- errorType: error instanceof Error ? error.name : "UnknownError",
5890
- repository: repositoryFullName
5891
- });
6619
+ if (error instanceof GitHubRepositoryUnreachableError) {
6620
+ args.log.warn("GitHub pull request reconcile skipped a repository", {
6621
+ repository: repositoryFullName,
6622
+ repositoryId
6623
+ });
6624
+ } else {
6625
+ args.log.error("GitHub pull request reconcile failed", {
6626
+ errorType: error instanceof Error ? error.name : "UnknownError",
6627
+ repository: repositoryFullName
6628
+ });
6629
+ }
5892
6630
  }
5893
6631
  }
5894
6632
  }
@@ -5917,30 +6655,30 @@ function gitHubResourceUrl(input) {
5917
6655
  if (input.resourceType === "repository") {
5918
6656
  return `https://github.com/${input.identifier}`;
5919
6657
  }
5920
- const [repo, number31] = input.identifier.split("#");
5921
- if (!repo || !number31) return void 0;
6658
+ const [repo, number33] = input.identifier.split("#");
6659
+ if (!repo || !number33) return void 0;
5922
6660
  if (input.resourceType === "pull_request") {
5923
- return `https://github.com/${repo}/pull/${number31}`;
6661
+ return `https://github.com/${repo}/pull/${number33}`;
5924
6662
  }
5925
6663
  if (input.resourceType === "issue") {
5926
- return `https://github.com/${repo}/issues/${number31}`;
6664
+ return `https://github.com/${repo}/issues/${number33}`;
5927
6665
  }
5928
6666
  return void 0;
5929
6667
  }
5930
6668
 
5931
6669
  // src/pull-request-outcomes/commit-composition.ts
5932
- import * as z40 from "zod";
5933
- var canonicalCommitSchema = z40.object({
5934
- authorEmail: z40.string().nullable(),
5935
- authorLogin: z40.string().nullable()
6670
+ import * as z43 from "zod";
6671
+ var canonicalCommitSchema = z43.object({
6672
+ authorEmail: z43.string().nullable(),
6673
+ authorLogin: z43.string().nullable()
5936
6674
  }).strict();
5937
- var providerCommitSchema = z40.object({
5938
- author: z40.object({ login: z40.string() }).passthrough().nullable(),
5939
- commit: z40.object({
5940
- author: z40.object({ email: z40.string() }).passthrough().nullable()
6675
+ var providerCommitSchema = z43.object({
6676
+ author: z43.object({ login: z43.string() }).passthrough().nullable(),
6677
+ commit: z43.object({
6678
+ author: z43.object({ email: z43.string() }).passthrough().nullable()
5941
6679
  }).passthrough()
5942
6680
  }).passthrough();
5943
- var commitPageSchema2 = z40.array(providerCommitSchema).transform(
6681
+ var commitPageSchema2 = z43.array(providerCommitSchema).transform(
5944
6682
  (commits) => commits.map(
5945
6683
  (commit) => canonicalCommitSchema.parse({
5946
6684
  authorEmail: commit.commit.author?.email ?? null,
@@ -6447,8 +7185,8 @@ function linkifyLine(line) {
6447
7185
  if (isReferenceBoundary(index2 === 0 ? void 0 : line[index2 - 1])) {
6448
7186
  const match = GITHUB_ISSUE_REFERENCE_PATTERN.exec(line.slice(index2));
6449
7187
  if (match) {
6450
- const [reference, owner, repository2, number31] = match;
6451
- output += `[${reference}](https://github.com/${owner}/${repository2}/issues/${number31})`;
7188
+ const [reference, owner, repository2, number33] = match;
7189
+ output += `[${reference}](https://github.com/${owner}/${repository2}/issues/${number33})`;
6452
7190
  index2 += reference.length;
6453
7191
  continue;
6454
7192
  }
@@ -6590,9 +7328,9 @@ function parseGitHubReferences(text2, config) {
6590
7328
  }
6591
7329
  return [...references.values()];
6592
7330
  }
6593
- function objectTitle(kind, object41) {
6594
- if (!isRecord(object41)) return void 0;
6595
- const raw = kind === "commit" ? isRecord(object41.commit) && typeof object41.commit.message === "string" ? object41.commit.message.split("\n")[0] : void 0 : typeof object41.title === "string" ? object41.title : void 0;
7331
+ function objectTitle(kind, object43) {
7332
+ if (!isRecord(object43)) return void 0;
7333
+ const raw = kind === "commit" ? isRecord(object43.commit) && typeof object43.commit.message === "string" ? object43.commit.message.split("\n")[0] : void 0 : typeof object43.title === "string" ? object43.title : void 0;
6596
7334
  return raw?.replace(/\s+/g, " ").trim() || void 0;
6597
7335
  }
6598
7336
  async function loadGitHubConversationTitleContext(args) {
@@ -6871,9 +7609,9 @@ import {
6871
7609
  } from "@sentry/junior-plugin-api";
6872
7610
 
6873
7611
  // src/default-branch.ts
6874
- import * as z41 from "zod";
7612
+ import * as z44 from "zod";
6875
7613
  var DEFAULT_BRANCH_TTL_MS = 10 * 60 * 1e3;
6876
- var repositorySchema3 = z41.object({ default_branch: z41.string().min(1) });
7614
+ var repositorySchema3 = z44.object({ default_branch: z44.string().min(1) });
6877
7615
  async function loadDefaultBranch(env, cache, repository2) {
6878
7616
  const { owner, name } = repository2;
6879
7617
  return await cache.getOrLoad(
@@ -7088,8 +7826,8 @@ var ISSUE_PATH = /^\/repos\/[^/]+\/[^/]+\/issues\/\d+$/;
7088
7826
  var ISSUE_READ_DENIAL = `Use github_getIssue to read a GitHub issue, not gh issue view or gh api. Read comments with gh api repos/OWNER/REPO/issues/NUMBER/comments. ${CREATE_TOOL_ROUTING_GUIDANCE}`;
7089
7827
  function isGitHubIssueRead(input) {
7090
7828
  if (isGitHubGraphqlUrl(input.upstreamUrl)) {
7091
- const operation = input.method === "POST" ? githubGraphqlOperation(input.graphql) : void 0;
7092
- return operation?.fields.some(
7829
+ const operation2 = input.method === "POST" ? githubGraphqlOperation(input.graphql) : void 0;
7830
+ return operation2?.fields.some(
7093
7831
  (field) => (field.name === "issue" || field.name === "issueOrPullRequest") && field.arguments.length > 0
7094
7832
  ) ?? false;
7095
7833
  }
@@ -7244,16 +7982,16 @@ var HOST_GRAPHQL_MUTATIONS = [
7244
7982
  operationPrefix: "github.pull.review-reaction.update:"
7245
7983
  }
7246
7984
  ];
7247
- function hostGraphqlMutationRepository(operation, method, upstreamUrl, graphql) {
7248
- if (method !== "POST" || !isGitHubGraphqlUrl(upstreamUrl) || !operation) {
7985
+ function hostGraphqlMutationRepository(operation2, method, upstreamUrl, graphql) {
7986
+ if (method !== "POST" || !isGitHubGraphqlUrl(upstreamUrl) || !operation2) {
7249
7987
  return void 0;
7250
7988
  }
7251
7989
  const parsed = githubGraphqlOperation(graphql);
7252
7990
  const mutation = HOST_GRAPHQL_MUTATIONS.find(
7253
- (candidate) => operation.startsWith(candidate.operationPrefix) && parsed?.type === "mutation" && parsed.name === candidate.operationName && parsed.rootFields.length === 1 && parsed.rootFields[0] === candidate.field
7991
+ (candidate) => operation2.startsWith(candidate.operationPrefix) && parsed?.type === "mutation" && parsed.name === candidate.operationName && parsed.rootFields.length === 1 && parsed.rootFields[0] === candidate.field
7254
7992
  );
7255
7993
  if (!mutation) return void 0;
7256
- const repository2 = operation.slice(mutation.operationPrefix.length);
7994
+ const repository2 = operation2.slice(mutation.operationPrefix.length);
7257
7995
  return /^[^/]+\/[^/]+$/.test(repository2) ? repository2 : void 0;
7258
7996
  }
7259
7997
  function isGitHubGraphqlMutation(method, upstreamUrl, graphql, field) {
@@ -7556,7 +8294,7 @@ function githubPlugin(options = {}) {
7556
8294
  log: ctx.log,
7557
8295
  text: ctx.text,
7558
8296
  loadObject: async (reference) => {
7559
- const { collection, operation } = {
8297
+ const { collection, operation: operation2 } = {
7560
8298
  commit: {
7561
8299
  collection: "commits",
7562
8300
  operation: "github.commit.get"
@@ -7568,7 +8306,7 @@ function githubPlugin(options = {}) {
7568
8306
  }
7569
8307
  }[reference.kind];
7570
8308
  const response = await githubApi(ctx.egress, {
7571
- operation,
8309
+ operation: operation2,
7572
8310
  path: `${repoPath(reference)}/${collection}/${encodeURIComponent(reference.id)}`,
7573
8311
  signal: ctx.signal
7574
8312
  });
@@ -7694,7 +8432,8 @@ function githubPlugin(options = {}) {
7694
8432
  readEnv(botEmailEnv),
7695
8433
  gitHubPullRequestSubscription(
7696
8434
  options.pullRequestEvents?.subscribeAfterCreate
7697
- )
8435
+ ),
8436
+ options.experimental
7698
8437
  );
7699
8438
  },
7700
8439
  workspacePrepare: prepareWorkspace,