open-pstack 0.9.151 → 0.9.153

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.
@@ -0,0 +1,613 @@
1
+ // A Claude Code cloud session's GitHub proxy refuses GraphQL and serves REST.
2
+ // FallbackGitHubReader reads through GraphQL until the first refusal, then
3
+ // through CloudSessionReader for the rest of the process. The cloud reader
4
+ // turns each REST answer into the shape the other reader parses, the GraphQL
5
+ // response or gh pr checks' JSON, so one parser checks both. Where REST cannot
6
+ // say what GraphQL would, it answers the way that keeps the watcher from
7
+ // reporting ready.
8
+ import type { WatchDeadline } from "./deadline.ts";
9
+ import {
10
+ GhGitHubReader,
11
+ parseFastCheck,
12
+ parsePullRequest,
13
+ parseReviewThreadPage,
14
+ run,
15
+ runJson,
16
+ } from "./github.ts";
17
+ import {
18
+ GRAPHQL_REFUSAL,
19
+ isRecord,
20
+ missing,
21
+ WatcherQueryError,
22
+ } from "./query-error.ts";
23
+ import type * as T from "./types.ts";
24
+ import { parsePrNumber } from "./types.ts";
25
+
26
+ function record(value: unknown, path: string): Record<string, unknown> {
27
+ if (!isRecord(value)) missing(path, value);
28
+ return value;
29
+ }
30
+ function list(value: unknown, path: string): readonly unknown[] {
31
+ if (!Array.isArray(value)) missing(path, value);
32
+ return value;
33
+ }
34
+ function text(value: unknown, path: string): string {
35
+ if (typeof value !== "string") missing(path, value);
36
+ return value;
37
+ }
38
+
39
+ const refused = (error: unknown): boolean =>
40
+ error instanceof WatcherQueryError &&
41
+ error.failure.kind === "graphql-refused";
42
+
43
+ export class FallbackGitHubReader implements T.GitHubReader {
44
+ private cloudSession = false;
45
+ constructor(
46
+ private readonly graphql: T.GitHubReader,
47
+ private readonly cloud: T.GitHubReader
48
+ ) {}
49
+ private async read<R>(
50
+ call: (reader: T.GitHubReader) => Promise<R>
51
+ ): Promise<R> {
52
+ if (this.cloudSession) return call(this.cloud);
53
+ try {
54
+ return await call(this.graphql);
55
+ } catch (error) {
56
+ if (!refused(error)) throw error;
57
+ this.cloudSession = true;
58
+ return call(this.cloud);
59
+ }
60
+ }
61
+ originRepo() {
62
+ return this.read((reader) => reader.originRepo());
63
+ }
64
+ currentPr(pr: T.PrNumber | null) {
65
+ return this.read((reader) => reader.currentPr(pr));
66
+ }
67
+ pullRequest(context: T.PrContext) {
68
+ return this.read((reader) => reader.pullRequest(context));
69
+ }
70
+ openPullRequests(repository: T.Repository) {
71
+ return this.read((reader) => reader.openPullRequests(repository));
72
+ }
73
+ defaultBranch(repository: T.Repository) {
74
+ return this.read((reader) => reader.defaultBranch(repository));
75
+ }
76
+ // gh pr checks reports a refusal in its output instead of throwing.
77
+ checksFastPath(context: T.PrContext) {
78
+ return this.read(async (reader) => {
79
+ const fast = await reader.checksFastPath(context);
80
+ if (fast.kind === "unusable" && fast.stderr.includes(GRAPHQL_REFUSAL))
81
+ throw new WatcherQueryError({
82
+ kind: "graphql-refused",
83
+ retryable: false,
84
+ detail: GRAPHQL_REFUSAL,
85
+ });
86
+ return fast;
87
+ });
88
+ }
89
+ checkRollupPage(context: T.PrContext, after: string | null) {
90
+ return this.read((reader) => reader.checkRollupPage(context, after));
91
+ }
92
+ reviewThreadPage(context: T.PrContext, after: string | null) {
93
+ return this.read((reader) => reader.reviewThreadPage(context, after));
94
+ }
95
+ commitRollups(context: T.PrContext) {
96
+ return this.read((reader) => reader.commitRollups(context));
97
+ }
98
+ unsettledSuites(
99
+ context: T.PrContext,
100
+ head: string,
101
+ checksRead: T.CheckRead["kind"],
102
+ expectedApps: readonly string[]
103
+ ) {
104
+ return this.read((reader) =>
105
+ reader.unsettledSuites(context, head, checksRead, expectedApps)
106
+ );
107
+ }
108
+ }
109
+
110
+ // One check as `gh pr checks --json` reports it, which parseFastCheck reads.
111
+ interface FastCheck {
112
+ readonly name: string;
113
+ readonly state: string;
114
+ readonly bucket: string;
115
+ readonly link: string;
116
+ readonly workflow: string;
117
+ readonly description: string;
118
+ }
119
+ // gh's buckets by state; every state it does not name is pending.
120
+ const BUCKETS: Readonly<Record<string, string>> = {
121
+ SUCCESS: "pass",
122
+ SKIPPED: "skipping",
123
+ NEUTRAL: "skipping",
124
+ ERROR: "fail",
125
+ FAILURE: "fail",
126
+ TIMED_OUT: "fail",
127
+ ACTION_REQUIRED: "fail",
128
+ CANCELLED: "cancel",
129
+ };
130
+ const bucketOf = (state: string) => BUCKETS[state] ?? "pending";
131
+
132
+ // The checks gh pr checks lists for a commit. REST returns every check run,
133
+ // including runs a newer workflow run replaced; gh keeps the newest run for
134
+ // each name, workflow, and event, and the newest status for each context.
135
+ function fastChecks(
136
+ runs: readonly Record<string, unknown>[],
137
+ statuses: readonly Record<string, unknown>[],
138
+ workflowRuns: readonly Record<string, unknown>[]
139
+ ): readonly FastCheck[] {
140
+ const workflows = new Map(
141
+ workflowRuns.map((run) => [run.check_suite_id, run] as const)
142
+ );
143
+ // gh sorts by start time alone, so its pick on a tie, such as two jobs of one
144
+ // workflow run started in the same second, is arbitrary. Here a tie goes to a
145
+ // run still in flight, then to the run that finished last.
146
+ const unfinished = (run: Record<string, unknown>) =>
147
+ run.status === "completed" ? 0 : 1;
148
+ const newest = [...runs].sort(
149
+ (a, b) =>
150
+ String(b.started_at ?? "").localeCompare(String(a.started_at ?? "")) ||
151
+ unfinished(b) - unfinished(a) ||
152
+ String(b.completed_at ?? "").localeCompare(
153
+ String(a.completed_at ?? "")
154
+ ) ||
155
+ Number(b.id) - Number(a.id)
156
+ );
157
+ const seen = new Set<string>();
158
+ const checks: FastCheck[] = [];
159
+ for (const run of newest) {
160
+ const name = text(run.name, "check run.name");
161
+ const suite = record(run.check_suite, "check run.check_suite").id;
162
+ const workflow = workflows.get(suite);
163
+ // GitHub's rollup leaves out Copilot's code review agent
164
+ // (grafana/grafana#138617) but keeps other dynamic workflows, such as
165
+ // CodeQL default setup (github/docs#47025), so only the agents' path is left out.
166
+ if (String(workflow?.path ?? "").startsWith("dynamic/agents/")) continue;
167
+ const workflowName = workflow === undefined ? "" : String(workflow.name);
168
+ const event = workflow === undefined ? "" : String(workflow.event);
169
+ const key = `${name}/${workflowName}/${event}`;
170
+ if (seen.has(key)) continue;
171
+ seen.add(key);
172
+ const state = text(
173
+ run.status === "completed" ? run.conclusion : run.status,
174
+ "check run.conclusion"
175
+ ).toUpperCase();
176
+ checks.push({
177
+ name,
178
+ state,
179
+ bucket: bucketOf(state),
180
+ link: typeof run.details_url === "string" ? run.details_url : "",
181
+ workflow: workflowName,
182
+ description: "",
183
+ });
184
+ }
185
+ for (const status of statuses) {
186
+ const state = text(status.state, "status.state").toUpperCase();
187
+ checks.push({
188
+ name: text(status.context, "status.context"),
189
+ state,
190
+ bucket: bucketOf(state),
191
+ link: typeof status.target_url === "string" ? status.target_url : "",
192
+ workflow: "",
193
+ description:
194
+ typeof status.description === "string" ? status.description : "",
195
+ });
196
+ }
197
+ return checks;
198
+ }
199
+
200
+ // The rollup state GitHub's GraphQL reports for a commit. On grafana/grafana
201
+ // heads with cancelled runs among gh's checks, GitHub still reported SUCCESS,
202
+ // so a cancelled run does not fail the rollup; any other failure does.
203
+ function rollupState(checks: readonly FastCheck[]): T.RollupState {
204
+ if (checks.length === 0) return null;
205
+ if (checks.some((check) => check.state === "ERROR")) return "ERROR";
206
+ if (checks.some((check) => check.bucket === "fail")) return "FAILURE";
207
+ if (checks.some((check) => check.bucket === "pending")) return "PENDING";
208
+ return "SUCCESS";
209
+ }
210
+
211
+ // The latest review that counts, per reviewer. GraphQL's reviewDecision also
212
+ // weighs required reviewers and write access, which REST does not report; a
213
+ // required review that is missing still leaves mergeable_state blocked.
214
+ function reviewDecision(reviews: readonly unknown[]): T.ReviewDecision {
215
+ const latest = new Map<string, string>();
216
+ reviews.forEach((value, index) => {
217
+ const review = record(value, `reviews[${index}]`);
218
+ const state = text(review.state, `reviews[${index}].state`);
219
+ const user =
220
+ review.user === null
221
+ ? null
222
+ : record(review.user, `reviews[${index}].user`);
223
+ if (
224
+ user === null ||
225
+ !["APPROVED", "CHANGES_REQUESTED", "DISMISSED"].includes(state)
226
+ )
227
+ return;
228
+ latest.set(text(user.login, `reviews[${index}].user.login`), state);
229
+ });
230
+ const states = [...latest.values()];
231
+ if (states.includes("CHANGES_REQUESTED")) return "CHANGES_REQUESTED";
232
+ return states.includes("APPROVED") ? "APPROVED" : null;
233
+ }
234
+
235
+ // Every list read asks for this many rows per page.
236
+ const PAGE_SIZE = 100;
237
+
238
+ const MERGEABLE: ReadonlyMap<unknown, string> = new Map<unknown, string>([
239
+ [true, "MERGEABLE"],
240
+ [false, "CONFLICTING"],
241
+ [null, "UNKNOWN"],
242
+ ]);
243
+
244
+ export class CloudSessionReader implements T.GitHubReader {
245
+ // checksFastPath reads the head's checks and checkRollupPage, which
246
+ // resolveChecks calls next, takes that read instead of making it again.
247
+ private lastChecks: {
248
+ readonly pr: string;
249
+ readonly checks: readonly FastCheck[];
250
+ } | null = null;
251
+ constructor(
252
+ private readonly deadline: WatchDeadline,
253
+ private readonly local: GhGitHubReader
254
+ ) {}
255
+ private api(path: string): Promise<unknown> {
256
+ return runJson(["gh", "api", path], this.deadline);
257
+ }
258
+ private async pages(path: string): Promise<readonly unknown[]> {
259
+ return list(
260
+ await runJson(
261
+ ["gh", "api", "--paginate", "--slurp", path],
262
+ this.deadline
263
+ ),
264
+ path
265
+ );
266
+ }
267
+ // Every row of a list read, across its pages. These reads report no
268
+ // total_count, and the proxy's handling of next-page links is untested, so a
269
+ // full last page counts as a read that may have stopped early. A list of
270
+ // exactly 100, 200, or more rows fails the same way.
271
+ private async rows(path: string): Promise<readonly unknown[]> {
272
+ const pages = (await this.pages(path)).map((page, index) =>
273
+ list(page, `${path} page ${index}`)
274
+ );
275
+ if ((pages.at(-1)?.length ?? 0) >= PAGE_SIZE)
276
+ missing(
277
+ `${path} rows: the last page is full, so later pages may be missing`
278
+ );
279
+ return pages.flat();
280
+ }
281
+ // The rows under `key` across every page, checked against the total_count
282
+ // the first page reports, so a page the proxy did not serve is an error.
283
+ private async counted(
284
+ path: string,
285
+ key: string
286
+ ): Promise<readonly Record<string, unknown>[]> {
287
+ const pages = await this.pages(path);
288
+ if (pages.length === 0) missing(`${path} pages`);
289
+ const total = record(pages[0], `${path} page 0`).total_count;
290
+ const rows = pages.flatMap((page, index) =>
291
+ list(record(page, `${path} page ${index}`)[key], `${path}.${key}`)
292
+ );
293
+ if (rows.length !== total)
294
+ missing(`${path} rows (${rows.length} of total_count)`, total);
295
+ return rows.map((row, index) => record(row, `${path}.${key}[${index}]`));
296
+ }
297
+ private slug(context: T.PrContext | T.Repository): string {
298
+ return `repos/${context.owner}/${context.repo}`;
299
+ }
300
+ private prKey(context: T.PrContext): string {
301
+ return `${this.slug(context)}#${context.number}`;
302
+ }
303
+ private async headOf(context: T.PrContext): Promise<string> {
304
+ const pr = record(
305
+ await this.api(`${this.slug(context)}/pulls/${context.number}`),
306
+ "pull request"
307
+ );
308
+ return text(
309
+ record(pr.head, "pull request.head").sha,
310
+ "pull request.head.sha"
311
+ );
312
+ }
313
+ // The workflow runs name each Actions check run's workflow and event, which
314
+ // gh's de-duplication keys on; only Actions check runs need them.
315
+ private async checksAt(
316
+ context: T.PrContext,
317
+ head: string
318
+ ): Promise<readonly FastCheck[]> {
319
+ const [runs, statuses] = await Promise.all([
320
+ this.counted(
321
+ `${this.slug(context)}/commits/${head}/check-runs?per_page=100`,
322
+ "check_runs"
323
+ ),
324
+ this.counted(
325
+ `${this.slug(context)}/commits/${head}/status?per_page=100`,
326
+ "statuses"
327
+ ),
328
+ ]);
329
+ const actions = runs.some(
330
+ (run) => isRecord(run.app) && run.app.slug === "github-actions"
331
+ );
332
+ const workflowRuns = actions
333
+ ? await this.counted(
334
+ `${this.slug(context)}/actions/runs?head_sha=${head}&per_page=100`,
335
+ "workflow_runs"
336
+ )
337
+ : [];
338
+ return fastChecks(runs, statuses, workflowRuns);
339
+ }
340
+
341
+ originRepo(): Promise<T.Repository | null> {
342
+ return this.local.originRepo();
343
+ }
344
+ async currentPr(pr: T.PrNumber | null): Promise<T.PrContext> {
345
+ const origin = await this.local.originRepo();
346
+ if (origin === null)
347
+ throw new WatcherQueryError({
348
+ kind: "invalid-context-url",
349
+ retryable: false,
350
+ rawValue: "origin",
351
+ detail:
352
+ "the origin remote is not a github.com repository; pass --owner, --repo, and --pr",
353
+ });
354
+ if (pr !== null) return { ...origin, number: pr };
355
+ const shown = await run(["git", "branch", "--show-current"], this.deadline);
356
+ const branch = shown.code === 0 ? shown.stdout.trim() : "";
357
+ if (branch === "")
358
+ throw new WatcherQueryError({
359
+ kind: "invalid-context-url",
360
+ retryable: false,
361
+ rawValue: "HEAD",
362
+ detail: "the checkout is not on a branch; pass --pr",
363
+ });
364
+ const open = await this.rows(
365
+ `${this.slug(origin)}/pulls?head=${origin.owner}:${encodeURIComponent(branch)}&state=open&per_page=100`
366
+ );
367
+ if (open.length !== 1)
368
+ throw new WatcherQueryError({
369
+ kind: "invalid-context-url",
370
+ retryable: false,
371
+ rawValue: branch,
372
+ detail: `found ${open.length} open PRs for branch ${branch} in ${origin.owner}/${origin.repo}; pass --pr`,
373
+ });
374
+ return {
375
+ ...origin,
376
+ number: parsePrNumber(
377
+ record(open[0], "open PR").number,
378
+ "open PR.number"
379
+ ),
380
+ };
381
+ }
382
+ async pullRequest(context: T.PrContext): Promise<T.PullRequestFacts> {
383
+ const pr = record(
384
+ await this.api(`${this.slug(context)}/pulls/${context.number}`),
385
+ "pull request"
386
+ );
387
+ const head = record(pr.head, "pull request.head");
388
+ const base = record(pr.base, "pull request.base");
389
+ const baseRefName = text(base.ref, "pull request.base.ref");
390
+ const state =
391
+ pr.merged_at !== null ? "MERGED" : String(pr.state).toUpperCase();
392
+ const open = state === "OPEN";
393
+ const [reviews, baseTip] = open
394
+ ? await Promise.all([
395
+ this.rows(
396
+ `${this.slug(context)}/pulls/${context.number}/reviews?per_page=100`
397
+ ),
398
+ this.api(`${this.slug(context)}/git/ref/heads/${baseRefName}`),
399
+ ])
400
+ : [[], null];
401
+ return parsePullRequest(
402
+ {
403
+ mergeable: MERGEABLE.has(pr.mergeable)
404
+ ? MERGEABLE.get(pr.mergeable)
405
+ : pr.mergeable,
406
+ mergeStateStatus:
407
+ typeof pr.mergeable_state === "string"
408
+ ? pr.mergeable_state.toUpperCase()
409
+ : pr.mergeable_state,
410
+ reviewDecision: reviewDecision(reviews),
411
+ headRefOid: head.sha,
412
+ headRefName: head.ref,
413
+ baseRefName,
414
+ baseRef:
415
+ baseTip === null
416
+ ? null
417
+ : {
418
+ target: {
419
+ oid: record(
420
+ record(baseTip, "base ref").object,
421
+ "base ref.object"
422
+ ).sha,
423
+ },
424
+ },
425
+ state,
426
+ mergedAt: pr.merged_at,
427
+ isDraft: pr.draft,
428
+ },
429
+ context
430
+ );
431
+ }
432
+ async openPullRequests(
433
+ repository: T.Repository
434
+ ): Promise<readonly T.OpenPullRequest[]> {
435
+ const open = await this.rows(
436
+ `${this.slug(repository)}/pulls?state=open&per_page=100`
437
+ );
438
+ return open.map((value, index) => {
439
+ const pr = record(value, `open PRs[${index}]`);
440
+ const head = record(pr.head, `open PRs[${index}].head`);
441
+ const repo =
442
+ head.repo === null
443
+ ? null
444
+ : record(head.repo, `open PRs[${index}].head.repo`);
445
+ return {
446
+ number: parsePrNumber(pr.number, `open PRs[${index}].number`),
447
+ headRepository:
448
+ repo === null
449
+ ? null
450
+ : {
451
+ owner: text(
452
+ record(repo.owner, `open PRs[${index}].head.repo.owner`)
453
+ .login,
454
+ "head.repo.owner.login"
455
+ ),
456
+ repo: text(repo.name, `open PRs[${index}].head.repo.name`),
457
+ },
458
+ headRefName: text(head.ref, `open PRs[${index}].head.ref`),
459
+ baseRefName: text(
460
+ record(pr.base, `open PRs[${index}].base`).ref,
461
+ `open PRs[${index}].base.ref`
462
+ ),
463
+ };
464
+ });
465
+ }
466
+ async defaultBranch(repository: T.Repository): Promise<string> {
467
+ return text(
468
+ record(await this.api(this.slug(repository)), "repository")
469
+ .default_branch,
470
+ "repository.default_branch"
471
+ );
472
+ }
473
+ async checksFastPath(context: T.PrContext): Promise<T.ChecksFastPath> {
474
+ const checks = await this.checksAt(context, await this.headOf(context));
475
+ this.lastChecks = { pr: this.prKey(context), checks };
476
+ // No checks sends resolveChecks to the rollup page, which must agree
477
+ // before the watcher calls the head unchecked.
478
+ return checks.length === 0
479
+ ? { kind: "none-reported" }
480
+ : { kind: "checks", checks: checks.map(parseFastCheck) };
481
+ }
482
+ async checkRollupPage(
483
+ context: T.PrContext,
484
+ after: string | null
485
+ ): Promise<T.RollupPage> {
486
+ if (after !== null) missing("REST check rollup cursor", after);
487
+ const checks =
488
+ this.lastChecks?.pr === this.prKey(context)
489
+ ? this.lastChecks.checks
490
+ : await this.checksAt(context, await this.headOf(context));
491
+ this.lastChecks = null;
492
+ return checks.length === 0
493
+ ? { kind: "no-rollup" }
494
+ : {
495
+ kind: "contexts",
496
+ checks: checks.map(parseFastCheck),
497
+ endCursor: null,
498
+ };
499
+ }
500
+ async reviewThreadPage(
501
+ context: T.PrContext,
502
+ after: string | null
503
+ ): Promise<T.ReviewThreadPage> {
504
+ if (after !== null) missing("REST review thread cursor", after);
505
+ const prPath = `${this.slug(context)}/pulls/${context.number}`;
506
+ const [threads, comments] = await Promise.all([
507
+ this.api(`${prPath}/ccr/review_threads`),
508
+ this.rows(`${prPath}/comments?per_page=100`),
509
+ ]);
510
+ const byId = new Map(
511
+ comments.map((value, index) => {
512
+ const comment = record(value, `review comments[${index}]`);
513
+ return [comment.id, comment] as const;
514
+ })
515
+ );
516
+ // Every review comment that starts a thread must belong to a thread the
517
+ // route returned, so a thread the route left out cannot read as resolved.
518
+ const threaded = new Set(
519
+ list(threads, "ccr/review_threads").flatMap((value, index) =>
520
+ list(
521
+ record(value, `ccr/review_threads[${index}]`).comment_ids,
522
+ `ccr/review_threads[${index}].comment_ids`
523
+ )
524
+ )
525
+ );
526
+ for (const [id, comment] of byId)
527
+ if (comment.in_reply_to_id == null && !threaded.has(id))
528
+ missing(`review comment ${String(id)} in a ccr/review_threads thread`);
529
+ const nodes = list(threads, "ccr/review_threads").map((value, index) => {
530
+ const thread = record(value, `ccr/review_threads[${index}]`);
531
+ const ids = list(
532
+ thread.comment_ids,
533
+ `ccr/review_threads[${index}].comment_ids`
534
+ );
535
+ const first = ids.length === 0 ? undefined : byId.get(ids[0]);
536
+ return {
537
+ // The route gives a thread no id of its own.
538
+ id: `comment-${String(ids[0])}`,
539
+ isResolved: thread.resolved,
540
+ comments: {
541
+ nodes:
542
+ first === undefined
543
+ ? []
544
+ : [
545
+ {
546
+ body: first.body,
547
+ createdAt: first.created_at,
548
+ path: first.path,
549
+ line: first.line,
550
+ author:
551
+ first.user === null
552
+ ? null
553
+ : {
554
+ login: record(first.user, "review comment.user")
555
+ .login,
556
+ },
557
+ },
558
+ ],
559
+ },
560
+ };
561
+ });
562
+ return parseReviewThreadPage({
563
+ data: {
564
+ repository: {
565
+ pullRequest: {
566
+ reviewThreads: {
567
+ nodes,
568
+ pageInfo: { hasNextPage: false, endCursor: null },
569
+ },
570
+ },
571
+ },
572
+ },
573
+ });
574
+ }
575
+ // The head's rollup, and an earlier commit's only when the head reports
576
+ // nothing: that is the one case where an earlier report changes the verdict,
577
+ // by keeping a head with no checks from reading as a PR without CI. So
578
+ // hadPreviousPassingCi, which only labels a failing head, stays false here.
579
+ async commitRollups(
580
+ context: T.PrContext
581
+ ): Promise<readonly T.CommitRollup[]> {
582
+ const head = await this.headOf(context);
583
+ const state = rollupState(await this.checksAt(context, head));
584
+ if (state !== null) return [{ oid: head, state }];
585
+ const commits = await this.rows(
586
+ `${this.slug(context)}/pulls/${context.number}/commits?per_page=100`
587
+ );
588
+ const earlier = commits
589
+ .map((value, index) =>
590
+ text(record(value, `commits[${index}]`).sha, `commits[${index}].sha`)
591
+ )
592
+ .filter((sha) => sha !== head)
593
+ .slice(-49)
594
+ .reverse();
595
+ for (const sha of earlier) {
596
+ const earlierState = rollupState(await this.checksAt(context, sha));
597
+ if (earlierState !== null)
598
+ return [
599
+ { oid: head, state: null },
600
+ { oid: sha, state: earlierState },
601
+ ];
602
+ }
603
+ return [{ oid: head, state: null }];
604
+ }
605
+ unsettledSuites(
606
+ context: T.PrContext,
607
+ head: string,
608
+ checksRead: T.CheckRead["kind"],
609
+ expectedApps: readonly string[]
610
+ ) {
611
+ return this.local.unsettledSuites(context, head, checksRead, expectedApps);
612
+ }
613
+ }
@@ -10,7 +10,7 @@ import {
10
10
  } from "./workflow-runs.ts";
11
11
  import { spawn } from "node:child_process";
12
12
  import { DeadlineExceeded, type WatchDeadline } from "./deadline.ts";
13
- import { WatcherQueryError } from "./query-error.ts";
13
+ import { GRAPHQL_REFUSAL, WatcherQueryError } from "./query-error.ts";
14
14
  import type * as T from "./types.ts";
15
15
  import { nonEmpty, parsePrNumber } from "./types.ts";
16
16
  export const REVIEW_THREADS_QUERY =
@@ -50,7 +50,7 @@ export class ChecksUnavailable extends WatcherQueryError {
50
50
  }
51
51
  const firstLine = (value: string): string =>
52
52
  value.trim().split(/\r?\n/, 1)[0]?.slice(0, 240) ?? "";
53
- function run(
53
+ export function run(
54
54
  argv: readonly [string, ...string[]],
55
55
  deadline: WatchDeadline
56
56
  ): Promise<CommandResult> {
@@ -120,16 +120,15 @@ export async function runJson(
120
120
  return commandJson(await run(argv, deadline), argv.join(" "));
121
121
  }
122
122
  function commandJson(result: CommandResult, label: string): unknown {
123
- if (
124
- result.code !== 0 &&
125
- firstLine(result.stderr).includes(
126
- "GitHub GraphQL is not available from Claude Code sessions"
127
- )
128
- )
123
+ // Newer gh prints a hint block on stderr before its error, so check every line.
124
+ const refusal = result.stderr
125
+ .split(/\r?\n/)
126
+ .find((line) => line.includes(GRAPHQL_REFUSAL));
127
+ if (result.code !== 0 && refusal !== undefined)
129
128
  throw new WatcherQueryError({
130
129
  kind: "graphql-refused",
131
130
  retryable: false,
132
- detail: `This Claude Code session refuses GitHub GraphQL, which watch-pr and ship-pr read the PR through. ${firstLine(result.stderr)}`,
131
+ detail: `This Claude Code session refuses GitHub GraphQL, which watch-pr and ship-pr read the PR through. ${refusal.trim().slice(0, 240)}`,
133
132
  });
134
133
  if (result.code !== 0)
135
134
  throw new WatcherQueryError({
@@ -2,6 +2,10 @@ import type { QueryFailure } from "./types.ts";
2
2
 
3
3
  // Port-owned modules import the query error from here rather than from
4
4
  // github.ts, which imports them; github.ts re-exports it for its callers.
5
+ // The line gh prints when a Claude Code cloud session's GitHub proxy refuses GraphQL.
6
+ export const GRAPHQL_REFUSAL =
7
+ "GitHub GraphQL is not available from Claude Code sessions";
8
+
5
9
  export class WatcherQueryError extends Error {
6
10
  readonly failure: QueryFailure;
7
11
  constructor(failure: QueryFailure) {