Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Redacted from "effect/Redacted";
5import * as TestClock from "effect/testing/TestClock";
6import type { PullRequestReaction } from "@t3tools/contracts";
7
8import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
9import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
10import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
11import type {
12 GitHubPullRequestCore,
13 GitHubPullRequestSearchItem,
14} from "./gitHubPullRequestJson.ts";
15import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
16import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
17
18const coreFields = {
19 maintainerCanModify: true,
20 canEditMaintainerEdits: false,
21 reviewRequestTeams: [],
22 checksTruncated: false,
23 comparison: { behindBy: 0, viewerCanUpdate: true },
24 viewerAccess: {
25 canWrite: true,
26 canTriage: true,
27 canUpdate: true,
28 didAuthor: false,
29 mergeCapabilities: { merge: true, squash: true, rebase: true },
30 autoMergeAllowed: true,
31 },
32};
33
34it.effect("maps credential verification failures without relabeling operation failures", () =>
35 Effect.gen(function* () {
36 let verificationFails = true;
37 let operations = 0;
38 const provider = yield* make.pipe(
39 Effect.provide(
40 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
41 revalidateChecks: (_input, read) => read,
42 withVerifiedCredential: (_input, use) =>
43 verificationFails
44 ? Effect.fail(
45 new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({
46 cwd: "/w",
47 }),
48 )
49 : use({ accountId: "123", viewer: "viewer", credentialFingerprint: "fingerprint" }),
50 }),
51 ),
52 );
53 const verify = provider.withVerifiedCredential;
54 if (verify === undefined)
55 return yield* Effect.die("credential verification was not implemented");
56 const input = { cwd: "/w", host: "github.com" };
57 const operation = () =>
58 Effect.sync(() => {
59 operations++;
60 }).pipe(Effect.andThen(Effect.fail("operation-failed")));
61 expect(yield* verify(input, operation).pipe(Effect.flip)).toMatchObject({
62 _tag: "PullRequestProviderError",
63 operation: "routeIdentity",
64 });
65 expect(operations).toBe(0);
66 verificationFails = false;
67 expect(yield* verify(input, operation).pipe(Effect.flip)).toBe("operation-failed");
68 expect(operations).toBe(1);
69 }),
70);
71
72it.effect.each([
73 { status: 403, githubErrorTypes: [], reason: "forbidden" },
74 { status: 503, githubErrorTypes: [], reason: "failed" },
75 { status: 200, githubErrorTypes: ["FORBIDDEN"], reason: "forbidden" },
76 { status: 200, githubErrorTypes: ["INTERNAL"], reason: "failed" },
77 { status: 200, githubErrorTypes: ["FORBIDDEN", "NOT_FOUND"], reason: "forbidden" },
78 { status: 200, githubErrorTypes: ["FORBIDDEN", "INTERNAL"], reason: "failed" },
79 { status: 200, githubErrorTypes: ["FORBIDDEN", null], reason: "failed" },
80])("classifies GitHub response $status as $reason", ({ status, githubErrorTypes, reason }) =>
81 Effect.gen(function* () {
82 const provider = yield* make.pipe(
83 Effect.provide(
84 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
85 revalidateChecks: (_input, read) => read,
86 getPullRequestDetail: () =>
87 Effect.fail(
88 new GitHubRequestPolicy.GitHubApiResponseError({
89 host: "github.com",
90 operation: "detail",
91 status,
92 githubErrorTypes,
93 }),
94 ),
95 }),
96 ),
97 );
98 const error = yield* provider
99 .getChangeRequest({
100 cwd: "/w",
101 repository: "acme/web",
102 host: "github.com",
103 number: 7,
104 })
105 .pipe(Effect.flip);
106 expect(error.reason).toBe(reason);
107 }),
108);
109
110it.effect("advertises standalone branch deletion for source repository writers", () =>
111 Effect.gen(function* () {
112 let action: string | undefined;
113 const provider = yield* make.pipe(
114 Effect.provide(
115 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
116 runPullRequestAction: (input) =>
117 Effect.sync(() => {
118 action = input.action;
119 }),
120 }),
121 ),
122 );
123 expect(provider.capabilities.deleteBranch).toBe(true);
124 expect(provider.capabilities.actions).toContain("delete-branch");
125 yield* provider.runAction({
126 cwd: "/w",
127 repository: "acme/web",
128 host: "github.com",
129 number: 7,
130 action: "delete-branch",
131 });
132 expect(action).toBe("delete-branch");
133 const access = {
134 canWrite: false,
135 canTriage: false,
136 canUpdate: false,
137 didAuthor: false,
138 canDeleteBranch: true,
139 autoMergeAllowed: true,
140 };
141 expect(gitHubViewerPermissions(access).actions).toContain("delete-branch");
142 expect(
143 gitHubViewerPermissions({
144 ...access,
145 canWrite: true,
146 didAuthor: true,
147 canDeleteBranch: false,
148 }).actions,
149 ).not.toContain("delete-branch");
150 }),
151);
152
153describe("gitHubViewerPermissions", () => {
154 it("offers everything to a viewer who can write to the repository", () => {
155 expect(
156 gitHubViewerPermissions({
157 canWrite: true,
158 canDeleteBranch: true,
159 canTriage: true,
160 canUpdate: true,
161 didAuthor: false,
162 autoMergeAllowed: true,
163 }),
164 ).toEqual({
165 actions: [
166 "delete-branch",
167 "merge",
168 "enable-auto-merge",
169 "disable-auto-merge",
170 "revert",
171 "approve-workflows",
172 "ready",
173 "draft",
174 "close",
175 "reopen",
176 ],
177 comment: true,
178 resolve: true,
179 stackRebase: true,
180 verdicts: ["comment", "approve", "request-changes"],
181 requestReviewers: true,
182 labels: true,
183 });
184 });
185
186 it("leaves a passer-by on a repository they can only read nothing but the review", () => {
187 expect(
188 gitHubViewerPermissions({
189 canWrite: false,
190 canTriage: false,
191 canUpdate: false,
192 didAuthor: false,
193 autoMergeAllowed: true,
194 }),
195 ).toEqual({
196 actions: [],
197 comment: true,
198 resolve: false,
199 verdicts: ["comment", "approve", "request-changes"],
200 requestReviewers: false,
201 labels: false,
202 });
203 });
204
205 it("lets a triager label without letting them merge or ask for a review", () => {
206 const permissions = gitHubViewerPermissions({
207 canWrite: false,
208 canTriage: true,
209 canUpdate: false,
210 didAuthor: false,
211 autoMergeAllowed: true,
212 });
213 expect(permissions.labels).toBe(true);
214 expect(permissions.requestReviewers).toBe(false);
215 expect(permissions.actions).toEqual([]);
216 });
217
218 it("keeps an author's own pull request theirs to close, with read access and no more", () => {
219 expect(
220 gitHubViewerPermissions({
221 canWrite: false,
222 canTriage: false,
223 canUpdate: true,
224 didAuthor: true,
225 autoMergeAllowed: true,
226 }),
227 ).toEqual({
228 actions: ["ready", "draft", "close", "reopen"],
229 comment: true,
230 resolve: true,
231 verdicts: ["comment"],
232 requestReviewers: false,
233 labels: false,
234 });
235 });
236
237 it.effect("uses the permissions carried by the core read without a second request", () =>
238 Effect.gen(function* () {
239 const provider = yield* make;
240 const detail = yield* provider.getChangeRequest({
241 cwd: "/w",
242 repository: "acme/web",
243 host: "github.com",
244 number: 7,
245 });
246
247 expect(detail.viewerPermissions).toEqual({
248 maintainerEdits: false,
249 actions: ["ready", "draft", "close", "reopen"],
250 comment: true,
251 resolve: false,
252 verdicts: ["comment", "approve", "request-changes"],
253 requestReviewers: false,
254 labels: false,
255 });
256 expect(detail.workflowApprovalsRequired).toBeUndefined();
257 expect(detail.checks).toContainEqual({
258 name: "Workflow approval status",
259 status: "action-required",
260 description: "GitHub could not determine whether workflows are awaiting approval.",
261 url: null,
262 });
263 for (const fingerprint of ["broad", "restricted", "broad"]) {
264 const scoped = yield* provider
265 .getChangeRequest({
266 cwd: "/w",
267 repository: "acme/web",
268 host: "github.com",
269 number: 7,
270 })
271 .pipe(
272 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
273 host: "github.com",
274 token: Redacted.make("credential"),
275 credentialFingerprint: fingerprint,
276 }),
277 );
278 expect(scoped.mergeCapabilities.squash).toBe(fingerprint !== "restricted");
279 }
280 }).pipe(
281 Effect.provide(
282 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
283 revalidateChecks: (_input, read) => read,
284 getPullRequestDetail: () =>
285 Effect.succeed({
286 ...coreFields,
287 comparison: null,
288 viewerAccess: { ...coreFields.viewerAccess, canWrite: false, canTriage: false },
289 number: 7,
290 title: "Pull request 7",
291 url: "https://github.com/acme/web/pull/7",
292 author: null,
293 isCrossRepository: true,
294 headRepositoryOwner: null,
295 headBranch: "feat/page",
296 baseBranch: "main",
297 state: "open" as const,
298 isDraft: false,
299 mergeability: "mergeable" as const,
300 reviewDecision: null,
301 additions: 1,
302 deletions: 1,
303 createdAt: "2026-07-01T00:00:00Z",
304 updatedAt: "2026-07-02T00:00:00Z",
305 reviewRequestLogins: [],
306 hasTeamReviewRequest: false,
307 checksState: null,
308 labels: [],
309 body: "",
310 changedFiles: 1,
311 mergedAt: null,
312 closedAt: null,
313 checks: [],
314 comments: [],
315 commits: [],
316 }).pipe(
317 Effect.flatMap((detail) =>
318 GitHubRequestPolicy.PinnedGitHubCredential.pipe(
319 Effect.map((credential) => ({
320 ...detail,
321 viewerAccess: {
322 ...detail.viewerAccess,
323 mergeCapabilities: {
324 ...detail.viewerAccess.mergeCapabilities,
325 squash: credential?.credentialFingerprint !== "restricted",
326 },
327 },
328 })),
329 ),
330 ),
331 ),
332 }),
333 ),
334 ),
335 );
336
337 it.effect("keeps fork workflows awaiting approval out of the passing state", () =>
338 Effect.gen(function* () {
339 const provider = yield* make;
340 const detail = yield* provider.getChangeRequest({
341 cwd: "/w",
342 repository: "acme/web",
343 host: "github.com",
344 number: 7,
345 });
346
347 const readChecks = provider.getChangeRequestChecks;
348 if (readChecks === undefined) return yield* Effect.die("checks read missing");
349 expect(
350 yield* readChecks({ cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }),
351 ).toEqual({ state: detail.state, checks: detail.checks });
352 expect(detail.workflowApprovalsRequired).toBe(1);
353 expect(detail.checks).toEqual([
354 {
355 name: "manual gate",
356 status: "action-required",
357 description: null,
358 url: "https://example.com/manual-gate",
359 },
360 {
361 name: "build",
362 status: "success",
363 description: null,
364 url: null,
365 },
366 {
367 name: "contributor tests",
368 status: "action-required",
369 description: "A maintainer must approve this workflow before it can run.",
370 url: "https://github.com/acme/web/actions/runs/123",
371 },
372 ]);
373 }).pipe(
374 Effect.provide(
375 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
376 revalidateChecks: (_input, read) => read,
377 getPullRequestDetail: () =>
378 Effect.succeed({
379 ...coreFields,
380 number: 7,
381 title: "Pull request 7",
382 url: "https://github.com/acme/web/pull/7",
383 author: null,
384 isCrossRepository: true,
385 headRepositoryOwner: "octocat",
386 headSha: "abc123",
387 headBranch: "feat/page",
388 baseBranch: "main",
389 state: "open",
390 isDraft: false,
391 mergeability: "mergeable",
392 reviewDecision: null,
393 additions: 1,
394 deletions: 1,
395 createdAt: "2026-07-01T00:00:00Z",
396 updatedAt: "2026-07-02T00:00:00Z",
397 reviewRequestLogins: [],
398 hasTeamReviewRequest: false,
399 checksState: "passing",
400 labels: [],
401 body: "",
402 changedFiles: 1,
403 mergedAt: null,
404 closedAt: null,
405 checks: [
406 {
407 name: "manual gate",
408 status: "action-required",
409 description: null,
410 url: "https://example.com/manual-gate",
411 },
412 { name: "build", status: "success", description: null, url: null },
413 ],
414 comments: [],
415 commits: [],
416 }),
417 listWorkflowRunsRequiringApproval: () =>
418 Effect.succeed([
419 {
420 id: 123,
421 name: "contributor tests",
422 url: "https://github.com/acme/web/actions/runs/123",
423 },
424 ]),
425 getViewerAccess: () =>
426 Effect.succeed({
427 canWrite: true,
428 canTriage: true,
429 canUpdate: true,
430 didAuthor: false,
431 mergeCapabilities: { merge: true, squash: true, rebase: true },
432 autoMergeAllowed: true,
433 }),
434 }),
435 ),
436 ),
437 );
438});
439
440const openDetail = {
441 ...coreFields,
442 number: 7,
443 title: "Pull request 7",
444 url: "https://github.com/acme/web/pull/7",
445 author: null,
446 isCrossRepository: true,
447 headRepositoryOwner: "acme",
448 headSha: "abc123",
449 headBranch: "feat/page",
450 baseBranch: "main",
451 state: "open" as const,
452 isDraft: false,
453 mergeability: "mergeable" as const,
454 reviewDecision: null,
455 additions: 1,
456 deletions: 1,
457 createdAt: "2026-07-01T00:00:00Z",
458 updatedAt: "2026-07-02T00:00:00Z",
459 reviewRequestLogins: [],
460 hasTeamReviewRequest: false,
461 checksState: null,
462 labels: [],
463 body: "",
464 changedFiles: 1,
465 mergedAt: null,
466 closedAt: null,
467 checks: [],
468 comments: [],
469 commits: [],
470};
471
472it.effect("does not classify same-repository gates as fork workflow approvals", () =>
473 Effect.gen(function* () {
474 const provider = yield* make;
475 const detail = yield* provider.getChangeRequest({
476 cwd: "/w",
477 repository: "acme/web",
478 host: "github.com",
479 number: 7,
480 });
481
482 expect(detail.workflowApprovalsRequired).toBe(0);
483 expect(detail.checks).toEqual([]);
484 }).pipe(
485 Effect.provide(
486 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
487 revalidateChecks: (_input, read) => read,
488 getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),
489 listWorkflowRunsRequiringApproval: () =>
490 Effect.die("same-repository pull requests must not probe fork workflow approvals"),
491 getViewerAccess: () =>
492 Effect.succeed({
493 canWrite: true,
494 canTriage: true,
495 canUpdate: true,
496 didAuthor: false,
497 mergeCapabilities: { merge: true, squash: true, rebase: true },
498 autoMergeAllowed: true,
499 }),
500 }),
501 ),
502 ),
503);
504
505it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
506 Effect.gen(function* () {
507 const provider = yield* make;
508 const detail = yield* provider.getChangeRequest({
509 cwd: "/w",
510 repository: "acme/web",
511 host: "github.com",
512 number: 7,
513 });
514
515 expect(detail.workflowApprovalsRequired).toBeUndefined();
516 expect(detail.checks).toEqual([
517 {
518 name: "Workflow approval status",
519 status: "action-required",
520 description: "GitHub could not determine whether workflows are awaiting approval.",
521 url: null,
522 },
523 ]);
524 }).pipe(
525 Effect.provide(
526 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
527 revalidateChecks: (_input, read) => read,
528 getPullRequestDetail: () => Effect.succeed(openDetail),
529 listWorkflowRunsRequiringApproval: () =>
530 Effect.fail(
531 new GitHubPullRequestApi.GitHubWorkflowApprovalRefusedError({
532 cwd: "/w",
533 number: 7,
534 reason: "head-not-unique",
535 observedCount: 2,
536 limit: 1_000,
537 }),
538 ),
539 getViewerAccess: () =>
540 Effect.succeed({
541 canWrite: true,
542 canTriage: true,
543 canUpdate: true,
544 didAuthor: false,
545 mergeCapabilities: { merge: true, squash: true, rebase: true },
546 autoMergeAllowed: true,
547 }),
548 }),
549 ),
550 ),
551);
552
553describe("getViewerPermissions", () => {
554 const access = {
555 canWrite: true,
556 canTriage: true,
557 canUpdate: true,
558 didAuthor: false,
559 mergeCapabilities: { merge: true, squash: true, rebase: true },
560 autoMergeAllowed: true,
561 };
562
563 const layerWithDetail = (
564 detail: Effect.Effect<GitHubPullRequestCore, GitHubPullRequestApi.GitHubPullRequestApiError>,
565 onDetail: (allowReserve: boolean) => void = () => {},
566 ) =>
567 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
568 revalidateChecks: (_input, read) => read,
569 getPullRequestDetail: () =>
570 SourceControlRateLimit.Interactive.pipe(
571 Effect.tap((allowReserve) => Effect.sync(() => onDetail(allowReserve))),
572 Effect.flatMap(() => detail),
573 ),
574 getViewerAccess: () => Effect.die("Unexpected access read"),
575 });
576
577 it.effect("answers access and update-branch from the one detail read", () =>
578 Effect.gen(function* () {
579 const provider = yield* make;
580 const permissions = yield* provider.getViewerPermissions({
581 cwd: "/w",
582 repository: "acme/web",
583 host: "github.com",
584 number: 7,
585 });
586
587 expect(permissions.actions).toContain("merge");
588 expect(permissions.actions).toContain("update-branch");
589 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
590 }).pipe(
591 Effect.provide(
592 layerWithDetail(
593 Effect.succeed({ ...openDetail, comparison: { behindBy: 3, viewerCanUpdate: true } }),
594 ),
595 ),
596 ),
597 );
598
599 it.effect("still answers from the light access read when the detail read fails", () =>
600 Effect.gen(function* () {
601 const provider = yield* make;
602 const permissions = yield* provider.getViewerPermissions({
603 cwd: "/w",
604 repository: "acme/web",
605 host: "github.com",
606 number: 7,
607 });
608 expect(permissions.actions).toContain("merge");
609 expect(permissions.actions).not.toContain("update-branch");
610 }).pipe(
611 Effect.provide(
612 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
613 revalidateChecks: (_input, read) => read,
614 getPullRequestDetail: () =>
615 Effect.fail(
616 new GitHubPullRequestApi.GitHubPullRequestReadError({
617 cwd: "/w",
618 operation: "getPullRequestDetail",
619 cause: new Error("head changed"),
620 }),
621 ),
622 getViewerAccess: () => Effect.succeed(access),
623 }),
624 ),
625 ),
626 );
627
628 it.effect("withholds update-branch where GitHub could not compare the branch", () =>
629 Effect.gen(function* () {
630 const provider = yield* make;
631 const permissions = yield* provider.getViewerPermissions({
632 cwd: "/w",
633 repository: "acme/web",
634 host: "github.com",
635 number: 7,
636 });
637
638 expect(permissions.actions).not.toContain("update-branch");
639 expect(permissions.updateMethods).toBeUndefined();
640 expect(permissions.actions).toContain("merge");
641 }).pipe(Effect.provide(layerWithDetail(Effect.succeed({ ...openDetail, comparison: null })))),
642 );
643});
644
645describe("getChangeRequest commits", () => {
646 const baseDetail = {
647 number: 7,
648 title: "Pull request 7",
649 url: "https://github.com/acme/web/pull/7",
650 author: null,
651 headBranch: "feat/page",
652 baseBranch: "main",
653 state: "open" as const,
654 isDraft: false,
655 mergeability: "mergeable" as const,
656 additions: 1,
657 deletions: 1,
658 createdAt: "2026-07-01T00:00:00Z",
659 updatedAt: "2026-07-02T00:00:00Z",
660 reviewRequestLogins: [],
661 hasTeamReviewRequest: false,
662 checksState: null,
663 labels: [],
664 body: "",
665 changedFiles: 1,
666 mergedAt: null,
667 closedAt: null,
668 checks: [],
669 comments: [],
670 };
671
672 const baseThreadComments = {
673 comments: [],
674 dismissalsByReviewId: new Map<string, string>(),
675 reviewThreads: [],
676 commentCount: 0,
677 truncated: false,
678 reviewThreadsTruncated: false,
679 reactions: [],
680 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
681 editedAtById: new Map<string, string>(),
682 reviewers: [],
683 avatarsByLogin: new Map<string, string>(),
684 botLogins: new Set<string>(),
685 viewer: { canUpdate: true, didAuthor: false },
686 };
687
688 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
689 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
690 revalidateChecks: (_input, read) => read,
691 getPullRequestActivity: () =>
692 Effect.succeed({
693 author: baseDetail.author,
694 comments: baseDetail.comments,
695 commits: [
696 {
697 oid: "graphql-newest",
698 messageHeadline: "Activity metadata",
699 committedDate: "2026-07-06T00:00:00Z",
700 additions: 18,
701 deletions: 7,
702 authors: [],
703 },
704 {
705 oid: "view-oldest",
706 messageHeadline: "gh pr view's oldest commit",
707 committedDate: "2026-01-01T00:00:00Z",
708 authors: [],
709 },
710 ],
711 }),
712 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
713 });
714
715 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
716 Effect.gen(function* () {
717 const provider = yield* make;
718 const detail = yield* provider.getChangeRequestActivity({
719 cwd: "/w",
720 repository: "acme/web",
721 host: "github.com",
722 number: 7,
723 });
724
725 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
726 expect(detail.commits[0]).toMatchObject({
727 messageHeadline: "the newest commit gh pr view drops",
728 additions: 18,
729 deletions: 7,
730 });
731 }).pipe(
732 Effect.provide(
733 layerWith([
734 {
735 oid: "graphql-newest",
736 messageHeadline: "the newest commit gh pr view drops",
737 committedDate: "2026-07-06T00:00:00Z",
738 authors: [],
739 },
740 ]),
741 ),
742 ),
743 );
744
745 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
746 Effect.gen(function* () {
747 const provider = yield* make;
748 const detail = yield* provider.getChangeRequestActivity({
749 cwd: "/w",
750 repository: "acme/web",
751 host: "github.com",
752 number: 7,
753 });
754
755 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest", "view-oldest"]);
756 }).pipe(Effect.provide(layerWith([]))),
757 );
758});
759
760describe("getChangeRequestActivity dismissed reviews", () => {
761 const dismissedReview = (body: string) => ({
762 id: "PRR_1",
763 kind: "review" as const,
764 author: { login: "macroscopeapp", name: null, avatarUrl: null },
765 body,
766 createdAt: "2026-07-03T00:00:00Z",
767 url: null,
768 path: null,
769 reviewState: "DISMISSED",
770 });
771 const threadComments: GitHubReviewThreadComments = {
772 comments: [],
773 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
774 reviewThreads: [],
775 commentCount: 0,
776 truncated: false,
777 reviewThreadsTruncated: false,
778 reactions: [],
779 reactionsById: new Map(),
780 editedAtById: new Map([["PRR_1", "2026-07-04T00:00:00Z"]]),
781 reviewers: [],
782 avatarsByLogin: new Map(),
783 botLogins: new Set(["macroscopeapp"]),
784 commits: [],
785 viewer: { canUpdate: true, didAuthor: false },
786 };
787 const layerFor = (body: string) =>
788 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
789 revalidateChecks: (_input, read) => read,
790 getPullRequestActivity: () =>
791 Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
792 listReviewThreadComments: () => Effect.succeed(threadComments),
793 });
794 const readActivity = Effect.gen(function* () {
795 const provider = yield* make;
796 return yield* provider.getChangeRequestActivity({
797 cwd: "/w",
798 repository: "acme/web",
799 host: "github.com",
800 number: 7,
801 });
802 });
803
804 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
805 readActivity.pipe(
806 Effect.map((activity) => {
807 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
808 expect(activity.comments[0]?.author?.isBot).toBe(true);
809 expect(activity.comments[0]?.editedAt).toBe("2026-07-04T00:00:00Z");
810 }),
811 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
812 ),
813 );
814});
815
816describe("loginAvatarUrl", () => {
817 it("refuses anything that is not a login, rather than building a URL out of it", () => {
818 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
819 expect(loginAvatarUrl(login, "github.com")).toBeNull();
820 }
821 });
822});
823
824describe("listChangeRequestsAcross", () => {
825 const searched = (repository: string): GitHubPullRequestSearchItem => ({
826 repository,
827 number: 1,
828 title: "Change",
829 url: `https://github.com/${repository}/pull/1`,
830 author: null,
831 headBranch: "feature",
832 baseBranch: "main",
833 state: "open" as const,
834 isDraft: false,
835 mergeability: "mergeable" as const,
836 additions: 0,
837 deletions: 0,
838 createdAt: "2026-07-01T00:00:00Z",
839 updatedAt: "2026-07-02T00:00:00Z",
840 reviewRequestLogins: [],
841 hasTeamReviewRequest: false,
842 labels: [],
843 reviewDecision: null,
844 checksState: null,
845 });
846 const across = {
847 cwd: "/w",
848 host: "github.com",
849 repositories: ["acme/web", "acme/docs"],
850 state: "open" as const,
851 involvement: "all" as const,
852 viewer: "viewer",
853 limit: 50,
854 };
855 type Search = Parameters<
856 GitHubPullRequestApi.GitHubPullRequestApi["Service"]["searchPullRequests"]
857 >[0];
858 // Pages answer in turn; a one-repository check for any pull request answers from `covered`.
859 const providerAnswering = (input: {
860 readonly pages: Array<GitHubPullRequestApi.GitHubPullRequestSearchBatch>;
861 readonly covered?: (repository: string) => boolean;
862 readonly checks?: Array<string>;
863 }) =>
864 make.pipe(
865 Effect.provide(
866 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
867 searchPullRequests: (search: Search) => {
868 if (search.state !== "all") return Effect.succeed(input.pages.shift()!);
869 const repository = search.repositories[0]!;
870 input.checks?.push(repository);
871 return input.covered === undefined
872 ? Effect.fail(
873 new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({ cwd: search.cwd }),
874 )
875 : Effect.succeed({
876 items: input.covered(repository) ? [searched(repository)] : [],
877 truncated: false,
878 });
879 },
880 }),
881 ),
882 Effect.map((provider) => provider.listChangeRequestsAcross!),
883 );
884
885 it.effect("believes silence about a repository search covers, and checks it once", () =>
886 Effect.gen(function* () {
887 const checks: Array<string> = [];
888 const read = yield* providerAnswering({
889 pages: [
890 { items: [searched("acme/web")], truncated: false },
891 { items: [searched("acme/web")], truncated: false },
892 ],
893 covered: () => true,
894 checks,
895 });
896 expect((yield* read(across)).unresolved).toEqual([]);
897 expect((yield* read(across)).unresolved).toEqual([]);
898 expect(checks).toEqual(["acme/docs"]);
899 }),
900 );
901
902 it.effect("leaves a repository search does not cover to be read on its own", () =>
903 Effect.gen(function* () {
904 const read = yield* providerAnswering({
905 pages: [{ items: [searched("acme/web")], truncated: false }],
906 covered: (repository) => repository !== "acme/docs",
907 });
908 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
909 }),
910 );
911
912 it.effect("does not check a repository a page had rows for", () =>
913 Effect.gen(function* () {
914 const checks: Array<string> = [];
915 const read = yield* providerAnswering({
916 pages: [
917 { items: [searched("acme/web"), searched("acme/docs")], truncated: false },
918 { items: [searched("acme/web")], truncated: false },
919 ],
920 covered: () => true,
921 checks,
922 });
923 yield* read(across);
924 expect((yield* read(across)).unresolved).toEqual([]);
925 expect(checks).toEqual([]);
926 }),
927 );
928
929 it.effect("vouches for no silent repository in a truncated first slice", () =>
930 Effect.gen(function* () {
931 const read = yield* providerAnswering({
932 pages: [{ items: [searched("acme/web")], truncated: true }],
933 covered: () => true,
934 });
935 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
936 }),
937 );
938
939 it.effect("past the first slice, believes a covered repository and not an uncovered one", () =>
940 Effect.gen(function* () {
941 const read = yield* providerAnswering({
942 pages: [
943 { items: [searched("acme/web")], truncated: true },
944 { items: [searched("acme/web")], truncated: true },
945 ],
946 covered: (repository) => repository !== "acme/renamed",
947 });
948 const later = { ...across, cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 1 } };
949 expect((yield* read(later)).unresolved).toEqual([]);
950 expect(
951 (yield* read({ ...later, repositories: ["acme/web", "acme/renamed"] })).unresolved,
952 ).toEqual(["acme/renamed"]);
953 }),
954 );
955
956 it.effect("asks again after a failed check, and after coverage has had time to change", () =>
957 Effect.gen(function* () {
958 const checks: Array<string> = [];
959 const failing = yield* providerAnswering({
960 pages: [
961 { items: [searched("acme/web")], truncated: false },
962 { items: [searched("acme/web")], truncated: false },
963 ],
964 checks,
965 });
966 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
967 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
968 expect(checks).toEqual(["acme/docs", "acme/docs"]);
969
970 checks.length = 0;
971 const read = yield* providerAnswering({
972 pages: [
973 { items: [searched("acme/web")], truncated: false },
974 { items: [searched("acme/web")], truncated: false },
975 ],
976 covered: () => true,
977 checks,
978 });
979 yield* read(across);
980 yield* TestClock.adjust("61 minutes");
981 yield* read(across);
982 expect(checks).toEqual(["acme/docs", "acme/docs"]);
983 }),
984 );
985});