@deepseek-ai/dsh-experimental-forge-github 0.2.2-alpha.3 → 0.2.2-rc.2

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 (59) hide show
  1. package/README.i18n.yaml +6 -6
  2. package/README.md +27 -6
  3. package/README.zh.md +27 -6
  4. package/lib/index.js +1860 -112
  5. package/lib/types/commits.d.ts +24 -0
  6. package/lib/types/commits.d.ts.map +1 -0
  7. package/lib/types/commits.js.map +1 -0
  8. package/lib/types/compare.d.ts +23 -0
  9. package/lib/types/compare.d.ts.map +1 -0
  10. package/lib/types/compare.js.map +1 -0
  11. package/lib/types/gh.d.ts.map +1 -0
  12. package/lib/types/gh.js.map +1 -0
  13. package/lib/types/graphql.d.ts +66 -10
  14. package/lib/types/graphql.d.ts.map +1 -0
  15. package/lib/types/graphql.js.map +1 -0
  16. package/lib/types/index.d.ts +10 -1
  17. package/lib/types/index.d.ts.map +1 -0
  18. package/lib/types/index.js.map +1 -0
  19. package/lib/types/mutation.d.ts +40 -0
  20. package/lib/types/mutation.d.ts.map +1 -0
  21. package/lib/types/mutation.js.map +1 -0
  22. package/lib/types/overview.d.ts +51 -0
  23. package/lib/types/overview.d.ts.map +1 -0
  24. package/lib/types/overview.js.map +1 -0
  25. package/lib/types/provider.d.ts +71 -6
  26. package/lib/types/provider.d.ts.map +1 -0
  27. package/lib/types/provider.js.map +1 -0
  28. package/lib/types/pull-request-node.d.ts +15 -0
  29. package/lib/types/pull-request-node.d.ts.map +1 -0
  30. package/lib/types/pull-request-node.js.map +1 -0
  31. package/lib/types/review-writes.d.ts +44 -0
  32. package/lib/types/review-writes.d.ts.map +1 -0
  33. package/lib/types/review-writes.js.map +1 -0
  34. package/lib/types/review.d.ts.map +1 -0
  35. package/lib/types/review.js.map +1 -0
  36. package/lib/types/threads.d.ts +37 -0
  37. package/lib/types/threads.d.ts.map +1 -0
  38. package/lib/types/threads.js.map +1 -0
  39. package/lib/types/urls.d.ts +6 -0
  40. package/lib/types/urls.d.ts.map +1 -0
  41. package/lib/types/urls.js.map +1 -0
  42. package/lib/types/viewed.d.ts +37 -0
  43. package/lib/types/viewed.d.ts.map +1 -0
  44. package/lib/types/viewed.js.map +1 -0
  45. package/package.json +16 -12
  46. package/src/commits.ts +102 -0
  47. package/src/compare.ts +43 -0
  48. package/src/gh.ts +71 -0
  49. package/src/graphql.ts +685 -0
  50. package/src/index.ts +60 -0
  51. package/src/mutation.ts +86 -0
  52. package/src/overview.ts +197 -0
  53. package/src/provider.ts +534 -0
  54. package/src/pull-request-node.ts +42 -0
  55. package/src/review-writes.ts +192 -0
  56. package/src/review.ts +59 -0
  57. package/src/threads.ts +262 -0
  58. package/src/urls.ts +89 -0
  59. package/src/viewed.ts +132 -0
@@ -0,0 +1,534 @@
1
+ /** GitHub implementation of the forge provider contract. */
2
+
3
+ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
4
+ import type {
5
+ BranchUpdateRequest, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure,
6
+ ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewersRequest,
7
+ ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeRequest,
8
+ } from '@deepseek-ai/dsh-experimental-forge'
9
+ import { listCommits } from './commits.ts'
10
+ import type { GraphqlReader } from './commits.ts'
11
+ import { sendMutation, type GraphqlWriter } from './mutation.ts'
12
+ import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts'
13
+ import type { GhOutput, GhRunner } from './gh.ts'
14
+ import { readComparison } from './compare.ts'
15
+ import {
16
+ actionsRunOf, CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse,
17
+ mapSnapshotResponse, mapThreadPageResponse, PULL_REQUEST_COMMITS_QUERY, snapshotQuery, THREADS_QUERY,
18
+ } from './graphql.ts'
19
+ import type { PageResult, SnapshotPages } from './graphql.ts'
20
+ import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts'
21
+ import { submitGitHubReview } from './review.ts'
22
+ import { readViewed, writeViewed } from './viewed.ts'
23
+ import { gitHubReviewerCandidates, requestGitHubReviews, updateGitHubBranch } from './overview.ts'
24
+ import { writeGitHubReview } from './review-writes.ts'
25
+ import { readReviewThreads } from './threads.ts'
26
+
27
+ const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i
28
+
29
+ /** Status code `gh api` appends to the message of a failed request. */
30
+ const HTTP_STATUS = /\(HTTP (\d{3})\)/
31
+
32
+ /**
33
+ * GitHub's error code for an answer over its size limits, such as a file over
34
+ * the contents API limit: `gh api` returns it in the JSON error body.
35
+ */
36
+ const TOO_LARGE = /\btoo_large\b/
37
+
38
+ /** HTTP status GitHub answers when it refuses to render a diff over its limits. */
39
+ const NOT_ACCEPTABLE = '406'
40
+
41
+ /** Bounds on what one read retains or counts. */
42
+ export interface GitHubLimits {
43
+ /** Maximum combined JSON bytes retained by an explicit check read or a review read. */
44
+ readonly maxOutputBytes: number
45
+ /** Most review threads counted per pull request in one status read, and read in one review read. */
46
+ readonly maxReviewThreads: number
47
+ /** Most commits one commit listing returns. */
48
+ readonly maxCommits: number
49
+ /** Most files whose viewed marks one read lists. */
50
+ readonly maxViewedFiles: number
51
+ }
52
+
53
+ /** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */
54
+ export class GitHubProvider implements ForgeProvider {
55
+ readonly forge = 'github'
56
+ private readonly hosts: ReadonlySet<string>
57
+
58
+ async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
59
+ const failure = this.hostFailure(ref.repository.host)
60
+ if (failure !== undefined) return { ok: false, code: 'failed', message: failure.message }
61
+ return await submitGitHubReview(this.gh, ref, request, signal)
62
+ }
63
+
64
+ /**
65
+ * Read the review threads of a pull request at `headSha` through GraphQL, each page naming the head it was read at.
66
+ * @see readReviewThreads
67
+ */
68
+ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure> {
69
+ const failure = this.hostFailure(ref.repository.host)
70
+ if (failure !== undefined) return failure
71
+ if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`)
72
+ return await readReviewThreads(this.graphql, ref, headSha, this.limits, signal)
73
+ }
74
+
75
+ /**
76
+ * Write to the review threads or the pending review of a pull request through GraphQL mutations after a check of its head.
77
+ * @see writeGitHubReview
78
+ */
79
+ async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult> {
80
+ const failure = this.hostFailure(ref.repository.host)
81
+ if (failure !== undefined) return { ok: false, code: 'failed', message: failure.message }
82
+ if (!isCommit(write.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(write.headSha)}`)
83
+ return await writeGitHubReview(this.graphql, this.gh, ref, write, signal)
84
+ }
85
+
86
+ /**
87
+ * @param gh - runner that executes `gh` on the host.
88
+ * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts.
89
+ * @param limits - bounds on retained check and review bytes, counted and read review threads, listed commits, and listed
90
+ * viewed files.
91
+ */
92
+ constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) {
93
+ this.hosts = new Set(hosts.map(host => host.toLowerCase()))
94
+ }
95
+
96
+ repositoryFromRemote(url: string): ForgeRepository | undefined {
97
+ const location = parseRemoteUrl(url)
98
+ if (location === undefined || !this.hosts.has(location.host)) return undefined
99
+ return { forge: this.forge, ...location }
100
+ }
101
+
102
+ changeRequestFromUrl(url: string): ChangeRequestRef | undefined {
103
+ const parsed = parsePullRequestUrl(url)
104
+ if (parsed === undefined || !this.hosts.has(parsed.host)) return undefined
105
+ return { repository: { forge: this.forge, host: parsed.host, owner: parsed.owner, name: parsed.name }, number: parsed.number }
106
+ }
107
+
108
+ changeRequestUrl(ref: ChangeRequestRef): string {
109
+ const { host, owner, name } = ref.repository
110
+ return `https://${host}/${owner}/${name}/pull/${ref.number}`
111
+ }
112
+
113
+ async fetch(
114
+ refs: readonly ChangeRequestRef[],
115
+ signal: AbortSignal,
116
+ ): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
117
+ const byHost = new Map<string, ChangeRequestRef[]>()
118
+ const results = new Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>()
119
+ for (const ref of refs) {
120
+ const failure = this.hostFailure(ref.repository.host)
121
+ if (failure !== undefined) {
122
+ results.set(changeRequestKey(ref), failure)
123
+ continue
124
+ }
125
+ const group = byHost.get(ref.repository.host)
126
+ if (group === undefined) byHost.set(ref.repository.host, [ref])
127
+ else group.push(ref)
128
+ }
129
+ for (const [host, group] of byHost) {
130
+ for (const [key, result] of await this.fetchHost(host, group, signal)) results.set(key, result)
131
+ }
132
+ return results
133
+ }
134
+
135
+ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure> {
136
+ const failure = this.hostFailure(ref.repository.host)
137
+ if (failure !== undefined) return failure
138
+ try {
139
+ const results = await this.fetchHost(ref.repository.host, [ref], signal, true)
140
+ // oxlint-disable-next-line typescript/no-non-null-assertion -- fetchHost returns one result for each requested ref.
141
+ return results.get(changeRequestKey(ref))!
142
+ } catch (error) {
143
+ if (signal.aborted) throw signal.reason
144
+ return processFailure(error)
145
+ }
146
+ }
147
+
148
+ async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<readonly ChangeRequestRef[]> {
149
+ const failure = this.hostFailure(repository.host)
150
+ if (failure !== undefined) throw new Error(failure.message)
151
+ const output = await this.gh([
152
+ 'api', 'graphql', '--hostname', repository.host,
153
+ '-f', `query=${HEAD_QUERY}`, '-f', `owner=${repository.owner}`, '-f', `name=${repository.name}`, '-f', `branch=${branch}`,
154
+ ], signal)
155
+ const body = parseJson(output.stdout)
156
+ if (!hasGraphqlFields(body)) throw new Error(`forge-github: head branch lookup failed: ${responseFailure(output, body).message}`)
157
+ return mapHeadResponse(body, repository, branch)
158
+ }
159
+
160
+ /**
161
+ * Mark a draft pull request ready for review with `gh pr ready`; one that
162
+ * is already ready stays ready.
163
+ */
164
+ async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
165
+ const { host, owner, name } = checkedRepository(ref)
166
+ const failure = this.hostFailure(host)
167
+ if (failure !== undefined) return { code: 'failed', message: failure.message }
168
+ return await this.act(['pr', 'ready', String(ref.number), '--repo', `${host}/${owner}/${name}`], signal)
169
+ }
170
+
171
+ /**
172
+ * Merge a pull request through the REST merge endpoint with the expected
173
+ * head commit, so GitHub refuses with 409 once new commits arrived. Unlike
174
+ * `gh pr merge`, it never enables auto-merge, never joins a merge queue, and
175
+ * never deletes the head branch.
176
+ */
177
+ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
178
+ const { host, owner, name } = checkedRepository(ref)
179
+ const failure = this.hostFailure(host)
180
+ if (failure !== undefined) return { code: 'failed', message: failure.message }
181
+ if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`)
182
+ return await this.act([
183
+ 'api', '--hostname', host, '--method', 'PUT', `repos/${owner}/${name}/pulls/${ref.number}/merge`,
184
+ '-f', `merge_method=${request.method}`, '-f', `sha=${request.headSha}`,
185
+ ], signal)
186
+ }
187
+
188
+ /**
189
+ * Read the pull request's diff at `headSha`. One GraphQL read names the
190
+ * current head and the base commit GitHub recorded with it; a head other
191
+ * than `headSha` returns `stale`. Otherwise the compare endpoint reads the
192
+ * patch from the merge base of that base commit and `headSha`, as the pull
193
+ * request's own diff does, with both ends fixed. Given the `base` the latest
194
+ * status recorded with `headSha`, the comparison from it runs while the
195
+ * GraphQL read confirms the head; a stale head or another base commit
196
+ * cancels that comparison and waits for it to end before the read returns.
197
+ */
198
+ async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal, base?: string): Promise<string | ForgeFailure> {
199
+ const { host, owner, name } = checkedRepository(ref)
200
+ const failure = this.hostFailure(host)
201
+ if (failure !== undefined) return failure
202
+ if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`)
203
+ if (base !== undefined && !isCommit(base)) throw new Error(`forge-github: invalid base commit ${JSON.stringify(base)}`)
204
+ const compare = async (from: string, operation: AbortSignal): Promise<string | ForgeFailure> =>
205
+ await readComparison(async (args, inner) => await this.read(args, inner), ref.repository, from, headSha, operation)
206
+ const speculation = new AbortController()
207
+ const early = base === undefined ? undefined : { base, patch: compare(base, AbortSignal.any([signal, speculation.signal])) }
208
+ // The early comparison is observed here, so a cancelled or unused one never rejects unhandled.
209
+ const settled = early?.patch.then(() => undefined, () => undefined)
210
+ const discard = async (): Promise<void> => {
211
+ speculation.abort()
212
+ await settled
213
+ }
214
+ try {
215
+ const output = await this.read([
216
+ 'api', 'graphql', '--hostname', host,
217
+ '-f', `query=${PULL_REQUEST_COMMITS_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, '-F', `number=${ref.number}`,
218
+ ], signal)
219
+ if (typeof output !== 'string') return output
220
+ const commits = mapPullRequestCommitsResponse(parseJson(output))
221
+ if (commits === undefined) return { code: 'unavailable', message: 'unexpected GitHub response to the pull request commit read' }
222
+ if (commits.head.toLowerCase() !== headSha.toLowerCase()) {
223
+ return { code: 'stale', message: `the pull request head moved from ${headSha} to ${commits.head}` }
224
+ }
225
+ if (early?.base.toLowerCase() === commits.base.toLowerCase()) return await early.patch
226
+ await discard()
227
+ return await compare(commits.base, signal)
228
+ } finally {
229
+ await discard()
230
+ }
231
+ }
232
+
233
+ /** Read one file at a commit through the contents API in its raw form. */
234
+ async fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise<string | ForgeFailure> {
235
+ const { host, owner, name } = checkedRepository(ref)
236
+ const failure = this.hostFailure(host)
237
+ if (failure !== undefined) return failure
238
+ if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`)
239
+ return await this.read([
240
+ 'api', '--hostname', host, '-H', 'Accept: application/vnd.github.raw+json',
241
+ `repos/${owner}/${name}/contents/${encodedPath(path)}?ref=${commit}`,
242
+ ], signal)
243
+ }
244
+
245
+ /** List the pull request's commits through GraphQL, at most `maxCommits`, all read at one head. */
246
+ async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitList | ForgeFailure> {
247
+ const { host } = checkedRepository(ref)
248
+ const failure = this.hostFailure(host)
249
+ if (failure !== undefined) return failure
250
+ return await listCommits(this.graphql, ref, this.limits.maxCommits, signal)
251
+ }
252
+
253
+ /** Read the changes between two commits through the compare API in its diff form. */
254
+ async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure> {
255
+ const failure = this.hostFailure(checkedRepository(ref).host)
256
+ if (failure !== undefined) return failure
257
+ return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, base, head, signal)
258
+ }
259
+
260
+ /** Read the viewer's viewed marks through GraphQL, at most `maxViewedFiles`, every page at `headSha`. */
261
+ async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | ForgeFailure> {
262
+ const failure = this.hostFailure(checkedRepository(ref).host)
263
+ if (failure !== undefined) return failure
264
+ return await readViewed(this.graphql, ref, headSha, this.limits.maxViewedFiles, signal)
265
+ }
266
+
267
+ /** Set or clear the viewer's mark with `markFileAsViewed` or `unmarkFileAsViewed` after confirming the head. */
268
+ async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
269
+ const failure = this.hostFailure(checkedRepository(ref).host)
270
+ if (failure !== undefined) return { code: 'failed', message: failure.message }
271
+ return await writeViewed(this.graphql, this.mutate, ref, request, signal)
272
+ }
273
+
274
+ /**
275
+ * Rerun every finished workflow run with a failed GitHub Actions job on the head commit through the REST API; GitHub
276
+ * reruns its failed jobs with the jobs that depend on them. A run with a check still pending waits, as GitHub offers
277
+ * no rerun of a run in progress. Every eligible run is tried, and a refusal of one is reported with the others' outcome.
278
+ * Other checks name no rerun.
279
+ */
280
+ async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
281
+ const { host, owner, name } = checkedRepository(ref)
282
+ const failure = this.hostFailure(host)
283
+ if (failure !== undefined) return { code: 'failed', message: failure.message }
284
+ if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`)
285
+ const snapshot = await this.fetchChecks(ref, signal)
286
+ if ('code' in snapshot) return { code: snapshot.code === 'unauthenticated' ? 'unauthenticated' : 'failed', message: snapshot.message }
287
+ if (snapshot.headSha.toLowerCase() !== request.headSha.toLowerCase()) {
288
+ return { code: 'stale', message: `the pull request head moved from ${request.headSha} to ${snapshot.headSha}` }
289
+ }
290
+ const endpoint = `repos/${owner}/${name}/actions`
291
+ const failed = new Set<number>()
292
+ const running = new Set<number>()
293
+ for (const check of snapshot.checks) {
294
+ const run = check.rerun === null ? undefined : actionsRunOf(check.rerun)
295
+ if (run === undefined) continue
296
+ if (check.state === 'failure') failed.add(run)
297
+ else if (check.state === 'pending') running.add(run)
298
+ }
299
+ const runs = [...failed].filter(run => !running.has(run))
300
+ if (runs.length === 0) {
301
+ return { code: 'failed', message: failed.size === 0 ? 'No failed GitHub Actions job of the head commit can be rerun'
302
+ : 'Every workflow run with a failed job is still running; rerun it once it finishes' }
303
+ }
304
+ const refusals: string[] = []
305
+ for (const run of runs) {
306
+ const refused = await this.act(['api', '--hostname', host, '--method', 'POST', `${endpoint}/runs/${run}/rerun-failed-jobs`], signal)
307
+ if (refused === undefined) continue
308
+ if (refused.code === 'unauthenticated') return refused
309
+ // The head was checked before the first request, so a conflict here names no new commit.
310
+ refusals.push(`run ${run}: ${refused.message}`)
311
+ }
312
+ return refusals.length === 0 ? undefined
313
+ : { code: 'failed', message: `GitHub refused to rerun ${refusals.length} of ${runs.length} workflow runs: ${refusals.join('; ')}` }
314
+ }
315
+
316
+ async requestReviews(
317
+ ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal,
318
+ ): Promise<ForgeActionFailure | undefined> {
319
+ const failure = this.hostFailure(checkedRepository(ref).host)
320
+ if (failure !== undefined) return { code: 'failed', message: failure.message }
321
+ return await requestGitHubReviews(this.graphql, this.mutate, ref, request, signal)
322
+ }
323
+
324
+ async reviewerCandidates(
325
+ ref: ChangeRequestRef, query: string, signal: AbortSignal,
326
+ ): Promise<readonly ForgeReviewerCandidate[] | ForgeFailure> {
327
+ const failure = this.hostFailure(checkedRepository(ref).host)
328
+ if (failure !== undefined) return failure
329
+ return await gitHubReviewerCandidates(this.graphql, ref, query, signal)
330
+ }
331
+
332
+ async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
333
+ const failure = this.hostFailure(checkedRepository(ref).host)
334
+ if (failure !== undefined) return { code: 'failed', message: failure.message }
335
+ return await updateGitHubBranch(this.graphql, this.mutate, ref, request, signal)
336
+ }
337
+
338
+ fileUrl(ref: ChangeRequestRef, commit: string, path: string): string {
339
+ const { host, owner, name } = ref.repository
340
+ return `https://${host}/${owner}/${name}/blob/${commit}/${encodedPath(path)}`
341
+ }
342
+
343
+ async readiness(host: string, signal: AbortSignal): Promise<ForgeReadiness> {
344
+ const failure = this.hostFailure(host)
345
+ if (failure !== undefined) return { state: 'unavailable', message: failure.message }
346
+ try {
347
+ const output = await this.gh(['auth', 'status', '--hostname', host], signal)
348
+ if (output.exitCode === 0) return { state: 'ready', message: null }
349
+ return { state: 'unauthenticated', message: firstLine(output.stderr) ?? firstLine(output.stdout) ?? `gh is not signed in to ${host}` }
350
+ } catch (error) {
351
+ if (error instanceof GhUnavailableError) return { state: 'unavailable', message: error.message }
352
+ throw error
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Run one reading `gh` command, returning its output. A refusal, a `gh` that
358
+ * cannot start, output over `maxOutputBytes`, and a run past `timeoutMs` become failures.
359
+ */
360
+ private async read(args: readonly string[], signal: AbortSignal): Promise<string | ForgeFailure> {
361
+ let output: GhOutput | GhUnavailableError
362
+ try {
363
+ output = await this.attempt(args, signal)
364
+ } catch (error) {
365
+ if (error instanceof GhOutputLimitError) return { code: 'too-large', message: error.message }
366
+ if (error instanceof GhTimeoutError) return { code: 'unavailable', message: error.message }
367
+ throw error
368
+ }
369
+ if (output instanceof GhUnavailableError) return { code: 'unavailable', message: output.message }
370
+ if (output.exitCode === 0) return output.stdout
371
+ const { message, status } = refusal(output)
372
+ if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message }
373
+ if (status === NOT_ACCEPTABLE || TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message }
374
+ return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message }
375
+ }
376
+
377
+ /** Run one GraphQL request; a refusal, a body that is not GraphQL, and GraphQL errors become failures. */
378
+ private readonly graphql: GraphqlReader = async (args, signal) => {
379
+ const output = await this.read(args, signal)
380
+ if (typeof output !== 'string') return { ok: false, failure: output }
381
+ const body = parseJson(output)
382
+ if (!hasGraphqlFields(body)) return { ok: false, failure: { code: 'unavailable', message: 'unexpected GitHub response' } }
383
+ const errors = typeof body === 'object' && body !== null && 'errors' in body && Array.isArray(body.errors) ? body.errors : []
384
+ if (errors.length > 0) return { ok: false, failure: responseFailure({ exitCode: 0, stdout: output, stderr: '' }, errors[0]) }
385
+ return { ok: true, body }
386
+ }
387
+
388
+ /**
389
+ * Run one GraphQL mutation through {@link sendMutation}, which never retries it: a refusal or a `gh` that cannot
390
+ * start is `failed`, and an answer that does not confirm the outcome is `unknown`.
391
+ */
392
+ private readonly mutate: GraphqlWriter = async (host, mutation, signal) => {
393
+ const sent = await sendMutation(this.gh, host, mutation, signal)
394
+ return sent.ok ? undefined : { code: sent.code, message: sent.message }
395
+ }
396
+
397
+ /** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */
398
+ private async act(args: readonly string[], signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
399
+ const output = await this.attempt(args, signal)
400
+ if (output instanceof GhUnavailableError) return { code: 'failed', message: output.message }
401
+ if (output.exitCode === 0) return undefined
402
+ const { message, status } = refusal(output)
403
+ if (status === '409') return { code: 'stale', message }
404
+ if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message }
405
+ return { code: 'failed', message }
406
+ }
407
+
408
+ /** Run one `gh` command; a `gh` that cannot start resolves to its error, and every other rejection passes on. */
409
+ private async attempt(args: readonly string[], signal: AbortSignal): Promise<GhOutput | GhUnavailableError> {
410
+ try {
411
+ return await this.gh(args, signal)
412
+ } catch (error) {
413
+ if (error instanceof GhUnavailableError) return error
414
+ throw error
415
+ }
416
+ }
417
+
418
+ private hostFailure(host: string): ForgeFailure | undefined {
419
+ return this.hosts.has(host.toLowerCase()) ? undefined : {
420
+ code: 'unavailable', message: `forge-github: host ${JSON.stringify(host)} is not configured`,
421
+ }
422
+ }
423
+
424
+ private async fetchHost(
425
+ host: string,
426
+ refs: readonly ChangeRequestRef[],
427
+ signal: AbortSignal,
428
+ completeChecks = false,
429
+ ): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
430
+ const query = snapshotQuery(refs, this.limits.maxReviewThreads)
431
+ const output = await this.gh(['api', 'graphql', '--hostname', host, '-f', `query=${query.document}`], signal)
432
+ const body = parseJson(output.stdout)
433
+ // A complete check read retains every response it reads, so all of them share one byte budget.
434
+ let bytes = Buffer.byteLength(output.stdout)
435
+ const tooLarge: ForgeFailure = { code: 'too-large', message: 'GitHub check details exceed the output size limit' }
436
+ const overBudget = (page: GhOutput): boolean => {
437
+ if (!completeChecks) return false
438
+ bytes += Buffer.byteLength(page.stdout)
439
+ return bytes > this.limits.maxOutputBytes
440
+ }
441
+ const continuation = async <T>(
442
+ variables: readonly string[], map: (value: unknown) => PageResult<T>,
443
+ ): Promise<PageResult<T>> => {
444
+ const page = await this.continuation(host, variables, signal)
445
+ if (!('stdout' in page)) return { ok: false, failure: page }
446
+ if (overBudget(page)) return { ok: false, failure: tooLarge }
447
+ const value = parseJson(page.stdout)
448
+ return hasGraphqlFields(value) ? map(value) : { ok: false, failure: responseFailure(page, value) }
449
+ }
450
+ const threads: SnapshotPages['threads'] = async (id, cursor, first) => await continuation(
451
+ ['-f', `query=${THREADS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`, '-F', `first=${first}`], mapThreadPageResponse)
452
+ if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads })
453
+ if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge]))
454
+ if (hasGraphqlFields(body)) {
455
+ return await mapSnapshotResponse(body, query, { threads, checks: async (id, cursor) => await continuation(
456
+ ['-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], mapCheckPageResponse) })
457
+ }
458
+ const failure = responseFailure(output, body)
459
+ return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), failure] as const))
460
+ }
461
+
462
+ /**
463
+ * Run one continuation query of a snapshot read.
464
+ * @param host - host the snapshot was read from.
465
+ * @param variables - `gh api graphql` field flags, the query first.
466
+ * @param signal - cancellation of the snapshot read.
467
+ * @returns the output, or the failure of a `gh` that cannot start, times out, or prints over its limit.
468
+ * @throws with `signal.reason` when the read is cancelled.
469
+ */
470
+ private async continuation(host: string, variables: readonly string[], signal: AbortSignal): Promise<GhOutput | ForgeFailure> {
471
+ signal.throwIfAborted()
472
+ try {
473
+ return await this.gh(['api', 'graphql', '--hostname', host, ...variables], signal)
474
+ } catch (error) {
475
+ if (signal.aborted) throw signal.reason
476
+ return processFailure(error)
477
+ }
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Report a `gh` invocation that did not run to an exit code.
483
+ * @param error - what the runner threw.
484
+ * @returns `too-large` for output over its limit, `unavailable` for a `gh` that cannot start or times out.
485
+ * @throws `error` when it is any other failure.
486
+ */
487
+ function processFailure(error: unknown): ForgeFailure {
488
+ if (error instanceof GhOutputLimitError) return { code: 'too-large', message: error.message }
489
+ if (error instanceof GhUnavailableError || error instanceof GhTimeoutError) return { code: 'unavailable', message: error.message }
490
+ throw error
491
+ }
492
+
493
+ /** Why `gh` refused: GitHub's message, else its first diagnostic line, with the HTTP status it names. */
494
+ function refusal(output: GhOutput): { readonly message: string; readonly status: string | undefined } {
495
+ return {
496
+ message: hostMessage(output.stdout) ?? firstLine(output.stderr) ?? `gh exited with ${output.exitCode}`,
497
+ status: HTTP_STATUS.exec(output.stderr)?.[1],
498
+ }
499
+ }
500
+
501
+ /** The `message` of the JSON error body `gh api` prints for a failed request. */
502
+ function hostMessage(stdout: string): string | undefined {
503
+ const body = parseJson(stdout)
504
+ if (typeof body !== 'object' || body === null || !('message' in body) || typeof body.message !== 'string') return undefined
505
+ return body.message.trim().length > 0 ? body.message : undefined
506
+ }
507
+
508
+ /** A repository path with each segment percent-encoded, for an API path or a web URL. */
509
+ function encodedPath(path: string): string {
510
+ return path.split('/').map(segment => encodeURIComponent(segment)).join('/')
511
+ }
512
+
513
+ function responseFailure(output: GhOutput, body: unknown): ForgeFailure {
514
+ const detail = typeof body === 'object' && body !== null && 'message' in body && typeof body.message === 'string'
515
+ ? firstLine(body.message) : undefined
516
+ const message = firstLine(output.stderr) ?? detail
517
+ ?? (output.exitCode === 0 ? 'unexpected GitHub response' : `gh exited with ${output.exitCode}`)
518
+ return { code: AUTHENTICATION.test(message) ? 'unauthenticated' : 'unavailable', message }
519
+ }
520
+
521
+ function parseJson(text: string): unknown {
522
+ let value: unknown
523
+ try {
524
+ value = JSON.parse(text)
525
+ } catch (error) {
526
+ void error // gh prints diagnostics instead of JSON when a request fails before GitHub answers.
527
+ return undefined
528
+ }
529
+ return value
530
+ }
531
+
532
+ function firstLine(text: string): string | undefined {
533
+ return text.split('\n').map(line => line.trim()).find(line => line.length > 0)
534
+ }
@@ -0,0 +1,42 @@
1
+ /** The node id of a pull request that a GraphQL mutation names, read together with the head the write must still find. */
2
+
3
+ import type { ChangeRequestRef, ForgeActionFailure } from '@deepseek-ai/dsh-experimental-forge'
4
+ import { z } from 'zod'
5
+ import type { GraphqlReader } from './commits.ts'
6
+ import { checkedRepository } from './urls.ts'
7
+
8
+ /** Node id and head commit of one pull request; variables `owner` and `name` are strings, `number` is an integer. */
9
+ export const PULL_REQUEST_NODE_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
10
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { id headRefOid } }
11
+ }`
12
+
13
+ const nodeSchema = z.object({
14
+ data: z.object({ repository: z.object({ pullRequest: z.object({ id: z.string(), headRefOid: z.string() }).nullable() }).nullable() }),
15
+ })
16
+
17
+ /**
18
+ * Read a pull request's node id before a write, refusing once its head is not `headSha`.
19
+ * @param read - runs one GraphQL query.
20
+ * @param ref - pull request address.
21
+ * @param headSha - head commit the write must still find, or null for a write that does not depend on the head.
22
+ * @param signal - cancellation of the read.
23
+ * @returns the node id, `stale` when the head moved, or why the write must not proceed.
24
+ */
25
+ export async function pullRequestNode(
26
+ read: GraphqlReader, ref: ChangeRequestRef, headSha: string | null, signal: AbortSignal,
27
+ ): Promise<string | ForgeActionFailure> {
28
+ const { host, owner, name } = checkedRepository(ref)
29
+ const node = await read([
30
+ 'api', 'graphql', '--hostname', host, '-f', `query=${PULL_REQUEST_NODE_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`,
31
+ '-F', `number=${ref.number}`,
32
+ ], signal)
33
+ if (!node.ok) return { code: node.failure.code === 'unauthenticated' ? 'unauthenticated' : 'failed', message: node.failure.message }
34
+ const parsed = nodeSchema.safeParse(node.body)
35
+ if (!parsed.success) return { code: 'failed', message: 'unexpected GitHub response to the pull request read' }
36
+ const pull = parsed.data.data.repository?.pullRequest
37
+ if (pull == null) return { code: 'failed', message: `pull request ${ref.number} was not found` }
38
+ if (headSha !== null && pull.headRefOid.toLowerCase() !== headSha.toLowerCase()) {
39
+ return { code: 'stale', message: `the pull request head moved from ${headSha} to ${pull.headRefOid}` }
40
+ }
41
+ return pull.id
42
+ }