pr-shepherd 2.1.0 → 2.2.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 (181) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +28 -22
  3. package/bin/api.d.mts +10 -2
  4. package/bin/api.mjs +30 -6
  5. package/bin/checks/pending-deployments.d.mts +10 -0
  6. package/bin/checks/pending-deployments.mjs +66 -0
  7. package/bin/checks/run-workflow-paths.d.mts +7 -0
  8. package/bin/checks/run-workflow-paths.mjs +19 -0
  9. package/bin/checks/triage.mjs +3 -2
  10. package/bin/checks/unreported-required.d.mts +11 -1
  11. package/bin/checks/unreported-required.mjs +8 -3
  12. package/bin/checks/workflow-concurrency.d.mts +9 -0
  13. package/bin/checks/workflow-concurrency.mjs +84 -0
  14. package/bin/checks/workflow-path.d.mts +2 -0
  15. package/bin/checks/workflow-path.mjs +4 -0
  16. package/bin/cli/arg-flags.mjs +3 -0
  17. package/bin/cli/clean-handler.mjs +1 -1
  18. package/bin/cli/default-poll.mjs +1 -0
  19. package/bin/cli/handlers.mjs +2 -0
  20. package/bin/cli/help-command-pages.d.mts +5 -4
  21. package/bin/cli/help-command-pages.mjs +2 -1
  22. package/bin/cli/help-iterate-poll-pages.d.mts +3 -3
  23. package/bin/cli/help-iterate-poll-pages.mjs +10 -2
  24. package/bin/cli/help-top-page.d.mts +1 -1
  25. package/bin/cli/help-top-page.mjs +2 -2
  26. package/bin/cli/help.d.mts +6 -5
  27. package/bin/cli/in-progress-run-format.d.mts +3 -0
  28. package/bin/cli/in-progress-run-format.mjs +14 -0
  29. package/bin/cli/iterate-activity-formatter.d.mts +2 -0
  30. package/bin/cli/iterate-activity-formatter.mjs +11 -0
  31. package/bin/cli/iterate-flags.d.mts +3 -0
  32. package/bin/cli/iterate-flags.mjs +18 -1
  33. package/bin/cli/iterate-formatter.mjs +2 -1
  34. package/bin/cli/iterate-lean.mjs +2 -0
  35. package/bin/cli/pending-deployments-format.d.mts +5 -0
  36. package/bin/cli/pending-deployments-format.mjs +19 -0
  37. package/bin/cli/poll-handler.d.mts +1 -1
  38. package/bin/cli/poll-handler.mjs +33 -10
  39. package/bin/cli/poll-targets.mjs +2 -0
  40. package/bin/cli/stack-merge-args.d.mts +10 -0
  41. package/bin/cli/stack-merge-args.mjs +27 -0
  42. package/bin/cli/stack-overview.d.mts +1 -0
  43. package/bin/cli/stack-overview.mjs +5 -1
  44. package/bin/cli/stalled-check-format.d.mts +3 -0
  45. package/bin/cli/stalled-check-format.mjs +23 -0
  46. package/bin/cli/suggestion-renderer.mjs +6 -0
  47. package/bin/cli/triage-formatter.mjs +14 -0
  48. package/bin/commands/check.mjs +7 -2
  49. package/bin/commands/clean.d.mts +1 -1
  50. package/bin/commands/clean.mjs +7 -0
  51. package/bin/commands/iterate/check-follow-up.d.mts +9 -0
  52. package/bin/commands/iterate/check-follow-up.mjs +34 -0
  53. package/bin/commands/iterate/ci-start-stall.d.mts +23 -0
  54. package/bin/commands/iterate/ci-start-stall.mjs +33 -0
  55. package/bin/commands/iterate/duration-approx.d.mts +2 -0
  56. package/bin/commands/iterate/duration-approx.mjs +8 -0
  57. package/bin/commands/iterate/escalate.d.mts +8 -17
  58. package/bin/commands/iterate/escalate.mjs +19 -48
  59. package/bin/commands/iterate/helpers.mjs +1 -0
  60. package/bin/commands/iterate/in-progress-runs.d.mts +10 -0
  61. package/bin/commands/iterate/in-progress-runs.mjs +120 -0
  62. package/bin/commands/iterate/index.mjs +12 -6
  63. package/bin/commands/iterate/merge-plan.d.mts +2 -0
  64. package/bin/commands/iterate/merge-plan.mjs +2 -1
  65. package/bin/commands/iterate/merge-state.d.mts +2 -0
  66. package/bin/commands/iterate/merge-state.mjs +8 -21
  67. package/bin/commands/iterate/native-stack-rebase.d.mts +3 -2
  68. package/bin/commands/iterate/native-stack-rebase.mjs +32 -11
  69. package/bin/commands/iterate/queue-removal.d.mts +19 -0
  70. package/bin/commands/iterate/queue-removal.mjs +64 -0
  71. package/bin/commands/iterate/render.d.mts +2 -1
  72. package/bin/commands/iterate/render.mjs +4 -1
  73. package/bin/commands/iterate/stack-boundary.d.mts +17 -0
  74. package/bin/commands/iterate/stack-boundary.mjs +95 -0
  75. package/bin/commands/iterate/stall-repair.d.mts +17 -0
  76. package/bin/commands/iterate/stall-repair.mjs +25 -0
  77. package/bin/commands/iterate/stall.d.mts +1 -1
  78. package/bin/commands/iterate/stall.mjs +27 -18
  79. package/bin/commands/iterate/state-unavailable.d.mts +8 -0
  80. package/bin/commands/iterate/state-unavailable.mjs +23 -0
  81. package/bin/commands/iterate/triage-loop-instruction.mjs +1 -1
  82. package/bin/commands/iterate/triage.mjs +41 -74
  83. package/bin/commands/iterate/unreported-required.d.mts +5 -2
  84. package/bin/commands/iterate/unreported-required.mjs +13 -8
  85. package/bin/commands/iterate/workflow-files.d.mts +27 -0
  86. package/bin/commands/iterate/workflow-files.mjs +85 -0
  87. package/bin/commands/poll-summary-explicit-instructions.mjs +15 -1
  88. package/bin/commands/poll-summary-instructions.d.mts +4 -3
  89. package/bin/commands/poll-summary-instructions.mjs +60 -22
  90. package/bin/commands/poll-summary.mjs +38 -10
  91. package/bin/commands/poll.mjs +4 -2
  92. package/bin/commands/stack-drain.d.mts +4 -4
  93. package/bin/commands/stack-drain.mjs +19 -113
  94. package/bin/commands/stack-handoffs.d.mts +3 -3
  95. package/bin/commands/stack-handoffs.mjs +8 -8
  96. package/bin/commands/stack-lower-ready-note.d.mts +6 -0
  97. package/bin/commands/stack-lower-ready-note.mjs +35 -0
  98. package/bin/commands/stack-merge-escalations.d.mts +17 -0
  99. package/bin/commands/stack-merge-escalations.mjs +57 -0
  100. package/bin/commands/stack-merge-plan.d.mts +10 -0
  101. package/bin/commands/stack-merge-plan.mjs +132 -0
  102. package/bin/commands/stack-merge-scope.d.mts +42 -0
  103. package/bin/commands/stack-merge-scope.mjs +113 -0
  104. package/bin/commands/stack-ownership.d.mts +25 -0
  105. package/bin/commands/stack-ownership.mjs +85 -0
  106. package/bin/commands/stack-stall.d.mts +2 -0
  107. package/bin/commands/stack-stall.mjs +25 -3
  108. package/bin/commands/stack-targets-error.d.mts +16 -0
  109. package/bin/commands/stack-targets-error.mjs +44 -0
  110. package/bin/commands/stack-targets.d.mts +30 -0
  111. package/bin/commands/stack-targets.mjs +121 -0
  112. package/bin/commands/stack-work.d.mts +4 -3
  113. package/bin/commands/stack-work.mjs +7 -4
  114. package/bin/commands/tick.mjs +14 -2
  115. package/bin/config/renames.mjs +1 -1
  116. package/bin/config/schema.d.mts +4 -0
  117. package/bin/config/schema.mjs +2 -0
  118. package/bin/github/batch-parse-suites.d.mts +4 -1
  119. package/bin/github/batch-parse-suites.mjs +15 -3
  120. package/bin/github/batch-raw-types.d.mts +6 -0
  121. package/bin/github/gql/commit-check-suites.gql +6 -0
  122. package/bin/github/gql/poll-summary-fragment.gql +6 -0
  123. package/bin/github/poll-summary-command.d.mts +15 -1
  124. package/bin/github/poll-summary-command.mjs +39 -3
  125. package/bin/github/poll-summary-projector.d.mts +1 -1
  126. package/bin/github/poll-summary-projector.mjs +1 -4
  127. package/bin/github/poll-summary-raw.d.mts +6 -0
  128. package/bin/github/poll-summary-route.mjs +4 -1
  129. package/bin/github/poll-summary.mjs +10 -3
  130. package/bin/github/rest-batch-read.mjs +17 -6
  131. package/bin/github/rest-batch-snapshot.d.mts +2 -2
  132. package/bin/github/rest-batch-snapshot.mjs +3 -0
  133. package/bin/github/rest-check-read.d.mts +1 -18
  134. package/bin/github/rest-check-read.mjs +1 -2
  135. package/bin/github/rest-stack-read.d.mts +9 -0
  136. package/bin/github/rest-stack-read.mjs +40 -0
  137. package/bin/github/rest-suite-types.d.mts +23 -0
  138. package/bin/github/rest-suite-types.mjs +1 -0
  139. package/bin/github/rest-summary-read.mjs +2 -0
  140. package/bin/mcp/server.mjs +29 -3
  141. package/bin/pr-reference.d.mts +2 -0
  142. package/bin/pr-reference.mjs +1 -1
  143. package/bin/reporters/agent.mjs +3 -0
  144. package/bin/state/check-follow-up.d.mts +30 -0
  145. package/bin/state/check-follow-up.mjs +51 -0
  146. package/bin/state/ci-start-follow-up.d.mts +14 -0
  147. package/bin/state/ci-start-follow-up.mjs +21 -0
  148. package/bin/state/queue-removal-follow-up.d.mts +20 -0
  149. package/bin/state/queue-removal-follow-up.mjs +23 -0
  150. package/bin/state/signature-marker.d.mts +10 -0
  151. package/bin/state/signature-marker.mjs +28 -0
  152. package/bin/state/stack-merge-approval.d.mts +26 -0
  153. package/bin/state/stack-merge-approval.mjs +39 -0
  154. package/bin/state/stall-repair.d.mts +16 -0
  155. package/bin/state/stall-repair.mjs +47 -0
  156. package/bin/types/activity.d.mts +2 -1
  157. package/bin/types/escalate.d.mts +9 -2
  158. package/bin/types/github.d.mts +18 -0
  159. package/bin/types/in-progress-run.d.mts +20 -0
  160. package/bin/types/in-progress-run.mjs +1 -0
  161. package/bin/types/iterate.d.mts +22 -1
  162. package/bin/types/poll-summary.d.mts +18 -1
  163. package/bin/types/report.d.mts +5 -1
  164. package/bin/types.d.mts +1 -0
  165. package/bin/types.mjs +1 -0
  166. package/package.json +2 -2
  167. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  168. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  169. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  170. package/plugins/pr-shepherd/.mcp.json +1 -1
  171. package/plugins/pr-shepherd/package-lock.json +4 -4
  172. package/plugins/pr-shepherd/package.json +1 -1
  173. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +8 -7
  174. package/plugins/pr-shepherd/skills/pr-shepherd/references/check-follow-up.md +14 -0
  175. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-failure-triage.md +6 -5
  176. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-start-stall.md +15 -0
  177. package/plugins/pr-shepherd/skills/pr-shepherd/references/create-a-pr.md +4 -1
  178. package/plugins/pr-shepherd/skills/pr-shepherd/references/mcp-fallback.md +1 -1
  179. package/plugins/pr-shepherd/skills/pr-shepherd/references/merge-queue-ejection.md +6 -5
  180. package/plugins/pr-shepherd/skills/pr-shepherd/references/required-checks-unreported.md +16 -0
  181. package/pr-shepherd.schema.json +11 -0
@@ -3,6 +3,9 @@ import { readStallState, writeStallState } from "../../state/iterate-stall.mjs";
3
3
  import { toAgentThread, toAgentComment, toAgentStalledCheck } from "../../reporters/agent.mjs";
4
4
  import { buildEscalateSuggestion, buildEscalateHumanMessage, formatDurationApprox, } from "./escalate.mjs";
5
5
  import { checksWithActionableAnnotations } from "../check-annotations.mjs";
6
+ import { planCiStartInvestigation } from "./ci-start-stall.mjs";
7
+ import { stateUnavailableResult } from "./state-unavailable.mjs";
8
+ import { planStallRepair } from "./stall-repair.mjs";
6
9
  import { formatPrUrl } from "../../pr-reference.mjs";
7
10
  function pendingReviewCommandsFromResult(result) {
8
11
  if (result.action !== "triage")
@@ -64,7 +67,7 @@ function computeStallFingerprint(action, headSha, base, report, reviewSummaryIds
64
67
  annotations,
65
68
  });
66
69
  }
67
- export async function applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, prospectiveResult, report, reviewSummaryIds, stallDeadlineSink) {
70
+ export async function applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, prospectiveResult, report, reviewSummaryIds, stallDeadlineSink, persistState = true) {
68
71
  const prReference = formatPrUrl(report.repo, prNumber);
69
72
  const nowSeconds = Math.floor(Date.now() / 1000);
70
73
  const ciStartOpts = { stallTimeoutSeconds, action: prospectiveResult.action };
@@ -73,6 +76,17 @@ export async function applyStallGuard(stallKey, stallTimeoutSeconds, headSha, ba
73
76
  stallDeadlineSink.ciStartDeadlineSeconds = ciStartStallDeadline(report.checks.inProgress, nowSeconds, ciStartOpts);
74
77
  }
75
78
  if (stalledChecks.length > 0) {
79
+ const investigation = await planCiStartInvestigation({
80
+ base,
81
+ report,
82
+ stallKey,
83
+ headSha,
84
+ stalledChecks,
85
+ persistState,
86
+ stateUnavailable: (reason) => stallStateUnavailable(base, prReference, prospectiveResult, reason),
87
+ });
88
+ if (investigation)
89
+ return investigation;
76
90
  const pending = pendingReviewCommandsFromResult(prospectiveResult);
77
91
  const stalledDuration = formatDurationApprox(Math.max(...stalledChecks.map((c) => c.ageSeconds)));
78
92
  const escalateBase = {
@@ -95,17 +109,25 @@ export async function applyStallGuard(stallKey, stallTimeoutSeconds, headSha, ba
95
109
  };
96
110
  }
97
111
  const fingerprint = computeStallFingerprint(prospectiveResult.action, headSha, base, report, reviewSummaryIds);
112
+ const stateUnavailable = async (reason) => (await planStallRepair({
113
+ base,
114
+ report,
115
+ prospective: prospectiveResult,
116
+ scope: `${stallKey.owner}/${stallKey.repo}#${stallKey.pr}`,
117
+ reason,
118
+ persistState,
119
+ })) ?? stallStateUnavailable(base, prReference, prospectiveResult, reason);
98
120
  const read = await readStallState(stallKey);
99
121
  if (!read.ok) {
100
122
  if (stallTimeoutSeconds <= 0)
101
123
  return prospectiveResult;
102
- return stallStateUnavailable(base, prReference, prospectiveResult, read.reason);
124
+ return await stateUnavailable(read.reason);
103
125
  }
104
126
  const stored = read.state;
105
127
  const persistTimer = async () => {
106
128
  const wrote = await writeStallState(stallKey, { fingerprint, firstSeenAt: nowSeconds });
107
129
  if (!wrote.ok && stallTimeoutSeconds > 0) {
108
- return stallStateUnavailable(base, prReference, prospectiveResult, wrote.reason);
130
+ return stateUnavailable(wrote.reason);
109
131
  }
110
132
  return undefined;
111
133
  };
@@ -153,23 +175,10 @@ export async function applyStallGuard(stallKey, stallTimeoutSeconds, headSha, ba
153
175
  }
154
176
  function stallStateUnavailable(base, prReference, prospectiveResult, reason) {
155
177
  const pending = pendingReviewCommandsFromResult(prospectiveResult);
156
- const escalateBase = {
157
- triggers: ["stall-state-unavailable"],
158
- unresolvedThreads: [],
159
- ambiguousComments: [],
160
- changesRequestedReviews: [],
178
+ return stateUnavailableResult(base, prReference, reason, {
161
179
  ...surfacedSummariesFromResult(prospectiveResult),
162
180
  ...(pending && { pendingReviewCommands: pending }),
163
- suggestion: buildEscalateSuggestion(["stall-state-unavailable"], reason),
164
- };
165
- return {
166
- ...base,
167
- action: "escalate",
168
- escalate: {
169
- ...escalateBase,
170
- humanMessage: buildEscalateHumanMessage(escalateBase, prReference),
171
- },
172
- };
181
+ });
173
182
  }
174
183
  function unstartedStallCandidates(checks, nowSeconds, opts) {
175
184
  if (opts.stallTimeoutSeconds <= 0 || opts.action !== "wait")
@@ -0,0 +1,8 @@
1
+ import type { EscalateDetails, IterateResult, IterateResultBase } from "../../types.mts";
2
+ type Extras = Partial<Pick<EscalateDetails, "firstLookSummaries" | "editedSummaries" | "pendingReviewCommands">>;
3
+ /**
4
+ * `stall-state-unavailable`: Shepherd could not read or save the state that bounds a repeated
5
+ * situation (the stall timer, or an investigation marker), so it cannot detect a stuck loop.
6
+ */
7
+ export declare function stateUnavailableResult(base: IterateResultBase, prReference: string, reason: string, extras?: Extras): IterateResult;
8
+ export {};
@@ -0,0 +1,23 @@
1
+ import { buildEscalateHumanMessage, buildEscalateSuggestion } from "./escalate.mjs";
2
+ /**
3
+ * `stall-state-unavailable`: Shepherd could not read or save the state that bounds a repeated
4
+ * situation (the stall timer, or an investigation marker), so it cannot detect a stuck loop.
5
+ */
6
+ export function stateUnavailableResult(base, prReference, reason, extras = {}) {
7
+ const escalateBase = {
8
+ triggers: ["stall-state-unavailable"],
9
+ unresolvedThreads: [],
10
+ ambiguousComments: [],
11
+ changesRequestedReviews: [],
12
+ ...extras,
13
+ suggestion: buildEscalateSuggestion(["stall-state-unavailable"], reason),
14
+ };
15
+ return {
16
+ ...base,
17
+ action: "escalate",
18
+ escalate: {
19
+ ...escalateBase,
20
+ humanMessage: buildEscalateHumanMessage(escalateBase, prReference),
21
+ },
22
+ };
23
+ }
@@ -6,7 +6,7 @@ const TRIAGE_LOOP_PLAYBOOK = "Triage loop";
6
6
  export function buildPushSteps(style, genericPush) {
7
7
  if (!genericPush)
8
8
  return [];
9
- const push = "Commit and push any changes.";
9
+ const push = "Commit and push any changes to the PR head.";
10
10
  if (style === "inline")
11
11
  return [push];
12
12
  const cli = renderShellCommand([
@@ -6,8 +6,10 @@ import { checkEscalateTriggers, validateBaseBranch, buildEscalateSuggestion, bui
6
6
  import { buildResolveCommand } from "./classify.mjs";
7
7
  import { buildThreadMutationRouting, threadHasAuthorizedMutation, } from "./thread-mutation-routing.mjs";
8
8
  import { buildFixInstructions } from "./render.mjs";
9
+ import { buildCancelRunsInstruction, buildInProgressRuns } from "./in-progress-runs.mjs";
9
10
  import { buildRemovedQueueRecovery, buildStackQueueRemovalAcknowledgment } from "./merge.mjs";
10
- import { hasLogEvidence } from "./check-evidence.mjs";
11
+ import { buildCheckFollowUpInstructions, checkFollowUp } from "./check-follow-up.mjs";
12
+ import { checkFollowUpKeys, readCheckFollowUp, sameCheckFollowUp, writeCheckFollowUp, } from "../../state/check-follow-up.mjs";
11
13
  import { currentEjectionCommit, } from "./queue-recovery-instructions.mjs";
12
14
  import { buildReleasedBlockerInstruction, buildReviewSubsetInstruction, } from "./check-instructions.mjs";
13
15
  import { buildNativeStackLayerRebase } from "./native-stack-rebase.mjs";
@@ -15,6 +17,7 @@ import { buildDequeueCommand } from "./merge-plan.mjs";
15
17
  import { renderShellCommand } from "../../cli/runner.mjs";
16
18
  import { lookupUpperLayerTrunkConflict } from "./stack-trunk-conflict.mjs";
17
19
  import { lookupConflictCandidateFiles } from "./conflict-candidate-files.mjs";
20
+ import { playbookPointer } from "../playbook-pointer.mjs";
18
21
  import { lookupMergedBasePullRequests } from "./merged-base-pull-requests.mjs";
19
22
  import { conflictingHeadCiNote, countReportedChecks, insertConflictingHeadCiNote, } from "./conflicting-head-ci.mjs";
20
23
  import { conflictingHeadFirstSeenUnix } from "../../state/conflicting-head-seen.mjs";
@@ -27,25 +30,6 @@ import { canGenerateGithubMutation } from "../../github/mutation-policy.mjs";
27
30
  import { loadConfig } from "../../config/load.mjs";
28
31
  import { formatPrUrl } from "../../pr-reference.mjs";
29
32
  const EMPTY_RELEASED = new Set();
30
- function checkRequiresHumanFollowUp(check) {
31
- if (check.rerunCommand)
32
- return false;
33
- if (check.conclusion === "ACTION_REQUIRED" ||
34
- check.conclusion === "CANCELLED" ||
35
- check.conclusion === "STARTUP_FAILURE")
36
- return true;
37
- // A later attempt cannot be rerun automatically, but its included log can still
38
- // identify a code or configuration fix for the agent. Only a later failure with
39
- // no actionable evidence needs a human handoff.
40
- if (check.runAttempt !== undefined && check.runAttempt > 1)
41
- return !hasLogEvidence(check);
42
- // An external check's direct URL is actionable evidence: the agent can inspect the
43
- // provider and/or reproduce the reported failure locally. Only a truly bare check
44
- // has no autonomous investigation path.
45
- if (check.runId === null)
46
- return !check.detailsUrl?.trim();
47
- return !hasLogEvidence(check);
48
- }
49
33
  function nextFixAttempts(stored, threads, countAttempt) {
50
34
  const threadAttempts = stored ? { ...stored.threadAttempts } : {};
51
35
  const threadBodyHashes = stored?.threadBodyHashes
@@ -156,13 +140,11 @@ async function handleTriageTick(ctx) {
156
140
  },
157
141
  };
158
142
  }
159
- // GitHub does not expose a per-run viewer capability for cancellation, so Shepherd never
160
- // issues or recommends a cancellation regardless of repository role. A rerun is different:
161
- // GitHub's Actions rerun API requires actions:write, which rides with WRITE+ repo access, so
162
- // repositoryPermission is a proxy for account-level rerun capability (see canRerunWorkflows) —
163
- // it does not confirm the credential executing `gh` has that scope; an unauthorized rerun
164
- // simply fails when the agent runs it, the same residual risk as every other CLI-recommended
165
- // git/gh mutation in this codebase.
143
+ // GitHub's Actions rerun and cancel APIs both require actions:write, which rides with WRITE+
144
+ // repo access, so repositoryPermission is a proxy for account-level capability (see
145
+ // canRerunWorkflows) — it does not confirm the credential executing `gh` has that scope; an
146
+ // unauthorized rerun or cancel simply fails when the agent runs it, the same residual risk as
147
+ // every other CLI-recommended command in this codebase. Shepherd itself never cancels a run.
166
148
  const baseLookup = validateBaseBranch(report.baseBranch);
167
149
  const threads = report.threads.actionable.map(toAgentThread);
168
150
  const resolutionOnlyThreads = report.threads.resolutionOnly;
@@ -213,7 +195,7 @@ async function handleTriageTick(ctx) {
213
195
  const belongsToActiveWorkflowRun = (check) => check.runId !== null && inProgressWorkflowRunIds.has(check.runId);
214
196
  const manualFollowUpChecks = failingAgentChecks.filter((check) => !releasedCheckNames.has(check.name) &&
215
197
  !belongsToActiveWorkflowRun(check) &&
216
- checkRequiresHumanFollowUp(check));
198
+ checkFollowUp(check) !== undefined);
217
199
  const exhaustedAttempts = failingAgentChecks.filter((check) => check.runAttempt !== undefined && check.runAttempt > 1);
218
200
  const manualExhaustedAttempts = exhaustedAttempts.filter((check) => manualFollowUpChecks.includes(check));
219
201
  const hasBehindBaseRecovery = isBehind && manualExhaustedAttempts.length > 0;
@@ -233,15 +215,21 @@ async function handleTriageTick(ctx) {
233
215
  checks.some((check) => (check.annotations?.length ?? 0) > 0) ||
234
216
  failingAgentChecks.some((check) => releasedCheckNames.has(check.name) ||
235
217
  belongsToActiveWorkflowRun(check) ||
236
- !checkRequiresHumanFollowUp(check));
237
- if (manualFollowUpChecks.length > 0 && !hasAutonomousWork) {
218
+ checkFollowUp(check) === undefined);
219
+ // Only a gate a human must grant escalates at once; every other manual-only check gets one
220
+ // investigation tick for this head and check set before it escalates.
221
+ const needsApproval = manualFollowUpChecks.some((check) => checkFollowUp(check) === "approval");
222
+ const followUpKeys = checkFollowUpKeys(manualFollowUpChecks);
223
+ const investigated = needsApproval || sameCheckFollowUp(await readCheckFollowUp(stallKey), headSha, followUpKeys);
224
+ const investigate = manualFollowUpChecks.length > 0 && !hasAutonomousWork && !investigated;
225
+ if (manualFollowUpChecks.length > 0 && !hasAutonomousWork && investigated) {
238
226
  const { resolveCommand, resolveOnlyCommand } = buildReviewCommands(failingAgentChecks);
239
227
  const pending = pendingReviewCommands(resolveCommand, resolveOnlyCommand);
240
228
  const checkSuggestion = manualExhaustedAttempts.length > 0
241
229
  ? `GitHub reports a later workflow attempt (${manualExhaustedAttempts
242
230
  .map((check) => `${check.runId ?? check.name}: attempt ${check.runAttempt}`)
243
- .join(", ")}), so Shepherd's single rerun allowance is exhausted. Use the included evidence to handle the repeated failure manually before resuming.`
244
- : buildEscalateSuggestion(["check-follow-up-unavailable"]);
231
+ .join(", ")}), so Shepherd's single rerun allowance is exhausted. ${needsApproval ? "Use the included evidence to handle the repeated failure manually before resuming." : buildEscalateSuggestion(["check-follow-up-unavailable"], "investigated")}`
232
+ : buildEscalateSuggestion(["check-follow-up-unavailable"], needsApproval ? undefined : "investigated");
245
233
  const checkEscalateBase = {
246
234
  triggers: ["check-follow-up-unavailable"],
247
235
  unresolvedThreads: [],
@@ -267,46 +255,11 @@ async function handleTriageTick(ctx) {
267
255
  // Push access to the PR head branch is a usage precondition. Build review mutations for
268
256
  // conflict ticks normally so the caller can push and complete the same triage cycle.
269
257
  const { resolveCommand, resolveOnlyCommand } = buildReviewCommands(failingAgentChecks);
270
- // Safety: if the base branch is unknown, escalate when a push is plausible — the agent
271
- // would need the correct base to rebase safely. This is a conservative guard, not a
272
- // prediction that the agent *will* push. Located resolution-only threads retain that guard;
273
- // an outdated bot thread resolved only by ID has no code or push path.
274
- const locatedResolutionOnlyThreadsForWork = resolutionOnlyThreadsForWork.filter((thread) => thread.path !== null && thread.line !== null);
275
- const pushIsPlausible = retryableActionableThreads.length > 0 ||
276
- failingAgentChecks.length > 0 ||
277
- annotatedExtra.length > 0 ||
278
- hasConflicts ||
279
- changesRequestedReviewsForWork.length > 0 ||
280
- actionableComments.length > 0 ||
281
- locatedResolutionOnlyThreadsForWork.length > 0;
282
- if (baseLookup.isFallback && pushIsPlausible) {
283
- const pending = pendingReviewCommands(resolveCommand, resolveOnlyCommand);
284
- const fallbackEscalateBase = {
285
- triggers: ["base-branch-unknown"],
286
- unresolvedThreads: [...threads, ...resolutionOnlyThreads.map(toAgentThread)],
287
- ambiguousComments: actionableComments,
288
- changesRequestedReviews,
289
- ...(firstLookSummaries.length > 0 && { firstLookSummaries }),
290
- ...(editedSummaries.length > 0 && { editedSummaries }),
291
- ...(pending && { pendingReviewCommands: pending }),
292
- suggestion: buildEscalateSuggestion(["base-branch-unknown"], baseLookup.failureReason),
293
- };
294
- return {
295
- ...base,
296
- action: "escalate",
297
- escalate: {
298
- ...fallbackEscalateBase,
299
- humanMessage: buildEscalateHumanMessage(fallbackEscalateBase, prReference, {
300
- merge: opts.merge,
301
- }),
302
- },
303
- };
304
- }
305
258
  const firstLookThreads = report.threads.firstLook;
306
259
  const firstLookComments = report.comments.firstLook;
307
260
  const stack = report.mergeStatus.mergeRequirements?.stack;
308
261
  const headRef = report.headSha;
309
- const mergedBasePullRequests = hasConflicts && !stack && report.baseRefOid
262
+ const mergedBasePullRequests = hasConflicts && !stack && report.baseRefOid && !baseLookup.unusable
310
263
  ? await lookupMergedBasePullRequests({
311
264
  owner: repoOwner,
312
265
  repo: repoName,
@@ -315,7 +268,7 @@ async function handleTriageTick(ctx) {
315
268
  })
316
269
  : [];
317
270
  // Native stack layers update from trunk or a parent, so a base comparison names no useful files.
318
- const conflictCandidateFiles = hasConflicts && !stack && headRef
271
+ const conflictCandidateFiles = hasConflicts && !stack && headRef && !baseLookup.unusable
319
272
  ? await lookupConflictCandidateFiles({
320
273
  owner: repoOwner,
321
274
  repo: repoName,
@@ -353,12 +306,18 @@ async function handleTriageTick(ctx) {
353
306
  // Conflicts, a behind branch whose rerun already failed, and a queue ejection that may be
354
307
  // reproduced on the latest base all print the branch update route.
355
308
  const stackRebase = hasConflicts || (isBehind && exhaustedAttempts.length > 0) || queueEjection
356
- ? buildNativeStackLayerRebase(report.repo, { number: prNumber, baseBranch: baseLookup.branch }, stack, trunkConflict, report.stackBottomPr)
309
+ ? buildNativeStackLayerRebase(report.repo, { number: prNumber, baseBranch: baseLookup.unusable ? undefined : baseLookup.branch }, stack, trunkConflict, report.stackBottomPr)
357
310
  : undefined;
358
311
  const dequeueCommand = queuedConflict
359
312
  ? renderShellCommand(buildDequeueCommand(report.nodeId))
360
313
  : undefined;
361
- const instructions = buildFixInstructions(threads, actionableComments, checks.filter((check) => !releasedCheckNames.has(check.name)), changesRequestedReviews, baseLookup.branch, resolveCommand, hasConflicts, prReference, firstLookThreads, firstLookComments, firstLookSummaries, editedSummaries, resolutionOnlyThreads, resolveOnlyCommand, behindBaseHint, isBehind, canGenerateGithubMutation(report.viewerAuthorization?.viewerCanUpdate, "ready"), exhaustedAttempts.length > 0, stackRebase, queueEjection, opts.instructions ?? configuredInstructions, dequeueCommand);
314
+ const inProgressRuns = await buildInProgressRuns(report, rerunAuthorized);
315
+ const instructions = buildFixInstructions(threads, actionableComments, checks.filter((check) => !releasedCheckNames.has(check.name)), changesRequestedReviews, baseLookup.branch, resolveCommand, hasConflicts, prReference, firstLookThreads, firstLookComments, firstLookSummaries, editedSummaries, resolutionOnlyThreads, resolveOnlyCommand, behindBaseHint, isBehind, canGenerateGithubMutation(report.viewerAuthorization?.viewerCanUpdate, "ready"), exhaustedAttempts.length > 0, stackRebase, queueEjection, opts.instructions ?? configuredInstructions, dequeueCommand, buildCancelRunsInstruction(inProgressRuns));
316
+ if (investigate) {
317
+ // The failing-checks pointer is replaced: these checks have no excerpt for the CI playbook.
318
+ const triageStep = instructions.findIndex((step) => step.startsWith("Triage `## Failing checks`."));
319
+ instructions.splice(triageStep, 1, ...buildCheckFollowUpInstructions(manualFollowUpChecks, report.repo, actionsRunIds));
320
+ }
362
321
  if (recovery && "unavailable" in recovery)
363
322
  instructions.unshift(recovery.unavailable);
364
323
  if (acknowledgmentRecovery && "unavailable" in acknowledgmentRecovery)
@@ -392,7 +351,7 @@ async function handleTriageTick(ctx) {
392
351
  ? `gh api --method PATCH repos/${report.repo}/pulls/${prNumber} -f base=<verified-parent-base>`
393
352
  : `gh pr edit ${prReference} --base <verified-parent-base>`;
394
353
  prependBranchSteps([
395
- `Inspect every PR under \`## Merged PRs matching the current base\`. If this PR is the remaining layer intended for a merged parent's base branch, run \`${retarget}\` after replacing \`<verified-parent-base>\` with that parent's shell-quoted base branch, then rerun Shepherd immediately and follow its fresh instructions instead of the remaining steps here. Otherwise keep the current base and follow the remaining conflict-resolution steps.`,
354
+ `Inspect every PR under \`## Merged PRs matching the current base\`. If this PR is the remaining layer intended for a merged parent's base branch, run \`${retarget}\` after replacing \`<verified-parent-base>\` with that parent's shell-quoted base branch, then rerun Shepherd immediately and follow its fresh instructions instead of the remaining steps here. Otherwise keep the current base and follow the remaining conflict-resolution steps. These PRs are chained by base branch. For future dependent PRs, use \`gh stack\`. ${playbookPointer("Create a PR")}`,
396
355
  ]);
397
356
  }
398
357
  if (conflictCandidateFiles) {
@@ -406,6 +365,11 @@ async function handleTriageTick(ctx) {
406
365
  const firstSeenAtUnix = hasConflicts && suitesEmpty && checkRunCount === 0 && report.headSha
407
366
  ? await conflictingHeadFirstSeenUnix({ owner: repoOwner, repo: repoName, pr: prNumber }, report.headSha, nowMs)
408
367
  : undefined;
368
+ if (baseLookup.unusable && (hasConflicts || isBehind)) {
369
+ instructions.unshift(`Shepherd could not use the PR's base branch name from GitHub (empty, or characters outside \`[A-Za-z0-9._/-]\`), so it prints no command that names the base. Read it with ${report.transport === "rest"
370
+ ? `\`gh api repos/${report.repo}/pulls/${prNumber} --jq .base.ref\``
371
+ : `\`gh pr view ${prReference} --json baseRefName\``} and quote it in any command you run.`);
372
+ }
409
373
  insertConflictingHeadCiNote(instructions, conflictingHeadCiNote({
410
374
  hasConflicts,
411
375
  headCheckSuitesEmpty: suitesEmpty,
@@ -415,7 +379,7 @@ async function handleTriageTick(ctx) {
415
379
  }));
416
380
  const prospectiveResult = {
417
381
  ...base,
418
- baseBranch: baseLookup.branch,
382
+ baseBranch: baseLookup.unusable ? "" : baseLookup.branch,
419
383
  ...(mergedBasePullRequests.length > 0 && { mergedBasePullRequests }),
420
384
  ...(conflictCandidateFiles && { conflictCandidateFiles }),
421
385
  ...(trunkConflict && { stackTrunkConflict: trunkConflict.trunk }),
@@ -429,6 +393,7 @@ async function handleTriageTick(ctx) {
429
393
  editedSummaries,
430
394
  surfacedApprovals,
431
395
  checks,
396
+ ...(inProgressRuns.length > 0 && { inProgressRuns }),
432
397
  ...(requeue && { requeue }),
433
398
  ...(queueRemovalAcknowledgment && { queueRemovalAcknowledgment }),
434
399
  changesRequestedReviews,
@@ -441,9 +406,11 @@ async function handleTriageTick(ctx) {
441
406
  ...(ctx.deferredWork && { deferredWork: ctx.deferredWork }),
442
407
  },
443
408
  };
444
- const result = await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, prospectiveResult, report, reviewSummaryIds);
409
+ const result = await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, prospectiveResult, report, reviewSummaryIds, undefined, opts.persistSeen !== false);
445
410
  if (result.action === "triage" && opts.persistSeen !== false) {
446
411
  await writeFixAttempts({ owner: repoOwner, repo: repoName, pr: prNumber }, { headSha, threadAttempts, threadBodyHashes });
412
+ if (investigate)
413
+ await writeCheckFollowUp(stallKey, { headSha, checks: followUpKeys });
447
414
  // A queued conflict's annotation fixes are path (a); waiting keeps them unseen.
448
415
  if (!queuedConflict)
449
416
  await Promise.allSettled(result.triage.checks.flatMap((ch) => (ch.annotations ?? []).map((a) => markSeen(stallKey, a.id, annotationMarkerBody(a)))));
@@ -1,4 +1,4 @@
1
- import type { IterateResult, IterateResultBase, ShepherdReport } from "../../types.mts";
1
+ import type { IterateResult, IterateResultBase, ShepherdReport, AgentStalledCheck } from "../../types.mts";
2
2
  interface UnreportedPlan {
3
3
  escalate?: IterateResult;
4
4
  repairInstructions?: string[];
@@ -16,5 +16,8 @@ export declare function planUnreportedRequired(input: {
16
16
  /** Internal preview ticks must not consume the one-time reopen opportunity. */
17
17
  persistState?: boolean;
18
18
  }): Promise<UnreportedPlan>;
19
- export declare function buildUnreportedFixResult(base: IterateResultBase, report: ShepherdReport, instructions: string[]): IterateResult;
19
+ export declare function buildUnreportedFixResult(base: IterateResultBase, report: ShepherdReport, instructions: string[], data?: {
20
+ stalledChecks?: AgentStalledCheck[];
21
+ }): IterateResult;
22
+ export declare function stackRebase(report: ShepherdReport): string | undefined;
20
23
  export {};
@@ -4,6 +4,7 @@ import { readCiRetrigger, sameCiRetrigger, writeCiRetrigger } from "../../state/
4
4
  import { buildFixCompletionInstruction } from "./check-instructions.mjs";
5
5
  import { buildEscalateHumanMessage, buildEscalateSuggestion } from "./escalate.mjs";
6
6
  import { buildNativeStackRebaseInstruction } from "./native-stack-rebase.mjs";
7
+ import { playbookPointer } from "../playbook-pointer.mjs";
7
8
  import { getGithubTransport } from "../../github/transport.mjs";
8
9
  /** Rebase when the trunk or the PR base is behind; otherwise close and reopen once. */
9
10
  function decideUnreportedRequired(input) {
@@ -26,14 +27,16 @@ function buildUnreportedRequiredInstructions(input) {
26
27
  : input.behind
27
28
  ? "This PR's derived merge status is BEHIND."
28
29
  : `This branch is not behind \`${input.baseBranch}\`.`;
29
- const facts = `${gap} No CI checks are running, and required checks have not passed: ${names}.`;
30
+ const facts = `${gap} No CI checks are running on head \`${input.headSha.slice(0, 7)}\`, and required checks have not passed: ${names}.`;
31
+ const playbook = playbookPointer("Required checks unreported");
30
32
  if (!input.behind) {
33
+ const retrigger = getGithubTransport() === "rest"
34
+ ? `run \`gh api --method PATCH repos/${input.repo}/pulls/${input.pr} -f state=closed\`, then run \`gh api --method PATCH repos/${input.repo}/pulls/${input.pr} -f state=open\``
35
+ : `run \`gh pr close ${input.pr} -R ${input.repo}\` then \`gh pr reopen ${input.pr} -R ${input.repo}\``;
31
36
  return [
32
37
  facts,
33
- getGithubTransport() === "rest"
34
- ? `Retrigger workflows once for this head: run \`gh api --method PATCH repos/${input.repo}/pulls/${input.pr} -f state=closed\`, then run \`gh api --method PATCH repos/${input.repo}/pulls/${input.pr} -f state=open\`.`
35
- : `Retrigger workflows once for this head with \`gh pr close ${input.pr} -R ${input.repo}\` then \`gh pr reopen ${input.pr} -R ${input.repo}\`.`,
36
- "If those checks are still missing on the next poll, investigate why the workflows did not start. Do not close the PR again. Shepherd escalates with `required-checks-unreported` when this remains the only blocker.",
38
+ `Shepherd cannot tell from GitHub's data why nothing started. Find out before acting. ${playbook}`,
39
+ `If the cause is within this PR, fix it and push. If the workflows should have run and the PR is fine, retrigger once: ${retrigger}. Otherwise make no change and keep what you found. If the checks are still missing on the next poll, Shepherd escalates with \`required-checks-unreported\`; report that diagnosis then.`,
37
40
  ];
38
41
  }
39
42
  const rebase = input.stackRebase
@@ -42,7 +45,7 @@ function buildUnreportedRequiredInstructions(input) {
42
45
  return [
43
46
  facts,
44
47
  `${rebase} Rebase and push is how these checks start.`,
45
- "If that push does not start the checks, investigate why the workflows did not run. Shepherd escalates with `required-checks-unreported` when the branch is current and this remains the only blocker.",
48
+ `If that push does not start the checks, find out why nothing started. ${playbook} Shepherd escalates with \`required-checks-unreported\` when the branch is current and this remains the only blocker.`,
46
49
  ];
47
50
  }
48
51
  export async function planUnreportedRequired(input) {
@@ -67,6 +70,7 @@ export async function planUnreportedRequired(input) {
67
70
  const rebase = stackRebase(input.report);
68
71
  const instructions = buildUnreportedRequiredInstructions({
69
72
  names,
73
+ headSha: input.headSha,
70
74
  repo: input.report.repo,
71
75
  pr: input.report.pr,
72
76
  baseBranch: input.report.baseBranch,
@@ -80,7 +84,7 @@ export async function planUnreportedRequired(input) {
80
84
  }
81
85
  return { repairInstructions: instructions };
82
86
  }
83
- export function buildUnreportedFixResult(base, report, instructions) {
87
+ export function buildUnreportedFixResult(base, report, instructions, data = {}) {
84
88
  const prUrl = formatPrUrl(report.repo, report.pr);
85
89
  return {
86
90
  ...base,
@@ -104,10 +108,11 @@ export function buildUnreportedFixResult(base, report, instructions) {
104
108
  instructions: [...instructions, buildFixCompletionInstruction()],
105
109
  firstLookThreads: [],
106
110
  firstLookComments: [],
111
+ ...data,
107
112
  },
108
113
  };
109
114
  }
110
- function stackRebase(report) {
115
+ export function stackRebase(report) {
111
116
  const stack = report.mergeStatus.mergeRequirements?.stack;
112
117
  if (!stack)
113
118
  return undefined;
@@ -0,0 +1,27 @@
1
+ import type { RepoInfo } from "../../github/client.mts";
2
+ /** A workflow file at a ref: a commit SHA, or a branch name whose live tip is wanted. */
3
+ export interface WorkflowFileRequest {
4
+ ref: string;
5
+ path: string;
6
+ /** True when `ref` is a commit SHA, so the answer can be remembered for the process. */
7
+ pinned: boolean;
8
+ }
9
+ /** The file's text, or why it could not be read. */
10
+ export type WorkflowFileResult = {
11
+ text: string;
12
+ } | {
13
+ unreadable: string;
14
+ };
15
+ /** Forget remembered files. */
16
+ export declare function clearWorkflowFileMemo(): void;
17
+ /** Lookup key for a request in the result map. */
18
+ export declare const workflowFileKey: (request: {
19
+ ref: string;
20
+ path: string;
21
+ }) => string;
22
+ /**
23
+ * One aliased GraphQL read (or one REST `contents` read per file) of the requested workflow
24
+ * files, best-effort: a failure marks the file unreadable, a rate limit propagates. Files read
25
+ * at a commit SHA are remembered for the process, so a `--until-terminal` loop reads each once.
26
+ */
27
+ export declare function readWorkflowFiles(repo: RepoInfo, requests: readonly WorkflowFileRequest[]): Promise<Map<string, WorkflowFileResult>>;
@@ -0,0 +1,85 @@
1
+ import { graphql } from "../../github/client.mjs";
2
+ import { GitHubRequestError } from "../../github/errors.mjs";
3
+ import { githubOperation, isGithubReadFallbackError } from "../../github/transport.mjs";
4
+ import { readRest, restObject, restRepoPath } from "../../github/rest-reader-core.mjs";
5
+ import { pollRateLimitRetryAfterMs } from "../poll-quota.mjs";
6
+ const memo = new Map();
7
+ /** Forget remembered files. */
8
+ export function clearWorkflowFileMemo() {
9
+ memo.clear();
10
+ }
11
+ /** Lookup key for a request in the result map. */
12
+ export const workflowFileKey = (request) => `${request.ref}:${request.path}`;
13
+ const memoKey = (repo, request) => `${repo.owner}/${repo.name}\0${workflowFileKey(request)}`;
14
+ function fromBlob(blob) {
15
+ if (blob == null || typeof blob.text !== "string")
16
+ return { unreadable: "404" };
17
+ return blob.isTruncated ? { unreadable: "truncated" } : { text: blob.text };
18
+ }
19
+ async function readGraphql(repo, requests) {
20
+ const declarations = requests.map((_, i) => `, $e${i}: String!`).join("");
21
+ const fields = requests
22
+ .map((_, i) => `w${i}: object(expression: $e${i}) { ... on Blob { text isTruncated } }`)
23
+ .join(" ");
24
+ const query = `query WorkflowFiles($owner: String!, $name: String!${declarations}) { repository(owner: $owner, name: $name) { ${fields} } }`;
25
+ const variables = { owner: repo.owner, name: repo.name };
26
+ requests.forEach((request, i) => {
27
+ variables[`e${i}`] = workflowFileKey(request);
28
+ });
29
+ const { data } = await graphql(query, variables);
30
+ return requests.map((_, i) => fromBlob(data.repository?.[`w${i}`]));
31
+ }
32
+ async function readOneRest(repo, request) {
33
+ const path = request.path.split("/").map(encodeURIComponent).join("/");
34
+ try {
35
+ const body = restObject(await readRest("GET", `${restRepoPath(repo)}/contents/${path}?ref=${encodeURIComponent(request.ref)}`), "workflow file");
36
+ if (body["encoding"] !== "base64" || typeof body["content"] !== "string") {
37
+ return { unreadable: "truncated" };
38
+ }
39
+ return { text: Buffer.from(body["content"], "base64").toString("utf8") };
40
+ }
41
+ catch (error) {
42
+ if (pollRateLimitRetryAfterMs(error) !== null)
43
+ throw error;
44
+ return {
45
+ unreadable: error instanceof GitHubRequestError ? String(error.status) : "request failed",
46
+ };
47
+ }
48
+ }
49
+ /**
50
+ * One aliased GraphQL read (or one REST `contents` read per file) of the requested workflow
51
+ * files, best-effort: a failure marks the file unreadable, a rate limit propagates. Files read
52
+ * at a commit SHA are remembered for the process, so a `--until-terminal` loop reads each once.
53
+ */
54
+ export async function readWorkflowFiles(repo, requests) {
55
+ const results = new Map();
56
+ const pending = new Map();
57
+ for (const request of requests) {
58
+ const known = request.pinned ? memo.get(memoKey(repo, request)) : undefined;
59
+ if (known)
60
+ results.set(workflowFileKey(request), known);
61
+ else
62
+ pending.set(workflowFileKey(request), request);
63
+ }
64
+ if (pending.size === 0)
65
+ return results;
66
+ const wanted = [...pending.values()];
67
+ let answers;
68
+ try {
69
+ answers = await githubOperation("WorkflowFiles", () => readGraphql(repo, wanted), () => Promise.all(wanted.map((request) => readOneRest(repo, request))));
70
+ }
71
+ catch (error) {
72
+ if (pollRateLimitRetryAfterMs(error) !== null || isGithubReadFallbackError(error))
73
+ throw error;
74
+ process.stderr.write(`pr-shepherd: workflow files unavailable (ignored): ${error instanceof Error ? error.message : String(error)}\n`);
75
+ answers = wanted.map(() => ({ unreadable: "request failed" }));
76
+ }
77
+ wanted.forEach((request, i) => {
78
+ const answer = answers[i];
79
+ results.set(workflowFileKey(request), answer);
80
+ if (request.pinned && ("text" in answer || answer.unreadable === "404")) {
81
+ memo.set(memoKey(repo, request), answer);
82
+ }
83
+ });
84
+ return results;
85
+ }
@@ -14,6 +14,19 @@ export function onlyDraftVerificationSelection(result) {
14
14
  }
15
15
  /** Rerunning is mandatory while any selected row is non-terminal; a finished one-PR poll is not the end. */
16
16
  const KEEP_WATCHING = "Do not end the turn while any selected row is non-terminal: a one-PR poll returning `CANCEL` or `ESCALATE` finishes only that row, and rows that are `CANCEL`, `ESCALATE`, or handed off do not count. If a background exit wakes you, end the turn and continue then.";
17
+ /**
18
+ * A multi-PR poll reads stack layers without verifying them, so `appears-ready` here is not the
19
+ * READY receipt a `stack --merge` requires. Say so once, only when a stack layer looks ready.
20
+ */
21
+ function stackReceiptNote(result) {
22
+ const layers = result.prs.filter((item) => item.state === "OPEN" && item.stack && item.reasons.includes("appears-ready"));
23
+ if (layers.length === 0)
24
+ return [];
25
+ const names = layers.map((item) => `#${item.pr}`).join(", ");
26
+ return [
27
+ `2. ${names} ${layers.length === 1 ? "is a native stack layer" : "are native stack layers"}: this poll does not record the READY receipt a stack merge needs. If the user asked to merge, run \`pr-shepherd stack\` with \`--merge\` instead; it starts the one-PR sessions that record them.`,
28
+ ];
29
+ }
17
30
  export function explicitInstructions(result, rerunCommand) {
18
31
  const again = rerunCommand ? `\`${rerunCommand}\`` : "this aggregate command";
19
32
  if (result.reason === "all_terminal")
@@ -21,6 +34,7 @@ export function explicitInstructions(result, rerunCommand) {
21
34
  result.prs.some((item) => item.reasons.includes("draft-auto-mark-ready-disabled"))
22
35
  ? "1. Stop — every selected PR is complete for this Shepherd run."
23
36
  : "1. Stop — every selected PR is terminal.",
37
+ ...stackReceiptNote(result),
24
38
  ];
25
39
  if (result.quotaWarning && result.reason !== "actionable") {
26
40
  return [
@@ -33,7 +47,7 @@ export function explicitInstructions(result, rerunCommand) {
33
47
  const instructions = [
34
48
  "1. Choose each non-WAIT, non-CANCEL row that can proceed independently and run or delegate its exact `pollCommand`.",
35
49
  "2. Follow each selected one-PR poll's `## Instructions` until it returns `CANCEL` or `ESCALATE`.",
36
- `3. Run ${again} again after selected work completes; one row's \`ESCALATE\` does not stop work on other rows. ${KEEP_WATCHING}`,
50
+ `3. When the selected one-PR polls return, always run ${again} again: its output, not theirs, decides whether this selection is done. One row's \`ESCALATE\` does not stop work on other rows. ${KEEP_WATCHING}`,
37
51
  ];
38
52
  if (result.prs.some((item) => item.action === "escalate") && !isHandedOffSelection(result)) {
39
53
  instructions[0] = `${instructions[0]} Report each \`ESCALATE\` row's reasons to the user now and leave that PR alone; keep working on the other rows.`;
@@ -1,8 +1,9 @@
1
- import type { PollSummaryItem, PollSummaryResult } from "../types.mts";
1
+ import type { PollSummaryItem, PollSummaryResult, StackMergeScope } from "../types.mts";
2
+ import { type ApproveCommands } from "./stack-merge-plan.mts";
2
3
  /** Keep aggregate JSON, Markdown, and MCP instructions on one projection. */
3
- export declare function withPollSummaryInstructions(result: PollSummaryResult, mergeRequested: boolean, rerunCommand?: string): PollSummaryResult;
4
+ export declare function withPollSummaryInstructions(result: PollSummaryResult, mergeRequested: boolean, rerunCommand?: string, scope?: StackMergeScope): PollSummaryResult;
4
5
  /** The projected summary, plus the idle layers when the stack plan can only wait on them. */
5
- export declare function planPollSummary(result: PollSummaryResult, mergeRequested: boolean, rerunCommand?: string): {
6
+ export declare function planPollSummary(result: PollSummaryResult, mergeRequested: boolean, rerunCommand?: string, scope?: StackMergeScope | undefined, approve?: ApproveCommands): {
6
7
  result: PollSummaryResult;
7
8
  idle?: PollSummaryItem[];
8
9
  };