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
@@ -0,0 +1,120 @@
1
+ import picomatch from "picomatch";
2
+ import { loadConfig } from "../../config/load.mjs";
3
+ import { parseWorkflowConcurrency } from "../../checks/workflow-concurrency.mjs";
4
+ import { readWorkflowFiles, workflowFileKey } from "./workflow-files.mjs";
5
+ /** Raw `pull_request_target` runs execute the base branch's workflow file, not the head's. */
6
+ const BASE_FILE_EVENT = "pull_request_target";
7
+ /**
8
+ * Display text from PR-controlled YAML or check names: control characters and backticks would
9
+ * let a name forge a `cancel:` line or close the code span around it.
10
+ */
11
+ function label(text) {
12
+ return text
13
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}`\s]+/gu, " ")
14
+ .trim()
15
+ .slice(0, 200);
16
+ }
17
+ function groupByRun(checks) {
18
+ const groups = new Map();
19
+ for (const check of checks) {
20
+ // Actions provenance: a third-party app's check can carry a run-looking id without a workflow.
21
+ if (check.runId === null || check.workflowName === undefined)
22
+ continue;
23
+ if (check.scope === "merge_group")
24
+ continue;
25
+ groups.set(check.runId, [...(groups.get(check.runId) ?? []), check]);
26
+ }
27
+ return groups;
28
+ }
29
+ /** The first `checks.never-cancel` pattern matching the workflow name or any check name. */
30
+ function matchedNeverCancel(patterns, names) {
31
+ return patterns.find((pattern) => {
32
+ const matches = picomatch(pattern, { nocase: true });
33
+ return names.some((name) => matches(name));
34
+ });
35
+ }
36
+ function fileRequest(report, group) {
37
+ const path = group.find((check) => check.workflowPath !== undefined)?.workflowPath;
38
+ const baseRead = group[0]?.event === BASE_FILE_EVENT;
39
+ // GitHub runs a `pull_request` workflow from the PR merge revision, not the head commit.
40
+ const ref = baseRead ? report.baseBranch : `refs/pull/${report.pr}/merge`;
41
+ return path && ref ? { ref, path, pinned: false } : undefined;
42
+ }
43
+ /**
44
+ * In-progress Actions runs on the head, with each workflow's raw `cancel-in-progress` and a
45
+ * `gh run cancel` command only for a run that sets it to the literal `true`. Empty when the
46
+ * feature is off or the PR is in the merge queue (a push would eject it). Reads each workflow
47
+ * file once per call, through one aliased GraphQL read.
48
+ */
49
+ export async function buildInProgressRuns(report, rerunAuthorized) {
50
+ const config = loadConfig();
51
+ if (!config.actions["cancel-runs-before-push"] || report.mergeQueue?.inQueue)
52
+ return [];
53
+ const groups = groupByRun(report.checks.inProgress);
54
+ if (groups.size === 0)
55
+ return [];
56
+ const requests = new Map([...groups].map(([runId, group]) => [runId, fileRequest(report, group)]));
57
+ const [owner, name] = report.repo.split("/");
58
+ const wanted = [...requests.values()].filter((request) => request !== undefined);
59
+ // Optional enrichment: a failed read (rate limit included) must not drop the triage output
60
+ // after the feedback's seen markers are written, so every file is reported unreadable.
61
+ const files = await readWorkflowFiles({ owner, name }, wanted).catch((error) => {
62
+ process.stderr.write(`workflow files unreadable: ${String(error)}\n`);
63
+ return new Map(wanted.map((request) => [workflowFileKey(request), { unreadable: "request failed" }]));
64
+ });
65
+ return [...groups].map(([runId, group]) => {
66
+ const request = requests.get(runId);
67
+ const file = request ? files.get(workflowFileKey(request)) : undefined;
68
+ const parsed = file && "text" in file ? parseWorkflowConcurrency(file.text) : undefined;
69
+ const why = !file ? "no workflow file" : "unreadable" in file ? file.unreadable : "parse error";
70
+ const concurrency = label(parsed ? parsed.raw : `unreadable (${why})`);
71
+ const workflowName = label(group[0].workflowName);
72
+ // Protection covers every check of the run, finished or not.
73
+ const siblings = [
74
+ ...report.checks.passing,
75
+ ...report.checks.failing,
76
+ ...report.checks.skipped,
77
+ ...report.checks.filtered,
78
+ ...group,
79
+ ]
80
+ .filter((check) => check.runId === runId)
81
+ .map((check) => check.name);
82
+ // `checks.ignore` drops a check's run association, so a protected name that is ignored
83
+ // protects every run.
84
+ const neverCancel = matchedNeverCancel(config.checks["never-cancel"], [
85
+ group[0].workflowName,
86
+ ...siblings,
87
+ ...(report.checks.ignoredNames ?? []),
88
+ ]);
89
+ const status = group.some((check) => check.status === "WAITING") ? "WAITING" : group[0].status;
90
+ const failed = report.checks.failing
91
+ .filter((check) => check.runId === runId)
92
+ .map((check) => label(check.name));
93
+ const cancel = parsed?.cancelInProgress &&
94
+ !neverCancel &&
95
+ status !== "WAITING" &&
96
+ rerunAuthorized &&
97
+ (group[0].event === "pull_request" || group[0].event === BASE_FILE_EVENT) &&
98
+ /^\d+$/.test(runId);
99
+ return {
100
+ runId,
101
+ workflowName,
102
+ status,
103
+ concurrency,
104
+ ...(failed.length > 0 && { failed, running: group.map((check) => label(check.name)) }),
105
+ ...(neverCancel !== undefined && { neverCancel: label(neverCancel) }),
106
+ ...(cancel && { cancelCommand: `gh run cancel ${runId} -R ${report.repo}` }),
107
+ };
108
+ });
109
+ }
110
+ /** The first fix step: cancel the superseded runs before editing, only when one has a command. */
111
+ export function buildCancelRunsInstruction(runs) {
112
+ const ids = runs.filter((run) => run.cancelCommand).map((run) => run.runId);
113
+ if (ids.length === 0)
114
+ return undefined;
115
+ const named = ids.length === 1 ? `run ${ids[0]}` : `runs ${ids.join(", ")}`;
116
+ const others = runs.length > ids.length
117
+ ? " Cancel no other run: a push does not cancel the rest, so cancelling them only discards their results."
118
+ : "";
119
+ return `If any item will need a code change, cancel ${named} now with ${ids.length === 1 ? "its `cancel:` command" : "their `cancel:` commands"}, before editing; ignore errors for runs that already finished.${others} If you will push nothing, leave every run running.`;
120
+ }
@@ -25,6 +25,7 @@ import { fingerprintRawSummaryPr } from "../../github/poll-summary-fingerprint.m
25
25
  import { currentQueueRemovalEvent } from "../../github/poll-summary-queue-removal.mjs";
26
26
  import { isCurrentSummaryReady } from "../../github/poll-summary-readiness.mjs";
27
27
  import { clearReadyReceipt, isReadyReceiptCurrent, readReadyReceipt, writeReadyReceipt, } from "../../state/ready-receipts.mjs";
28
+ import { withStackBoundary } from "./stack-boundary.mjs";
28
29
  import { findStaleNativeStackAncestry } from "./stale-ancestry.mjs";
29
30
  import { annotateBlockedWait, resolveCheckBlockerGate } from "./check-blocker-gate.mjs";
30
31
  import { buildUnreportedFixResult, planUnreportedRequired } from "./unreported-required.mjs";
@@ -33,10 +34,10 @@ import { transportReadinessGaps } from "../../github/transport-evidence.mjs";
33
34
  import { buildEscalateHumanMessage } from "./escalate.mjs";
34
35
  import { markEditedCommentsSeen } from "./edited-comment-markers.mjs";
35
36
  export function runIterate(opts) {
36
- return withIterateApiUsage(opts, async () => {
37
+ return withIterateApiUsage(opts, () => withStackBoundary(opts.prNumber, opts.stackLayers, async () => {
37
38
  const tick = {};
38
39
  return attachEditedComments(await runIterateCore(opts, tick), tick, opts);
39
- });
40
+ }));
40
41
  }
41
42
  // Edited PR comments are not readiness work. Hold them while the PR waits or counts down, and show
42
43
  // each once on any other action (including MERGE after the ready delay), writing its marker then.
@@ -239,7 +240,7 @@ async function runIterateCore(opts, tick) {
239
240
  });
240
241
  }
241
242
  if (unreportedRepair.length > 0) {
242
- return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, buildUnreportedFixResult(base, report, unreportedRepair), reportForWork, reviewSummaryIds, opts.stallDeadlineSink), blockerGate);
243
+ return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, buildUnreportedFixResult(base, report, unreportedRepair), reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
243
244
  }
244
245
  const mergeStateResult = await handleActiveMergeState({
245
246
  enabled: opts.merge,
@@ -252,6 +253,7 @@ async function runIterateCore(opts, tick) {
252
253
  editedSummaries,
253
254
  surfacedApprovals,
254
255
  minimizeApprovals: config.iterate["minimize-approvals"],
256
+ persistState: opts.persistSeen !== false,
255
257
  });
256
258
  if (mergeStateResult)
257
259
  return annotateBlockedWait(mergeStateResult, blockerGate);
@@ -334,11 +336,15 @@ async function runIterateCore(opts, tick) {
334
336
  ? `WAIT: PR #${base.pr} reached ready-delay but GitHub reports BLOCKED, so its stack readiness receipt was not certified`
335
337
  : `WAIT: PR #${base.pr} reached ready-delay but its stack readiness receipt could not be persisted`,
336
338
  };
337
- return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, receiptWait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink), blockerGate);
339
+ return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, receiptWait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
340
+ }
341
+ const mergeResult = buildReadyMergeOutcome(opts.merge, true, base, report);
342
+ if (mergeResult?.action === "wait") {
343
+ // Unreadable REST queue policy: keep the ready-delay and run the stall timer across ticks.
344
+ return await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, mergeResult, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false);
338
345
  }
339
346
  await clearReadyDelay(report.pr, repoOwner, repoName);
340
347
  await clearStallState(stallKey);
341
- const mergeResult = buildReadyMergeOutcome(opts.merge, true, base, report);
342
348
  if (mergeResult)
343
349
  return mergeResult;
344
350
  const cancelNote = blockedCancelNote(base);
@@ -365,7 +371,7 @@ async function runIterateCore(opts, tick) {
365
371
  action: "wait",
366
372
  log: buildWaitLog(base),
367
373
  };
368
- return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, wait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink), blockerGate);
374
+ return annotateBlockedWait(await applyStallGuard(stallKey, stallTimeoutSeconds, headSha, base, prNumber, wait, reportForWork, reviewSummaryIds, opts.stallDeadlineSink, opts.persistSeen !== false), blockerGate);
369
375
  }
370
376
  /**
371
377
  * Persist a READY receipt from a fresh compact snapshot. `blocked` means the
@@ -17,5 +17,7 @@ export interface MergePlanInput {
17
17
  }
18
18
  export interface MergeMethodUnavailable {
19
19
  unavailable: string;
20
+ /** REST could not read queue policy: a retry may read it, so the caller waits instead of escalating. */
21
+ refresh?: true;
20
22
  }
21
23
  export declare function buildMergeCommandPlan(input: MergePlanInput): MergeCommandPlan | MergeMethodUnavailable;
@@ -15,7 +15,8 @@ export function buildMergeCommandPlan(input) {
15
15
  const configured = configuredMergeMethod(loadConfig().merge);
16
16
  if (!input.queue && input.queueKnown !== true && configured)
17
17
  return {
18
- unavailable: "REST cannot verify merge-queue policy and cannot apply a configured direct merge method to an automatic merge request. Refresh branch policy before merging.",
18
+ unavailable: "REST could not read merge-queue policy, so it cannot apply the configured direct merge method to an automatic merge request. Shepherd rereads branch policy on the next poll and stops with `stall-timeout` if it stays unreadable.",
19
+ refresh: true,
19
20
  };
20
21
  let method;
21
22
  if (!input.queue && input.queueKnown === true) {
@@ -25,5 +25,7 @@ export declare function handleActiveMergeState(input: {
25
25
  editedSummaries: Review[];
26
26
  surfacedApprovals: Review[];
27
27
  minimizeApprovals: boolean;
28
+ /** False on internal debounce preview ticks, which must not write follow-up markers. */
29
+ persistState?: boolean;
28
30
  }): Promise<IterateResult | null>;
29
31
  export {};
@@ -1,5 +1,5 @@
1
1
  import { clearStallState } from "../../state/iterate-stall.mjs";
2
- import { buildEscalateHumanMessage, buildEscalateSuggestion } from "./escalate.mjs";
2
+ import { planQueueRemoval } from "./queue-removal.mjs";
3
3
  import { buildMergeCommandPlan, unavailableMergeResult } from "./merge.mjs";
4
4
  import { formatPrUrl } from "../../pr-reference.mjs";
5
5
  import { buildPrShepherdCommand } from "../../cli/runner.mjs";
@@ -31,7 +31,7 @@ function buildStackedRouteResult(base, report, stack) {
31
31
  },
32
32
  instructions: [
33
33
  `PR #${report.pr} is layer ${stack.position} of ${stack.size} in native stack #${stack.number}; do not run \`gh pr merge\` for this layer.`,
34
- `Run ${inlineCode(buildPrShepherdCommand(["stack", prUrl, "--until-terminal", "--merge"]).text)} to reconcile the stack and run each bottom-layer merge command it emits.`,
34
+ `Run ${inlineCode(buildPrShepherdCommand(["stack", prUrl, "--until-terminal", "--merge-through", prUrl]).text)} to merge this layer and the unmerged layers below it, never a layer above it. If lower layers are not yours it escalates \`unowned-stack-layers\` and merges nothing: follow its instructions. Otherwise it emits one merge command that lands every layer it lists. Run that command as printed: do not merge the layers one at a time with \`gh pr merge\`, and do not rebase or push between layers.`,
35
35
  ],
36
36
  firstLookThreads: [],
37
37
  firstLookComments: [],
@@ -57,8 +57,12 @@ export function buildReadyMergeOutcome(enabled, readyElapsed, base, report) {
57
57
  !(report.transportUnavailable ?? []).some(({ field }) => ["branchProtection", "branchRules"].includes(field)),
58
58
  ...(report.allowedMergeMethods && { allowedMergeMethods: report.allowedMergeMethods }),
59
59
  });
60
- if ("unavailable" in plan)
60
+ if ("unavailable" in plan) {
61
+ // A REST policy read that may succeed on a later poll waits under the stall timer.
62
+ if (plan.refresh)
63
+ return { ...base, action: "wait", log: `WAIT: PR #${report.pr} ${plan.unavailable}` };
61
64
  return unavailableMergeResult(base, report, plan.unavailable);
65
+ }
62
66
  return { ...base, action: "merge", merge: plan };
63
67
  }
64
68
  /** Raw counts of non-CI actionable work held back for one queued-PR wait tick. Omitted (all zero) when empty. */
@@ -121,22 +125,5 @@ export async function handleActiveMergeState(input) {
121
125
  report.mergeQueue?.removalAcknowledged)
122
126
  return null;
123
127
  await clearStallState(stallKey);
124
- const escalateBase = {
125
- triggers: ["merge-queue-removed"],
126
- unresolvedThreads: [],
127
- ambiguousComments: [],
128
- changesRequestedReviews: [],
129
- mergeQueueRemoval: removal,
130
- suggestion: buildEscalateSuggestion(["merge-queue-removed"], removal.reason ?? "GitHub did not provide a reason"),
131
- };
132
- return {
133
- ...base,
134
- action: "escalate",
135
- escalate: {
136
- ...escalateBase,
137
- humanMessage: buildEscalateHumanMessage(escalateBase, formatPrUrl(report.repo, report.pr), {
138
- merge: true,
139
- }),
140
- },
141
- };
128
+ return planQueueRemoval({ base, report, stallKey, persistState: input.persistState !== false });
142
129
  }
@@ -26,11 +26,12 @@ export declare function buildNativeStackRebaseInstruction(repo: string, stackNum
26
26
  * retains its merged parent's branch as its PR base. Without that topology, a PR base matching
27
27
  * the stack trunk also identifies a bottom layer. Other layers rebase from their PR base.
28
28
  * `trunkConflict` means an upper layer already contains its parent, so the rebase starts
29
- * at the bottom open layer.
29
+ * at the bottom open layer. An unusable base name (`baseBranch` undefined) is never named: the
30
+ * route starts at the known bottom open layer, which updates every layer above it as well.
30
31
  */
31
32
  export declare function buildNativeStackLayerRebase(repo: string, pr: {
32
33
  number: number;
33
- baseBranch: string;
34
+ baseBranch: string | undefined;
34
35
  }, stack: StackStatus | undefined, trunkConflict?: {
35
36
  trunk: string;
36
37
  bottomPr?: number;
@@ -1,5 +1,6 @@
1
1
  import { playbookPointer } from "../playbook-pointer.mjs";
2
2
  import { getGithubTransport } from "../../github/transport.mjs";
3
+ import { boundedStackPush, boundedStackRebase } from "./stack-boundary.mjs";
3
4
  /**
4
5
  * One gh-stack rebase step. A native stack layer must not be rebased or merged from its base
5
6
  * branch alone: that rewrites one branch and strands every layer above it.
@@ -9,6 +10,10 @@ import { getGithubTransport } from "../../github/transport.mjs";
9
10
  * stack number before a PR number) and checks each local layer against its PR head.
10
11
  */
11
12
  export function buildNativeStackRebaseInstruction(repo, stackNumber, start) {
13
+ // A one-PR session that carries unowned layers never runs a whole-stack update.
14
+ const bounded = boundedStackRebase(stackNumber, playbookPointer("Branch update"), getGithubTransport() === "rest");
15
+ if (bounded)
16
+ return bounded;
12
17
  if (getGithubTransport() === "rest") {
13
18
  const boundary = "parentBranch" in start
14
19
  ? `parent branch \`${start.parentBranch}\``
@@ -38,21 +43,31 @@ export function buildNativeStackRebaseInstruction(repo, stackNumber, start) {
38
43
  * retains its merged parent's branch as its PR base. Without that topology, a PR base matching
39
44
  * the stack trunk also identifies a bottom layer. Other layers rebase from their PR base.
40
45
  * `trunkConflict` means an upper layer already contains its parent, so the rebase starts
41
- * at the bottom open layer.
46
+ * at the bottom open layer. An unusable base name (`baseBranch` undefined) is never named: the
47
+ * route starts at the known bottom open layer, which updates every layer above it as well.
42
48
  */
43
49
  export function buildNativeStackLayerRebase(repo, pr, stack, trunkConflict, stackBottomPr) {
44
50
  if (!stack)
45
51
  return undefined;
46
- const start = trunkConflict
47
- ? trunkConflict.bottomPr !== undefined
48
- ? { bottomPr: trunkConflict.bottomPr }
49
- : { trunk: trunkConflict.trunk }
50
- : (stackBottomPr !== undefined
51
- ? pr.number === stackBottomPr
52
- : pr.baseBranch === stack.baseRefName)
53
- ? { bottomPr: pr.number }
54
- : { parentBranch: pr.baseBranch };
55
- return buildNativeStackRebaseInstruction(repo, stack.number, start);
52
+ const { baseBranch } = pr;
53
+ let start;
54
+ if (trunkConflict) {
55
+ start =
56
+ trunkConflict.bottomPr !== undefined
57
+ ? { bottomPr: trunkConflict.bottomPr }
58
+ : { trunk: trunkConflict.trunk };
59
+ }
60
+ else if (baseBranch === undefined) {
61
+ if (stackBottomPr !== undefined)
62
+ start = { bottomPr: stackBottomPr };
63
+ }
64
+ else if (stackBottomPr !== undefined ? pr.number === stackBottomPr : baseBranch === stack.baseRefName) {
65
+ start = { bottomPr: pr.number };
66
+ }
67
+ else {
68
+ start = { parentBranch: baseBranch };
69
+ }
70
+ return start && buildNativeStackRebaseInstruction(repo, stack.number, start);
56
71
  }
57
72
  /**
58
73
  * The branch-update route for a conflicting PR that is not a native stack layer. Rebase versus
@@ -89,6 +104,12 @@ export function buildQueuedConflictChoice(dequeueCommand, resolve, stack) {
89
104
  * After a merge-queue ejection update, push only when the update or a fix changed the head.
90
105
  */
91
106
  export function buildBranchPushInstruction(stackRebase, hasConflicts, mutationSuffix, ejectionUpdate = false) {
107
+ const bounded = stackRebase ? boundedStackPush() : undefined;
108
+ if (bounded) {
109
+ return ejectionUpdate
110
+ ? `If the base update or a fix changed the head, commit any remaining changes and ${bounded}${mutationSuffix}. If neither did, do not push.`
111
+ : `Commit any remaining changes on the PR head branch and ${bounded}${mutationSuffix}.`;
112
+ }
92
113
  if (stackRebase && getGithubTransport() === "rest")
93
114
  return `If the base update or a fix changed any heads, commit the remaining changes and push every affected stack branch using the repository's stack-update procedure${mutationSuffix}. If no heads changed, do not push.`;
94
115
  if (ejectionUpdate) {
@@ -0,0 +1,19 @@
1
+ import type { IterateResult, IterateResultBase, ShepherdReport } from "../../types.mts";
2
+ type StateKey = {
3
+ owner: string;
4
+ repo: string;
5
+ pr: number;
6
+ };
7
+ /**
8
+ * A current merge-queue removal with no failed queue-commit check to triage. The first presented
9
+ * tick for this head and removal is one bounded `triage`; the same removal unchanged on the next
10
+ * presented tick escalates. A new head ends the removal's currency, so it never reaches here.
11
+ */
12
+ export declare function planQueueRemoval(input: {
13
+ base: IterateResultBase;
14
+ report: ShepherdReport;
15
+ stallKey: StateKey;
16
+ /** Internal preview ticks must not consume the one investigation tick. */
17
+ persistState: boolean;
18
+ }): Promise<IterateResult>;
19
+ export {};
@@ -0,0 +1,64 @@
1
+ import { formatPrUrl } from "../../pr-reference.mjs";
2
+ import { queueRemovalSignature, readQueueRemovalFollowUp, writeQueueRemovalFollowUp, } from "../../state/queue-removal-follow-up.mjs";
3
+ import { playbookPointer } from "../playbook-pointer.mjs";
4
+ import { buildEscalateHumanMessage, buildEscalateSuggestion } from "./escalate.mjs";
5
+ import { stateUnavailableResult } from "./state-unavailable.mjs";
6
+ import { buildUnreportedFixResult, stackRebase } from "./unreported-required.mjs";
7
+ function buildQueueRemovalInstructions(report) {
8
+ const route = stackRebase(report);
9
+ const update = route
10
+ ? `update the stack from the latest base (${route}) and push it`
11
+ : "update the PR head from the latest base and push";
12
+ return [
13
+ `GitHub removed PR #${report.pr} from the merge queue, and Shepherd has no failed queue-commit check to triage. The \`**queue removal**\` line above carries the raw reason and actor.`,
14
+ `Decide from them. If the reason names a merge conflict, an invalid merge commit, or a stack that changed, ${update}. If a person dequeued the PR (the actor is a user, not a bot or \`github-actions\`), make no change and report that. If the reason is missing or unclear, find out why before acting. Never enqueue the PR yourself. ${playbookPointer("Merge queue ejection")}`,
15
+ "If the head is unchanged on the next poll, Shepherd escalates with `merge-queue-removed`; report what you found then.",
16
+ ];
17
+ }
18
+ function escalateResult(base, report) {
19
+ const removal = report.mergeQueue.latestRemoval;
20
+ const escalateBase = {
21
+ triggers: ["merge-queue-removed"],
22
+ unresolvedThreads: [],
23
+ ambiguousComments: [],
24
+ changesRequestedReviews: [],
25
+ mergeQueueRemoval: removal,
26
+ suggestion: buildEscalateSuggestion(["merge-queue-removed"], removal.reason ?? "GitHub did not provide a reason"),
27
+ };
28
+ return {
29
+ ...base,
30
+ action: "escalate",
31
+ escalate: {
32
+ ...escalateBase,
33
+ humanMessage: buildEscalateHumanMessage(escalateBase, formatPrUrl(report.repo, report.pr), {
34
+ merge: true,
35
+ }),
36
+ },
37
+ };
38
+ }
39
+ /**
40
+ * A current merge-queue removal with no failed queue-commit check to triage. The first presented
41
+ * tick for this head and removal is one bounded `triage`; the same removal unchanged on the next
42
+ * presented tick escalates. A new head ends the removal's currency, so it never reaches here.
43
+ */
44
+ export async function planQueueRemoval(input) {
45
+ const { base, report, stallKey, persistState } = input;
46
+ const removal = report.mergeQueue.latestRemoval;
47
+ const signature = queueRemovalSignature({
48
+ headSha: report.headSha ?? "unknown",
49
+ createdAtUnix: removal.createdAtUnix,
50
+ ...(removal.beforeCommitOid && { beforeCommitOid: removal.beforeCommitOid }),
51
+ });
52
+ if (await readQueueRemovalFollowUp(stallKey, signature))
53
+ return escalateResult(base, report);
54
+ // A reused cached report is re-run by the poll before it is shown, so it must not spend the one
55
+ // investigation tick the caller never sees.
56
+ if (persistState && report.fingerprintReused !== true) {
57
+ // A marker that cannot be saved would repeat the investigation forever.
58
+ const saveError = await writeQueueRemovalFollowUp(stallKey, signature);
59
+ if (saveError) {
60
+ return stateUnavailableResult(base, formatPrUrl(report.repo, report.pr), saveError);
61
+ }
62
+ }
63
+ return buildUnreportedFixResult(base, report, buildQueueRemovalInstructions(report));
64
+ }
@@ -11,4 +11,5 @@ export declare function buildFixInstructions(threads: AgentThread[], actionableC
11
11
  isBehind?: boolean, _viewerCanUpdate?: boolean, hasExhaustedWorkflowRerun?: boolean, stackRebase?: string, // native stack layers rebase with gh-stack, not branch by branch
12
12
  queueEjection?: QueueEjectionRecovery, // current merge-queue removal with failing queue checks
13
13
  instructionStyle?: InstructionStyle, // see iterate.instructions
14
- dequeueCommand?: string): string[];
14
+ dequeueCommand?: string, // a conflicting PR that is still a merge-queue entry
15
+ cancelRunsStep?: string): string[];
@@ -20,7 +20,8 @@ export function buildFixInstructions(threads, actionableComments, checks, change
20
20
  isBehind = false, _viewerCanUpdate = false, hasExhaustedWorkflowRerun = false, stackRebase, // native stack layers rebase with gh-stack, not branch by branch
21
21
  queueEjection, // current merge-queue removal with failing queue checks
22
22
  instructionStyle = "inline", // see iterate.instructions
23
- dequeueCommand) {
23
+ dequeueCommand, // a conflicting PR that is still a merge-queue entry
24
+ cancelRunsStep) {
24
25
  const instructions = [];
25
26
  const { locatedThreads, unlocatedThreads } = partitionFixThreads(threads, resolveCommand, resolveOnlyCommand);
26
27
  const failingChecks = checks.filter((c) => isFailingAgentCheck(c));
@@ -36,6 +37,8 @@ dequeueCommand) {
36
37
  // A queued conflict offers a wait path that publishes nothing, so fixes, branch updates,
37
38
  // pushes, and review mutations (which must follow a push) become path (a).
38
39
  const pathA = (step) => (dequeueCommand ? `If you chose (a): ${step}` : step);
40
+ if (cancelRunsStep)
41
+ instructions.push(cancelRunsStep);
39
42
  if (hasNonConflictHints)
40
43
  instructions.push(pathA("Fix each warranted item."));
41
44
  // A conflicting native stack layer follows the printed gh-stack route, so it omits the hint.
@@ -0,0 +1,17 @@
1
+ import type { StackLayerOwnership } from "../../types.mts";
2
+ /** Run one iterate tick with the stack ownership its command carried. */
3
+ export declare function withStackBoundary<T>(pr: number | undefined, layers: StackLayerOwnership[] | undefined, run: () => Promise<T>): Promise<T>;
4
+ /** `pr:position:o|u:branch` per layer, comma separated: the `--layers` value. The branch is percent-encoded so commas and colons survive. */
5
+ export declare function formatStackLayers(layers: StackLayerOwnership[]): string;
6
+ /** Parse a `--layers` value; null when any entry is malformed. */
7
+ export declare function parseStackLayers(value: string): StackLayerOwnership[] | null;
8
+ /**
9
+ * Whether the ownership this tick carries rules out a whole-stack `gh stack rebase` / `push`
10
+ * (some layer is not the caller's), and the instruction to give instead; undefined otherwise.
11
+ */
12
+ export declare function boundedStackRebase(stackNumber: number, playbook: string, rest?: boolean): string | undefined;
13
+ /**
14
+ * The push clause that replaces "push the rewritten stack with `gh stack push`" when ownership
15
+ * is bounded; undefined when it is not.
16
+ */
17
+ export declare function boundedStackPush(): string | undefined;
@@ -0,0 +1,95 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const storage = new AsyncLocalStorage();
3
+ /** Run one iterate tick with the stack ownership its command carried. */
4
+ export function withStackBoundary(pr, layers, run) {
5
+ return layers?.some((layer) => !layer.owned) ? storage.run({ pr, layers }, run) : run();
6
+ }
7
+ /** `pr:position:o|u:branch` per layer, comma separated: the `--layers` value. The branch is percent-encoded so commas and colons survive. */
8
+ export function formatStackLayers(layers) {
9
+ return layers
10
+ .map((l) => `${l.pr}:${l.position}:${l.owned ? "o" : "u"}:${encodeURIComponent(l.branch)}`)
11
+ .join(",");
12
+ }
13
+ function decodeBranch(value) {
14
+ try {
15
+ return decodeURIComponent(value);
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ /** Parse a `--layers` value; null when any entry is malformed. */
22
+ export function parseStackLayers(value) {
23
+ const layers = [];
24
+ for (const entry of value.split(",")) {
25
+ const match = /^(\d+):(\d+):([ou]):(.+)$/.exec(entry);
26
+ const branch = match ? decodeBranch(match[4]) : null;
27
+ if (!match || !branch)
28
+ return null;
29
+ layers.push({
30
+ pr: Number(match[1]),
31
+ position: Number(match[2]),
32
+ owned: match[3] === "o",
33
+ branch,
34
+ });
35
+ }
36
+ return layers.length > 0 ? layers : null;
37
+ }
38
+ const PUSH_REMOTE = "(substitute this repository's push remote for `<push-remote>`, the remote `gh stack push` uses)";
39
+ function plan() {
40
+ const boundary = storage.getStore();
41
+ if (!boundary)
42
+ return undefined;
43
+ const layers = [...boundary.layers].sort((a, b) => a.position - b.position);
44
+ const unowned = layers.filter((layer) => !layer.owned);
45
+ const me = layers.find((layer) => layer.pr === boundary.pr && layer.owned);
46
+ if (!me)
47
+ return { unowned, pushable: [] };
48
+ const below = layers.filter((layer) => layer.position <= me.position);
49
+ const blockedBy = below.filter((layer) => !layer.owned);
50
+ return {
51
+ unowned,
52
+ me,
53
+ pushable: blockedBy.length > 0 ? [] : below,
54
+ ...(blockedBy.length > 0 && { blockedBy }),
55
+ };
56
+ }
57
+ const names = (layers) => layers.map((l) => `#${l.pr}`).join(", ");
58
+ /**
59
+ * Whether the ownership this tick carries rules out a whole-stack `gh stack rebase` / `push`
60
+ * (some layer is not the caller's), and the instruction to give instead; undefined otherwise.
61
+ */
62
+ export function boundedStackRebase(stackNumber, playbook, rest = false) {
63
+ const p = plan();
64
+ if (!p)
65
+ return undefined;
66
+ const lead = `Unowned ${p.unowned.length === 1 ? "layer" : "layers"} ${names(p.unowned)} in native stack #${stackNumber} must not be rebased or pushed, and a whole-stack update (\`gh stack rebase\`, \`gh stack push\`) would rewrite ${p.unowned.length === 1 ? "it" : "them"}, so do not run one.`;
67
+ if (!p.me) {
68
+ return `${lead} This session cannot tell which layers are owned; do not update any branch of the stack, and report that to the caller. ${playbook}`;
69
+ }
70
+ if (p.blockedBy) {
71
+ return `${lead} ${names(p.blockedBy)} sits below this PR, so no branch of this PR can be restacked without rewriting ${p.blockedBy.length === 1 ? "it" : "them"}. Do not rebase or push; report that PR #${p.me.pr} waits on ${p.blockedBy.length === 1 ? "that layer's" : "those layers'"} owner. ${playbook}`;
72
+ }
73
+ const above = p.unowned.filter((layer) => layer.position > p.me.position);
74
+ const stale = above.length > 0
75
+ ? ` ${names(above)} will be stale afterwards: tell the user its owner must restack ${above.length === 1 ? "it" : "them"}.`
76
+ : "";
77
+ const update = rest
78
+ ? `Instead, update only PR #${p.me.pr} (\`${p.me.branch}\`) and the layers below it, using the repository's stack-update procedure.`
79
+ : `Instead, from a clean checkout, if \`gh stack\` does not track stack #${stackNumber} locally, import it with \`gh stack checkout ${stackNumber}\`; then check out \`${p.me.branch}\` (PR #${p.me.pr}) and run \`gh stack rebase --downstack\`, which rewrites only this layer and the layers below it.`;
80
+ return `${lead} ${update}${stale} ${playbook}`;
81
+ }
82
+ /**
83
+ * The push clause that replaces "push the rewritten stack with `gh stack push`" when ownership
84
+ * is bounded; undefined when it is not.
85
+ */
86
+ export function boundedStackPush() {
87
+ const p = plan();
88
+ if (!p)
89
+ return undefined;
90
+ if (p.pushable.length === 0) {
91
+ return "do not push the stack: `gh stack push` would publish unowned layers, and this PR has no branch it can restack alone";
92
+ }
93
+ const branches = p.pushable.map((layer) => `\`${layer.branch}\``).join(", ");
94
+ return `push only the owned branches (${branches}) with \`git push --force-with-lease <push-remote> <branch>\` ${PUSH_REMOTE}; do not run \`gh stack push\`, which would also publish unowned layers (${names(p.unowned)})`;
95
+ }
@@ -0,0 +1,17 @@
1
+ import type { IterateResult, IterateResultBase, ShepherdReport } from "../../types.mts";
2
+ /** One repair step; the unchanged failure on the next poll escalates `stall-state-unavailable`. */
3
+ export declare function stallRepairStep(reason: string): string;
4
+ /**
5
+ * The first time a stall timer cannot be saved: the tick's own work plus one repair step (a
6
+ * `triage` when the tick had none). `undefined` (escalate) once that repair tick was already
7
+ * presented for this reason, or when the marker that bounds it cannot be saved.
8
+ */
9
+ export declare function planStallRepair(input: {
10
+ base: IterateResultBase;
11
+ report: ShepherdReport;
12
+ prospective: IterateResult;
13
+ scope: string;
14
+ reason: string;
15
+ /** Internal preview ticks must not consume the one repair tick. */
16
+ persistState: boolean;
17
+ }): Promise<IterateResult | undefined>;
@@ -0,0 +1,25 @@
1
+ import { readStallRepair, writeStallRepair } from "../../state/stall-repair.mjs";
2
+ import { buildUnreportedFixResult } from "./unreported-required.mjs";
3
+ /** One repair step; the unchanged failure on the next poll escalates `stall-state-unavailable`. */
4
+ export function stallRepairStep(reason) {
5
+ return `The stall timer could not be saved (${reason}). Fix PR_SHEPHERD_STATE_DIR or the state directory's permissions, then rerun Shepherd. Until it can be saved Shepherd cannot detect a stuck loop; if it still cannot be saved on the next poll, Shepherd escalates \`stall-state-unavailable\`.`;
6
+ }
7
+ /**
8
+ * The first time a stall timer cannot be saved: the tick's own work plus one repair step (a
9
+ * `triage` when the tick had none). `undefined` (escalate) once that repair tick was already
10
+ * presented for this reason, or when the marker that bounds it cannot be saved.
11
+ */
12
+ export async function planStallRepair(input) {
13
+ const { base, report, prospective, scope, reason, persistState } = input;
14
+ if (await readStallRepair(scope, reason))
15
+ return undefined;
16
+ if (persistState && !(await writeStallRepair(scope, reason)))
17
+ return undefined;
18
+ const step = stallRepairStep(reason);
19
+ if (prospective.action !== "triage")
20
+ return buildUnreportedFixResult(base, report, [step]);
21
+ return {
22
+ ...prospective,
23
+ triage: { ...prospective.triage, instructions: [step, ...prospective.triage.instructions] },
24
+ };
25
+ }
@@ -3,7 +3,7 @@ export declare function applyStallGuard(stallKey: {
3
3
  owner: string;
4
4
  repo: string;
5
5
  pr: number;
6
- }, stallTimeoutSeconds: number, headSha: string, base: IterateResultBase, prNumber: number, prospectiveResult: IterateResult, report: ShepherdReport, reviewSummaryIds: string[], stallDeadlineSink?: StallDeadlineSink): Promise<IterateResult>;
6
+ }, stallTimeoutSeconds: number, headSha: string, base: IterateResultBase, prNumber: number, prospectiveResult: IterateResult, report: ShepherdReport, reviewSummaryIds: string[], stallDeadlineSink?: StallDeadlineSink, persistState?: boolean): Promise<IterateResult>;
7
7
  /** Internal out-parameter: when the earliest unstarted check would trip the CI-start stall. */
8
8
  export interface StallDeadlineSink {
9
9
  ciStartDeadlineSeconds?: number;