Files
deepseek-harness/packages/experimental/forge-gitlab/src/writes.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

297 lines
16 KiB
TypeScript

/** GitLab writes to merge request discussions, draft notes, and reviews, each after a check of the head. */
import type {
ChangeRequestRef, ForgeActionFailure, ForgeLineComment, ForgeReviewEvent, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite,
ForgeReviewWriteResult,
} from '@deepseek-ai/dsh-experimental-forge'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { z } from 'zod'
import type { GitLabApi, WriteResult } from './api.ts'
import { newestVersion } from './diff.ts'
import type { DiffVersion } from './diff.ts'
import { textPosition } from './position.ts'
import type { VersionFile } from './position.ts'
import { discussionOf, DRAFT_REVIEW, noteOf } from './review.ts'
import { mergeRequestPath } from './urls.ts'
/** Reads the changed files of one diff version by their path on either side, or undefined when GitLab does not list them. */
export type VersionFiles = (version: number) => Promise<ReadonlyMap<string, VersionFile> | undefined>
/** The review state GitLab records for a reviewer who publishes with a decision; an approval records its own. */
const REVIEWER_STATES: Readonly<Record<ForgeReviewEvent, string | undefined>> = {
comment: 'reviewed', 'request-changes': 'requested_changes', approve: undefined,
}
const draftList = z.array(z.object({ id: z.number() }))
/** A failed review write or submission. */
type Refusal = Extract<ForgeReviewWriteResult, { readonly ok: false }>
/** Writes for one merge request, each sent once. */
class Writer {
constructor(
private readonly api: GitLabApi, private readonly ref: ChangeRequestRef, private readonly files: VersionFiles,
private readonly signal: AbortSignal,
) {}
/** The newest diff version once it is at `headSha`, else `stale` or why it could not be read. */
async version(headSha: string): Promise<DiffVersion | Refusal> {
const version = await newestVersion(this.api, this.ref, headSha, this.signal)
if (!('code' in version)) return version
return { ok: false, code: version.code === 'stale' ? 'stale' : 'failed', message: version.message }
}
/** Send one REST write, with `body` as JSON on stdin when it is given. */
async send(method: 'POST' | 'PUT' | 'DELETE', path: string, body?: Readonly<Record<string, unknown>>): Promise<WriteResult> {
const args = ['-X', method, `${mergeRequestPath(this.ref)}${path}`]
if (body === undefined) return await this.api.write(this.ref.repository.host, args, this.signal)
return await this.api.write(this.ref.repository.host, [...args, '--input', '-', '-H', 'Content-Type: application/json'], this.signal,
JSON.stringify(body))
}
/** The ids of the signed-in user's draft notes, which GitLab lists at once. */
async drafts(): Promise<number[] | Refusal> {
const read = await this.api.rest(this.ref.repository.host, `${mergeRequestPath(this.ref)}/draft_notes`, this.signal)
if (!read.ok) return { ok: false, code: 'failed', message: read.failure.message }
const parsed = draftList.safeParse(read.body)
return parsed.success ? parsed.data.map(draft => draft.id)
: { ok: false, code: 'failed', message: 'unexpected GitLab response to the draft note read' }
}
/** The position of a comment on the lines of `version`, or a refusal when GitLab could not place it. */
async position(
version: DiffVersion, comment: ForgeLineComment,
): Promise<{ readonly position: Readonly<Record<string, unknown>> } | Refusal> {
const files = await this.files(version.id)
if (files === undefined) return { ok: false, code: 'failed', message: 'GitLab did not list the changed files of the merge request' }
const file = files.get(comment.path)
const position = file === undefined ? undefined
: textPosition({ base: version.base_commit_sha, start: version.start_commit_sha, head: version.head_commit_sha }, file, comment)
return position !== undefined ? { position } : {
ok: false, code: 'failed',
message: `merge request ${this.ref.number} does not change lines ${comment.startLine}-${comment.endLine} of ${comment.path} on that side`,
}
}
/**
* Approve at `headSha` unless the signed-in user already approved; GitLab refuses an approval with HTTP 409 once the
* head is another commit, and answers a second approval with HTTP 401, which this check avoids.
*/
async approve(headSha: string): Promise<Refusal | undefined> {
const read = await this.api.rest(this.ref.repository.host, `${mergeRequestPath(this.ref)}/approvals`, this.signal)
const approvals = read.ok ? z.object({ user_has_approved: z.boolean() }).safeParse(read.body) : undefined
if (approvals?.success !== true) return { ok: false, code: 'failed', message: read.ok ? 'unexpected GitLab response to the approval read' : read.failure.message }
if (approvals.data.user_has_approved) return undefined
const approved = await this.send('POST', '/approve', { sha: headSha })
if (approved.ok) return undefined
if (approved.status === 409) return { ok: false, code: 'stale', message: approved.failure.message }
return refusal(approved.failure)
}
/**
* Delete draft notes this provider created, keeping going past failures, since nobody else sees them.
* @returns the ids GitLab did not confirm deleting.
*/
async discard(ids: readonly number[]): Promise<number[]> {
const left: number[] = []
for (const id of ids) if (!(await this.send('DELETE', `/draft_notes/${id}`)).ok) left.push(id)
return left
}
/** Delete the draft notes of a review that stopped, and report `failure` with any draft that may remain. */
async rollBack(failure: Refusal, ids: readonly number[]): Promise<Refusal> {
const left = await this.discard(ids)
if (left.length === 0) return failure
return {
ok: false, code: 'unknown',
message: `${failure.message}; ${left.length} pending ${left.length === 1 ? 'comment' : 'comments'} of yours may remain on merge request `
+ `${this.ref.number}, so check its pending comments before you submit again`,
}
}
}
/**
* Write to the discussions or the draft notes of a merge request. The newest diff version is read first and the write
* is refused with `stale` once its head is another commit. Replies and resolutions name a discussion and edits and
* deletions a note or draft note through the merge request's own paths, so GitLab refuses ids of another merge request;
* an id this provider never issued, such as the thread of a draft note, is refused without a write. A pending reply or
* comment is a draft note, which only its author sees; a comment's position addresses the lines of the newest version.
* Submitting publishes every draft note with the summary, after approving at the head when the decision is `approve`;
* requesting changes or commenting records that review state for a reviewer. Discarding deletes the draft notes one by
* one. No write is retried: a refusal GitLab reports returns `failed`, and an answer that does not show whether GitLab
* applied a write returns `unknown`.
* @param api - GitLab reads and writes.
* @param files - reads the changed files of a diff version.
* @param ref - merge request, with a project path already checked for inlining.
* @param write - the write and the head commit the user saw.
* @param signal - cancellation of the reads and writes.
* @returns whether GitLab took the write.
*/
export async function writeGitLabReview(
api: GitLabApi, files: VersionFiles, ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal,
): Promise<ForgeReviewWriteResult> {
const writer = new Writer(api, ref, files, signal)
const unknownTarget: Refusal = { ok: false, code: 'failed', message: `merge request ${ref.number} has no discussion or note with that id` }
const version = await writer.version(write.headSha)
if ('ok' in version) return version
switch (write.kind) {
case 'reply': {
const discussion = discussionOf(write.thread)
if (discussion === undefined) return unknownTarget
return done(write.pending
? await writer.send('POST', '/draft_notes', { note: write.body, in_reply_to_discussion_id: discussion })
: await writer.send('POST', `/discussions/${discussion}/notes`, { body: write.body }))
}
case 'resolve': {
const discussion = discussionOf(write.thread)
if (discussion === undefined) return unknownTarget
return done(await writer.send('PUT', `/discussions/${discussion}`, { resolved: write.resolved }))
}
case 'edit-comment': {
const note = noteOf(write.comment)
if (note === undefined) return unknownTarget
return done(note.draft
? await writer.send('PUT', `/draft_notes/${note.id}`, { note: write.body })
: await writer.send('PUT', `/notes/${note.id}`, { body: write.body }))
}
case 'delete-comment': {
const note = noteOf(write.comment)
if (note === undefined) return unknownTarget
return done(await writer.send('DELETE', note.draft ? `/draft_notes/${note.id}` : `/notes/${note.id}`))
}
case 'add-pending': {
const placed = await writer.position(version, write.comment)
if ('ok' in placed) return placed
return done(await writer.send('POST', '/draft_notes', { note: write.comment.body, position: placed.position }))
}
case 'submit-pending': {
const drafts = await pendingDrafts(writer, write.review)
if ('ok' in drafts) return drafts
if (write.event === 'approve') {
const refused = await writer.approve(write.headSha)
if (refused !== undefined) return refused
}
return done(await publish(writer, write.event, write.body))
}
case 'discard-pending': {
const drafts = await pendingDrafts(writer, write.review)
if ('ok' in drafts) return drafts
for (const [index, id] of drafts.entries()) {
const deleted = await writer.send('DELETE', `/draft_notes/${id}`)
if (!deleted.ok) {
const failure = refusal(deleted.failure)
return index === 0 ? failure : { ...failure, message: `GitLab deleted ${index} of ${drafts.length} pending comments: ${failure.message}` }
}
}
return { ok: true }
}
/* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */
default: return assertNever(write, 'ForgeReviewWrite.kind')
}
}
/**
* Publish one comment or one complete review on a merge request. The newest diff version is read first and the
* submission is refused with `stale` once its head is another commit; comment positions address its lines, and every
* position is found before anything is written. A comment starts a discussion at once. A review is refused while the
* signed-in user has draft notes, which publishing would include; otherwise each comment becomes a draft note, an
* `approve` decision approves at the head, and the drafts are published with the summary and the decision's review state.
* A refused draft or approval deletes the drafts written before it, so a refused review changes nothing; a refused
* publication deletes them too, keeping only an approval, which a retry does not repeat. Nothing is retried.
* @param api - GitLab reads and writes.
* @param files - reads the changed files of a diff version.
* @param ref - merge request, with a project path already checked for inlining.
* @param request - the comment or review and the head commit the user reviewed.
* @param signal - cancellation of the reads and writes.
* @returns the page of the published comment or of the merge request, or why GitLab did not take it.
*/
export async function submitGitLabReview(
api: GitLabApi, files: VersionFiles, ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal,
): Promise<ForgeReviewResult> {
const writer = new Writer(api, ref, files, signal)
const { host, owner, name } = ref.repository
const url = `https://${host}/${owner}/${name}/-/merge_requests/${ref.number}`
const version = await writer.version(request.headSha)
if ('ok' in version) return version
if (request.kind === 'comment') {
const placed = await writer.position(version, request.comment)
if ('ok' in placed) return placed
const started = await writer.send('POST', '/discussions', { body: request.comment.body, position: placed.position })
if (!started.ok) return refusal(started.failure)
const note = z.object({ notes: z.array(z.object({ id: z.number() })).min(1) }).safeParse(started.body).data?.notes[0]
return { ok: true, url: note === undefined ? url : `${url}#note_${note.id}` }
}
const existing = await writer.drafts()
if ('ok' in existing) return existing
if (existing.length > 0) {
return { ok: false, code: 'failed', message: 'GitLab holds pending comments of yours on this merge request; submit or discard them first' }
}
if (request.event === 'comment' && request.comments.length === 0 && request.body.trim() === '') {
return { ok: false, code: 'failed', message: 'A review without a decision needs a comment or a summary' }
}
const positions: Readonly<Record<string, unknown>>[] = []
for (const comment of request.comments) {
const placed = await writer.position(version, comment)
if ('ok' in placed) return placed
positions.push(placed.position)
}
const written: number[] = []
for (const [index, comment] of request.comments.entries()) {
const draft = await writer.send('POST', '/draft_notes', { note: comment.body, position: positions[index] })
const id = draft.ok ? z.object({ id: z.number() }).safeParse(draft.body).data?.id : undefined
if (id === undefined) {
return await writer.rollBack(draft.ok ? { ok: false, code: 'unknown', message: 'unexpected GitLab response to a draft note' } : refusal(draft.failure),
written)
}
written.push(id)
}
if (request.event === 'approve') {
const refused = await writer.approve(request.headSha)
if (refused !== undefined) return await writer.rollBack(refused, written)
if (written.length === 0 && request.body.trim() === '') return { ok: true, url }
}
const published = await publish(writer, request.event, request.body)
if (published.ok) return { ok: true, url }
if (published.failure.code === 'unknown') return refusal(published.failure)
return await afterRefusedPublish(writer, written, refusal(published.failure))
}
/**
* Settle a publication GitLab refused. GitLab can publish the draft notes before it refuses the summary or the review
* state, so the drafts are read again: when every draft remains, nothing was published and they are deleted; when one
* is gone, the comments may be public, so none is deleted and the outcome is reported for the user to check.
*/
async function afterRefusedPublish(writer: Writer, written: readonly number[], failure: Refusal): Promise<Refusal> {
const drafts = await writer.drafts()
if (!('ok' in drafts) && written.every(id => drafts.includes(id))) return await writer.rollBack(failure, written)
return {
ok: false, code: 'unknown',
message: `${failure.message}; GitLab may have published the comments of this review, so check the merge request before you submit again`,
}
}
/** The ids of the pending review's draft notes, or a refusal when `review` is not the user's pending review. */
async function pendingDrafts(writer: Writer, review: string): Promise<number[] | Refusal> {
const drafts = review === DRAFT_REVIEW ? await writer.drafts() : []
if ('ok' in drafts) return drafts
return drafts.length > 0 ? drafts : { ok: false, code: 'failed', message: `the pending review ${review} is no longer the signed-in user's pending review` }
}
/** Publish every draft note with an optional summary and the review state of `event`. */
async function publish(writer: Writer, event: ForgeReviewEvent, body: string): Promise<WriteResult> {
const state = REVIEWER_STATES[event]
return await writer.send('POST', '/draft_notes/bulk_publish', {
...body.trim() === '' ? {} : { note: body }, ...state === undefined ? {} : { reviewer_state: state },
})
}
/** The result of one write that ends a review write. */
function done(written: WriteResult): ForgeReviewWriteResult {
return written.ok ? { ok: true } : refusal(written.failure)
}
/** A write failure as a review result, in which missing credentials are a refusal. */
function refusal(failure: ForgeActionFailure): Refusal {
return { ok: false, code: failure.code === 'unauthenticated' ? 'failed' : failure.code, message: failure.message }
}