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,11 +1,18 @@
1
1
  /**
2
2
  * Surface where each changes-requested review was submitted relative to the PR head.
3
- * `commitOid` stays only when it differs from the head, and then `headOid` carries the head;
4
- * a review on the head carries neither (lean output). Raw data only — no staleness verdict.
3
+ * `commitOid` stays only when it differs from the head, and then `headOid` carries the head and `commitsSince` the commit count between them when known;
4
+ * a review on the head carries neither. Both OIDs are shortened to 7 characters; (lean output). Raw data only — no staleness verdict.
5
5
  */
6
6
  export function withHeadOid(reviews, headOid) {
7
7
  return reviews.map((review) => {
8
- const { commitOid, ...rest } = review;
9
- return commitOid && commitOid !== headOid ? { ...rest, commitOid, headOid } : rest;
8
+ const { commitOid, commitsSince, ...rest } = review;
9
+ return commitOid && commitOid !== headOid
10
+ ? {
11
+ ...rest,
12
+ commitOid: commitOid.slice(0, 7),
13
+ headOid: headOid.slice(0, 7),
14
+ ...(commitsSince !== undefined && { commitsSince }),
15
+ }
16
+ : rest;
10
17
  });
11
18
  }
@@ -3,6 +3,7 @@ import { buildMergeCommandPlan, renderMergeCommand } from "./iterate/merge.mjs";
3
3
  import { appendAutonomousInstructions, idleWaitPlan, appendHumanHandoffInstructions, findHumanHandoffs, hasListedOwnership, } from "./stack-drain.mjs";
4
4
  import { isStackLayerReady, aboveThroughTarget, closedInScope, mergeScopeLayers, openLayers, readyPrefix, stackPosition, } from "./stack-merge-scope.mjs";
5
5
  import { stackMergeFlag } from "./stack-merge-flag.mjs";
6
+ import { MERGE_CONFLICT_NOTE, trunkPreCheck } from "./stack-merge-trunk-check.mjs";
6
7
  import { addedLayersEscalation, escalation, list, scopeDone, unlistedEscalation, } from "./stack-merge-escalations.mjs";
7
8
  import { splitStackWork, stackRerunTarget } from "./stack-work.mjs";
8
9
  const NO_PER_LAYER = "One command lands every listed layer. Do not merge the layers one at a time with `gh pr merge`, and do not rebase or push between layers; GitHub retargets the remaining layers itself.";
@@ -77,7 +78,8 @@ function mergePlan(result, top, scope, rerunCommand) {
77
78
  const waiting = idleWaitPlan(lands);
78
79
  return { ...waiting, instructions: [`1. ${first.unavailable}`] };
79
80
  }
80
- const instructions = [first.text];
81
+ const check = trunkPreCheck(result, top);
82
+ const instructions = check ? [`1. ${check}`, `2. ${first.text}`] : [`1. ${first.text}`];
81
83
  appendAutonomousInstructions(instructions, work.sessions, hasListedOwnership(result));
82
84
  const handoffs = findHumanHandoffs(result);
83
85
  if (handoffs)
@@ -120,13 +122,13 @@ function mergeStep(result, top, landing, left) {
120
122
  if ("unavailable" in plan)
121
123
  return { unavailable: plan.unavailable, ...(plan.refresh && { refresh: true }) };
122
124
  return {
123
- text: `1. Run \`${renderMergeCommand(plan.command)}\` to request merging ${landing} of native stack #${stack.number}.${left} ${NO_PER_LAYER} If status is \`pending\`, rerun that command at the configured cadence to resume its UUID. \`enqueued\` is not merged. Shepherd revalidates every open lower layer's READY receipt before submission.`,
125
+ text: `Run \`${renderMergeCommand(plan.command)}\` to request merging ${landing} of native stack #${stack.number}.${left} ${NO_PER_LAYER} If status is \`pending\`, rerun that command at the configured cadence to resume its UUID. \`enqueued\` is not merged. Shepherd revalidates every open lower layer's READY receipt before submission.`,
124
126
  };
125
127
  }
126
128
  const method = stackMergeFlag(result.allowedMergeMethods);
127
129
  if ("unavailable" in method)
128
130
  return { unavailable: method.unavailable };
129
131
  return {
130
- text: `1. Run \`GH_REPO=${result.repo} gh stack merge ${top.pr} --yes ${method.flag}\` in \`${result.repo}\` to merge ${landing} of stack #${stack.number}.${left} ${NO_PER_LAYER} If \`gh stack\` is an unknown command, run \`gh extension install github/gh-stack\`, then rerun that merge command.`,
132
+ text: `Run \`GH_REPO=${result.repo} gh stack merge ${top.pr} --yes ${method.flag}\` in \`${result.repo}\` to merge ${landing} of stack #${stack.number}.${left} ${NO_PER_LAYER} If \`gh stack\` is an unknown command, run \`gh extension install github/gh-stack\`, then rerun that merge command. ${MERGE_CONFLICT_NOTE}`,
131
133
  };
132
134
  }
@@ -0,0 +1,12 @@
1
+ import type { PollSummaryItem, PollSummaryResult } from "../types.mts";
2
+ /**
3
+ * The read-only trunk check printed before a stack merge whose top layer is not the bottom one.
4
+ * GitHub's per-layer `mergeable` compares an upper layer only with its parent, so trunk commits
5
+ * that conflict with the top head are invisible until the atomic merge fails. The CLI cannot
6
+ * fetch, so the caller runs `git merge-tree`, which writes nothing to the work tree or refs.
7
+ * Present only when Shepherd saw trunk ahead of the head (`trunkBehindBy`) or could not compare
8
+ * (`trunkBehindUnknown`); otherwise the merge step stays as it was.
9
+ */
10
+ export declare function trunkPreCheck(result: PollSummaryResult, top: PollSummaryItem): string | undefined;
11
+ /** Appended to the `gh stack merge` step: that merge is atomic, so a conflict merges nothing. */
12
+ export declare const MERGE_CONFLICT_NOTE = "If `gh stack merge` reports `Merge conflict detected`, nothing was merged. Do not rerun the merge; update the stack from its bottom layer onto trunk with `gh stack rebase`, then `gh stack push`, following the Branch update playbook, and rerun the stack command.";
@@ -0,0 +1,26 @@
1
+ import { buildNativeStackRebaseInstruction } from "./iterate/native-stack-rebase.mjs";
2
+ import { openLayers } from "./stack-merge-scope.mjs";
3
+ /**
4
+ * The read-only trunk check printed before a stack merge whose top layer is not the bottom one.
5
+ * GitHub's per-layer `mergeable` compares an upper layer only with its parent, so trunk commits
6
+ * that conflict with the top head are invisible until the atomic merge fails. The CLI cannot
7
+ * fetch, so the caller runs `git merge-tree`, which writes nothing to the work tree or refs.
8
+ * Present only when Shepherd saw trunk ahead of the head (`trunkBehindBy`) or could not compare
9
+ * (`trunkBehindUnknown`); otherwise the merge step stays as it was.
10
+ */
11
+ export function trunkPreCheck(result, top) {
12
+ if (!top.trunkBehindBy && !top.trunkBehindUnknown)
13
+ return undefined;
14
+ const stack = top.stack;
15
+ const trunk = stack.baseRefName;
16
+ const bottom = openLayers(result)[0] ?? top;
17
+ const why = top.trunkBehindBy
18
+ ? `Trunk \`${trunk}\` has ${top.trunkBehindBy} commit${top.trunkBehindBy === 1 ? "" : "s"} that PR #${top.pr} lacks`
19
+ : `Shepherd could not compare trunk \`${trunk}\` with PR #${top.pr}`;
20
+ const rebase = buildNativeStackRebaseInstruction(result.repo, stack.number, {
21
+ bottomPr: bottom.pr,
22
+ });
23
+ return `Before merging, check the top layer against trunk, because GitHub's \`mergeable\` compares an upper layer only with its parent layer. ${why}. From a checkout of \`${result.repo}\`, run \`git fetch <remote> ${trunk}\` (\`<remote>\` is the remote that points at \`${result.repo}\`), then \`git merge-tree --write-tree FETCH_HEAD ${top.headRefOid}\`. This writes no files and no refs. If it exits 0, continue with the next step. If it exits 1, it lists the conflicts: do not merge, and do not merge layer by layer. Update the whole stack from its bottom layer onto \`${trunk}\`, then push it. ${rebase} Then rerun the stack command.`;
24
+ }
25
+ /** Appended to the `gh stack merge` step: that merge is atomic, so a conflict merges nothing. */
26
+ export const MERGE_CONFLICT_NOTE = "If `gh stack merge` reports `Merge conflict detected`, nothing was merged. Do not rerun the merge; update the stack from its bottom layer onto trunk with `gh stack rebase`, then `gh stack push`, following the Branch update playbook, and rerun the stack command.";
@@ -0,0 +1,9 @@
1
+ import type { PollSummaryResult, StackMergeScope } from "../types.mts";
2
+ /**
3
+ * GitHub compares an upper layer's `mergeable` only with its parent layer, so a conflict with
4
+ * trunk stays invisible until `gh stack merge` fails. Compare trunk with the top landing layer's
5
+ * head once and record the result on that row: `trunkBehindBy` when trunk has commits the head
6
+ * lacks, `trunkBehindUnknown` when the compare failed. A failure never blocks the merge; the
7
+ * printed pre-check still runs, because a missed conflict costs a failed atomic merge.
8
+ */
9
+ export declare function withTrunkBehind(result: PollSummaryResult, scope: StackMergeScope | undefined): Promise<PollSummaryResult>;
@@ -0,0 +1,51 @@
1
+ import { loadBaseBehindBy } from "../github/merge-target-rules.mjs";
2
+ import { pollRateLimitRetryAfterMs } from "./poll-quota.mjs";
3
+ import { mergeScopeLayers, openLayers, readyPrefix } from "./stack-merge-scope.mjs";
4
+ /**
5
+ * The layer a stack merge would target, or undefined when none is ready to land. Mirrors the
6
+ * choice `planStackMerge` makes: the highest ready owned layer for `ready`, otherwise the scope
7
+ * target once it sits inside the ready prefix.
8
+ */
9
+ function stackMergeTop(result, scope) {
10
+ if (openLayers(result).length === 0)
11
+ return undefined;
12
+ if (scope.kind === "ready")
13
+ return readyPrefix(result, true).at(-1);
14
+ const { target } = mergeScopeLayers(result, scope);
15
+ return target && readyPrefix(result, false).some((item) => item.pr === target.pr)
16
+ ? target
17
+ : undefined;
18
+ }
19
+ /**
20
+ * GitHub compares an upper layer's `mergeable` only with its parent layer, so a conflict with
21
+ * trunk stays invisible until `gh stack merge` fails. Compare trunk with the top landing layer's
22
+ * head once and record the result on that row: `trunkBehindBy` when trunk has commits the head
23
+ * lacks, `trunkBehindUnknown` when the compare failed. A failure never blocks the merge; the
24
+ * printed pre-check still runs, because a missed conflict costs a failed atomic merge.
25
+ */
26
+ export async function withTrunkBehind(result, scope) {
27
+ if (!scope || result.selection.kind !== "stack")
28
+ return result;
29
+ const top = stackMergeTop(result, scope);
30
+ const trunk = top?.stack?.baseRefName;
31
+ if (!top || !trunk || top.baseRefName === trunk)
32
+ return result;
33
+ const [owner, name] = result.repo.split("/");
34
+ let mark;
35
+ try {
36
+ const behind = await loadBaseBehindBy(owner, name, trunk, top.headRefOid);
37
+ if (behind <= 0)
38
+ return result;
39
+ mark = { trunkBehindBy: behind };
40
+ }
41
+ catch (err) {
42
+ if (pollRateLimitRetryAfterMs(err) !== null)
43
+ throw err;
44
+ process.stderr.write(`pr-shepherd: trunk compare unavailable for PR #${top.pr} (ignored): ${err instanceof Error ? err.message : String(err)}\n`);
45
+ mark = { trunkBehindUnknown: true };
46
+ }
47
+ return {
48
+ ...result,
49
+ prs: result.prs.map((item) => (item.pr === top.pr ? { ...item, ...mark } : item)),
50
+ };
51
+ }
@@ -21,6 +21,13 @@ async function paths(context, id, message) {
21
21
  catch { }
22
22
  return [...new Set(identities)].map((identity) => resolvePrStatePath({ owner: context.repo.owner, repo: context.repo.name, pr: context.pr }, "uncertain-replies", `${createHash("sha256").update(`${identity}\n${message}`).digest("hex")}.json`));
23
23
  }
24
+ function uncertainMessage(undecided) {
25
+ return (`Previous GraphQL reply outcome is uncertain for ${undecided.length} thread(s): ${undecided.map((item) => item.id).join(", ")}; no duplicate reply was sent.\n` +
26
+ "1. Inspect each complete thread transcript and verify whether the previous reply was delivered. If it was, rerun the same generated command with `--adopt-existing-replies`.\n" +
27
+ "2. For each thread you verified was not delivered, with no request still in flight, clear only that thread's markers:\n" +
28
+ undecided.map((item) => ` ${item.command}`).join("\n") +
29
+ "\n3. Rerun the original reply command; do not clear all PR state or change the disposition to bypass this check.");
30
+ }
24
31
  export async function assertReplyOutcomeKnown(context, ids, message) {
25
32
  await prepareUnmappedIntents(context, ids, message, paths);
26
33
  const pending = new Map();
@@ -56,6 +63,7 @@ export async function assertReplyOutcomeKnown(context, ids, message) {
56
63
  }
57
64
  return true;
58
65
  });
66
+ const undecided = [];
59
67
  for (let offset = 0; offset < pendingIds.length; offset += 10) {
60
68
  let evidence = new Map();
61
69
  try {
@@ -85,11 +93,8 @@ export async function assertReplyOutcomeKnown(context, ids, message) {
85
93
  ...new Set([...item.paths, ...(await paths(context, record.id, message))]),
86
94
  ];
87
95
  const command = `rm -- ${recoveryPaths.map((path) => `'${path.replaceAll("'", "'\\''")}'`).join(" ")}`;
88
- throw new Error(`Previous GraphQL reply outcome is uncertain for ${id}; no duplicate reply was sent.\n` +
89
- "1. Inspect the complete thread transcript and verify whether the previous reply was delivered.\n" +
90
- "2. If you verified non-delivery and no request remains in flight, clear only this reply's markers and run:\n" +
91
- ` ${command}\n` +
92
- "3. Rerun the original reply command; do not clear all PR state or change the disposition to bypass this check.");
96
+ undecided.push({ id, command });
97
+ continue;
93
98
  }
94
99
  // Keep confirmed outcomes durable: another pending ID or a later resolve can still fail.
95
100
  const outcomePaths = new Set([...item.paths, ...(await paths(context, record.id, message))]);
@@ -98,6 +103,8 @@ export async function assertReplyOutcomeKnown(context, ids, message) {
98
103
  adopted.push(id);
99
104
  }
100
105
  }
106
+ if (undecided.length)
107
+ throw new Error(uncertainMessage(undecided));
101
108
  await prepareUnmappedIntents(context, ids, message, paths);
102
109
  return adopted;
103
110
  }
@@ -14,6 +14,8 @@ export declare function chooseMergeMethod(input: {
14
14
  allowed: readonly MergeMethod[] | undefined;
15
15
  configured: MergeMethod | null;
16
16
  fallback: MergeMethod;
17
+ /** Branch policy requires linear history: a merge commit can never satisfy it. */
18
+ linearHistory?: boolean;
17
19
  }): {
18
20
  method: MergeMethod;
19
21
  } | {
@@ -22,6 +22,23 @@ export function configuredMergeMethod(merge) {
22
22
  return merge.method ?? fromArgs ?? null;
23
23
  }
24
24
  export function chooseMergeMethod(input) {
25
+ if (input.linearHistory) {
26
+ const linear = (input.allowed ?? METHOD_ORDER).filter((method) => method !== "merge");
27
+ if (input.allowed !== undefined && linear.length === 0)
28
+ return {
29
+ unavailable: "Required linear history excludes merge commits, and this repository allows no squash or rebase merge.",
30
+ };
31
+ if (input.configured === "merge")
32
+ return {
33
+ unavailable: "Configured merge method `merge` conflicts with the required linear history; use `squash` or `rebase`.",
34
+ };
35
+ if (input.allowed === undefined) {
36
+ return {
37
+ method: input.configured ?? (input.fallback === "merge" ? "squash" : input.fallback),
38
+ };
39
+ }
40
+ return chooseMergeMethod({ ...input, allowed: linear, linearHistory: false });
41
+ }
25
42
  if (input.allowed === undefined)
26
43
  return { method: input.configured ?? input.fallback };
27
44
  if (input.configured) {
@@ -22,6 +22,12 @@ function parseReviewNode(r) {
22
22
  }
23
23
  return base;
24
24
  }
25
+ function commitsSince(oid, commits) {
26
+ if (!oid || !commits)
27
+ return undefined;
28
+ const index = commits.nodes.findIndex((node) => node.commit.oid === oid);
29
+ return index < 0 ? undefined : commits.nodes.length - 1 - index;
30
+ }
25
31
  export function parseRawPr(raw, rawThreadPages, rawCommentNodes, rawReviewNodes, rawReviewSummaryNodes, rawApprovedReviewNodes, rawCheckNodes, repository) {
26
32
  const reviewRequests = (raw.reviewRequests?.nodes ?? []).flatMap((n) => {
27
33
  const login = n.requestedReviewer?.login ?? n.requestedReviewer?.name;
@@ -82,6 +88,9 @@ export function parseRawPr(raw, rawThreadPages, rawCommentNodes, rawReviewNodes,
82
88
  }));
83
89
  const allChangesRequestedReviews = rawReviewNodes.map((r) => {
84
90
  const review = parseReviewNode(r);
91
+ const since = commitsSince(review.commitOid, raw.prCommitOids);
92
+ if (since !== undefined)
93
+ review.commitsSince = since;
85
94
  if (isReviewStale(review, raw.headRefOid, reviewThreads)) {
86
95
  review.staleReview = true;
87
96
  }
@@ -96,6 +96,14 @@ export interface RawPr extends RawPrMergeFields {
96
96
  };
97
97
  nodes: RawReviewSummary[];
98
98
  };
99
+ /** Last 100 commit OIDs, oldest first. GraphQL only. */
100
+ prCommitOids?: {
101
+ nodes: Array<{
102
+ commit: {
103
+ oid: string;
104
+ };
105
+ }>;
106
+ };
99
107
  commits: {
100
108
  totalCount?: number;
101
109
  nodes: Array<{
@@ -307,6 +307,14 @@ query BatchPr($owner: String!, $repo: String!, $pr: Int!) {
307
307
  url
308
308
  }
309
309
  }
310
+ # Chronological OIDs only: positions a changes-requested review's commit relative to the head.
311
+ prCommitOids: commits(last: 100) {
312
+ nodes {
313
+ commit {
314
+ oid
315
+ }
316
+ }
317
+ }
310
318
  commits(last: 1) {
311
319
  totalCount
312
320
  nodes {
@@ -26,7 +26,8 @@ export function isCurrentSummaryReady(raw, checks, review, options = {}) {
26
26
  // alone is not that proof.
27
27
  const requiresConversationResolution = parseBranchRules(raw.baseRef).requiresConversationResolution;
28
28
  return (isKnownMergeStateStatus(raw.mergeStateStatus) &&
29
- transportReadinessGaps(raw, raw.mergeStateStatus).length === 0 &&
29
+ transportReadinessGaps(raw, raw.mergeStateStatus, requiresConversationResolution).length ===
30
+ 0 &&
30
31
  checks.incomplete !== true &&
31
32
  sourceChecks.incomplete !== true &&
32
33
  (review.incomplete !== true ||
@@ -1,6 +1,7 @@
1
1
  import { loadConfig } from "../config/load.mjs";
2
2
  import { hasNoRelevantChecks } from "./poll-summary-unreported.mjs";
3
3
  import { isKnownMergeStateStatus, transportReadinessGaps } from "./transport-evidence.mjs";
4
+ import { parseBranchRules } from "./batch-parsers-rules.mjs";
4
5
  import { canGenerateGithubMutation } from "./mutation-policy.mjs";
5
6
  import { getGithubTransport, isCcrTransport } from "./transport.mjs";
6
7
  export function routePollSummary(raw, checks, review, opts) {
@@ -31,7 +32,7 @@ export function routePollSummary(raw, checks, review, opts) {
31
32
  raw.mergeable === "UNKNOWN" ||
32
33
  raw.mergeStateStatus === "UNKNOWN")
33
34
  return { action: "wait", reasons: ["pending-or-unknown"] };
34
- if (transportReadinessGaps(raw, raw.mergeStateStatus).length > 0)
35
+ if (transportReadinessGaps(raw, raw.mergeStateStatus, parseBranchRules(raw.baseRef).requiresConversationResolution).length > 0)
35
36
  return { action: "escalate", reasons: ["transport-unsupported"] };
36
37
  if (raw.mergeable === "UNKNOWN" ||
37
38
  raw.mergeStateStatus === "UNKNOWN" ||
@@ -27,3 +27,13 @@ export declare function requestRestMerge(repo: RepoInfo, pr: number, options: Re
27
27
  export declare function getRestMerge(repo: RepoInfo, pr: number, uuid: string): Promise<RestMergeResponse>;
28
28
  /** Conflict requests must match the caller's guarded options before their UUID can be adopted. */
29
29
  export declare function matchesRestMergeRequest(result: RestMergeResponse, options: RestMergeOptions): boolean;
30
+ /**
31
+ * Synchronous `PUT /pulls/{n}/merge`, guarded by the head SHA. It is the fallback when the
32
+ * asynchronous request's status cannot be read (403 for tokens without access, or an expired
33
+ * UUID): GitHub refuses it with 405/409 unless the guarded head is mergeable, so repeating it
34
+ * after an unknown outcome cannot merge anything the caller did not guard.
35
+ */
36
+ export declare function requestRestSyncMerge(repo: RepoInfo, pr: number, options: {
37
+ requireSha: string;
38
+ mergeMethod: MergeMethod;
39
+ }): Promise<RestMergeResponse>;
@@ -54,3 +54,29 @@ export function matchesRestMergeRequest(result, options) {
54
54
  typeof details.uuid === "string" &&
55
55
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(details.uuid));
56
56
  }
57
+ /**
58
+ * Synchronous `PUT /pulls/{n}/merge`, guarded by the head SHA. It is the fallback when the
59
+ * asynchronous request's status cannot be read (403 for tokens without access, or an expired
60
+ * UUID): GitHub refuses it with 405/409 unless the guarded head is mergeable, so repeating it
61
+ * after an unknown outcome cannot merge anything the caller did not guard.
62
+ */
63
+ export async function requestRestSyncMerge(repo, pr, options) {
64
+ const { data } = await restWithRateLimit("PUT", `${restRepoPath(repo)}/pulls/${pr}/merge`, {
65
+ sha: options.requireSha,
66
+ merge_method: options.mergeMethod,
67
+ });
68
+ const body = (data ?? {});
69
+ const message = typeof body.message === "string" ? body.message : undefined;
70
+ if (body.merged !== true)
71
+ return {
72
+ status: "failed",
73
+ details: { message: message ?? "GitHub did not merge the pull request." },
74
+ };
75
+ return {
76
+ status: "merged",
77
+ details: {
78
+ message: message ?? "Pull request merged.",
79
+ ...(typeof body.sha === "string" && { sha: body.sha }),
80
+ },
81
+ };
82
+ }
@@ -7,13 +7,20 @@ interface TransportEvidence {
7
7
  }
8
8
  /** A future GitHub state cannot prove readiness through a negative blocker list. */
9
9
  export declare function isKnownMergeStateStatus(status: string): boolean;
10
+ /**
11
+ * REST has no resolved/outdated thread state. When branch policy requires conversation resolution,
12
+ * GitHub's CLEAN merge state proves no unresolved thread exists, so the unknown status is not a
13
+ * readiness gap. Without that policy, or on any other merge state, the gap stands.
14
+ */
15
+ export declare function conversationResolutionProven(mergeStateStatus: string, requiresConversationResolution: boolean | undefined): boolean;
10
16
  /**
11
17
  * Missing feedback cannot certify readiness, even when GitHub reports CLEAN. Missing branch policy
12
18
  * blocks only a non-CLEAN state, whose unmet requirements Shepherd derives from that policy. The
13
19
  * aggregate `reviewDecision` is never a readiness input on either transport (approvals come from
14
- * branch policy plus latest reviews), so its absence alone is not a gap.
20
+ * branch policy plus latest reviews), so its absence alone is not a gap. Unknown thread status
21
+ * (`reviewThreads.status`) is cleared by `conversationResolutionProven`.
15
22
  */
16
- export declare function transportReadinessGaps(value: TransportEvidence, mergeStateStatus: string): Array<{
23
+ export declare function transportReadinessGaps(value: TransportEvidence, mergeStateStatus: string, requiresConversationResolution?: boolean): Array<{
17
24
  field: string;
18
25
  reason: string;
19
26
  }>;
@@ -11,16 +11,28 @@ export function isKnownMergeStateStatus(status) {
11
11
  "UNSTABLE",
12
12
  ].includes(status);
13
13
  }
14
+ /**
15
+ * REST has no resolved/outdated thread state. When branch policy requires conversation resolution,
16
+ * GitHub's CLEAN merge state proves no unresolved thread exists, so the unknown status is not a
17
+ * readiness gap. Without that policy, or on any other merge state, the gap stands.
18
+ */
19
+ export function conversationResolutionProven(mergeStateStatus, requiresConversationResolution) {
20
+ return mergeStateStatus === "CLEAN" && requiresConversationResolution === true;
21
+ }
14
22
  /**
15
23
  * Missing feedback cannot certify readiness, even when GitHub reports CLEAN. Missing branch policy
16
24
  * blocks only a non-CLEAN state, whose unmet requirements Shepherd derives from that policy. The
17
25
  * aggregate `reviewDecision` is never a readiness input on either transport (approvals come from
18
- * branch policy plus latest reviews), so its absence alone is not a gap.
26
+ * branch policy plus latest reviews), so its absence alone is not a gap. Unknown thread status
27
+ * (`reviewThreads.status`) is cleared by `conversationResolutionProven`.
19
28
  */
20
- export function transportReadinessGaps(value, mergeStateStatus) {
29
+ export function transportReadinessGaps(value, mergeStateStatus, requiresConversationResolution) {
21
30
  if (value.transport !== "rest")
22
31
  return [];
23
- return (value.transportUnavailable ?? []).filter(({ field }) => /^(reviewThreads|reviewTranscripts|changesRequestedReviews|reviewSummaries|checks|checkRuns|checkSuites|checkAnnotations|annotations|nativeStack)(?:\.|$)/.test(field) ||
32
+ const threadStatusProven = conversationResolutionProven(mergeStateStatus, requiresConversationResolution);
33
+ return (value.transportUnavailable ?? []).filter(({ field }) => (field === "reviewThreads.status" && !threadStatusProven) ||
34
+ (field !== "reviewThreads.status" &&
35
+ /^(reviewThreads|reviewTranscripts|changesRequestedReviews|reviewSummaries|checks|checkRuns|checkSuites|checkAnnotations|annotations|nativeStack)(?:\.|$)/.test(field)) ||
24
36
  (mergeStateStatus !== "CLEAN" &&
25
37
  ["branchProtection", "branchRules", "mergeRequirements"].some((policy) => field === policy || field.startsWith(`${policy}.`))));
26
38
  }
@@ -1,30 +1,8 @@
1
- import { execFileSync } from "node:child_process";
2
1
  import { accessSync, constants, lstatSync, mkdirSync } from "node:fs";
3
- import { isAbsolute, join } from "node:path";
2
+ import { join } from "node:path";
4
3
  import { tmpdir } from "node:os";
5
4
  import { SAFE_PR_NUMBER, SAFE_SEGMENT } from "../util/path-segment.mjs";
6
5
  import { resolveDurableStateBase } from "./durable-state.mjs";
7
- /** Read once per process; null when the platform or `getconf` offers no per-user temp dir. */
8
- let darwinUserTempDir;
9
- /**
10
- * macOS's per-user temp dir, read from `confstr(_CS_DARWIN_USER_TEMP_DIR)` rather than
11
- * `TMPDIR`. Sandboxed agent shells point `TMPDIR` at their own directory, so the same user's
12
- * sandboxed CLI, unsandboxed CLI, and MCP server would otherwise keep separate state.
13
- */
14
- function readDarwinUserTempDir() {
15
- if (process.platform !== "darwin")
16
- return null;
17
- try {
18
- const dir = execFileSync("/usr/bin/getconf", ["DARWIN_USER_TEMP_DIR"], {
19
- encoding: "utf8",
20
- stdio: ["ignore", "pipe", "ignore"],
21
- }).trim();
22
- return isAbsolute(dir) ? dir : null;
23
- }
24
- catch {
25
- return null;
26
- }
27
- }
28
6
  /** Read once per process; null when the platform is not Linux or the shared base is unusable. */
29
7
  let linuxUserStateBase;
30
8
  /**
@@ -68,9 +46,7 @@ export function resolveStateBase() {
68
46
  linuxUserStateBase = readLinuxUserStateBase();
69
47
  if (linuxUserStateBase)
70
48
  return linuxUserStateBase;
71
- if (darwinUserTempDir === undefined)
72
- darwinUserTempDir = readDarwinUserTempDir();
73
- return join(darwinUserTempDir ?? tmpdir(), "pr-shepherd-state");
49
+ return join(tmpdir(), "pr-shepherd-state");
74
50
  }
75
51
  /**
76
52
  * `$PR_SHEPHERD_STATE_DIR/<owner>/<repo>/<pr>/...parts`.
@@ -19,6 +19,12 @@ export declare function readMergeRequest(key: Key): Promise<MergeRequestRecord |
19
19
  export declare function claimMergeRequest(key: Key, record: MergeRequestRecord): Promise<boolean>;
20
20
  /** Consume one durable successor of a failed request or an enqueue guarded by an older head. */
21
21
  export declare function replaceFailedMergeRequest(key: Key, previous: MergeRequestRecord, next: MergeRequestRecord): Promise<boolean>;
22
+ /**
23
+ * Retire a request whose asynchronous status can no longer be read, once the synchronous fallback
24
+ * has answered. A merged PR is detected from the pull itself, so no record is needed; a refusal is
25
+ * surfaced to the caller, and a rerun starts a fresh guarded attempt instead of replaying it.
26
+ */
27
+ export declare function clearMergeRequest(key: Key): Promise<void>;
22
28
  export declare function writeMergeRequest(key: Key, record: MergeRequestRecord): Promise<void>;
23
29
  /** A delayed status poll can update only its own intent, never a later main request. */
24
30
  export declare function writeMergeRequestStatus(key: Key, record: MergeRequestRecord): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { link, mkdir, readFile, rename, rm, unlink, writeFile } from "node:fs/promises";
3
3
  import { dirname } from "node:path";
4
4
  import { resolvePrStatePath } from "./base.mjs";
5
5
  import { restMergeStackGuardKey, validateRestMergeStackGuard, } from "../github/rest-merge-stack-guard.mjs";
@@ -126,6 +126,14 @@ export async function replaceFailedMergeRequest(key, previous, next) {
126
126
  await unlink(source).catch(() => { });
127
127
  }
128
128
  }
129
+ /**
130
+ * Retire a request whose asynchronous status can no longer be read, once the synchronous fallback
131
+ * has answered. A merged PR is detected from the pull itself, so no record is needed; a refusal is
132
+ * surfaced to the caller, and a rerun starts a fresh guarded attempt instead of replaying it.
133
+ */
134
+ export async function clearMergeRequest(key) {
135
+ await rm(path(key), { force: true });
136
+ }
129
137
  export async function writeMergeRequest(key, record) {
130
138
  await writeRecord(path(key), record);
131
139
  }
@@ -160,6 +160,8 @@ export interface Review {
160
160
  commitOid?: string;
161
161
  /** PR head OID, set on changes-requested reviews only when `commitOid` differs from it. Raw data, not a staleness verdict. */
162
162
  headOid?: string;
163
+ /** Commits pushed after `commitOid` up to the head. Set with `headOid`, GraphQL only, and only when `commitOid` is among the PR's last 100 commits. */
164
+ commitsSince?: number;
163
165
  /** Review HTML URL, when the batch query selected it. */
164
166
  url?: string;
165
167
  /** True when commitOid !== headRefOid AND all associated threads are resolved/outdated. Distinct from `staleBotCr` (time-based). Reviews with no threads are not marked stale. */
@@ -8,5 +8,11 @@ export interface MergeCommandPlan {
8
8
  fallbackCommand?: ShellCommand;
9
9
  /** Direct enqueuePullRequest fallback for the known gh CLI queue limitation. */
10
10
  queueApiFallbackCommand?: ShellCommand;
11
+ /**
12
+ * GraphQL-mode commands (`gh pr merge`, `gh api graphql`) all spend GraphQL quota. This REST
13
+ * equivalent is for when that quota is exhausted: `gh api` PUT for an ordinary merge, or
14
+ * `apply merge --transport rest` for a queue.
15
+ */
16
+ restFallbackCommand?: ShellCommand;
11
17
  }
12
18
  export {};
@@ -104,6 +104,10 @@ export interface PollSummaryItem {
104
104
  pollProbe?: true;
105
105
  /** A current one-PR READY-after-delay completion was verified. */
106
106
  readyReceipt?: true;
107
+ /** Stack merge top only: commits on the stack trunk that this head lacks (omitted when 0). */
108
+ trunkBehindBy?: number;
109
+ /** Stack merge top only: the trunk compare failed, so the conflict check is unverified. */
110
+ trunkBehindUnknown?: true;
107
111
  }
108
112
  export type PollSummarySelection = {
109
113
  kind: "prs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "2.2.5",
3
+ "version": "2.2.7",
4
4
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
5
5
  "keywords": [
6
6
  "automation",
@@ -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"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
- "version": "2.2.5",
3
+ "version": "2.2.7",
4
4
  "description": "Autonomous PR CI monitor and review-comment resolver for Codex.",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
@@ -13,7 +13,7 @@ allowed-tools: Bash(npx pr-shepherd:*), Bash(pnpm exec pr-shepherd:*), Bash(pnpm
13
13
  - To make, create, or open a PR, read the "Create a PR" playbook, then pass its URL on.
14
14
  - External shepherd: read the "Draft handoff" playbook, not an in-session loop.
15
15
  - `$ARGUMENTS`: PR numbers, PR URLs, or `'owner/repo#N'` (quoted), or `stack PR...` / `stack owner/repo#N` (the number owns all layers), plus one optional merge flag: `--merge`, `--merge-ready`, `--merge-through PR`; reject anything else. Use `stack` only when asked or routed. With no PR, pass none. A qualified PR picks the GitHub target; this checkout supplies git and config.
16
- - Stack merge: "the stack" -> `stack owner/repo#N --merge`; "as they're ready"/"drain" -> `--merge-ready`; "#N" -> one-PR `--merge`, but if they claim other layers or say "up to #N" -> `stack <claimed PRs incl. N> --merge-through N`; "ship it" -> ask.
16
+ - Stack merge: "the stack" -> `stack owner/repo#N --merge` (given only a PR, `stack PR --merge`, then on `unowned-stack-layers` run its printed stack-number command); "as they're ready"/"drain" -> `--merge-ready`; "#N" -> one-PR `--merge`, but if they claim other layers or say "up to #N" -> `stack <claimed PRs incl. N> --merge-through N`; "ship it" -> ask.
17
17
  - Follow printed branch-update steps without asking: rebase or merge the base, resolve conflicts, push your own PR head with `--force-with-lease`.
18
18
  - A merge flag, or a request to merge, land, enqueue, or requeue after an ejection, allows the printed merge/enqueue/dequeue commands. Run Shepherd first: never merge, enqueue or retarget with `gh` or a GitHub MCP tool before Shepherd prints that step. Run them without asking again; escalate only when the host requires it.
19
19
  - Run `pr-shepherd [PR ...]` or `pr-shepherd stack PR...`, plus any merge flag, with `--until-terminal` in the background only if its exit wakes you, else in the foreground ([Waiting](references/waiting.md)). Requeue commands print only under `--merge`. PRs with the same flags share one command; if the set changes, stop and rerun with the new list. Do not run `pr-shepherd iterate`, except once for a one-time status question.
@@ -11,4 +11,4 @@ Then:
11
11
 
12
12
  1. Cause within this PR: fix it and push.
13
13
  2. Transient and the output printed a rerun command for it: run that command. Without one, do not rerun; the allowance is spent or the check is not rerunnable.
14
- 3. Otherwise change nothing and keep your findings. CI configuration, repository settings, and approving a gated run are human decisions. Rerun Shepherd now; if the checks are unchanged, it escalates `check-follow-up-unavailable`. Report your findings then.
14
+ 3. Otherwise investigate first, including the check's details URL. If you are still unsure of the cause, or it is outside this PR (CI configuration, repository settings, approving a gated run), change nothing, rerun Shepherd so it escalates `check-follow-up-unavailable` if the checks are unchanged, and report your findings.
@@ -12,4 +12,4 @@ Then act on what you found:
12
12
 
13
13
  1. If the cause is within this PR (a `runs-on` label that matches no runner, a workflow change that breaks scheduling, a wrong base), fix it and push.
14
14
  2. If a run is only waiting on an approval you can legitimately grant, grant it. An approval that needs a human reviewer is not yours to grant.
15
- 3. Otherwise make no change and keep what you found. Runner capacity, billing, repository settings, and GitHub incidents are human decisions. If the same checks are still not started on the next poll, Shepherd escalates with `stall-timeout`; report your diagnosis then.
15
+ 3. Otherwise investigate first. If you are still unsure of the cause, or it is outside this PR, make no change and keep what you found. Runner capacity, billing, repository settings, and GitHub incidents are human decisions. If the same checks are still not started on the next poll, Shepherd escalates with `stall-timeout`; report your diagnosis then.
@@ -13,4 +13,4 @@ Then act on what you found:
13
13
 
14
14
  1. If the cause is within this PR (wrong base or stack parent, a changed file that breaks the workflow, configuration the PR should carry), fix it and push.
15
15
  2. If the workflows should have run and the PR is fine, run the printed close and reopen commands once for this head. Do not close it again.
16
- 3. Otherwise make no change and keep what you found. Changing CI configuration, repository settings, or branch rules is a human decision. If the checks are still missing on the next poll, Shepherd escalates with `required-checks-unreported`; report your diagnosis then.
16
+ 3. Otherwise investigate first. If you are still unsure of the cause, or it is outside this PR, make no change and keep what you found. Changing CI configuration, repository settings, or branch rules is a human decision. If the checks are still missing on the next poll, Shepherd escalates with `required-checks-unreported`; report your diagnosis then.