Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestProvider.ts

597 lines24.6 KB

1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3import type {
4 PullRequestStackMembership,
5 PullRequestAction,
6 PullRequestStackHead,
7 PullRequestActor,
8 PullRequestBaseComparison,
9 PullRequestCapabilities,
10 PullRequestChecksState,
11 PullRequestCheck,
12 PullRequestComment,
13 PullRequestCommit,
14 PullRequestInvolvement,
15 PullRequestLabel,
16 PullRequestListFilters,
17 PullRequestListState,
18 PullRequestMergeCapabilities,
19 PullRequestMergeMethod,
20 PullRequestMergeability,
21 PullRequestOmittedFileStat,
22 PullRequestReaction,
23 PullRequestReactionContent,
24 PullRequestReviewCommentDraft,
25 PullRequestReviewDecision,
26 PullRequestReviewThread,
27 PullRequestThreadCommentsResult,
28 PullRequestReviewVerdict,
29 PullRequestReviewerCandidateList,
30 PullRequestReviewerKind,
31 PullRequestLabelCandidateList,
32 PullRequestState,
33 PullRequestUpdateMethod,
34 PullRequestViewerPermissions,
35 SourceControlProviderKind,
36} from "@t3tools/contracts";
37import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t3tools/contracts";
38​
39/**
40 * The one failure shape every provider reports, so the service can decide what a failure means
41 * without knowing which CLI or API produced it.
42 *
43 * `reason` is the part the service acts on: a missing or unauthenticated tool disables the
44 * provider for the whole workspace, a rate limit pauses its host, and anything else is specific
45 * to the request.
46 */
47export class PullRequestProviderError extends Schema.TaggedError<PullRequestProviderError>()(
48 "PullRequestProviderError",
49 {
50 provider: SourceControlProviderKindSchema,
51 operation: Schema.String,
52 reason: Schema.Literals(["missing-tool", "unauthenticated", "rate-limited", "failed"]),
53 detail: Schema.String,
54 retryAt: Schema.optional(Schema.Number),
55 cause: Schema.optional(Schema.Defect()),
56 },
57) {
58 override get message(): string {
59 return `${this.provider} failed in ${this.operation}: ${this.detail}`;
60 }
62​
63export interface PullRequestProviderFailure {
64 readonly reason: PullRequestProviderError["reason"];
65 readonly retryAt?: number | undefined;
67​
68/** A change request as the provider sees it, before the service attaches project context. */
69export interface ProviderChangeRequest {
70 readonly stack?: PullRequestStackMembership;
71 readonly number: number;
72 readonly title: string;
73 readonly url: string;
74 readonly author: PullRequestActor | null;
75 readonly headBranch: string;
76 readonly headRepositoryNameWithOwner?: string | null;
77 readonly baseBranch: string;
78 readonly state: PullRequestState;
79 readonly isDraft: boolean;
80 readonly mergeability: PullRequestMergeability;
81 readonly additions: number;
82 readonly deletions: number;
83 readonly createdAt: string;
84 readonly closedAt?: string | null;
85 readonly mergedAt?: string | null;
86 readonly updatedAt: string;
87 /** Accounts with a review requested. Team-level requests are excluded by each provider. */
88 readonly reviewRequestLogins: ReadonlyArray<string>;
89 readonly labels: ReadonlyArray<PullRequestLabel>;
90 /** Absent from a host that does not summarise its reviews, which is every host but GitHub. */
91 readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
92 /** Absent from a host that reports no check rollup on its listings. */
93 readonly checksState?: PullRequestChecksState | null | undefined;
95​
96/** The fields needed to keep a linked thread's pull request status live. */
97export interface ProviderChangeRequestSummary {
98 readonly number: number;
99 readonly title: string;
100 readonly url: string;
101 readonly headBranch: string;
102 readonly baseBranch: string;
103 readonly state: PullRequestState;
104 /** Present when the host says an open pull request is still a draft. */
105 readonly isDraft?: boolean;
106 readonly closedAt?: string | null;
107 readonly mergedAt?: string | null;
108 readonly updatedAt: string;
109 /** Overview fields, present where the host's single read returns them at no extra cost. */
110 readonly author?: PullRequestActor | null | undefined;
111 readonly additions?: number | undefined;
112 readonly deletions?: number | undefined;
113 readonly changedFiles?: number | undefined;
114 readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
115 readonly checksState?: PullRequestChecksState | null | undefined;
116 readonly mergeability?: PullRequestMergeability | undefined;
118​
119/** One layer of a host-native stack, bottom to top order is the array's. */
120export interface ProviderChangeRequestStackLayer {
121 readonly title?: string;
122 readonly isDraft?: boolean;
123 readonly headSha?: string;
124 readonly number: number;
125 readonly headBranch: string;
126 readonly state: PullRequestState;
128​
129/**
130 * A host-native stack: an ordered set of change requests the host itself merges and retargets as
131 * a unit. Only GitHub offers one today; the neutral shape lets the sync reactor and the UI stay
132 * ignorant of which host said so.
133 */
134export interface ProviderChangeRequestStack {
135 readonly id: string;
136 readonly number: number;
137 readonly url: string;
138 readonly base: string;
139 readonly layers: ReadonlyArray<ProviderChangeRequestStackLayer>;
141​
142export interface ProviderChangeRequestPage {
143 readonly items: ReadonlyArray<ProviderChangeRequest>;
144 /** True when the host has more rows than the page size asked for. */
145 readonly truncated: boolean;
146 /**
147 * Optional count-based cursor advance. Most hosts advance by the rows delivered after local
148 * de-duplication; an offset-paged host may need to count malformed raw rows it consumed too.
149 */
150 readonly cursorAdvance?: number;
151 /**
152 * This page can be carried on from, so the service may hand the caller a cursor for it. False
153 * where the host answered in an order a cursor means nothing in, which leaves a larger `limit`
154 * as the only way to the rest — what every listing did before there were cursors.
155 */
156 readonly continues: boolean;
158​
159/**
160 * Where a repository's next slice starts, as the provider that has to ask for it needs it. Built
161 * by the service out of the slice it just handed over, so the boundary that decides whether a row
162 * arrives twice or not at all is decided in one place rather than in four.
163 */
164export interface ProviderListCursor {
165 /**
166 * The instant of the oldest row already handed over, checked against a timestamp's shape before
167 * it gets here because it goes into a host's own filter. Asked for inclusively: several rows
168 * share one instant often enough — a bot that touches eight change requests writes one timestamp
169 * on all eight — and asking for strictly older would lose whichever of them the slice ended
170 * before. The service drops the ones it has already sent.
171 */
172 readonly updatedBefore: string;
173 /**
174 * How many provider rows this repository has consumed so far, for a host that carries on by
175 * counting rather than by date. Usually this is the number handed over; malformed raw rows may
176 * count too when the provider reports a `cursorAdvance`.
177 */
178 readonly delivered: number;
180​
181/** One repository's row inside an answer that spans several of them. */
182export interface ProviderBatchedChangeRequest extends ProviderChangeRequest {
183 /** Provider-native identity, exactly as it was asked for, so the caller can file the row. */
184 readonly repository: string;
186​
187/**
188 * One slice of a host read across several repositories at once, newest update first across all
189 * of them. There is no per-repository page here because the host was asked one question: the
190 * caller splits the rows by `repository` and works out where each of them carries on from the
191 * oldest row in the slice, which every repository the slice covers is now read up to.
192 */
193export interface ProviderBatchedChangeRequestPage {
194 readonly items: ReadonlyArray<ProviderBatchedChangeRequest>;
195 /** True when the host has more rows than the slice asked for, for any of the repositories. */
196 readonly truncated: boolean;
198​
199/** The line counts for one change request, which a listing may leave for a second read. */
200export interface ProviderChangeRequestStat {
201 readonly repository: string;
202 readonly number: number;
203 readonly additions: number;
204 readonly deletions: number;
206​
207export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
208 readonly body: string;
209 readonly changedFiles: number;
210 readonly mergedAt: string | null;
211 readonly closedAt: string | null;
212 readonly reviewers: ReadonlyArray<PullRequestActor>;
213 readonly checks: ReadonlyArray<PullRequestCheck>;
214 readonly mergeCapabilities: PullRequestMergeCapabilities;
215 readonly viewerPermissions: PullRequestViewerPermissions;
216 /** Absent from a host that cannot compare the branch with its base, which is most of them. */
217 readonly baseComparison?: PullRequestBaseComparison;
218 readonly behindBy?: number;
219 /** Absent from a host that does not report whether it is armed to merge this on its own. */
220 readonly autoMergeEnabled?: boolean;
221 /** The strategy stored with an armed auto-merge, where the host reports it. */
222 readonly autoMergeMethod?: PullRequestMergeMethod;
223 /** Workflow runs on this head commit that still need a maintainer's approval. */
224 readonly workflowApprovalsRequired?: number;
226​
227/** The conversation-shaped half of a detail, loaded after the core can already render. */
228export interface ProviderChangeRequestActivity {
229 /** An optional richer actor, e.g. after GitHub's GraphQL read supplies an avatar. */
230 readonly author?: PullRequestActor | null;
231 /** Optional because most hosts already report their reviewer list in the core detail. */
232 readonly reviewers?: ReadonlyArray<PullRequestActor>;
233 readonly comments: ReadonlyArray<PullRequestComment>;
234 /**
235 * The host's own count of the conversation, which a bounded read can fall short of. A host
236 * that reports no count of its own answers with what it handed over, which is the same number
237 * once the read went to the end.
238 */
239 readonly commentCount: number;
240 readonly commentsTruncated: boolean;
241 readonly reviewThreads: ReadonlyArray<PullRequestReviewThread>;
242 readonly commits: ReadonlyArray<PullRequestCommit>;
243 /** The change request's own reactions, from a host that has them. */
244 readonly reactions?: ReadonlyArray<PullRequestReaction>;
246​
247export interface ProviderDiffSlice {
248 readonly patch: string;
249 /** Something in this slice could not be shown, as opposed to there being more slices. */
250 readonly truncated: boolean;
251 readonly nextCursor: string | null;
252 /** The host's own counts for the files whose hunks it withheld from this slice. */
253 readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
255​
256export interface ProviderDiffFileContents {
257 readonly oldContents: string;
258 readonly newContents: string;
260​
261export interface ProviderRepositoryRef {
262 readonly cwd: string;
263 /** Provider-native repository identity, e.g. `owner/repo` or `group/subgroup/project`. */
264 readonly repository: string;
265 /**
266 * The host it lives on, which `repository` deliberately leaves out — the same `owner/repo`
267 * exists on github.com and on a GitHub Enterprise install, and only the caller knows which
268 * one a project's remote points at.
269 */
270 readonly host: string;
272​
273/**
274 * One host's change requests. Implementations own their own tool and JSON shapes and hand back
275 * the neutral types above; anything a host cannot do is declared in `capabilities` rather than
276 * failing at call time.
277 */
278export interface PullRequestProviderApi {
279 readonly withVerifiedCredential?: <A, E, R>(
280 input: { readonly cwd: string; readonly host: string },
281 use: (identity: {
282 readonly accountId: string;
283 readonly viewer: string;
284 readonly credentialFingerprint: string;
285 }) => Effect.Effect<A, E, R>,
286 ) => Effect.Effect<A, E | PullRequestProviderError, R>;
287 readonly getRoutingIdentity?: (input: {
288 readonly cwd: string;
289 readonly host: string;
290 }) => Effect.Effect<
291 { readonly accountId: string; readonly viewer: string },
292 PullRequestProviderError
293 >;
294 readonly kind: SourceControlProviderKind;
295 readonly capabilities: PullRequestCapabilities;
296​
297 /**
298 * The signed-in account, which is what involvement filtering compares against. The host is
299 * named because a tool signed into more than one answers for a different account on each, and
300 * the wrong login silently empties every involvement filter.
301 */
302 readonly getViewer: (input: {
303 readonly cwd: string;
304 readonly host: string;
305 }) => Effect.Effect<string, PullRequestProviderError>;
306​
307 readonly listChangeRequests: (
308 input: ProviderRepositoryRef & {
309 readonly state: PullRequestListState;
310 readonly involvement: PullRequestInvolvement;
311 readonly viewer: string;
312 readonly limit: number;
313 /**
314 * Free text to narrow the listing by, as the host understands it. A host with no text
315 * filter of its own ignores it and answers with the page it would have answered with
316 * anyway — the caller narrows what it gets, so an unfiltered page is a wider answer
317 * rather than a wrong one.
318 */
319 readonly query?: string | undefined;
320 /**
321 * Where to carry on from, rather than reading this repository from its newest row. Absent
322 * asks for the first slice, which is every listing that has not been continued.
323 */
324 readonly cursor?: ProviderListCursor | undefined;
325 /**
326 * Further narrowings, which a host applies as far as it can and ignores the rest of —
327 * an unnarrowed page is a wider answer rather than a wrong one, and the caller narrows
328 * what it gets for the fields a row carries.
329 */
330 readonly filters?: PullRequestListFilters | undefined;
331 },
332 ) => Effect.Effect<ProviderChangeRequestPage, PullRequestProviderError>;
333​
334 /**
335 * The same listing for a whole host in one request, for a host that has a search across
336 * repositories. Optional: three of the four hosts here have no such API, and breaking the port
337 * for them to spare GitHub a fan-out would be paying for the fix with everyone else's clarity.
338 * The caller falls back to `listChangeRequests` per repository where this is absent, and where
339 * it fails.
340 *
341 * `limit` is the whole slice rather than a size per repository, because that is the shape of
342 * the answer: the newest `limit` rows across every repository named, which is exactly the rows
343 * a page ordered by update shows.
344 *
345 * `cursor` is one boundary for all of them, so a caller with repositories standing at different
346 * boundaries asks in groups rather than in one call.
347 */
348 readonly listChangeRequestsAcross?: (input: {
349 /** Any checkout on the host, which is what the tool is run in. */
350 readonly cwd: string;
351 readonly host: string;
352 readonly repositories: ReadonlyArray<string>;
353 readonly state: PullRequestListState;
354 readonly involvement: PullRequestInvolvement;
355 readonly viewer: string;
356 readonly limit: number;
357 readonly query?: string | undefined;
358 readonly cursor?: ProviderListCursor | undefined;
359 readonly filters?: PullRequestListFilters | undefined;
360 }) => Effect.Effect<ProviderBatchedChangeRequestPage, PullRequestProviderError>;
361​
362 /**
363 * The line counts for rows a listing has already handed over. Only implemented by a provider
364 * whose listing leaves them out — for everyone else the numbers arrived with the row, and the
365 * caller has nothing to ask for.
366 */
367 readonly listChangeRequestStats?: (input: {
368 readonly cwd: string;
369 readonly host: string;
370 readonly changeRequests: ReadonlyArray<{
371 readonly repository: string;
372 readonly number: number;
373 }>;
374 }) => Effect.Effect<ReadonlyArray<ProviderChangeRequestStat>, PullRequestProviderError>;
375​
376 readonly getChangeRequest: (
377 input: ProviderRepositoryRef & { readonly number: number },
378 ) => Effect.Effect<ProviderChangeRequestDetail, PullRequestProviderError>;
379​
380 /**
381 * The cheap live fields used by linked threads. Optional because a provider without a narrow
382 * endpoint can fall back to its full detail read at the service boundary.
383 */
384 readonly getChangeRequestSummary?: (
385 input: ProviderRepositoryRef & { readonly number: number },
386 ) => Effect.Effect<ProviderChangeRequestSummary, PullRequestProviderError>;
387​
388 /**
389 * The host-native stack a change request belongs to, or null when it is not stacked. Optional
390 * because most hosts have no such object; the service derives chains from base branches there.
391 */
392 readonly getChangeRequestStack?: (
393 input: ProviderRepositoryRef & { readonly includeDetails?: boolean; readonly number: number },
394 ) => Effect.Effect<ProviderChangeRequestStack | null, PullRequestProviderError>;
395​
396 /** Comments, line threads, and commits, kept off the critical path for the core detail. */
397 readonly getChangeRequestActivity: (
398 input: ProviderRepositoryRef & { readonly number: number },
399 ) => Effect.Effect<ProviderChangeRequestActivity, PullRequestProviderError>;
400​
401 /** One explicit page after a reader asks to continue an unfinished review thread. */
402 readonly getReviewThreadComments?: (
403 input: ProviderRepositoryRef & {
404 readonly number: number;
405 readonly threadId: string;
406 readonly cursor: string;
407 },
408 ) => Effect.Effect<PullRequestThreadCommentsResult, PullRequestProviderError>;
409​
410 /**
411 * The same answer `getChangeRequest` carries, on its own. Asked before anything is written, so
412 * a request that reached the server without going past the page is refused by what the host
413 * says rather than by what the client claimed — and asked freshly, because access granted or
414 * taken away since the page loaded is exactly the case this guards.
415 *
416 * Implementations read the cheapest thing that answers it, which for a host with nothing to say
417 * is no request at all.
418 */
419 readonly getViewerPermissions: (
420 input: ProviderRepositoryRef & {
421 readonly number: number;
422 /** Skip branch comparison when checking permission for an unrelated operation. */
423 readonly includeUpdateBranch?: boolean;
424 },
425 ) => Effect.Effect<PullRequestViewerPermissions, PullRequestProviderError>;
426​
427 /**
428 * One slice of the patch. Only called when `capabilities.diff` is true. A provider that can
429 * serve the whole diff at once answers with `nextCursor: null` and is done; one that pages
430 * hands back whatever it needs to find the next slice.
431 */
432 readonly getDiff: (
433 input: ProviderRepositoryRef & {
434 readonly number: number;
435 readonly cursor?: string | undefined;
436 /** One commit's own changes, rather than everything the change request carries. */
437 readonly commit?: string | undefined;
438 },
439 ) => Effect.Effect<ProviderDiffSlice, PullRequestProviderError>;
440​
441 /**
442 * Full files at the exact revisions the host used for its patch. Optional where the provider
443 * exposes no diff at all; the service refuses expansion there just as it refuses the patch.
444 */
445 readonly getDiffFileContents?: (
446 input: ProviderRepositoryRef & {
447 readonly number: number;
448 readonly commit?: string | undefined;
449 readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted";
450 readonly oldPath: string;
451 readonly newPath: string;
452 },
453 ) => Effect.Effect<ProviderDiffFileContents, PullRequestProviderError>;
454​
455 readonly runAction: (
456 input: ProviderRepositoryRef & {
457 readonly number: number;
458 readonly action: PullRequestAction;
459 readonly stackNumber?: number;
460 readonly expectedStackHeads?: ReadonlyArray<PullRequestStackHead>;
461 /** Meaningful for `merge` and `enable-auto-merge`; absent takes the host's own default. */
462 readonly mergeMethod?: PullRequestMergeMethod;
463 /** Only meaningful for `update-branch`; absent takes the host's own default. */
464 readonly updateMethod?: PullRequestUpdateMethod;
465 },
466 ) => Effect.Effect<void, PullRequestProviderError>;
467​
468 /**
469 * Rewrites the change request's own words. Only called when `capabilities.edit.changeRequest`
470 * is true, and never with both fields absent — the caller refuses that before it gets here,
471 * because a host asked to change nothing answers differently on each of them.
472 */
473 readonly updateChangeRequest?: (
474 input: ProviderRepositoryRef & {
475 readonly number: number;
476 readonly title?: string | undefined;
477 readonly body?: string | undefined;
478 },
479 ) => Effect.Effect<void, PullRequestProviderError>;
480​
481 readonly comment: (
482 input: ProviderRepositoryRef & { readonly number: number; readonly body: string },
483 ) => Effect.Effect<void, PullRequestProviderError>;
484​
485 /**
486 * Rewrites a remark somebody already posted. Only called when `capabilities.edit.comment` is
487 * true, with an id exactly as the conversation carried it.
488 *
489 * Whether this remark is the reader's to rewrite is the host's own answer: no read here can
490 * settle it, since access can be taken away between the conversation being read and the
491 * rewrite being sent, and a host refuses a stranger's remark with a sentence saying so.
492 */
493 readonly updateComment?: (
494 input: ProviderRepositoryRef & {
495 readonly number: number;
496 readonly commentId: string;
497 readonly kind: "issue-comment" | "review-comment";
498 readonly body: string;
499 },
500 ) => Effect.Effect<void, PullRequestProviderError>;
501​
502 /**
503 * Sends a whole review at once. Only called for a verdict the host declared in
504 * `capabilities.review.verdicts`, and with line comments only where it declared
505 * `inlineComment`.
506 */
507 readonly submitReview: (
508 input: ProviderRepositoryRef & {
509 readonly number: number;
510 readonly verdict: PullRequestReviewVerdict;
511 readonly body: string;
512 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
513 },
514 ) => Effect.Effect<void, PullRequestProviderError>;
515​
516 /**
517 * The people this viewer may ask for a review, with whoever has already been asked marked as
518 * such. Only called when `capabilities.reviewers.listCandidates` is true.
519 *
520 * The author is left out by each provider rather than by the caller, because only the provider
521 * knows how the host spells the same person in a candidate list and on a pull request.
522 */
523 readonly listReviewerCandidates: (
524 input: ProviderRepositoryRef & { readonly number: number },
525 ) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestProviderError>;
526​
527 /**
528 * Asks for a review, or takes the request back. Only called when
529 * `capabilities.reviewers.request` is true.
530 *
531 * One call for both directions, because that is what every host does with them: GitHub posts and
532 * deletes the same collection, and GitLab and Bitbucket write the whole reviewer set either way.
533 * Asking again somebody who has already reviewed is a request like any other — which is how a
534 * re-request is made.
535 */
536 readonly setReviewerRequest: (
537 input: ProviderRepositoryRef & {
538 readonly number: number;
539 readonly reviewers: ReadonlyArray<{
540 readonly id: string;
541 readonly kind: PullRequestReviewerKind;
542 }>;
543 readonly requested: boolean;
544 },
545 ) => Effect.Effect<void, PullRequestProviderError>;
546​
547 /**
548 * The repository's labels, with the ones already on the change request marked. Present with
549 * `setLabels` only where `capabilities.labels` is true; the service refuses both without it.
550 */
551 readonly listLabelCandidates?: (
552 input: ProviderRepositoryRef & { readonly number: number },
553 ) => Effect.Effect<PullRequestLabelCandidateList, PullRequestProviderError>;
554​
555 /** Puts labels on the change request, or takes them off. One call for both directions. */
556 readonly setLabels?: (
557 input: ProviderRepositoryRef & {
558 readonly number: number;
559 readonly labels: ReadonlyArray<string>;
560 readonly applied: boolean;
561 },
562 ) => Effect.Effect<void, PullRequestProviderError>;
563​
564 /** Only called when `capabilities.review.reply` is true. */
565 readonly replyToThread: (
566 input: ProviderRepositoryRef & {
567 readonly number: number;
568 readonly threadId: string;
569 readonly body: string;
570 },
571 ) => Effect.Effect<void, PullRequestProviderError>;
572​
573 /**
574 * Adds a reaction, or takes it back. Only called when `capabilities.reactions` is true.
575 *
576 * `subjectId` is a remark's id as the conversation carried it; absent means the change request
577 * itself, whose reactions sit on its description. Whatever a host needs to address either of
578 * them is worked out here, because the id a conversation travels with is the one the reader has.
579 */
580 readonly setReaction: (
581 input: ProviderRepositoryRef & {
582 readonly number: number;
583 readonly subjectId?: string | undefined;
584 readonly content: PullRequestReactionContent;
585 readonly reacted: boolean;
586 },
587 ) => Effect.Effect<void, PullRequestProviderError>;
588​
589 /** Only called when `capabilities.review.resolve` is true. */
590 readonly setThreadResolution: (
591 input: ProviderRepositoryRef & {
592 readonly number: number;
593 readonly threadId: string;
594 readonly resolved: boolean;
595 },
596 ) => Effect.Effect<void, PullRequestProviderError>;