pr-shepherd 2.0.0 → 2.2.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 (194) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +41 -32
  3. package/bin/api.d.mts +10 -2
  4. package/bin/api.mjs +30 -6
  5. package/bin/checks/pending-deployments.d.mts +10 -0
  6. package/bin/checks/pending-deployments.mjs +66 -0
  7. package/bin/checks/run-workflow-paths.d.mts +7 -0
  8. package/bin/checks/run-workflow-paths.mjs +19 -0
  9. package/bin/checks/triage.mjs +3 -2
  10. package/bin/checks/unreported-required.d.mts +11 -1
  11. package/bin/checks/unreported-required.mjs +8 -3
  12. package/bin/checks/workflow-concurrency.d.mts +9 -0
  13. package/bin/checks/workflow-concurrency.mjs +84 -0
  14. package/bin/checks/workflow-path.d.mts +2 -0
  15. package/bin/checks/workflow-path.mjs +4 -0
  16. package/bin/classify/standard/dependency-review-no-issues.d.mts +4 -0
  17. package/bin/classify/standard/dependency-review-no-issues.mjs +16 -0
  18. package/bin/classify/standard/index.mjs +8 -0
  19. package/bin/classify/standard/snyk-no-issues.d.mts +7 -0
  20. package/bin/classify/standard/snyk-no-issues.mjs +27 -0
  21. package/bin/classify/standard/socket-reports.d.mts +4 -0
  22. package/bin/classify/standard/socket-reports.mjs +18 -0
  23. package/bin/classify/standard/sonarqube-gate-passed.d.mts +7 -0
  24. package/bin/classify/standard/sonarqube-gate-passed.mjs +41 -0
  25. package/bin/cli/arg-flags.mjs +3 -0
  26. package/bin/cli/clean-handler.mjs +1 -1
  27. package/bin/cli/default-poll.mjs +1 -0
  28. package/bin/cli/handlers.mjs +2 -0
  29. package/bin/cli/help-command-pages.d.mts +5 -4
  30. package/bin/cli/help-command-pages.mjs +2 -1
  31. package/bin/cli/help-iterate-poll-pages.d.mts +3 -3
  32. package/bin/cli/help-iterate-poll-pages.mjs +10 -2
  33. package/bin/cli/help-top-page.d.mts +1 -1
  34. package/bin/cli/help-top-page.mjs +2 -2
  35. package/bin/cli/help.d.mts +6 -5
  36. package/bin/cli/in-progress-run-format.d.mts +3 -0
  37. package/bin/cli/in-progress-run-format.mjs +14 -0
  38. package/bin/cli/iterate-activity-formatter.d.mts +2 -0
  39. package/bin/cli/iterate-activity-formatter.mjs +11 -0
  40. package/bin/cli/iterate-flags.d.mts +3 -0
  41. package/bin/cli/iterate-flags.mjs +18 -1
  42. package/bin/cli/iterate-formatter.mjs +2 -1
  43. package/bin/cli/iterate-lean.mjs +2 -0
  44. package/bin/cli/pending-deployments-format.d.mts +5 -0
  45. package/bin/cli/pending-deployments-format.mjs +19 -0
  46. package/bin/cli/poll-handler.d.mts +1 -1
  47. package/bin/cli/poll-handler.mjs +33 -10
  48. package/bin/cli/poll-targets.mjs +2 -0
  49. package/bin/cli/stack-merge-args.d.mts +10 -0
  50. package/bin/cli/stack-merge-args.mjs +27 -0
  51. package/bin/cli/stack-overview.d.mts +1 -0
  52. package/bin/cli/stack-overview.mjs +5 -1
  53. package/bin/cli/stalled-check-format.d.mts +3 -0
  54. package/bin/cli/stalled-check-format.mjs +23 -0
  55. package/bin/cli/suggestion-renderer.mjs +6 -0
  56. package/bin/cli/triage-formatter.mjs +14 -0
  57. package/bin/commands/check.mjs +7 -2
  58. package/bin/commands/clean.d.mts +1 -1
  59. package/bin/commands/clean.mjs +7 -0
  60. package/bin/commands/iterate/check-follow-up.d.mts +9 -0
  61. package/bin/commands/iterate/check-follow-up.mjs +34 -0
  62. package/bin/commands/iterate/ci-start-stall.d.mts +23 -0
  63. package/bin/commands/iterate/ci-start-stall.mjs +33 -0
  64. package/bin/commands/iterate/duration-approx.d.mts +2 -0
  65. package/bin/commands/iterate/duration-approx.mjs +8 -0
  66. package/bin/commands/iterate/escalate.d.mts +8 -17
  67. package/bin/commands/iterate/escalate.mjs +19 -48
  68. package/bin/commands/iterate/helpers.mjs +1 -0
  69. package/bin/commands/iterate/in-progress-runs.d.mts +10 -0
  70. package/bin/commands/iterate/in-progress-runs.mjs +120 -0
  71. package/bin/commands/iterate/index.mjs +12 -6
  72. package/bin/commands/iterate/merge-plan.d.mts +2 -0
  73. package/bin/commands/iterate/merge-plan.mjs +2 -1
  74. package/bin/commands/iterate/merge-state.d.mts +2 -0
  75. package/bin/commands/iterate/merge-state.mjs +8 -21
  76. package/bin/commands/iterate/native-stack-rebase.d.mts +3 -2
  77. package/bin/commands/iterate/native-stack-rebase.mjs +32 -11
  78. package/bin/commands/iterate/queue-removal.d.mts +19 -0
  79. package/bin/commands/iterate/queue-removal.mjs +64 -0
  80. package/bin/commands/iterate/render.d.mts +2 -1
  81. package/bin/commands/iterate/render.mjs +4 -1
  82. package/bin/commands/iterate/stack-boundary.d.mts +17 -0
  83. package/bin/commands/iterate/stack-boundary.mjs +95 -0
  84. package/bin/commands/iterate/stall-repair.d.mts +17 -0
  85. package/bin/commands/iterate/stall-repair.mjs +25 -0
  86. package/bin/commands/iterate/stall.d.mts +1 -1
  87. package/bin/commands/iterate/stall.mjs +27 -18
  88. package/bin/commands/iterate/state-unavailable.d.mts +8 -0
  89. package/bin/commands/iterate/state-unavailable.mjs +23 -0
  90. package/bin/commands/iterate/triage-loop-instruction.mjs +1 -1
  91. package/bin/commands/iterate/triage.mjs +41 -74
  92. package/bin/commands/iterate/unreported-required.d.mts +5 -2
  93. package/bin/commands/iterate/unreported-required.mjs +13 -8
  94. package/bin/commands/iterate/workflow-files.d.mts +27 -0
  95. package/bin/commands/iterate/workflow-files.mjs +85 -0
  96. package/bin/commands/poll-summary-explicit-instructions.mjs +15 -1
  97. package/bin/commands/poll-summary-instructions.d.mts +4 -3
  98. package/bin/commands/poll-summary-instructions.mjs +60 -22
  99. package/bin/commands/poll-summary.mjs +38 -10
  100. package/bin/commands/poll.mjs +4 -2
  101. package/bin/commands/stack-drain.d.mts +4 -4
  102. package/bin/commands/stack-drain.mjs +19 -113
  103. package/bin/commands/stack-handoffs.d.mts +3 -3
  104. package/bin/commands/stack-handoffs.mjs +8 -8
  105. package/bin/commands/stack-lower-ready-note.d.mts +6 -0
  106. package/bin/commands/stack-lower-ready-note.mjs +35 -0
  107. package/bin/commands/stack-merge-escalations.d.mts +17 -0
  108. package/bin/commands/stack-merge-escalations.mjs +57 -0
  109. package/bin/commands/stack-merge-plan.d.mts +10 -0
  110. package/bin/commands/stack-merge-plan.mjs +132 -0
  111. package/bin/commands/stack-merge-scope.d.mts +42 -0
  112. package/bin/commands/stack-merge-scope.mjs +113 -0
  113. package/bin/commands/stack-ownership.d.mts +25 -0
  114. package/bin/commands/stack-ownership.mjs +85 -0
  115. package/bin/commands/stack-stall.d.mts +2 -0
  116. package/bin/commands/stack-stall.mjs +25 -3
  117. package/bin/commands/stack-targets-error.d.mts +16 -0
  118. package/bin/commands/stack-targets-error.mjs +44 -0
  119. package/bin/commands/stack-targets.d.mts +30 -0
  120. package/bin/commands/stack-targets.mjs +121 -0
  121. package/bin/commands/stack-work.d.mts +4 -3
  122. package/bin/commands/stack-work.mjs +7 -4
  123. package/bin/commands/tick.mjs +14 -2
  124. package/bin/config/renames.mjs +1 -1
  125. package/bin/config/schema.d.mts +4 -0
  126. package/bin/config/schema.mjs +2 -0
  127. package/bin/github/batch-parse-suites.d.mts +4 -1
  128. package/bin/github/batch-parse-suites.mjs +15 -3
  129. package/bin/github/batch-raw-types.d.mts +6 -0
  130. package/bin/github/gql/commit-check-suites.gql +6 -0
  131. package/bin/github/gql/poll-summary-fragment.gql +6 -0
  132. package/bin/github/poll-summary-command.d.mts +15 -1
  133. package/bin/github/poll-summary-command.mjs +39 -3
  134. package/bin/github/poll-summary-projector.d.mts +1 -1
  135. package/bin/github/poll-summary-projector.mjs +1 -4
  136. package/bin/github/poll-summary-raw.d.mts +6 -0
  137. package/bin/github/poll-summary-route.mjs +4 -1
  138. package/bin/github/poll-summary.mjs +10 -3
  139. package/bin/github/rest-batch-read.mjs +17 -6
  140. package/bin/github/rest-batch-snapshot.d.mts +2 -2
  141. package/bin/github/rest-batch-snapshot.mjs +3 -0
  142. package/bin/github/rest-check-read.d.mts +1 -18
  143. package/bin/github/rest-check-read.mjs +1 -2
  144. package/bin/github/rest-stack-read.d.mts +9 -0
  145. package/bin/github/rest-stack-read.mjs +40 -0
  146. package/bin/github/rest-suite-types.d.mts +23 -0
  147. package/bin/github/rest-suite-types.mjs +1 -0
  148. package/bin/github/rest-summary-read.mjs +2 -0
  149. package/bin/mcp/server.mjs +29 -3
  150. package/bin/pr-reference.d.mts +2 -0
  151. package/bin/pr-reference.mjs +1 -1
  152. package/bin/reporters/agent.mjs +3 -0
  153. package/bin/state/check-follow-up.d.mts +30 -0
  154. package/bin/state/check-follow-up.mjs +51 -0
  155. package/bin/state/ci-start-follow-up.d.mts +14 -0
  156. package/bin/state/ci-start-follow-up.mjs +21 -0
  157. package/bin/state/queue-removal-follow-up.d.mts +20 -0
  158. package/bin/state/queue-removal-follow-up.mjs +23 -0
  159. package/bin/state/signature-marker.d.mts +10 -0
  160. package/bin/state/signature-marker.mjs +28 -0
  161. package/bin/state/stack-merge-approval.d.mts +26 -0
  162. package/bin/state/stack-merge-approval.mjs +39 -0
  163. package/bin/state/stall-repair.d.mts +16 -0
  164. package/bin/state/stall-repair.mjs +47 -0
  165. package/bin/types/activity.d.mts +2 -1
  166. package/bin/types/escalate.d.mts +9 -2
  167. package/bin/types/github.d.mts +18 -0
  168. package/bin/types/in-progress-run.d.mts +20 -0
  169. package/bin/types/in-progress-run.mjs +1 -0
  170. package/bin/types/iterate.d.mts +22 -1
  171. package/bin/types/poll-summary.d.mts +18 -1
  172. package/bin/types/report.d.mts +5 -1
  173. package/bin/types.d.mts +1 -0
  174. package/bin/types.mjs +1 -0
  175. package/package.json +2 -2
  176. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  177. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  178. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  179. package/plugins/pr-shepherd/.mcp.json +1 -1
  180. package/plugins/pr-shepherd/hooks/poll-guard-args.mjs +49 -0
  181. package/plugins/pr-shepherd/hooks/poll-guard-detect.mjs +134 -26
  182. package/plugins/pr-shepherd/hooks/poll-guard-shell.mjs +192 -0
  183. package/plugins/pr-shepherd/package-lock.json +7 -7
  184. package/plugins/pr-shepherd/package.json +1 -1
  185. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +8 -7
  186. package/plugins/pr-shepherd/skills/pr-shepherd/references/check-follow-up.md +14 -0
  187. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-failure-triage.md +6 -5
  188. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-start-stall.md +15 -0
  189. package/plugins/pr-shepherd/skills/pr-shepherd/references/create-a-pr.md +4 -1
  190. package/plugins/pr-shepherd/skills/pr-shepherd/references/mcp-fallback.md +1 -1
  191. package/plugins/pr-shepherd/skills/pr-shepherd/references/merge-queue-ejection.md +6 -5
  192. package/plugins/pr-shepherd/skills/pr-shepherd/references/required-checks-unreported.md +16 -0
  193. package/plugins/pr-shepherd/skills/reduce-pr-noise/references/classifiers.md +1 -1
  194. package/pr-shepherd.schema.json +15 -0
@@ -1,6 +1,8 @@
1
1
  /* eslint-disable max-lines */
2
2
  import { renderReviewCommitTag } from "../../cli/list-formatters.mjs";
3
3
  import { renderRelatedJobLines } from "../../cli/related-jobs-format.mjs";
4
+ import { renderPendingDeploymentLines } from "../../cli/pending-deployments-format.mjs";
5
+ import { renderStalledCheckLines } from "../../cli/stalled-check-format.mjs";
4
6
  import { loadConfig } from "../../config/load.mjs";
5
7
  import { renderResolveCommand } from "./render.mjs";
6
8
  function renderEscalateAuthor(item) {
@@ -58,6 +60,7 @@ function renderEscalateCheck(check) {
58
60
  if (check.logExcerpt)
59
61
  lines.push(...renderBlockquoteLines(check.logExcerpt, " "));
60
62
  lines.push(...renderRelatedJobLines(check.relatedJobs));
63
+ lines.push(...renderPendingDeploymentLines(check.pendingDeployments));
61
64
  if (check.rerunCommand)
62
65
  lines.push(` rerun: \`${check.rerunCommand}\``);
63
66
  for (const annotation of check.annotations ?? []) {
@@ -80,42 +83,19 @@ export function checkEscalateTriggers(actionableThreads, threadAttempts) {
80
83
  : undefined,
81
84
  };
82
85
  }
86
+ export { formatDurationApprox } from "./duration-approx.mjs";
87
+ /** Stands in for a base branch name that failed validation, in prose only. */
88
+ const UNKNOWN_BASE_BRANCH = "<base branch>";
83
89
  /**
84
- * Validate the base branch name from the GraphQL batch (`report.baseBranch`)
85
- * and fall back safely if it's missing/unsafe. The branch is interpolated into
86
- * shell commands by `buildFixInstructions`, so we reject anything outside
87
- * `[A-Za-z0-9._/-]` to prevent shell injection.
90
+ * Validate the base branch name from the GraphQL batch (`report.baseBranch`). The branch is
91
+ * interpolated into printed shell commands, so a name outside `[A-Za-z0-9._/-]` (or an empty
92
+ * one) is `unusable`: callers omit the command and tell the agent to read the base from the PR.
88
93
  */
89
- /**
90
- * Render a seconds count as an approximate human duration: "8 seconds" below one minute,
91
- * otherwise whole minutes ("166 minutes", "60 minutes") — matching the precision the
92
- * generic stall timer has always reported, just adding a seconds tier for sub-minute ages
93
- * instead of always flooring to "0 minutes".
94
- */
95
- export function formatDurationApprox(seconds) {
96
- const s = Math.max(0, Math.floor(seconds));
97
- if (s < 60)
98
- return `${s} second${s === 1 ? "" : "s"}`;
99
- const mins = Math.floor(s / 60);
100
- return `${mins} minute${mins === 1 ? "" : "s"}`;
101
- }
102
94
  export function validateBaseBranch(raw) {
103
95
  const trimmed = raw.trim();
104
- if (trimmed === "") {
105
- return {
106
- branch: "main",
107
- isFallback: true,
108
- failureReason: "GraphQL batch returned an empty base branch name",
109
- };
110
- }
111
- if (!/^[A-Za-z0-9._/-]+$/.test(trimmed)) {
112
- return {
113
- branch: "main",
114
- isFallback: true,
115
- failureReason: `base branch ${JSON.stringify(trimmed)} contains unsafe characters`,
116
- };
117
- }
118
- return { branch: trimmed, isFallback: false };
96
+ return /^[A-Za-z0-9._/-]+$/.test(trimmed)
97
+ ? { branch: trimmed, unusable: false }
98
+ : { branch: UNKNOWN_BASE_BRANCH, unusable: true };
119
99
  }
120
100
  export function buildEscalateHumanMessage(escalate, pr, opts) {
121
101
  const lines = [];
@@ -135,16 +115,8 @@ export function buildEscalateHumanMessage(escalate, pr, opts) {
135
115
  lines.push("");
136
116
  lines.push("## Items needing attention");
137
117
  lines.push("");
138
- for (const c of escalate.stalledChecks ?? []) {
139
- const target = c.runId
140
- ? `run \`${c.runId}\``
141
- : c.detailsUrl
142
- ? `external \`${c.detailsUrl}\``
143
- : "no run ID";
144
- lines.push(`- check \`${c.name}\` — ${c.status} ${c.source}, ${target}, waiting ${formatDurationApprox(c.ageSeconds)}`);
145
- if (c.summary)
146
- lines.push(` > ${c.summary}`);
147
- }
118
+ for (const c of escalate.stalledChecks ?? [])
119
+ lines.push(...renderStalledCheckLines(c));
148
120
  if ((escalate.stalledChecks?.length ?? 0) > 0)
149
121
  lines.push("");
150
122
  for (const check of escalate.checks ?? []) {
@@ -243,6 +215,9 @@ export function buildEscalateHumanMessage(escalate, pr, opts) {
243
215
  }
244
216
  export function buildEscalateSuggestion(triggers, detail) {
245
217
  if (triggers.includes("check-follow-up-unavailable")) {
218
+ if (detail === "investigated") {
219
+ return "The failing checks below had no rerun and no log excerpt Shepherd could show. After one investigation tick they are unchanged on this head. Report what the investigation found. What remains is a repository, CI-configuration, or workflow-permission change, or waiting out a GitHub incident; each is a human decision.";
220
+ }
246
221
  return "One or more failing checks have no autonomous follow-up available. Use the displayed conclusion, run or URL, and included evidence to handle them manually.";
247
222
  }
248
223
  if (triggers.includes("authorization-required")) {
@@ -250,7 +225,7 @@ export function buildEscalateSuggestion(triggers, detail) {
250
225
  }
251
226
  if (triggers.includes("merge-queue-removed")) {
252
227
  const reason = detail ? ` GitHub reason: ${detail}.` : "";
253
- return `The PR left the merge queue without an actionable check failure.${reason} Confirm the removal was not intentional before adding it again.`;
228
+ return `The PR left the merge queue without an actionable check failure, and the removal was unchanged after one investigation tick.${reason} Report what the investigation found. Confirm the removal was not intentional before adding it again.`;
254
229
  }
255
230
  if (triggers.includes("stall-timeout")) {
256
231
  const duration = detail ?? "60 minutes";
@@ -258,16 +233,12 @@ export function buildEscalateSuggestion(triggers, detail) {
258
233
  }
259
234
  if (triggers.includes("required-checks-unreported")) {
260
235
  const names = detail ? ` (${detail})` : "";
261
- return `Required checks are still unreported${names}, and no CI is running. Rebase and push is the fix when the branch is behind. This head is current, and another reopen will not create a job the workflow does not emit. Path filters are the usual cause. Investigate that, then handle the missing checks manually.`;
236
+ return `Required checks are still unreported${names}: no CI ran on this head after the investigation tick and one retrigger, and no CI is running. Report what the investigation found. What remains is a repository, CI-configuration, or branch-policy change, or waiting out a GitHub incident; each is a human decision.`;
262
237
  }
263
238
  if (triggers.includes("stall-state-unavailable")) {
264
239
  const reason = detail ?? "unknown error";
265
240
  return `The stall timer could not be saved (${reason}). Fix PR_SHEPHERD_STATE_DIR or the directory permissions, then resume. Automated polling is paused because a stuck loop would not be detected.`;
266
241
  }
267
- if (triggers.includes("base-branch-unknown")) {
268
- const reason = detail ? ` (${detail})` : "";
269
- return `Could not determine the PR's base branch${reason} — automated rebases are paused because branch safety is unclear. Run the rebase manually against the PR's real target branch.`;
270
- }
271
242
  if (triggers.includes("triage-thrash")) {
272
243
  const attempts = loadConfig().iterate["triage-attempts-per-thread"];
273
244
  return `The same thread(s) remain unresolved after their pending review commands were returned for ${attempts} TRIAGE ticks. Automated iteration is paused for a manual decision.`;
@@ -106,6 +106,7 @@ export function buildActiveChecks(report) {
106
106
  detailsUrl: c.detailsUrl || null,
107
107
  ...(c.workflowName !== undefined && { workflowName: c.workflowName }),
108
108
  ...(c.summary !== undefined && { summary: c.summary }),
109
+ ...(c.pendingDeployments !== undefined && { pendingDeployments: c.pendingDeployments }),
109
110
  ...(c.scope !== undefined && { scope: c.scope }),
110
111
  ...(c.commitOid !== undefined && { commitOid: c.commitOid }),
111
112
  }));
@@ -0,0 +1,10 @@
1
+ import type { InProgressRun, ShepherdReport } from "../../types.mts";
2
+ /**
3
+ * In-progress Actions runs on the head, with each workflow's raw `cancel-in-progress` and a
4
+ * `gh run cancel` command only for a run that sets it to the literal `true`. Empty when the
5
+ * feature is off or the PR is in the merge queue (a push would eject it). Reads each workflow
6
+ * file once per call, through one aliased GraphQL read.
7
+ */
8
+ export declare function buildInProgressRuns(report: ShepherdReport, rerunAuthorized: boolean): Promise<InProgressRun[]>;
9
+ /** The first fix step: cancel the superseded runs before editing, only when one has a command. */
10
+ export declare function buildCancelRunsInstruction(runs: readonly InProgressRun[]): string | undefined;
@@ -0,0 +1,120 @@
1
+ import picomatch from "picomatch";
2
+ import { loadConfig } from "../../config/load.mjs";
3
+ import { parseWorkflowConcurrency } from "../../checks/workflow-concurrency.mjs";
4
+ import { readWorkflowFiles, workflowFileKey } from "./workflow-files.mjs";
5
+ /** Raw `pull_request_target` runs execute the base branch's workflow file, not the head's. */
6
+ const BASE_FILE_EVENT = "pull_request_target";
7
+ /**
8
+ * Display text from PR-controlled YAML or check names: control characters and backticks would
9
+ * let a name forge a `cancel:` line or close the code span around it.
10
+ */
11
+ function label(text) {
12
+ return text
13
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}`\s]+/gu, " ")
14
+ .trim()
15
+ .slice(0, 200);
16
+ }
17
+ function groupByRun(checks) {
18
+ const groups = new Map();
19
+ for (const check of checks) {
20
+ // Actions provenance: a third-party app's check can carry a run-looking id without a workflow.
21
+ if (check.runId === null || check.workflowName === undefined)
22
+ continue;
23
+ if (check.scope === "merge_group")
24
+ continue;
25
+ groups.set(check.runId, [...(groups.get(check.runId) ?? []), check]);
26
+ }
27
+ return groups;
28
+ }
29
+ /** The first `checks.never-cancel` pattern matching the workflow name or any check name. */
30
+ function matchedNeverCancel(patterns, names) {
31
+ return patterns.find((pattern) => {
32
+ const matches = picomatch(pattern, { nocase: true });
33
+ return names.some((name) => matches(name));
34
+ });
35
+ }
36
+ function fileRequest(report, group) {
37
+ const path = group.find((check) => check.workflowPath !== undefined)?.workflowPath;
38
+ const baseRead = group[0]?.event === BASE_FILE_EVENT;
39
+ // GitHub runs a `pull_request` workflow from the PR merge revision, not the head commit.
40
+ const ref = baseRead ? report.baseBranch : `refs/pull/${report.pr}/merge`;
41
+ return path && ref ? { ref, path, pinned: false } : undefined;
42
+ }
43
+ /**
44
+ * In-progress Actions runs on the head, with each workflow's raw `cancel-in-progress` and a
45
+ * `gh run cancel` command only for a run that sets it to the literal `true`. Empty when the
46
+ * feature is off or the PR is in the merge queue (a push would eject it). Reads each workflow
47
+ * file once per call, through one aliased GraphQL read.
48
+ */
49
+ export async function buildInProgressRuns(report, rerunAuthorized) {
50
+ const config = loadConfig();
51
+ if (!config.actions["cancel-runs-before-push"] || report.mergeQueue?.inQueue)
52
+ return [];
53
+ const groups = groupByRun(report.checks.inProgress);
54
+ if (groups.size === 0)
55
+ return [];
56
+ const requests = new Map([...groups].map(([runId, group]) => [runId, fileRequest(report, group)]));
57
+ const [owner, name] = report.repo.split("/");
58
+ const wanted = [...requests.values()].filter((request) => request !== undefined);
59
+ // Optional enrichment: a failed read (rate limit included) must not drop the triage output
60
+ // after the feedback's seen markers are written, so every file is reported unreadable.
61
+ const files = await readWorkflowFiles({ owner, name }, wanted).catch((error) => {
62
+ process.stderr.write(`workflow files unreadable: ${String(error)}\n`);
63
+ return new Map(wanted.map((request) => [workflowFileKey(request), { unreadable: "request failed" }]));
64
+ });
65
+ return [...groups].map(([runId, group]) => {
66
+ const request = requests.get(runId);
67
+ const file = request ? files.get(workflowFileKey(request)) : undefined;
68
+ const parsed = file && "text" in file ? parseWorkflowConcurrency(file.text) : undefined;
69
+ const why = !file ? "no workflow file" : "unreadable" in file ? file.unreadable : "parse error";
70
+ const concurrency = label(parsed ? parsed.raw : `unreadable (${why})`);
71
+ const workflowName = label(group[0].workflowName);
72
+ // Protection covers every check of the run, finished or not.
73
+ const siblings = [
74
+ ...report.checks.passing,
75
+ ...report.checks.failing,
76
+ ...report.checks.skipped,
77
+ ...report.checks.filtered,
78
+ ...group,
79
+ ]
80
+ .filter((check) => check.runId === runId)
81
+ .map((check) => check.name);
82
+ // `checks.ignore` drops a check's run association, so a protected name that is ignored
83
+ // protects every run.
84
+ const neverCancel = matchedNeverCancel(config.checks["never-cancel"], [
85
+ group[0].workflowName,
86
+ ...siblings,
87
+ ...(report.checks.ignoredNames ?? []),
88
+ ]);
89
+ const status = group.some((check) => check.status === "WAITING") ? "WAITING" : group[0].status;
90
+ const failed = report.checks.failing
91
+ .filter((check) => check.runId === runId)
92
+ .map((check) => label(check.name));
93
+ const cancel = parsed?.cancelInProgress &&
94
+ !neverCancel &&
95
+ status !== "WAITING" &&
96
+ rerunAuthorized &&
97
+ (group[0].event === "pull_request" || group[0].event === BASE_FILE_EVENT) &&
98
+ /^\d+$/.test(runId);
99
+ return {
100
+ runId,
101
+ workflowName,
102
+ status,
103
+ concurrency,
104
+ ...(failed.length > 0 && { failed, running: group.map((check) => label(check.name)) }),
105
+ ...(neverCancel !== undefined && { neverCancel: label(neverCancel) }),
106
+ ...(cancel && { cancelCommand: `gh run cancel ${runId} -R ${report.repo}` }),
107
+ };
108
+ });
109
+ }
110
+ /** The first fix step: cancel the superseded runs before editing, only when one has a command. */
111
+ export function buildCancelRunsInstruction(runs) {
112
+ const ids = runs.filter((run) => run.cancelCommand).map((run) => run.runId);
113
+ if (ids.length === 0)
114
+ return undefined;
115
+ const named = ids.length === 1 ? `run ${ids[0]}` : `runs ${ids.join(", ")}`;
116
+ const others = runs.length > ids.length
117
+ ? " Cancel no other run: a push does not cancel the rest, so cancelling them only discards their results."
118
+ : "";
119
+ return `If any item will need a code change, cancel ${named} now with ${ids.length === 1 ? "its `cancel:` command" : "their `cancel:` commands"}, before editing; ignore errors for runs that already finished.${others} If you will push nothing, leave every run running.`;
120
+ }
@@ -25,6 +25,7 @@ import { fingerprintRawSummaryPr } from "../../github/poll-summary-fingerprint.m
25
25
  import { currentQueueRemovalEvent } from "../../github/poll-summary-queue-removal.mjs";
26
26
  import { isCurrentSummaryReady } from "../../github/poll-summary-readiness.mjs";
27
27
  import { clearReadyReceipt, isReadyReceiptCurrent, readReadyReceipt, writeReadyReceipt, } from "../../state/ready-receipts.mjs";
28
+ import { withStackBoundary } from "./stack-boundary.mjs";
28
29
  import { findStaleNativeStackAncestry } from "./stale-ancestry.mjs";
29
30
  import { annotateBlockedWait, resolveCheckBlockerGate } from "./check-blocker-gate.mjs";
30
31
  import { buildUnreportedFixResult, planUnreportedRequired } from "./unreported-required.mjs";
@@ -33,10 +34,10 @@ import { transportReadinessGaps } from "../../github/transport-evidence.mjs";
33
34
  import { buildEscalateHumanMessage } from "./escalate.mjs";
34
35
  import { markEditedCommentsSeen } from "./edited-comment-markers.mjs";
35
36
  export function runIterate(opts) {
36
- return withIterateApiUsage(opts, async () => {
37
+ return withIterateApiUsage(opts, () => withStackBoundary(opts.prNumber, opts.stackLayers, async () => {
37
38
  const tick = {};
38
39
  return attachEditedComments(await runIterateCore(opts, tick), tick, opts);
39
- });
40
+ }));
40
41
  }
41
42
  // Edited PR comments are not readiness work. Hold them while the PR waits or counts down, and show
42
43
  // each once on any other action (including MERGE after the ready delay), writing its marker then.
@@ -239,7 +240,7 @@ async function runIterateCore(opts, tick) {
239
240
  });
240
241
  }
241
242
  if (unreportedRepair.length > 0) {
242
- return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, buildUnreportedFixResult(base, report, unreportedRepair), reportForWork, reviewSummaryIds, opts.stallDeadlineSink), blockerGate);
243
+ return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, buildUnreportedFixResult(base, report, unreportedRepair), reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
243
244
  }
244
245
  const mergeStateResult = await handleActiveMergeState({
245
246
  enabled: opts.merge,
@@ -252,6 +253,7 @@ async function runIterateCore(opts, tick) {
252
253
  editedSummaries,
253
254
  surfacedApprovals,
254
255
  minimizeApprovals: config.iterate["minimize-approvals"],
256
+ persistState: opts.persistSeen !== false,
255
257
  });
256
258
  if (mergeStateResult)
257
259
  return annotateBlockedWait(mergeStateResult, blockerGate);
@@ -334,11 +336,15 @@ async function runIterateCore(opts, tick) {
334
336
  ? `WAIT: PR #${base.pr} reached ready-delay but GitHub reports BLOCKED, so its stack readiness receipt was not certified`
335
337
  : `WAIT: PR #${base.pr} reached ready-delay but its stack readiness receipt could not be persisted`,
336
338
  };
337
- return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, receiptWait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink), blockerGate);
339
+ return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, receiptWait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
340
+ }
341
+ const mergeResult = buildReadyMergeOutcome(opts.merge, true, base, report);
342
+ if (mergeResult?.action === "wait") {
343
+ // Unreadable REST queue policy: keep the ready-delay and run the stall timer across ticks.
344
+ return await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, mergeResult, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false);
338
345
  }
339
346
  await clearReadyDelay(report.pr, repoOwner, repoName);
340
347
  await clearStallState(stallKey);
341
- const mergeResult = buildReadyMergeOutcome(opts.merge, true, base, report);
342
348
  if (mergeResult)
343
349
  return mergeResult;
344
350
  const cancelNote = blockedCancelNote(base);
@@ -365,7 +371,7 @@ async function runIterateCore(opts, tick) {
365
371
  action: "wait",
366
372
  log: buildWaitLog(base),
367
373
  };
368
- return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, wait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink), blockerGate);
374
+ return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, wait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
369
375
  }
370
376
  /**
371
377
  * Persist a READY receipt from a fresh compact snapshot. `blocked` means the
@@ -17,5 +17,7 @@ export interface MergePlanInput {
17
17
  }
18
18
  export interface MergeMethodUnavailable {
19
19
  unavailable: string;
20
+ /** REST could not read queue policy: a retry may read it, so the caller waits instead of escalating. */
21
+ refresh?: true;
20
22
  }
21
23
  export declare function buildMergeCommandPlan(input: MergePlanInput): MergeCommandPlan | MergeMethodUnavailable;
@@ -15,7 +15,8 @@ export function buildMergeCommandPlan(input) {
15
15
  const configured = configuredMergeMethod(loadConfig().merge);
16
16
  if (!input.queue && input.queueKnown !== true && configured)
17
17
  return {
18
- unavailable: "REST cannot verify merge-queue policy and cannot apply a configured direct merge method to an automatic merge request. Refresh branch policy before merging.",
18
+ unavailable: "REST could not read merge-queue policy, so it cannot apply the configured direct merge method to an automatic merge request. Shepherd rereads branch policy on the next poll and stops with `stall-timeout` if it stays unreadable.",
19
+ refresh: true,
19
20
  };
20
21
  let method;
21
22
  if (!input.queue && input.queueKnown === true) {
@@ -25,5 +25,7 @@ export declare function handleActiveMergeState(input: {
25
25
  editedSummaries: Review[];
26
26
  surfacedApprovals: Review[];
27
27
  minimizeApprovals: boolean;
28
+ /** False on internal debounce preview ticks, which must not write follow-up markers. */
29
+ persistState?: boolean;
28
30
  }): Promise<IterateResult | null>;
29
31
  export {};
@@ -1,5 +1,5 @@
1
1
  import { clearStallState } from "../../state/iterate-stall.mjs";
2
- import { buildEscalateHumanMessage, buildEscalateSuggestion } from "./escalate.mjs";
2
+ import { planQueueRemoval } from "./queue-removal.mjs";
3
3
  import { buildMergeCommandPlan, unavailableMergeResult } from "./merge.mjs";
4
4
  import { formatPrUrl } from "../../pr-reference.mjs";
5
5
  import { buildPrShepherdCommand } from "../../cli/runner.mjs";
@@ -31,7 +31,7 @@ function buildStackedRouteResult(base, report, stack) {
31
31
  },
32
32
  instructions: [
33
33
  `PR #${report.pr} is layer ${stack.position} of ${stack.size} in native stack #${stack.number}; do not run \`gh pr merge\` for this layer.`,
34
- `Run ${inlineCode(buildPrShepherdCommand(["stack", prUrl, "--until-terminal", "--merge"]).text)} to reconcile the stack and run each bottom-layer merge command it emits.`,
34
+ `Run ${inlineCode(buildPrShepherdCommand(["stack", prUrl, "--until-terminal", "--merge-through", prUrl]).text)} to merge this layer and the unmerged layers below it, never a layer above it. If lower layers are not yours it escalates \`unowned-stack-layers\` and merges nothing: follow its instructions. Otherwise it emits one merge command that lands every layer it lists. Run that command as printed: do not merge the layers one at a time with \`gh pr merge\`, and do not rebase or push between layers.`,
35
35
  ],
36
36
  firstLookThreads: [],
37
37
  firstLookComments: [],
@@ -57,8 +57,12 @@ export function buildReadyMergeOutcome(enabled, readyElapsed, base, report) {
57
57
  !(report.transportUnavailable ?? []).some(({ field }) => ["branchProtection", "branchRules"].includes(field)),
58
58
  ...(report.allowedMergeMethods && { allowedMergeMethods: report.allowedMergeMethods }),
59
59
  });
60
- if ("unavailable" in plan)
60
+ if ("unavailable" in plan) {
61
+ // A REST policy read that may succeed on a later poll waits under the stall timer.
62
+ if (plan.refresh)
63
+ return { ...base, action: "wait", log: `WAIT: PR #${report.pr} ${plan.unavailable}` };
61
64
  return unavailableMergeResult(base, report, plan.unavailable);
65
+ }
62
66
  return { ...base, action: "merge", merge: plan };
63
67
  }
64
68
  /** Raw counts of non-CI actionable work held back for one queued-PR wait tick. Omitted (all zero) when empty. */
@@ -121,22 +125,5 @@ export async function handleActiveMergeState(input) {
121
125
  report.mergeQueue?.removalAcknowledged)
122
126
  return null;
123
127
  await clearStallState(stallKey);
124
- const escalateBase = {
125
- triggers: ["merge-queue-removed"],
126
- unresolvedThreads: [],
127
- ambiguousComments: [],
128
- changesRequestedReviews: [],
129
- mergeQueueRemoval: removal,
130
- suggestion: buildEscalateSuggestion(["merge-queue-removed"], removal.reason ?? "GitHub did not provide a reason"),
131
- };
132
- return {
133
- ...base,
134
- action: "escalate",
135
- escalate: {
136
- ...escalateBase,
137
- humanMessage: buildEscalateHumanMessage(escalateBase, formatPrUrl(report.repo, report.pr), {
138
- merge: true,
139
- }),
140
- },
141
- };
128
+ return planQueueRemoval({ base, report, stallKey, persistState: input.persistState !== false });
142
129
  }
@@ -26,11 +26,12 @@ export declare function buildNativeStackRebaseInstruction(repo: string, stackNum
26
26
  * retains its merged parent's branch as its PR base. Without that topology, a PR base matching
27
27
  * the stack trunk also identifies a bottom layer. Other layers rebase from their PR base.
28
28
  * `trunkConflict` means an upper layer already contains its parent, so the rebase starts
29
- * at the bottom open layer.
29
+ * at the bottom open layer. An unusable base name (`baseBranch` undefined) is never named: the
30
+ * route starts at the known bottom open layer, which updates every layer above it as well.
30
31
  */
31
32
  export declare function buildNativeStackLayerRebase(repo: string, pr: {
32
33
  number: number;
33
- baseBranch: string;
34
+ baseBranch: string | undefined;
34
35
  }, stack: StackStatus | undefined, trunkConflict?: {
35
36
  trunk: string;
36
37
  bottomPr?: number;
@@ -1,5 +1,6 @@
1
1
  import { playbookPointer } from "../playbook-pointer.mjs";
2
2
  import { getGithubTransport } from "../../github/transport.mjs";
3
+ import { boundedStackPush, boundedStackRebase } from "./stack-boundary.mjs";
3
4
  /**
4
5
  * One gh-stack rebase step. A native stack layer must not be rebased or merged from its base
5
6
  * branch alone: that rewrites one branch and strands every layer above it.
@@ -9,6 +10,10 @@ import { getGithubTransport } from "../../github/transport.mjs";
9
10
  * stack number before a PR number) and checks each local layer against its PR head.
10
11
  */
11
12
  export function buildNativeStackRebaseInstruction(repo, stackNumber, start) {
13
+ // A one-PR session that carries unowned layers never runs a whole-stack update.
14
+ const bounded = boundedStackRebase(stackNumber, playbookPointer("Branch update"), getGithubTransport() === "rest");
15
+ if (bounded)
16
+ return bounded;
12
17
  if (getGithubTransport() === "rest") {
13
18
  const boundary = "parentBranch" in start
14
19
  ? `parent branch \`${start.parentBranch}\``
@@ -38,21 +43,31 @@ export function buildNativeStackRebaseInstruction(repo, stackNumber, start) {
38
43
  * retains its merged parent's branch as its PR base. Without that topology, a PR base matching
39
44
  * the stack trunk also identifies a bottom layer. Other layers rebase from their PR base.
40
45
  * `trunkConflict` means an upper layer already contains its parent, so the rebase starts
41
- * at the bottom open layer.
46
+ * at the bottom open layer. An unusable base name (`baseBranch` undefined) is never named: the
47
+ * route starts at the known bottom open layer, which updates every layer above it as well.
42
48
  */
43
49
  export function buildNativeStackLayerRebase(repo, pr, stack, trunkConflict, stackBottomPr) {
44
50
  if (!stack)
45
51
  return undefined;
46
- const start = trunkConflict
47
- ? trunkConflict.bottomPr !== undefined
48
- ? { bottomPr: trunkConflict.bottomPr }
49
- : { trunk: trunkConflict.trunk }
50
- : (stackBottomPr !== undefined
51
- ? pr.number === stackBottomPr
52
- : pr.baseBranch === stack.baseRefName)
53
- ? { bottomPr: pr.number }
54
- : { parentBranch: pr.baseBranch };
55
- return buildNativeStackRebaseInstruction(repo, stack.number, start);
52
+ const { baseBranch } = pr;
53
+ let start;
54
+ if (trunkConflict) {
55
+ start =
56
+ trunkConflict.bottomPr !== undefined
57
+ ? { bottomPr: trunkConflict.bottomPr }
58
+ : { trunk: trunkConflict.trunk };
59
+ }
60
+ else if (baseBranch === undefined) {
61
+ if (stackBottomPr !== undefined)
62
+ start = { bottomPr: stackBottomPr };
63
+ }
64
+ else if (stackBottomPr !== undefined ? pr.number === stackBottomPr : baseBranch === stack.baseRefName) {
65
+ start = { bottomPr: pr.number };
66
+ }
67
+ else {
68
+ start = { parentBranch: baseBranch };
69
+ }
70
+ return start && buildNativeStackRebaseInstruction(repo, stack.number, start);
56
71
  }
57
72
  /**
58
73
  * The branch-update route for a conflicting PR that is not a native stack layer. Rebase versus
@@ -89,6 +104,12 @@ export function buildQueuedConflictChoice(dequeueCommand, resolve, stack) {
89
104
  * After a merge-queue ejection update, push only when the update or a fix changed the head.
90
105
  */
91
106
  export function buildBranchPushInstruction(stackRebase, hasConflicts, mutationSuffix, ejectionUpdate = false) {
107
+ const bounded = stackRebase ? boundedStackPush() : undefined;
108
+ if (bounded) {
109
+ return ejectionUpdate
110
+ ? `If the base update or a fix changed the head, commit any remaining changes and ${bounded}${mutationSuffix}. If neither did, do not push.`
111
+ : `Commit any remaining changes on the PR head branch and ${bounded}${mutationSuffix}.`;
112
+ }
92
113
  if (stackRebase && getGithubTransport() === "rest")
93
114
  return `If the base update or a fix changed any heads, commit the remaining changes and push every affected stack branch using the repository's stack-update procedure${mutationSuffix}. If no heads changed, do not push.`;
94
115
  if (ejectionUpdate) {
@@ -0,0 +1,19 @@
1
+ import type { IterateResult, IterateResultBase, ShepherdReport } from "../../types.mts";
2
+ type StateKey = {
3
+ owner: string;
4
+ repo: string;
5
+ pr: number;
6
+ };
7
+ /**
8
+ * A current merge-queue removal with no failed queue-commit check to triage. The first presented
9
+ * tick for this head and removal is one bounded `triage`; the same removal unchanged on the next
10
+ * presented tick escalates. A new head ends the removal's currency, so it never reaches here.
11
+ */
12
+ export declare function planQueueRemoval(input: {
13
+ base: IterateResultBase;
14
+ report: ShepherdReport;
15
+ stallKey: StateKey;
16
+ /** Internal preview ticks must not consume the one investigation tick. */
17
+ persistState: boolean;
18
+ }): Promise<IterateResult>;
19
+ export {};
@@ -0,0 +1,64 @@
1
+ import { formatPrUrl } from "../../pr-reference.mjs";
2
+ import { queueRemovalSignature, readQueueRemovalFollowUp, writeQueueRemovalFollowUp, } from "../../state/queue-removal-follow-up.mjs";
3
+ import { playbookPointer } from "../playbook-pointer.mjs";
4
+ import { buildEscalateHumanMessage, buildEscalateSuggestion } from "./escalate.mjs";
5
+ import { stateUnavailableResult } from "./state-unavailable.mjs";
6
+ import { buildUnreportedFixResult, stackRebase } from "./unreported-required.mjs";
7
+ function buildQueueRemovalInstructions(report) {
8
+ const route = stackRebase(report);
9
+ const update = route
10
+ ? `update the stack from the latest base (${route}) and push it`
11
+ : "update the PR head from the latest base and push";
12
+ return [
13
+ `GitHub removed PR #${report.pr} from the merge queue, and Shepherd has no failed queue-commit check to triage. The \`**queue removal**\` line above carries the raw reason and actor.`,
14
+ `Decide from them. If the reason names a merge conflict, an invalid merge commit, or a stack that changed, ${update}. If a person dequeued the PR (the actor is a user, not a bot or \`github-actions\`), make no change and report that. If the reason is missing or unclear, find out why before acting. Never enqueue the PR yourself. ${playbookPointer("Merge queue ejection")}`,
15
+ "If the head is unchanged on the next poll, Shepherd escalates with `merge-queue-removed`; report what you found then.",
16
+ ];
17
+ }
18
+ function escalateResult(base, report) {
19
+ const removal = report.mergeQueue.latestRemoval;
20
+ const escalateBase = {
21
+ triggers: ["merge-queue-removed"],
22
+ unresolvedThreads: [],
23
+ ambiguousComments: [],
24
+ changesRequestedReviews: [],
25
+ mergeQueueRemoval: removal,
26
+ suggestion: buildEscalateSuggestion(["merge-queue-removed"], removal.reason ?? "GitHub did not provide a reason"),
27
+ };
28
+ return {
29
+ ...base,
30
+ action: "escalate",
31
+ escalate: {
32
+ ...escalateBase,
33
+ humanMessage: buildEscalateHumanMessage(escalateBase, formatPrUrl(report.repo, report.pr), {
34
+ merge: true,
35
+ }),
36
+ },
37
+ };
38
+ }
39
+ /**
40
+ * A current merge-queue removal with no failed queue-commit check to triage. The first presented
41
+ * tick for this head and removal is one bounded `triage`; the same removal unchanged on the next
42
+ * presented tick escalates. A new head ends the removal's currency, so it never reaches here.
43
+ */
44
+ export async function planQueueRemoval(input) {
45
+ const { base, report, stallKey, persistState } = input;
46
+ const removal = report.mergeQueue.latestRemoval;
47
+ const signature = queueRemovalSignature({
48
+ headSha: report.headSha ?? "unknown",
49
+ createdAtUnix: removal.createdAtUnix,
50
+ ...(removal.beforeCommitOid && { beforeCommitOid: removal.beforeCommitOid }),
51
+ });
52
+ if (await readQueueRemovalFollowUp(stallKey, signature))
53
+ return escalateResult(base, report);
54
+ // A reused cached report is re-run by the poll before it is shown, so it must not spend the one
55
+ // investigation tick the caller never sees.
56
+ if (persistState && report.fingerprintReused !== true) {
57
+ // A marker that cannot be saved would repeat the investigation forever.
58
+ const saveError = await writeQueueRemovalFollowUp(stallKey, signature);
59
+ if (saveError) {
60
+ return stateUnavailableResult(base, formatPrUrl(report.repo, report.pr), saveError);
61
+ }
62
+ }
63
+ return buildUnreportedFixResult(base, report, buildQueueRemovalInstructions(report));
64
+ }
@@ -11,4 +11,5 @@ export declare function buildFixInstructions(threads: AgentThread[], actionableC
11
11
  isBehind?: boolean, _viewerCanUpdate?: boolean, hasExhaustedWorkflowRerun?: boolean, stackRebase?: string, // native stack layers rebase with gh-stack, not branch by branch
12
12
  queueEjection?: QueueEjectionRecovery, // current merge-queue removal with failing queue checks
13
13
  instructionStyle?: InstructionStyle, // see iterate.instructions
14
- dequeueCommand?: string): string[];
14
+ dequeueCommand?: string, // a conflicting PR that is still a merge-queue entry
15
+ cancelRunsStep?: string): string[];
@@ -20,7 +20,8 @@ export function buildFixInstructions(threads, actionableComments, checks, change
20
20
  isBehind = false, _viewerCanUpdate = false, hasExhaustedWorkflowRerun = false, stackRebase, // native stack layers rebase with gh-stack, not branch by branch
21
21
  queueEjection, // current merge-queue removal with failing queue checks
22
22
  instructionStyle = "inline", // see iterate.instructions
23
- dequeueCommand) {
23
+ dequeueCommand, // a conflicting PR that is still a merge-queue entry
24
+ cancelRunsStep) {
24
25
  const instructions = [];
25
26
  const { locatedThreads, unlocatedThreads } = partitionFixThreads(threads, resolveCommand, resolveOnlyCommand);
26
27
  const failingChecks = checks.filter((c) => isFailingAgentCheck(c));
@@ -36,6 +37,8 @@ dequeueCommand) {
36
37
  // A queued conflict offers a wait path that publishes nothing, so fixes, branch updates,
37
38
  // pushes, and review mutations (which must follow a push) become path (a).
38
39
  const pathA = (step) => (dequeueCommand ? `If you chose (a): ${step}` : step);
40
+ if (cancelRunsStep)
41
+ instructions.push(cancelRunsStep);
39
42
  if (hasNonConflictHints)
40
43
  instructions.push(pathA("Fix each warranted item."));
41
44
  // A conflicting native stack layer follows the printed gh-stack route, so it omits the hint.
@@ -0,0 +1,17 @@
1
+ import type { StackLayerOwnership } from "../../types.mts";
2
+ /** Run one iterate tick with the stack ownership its command carried. */
3
+ export declare function withStackBoundary<T>(pr: number | undefined, layers: StackLayerOwnership[] | undefined, run: () => Promise<T>): Promise<T>;
4
+ /** `pr:position:o|u:branch` per layer, comma separated: the `--layers` value. The branch is percent-encoded so commas and colons survive. */
5
+ export declare function formatStackLayers(layers: StackLayerOwnership[]): string;
6
+ /** Parse a `--layers` value; null when any entry is malformed. */
7
+ export declare function parseStackLayers(value: string): StackLayerOwnership[] | null;
8
+ /**
9
+ * Whether the ownership this tick carries rules out a whole-stack `gh stack rebase` / `push`
10
+ * (some layer is not the caller's), and the instruction to give instead; undefined otherwise.
11
+ */
12
+ export declare function boundedStackRebase(stackNumber: number, playbook: string, rest?: boolean): string | undefined;
13
+ /**
14
+ * The push clause that replaces "push the rewritten stack with `gh stack push`" when ownership
15
+ * is bounded; undefined when it is not.
16
+ */
17
+ export declare function boundedStackPush(): string | undefined;