pr-shepherd 2.6.1 → 2.7.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 (131) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/bin/classify/standard/coderabbit-walkthrough.d.mts +10 -0
  3. package/bin/classify/standard/coderabbit-walkthrough.mjs +21 -0
  4. package/bin/classify/standard/devin-no-issues.d.mts +7 -0
  5. package/bin/classify/standard/devin-no-issues.mjs +18 -0
  6. package/bin/classify/standard/index.d.mts +2 -1
  7. package/bin/classify/standard/index.mjs +6 -1
  8. package/bin/cli/apply-merge-handler.mjs +2 -0
  9. package/bin/cli/body-truncate.d.mts +7 -0
  10. package/bin/cli/body-truncate.mjs +8 -4
  11. package/bin/cli/help-command-pages.d.mts +4 -2
  12. package/bin/cli/help-command-pages.mjs +4 -1
  13. package/bin/cli/help-iterate-poll-pages.d.mts +1 -1
  14. package/bin/cli/help-iterate-poll-pages.mjs +1 -1
  15. package/bin/cli/help-top-page.d.mts +1 -1
  16. package/bin/cli/help-top-page.mjs +3 -1
  17. package/bin/cli/help-watch-status-page.d.mts +1 -0
  18. package/bin/cli/help-watch-status-page.mjs +21 -0
  19. package/bin/cli/help.d.mts +5 -3
  20. package/bin/cli/help.mjs +2 -0
  21. package/bin/cli/iterate-lean.d.mts +0 -5
  22. package/bin/cli/iterate-lean.mjs +9 -2
  23. package/bin/cli/poll-summary-formatter.mjs +2 -1
  24. package/bin/cli/review-body-cap.d.mts +10 -0
  25. package/bin/cli/review-body-cap.mjs +84 -0
  26. package/bin/cli/stack-layer-view.d.mts +2 -0
  27. package/bin/cli/stack-layer-view.mjs +8 -0
  28. package/bin/cli/stack-overview.mjs +4 -5
  29. package/bin/cli/triage-formatter.mjs +4 -1
  30. package/bin/cli/watch-status-handler.d.mts +2 -0
  31. package/bin/cli/watch-status-handler.mjs +56 -0
  32. package/bin/cli-parser.mjs +7 -0
  33. package/bin/commands/apply-merge-default-route.d.mts +56 -0
  34. package/bin/commands/apply-merge-default-route.mjs +149 -0
  35. package/bin/commands/apply-merge-output.d.mts +2 -0
  36. package/bin/commands/apply-merge-output.mjs +8 -0
  37. package/bin/commands/apply-merge-pull.d.mts +3 -0
  38. package/bin/commands/apply-merge-resume.d.mts +2 -3
  39. package/bin/commands/apply-merge-resume.mjs +74 -32
  40. package/bin/commands/apply-merge-stack-membership.d.mts +27 -0
  41. package/bin/commands/apply-merge-stack-membership.mjs +85 -0
  42. package/bin/commands/apply-merge-submit.d.mts +20 -0
  43. package/bin/commands/apply-merge-submit.mjs +47 -0
  44. package/bin/commands/apply-merge-supersede.d.mts +17 -0
  45. package/bin/commands/apply-merge-supersede.mjs +30 -0
  46. package/bin/commands/apply-merge-sync-fallback.d.mts +16 -0
  47. package/bin/commands/apply-merge-sync-fallback.mjs +55 -0
  48. package/bin/commands/apply-merge.d.mts +2 -0
  49. package/bin/commands/apply-merge.mjs +65 -41
  50. package/bin/commands/check-review-budget.mjs +12 -1
  51. package/bin/commands/check.d.mts +2 -0
  52. package/bin/commands/check.mjs +9 -1
  53. package/bin/commands/iterate/escalate.mjs +5 -0
  54. package/bin/commands/iterate/index.mjs +34 -4
  55. package/bin/commands/iterate/merge-plan.d.mts +2 -0
  56. package/bin/commands/iterate/merge-plan.mjs +1 -1
  57. package/bin/commands/iterate/merge.mjs +7 -3
  58. package/bin/commands/iterate/stack-boundary.mjs +6 -6
  59. package/bin/commands/iterate/triage.mjs +19 -6
  60. package/bin/commands/poll-events.d.mts +1 -1
  61. package/bin/commands/poll-events.mjs +8 -3
  62. package/bin/commands/poll-seen-options.d.mts +7 -0
  63. package/bin/commands/poll-seen-options.mjs +9 -0
  64. package/bin/commands/poll-summary-instructions.d.mts +1 -0
  65. package/bin/commands/poll-summary-instructions.mjs +17 -7
  66. package/bin/commands/poll-summary.mjs +8 -4
  67. package/bin/commands/poll.mjs +2 -2
  68. package/bin/commands/rest-stack-merge-readiness.d.mts +6 -2
  69. package/bin/commands/rest-stack-merge-readiness.mjs +59 -7
  70. package/bin/commands/stack-drain.d.mts +7 -1
  71. package/bin/commands/stack-drain.mjs +30 -6
  72. package/bin/commands/stack-lower-heads.d.mts +32 -0
  73. package/bin/commands/stack-lower-heads.mjs +53 -0
  74. package/bin/commands/stack-merge-escalations.d.mts +2 -1
  75. package/bin/commands/stack-merge-plan.mjs +35 -41
  76. package/bin/commands/stack-merge-trunk-check.d.mts +0 -2
  77. package/bin/commands/stack-merge-trunk-check.mjs +0 -2
  78. package/bin/commands/stack-ownership.mjs +3 -3
  79. package/bin/commands/stack-stall.d.mts +1 -0
  80. package/bin/commands/stack-stall.mjs +6 -2
  81. package/bin/commands/stack-trunk-behind.d.mts +1 -1
  82. package/bin/commands/stack-trunk-behind.mjs +1 -1
  83. package/bin/commands/stack-work.mjs +1 -1
  84. package/bin/config/merge-command-args.d.mts +2 -0
  85. package/bin/config/merge-command-args.mjs +13 -0
  86. package/bin/config/merge-method.d.mts +0 -5
  87. package/bin/config/merge-method.mjs +0 -6
  88. package/bin/config/schema.d.mts +2 -0
  89. package/bin/config/schema.mjs +2 -13
  90. package/bin/github/batch-parser-helpers.d.mts +5 -0
  91. package/bin/github/batch-parser-helpers.mjs +7 -2
  92. package/bin/github/batch-parsers.mjs +6 -2
  93. package/bin/github/errors.d.mts +2 -0
  94. package/bin/github/errors.mjs +1 -1
  95. package/bin/github/poll-summary-annotation-probe.d.mts +1 -1
  96. package/bin/github/poll-summary-annotation-probe.mjs +2 -2
  97. package/bin/github/poll-summary-command.d.mts +3 -2
  98. package/bin/github/poll-summary-command.mjs +6 -4
  99. package/bin/github/poll-summary-projector.mjs +16 -14
  100. package/bin/github/poll-summary-readiness.d.mts +4 -0
  101. package/bin/github/poll-summary-readiness.mjs +22 -0
  102. package/bin/github/poll-summary-rest-queue.d.mts +13 -0
  103. package/bin/github/poll-summary-rest-queue.mjs +21 -0
  104. package/bin/github/poll-summary-review-helpers.mjs +8 -4
  105. package/bin/state/merge-method-cache.d.mts +19 -0
  106. package/bin/state/merge-method-cache.mjs +27 -0
  107. package/bin/state/merge-request-claim.d.mts +23 -0
  108. package/bin/state/merge-request-claim.mjs +44 -0
  109. package/bin/state/merge-request-clear.d.mts +24 -0
  110. package/bin/state/merge-request-clear.mjs +36 -0
  111. package/bin/state/merge-request-lock.d.mts +13 -0
  112. package/bin/state/merge-request-lock.mjs +136 -0
  113. package/bin/state/merge-request-stack-heads.d.mts +2 -0
  114. package/bin/state/merge-request-stack-heads.mjs +8 -0
  115. package/bin/state/merge-request.d.mts +23 -6
  116. package/bin/state/merge-request.mjs +29 -29
  117. package/bin/state/ready-receipts.d.mts +11 -0
  118. package/bin/state/ready-receipts.mjs +7 -0
  119. package/bin/state/watch-lock.d.mts +10 -0
  120. package/bin/state/watch-lock.mjs +38 -3
  121. package/bin/types/poll-summary.d.mts +2 -0
  122. package/package.json +12 -5
  123. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  124. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  125. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +1 -1
  126. package/plugins/pr-shepherd/skills/pr-shepherd/references/create-a-pr.md +2 -2
  127. package/plugins/pr-shepherd/skills/pr-shepherd/references/waiting.md +1 -1
  128. package/plugins/pr-shepherd/skills/setup-pr-shepherd/references/classifiers.md +1 -1
  129. package/pr-shepherd.schema.json +8 -0
  130. package/bin/commands/stack-merge-flag.d.mts +0 -7
  131. package/bin/commands/stack-merge-flag.mjs +0 -6
@@ -0,0 +1,84 @@
1
+ import { fenceOpener, HEAD_FRACTION, isFenceCloser } from "./body-truncate.mjs";
2
+ import { displayBody } from "./display-body.mjs";
3
+ const REVIEW_URL_RE = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)#pullrequestreview-(\d+)$/;
4
+ /**
5
+ * A `gh` command that prints a review's full body: REST when the review URL is known (the REST
6
+ * transport reads it, and GraphQL can be refused there), otherwise GraphQL by node ID.
7
+ */
8
+ function reviewViewCommand(id, url) {
9
+ const match = url === undefined ? null : REVIEW_URL_RE.exec(url);
10
+ if (match) {
11
+ const [, owner, repo, pr, reviewId] = match;
12
+ return `gh api repos/${owner}/${repo}/pulls/${pr}/reviews/${reviewId} --jq .body`;
13
+ }
14
+ return `gh api graphql -f query='query { node(id: "${id}") { ... on PullRequestReview { body } } }' --jq .data.node.body`;
15
+ }
16
+ /**
17
+ * Caps a review body at `maxChars` of GitHub-visible text (`0` disables the cap). An over-cap body
18
+ * keeps a head and a tail around a notice that names the review ID and the cap, and gives the
19
+ * command that prints the full text. A body within the cap is returned unchanged.
20
+ */
21
+ export function capReviewBody(review, maxChars) {
22
+ if (maxChars <= 0)
23
+ return review;
24
+ const shown = displayBody(review.body);
25
+ if (shown.length <= maxChars)
26
+ return review;
27
+ const marker = (elided) => `[…${elided} chars elided — reviewId=${review.id} is over the ${maxChars}-char cap; read the full review with: ${reviewViewCommand(review.id, review.url)}]`;
28
+ return { ...review, body: boundedCut(shown, maxChars, marker) };
29
+ }
30
+ /** The fence still open after each line, or null. */
31
+ function openFences(lines) {
32
+ let fence = null;
33
+ return lines.map((line) => {
34
+ const trimmed = line.trim();
35
+ if (fence) {
36
+ if (isFenceCloser(trimmed, fence))
37
+ fence = null;
38
+ }
39
+ else {
40
+ fence = fenceOpener(trimmed);
41
+ }
42
+ return fence;
43
+ });
44
+ }
45
+ const fenceLine = (fence) => fence.char.repeat(fence.len);
46
+ /**
47
+ * A head (70% of `maxChars`) and a tail (the rest) on line boundaries around `marker`, never longer
48
+ * than `maxChars` plus the marker and fence lines. A cut inside a code block closes the fence at
49
+ * the end of the head and reopens it at the start of the tail, so the block cannot swallow the
50
+ * marker and the review's closing text still shows.
51
+ */
52
+ function boundedCut(body, maxChars, marker) {
53
+ const lines = body.split("\n");
54
+ const open = openFences(lines);
55
+ const headBudget = Math.ceil(maxChars * HEAD_FRACTION);
56
+ const tailBudget = maxChars - headBudget;
57
+ let headEnd = -1;
58
+ let used = 0;
59
+ while (headEnd + 1 < lines.length && used + lines[headEnd + 1].length + 1 <= headBudget) {
60
+ headEnd++;
61
+ used += lines[headEnd].length + 1;
62
+ }
63
+ let tailStart = lines.length;
64
+ used = 0;
65
+ while (tailStart - 1 > headEnd && used + lines[tailStart - 1].length + 1 <= tailBudget) {
66
+ tailStart--;
67
+ used += lines[tailStart].length + 1;
68
+ }
69
+ const head = headEnd >= 0 ? lines.slice(0, headEnd + 1).join("\n") : lines[0].slice(0, headBudget);
70
+ // A last line too long for the tail budget keeps its end rather than dropping the whole tail.
71
+ const last = lines.length - 1;
72
+ const slicedLast = tailStart > last && last > headEnd && tailBudget > 0;
73
+ const tailFrom = slicedLast ? last : tailStart;
74
+ const tail = slicedLast ? lines[last].slice(-tailBudget) : lines.slice(tailStart).join("\n");
75
+ const headFence = headEnd >= 0 ? open[headEnd] : null;
76
+ const tailFence = tail !== "" && tailFrom > 0 ? open[tailFrom - 1] : null;
77
+ const parts = [
78
+ headFence ? `${head}\n${fenceLine(headFence)}` : head,
79
+ marker(body.length - head.length - tail.length),
80
+ ];
81
+ if (tail !== "")
82
+ parts.push(tailFence ? `${fenceLine(tailFence)}\n${tail}` : tail);
83
+ return parts.join("\n\n");
84
+ }
@@ -18,6 +18,7 @@ export interface StackLayerView {
18
18
  isDraft?: true;
19
19
  isInMergeQueue?: true;
20
20
  requiresMergeQueue?: boolean;
21
+ requiresLinearHistory?: true;
21
22
  position?: number;
22
23
  stackSize?: number;
23
24
  baseRefName: string;
@@ -37,3 +38,4 @@ export interface StackLayerView {
37
38
  /** The `trunk behind` detail of a merge-top row, or undefined when trunk is not ahead. */
38
39
  export declare function trunkDetail(layer: StackLayerView): string | undefined;
39
40
  export declare function removalDetail(removal: StackLayerView["queueRemoval"]): string | undefined;
41
+ export declare function policyOf(layer: StackLayerView): string[];
@@ -9,3 +9,11 @@ export function removalDetail(removal) {
9
9
  return undefined;
10
10
  return `removed from merge queue (${removal.reason ?? "unknown reason"}${removal.actor ? ` by @${removal.actor}` : ""})`;
11
11
  }
12
+ export function policyOf(layer) {
13
+ return [
14
+ ...(layer.requiresMergeQueue === undefined
15
+ ? []
16
+ : [`merge queue ${layer.requiresMergeQueue ? "required" : "not required"}`]),
17
+ ...(layer.requiresLinearHistory ? ["linear history required"] : []),
18
+ ];
19
+ }
@@ -1,7 +1,7 @@
1
1
  import { stackLayerBlockReason } from "../commands/stack-layer-readiness.mjs";
2
2
  import { formatApiUsage, formatQuotaWarning } from "./api-usage-formatter.mjs";
3
3
  import { formatTransportEvidence, projectTransportEvidence } from "./transport-formatter.mjs";
4
- import { removalDetail, trunkDetail } from "./stack-layer-view.mjs";
4
+ import { policyOf, removalDetail, trunkDetail } from "./stack-layer-view.mjs";
5
5
  import { formatNextCheckLines } from "./next-check-format.mjs";
6
6
  import { formatPrUrl } from "../pr-reference.mjs";
7
7
  import { formatRuleAutoResolveLines } from "./rule-auto-resolve-lines.mjs";
@@ -49,6 +49,7 @@ function projectLayer(item, stale) {
49
49
  ...(item.isDraft && { isDraft: true }),
50
50
  ...(item.isInMergeQueue && { isInMergeQueue: true }),
51
51
  ...(item.requiresMergeQueue !== undefined && { requiresMergeQueue: item.requiresMergeQueue }),
52
+ ...(item.requiresLinearHistory && { requiresLinearHistory: true }),
52
53
  ...(item.stack && { position: item.stack.position, stackSize: item.stack.size }),
53
54
  baseRefName: item.baseRefName,
54
55
  ...(blocker === "failing-checks" &&
@@ -136,16 +137,14 @@ function formatLayerLines(layer, index, overview) {
136
137
  : layer.mergeable
137
138
  ? `mergeable${layer.shepherded ? "" : ", no READY receipt yet"}`
138
139
  : `not mergeable (\`${layer.blocker ?? "unknown"}\`)`,
139
- layer.author ? `owner \`@${layer.author}\`` : undefined,
140
+ layer.author ? `author \`@${layer.author}\`` : undefined,
140
141
  layer.owned ? "owned" : undefined,
141
142
  ].filter((fact) => fact !== undefined);
142
143
  const details = [
143
144
  layer.state,
144
145
  layer.isDraft ? "draft" : undefined,
145
146
  layer.isInMergeQueue ? "in merge queue" : undefined,
146
- layer.requiresMergeQueue !== undefined
147
- ? `merge queue ${layer.requiresMergeQueue ? "required" : "not required"}`
148
- : undefined,
147
+ ...policyOf(layer),
149
148
  !inOrder && layer.position !== undefined && layer.stackSize !== undefined
150
149
  ? `position ${layer.position}/${layer.stackSize}`
151
150
  : undefined,
@@ -173,7 +173,10 @@ export function formatTriageResult(header, result, opts = {}) {
173
173
  ? " [stale — review is on an old commit, all threads resolved; ask reviewer to re-review or dismiss]"
174
174
  : "";
175
175
  sections.push(`### \`reviewId=${r.id}\` (${renderAuthor(r.author, r.authorType, r.authorAssociation)})${renderReviewCommitTag(r)}${staleTag}`);
176
- sections.push(r.body.trim() === "" ? "(no review body)" : blockquote(r.body, topCap));
176
+ // The body is already capped by `iterate.changes-requested-review-max-chars`; it shows once.
177
+ sections.push(r.body.trim() === ""
178
+ ? "(no review body)"
179
+ : blockquote(r.body, verbose ? undefined : Infinity));
177
180
  }
178
181
  }
179
182
  if (result.triage.firstLookSummaries.length > 0) {
@@ -0,0 +1,2 @@
1
+ /** `admin watch-status <PR>`: prints whether a live watcher holds the PR; exit 17 if so, 65 when the lock is unreadable, else 0. */
2
+ export declare function handleWatchStatus(args: string[]): Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { EXIT } from "../exit-codes.mjs";
2
+ import { getRepoInfo } from "../github/client.mjs";
3
+ import { inspectWatcher } from "../state/watch-lock.mjs";
4
+ import { parseCommonArgs } from "./args.mjs";
5
+ import { maybePrintHelp, USAGE } from "./help.mjs";
6
+ import { rejectUnknownFlags } from "./unknown-flags.mjs";
7
+ /** `admin watch-status <PR>`: prints whether a live watcher holds the PR; exit 17 if so, 65 when the lock is unreadable, else 0. */
8
+ export async function handleWatchStatus(args) {
9
+ const command = "admin watch-status";
10
+ if (maybePrintHelp(args, command))
11
+ return;
12
+ if (rejectUnknownFlags(args, command, []))
13
+ return;
14
+ const { prNumber, global, extra } = parseCommonArgs(args);
15
+ if (prNumber === undefined || extra.length > 0) {
16
+ process.stderr.write(`pr-shepherd: ${command}: exactly one PR is required.\n`);
17
+ process.stderr.write(`${USAGE[command]}\n`);
18
+ process.exitCode = EXIT.USAGE;
19
+ return;
20
+ }
21
+ if (global.format !== "text" && global.format !== "json") {
22
+ process.stderr.write(`pr-shepherd: ${command}: --format must be "text" or "json".\n`);
23
+ process.exitCode = EXIT.USAGE;
24
+ return;
25
+ }
26
+ const repo = global.targetRepository ?? (await getRepoInfo());
27
+ const inspection = inspectWatcher(repo, prNumber);
28
+ const name = `${repo.owner}/${repo.name}`;
29
+ if (inspection.state === "unreadable") {
30
+ // `watched` is omitted: an unreadable lock proves neither answer.
31
+ if (global.format === "json") {
32
+ process.stdout.write(`${JSON.stringify({ repo: name, pr: prNumber, unreadable: true })}\n`);
33
+ }
34
+ else {
35
+ process.stdout.write(`${name}#${prNumber}: the watcher lock exists but is unreadable or not valid, so whether a watcher is live is unknown.\n`);
36
+ }
37
+ process.exitCode = EXIT.DATAERR;
38
+ return;
39
+ }
40
+ const holder = inspection.state === "live" ? inspection.holder : undefined;
41
+ if (global.format === "json") {
42
+ const report = holder
43
+ ? { repo: name, pr: prNumber, watched: true, pid: holder.pid, flags: holder.flags }
44
+ : { repo: name, pr: prNumber, watched: false };
45
+ process.stdout.write(`${JSON.stringify(report)}\n`);
46
+ }
47
+ else if (holder) {
48
+ const flags = holder.flags.length > 0 ? holder.flags.join(" ") : "none";
49
+ process.stdout.write(`${name}#${prNumber} is watched by PID ${holder.pid} (flags: ${flags}).\n`);
50
+ }
51
+ else {
52
+ process.stdout.write(`${name}#${prNumber} is not watched.\n`);
53
+ }
54
+ if (holder)
55
+ process.exitCode = EXIT.WATCHED;
56
+ }
@@ -17,6 +17,7 @@ import { handleJournalExtract } from "./cli/journal-extract-handler.mjs";
17
17
  import { handlePlaybook } from "./cli/playbook-handler.mjs";
18
18
  import { handlePoll, handleStack } from "./cli/poll-handler.mjs";
19
19
  import { warnPrrcThreadIds, validateRequireSha, rejectPrrcMinimizeIds, } from "./cli/resolve-validators.mjs";
20
+ import { handleWatchStatus } from "./cli/watch-status-handler.mjs";
20
21
  import { handleCheckBlocker } from "./cli/check-blocker-handler.mjs";
21
22
  import { handleQueueRemoval } from "./cli/queue-removal-handler.mjs";
22
23
  import { setupLog } from "./log/setup.mjs";
@@ -39,6 +40,7 @@ export async function main(argv) {
39
40
  extracted.args[0] === "-v" ||
40
41
  extracted.args[0] === "playbook" ||
41
42
  (extracted.args[0] === "admin" && extracted.args[1] === "log-file") ||
43
+ (extracted.args[0] === "admin" && extracted.args[1] === "watch-status") ||
42
44
  (extracted.args[0] === "journal" && extracted.args[1] === "extract")) {
43
45
  return dispatch(dispatched);
44
46
  }
@@ -102,6 +104,11 @@ async function dispatch(argv) {
102
104
  }
103
105
  return;
104
106
  }
107
+ // A read of one lock file: no GitHub, state writes, or log setup.
108
+ if (subcommand === "admin" && args[1] === "watch-status") {
109
+ await handleWatchStatus(args.slice(2));
110
+ return;
111
+ }
105
112
  // A local read of shipped files: no GitHub, git, or log I/O.
106
113
  if (subcommand === "playbook") {
107
114
  handlePlaybook(args.slice(1));
@@ -0,0 +1,56 @@
1
+ import type { RepoInfo } from "../github/client.mts";
2
+ import type { MergeMethod } from "../config/merge-method.mts";
3
+ import { GitHubRequestError } from "../github/errors.mts";
4
+ import { type RestMergeOptions } from "../github/rest-merge.mts";
5
+ import type { MergeRequestRecord } from "../state/merge-request.mts";
6
+ import type { PullState } from "./apply-merge-pull.mts";
7
+ import type { ApplyMergeResult } from "./apply-merge.mts";
8
+ import { type mergeResultFactory } from "./apply-merge-output.mts";
9
+ export type DefaultMergeResolution = {
10
+ kind: "method";
11
+ method: MergeMethod;
12
+ } | {
13
+ kind: "ambiguous";
14
+ allowed: MergeMethod[];
15
+ } | {
16
+ kind: "unknown";
17
+ };
18
+ /** The repository's single allowed merge method, when there is no queue and exactly one is on. */
19
+ export declare function resolveDefaultMergeMethod(repo: RepoInfo, pull: PullState): Promise<DefaultMergeResolution>;
20
+ /** The failure for an unreadable `default` status that could not be routed, naming the retry. */
21
+ export declare function unroutedDefaultMessage(status: number, resolution: DefaultMergeResolution): string;
22
+ /** Persist the repository's method once the status-read fallback resolved it. */
23
+ export declare function rememberRepoMergeMethod(repo: RepoInfo, method: MergeMethod, status: number): Promise<void>;
24
+ /**
25
+ * The method learned earlier for a `default` request, while REST still proves there is no queue
26
+ * and the repository settings still allow only that method. Settings that now allow another or a
27
+ * different method drop the cache. Undefined means the normal asynchronous route applies.
28
+ */
29
+ export declare function cachedDefaultMethod(repo: RepoInfo, pull: PullState, options: RestMergeOptions): Promise<MergeMethod | undefined>;
30
+ /**
31
+ * The synchronous SHA-guarded merge both routes share, under the request claim the caller holds.
32
+ * Only a merged answer retires the claim (only while the path still holds `record`, never a
33
+ * successor) and earns the success suffix. A 2xx that did not merge is a definite "not merged"
34
+ * answer: the `cached-method` route (no UUID, no other request that could land) records it as a
35
+ * failed response so a changed head or option can proceed; `sync-fallback` keeps its claim, since
36
+ * its UUID'd asynchronous request may still merge the PR. A definite 4xx
37
+ * refusal retires it; an unknown outcome (5xx, network) keeps it. A disabled method (405) also
38
+ * drops the repository's cached method.
39
+ */
40
+ export declare function settleSyncMerge(ctx: {
41
+ repo: RepoInfo;
42
+ pr: number;
43
+ key: {
44
+ owner: string;
45
+ repo: string;
46
+ pr: number;
47
+ };
48
+ record: MergeRequestRecord;
49
+ method: MergeMethod;
50
+ options: RestMergeOptions;
51
+ factory: ReturnType<typeof mergeResultFactory>;
52
+ suffix: string;
53
+ route: NonNullable<ApplyMergeResult["merge_route"]>;
54
+ /** Called on a definite 4xx refusal; a reason keeps the claim instead of retiring it. */
55
+ keepOnRefusal?: (refusal: GitHubRequestError) => Promise<string | null>;
56
+ }): Promise<ApplyMergeResult>;
@@ -0,0 +1,149 @@
1
+ import { GitHubRequestError } from "../github/errors.mjs";
2
+ import { restQueueRequirement } from "../github/poll-summary-rest-queue.mjs";
3
+ import { readRestBranchRules } from "../github/rest-rules-read.mjs";
4
+ import { readRest, restObject, restRepoPath } from "../github/rest-reader-core.mjs";
5
+ import { requestRestSyncMerge } from "../github/rest-merge.mjs";
6
+ import { clearMergeRequestIf, recordFailedResponseIf } from "../state/merge-request-clear.mjs";
7
+ import { clearRepoMergeMethod, readRepoMergeMethod, writeRepoMergeMethod, } from "../state/merge-method-cache.mjs";
8
+ import { withUnrecordedNote } from "./apply-merge-output.mjs";
9
+ const METHODS = [
10
+ ["merge", "allow_merge_commit"],
11
+ ["squash", "allow_squash_merge"],
12
+ ["rebase", "allow_rebase_merge"],
13
+ ];
14
+ /**
15
+ * True only when REST proves the base branch has no merge queue: the same positive-rules-or-
16
+ * complete-absence reading that routes `iterate` (`restQueueRequirement`). Classic branch
17
+ * protection, hidden or paged rules, and any failed read all answer "not proven", because REST
18
+ * exposes no queue flag of its own and `default` means "enqueue" on a queue repository.
19
+ */
20
+ async function proveNoMergeQueue(repo, pull) {
21
+ try {
22
+ const { baseRef, unavailable } = await readRestBranchRules(repo, pull.base.ref);
23
+ return (restQueueRequirement({
24
+ ...(baseRef && { baseRef }),
25
+ transportUnavailable: unavailable,
26
+ }) === false);
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /** The repository's single allowed merge method, when there is no queue and exactly one is on. */
33
+ export async function resolveDefaultMergeMethod(repo, pull) {
34
+ if (!(await proveNoMergeQueue(repo, pull)))
35
+ return { kind: "unknown" };
36
+ let settings;
37
+ try {
38
+ settings = restObject(await readRest("GET", restRepoPath(repo)), "repository");
39
+ }
40
+ catch {
41
+ return { kind: "unknown" };
42
+ }
43
+ const allowed = METHODS.filter(([, field]) => settings[field] === true).map(([method]) => method);
44
+ if (allowed.length === 1)
45
+ return { kind: "method", method: allowed[0] };
46
+ return allowed.length > 1 ? { kind: "ambiguous", allowed } : { kind: "unknown" };
47
+ }
48
+ /** The failure for an unreadable `default` status that could not be routed, naming the retry. */
49
+ export function unroutedDefaultMessage(status, resolution) {
50
+ const retry = resolution.kind === "ambiguous"
51
+ ? `retry with one of: ${resolution.allowed
52
+ .map((method) => `--merge-action direct_merge --method ${method}`)
53
+ .join(" ; ")}`
54
+ : "if the repository has no merge queue, retry with --merge-action direct_merge --method <m> using a method it allows";
55
+ return `The asynchronous merge status is unavailable (${status}). The PR is not merged; its request outcome is unknown and no duplicate was submitted. Shepherd did not choose a merge method for you: ${retry}.`;
56
+ }
57
+ /** GitHub names a disabled method in its 405, unlike the 405 of a pull that is not mergeable. */
58
+ function isMethodRefusal(error) {
59
+ return (error instanceof GitHubRequestError &&
60
+ error.status === 405 &&
61
+ /not allowed/i.test(error.message));
62
+ }
63
+ /** Persist the repository's method once the status-read fallback resolved it. */
64
+ export async function rememberRepoMergeMethod(repo, method, status) {
65
+ await writeRepoMergeMethod({ owner: repo.owner, repo: repo.name }, {
66
+ method,
67
+ reason: `merge-async-status-${status}`,
68
+ recordedAt: Math.floor(Date.now() / 1000),
69
+ });
70
+ }
71
+ /**
72
+ * The method learned earlier for a `default` request, while REST still proves there is no queue
73
+ * and the repository settings still allow only that method. Settings that now allow another or a
74
+ * different method drop the cache. Undefined means the normal asynchronous route applies.
75
+ */
76
+ export async function cachedDefaultMethod(repo, pull, options) {
77
+ if (options.mergeAction !== "default" || options.expectedStack)
78
+ return undefined;
79
+ const cacheKey = { owner: repo.owner, repo: repo.name };
80
+ const cached = await readRepoMergeMethod(cacheKey);
81
+ if (!cached)
82
+ return undefined;
83
+ const resolution = await resolveDefaultMergeMethod(repo, pull);
84
+ if (resolution.kind === "method" && resolution.method === cached.method)
85
+ return cached.method;
86
+ if (resolution.kind !== "unknown")
87
+ await clearRepoMergeMethod(cacheKey);
88
+ return undefined;
89
+ }
90
+ /**
91
+ * The synchronous SHA-guarded merge both routes share, under the request claim the caller holds.
92
+ * Only a merged answer retires the claim (only while the path still holds `record`, never a
93
+ * successor) and earns the success suffix. A 2xx that did not merge is a definite "not merged"
94
+ * answer: the `cached-method` route (no UUID, no other request that could land) records it as a
95
+ * failed response so a changed head or option can proceed; `sync-fallback` keeps its claim, since
96
+ * its UUID'd asynchronous request may still merge the PR. A definite 4xx
97
+ * refusal retires it; an unknown outcome (5xx, network) keeps it. A disabled method (405) also
98
+ * drops the repository's cached method.
99
+ */
100
+ export async function settleSyncMerge(ctx) {
101
+ const { repo, pr, key, record, method, options, factory, suffix, route, keepOnRefusal } = ctx;
102
+ try {
103
+ const response = await requestRestSyncMerge(repo, pr, {
104
+ requireSha: options.requireSha,
105
+ mergeMethod: method,
106
+ });
107
+ const merged = response.status === "merged";
108
+ if (merged)
109
+ await clearMergeRequestIf(key, record);
110
+ // An unrecordable failure names the stuck state the next run meets.
111
+ const unrecorded = !merged &&
112
+ route === "cached-method" &&
113
+ !(await recordFailedResponseIf(key, record, response.details));
114
+ return {
115
+ ...factory.project(merged
116
+ ? {
117
+ ...response,
118
+ details: { ...response.details, message: `${response.details.message} ${suffix}` },
119
+ }
120
+ : unrecorded
121
+ ? withUnrecordedNote(response, pr)
122
+ : response),
123
+ merge_route: route,
124
+ };
125
+ }
126
+ catch (error) {
127
+ const refused = error instanceof GitHubRequestError && error.status >= 400 && error.status < 500;
128
+ const kept = refused ? ((await keepOnRefusal?.(error)) ?? null) : null;
129
+ if (refused && kept === null)
130
+ await clearMergeRequestIf(key, record);
131
+ if (options.mergeAction === "default" && isMethodRefusal(error))
132
+ await clearRepoMergeMethod({ owner: repo.owner, repo: repo.name });
133
+ // Name why the record stayed, so a later "already sent" report is not a mystery; the status
134
+ // and exit code stay GitHub's, so batches still stop.
135
+ if (kept !== null && error instanceof GitHubRequestError)
136
+ throw new GitHubRequestError(`${error.message} The merge request record, its UUID, and the sent fallback marker were kept because ${kept}`, {
137
+ status: error.status,
138
+ ...(error.rateLimit !== undefined && { rateLimit: error.rateLimit }),
139
+ ...(error.retryAfterSeconds !== undefined && {
140
+ retryAfterSeconds: error.retryAfterSeconds,
141
+ }),
142
+ ...(error.responseMessage !== undefined && { responseMessage: error.responseMessage }),
143
+ ...(error.authSource !== undefined && { authSource: error.authSource }),
144
+ exitCodeOverride: error.exitCode,
145
+ cause: error,
146
+ });
147
+ throw error;
148
+ }
149
+ }
@@ -5,3 +5,5 @@ export declare function mergeResultFactory(pr: number, repo: RepoInfo, options:
5
5
  failed: (message: string, uncertain?: true) => ApplyMergeResult;
6
6
  project: (response: RestMergeResponse) => ApplyMergeResult;
7
7
  };
8
+ /** A failed answer the lock kept from being recorded, naming the stuck state the next run meets. */
9
+ export declare const withUnrecordedNote: (response: RestMergeResponse, pr: number) => RestMergeResponse;
@@ -18,3 +18,11 @@ export function mergeResultFactory(pr, repo, options) {
18
18
  });
19
19
  return { failed, project };
20
20
  }
21
+ /** A failed answer the lock kept from being recorded, naming the stuck state the next run meets. */
22
+ export const withUnrecordedNote = (response, pr) => ({
23
+ ...response,
24
+ details: {
25
+ ...response.details,
26
+ message: `${response.details.message} This failure could not be recorded (the merge request lock was busy or the record changed). If the original request record is still there, a rerun reports an unknown outcome with no UUID, and its message names \`pr-shepherd admin clean pr ${pr}\`; if another request replaced or removed it, a rerun follows that record instead.`,
27
+ },
28
+ });
@@ -6,6 +6,9 @@ export interface PullState {
6
6
  head: {
7
7
  sha: string;
8
8
  };
9
+ base: {
10
+ ref: string;
11
+ };
9
12
  merge_commit_sha?: string;
10
13
  }
11
14
  /**
@@ -1,9 +1,9 @@
1
1
  import type { RepoInfo } from "../github/client.mts";
2
2
  import { type RestMergeOptions } from "../github/rest-merge.mts";
3
- import { type MergeRequestRecord } from "../state/merge-request.mts";
3
+ import type { MergeRequestRecord } from "../state/merge-request.mts";
4
4
  import type { mergeResultFactory } from "./apply-merge-output.mts";
5
5
  import type { ApplyMergeResult } from "./apply-merge.mts";
6
- interface ResumeContext {
6
+ export interface ResumeContext {
7
7
  repo: RepoInfo;
8
8
  pr: number;
9
9
  key: {
@@ -19,4 +19,3 @@ interface ResumeContext {
19
19
  }
20
20
  /** Resume a recorded asynchronous request, falling back to the synchronous merge when unreadable. */
21
21
  export declare function resumeMergeRequest(ctx: ResumeContext): Promise<ApplyMergeResult>;
22
- export {};
@@ -1,7 +1,12 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  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";
3
+ import { getRestMerge, matchesRestMergeRequest, } from "../github/rest-merge.mjs";
4
+ import { updateMergeRequestStatusLocked } from "../state/merge-request-claim.mjs";
5
+ import { describeStackDrift, movedStackLayerHeads } from "./stack-lower-heads.mjs";
4
6
  import { mergedResponse, readPull } from "./apply-merge-pull.mjs";
7
+ import { rememberRepoMergeMethod, resolveDefaultMergeMethod, unroutedDefaultMessage, } from "./apply-merge-default-route.mjs";
8
+ import { syncFallback, syncSentMessage } from "./apply-merge-sync-fallback.mjs";
9
+ import { stackedFailure, unreadableStatusMessage } from "./apply-merge-stack-membership.mjs";
5
10
  /** Resume a recorded asynchronous request, falling back to the synchronous merge when unreadable. */
6
11
  export async function resumeMergeRequest(ctx) {
7
12
  const { repo, pr, key, existing, options, factory } = ctx;
@@ -11,7 +16,41 @@ export async function resumeMergeRequest(ctx) {
11
16
  if (response.status === "pending" &&
12
17
  (!matchesRestMergeRequest(response, options) || response.details.uuid !== existing.uuid))
13
18
  return failed("Asynchronous merge status does not match the persisted guarded request.", true);
14
- await writeMergeRequestStatus(key, { ...existing, response });
19
+ // A readable status ends the unreadable episode: the `direct_merge` retry may no longer
20
+ // supersede this request.
21
+ const recorded = await updateMergeRequestStatusLocked(key, existing, (current) => {
22
+ const { statusUnreadable: _readable, ...readable } = current;
23
+ return { ...readable, response, statusRevision: randomUUID() };
24
+ });
25
+ // Only a write under the lock proves no unreadable marker remains; reporting pending while one
26
+ // might would let the `direct_merge` retry supersede a request GitHub just reported.
27
+ if (!recorded && response.status === "pending")
28
+ return failed("The asynchronous merge status is readable, but another `apply merge` run held the merge-request lock, so the readable status was not recorded. Rerun this command.", true);
29
+ // GitHub offers no way to cancel a pending request, and it binds only the top head, so a
30
+ // lower layer pushed since validation can only be reported, not prevented.
31
+ // The persisted baseline covers requests submitted without an `expectedStack`; the guard's
32
+ // prefix covers records written before the baseline was kept.
33
+ const baseline = existing.stackHeads ??
34
+ options.expectedStack?.prefix.map((layer) => ({
35
+ pr: layer.pr,
36
+ headRefOid: layer.headRefOid,
37
+ }));
38
+ const drift = response.status === "pending" && baseline
39
+ ? await movedStackLayerHeads(pr, repo, baseline).catch(() => undefined)
40
+ : null;
41
+ if (drift === undefined)
42
+ return {
43
+ ...project(response),
44
+ uncertain: true,
45
+ note: "Stack layer heads could not be re-read; a lower-layer push since validation cannot be ruled out. This pending request cannot be cancelled and may merge an unapproved commit. Rerun this command, check the PR on GitHub, and report this to the user.",
46
+ };
47
+ const drifted = drift && describeStackDrift(drift);
48
+ if (drifted)
49
+ return {
50
+ ...project(response),
51
+ uncertain: true,
52
+ note: `${drifted}. This pending request cannot be cancelled and may merge the unapproved commit. Check the PR on GitHub and report this to the user.`,
53
+ };
15
54
  return project(response);
16
55
  }
17
56
  catch (error) {
@@ -23,34 +62,37 @@ export async function resumeMergeRequest(ctx) {
23
62
  const latest = await readPull(repo, pr);
24
63
  if (latest.merged === true)
25
64
  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;
65
+ if (existing.syncMergeSent)
66
+ return failed(syncSentMessage(pr), true);
67
+ // The synchronous route guards the head SHA itself. A direct merge names its method; a
68
+ // `default` request has none, so a repository without a merge queue and with exactly one
69
+ // allowed method supplies it. Queue, method-less, and native-stack requests otherwise have no
70
+ // synchronous equivalent, so their unknown outcome stays blocked.
71
+ if (options.expectedStack ||
72
+ existing.stackHeads ||
73
+ options.mergeAction === "merge_queue" ||
74
+ (options.mergeAction === "direct_merge" && !options.mergeMethod))
75
+ return failed(unreadableStatusMessage(error.status), true);
76
+ // Older records may lack a stack baseline, and the PR may have joined a stack since submission;
77
+ // `syncFallback` reads membership right before its claim.
78
+ if (options.mergeAction === "direct_merge" && options.mergeMethod)
79
+ return syncFallback(ctx, options.mergeMethod, error.status);
80
+ // Read before resolution too, so a stacked PR never caches a repository method.
81
+ const stacked = await stackedFailure(ctx, error.status);
82
+ if (stacked)
83
+ return stacked;
84
+ const resolution = await resolveDefaultMergeMethod(repo, latest);
85
+ if (resolution.kind === "method") {
86
+ // Cached only once the final membership check confirms the PR is standalone.
87
+ return syncFallback(ctx, resolution.method, error.status, () => rememberRepoMergeMethod(repo, resolution.method, error.status));
88
+ }
89
+ // The pending request may still execute, so the outcome stays uncertain. The marker lets the
90
+ // `direct_merge` retry named in the message replace this request instead of being blocked by it.
91
+ // A readable status another run recorded since this run read the request is newer than this
92
+ // refusal, even when its response is unchanged, so it keeps the marker off.
93
+ await updateMergeRequestStatusLocked(key, existing, (current) => current.statusRevision === existing.statusRevision
94
+ ? { ...current, statusUnreadable: true }
95
+ : null);
96
+ return failed(unroutedDefaultMessage(error.status, resolution), true);
55
97
  }
56
98
  }