pr-shepherd 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +8 -1
  3. package/bin/api.d.mts +1 -1
  4. package/bin/cli/display-body.d.mts +8 -0
  5. package/bin/cli/display-body.mjs +157 -0
  6. package/bin/cli/list-formatters.mjs +4 -2
  7. package/bin/commands/iterate/index.mjs +4 -0
  8. package/bin/commands/poll-events.d.mts +44 -0
  9. package/bin/commands/poll-events.mjs +123 -0
  10. package/bin/commands/poll-options.d.mts +9 -0
  11. package/bin/commands/poll-options.mjs +1 -0
  12. package/bin/commands/poll-progress.d.mts +2 -0
  13. package/bin/commands/poll-progress.mjs +6 -4
  14. package/bin/commands/poll-quota.d.mts +2 -0
  15. package/bin/commands/poll-quota.mjs +4 -0
  16. package/bin/commands/poll-summary.d.mts +1 -0
  17. package/bin/commands/poll-summary.mjs +30 -18
  18. package/bin/commands/poll-tick.d.mts +17 -0
  19. package/bin/commands/poll-tick.mjs +24 -0
  20. package/bin/commands/poll.d.mts +3 -9
  21. package/bin/commands/poll.mjs +64 -60
  22. package/bin/commands/stall-deadline.d.mts +20 -0
  23. package/bin/commands/stall-deadline.mjs +42 -0
  24. package/bin/commands/tick.mjs +1 -16
  25. package/bin/config/schema.d.mts +14 -0
  26. package/bin/config/schema.mjs +6 -0
  27. package/bin/events/config.d.mts +7 -0
  28. package/bin/events/config.mjs +66 -0
  29. package/bin/events/envelope.d.mts +4 -0
  30. package/bin/events/envelope.mjs +27 -0
  31. package/bin/events/filters.d.mts +8 -0
  32. package/bin/events/filters.mjs +27 -0
  33. package/bin/events/health.d.mts +14 -0
  34. package/bin/events/health.mjs +27 -0
  35. package/bin/events/matcher.d.mts +2 -0
  36. package/bin/events/matcher.mjs +32 -0
  37. package/bin/events/relay.d.mts +11 -0
  38. package/bin/events/relay.mjs +86 -0
  39. package/bin/events/serve.d.mts +10 -0
  40. package/bin/events/serve.mjs +137 -0
  41. package/bin/events/sse.d.mts +10 -0
  42. package/bin/events/sse.mjs +50 -0
  43. package/bin/events/types.d.mts +69 -0
  44. package/bin/events/types.mjs +1 -0
  45. package/bin/events/waiter.d.mts +47 -0
  46. package/bin/events/waiter.mjs +80 -0
  47. package/bin/github/batch-first-page.d.mts +17 -0
  48. package/bin/github/batch-first-page.mjs +48 -0
  49. package/bin/github/batch-page.d.mts +2 -0
  50. package/bin/github/batch-page.mjs +2 -2
  51. package/bin/github/batch-stack-evidence.d.mts +3 -1
  52. package/bin/github/batch-stack-evidence.mjs +4 -2
  53. package/bin/github/batch-viewer.d.mts +24 -0
  54. package/bin/github/batch-viewer.mjs +66 -0
  55. package/bin/github/batch.d.mts +1 -1
  56. package/bin/github/batch.mjs +30 -35
  57. package/bin/github/check-annotations-batch.mjs +1 -7
  58. package/bin/github/gql/batch-pr-viewer.gql +46 -0
  59. package/bin/github/gql-strip-viewer.d.mts +7 -0
  60. package/bin/github/gql-strip-viewer.mjs +14 -0
  61. package/bin/github/queries.d.mts +8 -0
  62. package/bin/github/queries.mjs +9 -0
  63. package/bin/github/thread-comments.d.mts +1 -1
  64. package/bin/github/thread-comments.mjs +7 -7
  65. package/bin/types/iterate.d.mts +9 -0
  66. package/bin/util/chunks.d.mts +2 -0
  67. package/bin/util/chunks.mjs +8 -0
  68. package/package.json +1 -1
  69. package/plugins/pr-shepherd/.claude-plugin/plugin.json +1 -1
  70. package/plugins/pr-shepherd/.codex-plugin/plugin.json +1 -1
  71. package/plugins/pr-shepherd/.codex.mcp.json +1 -1
  72. package/plugins/pr-shepherd/.mcp.json +1 -1
  73. package/plugins/pr-shepherd/package-lock.json +4 -4
  74. package/plugins/pr-shepherd/package.json +1 -1
  75. package/plugins/pr-shepherd/skills/pr-shepherd/SKILL.md +1 -0
  76. package/pr-shepherd.schema.json +21 -0
@@ -0,0 +1,86 @@
1
+ import { filtersParam } from "./filters.mjs";
2
+ import { parseEnvelopes } from "./envelope.mjs";
3
+ const RELAY_POLL_MS = 15_000;
4
+ /** Per-request bound the default fetch applies (proxy-aware `githubFetch`). */
5
+ export const RELAY_REQUEST_TIMEOUT_MS = 10_000;
6
+ const PAGE_LIMIT = 100;
7
+ /** `more: true` repolls at once; this bounds a runaway relay. */
8
+ const MAX_PAGES = 20;
9
+ /**
10
+ * Polls the relay's `GET /events`, one request per owner (DynamoDB partitions by owner). Cursors
11
+ * are opaque and echoed back exactly; the only one constructed is the bare epoch-ms start.
12
+ */
13
+ export function createRelayTransport(config, startMs, deps) {
14
+ const base = config.url.endsWith("/") ? config.url : `${config.url}/`;
15
+ const cursors = new Map();
16
+ let filtersRejected = false;
17
+ let notice;
18
+ async function pollOwner(scope) {
19
+ const events = [];
20
+ let failure;
21
+ try {
22
+ for (let page = 0; page < MAX_PAGES; page += 1) {
23
+ const params = new URLSearchParams({ owner: scope.owner });
24
+ if (scope.repos.length > 0)
25
+ params.set("repos", scope.repos.join(","));
26
+ params.set("after", cursors.get(scope.owner) ?? String(startMs));
27
+ params.set("limit", String(PAGE_LIMIT));
28
+ params.set("payload", "0");
29
+ const filters = filtersRejected ? undefined : filtersParam(scope.filters);
30
+ if (filters)
31
+ params.set("filters", filters);
32
+ const response = await deps.fetch(new URL(`events?${params}`, base), {
33
+ headers: { authorization: `Bearer ${config.token}` },
34
+ });
35
+ if (response.status === 401 || response.status === 403) {
36
+ return { kind: "uncovered", reason: `relay answered HTTP ${response.status}` };
37
+ }
38
+ if (response.status === 400 && filters) {
39
+ filtersRejected = true;
40
+ notice = "events: relay rejected `filters` (HTTP 400); matching locally without them";
41
+ page -= 1;
42
+ continue;
43
+ }
44
+ if (!response.ok) {
45
+ failure = `relay answered HTTP ${response.status}`;
46
+ break;
47
+ }
48
+ const body = (await response.json());
49
+ if (body === null || typeof body.cursor !== "string" || !Array.isArray(body.events)) {
50
+ failure = "relay returned a malformed page";
51
+ break;
52
+ }
53
+ cursors.set(scope.owner, body.cursor);
54
+ events.push(...parseEnvelopes(body.events));
55
+ if (body.gap === true)
56
+ failure = "relay reported a gap (cursor older than retention)";
57
+ if (body.more !== true)
58
+ break;
59
+ }
60
+ }
61
+ catch (error) {
62
+ failure = `relay request failed (${error instanceof Error ? error.name : "error"})`;
63
+ }
64
+ return { kind: "ok", events, ...(failure && { failure }) };
65
+ }
66
+ return {
67
+ intervalMs: RELAY_POLL_MS,
68
+ async poll(scopes) {
69
+ const outcomes = await Promise.all(scopes.map(pollOwner));
70
+ const result = { events: [], ...(notice && { notice }) };
71
+ notice = undefined;
72
+ outcomes.forEach((outcome, index) => {
73
+ if (outcome.kind === "ok") {
74
+ result.events.push(...outcome.events);
75
+ if (outcome.failure)
76
+ result.unhealthy = outcome.failure;
77
+ }
78
+ else {
79
+ (result.uncovered ??= []).push({ owner: scopes[index].owner, reason: outcome.reason });
80
+ }
81
+ });
82
+ return result;
83
+ },
84
+ close() { },
85
+ };
86
+ }
@@ -0,0 +1,10 @@
1
+ import type { EventDeps, EventTransport } from "./types.mts";
2
+ /**
3
+ * Streams a local `hook-harness serve` over SSE. The stream feeds an in-memory buffer; `poll`
4
+ * drains it, waiting up to `waitMs` for the first event. A dropped stream is reconnected on the
5
+ * next poll from the last `id` seen, so a wait that finds it dead degrades rather than hangs.
6
+ */
7
+ export declare function createServeTransport(config: {
8
+ url: string;
9
+ token: string;
10
+ }, startMs: number, deps: Pick<EventDeps, "fetch">): EventTransport;
@@ -0,0 +1,137 @@
1
+ import { parseEnvelope } from "./envelope.mjs";
2
+ import { createSseParser } from "./sse.mjs";
3
+ const CONNECT_TIMEOUT_MS = 10_000;
4
+ /** hook-harness's own resume cursor: base64url JSON around the relay sort key. */
5
+ function resumeCursor(startMs) {
6
+ return Buffer.from(JSON.stringify({ v: 1, sk: String(startMs), seen: [] })).toString("base64url");
7
+ }
8
+ /**
9
+ * Streams a local `hook-harness serve` over SSE. The stream feeds an in-memory buffer; `poll`
10
+ * drains it, waiting up to `waitMs` for the first event. A dropped stream is reconnected on the
11
+ * next poll from the last `id` seen, so a wait that finds it dead degrades rather than hangs.
12
+ */
13
+ export function createServeTransport(config, startMs, deps) {
14
+ const url = new URL("events", config.url.endsWith("/") ? config.url : `${config.url}/`);
15
+ let lastId = resumeCursor(startMs);
16
+ let controller;
17
+ let streamError;
18
+ let gap = false;
19
+ let buffer = [];
20
+ let wake;
21
+ const notify = () => {
22
+ wake?.();
23
+ wake = undefined;
24
+ };
25
+ async function read(body, mine) {
26
+ const parse = createSseParser();
27
+ const decoder = new TextDecoder();
28
+ try {
29
+ for await (const chunk of body) {
30
+ if (controller !== mine)
31
+ return;
32
+ for (const message of parse(decoder.decode(chunk, { stream: true }))) {
33
+ if (message.id)
34
+ lastId = message.id;
35
+ if (message.event === "gap")
36
+ gap = true;
37
+ const envelope = message.event === "envelope" ? parseEnvelope(safeJson(message.data)) : null;
38
+ if (envelope)
39
+ buffer.push(envelope);
40
+ }
41
+ notify();
42
+ }
43
+ if (controller === mine)
44
+ streamError = "serve closed the stream";
45
+ }
46
+ catch (error) {
47
+ if (controller === mine) {
48
+ streamError = `serve stream failed (${error instanceof Error ? error.name : "error"})`;
49
+ }
50
+ }
51
+ notify();
52
+ }
53
+ /** Open the stream; returns a failure reason, or undefined once connected. */
54
+ async function connect() {
55
+ const next = new AbortController();
56
+ const timer = setTimeout(() => next.abort(), CONNECT_TIMEOUT_MS);
57
+ try {
58
+ const response = await deps.fetch(url, {
59
+ headers: {
60
+ accept: "text/event-stream",
61
+ "last-event-id": lastId,
62
+ ...(config.token && { authorization: `Bearer ${config.token}` }),
63
+ },
64
+ signal: next.signal,
65
+ });
66
+ if (response.status === 401 || response.status === 403) {
67
+ return { reason: `serve answered HTTP ${response.status}`, denied: true };
68
+ }
69
+ if (!response.ok || !response.body) {
70
+ return { reason: `serve answered HTTP ${response.status}`, denied: false };
71
+ }
72
+ controller = next;
73
+ streamError = undefined;
74
+ void read(response.body, next);
75
+ return undefined;
76
+ }
77
+ catch (error) {
78
+ next.abort();
79
+ return {
80
+ reason: `serve connection failed (${error instanceof Error ? error.name : "error"})`,
81
+ denied: false,
82
+ };
83
+ }
84
+ finally {
85
+ clearTimeout(timer);
86
+ }
87
+ }
88
+ return {
89
+ intervalMs: 0,
90
+ async poll(scopes, waitMs) {
91
+ if (controller === undefined || streamError !== undefined) {
92
+ controller?.abort();
93
+ controller = undefined;
94
+ const failure = await connect();
95
+ if (failure?.denied) {
96
+ return {
97
+ events: [],
98
+ uncovered: scopes.map(({ owner }) => ({ owner, reason: failure.reason })),
99
+ };
100
+ }
101
+ if (failure)
102
+ return { events: [], unhealthy: failure.reason };
103
+ }
104
+ if (buffer.length === 0 && streamError === undefined) {
105
+ await new Promise((resolve) => {
106
+ const timer = setTimeout(() => done(), waitMs);
107
+ const done = () => {
108
+ clearTimeout(timer);
109
+ resolve();
110
+ };
111
+ wake = done;
112
+ });
113
+ }
114
+ const events = buffer;
115
+ buffer = [];
116
+ const result = { events };
117
+ if (gap)
118
+ result.unhealthy = "serve reported a gap";
119
+ else if (streamError)
120
+ result.unhealthy = streamError;
121
+ gap = false;
122
+ return result;
123
+ },
124
+ close() {
125
+ controller?.abort();
126
+ controller = undefined;
127
+ },
128
+ };
129
+ }
130
+ function safeJson(text) {
131
+ try {
132
+ return JSON.parse(text);
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ }
@@ -0,0 +1,10 @@
1
+ export interface SseMessage {
2
+ id?: string;
3
+ event: string;
4
+ data: string;
5
+ }
6
+ /**
7
+ * Incremental Server-Sent Events parser. Feed it decoded chunks; it returns each completed
8
+ * message. Comment lines (`: ping` keepalives) and unknown fields are dropped.
9
+ */
10
+ export declare function createSseParser(): (chunk: string) => SseMessage[];
@@ -0,0 +1,50 @@
1
+ /** Longest line or frame accepted; a larger one throws so the wait degrades to plain polling. */
2
+ const MAX_SSE_BYTES = 1024 * 1024;
3
+ /**
4
+ * Incremental Server-Sent Events parser. Feed it decoded chunks; it returns each completed
5
+ * message. Comment lines (`: ping` keepalives) and unknown fields are dropped.
6
+ */
7
+ export function createSseParser() {
8
+ let buffer = "";
9
+ let id;
10
+ let event = "message";
11
+ let data = [];
12
+ let dataLength = 0;
13
+ return (chunk) => {
14
+ buffer += chunk;
15
+ // A trailing "\r" may be the first half of "\r\n"; keep it until the next chunk decides.
16
+ const heldCr = buffer.endsWith("\r");
17
+ const lines = (heldCr ? buffer.slice(0, -1) : buffer).split(/\r\n|\n|\r/);
18
+ const tail = lines.pop();
19
+ buffer = heldCr ? `${tail}\r` : tail;
20
+ if (buffer.length > MAX_SSE_BYTES)
21
+ throw new Error("SSE line exceeds 1 MiB");
22
+ const messages = [];
23
+ for (const line of lines) {
24
+ if (line === "") {
25
+ if (data.length > 0)
26
+ messages.push({ ...(id !== undefined && { id }), event, data: data.join("\n") });
27
+ event = "message";
28
+ data = [];
29
+ dataLength = 0;
30
+ continue;
31
+ }
32
+ if (line.startsWith(":"))
33
+ continue;
34
+ const colon = line.indexOf(":");
35
+ const field = colon === -1 ? line : line.slice(0, colon);
36
+ const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
37
+ if (field === "id")
38
+ id = value;
39
+ else if (field === "event")
40
+ event = value;
41
+ else if (field === "data") {
42
+ dataLength += value.length + 1;
43
+ if (dataLength > MAX_SSE_BYTES)
44
+ throw new Error("SSE frame exceeds 1 MiB");
45
+ data.push(value);
46
+ }
47
+ }
48
+ return messages;
49
+ };
50
+ }
@@ -0,0 +1,69 @@
1
+ /** The envelope fields pr-shepherd reads. Events are wake signals; payloads are never used. */
2
+ export interface EventEnvelope {
3
+ id: string;
4
+ event: string;
5
+ action?: string | null;
6
+ repo: string | null;
7
+ prs: number[];
8
+ headSha: string | null;
9
+ headRef: string | null;
10
+ baseRef: string | null;
11
+ }
12
+ /** One watched PR. `headSha` and `headRef` are omitted when the tick never read them. */
13
+ export interface WatchTarget {
14
+ repo: string;
15
+ pr: number;
16
+ headSha?: string;
17
+ headRef?: string;
18
+ baseRef?: string;
19
+ }
20
+ /** Relay-side bandwidth hint; the waiter always matches locally too. */
21
+ export type EventFilter = {
22
+ pr: number[];
23
+ } | {
24
+ sha: string[];
25
+ } | {
26
+ ref: string[];
27
+ } | {
28
+ event: string[];
29
+ branch: string[];
30
+ };
31
+ export interface OwnerScope {
32
+ owner: string;
33
+ repos: string[];
34
+ filters: EventFilter[];
35
+ }
36
+ export interface TransportResult {
37
+ events: EventEnvelope[];
38
+ /** A one-time note for the verbose progress and debug log. */
39
+ notice?: string;
40
+ /** The source could not be trusted this poll (5xx, network, gap, malformed). */
41
+ unhealthy?: string;
42
+ /** Owners the token cannot read; they stay uncovered for the rest of the run. */
43
+ uncovered?: Array<{
44
+ owner: string;
45
+ reason: string;
46
+ }>;
47
+ }
48
+ export interface EventTransport {
49
+ /** Pause the waiter leaves between polls; 0 when `poll` blocks on its own. */
50
+ intervalMs: number;
51
+ /** Fetch new events; a blocking transport waits up to `waitMs` for one. */
52
+ poll(scopes: OwnerScope[], waitMs: number): Promise<TransportResult>;
53
+ close(): void;
54
+ }
55
+ export type EventsSourceConfig = {
56
+ kind: "relay";
57
+ url: string;
58
+ token: string;
59
+ } | {
60
+ kind: "serve";
61
+ url: string;
62
+ token: string;
63
+ };
64
+ /** Injectable I/O so the sources are testable without a network. */
65
+ export interface EventDeps {
66
+ fetch: (input: string | URL, init?: RequestInit) => Promise<Response>;
67
+ now: () => number;
68
+ sleep: (ms: number) => Promise<void>;
69
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,47 @@
1
+ import type { EventDeps, EventEnvelope, EventTransport, WatchTarget } from "./types.mts";
2
+ interface WaitRequest {
3
+ targets: readonly WatchTarget[];
4
+ /** The plain sleep: `poll.interval-seconds` raised by any quota band. */
5
+ sleepMs: number;
6
+ /** Time left in the poll window; `Infinity` for `--until-terminal`. */
7
+ windowMs: number;
8
+ /** GitHub is still recomputing mergeability: keep the plain recheck cadence. */
9
+ recheck: boolean;
10
+ /** Earliest gap after `tickStartedAt` before the next tick may start. */
11
+ minGapMs: number;
12
+ tickStartedAt: number;
13
+ /**
14
+ * Epoch ms of a time-based deadline no event announces (the stall timeout). It caps the healthy
15
+ * wait, but never below `sleepMs`.
16
+ */
17
+ deadlineAt?: number;
18
+ }
19
+ export type Wake = {
20
+ kind: "event";
21
+ event: EventEnvelope;
22
+ } | {
23
+ kind: "timer";
24
+ };
25
+ interface WaitOutcome {
26
+ wake: Wake;
27
+ /** The source was lost during this wait, so the plain deadline applied. */
28
+ degraded: boolean;
29
+ }
30
+ export interface EventWaiter {
31
+ /** False once an owner is known uncovered: the caller keeps today's plain polling. */
32
+ engaged(targets: readonly WatchTarget[]): boolean;
33
+ wait(request: WaitRequest): Promise<WaitOutcome>;
34
+ close(): void;
35
+ }
36
+ /**
37
+ * Wait for an event that matches a watched PR, or a deadline. The healthy deadline is the
38
+ * fallback interval; once the source fails the plain `sleepMs` applies from the start of the wait.
39
+ * Events are wake signals only: the caller always runs a full tick afterwards.
40
+ */
41
+ export declare function createEventWaiter(options: {
42
+ transport: EventTransport;
43
+ fallbackMs: number;
44
+ deps: Pick<EventDeps, "now" | "sleep">;
45
+ note: (message: string) => void;
46
+ }): EventWaiter;
47
+ export {};
@@ -0,0 +1,80 @@
1
+ import { createHealth, ownerOf } from "./health.mjs";
2
+ import { filtersFor } from "./filters.mjs";
3
+ import { matchesAny } from "./matcher.mjs";
4
+ /** After the first matching event, wait this long so a burst becomes one tick. */
5
+ const SETTLE_MS = 10_000;
6
+ const SEEN_LIMIT = 2000;
7
+ function scopesOf(targets) {
8
+ const byOwner = new Map();
9
+ for (const target of targets) {
10
+ const owner = ownerOf(target.repo);
11
+ byOwner.set(owner, [...(byOwner.get(owner) ?? []), target]);
12
+ }
13
+ return [...byOwner].map(([owner, owned]) => ({
14
+ owner,
15
+ repos: [...new Set(owned.map((target) => target.repo.toLowerCase()))],
16
+ filters: filtersFor(owned),
17
+ }));
18
+ }
19
+ /**
20
+ * Wait for an event that matches a watched PR, or a deadline. The healthy deadline is the
21
+ * fallback interval; once the source fails the plain `sleepMs` applies from the start of the wait.
22
+ * Events are wake signals only: the caller always runs a full tick afterwards.
23
+ */
24
+ export function createEventWaiter(options) {
25
+ const { transport, fallbackMs, deps } = options;
26
+ const health = createHealth(options.note);
27
+ const seen = new Set();
28
+ const fresh = (events) => events.filter((event) => {
29
+ if (seen.has(event.id))
30
+ return false;
31
+ seen.add(event.id);
32
+ if (seen.size > SEEN_LIMIT)
33
+ seen.delete(seen.values().next().value);
34
+ return true;
35
+ });
36
+ return {
37
+ engaged: (targets) => health.covers(targets),
38
+ async wait(request) {
39
+ const scopes = scopesOf(request.targets);
40
+ const start = deps.now();
41
+ const capped = request.deadlineAt === undefined
42
+ ? fallbackMs
43
+ : Math.min(fallbackMs, request.deadlineAt - start);
44
+ const healthyMs = request.recheck ? request.sleepMs : Math.max(request.sleepMs, capped);
45
+ const deadline = (degraded) => start + Math.min(degraded ? request.sleepMs : healthyMs, request.windowMs);
46
+ let degraded = false;
47
+ while (true) {
48
+ const result = await transport.poll(scopes, Math.max(deadline(degraded) - deps.now(), 0));
49
+ if (result.notice)
50
+ options.note(result.notice);
51
+ for (const { owner, reason } of result.uncovered ?? [])
52
+ health.markUncovered(owner, reason);
53
+ if (result.uncovered || result.unhealthy)
54
+ degraded = true;
55
+ if (result.unhealthy)
56
+ health.markUnhealthy(result.unhealthy);
57
+ else if (!result.uncovered)
58
+ health.markHealthy();
59
+ const hit = fresh(result.events).find((event) => matchesAny(event, request.targets));
60
+ if (hit) {
61
+ const hitAt = deps.now();
62
+ const settled = Math.max(hitAt + SETTLE_MS, request.tickStartedAt + request.minGapMs);
63
+ const wakeAt = Math.min(settled, Math.max(start + request.windowMs, hitAt));
64
+ await deps.sleep(Math.max(wakeAt - hitAt, 0));
65
+ return { wake: { kind: "event", event: hit }, degraded };
66
+ }
67
+ const left = deadline(degraded) - deps.now();
68
+ if (left <= 0)
69
+ return { wake: { kind: "timer" }, degraded };
70
+ if (degraded) {
71
+ await deps.sleep(left);
72
+ return { wake: { kind: "timer" }, degraded };
73
+ }
74
+ if (transport.intervalMs > 0)
75
+ await deps.sleep(Math.min(transport.intervalMs, left));
76
+ }
77
+ },
78
+ close: () => transport.close(),
79
+ };
80
+ }
@@ -0,0 +1,17 @@
1
+ import { type RateLimitInfo, type RepoInfo } from "./client.mts";
2
+ import type { RawBatchResponse } from "./batch-raw-types.mts";
3
+ interface FirstPageOptions {
4
+ includeReceiptSummary?: boolean;
5
+ }
6
+ /**
7
+ * Whether this tick reads `BatchPr` viewer-free and the viewer fields apart. A GitHub App
8
+ * answers only viewer-free documents, so the split is worth its extra request only when one
9
+ * covers the repository and its GraphQL bucket has quota. Without an App the single combined query stays. The READY receipt
10
+ * sibling stays combined too: a READY candidate needs the viewer fields in that tick anyway.
11
+ */
12
+ export declare function usesViewerSplit(repo: RepoInfo, opts: FirstPageOptions): Promise<boolean>;
13
+ export declare function readBatchFirstPage(pr: number, repo: RepoInfo, opts: FirstPageOptions, split: boolean): Promise<{
14
+ data: RawBatchResponse;
15
+ rateLimit?: RateLimitInfo;
16
+ }>;
17
+ export {};
@@ -0,0 +1,48 @@
1
+ import { graphqlWithRateLimit } from "./client.mjs";
2
+ import { BATCH_PR_DATA_QUERY, BATCH_PR_QUERY, BATCH_PR_RECEIPT_QUERY } from "./queries.mjs";
3
+ import { findGithubApp } from "./github-app-config.mjs";
4
+ import { appCredential } from "./github-app-token.mjs";
5
+ import { isAppExhausted } from "./app-quota.mjs";
6
+ import { GitHubRequestError, isRetryableGraphQlResourceLimit, } from "./errors.mjs";
7
+ import { rateLimitKind } from "./rate-limit-kind.mjs";
8
+ /**
9
+ * Whether this tick reads `BatchPr` viewer-free and the viewer fields apart. A GitHub App
10
+ * answers only viewer-free documents, so the split is worth its extra request only when one
11
+ * covers the repository and its GraphQL bucket has quota. Without an App the single combined query stays. The READY receipt
12
+ * sibling stays combined too: a READY candidate needs the viewer fields in that tick anyway.
13
+ */
14
+ export async function usesViewerSplit(repo, opts) {
15
+ const app = opts.includeReceiptSummary ? undefined : findGithubApp(repo.owner, repo.name);
16
+ if (!app)
17
+ return false;
18
+ // An exhausted installation sends the data read to the user's token, so splitting would add a
19
+ // user-token request: use the combined query until the bucket resets.
20
+ const { installationId } = await appCredential(app, { owner: repo.owner, repo: repo.name });
21
+ return !isAppExhausted(installationId, "graphql");
22
+ }
23
+ function onlyReceiptSummaryErrors(errors) {
24
+ return (!!errors?.length &&
25
+ errors.every((error) => Array.isArray(error.path) &&
26
+ error.path[0] === "repository" &&
27
+ error.path[1] === "receiptSummary"));
28
+ }
29
+ export async function readBatchFirstPage(pr, repo, opts, split) {
30
+ const variables = { owner: repo.owner, repo: repo.name, pr };
31
+ // The data read goes to the App; `applyBatchViewer` reads the viewer fields on the user's token.
32
+ if (split)
33
+ return graphqlWithRateLimit(BATCH_PR_DATA_QUERY, variables);
34
+ try {
35
+ return await graphqlWithRateLimit(opts.includeReceiptSummary ? BATCH_PR_RECEIPT_QUERY : BATCH_PR_QUERY, variables);
36
+ }
37
+ catch (error) {
38
+ if (!opts.includeReceiptSummary ||
39
+ !(error instanceof GitHubRequestError) ||
40
+ rateLimitKind(error) !== null ||
41
+ !(isRetryableGraphQlResourceLimit(error.graphqlErrors) ||
42
+ (error.status === 200 && onlyReceiptSummaryErrors(error.graphqlErrors))))
43
+ throw error;
44
+ // Receipt evidence is optional; a resource-limited combined query or an
45
+ // error confined to its sibling must not prevent the ordinary snapshot.
46
+ return graphqlWithRateLimit(BATCH_PR_QUERY, variables);
47
+ }
48
+ }
@@ -6,6 +6,8 @@ export interface PaginatedBatchNodes extends PageAccumulator {
6
6
  }
7
7
  export interface PaginateBatchOptions {
8
8
  paginateApprovedReviews?: boolean;
9
+ /** Select no viewer field, so a GitHub App can answer the follow-up pages. */
10
+ viewerFree?: boolean;
9
11
  }
10
12
  /**
11
13
  * Fetch remaining connection pages with a slim `@include` query. Independent
@@ -1,6 +1,6 @@
1
1
  import { graphqlWithRateLimit } from "./client.mjs";
2
2
  import { GitHubRequestError } from "./errors.mjs";
3
- import { BATCH_PR_PAGE_QUERY } from "./queries.mjs";
3
+ import { BATCH_PR_PAGE_DATA_QUERY, BATCH_PR_PAGE_QUERY } from "./queries.mjs";
4
4
  import { requireContextNodes } from "./batch-response.mjs";
5
5
  import { applyIncludedPage, backwardCursor, forwardCursor, } from "./batch-page-helpers.mjs";
6
6
  /**
@@ -33,7 +33,7 @@ export async function paginateBatchConnections(pr, repo, raw, opts, initialRateL
33
33
  if (rateLimit?.remaining === 0) {
34
34
  throw new GitHubRequestError("GitHub GraphQL rate limit remaining is 0; pagination incomplete", { status: 403, rateLimit });
35
35
  }
36
- const res = await graphqlWithRateLimit(BATCH_PR_PAGE_QUERY, {
36
+ const res = await graphqlWithRateLimit(opts.viewerFree === true ? BATCH_PR_PAGE_DATA_QUERY : BATCH_PR_PAGE_QUERY, {
37
37
  owner: repo.owner,
38
38
  repo: repo.name,
39
39
  pr,
@@ -25,4 +25,6 @@ export declare function stackEvidenceFromRaw(raw: RawPrMergeFields & {
25
25
  repository?: {
26
26
  viewerCanAdminister?: boolean;
27
27
  } | null;
28
- }): BatchStackEvidence | undefined;
28
+ },
29
+ /** A viewer-free read has no viewer login or administer bit, so it omits the topology. */
30
+ viewerFree?: boolean): BatchStackEvidence | undefined;
@@ -1,7 +1,9 @@
1
1
  import { parseBranchRules } from "./batch-parsers-rules.mjs";
2
2
  import { orderedStackMembers } from "./stack-order.mjs";
3
3
  /** Validate the embedded stack selections of one `BatchPr` first page. */
4
- export function stackEvidenceFromRaw(raw, data) {
4
+ export function stackEvidenceFromRaw(raw, data,
5
+ /** A viewer-free read has no viewer login or administer bit, so it omits the topology. */
6
+ viewerFree = false) {
5
7
  const stack = raw.stack;
6
8
  if (!stack)
7
9
  return undefined;
@@ -9,7 +11,7 @@ export function stackEvidenceFromRaw(raw, data) {
9
11
  login: data.viewer?.login ?? null,
10
12
  canAdminister: data.repository?.viewerCanAdminister,
11
13
  };
12
- const topology = embeddedTopology(stack, raw.number, viewer);
14
+ const topology = viewerFree ? undefined : embeddedTopology(stack, raw.number, viewer);
13
15
  const trunk = embeddedTrunkRules(stack, raw);
14
16
  if (!topology && !trunk)
15
17
  return undefined;
@@ -0,0 +1,24 @@
1
+ import { type RateLimitInfo, type RepoInfo } from "./client.mts";
2
+ import type { RawComment, RawPr, RawReviewSummary, RawThread } from "./batch-raw-types.mts";
3
+ /** The nodes of a viewer-free `BatchPr` read whose viewer fields are still missing. */
4
+ export interface ViewerTargets {
5
+ threads: RawThread[];
6
+ comments: RawComment[];
7
+ reviews: RawReviewSummary[];
8
+ }
9
+ export interface BatchViewer {
10
+ login: string | null;
11
+ repository: {
12
+ viewerPermission: string | null;
13
+ viewerCanAdminister: boolean;
14
+ };
15
+ rateLimit?: RateLimitInfo;
16
+ }
17
+ /**
18
+ * Read the viewer-relative fields a viewer-free `BatchPr` read omitted, on the user's token, in
19
+ * the same tick, and write them onto the raw nodes. A node GitHub did not return keeps its
20
+ * fields unset, which the parser reads as "no" (fail closed). `viewerDidAuthor` on thread
21
+ * comments is the viewer login compared with the comment author: one login per request instead
22
+ * of one id per comment.
23
+ */
24
+ export declare function applyBatchViewer(repo: RepoInfo, raw: RawPr, targets: ViewerTargets): Promise<BatchViewer>;