pr-shepherd 0.52.0 → 0.52.1

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 (104) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +11 -8
  3. package/bin/cli/help-command-pages.d.mts +1 -1
  4. package/bin/cli/help-iterate-poll-pages.d.mts +1 -1
  5. package/bin/cli/help-iterate-poll-pages.mjs +4 -3
  6. package/bin/cli/help-top-page.d.mts +1 -1
  7. package/bin/cli/help-top-page.mjs +3 -2
  8. package/bin/cli/help.d.mts +2 -2
  9. package/bin/cli/iterate-instructions.mjs +41 -0
  10. package/bin/cli/iterate-lean.mjs +1 -0
  11. package/bin/cli/poll-summary-formatter.mjs +3 -1
  12. package/bin/cli/runner.d.mts +1 -0
  13. package/bin/cli/runner.mjs +3 -1
  14. package/bin/commands/check.mjs +13 -4
  15. package/bin/commands/clean.mjs +7 -13
  16. package/bin/commands/iterate/check-instructions.d.mts +2 -2
  17. package/bin/commands/iterate/check-instructions.mjs +11 -7
  18. package/bin/commands/iterate/escalate.mjs +4 -0
  19. package/bin/commands/iterate/fix-code.mjs +6 -1
  20. package/bin/commands/iterate/helpers.d.mts +0 -1
  21. package/bin/commands/iterate/helpers.mjs +0 -15
  22. package/bin/commands/iterate/index.mjs +57 -27
  23. package/bin/commands/iterate/merge-state.mjs +6 -4
  24. package/bin/commands/iterate/native-stack-rebase.d.mts +34 -0
  25. package/bin/commands/iterate/native-stack-rebase.mjs +43 -0
  26. package/bin/commands/iterate/parent-first.d.mts +18 -2
  27. package/bin/commands/iterate/parent-first.mjs +45 -32
  28. package/bin/commands/iterate/render.d.mts +1 -1
  29. package/bin/commands/iterate/render.mjs +7 -12
  30. package/bin/commands/iterate/stale-ancestry.d.mts +1 -1
  31. package/bin/commands/iterate/stale-ancestry.mjs +10 -7
  32. package/bin/commands/iterate/stall.mjs +40 -3
  33. package/bin/commands/poll-progress.d.mts +5 -1
  34. package/bin/commands/poll-progress.mjs +7 -1
  35. package/bin/commands/poll-summary-instructions.d.mts +6 -1
  36. package/bin/commands/poll-summary-instructions.mjs +51 -87
  37. package/bin/commands/poll-summary.mjs +4 -2
  38. package/bin/commands/poll.mjs +3 -1
  39. package/bin/commands/ready-delay.d.mts +9 -4
  40. package/bin/commands/ready-delay.mjs +34 -20
  41. package/bin/commands/shepherd-journal.mjs +4 -1
  42. package/bin/commands/stack-drain.d.mts +35 -0
  43. package/bin/commands/stack-drain.mjs +129 -0
  44. package/bin/commands/stack-layer-readiness.d.mts +7 -0
  45. package/bin/commands/stack-layer-readiness.mjs +35 -0
  46. package/bin/commands/stack-stall.d.mts +14 -0
  47. package/bin/commands/stack-stall.mjs +69 -0
  48. package/bin/commands/stack-work.d.mts +32 -0
  49. package/bin/commands/stack-work.mjs +39 -0
  50. package/bin/config/load.d.mts +2 -0
  51. package/bin/config/load.mjs +10 -0
  52. package/bin/config.json +1 -0
  53. package/bin/github/batch-parsers.mjs +1 -1
  54. package/bin/github/batch-raw-rules.d.mts +0 -3
  55. package/bin/github/batch-raw-types.d.mts +2 -0
  56. package/bin/github/errors.d.mts +5 -0
  57. package/bin/github/errors.mjs +4 -0
  58. package/bin/github/gql/batch-pr.gql +1 -0
  59. package/bin/github/gql/poll-stack-summary.gql +8 -2
  60. package/bin/github/gql/poll-stack-topology.gql +38 -0
  61. package/bin/github/gql/poll-summary-check-contexts.gql +34 -0
  62. package/bin/github/gql/poll-summary-check-page.gql +23 -0
  63. package/bin/github/gql/poll-summary-fragment.gql +5 -62
  64. package/bin/github/gql/pr-merge-policy.gql +0 -3
  65. package/bin/github/merge-queue-checks.mjs +10 -1
  66. package/bin/github/poll-summary-check-hydration.d.mts +12 -0
  67. package/bin/github/poll-summary-check-hydration.mjs +55 -0
  68. package/bin/github/poll-summary-fingerprint.mjs +24 -4
  69. package/bin/github/poll-summary-projector.mjs +8 -7
  70. package/bin/github/poll-summary-queue-removal.mjs +10 -1
  71. package/bin/github/poll-summary-raw.d.mts +19 -31
  72. package/bin/github/poll-summary-route.mjs +8 -5
  73. package/bin/github/poll-summary.mjs +16 -73
  74. package/bin/github/queries.d.mts +7 -0
  75. package/bin/github/queries.mjs +9 -1
  76. package/bin/github/queue-removal-freshness.d.mts +16 -0
  77. package/bin/github/queue-removal-freshness.mjs +26 -0
  78. package/bin/github/stack-read.d.mts +34 -0
  79. package/bin/github/stack-read.mjs +92 -0
  80. package/bin/log/log-file.d.mts +1 -1
  81. package/bin/log/log-file.mjs +4 -17
  82. package/bin/state/base.d.mts +18 -1
  83. package/bin/state/base.mjs +65 -13
  84. package/bin/state/fix-attempts.d.mts +1 -1
  85. package/bin/state/fix-attempts.mjs +1 -1
  86. package/bin/state/graphql-quota-warnings.mjs +2 -6
  87. package/bin/state/iterate-stall.d.mts +7 -15
  88. package/bin/state/iterate-stall.mjs +6 -64
  89. package/bin/state/rest-cache.d.mts +1 -1
  90. package/bin/state/rest-cache.mjs +1 -1
  91. package/bin/state/stack-stall.d.mts +16 -0
  92. package/bin/state/stack-stall.mjs +12 -0
  93. package/bin/state/stall-state-store.d.mts +37 -0
  94. package/bin/state/stall-state-store.mjs +74 -0
  95. package/bin/types/escalate.d.mts +1 -1
  96. package/bin/types/github.d.mts +1 -1
  97. package/bin/types/iterate.d.mts +2 -1
  98. package/bin/types/merge-requirements.d.mts +19 -0
  99. package/bin/types/poll-summary.d.mts +5 -0
  100. package/bin/types/report.d.mts +1 -1
  101. package/package.json +1 -1
  102. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  103. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  104. package/plugins/pr-shepherd/.mcp.json +1 -1
@@ -1,6 +1,9 @@
1
1
  function writeTickProgress(tick, elapsedSeconds, detail) {
2
2
  process.stderr.write(`[poll tick ${tick} / +${elapsedSeconds}s] WAIT — ${detail}\n`);
3
3
  }
4
+ function waitReason(result) {
5
+ return result.log.replace(/^WAIT: /, "");
6
+ }
4
7
  function waitSignature(result) {
5
8
  const activity = result.activity ?? {
6
9
  commitCount: 0,
@@ -36,7 +39,10 @@ export function writeWaitProgress(opts) {
36
39
  const elapsedSeconds = Math.round(opts.elapsedMs / 1000);
37
40
  const sleepSeconds = Math.round(opts.sleepMs / 1000);
38
41
  if (!opts.quietStatus) {
39
- writeTickProgress(opts.tick, elapsedSeconds, opts.verbose ? `sleeping ${sleepSeconds}s` : `still running; next tick in ${sleepSeconds}s`);
42
+ const reason = waitReason(opts.result);
43
+ writeTickProgress(opts.tick, elapsedSeconds, opts.verbose
44
+ ? `${reason} — sleeping ${sleepSeconds}s`
45
+ : `${reason}; next tick in ${sleepSeconds}s`);
40
46
  return opts.lastWaitSignature;
41
47
  }
42
48
  const signature = waitSignature(opts.result);
@@ -1,3 +1,8 @@
1
- import type { PollSummaryResult } from "../types.mts";
1
+ import type { PollSummaryItem, PollSummaryResult } from "../types.mts";
2
2
  /** Keep aggregate JSON, Markdown, and MCP instructions on one projection. */
3
3
  export declare function withPollSummaryInstructions(result: PollSummaryResult, mergeRequested: boolean): PollSummaryResult;
4
+ /** 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): {
6
+ result: PollSummaryResult;
7
+ idle?: PollSummaryItem[];
8
+ };
@@ -1,15 +1,21 @@
1
1
  /* eslint-disable max-lines */
2
2
  import { buildQuotaAwareContinuation } from "../quota-warning.mjs";
3
3
  import { explicitInstructions } from "./poll-summary-explicit-instructions.mjs";
4
+ import { appendAutonomousInstructions, appendHumanHandoffInstructions, findHumanHandoffs, idleWaitPlan, isStackLayerReady, planBottomDrain, retargetWaitPlan, stackPosition, } from "./stack-drain.mjs";
5
+ import { appendMarkReadyInstructions, splitStackWork } from "./stack-work.mjs";
4
6
  /** Keep aggregate JSON, Markdown, and MCP instructions on one projection. */
5
7
  export function withPollSummaryInstructions(result, mergeRequested) {
8
+ return planPollSummary(result, mergeRequested).result;
9
+ }
10
+ /** The projected summary, plus the idle layers when the stack plan can only wait on them. */
11
+ export function planPollSummary(result, mergeRequested) {
6
12
  if (result.selection.kind !== "stack") {
7
- return { ...result, instructions: explicitInstructions(result) };
13
+ return { result: { ...result, instructions: explicitInstructions(result) } };
8
14
  }
9
- const prs = [...result.prs].sort((left, right) => position(left) - position(right));
15
+ const prs = [...result.prs].sort((left, right) => stackPosition(left) - stackPosition(right));
10
16
  const staleChildren = new Set(result.stackAncestry?.map((gap) => gap.childPr) ?? []);
11
- const firstUnready = prs.find((item) => item.state === "OPEN" && (!isReady(item) || staleChildren.has(item.pr)));
12
- const blocked = prs.map((item) => firstUnready && item.state === "OPEN" && position(item) > position(firstUnready)
17
+ const firstUnready = prs.find((item) => item.state === "OPEN" && (!isStackLayerReady(item) || staleChildren.has(item.pr)));
18
+ const blocked = prs.map((item) => firstUnready && item.state === "OPEN" && stackPosition(item) > stackPosition(firstUnready)
13
19
  ? {
14
20
  ...item,
15
21
  ...(["cancel", "mark_ready", "merge"].includes(item.action) && {
@@ -21,10 +27,11 @@ export function withPollSummaryInstructions(result, mergeRequested) {
21
27
  item.pollCommand && {
22
28
  pollCommand: item.pollCommand.replace(" --until-terminal", " --timeout 1s --debounce 0s") +
23
29
  (item.pollCommand.includes("--no-auto-mark-ready") ? "" : " --no-auto-mark-ready"),
30
+ pollProbe: true,
24
31
  }),
25
32
  }
26
33
  : item.state === "OPEN" &&
27
- (!isReady(item) || staleChildren.has(item.pr)) &&
34
+ (!isStackLayerReady(item) || staleChildren.has(item.pr)) &&
28
35
  ["cancel", "merge"].includes(item.action)
29
36
  ? {
30
37
  ...item,
@@ -68,50 +75,45 @@ export function withPollSummaryInstructions(result, mergeRequested) {
68
75
  instructions.push(buildQuotaAwareContinuation(result.quotaWarning, `${instructions.length + 1}. After completing the stack action,`));
69
76
  }
70
77
  return {
71
- ...projected,
72
- reason: planned.action === "cancel"
73
- ? "all_terminal"
74
- : planned.waiting
75
- ? result.reason === "timeout"
76
- ? "timeout"
77
- : "waiting"
78
- : "actionable",
79
- stackMergeable: planned.stackMergeable,
80
- nextAction: planned.action,
81
- instructions,
78
+ result: {
79
+ ...projected,
80
+ reason: planned.action === "cancel"
81
+ ? "all_terminal"
82
+ : planned.waiting
83
+ ? result.reason === "timeout"
84
+ ? "timeout"
85
+ : "waiting"
86
+ : "actionable",
87
+ stackMergeable: planned.stackMergeable,
88
+ nextAction: planned.action,
89
+ instructions,
90
+ },
91
+ ...(planned.idle && { idle: planned.idle }),
82
92
  };
83
93
  }
84
94
  function planStack(result, mergeRequested) {
85
95
  const open = result.prs.filter((item) => item.state === "OPEN");
86
- const lastOpen = open.at(-1);
87
- const closedDependencyPr = result.prs.find((item) => item.state === "CLOSED" && lastOpen && position(item) < position(lastOpen));
88
- const unverifiedLayer = result.prs.find((item) => item.state !== "OPEN" && item.state !== "MERGED");
89
96
  const gaps = result.stackAncestry ?? [];
90
- const stackMergeable = gaps.length === 0 && open.every(isReady);
91
- const candidates = open.filter((item) => !isReady(item) || gaps.some((gap) => gap.childPr === item.pr));
92
- const autonomousCandidates = candidates.filter((item) => item.action !== "escalate");
93
- const runnableCandidates = autonomousCandidates.filter((item) => item.pollCommand);
94
- const missingCommands = autonomousCandidates.filter((item) => !item.pollCommand);
95
- const escalated = result.prs.filter((item) => item.action === "escalate");
96
- if (closedDependencyPr || unverifiedLayer || escalated.length > 0) {
97
+ const staleChildren = new Set(gaps.map((gap) => gap.childPr));
98
+ const stackMergeable = gaps.length === 0 && open.every(isStackLayerReady);
99
+ const work = splitStackWork(open.filter((item) => (!isStackLayerReady(item) || staleChildren.has(item.pr)) && item.action !== "escalate"), staleChildren);
100
+ const runnableCandidates = work.sessions.filter((item) => item.pollCommand);
101
+ const missingCommands = work.sessions.filter((item) => !item.pollCommand);
102
+ const agentWork = runnableCandidates.length > 0 || work.markReady.length > 0;
103
+ const drain = planBottomDrain(result, mergeRequested);
104
+ if (drain)
105
+ return drain;
106
+ const handoffs = findHumanHandoffs(result);
107
+ if (handoffs) {
97
108
  const instructions = [];
98
109
  appendAutonomousInstructions(instructions, runnableCandidates);
99
- const stop = runnableCandidates.length === 0;
100
- if (closedDependencyPr) {
101
- instructions.push(`${instructions.length + 1}. PR #${closedDependencyPr.pr} was closed without merging below an open layer. ${stop ? "Stop and ask" : "After autonomous shepherding, ask"} the stack owner whether to restore that dependency or rebuild the upper branches.`);
102
- }
103
- if (unverifiedLayer && unverifiedLayer.pr !== closedDependencyPr?.pr) {
104
- instructions.push(`${instructions.length + 1}. PR #${unverifiedLayer.pr} has state \`${unverifiedLayer.state}\` rather than open or merged. ${stop ? "Stop and ask" : "After autonomous shepherding, ask"} the stack owner to reconcile this layer before declaring the stack complete.`);
105
- }
106
- for (const item of escalated) {
107
- if (item.pr === closedDependencyPr?.pr || item.pr === unverifiedLayer?.pr)
108
- continue;
109
- instructions.push(`${instructions.length + 1}. PR #${item.pr} requires human action (${item.reasons.join(", ")}). ${stop ? "Stop for that decision." : "Keep shepherding other PRs before the handoff."}`);
110
- }
110
+ appendMarkReadyInstructions(instructions, work.markReady);
111
+ const stop = !agentWork;
112
+ appendHumanHandoffInstructions(instructions, handoffs, stop);
111
113
  for (const item of missingCommands) {
112
114
  instructions.push(`${instructions.length + 1}. PR #${item.pr} needs a one-PR session, but Shepherd could not produce its command. Ask for direction.`);
113
115
  }
114
- if (runnableCandidates.length > 0) {
116
+ if (agentWork) {
115
117
  instructions.push(`${instructions.length + 1}. After the listed one-PR sessions, rerun this same \`--stack\` selector. Stop for the human handoff only when no autonomous shepherding remains.`);
116
118
  }
117
119
  return { action: stop ? "escalate" : "shepherd", stackMergeable: false, instructions };
@@ -127,20 +129,20 @@ function planStack(result, mergeRequested) {
127
129
  if (missingCommands.length > 0) {
128
130
  const instructions = [];
129
131
  appendAutonomousInstructions(instructions, runnableCandidates);
132
+ appendMarkReadyInstructions(instructions, work.markReady);
130
133
  for (const item of missingCommands) {
131
- instructions.push(`${instructions.length + 1}. PR #${item.pr} needs a one-PR session, but Shepherd could not produce its command. ${runnableCandidates.length === 0 ? "Stop and ask" : "After autonomous shepherding, ask"} for direction.`);
134
+ instructions.push(`${instructions.length + 1}. PR #${item.pr} needs a one-PR session, but Shepherd could not produce its command. ${agentWork ? "After autonomous shepherding, ask" : "Stop and ask"} for direction.`);
132
135
  }
133
- if (runnableCandidates.length > 0) {
136
+ if (agentWork) {
134
137
  instructions.push(`${instructions.length + 1}. After the listed one-PR sessions, rerun this same \`--stack\` selector. Stop for the human handoff only when no autonomous shepherding remains.`);
135
138
  }
136
- return {
137
- action: runnableCandidates.length > 0 ? "shepherd" : "escalate",
138
- stackMergeable: false,
139
- instructions,
140
- };
139
+ return { action: agentWork ? "shepherd" : "escalate", stackMergeable: false, instructions };
141
140
  }
141
+ if (!agentWork)
142
+ return idleWaitPlan(work.idle);
142
143
  const instructions = [];
143
- appendAutonomousInstructions(instructions, autonomousCandidates);
144
+ appendAutonomousInstructions(instructions, work.sessions);
145
+ appendMarkReadyInstructions(instructions, work.markReady);
144
146
  instructions.push(`${instructions.length + 1}. After the selected one-PR sessions, rerun this same \`--stack\` selector.`);
145
147
  return { action: "shepherd", stackMergeable: false, instructions };
146
148
  }
@@ -171,49 +173,11 @@ function planStack(result, mergeRequested) {
171
173
  instructions,
172
174
  };
173
175
  }
174
- const stackNumber = result.selection.kind === "stack" ? result.selection.stackNumber : 0;
175
- return {
176
- action: "merge",
177
- stackMergeable: true,
178
- instructions: [
179
- "1. Check `gh stack merge --help`. If the `gh-stack` extension is unavailable, run `gh extension install github/gh-stack`, then rerun this same `--stack --merge` selector before merging.",
180
- `2. Stack #${stackNumber} in \`${result.repo}\` is mergeable through PR #${open.at(-1).pr}. Run \`GH_REPO=${result.repo} gh stack merge --yes --squash ${stackNumber}\` to merge the whole native stack or enqueue it when the base uses a merge queue.`,
181
- "3. After the merge attempt, rerun this same `--stack --merge` selector until every layer is merged (`CANCEL`); shepherd any layer that GitHub rejects or ejects.",
182
- ],
183
- };
176
+ return retargetWaitPlan(open[0]);
184
177
  }
185
178
  function closedDependency(items, pr) {
186
179
  const open = items.filter((item) => item.state === "OPEN");
187
180
  const lastOpen = open.at(-1);
188
181
  return Boolean(lastOpen &&
189
- items.some((item) => item.pr === pr && item.state === "CLOSED" && position(item) < position(lastOpen)));
190
- }
191
- function appendAutonomousInstructions(instructions, candidates) {
192
- if (candidates.length === 0)
193
- return;
194
- instructions.push(`${instructions.length + 1}. Start or delegate the relevant one-PR sessions below; review and CI work on separate layers can proceed concurrently.`);
195
- for (const item of candidates) {
196
- instructions.push(item.pollCommand
197
- ? `${instructions.length + 1}. Run \`${item.pollCommand}\` for PR #${item.pr}${item.blockedByPr ? ` (stack-blocked by PR #${item.blockedByPr})` : ""}${item.queueRemoval ? `; GitHub removed it from the merge queue (${item.queueRemoval.reason ?? "unknown reason"})` : ""}.`
198
- : `${instructions.length + 1}. PR #${item.pr} needs a one-PR Shepherd session, but no command was available.`);
199
- }
200
- instructions.push(`${instructions.length + 1}. Keep upper draft PRs in draft until every lower layer has completed Shepherd READY.`);
201
- }
202
- function isReady(item) {
203
- return (item.state === "OPEN" &&
204
- item.stack !== undefined &&
205
- item.readyReceipt === true &&
206
- !item.isDraft &&
207
- !item.queueRemoval &&
208
- item.mergeable !== "CONFLICTING" &&
209
- item.mergeStateStatus !== "DIRTY" &&
210
- (item.isInMergeQueue || item.mergeable === "MERGEABLE") &&
211
- (item.isInMergeQueue ||
212
- !["DIRTY", "BEHIND", "UNKNOWN", "BLOCKED", "HAS_HOOKS"].includes(item.mergeStateStatus)) &&
213
- (item.checks?.failing ?? 0) === 0 &&
214
- (item.isInMergeQueue || (item.checks?.inProgress ?? 0) === 0) &&
215
- (item.review?.actionable ?? 0) === 0);
216
- }
217
- function position(item) {
218
- return item.stack?.position ?? Number.MAX_SAFE_INTEGER;
182
+ items.some((item) => item.pr === pr && item.state === "CLOSED" && stackPosition(item) < stackPosition(lastOpen)));
219
183
  }
@@ -6,8 +6,9 @@ import { withApiTelemetryScope, summarizeApiTelemetry } from "../github/api-tele
6
6
  import { fetchPollSummary } from "../github/poll-summary.mjs";
7
7
  import { sleep } from "../util/sleep.mjs";
8
8
  import { aggregateQuotaWarning, graphqlQuotaPollIntervalMs, pollGraphQlRetryAfterMs, } from "./poll-quota.mjs";
9
- import { withPollSummaryInstructions } from "./poll-summary-instructions.mjs";
9
+ import { planPollSummary, withPollSummaryInstructions } from "./poll-summary-instructions.mjs";
10
10
  import { summaryStatusSignature } from "./poll-summary-signature.mjs";
11
+ import { applyStackStallGuard } from "./stack-stall.mjs";
11
12
  const MAX_TIMER_MS = 2 ** 31 - 1;
12
13
  const TIMER_DRIFT_TOLERANCE_MS = 500;
13
14
  export function runPollSummary(opts) {
@@ -21,7 +22,7 @@ async function runPollSummaryCore(opts) {
21
22
  const fetched = await fetchPollSummary(opts, repo);
22
23
  const allTerminal = fetched.prs.every((item) => item.action === "cancel");
23
24
  const actionable = fetched.prs.some((item) => item.action !== "wait" && item.action !== "cancel");
24
- return withPollSummaryInstructions({
25
+ const planned = planPollSummary({
25
26
  mode: "summary",
26
27
  repo: `${repo.owner}/${repo.name}`,
27
28
  selection: fetched.selection,
@@ -29,6 +30,7 @@ async function runPollSummaryCore(opts) {
29
30
  prs: fetched.prs,
30
31
  ...(fetched.stackAncestry?.length && { stackAncestry: fetched.stackAncestry }),
31
32
  }, opts.merge === true);
33
+ return applyStackStallGuard(planned, repo, opts.stallTimeoutSeconds ?? loadConfig().iterate.stallTimeoutMinutes * 60);
32
34
  }
33
35
  async function runAggregatePollCore(opts) {
34
36
  const intervalMs = Math.min(opts.intervalSeconds * 1000, MAX_TIMER_MS);
@@ -1,4 +1,5 @@
1
1
  import { runIterate } from "./iterate/index.mjs";
2
+ import { heldByLowerLayer } from "./iterate/parent-first.mjs";
2
3
  import { sleep } from "../util/sleep.mjs";
3
4
  import { withPollApiUsage } from "./poll-run.mjs";
4
5
  import { loadConfig } from "../config/load.mjs";
@@ -97,7 +98,8 @@ async function runPollCore(opts) {
97
98
  }
98
99
  break;
99
100
  }
100
- if (lastResult.action === "wait" && !pastDebounce) {
101
+ // A held draft waits on another layer's session, so hand it straight back.
102
+ if (lastResult.action === "wait" && !pastDebounce && !heldByLowerLayer(lastResult)) {
101
103
  if (pendingQuotaWarning === undefined)
102
104
  debounceUntil = null;
103
105
  const elapsedMs = Date.now() - start;
@@ -2,8 +2,10 @@
2
2
  * Ready-delay state machine for the shepherd iterate loop.
3
3
  *
4
4
  * When all READY conditions hold, shepherd writes a `ready-since.txt` marker
5
- * to the state dir. The loop continues until the PR has been READY for
6
- * `readyDelaySeconds` consecutively. Any not-READY result resets the timer.
5
+ * bound to the PR head to the state dir. The loop continues until the PR has
6
+ * been READY on that head for `readyDelaySeconds` consecutively. Any not-READY
7
+ * result, or a different head, resets the timer. An elapsed marker stays until
8
+ * the caller consumes it with `clearReadyDelay`.
7
9
  */
8
10
  interface ReadyDelayState {
9
11
  isReady: boolean;
@@ -25,7 +27,10 @@ interface ReadyDelayState {
25
27
  * When `shouldCancel == true`, the formatter tells loop-capable agents to cancel
26
28
  * the loop and tells one-shot agents to stop.
27
29
  */
28
- export declare function updateReadyDelay(prNumber: number, isReady: boolean, readyDelaySeconds: number, owner: string, repo: string, options?: {
29
- retainElapsed?: boolean;
30
+ export declare function updateReadyDelay(prNumber: number, isReady: boolean, readyDelaySeconds: number, owner: string, repo: string, options: {
31
+ headSha: string;
32
+ alreadyElapsed?: boolean;
30
33
  }): Promise<ReadyDelayState>;
34
+ /** Delete the ready-delay marker once an elapsed delay has been consumed. */
35
+ export declare function clearReadyDelay(prNumber: number, owner: string, repo: string): Promise<void>;
31
36
  export {};
@@ -2,8 +2,10 @@
2
2
  * Ready-delay state machine for the shepherd iterate loop.
3
3
  *
4
4
  * When all READY conditions hold, shepherd writes a `ready-since.txt` marker
5
- * to the state dir. The loop continues until the PR has been READY for
6
- * `readyDelaySeconds` consecutively. Any not-READY result resets the timer.
5
+ * bound to the PR head to the state dir. The loop continues until the PR has
6
+ * been READY on that head for `readyDelaySeconds` consecutively. Any not-READY
7
+ * result, or a different head, resets the timer. An elapsed marker stays until
8
+ * the caller consumes it with `clearReadyDelay`.
7
9
  */
8
10
  import { readFile, writeFile, mkdir, unlink } from "node:fs/promises";
9
11
  import { dirname } from "node:path";
@@ -18,47 +20,59 @@ import { resolvePrStatePath } from "../state/base.mjs";
18
20
  * When `shouldCancel == true`, the formatter tells loop-capable agents to cancel
19
21
  * the loop and tells one-shot agents to stop.
20
22
  */
21
- export async function updateReadyDelay(prNumber, isReady, readyDelaySeconds, owner, repo, options = {}) {
23
+ export async function updateReadyDelay(prNumber, isReady, readyDelaySeconds, owner, repo, options) {
22
24
  const markerPath = readySincePath(prNumber, owner, repo);
23
25
  if (!isReady) {
24
26
  // Reset the timer.
25
27
  await safeUnlink(markerPath);
26
28
  return { isReady: false, shouldCancel: false, remainingSeconds: readyDelaySeconds };
27
29
  }
30
+ // Durable evidence (a current READY receipt) already proves the delay
31
+ // elapsed for this exact state, so a re-poll must not start a fresh timer.
32
+ if (options.alreadyElapsed) {
33
+ return { isReady: true, shouldCancel: true, remainingSeconds: 0 };
34
+ }
28
35
  // PR is READY — check or create the marker.
29
36
  const now = Math.floor(Date.now() / 1000);
30
- let readySince;
31
- try {
32
- const raw = await readFile(markerPath, "utf8");
33
- readySince = parseInt(raw.trim(), 10);
34
- // Reset if the stored value is not finite or is in the future (clock skew,
35
- // corrupted file, or manual edit). A future timestamp would produce a
36
- // negative elapsed value and an inflated remainingSeconds.
37
- if (!Number.isFinite(readySince) || readySince > now) {
38
- readySince = now;
39
- await safeWriteFile(markerPath, String(now));
40
- }
41
- }
42
- catch {
43
- // Marker doesn't exist yet — create it.
37
+ let readySince = await readReadySince(markerPath, options.headSha);
38
+ // Reset if the marker is missing, names another head, is not finite, or is
39
+ // in the future (clock skew, corrupted file, or manual edit). A future
40
+ // timestamp would produce a negative elapsed value and an inflated
41
+ // remainingSeconds.
42
+ if (readySince === null || readySince > now) {
44
43
  readySince = now;
45
- await safeWriteFile(markerPath, String(now));
44
+ await safeWriteFile(markerPath, `${now} ${options.headSha}`);
46
45
  }
47
46
  const elapsed = now - readySince;
48
47
  const remaining = readyDelaySeconds - elapsed;
49
48
  if (remaining <= 0) {
50
- if (!options.retainElapsed)
51
- await safeUnlink(markerPath);
52
49
  return { isReady: true, shouldCancel: true, remainingSeconds: 0 };
53
50
  }
54
51
  return { isReady: true, shouldCancel: false, remainingSeconds: remaining };
55
52
  }
53
+ /** Delete the ready-delay marker once an elapsed delay has been consumed. */
54
+ export async function clearReadyDelay(prNumber, owner, repo) {
55
+ await safeUnlink(readySincePath(prNumber, owner, repo));
56
+ }
56
57
  // ---------------------------------------------------------------------------
57
58
  // Helpers
58
59
  // ---------------------------------------------------------------------------
59
60
  function readySincePath(pr, owner, repo) {
60
61
  return resolvePrStatePath({ owner, repo, pr }, "ready-since.txt");
61
62
  }
63
+ /** The marker's start time, or null when it is missing, malformed, or bound to another head. */
64
+ async function readReadySince(path, headSha) {
65
+ let raw;
66
+ try {
67
+ raw = await readFile(path, "utf8");
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ const [since, head] = raw.trim().split(" ");
73
+ const readySince = Number(since);
74
+ return head === headSha && Number.isSafeInteger(readySince) ? readySince : null;
75
+ }
62
76
  async function safeUnlink(path) {
63
77
  try {
64
78
  await unlink(path);
@@ -1,3 +1,4 @@
1
+ import { buildPrShepherdCommand } from "../cli/runner.mjs";
1
2
  export const SHEPHERD_JOURNAL_SECTION = "Shepherd Journal";
2
3
  export const SHEPHERD_JOURNAL_SECTION_PATTERN = /^##\s+Shepherd\s+Journal$/;
3
4
  export const SHEPHERD_JOURNAL_DETAILS_OPEN = "<details>";
@@ -12,5 +13,7 @@ export const SHEPHERD_JOURNAL_FIRST_LOOK_GUIDANCE = "Review each body under `##
12
13
  * of being re-emitted every tick (see CLAUDE.md "Keep skills and loop prompts minimal").
13
14
  */
14
15
  export function buildShepherdJournalInstruction(prReference) {
15
- return `For any substantial decision or rejection, append \`- <decision>\` to Shepherd Journal with \`pr-shepherd apply journal ${prReference} '- <decision>'\`. See "Shepherd Journal" in the pr-shepherd skill for citation conventions.`;
16
+ // Single-quote the placeholder so a substituted decision stays literal in the shell.
17
+ const command = `${buildPrShepherdCommand(["apply", "journal", String(prReference)]).text} '- <decision>'`;
18
+ return `For any substantial decision or rejection, append \`- <decision>\` to Shepherd Journal with \`${command}\`. See "Shepherd Journal" in the pr-shepherd skill for citation conventions.`;
16
19
  }
@@ -0,0 +1,35 @@
1
+ import type { PollSummaryItem, PollSummaryResult, StackNextAction } from "../types.mts";
2
+ export interface StackPlan {
3
+ action: StackNextAction;
4
+ stackMergeable: boolean;
5
+ waiting?: boolean;
6
+ /** Set only by {@link idleWaitPlan}: the layers whose one-PR probes could only report waiting. */
7
+ idle?: PollSummaryItem[];
8
+ instructions: string[];
9
+ }
10
+ /**
11
+ * Merge the ready bottom layer by PR number. `gh stack merge <n>` tries a stack
12
+ * number first, but stack numbers come from the repository's issue and pull
13
+ * request sequence, so a PR number never names a stack.
14
+ */
15
+ export declare function planBottomDrain(result: PollSummaryResult, mergeRequested: boolean): StackPlan | undefined;
16
+ /**
17
+ * A merge-requested, fully ready stack whose bottom open layer still targets
18
+ * the merged layer below it until GitHub retargets it onto the stack base.
19
+ */
20
+ export declare function retargetWaitPlan(first: PollSummaryItem): StackPlan;
21
+ /** Every remaining layer only waits: on CI or merge state, or on a lower layer that does. */
22
+ export declare function idleWaitPlan(idle: PollSummaryItem[]): StackPlan;
23
+ export declare function describeIdleLayers(idle: PollSummaryItem[]): string;
24
+ export declare function appendAutonomousInstructions(instructions: string[], candidates: PollSummaryItem[]): void;
25
+ /** Layers only a human can resolve: a closed dependency, an unverified state, or an escalation. */
26
+ export interface HumanHandoffs {
27
+ closedDependency?: PollSummaryItem;
28
+ unverified?: PollSummaryItem;
29
+ escalated: PollSummaryItem[];
30
+ }
31
+ export declare function findHumanHandoffs(result: PollSummaryResult): HumanHandoffs | undefined;
32
+ /** Name every human handoff; `stop` when no autonomous work precedes it. */
33
+ export declare function appendHumanHandoffInstructions(instructions: string[], { closedDependency, unverified, escalated }: HumanHandoffs, stop: boolean): void;
34
+ export declare function isStackLayerReady(item: PollSummaryItem): boolean;
35
+ export declare function stackPosition(item: PollSummaryItem): number;
@@ -0,0 +1,129 @@
1
+ import { stackLayerBlockReason } from "./stack-layer-readiness.mjs";
2
+ import { appendMarkReadyInstructions, splitStackWork } from "./stack-work.mjs";
3
+ /**
4
+ * The lowest open layer when it can merge by itself: every layer below it
5
+ * merged, GitHub retargeted it onto the stack base, it holds a current READY
6
+ * receipt, and no layer is already in the merge queue.
7
+ */
8
+ function drainableBottom(result) {
9
+ const layers = [...result.prs].sort((left, right) => stackPosition(left) - stackPosition(right));
10
+ const bottom = layers.find((item) => item.state !== "MERGED");
11
+ if (!bottom || !isStackLayer(bottom) || bottom.state !== "OPEN")
12
+ return undefined;
13
+ if (bottom.action === "escalate" || !isStackLayerReady(bottom))
14
+ return undefined;
15
+ if (bottom.baseRefName !== bottom.stack.baseRefName)
16
+ return undefined;
17
+ if (result.stackAncestry?.some((gap) => gap.childPr === bottom.pr))
18
+ return undefined;
19
+ if (layers.some((item) => item.state === "OPEN" && item.isInMergeQueue))
20
+ return undefined;
21
+ return bottom;
22
+ }
23
+ /**
24
+ * Merge the ready bottom layer by PR number. `gh stack merge <n>` tries a stack
25
+ * number first, but stack numbers come from the repository's issue and pull
26
+ * request sequence, so a PR number never names a stack.
27
+ */
28
+ export function planBottomDrain(result, mergeRequested) {
29
+ if (!mergeRequested)
30
+ return undefined;
31
+ const bottom = drainableBottom(result);
32
+ if (!bottom)
33
+ return undefined;
34
+ const gaps = result.stackAncestry ?? [];
35
+ const staleChildren = new Set(gaps.map((gap) => gap.childPr));
36
+ const open = result.prs.filter((item) => item.state === "OPEN");
37
+ const uppers = splitStackWork(open.filter((item) => item.pr !== bottom.pr &&
38
+ item.action !== "escalate" &&
39
+ (!isStackLayerReady(item) || staleChildren.has(item.pr))), staleChildren);
40
+ const instructions = [
41
+ `1. PR #${bottom.pr} is the bottom open layer of stack #${bottom.stack.number} in \`${result.repo}\` and is ready. Run \`GH_REPO=${result.repo} gh stack merge ${bottom.pr} --yes --squash\` to merge that layer alone, or to enqueue it when the base uses a merge queue. If \`gh stack\` is an unknown command, run \`gh extension install github/gh-stack\` first.`,
42
+ ];
43
+ appendAutonomousInstructions(instructions, uppers.sessions);
44
+ appendMarkReadyInstructions(instructions, uppers.markReady);
45
+ const handoffs = findHumanHandoffs(result);
46
+ if (handoffs)
47
+ appendHumanHandoffInstructions(instructions, handoffs, false);
48
+ instructions.push(`${instructions.length + 1}. After the merge attempt, rerun this same \`--stack --merge\` selector; GitHub retargets the next layer onto \`${bottom.stack.baseRefName}\`. Shepherd any layer that GitHub rejects or ejects.`);
49
+ return {
50
+ action: "merge",
51
+ stackMergeable: gaps.length === 0 && open.every(isStackLayerReady),
52
+ instructions,
53
+ };
54
+ }
55
+ /**
56
+ * A merge-requested, fully ready stack whose bottom open layer still targets
57
+ * the merged layer below it until GitHub retargets it onto the stack base.
58
+ */
59
+ export function retargetWaitPlan(first) {
60
+ return {
61
+ action: "wait",
62
+ stackMergeable: true,
63
+ waiting: true,
64
+ instructions: [
65
+ `1. PR #${first.pr} still targets \`${first.baseRefName}\` rather than \`${first.stack?.baseRefName}\`; wait for GitHub to retarget it before merging. Recheck at the configured polling cadence.`,
66
+ ],
67
+ };
68
+ }
69
+ /** Every remaining layer only waits: on CI or merge state, or on a lower layer that does. */
70
+ export function idleWaitPlan(idle) {
71
+ return {
72
+ action: "wait",
73
+ stackMergeable: false,
74
+ waiting: true,
75
+ idle,
76
+ instructions: [
77
+ `1. No one-PR session can advance the stack yet: ${describeIdleLayers(idle)}. Recheck at the configured polling cadence.`,
78
+ ],
79
+ };
80
+ }
81
+ export function describeIdleLayers(idle) {
82
+ return idle
83
+ .map((item) => `PR #${item.pr} (${item.blockedByPr ? `stack-blocked by PR #${item.blockedByPr}` : item.reasons.join(", ")})`)
84
+ .join("; ");
85
+ }
86
+ export function appendAutonomousInstructions(instructions, candidates) {
87
+ if (candidates.length === 0)
88
+ return;
89
+ instructions.push(`${instructions.length + 1}. Start or delegate the relevant one-PR sessions below; review and CI work on separate layers can proceed concurrently.`);
90
+ for (const item of candidates) {
91
+ instructions.push(item.pollCommand
92
+ ? `${instructions.length + 1}. Run \`${item.pollCommand}\` for PR #${item.pr}${item.blockedByPr ? ` (stack-blocked by PR #${item.blockedByPr})` : ""}${item.queueRemoval ? `; GitHub removed it from the merge queue (${item.queueRemoval.reason ?? "unknown reason"})` : ""}.`
93
+ : `${instructions.length + 1}. PR #${item.pr} needs a one-PR Shepherd session, but no command was available.`);
94
+ }
95
+ instructions.push(`${instructions.length + 1}. Keep upper draft PRs in draft until every lower layer has completed Shepherd READY.`);
96
+ }
97
+ export function findHumanHandoffs(result) {
98
+ const lastOpen = result.prs.filter((item) => item.state === "OPEN").at(-1);
99
+ const closedDependency = result.prs.find((item) => item.state === "CLOSED" && lastOpen && stackPosition(item) < stackPosition(lastOpen));
100
+ const unverified = result.prs.find((item) => item.state !== "OPEN" && item.state !== "MERGED");
101
+ const escalated = result.prs.filter((item) => item.action === "escalate");
102
+ return closedDependency || unverified || escalated.length > 0
103
+ ? { closedDependency, unverified, escalated }
104
+ : undefined;
105
+ }
106
+ /** Name every human handoff; `stop` when no autonomous work precedes it. */
107
+ export function appendHumanHandoffInstructions(instructions, { closedDependency, unverified, escalated }, stop) {
108
+ const ask = stop ? "Stop and ask" : "After autonomous shepherding, ask";
109
+ if (closedDependency) {
110
+ instructions.push(`${instructions.length + 1}. PR #${closedDependency.pr} was closed without merging below an open layer. ${ask} the stack owner whether to restore that dependency or rebuild the upper branches.`);
111
+ }
112
+ if (unverified && unverified.pr !== closedDependency?.pr) {
113
+ instructions.push(`${instructions.length + 1}. PR #${unverified.pr} has state \`${unverified.state}\` rather than open or merged. ${ask} the stack owner to reconcile this layer before declaring the stack complete.`);
114
+ }
115
+ for (const item of escalated) {
116
+ if (item.pr === closedDependency?.pr || item.pr === unverified?.pr)
117
+ continue;
118
+ instructions.push(`${instructions.length + 1}. PR #${item.pr} requires human action (${item.reasons.join(", ")}). ${stop ? "Stop for that decision." : "Keep shepherding other PRs before the handoff."}`);
119
+ }
120
+ }
121
+ export function isStackLayerReady(item) {
122
+ return item.stack !== undefined && stackLayerBlockReason(item) === undefined;
123
+ }
124
+ export function stackPosition(item) {
125
+ return item.stack?.position ?? Number.MAX_SAFE_INTEGER;
126
+ }
127
+ function isStackLayer(item) {
128
+ return item.stack !== undefined;
129
+ }
@@ -0,0 +1,7 @@
1
+ import type { PollSummaryItem, StackLayerBlockReason } from "../types.mts";
2
+ /**
3
+ * Why a native stack layer does not yet let the layers above it advance, or undefined
4
+ * when it does. The stack selector and an upper draft's parent-first mark-ready check
5
+ * share this predicate so both always name the same blocking layer.
6
+ */
7
+ export declare function stackLayerBlockReason(item: PollSummaryItem): StackLayerBlockReason | undefined;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Why a native stack layer does not yet let the layers above it advance, or undefined
3
+ * when it does. The stack selector and an upper draft's parent-first mark-ready check
4
+ * share this predicate so both always name the same blocking layer.
5
+ */
6
+ export function stackLayerBlockReason(item) {
7
+ if (item.state !== "OPEN")
8
+ return "closed";
9
+ if (item.isDraft)
10
+ return "draft";
11
+ if (item.mergeable === "CONFLICTING" || item.mergeStateStatus === "DIRTY")
12
+ return "conflicting";
13
+ // A receipt only establishes readiness after a merge-queue removal once
14
+ // the one-PR session has observed and acknowledged that exact removal.
15
+ // The aggregate projection preserves an unacknowledged removal here, so
16
+ // do not let its otherwise-current receipt promote a child draft.
17
+ if (item.queueRemoval)
18
+ return "queue-removal";
19
+ if ((item.checks?.failing ?? 0) > 0)
20
+ return "failing-checks";
21
+ if ((item.review?.actionable ?? 0) > 0)
22
+ return "review-work";
23
+ // Merge-group checks and the queue's own merge state supersede the source
24
+ // PR's while it is queued.
25
+ if (!item.isInMergeQueue) {
26
+ if ((item.checks?.inProgress ?? 0) > 0)
27
+ return "checks-in-progress";
28
+ if (item.mergeable !== "MERGEABLE" ||
29
+ ["BEHIND", "UNKNOWN", "BLOCKED", "HAS_HOOKS"].includes(item.mergeStateStatus))
30
+ return "merge-state";
31
+ }
32
+ // A layer that looks ready but has not completed its own one-PR receipt
33
+ // is not sufficient evidence for the layers above it.
34
+ return item.readyReceipt === true ? undefined : "no-ready-receipt";
35
+ }
@@ -0,0 +1,14 @@
1
+ import type { PollSummaryItem, PollSummaryResult } from "../types.mts";
2
+ /**
3
+ * A `--stack` plan that can only wait never reruns its layers' one-PR sessions, so their own
4
+ * stall guards cannot fire. Escalate `stall-timeout` once that idle plan's fingerprint stays
5
+ * unchanged for `stallTimeoutSeconds`; any other plan, or `0`, clears the timer. When the enabled
6
+ * timer cannot be read or written, escalate `stall-state-unavailable` instead of restarting it.
7
+ */
8
+ export declare function applyStackStallGuard(planned: {
9
+ result: PollSummaryResult;
10
+ idle?: PollSummaryItem[];
11
+ }, repo: {
12
+ owner: string;
13
+ name: string;
14
+ }, stallTimeoutSeconds: number): Promise<PollSummaryResult>;