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 placeholder: true,
263 });
264 for (const fingerprint of ["broad", "restricted", "broad"]) {
265 const scoped = yield* provider
266 .getChangeRequest({
267 cwd: "/w",
268 repository: "acme/web",
269 host: "github.com",
270 number: 7,
271 })
272 .pipe(
273 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
274 host: "github.com",
275 token: Redacted.make("credential"),
276 credentialFingerprint: fingerprint,
277 }),
278 );
279 expect(scoped.mergeCapabilities.squash).toBe(fingerprint !== "restricted");
280 }
281 }).pipe(
282 Effect.provide(
283 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
284 revalidateChecks: (_input, read) => read,
285 getPullRequestDetail: () =>
286 Effect.succeed({
287 ...coreFields,
288 comparison: null,
289 viewerAccess: { ...coreFields.viewerAccess, canWrite: false, canTriage: false },
290 number: 7,
291 title: "Pull request 7",
292 url: "https://github.com/acme/web/pull/7",
293 author: null,
294 isCrossRepository: true,
295 headRepositoryOwner: null,
296 headBranch: "feat/page",
297 baseBranch: "main",
298 state: "open" as const,
299 isDraft: false,
300 mergeability: "mergeable" as const,
301 reviewDecision: null,
302 additions: 1,
303 deletions: 1,
304 createdAt: "2026-07-01T00:00:00Z",
305 updatedAt: "2026-07-02T00:00:00Z",
306 reviewRequestLogins: [],
307 hasTeamReviewRequest: false,
308 checksState: null,
309 labels: [],
310 body: "",
311 changedFiles: 1,
312 mergedAt: null,
313 closedAt: null,
314 checks: [],
315 comments: [],
316 commits: [],
317 }).pipe(
318 Effect.flatMap((detail) =>
319 GitHubRequestPolicy.PinnedGitHubCredential.pipe(
320 Effect.map((credential) => ({
321 ...detail,
322 viewerAccess: {
323 ...detail.viewerAccess,
324 mergeCapabilities: {
325 ...detail.viewerAccess.mergeCapabilities,
326 squash: credential?.credentialFingerprint !== "restricted",
327 },
328 },
329 })),
330 ),
331 ),
332 ),
333 }),
334 ),
335 ),
336 );
337
338 it.effect("keeps fork workflows awaiting approval out of the passing state", () =>
339 Effect.gen(function* () {
340 const provider = yield* make;
341 const detail = yield* provider.getChangeRequest({
342 cwd: "/w",
343 repository: "acme/web",
344 host: "github.com",
345 number: 7,
346 });
347
348 const readChecks = provider.getChangeRequestChecks;
349 if (readChecks === undefined) return yield* Effect.die("checks read missing");
350 expect(
351 yield* readChecks({ cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }),
352 ).toEqual({ state: detail.state, checks: detail.checks });
353 expect(detail.workflowApprovalsRequired).toBe(1);
354 expect(detail.checks).toEqual([
355 {
356 name: "manual gate",
357 status: "action-required",
358 description: null,
359 url: "https://example.com/manual-gate",
360 },
361 {
362 name: "build",
363 status: "success",
364 description: null,
365 url: null,
366 },
367 {
368 name: "contributor tests",
369 status: "action-required",
370 description: "A maintainer must approve this workflow before it can run.",
371 url: "https://github.com/acme/web/actions/runs/123",
372 },
373 ]);
374 }).pipe(
375 Effect.provide(
376 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
377 revalidateChecks: (_input, read) => read,
378 getPullRequestDetail: () =>
379 Effect.succeed({
380 ...coreFields,
381 number: 7,
382 title: "Pull request 7",
383 url: "https://github.com/acme/web/pull/7",
384 author: null,
385 isCrossRepository: true,
386 headRepositoryOwner: "octocat",
387 headSha: "abc123",
388 headBranch: "feat/page",
389 baseBranch: "main",
390 state: "open",
391 isDraft: false,
392 mergeability: "mergeable",
393 reviewDecision: null,
394 additions: 1,
395 deletions: 1,
396 createdAt: "2026-07-01T00:00:00Z",
397 updatedAt: "2026-07-02T00:00:00Z",
398 reviewRequestLogins: [],
399 hasTeamReviewRequest: false,
400 checksState: "passing",
401 labels: [],
402 body: "",
403 changedFiles: 1,
404 mergedAt: null,
405 closedAt: null,
406 checks: [
407 {
408 name: "manual gate",
409 status: "action-required",
410 description: null,
411 url: "https://example.com/manual-gate",
412 },
413 { name: "build", status: "success", description: null, url: null },
414 ],
415 comments: [],
416 commits: [],
417 }),
418 listWorkflowRunsRequiringApproval: () =>
419 Effect.succeed([
420 {
421 id: 123,
422 name: "contributor tests",
423 url: "https://github.com/acme/web/actions/runs/123",
424 },
425 ]),
426 getViewerAccess: () =>
427 Effect.succeed({
428 canWrite: true,
429 canTriage: true,
430 canUpdate: true,
431 didAuthor: false,
432 mergeCapabilities: { merge: true, squash: true, rebase: true },
433 autoMergeAllowed: true,
434 }),
435 }),
436 ),
437 ),
438 );
439});
440
441const openDetail = {
442 ...coreFields,
443 number: 7,
444 title: "Pull request 7",
445 url: "https://github.com/acme/web/pull/7",
446 author: null,
447 isCrossRepository: true,
448 headRepositoryOwner: "acme",
449 headSha: "abc123",
450 headBranch: "feat/page",
451 baseBranch: "main",
452 state: "open" as const,
453 isDraft: false,
454 mergeability: "mergeable" as const,
455 reviewDecision: null,
456 additions: 1,
457 deletions: 1,
458 createdAt: "2026-07-01T00:00:00Z",
459 updatedAt: "2026-07-02T00:00:00Z",
460 reviewRequestLogins: [],
461 hasTeamReviewRequest: false,
462 checksState: null,
463 labels: [],
464 body: "",
465 changedFiles: 1,
466 mergedAt: null,
467 closedAt: null,
468 checks: [],
469 comments: [],
470 commits: [],
471};
472
473it.effect("does not classify same-repository gates as fork workflow approvals", () =>
474 Effect.gen(function* () {
475 const provider = yield* make;
476 const detail = yield* provider.getChangeRequest({
477 cwd: "/w",
478 repository: "acme/web",
479 host: "github.com",
480 number: 7,
481 });
482
483 expect(detail.workflowApprovalsRequired).toBe(0);
484 expect(detail.checks).toEqual([]);
485 }).pipe(
486 Effect.provide(
487 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
488 revalidateChecks: (_input, read) => read,
489 getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),
490 listWorkflowRunsRequiringApproval: () =>
491 Effect.die("same-repository pull requests must not probe fork workflow approvals"),
492 getViewerAccess: () =>
493 Effect.succeed({
494 canWrite: true,
495 canTriage: true,
496 canUpdate: true,
497 didAuthor: false,
498 mergeCapabilities: { merge: true, squash: true, rebase: true },
499 autoMergeAllowed: true,
500 }),
501 }),
502 ),
503 ),
504);
505
506it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
507 Effect.gen(function* () {
508 const provider = yield* make;
509 const detail = yield* provider.getChangeRequest({
510 cwd: "/w",
511 repository: "acme/web",
512 host: "github.com",
513 number: 7,
514 });
515
516 expect(detail.workflowApprovalsRequired).toBeUndefined();
517 expect(detail.checks).toEqual([
518 {
519 name: "Workflow approval status",
520 status: "action-required",
521 description: "GitHub could not determine whether workflows are awaiting approval.",
522 url: null,
523 placeholder: true,
524 },
525 ]);
526 }).pipe(
527 Effect.provide(
528 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
529 revalidateChecks: (_input, read) => read,
530 getPullRequestDetail: () => Effect.succeed(openDetail),
531 listWorkflowRunsRequiringApproval: () =>
532 Effect.fail(
533 new GitHubPullRequestApi.GitHubWorkflowApprovalRefusedError({
534 cwd: "/w",
535 number: 7,
536 reason: "head-not-unique",
537 observedCount: 2,
538 limit: 1_000,
539 }),
540 ),
541 getViewerAccess: () =>
542 Effect.succeed({
543 canWrite: true,
544 canTriage: true,
545 canUpdate: true,
546 didAuthor: false,
547 mergeCapabilities: { merge: true, squash: true, rebase: true },
548 autoMergeAllowed: true,
549 }),
550 }),
551 ),
552 ),
553);
554
555describe("getViewerPermissions", () => {
556 const access = {
557 canWrite: true,
558 canTriage: true,
559 canUpdate: true,
560 didAuthor: false,
561 mergeCapabilities: { merge: true, squash: true, rebase: true },
562 autoMergeAllowed: true,
563 };
564
565 const layerWithDetail = (
566 detail: Effect.Effect<GitHubPullRequestCore, GitHubPullRequestApi.GitHubPullRequestApiError>,
567 onDetail: (allowReserve: boolean) => void = () => {},
568 ) =>
569 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
570 revalidateChecks: (_input, read) => read,
571 getPullRequestDetail: () =>
572 SourceControlRateLimit.Interactive.pipe(
573 Effect.tap((allowReserve) => Effect.sync(() => onDetail(allowReserve))),
574 Effect.flatMap(() => detail),
575 ),
576 getViewerAccess: () => Effect.die("Unexpected access read"),
577 });
578
579 it.effect("answers access and update-branch from the one detail read", () =>
580 Effect.gen(function* () {
581 const provider = yield* make;
582 const permissions = yield* provider.getViewerPermissions({
583 cwd: "/w",
584 repository: "acme/web",
585 host: "github.com",
586 number: 7,
587 });
588
589 expect(permissions.actions).toContain("merge");
590 expect(permissions.actions).toContain("update-branch");
591 expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
592 }).pipe(
593 Effect.provide(
594 layerWithDetail(
595 Effect.succeed({ ...openDetail, comparison: { behindBy: 3, viewerCanUpdate: true } }),
596 ),
597 ),
598 ),
599 );
600
601 it.effect("still answers from the light access read when the detail read fails", () =>
602 Effect.gen(function* () {
603 const provider = yield* make;
604 const permissions = yield* provider.getViewerPermissions({
605 cwd: "/w",
606 repository: "acme/web",
607 host: "github.com",
608 number: 7,
609 });
610 expect(permissions.actions).toContain("merge");
611 expect(permissions.actions).not.toContain("update-branch");
612 }).pipe(
613 Effect.provide(
614 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
615 revalidateChecks: (_input, read) => read,
616 getPullRequestDetail: () =>
617 Effect.fail(
618 new GitHubPullRequestApi.GitHubPullRequestReadError({
619 cwd: "/w",
620 operation: "getPullRequestDetail",
621 cause: new Error("head changed"),
622 }),
623 ),
624 getViewerAccess: () => Effect.succeed(access),
625 }),
626 ),
627 ),
628 );
629
630 it.effect("withholds update-branch where GitHub could not compare the branch", () =>
631 Effect.gen(function* () {
632 const provider = yield* make;
633 const permissions = yield* provider.getViewerPermissions({
634 cwd: "/w",
635 repository: "acme/web",
636 host: "github.com",
637 number: 7,
638 });
639
640 expect(permissions.actions).not.toContain("update-branch");
641 expect(permissions.updateMethods).toBeUndefined();
642 expect(permissions.actions).toContain("merge");
643 }).pipe(Effect.provide(layerWithDetail(Effect.succeed({ ...openDetail, comparison: null })))),
644 );
645});
646
647describe("getChangeRequest commits", () => {
648 const baseDetail = {
649 number: 7,
650 title: "Pull request 7",
651 url: "https://github.com/acme/web/pull/7",
652 author: null,
653 headBranch: "feat/page",
654 baseBranch: "main",
655 state: "open" as const,
656 isDraft: false,
657 mergeability: "mergeable" as const,
658 additions: 1,
659 deletions: 1,
660 createdAt: "2026-07-01T00:00:00Z",
661 updatedAt: "2026-07-02T00:00:00Z",
662 reviewRequestLogins: [],
663 hasTeamReviewRequest: false,
664 checksState: null,
665 labels: [],
666 body: "",
667 changedFiles: 1,
668 mergedAt: null,
669 closedAt: null,
670 checks: [],
671 comments: [],
672 };
673
674 const baseThreadComments = {
675 comments: [],
676 dismissalsByReviewId: new Map<string, string>(),
677 reviewThreads: [],
678 commentCount: 0,
679 truncated: false,
680 reviewThreadsTruncated: false,
681 reactions: [],
682 reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
683 editedAtById: new Map<string, string>(),
684 reviewers: [],
685 avatarsByLogin: new Map<string, string>(),
686 botLogins: new Set<string>(),
687 viewer: { canUpdate: true, didAuthor: false },
688 };
689
690 const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
691 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
692 revalidateChecks: (_input, read) => read,
693 getPullRequestActivity: () =>
694 Effect.succeed({
695 author: baseDetail.author,
696 comments: baseDetail.comments,
697 commits: [
698 {
699 oid: "graphql-newest",
700 messageHeadline: "Activity metadata",
701 committedDate: "2026-07-06T00:00:00Z",
702 additions: 18,
703 deletions: 7,
704 authors: [],
705 },
706 {
707 oid: "view-oldest",
708 messageHeadline: "gh pr view's oldest commit",
709 committedDate: "2026-01-01T00:00:00Z",
710 authors: [],
711 },
712 ],
713 }),
714 listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
715 });
716
717 it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
718 Effect.gen(function* () {
719 const provider = yield* make;
720 const detail = yield* provider.getChangeRequestActivity({
721 cwd: "/w",
722 repository: "acme/web",
723 host: "github.com",
724 number: 7,
725 });
726
727 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
728 expect(detail.commits[0]).toMatchObject({
729 messageHeadline: "the newest commit gh pr view drops",
730 additions: 18,
731 deletions: 7,
732 });
733 }).pipe(
734 Effect.provide(
735 layerWith([
736 {
737 oid: "graphql-newest",
738 messageHeadline: "the newest commit gh pr view drops",
739 committedDate: "2026-07-06T00:00:00Z",
740 authors: [],
741 },
742 ]),
743 ),
744 ),
745 );
746
747 it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
748 Effect.gen(function* () {
749 const provider = yield* make;
750 const detail = yield* provider.getChangeRequestActivity({
751 cwd: "/w",
752 repository: "acme/web",
753 host: "github.com",
754 number: 7,
755 });
756
757 expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest", "view-oldest"]);
758 }).pipe(Effect.provide(layerWith([]))),
759 );
760});
761
762describe("getChangeRequestActivity dismissed reviews", () => {
763 const dismissedReview = (body: string) => ({
764 id: "PRR_1",
765 kind: "review" as const,
766 author: { login: "macroscopeapp", name: null, avatarUrl: null },
767 body,
768 createdAt: "2026-07-03T00:00:00Z",
769 url: null,
770 path: null,
771 reviewState: "DISMISSED",
772 });
773 const threadComments: GitHubReviewThreadComments = {
774 comments: [],
775 dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
776 reviewThreads: [],
777 commentCount: 0,
778 truncated: false,
779 reviewThreadsTruncated: false,
780 reactions: [],
781 reactionsById: new Map(),
782 editedAtById: new Map([["PRR_1", "2026-07-04T00:00:00Z"]]),
783 reviewers: [],
784 avatarsByLogin: new Map(),
785 botLogins: new Set(["macroscopeapp"]),
786 commits: [],
787 viewer: { canUpdate: true, didAuthor: false },
788 };
789 const layerFor = (body: string) =>
790 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
791 revalidateChecks: (_input, read) => read,
792 getPullRequestActivity: () =>
793 Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
794 listReviewThreadComments: () => Effect.succeed(threadComments),
795 });
796 const readActivity = Effect.gen(function* () {
797 const provider = yield* make;
798 return yield* provider.getChangeRequestActivity({
799 cwd: "/w",
800 repository: "acme/web",
801 host: "github.com",
802 number: 7,
803 });
804 });
805
806 it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
807 readActivity.pipe(
808 Effect.map((activity) => {
809 expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
810 expect(activity.comments[0]?.author?.isBot).toBe(true);
811 expect(activity.comments[0]?.editedAt).toBe("2026-07-04T00:00:00Z");
812 }),
813 Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
814 ),
815 );
816});
817
818describe("loginAvatarUrl", () => {
819 it("refuses anything that is not a login, rather than building a URL out of it", () => {
820 for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
821 expect(loginAvatarUrl(login, "github.com")).toBeNull();
822 }
823 });
824});
825
826describe("listChangeRequestsAcross", () => {
827 const searched = (repository: string): GitHubPullRequestSearchItem => ({
828 repository,
829 number: 1,
830 title: "Change",
831 url: `https://github.com/${repository}/pull/1`,
832 author: null,
833 headBranch: "feature",
834 baseBranch: "main",
835 state: "open" as const,
836 isDraft: false,
837 mergeability: "mergeable" as const,
838 additions: 0,
839 deletions: 0,
840 createdAt: "2026-07-01T00:00:00Z",
841 updatedAt: "2026-07-02T00:00:00Z",
842 reviewRequestLogins: [],
843 hasTeamReviewRequest: false,
844 labels: [],
845 reviewDecision: null,
846 checksState: null,
847 });
848 const across = {
849 cwd: "/w",
850 host: "github.com",
851 repositories: ["acme/web", "acme/docs"],
852 state: "open" as const,
853 involvement: "all" as const,
854 viewer: "viewer",
855 limit: 50,
856 };
857 type Search = Parameters<
858 GitHubPullRequestApi.GitHubPullRequestApi["Service"]["searchPullRequests"]
859 >[0];
860 // Pages answer in turn; a one-repository check for any pull request answers from `covered`.
861 const providerAnswering = (input: {
862 readonly pages: Array<GitHubPullRequestApi.GitHubPullRequestSearchBatch>;
863 readonly covered?: (repository: string) => boolean;
864 readonly checks?: Array<string>;
865 }) =>
866 make.pipe(
867 Effect.provide(
868 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
869 searchPullRequests: (search: Search) => {
870 if (search.state !== "all") return Effect.succeed(input.pages.shift()!);
871 const repository = search.repositories[0]!;
872 input.checks?.push(repository);
873 return input.covered === undefined
874 ? Effect.fail(
875 new GitHubPullRequestApi.GitHubViewerLoginUnavailableError({ cwd: search.cwd }),
876 )
877 : Effect.succeed({
878 items: input.covered(repository) ? [searched(repository)] : [],
879 truncated: false,
880 });
881 },
882 }),
883 ),
884 Effect.map((provider) => provider.listChangeRequestsAcross!),
885 );
886
887 it.effect("believes silence about a repository search covers, and checks it once", () =>
888 Effect.gen(function* () {
889 const checks: Array<string> = [];
890 const read = yield* providerAnswering({
891 pages: [
892 { items: [searched("acme/web")], truncated: false },
893 { items: [searched("acme/web")], truncated: false },
894 ],
895 covered: () => true,
896 checks,
897 });
898 expect((yield* read(across)).unresolved).toEqual([]);
899 expect((yield* read(across)).unresolved).toEqual([]);
900 expect(checks).toEqual(["acme/docs"]);
901 }),
902 );
903
904 it.effect("leaves a repository search does not cover to be read on its own", () =>
905 Effect.gen(function* () {
906 const read = yield* providerAnswering({
907 pages: [{ items: [searched("acme/web")], truncated: false }],
908 covered: (repository) => repository !== "acme/docs",
909 });
910 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
911 }),
912 );
913
914 it.effect("does not check a repository a page had rows for", () =>
915 Effect.gen(function* () {
916 const checks: Array<string> = [];
917 const read = yield* providerAnswering({
918 pages: [
919 { items: [searched("acme/web"), searched("acme/docs")], truncated: false },
920 { items: [searched("acme/web")], truncated: false },
921 ],
922 covered: () => true,
923 checks,
924 });
925 yield* read(across);
926 expect((yield* read(across)).unresolved).toEqual([]);
927 expect(checks).toEqual([]);
928 }),
929 );
930
931 it.effect("vouches for no silent repository in a truncated first slice", () =>
932 Effect.gen(function* () {
933 const read = yield* providerAnswering({
934 pages: [{ items: [searched("acme/web")], truncated: true }],
935 covered: () => true,
936 });
937 expect((yield* read(across)).unresolved).toEqual(["acme/docs"]);
938 }),
939 );
940
941 it.effect("past the first slice, believes a covered repository and not an uncovered one", () =>
942 Effect.gen(function* () {
943 const read = yield* providerAnswering({
944 pages: [
945 { items: [searched("acme/web")], truncated: true },
946 { items: [searched("acme/web")], truncated: true },
947 ],
948 covered: (repository) => repository !== "acme/renamed",
949 });
950 const later = { ...across, cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 1 } };
951 expect((yield* read(later)).unresolved).toEqual([]);
952 expect(
953 (yield* read({ ...later, repositories: ["acme/web", "acme/renamed"] })).unresolved,
954 ).toEqual(["acme/renamed"]);
955 }),
956 );
957
958 it.effect("asks again after a failed check, and after coverage has had time to change", () =>
959 Effect.gen(function* () {
960 const checks: Array<string> = [];
961 const failing = yield* providerAnswering({
962 pages: [
963 { items: [searched("acme/web")], truncated: false },
964 { items: [searched("acme/web")], truncated: false },
965 ],
966 checks,
967 });
968 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
969 expect((yield* failing(across)).unresolved).toEqual(["acme/docs"]);
970 expect(checks).toEqual(["acme/docs", "acme/docs"]);
971
972 checks.length = 0;
973 const read = yield* providerAnswering({
974 pages: [
975 { items: [searched("acme/web")], truncated: false },
976 { items: [searched("acme/web")], truncated: false },
977 ],
978 covered: () => true,
979 checks,
980 });
981 yield* read(across);
982 yield* TestClock.adjust("61 minutes");
983 yield* read(across);
984 expect(checks).toEqual(["acme/docs", "acme/docs"]);
985 }),
986 );
987});