pr-shepherd 2.2.18 → 2.4.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 (79) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -0
  3. package/bin/api.d.mts +10 -0
  4. package/bin/api.mjs +21 -1
  5. package/bin/cli/iterate-formatter.mjs +3 -1
  6. package/bin/cli/triage-formatter.mjs +2 -0
  7. package/bin/cli/workflow-elsewhere-format.d.mts +3 -0
  8. package/bin/cli/workflow-elsewhere-format.mjs +112 -0
  9. package/bin/commands/iterate/base.mjs +1 -0
  10. package/bin/commands/iterate/helpers.mjs +1 -0
  11. package/bin/commands/iterate/index.mjs +11 -3
  12. package/bin/commands/iterate/queue-recovery-instructions.d.mts +1 -1
  13. package/bin/commands/iterate/queue-recovery-instructions.mjs +7 -4
  14. package/bin/commands/iterate/render.mjs +2 -1
  15. package/bin/commands/iterate/triage.mjs +24 -7
  16. package/bin/commands/iterate/workflow-elsewhere.d.mts +19 -0
  17. package/bin/commands/iterate/workflow-elsewhere.mjs +144 -0
  18. package/bin/commands/ready-delay.mjs +24 -1
  19. package/bin/comments/rest-reply.mjs +2 -1
  20. package/bin/comments/uncertain-replies.mjs +2 -1
  21. package/bin/comments/uncertain-reply-guards.mjs +2 -1
  22. package/bin/config/schema.d.mts +6 -0
  23. package/bin/config/schema.mjs +3 -0
  24. package/bin/execution-context.d.mts +7 -0
  25. package/bin/execution-context.mjs +13 -1
  26. package/bin/github/gql/default-branch-workflow-runs.gql +71 -0
  27. package/bin/github/graphql-http.mjs +2 -0
  28. package/bin/github/graphql-internal-retry.mjs +2 -1
  29. package/bin/github/queries.d.mts +2 -0
  30. package/bin/github/queries.mjs +2 -0
  31. package/bin/github/read-only-guard.d.mts +4 -0
  32. package/bin/github/read-only-guard.mjs +25 -0
  33. package/bin/github/rest-http.mjs +2 -0
  34. package/bin/github/rest-identities.mjs +16 -2
  35. package/bin/github/workflow-elsewhere-parse.d.mts +19 -0
  36. package/bin/github/workflow-elsewhere-parse.mjs +172 -0
  37. package/bin/github/workflow-elsewhere-queue.d.mts +28 -0
  38. package/bin/github/workflow-elsewhere-queue.mjs +137 -0
  39. package/bin/github/workflow-elsewhere-read.d.mts +26 -0
  40. package/bin/github/workflow-elsewhere-read.mjs +120 -0
  41. package/bin/github/workflow-elsewhere-rest-runs.d.mts +20 -0
  42. package/bin/github/workflow-elsewhere-rest-runs.mjs +54 -0
  43. package/bin/github/workflow-elsewhere-rest.d.mts +3 -0
  44. package/bin/github/workflow-elsewhere-rest.mjs +126 -0
  45. package/bin/log/log-file.mjs +1 -1
  46. package/bin/state/base.mjs +30 -12
  47. package/bin/state/check-blockers.mjs +2 -1
  48. package/bin/state/check-follow-up.mjs +2 -1
  49. package/bin/state/ci-retrigger.mjs +2 -1
  50. package/bin/state/conflicting-head-seen.mjs +2 -1
  51. package/bin/state/fix-attempts.mjs +2 -1
  52. package/bin/state/graphql-quota-claims.mjs +6 -1
  53. package/bin/state/graphql-quota-warnings.mjs +2 -1
  54. package/bin/state/guarded-fs.d.mts +16 -0
  55. package/bin/state/guarded-fs.mjs +49 -0
  56. package/bin/state/merge-request.mjs +2 -1
  57. package/bin/state/pr-fingerprint.mjs +2 -1
  58. package/bin/state/queue-removal-ack.mjs +2 -1
  59. package/bin/state/ready-receipts.mjs +2 -1
  60. package/bin/state/rest-cache.mjs +2 -1
  61. package/bin/state/rest-snapshot-report.mjs +2 -1
  62. package/bin/state/seen-comments.mjs +2 -1
  63. package/bin/state/signature-marker.mjs +2 -1
  64. package/bin/state/stack-merge-approval.mjs +2 -1
  65. package/bin/state/stall-repair.mjs +2 -1
  66. package/bin/state/stall-state-store.mjs +2 -1
  67. package/bin/types/iterate.d.mts +2 -0
  68. package/bin/types/report.d.mts +7 -0
  69. package/bin/types/workflow-elsewhere-raw.d.mts +108 -0
  70. package/bin/types/workflow-elsewhere-raw.mjs +1 -0
  71. package/bin/types/workflow-elsewhere.d.mts +55 -0
  72. package/bin/types/workflow-elsewhere.mjs +1 -0
  73. package/bin/types.d.mts +1 -0
  74. package/bin/types.mjs +1 -0
  75. package/package.json +1 -1
  76. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  77. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  78. package/plugins/pr-shepherd/skills/pr-shepherd/references/merge-queue-ejection.md +1 -1
  79. package/pr-shepherd.schema.json +13 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-shepherd",
3
3
  "description": "Autonomous PR CI monitor and review-comment resolver for agentic coding tools",
4
- "version": "2.2.18",
4
+ "version": "2.4.0",
5
5
  "author": {
6
6
  "name": "Jonathan Ong",
7
7
  "email": "jonathanrichardong@gmail.com"
package/README.md CHANGED
@@ -107,6 +107,7 @@ Requirements:
107
107
 
108
108
  - Node.js >= 22.19.0, Bun, or Deno, and `git`
109
109
  - A GitHub token or authenticated `gh` CLI with [the required access](docs/authentication.md)
110
+ - A repository where every check is expected to pass. Shepherd treats each failing check as work, required or not; list checks that may fail in [`checks.ignore`](docs/configuration.md#checksignore--default-) ([workflow assumptions](docs/features.md#workflow-assumptions))
110
111
 
111
112
  ## Documentation
112
113
 
package/bin/api.d.mts CHANGED
@@ -38,6 +38,11 @@ export type MultiIterateInput = IterateOptions & {
38
38
  pr?: never;
39
39
  };
40
40
  export type IterateInput = SingleIterateInput | MultiIterateInput;
41
+ /**
42
+ * The per-tick options of a single-PR `iterate` that a read-only `status` check honors. There is
43
+ * no `prs`: `status` answers for exactly one PR.
44
+ */
45
+ export type StatusInput = Pick<SingleIterateInput, "pr" | "merge" | "readyDelaySeconds" | "stallTimeoutSeconds" | "transport" | "instructions">;
41
46
  /**
42
47
  * One aggregate tick over one native stack. `refs` is one stack number (or `owner/repo#N` naming
43
48
  * one), which the caller owns entirely; or one or more PRs of one stack, which select it and own only
@@ -142,6 +147,11 @@ export interface PrShepherd {
142
147
  iterate(input?: SingleIterateInput): Promise<IterateResult>;
143
148
  iterate(input: MultiIterateInput): Promise<PollSummaryResult>;
144
149
  iterate(input: IterateInput): Promise<IterateResult | PollSummaryResult>;
150
+ /**
151
+ * One single-PR `iterate` tick through the same code path as `iterate`, with no GitHub mutation
152
+ * and no local state write. Library only: there is no CLI command or MCP tool for it.
153
+ */
154
+ status(input?: StatusInput): Promise<IterateResult>;
145
155
  stack(input: StackInput): Promise<PollSummaryResult>;
146
156
  apply(input: ApplyInput): Promise<ApplyResult>;
147
157
  suggest(input: SuggestInput): Promise<SuggestResult>;
package/bin/api.mjs CHANGED
@@ -12,7 +12,7 @@ import { validateJournalItem } from "./commands/journal/transform.mjs";
12
12
  import { runMarkFilesAsViewed, } from "./commands/mark-files-as-viewed.mjs";
13
13
  import { runResolveMutate } from "./commands/resolve-mutate.mjs";
14
14
  import { applyQueueRemovalAck, } from "./commands/apply-queue-removal.mjs";
15
- import { runWithExecutionCwd } from "./execution-context.mjs";
15
+ import { runReadOnly, runWithExecutionCwd } from "./execution-context.mjs";
16
16
  import { loadConfig } from "./config/load.mjs";
17
17
  import { parsePrReference, normalizeRepositoryIdentity, resolveParsedPrTarget, } from "./pr-reference.mjs";
18
18
  import { runWithAuthScope } from "./github/auth-target.mjs";
@@ -69,8 +69,28 @@ export function createPrShepherd(options = {}) {
69
69
  return runIterateTick({ ...iterateOptions, ...target, format: "json" });
70
70
  });
71
71
  }
72
+ function status(input = {}) {
73
+ // The read-only scope wraps the whole client run, so transport fallback probes and quota
74
+ // bookkeeping inside the runner are covered too.
75
+ return runReadOnly(() => runInClient(input, async () => {
76
+ if (input === null || typeof input !== "object" || "prs" in input) {
77
+ throw new PrShepherdValidationError("status takes one PR: pass pr, not prs");
78
+ }
79
+ const { pr, merge, readyDelaySeconds, stallTimeoutSeconds, instructions } = input;
80
+ const target = resolvePrReference(pr);
81
+ return runIterateTick({
82
+ ...(merge !== undefined && { merge }),
83
+ ...(readyDelaySeconds !== undefined && { readyDelaySeconds }),
84
+ ...(stallTimeoutSeconds !== undefined && { stallTimeoutSeconds }),
85
+ ...(instructions !== undefined && { instructions }),
86
+ ...target,
87
+ format: "json",
88
+ });
89
+ }));
90
+ }
72
91
  return Object.freeze({
73
92
  iterate,
93
+ status,
74
94
  stack(input) {
75
95
  return runInClient(input ?? {}, async () => {
76
96
  if (!input || !Array.isArray(input.refs) || input.refs.length === 0) {
@@ -55,7 +55,9 @@ export function formatIterateResult(result, opts) {
55
55
  ? ` · **merge** \`${result.mergeStateStatus}\``
56
56
  : "";
57
57
  const stateSeg = verbose || result.state !== "OPEN" ? ` · **state** \`${result.state}\`` : "";
58
- const baseLine = `**status** \`${result.status}\`${mergeSeg}${reviewDecisionSeg}${stateSeg}${repoSeg}${baseBranchSeg}`;
58
+ // Verbose only, like baseBranch: the raw result and verbose JSON always carry `headSha`.
59
+ const headSeg = verbose && result.headSha ? ` · **head** \`${result.headSha}\`` : "";
60
+ const baseLine = `**status** \`${result.status}\`${mergeSeg}${reviewDecisionSeg}${stateSeg}${repoSeg}${headSeg}${baseBranchSeg}`;
59
61
  const branchSeg = branchStateSegment(result);
60
62
  let summaryLine;
61
63
  if (verbose) {
@@ -7,6 +7,7 @@ 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
9
  import { renderPendingDeploymentLines } from "./pending-deployments-format.mjs";
10
+ import { renderWorkflowElsewhereLines } from "./workflow-elsewhere-format.mjs";
10
11
  import { renderStalledCheckLines } from "./stalled-check-format.mjs";
11
12
  import { renderInProgressRun } from "./in-progress-run-format.mjs";
12
13
  import { isFailingAgentCheck } from "../checks/conclusions.mjs";
@@ -111,6 +112,7 @@ export function formatTriageResult(header, result, opts = {}) {
111
112
  lines.push(...renderRelatedJobLines(ch.relatedJobs));
112
113
  }
113
114
  lines.push(...renderPendingDeploymentLines(ch.pendingDeployments));
115
+ lines.push(...renderWorkflowElsewhereLines(ch));
114
116
  if (ch.rerunCommand && ch.runId && !seenRerunRunIds.has(ch.runId)) {
115
117
  seenRerunRunIds.add(ch.runId);
116
118
  lines.push(` rerun: \`${ch.rerunCommand}\``);
@@ -0,0 +1,3 @@
1
+ import type { AgentCheck } from "../types.mts";
2
+ /** Render the `Same workflow elsewhere` sub-lines for a failing merge-group Actions check. */
3
+ export declare function renderWorkflowElsewhereLines(check: AgentCheck, indent?: string): string[];
@@ -0,0 +1,112 @@
1
+ /** Format an ISO UTC timestamp as `HH:MMZ` for compact text output. */
2
+ function formatElsewhereShortTime(iso) {
3
+ if (!iso)
4
+ return "unknown";
5
+ const match = /T(\d{2}:\d{2}):\d{2}/.exec(iso);
6
+ return match?.[1] ? `${match[1]}Z` : iso;
7
+ }
8
+ function sanitizeInline(value) {
9
+ return value.replace(/[`\r\n]+/g, " ").trim();
10
+ }
11
+ function plural(n, singular, pluralForm) {
12
+ return `${n} ${n === 1 ? singular : pluralForm}`;
13
+ }
14
+ function formatAnnotation(ann) {
15
+ const path = sanitizeInline(ann.path);
16
+ const loc = path ? `\`${ann.line !== null ? `${path}:${ann.line}` : path}\`` : "";
17
+ const message = sanitizeInline(ann.message);
18
+ if (loc && message)
19
+ return `${loc} — ${message}`;
20
+ return loc || message;
21
+ }
22
+ function formatMoreAnnotations(count) {
23
+ if (!count || count <= 0)
24
+ return "";
25
+ return `(+${count} more ${count === 1 ? "annotation" : "annotations"})`;
26
+ }
27
+ function renderFailedJob(job, runConclusion, indent) {
28
+ const name = sanitizeInline(job.name);
29
+ const sameJob = job.sameJob ? " ← same job" : "";
30
+ const showConclusion = job.annotations.length === 0 || job.conclusion !== runConclusion;
31
+ const conclusionTag = showConclusion ? ` [conclusion: ${job.conclusion}]` : "";
32
+ const more = formatMoreAnnotations(job.moreAnnotations);
33
+ if (job.annotations.length === 0) {
34
+ return [`${indent}- ${name}${conclusionTag}${sameJob}${more ? ` ${more}` : ""}`];
35
+ }
36
+ if (job.annotations.length === 1) {
37
+ return [
38
+ `${indent}- ${name}${conclusionTag}${sameJob}: ${formatAnnotation(job.annotations[0])}${more ? ` ${more}` : ""}`,
39
+ ];
40
+ }
41
+ const lines = [
42
+ `${indent}- ${name}${conclusionTag}${sameJob}:`,
43
+ ...job.annotations.map((ann) => `${indent} - ${formatAnnotation(ann)}`),
44
+ ];
45
+ if (more)
46
+ lines.push(`${indent} - ${more}`);
47
+ return lines;
48
+ }
49
+ function formatRunHeader(run) {
50
+ const target = run.source === "default-branch"
51
+ ? `\`${sanitizeInline(run.branch ?? "default branch")}\``
52
+ : run.pr !== undefined
53
+ ? `merge queue #${run.pr}`
54
+ : "merge queue";
55
+ return `${target} \`${run.headSha}\` run \`${run.runId}\` [conclusion: ${run.conclusion}]`;
56
+ }
57
+ function formatWorkflowLabel(scope) {
58
+ const name = scope?.workflowName ? sanitizeInline(scope.workflowName) : "";
59
+ const path = scope?.workflowPath ? sanitizeInline(scope.workflowPath) : "";
60
+ if (name && path)
61
+ return ` — \`${name}\` (${path})`;
62
+ if (name)
63
+ return ` — \`${name}\``;
64
+ if (path)
65
+ return ` — (${path})`;
66
+ return "";
67
+ }
68
+ function formatCheckedLine(scope, indent) {
69
+ const branch = `\`${sanitizeInline(scope.defaultBranch.branch)}\``;
70
+ const defaultPart = scope.defaultBranch.commitsRead !== undefined
71
+ ? `${branch} last ${plural(scope.defaultBranch.commitsRead, "commit", "commits")}`
72
+ : `${branch} newest ${plural(scope.defaultBranch.runsRead ?? 0, "run", "runs")}`;
73
+ const queuePart = `merge queue newest ${plural(scope.mergeQueue.runsRead, "run", "runs")}`;
74
+ return `${indent} checked: ${defaultPart} · ${queuePart}`;
75
+ }
76
+ function formatShowingLine(scope, indent) {
77
+ const branch = `\`${sanitizeInline(scope.defaultBranch.branch)}\``;
78
+ const { defaultBranch: def, mergeQueue: mq } = scope;
79
+ const defMatched = `${def.matched}${def.matchedComplete ? "" : "+"}`;
80
+ const mqMatched = `${mq.matched}${mq.matchedComplete ? "" : "+"}`;
81
+ return `${indent} showing newest ${def.shown} of ${defMatched} on ${branch}, ${mq.shown} of ${mqMatched} in the merge queue`;
82
+ }
83
+ /** Render the `Same workflow elsewhere` sub-lines for a failing merge-group Actions check. */
84
+ export function renderWorkflowElsewhereLines(check, indent = " ") {
85
+ if (check.elsewhereUnread !== undefined) {
86
+ return [
87
+ `${indent}Same workflow elsewhere: not read (${sanitizeInline(check.elsewhereUnread)})`,
88
+ ];
89
+ }
90
+ if (check.elsewhere === undefined)
91
+ return [];
92
+ const scope = check.elsewhereScope;
93
+ const since = formatElsewhereShortTime(scope?.since);
94
+ const wfLabel = formatWorkflowLabel(scope);
95
+ if (check.elsewhere.length === 0) {
96
+ const lines = [`${indent}Same workflow elsewhere${wfLabel}, since ${since}: none found`];
97
+ if (scope)
98
+ lines.push(formatCheckedLine(scope, indent));
99
+ return lines;
100
+ }
101
+ const lines = [`${indent}Same workflow elsewhere${wfLabel}, since ${since}:`];
102
+ if (scope) {
103
+ lines.push(formatCheckedLine(scope, indent), formatShowingLine(scope, indent));
104
+ }
105
+ for (const run of check.elsewhere) {
106
+ lines.push(`${indent}- ${formatRunHeader(run)}`);
107
+ for (const job of run.failedJobs) {
108
+ lines.push(...renderFailedJob(job, run.conclusion, `${indent} `));
109
+ }
110
+ }
111
+ return lines;
112
+ }
@@ -5,6 +5,7 @@ export function buildIterateBase(report, readyState) {
5
5
  return {
6
6
  pr: report.pr,
7
7
  repo: report.repo,
8
+ ...(report.headSha && { headSha: report.headSha }),
8
9
  ...(report.transport && { transport: report.transport }),
9
10
  ...(report.transportReason && { transportReason: report.transportReason }),
10
11
  ...(report.transportUnavailable?.length && {
@@ -28,6 +28,7 @@ export function buildTerminalCancelResult(report) {
28
28
  return {
29
29
  pr: report.pr,
30
30
  repo: report.repo,
31
+ ...(report.headSha && { headSha: report.headSha }),
31
32
  ...(report.transport && { transport: report.transport }),
32
33
  ...(report.transportReason && { transportReason: report.transportReason }),
33
34
  ...(report.transportUnavailable?.length && {
@@ -3,6 +3,7 @@ import { runCheck } from "../check.mjs";
3
3
  import { clearReadyDelay, updateReadyDelay } from "../ready-delay.mjs";
4
4
  import { getCurrentPrNumber } from "../../github/client.mjs";
5
5
  import { loadConfig } from "../../config/load.mjs";
6
+ import { isReadOnly } from "../../execution-context.mjs";
6
7
  import { EXIT, ShepherdError } from "../../exit-codes.mjs";
7
8
  import { buildWaitLog, buildTerminalCancelResult, blockedCancelNote } from "./helpers.mjs";
8
9
  import { classifyReviewSummaries } from "./classify.mjs";
@@ -71,12 +72,15 @@ async function runIterateCore(opts, tick) {
71
72
  throw new ShepherdError("No open PR found for current branch. Pass a PR number explicitly.", EXIT.UNAVAILABLE);
72
73
  }
73
74
  const checkContext = createCheckExecutionContext(readyDelaySeconds);
75
+ // A read-only status check sends no GitHub mutation: nothing is auto-resolved or auto-minimized,
76
+ // so those IDs stay in the agent-facing set exactly as when a mutation is not confirmed.
77
+ const readOnly = isReadOnly();
74
78
  const report = await runCheck({
75
79
  ...opts,
76
80
  prNumber,
77
81
  // Outdated Shepherd-visible threads are always resolved by iterate.
78
82
  autoResolve: true,
79
- autoMinimizeSuppressed: config.actions["auto-minimize-suppressed"],
83
+ autoMinimizeSuppressed: !readOnly && config.actions["auto-minimize-suppressed"],
80
84
  reviewOutputMaxChars: config.iterate["review-output-max-chars"],
81
85
  }, checkContext);
82
86
  tick.report = report;
@@ -122,7 +126,10 @@ async function runIterateCore(opts, tick) {
122
126
  // any ID it did not confirm minimized falls back into the agent-facing set so
123
127
  // the apply command remains a working fallback instead of silently dropping it.
124
128
  let reviewSummaryIds = minimizeIds;
125
- if (selfMinimizeIds.length > 0) {
129
+ if (selfMinimizeIds.length > 0 && readOnly) {
130
+ reviewSummaryIds = [...reviewSummaryIds, ...selfMinimizeIds];
131
+ }
132
+ else if (selfMinimizeIds.length > 0) {
126
133
  checkContext.invalidateReceiptSummary();
127
134
  const { minimized } = await autoMinimizeComments(selfMinimizeIds);
128
135
  const minimizedIds = new Set(minimized);
@@ -301,7 +308,8 @@ async function runIterateCore(opts, tick) {
301
308
  escalate: { ...escalation, humanMessage: buildEscalateHumanMessage(escalation, report.pr) },
302
309
  };
303
310
  }
304
- const autoMarkReady = !opts.noAutoMarkReady && config["mark-ready"].auto;
311
+ // Marking a draft ready is a GitHub mutation, so a read-only check treats it as disabled.
312
+ const autoMarkReady = !opts.noAutoMarkReady && !readOnly && config["mark-ready"].auto;
305
313
  if (canMarkReady && !autoMarkReady) {
306
314
  await clearReadyDelay(report.pr, repoOwner, repoName);
307
315
  await clearStallState(stallKey);
@@ -5,4 +5,4 @@ export type QueueEjectionRecovery = "requeue" | "acknowledge" | "none";
5
5
  /** The removed queue commit whose failed checks this tick surfaces, if the removal is current. */
6
6
  export declare function currentEjectionCommit(report: ShepherdReport, checks: AgentCheck[]): string | undefined;
7
7
  /** The ejection step after failing-check triage; points at a stack route already printed. */
8
- export declare function queueEjectionSteps(recovery: QueueEjectionRecovery | undefined, stackRebase: string | undefined, routePrinted: boolean): string[];
8
+ export declare function queueEjectionSteps(recovery: QueueEjectionRecovery | undefined, stackRebase: string | undefined, routePrinted: boolean, hasElsewhere?: boolean): string[];
@@ -11,20 +11,23 @@ export function currentEjectionCommit(report, checks) {
11
11
  : undefined;
12
12
  }
13
13
  /** The ejection step after failing-check triage; points at a stack route already printed. */
14
- export function queueEjectionSteps(recovery, stackRebase, routePrinted) {
14
+ export function queueEjectionSteps(recovery, stackRebase, routePrinted, hasElsewhere = false) {
15
15
  if (!recovery)
16
16
  return [];
17
17
  const route = stackRebase && routePrinted ? "use the stack route printed above." : stackRebase;
18
- return [buildQueueEjectionInstruction(recovery, route)];
18
+ return [buildQueueEjectionInstruction(recovery, route, hasElsewhere)];
19
19
  }
20
20
  /**
21
21
  * The trigger, update route, and command guard; the fixed procedure lives in the playbook.
22
22
  * A printed command implies a `failed_checks` removal. Without one, the agent reads the raw
23
23
  * removal reason, since a person's dequeue must not be undone by a branch update.
24
24
  */
25
- function buildQueueEjectionInstruction(recovery, stackRoute) {
25
+ function buildQueueEjectionInstruction(recovery, stackRoute, hasElsewhere = false) {
26
26
  const target = stackRoute ? "the stack" : "the PR head";
27
27
  const route = stackRoute ? `: ${stackRoute}` : ".";
28
+ const elsewhere = hasElsewhere
29
+ ? " Check `Same workflow elsewhere` under `## Failing checks` for recent runs of this workflow on the default branch and other merge-queue entries."
30
+ : "";
28
31
  const update = recovery === "none"
29
32
  ? `If the \`**queue removal**\` reason shows GitHub removed the entry itself, update ${target} from the latest base first${route} If a person may have dequeued the PR, skip that update unless a conflict step above requires it.`
30
33
  : `Update ${target} from the latest base first${route}`;
@@ -34,5 +37,5 @@ function buildQueueEjectionInstruction(recovery, stackRoute) {
34
37
  : recovery === "acknowledge"
35
38
  ? `Run \`acknowledge queue removal:\` ${reproduce}`
36
39
  : "Shepherd printed no queue command for this session, so do not enqueue the PR.";
37
- return `Triage the merge-queue ejection before any requeue. ${update} ${guard} ${playbookPointer("Merge queue ejection")}`;
40
+ return `Triage the merge-queue ejection before any requeue.${elsewhere} ${update} ${guard} ${playbookPointer("Merge queue ejection")}`;
38
41
  }
@@ -68,7 +68,8 @@ cancelRunsStep) {
68
68
  instructions.push(pathA(buildCommitSuggestionInstruction(prReference, "## Review threads")));
69
69
  if (resolutionOnlyThreads.length > 0)
70
70
  instructions.push("Review the threads under `## Review threads to resolve` before running the generated mutations.");
71
- instructions.push(...buildFailingCheckInstructions(failingChecks), ...repeatedWorkflowBranchRecoveryInstructions.map(pathA), ...queueEjectionSteps(queueEjection, stackRebase, branchRecovery));
71
+ const hasElsewhere = failingChecks.some((c) => c.elsewhere !== undefined || c.elsewhereUnread !== undefined);
72
+ instructions.push(...buildFailingCheckInstructions(failingChecks), ...repeatedWorkflowBranchRecoveryInstructions.map(pathA), ...queueEjectionSteps(queueEjection, stackRebase, branchRecovery, hasElsewhere));
72
73
  if (hasAnnotations)
73
74
  instructions.push(pathA("Inspect every referenced range under `## Check annotations` and apply any warranted change."));
74
75
  // The first step already covers applying changes-requested bodies; only stale CRs add a step.
@@ -12,6 +12,7 @@ import { buildCheckFollowUpInstructions, buildEvidenceFollowUpInstruction, check
12
12
  import { checkFollowUpKeys, readCheckFollowUp, readShownRunFailures, sameCheckFollowUp, writeCheckFollowUp, writeShownRunFailures, } from "../../state/check-follow-up.mjs";
13
13
  import { activeRunFailures, buildRunFailureWait, runFailureKeys, runFailuresShown, } from "./run-failure-wait.mjs";
14
14
  import { currentEjectionCommit, } from "./queue-recovery-instructions.mjs";
15
+ import { attachWorkflowElsewhere } from "./workflow-elsewhere.mjs";
15
16
  import { buildReleasedBlockerInstruction, buildReviewSubsetInstruction, } from "./check-instructions.mjs";
16
17
  import { buildNativeStackLayerRebase } from "./native-stack-rebase.mjs";
17
18
  import { buildDequeueCommand } from "./merge-plan.mjs";
@@ -183,10 +184,11 @@ async function handleTriageTick(ctx) {
183
184
  ? { ...c, rerunCommand: `gh run rerun ${c.runId} -R ${report.repo}` }
184
185
  : c;
185
186
  });
186
- const checks = [
187
- ...failingAgentChecks,
188
- ...toAgentChecks(annotatedExtra).map((c) => ({ ...c, annotationOnly: true })),
189
- ];
187
+ const annotatedAgentChecks = toAgentChecks(annotatedExtra).map((c) => ({
188
+ ...c,
189
+ annotationOnly: true,
190
+ }));
191
+ const checks = [...failingAgentChecks, ...annotatedAgentChecks];
190
192
  const { changesRequestedReviews } = report;
191
193
  const hasConflicts = report.mergeStatus.status === "CONFLICTS";
192
194
  const queuedConflict = isQueuedConflict(report.mergeQueue?.inQueue, report.mergeStatus.status);
@@ -325,13 +327,28 @@ async function handleTriageTick(ctx) {
325
327
  const queueRemovalAcknowledgment = acknowledgmentRecovery && !("unavailable" in acknowledgmentRecovery)
326
328
  ? acknowledgmentRecovery
327
329
  : undefined;
328
- const queueEjection = !currentEjectionCommit(report, failingAgentChecks)
330
+ const ejectionCommit = currentEjectionCommit(report, failingAgentChecks);
331
+ const queueEjection = !ejectionCommit
329
332
  ? undefined
330
333
  : requeue
331
334
  ? "requeue"
332
335
  : queueRemovalAcknowledgment
333
336
  ? "acknowledge"
334
337
  : "none";
338
+ const triageChecks = ejectionCommit
339
+ ? [
340
+ ...(await attachWorkflowElsewhere({
341
+ checks: failingAgentChecks,
342
+ rawFailing: failingChecks,
343
+ report,
344
+ repo: { owner: repoOwner, name: repoName },
345
+ stateKey: stallKey,
346
+ ejectionCommit,
347
+ compareWindowHours: loadConfig()["merge-queue"]["compare-window-hours"],
348
+ })),
349
+ ...annotatedAgentChecks,
350
+ ]
351
+ : checks;
335
352
  // Conflicts, a behind branch whose rerun already failed, and a queue ejection that may be
336
353
  // reproduced on the latest base all print the branch update route.
337
354
  const stackRebase = hasConflicts || (isBehind && exhaustedAttempts.length > 0) || queueEjection
@@ -341,7 +358,7 @@ async function handleTriageTick(ctx) {
341
358
  ? renderShellCommand(buildDequeueCommand(report.nodeId))
342
359
  : undefined;
343
360
  const inProgressRuns = await buildInProgressRuns(report, rerunAuthorized);
344
- const instructions = buildFixInstructions(threads, actionableComments, checks.filter((check) => !releasedCheckNames.has(check.name)), changesRequestedReviews, baseLookup.branch, resolveCommand, hasConflicts, prReference, firstLookThreads, firstLookComments, firstLookSummaries, editedSummaries, resolutionOnlyThreads, resolveOnlyCommand, behindBaseHint, isBehind, canGenerateGithubMutation(report.viewerAuthorization?.viewerCanUpdate, "ready"), exhaustedAttempts.length > 0, stackRebase, queueEjection, opts.instructions ?? configuredInstructions, dequeueCommand, buildCancelRunsInstruction(inProgressRuns));
361
+ const instructions = buildFixInstructions(threads, actionableComments, triageChecks.filter((check) => !releasedCheckNames.has(check.name)), changesRequestedReviews, baseLookup.branch, resolveCommand, hasConflicts, prReference, firstLookThreads, firstLookComments, firstLookSummaries, editedSummaries, resolutionOnlyThreads, resolveOnlyCommand, behindBaseHint, isBehind, canGenerateGithubMutation(report.viewerAuthorization?.viewerCanUpdate, "ready"), exhaustedAttempts.length > 0, stackRebase, queueEjection, opts.instructions ?? configuredInstructions, dequeueCommand, buildCancelRunsInstruction(inProgressRuns));
345
362
  if (investigate) {
346
363
  // The failing-checks pointer is replaced: these checks have no excerpt for the CI playbook.
347
364
  const triageStep = instructions.findIndex((step) => step.startsWith("Triage `## Failing checks`."));
@@ -426,7 +443,7 @@ async function handleTriageTick(ctx) {
426
443
  firstLookSummaries,
427
444
  editedSummaries,
428
445
  surfacedApprovals,
429
- checks,
446
+ checks: triageChecks,
430
447
  ...(inProgressRuns.length > 0 && { inProgressRuns }),
431
448
  ...(requeue && { requeue }),
432
449
  ...(queueRemovalAcknowledgment && { queueRemovalAcknowledgment }),
@@ -0,0 +1,19 @@
1
+ import type { RepoInfo } from "../../github/client.mts";
2
+ import { type StateKey } from "../../state/rest-cache.mts";
3
+ import type { AgentCheck, ShepherdReport, TriagedCheck } from "../../types.mts";
4
+ export interface AttachWorkflowElsewhereInput {
5
+ checks: AgentCheck[];
6
+ rawFailing: TriagedCheck[];
7
+ report: ShepherdReport;
8
+ repo: RepoInfo;
9
+ stateKey: StateKey;
10
+ ejectionCommit: string;
11
+ compareWindowHours: number;
12
+ nowMs?: number;
13
+ }
14
+ /**
15
+ * Enrich failing `merge_group` Actions checks belonging to the current queue removal with recent
16
+ * runs of the same workflow on the default branch and other queue entries. Cached briefly per
17
+ * removal; incomplete or failed reads are never cached and surface `elsewhereUnread`.
18
+ */
19
+ export declare function attachWorkflowElsewhere(input: AttachWorkflowElsewhereInput): Promise<AgentCheck[]>;
@@ -0,0 +1,144 @@
1
+ import { readWorkflowElsewhere, resolveWorkflowId, summarizeElsewhereError, } from "../../github/workflow-elsewhere-read.mjs";
2
+ import { stampSameJob } from "../../github/workflow-elsewhere-parse.mjs";
3
+ import { queueRemovalSignature } from "../../state/queue-removal-follow-up.mjs";
4
+ import { loadDerived, storeDerived } from "../../state/rest-cache.mjs";
5
+ /** Cache TTL so later default-branch failures/recoveries appear on subsequent ticks. */
6
+ const ELSEWHERE_CACHE_TTL_MS = 5 * 60 * 1000;
7
+ function isActionsProvenance(raw) {
8
+ return Boolean(raw &&
9
+ (raw.source === "startup_failure" ||
10
+ raw.workflowId !== undefined ||
11
+ raw.workflowName !== undefined));
12
+ }
13
+ function isFreshCached(value, nowMs) {
14
+ const e = value;
15
+ return Boolean(e &&
16
+ Array.isArray(e.runs) &&
17
+ typeof e.scope?.since === "string" &&
18
+ typeof e.scope?.defaultBranch?.branch === "string" &&
19
+ typeof e.scope?.defaultBranch?.matchedComplete === "boolean" &&
20
+ typeof e.scope?.mergeQueue?.runsRead === "number" &&
21
+ typeof e.scope?.mergeQueue?.matchedComplete === "boolean" &&
22
+ typeof e.cachedAtMs === "number" &&
23
+ nowMs - e.cachedAtMs >= 0 &&
24
+ nowMs - e.cachedAtMs < ELSEWHERE_CACHE_TTL_MS);
25
+ }
26
+ /**
27
+ * Enrich failing `merge_group` Actions checks belonging to the current queue removal with recent
28
+ * runs of the same workflow on the default branch and other queue entries. Cached briefly per
29
+ * removal; incomplete or failed reads are never cached and surface `elsewhereUnread`.
30
+ */
31
+ export async function attachWorkflowElsewhere(input) {
32
+ const { checks, rawFailing, report, repo, stateKey, ejectionCommit, compareWindowHours } = input;
33
+ const nowMs = input.nowMs ?? Date.now();
34
+ const removal = report.mergeQueue?.latestRemoval;
35
+ if (compareWindowHours <= 0 || !removal)
36
+ return checks;
37
+ const windowStartMs = Math.floor((removal.createdAtUnix - compareWindowHours * 3600) * 1000);
38
+ const since = new Date(windowStartMs).toISOString().replace(/\.\d{3}Z$/, "Z");
39
+ const signature = queueRemovalSignature({
40
+ headSha: report.headSha ?? "unknown",
41
+ createdAtUnix: removal.createdAtUnix,
42
+ beforeCommitOid: ejectionCommit,
43
+ });
44
+ const rawByRunId = new Map();
45
+ for (const raw of rawFailing) {
46
+ if (raw.runId !== null &&
47
+ raw.scope === "merge_group" &&
48
+ raw.commitOid === ejectionCommit &&
49
+ (!rawByRunId.has(raw.runId) || raw.workflowId !== undefined)) {
50
+ rawByRunId.set(raw.runId, raw);
51
+ }
52
+ }
53
+ const workflowIdByRunId = new Map();
54
+ const outcomeByWorkflowId = new Map();
55
+ const resolveForRun = async (runId, raw) => {
56
+ const cached = workflowIdByRunId.get(runId);
57
+ if (cached)
58
+ return cached;
59
+ if (raw.workflowId && /^\d+$/.test(raw.workflowId)) {
60
+ const hit = { id: raw.workflowId };
61
+ workflowIdByRunId.set(runId, hit);
62
+ return hit;
63
+ }
64
+ try {
65
+ const id = await resolveWorkflowId(repo, runId, stateKey);
66
+ const outcome = id ? { id } : { unread: "workflow ID unavailable" };
67
+ workflowIdByRunId.set(runId, outcome);
68
+ return outcome;
69
+ }
70
+ catch (error) {
71
+ const outcome = { unread: summarizeElsewhereError(error) };
72
+ workflowIdByRunId.set(runId, outcome);
73
+ return outcome;
74
+ }
75
+ };
76
+ const fetchForWorkflow = async (workflowId, currentRunId, raw, check) => {
77
+ const memoized = outcomeByWorkflowId.get(workflowId);
78
+ if (memoized)
79
+ return memoized;
80
+ const cacheName = `workflow-elsewhere:${signature}:wf:${workflowId}:h=${compareWindowHours}`;
81
+ const stored = await loadDerived(stateKey, cacheName);
82
+ if (stored && isFreshCached(stored.value, nowMs)) {
83
+ const hit = {
84
+ runs: stored.value.runs,
85
+ scope: stored.value.scope,
86
+ };
87
+ outcomeByWorkflowId.set(workflowId, hit);
88
+ return hit;
89
+ }
90
+ const workflowName = raw.workflowName ?? check.workflowName;
91
+ const workflowPath = raw.workflowPath ?? check.workflowPath;
92
+ let outcome;
93
+ try {
94
+ outcome = await readWorkflowElsewhere({
95
+ repo,
96
+ prNumber: report.pr,
97
+ workflowId,
98
+ ...(workflowName !== undefined && { workflowName }),
99
+ ...(workflowPath !== undefined && { workflowPath }),
100
+ currentRunId,
101
+ currentCommitOid: ejectionCommit,
102
+ windowStartMs,
103
+ since,
104
+ });
105
+ }
106
+ catch (error) {
107
+ outcome = { unread: summarizeElsewhereError(error) };
108
+ }
109
+ outcomeByWorkflowId.set(workflowId, outcome);
110
+ if ("runs" in outcome) {
111
+ await storeDerived(stateKey, cacheName, { runs: outcome.runs, scope: outcome.scope, cachedAtMs: nowMs }, report.headSha);
112
+ }
113
+ return outcome;
114
+ };
115
+ const enriched = [];
116
+ for (const check of checks) {
117
+ const raw = check.scope === "merge_group" && check.commitOid === ejectionCommit && check.runId
118
+ ? rawByRunId.get(check.runId)
119
+ : undefined;
120
+ if (!isActionsProvenance(raw)) {
121
+ enriched.push(check);
122
+ continue;
123
+ }
124
+ // eslint-disable-next-line no-await-in-loop
125
+ const resolved = await resolveForRun(check.runId, raw);
126
+ if ("unread" in resolved) {
127
+ enriched.push({ ...check, elsewhereUnread: resolved.unread });
128
+ continue;
129
+ }
130
+ // eslint-disable-next-line no-await-in-loop
131
+ const outcome = await fetchForWorkflow(resolved.id, check.runId, raw, check);
132
+ if ("unread" in outcome) {
133
+ enriched.push({ ...check, elsewhereUnread: outcome.unread });
134
+ }
135
+ else {
136
+ enriched.push({
137
+ ...check,
138
+ elsewhere: stampSameJob(outcome.runs, check.name),
139
+ elsewhereScope: outcome.scope,
140
+ });
141
+ }
142
+ }
143
+ return enriched;
144
+ }
@@ -7,9 +7,11 @@
7
7
  * result, or a different head, resets the timer. An elapsed marker stays until
8
8
  * the caller consumes it with `clearReadyDelay`.
9
9
  */
10
- import { readFile, writeFile, mkdir, unlink } from "node:fs/promises";
10
+ import { readFile } from "node:fs/promises";
11
+ import { writeFile, mkdir, unlink } from "../state/guarded-fs.mjs";
11
12
  import { dirname } from "node:path";
12
13
  import { resolvePrStatePath } from "../state/base.mjs";
14
+ import { isReadOnly } from "../execution-context.mjs";
13
15
  /**
14
16
  * Update the ready-delay state machine and return the current decision.
15
17
  *
@@ -22,6 +24,8 @@ import { resolvePrStatePath } from "../state/base.mjs";
22
24
  */
23
25
  export async function updateReadyDelay(prNumber, isReady, readyDelaySeconds, owner, repo, options) {
24
26
  const markerPath = readySincePath(prNumber, owner, repo, options.summary);
27
+ if (isReadOnly())
28
+ return readOnlyReadyDelay(markerPath, isReady, readyDelaySeconds, options);
25
29
  if (!isReady) {
26
30
  // Reset the timer.
27
31
  await safeUnlink(markerPath);
@@ -50,6 +54,25 @@ export async function updateReadyDelay(prNumber, isReady, readyDelaySeconds, own
50
54
  }
51
55
  return { isReady: true, shouldCancel: false, remainingSeconds: remaining };
52
56
  }
57
+ /**
58
+ * What the existing marker implies, without creating, refreshing or deleting it: no usable marker
59
+ * means the countdown has not started, so the full delay remains; a delay of 0 has elapsed at once.
60
+ */
61
+ async function readOnlyReadyDelay(markerPath, isReady, readyDelaySeconds, options) {
62
+ if (!isReady)
63
+ return { isReady: false, shouldCancel: false, remainingSeconds: readyDelaySeconds };
64
+ if (options.alreadyElapsed || readyDelaySeconds <= 0) {
65
+ return { isReady: true, shouldCancel: true, remainingSeconds: 0 };
66
+ }
67
+ const now = Math.floor(Date.now() / 1000);
68
+ const readySince = await readReadySince(markerPath, options.headSha);
69
+ const remaining = readySince === null || readySince > now
70
+ ? readyDelaySeconds
71
+ : readyDelaySeconds - (now - readySince);
72
+ return remaining <= 0
73
+ ? { isReady: true, shouldCancel: true, remainingSeconds: 0 }
74
+ : { isReady: true, shouldCancel: false, remainingSeconds: remaining };
75
+ }
53
76
  /** Delete the ready-delay marker once an elapsed delay has been consumed. */
54
77
  export async function clearReadyDelay(prNumber, owner, repo) {
55
78
  await safeUnlink(readySincePath(prNumber, owner, repo));
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readFile, writeFile, mkdir, unlink } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
+ import { writeFile, mkdir, unlink } from "../state/guarded-fs.mjs";
3
4
  import { dirname } from "node:path";
4
5
  import { resolvePrStatePath } from "../state/base.mjs";
5
6
  import { rest, restWithRateLimit } from "../github/http.mjs";