pr-shepherd 2.4.0 → 2.5.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 (76) hide show
  1. package/.claude-plugin/plugin.json +3 -3
  2. package/.grok-plugin/marketplace.json +1 -1
  3. package/README.md +7 -9
  4. package/bin/classify/apply.d.mts +8 -1
  5. package/bin/classify/apply.mjs +37 -47
  6. package/bin/classify/items.d.mts +7 -0
  7. package/bin/classify/items.mjs +57 -0
  8. package/bin/classify/standard/coderabbit-notices.d.mts +2 -1
  9. package/bin/classify/standard/coderabbit-notices.mjs +33 -1
  10. package/bin/classify/standard/index.d.mts +2 -1
  11. package/bin/classify/standard/index.mjs +2 -1
  12. package/bin/classify/types.d.mts +8 -3
  13. package/bin/cli/iterate-lean.mjs +3 -0
  14. package/bin/cli/list-formatters.d.mts +1 -0
  15. package/bin/cli/list-formatters.mjs +3 -1
  16. package/bin/cli/triage-formatter.mjs +6 -1
  17. package/bin/commands/check-activity.mjs +2 -1
  18. package/bin/commands/check-fingerprint.mjs +1 -0
  19. package/bin/commands/check.mjs +39 -9
  20. package/bin/commands/iterate/check-instructions.d.mts +2 -0
  21. package/bin/commands/iterate/check-instructions.mjs +14 -0
  22. package/bin/commands/iterate/classify.d.mts +17 -3
  23. package/bin/commands/iterate/classify.mjs +105 -66
  24. package/bin/commands/iterate/escalate.mjs +6 -1
  25. package/bin/commands/iterate/index.mjs +16 -24
  26. package/bin/commands/iterate/render.d.mts +2 -11
  27. package/bin/commands/iterate/render.mjs +10 -19
  28. package/bin/commands/iterate/stall.mjs +3 -0
  29. package/bin/commands/iterate/triage.d.mts +1 -0
  30. package/bin/commands/iterate/triage.mjs +18 -13
  31. package/bin/commands/poll-summary-instructions.d.mts +1 -1
  32. package/bin/commands/poll-summary-instructions.mjs +2 -2
  33. package/bin/commands/poll-summary.mjs +1 -1
  34. package/bin/commands/resolve-mutate.mjs +39 -4
  35. package/bin/commands/resolve-review-guard.d.mts +19 -0
  36. package/bin/commands/resolve-review-guard.mjs +61 -0
  37. package/bin/commands/stack-merge-escalations.d.mts +6 -0
  38. package/bin/commands/stack-merge-escalations.mjs +17 -0
  39. package/bin/commands/stack-merge-plan.mjs +10 -6
  40. package/bin/comments/resolve.mjs +4 -4
  41. package/bin/comments/review-thread-markers.d.mts +1 -1
  42. package/bin/comments/review-thread-markers.mjs +23 -9
  43. package/bin/comments/superseded-approvals.d.mts +28 -0
  44. package/bin/comments/superseded-approvals.mjs +99 -0
  45. package/bin/config/schema.d.mts +2 -0
  46. package/bin/config/schema.mjs +1 -0
  47. package/bin/github/batch-parsers.mjs +31 -0
  48. package/bin/github/batch-raw-types.d.mts +3 -0
  49. package/bin/github/batch-viewer.d.mts +2 -2
  50. package/bin/github/batch.mjs +1 -1
  51. package/bin/github/gql/batch-pr-page.gql +8 -2
  52. package/bin/github/gql/batch-pr.gql +4 -1
  53. package/bin/github/poll-summary-review-helpers.d.mts +20 -0
  54. package/bin/github/poll-summary-review-helpers.mjs +81 -0
  55. package/bin/github/poll-summary-review.mjs +37 -46
  56. package/bin/github/poll-summary-rule-auto-resolve.mjs +1 -0
  57. package/bin/github/poll-summary-rule-items.d.mts +1 -1
  58. package/bin/github/poll-summary-rule-items.mjs +3 -2
  59. package/bin/github/rest-batch-snapshot.mjs +25 -1
  60. package/bin/github/review-unresolved-threads.d.mts +13 -0
  61. package/bin/github/review-unresolved-threads.mjs +152 -0
  62. package/bin/github/stack-handoff-page.mjs +5 -1
  63. package/bin/state/seen-comments.d.mts +3 -1
  64. package/bin/state/seen-comments.mjs +28 -2
  65. package/bin/types/escalate.d.mts +1 -0
  66. package/bin/types/github.d.mts +7 -1
  67. package/bin/types/iterate.d.mts +4 -2
  68. package/bin/types/report.d.mts +8 -0
  69. package/package.json +5 -5
  70. package/plugins/pr-shepherd/.claude-plugin/plugin.json +3 -3
  71. package/plugins/pr-shepherd/.codex-plugin/plugin.json +6 -6
  72. package/plugins/pr-shepherd/skills/setup-pr-shepherd/SKILL.md +1 -1
  73. package/plugins/pr-shepherd/skills/setup-pr-shepherd/references/classifiers.md +3 -3
  74. package/plugins/pr-shepherd/skills/setup-pr-shepherd/references/upstream-standard-rule.md +2 -2
  75. package/pr-shepherd.schema.json +4 -0
  76. package/src/classify/types.mts +9 -1
@@ -1,7 +1,7 @@
1
1
  import type { PollSummaryItem, PollSummaryResult, StackMergeScope } from "../types.mts";
2
2
  import { type ApproveCommands } from "./stack-merge-plan.mts";
3
3
  /** Keep aggregate JSON, Markdown, and MCP instructions on one projection. */
4
- export declare function withPollSummaryInstructions(result: PollSummaryResult, mergeRequested: boolean, rerunCommand?: string, scope?: StackMergeScope): PollSummaryResult;
4
+ export declare function withPollSummaryInstructions(result: PollSummaryResult, mergeRequested: boolean, rerunCommand?: string, scope?: StackMergeScope, approve?: ApproveCommands): PollSummaryResult;
5
5
  /** The projected summary, plus the idle layers when the stack plan can only wait on them. */
6
6
  export declare function planPollSummary(result: PollSummaryResult, mergeRequested: boolean, rerunCommand?: string, scope?: StackMergeScope | undefined, approve?: ApproveCommands): {
7
7
  result: PollSummaryResult;
@@ -8,8 +8,8 @@ import { aboveThroughTarget } from "./stack-merge-scope.mjs";
8
8
  import { ownershipBoundaryStep } from "./stack-ownership.mjs";
9
9
  import { appendStackRerunInstruction, onlyDraftReadinessVerification, splitStackWork, stackRerunTarget, } from "./stack-work.mjs";
10
10
  /** Keep aggregate JSON, Markdown, and MCP instructions on one projection. */
11
- export function withPollSummaryInstructions(result, mergeRequested, rerunCommand, scope) {
12
- return planPollSummary(result, mergeRequested, rerunCommand, scope).result;
11
+ export function withPollSummaryInstructions(result, mergeRequested, rerunCommand, scope, approve) {
12
+ return planPollSummary(result, mergeRequested, rerunCommand, scope, approve).result;
13
13
  }
14
14
  /** The projected summary, plus the idle layers when the stack plan can only wait on them. */
15
15
  export function planPollSummary(result, mergeRequested, rerunCommand, scope = mergeRequested ? { kind: "all" } : undefined, approve) {
@@ -259,7 +259,7 @@ function attachUsage(result, opts) {
259
259
  return withoutImpliedOwnership(enriched);
260
260
  }
261
261
  const scope = requestedMergeScope(opts);
262
- return withoutImpliedOwnership(withPollSummaryInstructions(enriched, scope !== undefined, aggregateRerunCommand(enriched.repo, enriched.selection, opts), scope));
262
+ return withoutImpliedOwnership(withPollSummaryInstructions(enriched, scope !== undefined, aggregateRerunCommand(enriched.repo, enriched.selection, opts), scope, (extra) => stackApprovalCommands(enriched.repo, enriched.selection, opts, extra)));
263
263
  }
264
264
  /** Whole-stack ownership is the default, so rows say `owned` only when the caller listed PRs. */
265
265
  function withoutImpliedOwnership(result) {
@@ -2,7 +2,8 @@ import { getRepoInfo, getCurrentPrNumber } from "../github/client.mjs";
2
2
  import { applyResolveOptions } from "../comments/resolve.mjs";
3
3
  import { fetchReplyThreadTranscripts } from "../github/reply-thread-transcripts.mjs";
4
4
  import { readApplyReviewPreflight, } from "../github/apply-review-preflight.mjs";
5
- import { markReplySeen } from "../state/seen-comments.mjs";
5
+ import { BLOCKED_REVIEW_INSTRUCTION, collectReviewIdsToGuard, formatBlockedReviewErrors, resolveBlockedReviews, } from "./resolve-review-guard.mjs";
6
+ import { markReplySeen, pruneResolvedReviewThreads } from "../state/seen-comments.mjs";
6
7
  import { threadTranscriptBodies } from "../threads/transcript.mjs";
7
8
  import { addPrShepherdMarker } from "../comments/marker.mjs";
8
9
  import { adoptedReplyThreads } from "../comments/uncertain-replies.mjs";
@@ -37,19 +38,50 @@ export async function runResolveMutate(opts) {
37
38
  // the explicit mutation request; GitHub's mutation response is authoritative.
38
39
  }
39
40
  }
41
+ const stateKey = { owner: repo.owner, repo: repo.name, pr: prNumber };
42
+ // Guard: never allow dismissing or hiding a review while any of its inline threads are
43
+ // unresolved — even if those threads are also passed to `--resolve-thread-ids` in the same
44
+ // command. Local markers track each review's unresolved threads across `check` and `apply`,
45
+ // so already-resolved reviews need zero GraphQL calls; GitHub is only queried when local
46
+ // state still has unresolved thread IDs (to check for external resolution) or has no record yet.
47
+ const reviewIdsToCheck = collectReviewIdsToGuard(opts.dismissReviewIds, opts.minimizeCommentIds);
48
+ const blockedByReview = reviewIdsToCheck.length > 0
49
+ ? await resolveBlockedReviews(stateKey, prNumber, repo, reviewIdsToCheck)
50
+ : new Map();
51
+ const blockedErrors = formatBlockedReviewErrors(blockedByReview);
52
+ const allowedDismissReviewIds = opts.dismissReviewIds?.filter((id) => !blockedByReview.has(id));
53
+ const allowedMinimizeCommentIds = opts.minimizeCommentIds?.filter((id) => !blockedByReview.has(id));
54
+ const hasAllowedMutations = (opts.resolveThreadIds?.length ?? 0) > 0 ||
55
+ (opts.replyThreadIds?.length ?? 0) > 0 ||
56
+ (allowedMinimizeCommentIds?.length ?? 0) > 0 ||
57
+ (allowedDismissReviewIds?.length ?? 0) > 0;
58
+ if (!hasAllowedMutations && blockedErrors.length > 0) {
59
+ return {
60
+ repliedThreads: [],
61
+ resolvedThreads: [],
62
+ minimizedComments: [],
63
+ dismissedReviews: [],
64
+ errors: blockedErrors,
65
+ instructions: [BLOCKED_REVIEW_INSTRUCTION],
66
+ };
67
+ }
40
68
  // Iterate capability-checks and routes its generated commands. Direct apply
41
- // requests are user-directed: forward every supplied ID unchanged and let
69
+ // requests are user-directed: forward every remaining supplied ID unchanged and let
42
70
  // GitHub report whether each requested mutation is permitted or applicable.
43
71
  // Only generated durable-state commands carry `--adopt-existing-replies`.
44
72
  const result = await applyResolveOptions(prNumber, repo, {
45
73
  resolveThreadIds: opts.resolveThreadIds,
46
74
  replyThreadIds: opts.replyThreadIds,
47
- minimizeCommentIds: opts.minimizeCommentIds,
48
- dismissReviewIds: opts.dismissReviewIds,
75
+ minimizeCommentIds: allowedMinimizeCommentIds,
76
+ dismissReviewIds: allowedDismissReviewIds,
49
77
  dismissMessage: opts.dismissMessage,
50
78
  requireSha: opts.requireSha,
51
79
  ...(opts.adoptExistingReplies && { adoptExistingReplies: true }),
52
80
  }, ...(preflight ? [preflight] : []));
81
+ if (blockedErrors.length > 0) {
82
+ result.errors.push(...blockedErrors);
83
+ result.instructions = [...(result.instructions ?? []), BLOCKED_REVIEW_INSTRUCTION];
84
+ }
53
85
  const adopted = new Set(adoptedReplyThreads(result));
54
86
  let adoptedTranscripts;
55
87
  if (adopted.size) {
@@ -72,5 +104,8 @@ export async function runResolveMutate(opts) {
72
104
  return markReplySeen({ owner: repo.owner, repo: repo.name, pr: prNumber }, id, previousBody, currentBody ?? threadTranscriptBodies([previousBody, markedMessage]), markedMessage);
73
105
  }));
74
106
  }
107
+ if (result.resolvedThreads.length > 0) {
108
+ await pruneResolvedReviewThreads(stateKey, result.resolvedThreads);
109
+ }
75
110
  return result;
76
111
  }
@@ -0,0 +1,19 @@
1
+ export declare const BLOCKED_REVIEW_INSTRUCTION = "Resolve every unresolved inline thread belonging to the blocked review(s) first, then run a separate `apply review` command to dismiss/hide the review.";
2
+ export declare function collectReviewIdsToGuard(dismissReviewIds?: readonly string[], minimizeCommentIds?: readonly string[]): string[];
3
+ export declare function formatBlockedReviewErrors(blockedByReview: ReadonlyMap<string, string[]>): string[];
4
+ /**
5
+ * Determine which target review IDs still have unresolved inline threads.
6
+ *
7
+ * Uses local seen-marker tracking (`unresolvedInlineThreadIds`) so reviews whose
8
+ * inline threads were already resolved require zero GitHub calls. GitHub is only
9
+ * queried when local state still lists unresolved thread IDs (targeted `nodes(ids:)`
10
+ * lookup to detect out-of-band resolution) or when no local record exists yet.
11
+ */
12
+ export declare function resolveBlockedReviews(stateKey: {
13
+ owner: string;
14
+ repo: string;
15
+ pr: number;
16
+ }, prNumber: number, repo: {
17
+ owner: string;
18
+ name: string;
19
+ }, reviewIds: readonly string[]): Promise<Map<string, string[]>>;
@@ -0,0 +1,61 @@
1
+ import { checkThreadsStillUnresolved, findUnresolvedThreadsByReviewId, isReviewNodeId, } from "../github/review-unresolved-threads.mjs";
2
+ import { loadSeenMap, markReviewUnresolvedThreads } from "../state/seen-comments.mjs";
3
+ export const BLOCKED_REVIEW_INSTRUCTION = "Resolve every unresolved inline thread belonging to the blocked review(s) first, then run a separate `apply review` command to dismiss/hide the review.";
4
+ export function collectReviewIdsToGuard(dismissReviewIds, minimizeCommentIds) {
5
+ return [
6
+ ...new Set([...(dismissReviewIds ?? []), ...(minimizeCommentIds ?? []).filter(isReviewNodeId)]),
7
+ ];
8
+ }
9
+ export function formatBlockedReviewErrors(blockedByReview) {
10
+ return [...blockedByReview.entries()].map(([reviewId, threadIds]) => {
11
+ const noun = threadIds.length === 1 ? "thread remains" : "threads remain";
12
+ return `Refused to dismiss/hide review ${reviewId}: ${threadIds.length} unresolved inline ${noun} (${threadIds.join(", ")}). Resolve all inline threads first, then dismiss/hide the review in a separate command.`;
13
+ });
14
+ }
15
+ /**
16
+ * Determine which target review IDs still have unresolved inline threads.
17
+ *
18
+ * Uses local seen-marker tracking (`unresolvedInlineThreadIds`) so reviews whose
19
+ * inline threads were already resolved require zero GitHub calls. GitHub is only
20
+ * queried when local state still lists unresolved thread IDs (targeted `nodes(ids:)`
21
+ * lookup to detect out-of-band resolution) or when no local record exists yet.
22
+ */
23
+ export async function resolveBlockedReviews(stateKey, prNumber, repo, reviewIds) {
24
+ const seen = await loadSeenMap(stateKey);
25
+ const blocked = new Map();
26
+ const cachedWithUnresolved = new Map();
27
+ const coldReviewIds = [];
28
+ for (const reviewId of reviewIds) {
29
+ const raw = seen.get(reviewId)?.unresolvedInlineThreadIds;
30
+ if (!Array.isArray(raw)) {
31
+ coldReviewIds.push(reviewId);
32
+ continue;
33
+ }
34
+ const pending = raw.filter((id) => typeof id === "string");
35
+ if (pending.length > 0)
36
+ cachedWithUnresolved.set(reviewId, pending);
37
+ // Empty cached array means all inline threads were already resolved — zero GitHub calls.
38
+ }
39
+ if (cachedWithUnresolved.size > 0) {
40
+ const allPending = [...new Set([...cachedWithUnresolved.values()].flat())];
41
+ const stillUnresolved = await checkThreadsStillUnresolved(prNumber, repo, allPending);
42
+ const updates = [];
43
+ for (const [reviewId, pending] of cachedWithUnresolved) {
44
+ const remaining = pending.filter((id) => stillUnresolved.has(id));
45
+ if (remaining.length > 0)
46
+ blocked.set(reviewId, remaining);
47
+ if (remaining.length !== pending.length) {
48
+ updates.push(markReviewUnresolvedThreads(stateKey, reviewId, remaining));
49
+ }
50
+ }
51
+ await Promise.allSettled(updates);
52
+ }
53
+ if (coldReviewIds.length > 0) {
54
+ const coldBlocked = await findUnresolvedThreadsByReviewId(prNumber, repo, coldReviewIds);
55
+ await Promise.allSettled(coldReviewIds.map((reviewId) => markReviewUnresolvedThreads(stateKey, reviewId, coldBlocked.get(reviewId) ?? [])));
56
+ for (const [reviewId, threadIds] of coldBlocked) {
57
+ blocked.set(reviewId, threadIds);
58
+ }
59
+ }
60
+ return blocked;
61
+ }
@@ -10,6 +10,12 @@ export type ApproveCommands = (extra: number[]) => {
10
10
  * with its author and title, says what merging would do, and prints the commands that approve.
11
11
  */
12
12
  export declare function unlistedEscalation(target: PollSummaryItem, unlisted: PollSummaryItem[], rerunCommand: string | undefined, approve: ApproveCommands | undefined): StackPlan;
13
+ /**
14
+ * `--merge` with listed PRs leaves unlisted layers above the merge open. The
15
+ * caller may have listed only the bottom PR of a stack it was asked to merge whole, so the step
16
+ * names those layers and prints the command that lands them in the same merge.
17
+ */
18
+ export declare function unlistedAboveStep(above: PollSummaryItem[], rerunCommand: string | undefined, approve: ApproveCommands | undefined): string | undefined;
13
19
  export declare const list: (items: PollSummaryItem[]) => string;
14
20
  /** Layers that joined the stack after the merge was requested: the request never covered them. */
15
21
  export declare function addedLayersEscalation(result: PollSummaryResult, open: PollSummaryItem[], scope: StackMergeScope, rerunCommand?: string): StackPlan | undefined;
@@ -22,6 +22,23 @@ export function unlistedEscalation(target, unlisted, rerunCommand, approve) {
22
22
  : `They either approve it, and you ${listAll}, or wait for ${owner}.`;
23
23
  return escalation(`\`unowned-stack-layers\`: merging PR #${target.pr} also merges ${describeLayers(unlisted)}, which you did not list as yours. Nothing was merged, and never merge only #${target.pr} while leaving ${them} open. If the user's request already covers ${them} (they asked for the whole stack, or for every layer up to #${target.pr}), ${listAll} now. Otherwise stop and tell the user that merging #${target.pr} also merges ${list(unlisted)}. ${approval}`);
24
24
  }
25
+ /**
26
+ * `--merge` with listed PRs leaves unlisted layers above the merge open. The
27
+ * caller may have listed only the bottom PR of a stack it was asked to merge whole, so the step
28
+ * names those layers and prints the command that lands them in the same merge.
29
+ */
30
+ export function unlistedAboveStep(above, rerunCommand, approve) {
31
+ const unlisted = above.filter((item) => !item.owned);
32
+ if (unlisted.length === 0)
33
+ return undefined;
34
+ const one = unlisted.length === 1;
35
+ const names = list(unlisted);
36
+ const commands = approve?.(unlisted.map((item) => item.pr));
37
+ const instead = commands
38
+ ? `run \`${commands.listed}\` instead (or \`${commands.whole}\`; the stack number owns every layer)`
39
+ : `rerun ${stackRerunTarget(rerunCommand)} with ${one ? "it" : "them"} listed after \`stack\` instead`;
40
+ return `${names} ${one ? "sits" : "sit"} above this merge and ${one ? "is" : "are"} not listed after \`stack\`, so the merge below leaves ${one ? "it" : "them"} open and GitHub retargets ${one ? "it" : "them"} onto the trunk, which needs another rebase and CI run. "Not listed" is about this command line, not authorship. If the user asked to merge the whole stack or ${names} too, do not run the merge below: ${instead}, which lands every layer in one command. Otherwise continue with the merge.`;
41
+ }
25
42
  export const list = (items) => items.map((i) => `#${i.pr}`).join(", ");
26
43
  /** Layers that joined the stack after the merge was requested: the request never covered them. */
27
44
  export function addedLayersEscalation(result, open, scope, rerunCommand) {
@@ -4,7 +4,7 @@ import { appendAutonomousInstructions, idleWaitPlan, appendHumanHandoffInstructi
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
6
  import { MERGE_CONFLICT_NOTE, trunkPreCheck } from "./stack-merge-trunk-check.mjs";
7
- import { addedLayersEscalation, escalation, list, scopeDone, unlistedEscalation, } from "./stack-merge-escalations.mjs";
7
+ import { addedLayersEscalation, escalation, list, scopeDone, unlistedAboveStep, unlistedEscalation, } from "./stack-merge-escalations.mjs";
8
8
  import { splitStackWork, stackRerunTarget } from "./stack-work.mjs";
9
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.";
10
10
  /**
@@ -23,7 +23,7 @@ export function planStackMerge(result, scope, rerunCommand, approve) {
23
23
  const prefix = readyPrefix(result, true);
24
24
  const top = prefix.at(-1);
25
25
  if (top)
26
- return mergePlan(result, top, scope, rerunCommand);
26
+ return mergePlan(result, top, scope, rerunCommand, approve);
27
27
  const bottom = open.reduce((low, item) => stackPosition(item) < stackPosition(low) ? item : low);
28
28
  if (!bottom.owned && isStackLayerReady(bottom) && open.some((item) => item.owned)) {
29
29
  const above = open.filter((item) => item.owned).at(-1);
@@ -48,11 +48,11 @@ export function planStackMerge(result, scope, rerunCommand, approve) {
48
48
  if (unowned.length > 0)
49
49
  return unlistedEscalation(target, unowned, rerunCommand, approve);
50
50
  return readyPrefix(result, false).some((item) => item.pr === target.pr)
51
- ? mergePlan(result, target, scope, rerunCommand)
51
+ ? mergePlan(result, target, scope, rerunCommand, approve)
52
52
  : undefined;
53
53
  }
54
54
  /** The one merge for `top`, which lands it and every unmerged layer below it. */
55
- function mergePlan(result, top, scope, rerunCommand) {
55
+ function mergePlan(result, top, scope, rerunCommand, approve) {
56
56
  const stack = top.stack;
57
57
  const outside = aboveThroughTarget(result, scope);
58
58
  const open = openLayers(result);
@@ -78,8 +78,12 @@ function mergePlan(result, top, scope, rerunCommand) {
78
78
  const waiting = idleWaitPlan(lands);
79
79
  return { ...waiting, instructions: [`1. ${first.unavailable}`] };
80
80
  }
81
- const check = trunkPreCheck(result, top);
82
- const instructions = check ? [`1. ${check}`, `2. ${first.text}`] : [`1. ${first.text}`];
81
+ const steps = [
82
+ partial && scope.kind === "all" ? unlistedAboveStep(above, rerunCommand, approve) : undefined,
83
+ trunkPreCheck(result, top),
84
+ first.text,
85
+ ].filter((step) => step !== undefined);
86
+ const instructions = steps.map((step, index) => `${index + 1}. ${step}`);
83
87
  appendAutonomousInstructions(instructions, work.sessions, hasListedOwnership(result));
84
88
  const handoffs = findHumanHandoffs(result);
85
89
  if (handoffs)
@@ -134,20 +134,20 @@ function buildBulkMutation(replyIds, resolveIds, minimizeIds, dismissIds, dismis
134
134
  for (let i = 0; i < resolveIds.length; i++) {
135
135
  ops.push(` r${i}: resolveReviewThread(input: { threadId: ${JSON.stringify(resolveIds[i])} }) { thread { isResolved } }`);
136
136
  }
137
- for (let i = 0; i < minimizeIds.length; i++) {
138
- ops.push(` m${i}: minimizeComment(input: { subjectId: ${JSON.stringify(minimizeIds[i])}, classifier: RESOLVED }) { minimizedComment { isMinimized } }`);
139
- }
140
137
  for (let i = 0; i < dismissIds.length; i++) {
141
138
  ops.push(` d${i}: dismissPullRequestReview(input: { pullRequestReviewId: ${JSON.stringify(dismissIds[i])}, message: ${JSON.stringify(dismissMessage)} }) { pullRequestReview { state } }`);
142
139
  }
140
+ for (let i = 0; i < minimizeIds.length; i++) {
141
+ ops.push(` m${i}: minimizeComment(input: { subjectId: ${JSON.stringify(minimizeIds[i])}, classifier: RESOLVED }) { minimizedComment { isMinimized } }`);
142
+ }
143
143
  return `mutation BulkApply {\n${ops.join("\n")}\n}`;
144
144
  }
145
145
  async function bulkApply(replyIds, resolveIds, minimizeIds, dismissIds, dismissMessage, result, context, firstChunkEvidence) {
146
146
  const allOps = [
147
147
  ...replyIds.map((id) => ({ kind: "p", id })),
148
148
  ...resolveIds.map((id) => ({ kind: "r", id })),
149
- ...minimizeIds.map((id) => ({ kind: "m", id })),
150
149
  ...dismissIds.map((id) => ({ kind: "d", id })),
150
+ ...minimizeIds.map((id) => ({ kind: "m", id })),
151
151
  ];
152
152
  for (let i = 0; i < allOps.length; i += BULK_CHUNK_SIZE) {
153
153
  const chunk = allOps.slice(i, i + BULK_CHUNK_SIZE);
@@ -4,5 +4,5 @@ interface StateKey {
4
4
  repo: string;
5
5
  pr: number;
6
6
  }
7
- export declare function markReviewInlineThreadMarkers(key: StateKey, threads: readonly ReviewThread[]): Promise<void>;
7
+ export declare function markReviewInlineThreadMarkers(key: StateKey, threads: readonly ReviewThread[], reviewIds?: readonly string[]): Promise<void>;
8
8
  export {};
@@ -1,18 +1,32 @@
1
- import { markReviewInlineThreads } from "../state/seen-comments.mjs";
2
- function groupInlineThreadIdsByReview(threads) {
1
+ import { markReviewInlineThreads, markReviewUnresolvedThreads } from "../state/seen-comments.mjs";
2
+ function groupInlineThreadsByReview(threads) {
3
3
  const byReview = new Map();
4
4
  for (const thread of threads) {
5
5
  if (thread.reviewId === undefined)
6
6
  continue;
7
- const ids = byReview.get(thread.reviewId) ?? new Set();
8
- ids.add(thread.id);
9
- byReview.set(thread.reviewId, ids);
7
+ const entry = byReview.get(thread.reviewId) ?? {
8
+ all: new Set(),
9
+ unresolved: new Set(),
10
+ };
11
+ entry.all.add(thread.id);
12
+ if (thread.isResolved !== true)
13
+ entry.unresolved.add(thread.id);
14
+ byReview.set(thread.reviewId, entry);
10
15
  }
11
- return new Map([...byReview.entries()].map(([reviewId, ids]) => [
16
+ return new Map([...byReview.entries()].map(([reviewId, entry]) => [
12
17
  reviewId,
13
- [...ids].sort((a, b) => a.localeCompare(b)),
18
+ {
19
+ all: [...entry.all].sort((a, b) => a.localeCompare(b)),
20
+ unresolved: [...entry.unresolved].sort((a, b) => a.localeCompare(b)),
21
+ },
14
22
  ]));
15
23
  }
16
- export async function markReviewInlineThreadMarkers(key, threads) {
17
- await Promise.allSettled([...groupInlineThreadIdsByReview(threads)].map(([reviewId, inlineThreadIds]) => markReviewInlineThreads(key, reviewId, inlineThreadIds)));
24
+ export async function markReviewInlineThreadMarkers(key, threads, reviewIds = []) {
25
+ const grouped = groupInlineThreadsByReview(threads);
26
+ const writes = [...grouped.entries()].map(([reviewId, entry]) => markReviewInlineThreads(key, reviewId, entry.all, entry.unresolved));
27
+ for (const reviewId of new Set(reviewIds)) {
28
+ if (!grouped.has(reviewId))
29
+ writes.push(markReviewUnresolvedThreads(key, reviewId, []));
30
+ }
31
+ await Promise.allSettled(writes);
18
32
  }
@@ -0,0 +1,28 @@
1
+ import type { Review } from "../types.mts";
2
+ export interface ReviewOrderingEntry {
3
+ id: string;
4
+ author: string;
5
+ state: "APPROVED" | "CHANGES_REQUESTED" | "DISMISSED" | "COMMENTED";
6
+ body?: string;
7
+ createdAtUnix?: number;
8
+ }
9
+ /**
10
+ * Return the IDs of `APPROVED` reviews that are no longer the latest review from
11
+ * their author — either because the same author posted a later `APPROVED` review
12
+ * or because they posted a later substantive review (`CHANGES_REQUESTED`,
13
+ * `DISMISSED`, or non-empty `COMMENTED`). Empty-body `COMMENTED` reviews (GitHub's
14
+ * wrapper for inline thread replies) never supersede an approval.
15
+ */
16
+ export declare function findSupersededApprovalIds(input: {
17
+ reviews: readonly ReviewOrderingEntry[];
18
+ latestReviews?: ReadonlyArray<{
19
+ login: string;
20
+ state: string;
21
+ }>;
22
+ precomputedSupersededIds?: ReadonlySet<string>;
23
+ }): Set<string>;
24
+ export declare function reviewOrderingEntriesFromReviews(input: {
25
+ approvedReviews: readonly Review[];
26
+ changesRequestedReviews: readonly Review[];
27
+ reviewSummaries: readonly Review[];
28
+ }): ReviewOrderingEntry[];
@@ -0,0 +1,99 @@
1
+ function normalizeAuthor(author) {
2
+ const normalized = (author ?? "").trim().toLowerCase();
3
+ return normalized === "unknown" ? "" : normalized;
4
+ }
5
+ /**
6
+ * Return the IDs of `APPROVED` reviews that are no longer the latest review from
7
+ * their author — either because the same author posted a later `APPROVED` review
8
+ * or because they posted a later substantive review (`CHANGES_REQUESTED`,
9
+ * `DISMISSED`, or non-empty `COMMENTED`). Empty-body `COMMENTED` reviews (GitHub's
10
+ * wrapper for inline thread replies) never supersede an approval.
11
+ */
12
+ export function findSupersededApprovalIds(input) {
13
+ const superseded = new Set(input.precomputedSupersededIds);
14
+ const approvalsByAuthor = new Map();
15
+ const latestNonApprovalAtByAuthor = new Map();
16
+ input.reviews.forEach((review, order) => {
17
+ const author = normalizeAuthor(review.author);
18
+ if (!author)
19
+ return;
20
+ const createdAtUnix = review.createdAtUnix ?? 0;
21
+ if (review.state === "APPROVED") {
22
+ const list = approvalsByAuthor.get(author) ?? [];
23
+ list.push({ id: review.id, createdAtUnix, order });
24
+ approvalsByAuthor.set(author, list);
25
+ return;
26
+ }
27
+ if (review.state === "COMMENTED" && (review.body ?? "").trim() === "")
28
+ return;
29
+ const prev = latestNonApprovalAtByAuthor.get(author);
30
+ if (prev === undefined || createdAtUnix > prev) {
31
+ latestNonApprovalAtByAuthor.set(author, createdAtUnix);
32
+ }
33
+ });
34
+ const latestOpinionatedState = new Map();
35
+ for (const entry of input.latestReviews ?? []) {
36
+ const author = normalizeAuthor(entry.login);
37
+ if (author)
38
+ latestOpinionatedState.set(author, entry.state);
39
+ }
40
+ for (const [author, approvals] of approvalsByAuthor) {
41
+ const precomputed = input.precomputedSupersededIds;
42
+ const isBetterLatest = (candidate, current) => {
43
+ if (candidate.createdAtUnix !== current.createdAtUnix) {
44
+ return candidate.createdAtUnix > current.createdAtUnix;
45
+ }
46
+ const candPre = precomputed?.has(candidate.id) === true;
47
+ const curPre = precomputed?.has(current.id) === true;
48
+ if (candPre !== curPre)
49
+ return !candPre;
50
+ return candidate.order > current.order;
51
+ };
52
+ let latest = approvals[0];
53
+ for (let i = 1; i < approvals.length; i++) {
54
+ const candidate = approvals[i];
55
+ if (isBetterLatest(candidate, latest)) {
56
+ latest = candidate;
57
+ }
58
+ }
59
+ const latestNonApprovalAt = latestNonApprovalAtByAuthor.get(author);
60
+ const opinionatedState = latestOpinionatedState.get(author);
61
+ const nonApprovalLatest = opinionatedState === "CHANGES_REQUESTED" || opinionatedState === "DISMISSED";
62
+ for (const approval of approvals) {
63
+ if (approval.id !== latest.id) {
64
+ superseded.add(approval.id);
65
+ continue;
66
+ }
67
+ if ((latestNonApprovalAt !== undefined && latestNonApprovalAt > approval.createdAtUnix) ||
68
+ nonApprovalLatest) {
69
+ superseded.add(approval.id);
70
+ }
71
+ }
72
+ }
73
+ return superseded;
74
+ }
75
+ export function reviewOrderingEntriesFromReviews(input) {
76
+ return [
77
+ ...input.approvedReviews.map((r) => ({
78
+ id: r.id,
79
+ author: r.author,
80
+ state: "APPROVED",
81
+ body: r.body,
82
+ createdAtUnix: r.createdAtUnix,
83
+ })),
84
+ ...input.changesRequestedReviews.map((r) => ({
85
+ id: r.id,
86
+ author: r.author,
87
+ state: "CHANGES_REQUESTED",
88
+ body: r.body,
89
+ createdAtUnix: r.createdAtUnix,
90
+ })),
91
+ ...input.reviewSummaries.map((r) => ({
92
+ id: r.id,
93
+ author: r.author,
94
+ state: "COMMENTED",
95
+ body: r.body,
96
+ createdAtUnix: r.createdAtUnix,
97
+ })),
98
+ ];
99
+ }
@@ -24,6 +24,7 @@ export declare const configSchema: z.ZodObject<{
24
24
  "stall-timeout-minutes": z.ZodDefault<z.ZodNumber>;
25
25
  "ready-delay-minutes": z.ZodDefault<z.ZodNumber>;
26
26
  "minimize-approvals": z.ZodDefault<z.ZodBoolean>;
27
+ "minimize-superseded-approvals": z.ZodDefault<z.ZodBoolean>;
27
28
  "minimize-comments": z.ZodDefault<z.ZodEnum<{
28
29
  all: "all";
29
30
  bots: "bots";
@@ -114,6 +115,7 @@ export declare const configFileSchema: z.ZodObject<{
114
115
  "stall-timeout-minutes": z.ZodDefault<z.ZodNumber>;
115
116
  "ready-delay-minutes": z.ZodDefault<z.ZodNumber>;
116
117
  "minimize-approvals": z.ZodDefault<z.ZodBoolean>;
118
+ "minimize-superseded-approvals": z.ZodDefault<z.ZodBoolean>;
117
119
  "minimize-comments": z.ZodDefault<z.ZodEnum<{
118
120
  all: "all";
119
121
  bots: "bots";
@@ -117,6 +117,7 @@ export const configSchema = z.strictObject({
117
117
  "stall-timeout-minutes": nonNegative().default(60),
118
118
  "ready-delay-minutes": nonNegative().default(0),
119
119
  "minimize-approvals": z.boolean().default(false),
120
+ "minimize-superseded-approvals": z.boolean().default(true),
120
121
  "minimize-comments": z.enum(["all", "bots", "none"]).default("bots"),
121
122
  "behind-base-hint": z.string().default(""),
122
123
  "review-output-max-chars": z.number().int().nonnegative().default(50000),
@@ -4,6 +4,7 @@ import { headFreshAtUnix } from "./head-freshness.mjs";
4
4
  import { headPushUnixFromCheckNodes } from "./queue-removal-freshness.mjs";
5
5
  import { contextNodes } from "./batch-response.mjs";
6
6
  import { buildPrActivitySummary } from "./activity.mjs";
7
+ import { findSupersededApprovalIds } from "../comments/superseded-approvals.mjs";
7
8
  import { parseBranchProtection } from "./branch-protection.mjs";
8
9
  import { readAllowedMergeMethods } from "../config/merge-method.mjs";
9
10
  import { parseAutoMergeRequest, parseBranchRules, parseLatestMergeQueueRemoval, parseMergeQueueEntry, parseStack, } from "./batch-parsers-rules.mjs";
@@ -13,6 +14,7 @@ function parseReviewNode(r) {
13
14
  author: r.author?.login ?? "unknown",
14
15
  authorType: mapAuthorType(r.author?.__typename, r.author?.login),
15
16
  ...(r.authorAssociation !== undefined && { authorAssociation: r.authorAssociation }),
17
+ ...("isMinimized" in r && r.isMinimized === true && { isMinimized: true }),
16
18
  viewerCanMinimize: "viewerCanMinimize" in r && r.viewerCanMinimize === true,
17
19
  body: r.body,
18
20
  createdAtUnix: r.createdAt ? parseCreatedAt(r.createdAt) : 0,
@@ -107,6 +109,34 @@ export function parseRawPr(raw, rawThreadPages, rawCommentNodes, rawReviewNodes,
107
109
  const approvedReviews = rawApprovedReviewNodes
108
110
  .filter((r) => !r.isMinimized)
109
111
  .map((r) => parseReviewNode(r));
112
+ const supersededApprovalIds = [
113
+ ...findSupersededApprovalIds({
114
+ reviews: [
115
+ ...rawApprovedReviewNodes.map((r) => ({
116
+ id: r.id,
117
+ author: r.author?.login ?? "unknown",
118
+ state: "APPROVED",
119
+ body: r.body,
120
+ createdAtUnix: r.createdAt ? parseCreatedAt(r.createdAt) : 0,
121
+ })),
122
+ ...rawReviewNodes.map((r) => ({
123
+ id: r.id,
124
+ author: r.author?.login ?? "unknown",
125
+ state: "CHANGES_REQUESTED",
126
+ body: r.body,
127
+ createdAtUnix: r.createdAt ? parseCreatedAt(r.createdAt) : 0,
128
+ })),
129
+ ...rawReviewSummaryNodes.map((r) => ({
130
+ id: r.id,
131
+ author: r.author?.login ?? "unknown",
132
+ state: r.state === "DISMISSED" ? "DISMISSED" : "COMMENTED",
133
+ body: r.body,
134
+ createdAtUnix: r.createdAt ? parseCreatedAt(r.createdAt) : 0,
135
+ })),
136
+ ],
137
+ latestReviews,
138
+ }),
139
+ ].filter((id) => approvedReviews.some((review) => review.id === id));
110
140
  const checks = parseCheckNodes(rawCheckNodes);
111
141
  const queueHead = raw.mergeQueueEntry?.headCommit;
112
142
  const removedQueueHead = raw.mergeQueueRemovals?.nodes[0]?.beforeCommit;
@@ -164,6 +194,7 @@ export function parseRawPr(raw, rawThreadPages, rawCommentNodes, rawReviewNodes,
164
194
  changesRequestedReviews,
165
195
  reviewSummaries,
166
196
  approvedReviews,
197
+ ...(supersededApprovalIds.length > 0 && { supersededApprovalIds }),
167
198
  checks,
168
199
  branchProtection: parseBranchProtection(raw),
169
200
  ...(allowedMergeMethods && { allowedMergeMethods }),
@@ -216,6 +216,8 @@ export interface RawComment {
216
216
  }
217
217
  export interface RawReview {
218
218
  id: string;
219
+ isMinimized?: boolean;
220
+ viewerCanMinimize?: boolean;
219
221
  authorAssociation?: CommentAuthorAssociation;
220
222
  author: RawAuthor | null;
221
223
  body: string;
@@ -226,6 +228,7 @@ export interface RawReview {
226
228
  }
227
229
  export interface RawReviewSummary {
228
230
  id: string;
231
+ state?: string;
229
232
  isMinimized: boolean;
230
233
  viewerCanMinimize: boolean;
231
234
  authorAssociation?: CommentAuthorAssociation;
@@ -1,10 +1,10 @@
1
1
  import { type RateLimitInfo, type RepoInfo } from "./client.mts";
2
- import type { RawComment, RawPr, RawReviewSummary, RawThread } from "./batch-raw-types.mts";
2
+ import type { RawComment, RawPr, RawReview, RawReviewSummary, RawThread } from "./batch-raw-types.mts";
3
3
  /** The nodes of a viewer-free `BatchPr` read whose viewer fields are still missing. */
4
4
  export interface ViewerTargets {
5
5
  threads: RawThread[];
6
6
  comments: RawComment[];
7
- reviews: RawReviewSummary[];
7
+ reviews: Array<RawReview | RawReviewSummary>;
8
8
  }
9
9
  export interface BatchViewer {
10
10
  login: string | null;
@@ -44,7 +44,7 @@ async function fetchGraphqlPrBatch(pr, repo, opts = {}, reuse) {
44
44
  (await applyBatchViewer(repo, raw, {
45
45
  threads: threadPages.threads,
46
46
  comments: paged.comments,
47
- reviews: [...paged.reviewSummaries, ...paged.approvedReviews],
47
+ reviews: [...paged.changesRequested, ...paged.reviewSummaries, ...paged.approvedReviews],
48
48
  }));
49
49
  // The topology's viewer login and administer bit come from this snapshot's viewer read.
50
50
  if (viewer) {
@@ -99,6 +99,8 @@ query BatchPrPage(
99
99
  }
100
100
  nodes {
101
101
  id
102
+ isMinimized
103
+ viewerCanMinimize
102
104
  authorAssociation
103
105
  author {
104
106
  __typename
@@ -111,14 +113,18 @@ query BatchPrPage(
111
113
  }
112
114
  }
113
115
  }
114
- reviewSummaries: reviews(states: COMMENTED, last: 50, before: $reviewSummariesCursor)
115
- @include(if: $includeReviewSummaries) {
116
+ reviewSummaries: reviews(
117
+ states: [COMMENTED, DISMISSED]
118
+ last: 50
119
+ before: $reviewSummariesCursor
120
+ ) @include(if: $includeReviewSummaries) {
116
121
  pageInfo {
117
122
  hasPreviousPage
118
123
  startCursor
119
124
  }
120
125
  nodes {
121
126
  id
127
+ state
122
128
  isMinimized
123
129
  viewerCanMinimize
124
130
  authorAssociation