@sentry/junior-github 0.261.0 → 0.263.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.
@@ -2,6 +2,9 @@
2
2
  import { z as z2 } from "zod";
3
3
 
4
4
  // src/events/deployment.ts
5
+ import {
6
+ eventMatchFieldsSchema
7
+ } from "@sentry/junior-plugin-api";
5
8
  var GITHUB_DEPLOYMENT_EVENTS = [
6
9
  "deployment.created",
7
10
  "deployment.queued",
@@ -16,6 +19,20 @@ var GITHUB_DEPLOYMENT_SUGGESTED_EVENTS = [
16
19
  "deployment.failed",
17
20
  "deployment.error"
18
21
  ];
22
+ var GITHUB_DEPLOYMENT_MATCH_FIELDS = eventMatchFieldsSchema.parse({
23
+ environment: {
24
+ kind: "string",
25
+ description: "lowercase deployment environment name, such as production"
26
+ },
27
+ workflowId: {
28
+ kind: "number",
29
+ description: "numeric GitHub Actions workflow id when a workflow created the deployment"
30
+ },
31
+ workflowPath: {
32
+ kind: "string",
33
+ description: "GitHub Actions workflow file, such as .github/workflows/deploy.yml, when a workflow created the deployment"
34
+ }
35
+ });
19
36
  var GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER = {
20
37
  format: "deployment-source:owner/repo[:environment]:<full-commit-sha>",
21
38
  pattern: /^deployment-source:[^\s/:#]+\/[^\s/:#]+(?::[^\s:]+)?:[0-9a-f]+$/
@@ -42,7 +59,7 @@ function gitHubDeploymentSourceSubscribable(input) {
42
59
 
43
60
  // src/events/issue.ts
44
61
  import {
45
- eventMatchFieldsSchema
62
+ eventMatchFieldsSchema as eventMatchFieldsSchema2
46
63
  } from "@sentry/junior-plugin-api";
47
64
  var GITHUB_ISSUE_EVENTS = [
48
65
  "issue.comment.created",
@@ -55,7 +72,7 @@ var GITHUB_ISSUE_SUGGESTED_EVENTS = [
55
72
  "issue.closed",
56
73
  "issue.reopened"
57
74
  ];
58
- var GITHUB_ISSUE_COMMENT_MATCH_FIELDS = eventMatchFieldsSchema.parse({
75
+ var GITHUB_ISSUE_COMMENT_MATCH_FIELDS = eventMatchFieldsSchema2.parse({
59
76
  mentionsBot: {
60
77
  kind: "boolean",
61
78
  description: "true when the issue comment mentions the Junior GitHub App"
@@ -92,7 +109,7 @@ function gitHubIssueSubscribable(input) {
92
109
 
93
110
  // src/events/pull-request.ts
94
111
  import {
95
- eventMatchFieldsSchema as eventMatchFieldsSchema2
112
+ eventMatchFieldsSchema as eventMatchFieldsSchema3
96
113
  } from "@sentry/junior-plugin-api";
97
114
  var GITHUB_PULL_REQUEST_EVENTS = [
98
115
  "pull_request.checks.failed",
@@ -145,7 +162,7 @@ var GITHUB_PULL_REQUEST_SUGGESTED_EVENTS = [
145
162
  "pull_request.merged",
146
163
  "pull_request.closed_unmerged"
147
164
  ];
148
- var GITHUB_PULL_REQUEST_MATCH_FIELDS = eventMatchFieldsSchema2.parse({
165
+ var GITHUB_PULL_REQUEST_MATCH_FIELDS = eventMatchFieldsSchema3.parse({
149
166
  authorEmail: {
150
167
  kind: "string",
151
168
  description: "pull request author email when GitHub sends it"
@@ -154,6 +171,10 @@ var GITHUB_PULL_REQUEST_MATCH_FIELDS = eventMatchFieldsSchema2.parse({
154
171
  kind: "string",
155
172
  description: "pull request author login"
156
173
  },
174
+ authorRole: {
175
+ kind: "string",
176
+ description: "pull request author's repository role: admin, maintain, write, triage, read, none (no access, such as most bots), or a custom role name"
177
+ },
157
178
  headBranch: {
158
179
  kind: "string",
159
180
  description: "head branch name from the webhook"
@@ -236,7 +257,11 @@ function gitHubRepositorySubscribable(input) {
236
257
  ...GITHUB_ISSUE_SUGGESTED_EVENTS,
237
258
  ...GITHUB_PULL_REQUEST_SUGGESTED_EVENTS
238
259
  ],
239
- supportedEvents: [...GITHUB_ISSUE_EVENTS, ...GITHUB_PULL_REQUEST_EVENTS],
260
+ supportedEvents: [
261
+ ...GITHUB_DEPLOYMENT_EVENTS,
262
+ ...GITHUB_ISSUE_EVENTS,
263
+ ...GITHUB_PULL_REQUEST_EVENTS
264
+ ],
240
265
  type: "repository"
241
266
  };
242
267
  }
@@ -929,6 +954,7 @@ function createPermissionCache() {
929
954
  // src/webhooks/check-suite.ts
930
955
  var CHECK_SUITE_PULL_REQUEST_MATCH_KEYS = /* @__PURE__ */ new Set([
931
956
  "authorEmail",
957
+ "authorRole",
932
958
  "authorUsername",
933
959
  "isDraft"
934
960
  ]);
@@ -1421,10 +1447,15 @@ var deploymentSchema = z2.object({
1421
1447
  id: z2.number(),
1422
1448
  sha: z2.string().regex(/^[0-9a-f]{40}$/i)
1423
1449
  }).passthrough();
1450
+ var deploymentWorkflowSchema = {
1451
+ workflow: z2.object({ id: z2.number(), path: z2.string().min(1) }).passthrough().nullish(),
1452
+ workflow_run: z2.object({ id: z2.number() }).passthrough().nullish()
1453
+ };
1424
1454
  var deploymentWebhookSchema = z2.object({
1425
1455
  action: z2.string(),
1426
1456
  deployment: deploymentSchema,
1427
- repository: repositorySchema2
1457
+ repository: repositorySchema2,
1458
+ ...deploymentWorkflowSchema
1428
1459
  }).passthrough();
1429
1460
  var canonicalDeploymentEventSchema = z2.object({
1430
1461
  action: z2.string(),
@@ -1432,42 +1463,52 @@ var canonicalDeploymentEventSchema = z2.object({
1432
1463
  createdAt: z2.string().optional(),
1433
1464
  deploymentId: z2.number(),
1434
1465
  environment: z2.string().min(1),
1435
- repo: z2.string().min(1)
1466
+ repo: z2.string().min(1),
1467
+ workflowId: z2.number().optional(),
1468
+ workflowPath: z2.string().min(1).optional(),
1469
+ workflowRunId: z2.number().optional()
1436
1470
  }).strict();
1471
+ function canonicalDeploymentFields(data) {
1472
+ return {
1473
+ action: data.action,
1474
+ commitSha: data.deployment.sha,
1475
+ createdAt: data.deployment.created_at,
1476
+ deploymentId: data.deployment.id,
1477
+ environment: data.deployment.environment,
1478
+ repo: data.repository.full_name,
1479
+ workflowId: data.workflow?.id,
1480
+ workflowPath: data.workflow?.path,
1481
+ workflowRunId: data.workflow_run?.id
1482
+ };
1483
+ }
1437
1484
  function parseDeploymentEvent(body) {
1438
1485
  const parsed = deploymentWebhookSchema.safeParse(body);
1439
1486
  if (!parsed.success) return void 0;
1440
- return canonicalDeploymentEventSchema.parse({
1441
- action: parsed.data.action,
1442
- commitSha: parsed.data.deployment.sha,
1443
- createdAt: parsed.data.deployment.created_at,
1444
- deploymentId: parsed.data.deployment.id,
1445
- environment: parsed.data.deployment.environment,
1446
- repo: parsed.data.repository.full_name
1447
- });
1487
+ return canonicalDeploymentEventSchema.parse(
1488
+ canonicalDeploymentFields(parsed.data)
1489
+ );
1448
1490
  }
1449
1491
  function normalizeDeploymentEvent(deliveryId, body) {
1450
1492
  const parsed = parseDeploymentEvent(body);
1451
1493
  if (!parsed || parsed.action !== "created") return [];
1452
1494
  const eventType = "deployment.created";
1453
- return deploymentSourceTargets(parsed).map(({ resource }) => ({
1495
+ const { label } = gitHubDeploymentSourceResource(parsed);
1496
+ return deploymentTargets(parsed).map(({ identifier }) => ({
1454
1497
  eventKey: gitHubEventKey2(deliveryId, eventType),
1455
1498
  eventType,
1456
1499
  occurredAtMs: providerTime(parsed.createdAt) ?? Date.now(),
1457
- identifier: resource.identifier,
1458
- trustedSummary: `${resource.label} was created (deployment ${parsed.deploymentId}).`
1500
+ identifier,
1501
+ trustedSummary: `${label} was created (deployment ${parsed.deploymentId}).`,
1502
+ data: deploymentEventData(parsed)
1459
1503
  }));
1460
1504
  }
1461
- var deploymentStatusWebhookSchema = z2.object({
1462
- action: z2.string(),
1463
- deployment: deploymentSchema,
1505
+ var deploymentStatusWebhookSchema = deploymentWebhookSchema.extend({
1464
1506
  deployment_status: z2.object({
1465
1507
  created_at: z2.string().optional(),
1466
1508
  description: z2.string().optional().nullable(),
1467
1509
  state: z2.string()
1468
- }).passthrough(),
1469
- repository: repositorySchema2
1470
- }).passthrough();
1510
+ }).passthrough()
1511
+ });
1471
1512
  var canonicalDeploymentStatusEventSchema = canonicalDeploymentEventSchema.extend({
1472
1513
  description: z2.string().optional().nullable(),
1473
1514
  state: z2.string(),
@@ -1477,13 +1518,8 @@ function parseDeploymentStatusEvent(body) {
1477
1518
  const parsed = deploymentStatusWebhookSchema.safeParse(body);
1478
1519
  if (!parsed.success) return void 0;
1479
1520
  return canonicalDeploymentStatusEventSchema.parse({
1480
- action: parsed.data.action,
1481
- commitSha: parsed.data.deployment.sha,
1482
- createdAt: parsed.data.deployment.created_at,
1483
- deploymentId: parsed.data.deployment.id,
1521
+ ...canonicalDeploymentFields(parsed.data),
1484
1522
  description: parsed.data.deployment_status.description,
1485
- environment: parsed.data.deployment.environment,
1486
- repo: parsed.data.repository.full_name,
1487
1523
  state: parsed.data.deployment_status.state,
1488
1524
  statusCreatedAt: parsed.data.deployment_status.created_at
1489
1525
  });
@@ -1511,30 +1547,44 @@ function normalizeDeploymentStatusEvent(deliveryId, body) {
1511
1547
  if (!eventType) return [];
1512
1548
  const outcome = eventType === "deployment.succeeded" ? "succeeded" : eventType === "deployment.failed" ? "failed" : eventType === "deployment.error" ? "reported an error" : eventType === "deployment.in_progress" ? "started" : `is ${parsed.state}`;
1513
1549
  const terminal = eventType === "deployment.succeeded" || eventType === "deployment.failed" || eventType === "deployment.error";
1514
- return deploymentSourceTargets(parsed).map(
1515
- ({ completeOnTerminalEvent, resource }) => ({
1550
+ const { label } = gitHubDeploymentSourceResource(parsed);
1551
+ return deploymentTargets(parsed).map(
1552
+ ({ completeOnTerminalEvent, identifier }) => ({
1516
1553
  eventKey: gitHubEventKey2(deliveryId, eventType),
1517
1554
  eventType,
1518
1555
  occurredAtMs: providerTime(parsed.statusCreatedAt) ?? Date.now(),
1519
- identifier: resource.identifier,
1556
+ identifier,
1520
1557
  ...terminal && completeOnTerminalEvent ? { terminal: true } : void 0,
1521
- trustedSummary: `${resource.label} ${outcome} (deployment ${parsed.deploymentId}).`,
1558
+ trustedSummary: `${label} ${outcome} (deployment ${parsed.deploymentId}).`,
1559
+ data: deploymentEventData(parsed),
1522
1560
  untrustedText: parsed.description ?? void 0
1523
1561
  })
1524
1562
  );
1525
1563
  }
1526
- function deploymentSourceTargets(input) {
1564
+ function deploymentEventData(input) {
1565
+ return {
1566
+ environment: input.environment.toLowerCase(),
1567
+ ...input.workflowId === void 0 ? void 0 : { workflowId: input.workflowId },
1568
+ ...input.workflowPath ? { workflowPath: input.workflowPath } : void 0,
1569
+ ...input.workflowRunId === void 0 ? void 0 : { workflowRunId: input.workflowRunId }
1570
+ };
1571
+ }
1572
+ function deploymentTargets(input) {
1527
1573
  return [
1528
1574
  {
1529
1575
  completeOnTerminalEvent: true,
1530
- resource: gitHubDeploymentSourceResource(input)
1576
+ identifier: gitHubDeploymentSourceResource(input).identifier
1531
1577
  },
1532
1578
  {
1533
1579
  completeOnTerminalEvent: false,
1534
- resource: gitHubDeploymentSourceResource({
1580
+ identifier: gitHubDeploymentSourceResource({
1535
1581
  commitSha: input.commitSha,
1536
1582
  repo: input.repo
1537
- })
1583
+ }).identifier
1584
+ },
1585
+ {
1586
+ completeOnTerminalEvent: false,
1587
+ identifier: gitHubRepositoryResource({ repo: input.repo }).identifier
1538
1588
  }
1539
1589
  ];
1540
1590
  }
@@ -2028,6 +2078,7 @@ export {
2028
2078
  gitHubIssueSubscribable,
2029
2079
  GITHUB_DEPLOYMENT_EVENTS,
2030
2080
  GITHUB_DEPLOYMENT_SUGGESTED_EVENTS,
2081
+ GITHUB_DEPLOYMENT_MATCH_FIELDS,
2031
2082
  GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER,
2032
2083
  gitHubDeploymentSourceSubscribable,
2033
2084
  GITHUB_PULL_REQUEST_EVENTS,
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Return a redirect message when a bash command clones a GitHub repository
3
+ * without `github_cloneRepository`. Return undefined for other commands.
4
+ */
5
+ export declare function githubCloneCommandRedirect(command: string): string | undefined;
@@ -6,6 +6,12 @@
6
6
  */
7
7
  import { type EgressHookContext, type EgressResponseHookContext } from "@sentry/junior-plugin-api";
8
8
  import { type GitHubGrant } from "./credential-support.js";
9
- export declare function githubGraphqlPermissionDeniedMessage(bodyText: string): string | undefined;
10
- export declare function shouldInspectGitHubGraphqlResponse(ctx: EgressResponseHookContext): boolean;
9
+ /**
10
+ * Classify a GitHub response as a permission denial.
11
+ *
12
+ * Returns a message only when GitHub says that the credential lacks access.
13
+ * Other GitHub refusals return undefined, so the runtime does not call them
14
+ * permission problems.
15
+ */
16
+ export declare function githubPermissionDeniedMessage(ctx: EgressResponseHookContext): Promise<string | undefined>;
11
17
  export declare function githubGrantForEgress(ctx: EgressHookContext): Promise<GitHubGrant>;
@@ -1,6 +1,12 @@
1
- import type { SubscribableResource } from "@sentry/junior-plugin-api";
1
+ import { type SubscribableResource } from "@sentry/junior-plugin-api";
2
2
  export declare const GITHUB_DEPLOYMENT_EVENTS: readonly ["deployment.created", "deployment.queued", "deployment.pending", "deployment.in_progress", "deployment.succeeded", "deployment.failed", "deployment.error"];
3
3
  export declare const GITHUB_DEPLOYMENT_SUGGESTED_EVENTS: string[];
4
+ /** Trusted deployment values that watches and event automations can match. */
5
+ export declare const GITHUB_DEPLOYMENT_MATCH_FIELDS: Record<string, {
6
+ kind: "boolean" | "number" | "string";
7
+ description: string;
8
+ enum?: string[] | undefined;
9
+ }>;
4
10
  /** The identifier shape that `gitHubDeploymentSourceResource` builds. */
5
11
  export declare const GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER: {
6
12
  format: string;
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  GITHUB_AUTH_TOKEN_ENV,
6
6
  GITHUB_AUTH_TOKEN_PLACEHOLDER,
7
7
  GITHUB_DEPLOYMENT_EVENTS,
8
+ GITHUB_DEPLOYMENT_MATCH_FIELDS,
8
9
  GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER,
9
10
  GITHUB_DEPLOYMENT_SUGGESTED_EVENTS,
10
11
  GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES,
@@ -50,7 +51,7 @@ import {
50
51
  readGrantPermissions,
51
52
  requireEnv,
52
53
  resolveUserAccount
53
- } from "./chunk-3PD7XTQH.js";
54
+ } from "./chunk-VEN7LFRI.js";
54
55
 
55
56
  // src/plugin.ts
56
57
  import {
@@ -87,12 +88,13 @@ var inputSchema = z.object({
87
88
  "Optional destination directory under the sandbox root. Defaults to repos/{name}."
88
89
  ).optional(),
89
90
  allowAdHoc: z.boolean().optional().describe(
90
- "Set true to keep an intentional ad-hoc checkout when matching Workspaces exist. Prefer switchWorkspace; the checkout is already present after a successful switch."
91
+ "Set true in the default Sandbox to keep an intentional ad-hoc checkout when matching Workspaces exist. Prefer switchWorkspace; the checkout is already present after a successful switch."
91
92
  )
92
93
  }).strict();
93
94
  var cloneSchema = z.object({
94
95
  path: z.string(),
95
- repo: z.string()
96
+ repo: z.string(),
97
+ note: z.string().optional()
96
98
  });
97
99
  var outputSchema = pluginToolOutputSchema.merge(
98
100
  cloneSchema.extend({
@@ -106,8 +108,11 @@ function parseRepo(value) {
106
108
  }
107
109
  return { owner: parts[0], name: parts[1] };
108
110
  }
111
+ function quotedNames(workspaces) {
112
+ return workspaces.map((name) => `"${name}"`).join(", ");
113
+ }
109
114
  function workspaceRequiredError(repoId, workspaces) {
110
- const names = workspaces.map((name) => `"${name}"`).join(", ");
115
+ const names = quotedNames(workspaces);
111
116
  if (workspaces.length === 1) {
112
117
  return new PluginToolInputError(
113
118
  `Repository ${repoId} is part of Workspace ${names}. Call switchWorkspace with that name; the checkout is already present after the switch. Pass allowAdHoc=true only for an intentional ad-hoc checkout.`
@@ -117,6 +122,11 @@ function workspaceRequiredError(repoId, workspaces) {
117
122
  `Repository ${repoId} is part of Workspaces ${names}. Call switchWorkspace with one of those names; the checkout is already present after the switch. Pass allowAdHoc=true only for an intentional ad-hoc checkout.`
118
123
  );
119
124
  }
125
+ function workspaceAvailableNote(repoId, active, workspaces) {
126
+ const current = active.name ? `the current Workspace "${active.name}"` : "the current Workspace";
127
+ const matches = workspaces.length === 1 ? `Workspace ${quotedNames(workspaces)} also includes` : `Workspaces ${quotedNames(workspaces)} also include`;
128
+ return `Cloned ${repoId} ad hoc to keep ${current}. ${matches} ${repoId}. switchWorkspace replaces this Sandbox and drops its files.`;
129
+ }
120
130
  function defaultDirectory(repoName) {
121
131
  return `repos/${repoName}`;
122
132
  }
@@ -156,7 +166,7 @@ function createGitHubCloneRepositoryTool(ctx) {
156
166
  openWorldHint: true,
157
167
  readOnlyHint: true
158
168
  },
159
- description: "Clone a GitHub repository into the sandbox as an ad-hoc checkout. The destination must not already exist. When matching Workspaces exist this is a tool input error: call switchWorkspace instead, or pass allowAdHoc=true for an intentional ad-hoc checkout.",
169
+ description: "Clone a GitHub repository into the sandbox as an ad-hoc checkout. The destination must not already exist. In the default Sandbox, a matching Workspace is a tool input error: call switchWorkspace instead, or pass allowAdHoc=true for an intentional ad-hoc checkout. Inside a Workspace, the clone proceeds and the result notes matching Workspaces.",
160
170
  describeProposal(input) {
161
171
  const directory = typeof input.directory === "string" && input.directory.length > 0 ? input.directory : void 0;
162
172
  const adHoc = input.allowAdHoc === true ? " as an intentional ad-hoc checkout" : "";
@@ -169,20 +179,28 @@ function createGitHubCloneRepositoryTool(ctx) {
169
179
  const repo = parseRepo(input.repo);
170
180
  const repoId = `${repo.owner}/${repo.name}`;
171
181
  let workspaces = [];
182
+ let active;
172
183
  try {
173
- workspaces = await ctx.workspaces.findByRepository({
174
- provider: "github",
175
- repo: repoId
176
- });
184
+ [workspaces, active] = await Promise.all([
185
+ ctx.workspaces.findByRepository({
186
+ provider: "github",
187
+ repo: repoId
188
+ }),
189
+ ctx.workspaces.active()
190
+ ]);
177
191
  } catch (error) {
178
192
  ctx.log.error("github.clone.workspaces_lookup.failed", {
179
193
  repo: repoId,
180
194
  error: error instanceof Error ? error.message : String(error)
181
195
  });
182
196
  }
183
- if (workspaces.length > 0 && input.allowAdHoc !== true) {
197
+ if (workspaces.length > 0 && !active && input.allowAdHoc !== true) {
184
198
  throw workspaceRequiredError(repoId, workspaces);
185
199
  }
200
+ const otherWorkspaces = workspaces.filter(
201
+ (name) => name !== active?.name
202
+ );
203
+ const note = active && otherWorkspaces.length > 0 ? workspaceAvailableNote(repoId, active, otherWorkspaces) : void 0;
186
204
  const directory = input.directory ?? defaultDirectory(repo.name);
187
205
  const rootSegment = directory.split("/")[0] ?? directory;
188
206
  if (isReservedSandboxDirectory(rootSegment)) {
@@ -239,7 +257,12 @@ function createGitHubCloneRepositoryTool(ctx) {
239
257
  `GitHub repository clone failed: ${clone.stderr.trim() || `exit ${clone.exitCode}`}`
240
258
  );
241
259
  }
242
- return { target: "cloneRepository", repo: repoId, path };
260
+ return {
261
+ target: "cloneRepository",
262
+ repo: repoId,
263
+ path,
264
+ ...note ? { note } : void 0
265
+ };
243
266
  }
244
267
  });
245
268
  }
@@ -3528,8 +3551,51 @@ function normalizeGitHubPullRequestLinkedIssues(args) {
3528
3551
  } : void 0;
3529
3552
  }
3530
3553
 
3531
- // src/webhooks/pull-request-people.ts
3554
+ // src/webhooks/pull-request-author-role.ts
3532
3555
  import { z as z19 } from "zod";
3556
+ var AUTHOR_ROLE_MATCH_KEY = "authorRole";
3557
+ var webhookSchema = z19.object({
3558
+ repository: z19.object({ full_name: z19.string().min(1) })
3559
+ });
3560
+ async function withGitHubPullRequestAuthorRole(args) {
3561
+ const { neededMatchKeys } = args;
3562
+ const authored = args.events.filter(
3563
+ (event) => typeof event.data?.authorUsername === "string"
3564
+ );
3565
+ const parsed = webhookSchema.safeParse(args.body);
3566
+ if (authored.length === 0 || !neededMatchKeys || !args.load || !parsed.success) {
3567
+ return args.events;
3568
+ }
3569
+ const keys = await neededMatchKeys({
3570
+ eventTypes: [...new Set(authored.map((event) => event.eventType))],
3571
+ identifiers: [...new Set(authored.map((event) => event.identifier))]
3572
+ });
3573
+ if (!keys.includes(AUTHOR_ROLE_MATCH_KEY)) return args.events;
3574
+ const repositoryFullName = parsed.data.repository.full_name;
3575
+ const logins = new Set(
3576
+ authored.map((event) => event.data.authorUsername)
3577
+ );
3578
+ const roles = /* @__PURE__ */ new Map();
3579
+ for (const login of logins) {
3580
+ try {
3581
+ roles.set(login, await args.load({ login, repositoryFullName }));
3582
+ } catch (error) {
3583
+ args.log?.error("GitHub pull request author role lookup failed", {
3584
+ deliveryId: args.deliveryId,
3585
+ errorType: error instanceof Error ? error.name : "UnknownError",
3586
+ repository: repositoryFullName
3587
+ });
3588
+ }
3589
+ }
3590
+ return args.events.map((event) => {
3591
+ const login = event.data?.authorUsername;
3592
+ const role = typeof login === "string" ? roles.get(login) : void 0;
3593
+ return role ? { ...event, data: { ...event.data, [AUTHOR_ROLE_MATCH_KEY]: role } } : event;
3594
+ });
3595
+ }
3596
+
3597
+ // src/webhooks/pull-request-people.ts
3598
+ import { z as z20 } from "zod";
3533
3599
  var PEOPLE_EVENTS = /* @__PURE__ */ new Set([
3534
3600
  "pull_request.review.approved",
3535
3601
  "pull_request.merged"
@@ -3539,18 +3605,18 @@ var PAGE_SIZE = 100;
3539
3605
  var MAX_PAGES = 3;
3540
3606
  var CO_AUTHOR_TRAILER = /^co-authored-by:[^<\n]*<([^>\s]+@[^>\s]+)>\s*$/gim;
3541
3607
  var GITHUB_NOREPLY_EMAIL = /^(?:\d+\+)?(?<login>[^@+]+)@users\.noreply\.github\.com$/i;
3542
- var webhookSchema = z19.object({
3543
- pull_request: z19.object({
3544
- assignees: z19.array(z19.object({ login: z19.string().min(1) })).nullish(),
3545
- number: z19.number(),
3546
- user: z19.object({ login: z19.string().min(1) }).nullish()
3608
+ var webhookSchema2 = z20.object({
3609
+ pull_request: z20.object({
3610
+ assignees: z20.array(z20.object({ login: z20.string().min(1) })).nullish(),
3611
+ number: z20.number(),
3612
+ user: z20.object({ login: z20.string().min(1) }).nullish()
3547
3613
  }),
3548
- repository: z19.object({ full_name: z19.string().min(1) })
3614
+ repository: z20.object({ full_name: z20.string().min(1) })
3549
3615
  });
3550
- var commitPageSchema = z19.array(
3551
- z19.object({
3552
- author: z19.object({ login: z19.string().min(1) }).nullish(),
3553
- commit: z19.object({ message: z19.string() })
3616
+ var commitPageSchema = z20.array(
3617
+ z20.object({
3618
+ author: z20.object({ login: z20.string().min(1) }).nullish(),
3619
+ commit: z20.object({ message: z20.string() })
3554
3620
  })
3555
3621
  );
3556
3622
  async function loadGitHubPullRequestPeople(args) {
@@ -3589,7 +3655,7 @@ async function withGitHubPullRequestPeople(args) {
3589
3655
  const peopleEvents = args.events.filter(
3590
3656
  (event) => PEOPLE_EVENTS.has(event.eventType)
3591
3657
  );
3592
- const parsed = webhookSchema.safeParse(args.body);
3658
+ const parsed = webhookSchema2.safeParse(args.body);
3593
3659
  if (peopleEvents.length === 0 || !hasMatch || !args.load || !parsed.success) {
3594
3660
  return args.events;
3595
3661
  }
@@ -3820,12 +3886,19 @@ function createGitHubWebhookRoute(args) {
3820
3886
  const events = await withGitHubPullRequestPeople({
3821
3887
  body,
3822
3888
  deliveryId,
3823
- events: normalizeGitHubEvents({
3889
+ events: await withGitHubPullRequestAuthorRole({
3824
3890
  body,
3825
- botEmail,
3826
- ...checkSuiteFacts ? { checkSuiteFacts } : void 0,
3827
3891
  deliveryId,
3828
- eventName
3892
+ events: normalizeGitHubEvents({
3893
+ body,
3894
+ botEmail,
3895
+ ...checkSuiteFacts ? { checkSuiteFacts } : void 0,
3896
+ deliveryId,
3897
+ eventName
3898
+ }),
3899
+ load: args.loadAuthorRole,
3900
+ log: args.log,
3901
+ neededMatchKeys: args.events.neededMatchKeys
3829
3902
  }),
3830
3903
  hasMatch,
3831
3904
  load: args.loadPullRequestPeople,
@@ -3862,6 +3935,7 @@ function createGitHubWebhookRoute(args) {
3862
3935
  }
3863
3936
 
3864
3937
  // src/webhooks/installation-requests.ts
3938
+ import { z as z21 } from "zod";
3865
3939
  function splitRepository(fullName, label) {
3866
3940
  const [owner, name, ...extra] = fullName.split("/");
3867
3941
  if (!owner || !name || extra.length > 0) {
@@ -3906,20 +3980,52 @@ async function markPullRequestFeedbackReviewing(env, target) {
3906
3980
  }
3907
3981
  );
3908
3982
  }
3983
+ var repositoryPermissionSchema = z21.object({
3984
+ permission: z21.string().min(1),
3985
+ role_name: z21.string().optional()
3986
+ });
3987
+ var REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1e3;
3988
+ async function loadRepositoryRole(env, cache, target) {
3989
+ const { owner, name } = splitRepository(
3990
+ target.repositoryFullName,
3991
+ "repository role"
3992
+ );
3993
+ return await cache.getOrLoad(
3994
+ `repository-role:${owner}/${name}:${target.login}`.toLowerCase(),
3995
+ async () => {
3996
+ const token = await issueInstallationToken({
3997
+ ...env,
3998
+ permissions: { metadata: "read" },
3999
+ repositories: [name]
4000
+ });
4001
+ const response = repositoryPermissionSchema.parse(
4002
+ await githubRequest(
4003
+ "https://api.github.com",
4004
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/collaborators/${encodeURIComponent(target.login)}/permission`,
4005
+ { token: token.token }
4006
+ )
4007
+ );
4008
+ return {
4009
+ value: response.role_name?.trim() || response.permission,
4010
+ ttlMs: REPOSITORY_ROLE_TTL_MS
4011
+ };
4012
+ }
4013
+ );
4014
+ }
3909
4015
 
3910
4016
  // src/pull-request-outcomes/commit-composition.ts
3911
- import { z as z20 } from "zod";
3912
- var canonicalCommitSchema = z20.object({
3913
- authorEmail: z20.string().nullable(),
3914
- authorLogin: z20.string().nullable()
4017
+ import { z as z22 } from "zod";
4018
+ var canonicalCommitSchema = z22.object({
4019
+ authorEmail: z22.string().nullable(),
4020
+ authorLogin: z22.string().nullable()
3915
4021
  }).strict();
3916
- var providerCommitSchema = z20.object({
3917
- author: z20.object({ login: z20.string() }).passthrough().nullable(),
3918
- commit: z20.object({
3919
- author: z20.object({ email: z20.string() }).passthrough().nullable()
4022
+ var providerCommitSchema = z22.object({
4023
+ author: z22.object({ login: z22.string() }).passthrough().nullable(),
4024
+ commit: z22.object({
4025
+ author: z22.object({ email: z22.string() }).passthrough().nullable()
3920
4026
  }).passthrough()
3921
4027
  }).passthrough();
3922
- var commitPageSchema2 = z20.array(providerCommitSchema).transform(
4028
+ var commitPageSchema2 = z22.array(providerCommitSchema).transform(
3923
4029
  (commits) => commits.map(
3924
4030
  (commit) => canonicalCommitSchema.parse({
3925
4031
  authorEmail: commit.commit.author?.email ?? null,
@@ -4600,6 +4706,38 @@ async function prepareWorkspace(ctx) {
4600
4706
  };
4601
4707
  }
4602
4708
 
4709
+ // src/clone-command.ts
4710
+ import { parseShellCommands } from "@sentry/junior-plugin-api";
4711
+ var CLONE_REDIRECT_MESSAGE = "Use github_cloneRepository to clone GitHub repositories, not git clone or gh repo clone. It checks for a matching Workspace first.";
4712
+ var GIT_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-C", "-c"]);
4713
+ function githubCloneCommandRedirect(command) {
4714
+ return parseShellCommands(command).some(isGitHubClone) ? CLONE_REDIRECT_MESSAGE : void 0;
4715
+ }
4716
+ function isGitHubClone([program, ...args]) {
4717
+ if (program === "gh") {
4718
+ return args[0] === "repo" && (args[1] === "clone" || args[1] === "fork" && args.some((arg) => arg === "--clone" || arg === "--clone=true"));
4719
+ }
4720
+ if (program !== "git") {
4721
+ return false;
4722
+ }
4723
+ let index2 = 0;
4724
+ while (args[index2]?.startsWith("-")) {
4725
+ index2 += GIT_OPTIONS_WITH_VALUE.has(args[index2]) ? 2 : 1;
4726
+ }
4727
+ return args[index2] === "clone" && args.slice(index2 + 1).some(isGitHubRemote);
4728
+ }
4729
+ function isGitHubRemote(arg) {
4730
+ const scpHost = /^[^@/:]+@([^/:]+):/.exec(arg)?.[1];
4731
+ if (scpHost) {
4732
+ return scpHost.toLowerCase() === "github.com";
4733
+ }
4734
+ try {
4735
+ return new URL(arg).hostname.toLowerCase() === "github.com";
4736
+ } catch {
4737
+ return false;
4738
+ }
4739
+ }
4740
+
4603
4741
  // src/egress-policy.ts
4604
4742
  import {
4605
4743
  EgressPolicyDenied as EgressPolicyDenied2,
@@ -4812,6 +4950,50 @@ function shouldInspectGitHubGraphqlResponse(ctx) {
4812
4950
  const contentType = ctx.response.headers.get("content-type");
4813
4951
  return contentType ? /\bjson\b/i.test(contentType) : false;
4814
4952
  }
4953
+ var GITHUB_ERROR_BODY_LIMIT_BYTES = 4 * 1024;
4954
+ var GITHUB_ACCESS_DENIED_MESSAGE = "Resource not accessible by integration";
4955
+ var GITHUB_ACCEPTED_PERMISSIONS_PATTERN = /^[a-z_]+=[a-z]+(?:\s*[,;]\s*[a-z_]+=[a-z]+)*$/;
4956
+ function githubErrorMessage(bodyText) {
4957
+ if (!bodyText) {
4958
+ return void 0;
4959
+ }
4960
+ try {
4961
+ const parsed = JSON.parse(bodyText);
4962
+ return isRecord(parsed) && typeof parsed.message === "string" ? parsed.message.trim() : void 0;
4963
+ } catch {
4964
+ return void 0;
4965
+ }
4966
+ }
4967
+ async function githubForbiddenPermissionDeniedMessage(ctx) {
4968
+ const sso = ctx.response.headers.get("x-github-sso");
4969
+ if (sso?.startsWith("required")) {
4970
+ const url = sso.match(/\burl=(https:\/\/github\.com\/\S+)/)?.[1];
4971
+ return `GitHub requires SAML SSO authorization for this credential.${url ? ` Authorize it at ${url}` : ""}`;
4972
+ }
4973
+ const message = githubErrorMessage(
4974
+ await ctx.response.readText(GITHUB_ERROR_BODY_LIMIT_BYTES)
4975
+ );
4976
+ if (message !== GITHUB_ACCESS_DENIED_MESSAGE) {
4977
+ return void 0;
4978
+ }
4979
+ const accepted = ctx.response.headers.get("x-accepted-github-permissions")?.trim();
4980
+ return [
4981
+ `GitHub denied access: ${message}.`,
4982
+ ...accepted && GITHUB_ACCEPTED_PERMISSIONS_PATTERN.test(accepted) ? [`This endpoint accepts these GitHub permissions: ${accepted}.`] : []
4983
+ ].join(" ");
4984
+ }
4985
+ async function githubPermissionDeniedMessage(ctx) {
4986
+ if (ctx.response.status === 403) {
4987
+ return await githubForbiddenPermissionDeniedMessage(ctx);
4988
+ }
4989
+ if (!shouldInspectGitHubGraphqlResponse(ctx)) {
4990
+ return void 0;
4991
+ }
4992
+ const bodyText = await ctx.response.readText(
4993
+ GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES
4994
+ );
4995
+ return bodyText ? githubGraphqlPermissionDeniedMessage(bodyText) : void 0;
4996
+ }
4815
4997
  var PULL_REQUEST_COMMENT_REACTIONS_PATH = /^\/repos\/[^/]+\/[^/]+\/(issues|pulls)\/comments\/[^/]+\/reactions(?:\/[^/]+)?$/;
4816
4998
  var GITHUB_BODY_WRITES = [
4817
4999
  {
@@ -5095,7 +5277,8 @@ function githubPlugin(options = {}) {
5095
5277
  type: "deployment_source",
5096
5278
  identifier: GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER,
5097
5279
  supportedEvents: [...GITHUB_DEPLOYMENT_EVENTS],
5098
- suggestedEvents: [...GITHUB_DEPLOYMENT_SUGGESTED_EVENTS]
5280
+ suggestedEvents: [...GITHUB_DEPLOYMENT_SUGGESTED_EVENTS],
5281
+ matchFields: GITHUB_DEPLOYMENT_MATCH_FIELDS
5099
5282
  },
5100
5283
  {
5101
5284
  type: "issue",
@@ -5124,6 +5307,7 @@ function githubPlugin(options = {}) {
5124
5307
  type: "repository",
5125
5308
  identifier: GITHUB_REPOSITORY_IDENTIFIER,
5126
5309
  supportedEvents: [
5310
+ ...GITHUB_DEPLOYMENT_EVENTS,
5127
5311
  ...GITHUB_ISSUE_EVENTS,
5128
5312
  ...GITHUB_PULL_REQUEST_EVENTS
5129
5313
  ],
@@ -5134,6 +5318,7 @@ function githubPlugin(options = {}) {
5134
5318
  ...GITHUB_PULL_REQUEST_SUGGESTED_EVENTS
5135
5319
  ],
5136
5320
  matchFields: {
5321
+ ...GITHUB_DEPLOYMENT_MATCH_FIELDS,
5137
5322
  ...GITHUB_ISSUE_COMMENT_MATCH_FIELDS,
5138
5323
  ...GITHUB_PULL_REQUEST_MATCH_FIELDS
5139
5324
  },
@@ -5286,6 +5471,7 @@ function githubPlugin(options = {}) {
5286
5471
  db: ctx.db,
5287
5472
  installationId: () => readEnv(installationIdEnv),
5288
5473
  installationIdEnv,
5474
+ loadAuthorRole: async (target) => await loadRepositoryRole(installationEnv, ctx.cache, target),
5289
5475
  loadPullRequestPeople: async (pullRequest) => await loadGitHubPullRequestPeople({
5290
5476
  logins: pullRequest.logins,
5291
5477
  loadPage: await loadPullRequestCommitPages(
@@ -5325,6 +5511,11 @@ function githubPlugin(options = {}) {
5325
5511
  if (ctx.tool.name !== "bash") {
5326
5512
  return;
5327
5513
  }
5514
+ const cloneRedirect = typeof ctx.tool.input.command === "string" ? githubCloneCommandRedirect(ctx.tool.input.command) : void 0;
5515
+ if (cloneRedirect) {
5516
+ ctx.decision.redirect(cloneRedirect);
5517
+ return;
5518
+ }
5328
5519
  const botName = requireEnv(botNameEnv);
5329
5520
  const botEmail = requireEnv(botEmailEnv);
5330
5521
  ctx.env.set("GIT_AUTHOR_NAME", botName);
@@ -5355,16 +5546,13 @@ function githubPlugin(options = {}) {
5355
5546
  return githubGrantForEgress(ctx);
5356
5547
  },
5357
5548
  async onEgressResponse(ctx) {
5358
- if (!shouldInspectGitHubGraphqlResponse(ctx)) {
5359
- return;
5360
- }
5361
- const bodyText = await ctx.response.readText(
5362
- GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES
5363
- );
5364
- if (!bodyText) {
5365
- return;
5549
+ if (ctx.response.status === 403) {
5550
+ ctx.log.warn("github.egress.upstream_forbidden", {
5551
+ "app.github.accepted_permissions": ctx.response.headers.get("x-accepted-github-permissions") ?? void 0,
5552
+ "app.github.sso": ctx.response.headers.get("x-github-sso") ?? void 0
5553
+ });
5366
5554
  }
5367
- const message = githubGraphqlPermissionDeniedMessage(bodyText);
5555
+ const message = await githubPermissionDeniedMessage(ctx);
5368
5556
  if (message) {
5369
5557
  ctx.permissionDenied(message);
5370
5558
  }
package/dist/testing.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  normalizeGitHubEvents
3
- } from "./chunk-3PD7XTQH.js";
3
+ } from "./chunk-VEN7LFRI.js";
4
4
  export {
5
5
  normalizeGitHubEvents
6
6
  };
@@ -65,6 +65,7 @@ export declare function createGitHubCloneRepositoryTool(ctx: {
65
65
  } | undefined;
66
66
  path: string;
67
67
  repo: string;
68
+ note?: string | undefined;
68
69
  target: "cloneRepository";
69
70
  }, {
70
71
  objectAnnotations?: {
@@ -123,5 +124,6 @@ export declare function createGitHubCloneRepositoryTool(ctx: {
123
124
  } | undefined;
124
125
  path: string;
125
126
  repo: string;
127
+ note?: string | undefined;
126
128
  target: "cloneRepository";
127
129
  }>;
@@ -1,6 +1,7 @@
1
1
  import type { CodeChangePublisher, PluginConversationAnnotations, PluginLogger, PluginRoute, EventPerson, EventPublisher } from "@sentry/junior-plugin-api";
2
2
  import type { GitHubDb } from "../db/database.js";
3
3
  import type { GitHubPullRequestCommitComposition } from "../db/schema.js";
4
+ import { type GitHubAuthorRoleTarget } from "./pull-request-author-role.js";
4
5
  import { type GitHubPullRequestPeopleTarget } from "./pull-request-people.js";
5
6
  interface FeedbackTarget {
6
7
  commentId: number;
@@ -20,6 +21,8 @@ export declare function createGitHubWebhookRoute(args: {
20
21
  db: GitHubDb;
21
22
  installationId(): string | undefined;
22
23
  installationIdEnv: string;
24
+ /** Load a pull request author's repository role for `authorRole` filters. */
25
+ loadAuthorRole?(target: GitHubAuthorRoleTarget): Promise<string>;
23
26
  /** Load the people involved in a pull request for approvals and merges. */
24
27
  loadPullRequestPeople?(target: GitHubPullRequestPeopleTarget): Promise<EventPerson[]>;
25
28
  log?: Pick<PluginLogger, "error">;
@@ -1,3 +1,10 @@
1
+ /**
2
+ * GitHub requests that webhook handling makes with installation tokens.
3
+ *
4
+ * A webhook delivery has no Turn and no egress context, so these requests
5
+ * call GitHub directly. Other plugin code must use host egress.
6
+ */
7
+ import type { PluginCache } from "@sentry/junior-plugin-api";
1
8
  /** Environment variable names for the GitHub App installation. */
2
9
  export interface GitHubInstallationEnv {
3
10
  appIdEnv: string;
@@ -15,3 +22,12 @@ export declare function markPullRequestFeedbackReviewing(env: GitHubInstallation
15
22
  commentKind: "conversation" | "review";
16
23
  repo: string;
17
24
  }): Promise<void>;
25
+ /**
26
+ * Read one user's role on a repository, with a metadata-only token. GitHub
27
+ * returns "none" for accounts without access, such as most bots. Roles are
28
+ * cached for ten minutes.
29
+ */
30
+ export declare function loadRepositoryRole(env: GitHubInstallationEnv, cache: PluginCache, target: {
31
+ login: string;
32
+ repositoryFullName: string;
33
+ }): Promise<string>;
@@ -0,0 +1,20 @@
1
+ import type { EventInput, EventPublisher, PluginLogger } from "@sentry/junior-plugin-api";
2
+ /** The author whose repository role a lookup reads. */
3
+ export interface GitHubAuthorRoleTarget {
4
+ login: string;
5
+ repositoryFullName: string;
6
+ }
7
+ /**
8
+ * Add the author's repository role to events that name a pull request author.
9
+ * It loads the role only when a Watch or event automation filters on
10
+ * `authorRole`, so other deliveries make no extra GitHub calls. A failed load
11
+ * leaves the field out, so filters on it do not match.
12
+ */
13
+ export declare function withGitHubPullRequestAuthorRole(args: {
14
+ body: unknown;
15
+ deliveryId: string;
16
+ events: EventInput[];
17
+ load?(target: GitHubAuthorRoleTarget): Promise<string>;
18
+ log?: Pick<PluginLogger, "error">;
19
+ neededMatchKeys: EventPublisher["neededMatchKeys"];
20
+ }): Promise<EventInput[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/junior-github",
3
- "version": "0.261.0",
3
+ "version": "0.263.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -32,7 +32,7 @@
32
32
  "drizzle-orm": "^0.45.2",
33
33
  "marked": "^18.1.2",
34
34
  "zod": "^4.5.4",
35
- "@sentry/junior-plugin-api": "0.261.0"
35
+ "@sentry/junior-plugin-api": "0.263.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@oxlint/plugins": "1.79.0",
@@ -11,6 +11,7 @@ Guide evidence-first GitHub repository work from inspection through a reviewable
11
11
  - Treat shallow clones as inspection checkouts; deepen before history work; never force-push around missing ancestry.
12
12
  - Install dependencies with the lockfile frozen mode before verification when needed.
13
13
  - Finish completed edits with a pushed PR unless the user opts out; default draft.
14
+ - After each push to a branch with an open PR, check mergeability. Resolve conflicts without asking, by merging the PR base branch (usually the default branch). Never rebase for this. GitHub sends no event for a new conflict, and conflicted PRs get no new checks.
14
15
  - Write conventional PR titles and short plain-English bodies; keep check results out of the PR body.
15
16
  - Report exact validation and permission failures.
16
17
 
@@ -45,6 +45,7 @@ If the user omits `owner/repo`, run `jr-rpc config get github.repo`. Then pass `
45
45
  | Resolve review thread | `github_resolvePullRequestReviewThread` |
46
46
  | Inline review comment | `gh api repos/owner/repo/pulls/NUMBER/comments --method POST --input comment.json` |
47
47
  | View PR / checks | `gh pr view NUMBER --repo owner/repo` / `gh pr checks NUMBER --repo owner/repo` |
48
+ | PR mergeability | `gh pr view NUMBER --repo owner/repo --json mergeable,baseRefName` |
48
49
  | Diff PR | `gh pr diff NUMBER --repo owner/repo` |
49
50
  | List runs | `gh run list -R owner/repo --workflow WORKFLOW` |
50
51
  | View / watch run | `gh run view RUN_ID -R owner/repo` / `gh run watch RUN_ID -R owner/repo --exit-status` |
@@ -7,7 +7,7 @@
7
7
  | GraphQL cannot find the repository | Check `owner/repo` and the GitHub App installation. |
8
8
  | `junior-auth-required` with `user-write` | Follow the private OAuth prompt. Never ask for a pasted token. |
9
9
  | `git push` returns 401 or 403 | Check the remote and repository. Retry once, then report the installation access failure. |
10
- | `permission_denied` has `source: "upstream"` | GitHub rejected the request. Report the grant, account, or SSO details. |
10
+ | `permission_denied` has `source: "upstream"` | Read GitHub's error. Report an access problem only if it says access denied or SSO. |
11
11
  | Other 403 response | Read the error and use the tool it names. |
12
12
  | `gh auth status` shows no token scopes | This is normal for GitHub App user tokens. Check App permissions instead. |
13
13
  | `github_createPullRequest` returns 401 or 403 | Report the installation access failure. Do not use user OAuth. |
@@ -27,5 +27,5 @@
27
27
  - Retry a transport failure once after you check the repository.
28
28
  - Do not repeat 401, 403, 404, or validation failures.
29
29
  - A `user-read` or `user-write` failure needs private App OAuth.
30
- - An `installation-*` failure needs an App permission or installation fix.
30
+ - An `installation-*` access denial needs an App permission or installation fix.
31
31
  - Use structured `permission_denied` details when present.
@@ -34,6 +34,11 @@ Open this when making repository edits, not for read-only inspection.
34
34
  1. Reuse the current non-default branch or create a focused branch.
35
35
  2. Commit with repo conventions, else `<type>(<scope>): <Subject>` imperative present, no agent branding.
36
36
  3. Push with `git push -u origin BRANCH`.
37
+ If the branch has an open PR, check that it can merge. Do this after every push, including fixes for review feedback or failed checks. A conflicted PR gets no new checks, so no event shows it.
38
+ - Run `gh pr view NUMBER --repo owner/repo --json mergeable,baseRefName`.
39
+ - `UNKNOWN`: GitHub is still calculating it. Wait about 5 seconds and check again, up to 3 times. If it stays `UNKNOWN`, report that and continue.
40
+ - `CONFLICTING`: resolve it now. Do not ask first. GitHub checks mergeability against the PR base (`baseRefName`), which is usually the default branch. Fetch the base and merge `origin/BASE` into the PR branch. Do not rebase. Resolve each conflict so that both the PR change and the base branch change stay intact. Run the checks again, push, and check mergeability again.
41
+ - In the report, name the files that had conflicts and say how you resolved them.
37
42
  4. Resolve the actual default branch.
38
43
  5. Update an existing PR for the branch with `github_updatePullRequest`, or create with `github_createPullRequest` (`draft: true` only when work, checks, or decisions remain; otherwise ready for review).
39
44
  6. PR title matches the current dominant change, same conventional form as commits.
@@ -2,19 +2,19 @@
2
2
 
3
3
  Use this table to recover quickly while keeping operations deterministic.
4
4
 
5
- | Symptom | Likely cause | Fix |
6
- | ---------------------------------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
7
- | `unknown command "issue"` from `gh` | CLI version too old or wrong binary in the plugin runtime. | Verify `gh --version`; if it is unavailable or too old, report that the GitHub plugin runtime dependency is not available. |
8
- | `Missing required option --repo` | Repo not passed and no default was resolved. | Resolve with `jr-rpc config get github.repo`; pass `--repo owner/repo` explicitly when missing. |
9
- | Command affects or authenticates against the wrong repo | Stale `github.repo` default or authenticated command missing explicit repo. | Pass `--repo owner/repo` for the target repository, or update `github.repo` before retrying. |
10
- | `GraphQL: Could not resolve to a Repository` | Repo slug is wrong or inaccessible. | Validate `owner/repo` and confirm app installation on target repository. |
11
- | 401 Unauthorized | Issued GitHub credentials were rejected upstream. | Verify the target repo, then use the grant/auth signal to distinguish stale user OAuth from app installation or host env setup. |
12
- | `junior-auth-required provider=github grant=user-write` | User-to-server OAuth is missing or stale for a human-identity operation. | Follow the private OAuth prompt; do not ask the user to paste or manage tokens manually. |
13
- | 403 without `permission_denied` where `source: "upstream"` | The runtime may have rejected an unsupported route before contacting GitHub. | Read the response body. Follow any required-tool instruction; do not ask for GitHub permissions unless the failure is confirmed upstream. |
14
- | `permission_denied` with `source: "upstream"` | GitHub rejected the injected installation credential. | Verify the target, accepted permissions, and App installation scope; do not request user OAuth for a bot-owned issue operation. |
15
- | 404 Not Found | Issue number or repo is wrong. | Validate repo + issue ID with `gh issue view NUMBER --repo owner/repo`. |
16
- | Issue label mutation fails | Wrong REST payload or wrong repo context. | Use the allowlisted issue labels endpoint with an explicit `owner/repo` path and valid JSON input. |
17
- | Comment command fails with empty body | JSON input is missing a non-empty `body`. | Ensure the REST comment payload contains a non-empty `body` before retrying. |
5
+ | Symptom | Likely cause | Fix |
6
+ | ---------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
7
+ | `unknown command "issue"` from `gh` | CLI version too old or wrong binary in the plugin runtime. | Verify `gh --version`; if it is unavailable or too old, report that the GitHub plugin runtime dependency is not available. |
8
+ | `Missing required option --repo` | Repo not passed and no default was resolved. | Resolve with `jr-rpc config get github.repo`; pass `--repo owner/repo` explicitly when missing. |
9
+ | Command affects or authenticates against the wrong repo | Stale `github.repo` default or authenticated command missing explicit repo. | Pass `--repo owner/repo` for the target repository, or update `github.repo` before retrying. |
10
+ | `GraphQL: Could not resolve to a Repository` | Repo slug is wrong or inaccessible. | Validate `owner/repo` and confirm app installation on target repository. |
11
+ | 401 Unauthorized | Issued GitHub credentials were rejected upstream. | Verify the target repo, then use the grant/auth signal to distinguish stale user OAuth from app installation or host env setup. |
12
+ | `junior-auth-required provider=github grant=user-write` | User-to-server OAuth is missing or stale for a human-identity operation. | Follow the private OAuth prompt; do not ask the user to paste or manage tokens manually. |
13
+ | 403 without `permission_denied` where `source: "upstream"` | The runtime may have rejected an unsupported route before contacting GitHub. | Read the response body. Follow any required-tool instruction; do not ask for GitHub permissions unless the failure is confirmed upstream. |
14
+ | `permission_denied` with `source: "upstream"` | GitHub rejected the forwarded request. | Read GitHub's error first. If the message says GitHub denied access, verify the target, App permissions, and installation scope. Do not request user OAuth for a bot-owned issue operation. |
15
+ | 404 Not Found | Issue number or repo is wrong. | Validate repo + issue ID with `gh issue view NUMBER --repo owner/repo`. |
16
+ | Issue label mutation fails | Wrong REST payload or wrong repo context. | Use the allowlisted issue labels endpoint with an explicit `owner/repo` path and valid JSON input. |
17
+ | Comment command fails with empty body | JSON input is missing a non-empty `body`. | Ensure the REST comment payload contains a non-empty `body` before retrying. |
18
18
 
19
19
  ## Retry guidance
20
20