pr-shepherd 2.0.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 (194) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +41 -32
  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/classify/standard/dependency-review-no-issues.d.mts +4 -0
  17. package/bin/classify/standard/dependency-review-no-issues.mjs +16 -0
  18. package/bin/classify/standard/index.mjs +8 -0
  19. package/bin/classify/standard/snyk-no-issues.d.mts +7 -0
  20. package/bin/classify/standard/snyk-no-issues.mjs +27 -0
  21. package/bin/classify/standard/socket-reports.d.mts +4 -0
  22. package/bin/classify/standard/socket-reports.mjs +18 -0
  23. package/bin/classify/standard/sonarqube-gate-passed.d.mts +7 -0
  24. package/bin/classify/standard/sonarqube-gate-passed.mjs +41 -0
  25. package/bin/cli/arg-flags.mjs +3 -0
  26. package/bin/cli/clean-handler.mjs +1 -1
  27. package/bin/cli/default-poll.mjs +1 -0
  28. package/bin/cli/handlers.mjs +2 -0
  29. package/bin/cli/help-command-pages.d.mts +5 -4
  30. package/bin/cli/help-command-pages.mjs +2 -1
  31. package/bin/cli/help-iterate-poll-pages.d.mts +3 -3
  32. package/bin/cli/help-iterate-poll-pages.mjs +10 -2
  33. package/bin/cli/help-top-page.d.mts +1 -1
  34. package/bin/cli/help-top-page.mjs +2 -2
  35. package/bin/cli/help.d.mts +6 -5
  36. package/bin/cli/in-progress-run-format.d.mts +3 -0
  37. package/bin/cli/in-progress-run-format.mjs +14 -0
  38. package/bin/cli/iterate-activity-formatter.d.mts +2 -0
  39. package/bin/cli/iterate-activity-formatter.mjs +11 -0
  40. package/bin/cli/iterate-flags.d.mts +3 -0
  41. package/bin/cli/iterate-flags.mjs +18 -1
  42. package/bin/cli/iterate-formatter.mjs +2 -1
  43. package/bin/cli/iterate-lean.mjs +2 -0
  44. package/bin/cli/pending-deployments-format.d.mts +5 -0
  45. package/bin/cli/pending-deployments-format.mjs +19 -0
  46. package/bin/cli/poll-handler.d.mts +1 -1
  47. package/bin/cli/poll-handler.mjs +33 -10
  48. package/bin/cli/poll-targets.mjs +2 -0
  49. package/bin/cli/stack-merge-args.d.mts +10 -0
  50. package/bin/cli/stack-merge-args.mjs +27 -0
  51. package/bin/cli/stack-overview.d.mts +1 -0
  52. package/bin/cli/stack-overview.mjs +5 -1
  53. package/bin/cli/stalled-check-format.d.mts +3 -0
  54. package/bin/cli/stalled-check-format.mjs +23 -0
  55. package/bin/cli/suggestion-renderer.mjs +6 -0
  56. package/bin/cli/triage-formatter.mjs +14 -0
  57. package/bin/commands/check.mjs +7 -2
  58. package/bin/commands/clean.d.mts +1 -1
  59. package/bin/commands/clean.mjs +7 -0
  60. package/bin/commands/iterate/check-follow-up.d.mts +9 -0
  61. package/bin/commands/iterate/check-follow-up.mjs +34 -0
  62. package/bin/commands/iterate/ci-start-stall.d.mts +23 -0
  63. package/bin/commands/iterate/ci-start-stall.mjs +33 -0
  64. package/bin/commands/iterate/duration-approx.d.mts +2 -0
  65. package/bin/commands/iterate/duration-approx.mjs +8 -0
  66. package/bin/commands/iterate/escalate.d.mts +8 -17
  67. package/bin/commands/iterate/escalate.mjs +19 -48
  68. package/bin/commands/iterate/helpers.mjs +1 -0
  69. package/bin/commands/iterate/in-progress-runs.d.mts +10 -0
  70. package/bin/commands/iterate/in-progress-runs.mjs +120 -0
  71. package/bin/commands/iterate/index.mjs +12 -6
  72. package/bin/commands/iterate/merge-plan.d.mts +2 -0
  73. package/bin/commands/iterate/merge-plan.mjs +2 -1
  74. package/bin/commands/iterate/merge-state.d.mts +2 -0
  75. package/bin/commands/iterate/merge-state.mjs +8 -21
  76. package/bin/commands/iterate/native-stack-rebase.d.mts +3 -2
  77. package/bin/commands/iterate/native-stack-rebase.mjs +32 -11
  78. package/bin/commands/iterate/queue-removal.d.mts +19 -0
  79. package/bin/commands/iterate/queue-removal.mjs +64 -0
  80. package/bin/commands/iterate/render.d.mts +2 -1
  81. package/bin/commands/iterate/render.mjs +4 -1
  82. package/bin/commands/iterate/stack-boundary.d.mts +17 -0
  83. package/bin/commands/iterate/stack-boundary.mjs +95 -0
  84. package/bin/commands/iterate/stall-repair.d.mts +17 -0
  85. package/bin/commands/iterate/stall-repair.mjs +25 -0
  86. package/bin/commands/iterate/stall.d.mts +1 -1
  87. package/bin/commands/iterate/stall.mjs +27 -18
  88. package/bin/commands/iterate/state-unavailable.d.mts +8 -0
  89. package/bin/commands/iterate/state-unavailable.mjs +23 -0
  90. package/bin/commands/iterate/triage-loop-instruction.mjs +1 -1
  91. package/bin/commands/iterate/triage.mjs +41 -74
  92. package/bin/commands/iterate/unreported-required.d.mts +5 -2
  93. package/bin/commands/iterate/unreported-required.mjs +13 -8
  94. package/bin/commands/iterate/workflow-files.d.mts +27 -0
  95. package/bin/commands/iterate/workflow-files.mjs +85 -0
  96. package/bin/commands/poll-summary-explicit-instructions.mjs +15 -1
  97. package/bin/commands/poll-summary-instructions.d.mts +4 -3
  98. package/bin/commands/poll-summary-instructions.mjs +60 -22
  99. package/bin/commands/poll-summary.mjs +38 -10
  100. package/bin/commands/poll.mjs +4 -2
  101. package/bin/commands/stack-drain.d.mts +4 -4
  102. package/bin/commands/stack-drain.mjs +19 -113
  103. package/bin/commands/stack-handoffs.d.mts +3 -3
  104. package/bin/commands/stack-handoffs.mjs +8 -8
  105. package/bin/commands/stack-lower-ready-note.d.mts +6 -0
  106. package/bin/commands/stack-lower-ready-note.mjs +35 -0
  107. package/bin/commands/stack-merge-escalations.d.mts +17 -0
  108. package/bin/commands/stack-merge-escalations.mjs +57 -0
  109. package/bin/commands/stack-merge-plan.d.mts +10 -0
  110. package/bin/commands/stack-merge-plan.mjs +132 -0
  111. package/bin/commands/stack-merge-scope.d.mts +42 -0
  112. package/bin/commands/stack-merge-scope.mjs +113 -0
  113. package/bin/commands/stack-ownership.d.mts +25 -0
  114. package/bin/commands/stack-ownership.mjs +85 -0
  115. package/bin/commands/stack-stall.d.mts +2 -0
  116. package/bin/commands/stack-stall.mjs +25 -3
  117. package/bin/commands/stack-targets-error.d.mts +16 -0
  118. package/bin/commands/stack-targets-error.mjs +44 -0
  119. package/bin/commands/stack-targets.d.mts +30 -0
  120. package/bin/commands/stack-targets.mjs +121 -0
  121. package/bin/commands/stack-work.d.mts +4 -3
  122. package/bin/commands/stack-work.mjs +7 -4
  123. package/bin/commands/tick.mjs +14 -2
  124. package/bin/config/renames.mjs +1 -1
  125. package/bin/config/schema.d.mts +4 -0
  126. package/bin/config/schema.mjs +2 -0
  127. package/bin/github/batch-parse-suites.d.mts +4 -1
  128. package/bin/github/batch-parse-suites.mjs +15 -3
  129. package/bin/github/batch-raw-types.d.mts +6 -0
  130. package/bin/github/gql/commit-check-suites.gql +6 -0
  131. package/bin/github/gql/poll-summary-fragment.gql +6 -0
  132. package/bin/github/poll-summary-command.d.mts +15 -1
  133. package/bin/github/poll-summary-command.mjs +39 -3
  134. package/bin/github/poll-summary-projector.d.mts +1 -1
  135. package/bin/github/poll-summary-projector.mjs +1 -4
  136. package/bin/github/poll-summary-raw.d.mts +6 -0
  137. package/bin/github/poll-summary-route.mjs +4 -1
  138. package/bin/github/poll-summary.mjs +10 -3
  139. package/bin/github/rest-batch-read.mjs +17 -6
  140. package/bin/github/rest-batch-snapshot.d.mts +2 -2
  141. package/bin/github/rest-batch-snapshot.mjs +3 -0
  142. package/bin/github/rest-check-read.d.mts +1 -18
  143. package/bin/github/rest-check-read.mjs +1 -2
  144. package/bin/github/rest-stack-read.d.mts +9 -0
  145. package/bin/github/rest-stack-read.mjs +40 -0
  146. package/bin/github/rest-suite-types.d.mts +23 -0
  147. package/bin/github/rest-suite-types.mjs +1 -0
  148. package/bin/github/rest-summary-read.mjs +2 -0
  149. package/bin/mcp/server.mjs +29 -3
  150. package/bin/pr-reference.d.mts +2 -0
  151. package/bin/pr-reference.mjs +1 -1
  152. package/bin/reporters/agent.mjs +3 -0
  153. package/bin/state/check-follow-up.d.mts +30 -0
  154. package/bin/state/check-follow-up.mjs +51 -0
  155. package/bin/state/ci-start-follow-up.d.mts +14 -0
  156. package/bin/state/ci-start-follow-up.mjs +21 -0
  157. package/bin/state/queue-removal-follow-up.d.mts +20 -0
  158. package/bin/state/queue-removal-follow-up.mjs +23 -0
  159. package/bin/state/signature-marker.d.mts +10 -0
  160. package/bin/state/signature-marker.mjs +28 -0
  161. package/bin/state/stack-merge-approval.d.mts +26 -0
  162. package/bin/state/stack-merge-approval.mjs +39 -0
  163. package/bin/state/stall-repair.d.mts +16 -0
  164. package/bin/state/stall-repair.mjs +47 -0
  165. package/bin/types/activity.d.mts +2 -1
  166. package/bin/types/escalate.d.mts +9 -2
  167. package/bin/types/github.d.mts +18 -0
  168. package/bin/types/in-progress-run.d.mts +20 -0
  169. package/bin/types/in-progress-run.mjs +1 -0
  170. package/bin/types/iterate.d.mts +22 -1
  171. package/bin/types/poll-summary.d.mts +18 -1
  172. package/bin/types/report.d.mts +5 -1
  173. package/bin/types.d.mts +1 -0
  174. package/bin/types.mjs +1 -0
  175. package/package.json +2 -2
  176. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  177. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  178. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  179. package/plugins/pr-shepherd/.mcp.json +1 -1
  180. package/plugins/pr-shepherd/hooks/poll-guard-args.mjs +49 -0
  181. package/plugins/pr-shepherd/hooks/poll-guard-detect.mjs +134 -26
  182. package/plugins/pr-shepherd/hooks/poll-guard-shell.mjs +192 -0
  183. package/plugins/pr-shepherd/package-lock.json +7 -7
  184. package/plugins/pr-shepherd/package.json +1 -1
  185. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +8 -7
  186. package/plugins/pr-shepherd/skills/pr-shepherd/references/check-follow-up.md +14 -0
  187. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-failure-triage.md +6 -5
  188. package/plugins/pr-shepherd/skills/pr-shepherd/references/ci-start-stall.md +15 -0
  189. package/plugins/pr-shepherd/skills/pr-shepherd/references/create-a-pr.md +4 -1
  190. package/plugins/pr-shepherd/skills/pr-shepherd/references/mcp-fallback.md +1 -1
  191. package/plugins/pr-shepherd/skills/pr-shepherd/references/merge-queue-ejection.md +6 -5
  192. package/plugins/pr-shepherd/skills/pr-shepherd/references/required-checks-unreported.md +16 -0
  193. package/plugins/pr-shepherd/skills/reduce-pr-noise/references/classifiers.md +1 -1
  194. package/pr-shepherd.schema.json +15 -0
@@ -1,4 +1,5 @@
1
1
  import { INSTRUCTION_STYLES, isInstructionStyle, } from "../config/resolve.mjs";
2
+ import { parseStackLayers } from "../commands/iterate/stack-boundary.mjs";
2
3
  import { EXIT } from "../exit-codes.mjs";
3
4
  import { getFlag, hasFlag } from "./args.mjs";
4
5
  import { parseDurationToSeconds } from "./duration.mjs";
@@ -10,7 +11,8 @@ const MINUTE_FLAG_OPTS = { defaultUnit: "m", allowZero: true };
10
11
  export function hasInvalidIterateFlags(flags) {
11
12
  return (flags.readyDelaySuffix === null ||
12
13
  flags.stallTimeoutSuffix === null ||
13
- flags.instructions === null);
14
+ flags.instructions === null ||
15
+ flags.stackLayers === null);
14
16
  }
15
17
  export function parseIterateFlags(extra, cfg) {
16
18
  const readyDelayStr = getFlag(extra, "--ready-delay");
@@ -22,8 +24,10 @@ export function parseIterateFlags(extra, cfg) {
22
24
  const stallTimeoutSuffix = validateSecondsDurationFlag("pr-shepherd", "--stall-timeout", stallTimeoutStr, hasFlag(extra, "--stall-timeout"), MINUTE_FLAG_OPTS);
23
25
  const stallTimeoutSeconds = parseDurationToSeconds(stallTimeoutSuffix ?? "", cfg.iterate["stall-timeout-minutes"] * 60, MINUTE_FLAG_OPTS);
24
26
  const instructions = parseInstructionsFlag(extra);
27
+ const stackLayers = parseStackLayersFlag(extra);
25
28
  return {
26
29
  instructions,
30
+ stackLayers,
27
31
  readyDelaySuffix,
28
32
  readyDelaySeconds,
29
33
  stallTimeoutSuffix,
@@ -46,3 +50,16 @@ function parseInstructionsFlag(extra) {
46
50
  function hasInstructionsFlag(extra) {
47
51
  return extra.some((arg) => arg === "--instructions" || arg.startsWith("--instructions="));
48
52
  }
53
+ /** Validate `--layers`. Returns `undefined` when absent, `null` after printing a usage error. */
54
+ function parseStackLayersFlag(extra) {
55
+ const value = getFlag(extra, "--layers");
56
+ if (!extra.some((arg) => arg === "--layers" || arg.startsWith("--layers="))) {
57
+ return undefined;
58
+ }
59
+ const layers = value === null ? null : parseStackLayers(value);
60
+ if (layers)
61
+ return layers;
62
+ process.stderr.write(`pr-shepherd: --layers must be comma-separated pr:position:o|u:branch entries (branch percent-encoded), got ${JSON.stringify(value ?? "")}\n`);
63
+ process.exitCode = EXIT.USAGE;
64
+ return null;
65
+ }
@@ -7,7 +7,7 @@ import { adaptIterateLog, buildSimpleIterateInstructions, numberInstructions, }
7
7
  import { formatMergeRequirementLines } from "../merge-status/requirements-format.mjs";
8
8
  import { appendMergeQueueHeader, formatDeferredWorkLine, formatMergeAction, } from "./iterate-merge-formatter.mjs";
9
9
  import { formatApiUsage, formatQuotaWarning } from "./api-usage-formatter.mjs";
10
- import { formatActivityLine } from "./iterate-activity-formatter.mjs";
10
+ import { formatActivityLine, formatPendingDeploymentLines } from "./iterate-activity-formatter.mjs";
11
11
  import { formatSuppressedNameLines } from "./iterate-check-names.mjs";
12
12
  import { branchStateSegment } from "./iterate-branch-segment.mjs";
13
13
  import { insertRuleAutoResolveSection } from "../commands/rule-auto-resolve-format.mjs";
@@ -125,6 +125,7 @@ export function formatIterateResult(result, opts) {
125
125
  const activityLine = formatActivityLine(result, verbose);
126
126
  if (activityLine)
127
127
  headerLines.push(activityLine);
128
+ headerLines.push(...formatPendingDeploymentLines(result));
128
129
  headerLines.push(...formatNextCheckLines(result.nextCheck));
129
130
  const header = headerLines.join("\n");
130
131
  const quotaWarning = formatQuotaWarning(result.quotaWarning);
@@ -175,6 +175,8 @@ export function projectIterateLean(result, opts) {
175
175
  queueRemovalAcknowledgment: result.triage.queueRemovalAcknowledgment,
176
176
  }),
177
177
  ...(result.triage.checks.length > 0 && { checks: result.triage.checks }),
178
+ ...(result.triage.stalledChecks && { stalledChecks: result.triage.stalledChecks }),
179
+ ...(result.triage.inProgressRuns && { inProgressRuns: result.triage.inProgressRuns }),
178
180
  ...(result.triage.changesRequestedReviews.length > 0 && {
179
181
  changesRequestedReviews: result.triage.changesRequestedReviews,
180
182
  }),
@@ -0,0 +1,5 @@
1
+ import type { PendingDeployment } from "../types.mts";
2
+ /** One environment approval, as raw fields: name, required reviewers, viewer capability, timer. */
3
+ export declare function formatPendingDeployment(deployment: PendingDeployment): string;
4
+ /** Shared text rendering of environment approvals under a check bullet. */
5
+ export declare function renderPendingDeploymentLines(deployments: PendingDeployment[] | undefined, indent?: string): string[];
@@ -0,0 +1,19 @@
1
+ function renderReviewer(reviewer) {
2
+ return reviewer.type === "Team" ? `team \`${reviewer.name}\`` : `\`@${reviewer.name}\``;
3
+ }
4
+ /** One environment approval, as raw fields: name, required reviewers, viewer capability, timer. */
5
+ export function formatPendingDeployment(deployment) {
6
+ const parts = [`environment \`${deployment.environment}\``];
7
+ if (deployment.reviewers) {
8
+ parts.push(`required reviewers ${deployment.reviewers.map(renderReviewer).join(", ")}`);
9
+ }
10
+ parts.push(`viewer can approve: ${deployment.currentUserCanApprove ? "yes" : "no"}`);
11
+ if (deployment.waitTimerMinutes !== undefined) {
12
+ parts.push(`wait timer ${deployment.waitTimerMinutes} min`);
13
+ }
14
+ return parts.join(", ");
15
+ }
16
+ /** Shared text rendering of environment approvals under a check bullet. */
17
+ export function renderPendingDeploymentLines(deployments, indent = " ") {
18
+ return (deployments ?? []).map((d) => `${indent}pending deployment: ${formatPendingDeployment(d)}`);
19
+ }
@@ -1,4 +1,4 @@
1
1
  /** The default command: one PR, or several PRs from one repository. */
2
2
  export declare function handlePoll(args: string[]): Promise<void>;
3
- /** `pr-shepherd stack <PR>`: the native stack containing one PR. */
3
+ /** `pr-shepherd stack <ref> [<ref> ...]`: the native stack that a stack number or PRs select. */
4
4
  export declare function handleStack(args: string[]): Promise<void>;
@@ -8,6 +8,8 @@ import { emitIterateResult } from "./iterate-emitter.mjs";
8
8
  import { EXIT } from "../exit-codes.mjs";
9
9
  import { emitPollSummaryResult } from "./poll-summary-emitter.mjs";
10
10
  import { parsePollTargets, resolvePollTargets } from "./poll-targets.mjs";
11
+ import { parseStackMerge } from "./stack-merge-args.mjs";
12
+ import { resolveStackTarget, stackMergeScope } from "../commands/stack-targets.mjs";
11
13
  import { DEFAULT_POLL_BOOLEAN_FLAGS, DEFAULT_POLL_FLAGS_WITH_VALUES } from "./default-poll.mjs";
12
14
  import { validateDefaultArgs } from "./validate-default-args.mjs";
13
15
  import { rejectRemovedFlags } from "./removed-flags.mjs";
@@ -39,33 +41,53 @@ export async function handlePoll(args) {
39
41
  readyDelaySuffix: shared.readyDelaySuffix,
40
42
  });
41
43
  }
42
- /** `pr-shepherd stack <PR>`: the native stack containing one PR. */
44
+ /** `pr-shepherd stack <ref> [<ref> ...]`: the native stack that a stack number or PRs select. */
43
45
  export async function handleStack(args) {
44
46
  if (maybePrintHelp(args, "stack"))
45
47
  return;
46
48
  if (rejectRemovedFlags(args) || rejectUnknownFlags(args, "stack", STACK_FLAGS))
47
49
  return;
48
- if (!validateDefaultArgs(args, DEFAULT_POLL_FLAGS_WITH_VALUES, STACK_BOOLEAN_FLAGS, usageArg))
50
+ if (!validateDefaultArgs(args, STACK_FLAGS_WITH_VALUES, STACK_BOOLEAN_FLAGS, usageArg))
49
51
  return;
50
52
  const parsedTargets = parsePollTargets(args);
51
53
  if (!parsedTargets)
52
54
  return;
53
- if (parsedTargets.refs.length !== 1) {
54
- usage("stack requires exactly one PR reference.");
55
+ if (parsedTargets.refs.length === 0) {
56
+ usage("stack requires a PR or stack reference.");
55
57
  return;
56
58
  }
57
- const { prNumbers, targetRepository } = await resolvePollTargets(parsedTargets);
59
+ const merge = parseStackMerge(parsedTargets.extra);
60
+ if (!merge)
61
+ return;
58
62
  const shared = parseLoopOptions(parsedTargets.extra, parsedTargets.global, true);
59
63
  if (!shared)
60
64
  return;
61
- const target = { stackPrNumber: prNumbers[0], targetRepository };
65
+ const target = await resolveStackTarget({
66
+ refs: parsedTargets.refs,
67
+ ...(merge.through && { through: merge.through }),
68
+ ...(merge.flag && { merge: merge.flag }),
69
+ });
70
+ const scope = stackMergeScope(merge.flag, target.through);
71
+ const options = {
72
+ ...shared.options,
73
+ merge: scope !== undefined,
74
+ ...(scope && { stackMerge: scope }),
75
+ stackPrNumber: target.anchor,
76
+ ...(target.owned && { stackOwned: target.owned }),
77
+ targetRepository: target.targetRepository,
78
+ };
62
79
  const result = hasFlag(parsedTargets.extra, "--once")
63
- ? await runPollSummaryTick({ ...shared.options, ...target })
64
- : await runAggregatePollCommand({ ...shared.options, ...target });
80
+ ? await runPollSummaryTick(options)
81
+ : await runAggregatePollCommand(options);
65
82
  emitPollSummaryResult(result, { format: parsedTargets.global.format });
66
83
  }
67
- const STACK_BOOLEAN_FLAGS = new Set([...DEFAULT_POLL_BOOLEAN_FLAGS, "--once"]);
68
- const STACK_FLAGS = [...DEFAULT_POLL_FLAGS_WITH_VALUES, ...STACK_BOOLEAN_FLAGS];
84
+ // `--layers` is for the one-PR commands a stack prints; `stack` itself has no use for it.
85
+ const STACK_FLAGS_WITH_VALUES = new Set([
86
+ ...[...DEFAULT_POLL_FLAGS_WITH_VALUES].filter((flag) => flag !== "--layers"),
87
+ "--merge-through",
88
+ ]);
89
+ const STACK_BOOLEAN_FLAGS = new Set([...DEFAULT_POLL_BOOLEAN_FLAGS, "--once", "--merge-ready"]);
90
+ const STACK_FLAGS = [...STACK_FLAGS_WITH_VALUES, ...STACK_BOOLEAN_FLAGS];
69
91
  function parseLoopOptions(extra, globalOpts, isAggregate) {
70
92
  const cfg = loadConfig();
71
93
  const flags = parseIterateFlags(extra, cfg);
@@ -109,6 +131,7 @@ function parseLoopOptions(extra, globalOpts, isAggregate) {
109
131
  noAutoMarkReady: flags.noAutoMarkReady,
110
132
  merge: flags.merge,
111
133
  instructions: flags.instructions ?? undefined,
134
+ ...(flags.stackLayers && { stackLayers: flags.stackLayers }),
112
135
  intervalSeconds,
113
136
  timeoutSeconds,
114
137
  debounceSeconds,
@@ -11,6 +11,8 @@ const VALUE_FLAGS = new Set([
11
11
  "--interval",
12
12
  "--timeout",
13
13
  "--debounce",
14
+ "--merge-through",
15
+ "--layers",
14
16
  ]);
15
17
  /** Splits PR references from flags. Returns null after printing a usage error. */
16
18
  export function parsePollTargets(args) {
@@ -0,0 +1,10 @@
1
+ import type { StackMergeFlag } from "../commands/stack-targets.mts";
2
+ import { type ParsedPrReference } from "../pr-reference.mts";
3
+ /**
4
+ * The stack merge scope flags: `--merge`, `--merge-ready`, and `--merge-through <ref>` are
5
+ * mutually exclusive. Returns null after printing a usage error.
6
+ */
7
+ export declare function parseStackMerge(extra: string[]): {
8
+ flag?: StackMergeFlag;
9
+ through?: ParsedPrReference;
10
+ } | null;
@@ -0,0 +1,27 @@
1
+ import { EXIT } from "../exit-codes.mjs";
2
+ import { parseCliPrReference } from "../pr-reference.mjs";
3
+ import { getFlag, hasFlag } from "./args.mjs";
4
+ /**
5
+ * The stack merge scope flags: `--merge`, `--merge-ready`, and `--merge-through <ref>` are
6
+ * mutually exclusive. Returns null after printing a usage error.
7
+ */
8
+ export function parseStackMerge(extra) {
9
+ const through = getFlag(extra, "--merge-through");
10
+ const flags = [
11
+ ...(hasFlag(extra, "--merge") ? ["merge"] : []),
12
+ ...(hasFlag(extra, "--merge-ready") ? ["ready"] : []),
13
+ ...(hasFlag(extra, "--merge-through") || through !== null ? ["through"] : []),
14
+ ];
15
+ const fail = (message) => {
16
+ process.stderr.write(`pr-shepherd: stack: ${message}\n`);
17
+ process.exitCode = EXIT.USAGE;
18
+ return null;
19
+ };
20
+ if (flags.length > 1) {
21
+ return fail("--merge, --merge-ready, and --merge-through are mutually exclusive.");
22
+ }
23
+ if (flags[0] !== "through")
24
+ return flags[0] ? { flag: flags[0] } : {};
25
+ const ref = through === null ? null : parseCliPrReference(through);
26
+ return ref ? { flag: "through", through: ref } : fail("--merge-through requires a PR reference.");
27
+ }
@@ -18,6 +18,7 @@ export interface StackOverview {
18
18
  nextAction?: StackNextAction;
19
19
  prs: StackLayerView[];
20
20
  stackAncestry?: PollSummaryStackAncestry[];
21
+ addedLayers?: number[];
21
22
  instructions?: string[];
22
23
  apiUsage?: ApiUsage;
23
24
  quotaWarning?: GraphqlQuotaWarning;
@@ -24,6 +24,7 @@ export function projectStackOverview(result) {
24
24
  ...(result.nextAction && { nextAction: result.nextAction }),
25
25
  prs: result.prs.map((item) => projectLayer(item, stale.has(item.pr))),
26
26
  ...(result.stackAncestry?.length && { stackAncestry: result.stackAncestry }),
27
+ ...(result.addedLayers?.length && { addedLayers: result.addedLayers }),
27
28
  ...(result.instructions?.length && { instructions: result.instructions }),
28
29
  ...(result.apiUsage && { apiUsage: result.apiUsage }),
29
30
  ...(result.quotaWarning && { quotaWarning: result.quotaWarning }),
@@ -111,6 +112,9 @@ export function formatStackOverview(overview) {
111
112
  lines.push(`- PR #${gap.childPr} base \`${gap.childBaseRefName}\` at \`${gap.childBaseRefOid}\` differs from parent PR #${gap.parentPr} head \`${gap.parentHeadRefName}\` at \`${gap.parentHeadRefOid}\`.`);
112
113
  }
113
114
  }
115
+ const added = overview.addedLayers?.map((pr) => `#${pr}`).join(", ");
116
+ if (added)
117
+ lines.push("", `Layers added after approval: ${added}`);
114
118
  if (overview.instructions?.length) {
115
119
  lines.push("", "## Instructions", "", ...overview.instructions);
116
120
  }
@@ -130,7 +134,7 @@ function formatLayerLines(layer, index, overview) {
130
134
  layer.mergeable === undefined
131
135
  ? undefined
132
136
  : layer.mergeable
133
- ? "mergeable"
137
+ ? `mergeable${layer.shepherded ? "" : ", no READY receipt yet"}`
134
138
  : `not mergeable (\`${layer.blocker ?? "unknown"}\`)`,
135
139
  layer.author ? `owner \`@${layer.author}\`` : undefined,
136
140
  layer.owned ? "owned" : undefined,
@@ -0,0 +1,3 @@
1
+ import type { AgentStalledCheck } from "../types.mts";
2
+ /** One unstarted check as raw data: a bullet, its summary as a blockquote, and any approvals. */
3
+ export declare function renderStalledCheckLines(check: AgentStalledCheck): string[];
@@ -0,0 +1,23 @@
1
+ import { formatDurationApprox } from "../commands/iterate/duration-approx.mjs";
2
+ import { renderPendingDeploymentLines } from "./pending-deployments-format.mjs";
3
+ /** Names and URLs come from check providers: keep each inside one code span on one line. */
4
+ function inline(text) {
5
+ return text.replace(/[`\r\n]+/g, " ");
6
+ }
7
+ /** One unstarted check as raw data: a bullet, its summary as a blockquote, and any approvals. */
8
+ export function renderStalledCheckLines(check) {
9
+ const target = check.runId
10
+ ? `run \`${inline(check.runId)}\``
11
+ : check.detailsUrl
12
+ ? `external \`${inline(check.detailsUrl)}\``
13
+ : "no run ID";
14
+ const lines = [
15
+ `- check \`${inline(check.name)}\` — ${check.status} ${check.source}, ${target}, waiting ${formatDurationApprox(check.ageSeconds)}`,
16
+ ];
17
+ if (check.summary) {
18
+ for (const line of check.summary.split(/\r?\n/))
19
+ lines.push(` > ${line}`);
20
+ }
21
+ lines.push(...renderPendingDeploymentLines(check.pendingDeployments, " "));
22
+ return lines;
23
+ }
@@ -15,6 +15,11 @@ export function renderSuggestionBlock(s, indent = " ") {
15
15
  : s.lines.length === 1 && s.lines[0] === ""
16
16
  ? `Replaces ${rangeLabel} with a blank line:`
17
17
  : `Replaces ${rangeLabel}:`;
18
+ const note = /`{3,}/.test(content)
19
+ ? [
20
+ `${indent}Replacement contains backtick runs of 3 or more; \`suggest\` builds the exact patch.`,
21
+ ]
22
+ : [];
18
23
  return [
19
24
  `${indent}${label}`,
20
25
  `${indent}${fence}`,
@@ -27,5 +32,6 @@ export function renderSuggestionBlock(s, indent = " ") {
27
32
  .join("\n"),
28
33
  ]),
29
34
  `${indent}${fence}`,
35
+ ...note,
30
36
  ].join("\n");
31
37
  }
@@ -6,6 +6,9 @@ import { BODY_TRUNCATE_MAX_CHARS } from "./body-truncate.mjs";
6
6
  import { numberInstructions } from "./iterate-instructions.mjs";
7
7
  import { renderCheckAnnotation } from "./triage-formatter-extra.mjs";
8
8
  import { renderRelatedJobLines } from "./related-jobs-format.mjs";
9
+ import { renderPendingDeploymentLines } from "./pending-deployments-format.mjs";
10
+ import { renderStalledCheckLines } from "./stalled-check-format.mjs";
11
+ import { renderInProgressRun } from "./in-progress-run-format.mjs";
9
12
  import { isFailingAgentCheck } from "../checks/conclusions.mjs";
10
13
  import { renderMergeCommand } from "../commands/iterate/merge.mjs";
11
14
  import { partitionFixThreads } from "../commands/iterate/fix-instruction-threads.mjs";
@@ -96,6 +99,8 @@ export function formatTriageResult(header, result, opts = {}) {
96
99
  const lines = [
97
100
  `- ${locator} — \`${workflowPrefix}${jobLabel}\`${conclusionTag}${attemptTag}${blockerTag}${scopeTag}`,
98
101
  ];
102
+ if (ch.workflowPath)
103
+ lines.push(` workflow file: \`${ch.workflowPath}\``);
99
104
  if (ch.conclusion !== "CANCELLED") {
100
105
  if (ch.failedStep)
101
106
  lines.push(` > ${ch.failedStep}`);
@@ -105,6 +110,7 @@ export function formatTriageResult(header, result, opts = {}) {
105
110
  lines.push(indentBlockquote(ch.logExcerpt, " "));
106
111
  lines.push(...renderRelatedJobLines(ch.relatedJobs));
107
112
  }
113
+ lines.push(...renderPendingDeploymentLines(ch.pendingDeployments));
108
114
  if (ch.rerunCommand && ch.runId && !seenRerunRunIds.has(ch.runId)) {
109
115
  seenRerunRunIds.add(ch.runId);
110
116
  lines.push(` rerun: \`${ch.rerunCommand}\``);
@@ -135,6 +141,14 @@ export function formatTriageResult(header, result, opts = {}) {
135
141
  sections.push(rendered.join("\n\n"));
136
142
  }
137
143
  }
144
+ if (result.triage.stalledChecks) {
145
+ sections.push("## Unstarted checks");
146
+ sections.push(result.triage.stalledChecks.flatMap(renderStalledCheckLines).join("\n"));
147
+ }
148
+ if (result.triage.inProgressRuns) {
149
+ sections.push("## In-progress runs");
150
+ sections.push(result.triage.inProgressRuns.map(renderInProgressRun).join("\n\n"));
151
+ }
138
152
  if (result.triage.changesRequestedReviews.length > 0) {
139
153
  sections.push("## Changes-requested reviews");
140
154
  for (const r of result.triage.changesRequestedReviews) {
@@ -11,8 +11,10 @@ import { collectUnreportedRequired, refreshCachedUnreported } from "./check-unre
11
11
  import { getRepoInfo, getCurrentPrNumber } from "../github/client.mjs";
12
12
  import { classifyChecks, getCiVerdict } from "../checks/classify.mjs";
13
13
  import { mergeStartupFailureChecks } from "../checks/startup-failures.mjs";
14
+ import { withRunWorkflowPaths } from "../checks/run-workflow-paths.mjs";
14
15
  import { fetchStartupFailureChecks, triageFailingChecks } from "../checks/triage.mjs";
15
16
  import { TriageBudget } from "../checks/triage-budget.mjs";
17
+ import { attachPendingDeployments } from "../checks/pending-deployments.mjs";
16
18
  import { deriveMergeStatus } from "../merge-status/derive.mjs";
17
19
  import { loadConfig } from "../config/load.mjs";
18
20
  import { classifyVisibleComments } from "../comments/visible-comments.mjs";
@@ -119,7 +121,7 @@ async function runScopedCheck(opts, context, repo, prNumber, stateKey) {
119
121
  const startupFailureChecks = result.checkSuitesComplete && !startupFailuresNeedAttempt
120
122
  ? []
121
123
  : await fetchStartupFailureChecks(repo, batchData.headRefOid, prNumber, stateKey, triageBudget);
122
- const allChecks = mergeStartupFailureChecks(batchData.checks, startupFailureChecks);
124
+ const allChecks = withRunWorkflowPaths(mergeStartupFailureChecks(batchData.checks, startupFailureChecks), result.headWorkflowSuites ?? []);
123
125
  const unreported = await collectUnreportedRequired({
124
126
  batchData,
125
127
  checks: allChecks,
@@ -180,7 +182,10 @@ async function runScopedCheck(opts, context, repo, prNumber, stateKey) {
180
182
  additionalRelevantEvents: ["merge_group"],
181
183
  requiredContexts: unreported.requiredContexts,
182
184
  });
183
- const classifiedChecks = [...classifiedPrChecks, ...classifiedQueueChecks];
185
+ const classifiedBaseChecks = [...classifiedPrChecks, ...classifiedQueueChecks];
186
+ const classifiedChecks = opts.skipTriage
187
+ ? classifiedBaseChecks
188
+ : await attachPendingDeployments(classifiedBaseChecks, repo, stateKey, triageBudget);
184
189
  const verdict = getCiVerdict(classifiedChecks);
185
190
  const passing = classifiedChecks.filter((c) => c.category === "passed");
186
191
  const failing = classifiedChecks.filter((c) => c.category === "failing");
@@ -1,4 +1,4 @@
1
- export type CleanVariant = "pr" | "branch" | "current" | "repo" | "all";
1
+ export type CleanVariant = "pr" | "stack" | "branch" | "current" | "repo" | "all";
2
2
  interface CleanOptions {
3
3
  variant: CleanVariant;
4
4
  /** PR number string (for "pr") or branch name (for "branch"). Defaults to current. */
@@ -116,6 +116,13 @@ async function resolveTarget(base, opts) {
116
116
  }
117
117
  return repoDir;
118
118
  }
119
+ if (variant === "stack") {
120
+ const n = value === undefined ? NaN : parseInt(value, 10);
121
+ if (!Number.isFinite(n) || n <= 0 || String(n) !== value.trim()) {
122
+ throw new Error(`"clean stack" needs a native stack number; got ${value ?? "none"}`);
123
+ }
124
+ return join(repoDir, `stack-${n}`);
125
+ }
119
126
  let prNumber;
120
127
  if (variant === "pr") {
121
128
  if (value !== undefined) {
@@ -0,0 +1,9 @@
1
+ import type { AgentCheck } from "../../types.mts";
2
+ /**
3
+ * What a failing check with no authorized rerun needs next.
4
+ * `approval`: a gate only a human can grant. `investigate`: the agent can find out why.
5
+ */
6
+ export type CheckFollowUp = "approval" | "investigate";
7
+ export declare function checkFollowUp(check: AgentCheck): CheckFollowUp | undefined;
8
+ /** The one investigation tick: raw facts, the playbook, and the bounded outcome. */
9
+ export declare function buildCheckFollowUpInstructions(checks: AgentCheck[], repo: string, actionsRunIds: ReadonlySet<string>): string[];
@@ -0,0 +1,34 @@
1
+ import { playbookPointer } from "../playbook-pointer.mjs";
2
+ import { hasLogEvidence } from "./check-evidence.mjs";
3
+ export function checkFollowUp(check) {
4
+ if (check.rerunCommand)
5
+ return undefined;
6
+ if (check.conclusion === "ACTION_REQUIRED")
7
+ return "approval";
8
+ if (check.conclusion === "CANCELLED" || check.conclusion === "STARTUP_FAILURE") {
9
+ return "investigate";
10
+ }
11
+ // A later attempt cannot be rerun automatically, but its included log can still identify a
12
+ // fix. Without evidence the agent can fetch the log itself.
13
+ if (check.runAttempt !== undefined && check.runAttempt > 1) {
14
+ return hasLogEvidence(check) ? undefined : "investigate";
15
+ }
16
+ // An external check's direct URL is actionable evidence: the agent can inspect the provider.
17
+ if (check.runId === null)
18
+ return check.detailsUrl?.trim() ? undefined : "investigate";
19
+ return hasLogEvidence(check) ? undefined : "investigate";
20
+ }
21
+ /** The one investigation tick: raw facts, the playbook, and the bounded outcome. */
22
+ export function buildCheckFollowUpInstructions(checks, repo, actionsRunIds) {
23
+ // Only confirmed Actions runs: an external check's details-URL run id is not one.
24
+ const runIds = [
25
+ ...new Set(checks.flatMap((check) => check.runId && actionsRunIds.has(check.runId) ? [check.runId] : [])),
26
+ ];
27
+ const start = runIds.length
28
+ ? ` Start with ${runIds.map((id) => `\`gh run view ${id} -R ${repo}\``).join(", ")}: it lists the run's jobs and annotations.`
29
+ : "";
30
+ return [
31
+ `Shepherd has no rerun to offer and no log excerpt to show for the checks under \`## Failing checks\`, so it cannot tell from GitHub's data why they failed or what would fix them. Find out before acting.${start} ${playbookPointer("Check follow-up")}`,
32
+ "If the cause is within this PR, fix it and push. Otherwise make no change and keep what you found; do not rerun or retrigger these checks. If these checks are unchanged on the next poll, Shepherd escalates with `check-follow-up-unavailable`; report that diagnosis then.",
33
+ ];
34
+ }
@@ -0,0 +1,23 @@
1
+ import type { AgentStalledCheck, IterateResult, IterateResultBase, ShepherdReport } from "../../types.mts";
2
+ type StateKey = {
3
+ owner: string;
4
+ repo: string;
5
+ pr: number;
6
+ };
7
+ /**
8
+ * One bounded investigation `triage` the first time unstarted checks stall on a head; `undefined`
9
+ * (escalate) once the same checks on the same head were already presented, or at once when a
10
+ * stalled check waits on a deployment-environment approval.
11
+ */
12
+ export declare function planCiStartInvestigation(input: {
13
+ base: IterateResultBase;
14
+ report: ShepherdReport;
15
+ stallKey: StateKey;
16
+ headSha: string;
17
+ stalledChecks: readonly AgentStalledCheck[];
18
+ /** Internal preview ticks must not consume the one investigation tick. */
19
+ persistState: boolean;
20
+ /** The escalation when the investigation marker cannot be saved. */
21
+ stateUnavailable: (reason: string) => IterateResult;
22
+ }): Promise<IterateResult | undefined>;
23
+ export {};
@@ -0,0 +1,33 @@
1
+ import { ciStartSignature, readCiStartFollowUp, writeCiStartFollowUp, } from "../../state/ci-start-follow-up.mjs";
2
+ import { playbookPointer } from "../playbook-pointer.mjs";
3
+ import { buildUnreportedFixResult } from "./unreported-required.mjs";
4
+ /** Constant text: the checks' names, URLs and summaries are data under `## Unstarted checks`. */
5
+ const CI_START_INSTRUCTIONS = [
6
+ `The checks under \`## Unstarted checks\` have not started after the stall timeout, and Shepherd cannot tell from GitHub's data why. Find out before acting. ${playbookPointer("CI start stall")}`,
7
+ "If the cause is within this PR, fix it and push. Otherwise make no change and keep what you found. If the same checks are still not started on the next poll, Shepherd escalates with `stall-timeout`; report your diagnosis then.",
8
+ ];
9
+ /**
10
+ * One bounded investigation `triage` the first time unstarted checks stall on a head; `undefined`
11
+ * (escalate) once the same checks on the same head were already presented, or at once when a
12
+ * stalled check waits on a deployment-environment approval.
13
+ */
14
+ export async function planCiStartInvestigation(input) {
15
+ const { base, report, stallKey, headSha, stalledChecks, persistState } = input;
16
+ // A deployment-environment approval is a known human gate: nothing to investigate.
17
+ if (stalledChecks.some((check) => check.pendingDeployments?.length))
18
+ return undefined;
19
+ const signature = ciStartSignature(headSha, stalledChecks.map((check) => check.name));
20
+ if (await readCiStartFollowUp(stallKey, signature))
21
+ return undefined;
22
+ // A reused cached report is re-run by the poll before it is shown, so it must not spend the one
23
+ // investigation tick the caller never sees. A marker that cannot be saved would repeat the
24
+ // investigation forever, so that escalates with the save error.
25
+ if (persistState && report.fingerprintReused !== true) {
26
+ const saveError = await writeCiStartFollowUp(stallKey, signature);
27
+ if (saveError)
28
+ return input.stateUnavailable(saveError);
29
+ }
30
+ return buildUnreportedFixResult(base, report, CI_START_INSTRUCTIONS, {
31
+ stalledChecks: [...stalledChecks],
32
+ });
33
+ }
@@ -0,0 +1,2 @@
1
+ /** A rough human duration: whole seconds under a minute, else whole minutes. */
2
+ export declare function formatDurationApprox(seconds: number): string;
@@ -0,0 +1,8 @@
1
+ /** A rough human duration: whole seconds under a minute, else whole minutes. */
2
+ export function formatDurationApprox(seconds) {
3
+ const s = Math.max(0, Math.floor(seconds));
4
+ if (s < 60)
5
+ return `${s} second${s === 1 ? "" : "s"}`;
6
+ const mins = Math.floor(s / 60);
7
+ return `${mins} minute${mins === 1 ? "" : "s"}`;
8
+ }
@@ -4,30 +4,21 @@ interface EscalateCheck {
4
4
  thrashHistory?: EscalateDetails["thrashHistory"];
5
5
  }
6
6
  export declare function checkEscalateTriggers(actionableThreads: ReviewThread[], threadAttempts: Record<string, number>): EscalateCheck;
7
+ export { formatDurationApprox } from "./duration-approx.mts";
7
8
  interface BaseBranchLookup {
9
+ /** The validated name, or a placeholder when `unusable` is set. */
8
10
  branch: string;
9
- /** True when we could not confirm the branch name from GitHub. Callers must
10
- * escalate rather than emitting a rebase against a potentially-wrong base. */
11
- isFallback: boolean;
12
- /** Populated when `isFallback`; one-line reason shown in escalate output. */
13
- failureReason?: string;
11
+ /** True when the name is empty or outside `[A-Za-z0-9._/-]`. A name outside that set is never
12
+ * interpolated into a printed command; the caller reads the base from the PR instead. */
13
+ unusable: boolean;
14
14
  }
15
15
  /**
16
- * Validate the base branch name from the GraphQL batch (`report.baseBranch`)
17
- * and fall back safely if it's missing/unsafe. The branch is interpolated into
18
- * shell commands by `buildFixInstructions`, so we reject anything outside
19
- * `[A-Za-z0-9._/-]` to prevent shell injection.
16
+ * Validate the base branch name from the GraphQL batch (`report.baseBranch`). The branch is
17
+ * interpolated into printed shell commands, so a name outside `[A-Za-z0-9._/-]` (or an empty
18
+ * one) is `unusable`: callers omit the command and tell the agent to read the base from the PR.
20
19
  */
21
- /**
22
- * Render a seconds count as an approximate human duration: "8 seconds" below one minute,
23
- * otherwise whole minutes ("166 minutes", "60 minutes") — matching the precision the
24
- * generic stall timer has always reported, just adding a seconds tier for sub-minute ages
25
- * instead of always flooring to "0 minutes".
26
- */
27
- export declare function formatDurationApprox(seconds: number): string;
28
20
  export declare function validateBaseBranch(raw: string): BaseBranchLookup;
29
21
  export declare function buildEscalateHumanMessage(escalate: Omit<EscalateDetails, "humanMessage">, pr: string | number, opts?: {
30
22
  merge?: boolean;
31
23
  }): string;
32
24
  export declare function buildEscalateSuggestion(triggers: EscalateTrigger[], detail?: string): string;
33
- export {};