pr-shepherd 2.2.6 → 2.2.8

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 (66) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/bin/classify/standard/claude-notices.d.mts +9 -0
  3. package/bin/classify/standard/claude-notices.mjs +26 -0
  4. package/bin/classify/standard/index.mjs +2 -0
  5. package/bin/cli/iterate-instructions.mjs +3 -0
  6. package/bin/cli/iterate-lean.mjs +1 -0
  7. package/bin/cli/list-formatters.d.mts +3 -1
  8. package/bin/cli/list-formatters.mjs +7 -4
  9. package/bin/cli/runner.mjs +4 -2
  10. package/bin/cli/stack-layer-view.d.mts +5 -0
  11. package/bin/cli/stack-layer-view.mjs +11 -1
  12. package/bin/cli/stack-overview.d.mts +3 -1
  13. package/bin/cli/stack-overview.mjs +7 -8
  14. package/bin/cli/transport-formatter.d.mts +4 -0
  15. package/bin/cli/transport-formatter.mjs +13 -1
  16. package/bin/commands/apply-merge-resume.d.mts +22 -0
  17. package/bin/commands/apply-merge-resume.mjs +56 -0
  18. package/bin/commands/apply-merge.mjs +11 -19
  19. package/bin/commands/check-terminal-report.mjs +2 -0
  20. package/bin/commands/check.mjs +7 -4
  21. package/bin/commands/iterate/base.mjs +1 -0
  22. package/bin/commands/iterate/check-follow-up.mjs +1 -1
  23. package/bin/commands/iterate/helpers.mjs +1 -0
  24. package/bin/commands/iterate/index.mjs +4 -4
  25. package/bin/commands/iterate/merge-plan.d.mts +4 -0
  26. package/bin/commands/iterate/merge-plan.mjs +18 -0
  27. package/bin/commands/iterate/merge-state.mjs +2 -0
  28. package/bin/commands/iterate/report-gaps.d.mts +6 -0
  29. package/bin/commands/iterate/report-gaps.mjs +5 -0
  30. package/bin/commands/poll-summary.mjs +10 -1
  31. package/bin/commands/review-commit.d.mts +2 -2
  32. package/bin/commands/review-commit.mjs +11 -4
  33. package/bin/commands/stack-merge-plan.mjs +5 -3
  34. package/bin/commands/stack-merge-trunk-check.d.mts +12 -0
  35. package/bin/commands/stack-merge-trunk-check.mjs +26 -0
  36. package/bin/commands/stack-trunk-behind.d.mts +9 -0
  37. package/bin/commands/stack-trunk-behind.mjs +51 -0
  38. package/bin/config/merge-method.d.mts +2 -0
  39. package/bin/config/merge-method.mjs +17 -0
  40. package/bin/github/batch-parsers.mjs +9 -0
  41. package/bin/github/batch-raw-types.d.mts +8 -0
  42. package/bin/github/gql/batch-pr.gql +8 -0
  43. package/bin/github/poll-summary-readiness.mjs +2 -1
  44. package/bin/github/poll-summary-route.mjs +2 -1
  45. package/bin/github/rest-merge.d.mts +10 -0
  46. package/bin/github/rest-merge.mjs +26 -0
  47. package/bin/github/transport-evidence.d.mts +13 -2
  48. package/bin/github/transport-evidence.mjs +21 -3
  49. package/bin/github/transport.d.mts +7 -0
  50. package/bin/github/transport.mjs +26 -0
  51. package/bin/state/merge-request.d.mts +6 -0
  52. package/bin/state/merge-request.mjs +9 -1
  53. package/bin/types/github.d.mts +2 -0
  54. package/bin/types/iterate.d.mts +2 -0
  55. package/bin/types/merge-action.d.mts +6 -0
  56. package/bin/types/poll-summary.d.mts +6 -0
  57. package/bin/types/report.d.mts +2 -0
  58. package/package.json +1 -1
  59. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  60. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  61. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +1 -1
  62. package/plugins/pr-shepherd/skills/pr-shepherd/references/check-follow-up.md +1 -1
  63. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-start-stall.md +1 -1
  64. package/plugins/pr-shepherd/skills/pr-shepherd/references/required-checks-unreported.md +1 -1
  65. package/plugins/pr-shepherd/skills/setup-pr-shepherd/references/classifiers.md +1 -1
  66. package/pr-shepherd.schema.json +1 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
3
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
4
- "version": "2.2.6",
4
+ "version": "2.2.8",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
7
7
  "email": "jonathanrichardong@gmail.com"
@@ -0,0 +1,9 @@
1
+ import type { ClassifyRule } from "../types.mts";
2
+ /**
3
+ * The `@claude` mention bot's in-progress placeholder comment (claude-code-action). The action
4
+ * edits this same comment into its result, so the rule only suppresses it and never auto-resolves:
5
+ * minimizing the placeholder would leave the finished review minimized. Once the comment is
6
+ * edited its body no longer matches, and Shepherd surfaces it as an edited comment.
7
+ */
8
+ declare const rule: ClassifyRule;
9
+ export default rule;
@@ -0,0 +1,26 @@
1
+ import { isBotItem } from "./author.mjs";
2
+ /** The title line, with the optional inline spinner image the action appends. */
3
+ const TITLE = "Claude Code is working…(?: <img [^>\\n]*>)?";
4
+ /** The to-do list the action shows while it works: a heading and only checkbox lines. */
5
+ const TODO_LIST = "#{2,4} To-?[Dd]o [Ll]ist:?\\n(?:\\n?- \\[[ xX]\\] [^\\n]+)+";
6
+ /** The run link the action appends: `[View job run](…/actions/runs/N)`. */
7
+ const JOB_LINK = "\\[View job(?: run)?\\]\\(https:\\/\\/[^\\s)]+\\/actions\\/runs\\/\\d+[^\\s)]*\\)";
8
+ /**
9
+ * The whole comment is the title, then optionally the intro sentence, the to-do list and a rule
10
+ * line, then optionally the run link. Any other text, such as the finished review, does not match.
11
+ */
12
+ const PLACEHOLDER = new RegExp(`^${TITLE}(?:\\n\\n(?:I'll analyze this and get back to you\\.|${TODO_LIST}))*(?:\\n\\n---)?(?:\\n\\n${JOB_LINK})?$`);
13
+ /**
14
+ * The `@claude` mention bot's in-progress placeholder comment (claude-code-action). The action
15
+ * edits this same comment into its result, so the rule only suppresses it and never auto-resolves:
16
+ * minimizing the placeholder would leave the finished review minimized. Once the comment is
17
+ * edited its body no longer matches, and Shepherd surfaces it as an edited comment.
18
+ */
19
+ const rule = (item) => {
20
+ if (!isBotItem(item, ["claude", "github-actions"], ["pr-comment"]))
21
+ return null;
22
+ if (!PLACEHOLDER.test(item.body.trim()))
23
+ return null;
24
+ return { suppress: true, reason: "Claude Code in-progress placeholder (edited into its result)" };
25
+ };
26
+ export default rule;
@@ -1,3 +1,4 @@
1
+ import claudeNotices from "./claude-notices.mjs";
1
2
  import coderabbitNotices from "./coderabbit-notices.mjs";
2
3
  import codecovReport from "./codecov-report.mjs";
3
4
  import codexNotices from "./codex-notices.mjs";
@@ -14,6 +15,7 @@ import sourceryNotices from "./sourcery-notices.mjs";
14
15
  * Each rule matches conversation comments (`pr-comment`) only.
15
16
  */
16
17
  export const STANDARD_RULES = {
18
+ "claude-notices": claudeNotices,
17
19
  "coderabbit-notices": coderabbitNotices,
18
20
  "codecov-report": codecovReport,
19
21
  "codex-notices": codexNotices,
@@ -59,6 +59,9 @@ export function buildSimpleIterateInstructions(result) {
59
59
  else if (result.merge.fallbackCommand) {
60
60
  instructions.push(`Only if GitHub reports that auto-merge is unavailable, run the plain merge fallback: ${inlineCode(renderShellCommand(result.merge.fallbackCommand.argv))}.`);
61
61
  }
62
+ if (result.merge.restFallbackCommand) {
63
+ instructions.push(`If GraphQL is rate limited, use REST: ${inlineCode(renderShellCommand(result.merge.restFallbackCommand.argv))}.`);
64
+ }
62
65
  instructions.push(result.quotaWarning
63
66
  ? buildQuotaAwareContinuation(result.quotaWarning, "After running the merge command.")
64
67
  : "Then iterate immediately with the same options until the PR merges or needs work.");
@@ -45,6 +45,7 @@ export function projectIterateLean(result, opts) {
45
45
  pr: result.pr,
46
46
  repo: result.repo || undefined,
47
47
  ...(result.transport && { transport: result.transport }),
48
+ ...(result.transportReason && { transportReason: result.transportReason }),
48
49
  ...(result.transportUnavailable?.length && {
49
50
  transportUnavailable: result.transportUnavailable,
50
51
  }),
@@ -49,10 +49,11 @@ export declare function renderCommentBullet(c: {
49
49
  }, opts?: {
50
50
  statusTag?: string;
51
51
  }): string;
52
- /** ` [submitted on <sha>, head is <sha>]` when the review was submitted on a commit other than the PR head. */
52
+ /** ` [reviewed <sha>, head <sha>, N commits since]` when the review is on a commit other than the PR head. */
53
53
  export declare function renderReviewCommitTag(r: {
54
54
  commitOid?: string;
55
55
  headOid?: string;
56
+ commitsSince?: number;
56
57
  }): string;
57
58
  export declare function renderReviewBullet(r: {
58
59
  id: string;
@@ -64,6 +65,7 @@ export declare function renderReviewBullet(r: {
64
65
  staleReview?: boolean;
65
66
  commitOid?: string;
66
67
  headOid?: string;
68
+ commitsSince?: number;
67
69
  }, opts?: {
68
70
  includeBody?: boolean;
69
71
  }): string;
@@ -103,11 +103,14 @@ export function renderCommentBullet(c, opts = {}) {
103
103
  const statusSuffix = opts.statusTag ? ` ${opts.statusTag}` : "";
104
104
  return `- \`commentId=${c.id}\`${link} (${renderAuthor(c.author, c.authorType, c.authorAssociation)})${statusSuffix}: ${renderBodyPreview(c.body)}`;
105
105
  }
106
- /** ` [submitted on <sha>, head is <sha>]` when the review was submitted on a commit other than the PR head. */
106
+ /** ` [reviewed <sha>, head <sha>, N commits since]` when the review is on a commit other than the PR head. */
107
107
  export function renderReviewCommitTag(r) {
108
- return r.commitOid && r.headOid
109
- ? ` [submitted on \`${r.commitOid}\`, head is \`${r.headOid}\`]`
110
- : "";
108
+ if (!r.commitOid || !r.headOid)
109
+ return "";
110
+ const since = r.commitsSince === undefined
111
+ ? ""
112
+ : `, ${r.commitsSince} commit${r.commitsSince === 1 ? "" : "s"} since`;
113
+ return ` [reviewed \`${r.commitOid}\`, head \`${r.headOid}\`${since}]`;
111
114
  }
112
115
  export function renderReviewBullet(r, opts = {}) {
113
116
  const base = `- \`reviewId=${r.id}\` (${renderAuthor(r.author, r.authorType, r.authorAssociation)})${renderReviewCommitTag(r)}`;
@@ -1,8 +1,10 @@
1
1
  import { loadConfig } from "../config/load.mjs";
2
- import { getGithubTransport } from "../github/transport.mjs";
2
+ import { getGithubTransportMode } from "../github/transport.mjs";
3
3
  /** Every emitted pr-shepherd command starts with the configured `cli-command` launcher. */
4
4
  export function buildPrShepherdCommand(args) {
5
- const transport = getGithubTransport() === "rest" &&
5
+ const transport =
6
+ // Only an explicit request propagates; an auto fallback is not the caller's choice and stays local.
7
+ getGithubTransportMode() === "rest" &&
6
8
  !args.some((arg) => arg === "--transport" || arg.startsWith("--transport="))
7
9
  ? ["--transport", "rest"]
8
10
  : [];
@@ -27,8 +27,13 @@ export interface StackLayerView {
27
27
  checksIncomplete?: true;
28
28
  reviewIncomplete?: true;
29
29
  ruleAutoResolve?: PollSummaryRuleAutoResolve;
30
+ trunkBehindBy?: number;
31
+ trunkBehindUnknown?: true;
30
32
  queueRemoval?: {
31
33
  reason: string | null;
32
34
  actor?: string;
33
35
  };
34
36
  }
37
+ /** The `trunk behind` detail of a merge-top row, or undefined when trunk is not ahead. */
38
+ export declare function trunkDetail(layer: StackLayerView): string | undefined;
39
+ export declare function removalDetail(removal: StackLayerView["queueRemoval"]): string | undefined;
@@ -1 +1,11 @@
1
- export {};
1
+ /** The `trunk behind` detail of a merge-top row, or undefined when trunk is not ahead. */
2
+ export function trunkDetail(layer) {
3
+ if (layer.trunkBehindBy)
4
+ return `trunk behind ${layer.trunkBehindBy}`;
5
+ return layer.trunkBehindUnknown ? "trunk behind unknown" : undefined;
6
+ }
7
+ export function removalDetail(removal) {
8
+ if (!removal)
9
+ return undefined;
10
+ return `removed from merge queue (${removal.reason ?? "unknown reason"}${removal.actor ? ` by @${removal.actor}` : ""})`;
11
+ }
@@ -1,9 +1,11 @@
1
1
  import type { PollSummaryResult, PollSummaryStackAncestry, StackNextAction } from "../types.mts";
2
2
  import type { ApiUsage, GraphqlQuotaWarning } from "../types/api-usage.mts";
3
- import type { StackLayerView } from "./stack-layer-view.mts";
3
+ import { type StackLayerView } from "./stack-layer-view.mts";
4
4
  import type { NextCheck } from "../types/next-check.mts";
5
5
  export interface StackOverview {
6
6
  transport?: "rest";
7
+ /** Why REST is in use; present only with `transport`. */
8
+ transportReason?: string;
7
9
  transportUnavailable?: Array<{
8
10
  field: string;
9
11
  reason: string;
@@ -1,6 +1,7 @@
1
1
  import { stackLayerBlockReason } from "../commands/stack-layer-readiness.mjs";
2
2
  import { formatApiUsage, formatQuotaWarning } from "./api-usage-formatter.mjs";
3
- import { formatTransportEvidence } from "./transport-formatter.mjs";
3
+ import { formatTransportEvidence, projectTransportEvidence } from "./transport-formatter.mjs";
4
+ import { removalDetail, trunkDetail } from "./stack-layer-view.mjs";
4
5
  import { formatNextCheckLines } from "./next-check-format.mjs";
5
6
  import { formatPrUrl } from "../pr-reference.mjs";
6
7
  import { formatRuleAutoResolveLines } from "./rule-auto-resolve-lines.mjs";
@@ -14,10 +15,7 @@ export function projectStackOverview(result) {
14
15
  return {
15
16
  mode: "summary",
16
17
  repo: result.repo,
17
- ...(result.transport && { transport: result.transport }),
18
- ...(result.transportUnavailable?.length && {
19
- transportUnavailable: result.transportUnavailable,
20
- }),
18
+ ...projectTransportEvidence(result),
21
19
  selection,
22
20
  reason: result.reason,
23
21
  ...(result.stackMergeable && { stackMergeable: true }),
@@ -62,6 +60,8 @@ function projectLayer(item, stale) {
62
60
  ...(item.checks?.incomplete && { checksIncomplete: true }),
63
61
  ...(item.review?.incomplete && { reviewIncomplete: true }),
64
62
  ...(item.ruleAutoResolve && { ruleAutoResolve: item.ruleAutoResolve }),
63
+ ...(item.trunkBehindBy && { trunkBehindBy: item.trunkBehindBy }),
64
+ ...(item.trunkBehindUnknown && { trunkBehindUnknown: true }),
65
65
  ...(removal && {
66
66
  queueRemoval: {
67
67
  reason: removal.reason,
@@ -155,9 +155,8 @@ function formatLayerLines(layer, index, overview) {
155
155
  layer.actionable ? `${layer.actionable} actionable` : undefined,
156
156
  layer.checksIncomplete ? "checks incomplete" : undefined,
157
157
  layer.reviewIncomplete ? "review incomplete" : undefined,
158
- layer.queueRemoval
159
- ? `removed from merge queue (${layer.queueRemoval.reason ?? "unknown reason"}${layer.queueRemoval.actor ? ` by @${layer.queueRemoval.actor}` : ""})`
160
- : undefined,
158
+ trunkDetail(layer),
159
+ removalDetail(layer.queueRemoval),
161
160
  ].filter((detail) => detail !== undefined);
162
161
  return [
163
162
  `- ${layer.url === formatPrUrl(overview.repo, layer.pr) ? `PR #${layer.pr}: ${layer.title}` : `[PR #${layer.pr}: ${layer.title}](${layer.url})`}${facts.length > 0 ? ` — ${facts.join(" · ")}` : ""}`,
@@ -1,9 +1,13 @@
1
1
  interface TransportEvidence {
2
2
  transport?: "rest";
3
+ /** Why REST is in use; present only with `transport`. */
4
+ transportReason?: string;
3
5
  transportUnavailable?: Array<{
4
6
  field: string;
5
7
  reason: string;
6
8
  }>;
7
9
  }
8
10
  export declare function formatTransportEvidence(value: TransportEvidence): string[];
11
+ /** The JSON counterpart of `formatTransportEvidence`: only the fields that carry information. */
12
+ export declare function projectTransportEvidence(value: TransportEvidence): TransportEvidence;
9
13
  export {};
@@ -1,6 +1,10 @@
1
1
  export function formatTransportEvidence(value) {
2
2
  return [
3
- ...(value.transport ? [`**transport** \`${value.transport}\``] : []),
3
+ ...(value.transport
4
+ ? [
5
+ `**transport** \`${value.transport}\`${value.transportReason ? ` (${value.transportReason})` : ""}`,
6
+ ]
7
+ : []),
4
8
  ...(value.transportUnavailable?.length
5
9
  ? [
6
10
  "",
@@ -11,3 +15,11 @@ export function formatTransportEvidence(value) {
11
15
  : []),
12
16
  ];
13
17
  }
18
+ /** The JSON counterpart of `formatTransportEvidence`: only the fields that carry information. */
19
+ export function projectTransportEvidence(value) {
20
+ return {
21
+ ...(value.transport && { transport: value.transport }),
22
+ ...(value.transportReason && { transportReason: value.transportReason }),
23
+ ...(value.transportUnavailable?.length && { transportUnavailable: value.transportUnavailable }),
24
+ };
25
+ }
@@ -0,0 +1,22 @@
1
+ import type { RepoInfo } from "../github/client.mts";
2
+ import { type RestMergeOptions } from "../github/rest-merge.mts";
3
+ import { type MergeRequestRecord } from "../state/merge-request.mts";
4
+ import type { mergeResultFactory } from "./apply-merge-output.mts";
5
+ import type { ApplyMergeResult } from "./apply-merge.mts";
6
+ interface ResumeContext {
7
+ repo: RepoInfo;
8
+ pr: number;
9
+ key: {
10
+ owner: string;
11
+ repo: string;
12
+ pr: number;
13
+ };
14
+ existing: MergeRequestRecord & {
15
+ uuid: string;
16
+ };
17
+ options: RestMergeOptions;
18
+ factory: ReturnType<typeof mergeResultFactory>;
19
+ }
20
+ /** Resume a recorded asynchronous request, falling back to the synchronous merge when unreadable. */
21
+ export declare function resumeMergeRequest(ctx: ResumeContext): Promise<ApplyMergeResult>;
22
+ export {};
@@ -0,0 +1,56 @@
1
+ import { GitHubRequestError } from "../github/errors.mjs";
2
+ import { getRestMerge, matchesRestMergeRequest, requestRestSyncMerge, } from "../github/rest-merge.mjs";
3
+ import { clearMergeRequest, writeMergeRequestStatus, } from "../state/merge-request.mjs";
4
+ import { mergedResponse, readPull } from "./apply-merge-pull.mjs";
5
+ /** Resume a recorded asynchronous request, falling back to the synchronous merge when unreadable. */
6
+ export async function resumeMergeRequest(ctx) {
7
+ const { repo, pr, key, existing, options, factory } = ctx;
8
+ const { failed, project } = factory;
9
+ try {
10
+ const response = await getRestMerge(repo, pr, existing.uuid);
11
+ if (response.status === "pending" &&
12
+ (!matchesRestMergeRequest(response, options) || response.details.uuid !== existing.uuid))
13
+ return failed("Asynchronous merge status does not match the persisted guarded request.", true);
14
+ await writeMergeRequestStatus(key, { ...existing, response });
15
+ return project(response);
16
+ }
17
+ catch (error) {
18
+ // 404: the UUID expired. 403: the token cannot read merge-async status at all (for example a
19
+ // GitHub App installation without that permission). Either way the status is unknown, so the
20
+ // pull itself decides, and an unmerged direct merge converges through the synchronous route.
21
+ if (!(error instanceof GitHubRequestError) || (error.status !== 404 && error.status !== 403))
22
+ throw error;
23
+ const latest = await readPull(repo, pr);
24
+ if (latest.merged === true)
25
+ return project(mergedResponse(latest, "Pull request is merged; its asynchronous status was unreadable."));
26
+ // The synchronous route guards the head SHA itself; queue, default, method-less, and native
27
+ // stack requests have no synchronous equivalent, so their unknown outcome stays blocked.
28
+ if (options.mergeAction !== "direct_merge" || !options.mergeMethod || options.expectedStack)
29
+ return failed(`The asynchronous merge status is unavailable (${error.status}). The PR is not merged; its request outcome is unknown and no duplicate was submitted.`, true);
30
+ return syncFallback(ctx, options.mergeMethod);
31
+ }
32
+ }
33
+ async function syncFallback(ctx, mergeMethod) {
34
+ const { repo, pr, key, options, factory } = ctx;
35
+ try {
36
+ const response = await requestRestSyncMerge(repo, pr, {
37
+ requireSha: options.requireSha,
38
+ mergeMethod,
39
+ });
40
+ await clearMergeRequest(key);
41
+ return factory.project({
42
+ ...response,
43
+ details: {
44
+ ...response.details,
45
+ message: `${response.details.message ?? ""} (merged synchronously: the asynchronous status was unreadable)`.trim(),
46
+ },
47
+ });
48
+ }
49
+ catch (error) {
50
+ // A definite refusal (not mergeable, head changed) retires the stale request so the next
51
+ // command starts a fresh guarded attempt; an unknown outcome keeps the record and retries.
52
+ if (error instanceof GitHubRequestError && error.status >= 400 && error.status < 500)
53
+ await clearMergeRequest(key);
54
+ throw error;
55
+ }
56
+ }
@@ -6,10 +6,11 @@ import { EXIT, ShepherdError } from "../exit-codes.mjs";
6
6
  import { getCurrentPrNumber, getRepoInfo } from "../github/client.mjs";
7
7
  import { GitHubRequestError } from "../github/errors.mjs";
8
8
  import { mergedResponse, readPull } from "./apply-merge-pull.mjs";
9
+ import { resumeMergeRequest } from "./apply-merge-resume.mjs";
9
10
  import { withRestConditionalScope } from "../github/rest-conditional-scope.mjs";
10
11
  import { getGithubTransport } from "../github/transport.mjs";
11
- import { getRestMerge, matchesRestMergeRequest, requestRestMerge, } from "../github/rest-merge.mjs";
12
- import { claimMergeRequest, replaceFailedMergeRequest, readMergeRequest, writeMergeRequest, writeMergeRequestStatus, } from "../state/merge-request.mjs";
12
+ import { matchesRestMergeRequest, requestRestMerge, } from "../github/rest-merge.mjs";
13
+ import { claimMergeRequest, replaceFailedMergeRequest, readMergeRequest, writeMergeRequest, } from "../state/merge-request.mjs";
13
14
  /** Submit one guarded asynchronous request, or resume its existing UUID without resubmitting. */
14
15
  export async function runApplyMerge(input) {
15
16
  validateApplyMergeOptions(input);
@@ -61,23 +62,14 @@ async function submitApplyMerge(input, repo, pr, key) {
61
62
  };
62
63
  if (!existing.uuid)
63
64
  return failed("The previous merge submission has an unknown outcome and no UUID. The PR is not merged; no duplicate request was submitted.", true);
64
- try {
65
- const response = await getRestMerge(repo, pr, existing.uuid);
66
- if (response.status === "pending" &&
67
- (!matchesRestMergeRequest(response, options) || response.details.uuid !== existing.uuid))
68
- return failed("Asynchronous merge status does not match the persisted guarded request.", true);
69
- await writeMergeRequestStatus(key, { ...existing, response });
70
- return project(response);
71
- }
72
- catch (error) {
73
- if (error instanceof GitHubRequestError && error.status === 404) {
74
- const latest = await readPull(repo, pr);
75
- if (latest.merged === true)
76
- return project(mergedResponse(latest, "Pull request is merged; its asynchronous request has expired."));
77
- return failed("The asynchronous merge UUID expired or is unavailable. The PR is not merged; its request outcome is unknown and no duplicate was submitted.", true);
78
- }
79
- throw error;
80
- }
65
+ return resumeMergeRequest({
66
+ repo,
67
+ pr,
68
+ key,
69
+ existing: { ...existing, uuid: existing.uuid },
70
+ options,
71
+ factory: { failed, project },
72
+ });
81
73
  }
82
74
  let record = {
83
75
  version: 1,
@@ -1,3 +1,4 @@
1
+ import { transportReasonField } from "../github/transport-evidence.mjs";
1
2
  /** A merged PR answered from its first REST pull read never read reviews, threads or rules. */
2
3
  const requirementsUnread = (batchData) => (batchData.transportUnavailable ?? []).some(({ field }) => field === "mergeRequirements");
3
4
  function withoutRequirements(mergeStatus) {
@@ -9,6 +10,7 @@ export function buildTerminalReport(prNumber, repo, batchData, mergeStatus, stat
9
10
  pr: prNumber,
10
11
  nodeId: batchData.nodeId,
11
12
  ...(batchData.transport && { transport: batchData.transport }),
13
+ ...(batchData.transport && transportReasonField()),
12
14
  ...(batchData.transportUnavailable?.length && {
13
15
  transportUnavailable: batchData.transportUnavailable,
14
16
  }),
@@ -13,6 +13,7 @@ import { classifyChecks, getCiVerdict } from "../checks/classify.mjs";
13
13
  import { mergeStartupFailureChecks } from "../checks/startup-failures.mjs";
14
14
  import { withRunWorkflowPaths } from "../checks/run-workflow-paths.mjs";
15
15
  import { fetchStartupFailureChecks, triageFailingChecks } from "../checks/triage.mjs";
16
+ import { transportReasonField } from "../github/transport-evidence.mjs";
16
17
  import { TriageBudget } from "../checks/triage-budget.mjs";
17
18
  import { attachPendingDeployments } from "../checks/pending-deployments.mjs";
18
19
  import { deriveMergeStatus } from "../merge-status/derive.mjs";
@@ -25,7 +26,7 @@ import { buildTerminalReport } from "./check-terminal-report.mjs";
25
26
  import { isBlockedByFilteredCheck, refreshReadyMergeability, refreshUnknownMergeability, } from "./ready-mergeability.mjs";
26
27
  import { loadSeenMap, markSeen, classifyItem, mutationWasDenied } from "../state/seen-comments.mjs";
27
28
  import { aliasThreadSeenMarkers } from "../github/rest-identities.mjs";
28
- import { transportReadinessGaps } from "../github/transport-evidence.mjs";
29
+ import { conversationResolutionProven, transportReadinessGaps, } from "../github/transport-evidence.mjs";
29
30
  import { canGenerateGithubMutation } from "../github/mutation-policy.mjs";
30
31
  import { threadTranscriptBody } from "../threads/transcript.mjs";
31
32
  import { classifyThreadVisibility } from "../comments/thread-visibility.mjs";
@@ -43,11 +44,12 @@ import { getEffectiveCwd } from "../execution-context.mjs";
43
44
  function enforceTransportReadiness(status, data) {
44
45
  if (status !== "READY" || data.transport !== "rest")
45
46
  return status;
46
- if (data.reviewThreads.some((thread) => thread.isResolved === undefined ||
47
- thread.isOutdated === undefined ||
47
+ const conversationsGated = data.branchRules?.requiresConversationResolution;
48
+ const statusProven = conversationResolutionProven(data.mergeStateStatus, conversationsGated);
49
+ if (data.reviewThreads.some((thread) => (!statusProven && (thread.isResolved === undefined || thread.isOutdated === undefined)) ||
48
50
  thread.comments === undefined))
49
51
  return "UNKNOWN";
50
- if (transportReadinessGaps(data, data.mergeStateStatus).length > 0)
52
+ if (transportReadinessGaps(data, data.mergeStateStatus, conversationsGated).length > 0)
51
53
  return "UNKNOWN";
52
54
  return status;
53
55
  }
@@ -392,6 +394,7 @@ async function runScopedCheck(opts, context, repo, prNumber, stateKey) {
392
394
  pr: prNumber,
393
395
  nodeId: batchData.nodeId,
394
396
  ...(batchData.transport && { transport: batchData.transport }),
397
+ ...(batchData.transport && transportReasonField()),
395
398
  ...(batchData.transportUnavailable && {
396
399
  transportUnavailable: batchData.transportUnavailable,
397
400
  }),
@@ -6,6 +6,7 @@ export function buildIterateBase(report, readyState) {
6
6
  pr: report.pr,
7
7
  repo: report.repo,
8
8
  ...(report.transport && { transport: report.transport }),
9
+ ...(report.transportReason && { transportReason: report.transportReason }),
9
10
  ...(report.transportUnavailable?.length && {
10
11
  transportUnavailable: report.transportUnavailable,
11
12
  }),
@@ -29,7 +29,7 @@ export function buildCheckFollowUpInstructions(checks, repo, actionsRunIds) {
29
29
  : "";
30
30
  return [
31
31
  `Shepherd has no rerun to offer and no log excerpt to show for the checks under \`## Failing checks\`, so it cannot tell from GitHub's data why they failed or what would fix them. Find out before acting.${start} ${playbookPointer("Check follow-up")}`,
32
- "If the cause is within this PR, fix it and push. Otherwise make no change and keep what you found; do not rerun or retrigger these checks. If these checks are unchanged on the next poll, Shepherd escalates with `check-follow-up-unavailable`; report that diagnosis then.",
32
+ "If the cause is within this PR, fix it and push. Otherwise make no change and keep what you found; do not rerun or retrigger these checks, including with an empty or no-op commit. If these checks are unchanged on the next poll, Shepherd escalates with `check-follow-up-unavailable`; report that diagnosis then.",
33
33
  ];
34
34
  }
35
35
  /**
@@ -29,6 +29,7 @@ export function buildTerminalCancelResult(report) {
29
29
  pr: report.pr,
30
30
  repo: report.repo,
31
31
  ...(report.transport && { transport: report.transport }),
32
+ ...(report.transportReason && { transportReason: report.transportReason }),
32
33
  ...(report.transportUnavailable?.length && {
33
34
  transportUnavailable: report.transportUnavailable,
34
35
  }),
@@ -30,7 +30,7 @@ import { findStaleNativeStackAncestry } from "./stale-ancestry.mjs";
30
30
  import { annotateBlockedWait, resolveCheckBlockerGate } from "./check-blocker-gate.mjs";
31
31
  import { buildUnreportedFixResult, planUnreportedRequired } from "./unreported-required.mjs";
32
32
  import { createCheckExecutionContext } from "../check-execution-context.mjs";
33
- import { transportReadinessGaps } from "../../github/transport-evidence.mjs";
33
+ import { reportReadinessGaps } from "./report-gaps.mjs";
34
34
  import { buildEscalateHumanMessage } from "./escalate.mjs";
35
35
  import { markEditedCommentsSeen } from "./edited-comment-markers.mjs";
36
36
  export function runIterate(opts) {
@@ -282,7 +282,7 @@ async function runIterateCore(opts, tick) {
282
282
  const canMarkReady = report.status === "READY" &&
283
283
  report.mergeStatus.isDraft &&
284
284
  !report.mergeStatus.blockingBotReviewInProgress;
285
- const gaps = transportReadinessGaps(report, report.mergeStatus.mergeStateStatus);
285
+ const gaps = reportReadinessGaps(report);
286
286
  if (gaps.length > 0 &&
287
287
  report.checks.inProgress.length === 0 &&
288
288
  report.mergeStatus.mergeStateStatus !== "UNKNOWN") {
@@ -384,7 +384,7 @@ async function recordReadyReceipt(key, report, context) {
384
384
  report.mergeStatus.isDraft ||
385
385
  !report.headSha ||
386
386
  !report.baseRefOid ||
387
- transportReadinessGaps(report, report.mergeStatus.mergeStateStatus).length > 0)
387
+ reportReadinessGaps(report).length > 0)
388
388
  return "failed";
389
389
  try {
390
390
  const raw = await receiptSummaryForReport(key, report, context);
@@ -457,7 +457,7 @@ async function revalidateReadyReceipt(key, report, hasReadinessWork, context) {
457
457
  report.mergeStatus.isDraft ||
458
458
  !report.headSha ||
459
459
  !report.baseRefOid ||
460
- transportReadinessGaps(report, report.mergeStatus.mergeStateStatus).length > 0 ||
460
+ reportReadinessGaps(report).length > 0 ||
461
461
  (!retainQueuedReceipt && (report.status !== "READY" || hasReadinessWork))) {
462
462
  await clearReadyReceipt(key);
463
463
  return false;
@@ -13,6 +13,10 @@ export interface MergePlanInput {
13
13
  queueKnown?: boolean;
14
14
  /** Omitted when the batch did not select repository merge settings. */
15
15
  allowedMergeMethods?: readonly MergeMethod[];
16
+ /** Branch policy requires linear history, so merge commits are excluded. */
17
+ linearHistory?: boolean;
18
+ /** Attach a REST equivalent of the GraphQL merge commands, for when GraphQL quota runs out. */
19
+ restFallback?: boolean;
16
20
  expectedStack?: RestMergeStackGuard;
17
21
  }
18
22
  export interface MergeMethodUnavailable {
@@ -24,6 +24,7 @@ export function buildMergeCommandPlan(input) {
24
24
  allowed: input.allowedMergeMethods,
25
25
  configured,
26
26
  fallback: "merge",
27
+ linearHistory: input.linearHistory,
27
28
  });
28
29
  if ("unavailable" in decision)
29
30
  return decision;
@@ -81,6 +82,7 @@ export function buildMergeCommandPlan(input) {
81
82
  allowed: input.allowedMergeMethods,
82
83
  configured: configuredMergeMethod(mergeConfig),
83
84
  fallback: "merge",
85
+ linearHistory: input.linearHistory,
84
86
  });
85
87
  if ("unavailable" in decision)
86
88
  return decision;
@@ -90,5 +92,21 @@ export function buildMergeCommandPlan(input) {
90
92
  mode: "auto",
91
93
  command: { argv: [...base, "--auto", ...commandArgs] },
92
94
  fallbackCommand: { argv: [...base, ...commandArgs] },
95
+ // `gh pr merge` is GraphQL; this REST call has its own quota and merges immediately.
96
+ ...(input.restFallback && {
97
+ restFallbackCommand: {
98
+ argv: [
99
+ "gh",
100
+ "api",
101
+ "-X",
102
+ "PUT",
103
+ `repos/${input.repo}/pulls/${input.pr}/merge`,
104
+ "-f",
105
+ `sha=${input.headSha}`,
106
+ "-f",
107
+ `merge_method=${decision.method}`,
108
+ ],
109
+ },
110
+ }),
93
111
  };
94
112
  }
@@ -56,6 +56,8 @@ export function buildReadyMergeOutcome(enabled, readyElapsed, base, report) {
56
56
  queueKnown: (report.transport !== "rest" || report.branchProtection === null) &&
57
57
  !(report.transportUnavailable ?? []).some(({ field }) => ["branchProtection", "branchRules"].includes(field)),
58
58
  ...(report.allowedMergeMethods && { allowedMergeMethods: report.allowedMergeMethods }),
59
+ restFallback: true,
60
+ linearHistory: report.mergeStatus.mergeRequirements?.linearHistory?.required === true,
59
61
  });
60
62
  if ("unavailable" in plan) {
61
63
  // A REST policy read that may succeed on a later poll waits under the stall timer.
@@ -0,0 +1,6 @@
1
+ import type { ShepherdReport } from "../../types.mts";
2
+ /** Transport readiness gaps for a report, using its branch policy to clear provable gaps. */
3
+ export declare function reportReadinessGaps(report: ShepherdReport): {
4
+ field: string;
5
+ reason: string;
6
+ }[];
@@ -0,0 +1,5 @@
1
+ import { transportReadinessGaps } from "../../github/transport-evidence.mjs";
2
+ /** Transport readiness gaps for a report, using its branch policy to clear provable gaps. */
3
+ export function reportReadinessGaps(report) {
4
+ return transportReadinessGaps(report, report.mergeStatus.mergeStateStatus, report.mergeStatus.mergeRequirements?.conversationsResolved.required);
5
+ }
@@ -3,6 +3,7 @@ import { loadConfig } from "../config/load.mjs";
3
3
  import { ShepherdError } from "../exit-codes.mjs";
4
4
  import { getRepoInfo } from "../github/client.mjs";
5
5
  import { getGithubTransport } from "../github/transport.mjs";
6
+ import { transportReasonField } from "../github/transport-evidence.mjs";
6
7
  import { withApiTelemetryScope, summarizeApiTelemetry } from "../github/api-telemetry.mjs";
7
8
  import { aggregateRerunCommand, stackApprovalCommands } from "../github/poll-summary-command.mjs";
8
9
  import { fetchPollSummary } from "../github/poll-summary.mjs";
@@ -15,6 +16,7 @@ import { summaryStatusSignature } from "./poll-summary-signature.mjs";
15
16
  import { applyStackStallGuard, isStackRepairTick } from "./stack-stall.mjs";
16
17
  import { applyStackOwnership, listedLayerLeftStack, missingListedLayers, } from "./stack-ownership.mjs";
17
18
  import { stackRerunTarget } from "./stack-work.mjs";
19
+ import { withTrunkBehind } from "./stack-trunk-behind.mjs";
18
20
  import { requestedMergeScope, stackAddedLayers } from "./stack-merge-scope.mjs";
19
21
  import { aggregateDeadline } from "./stall-deadline.mjs";
20
22
  import { aggregateTargets, pauseBeforeNextTick, withPollEvents, } from "./poll-events.mjs";
@@ -69,6 +71,7 @@ async function readPollSummaryTick(opts) {
69
71
  selection: fetched.selection,
70
72
  reason: allTerminal ? "all_terminal" : actionable ? "actionable" : "waiting",
71
73
  prs: fetched.prs,
74
+ ...restReason(),
72
75
  ...(fetched.stackAncestry?.length && { stackAncestry: fetched.stackAncestry }),
73
76
  ...(fetched.allowedMergeMethods && { allowedMergeMethods: fetched.allowedMergeMethods }),
74
77
  };
@@ -80,7 +83,8 @@ async function readPollSummaryTick(opts) {
80
83
  return { result: escalated, repo };
81
84
  }
82
85
  const addedLayers = await stackAddedLayers(summary, scope, rerunCommand);
83
- const planned = planPollSummary({ ...summary, ...(addedLayers.length > 0 && { addedLayers }) }, scope !== undefined, rerunCommand, scope, (extra) => stackApprovalCommands(`${repo.owner}/${repo.name}`, fetched.selection, opts, extra));
86
+ const withBehind = await withTrunkBehind(summary, scope);
87
+ const planned = planPollSummary({ ...withBehind, ...(addedLayers.length > 0 && { addedLayers }) }, scope !== undefined, rerunCommand, scope, (extra) => stackApprovalCommands(`${repo.owner}/${repo.name}`, fetched.selection, opts, extra));
84
88
  const result = await applyStackStallGuard(planned, repo, opts.stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
85
89
  return { result, repo, ...(fetched.handoffSource && { handoffSource: fetched.handoffSource }) };
86
90
  }
@@ -259,3 +263,8 @@ function withoutImpliedOwnership(result) {
259
263
  return result;
260
264
  return { ...result, prs: result.prs.map(({ owned: _owned, ...item }) => item) };
261
265
  }
266
+ /** The summary says why Shepherd moved to REST on its own; a requested REST run says nothing. */
267
+ function restReason() {
268
+ const { transportReason } = transportReasonField();
269
+ return transportReason ? { transport: "rest", transportReason } : {};
270
+ }