pr-shepherd 2.2.17 → 2.3.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 (72) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +4 -1
  3. package/bin/cli/triage-formatter.mjs +2 -0
  4. package/bin/cli/workflow-elsewhere-format.d.mts +3 -0
  5. package/bin/cli/workflow-elsewhere-format.mjs +112 -0
  6. package/bin/commands/check-annotations.d.mts +2 -0
  7. package/bin/commands/check-annotations.mjs +22 -7
  8. package/bin/commands/check-unread-readiness.d.mts +6 -0
  9. package/bin/commands/check-unread-readiness.mjs +7 -0
  10. package/bin/commands/check.mjs +5 -0
  11. package/bin/commands/iterate/queue-recovery-instructions.d.mts +1 -1
  12. package/bin/commands/iterate/queue-recovery-instructions.mjs +7 -4
  13. package/bin/commands/iterate/render.mjs +2 -1
  14. package/bin/commands/iterate/triage.mjs +24 -7
  15. package/bin/commands/iterate/workflow-elsewhere.d.mts +19 -0
  16. package/bin/commands/iterate/workflow-elsewhere.mjs +144 -0
  17. package/bin/config/schema.d.mts +6 -0
  18. package/bin/config/schema.mjs +3 -0
  19. package/bin/github/batch-page-helpers.d.mts +3 -0
  20. package/bin/github/batch-page-helpers.mjs +5 -2
  21. package/bin/github/batch-page.mjs +2 -4
  22. package/bin/github/batch-parser-helpers.mjs +2 -0
  23. package/bin/github/batch-parsers.mjs +3 -3
  24. package/bin/github/batch-raw-types.d.mts +4 -2
  25. package/bin/github/batch-receipt-evidence.mjs +1 -0
  26. package/bin/github/batch-response.d.mts +2 -1
  27. package/bin/github/batch-response.mjs +8 -11
  28. package/bin/github/batch.mjs +8 -3
  29. package/bin/github/check-annotation-pages.d.mts +10 -1
  30. package/bin/github/check-annotation-pages.mjs +26 -2
  31. package/bin/github/gql/default-branch-workflow-runs.gql +71 -0
  32. package/bin/github/merge-queue-checks.mjs +8 -4
  33. package/bin/github/null-nodes.d.mts +19 -0
  34. package/bin/github/null-nodes.mjs +68 -0
  35. package/bin/github/poll-summary-annotation-probe.mjs +3 -1
  36. package/bin/github/poll-summary-check-hydration.mjs +8 -5
  37. package/bin/github/poll-summary-checks.mjs +2 -0
  38. package/bin/github/poll-summary-fingerprint.mjs +2 -0
  39. package/bin/github/poll-summary-raw.d.mts +2 -0
  40. package/bin/github/poll-summary-readiness.mjs +2 -0
  41. package/bin/github/poll-summary-review.mjs +2 -1
  42. package/bin/github/queries.d.mts +2 -0
  43. package/bin/github/queries.mjs +2 -0
  44. package/bin/github/stack-handoff-page.mjs +2 -2
  45. package/bin/github/stack-read.mjs +1 -1
  46. package/bin/github/thread-comments.d.mts +6 -2
  47. package/bin/github/thread-comments.mjs +12 -1
  48. package/bin/github/workflow-elsewhere-parse.d.mts +19 -0
  49. package/bin/github/workflow-elsewhere-parse.mjs +172 -0
  50. package/bin/github/workflow-elsewhere-queue.d.mts +28 -0
  51. package/bin/github/workflow-elsewhere-queue.mjs +137 -0
  52. package/bin/github/workflow-elsewhere-read.d.mts +26 -0
  53. package/bin/github/workflow-elsewhere-read.mjs +120 -0
  54. package/bin/github/workflow-elsewhere-rest-runs.d.mts +20 -0
  55. package/bin/github/workflow-elsewhere-rest-runs.mjs +54 -0
  56. package/bin/github/workflow-elsewhere-rest.d.mts +3 -0
  57. package/bin/github/workflow-elsewhere-rest.mjs +126 -0
  58. package/bin/types/github.d.mts +2 -0
  59. package/bin/types/report.d.mts +7 -0
  60. package/bin/types/workflow-elsewhere-raw.d.mts +108 -0
  61. package/bin/types/workflow-elsewhere-raw.mjs +1 -0
  62. package/bin/types/workflow-elsewhere.d.mts +55 -0
  63. package/bin/types/workflow-elsewhere.mjs +1 -0
  64. package/bin/types.d.mts +1 -0
  65. package/bin/types.mjs +1 -0
  66. package/package.json +1 -1
  67. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  68. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  69. package/plugins/pr-shepherd/skills/pr-shepherd/references/merge-queue-ejection.md +1 -1
  70. package/pr-shepherd.schema.json +13 -0
  71. package/bin/github/check-suite-nodes.d.mts +0 -17
  72. package/bin/github/check-suite-nodes.mjs +0 -14
@@ -0,0 +1,19 @@
1
+ import type { ElsewhereFailedJob, ElsewhereRun } from "../types/workflow-elsewhere.mts";
2
+ import type { ParsedDefaultBranchRuns, RawDefaultBranchRunsResponse, RawElsewhereSuite } from "../types/workflow-elsewhere-raw.mts";
3
+ export declare const MAX_ELSEWHERE_RUNS_PER_SOURCE = 3;
4
+ export declare const MAX_ELSEWHERE_FAILED_JOBS = 15;
5
+ export declare const MAX_ELSEWHERE_ANNOTATIONS = 3;
6
+ export declare const NON_DEFAULT_BRANCH_EVENTS: Set<string>;
7
+ /** Collapse newlines and whitespace and bound an annotation message for single-line display. */
8
+ export declare function normalizeAnnotationMessage(raw: string | null | undefined): string;
9
+ /** Remove null annotation entries in place and report whether any were present. */
10
+ export declare function stripNullAnnotations(suites: Array<RawElsewhereSuite | null> | undefined): boolean;
11
+ /** Extract failed/timed-out check runs and up to 3 annotations per job from one GraphQL suite. */
12
+ export declare function mapFailedJobs(suite: RawElsewhereSuite | undefined): ElsewhereFailedJob[];
13
+ /** Sort runs newest-first by completion timestamp, breaking ties by numeric run ID descending. */
14
+ export declare function sortNewestFirst<T extends {
15
+ completedAt: string;
16
+ runId: string;
17
+ }>(items: T[]): T[];
18
+ export declare function parseDefaultBranchRuns(data: RawDefaultBranchRunsResponse, workflowId: string, windowStartMs: number): ParsedDefaultBranchRuns;
19
+ export declare function stampSameJob(runs: readonly ElsewhereRun[], checkName: string): ElsewhereRun[];
@@ -0,0 +1,172 @@
1
+ import { normalizeWorkflowPath } from "../checks/workflow-path.mjs";
2
+ import { dropNullNodes } from "./null-nodes.mjs";
3
+ export const MAX_ELSEWHERE_RUNS_PER_SOURCE = 3;
4
+ export const MAX_ELSEWHERE_FAILED_JOBS = 15;
5
+ export const MAX_ELSEWHERE_ANNOTATIONS = 3;
6
+ const MAX_ANNOTATION_MESSAGE_CHARS = 240;
7
+ export const NON_DEFAULT_BRANCH_EVENTS = new Set([
8
+ "pull_request",
9
+ "pull_request_target",
10
+ "merge_group",
11
+ ]);
12
+ /** Collapse newlines and whitespace and bound an annotation message for single-line display. */
13
+ export function normalizeAnnotationMessage(raw) {
14
+ const s = (raw ?? "").replace(/\s+/g, " ").trim();
15
+ return s.length <= MAX_ANNOTATION_MESSAGE_CHARS
16
+ ? s
17
+ : `${s.slice(0, MAX_ANNOTATION_MESSAGE_CHARS - 1)}…`;
18
+ }
19
+ /** Remove null annotation entries in place and report whether any were present. */
20
+ export function stripNullAnnotations(suites) {
21
+ let foundNull = false;
22
+ for (const suite of suites ?? []) {
23
+ for (const checkRun of suite?.checkRuns?.nodes ?? []) {
24
+ const nodes = checkRun?.annotations?.nodes;
25
+ if (!Array.isArray(nodes))
26
+ continue;
27
+ const kept = nodes.filter((node) => node !== null);
28
+ if (kept.length !== nodes.length) {
29
+ foundNull = true;
30
+ checkRun.annotations.nodes = kept;
31
+ }
32
+ }
33
+ }
34
+ return foundNull;
35
+ }
36
+ /** Extract failed/timed-out check runs and up to 3 annotations per job from one GraphQL suite. */
37
+ export function mapFailedJobs(suite) {
38
+ const failed = (suite?.checkRuns?.nodes ?? []).filter((run) => {
39
+ const c = run?.conclusion?.toUpperCase() ?? "";
40
+ return c === "FAILURE" || c === "TIMED_OUT";
41
+ });
42
+ return failed.slice(0, MAX_ELSEWHERE_FAILED_JOBS).map((run) => {
43
+ const annotations = (run.annotations?.nodes ?? [])
44
+ .slice(0, MAX_ELSEWHERE_ANNOTATIONS)
45
+ .map((ann) => ({
46
+ path: (ann.path ?? "").trim(),
47
+ line: typeof ann.location?.start?.line === "number" && ann.location.start.line > 0
48
+ ? ann.location.start.line
49
+ : null,
50
+ message: normalizeAnnotationMessage(ann.message),
51
+ }));
52
+ const total = run.annotations?.totalCount;
53
+ const more = typeof total === "number" && total > annotations.length
54
+ ? total - annotations.length
55
+ : undefined;
56
+ return {
57
+ name: run.name,
58
+ conclusion: run.conclusion.toUpperCase(),
59
+ annotations,
60
+ ...(more !== undefined && { moreAnnotations: more }),
61
+ };
62
+ });
63
+ }
64
+ /** Sort runs newest-first by completion timestamp, breaking ties by numeric run ID descending. */
65
+ export function sortNewestFirst(items) {
66
+ return [...items].sort((a, b) => Date.parse(b.completedAt) - Date.parse(a.completedAt) || Number(b.runId) - Number(a.runId));
67
+ }
68
+ function suiteUpdatedInWindow(suite, windowStartMs) {
69
+ const ts = suite?.workflowRun?.updatedAt ?? suite?.updatedAt;
70
+ const ms = ts ? Date.parse(ts) : Number.NaN;
71
+ return Number.isFinite(ms) && ms >= windowStartMs;
72
+ }
73
+ const emptyDefaultResult = (extra) => ({
74
+ runs: [],
75
+ incomplete: false,
76
+ commitsRead: 0,
77
+ matched: 0,
78
+ matchedComplete: false,
79
+ ...extra,
80
+ });
81
+ export function parseDefaultBranchRuns(data, workflowId, windowStartMs) {
82
+ const unread = dropNullNodes(data);
83
+ const defaultRef = data.repository?.defaultBranchRef;
84
+ const history = defaultRef?.target?.history;
85
+ const commits = history?.nodes;
86
+ if (!defaultRef?.name || !Array.isArray(commits)) {
87
+ return emptyDefaultResult({ unavailable: "default branch history unavailable" });
88
+ }
89
+ const nullAnnotations = commits.some((c) => stripNullAnnotations(c?.checkSuites?.nodes));
90
+ const nullSuites = commits.some((c) => c?.checkSuites === null);
91
+ if (unread || nullAnnotations || nullSuites) {
92
+ return emptyDefaultResult({ incomplete: true, commitsRead: commits.length });
93
+ }
94
+ const targetId = Number(workflowId);
95
+ const byRunId = new Map();
96
+ let truncatedSuites = false;
97
+ let lastCommitInWindow = false;
98
+ let workflowName;
99
+ let workflowPath;
100
+ for (const commit of commits) {
101
+ let matchedOnCommit = false;
102
+ let hasInWindowSuite = false;
103
+ for (const suite of commit.checkSuites?.nodes ?? []) {
104
+ if (suiteUpdatedInWindow(suite, windowStartMs))
105
+ hasInWindowSuite = true;
106
+ const wfRun = suite.workflowRun;
107
+ if (!wfRun || wfRun.workflow?.databaseId !== targetId)
108
+ continue;
109
+ if (!workflowName && wfRun.workflow.name?.trim())
110
+ workflowName = wfRun.workflow.name.trim();
111
+ if (!workflowPath)
112
+ workflowPath = normalizeWorkflowPath(wfRun.file?.path);
113
+ if (wfRun.databaseId == null || !Number.isSafeInteger(wfRun.databaseId))
114
+ continue;
115
+ if (suite.branch?.name && suite.branch.name !== defaultRef.name)
116
+ continue;
117
+ if (wfRun.event && NON_DEFAULT_BRANCH_EVENTS.has(wfRun.event))
118
+ continue;
119
+ if (!suite.conclusion || (suite.status && suite.status !== "COMPLETED"))
120
+ continue;
121
+ const completedAt = wfRun.updatedAt ?? suite.updatedAt ?? commit.committedDate;
122
+ const completedMs = Date.parse(completedAt);
123
+ if (!Number.isFinite(completedMs) || completedMs < windowStartMs)
124
+ continue;
125
+ matchedOnCommit = true;
126
+ const runId = String(wfRun.databaseId);
127
+ if (byRunId.has(runId))
128
+ continue;
129
+ byRunId.set(runId, {
130
+ source: "default-branch",
131
+ branch: defaultRef.name,
132
+ headSha: commit.oid.slice(0, 7),
133
+ runId,
134
+ conclusion: suite.conclusion.toUpperCase(),
135
+ completedAt,
136
+ failedJobs: mapFailedJobs(suite),
137
+ });
138
+ }
139
+ const commitMs = Date.parse(commit.committedDate);
140
+ lastCommitInWindow =
141
+ hasInWindowSuite || !Number.isFinite(commitMs) || commitMs >= windowStartMs;
142
+ if (lastCommitInWindow && commit.checkSuites?.pageInfo?.hasNextPage && !matchedOnCommit) {
143
+ truncatedSuites = true;
144
+ }
145
+ }
146
+ const truncated = truncatedSuites || (Boolean(history?.pageInfo?.hasNextPage) && lastCommitInWindow);
147
+ if (truncated && byRunId.size < MAX_ELSEWHERE_RUNS_PER_SOURCE) {
148
+ return emptyDefaultResult({
149
+ unavailable: "default branch workflow history truncated",
150
+ branch: defaultRef.name,
151
+ commitsRead: commits.length,
152
+ matched: byRunId.size,
153
+ });
154
+ }
155
+ return {
156
+ ...emptyDefaultResult({
157
+ branch: defaultRef.name,
158
+ commitsRead: commits.length,
159
+ matched: byRunId.size,
160
+ matchedComplete: !truncated,
161
+ }),
162
+ runs: sortNewestFirst([...byRunId.values()]).slice(0, MAX_ELSEWHERE_RUNS_PER_SOURCE),
163
+ ...(workflowName !== undefined && { workflowName }),
164
+ ...(workflowPath !== undefined && { workflowPath }),
165
+ };
166
+ }
167
+ export function stampSameJob(runs, checkName) {
168
+ return runs.map((run) => ({
169
+ ...run,
170
+ failedJobs: run.failedJobs.map((j) => j.name === checkName ? { ...j, sameJob: true } : { ...j }),
171
+ }));
172
+ }
@@ -0,0 +1,28 @@
1
+ import type { ElsewhereRun } from "../types/workflow-elsewhere.mts";
2
+ import type { RawQueueCommitsResponse, RestRunCandidate, RestWorkflowRunItem } from "../types/workflow-elsewhere-raw.mts";
3
+ /** Filter and cap REST `merge_group` workflow runs to up to 3 completed entries from other PRs. */
4
+ export declare function selectOtherQueueRestRuns(runs: readonly RestWorkflowRunItem[], opts: {
5
+ prNumber: number;
6
+ currentRunId: string;
7
+ currentCommitOid: string;
8
+ windowStartMs: number;
9
+ }): {
10
+ candidates: RestRunCandidate[];
11
+ matched: number;
12
+ };
13
+ /** Filter and cap REST default-branch workflow runs to up to 3 completed entries in the window. */
14
+ export declare function selectDefaultBranchRestRuns(runs: readonly RestWorkflowRunItem[], branch: string, windowStartMs: number): {
15
+ candidates: RestRunCandidate[];
16
+ matched: number;
17
+ };
18
+ /** Build one aliased GraphQL query fetching failed check runs and annotations for queue commits. */
19
+ export declare function buildQueueCommitsQuery(owner: string, repo: string, oids: readonly string[]): {
20
+ query: string;
21
+ variables: Record<string, string>;
22
+ };
23
+ /** Combine REST queue-run candidates with GraphQL commit check suites; missing suites mark unavailable. */
24
+ export declare function mergeQueueCommitDetails(candidates: readonly RestRunCandidate[], oidToAlias: ReadonlyMap<string, string>, data: RawQueueCommitsResponse | undefined): {
25
+ runs: ElsewhereRun[];
26
+ incomplete: boolean;
27
+ unavailable?: string;
28
+ };
@@ -0,0 +1,137 @@
1
+ import { dropNullNodes } from "./null-nodes.mjs";
2
+ import { MAX_ELSEWHERE_RUNS_PER_SOURCE, NON_DEFAULT_BRANCH_EVENTS, mapFailedJobs, sortNewestFirst, stripNullAnnotations, } from "./workflow-elsewhere-parse.mjs";
3
+ const QUEUE_BRANCH_PR_RE = /^gh-readonly-queue\/.+\/pr-(\d+)-[0-9a-f]+$/i;
4
+ /** Parse the PR number from GitHub's merge-queue head branch `gh-readonly-queue/<base>/pr-<N>-<sha>`. */
5
+ function parseQueueHeadBranchPr(headBranch) {
6
+ if (!headBranch)
7
+ return undefined;
8
+ const match = QUEUE_BRANCH_PR_RE.exec(headBranch);
9
+ if (!match)
10
+ return undefined;
11
+ const num = Number.parseInt(match[1], 10);
12
+ return Number.isSafeInteger(num) && num > 0 ? num : undefined;
13
+ }
14
+ function validRunAttempt(attempt) {
15
+ return typeof attempt === "number" && Number.isSafeInteger(attempt) && attempt > 0
16
+ ? attempt
17
+ : undefined;
18
+ }
19
+ /** Filter and cap REST `merge_group` workflow runs to up to 3 completed entries from other PRs. */
20
+ export function selectOtherQueueRestRuns(runs, opts) {
21
+ const byRunId = new Map();
22
+ for (const run of runs) {
23
+ if (run.status !== "completed" || !run.conclusion)
24
+ continue;
25
+ const runId = String(run.id);
26
+ if (runId === opts.currentRunId || run.head_sha === opts.currentCommitOid)
27
+ continue;
28
+ const pr = parseQueueHeadBranchPr(run.head_branch);
29
+ if (pr === opts.prNumber)
30
+ continue;
31
+ const completedAt = run.updated_at ?? run.created_at;
32
+ const completedMs = Date.parse(completedAt);
33
+ if (!Number.isFinite(completedMs) || completedMs < opts.windowStartMs)
34
+ continue;
35
+ if (byRunId.has(runId))
36
+ continue;
37
+ const runAttempt = validRunAttempt(run.run_attempt);
38
+ byRunId.set(runId, {
39
+ runId,
40
+ headSha: run.head_sha,
41
+ ...(pr !== undefined && { pr }),
42
+ ...(runAttempt !== undefined && { runAttempt }),
43
+ conclusion: run.conclusion.toUpperCase(),
44
+ completedAt,
45
+ });
46
+ }
47
+ const sorted = sortNewestFirst([...byRunId.values()]);
48
+ return {
49
+ candidates: sorted.slice(0, MAX_ELSEWHERE_RUNS_PER_SOURCE),
50
+ matched: sorted.length,
51
+ };
52
+ }
53
+ /** Filter and cap REST default-branch workflow runs to up to 3 completed entries in the window. */
54
+ export function selectDefaultBranchRestRuns(runs, branch, windowStartMs) {
55
+ const byRunId = new Map();
56
+ for (const run of runs) {
57
+ if (run.status !== "completed" || !run.conclusion)
58
+ continue;
59
+ if (run.event && NON_DEFAULT_BRANCH_EVENTS.has(run.event))
60
+ continue;
61
+ const completedAt = run.updated_at ?? run.created_at;
62
+ const completedMs = Date.parse(completedAt);
63
+ if (!Number.isFinite(completedMs) || completedMs < windowStartMs)
64
+ continue;
65
+ const runId = String(run.id);
66
+ if (byRunId.has(runId))
67
+ continue;
68
+ const runAttempt = validRunAttempt(run.run_attempt);
69
+ byRunId.set(runId, {
70
+ runId,
71
+ headSha: run.head_sha,
72
+ branch,
73
+ ...(runAttempt !== undefined && { runAttempt }),
74
+ conclusion: run.conclusion.toUpperCase(),
75
+ completedAt,
76
+ });
77
+ }
78
+ const sorted = sortNewestFirst([...byRunId.values()]);
79
+ return {
80
+ candidates: sorted.slice(0, MAX_ELSEWHERE_RUNS_PER_SOURCE),
81
+ matched: sorted.length,
82
+ };
83
+ }
84
+ /** Build one aliased GraphQL query fetching failed check runs and annotations for queue commits. */
85
+ export function buildQueueCommitsQuery(owner, repo, oids) {
86
+ const decls = oids.map((_, i) => `, $oid${i}: String!`).join("");
87
+ const fields = oids
88
+ .map((_, i) => `c${i}: object(expression: $oid${i}) { ... on Commit { oid checkSuites(first: 20) { pageInfo { hasNextPage } nodes { workflowRun { databaseId } checkRuns(first: 15, filterBy: { conclusions: [FAILURE, TIMED_OUT] }) { nodes { name conclusion annotations(first: 3) { totalCount nodes { path location { start { line } } message } } } } } } } }`)
89
+ .join(" ");
90
+ const query = `query QueueCommitCheckSuites($owner: String!, $repo: String!${decls}) { _shepherdRateLimit: rateLimit { cost limit nodeCount remaining resetAt used } repository(owner: $owner, name: $repo) { ${fields} } }`;
91
+ const variables = { owner, repo };
92
+ oids.forEach((oid, i) => {
93
+ variables[`oid${i}`] = oid;
94
+ });
95
+ return { query, variables };
96
+ }
97
+ /** Combine REST queue-run candidates with GraphQL commit check suites; missing suites mark unavailable. */
98
+ export function mergeQueueCommitDetails(candidates, oidToAlias, data) {
99
+ if (data) {
100
+ const unread = dropNullNodes(data);
101
+ let nullAnnotations = false;
102
+ for (const commit of Object.values(data.repository ?? {})) {
103
+ if (stripNullAnnotations(commit?.checkSuites?.nodes))
104
+ nullAnnotations = true;
105
+ }
106
+ if (unread || nullAnnotations)
107
+ return { runs: [], incomplete: true };
108
+ }
109
+ const runs = [];
110
+ for (const candidate of candidates) {
111
+ let failedJobs = [];
112
+ if (candidate.conclusion !== "SUCCESS") {
113
+ const alias = oidToAlias.get(candidate.headSha);
114
+ const commit = alias ? data?.repository?.[alias] : undefined;
115
+ const suite = (commit?.checkSuites?.nodes ?? []).find((s) => s?.workflowRun?.databaseId != null &&
116
+ String(s.workflowRun.databaseId) === candidate.runId);
117
+ if (!suite) {
118
+ return {
119
+ runs: [],
120
+ incomplete: false,
121
+ unavailable: "merge-queue commit check suite unavailable",
122
+ };
123
+ }
124
+ failedJobs = mapFailedJobs(suite);
125
+ }
126
+ runs.push({
127
+ source: "merge-queue",
128
+ ...(candidate.pr !== undefined && { pr: candidate.pr }),
129
+ headSha: candidate.headSha.slice(0, 7),
130
+ runId: candidate.runId,
131
+ conclusion: candidate.conclusion,
132
+ completedAt: candidate.completedAt,
133
+ failedJobs,
134
+ });
135
+ }
136
+ return { runs, incomplete: false };
137
+ }
@@ -0,0 +1,26 @@
1
+ import { type RepoInfo } from "./client.mts";
2
+ import { type StateKey } from "../state/rest-cache.mts";
3
+ import type { ElsewhereRun, ElsewhereScope } from "../types/workflow-elsewhere.mts";
4
+ export interface ReadWorkflowElsewhereInput {
5
+ repo: RepoInfo;
6
+ prNumber: number;
7
+ workflowId: string;
8
+ workflowName?: string;
9
+ workflowPath?: string;
10
+ currentRunId: string;
11
+ currentCommitOid: string;
12
+ windowStartMs: number;
13
+ since: string;
14
+ }
15
+ export type WorkflowElsewhereReadResult = {
16
+ runs: ElsewhereRun[];
17
+ scope: ElsewhereScope;
18
+ } | {
19
+ unread: string;
20
+ };
21
+ /** Format an optional workflow-elsewhere read failure into a single-line `unread` reason. */
22
+ export declare function summarizeElsewhereError(error: unknown): string;
23
+ /** Resolve numeric workflow ID from `GET /actions/runs/{id}` when GraphQL did not include it. */
24
+ export declare function resolveWorkflowId(repo: RepoInfo, runId: string, stateKey: StateKey): Promise<string | undefined>;
25
+ /** Read same-workflow runs on the default branch and other merge-queue entries. */
26
+ export declare function readWorkflowElsewhere(input: ReadWorkflowElsewhereInput): Promise<WorkflowElsewhereReadResult>;
@@ -0,0 +1,120 @@
1
+ import { graphql } from "./client.mjs";
2
+ import { GitHubRequestError } from "./errors.mjs";
3
+ import { rest } from "./http.mjs";
4
+ import { DEFAULT_BRANCH_WORKFLOW_RUNS_QUERY } from "./queries.mjs";
5
+ import { githubOperation } from "./transport.mjs";
6
+ import { pollRateLimitRetryAfterMs } from "../commands/poll-quota.mjs";
7
+ import { loadDerived, storeDerived } from "../state/rest-cache.mjs";
8
+ import { MAX_ELSEWHERE_RUNS_PER_SOURCE, parseDefaultBranchRuns, sortNewestFirst, } from "./workflow-elsewhere-parse.mjs";
9
+ import { buildQueueCommitsQuery, mergeQueueCommitDetails, selectOtherQueueRestRuns, } from "./workflow-elsewhere-queue.mjs";
10
+ import { readWorkflowElsewhereRest } from "./workflow-elsewhere-rest.mjs";
11
+ import { fetchRestWorkflowRunsPaged } from "./workflow-elsewhere-rest-runs.mjs";
12
+ const MAX_ERROR_CHARS = 120;
13
+ const repoPrefix = (repo) => `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
14
+ /** Format an optional workflow-elsewhere read failure into a single-line `unread` reason. */
15
+ export function summarizeElsewhereError(error) {
16
+ const retry = pollRateLimitRetryAfterMs(error);
17
+ if (retry !== null) {
18
+ return `rate limited, retry after ${Math.max(1, Math.ceil(retry.ms / 1000))}s`;
19
+ }
20
+ if (error instanceof GitHubRequestError)
21
+ return `HTTP ${error.status}`;
22
+ const raw = error instanceof Error ? error.message : String(error);
23
+ const compact = raw.replace(/\s+/g, " ").trim();
24
+ if (!compact)
25
+ return "request failed";
26
+ return compact.length <= MAX_ERROR_CHARS ? compact : `${compact.slice(0, MAX_ERROR_CHARS - 1)}…`;
27
+ }
28
+ /** Resolve numeric workflow ID from `GET /actions/runs/{id}` when GraphQL did not include it. */
29
+ export async function resolveWorkflowId(repo, runId, stateKey) {
30
+ const cacheName = `run-workflow-id:${runId}`;
31
+ const cached = await loadDerived(stateKey, cacheName);
32
+ if (cached && typeof cached.value === "string" && /^\d+$/.test(cached.value)) {
33
+ return cached.value;
34
+ }
35
+ const data = await rest("GET", `${repoPrefix(repo)}/actions/runs/${encodeURIComponent(runId)}`);
36
+ const id = data?.workflow_id;
37
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0)
38
+ return undefined;
39
+ const resolved = String(id);
40
+ await storeDerived(stateKey, cacheName, resolved);
41
+ return resolved;
42
+ }
43
+ /** Read same-workflow runs on the default branch and other merge-queue entries. */
44
+ export async function readWorkflowElsewhere(input) {
45
+ const { repo, workflowId, windowStartMs, since } = input;
46
+ const defaultOutcome = await githubOperation("WorkflowElsewhereDefault", async () => ({
47
+ kind: "graphql",
48
+ data: (await graphql(DEFAULT_BRANCH_WORKFLOW_RUNS_QUERY, {
49
+ owner: repo.owner,
50
+ repo: repo.name,
51
+ })).data,
52
+ }), async () => ({ kind: "rest", result: await readWorkflowElsewhereRest(input) }));
53
+ if (defaultOutcome.kind === "rest")
54
+ return defaultOutcome.result;
55
+ const defaultParsed = parseDefaultBranchRuns(defaultOutcome.data, workflowId, windowStartMs);
56
+ if (defaultParsed.incomplete)
57
+ return { unread: "GitHub returned incomplete (null) nodes" };
58
+ if (defaultParsed.unavailable)
59
+ return { unread: defaultParsed.unavailable };
60
+ // Keep the REST queue listing outside `githubOperation` so a REST error never flips the
61
+ // session transport from GraphQL to REST.
62
+ const wfPath = `${repoPrefix(repo)}/actions/workflows/${encodeURIComponent(workflowId)}/runs`;
63
+ let queueRead;
64
+ try {
65
+ queueRead = await fetchRestWorkflowRunsPaged(`${wfPath}?event=merge_group&status=completed`, windowStartMs, (items) => selectOtherQueueRestRuns(items, {
66
+ prNumber: input.prNumber,
67
+ currentRunId: input.currentRunId,
68
+ currentCommitOid: input.currentCommitOid,
69
+ windowStartMs,
70
+ }), MAX_ELSEWHERE_RUNS_PER_SOURCE);
71
+ }
72
+ catch (error) {
73
+ return { unread: summarizeElsewhereError(error) };
74
+ }
75
+ if ("unread" in queueRead)
76
+ return queueRead;
77
+ const queueCandidates = queueRead.candidates;
78
+ const oids = [
79
+ ...new Set(queueCandidates.filter((c) => c.conclusion !== "SUCCESS").map((c) => c.headSha)),
80
+ ];
81
+ let queueData;
82
+ const oidToAlias = new Map();
83
+ if (oids.length > 0) {
84
+ oids.forEach((oid, i) => oidToAlias.set(oid, `c${i}`));
85
+ const { query, variables } = buildQueueCommitsQuery(repo.owner, repo.name, oids);
86
+ const queueOutcome = await githubOperation("WorkflowElsewhereQueue", async () => ({
87
+ kind: "graphql",
88
+ data: (await graphql(query, variables)).data,
89
+ }), async () => ({ kind: "rest", result: await readWorkflowElsewhereRest(input) }));
90
+ if (queueOutcome.kind === "rest")
91
+ return queueOutcome.result;
92
+ queueData = queueOutcome.data;
93
+ }
94
+ const queueParsed = mergeQueueCommitDetails(queueCandidates, oidToAlias, queueData);
95
+ if (queueParsed.incomplete)
96
+ return { unread: "GitHub returned incomplete (null) nodes" };
97
+ if (queueParsed.unavailable)
98
+ return { unread: queueParsed.unavailable };
99
+ const workflowName = defaultParsed.workflowName ?? queueRead.workflowName ?? input.workflowName;
100
+ const workflowPath = defaultParsed.workflowPath ?? queueRead.workflowPath ?? input.workflowPath;
101
+ const scope = {
102
+ ...(workflowName !== undefined && { workflowName }),
103
+ ...(workflowPath !== undefined && { workflowPath }),
104
+ since,
105
+ defaultBranch: {
106
+ branch: defaultParsed.branch,
107
+ commitsRead: defaultParsed.commitsRead,
108
+ matched: defaultParsed.matched,
109
+ matchedComplete: defaultParsed.matchedComplete,
110
+ shown: defaultParsed.runs.length,
111
+ },
112
+ mergeQueue: {
113
+ runsRead: queueRead.runsRead,
114
+ matched: queueRead.matched,
115
+ matchedComplete: queueRead.matchedComplete,
116
+ shown: queueParsed.runs.length,
117
+ },
118
+ };
119
+ return { runs: sortNewestFirst([...defaultParsed.runs, ...queueParsed.runs]), scope };
120
+ }
@@ -0,0 +1,20 @@
1
+ import type { RestRunCandidate, RestWorkflowRunItem } from "../types/workflow-elsewhere-raw.mts";
2
+ /**
3
+ * Page REST workflow runs up to `MAX_RUN_PAGES` until `targetCount` candidates are found, a page
4
+ * is partial, or one full page past the `created_at < windowStartMs` cutoff has been read (so
5
+ * re-runs of older runs completing inside the window are seen). Returns `unread` if the budget
6
+ * exhausts before that condition is met.
7
+ */
8
+ export declare function fetchRestWorkflowRunsPaged(baseQuery: string, windowStartMs: number, select: (items: readonly RestWorkflowRunItem[]) => {
9
+ candidates: RestRunCandidate[];
10
+ matched: number;
11
+ }, targetCount: number): Promise<{
12
+ candidates: RestRunCandidate[];
13
+ matched: number;
14
+ matchedComplete: boolean;
15
+ runsRead: number;
16
+ workflowName?: string;
17
+ workflowPath?: string;
18
+ } | {
19
+ unread: string;
20
+ }>;
@@ -0,0 +1,54 @@
1
+ import { normalizeWorkflowPath } from "../checks/workflow-path.mjs";
2
+ import { rest } from "./http.mjs";
3
+ const REST_RUNS_PER_PAGE = 30;
4
+ const MAX_RUN_PAGES = 3;
5
+ function extractRestWorkflowMeta(items) {
6
+ let workflowName;
7
+ let workflowPath;
8
+ for (const item of items) {
9
+ if (!workflowName && item.name?.trim())
10
+ workflowName = item.name.trim();
11
+ if (!workflowPath)
12
+ workflowPath = normalizeWorkflowPath(item.path);
13
+ if (workflowName && workflowPath)
14
+ break;
15
+ }
16
+ return {
17
+ ...(workflowName !== undefined && { workflowName }),
18
+ ...(workflowPath !== undefined && { workflowPath }),
19
+ };
20
+ }
21
+ /**
22
+ * Page REST workflow runs up to `MAX_RUN_PAGES` until `targetCount` candidates are found, a page
23
+ * is partial, or one full page past the `created_at < windowStartMs` cutoff has been read (so
24
+ * re-runs of older runs completing inside the window are seen). Returns `unread` if the budget
25
+ * exhausts before that condition is met.
26
+ */
27
+ export async function fetchRestWorkflowRunsPaged(baseQuery, windowStartMs, select, targetCount) {
28
+ const all = [];
29
+ let sawPreWindowPage = false;
30
+ for (let page = 1; page <= MAX_RUN_PAGES; page++) {
31
+ // eslint-disable-next-line no-await-in-loop
32
+ const payload = await rest("GET", `${baseQuery}&per_page=${REST_RUNS_PER_PAGE}&page=${page}`);
33
+ if (!Array.isArray(payload?.workflow_runs))
34
+ return { unread: "malformed workflow runs response" };
35
+ const items = payload.workflow_runs;
36
+ all.push(...items);
37
+ const { candidates, matched } = select(all);
38
+ const reachedEnd = items.length < REST_RUNS_PER_PAGE || sawPreWindowPage;
39
+ if (reachedEnd || candidates.length >= targetCount) {
40
+ return {
41
+ candidates,
42
+ matched,
43
+ matchedComplete: reachedEnd,
44
+ runsRead: all.length,
45
+ ...extractRestWorkflowMeta(all),
46
+ };
47
+ }
48
+ const oldestCreatedMs = Date.parse(items[items.length - 1].created_at);
49
+ if (Number.isFinite(oldestCreatedMs) && oldestCreatedMs < windowStartMs) {
50
+ sawPreWindowPage = true;
51
+ }
52
+ }
53
+ return { unread: "workflow runs pagination truncated" };
54
+ }
@@ -0,0 +1,3 @@
1
+ import type { ReadWorkflowElsewhereInput, WorkflowElsewhereReadResult } from "./workflow-elsewhere-read.mts";
2
+ /** REST transport reader for same-workflow runs on the default branch and other queue entries. */
3
+ export declare function readWorkflowElsewhereRest(input: ReadWorkflowElsewhereInput): Promise<WorkflowElsewhereReadResult>;