Files
deepseek-harness/packages/experimental/forge-github/src/threads.ts
T
LegGasai cb44a3c2ee feat(forge): read, review, and bind GitLab merge requests (#8317)
* feat(forge): let providers declare their hosts, names, sign-in, and review decisions

Prepare the forge contract for a second provider:

- ForgeProvider lists the hosts it serves and names itself (label,
  changeRequestNoun); registering a provider that lists a host another
  registered provider lists throws, so each URL has at most one provider.
  ctx.forge.describe(forge) returns the family's ForgeDescription.
- ForgeReadiness carries the sign-in command, which the panel's sign-in
  banner shows instead of building `gh auth login` for the github family.
- ForgeReviewData lists the review decisions the host lets the reader
  record; the review dialog offers only those instead of hardcoding the
  GitHub rule that a pull request's author may only comment.
- ForgeReviewThread.original may name a later commit the host carried the
  thread to while its lines stayed unchanged.
- The changes view names the code host and its word for a change request
  from the entry's ForgeDescription instead of hardcoding GitHub and PR.

The GitHub provider declares its configured hosts, GitHub, pull requests,
`gh auth login --hostname <host>`, and reads viewerDidAuthor for the
review decisions. Upgrade guide: forge-provider-hosts.

* feat(forge-gitlab): read GitLab merge requests through the GitLab CLI

Add the experimental forge-gitlab provider. It serves the configured
GitLab hosts through glab: status batches over GraphQL, head-pinned
patches from merge request diff versions, commit listings, merge bases,
pipeline jobs, closing issues, and review threads mapped from REST
discussions, including outdated threads' hunks.

The forge bundle composes the provider, disabled by default.

* feat(forge-gitlab): write GitLab reviews, retry pipelines, request reviews, and rebase

The GitLab provider now writes through glab as well as reading:
comments start discussions at positions derived from the head's diff
version, pending replies and comments are draft notes that a review
publishes with its summary and review state, and approving checks the
head through GitLab's sha parameter. Review reads carry the signed-in
user's rights from GraphQL, their draft notes as the pending review,
and the decisions GitLab lets them record.

Snapshots name the head pipeline as every job's rerun, offer rebase as
the branch update, and follow GitLab's permissions for reruns and
review requests. updateBranch's contract now states how a provider
whose host takes no expected head checks it.

* feat(forge): let forge providers register the commands that bind change requests

forge-session no longer recognizes gh commands by itself. A provider now
registers a declarative ForgeCommandRule through
ctx.forgeSession.registerCommands: its executable, creation and reference
subcommands, change request page path, JSON URL members, declared
options, and a pure select that maps one parsed reference command to a
URL or a read-only lookup. forge-github registers gh and forge-gitlab
registers glab, which adds glab mr create, view, update, and checkout,
including numbers with -R: a full project URL binds directly, and other
repository forms resolve through glab mr view in the call's shell.

forge-session keeps the shared parts: the literal shell tokenizer,
option parsing, output reading, lookups, and the projection. The
forgeChangeRequests state version derives from the recognized rules, so
a changed rule set refolds every Session, including commands that ran
before the provider loaded. Ending a registration keeps its rule
recognized until restart, so unloading providers at shutdown does not
rewrite every checkpoint.

* refactor(forge-gitlab): publish the GitLab provider as @deepseek-ai/dsh-forge-gitlab

New experimental packages omit the experimental prefix so that promotion
keeps their npm name. Register the directory in
EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS instead of growing the legacy
prefixed list, and rename every dependency, configuration row, path
mapping, and document that names the package.

* fix(forge-gitlab): keep review writes, comment positions, and reads within GitLab's facts and the limits

- After GitLab refuses a publication, read the drafts again: delete
  them only when all remain, since GitLab can publish them before it
  refuses the summary, and report the outcome as unknown otherwise.
  A rollback that leaves drafts reports how many may remain.
- Place comments on files GitLab collapsed through the diff compared
  from their texts, and let a file's new path name it over another
  file's old path after chained renames.
- Keep the final newline of raw file reads.
- Apply maxOutputBytes to the complete review result, and report a
  read whose rights stop early or skip a discussion's later notes as
  truncated.
- Serve a version over maxCachedVersionBytes without keeping it.
- Resolve uploaded avatars GitLab names by their path on the host.
- Schedule bounded reads through p-limit.

* fix(forge-session): run lookups only for live command rules and keep the projection registered

- Reference lookups use the rules of live registrations, so a disposed
  provider's rule still folds but starts no gh or glab process.
- A failed re-registration registers the projection again with the
  earlier rules, so clients keep its view; an error is logged only when
  that fails too.
- Document the startup re-registration, test that the checkpointed
  state version survives a real Loader start, shutdown, and restart,
  and record that starting without a provider removes the bindings only
  its commands made.
- Describe the changes view's pending review and single comment
  without naming GitHub, which keeps its own rule in forge-github, and
  render registerCommands as code in the generated service reference.

* fix(forge-bundle): name GitLab merge requests in the bundle description

The bundle now follows GitLab merge requests as well as GitHub pull
requests, so the description's first sentence in every locale names
both kinds of change request.

* feat(forge): bind the change requests that gh api and glab api requests name

Models often read a merge request through `glab api` or a pull request
through `gh api` instead of `glab mr view` or `gh pr view`, which left
the change request unbound. A command rule now declares raw API request
subcommands beside its reference subcommands, each group with its own
options, since `-f` is a value of `gh api` and a flag of
`gh pr checkout`.

An API request binds, as referenced, only the change request its REST
path names, such as `projects/group%2Fapp/merge_requests/7/changes` or
`repos/octo/demo/pulls/7/files`; its output is not read, since one
request can list many change requests. A path whose host the command
names binds directly, and one without a host, or with the current
repository's placeholders, resolves through the CLI's view command in
the call's shell. The gh and glab rules move to version 2.

* docs(forge): add forge-gitlab and the forge-session peers to the module graph

Regenerate docs/module-graph for the renamed GitLab provider and the
optional forge-session peer of both providers.

* test(web): refresh the forge bundle description in the recommended plugin catalog

The creation recommendation recording carries every recommended
plugin's description; refresh it for the forge bundle description that
now names GitLab merge requests and the glab sign-in.

* chore(forge-gitlab): carry the 0.2.2-rc.3 release version and move upgrade guides to v0.2.2-rc.3
2026-11-13 07:56:57 +00:00

268 lines
13 KiB
TypeScript

/** Reads the review threads of a GitHub pull request at one head commit through GraphQL. */
import { Buffer } from 'node:buffer'
import type {
ChangeRequestRef, ForgeAnchor, ForgeCommentId, ForgeFailure, ForgeReviewComment, ForgeReviewData, ForgeReviewEvent, ForgeReviewId,
ForgeReviewThread, ForgeThreadId,
} from '@deepseek-ai/dsh-experimental-forge'
import { z } from 'zod'
import type { GraphqlReader } from './commits.ts'
import { checkedRepository, isCommit } from './urls.ts'
/** Most nodes GitHub returns in one connection page. */
const PAGE_SIZE = 100
/** Repository permissions that may comment on a locked conversation. */
const WRITERS: ReadonlySet<string> = new Set(['ADMIN', 'MAINTAIN', 'WRITE'])
const COMMENT_FIELDS = 'id state createdAt url body viewerCanUpdate viewerCanDelete author { __typename login avatarUrl(size: 48) }'
const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { ${COMMENT_FIELDS} } }`
/**
* Thread fields. `root` reads the commits and diff hunk of the first comment once, since replies repeat them; the
* first page of comments starts without a cursor.
*/
const THREAD_FIELDS = `id isOutdated isResolved path diffSide startDiffSide line startLine originalLine originalStartLine subjectType
viewerCanReply viewerCanResolve viewerCanUnresolve
root: comments(first: 1) { nodes { diffHunk commit { oid } originalCommit { oid } } }
${COMMENT_PAGE.replace(', after: $cursor', '')}`
const THREAD_PAGE = `pageInfo { hasNextPage endCursor } nodes { ${THREAD_FIELDS} }`
/**
* First thread page with the head, the viewer, whether the viewer may comment, and the viewer's pending review; variables
* `owner` and `name` are strings, `number` and `first` integers.
*/
export const REVIEW_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!) {
viewer { login }
repository(owner: $owner, name: $name) {
isArchived viewerPermission
pullRequest(number: $number) {
id headRefOid locked viewerDidAuthor
reviews(states: PENDING, first: 100) { nodes { id viewerDidAuthor comments { totalCount } } }
reviewThreads(first: $first) { ${THREAD_PAGE} }
}
}
}`
/** Following thread page with the head it was read at; variables `id` and `cursor` are strings, `first` an integer. */
export const REVIEW_THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) {
node(id: $id) { ... on PullRequest { headRefOid reviewThreads(first: $first, after: $cursor) { ${THREAD_PAGE} } } }
}`
/** Following comment page of one thread; variables `id` and `cursor` are strings. */
export const THREAD_COMMENTS_QUERY = `query($id: ID!, $cursor: String!) {
node(id: $id) { ... on PullRequestReviewThread { ${COMMENT_PAGE} } }
}`
/** Bounds of one review read. */
export interface ReviewLimits {
/** Most threads read. */
readonly maxReviewThreads: number
/**
* Most JSON bytes of all pages together: a later page that would pass it ends the read as truncated, and a first
* page whose output alone passes it fails the read as `too-large`.
*/
readonly maxOutputBytes: number
}
const pageInfoSchema = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() })
const commitSchema = z.object({ oid: z.string().refine(isCommit) }).nullable()
const commentSchema = z.object({
id: z.string(),
state: z.string(),
createdAt: z.string(),
url: z.string().nullable(),
body: z.string(),
viewerCanUpdate: z.boolean(),
viewerCanDelete: z.boolean(),
author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }).nullable(),
})
const commentPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(commentSchema) })
const threadSchema = z.object({
id: z.string(),
isOutdated: z.boolean(),
isResolved: z.boolean(),
path: z.string(),
diffSide: z.string(),
startDiffSide: z.string().nullable(),
line: z.number().int().nullable(),
startLine: z.number().int().nullable(),
originalLine: z.number().int().nullable(),
originalStartLine: z.number().int().nullable(),
subjectType: z.string(),
viewerCanReply: z.boolean(),
viewerCanResolve: z.boolean(),
viewerCanUnresolve: z.boolean(),
root: z.object({ nodes: z.array(z.object({ diffHunk: z.string(), commit: commitSchema, originalCommit: commitSchema })) }),
comments: commentPageSchema,
})
const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(threadSchema) })
const pendingSchema = z.object({
id: z.string(),
viewerDidAuthor: z.boolean(),
comments: z.object({ totalCount: z.number().int().nonnegative() }),
})
const pullRequestSchema = z.object({
id: z.string(),
headRefOid: z.string(),
locked: z.boolean(),
viewerDidAuthor: z.boolean(),
reviews: z.object({ nodes: z.array(pendingSchema) }),
reviewThreads: threadPageSchema,
})
const firstPageSchema = z.object({ data: z.object({
viewer: z.object({ login: z.string() }).nullable(),
repository: z.object({
isArchived: z.boolean(),
viewerPermission: z.string().nullable(),
pullRequest: pullRequestSchema.nullable(),
}).nullable(),
}) })
const nextPageSchema = z.object({ data: z.object({ node: z.object({ headRefOid: z.string(), reviewThreads: threadPageSchema }) }) })
const commentsPageSchema = z.object({ data: z.object({ node: z.object({ comments: commentPageSchema }) }) })
type ThreadNode = z.infer<typeof threadSchema>
type CommentNode = z.infer<typeof commentSchema>
/**
* Read the review threads of a pull request while its head is `headSha`. The first page also names the head; every
* following thread page names the head again, so a head that moves during the read returns
* `stale`, while a thread's comment pages do not. Threads are read up to `maxReviewThreads`, each with all of its
* comments. A later page that would bring the pages read, measured as JSON, past `maxOutputBytes` is dropped with the
* threads after it, and the result is marked truncated; `read` fails a first page whose output alone passes the limit.
* @param read - runs one GraphQL request.
* @param ref - pull request, with an owner and name already checked for inlining.
* @param headSha - head commit the threads must be read at.
* @param limits - thread and byte bounds.
* @param signal - cancellation of the read.
* @returns the threads, or why GitHub did not provide them at `headSha`.
*/
export async function readReviewThreads(
read: GraphqlReader, ref: ChangeRequestRef, headSha: string, limits: ReviewLimits, signal: AbortSignal,
): Promise<ForgeReviewData | ForgeFailure> {
const { host, owner, name } = checkedRepository(ref)
const graphql = async (variables: readonly string[]): Promise<{ readonly body: unknown; readonly bytes: number } | ForgeFailure> => {
const output = await read(['api', 'graphql', '--hostname', host, ...variables], signal)
if (!output.ok) return output.failure
return { body: output.body, bytes: Buffer.byteLength(JSON.stringify(output.body)) }
}
const unexpected: ForgeFailure = { code: 'unavailable', message: 'unexpected GitHub response to the review thread read' }
const stale = (head: string): ForgeFailure | undefined => head.toLowerCase() === headSha.toLowerCase() ? undefined
: { code: 'stale', message: `the pull request head moved from ${headSha} to ${head}` }
const first = await graphql(['-f', `query=${REVIEW_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`,
'-F', `number=${ref.number}`, '-F', `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads)}`])
if ('code' in first) return first
const parsed = firstPageSchema.safeParse(first.body)
if (!parsed.success) return unexpected
const repository = parsed.data.data.repository
const pull = repository?.pullRequest
if (repository == null || pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` }
const moved = stale(pull.headRefOid)
if (moved !== undefined) return moved
let bytes = first.bytes
let page = pull.reviewThreads
const threads: ForgeReviewThread[] = []
const viewer = parsed.data.data.viewer?.login ?? null
// GitHub lists a pending review only to its author; reading up to 100 finds the viewer's even if others were listed first.
const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor)
const pendingReview = pending === undefined ? null : { id: pending.id as ForgeReviewId, comments: pending.comments.totalCount }
// GitHub refuses every write to an archived repository, and comments on a locked conversation from anyone without write access.
const viewerCanReview = !repository.isArchived && (!pull.locked || WRITERS.has(repository.viewerPermission ?? ''))
// GitHub lets the author of a pull request comment on it but not approve it or request changes.
const reviewEvents: readonly ForgeReviewEvent[] = !viewerCanReview ? [] : pull.viewerDidAuthor ? ['comment'] : ['comment', 'approve', 'request-changes']
const result = (truncated: boolean): ForgeReviewData => ({
headSha, viewer, threads, truncated, pendingReview, viewerCanReview, reviewEvents,
})
const cursors = new Set<string>()
for (;;) {
for (const node of page.nodes.slice(0, limits.maxReviewThreads - threads.length)) {
const comments = [...node.comments.nodes]
const commentCursors = new Set<string>()
let more = node.comments.pageInfo
while (more.hasNextPage) {
const cursor = more.endCursor
if (cursor === null || commentCursors.has(cursor)) return { code: 'unavailable', message: 'GitHub review comment pagination did not advance' }
commentCursors.add(cursor)
const next = await graphql(['-f', `query=${THREAD_COMMENTS_QUERY}`, '-f', `id=${node.id}`, '-f', `cursor=${cursor}`])
if ('code' in next) return next
const comment = commentsPageSchema.safeParse(next.body)
if (!comment.success) return unexpected
bytes += next.bytes
if (bytes > limits.maxOutputBytes) return result(true)
comments.push(...comment.data.data.node.comments.nodes)
more = comment.data.data.node.comments.pageInfo
}
if (comments.length > 0) threads.push(toThread(node, comments, headSha))
}
if (threads.length >= limits.maxReviewThreads || !page.pageInfo.hasNextPage) return result(page.pageInfo.hasNextPage)
const cursor = page.pageInfo.endCursor
if (cursor === null || cursors.has(cursor)) return { code: 'unavailable', message: 'GitHub review thread pagination did not advance' }
cursors.add(cursor)
const next = await graphql(['-f', `query=${REVIEW_THREADS_QUERY}`, '-f', `id=${pull.id}`, '-f', `cursor=${cursor}`,
'-F', `first=${Math.min(PAGE_SIZE, limits.maxReviewThreads - threads.length)}`])
if ('code' in next) return next
const following = nextPageSchema.safeParse(next.body)
if (!following.success) return unexpected
const movedLater = stale(following.data.data.node.headRefOid)
if (movedLater !== undefined) return movedLater
bytes += next.bytes
if (bytes > limits.maxOutputBytes) return result(true)
page = following.data.data.node.reviewThreads
}
}
/**
* Map one thread. GitHub keeps a thread's `line` on the commit of its first comment, which stays an older commit for
* a comment written on a commit the head no longer is; such a thread, like one GitHub marks outdated or leaves
* without a line, has no position at `head`. A range whose start is on the other side of the diff keeps its last line.
*/
function toThread(node: ThreadNode, comments: readonly CommentNode[], head: string): ForgeReviewThread {
const root = node.root.nodes[0]
const line = node.subjectType !== 'FILE'
const sameSide = node.startDiffSide === null || node.startDiffSide === node.diffSide
const placed = line && !node.isOutdated && node.line !== null && root?.commit?.oid.toLowerCase() === head.toLowerCase()
return {
id: node.id as ForgeThreadId,
path: node.path,
side: node.diffSide === 'LEFT' ? 'L' : 'R',
subject: line ? 'line' : 'file',
current: placed && node.line !== null ? anchor(head, sameSide ? node.startLine : null, node.line) : null,
original: line && node.originalLine !== null && root?.originalCommit != null
? anchor(root.originalCommit.oid, sameSide ? node.originalStartLine : null, node.originalLine) : null,
diffHunk: root === undefined || root.diffHunk === '' ? null : root.diffHunk,
resolved: node.isResolved,
viewerCanReply: node.viewerCanReply,
viewerCanResolve: node.isResolved ? node.viewerCanUnresolve : node.viewerCanResolve,
comments: comments.map(toComment),
}
}
function anchor(commit: string, start: number | null, end: number): ForgeAnchor {
return { commit, startLine: start !== null && start >= 1 && start <= end ? start : end, endLine: end }
}
function toComment(node: CommentNode): ForgeReviewComment {
return {
id: node.id as ForgeCommentId,
author: node.author === null ? null : { login: node.author.login, avatarUrl: node.author.avatarUrl, bot: node.author.__typename === 'Bot' },
body: node.body,
createdAt: node.createdAt,
pending: node.state === 'PENDING',
url: node.url,
viewerCanEdit: node.viewerCanUpdate,
viewerCanDelete: node.viewerCanDelete,
}
}