pr-shepherd 2.2.5 → 2.2.7

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 (55) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +31 -36
  3. package/bin/cli/error-format.mjs +15 -1
  4. package/bin/cli/iterate-instructions.mjs +3 -0
  5. package/bin/cli/list-formatters.d.mts +3 -1
  6. package/bin/cli/list-formatters.mjs +7 -4
  7. package/bin/cli/mutate-formatter.mjs +5 -1
  8. package/bin/cli/stack-layer-view.d.mts +5 -0
  9. package/bin/cli/stack-layer-view.mjs +11 -1
  10. package/bin/cli/stack-overview.d.mts +1 -1
  11. package/bin/cli/stack-overview.mjs +5 -3
  12. package/bin/commands/apply-merge-resume.d.mts +22 -0
  13. package/bin/commands/apply-merge-resume.mjs +56 -0
  14. package/bin/commands/apply-merge.mjs +11 -19
  15. package/bin/commands/check.mjs +5 -4
  16. package/bin/commands/iterate/check-follow-up.mjs +1 -1
  17. package/bin/commands/iterate/index.mjs +4 -4
  18. package/bin/commands/iterate/merge-plan.d.mts +4 -0
  19. package/bin/commands/iterate/merge-plan.mjs +18 -0
  20. package/bin/commands/iterate/merge-state.mjs +2 -0
  21. package/bin/commands/iterate/report-gaps.d.mts +6 -0
  22. package/bin/commands/iterate/report-gaps.mjs +5 -0
  23. package/bin/commands/poll-summary.mjs +3 -1
  24. package/bin/commands/review-commit.d.mts +2 -2
  25. package/bin/commands/review-commit.mjs +11 -4
  26. package/bin/commands/stack-merge-plan.mjs +5 -3
  27. package/bin/commands/stack-merge-trunk-check.d.mts +12 -0
  28. package/bin/commands/stack-merge-trunk-check.mjs +26 -0
  29. package/bin/commands/stack-trunk-behind.d.mts +9 -0
  30. package/bin/commands/stack-trunk-behind.mjs +51 -0
  31. package/bin/comments/uncertain-replies.mjs +12 -5
  32. package/bin/config/merge-method.d.mts +2 -0
  33. package/bin/config/merge-method.mjs +17 -0
  34. package/bin/github/batch-parsers.mjs +9 -0
  35. package/bin/github/batch-raw-types.d.mts +8 -0
  36. package/bin/github/gql/batch-pr.gql +8 -0
  37. package/bin/github/poll-summary-readiness.mjs +2 -1
  38. package/bin/github/poll-summary-route.mjs +2 -1
  39. package/bin/github/rest-merge.d.mts +10 -0
  40. package/bin/github/rest-merge.mjs +26 -0
  41. package/bin/github/transport-evidence.d.mts +9 -2
  42. package/bin/github/transport-evidence.mjs +15 -3
  43. package/bin/state/base.mjs +2 -26
  44. package/bin/state/merge-request.d.mts +6 -0
  45. package/bin/state/merge-request.mjs +9 -1
  46. package/bin/types/github.d.mts +2 -0
  47. package/bin/types/merge-action.d.mts +6 -0
  48. package/bin/types/poll-summary.d.mts +4 -0
  49. package/package.json +1 -1
  50. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  51. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  52. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +1 -1
  53. package/plugins/pr-shepherd/skills/pr-shepherd/references/check-follow-up.md +1 -1
  54. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-start-stall.md +1 -1
  55. package/plugins/pr-shepherd/skills/pr-shepherd/references/required-checks-unreported.md +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
3
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
4
- "version": "2.2.5",
4
+ "version": "2.2.7",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
7
7
  "email": "jonathanrichardong@gmail.com"
package/README.md CHANGED
@@ -1,45 +1,42 @@
1
1
  # pr-shepherd
2
2
 
3
- Take pull requests from scratch to merge-ready with a coding agent as a [Code Mode-style](https://code.claude.com/docs/en/code-mode) plugin. It works with Claude Code, Codex, and Grok.
3
+ Take pull requests from scratch to merge-ready with a coding agent, as a [Code Mode-style](https://code.claude.com/docs/en/code-mode) plugin. It works with Claude Code, Codex, and Grok.
4
4
 
5
5
  ## Benefits
6
6
 
7
- - **Better decisions:** across 56 PR states, the agent scores 0.97 with the plugin vs. 0.47 with `gh` + the GitHub MCP server ([outcome evals](evals/README.md), 2026-11-15).
7
+ - **Better decisions:** across 56 PR states, it scores 0.97 with the plugin vs. 0.47 with `gh` + the GitHub MCP server ([outcome evals](evals/README.md), 2026-11-15).
8
8
  - **Lower cost:** modeled cost per PR session is about 36% lower than `gh` and 76% lower than the GitHub MCP server, with 20% / 69% fewer turns ([token bench](evals/tokens/README.md); assumes a warm prompt cache).
9
- - **More PRs on one GitHub quota:** 65% fewer GraphQL points than `gh` per PR session. While CI runs, one 5,000-point hourly budget covers about 80 waiting PRs, vs. about 13 with `gh pr checks --watch` ([GitHub API](docs/github-api.md), [GraphQL usage](docs/graphql-usage.md)). A [GitHub App](docs/github-app.md) and [webhook events](docs/hook-harness.md) cut it further.
10
- - **72 GitHub edge cases handled:** for example, outdated or resolved threads are still shown once, comments edited after the agent read them come back, and conflicts that GraphQL reports as `CLEAN` are caught ([handled cases](docs/handled-cases.md)).
11
- - **Tidy PRs:** bot and outdated comments are triaged and resolved, human reviews get replies, and known bot noise is minimized.
12
- - **Review hygiene:** Shepherd never answers its own replies, skips a denied reply once instead of retrying, hands a repeatedly rejected fix to a human, and never minimizes human comments ([comments and reviews](docs/handled-cases.md#comments-and-reviews)).
13
- - **Less context:** resolved comments and configured bot noise are filtered out before they reach the agent.
14
- - **CI failures, pre-read:** each failing check comes with its failed step, summary, and a log excerpt, so the agent can usually skip fetching logs. Superseded runs, required checks that never started, and approval gates are recognized ([failing checks](docs/actions.md#failing-checks-and-reruns), [CI cases](docs/handled-cases.md#ci-checks)).
15
- - **Cheaper CI:** names the in-progress runs a fix push would cancel anyway, so the agent cancels them early.
16
- - **Why a PR can't merge:** reads branch protection and rulesets and prints the actual requirements, such as `Approvals: None [Required]` ([merge requirements](docs/merge-status.md#merge-requirements)). Merges are pinned to the head the agent checked, review nits wait so a push doesn't eject a queued PR, and a PR a maintainer pulled from the queue is not requeued ([merge and queue](docs/handled-cases.md#merge-and-queue)).
17
- - **Full flow:** from scratch to draft, mergeable, and through the merge queue, including stacked PRs.
18
- - **Review suggestions:** applies suggested changes as commits that credit the reviewer.
19
- - **Safe by construction:** the CLI never mutates git or merges by itself, and human handoff is limited to a [short escalation list](docs/escalations.md).
9
+ - **More PRs on one GitHub quota:** 65% fewer GraphQL points than `gh` per PR session. While CI runs, a 5,000-point hourly budget covers about 80 waiting PRs, vs. about 13 with `gh pr checks --watch` ([GitHub API](docs/github-api.md), [GraphQL usage](docs/graphql-usage.md)). A [GitHub App](docs/github-app.md) and [webhook events](docs/hook-harness.md) cut it more.
10
+ - **72 GitHub edge cases handled:** outdated or resolved threads are still shown once, edited comments come back, and conflicts that GraphQL reports as `CLEAN` are caught ([handled cases](docs/handled-cases.md)).
11
+ - **Tidy PRs, less context:** bot and outdated comments are triaged and resolved, human reviews get replies, and known bot noise is minimized and filtered out before it reaches the agent.
12
+ - **Review hygiene:** it never answers its own replies or minimizes human comments, skips a denied reply once, and hands a repeatedly rejected fix to a human ([comments and reviews](docs/handled-cases.md#comments-and-reviews)).
13
+ - **CI failures, pre-read:** each failing check comes with its failed step, summary, and log excerpt, so the agent rarely fetches logs. Superseded runs, unstarted required checks, and approval gates are recognized ([failing checks](docs/actions.md#failing-checks-and-reruns), [CI cases](docs/handled-cases.md#ci-checks)).
14
+ - **Cheaper CI:** names the in-progress runs a fix push would cancel anyway.
15
+ - **Why a PR can't merge:** prints the actual branch protection and ruleset requirements, such as `Approvals: None [Required]` ([merge requirements](docs/merge-status.md#merge-requirements)). Merges are pinned to the head the agent checked, and a PR a maintainer pulled from the queue is not requeued ([merge and queue](docs/handled-cases.md#merge-and-queue)).
16
+ - **Full flow:** draft to mergeable to merged, through the merge queue and stacks. Suggested changes become commits that credit the reviewer.
17
+ - **Safe by construction:** the CLI never mutates git or merges by itself, and human handoff is limited to a [short list](docs/escalations.md).
20
18
 
21
19
  ## Use cases
22
20
 
23
- - **Autonomous agents.** An agent opens a PR and drives it to merge-ready, or merged when you allow it. Nobody has to watch CI and reviews.
24
- - **Exhaustive AI code review.** Some PRs get many bot reviews (CodeRabbit, Codex, Copilot, and others). Shepherd shows every thread and comment once and tracks first-look, edited, and outdated items. It pre-filters comments, batches the replies, resolves, and minimizes.
25
- - **High-velocity teams.** Supports stacked PRs, merge queues, and merge queue ejections, and directs agents to rebase or stack as needed, so work keeps moving even with many conflicts.
21
+ - **Autonomous agents.** An agent opens a PR and drives it to merge-ready, or merged when you allow it, with nobody watching CI and reviews.
22
+ - **Exhaustive AI code review.** For PRs with many bot reviews (CodeRabbit, Codex, Copilot), Shepherd shows every thread and comment once, tracks first-look, edited, and outdated items, and batches replies, resolves, and minimizes.
23
+ - **High-velocity teams.** Stacked PRs, merge queues, and ejections are supported, and agents are told to rebase or stack as needed, so work keeps moving.
26
24
 
27
25
  ## How to use
28
26
 
29
27
  [Install](#install) the plugin, then ask your agent:
30
28
 
31
- - **"make PRs, /pr-shepherd:pr-shepherd"** makes one PR per change that can be reviewed alone, stacks a PR on an earlier one when it needs that PR's code or edits the same lines, and shepherds every PR until it is mergeable.
32
- - **`/pr-shepherd <PR>`** takes a PR, including a draft, to mergeable. It does not merge. Leave out the PR to use the current branch.
33
- - **`/pr-shepherd <PR1> <PR2>`** shepherds several PRs and returns when any has an actionable step.
29
+ - **"make PRs, /pr-shepherd:pr-shepherd"** makes one PR per separately reviewable change, stacks a PR on an earlier one when it needs that PR's code or edits the same lines, and shepherds every PR until it is mergeable.
30
+ - **`/pr-shepherd <PR>`** takes a PR, including a draft, to mergeable without merging. Omit the PR to use the current branch.
31
+ - **`/pr-shepherd <PR1> <PR2>`** shepherds several PRs, returning when any needs action.
34
32
  - **`/pr-shepherd --merge <PR>`** takes the PR to mergeable and merges it.
35
- - **`/pr-shepherd stack <stack#> --merge`** shepherds a native stack and merges it all at once when it is ready. Use `--merge-through <PR>` instead to merge up to that layer, or `--merge-ready` to merge the bottom layers as they become ready. Listing PR numbers instead of the stack number owns only those layers.
33
+ - **`/pr-shepherd stack <stack#> --merge`** shepherds a native stack and merges it all at once when it is ready. `--merge-through <PR>` merges up to that layer, and `--merge-ready` merges the bottom layers as they become ready. Listing PR numbers instead of the stack number owns only those layers.
36
34
 
37
- In Codex, use `$pr-shepherd`. In a shell or CI, run `pr-shepherd <PR>`. `/goal` is generally not needed.
35
+ In Codex, use `$pr-shepherd`. In a shell or CI, run `pr-shepherd <PR>`.
38
36
 
39
- Then run **`/pr-shepherd:setup-pr-shepherd`** (Codex: `$setup-pr-shepherd`) to scan your recent PRs for recurring bot noise and configure `.pr-shepherdrc.yml` for you, or edit it by hand ([configuration](docs/configuration.md)):
37
+ Then run **`/pr-shepherd:setup-pr-shepherd`** (Codex: `$setup-pr-shepherd`) to scan recent PRs for recurring bot noise and configure `.pr-shepherdrc.yml`, or edit it by hand ([configuration](docs/configuration.md)):
40
38
 
41
- - turn on the bundled classification rules to hide known bot comments;
42
- - add your own [classification rules](examples/classification/);
39
+ - turn on the bundled classification rules to hide known bot comments, or add your own ([examples](examples/classification/));
43
40
  - list code-review workflows in `checks.never-cancel` so they always finish.
44
41
 
45
42
  ```yaml
@@ -52,11 +49,11 @@ checks:
52
49
  - "*review*"
53
50
  ```
54
51
 
55
- Optionally, write your policy ("reply instead of fixing nits", "never merge") into a skill that wraps the shipped one ([skills](docs/skills.md)).
52
+ Optionally, put your policy ("reply instead of fixing nits", "never merge") in a skill that wraps the shipped one ([skills](docs/skills.md)).
56
53
 
57
54
  ## What it does
58
55
 
59
- Shepherd gathers the full PR context (reviews, CI failures, merge requirements) in one call and returns one action with numbered instructions and exact commands. The agent spends fewer reasoning tokens, tool calls, and turns, and rarely has to investigate on its own.
56
+ Shepherd gathers the full PR context (reviews, CI failures, merge requirements) in one call and returns one action with numbered instructions and exact commands, so the agent needs fewer tokens, calls, and turns.
60
57
 
61
58
  ```text
62
59
  $ pr-shepherd 123
@@ -77,7 +74,7 @@ $ pr-shepherd 123
77
74
  4. Rerun Shepherd now.
78
75
  ```
79
76
 
80
- More features are in [docs/features.md](docs/features.md).
77
+ More in [docs/features.md](docs/features.md).
81
78
 
82
79
  ## Install
83
80
 
@@ -99,25 +96,23 @@ grok plugin install pr-shepherd --trust
99
96
  pnpm i -g pr-shepherd
100
97
  ```
101
98
 
102
- Use one package manager for global installs, because a second global copy shadows the first (`which -a pr-shepherd` lists every copy).
99
+ Use one package manager for global installs; a second copy shadows the first (`which -a pr-shepherd` lists them).
103
100
 
104
- The plugin is the CLI plus skills; it does not start the MCP server. For why, and to register the server yourself, see [docs/mcp.md](docs/mcp.md#why-the-plugin-does-not-start-it).
101
+ The plugin does not start the MCP server. For why, and to register it yourself, see [docs/mcp.md](docs/mcp.md#why-the-plugin-does-not-start-it).
105
102
 
106
103
  Requirements:
107
104
 
108
- - Node.js >= 22.19.0, Bun, or Deno
109
- - `git`
110
- - A GitHub token or an authenticated `gh` CLI with [the required access](docs/authentication.md)
105
+ - Node.js >= 22.19.0, Bun, or Deno, and `git`
106
+ - A GitHub token or authenticated `gh` CLI with [the required access](docs/authentication.md)
111
107
 
112
108
  ## Documentation
113
109
 
114
110
  [docs/README.md](docs/README.md) indexes every doc. Start with:
115
111
 
116
- - [Features, workflow assumptions, and limits](docs/features.md)
117
- - [CLI commands, flags, stacks, and polling](docs/cli-usage.md)
112
+ - [Features and limits](docs/features.md)
113
+ - [CLI commands and flags](docs/cli-usage.md)
118
114
  - [Actions](docs/actions.md) and [exit codes](docs/exit-codes.md)
119
- - [Configuration and classification rules](docs/configuration.md), with [examples](examples/classification/)
120
- - [Comparison with Cursor, Copilot, CodeRabbit, and others](docs/comparison.md)
115
+ - [Configuration](docs/configuration.md) and [comparison with other tools](docs/comparison.md)
121
116
  - [Upgrading from 0.x](docs/migrating-to-v1.md)
122
117
 
123
118
  ## Harness ecosystem
@@ -1,4 +1,6 @@
1
+ import { relative, isAbsolute } from "node:path";
1
2
  import { GitHubRequestError } from "../github/errors.mjs";
3
+ import { resolveStateBase } from "../state/base.mjs";
2
4
  /** Safe GitHub transport metadata suitable for user-facing structured error output. */
3
5
  export function serializeGitHubRequestErrorDetails(err) {
4
6
  if (!(err instanceof GitHubRequestError))
@@ -17,8 +19,20 @@ export function serializeGitHubRequestErrorDetails(err) {
17
19
  ...(err.authSource !== undefined && { credential: err.authSource }),
18
20
  };
19
21
  }
22
+ /** One-line hint when `err` is a permission failure on a path inside the state directory. */
23
+ function stateDirHint(err) {
24
+ const { code, path } = (err ?? {});
25
+ if ((code !== "EPERM" && code !== "EACCES") || typeof path !== "string")
26
+ return null;
27
+ const base = resolveStateBase();
28
+ const rel = relative(base, path);
29
+ if (rel.startsWith("..") || isAbsolute(rel))
30
+ return null;
31
+ return `state dir ${base} not writable; set PR_SHEPHERD_STATE_DIR to a writable directory or run outside the sandbox`;
32
+ }
20
33
  export function formatCliError(err) {
21
- const message = err instanceof Error ? err.message : String(err);
34
+ const hint = stateDirHint(err);
35
+ const message = (err instanceof Error ? err.message : String(err)) + (hint === null ? "" : `\n${hint}`);
22
36
  const githubDetails = serializeGitHubRequestErrorDetails(err);
23
37
  if (githubDetails === undefined)
24
38
  return message;
@@ -59,6 +59,9 @@ export function buildSimpleIterateInstructions(result) {
59
59
  else if (result.merge.fallbackCommand) {
60
60
  instructions.push(`Only if GitHub reports that auto-merge is unavailable, run the plain merge fallback: ${inlineCode(renderShellCommand(result.merge.fallbackCommand.argv))}.`);
61
61
  }
62
+ if (result.merge.restFallbackCommand) {
63
+ instructions.push(`If GraphQL is rate limited, use REST: ${inlineCode(renderShellCommand(result.merge.restFallbackCommand.argv))}.`);
64
+ }
62
65
  instructions.push(result.quotaWarning
63
66
  ? buildQuotaAwareContinuation(result.quotaWarning, "After running the merge command.")
64
67
  : "Then iterate immediately with the same options until the PR merges or needs work.");
@@ -49,10 +49,11 @@ export declare function renderCommentBullet(c: {
49
49
  }, opts?: {
50
50
  statusTag?: string;
51
51
  }): string;
52
- /** ` [submitted on <sha>, head is <sha>]` when the review was submitted on a commit other than the PR head. */
52
+ /** ` [reviewed <sha>, head <sha>, N commits since]` when the review is on a commit other than the PR head. */
53
53
  export declare function renderReviewCommitTag(r: {
54
54
  commitOid?: string;
55
55
  headOid?: string;
56
+ commitsSince?: number;
56
57
  }): string;
57
58
  export declare function renderReviewBullet(r: {
58
59
  id: string;
@@ -64,6 +65,7 @@ export declare function renderReviewBullet(r: {
64
65
  staleReview?: boolean;
65
66
  commitOid?: string;
66
67
  headOid?: string;
68
+ commitsSince?: number;
67
69
  }, opts?: {
68
70
  includeBody?: boolean;
69
71
  }): string;
@@ -103,11 +103,14 @@ export function renderCommentBullet(c, opts = {}) {
103
103
  const statusSuffix = opts.statusTag ? ` ${opts.statusTag}` : "";
104
104
  return `- \`commentId=${c.id}\`${link} (${renderAuthor(c.author, c.authorType, c.authorAssociation)})${statusSuffix}: ${renderBodyPreview(c.body)}`;
105
105
  }
106
- /** ` [submitted on <sha>, head is <sha>]` when the review was submitted on a commit other than the PR head. */
106
+ /** ` [reviewed <sha>, head <sha>, N commits since]` when the review is on a commit other than the PR head. */
107
107
  export function renderReviewCommitTag(r) {
108
- return r.commitOid && r.headOid
109
- ? ` [submitted on \`${r.commitOid}\`, head is \`${r.headOid}\`]`
110
- : "";
108
+ if (!r.commitOid || !r.headOid)
109
+ return "";
110
+ const since = r.commitsSince === undefined
111
+ ? ""
112
+ : `, ${r.commitsSince} commit${r.commitsSince === 1 ? "" : "s"} since`;
113
+ return ` [reviewed \`${r.commitOid}\`, head \`${r.headOid}\`${since}]`;
111
114
  }
112
115
  export function renderReviewBullet(r, opts = {}) {
113
116
  const base = `- \`reviewId=${r.id}\` (${renderAuthor(r.author, r.authorType, r.authorAssociation)})${renderReviewCommitTag(r)}`;
@@ -36,7 +36,11 @@ export function formatMutateResult(result) {
36
36
  const rateLimit = formatRateLimit(result);
37
37
  if (rateLimit)
38
38
  lines.push(rateLimit);
39
- const pendingReason = result.sessionRefusal ? "session access" : "rate limit";
39
+ const pendingReason = result.sessionRefusal
40
+ ? "session access"
41
+ : result.rateLimit
42
+ ? "rate limit"
43
+ : "an earlier error";
40
44
  pushIds(lines, `Not replied due to ${pendingReason}`, result.unrepliedThreads);
41
45
  pushIds(lines, `Not resolved due to ${pendingReason}`, result.unresolvedThreads);
42
46
  pushIds(lines, `Not minimized due to ${pendingReason}`, result.unminimizedComments);
@@ -27,8 +27,13 @@ export interface StackLayerView {
27
27
  checksIncomplete?: true;
28
28
  reviewIncomplete?: true;
29
29
  ruleAutoResolve?: PollSummaryRuleAutoResolve;
30
+ trunkBehindBy?: number;
31
+ trunkBehindUnknown?: true;
30
32
  queueRemoval?: {
31
33
  reason: string | null;
32
34
  actor?: string;
33
35
  };
34
36
  }
37
+ /** The `trunk behind` detail of a merge-top row, or undefined when trunk is not ahead. */
38
+ export declare function trunkDetail(layer: StackLayerView): string | undefined;
39
+ export declare function removalDetail(removal: StackLayerView["queueRemoval"]): string | undefined;
@@ -1 +1,11 @@
1
- export {};
1
+ /** The `trunk behind` detail of a merge-top row, or undefined when trunk is not ahead. */
2
+ export function trunkDetail(layer) {
3
+ if (layer.trunkBehindBy)
4
+ return `trunk behind ${layer.trunkBehindBy}`;
5
+ return layer.trunkBehindUnknown ? "trunk behind unknown" : undefined;
6
+ }
7
+ export function removalDetail(removal) {
8
+ if (!removal)
9
+ return undefined;
10
+ return `removed from merge queue (${removal.reason ?? "unknown reason"}${removal.actor ? ` by @${removal.actor}` : ""})`;
11
+ }
@@ -1,6 +1,6 @@
1
1
  import type { PollSummaryResult, PollSummaryStackAncestry, StackNextAction } from "../types.mts";
2
2
  import type { ApiUsage, GraphqlQuotaWarning } from "../types/api-usage.mts";
3
- import type { StackLayerView } from "./stack-layer-view.mts";
3
+ import { type StackLayerView } from "./stack-layer-view.mts";
4
4
  import type { NextCheck } from "../types/next-check.mts";
5
5
  export interface StackOverview {
6
6
  transport?: "rest";
@@ -1,6 +1,7 @@
1
1
  import { stackLayerBlockReason } from "../commands/stack-layer-readiness.mjs";
2
2
  import { formatApiUsage, formatQuotaWarning } from "./api-usage-formatter.mjs";
3
3
  import { formatTransportEvidence } from "./transport-formatter.mjs";
4
+ import { removalDetail, trunkDetail } from "./stack-layer-view.mjs";
4
5
  import { formatNextCheckLines } from "./next-check-format.mjs";
5
6
  import { formatPrUrl } from "../pr-reference.mjs";
6
7
  import { formatRuleAutoResolveLines } from "./rule-auto-resolve-lines.mjs";
@@ -62,6 +63,8 @@ function projectLayer(item, stale) {
62
63
  ...(item.checks?.incomplete && { checksIncomplete: true }),
63
64
  ...(item.review?.incomplete && { reviewIncomplete: true }),
64
65
  ...(item.ruleAutoResolve && { ruleAutoResolve: item.ruleAutoResolve }),
66
+ ...(item.trunkBehindBy && { trunkBehindBy: item.trunkBehindBy }),
67
+ ...(item.trunkBehindUnknown && { trunkBehindUnknown: true }),
65
68
  ...(removal && {
66
69
  queueRemoval: {
67
70
  reason: removal.reason,
@@ -155,9 +158,8 @@ function formatLayerLines(layer, index, overview) {
155
158
  layer.actionable ? `${layer.actionable} actionable` : undefined,
156
159
  layer.checksIncomplete ? "checks incomplete" : undefined,
157
160
  layer.reviewIncomplete ? "review incomplete" : undefined,
158
- layer.queueRemoval
159
- ? `removed from merge queue (${layer.queueRemoval.reason ?? "unknown reason"}${layer.queueRemoval.actor ? ` by @${layer.queueRemoval.actor}` : ""})`
160
- : undefined,
161
+ trunkDetail(layer),
162
+ removalDetail(layer.queueRemoval),
161
163
  ].filter((detail) => detail !== undefined);
162
164
  return [
163
165
  `- ${layer.url === formatPrUrl(overview.repo, layer.pr) ? `PR #${layer.pr}: ${layer.title}` : `[PR #${layer.pr}: ${layer.title}](${layer.url})`}${facts.length > 0 ? ` — ${facts.join(" · ")}` : ""}`,
@@ -0,0 +1,22 @@
1
+ import type { RepoInfo } from "../github/client.mts";
2
+ import { type RestMergeOptions } from "../github/rest-merge.mts";
3
+ import { type MergeRequestRecord } from "../state/merge-request.mts";
4
+ import type { mergeResultFactory } from "./apply-merge-output.mts";
5
+ import type { ApplyMergeResult } from "./apply-merge.mts";
6
+ interface ResumeContext {
7
+ repo: RepoInfo;
8
+ pr: number;
9
+ key: {
10
+ owner: string;
11
+ repo: string;
12
+ pr: number;
13
+ };
14
+ existing: MergeRequestRecord & {
15
+ uuid: string;
16
+ };
17
+ options: RestMergeOptions;
18
+ factory: ReturnType<typeof mergeResultFactory>;
19
+ }
20
+ /** Resume a recorded asynchronous request, falling back to the synchronous merge when unreadable. */
21
+ export declare function resumeMergeRequest(ctx: ResumeContext): Promise<ApplyMergeResult>;
22
+ export {};
@@ -0,0 +1,56 @@
1
+ import { GitHubRequestError } from "../github/errors.mjs";
2
+ import { getRestMerge, matchesRestMergeRequest, requestRestSyncMerge, } from "../github/rest-merge.mjs";
3
+ import { clearMergeRequest, writeMergeRequestStatus, } from "../state/merge-request.mjs";
4
+ import { mergedResponse, readPull } from "./apply-merge-pull.mjs";
5
+ /** Resume a recorded asynchronous request, falling back to the synchronous merge when unreadable. */
6
+ export async function resumeMergeRequest(ctx) {
7
+ const { repo, pr, key, existing, options, factory } = ctx;
8
+ const { failed, project } = factory;
9
+ try {
10
+ const response = await getRestMerge(repo, pr, existing.uuid);
11
+ if (response.status === "pending" &&
12
+ (!matchesRestMergeRequest(response, options) || response.details.uuid !== existing.uuid))
13
+ return failed("Asynchronous merge status does not match the persisted guarded request.", true);
14
+ await writeMergeRequestStatus(key, { ...existing, response });
15
+ return project(response);
16
+ }
17
+ catch (error) {
18
+ // 404: the UUID expired. 403: the token cannot read merge-async status at all (for example a
19
+ // GitHub App installation without that permission). Either way the status is unknown, so the
20
+ // pull itself decides, and an unmerged direct merge converges through the synchronous route.
21
+ if (!(error instanceof GitHubRequestError) || (error.status !== 404 && error.status !== 403))
22
+ throw error;
23
+ const latest = await readPull(repo, pr);
24
+ if (latest.merged === true)
25
+ return project(mergedResponse(latest, "Pull request is merged; its asynchronous status was unreadable."));
26
+ // The synchronous route guards the head SHA itself; queue, default, method-less, and native
27
+ // stack requests have no synchronous equivalent, so their unknown outcome stays blocked.
28
+ if (options.mergeAction !== "direct_merge" || !options.mergeMethod || options.expectedStack)
29
+ return failed(`The asynchronous merge status is unavailable (${error.status}). The PR is not merged; its request outcome is unknown and no duplicate was submitted.`, true);
30
+ return syncFallback(ctx, options.mergeMethod);
31
+ }
32
+ }
33
+ async function syncFallback(ctx, mergeMethod) {
34
+ const { repo, pr, key, options, factory } = ctx;
35
+ try {
36
+ const response = await requestRestSyncMerge(repo, pr, {
37
+ requireSha: options.requireSha,
38
+ mergeMethod,
39
+ });
40
+ await clearMergeRequest(key);
41
+ return factory.project({
42
+ ...response,
43
+ details: {
44
+ ...response.details,
45
+ message: `${response.details.message ?? ""} (merged synchronously: the asynchronous status was unreadable)`.trim(),
46
+ },
47
+ });
48
+ }
49
+ catch (error) {
50
+ // A definite refusal (not mergeable, head changed) retires the stale request so the next
51
+ // command starts a fresh guarded attempt; an unknown outcome keeps the record and retries.
52
+ if (error instanceof GitHubRequestError && error.status >= 400 && error.status < 500)
53
+ await clearMergeRequest(key);
54
+ throw error;
55
+ }
56
+ }
@@ -6,10 +6,11 @@ import { EXIT, ShepherdError } from "../exit-codes.mjs";
6
6
  import { getCurrentPrNumber, getRepoInfo } from "../github/client.mjs";
7
7
  import { GitHubRequestError } from "../github/errors.mjs";
8
8
  import { mergedResponse, readPull } from "./apply-merge-pull.mjs";
9
+ import { resumeMergeRequest } from "./apply-merge-resume.mjs";
9
10
  import { withRestConditionalScope } from "../github/rest-conditional-scope.mjs";
10
11
  import { getGithubTransport } from "../github/transport.mjs";
11
- import { getRestMerge, matchesRestMergeRequest, requestRestMerge, } from "../github/rest-merge.mjs";
12
- import { claimMergeRequest, replaceFailedMergeRequest, readMergeRequest, writeMergeRequest, writeMergeRequestStatus, } from "../state/merge-request.mjs";
12
+ import { matchesRestMergeRequest, requestRestMerge, } from "../github/rest-merge.mjs";
13
+ import { claimMergeRequest, replaceFailedMergeRequest, readMergeRequest, writeMergeRequest, } from "../state/merge-request.mjs";
13
14
  /** Submit one guarded asynchronous request, or resume its existing UUID without resubmitting. */
14
15
  export async function runApplyMerge(input) {
15
16
  validateApplyMergeOptions(input);
@@ -61,23 +62,14 @@ async function submitApplyMerge(input, repo, pr, key) {
61
62
  };
62
63
  if (!existing.uuid)
63
64
  return failed("The previous merge submission has an unknown outcome and no UUID. The PR is not merged; no duplicate request was submitted.", true);
64
- try {
65
- const response = await getRestMerge(repo, pr, existing.uuid);
66
- if (response.status === "pending" &&
67
- (!matchesRestMergeRequest(response, options) || response.details.uuid !== existing.uuid))
68
- return failed("Asynchronous merge status does not match the persisted guarded request.", true);
69
- await writeMergeRequestStatus(key, { ...existing, response });
70
- return project(response);
71
- }
72
- catch (error) {
73
- if (error instanceof GitHubRequestError && error.status === 404) {
74
- const latest = await readPull(repo, pr);
75
- if (latest.merged === true)
76
- return project(mergedResponse(latest, "Pull request is merged; its asynchronous request has expired."));
77
- return failed("The asynchronous merge UUID expired or is unavailable. The PR is not merged; its request outcome is unknown and no duplicate was submitted.", true);
78
- }
79
- throw error;
80
- }
65
+ return resumeMergeRequest({
66
+ repo,
67
+ pr,
68
+ key,
69
+ existing: { ...existing, uuid: existing.uuid },
70
+ options,
71
+ factory: { failed, project },
72
+ });
81
73
  }
82
74
  let record = {
83
75
  version: 1,
@@ -25,7 +25,7 @@ import { buildTerminalReport } from "./check-terminal-report.mjs";
25
25
  import { isBlockedByFilteredCheck, refreshReadyMergeability, refreshUnknownMergeability, } from "./ready-mergeability.mjs";
26
26
  import { loadSeenMap, markSeen, classifyItem, mutationWasDenied } from "../state/seen-comments.mjs";
27
27
  import { aliasThreadSeenMarkers } from "../github/rest-identities.mjs";
28
- import { transportReadinessGaps } from "../github/transport-evidence.mjs";
28
+ import { conversationResolutionProven, transportReadinessGaps, } from "../github/transport-evidence.mjs";
29
29
  import { canGenerateGithubMutation } from "../github/mutation-policy.mjs";
30
30
  import { threadTranscriptBody } from "../threads/transcript.mjs";
31
31
  import { classifyThreadVisibility } from "../comments/thread-visibility.mjs";
@@ -43,11 +43,12 @@ import { getEffectiveCwd } from "../execution-context.mjs";
43
43
  function enforceTransportReadiness(status, data) {
44
44
  if (status !== "READY" || data.transport !== "rest")
45
45
  return status;
46
- if (data.reviewThreads.some((thread) => thread.isResolved === undefined ||
47
- thread.isOutdated === undefined ||
46
+ const conversationsGated = data.branchRules?.requiresConversationResolution;
47
+ const statusProven = conversationResolutionProven(data.mergeStateStatus, conversationsGated);
48
+ if (data.reviewThreads.some((thread) => (!statusProven && (thread.isResolved === undefined || thread.isOutdated === undefined)) ||
48
49
  thread.comments === undefined))
49
50
  return "UNKNOWN";
50
- if (transportReadinessGaps(data, data.mergeStateStatus).length > 0)
51
+ if (transportReadinessGaps(data, data.mergeStateStatus, conversationsGated).length > 0)
51
52
  return "UNKNOWN";
52
53
  return status;
53
54
  }
@@ -29,7 +29,7 @@ export function buildCheckFollowUpInstructions(checks, repo, actionsRunIds) {
29
29
  : "";
30
30
  return [
31
31
  `Shepherd has no rerun to offer and no log excerpt to show for the checks under \`## Failing checks\`, so it cannot tell from GitHub's data why they failed or what would fix them. Find out before acting.${start} ${playbookPointer("Check follow-up")}`,
32
- "If the cause is within this PR, fix it and push. Otherwise make no change and keep what you found; do not rerun or retrigger these checks. If these checks are unchanged on the next poll, Shepherd escalates with `check-follow-up-unavailable`; report that diagnosis then.",
32
+ "If the cause is within this PR, fix it and push. Otherwise make no change and keep what you found; do not rerun or retrigger these checks, including with an empty or no-op commit. If these checks are unchanged on the next poll, Shepherd escalates with `check-follow-up-unavailable`; report that diagnosis then.",
33
33
  ];
34
34
  }
35
35
  /**
@@ -30,7 +30,7 @@ import { findStaleNativeStackAncestry } from "./stale-ancestry.mjs";
30
30
  import { annotateBlockedWait, resolveCheckBlockerGate } from "./check-blocker-gate.mjs";
31
31
  import { buildUnreportedFixResult, planUnreportedRequired } from "./unreported-required.mjs";
32
32
  import { createCheckExecutionContext } from "../check-execution-context.mjs";
33
- import { transportReadinessGaps } from "../../github/transport-evidence.mjs";
33
+ import { reportReadinessGaps } from "./report-gaps.mjs";
34
34
  import { buildEscalateHumanMessage } from "./escalate.mjs";
35
35
  import { markEditedCommentsSeen } from "./edited-comment-markers.mjs";
36
36
  export function runIterate(opts) {
@@ -282,7 +282,7 @@ async function runIterateCore(opts, tick) {
282
282
  const canMarkReady = report.status === "READY" &&
283
283
  report.mergeStatus.isDraft &&
284
284
  !report.mergeStatus.blockingBotReviewInProgress;
285
- const gaps = transportReadinessGaps(report, report.mergeStatus.mergeStateStatus);
285
+ const gaps = reportReadinessGaps(report);
286
286
  if (gaps.length > 0 &&
287
287
  report.checks.inProgress.length === 0 &&
288
288
  report.mergeStatus.mergeStateStatus !== "UNKNOWN") {
@@ -384,7 +384,7 @@ async function recordReadyReceipt(key, report, context) {
384
384
  report.mergeStatus.isDraft ||
385
385
  !report.headSha ||
386
386
  !report.baseRefOid ||
387
- transportReadinessGaps(report, report.mergeStatus.mergeStateStatus).length > 0)
387
+ reportReadinessGaps(report).length > 0)
388
388
  return "failed";
389
389
  try {
390
390
  const raw = await receiptSummaryForReport(key, report, context);
@@ -457,7 +457,7 @@ async function revalidateReadyReceipt(key, report, hasReadinessWork, context) {
457
457
  report.mergeStatus.isDraft ||
458
458
  !report.headSha ||
459
459
  !report.baseRefOid ||
460
- transportReadinessGaps(report, report.mergeStatus.mergeStateStatus).length > 0 ||
460
+ reportReadinessGaps(report).length > 0 ||
461
461
  (!retainQueuedReceipt && (report.status !== "READY" || hasReadinessWork))) {
462
462
  await clearReadyReceipt(key);
463
463
  return false;
@@ -13,6 +13,10 @@ export interface MergePlanInput {
13
13
  queueKnown?: boolean;
14
14
  /** Omitted when the batch did not select repository merge settings. */
15
15
  allowedMergeMethods?: readonly MergeMethod[];
16
+ /** Branch policy requires linear history, so merge commits are excluded. */
17
+ linearHistory?: boolean;
18
+ /** Attach a REST equivalent of the GraphQL merge commands, for when GraphQL quota runs out. */
19
+ restFallback?: boolean;
16
20
  expectedStack?: RestMergeStackGuard;
17
21
  }
18
22
  export interface MergeMethodUnavailable {
@@ -24,6 +24,7 @@ export function buildMergeCommandPlan(input) {
24
24
  allowed: input.allowedMergeMethods,
25
25
  configured,
26
26
  fallback: "merge",
27
+ linearHistory: input.linearHistory,
27
28
  });
28
29
  if ("unavailable" in decision)
29
30
  return decision;
@@ -81,6 +82,7 @@ export function buildMergeCommandPlan(input) {
81
82
  allowed: input.allowedMergeMethods,
82
83
  configured: configuredMergeMethod(mergeConfig),
83
84
  fallback: "merge",
85
+ linearHistory: input.linearHistory,
84
86
  });
85
87
  if ("unavailable" in decision)
86
88
  return decision;
@@ -90,5 +92,21 @@ export function buildMergeCommandPlan(input) {
90
92
  mode: "auto",
91
93
  command: { argv: [...base, "--auto", ...commandArgs] },
92
94
  fallbackCommand: { argv: [...base, ...commandArgs] },
95
+ // `gh pr merge` is GraphQL; this REST call has its own quota and merges immediately.
96
+ ...(input.restFallback && {
97
+ restFallbackCommand: {
98
+ argv: [
99
+ "gh",
100
+ "api",
101
+ "-X",
102
+ "PUT",
103
+ `repos/${input.repo}/pulls/${input.pr}/merge`,
104
+ "-f",
105
+ `sha=${input.headSha}`,
106
+ "-f",
107
+ `merge_method=${decision.method}`,
108
+ ],
109
+ },
110
+ }),
93
111
  };
94
112
  }
@@ -56,6 +56,8 @@ export function buildReadyMergeOutcome(enabled, readyElapsed, base, report) {
56
56
  queueKnown: (report.transport !== "rest" || report.branchProtection === null) &&
57
57
  !(report.transportUnavailable ?? []).some(({ field }) => ["branchProtection", "branchRules"].includes(field)),
58
58
  ...(report.allowedMergeMethods && { allowedMergeMethods: report.allowedMergeMethods }),
59
+ restFallback: true,
60
+ linearHistory: report.mergeStatus.mergeRequirements?.linearHistory?.required === true,
59
61
  });
60
62
  if ("unavailable" in plan) {
61
63
  // A REST policy read that may succeed on a later poll waits under the stall timer.
@@ -0,0 +1,6 @@
1
+ import type { ShepherdReport } from "../../types.mts";
2
+ /** Transport readiness gaps for a report, using its branch policy to clear provable gaps. */
3
+ export declare function reportReadinessGaps(report: ShepherdReport): {
4
+ field: string;
5
+ reason: string;
6
+ }[];
@@ -0,0 +1,5 @@
1
+ import { transportReadinessGaps } from "../../github/transport-evidence.mjs";
2
+ /** Transport readiness gaps for a report, using its branch policy to clear provable gaps. */
3
+ export function reportReadinessGaps(report) {
4
+ return transportReadinessGaps(report, report.mergeStatus.mergeStateStatus, report.mergeStatus.mergeRequirements?.conversationsResolved.required);
5
+ }
@@ -15,6 +15,7 @@ import { summaryStatusSignature } from "./poll-summary-signature.mjs";
15
15
  import { applyStackStallGuard, isStackRepairTick } from "./stack-stall.mjs";
16
16
  import { applyStackOwnership, listedLayerLeftStack, missingListedLayers, } from "./stack-ownership.mjs";
17
17
  import { stackRerunTarget } from "./stack-work.mjs";
18
+ import { withTrunkBehind } from "./stack-trunk-behind.mjs";
18
19
  import { requestedMergeScope, stackAddedLayers } from "./stack-merge-scope.mjs";
19
20
  import { aggregateDeadline } from "./stall-deadline.mjs";
20
21
  import { aggregateTargets, pauseBeforeNextTick, withPollEvents, } from "./poll-events.mjs";
@@ -80,7 +81,8 @@ async function readPollSummaryTick(opts) {
80
81
  return { result: escalated, repo };
81
82
  }
82
83
  const addedLayers = await stackAddedLayers(summary, scope, rerunCommand);
83
- const planned = planPollSummary({ ...summary, ...(addedLayers.length > 0 && { addedLayers }) }, scope !== undefined, rerunCommand, scope, (extra) => stackApprovalCommands(`${repo.owner}/${repo.name}`, fetched.selection, opts, extra));
84
+ const withBehind = await withTrunkBehind(summary, scope);
85
+ const planned = planPollSummary({ ...withBehind, ...(addedLayers.length > 0 && { addedLayers }) }, scope !== undefined, rerunCommand, scope, (extra) => stackApprovalCommands(`${repo.owner}/${repo.name}`, fetched.selection, opts, extra));
84
86
  const result = await applyStackStallGuard(planned, repo, opts.stallTimeoutSeconds ?? loadConfig().iterate["stall-timeout-minutes"] * 60);
85
87
  return { result, repo, ...(fetched.handoffSource && { handoffSource: fetched.handoffSource }) };
86
88
  }
@@ -1,7 +1,7 @@
1
1
  import type { Review } from "../types/github.mts";
2
2
  /**
3
3
  * Surface where each changes-requested review was submitted relative to the PR head.
4
- * `commitOid` stays only when it differs from the head, and then `headOid` carries the head;
5
- * a review on the head carries neither (lean output). Raw data only — no staleness verdict.
4
+ * `commitOid` stays only when it differs from the head, and then `headOid` carries the head and `commitsSince` the commit count between them when known;
5
+ * a review on the head carries neither. Both OIDs are shortened to 7 characters; (lean output). Raw data only — no staleness verdict.
6
6
  */
7
7
  export declare function withHeadOid(reviews: Review[], headOid: string): Review[];