pr-shepherd 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/bin/classify/standard/coderabbit-walkthrough.d.mts +10 -0
  3. package/bin/classify/standard/coderabbit-walkthrough.mjs +21 -0
  4. package/bin/classify/standard/devin-no-issues.d.mts +7 -0
  5. package/bin/classify/standard/devin-no-issues.mjs +18 -0
  6. package/bin/classify/standard/index.d.mts +2 -1
  7. package/bin/classify/standard/index.mjs +6 -1
  8. package/bin/cli/apply-merge-handler.mjs +2 -0
  9. package/bin/cli/body-truncate.d.mts +7 -0
  10. package/bin/cli/body-truncate.mjs +8 -4
  11. package/bin/cli/help-command-pages.d.mts +4 -2
  12. package/bin/cli/help-command-pages.mjs +4 -1
  13. package/bin/cli/help-iterate-poll-pages.d.mts +1 -1
  14. package/bin/cli/help-iterate-poll-pages.mjs +1 -1
  15. package/bin/cli/help-top-page.d.mts +1 -1
  16. package/bin/cli/help-top-page.mjs +3 -1
  17. package/bin/cli/help-watch-status-page.d.mts +1 -0
  18. package/bin/cli/help-watch-status-page.mjs +21 -0
  19. package/bin/cli/help.d.mts +5 -3
  20. package/bin/cli/help.mjs +2 -0
  21. package/bin/cli/iterate-lean.d.mts +0 -5
  22. package/bin/cli/iterate-lean.mjs +9 -2
  23. package/bin/cli/poll-summary-formatter.mjs +2 -1
  24. package/bin/cli/review-body-cap.d.mts +10 -0
  25. package/bin/cli/review-body-cap.mjs +84 -0
  26. package/bin/cli/stack-layer-view.d.mts +2 -0
  27. package/bin/cli/stack-layer-view.mjs +8 -0
  28. package/bin/cli/stack-overview.mjs +4 -5
  29. package/bin/cli/triage-formatter.mjs +4 -1
  30. package/bin/cli/watch-status-handler.d.mts +2 -0
  31. package/bin/cli/watch-status-handler.mjs +56 -0
  32. package/bin/cli-parser.mjs +7 -0
  33. package/bin/commands/apply-merge-default-route.d.mts +56 -0
  34. package/bin/commands/apply-merge-default-route.mjs +149 -0
  35. package/bin/commands/apply-merge-output.d.mts +2 -0
  36. package/bin/commands/apply-merge-output.mjs +8 -0
  37. package/bin/commands/apply-merge-pull.d.mts +3 -0
  38. package/bin/commands/apply-merge-resume.d.mts +2 -3
  39. package/bin/commands/apply-merge-resume.mjs +74 -32
  40. package/bin/commands/apply-merge-stack-membership.d.mts +27 -0
  41. package/bin/commands/apply-merge-stack-membership.mjs +85 -0
  42. package/bin/commands/apply-merge-submit.d.mts +20 -0
  43. package/bin/commands/apply-merge-submit.mjs +47 -0
  44. package/bin/commands/apply-merge-supersede.d.mts +17 -0
  45. package/bin/commands/apply-merge-supersede.mjs +30 -0
  46. package/bin/commands/apply-merge-sync-fallback.d.mts +16 -0
  47. package/bin/commands/apply-merge-sync-fallback.mjs +55 -0
  48. package/bin/commands/apply-merge.d.mts +2 -0
  49. package/bin/commands/apply-merge.mjs +65 -41
  50. package/bin/commands/check-review-budget.mjs +12 -1
  51. package/bin/commands/check.d.mts +2 -0
  52. package/bin/commands/check.mjs +9 -1
  53. package/bin/commands/iterate/escalate.mjs +5 -0
  54. package/bin/commands/iterate/index.mjs +34 -4
  55. package/bin/commands/iterate/merge-plan.d.mts +2 -0
  56. package/bin/commands/iterate/merge-plan.mjs +1 -1
  57. package/bin/commands/iterate/merge.mjs +7 -3
  58. package/bin/commands/iterate/stack-boundary.mjs +6 -6
  59. package/bin/commands/iterate/stale-ancestry.mjs +8 -3
  60. package/bin/commands/iterate/triage.mjs +19 -6
  61. package/bin/commands/poll-events.d.mts +1 -1
  62. package/bin/commands/poll-events.mjs +8 -3
  63. package/bin/commands/poll-seen-options.d.mts +7 -0
  64. package/bin/commands/poll-seen-options.mjs +9 -0
  65. package/bin/commands/poll-summary-instructions.d.mts +1 -0
  66. package/bin/commands/poll-summary-instructions.mjs +17 -7
  67. package/bin/commands/poll-summary.mjs +8 -4
  68. package/bin/commands/poll.mjs +2 -2
  69. package/bin/commands/rest-stack-merge-readiness.d.mts +6 -2
  70. package/bin/commands/rest-stack-merge-readiness.mjs +59 -7
  71. package/bin/commands/stack-drain.d.mts +7 -1
  72. package/bin/commands/stack-drain.mjs +30 -6
  73. package/bin/commands/stack-lower-heads.d.mts +32 -0
  74. package/bin/commands/stack-lower-heads.mjs +53 -0
  75. package/bin/commands/stack-merge-escalations.d.mts +2 -1
  76. package/bin/commands/stack-merge-plan.mjs +35 -41
  77. package/bin/commands/stack-merge-trunk-check.d.mts +0 -2
  78. package/bin/commands/stack-merge-trunk-check.mjs +0 -2
  79. package/bin/commands/stack-ownership.mjs +3 -3
  80. package/bin/commands/stack-stall.d.mts +1 -0
  81. package/bin/commands/stack-stall.mjs +6 -2
  82. package/bin/commands/stack-trunk-behind.d.mts +1 -1
  83. package/bin/commands/stack-trunk-behind.mjs +1 -1
  84. package/bin/commands/stack-work.mjs +1 -1
  85. package/bin/config/merge-command-args.d.mts +2 -0
  86. package/bin/config/merge-command-args.mjs +13 -0
  87. package/bin/config/merge-method.d.mts +0 -5
  88. package/bin/config/merge-method.mjs +0 -6
  89. package/bin/config/schema.d.mts +2 -0
  90. package/bin/config/schema.mjs +2 -13
  91. package/bin/github/batch-parser-helpers.d.mts +5 -0
  92. package/bin/github/batch-parser-helpers.mjs +7 -2
  93. package/bin/github/batch-parsers.mjs +6 -2
  94. package/bin/github/errors.d.mts +2 -0
  95. package/bin/github/errors.mjs +1 -1
  96. package/bin/github/poll-summary-annotation-probe.d.mts +1 -1
  97. package/bin/github/poll-summary-annotation-probe.mjs +2 -2
  98. package/bin/github/poll-summary-command.d.mts +3 -2
  99. package/bin/github/poll-summary-command.mjs +6 -4
  100. package/bin/github/poll-summary-projector.mjs +16 -14
  101. package/bin/github/poll-summary-readiness.d.mts +4 -0
  102. package/bin/github/poll-summary-readiness.mjs +22 -0
  103. package/bin/github/poll-summary-rest-queue.d.mts +13 -0
  104. package/bin/github/poll-summary-rest-queue.mjs +21 -0
  105. package/bin/github/poll-summary-review-helpers.mjs +8 -4
  106. package/bin/state/merge-method-cache.d.mts +19 -0
  107. package/bin/state/merge-method-cache.mjs +27 -0
  108. package/bin/state/merge-request-claim.d.mts +23 -0
  109. package/bin/state/merge-request-claim.mjs +44 -0
  110. package/bin/state/merge-request-clear.d.mts +24 -0
  111. package/bin/state/merge-request-clear.mjs +36 -0
  112. package/bin/state/merge-request-lock.d.mts +13 -0
  113. package/bin/state/merge-request-lock.mjs +136 -0
  114. package/bin/state/merge-request-stack-heads.d.mts +2 -0
  115. package/bin/state/merge-request-stack-heads.mjs +8 -0
  116. package/bin/state/merge-request.d.mts +23 -6
  117. package/bin/state/merge-request.mjs +29 -29
  118. package/bin/state/ready-receipts.d.mts +11 -0
  119. package/bin/state/ready-receipts.mjs +7 -0
  120. package/bin/state/watch-lock.d.mts +10 -0
  121. package/bin/state/watch-lock.mjs +38 -3
  122. package/bin/types/poll-summary.d.mts +2 -0
  123. package/package.json +12 -5
  124. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  125. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  126. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +1 -1
  127. package/plugins/pr-shepherd/skills/pr-shepherd/references/create-a-pr.md +2 -2
  128. package/plugins/pr-shepherd/skills/pr-shepherd/references/waiting.md +1 -1
  129. package/plugins/pr-shepherd/skills/setup-pr-shepherd/references/classifiers.md +1 -1
  130. package/pr-shepherd.schema.json +8 -0
  131. package/bin/commands/stack-merge-flag.d.mts +0 -7
  132. package/bin/commands/stack-merge-flag.mjs +0 -6
@@ -0,0 +1,27 @@
1
+ import type { RepoInfo } from "../github/client.mts";
2
+ import { GitHubRequestError } from "../github/errors.mts";
3
+ import type { ResumeContext } from "./apply-merge-resume.mts";
4
+ import type { ApplyMergeResult } from "./apply-merge.mts";
5
+ /**
6
+ * The failure to report when the PR belongs to a native stack, or when its membership cannot be
7
+ * read: either way no synchronous fallback is safe, so the original UUID stays on record. Null
8
+ * means GitHub confirmed the PR is standalone.
9
+ */
10
+ export declare function stackedFailure(ctx: ResumeContext, statusCode: number): Promise<ApplyMergeResult | null>;
11
+ /**
12
+ * A PR that joined a stack after the last membership check makes GitHub refuse the synchronous
13
+ * merge, while the original asynchronous request may still run. Only a confirmed standalone PR
14
+ * lets the refusal retire the record (null). A stack-specific 405, a stacked PR, or a failed
15
+ * lookup keeps the record, its UUID, and its sent marker, so no run, including one that read
16
+ * membership earlier, can send another fallback; the returned reason says why. Either way the
17
+ * refusal itself is raised.
18
+ */
19
+ export declare function keepRefusedFallback(ctx: ResumeContext, refusal: GitHubRequestError): Promise<string | null>;
20
+ /**
21
+ * Why an unreadable request cannot be replaced, from membership alone: a stacked PR must reconcile
22
+ * the original request. Null means GitHub confirmed the PR is standalone. A lookup that fails
23
+ * still throws, keeping its exit code and cause so batches stop; its message adds the
24
+ * reconciliation step.
25
+ */
26
+ export declare function supersedeRefusal(pr: number, repo: RepoInfo): Promise<string | null>;
27
+ export declare const unreadableStatusMessage: (status: number) => string;
@@ -0,0 +1,85 @@
1
+ import { GitHubRequestError } from "../github/errors.mjs";
2
+ import { ShepherdError } from "../exit-codes.mjs";
3
+ import { rateLimitKind } from "../github/rate-limit-kind.mjs";
4
+ import { readRestStackMembership } from "../github/rest-stack-read.mjs";
5
+ import { isRestSessionRefusalResponse } from "../github/rest-session-refusal.mjs";
6
+ /**
7
+ * The failure to report when the PR belongs to a native stack, or when its membership cannot be
8
+ * read: either way no synchronous fallback is safe, so the original UUID stays on record. Null
9
+ * means GitHub confirmed the PR is standalone.
10
+ */
11
+ export async function stackedFailure(ctx, statusCode) {
12
+ try {
13
+ if (!(await readRestStackMembership(ctx.pr, ctx.repo)))
14
+ return null;
15
+ return ctx.factory.failed(unreadableStatusMessage(statusCode), true);
16
+ }
17
+ catch (lookup) {
18
+ return ctx.factory.failed(`${unreadableStatusMessage(statusCode)} Shepherd could not verify native-stack membership: ${describeLookupFailure(lookup)}`, true);
19
+ }
20
+ }
21
+ /**
22
+ * A PR that joined a stack after the last membership check makes GitHub refuse the synchronous
23
+ * merge, while the original asynchronous request may still run. Only a confirmed standalone PR
24
+ * lets the refusal retire the record (null). A stack-specific 405, a stacked PR, or a failed
25
+ * lookup keeps the record, its UUID, and its sent marker, so no run, including one that read
26
+ * membership earlier, can send another fallback; the returned reason says why. Either way the
27
+ * refusal itself is raised.
28
+ */
29
+ export async function keepRefusedFallback(ctx, refusal) {
30
+ // GitHub's own stack refusal proves the PR was stacked when the PUT ran, even if it has left
31
+ // the stack before any later membership read.
32
+ if (refusal.status === 405 && /\bstack/i.test(refusal.responseMessage ?? refusal.message))
33
+ return "GitHub refused it because the PR was in a native stack.";
34
+ try {
35
+ return (await readRestStackMembership(ctx.pr, ctx.repo))
36
+ ? "the PR now belongs to a native stack."
37
+ : null;
38
+ }
39
+ catch (lookup) {
40
+ return `Shepherd could not verify native-stack membership: ${describeLookupFailure(lookup)}`;
41
+ }
42
+ }
43
+ const stackedSupersede = "This PR belongs to a native stack; reconcile the persisted asynchronous merge request before requesting another merge.";
44
+ /**
45
+ * Why an unreadable request cannot be replaced, from membership alone: a stacked PR must reconcile
46
+ * the original request. Null means GitHub confirmed the PR is standalone. A lookup that fails
47
+ * still throws, keeping its exit code and cause so batches stop; its message adds the
48
+ * reconciliation step.
49
+ */
50
+ export async function supersedeRefusal(pr, repo) {
51
+ try {
52
+ return (await readRestStackMembership(pr, repo)) ? stackedSupersede : null;
53
+ }
54
+ catch (lookup) {
55
+ const message = `Shepherd could not verify native-stack membership, so the persisted asynchronous merge request cannot be replaced: ${describeLookupFailure(lookup)} Until it can, reconcile the persisted request before requesting another merge.`;
56
+ if (lookup instanceof GitHubRequestError)
57
+ throw new GitHubRequestError(message, {
58
+ status: lookup.status,
59
+ ...(lookup.rateLimit && { rateLimit: lookup.rateLimit }),
60
+ ...(lookup.retryAfterSeconds !== undefined && {
61
+ retryAfterSeconds: lookup.retryAfterSeconds,
62
+ }),
63
+ ...(lookup.responseMessage !== undefined && { responseMessage: lookup.responseMessage }),
64
+ ...(lookup.authSource !== undefined && { authSource: lookup.authSource }),
65
+ exitCodeOverride: lookup.exitCode,
66
+ cause: lookup,
67
+ });
68
+ if (lookup instanceof ShepherdError)
69
+ throw new ShepherdError(message, lookup.exitCode, { cause: lookup });
70
+ throw new Error(message, { cause: lookup });
71
+ }
72
+ }
73
+ /**
74
+ * The stack lookup's own error text, as GitHub or the transport reported it, so callers need no
75
+ * further request to see why. Only a plain access refusal adds where to look.
76
+ */
77
+ function describeLookupFailure(error) {
78
+ const text = `the stack lookup failed (${error instanceof Error ? error.message : String(error)}).`;
79
+ const accessRefusal = error instanceof GitHubRequestError &&
80
+ (error.status === 401 || error.status === 403 || error.status === 404) &&
81
+ rateLimitKind(error) === null &&
82
+ !isRestSessionRefusalResponse(error.status, error.responseMessage ?? error.message);
83
+ return `${text} ${accessRefusal ? "Check REST stack-read access and retry the same command." : "Retry the same command."}`;
84
+ }
85
+ export const unreadableStatusMessage = (status) => `The asynchronous merge status is unavailable (${status}). The PR is not merged; its request outcome is unknown and no duplicate was submitted.`;
@@ -0,0 +1,20 @@
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 SubmitContext {
7
+ repo: RepoInfo;
8
+ pr: number;
9
+ key: {
10
+ owner: string;
11
+ repo: string;
12
+ pr: number;
13
+ };
14
+ record: MergeRequestRecord;
15
+ options: RestMergeOptions;
16
+ factory: ReturnType<typeof mergeResultFactory>;
17
+ }
18
+ /** Send the claimed asynchronous request once and record its outcome. */
19
+ export declare function submitClaimedRequest(ctx: SubmitContext): Promise<ApplyMergeResult>;
20
+ export {};
@@ -0,0 +1,47 @@
1
+ import { GitHubRequestError } from "../github/errors.mjs";
2
+ import { matchesRestMergeRequest, requestRestMerge, } from "../github/rest-merge.mjs";
3
+ import { writeMergeRequest } from "../state/merge-request.mjs";
4
+ /** Send the claimed asynchronous request once and record its outcome. */
5
+ export async function submitClaimedRequest(ctx) {
6
+ const { repo, pr, key, record, options } = ctx;
7
+ const { failed, project } = ctx.factory;
8
+ let response;
9
+ const submittedAtUnix = Math.floor(Date.now() / 1000);
10
+ try {
11
+ response = await requestRestMerge(repo, pr, options);
12
+ }
13
+ catch (error) {
14
+ if (error instanceof GitHubRequestError && error.status >= 400 && error.status < 500) {
15
+ await writeMergeRequest(key, {
16
+ ...record,
17
+ response: {
18
+ status: "failed",
19
+ details: { message: error.responseMessage ?? error.message },
20
+ },
21
+ });
22
+ throw error;
23
+ }
24
+ return failed(`Merge submission outcome is unknown: ${error instanceof Error ? error.message : String(error)}. No duplicate request will be submitted.`, true);
25
+ }
26
+ if (response.status === "pending" && !matchesRestMergeRequest(response, options)) {
27
+ const mismatch = failed("GitHub returned a pending merge with different or unverifiable options; its UUID was not adopted.", true);
28
+ await writeMergeRequest(key, {
29
+ ...record,
30
+ response: { status: mismatch.status, details: mismatch.details },
31
+ uncertain: true,
32
+ });
33
+ return mismatch;
34
+ }
35
+ await writeMergeRequest(key, {
36
+ ...record,
37
+ ...(response.details.uuid && response.status === "pending" && { uuid: response.details.uuid }),
38
+ ...(response.status === "enqueued" && { submittedAtUnix }),
39
+ response,
40
+ });
41
+ return {
42
+ ...project(response),
43
+ ...(record.supersededUuid && {
44
+ note: `Superseded the unreadable default request ${record.supersededUuid}; it may still execute, and both requests are guarded by the same head SHA.`,
45
+ }),
46
+ };
47
+ }
@@ -0,0 +1,17 @@
1
+ import type { RestMergeOptions } from "../github/rest-merge.mts";
2
+ import type { MergeRequestRecord } from "../state/merge-request.mts";
3
+ /**
4
+ * The retry an unreadable `default` status named (`direct_merge` with a method, same head)
5
+ * supersedes that request; both are SHA-guarded, so a late execution of the old one only makes
6
+ * the new one a refused no-op. The successor records the old UUID (`claimMergeRequestLocked`).
7
+ */
8
+ export declare function supersedesUnreadableDefault(existing: MergeRequestRecord | null, options: RestMergeOptions): boolean;
9
+ /**
10
+ * An acknowledged CI queue removal of this head, later than the second its submit PUT was sent (`submittedAtUnix`; a request that only became `enqueued` on a resumed status read has none, so the request start), retires that
11
+ * enqueue: the request is no longer in the queue, so a fresh, fully revalidated one may be sent.
12
+ */
13
+ export declare function acknowledgedQueueRemoval(key: {
14
+ owner: string;
15
+ repo: string;
16
+ pr: number;
17
+ }, existing: MergeRequestRecord | null, options: RestMergeOptions): Promise<boolean>;
@@ -0,0 +1,30 @@
1
+ import { readQueueRemovalAcknowledgment } from "../state/queue-removal-ack.mjs";
2
+ /**
3
+ * The retry an unreadable `default` status named (`direct_merge` with a method, same head)
4
+ * supersedes that request; both are SHA-guarded, so a late execution of the old one only makes
5
+ * the new one a refused no-op. The successor records the old UUID (`claimMergeRequestLocked`).
6
+ */
7
+ export function supersedesUnreadableDefault(existing, options) {
8
+ return Boolean(existing?.statusUnreadable &&
9
+ !existing.syncMergeSent &&
10
+ !existing.stackHeads &&
11
+ !existing.options.expectedStack &&
12
+ existing.options.mergeAction === "default" &&
13
+ options.mergeAction === "direct_merge" &&
14
+ options.mergeMethod &&
15
+ !options.expectedStack &&
16
+ existing.options.requireSha === options.requireSha);
17
+ }
18
+ /**
19
+ * An acknowledged CI queue removal of this head, later than the second its submit PUT was sent (`submittedAtUnix`; a request that only became `enqueued` on a resumed status read has none, so the request start), retires that
20
+ * enqueue: the request is no longer in the queue, so a fresh, fully revalidated one may be sent.
21
+ */
22
+ export async function acknowledgedQueueRemoval(key, existing, options) {
23
+ if (!existing || existing.uncertain || existing.response?.status !== "enqueued")
24
+ return false;
25
+ const ack = await readQueueRemovalAcknowledgment(key);
26
+ return (ack !== null &&
27
+ ack.headSha === options.requireSha &&
28
+ existing.options.requireSha === options.requireSha &&
29
+ ack.removedAtUnix > (existing.submittedAtUnix ?? existing.startedAtUnix));
30
+ }
@@ -0,0 +1,16 @@
1
+ import type { RestMergeOptions } from "../github/rest-merge.mts";
2
+ import type { ResumeContext } from "./apply-merge-resume.mts";
3
+ import type { ApplyMergeResult } from "./apply-merge.mts";
4
+ export declare const syncSentMessage: (pr: number) => string;
5
+ export declare const noUuidMessage: (pr: number, repo: {
6
+ owner: string;
7
+ name: string;
8
+ }) => string;
9
+ /**
10
+ * Sends the synchronous fallback at most once per request: under the merge-request lock the record
11
+ * must still be the one read, without a sent marker, and the marker is written before the PUT.
12
+ * A concurrent resumer, or a repeat after an unconfirmed answer, then reports `uncertain`.
13
+ */
14
+ export declare function syncFallback(ctx: ResumeContext, method: NonNullable<RestMergeOptions["mergeMethod"]>, statusCode: number,
15
+ /** Runs once the final membership check confirms the PR is standalone. */
16
+ onStandalone?: () => Promise<void>): Promise<ApplyMergeResult>;
@@ -0,0 +1,55 @@
1
+ import { mergeRequestGeneration, readMergeRequest, writeMergeRequestStatus, } from "../state/merge-request.mjs";
2
+ import { withMergeRequestLock } from "../state/merge-request-lock.mjs";
3
+ import { settleSyncMerge } from "./apply-merge-default-route.mjs";
4
+ import { keepRefusedFallback, stackedFailure } from "./apply-merge-stack-membership.mjs";
5
+ export const syncSentMessage = (pr) => `The synchronous merge fallback was already sent for this request and its outcome is unconfirmed. The PR is not merged yet, and no duplicate was submitted. A PR that still reads open does not mean the request failed: the earlier request may still merge it. Rerun Shepherd later and report the unconfirmed outcome to the user. Run \`pr-shepherd admin clean pr ${pr}\` only after a person has confirmed on GitHub that neither the earlier merge-async request nor the synchronous merge can still land (for example, the head changed or the PR closed), never because the PR merely reads open; it removes the request record so a new one can be submitted.`;
6
+ export const noUuidMessage = (pr, repo) => `The previous merge submission has an unknown outcome and no UUID. The PR is not merged; no duplicate request was submitted. A PR that still reads open does not mean the request failed: the earlier request may still merge it. Rerun Shepherd later and report the unconfirmed outcome to the user. Run \`pr-shepherd admin clean pr ${pr}\` from a checkout of ${repo.owner}/${repo.name} (it cleans the current checkout's repository) only after a person has confirmed on GitHub that the earlier request cannot still merge the PR (for example, the head changed or the PR closed), never because the PR merely reads open; it removes the request record so a new one can be submitted.`;
7
+ /**
8
+ * Sends the synchronous fallback at most once per request: under the merge-request lock the record
9
+ * must still be the one read, without a sent marker, and the marker is written before the PUT.
10
+ * A concurrent resumer, or a repeat after an unconfirmed answer, then reports `uncertain`.
11
+ */
12
+ export async function syncFallback(ctx, method, statusCode,
13
+ /** Runs once the final membership check confirms the PR is standalone. */
14
+ onStandalone) {
15
+ const { repo, pr, key, existing, options, factory } = ctx;
16
+ // The last membership read before the claim, on both routes: the PR can join a stack
17
+ // (`gh stack link`) outside this lock, and GitHub refuses a synchronous merge for a stacked PR.
18
+ const stacked = await stackedFailure(ctx, statusCode);
19
+ if (stacked)
20
+ return stacked;
21
+ await onStandalone?.();
22
+ const owned = await withMergeRequestLock(key, async () => {
23
+ const current = await readMergeRequest(key);
24
+ if (!current || mergeRequestGeneration(current) !== mergeRequestGeneration(existing))
25
+ return "changed";
26
+ if (current.syncMergeSent)
27
+ return "sent";
28
+ // A readable status recorded since this run's refused read is newer than that refusal.
29
+ if (current.statusRevision !== existing.statusRevision)
30
+ return "readable";
31
+ // The sent fallback owns this request now, so the unreadable marker no longer invites a
32
+ // `direct_merge` retry to supersede it.
33
+ const { statusUnreadable: _routed, ...sending } = current;
34
+ await writeMergeRequestStatus(key, { ...sending, syncMergeSent: true });
35
+ return "owned";
36
+ }, () => "changed");
37
+ if (owned === "sent")
38
+ return factory.failed(syncSentMessage(pr), true);
39
+ if (owned === "readable")
40
+ return factory.failed("Another `apply merge` run read this request's status after this run's status read was refused, so no synchronous fallback was sent. Rerun this command to resume the request.", true);
41
+ if (owned === "changed")
42
+ return factory.failed("Another merge request is already being submitted; resume this command after its outcome is recorded.", true);
43
+ return settleSyncMerge({
44
+ repo,
45
+ pr,
46
+ key,
47
+ record: existing,
48
+ method,
49
+ options,
50
+ factory,
51
+ suffix: "(merged synchronously: the asynchronous status was unreadable)",
52
+ route: "sync-fallback",
53
+ keepOnRefusal: (refusal) => keepRefusedFallback(ctx, refusal),
54
+ });
55
+ }
@@ -13,6 +13,8 @@ export interface ApplyMergeResult extends RestMergeResponse {
13
13
  /** A mutation may already have reached GitHub. No new request will be issued. */
14
14
  uncertain?: true;
15
15
  note?: string;
16
+ /** Present only when the merge left the asynchronous route: a synchronous fallback or cached method. */
17
+ merge_route?: "sync-fallback" | "cached-method";
16
18
  }
17
19
  /** Submit one guarded asynchronous request, or resume its existing UUID without resubmitting. */
18
20
  export declare function runApplyMerge(input: ApplyMergeInput): Promise<ApplyMergeResult>;
@@ -1,16 +1,23 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { mergeResultFactory } from "./apply-merge-output.mjs";
2
3
  import { validateApplyMergeOptions, validateApplyMergeTarget, sameMergeOptions, } from "./apply-merge-options.mjs";
3
4
  import { validateRestStackMergeReadiness } from "./rest-stack-merge-readiness.mjs";
5
+ import { supersedeRefusal } from "./apply-merge-stack-membership.mjs";
4
6
  export { validateApplyMergeOptions } from "./apply-merge-options.mjs";
5
7
  import { EXIT, ShepherdError } from "../exit-codes.mjs";
6
8
  import { getCurrentPrNumber, getRepoInfo } from "../github/client.mjs";
7
- import { GitHubRequestError } from "../github/errors.mjs";
8
9
  import { mergedResponse, readPull } from "./apply-merge-pull.mjs";
10
+ import { cachedDefaultMethod, settleSyncMerge } from "./apply-merge-default-route.mjs";
11
+ import { acknowledgedQueueRemoval, supersedesUnreadableDefault } from "./apply-merge-supersede.mjs";
12
+ import { claimMergeRequestLocked } from "../state/merge-request-claim.mjs";
13
+ import { stackHeadDrift } from "./stack-lower-heads.mjs";
9
14
  import { resumeMergeRequest } from "./apply-merge-resume.mjs";
10
15
  import { withRestConditionalScope } from "../github/rest-conditional-scope.mjs";
11
16
  import { getGithubTransport } from "../github/transport.mjs";
12
- import { matchesRestMergeRequest, requestRestMerge, } from "../github/rest-merge.mjs";
13
- import { claimMergeRequest, replaceFailedMergeRequest, readMergeRequest, writeMergeRequest, } from "../state/merge-request.mjs";
17
+ import { submitClaimedRequest } from "./apply-merge-submit.mjs";
18
+ import { noUuidMessage } from "./apply-merge-sync-fallback.mjs";
19
+ import {} from "../github/rest-merge.mjs";
20
+ import { readMergeRequest } from "../state/merge-request.mjs";
14
21
  /** Submit one guarded asynchronous request, or resume its existing UUID without resubmitting. */
15
22
  export async function runApplyMerge(input) {
16
23
  validateApplyMergeOptions(input);
@@ -44,12 +51,14 @@ async function submitApplyMerge(input, repo, pr, key) {
44
51
  return failed("Current PR head does not match --require-sha; no merge request was submitted.");
45
52
  if (pull.state !== "open" || pull.draft !== false)
46
53
  return failed("Pull request must be open and ready for review.");
54
+ const supersede = supersedesUnreadableDefault(existing, options);
55
+ const removalAcknowledged = await acknowledgedQueueRemoval(key, existing, options);
47
56
  const replaceFailed = existing &&
48
57
  !existing.uncertain &&
49
58
  ((existing.response?.status === "failed" && !sameMergeOptions(existing.options, options)) ||
50
59
  (existing.response?.status === "enqueued" &&
51
- existing.options.requireSha !== options.requireSha));
52
- if (existing && !replaceFailed) {
60
+ (removalAcknowledged || existing.options.requireSha !== options.requireSha)));
61
+ if (existing && !replaceFailed && !supersede) {
53
62
  if (!sameMergeOptions(existing.options, options))
54
63
  return failed("A persisted asynchronous merge request has different options; reconcile its outcome before requesting another merge.", true);
55
64
  if (existing.response?.status !== undefined && existing.response.status !== "pending")
@@ -61,7 +70,7 @@ async function submitApplyMerge(input, repo, pr, key) {
61
70
  }),
62
71
  };
63
72
  if (!existing.uuid)
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);
73
+ return failed(noUuidMessage(pr, repo), true);
65
74
  return resumeMergeRequest({
66
75
  repo,
67
76
  pr,
@@ -75,44 +84,59 @@ async function submitApplyMerge(input, repo, pr, key) {
75
84
  version: 1,
76
85
  options,
77
86
  startedAtUnix: Math.floor(Date.now() / 1000),
87
+ claimId: randomUUID(),
78
88
  };
79
- await validateRestStackMergeReadiness(pr, repo, input.requireSha, input.expectedStack);
80
- if (!(existing
81
- ? await replaceFailedMergeRequest(key, existing, record)
82
- : await claimMergeRequest(key, record)))
89
+ // A stacked PR can never replace its unreadable request, so membership alone decides, before
90
+ // any READY-receipt check could send the caller to `stack --merge`. A replacement confirmed
91
+ // standalone needs no stack readiness reads.
92
+ const blocked = supersede ? await supersedeRefusal(pr, repo) : null;
93
+ if (blocked)
94
+ return failed(blocked, true);
95
+ const validate = () => validateRestStackMergeReadiness(pr, repo, input.requireSha, input.expectedStack);
96
+ let validatedHeads = supersede ? null : await validate();
97
+ // Decided before the claim, but the synchronous merge only runs after it, so the durable
98
+ // cross-process claim covers this route like every other.
99
+ let cachedMethod = existing || validatedHeads ? undefined : await cachedDefaultMethod(repo, pull, options);
100
+ // A PR can join a stack (`gh stack link`) while the cached method resolves, and GitHub refuses a
101
+ // synchronous merge for a stacked PR. Readiness validation is the recheck: a stack it validates
102
+ // (READY receipts included) goes async with that baseline; a PR it finds standalone keeps the
103
+ // cached route, where GitHub's own refusal guards a later join.
104
+ if (cachedMethod) {
105
+ validatedHeads = await validate();
106
+ if (validatedHeads)
107
+ cachedMethod = undefined;
108
+ }
109
+ // The request binds only the top head, so re-read every layer right before submitting. This runs
110
+ // before the claim: a refusal then leaves no durable record, and an unreadable re-read throws, so
111
+ // the same command can be rerun and re-check instead of replaying a recorded failure.
112
+ const drift = validatedHeads && (await stackHeadDrift(pr, repo, validatedHeads));
113
+ if (drift)
114
+ return failed(drift);
115
+ if (validatedHeads)
116
+ record = { ...record, stackHeads: validatedHeads };
117
+ if (!(await claimMergeRequestLocked(key, existing, record, supersede, removalAcknowledged)))
83
118
  return failed("Another merge request is already being submitted; resume this command after its outcome is recorded.", true);
84
119
  // Recovery may have selected an older durable intent; retain its unique generation token.
120
+ // Until this run records a response, no other run can replace or retire the claim (each needs a
121
+ // response, a UUID, or an unreadable-status marker), so the writes below need no lock.
85
122
  record = (await readMergeRequest(key));
86
- let response;
87
- try {
88
- response = await requestRestMerge(repo, pr, options);
89
- }
90
- catch (error) {
91
- if (error instanceof GitHubRequestError && error.status >= 400 && error.status < 500) {
92
- await writeMergeRequest(key, {
93
- ...record,
94
- response: {
95
- status: "failed",
96
- details: { message: error.responseMessage ?? error.message },
97
- },
98
- });
99
- throw error;
100
- }
101
- return failed(`Merge submission outcome is unknown: ${error instanceof Error ? error.message : String(error)}. No duplicate request will be submitted.`, true);
102
- }
103
- if (response.status === "pending" && !matchesRestMergeRequest(response, options)) {
104
- const mismatch = failed("GitHub returned a pending merge with different or unverifiable options; its UUID was not adopted.", true);
105
- await writeMergeRequest(key, {
106
- ...record,
107
- response: { status: mismatch.status, details: mismatch.details },
108
- uncertain: true,
123
+ // A recovered successor may carry an older or absent baseline; resumes must compare against the
124
+ // heads this run just checked.
125
+ if (validatedHeads)
126
+ record = { ...record, stackHeads: validatedHeads };
127
+ // A PR that joins a stack after the membership check above gets a definite refusal, which
128
+ // retires this unsent claim; the next run validates it as a stack layer and submits async.
129
+ if (cachedMethod)
130
+ return settleSyncMerge({
131
+ repo,
132
+ pr,
133
+ key,
134
+ record,
135
+ method: cachedMethod,
136
+ options,
137
+ factory: { failed, project },
138
+ suffix: "(merged synchronously with the cached repository merge method)",
139
+ route: "cached-method",
109
140
  });
110
- return mismatch;
111
- }
112
- await writeMergeRequest(key, {
113
- ...record,
114
- ...(response.details.uuid && response.status === "pending" && { uuid: response.details.uuid }),
115
- response,
116
- });
117
- return project(response);
141
+ return submitClaimedRequest({ repo, pr, key, record, options, factory: { failed, project } });
118
142
  }
@@ -1,10 +1,21 @@
1
1
  import { selectReviewOutput, } from "../comments/review-output-budget.mjs";
2
+ import { renderReviewBullet } from "../cli/list-formatters.mjs";
2
3
  import { threadTranscriptBody } from "../threads/transcript.mjs";
3
4
  const bodyItem = (item) => ({
4
5
  id: item.id,
5
6
  cost: item.body.length,
6
7
  ...(item.createdAtUnix !== undefined && { createdAtUnix: item.createdAtUnix }),
7
8
  });
9
+ /**
10
+ * A changes-requested review shows its body once. A re-surfaced bot review is a one-line
11
+ * reminder, so it costs that line, not the body it already showed.
12
+ */
13
+ const changesRequestedItem = (review) => ({
14
+ ...bodyItem(review),
15
+ ...(review.staleBotCr === true && {
16
+ cost: renderReviewBullet(review, { pendingInlineThreads: true }).length,
17
+ }),
18
+ });
8
19
  const threadItem = (thread) => ({
9
20
  ...bodyItem(thread),
10
21
  cost: threadTranscriptBody(thread).length,
@@ -22,7 +33,7 @@ const threadItem = (thread) => ({
22
33
  export function applyReviewOutputBudget(buckets, maxChars) {
23
34
  const { changesRequested, threads, comments } = buckets;
24
35
  const selection = selectReviewOutput([
25
- changesRequested.visible.map(bodyItem),
36
+ changesRequested.visible.map(changesRequestedItem),
26
37
  [
27
38
  ...threads.activeThreads.map(threadItem),
28
39
  ...threads.resolutionOnlyThreads.map(threadItem),
@@ -9,6 +9,8 @@ type CheckOptions = GlobalOptions & {
9
9
  merge?: boolean;
10
10
  /** Per-tick review-item body budget (`iterate.review-output-max-chars`). Omitted or 0: no cap. */
11
11
  reviewOutputMaxChars?: number;
12
+ /** Cap on a changes-requested review body (`iterate.changes-requested-review-max-chars`). Omitted or 0: no cap. */
13
+ changesRequestedReviewMaxChars?: number;
12
14
  };
13
15
  export declare function runCheck(opts: CheckOptions, context?: CheckExecutionContext): Promise<ShepherdReport>;
14
16
  export {};
@@ -1,4 +1,5 @@
1
1
  import { fetchPrBatch } from "../github/batch.mjs";
2
+ import { capReviewBody } from "../cli/review-body-cap.mjs";
2
3
  import { headArrivalUnix, queueRemovalAppliesToHead } from "../github/queue-removal-freshness.mjs";
3
4
  import { readQueueRemovalAcknowledgment, matchesQueueRemovalAcknowledgment, isCiQueueRemovalReason, } from "../state/queue-removal-ack.mjs";
4
5
  import { storePrFingerprint } from "../state/pr-fingerprint.mjs";
@@ -341,7 +342,14 @@ async function runScopedCheck(opts, context, repo, prNumber, stateKey) {
341
342
  }, mergeStatus.status));
342
343
  // A deferred tick shows no review items, so it is never capped; its seen markers stay unwritten.
343
344
  const { buckets: budgeted, rollup: reviewItems, heldThreadReviewIds, } = applyReviewOutputBudget({
344
- changesRequested: changesRequestedReviewVisibility,
345
+ // A review body shows once: a re-surfaced review carries no body, and a first showing is
346
+ // capped. What the tick shows is what the budget charges; seen markers keep the raw body.
347
+ changesRequested: {
348
+ visible: changesRequestedReviewVisibility.visible.map((review) => review.staleBotCr
349
+ ? { ...review, body: "" }
350
+ : capReviewBody(review, opts.changesRequestedReviewMaxChars ?? 0)),
351
+ toMarkSeen: changesRequestedReviewVisibility.toMarkSeen,
352
+ },
345
353
  threads: threadVisibility,
346
354
  comments: visibleCommentClassification,
347
355
  firstLookComments,
@@ -141,6 +141,11 @@ export function buildEscalateHumanMessage(escalate, pr, opts) {
141
141
  }
142
142
  }
143
143
  for (const r of escalate.changesRequestedReviews) {
144
+ if (r.staleBotCr) {
145
+ // Its body was shown on an earlier tick.
146
+ lines.push(`- review \`${r.id}\` (${renderEscalateAuthor(r)})${renderReviewCommitTag(r)} [already surfaced]`, "");
147
+ continue;
148
+ }
144
149
  lines.push(`- review \`${r.id}\` (${renderEscalateAuthor(r)})${renderReviewCommitTag(r)}:`);
145
150
  lines.push("");
146
151
  for (const bodyLine of r.body.split("\n"))
@@ -20,7 +20,7 @@ import { classifyItem, loadSeenMap } from "../../state/seen-comments.mjs";
20
20
  import { withIterateApiUsage } from "./run.mjs";
21
21
  import { fetchRawSummaryPr } from "../../github/poll-summary.mjs";
22
22
  import { summarizePollSummaryPr } from "../../github/poll-summary-projector.mjs";
23
- import { annotationProbeUnavailable } from "../../github/poll-summary-annotation-probe.mjs";
23
+ import { annotationProbeUnavailable, hydrateAnnotationTotals, } from "../../github/poll-summary-annotation-probe.mjs";
24
24
  import { fingerprintRawSummaryPr } from "../../github/poll-summary-fingerprint.mjs";
25
25
  import { currentQueueRemovalEvent } from "../../github/poll-summary-queue-removal.mjs";
26
26
  import { freshSummaryRegression } from "./fresh-summary-regression.mjs";
@@ -81,6 +81,7 @@ async function runIterateCore(opts, tick) {
81
81
  autoResolve: true,
82
82
  autoMinimizeSuppressed: !readOnly && config.actions["auto-minimize-suppressed"],
83
83
  reviewOutputMaxChars: config.iterate["review-output-max-chars"],
84
+ changesRequestedReviewMaxChars: config.iterate["changes-requested-review-max-chars"],
84
85
  }, checkContext);
85
86
  tick.report = report;
86
87
  if (opts.eventTargetSink) {
@@ -404,6 +405,7 @@ async function recordReadyReceipt(key, report, context) {
404
405
  let raw;
405
406
  let fingerprint;
406
407
  let summary;
408
+ let olderThreadsSettled;
407
409
  try {
408
410
  raw = await receiptSummaryForReport(key, report, context);
409
411
  if (raw.state !== "OPEN")
@@ -416,6 +418,17 @@ async function recordReadyReceipt(key, report, context) {
416
418
  reason: `the head moved (report ${short(report.headSha)}, fresh ${short(raw.headRefOid)})`,
417
419
  regressed: true,
418
420
  };
421
+ // The full check read every thread and found all resolved (READY alone does not say so: an
422
+ // unresolved thread that is not review work leaves it READY). That covers threads older than
423
+ // the compact window, but only for the summary read in the same request: a later read could
424
+ // hash a review revision the full check never saw (best effort: see `olderThreadsOnlyGap`).
425
+ olderThreadsSettled =
426
+ raw === context?.getReceiptSummary() &&
427
+ report.mergeStatus.mergeRequirements?.conversationsResolved.resolved === true;
428
+ // The stack side probes an overflowing same-head layer that holds the exception, so hash the
429
+ // same evidence here. Other rows are hydrated inside the summary, as before.
430
+ if (olderThreadsSettled && raw.reviewThreads?.pageInfo.hasPreviousPage)
431
+ await hydrateAnnotationTotals(raw, { owner: key.owner, name: key.repo });
419
432
  // Summarize hydrates annotation totals onto the snapshot; hash only after,
420
433
  // so the stored hash matches the stack side's (which hashes hydrated evidence).
421
434
  summary = await summarizePollSummaryPr(raw, { owner: key.owner, name: key.repo }, { stackPrNumber: report.pr });
@@ -439,10 +452,10 @@ async function recordReadyReceipt(key, report, context) {
439
452
  // After the regression check: a base move alongside queued CI must still wait.
440
453
  if (raw.baseRefOid !== report.baseRefOid)
441
454
  return failed(`base moved (report ${short(report.baseRefOid)}, fresh ${short(raw.baseRefOid)})`);
442
- if (!isCurrentSummaryReady(raw, checks, review)) {
455
+ if (!isCurrentSummaryReady(raw, checks, review, { olderThreadsSettled })) {
443
456
  const onlyBlocked = raw.mergeStateStatus === "BLOCKED" &&
444
457
  !raw.isInMergeQueue &&
445
- isCurrentSummaryReady(raw, checks, review, { allowBlocked: true });
458
+ isCurrentSummaryReady(raw, checks, review, { allowBlocked: true, olderThreadsSettled });
446
459
  return onlyBlocked
447
460
  ? { status: "blocked" }
448
461
  : failed("fresh summary is not ready (checks, review, or merge state changed)");
@@ -472,6 +485,7 @@ async function recordReadyReceipt(key, report, context) {
472
485
  ...(removalEvent?.id && {
473
486
  acknowledgedQueueRemovalId: removalEvent.id,
474
487
  }),
488
+ ...(olderThreadsSettled && { allThreadsResolved: true }),
475
489
  recordedAtUnix: Math.floor(Date.now() / 1000),
476
490
  });
477
491
  return { status: "written" };
@@ -482,9 +496,23 @@ async function recordReadyReceipt(key, report, context) {
482
496
  }
483
497
  /** Clear a stale READY receipt; return whether a current receipt remains. */
484
498
  async function revalidateReadyReceipt(key, report, hasReadinessWork, context) {
485
- const receipt = await readReadyReceipt(key);
499
+ let receipt = await readReadyReceipt(key);
486
500
  if (!receipt)
487
501
  return false;
502
+ // A full check that no longer finds every thread resolved withdraws the older-threads
503
+ // assurance, even while the plain READY receipt stays current.
504
+ if (receipt.allThreadsResolved &&
505
+ report.mergeStatus.mergeRequirements?.conversationsResolved.resolved !== true) {
506
+ const { allThreadsResolved: _withdrawn, ...withdrawn } = receipt;
507
+ try {
508
+ await writeReadyReceipt(withdrawn);
509
+ receipt = withdrawn;
510
+ }
511
+ catch {
512
+ await clearReadyReceipt(key);
513
+ return false;
514
+ }
515
+ }
488
516
  const retainQueuedReceipt = report.mergeQueue?.inQueue === true &&
489
517
  report.mergeStatus.state === "OPEN" &&
490
518
  !report.mergeStatus.isDraft &&
@@ -504,6 +532,8 @@ async function revalidateReadyReceipt(key, report, hasReadinessWork, context) {
504
532
  if (annotationProbeUnavailable(raw)) {
505
533
  const sameHead = raw.headRefOid === report.headSha;
506
534
  const sameBase = retainQueuedReceipt || raw.baseRefOid === report.baseRefOid;
535
+ // No exception for older threads here: without the probe the receipt cannot be
536
+ // re-fingerprinted, so a truncated sample must not keep it.
507
537
  const stillReady = isCurrentSummaryReady(raw, summary.checks ?? {}, summary.review ?? {});
508
538
  if (!sameHead || !sameBase || !stillReady) {
509
539
  await clearReadyReceipt(key);