pr-shepherd 0.56.1 → 0.56.3

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 (51) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +7 -4
  3. package/bin/api.d.mts +11 -1
  4. package/bin/api.mjs +25 -0
  5. package/bin/checks/classify.d.mts +5 -6
  6. package/bin/checks/classify.mjs +5 -7
  7. package/bin/checks/superseded.d.mts +4 -17
  8. package/bin/checks/superseded.mjs +67 -43
  9. package/bin/cli/args.mjs +3 -0
  10. package/bin/cli/fix-formatter.mjs +3 -0
  11. package/bin/cli/help-command-pages.d.mts +17 -2
  12. package/bin/cli/help-command-pages.mjs +16 -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 +2 -0
  17. package/bin/cli/help.d.mts +18 -3
  18. package/bin/cli/help.mjs +2 -0
  19. package/bin/cli/iterate-instructions.mjs +4 -1
  20. package/bin/cli/iterate-lean.mjs +3 -0
  21. package/bin/cli/iterate-merge-formatter.mjs +2 -0
  22. package/bin/cli/queue-removal-handler.d.mts +2 -0
  23. package/bin/cli/queue-removal-handler.mjs +86 -0
  24. package/bin/cli-parser.mjs +4 -0
  25. package/bin/commands/apply-queue-removal.d.mts +18 -0
  26. package/bin/commands/apply-queue-removal.mjs +44 -0
  27. package/bin/commands/check-fingerprint.mjs +2 -0
  28. package/bin/commands/check.mjs +13 -1
  29. package/bin/commands/iterate/check-evidence.d.mts +4 -0
  30. package/bin/commands/iterate/check-evidence.mjs +8 -0
  31. package/bin/commands/iterate/fix-code.mjs +20 -4
  32. package/bin/commands/iterate/index.mjs +15 -1
  33. package/bin/commands/iterate/merge-state.mjs +4 -1
  34. package/bin/commands/iterate/merge.d.mts +7 -1
  35. package/bin/commands/iterate/merge.mjs +59 -1
  36. package/bin/github/gql/poll-summary-check-contexts.gql +2 -0
  37. package/bin/github/poll-summary-checks.mjs +22 -18
  38. package/bin/github/poll-summary-fingerprint.mjs +7 -0
  39. package/bin/github/poll-summary-raw.d.mts +2 -0
  40. package/bin/github/poll-summary-readiness.mjs +11 -1
  41. package/bin/mcp/server.mjs +18 -0
  42. package/bin/state/queue-removal-ack.d.mts +19 -0
  43. package/bin/state/queue-removal-ack.mjs +66 -0
  44. package/bin/types/iterate.d.mts +4 -0
  45. package/bin/types/merge-queue.d.mts +2 -0
  46. package/package.json +2 -2
  47. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  48. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  49. package/plugins/pr-shepherd/.mcp.json +1 -1
  50. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +3 -2
  51. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-failure-triage.md +1 -0
@@ -11,8 +11,9 @@ Usage:
11
11
  pr-shepherd apply journal [PR] --file <path> [--dry-run] [--format text|json]
12
12
  pr-shepherd apply check-blocker [PR] --check <name> --blocked-by <ref>
13
13
  pr-shepherd apply check-blocker [PR] --check <name> --clear
14
+ pr-shepherd apply queue-removal [PR] --require-sha <head> --queue-commit <commit> --removed-at <unix>
14
15
 
15
- Run 'pr-shepherd apply <review|files|journal|check-blocker> --help' for command-specific details.
16
+ Run 'pr-shepherd apply <review|files|journal|check-blocker|queue-removal> --help' for command-specific details.
16
17
  --help, -h Print this help and exit before GitHub I/O.`;
17
18
  readonly "apply review": `pr-shepherd apply review
18
19
 
@@ -80,6 +81,20 @@ Usage:
80
81
 
81
82
  \`--clear\` removes that check's record and leaves other checks alone.
82
83
  --help, -h Print this help and exit before any I/O.`;
84
+ readonly "apply queue-removal": `pr-shepherd apply queue-removal
85
+
86
+ Acknowledge one current CI-driven merge-queue removal for a native-stack PR.
87
+ This writes local state only after a fresh GitHub read confirms the supplied head,
88
+ queue commit, and removal timestamp still identify the current removal.
89
+
90
+ Usage:
91
+ pr-shepherd apply queue-removal [PR] --require-sha <head> --queue-commit <commit> --removed-at <unix>
92
+
93
+ --require-sha <sha> Full 40-character lowercase PR head SHA observed with the failure.
94
+ --queue-commit <sha> Full 40-character lowercase synthetic merge-group commit SHA.
95
+ --removed-at <unix> Removal time in Unix seconds.
96
+ --format text|json Output format. Default: text.
97
+ --help, -h Print this help and exit before any I/O.`;
83
98
  readonly "build-suggestion-patches": `pr-shepherd build-suggestion-patches
84
99
 
85
100
  Build an ordered list of patches and commit instructions from GitHub review suggestions.
@@ -212,7 +227,7 @@ Flags:
212
227
 
213
228
  PR may be a number or GitHub pull request URL. When omitted, the current branch PR is inferred.
214
229
  Exit code: 0 on success; nonzero on failure (sysexits.h — see docs/exit-codes.md).`;
215
- readonly iterate: "pr-shepherd iterate\n\nRun one iterate tick for a pull request. The no-subcommand form polls; use this subcommand for a single tick.\nThe output contains one action and an action-specific ## Instructions section.\n\nUsage:\n pr-shepherd iterate [PR] [iterate-flags]\n\nIterate flags:\n --ready-delay <duration> Settle window before a clean PR cancels. Bare number = minutes. Example: 15m.\n --stall-timeout <duration> Escalate repeated unchanged failures after this duration. Bare number = minutes. 0 disables.\n --no-auto-mark-ready Do not convert draft PRs to ready for review.\n --no-auto-cancel-actionable Legacy no-op; workflow runs are never cancelled.\n --merge Shepherd through readiness, then emit a merge or merge-queue command.\n --format text|json Output Markdown text or JSON. Default: text.\n --verbose Include verbose iterate fields.\n --help, -h Print this help and exit before GitHub, git, config, or log I/O.\n\nDurations accept s/m/h suffixes: 30s, 4.5m, 1h. A bare number is minutes; decimals are allowed only with an explicit unit (4.5m).\n\nActions:\n WAIT No immediate action; continue with the next poll.\n MARK_READY Draft PR was marked ready; continue with the next poll.\n READY Clean PR is inside the ready-delay. Schedule the rerun for when remainingSeconds elapses. Do not invent unrelated work. Already-owned later work may continue.\n FIX_CODE Agent action is required; follow the instructions, then continue polling.\n CANCEL Stop polling: merged/closed or ready-delay elapsed.\n ESCALATE Stop polling until a human provides direction.\n MERGE Run the emitted merge/queue command, then continue monitoring.\n\nExit codes:\n 0 CANCEL (merged or ready-delay elapsed)\n 10 WAIT or READY\n 11 MARK_READY\n 12 FIX_CODE\n 13 ESCALATE\n 14 CANCEL (closed without merging)\n 15 MERGE\n A command/validation/GitHub failure exits with a sysexits.h code instead (see docs/exit-codes.md).";
230
+ readonly iterate: "pr-shepherd iterate\n\nRun one iterate tick for a pull request. The no-subcommand form polls; use this subcommand for a single tick.\nThe output contains one action and an action-specific ## Instructions section.\n\nUsage:\n pr-shepherd iterate [PR] [iterate-flags]\n\nIterate flags:\n --ready-delay <duration> Settle window before a clean PR cancels. Bare number = minutes. Example: 15m.\n --stall-timeout <duration> Escalate repeated unchanged failures after this duration. Bare number = minutes. 0 disables.\n --no-auto-mark-ready Do not convert draft PRs to ready for review.\n --no-auto-cancel-actionable Legacy no-op; workflow runs are never cancelled.\n --merge Shepherd through readiness, then emit a merge or merge-queue command.\n --format text|json Output Markdown text or JSON. Default: text.\n --verbose Include verbose iterate fields.\n --help, -h Print this help and exit before GitHub, git, config, or log I/O.\n\nDurations accept s/m/h suffixes: 30s, 4.5m, 1h. A bare number is minutes; decimals are allowed only with an explicit unit (4.5m).\n\nActions:\n WAIT No immediate action; continue with the next poll.\n MARK_READY Draft PR was marked ready; continue with the next poll.\n READY Clean PR is inside the ready-delay. Schedule the rerun for when remainingSeconds elapses. Do not invent unrelated work. Already-owned later work may continue.\n FIX_CODE Agent action is required; follow the instructions, then continue polling.\n CANCEL Stop polling this pull request: merged/closed or ready-delay elapsed. Continue remaining work from the original request.\n ESCALATE Stop polling until a human provides direction.\n MERGE Run the emitted merge/queue command, then continue monitoring.\n\nExit codes:\n 0 CANCEL (merged or ready-delay elapsed)\n 10 WAIT or READY\n 11 MARK_READY\n 12 FIX_CODE\n 13 ESCALATE\n 14 CANCEL (closed without merging)\n 15 MERGE\n A command/validation/GitHub failure exits with a sysexits.h code instead (see docs/exit-codes.md).";
216
231
  readonly poll: "pr-shepherd poll\n\nRun iterate repeatedly for one PR, or read compact summaries for an explicit PR set or native\nGitHub stack. Aggregate mode returns when any row needs work, every row is terminal, or timeout.\nPoll exits as soon as iterate returns READY, MARK_READY, CANCEL, or ESCALATE, or when timeout\nreturns the last WAIT result. FIX_CODE starts a --debounce settle window (default:\npoll.debounceSeconds; built-in 1m): poll keeps\niterating at --interval, then runs one more tick after the window and returns that result.\nWith --until-terminal or --merge, poll also continues through MARK_READY.\n\nUsage:\n pr-shepherd poll [PR ...] [poll-flags] [iterate-flags]\n pr-shepherd poll --stack PR [poll-flags] [iterate-flags]\n\nPoll flags:\n --stack PR Select all entries in PR's native GitHub stack, bottom to top.\n --interval <duration> Sleep between WAIT ticks. Bare number = seconds. Default: poll.intervalSeconds (built-in 60s). Stack and multi-PR polls multiply that by poll.stackIntervalFactor (built-in 2) unless this flag is set.\n --timeout <duration> Maximum wall-clock wait for WAIT ticks. Bare number = seconds. Default: poll.timeoutSeconds (built-in 4.5m).\n --debounce <duration> Settle window after first FIX_CODE or stack SHEPHERD before returning. Bare number = seconds. Default: poll.debounceSeconds (built-in 60s). 0 disables.\n --quiet-status Print only changed WAIT snapshots. Overrides poll.quietStatus.\n --no-quiet-status Print every WAIT snapshot. Overrides poll.quietStatus.\n --until-terminal Continue through WAIT/MARK_READY until READY/FIX_CODE/MERGE/CANCEL/ESCALATE or stack SHEPHERD.\n\nForwarded iterate flags:\n --ready-delay <duration> Settle window before a clean PR cancels. Bare number = minutes. Example: 15m.\n --stall-timeout <duration> Escalate repeated unchanged failures after this duration. Bare number = minutes. 0 disables.\n --no-auto-mark-ready Do not convert draft PRs to ready for review.\n --no-auto-cancel-actionable Legacy no-op; workflow runs are never cancelled.\n --merge Shepherd through readiness, then emit a merge or merge-queue command.\n --format text|json Output Markdown text or JSON. Default: text.\n --verbose Include verbose iterate fields and detailed per-tick lines.\n --help, -h Print this help and exit before GitHub, git, config, or log I/O.\n\nDurations accept s/m/h suffixes: 30s, 4.5m, 1h. A bare number uses each flag's default unit (seconds\nfor --interval/--timeout/--debounce, minutes for --ready-delay/--stall-timeout); decimals are allowed only with\nan explicit unit (4.5m).\nEach WAIT tick writes a stderr line naming what it is waiting on by default; poll.quietStatus can change that default, --quiet-status/--no-quiet-status override it, and --verbose emits detailed per-tick lines.\nFIX_CODE debounce writes a remaining-seconds line to stderr. --timeout does not cut an in-flight debounce short.\nWith --until-terminal, --timeout is ignored for WAIT ticks and polling continues until READY, FIX_CODE, MERGE, CANCEL, or ESCALATE. With --merge, --timeout still bounds WAIT ticks; it only continues through MARK_READY while polling remains within that timeout.\n\nExit codes: same as iterate (the final tick's action/reason decides the code).\n 0 CANCEL (merged or ready-delay elapsed)\n 10 WAIT or READY (including a WAIT returned by --timeout)\n 11 MARK_READY\n 12 FIX_CODE\n 13 ESCALATE\n 14 CANCEL (closed without merging)\n 15 MERGE\n 16 SHEPHERD (--stack only: run the listed one-PR sessions, then rerun the selector)\n A command/validation/GitHub failure exits with a sysexits.h code instead (see docs/exit-codes.md).";
217
232
  readonly clean: `pr-shepherd clean
218
233
 
@@ -277,7 +292,7 @@ On POSIX, the final body-file path entry must be a readable regular file in a tr
277
292
  symlinks, FIFOs, devices, and unreadable paths exit 66. Unsupported platforms fail closed with exit 66.
278
293
  --help, -h Print this help and exit before any I/O.`;
279
294
  readonly "log-file": "pr-shepherd log-file\n\nPrint the per-worktree append-only debug log path for the current repository.\nThe log is created by the first non-help pr-shepherd command that initializes logging.\n\nUsage:\n pr-shepherd log-file [--format text|json]\n\nFlags:\n --format text|json Print a raw path or {\"path\": \"...\"} JSON. Default: text.\n --help, -h Print this help and exit before logging setup.\n\nEnvironment:\n PR_SHEPHERD_LOG_DISABLED=1 disables logging.\n PR_SHEPHERD_STATE_DIR overrides the base state directory.\n\nExit code: 0 on success; 1 if repository identity cannot be resolved.";
280
- readonly top: "pr-shepherd\n\nAutonomous PR CI monitor and review-comment resolver for agentic coding tools.\n\nUsage:\n pr-shepherd --version | -v\n pr-shepherd --help | -h\n pr-shepherd [PR ...] [poll-flags] [iterate-flags]\n pr-shepherd --stack PR [poll-flags] [iterate-flags]\n pr-shepherd iterate [PR] [iterate-flags]\n pr-shepherd apply review [PR] [review-flags]\n pr-shepherd apply files [PR] [files...] [--tests] [--match REGEX]\n pr-shepherd apply journal [PR] <item> [--dry-run] [--format text|json]\n pr-shepherd apply check-blocker [PR] --check <name> (--blocked-by <ref>|--clear)\n pr-shepherd journal extract --body-file <path>\n pr-shepherd build-suggestion-patches [PR] --thread-id ID --message MSG [groups...]\n pr-shepherd admin clean <pr|branch|current|repo|all> [value] [flags]\n pr-shepherd admin log-file [--format text|json]\n\nCommands:\n [PR ...] Poll one PR, an explicit same-repository set, or a native stack.\n iterate Run one iterate tick (single-tick alias).\n apply review Apply review-state mutations after fixes.\n apply files Mark selected changed files as viewed.\n apply journal Append a list item to the Shepherd Journal details block of a PR body.\n apply check-blocker Record that a failing check is blocked on an external PR or issue.\n journal extract Extract a validated Shepherd Journal from a local PR-body file as JSON.\n build-suggestion-patches\n Convert ordered GitHub suggestion threads into patches and commit instructions.\n admin clean Remove pr-shepherd state files.\n admin log-file Print the per-worktree debug log path.\n\nPR argument:\n PR may be a number, owner/repo#number, or a GitHub pull request URL.\n Multiple PRs must name one repository. --stack PR selects every entry in PR's native stack.\n When omitted, pr-shepherd infers the current branch's pull request.\n\nCommon flags:\n --format text|json Output Markdown text or JSON. Default: text.\n --verbose Include verbose iterate fields and detailed poll-tick lines.\n --help, -h Print help and exit before any GitHub, git, config, or log I/O.\n\nIterate flags:\n --ready-delay <duration> Settle window before a clean PR cancels. Bare number = minutes. Example: 15m.\n --stall-timeout <duration> Escalate repeated unchanged failures after this duration. Bare number = minutes. 0 disables.\n --no-auto-mark-ready Do not convert draft PRs to ready for review.\n --no-auto-cancel-actionable Legacy no-op; workflow runs are never cancelled.\n --merge Shepherd through readiness, then emit a merge or merge-queue command.\n\nPolling flags:\n --interval <duration> Delay between WAIT ticks. Bare number = seconds. Default: poll.intervalSeconds (built-in 60s). Stack and multi-PR polls multiply that by poll.stackIntervalFactor (built-in 2) unless this flag is set.\n --timeout <duration> Poll wall-clock cap for WAIT ticks. Bare number = seconds. Default: poll.timeoutSeconds (built-in 4.5m).\n --debounce <duration> Settle window after first FIX_CODE or stack SHEPHERD before returning. Bare number = seconds. Default: poll.debounceSeconds (built-in 60s). 0 disables.\n --quiet-status Print only changed WAIT snapshots. Overrides poll.quietStatus.\n --no-quiet-status Print every WAIT snapshot. Overrides poll.quietStatus.\n --until-terminal Continue through WAIT/MARK_READY until READY/FIX_CODE/MERGE/CANCEL/ESCALATE or stack SHEPHERD.\n\nClean variants:\n pr [number] Remove state for one PR. Defaults to current branch PR.\n branch [name] Remove state for a branch's PR. Defaults to current branch.\n current Alias for branch against the current branch.\n repo Remove all state for the current repository.\n all Remove all pr-shepherd state.\n\nExit codes: 0 done, 10-19 PR state, 64-78 shepherd failed (sysexits.h).\n 0 CANCEL (merged or ready-delay elapsed)\n 10 WAIT or READY\n 11 MARK_READY\n 12 FIX_CODE\n 13 ESCALATE\n 14 CANCEL (closed without merging)\n 15 MERGE\n 16 SHEPHERD (--stack only: run the listed one-PR sessions, then rerun the selector)\nSee docs/exit-codes.md for the full sysexits.h error-code table.\n\nDuration examples: 30s, 4.5m, 1h. A bare number uses each flag's default unit (see above); decimals are allowed with an explicit unit (4.5m).\n\nRun 'pr-shepherd <command> --help' for command-specific details.";
295
+ readonly top: "pr-shepherd\n\nAutonomous PR CI monitor and review-comment resolver for agentic coding tools.\n\nUsage:\n pr-shepherd --version | -v\n pr-shepherd --help | -h\n pr-shepherd [PR ...] [poll-flags] [iterate-flags]\n pr-shepherd --stack PR [poll-flags] [iterate-flags]\n pr-shepherd iterate [PR] [iterate-flags]\n pr-shepherd apply review [PR] [review-flags]\n pr-shepherd apply files [PR] [files...] [--tests] [--match REGEX]\n pr-shepherd apply journal [PR] <item> [--dry-run] [--format text|json]\n pr-shepherd apply check-blocker [PR] --check <name> (--blocked-by <ref>|--clear)\n pr-shepherd apply queue-removal [PR] --require-sha <head> --queue-commit <commit> --removed-at <unix>\n pr-shepherd journal extract --body-file <path>\n pr-shepherd build-suggestion-patches [PR] --thread-id ID --message MSG [groups...]\n pr-shepherd admin clean <pr|branch|current|repo|all> [value] [flags]\n pr-shepherd admin log-file [--format text|json]\n\nCommands:\n [PR ...] Poll one PR, an explicit same-repository set, or a native stack.\n iterate Run one iterate tick (single-tick alias).\n apply review Apply review-state mutations after fixes.\n apply files Mark selected changed files as viewed.\n apply journal Append a list item to the Shepherd Journal details block of a PR body.\n apply check-blocker Record that a failing check is blocked on an external PR or issue.\n apply queue-removal Acknowledge one current CI-driven native-stack queue removal.\n journal extract Extract a validated Shepherd Journal from a local PR-body file as JSON.\n build-suggestion-patches\n Convert ordered GitHub suggestion threads into patches and commit instructions.\n admin clean Remove pr-shepherd state files.\n admin log-file Print the per-worktree debug log path.\n\nPR argument:\n PR may be a number, owner/repo#number, or a GitHub pull request URL.\n Multiple PRs must name one repository. --stack PR selects every entry in PR's native stack.\n When omitted, pr-shepherd infers the current branch's pull request.\n\nCommon flags:\n --format text|json Output Markdown text or JSON. Default: text.\n --verbose Include verbose iterate fields and detailed poll-tick lines.\n --help, -h Print help and exit before any GitHub, git, config, or log I/O.\n\nIterate flags:\n --ready-delay <duration> Settle window before a clean PR cancels. Bare number = minutes. Example: 15m.\n --stall-timeout <duration> Escalate repeated unchanged failures after this duration. Bare number = minutes. 0 disables.\n --no-auto-mark-ready Do not convert draft PRs to ready for review.\n --no-auto-cancel-actionable Legacy no-op; workflow runs are never cancelled.\n --merge Shepherd through readiness, then emit a merge or merge-queue command.\n\nPolling flags:\n --interval <duration> Delay between WAIT ticks. Bare number = seconds. Default: poll.intervalSeconds (built-in 60s). Stack and multi-PR polls multiply that by poll.stackIntervalFactor (built-in 2) unless this flag is set.\n --timeout <duration> Poll wall-clock cap for WAIT ticks. Bare number = seconds. Default: poll.timeoutSeconds (built-in 4.5m).\n --debounce <duration> Settle window after first FIX_CODE or stack SHEPHERD before returning. Bare number = seconds. Default: poll.debounceSeconds (built-in 60s). 0 disables.\n --quiet-status Print only changed WAIT snapshots. Overrides poll.quietStatus.\n --no-quiet-status Print every WAIT snapshot. Overrides poll.quietStatus.\n --until-terminal Continue through WAIT/MARK_READY until READY/FIX_CODE/MERGE/CANCEL/ESCALATE or stack SHEPHERD.\n\nClean variants:\n pr [number] Remove state for one PR. Defaults to current branch PR.\n branch [name] Remove state for a branch's PR. Defaults to current branch.\n current Alias for branch against the current branch.\n repo Remove all state for the current repository.\n all Remove all pr-shepherd state.\n\nExit codes: 0 done, 10-19 PR state, 64-78 shepherd failed (sysexits.h).\n 0 CANCEL (merged or ready-delay elapsed)\n 10 WAIT or READY\n 11 MARK_READY\n 12 FIX_CODE\n 13 ESCALATE\n 14 CANCEL (closed without merging)\n 15 MERGE\n 16 SHEPHERD (--stack only: run the listed one-PR sessions, then rerun the selector)\nSee docs/exit-codes.md for the full sysexits.h error-code table.\n\nDuration examples: 30s, 4.5m, 1h. A bare number uses each flag's default unit (see above); decimals are allowed with an explicit unit (4.5m).\n\nRun 'pr-shepherd <command> --help' for command-specific details.";
281
296
  };
282
297
  /** Resolve help keys for nested public commands before any command I/O. */
283
298
  export declare function helpKeyForArgs(args: string[]): keyof typeof USAGE;
package/bin/cli/help.mjs CHANGED
@@ -15,6 +15,8 @@ export function helpKeyForArgs(args) {
15
15
  return "apply journal";
16
16
  if (args[0] === "apply" && args[1] === "check-blocker")
17
17
  return "apply check-blocker";
18
+ if (args[0] === "apply" && args[1] === "queue-removal")
19
+ return "apply queue-removal";
18
20
  if (args[0] === "journal" && args[1] === "extract")
19
21
  return "journal extract";
20
22
  if (args[0] === "admin" && args[1] === "clean")
@@ -48,7 +48,10 @@ export function buildSimpleIterateInstructions(result) {
48
48
  return instructions;
49
49
  }
50
50
  case "cancel":
51
- return ["Stop — the PR loop is complete. No further polling is needed."];
51
+ return [
52
+ "Stop polling this pull request — its poll is complete.",
53
+ "Continue any remaining pull requests or issues from the original request.",
54
+ ];
52
55
  case "escalate": {
53
56
  const pending = result.escalate.pendingReviewCommands;
54
57
  if (!pending)
@@ -152,6 +152,9 @@ export function projectIterateLean(result, opts) {
152
152
  protectedRuns: result.fix.protectedRuns,
153
153
  }),
154
154
  ...(result.fix.requeue && { requeue: result.fix.requeue }),
155
+ ...(result.fix.queueRemovalAcknowledgment && {
156
+ queueRemovalAcknowledgment: result.fix.queueRemovalAcknowledgment,
157
+ }),
155
158
  ...(result.fix.checks.length > 0 && { checks: result.fix.checks }),
156
159
  ...(result.fix.changesRequestedReviews.length > 0 && {
157
160
  changesRequestedReviews: result.fix.changesRequestedReviews,
@@ -40,6 +40,8 @@ export function appendMergeQueueHeader(lines, result) {
40
40
  parts.push("checks incomplete (first 100 shown)");
41
41
  if (queue.headUpdatedAfterRemoval)
42
42
  parts.push("head updated after removal");
43
+ if (queue.removalAcknowledged)
44
+ parts.push("removal acknowledged");
43
45
  lines.push(`**merge queue** ${parts.join(" · ")}`);
44
46
  if (queue.autoMergeRequest) {
45
47
  lines.push(`**auto-merge** method \`${queue.autoMergeRequest.mergeMethod}\` · enabledAtUnix \`${queue.autoMergeRequest.enabledAtUnix}\`${queue.autoMergeRequest.enabledBy ? ` · by \`@${queue.autoMergeRequest.enabledBy}\`` : ""}`);
@@ -0,0 +1,2 @@
1
+ /** `apply queue-removal`; help exits before argument validation and GitHub I/O. */
2
+ export declare function handleQueueRemoval(args: string[]): Promise<void>;
@@ -0,0 +1,86 @@
1
+ import { EXIT, errorToExitCode } from "../exit-codes.mjs";
2
+ import { applyQueueRemovalAck } from "../commands/apply-queue-removal.mjs";
3
+ import { getFlag, parseCommonArgs } from "./args.mjs";
4
+ import { maybePrintHelp, USAGE } from "./help.mjs";
5
+ const FLAGS = new Set(["--require-sha", "--queue-commit", "--removed-at"]);
6
+ /** `apply queue-removal`; help exits before argument validation and GitHub I/O. */
7
+ export async function handleQueueRemoval(args) {
8
+ if (maybePrintHelp(args, "apply queue-removal"))
9
+ return;
10
+ const { prNumber, global, extra } = parseCommonArgs(args);
11
+ const flagError = validateFlags(extra);
12
+ if (flagError) {
13
+ usage(flagError);
14
+ return;
15
+ }
16
+ const headSha = getFlag(extra, "--require-sha");
17
+ const queueCommitOid = getFlag(extra, "--queue-commit");
18
+ const removedAtText = getFlag(extra, "--removed-at");
19
+ if (headSha === null || !/^[0-9a-f]{40}$/.test(headSha)) {
20
+ usage("--require-sha must be a full 40-character lowercase hex SHA.", EXIT.DATAERR);
21
+ return;
22
+ }
23
+ if (queueCommitOid === null || !/^[0-9a-f]{40}$/.test(queueCommitOid)) {
24
+ usage("--queue-commit must be a full 40-character lowercase hex SHA.", EXIT.DATAERR);
25
+ return;
26
+ }
27
+ if (removedAtText === null || !/^[1-9]\d*$/.test(removedAtText)) {
28
+ usage("--removed-at must be a positive Unix timestamp in seconds.", EXIT.DATAERR);
29
+ return;
30
+ }
31
+ const removedAtUnix = Number(removedAtText);
32
+ if (!Number.isSafeInteger(removedAtUnix)) {
33
+ usage("--removed-at must be a positive Unix timestamp in seconds.", EXIT.DATAERR);
34
+ return;
35
+ }
36
+ try {
37
+ const result = await applyQueueRemovalAck({
38
+ prNumber,
39
+ targetRepository: global.targetRepository,
40
+ headSha,
41
+ queueCommitOid,
42
+ removedAtUnix,
43
+ });
44
+ const body = global.format === "json"
45
+ ? JSON.stringify(result, null, 2)
46
+ : [
47
+ `PR: ${result.repo}#${result.pr}`,
48
+ `headSha: ${result.acknowledgment.headSha}`,
49
+ `queueCommitOid: ${result.acknowledgment.queueCommitOid}`,
50
+ `removedAtUnix: ${result.acknowledgment.removedAtUnix}`,
51
+ ].join("\n");
52
+ process.stdout.write(`${body}\n`);
53
+ }
54
+ catch (err) {
55
+ const message = err instanceof Error ? err.message : String(err);
56
+ process.stderr.write(`pr-shepherd: apply queue-removal: ${message}\n`);
57
+ process.exitCode = errorToExitCode(err);
58
+ }
59
+ }
60
+ function validateFlags(args) {
61
+ for (let i = 0; i < args.length; i += 1) {
62
+ const arg = args[i];
63
+ if (!arg.startsWith("--"))
64
+ return `unexpected argument: "${arg}"`;
65
+ const eq = arg.indexOf("=");
66
+ const name = eq === -1 ? arg : arg.slice(0, eq);
67
+ if (!FLAGS.has(name))
68
+ return `unknown flag: "${name}"`;
69
+ if (eq !== -1) {
70
+ if (arg.slice(eq + 1) === "")
71
+ return `${name} requires a value.`;
72
+ continue;
73
+ }
74
+ const value = args[i + 1];
75
+ if (value === undefined || value.startsWith("--"))
76
+ return `${name} requires a value.`;
77
+ i += 1;
78
+ }
79
+ return null;
80
+ }
81
+ function usage(message, exitCode = EXIT.USAGE) {
82
+ process.stderr.write(`pr-shepherd: apply queue-removal: ${message}\n`);
83
+ if (exitCode === EXIT.USAGE)
84
+ process.stderr.write(`${USAGE["apply queue-removal"]}\n`);
85
+ process.exitCode = exitCode;
86
+ }
@@ -14,6 +14,7 @@ import { handleJournalExtract } from "./cli/journal-extract-handler.mjs";
14
14
  import { handlePoll } from "./cli/poll-handler.mjs";
15
15
  import { warnPrrcThreadIds, validateRequireSha, rejectPrrcMinimizeIds, } from "./cli/resolve-validators.mjs";
16
16
  import { handleCheckBlocker } from "./cli/check-blocker-handler.mjs";
17
+ import { handleQueueRemoval } from "./cli/queue-removal-handler.mjs";
17
18
  import { setupLog } from "./log/setup.mjs";
18
19
  // ---------------------------------------------------------------------------
19
20
  // Entry
@@ -135,6 +136,9 @@ async function handleApply(args) {
135
136
  case "check-blocker":
136
137
  await handleCheckBlocker(args.slice(1));
137
138
  return;
139
+ case "queue-removal":
140
+ await handleQueueRemoval(args.slice(1));
141
+ return;
138
142
  default:
139
143
  process.stderr.write(`Unknown apply action: ${action ?? "(none)"}\n`);
140
144
  process.stderr.write(`${USAGE.apply}\n`);
@@ -0,0 +1,18 @@
1
+ import { type QueueRemovalAcknowledgment } from "../state/queue-removal-ack.mts";
2
+ export interface ApplyQueueRemovalInput {
3
+ prNumber?: number;
4
+ targetRepository?: {
5
+ owner: string;
6
+ name: string;
7
+ };
8
+ headSha: string;
9
+ queueCommitOid: string;
10
+ removedAtUnix: number;
11
+ }
12
+ export interface ApplyQueueRemovalResult {
13
+ pr: number;
14
+ repo: string;
15
+ acknowledgment: QueueRemovalAcknowledgment;
16
+ }
17
+ /** Validate an observed native-stack CI queue removal before recording the caller's acknowledgment. */
18
+ export declare function applyQueueRemovalAck(input: ApplyQueueRemovalInput): Promise<ApplyQueueRemovalResult>;
@@ -0,0 +1,44 @@
1
+ import { EXIT, ShepherdError } from "../exit-codes.mjs";
2
+ import { fetchPrBatch } from "../github/batch.mjs";
3
+ import { queueRemovalAppliesToHead } from "../github/queue-removal-freshness.mjs";
4
+ import { getCurrentPrNumber, getRepoInfo } from "../github/client.mjs";
5
+ import { isCiQueueRemovalReason, writeQueueRemovalAcknowledgment, } from "../state/queue-removal-ack.mjs";
6
+ /** Validate an observed native-stack CI queue removal before recording the caller's acknowledgment. */
7
+ export async function applyQueueRemovalAck(input) {
8
+ const repo = input.targetRepository ?? (await getRepoInfo());
9
+ const pr = input.prNumber ?? (await getCurrentPrNumber());
10
+ if (pr === null) {
11
+ throw new ShepherdError("No open PR found for current branch. Pass a PR number explicitly.", EXIT.UNAVAILABLE);
12
+ }
13
+ const { data } = await fetchPrBatch(pr, repo);
14
+ const removal = data.latestMergeQueueRemoval;
15
+ if (data.state !== "OPEN" ||
16
+ !data.stack ||
17
+ data.isMergeQueueEnabled !== true ||
18
+ data.isInMergeQueue === true ||
19
+ !removal ||
20
+ !isCiQueueRemovalReason(removal.reason) ||
21
+ data.headRefOid !== input.headSha ||
22
+ removal.beforeCommitOid !== input.queueCommitOid ||
23
+ removal.createdAtUnix !== input.removedAtUnix ||
24
+ !queueRemovalAppliesToHead({
25
+ parentOids: removal.beforeCommitParentOids,
26
+ headOid: data.headRefOid,
27
+ ...(data.activity?.latestCommitCommittedAtUnix != null && {
28
+ headCommittedAtUnix: data.activity.latestCommitCommittedAtUnix,
29
+ }),
30
+ ...(data.headPushedAtUnix !== undefined && { headPushedAtUnix: data.headPushedAtUnix }),
31
+ removedAtUnix: removal.createdAtUnix,
32
+ })) {
33
+ throw new ShepherdError("The supplied queue-removal evidence is stale or is not a current CI-driven removal for this native-stack PR.", EXIT.UNAVAILABLE);
34
+ }
35
+ const acknowledgment = {
36
+ headSha: input.headSha,
37
+ queueCommitOid: input.queueCommitOid,
38
+ removedAtUnix: input.removedAtUnix,
39
+ };
40
+ if (!(await writeQueueRemovalAcknowledgment({ owner: repo.owner, repo: repo.name, pr }, acknowledgment))) {
41
+ throw new ShepherdError("Could not write queue-removal acknowledgment state.", EXIT.UNAVAILABLE);
42
+ }
43
+ return { pr, repo: `${repo.owner}/${repo.name}`, acknowledgment };
44
+ }
@@ -10,6 +10,8 @@ function reportAllowsFingerprintSkip(report) {
10
10
  return false;
11
11
  if (report.mergeQueue?.inQueue === true)
12
12
  return false;
13
+ if (report.mergeQueue?.removalAcknowledged === true)
14
+ return false;
13
15
  return (report.threads.actionable.length === 0 &&
14
16
  report.threads.resolutionOnly.length === 0 &&
15
17
  report.threads.firstLook.length === 0 &&
@@ -1,5 +1,6 @@
1
1
  import { fetchPrBatch } from "../github/batch.mjs";
2
2
  import { queueRemovalAppliesToHead } from "../github/queue-removal-freshness.mjs";
3
+ import { readQueueRemovalAcknowledgment, matchesQueueRemovalAcknowledgment, isCiQueueRemovalReason, } from "../state/queue-removal-ack.mjs";
3
4
  import { storePrFingerprint } from "../state/pr-fingerprint.mjs";
4
5
  import { tryReuseFingerprintReport } from "./check-fingerprint.mjs";
5
6
  import { collectUnreportedRequired, refreshCachedUnreported } from "./check-unreported.mjs";
@@ -91,9 +92,19 @@ export async function runCheck(opts, context) {
91
92
  }),
92
93
  removedAtUnix: latestRemoval.createdAtUnix,
93
94
  }));
95
+ const removalAcknowledged = Boolean(batchData.stack &&
96
+ latestRemoval?.beforeCommitOid &&
97
+ isCiQueueRemovalReason(latestRemoval.reason) &&
98
+ !batchData.isInMergeQueue &&
99
+ !headUpdatedAfterRemoval &&
100
+ matchesQueueRemovalAcknowledgment(await readQueueRemovalAcknowledgment(stateKey), {
101
+ headSha: batchData.headRefOid,
102
+ queueCommitOid: latestRemoval.beforeCommitOid,
103
+ removedAtUnix: latestRemoval.createdAtUnix,
104
+ }));
94
105
  const queueRawChecks = batchData.isInMergeQueue
95
106
  ? (batchData.mergeQueueChecks ?? [])
96
- : latestRemoval && !headUpdatedAfterRemoval
107
+ : latestRemoval && !headUpdatedAfterRemoval && !removalAcknowledged
97
108
  ? (batchData.removedMergeQueueChecks ?? [])
98
109
  : [];
99
110
  // Keep supersession grouping commit-local, but accept merge_group only for the
@@ -356,6 +367,7 @@ export async function runCheck(opts, context) {
356
367
  checksIncomplete: true,
357
368
  }),
358
369
  ...(headUpdatedAfterRemoval && { headUpdatedAfterRemoval: true }),
370
+ ...(removalAcknowledged && { removalAcknowledged: true }),
359
371
  },
360
372
  }),
361
373
  ...(unreported.unreportedRequiredChecks && {
@@ -0,0 +1,4 @@
1
+ import type { AgentCheck } from "../../types.mts";
2
+ export declare function hasLogEvidence(check: AgentCheck): boolean;
3
+ /** An external provider link is inspectable even when Actions log downloads are unavailable. */
4
+ export declare function hasQueueRecoveryEvidence(check: AgentCheck): boolean;
@@ -0,0 +1,8 @@
1
+ export function hasLogEvidence(check) {
2
+ return (Boolean(check.logExcerpt?.trim()) ||
3
+ (check.relatedJobs ?? []).some((job) => Boolean(job.logExcerpt?.trim())));
4
+ }
5
+ /** An external provider link is inspectable even when Actions log downloads are unavailable. */
6
+ export function hasQueueRecoveryEvidence(check) {
7
+ return hasLogEvidence(check) || (check.runId === null && Boolean(check.detailsUrl?.trim()));
8
+ }
@@ -6,6 +6,8 @@ import { checkEscalateTriggers, validateBaseBranch, buildEscalateSuggestion, bui
6
6
  import { buildResolveCommand } from "./classify.mjs";
7
7
  import { buildThreadMutationRouting, threadHasAuthorizedMutation, } from "./thread-mutation-routing.mjs";
8
8
  import { buildFixInstructions } from "./render.mjs";
9
+ import { buildRemovedQueueRecovery, buildStackQueueRemovalAcknowledgment } from "./merge.mjs";
10
+ import { hasLogEvidence } from "./check-evidence.mjs";
9
11
  import { buildReleasedBlockerInstruction } from "./check-instructions.mjs";
10
12
  import { buildNativeStackLayerRebase } from "./native-stack-rebase.mjs";
11
13
  import { lookupUpperLayerTrunkConflict } from "./stack-trunk-conflict.mjs";
@@ -19,10 +21,6 @@ import { canRerunWorkflows } from "../../checks/conclusions.mjs";
19
21
  import { loadConfig } from "../../config/load.mjs";
20
22
  import { formatPrUrl } from "../../pr-reference.mjs";
21
23
  const EMPTY_RELEASED = new Set();
22
- function hasLogEvidence(check) {
23
- return (Boolean(check.logExcerpt?.trim()) ||
24
- (check.relatedJobs ?? []).some((job) => Boolean(job.logExcerpt?.trim())));
25
- }
26
24
  function checkRequiresHumanFollowUp(check) {
27
25
  if (check.rerunCommand)
28
26
  return false;
@@ -171,6 +169,8 @@ export async function handleFixCode(ctx) {
171
169
  if (releasedCheckNames.has(c.name))
172
170
  return c;
173
171
  return rerunAuthorized &&
172
+ // Rerunning queue CI cannot restore a removed entry and overwrites its failure evidence.
173
+ c.scope !== "merge_group" &&
174
174
  c.runId &&
175
175
  actionsRunIds.has(c.runId) &&
176
176
  // GitHub increments run_attempt after every rerun. Recommend at most one rerun by limiting
@@ -306,6 +306,20 @@ export async function handleFixCode(ctx) {
306
306
  ? buildNativeStackLayerRebase(report.repo, { number: prNumber, baseBranch: baseLookup.branch }, stack, trunkConflict)
307
307
  : undefined;
308
308
  const instructions = buildFixInstructions(threads, actionableComments, checks, changesRequestedReviews, baseLookup.branch, resolveCommand, hasConflicts, prReference, cancelled.length, firstLookThreads, firstLookComments, firstLookSummaries, editedSummaries, inProgressRunIds, resolutionOnlyThreads, resolveOnlyCommand, behindBaseHint, isBehind, report.viewerAuthorization?.viewerCanUpdate === true, exhaustedAttempts.length > 0, stackRebase);
309
+ const requeue = buildRemovedQueueRecovery(report, failingAgentChecks, opts.merge);
310
+ const queueRemovalAcknowledgment = buildStackQueueRemovalAcknowledgment(report, failingAgentChecks);
311
+ if (queueRemovalAcknowledgment) {
312
+ const completion = instructions.pop();
313
+ instructions.push("If the merge-group failure belongs to this PR, fix and push its head, then iterate. Otherwise, if no code changed and no other blocker remains, run `acknowledge queue removal:` exactly as printed. This records only the disposition of that removed queue commit; finish this one-PR session to validate current source CI and record its READY receipt, then return to the aggregate `--stack` selector with its original options. In merge mode it verifies lower-layer readiness before merging. Do not enqueue or merge this layer directly.");
314
+ if (completion !== undefined)
315
+ instructions.push(completion);
316
+ }
317
+ if (requeue) {
318
+ const completion = instructions.pop();
319
+ instructions.push("If the merge-group failure belongs to this PR, fix and push the PR head, then iterate. Otherwise, if no code changed and no other blocker remains, run the `requeue:` command exactly as printed. If gh reports auto-merge is disabled instead of adding the PR to the queue, run the `requeue API fallback:` command. Both commands require the observed PR head SHA; if the head changed, iterate for a fresh command.");
320
+ if (completion !== undefined)
321
+ instructions.push(completion);
322
+ }
309
323
  if (failingAgentChecks.some((check) => releasedCheckNames.has(check.name))) {
310
324
  const completion = instructions.pop();
311
325
  instructions.push(buildReleasedBlockerInstruction(prNumber));
@@ -342,6 +356,8 @@ export async function handleFixCode(ctx) {
342
356
  editedSummaries,
343
357
  surfacedApprovals,
344
358
  checks,
359
+ ...(requeue && { requeue }),
360
+ ...(queueRemovalAcknowledgment && { queueRemovalAcknowledgment }),
345
361
  changesRequestedReviews,
346
362
  resolveCommand,
347
363
  ...(resolveOnlyCommand !== undefined ? { resolveOnlyCommand } : undefined),
@@ -109,7 +109,9 @@ async function runIterateCore(opts) {
109
109
  editedSummaries.length > 0 ||
110
110
  (config.iterate.minimizeApprovals && surfacedApprovals.length > 0);
111
111
  const hasActionableWork = hasReadinessWork || report.comments.firstLook.length > 0;
112
- const activeMerge = Boolean(opts.merge && (report.mergeQueue?.inQueue || report.mergeQueue?.autoMergeRequest));
112
+ const activeMerge = Boolean(opts.merge &&
113
+ (report.mergeQueue?.inQueue ||
114
+ (report.mergeQueue?.autoMergeRequest && !report.mergeQueue.removalAcknowledged)));
113
115
  const staleAncestry = await findStaleNativeStackAncestry(report, {
114
116
  owner: repoOwner,
115
117
  name: repoName,
@@ -307,6 +309,18 @@ async function recordReadyReceipt(key, report, context) {
307
309
  if (!isCurrentSummaryReady(raw, summary.checks ?? {}, summary.review ?? {}))
308
310
  return false;
309
311
  const removalEvent = currentQueueRemovalEvent(raw);
312
+ // Bind recovery to the exact evidence the one-PR check accepted. A new ejection
313
+ // between that check and this fresh snapshot must get its own acknowledgment.
314
+ if (report.mergeQueue?.removalAcknowledged) {
315
+ const accepted = report.mergeQueue.latestRemoval;
316
+ if (raw.isInMergeQueue ||
317
+ !accepted ||
318
+ !removalEvent ||
319
+ removalEvent.beforeCommit?.oid !== accepted.beforeCommitOid ||
320
+ Math.floor(Date.parse(removalEvent.createdAt) / 1000) !== accepted.createdAtUnix ||
321
+ removalEvent.reason !== accepted.reason)
322
+ return false;
323
+ }
310
324
  await writeReadyReceipt({
311
325
  version: 1,
312
326
  ...key,
@@ -115,7 +115,10 @@ export async function handleActiveMergeState(input) {
115
115
  };
116
116
  }
117
117
  const removal = report.mergeQueue?.latestRemoval;
118
- if (!enabled || !removal || report.mergeQueue?.headUpdatedAfterRemoval)
118
+ if (!enabled ||
119
+ !removal ||
120
+ report.mergeQueue?.headUpdatedAfterRemoval ||
121
+ report.mergeQueue?.removalAcknowledged)
119
122
  return null;
120
123
  await clearStallState(stallKey);
121
124
  const escalateBase = {
@@ -1,5 +1,5 @@
1
1
  import { type MergeMethod } from "../../config/merge-method.mts";
2
- import type { IterateResult, IterateResultBase, MergeCommandPlan } from "../../types.mts";
2
+ import type { AgentCheck, IterateResult, IterateResultBase, MergeCommandPlan, ShepherdReport } from "../../types.mts";
3
3
  interface MergePlanInput {
4
4
  pr: number;
5
5
  repo: string;
@@ -16,6 +16,12 @@ export declare function buildMergeCommandPlan(input: MergePlanInput): MergeComma
16
16
  export declare function renderMergeCommand(command: {
17
17
  argv: string[];
18
18
  }): string;
19
+ /** Offer a guarded queue command; the caller decides whether the failure warrants a PR fix. */
20
+ export declare function buildRemovedQueueRecovery(report: ShepherdReport, checks: AgentCheck[], merge: boolean | undefined): MergeCommandPlan | undefined;
21
+ /** Bind a caller's disposition to one removed stack queue commit, without submitting a merge. */
22
+ export declare function buildStackQueueRemovalAcknowledgment(report: ShepherdReport, checks: AgentCheck[]): {
23
+ argv: string[];
24
+ } | undefined;
19
25
  export declare function unavailableMergeResult(base: IterateResultBase, report: {
20
26
  pr: number;
21
27
  repo: string;
@@ -2,7 +2,9 @@ import { loadConfig } from "../../config/load.mjs";
2
2
  import { findMergeStrategies } from "../../config/merge-command-args.mjs";
3
3
  import { chooseMergeMethod, configuredMergeMethod, } from "../../config/merge-method.mjs";
4
4
  import { formatPrUrl } from "../../pr-reference.mjs";
5
- import { renderShellCommand } from "../../cli/runner.mjs";
5
+ import { renderShellCommand, buildPrShepherdCommand } from "../../cli/runner.mjs";
6
+ import { hasQueueRecoveryEvidence } from "./check-evidence.mjs";
7
+ import { isCiQueueRemovalReason } from "../../state/queue-removal-ack.mjs";
6
8
  import { buildEscalateHumanMessage } from "./escalate.mjs";
7
9
  const ENQUEUE_MUTATION = "mutation EnqueuePullRequest($pullRequestId: ID!, $expectedHeadOid: GitObjectID!) { enqueuePullRequest(input: { pullRequestId: $pullRequestId, expectedHeadOid: $expectedHeadOid }) { mergeQueueEntry { id } } }";
8
10
  export function buildMergeCommandPlan(input) {
@@ -55,6 +57,62 @@ export function buildMergeCommandPlan(input) {
55
57
  export function renderMergeCommand(command) {
56
58
  return renderShellCommand(command.argv);
57
59
  }
60
+ /** Offer a guarded queue command; the caller decides whether the failure warrants a PR fix. */
61
+ export function buildRemovedQueueRecovery(report, checks, merge) {
62
+ if (report.mergeStatus.mergeRequirements?.stack)
63
+ return undefined;
64
+ if (!removedQueueRecoveryAvailable(report, checks, merge))
65
+ return undefined;
66
+ const plan = buildMergeCommandPlan({
67
+ pr: report.pr,
68
+ repo: report.repo,
69
+ nodeId: report.nodeId,
70
+ headSha: report.headSha,
71
+ queue: true,
72
+ });
73
+ return "unavailable" in plan ? undefined : plan;
74
+ }
75
+ /** Bind a caller's disposition to one removed stack queue commit, without submitting a merge. */
76
+ export function buildStackQueueRemovalAcknowledgment(report, checks) {
77
+ if (!report.mergeStatus.mergeRequirements?.stack)
78
+ return undefined;
79
+ // This records a local disposition, without enqueueing; aggregate child sessions omit --merge.
80
+ if (!removedQueueRecoveryAvailable(report, checks, true))
81
+ return undefined;
82
+ const removal = report.mergeQueue.latestRemoval;
83
+ return buildPrShepherdCommand([
84
+ "apply",
85
+ "queue-removal",
86
+ formatPrUrl(report.repo, report.pr),
87
+ "--require-sha",
88
+ report.headSha,
89
+ "--queue-commit",
90
+ removal.beforeCommitOid,
91
+ "--removed-at",
92
+ String(removal.createdAtUnix),
93
+ ]);
94
+ }
95
+ function removedQueueRecoveryAvailable(report, checks, merge) {
96
+ const queue = report.mergeQueue;
97
+ const removedCommit = queue?.latestRemoval?.beforeCommitOid;
98
+ if (!merge ||
99
+ !queue?.enabled ||
100
+ queue.inQueue ||
101
+ queue.headUpdatedAfterRemoval ||
102
+ // GitHub exposes a raw string, not a capability to reverse a human's queue removal.
103
+ // Only known CI-driven reasons authorize offering automated recovery.
104
+ !isCiQueueRemovalReason(queue.latestRemoval?.reason) ||
105
+ !queue.latestRemoval ||
106
+ queue.latestRemoval.createdAtUnix <= 0 ||
107
+ !removedCommit ||
108
+ !report.headSha ||
109
+ !report.nodeId ||
110
+ !checks.some((check) => check.scope === "merge_group" && check.commitOid === removedCommit))
111
+ return false;
112
+ return checks
113
+ .filter((check) => check.scope === "merge_group" && check.commitOid === removedCommit)
114
+ .every(hasQueueRecoveryEvidence);
115
+ }
58
116
  export function unavailableMergeResult(base, report, unavailable) {
59
117
  const escalateBase = {
60
118
  triggers: ["merge-method-unavailable"],
@@ -12,6 +12,8 @@ fragment PollSummaryCheckContexts on StatusCheckRollupContextConnection {
12
12
  status
13
13
  conclusion
14
14
  detailsUrl
15
+ startedAt
16
+ completedAt
15
17
  checkSuite {
16
18
  createdAt
17
19
  workflowRun {