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

PullRequestReviewGuideService.test.ts

900 lines33.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Context from "effect/Context";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Ref from "effect/Ref";
10import * as Schedule from "effect/Schedule";
11import {
12 ProjectId,
13 GitCommandError,
14 type PullRequestActivity,
15 type PullRequestDetail,
16 type PullRequestStack,
17 type PullRequestRef,
18} from "@t3tools/contracts";
19import type { ReviewGuideGenerationInput } from "@t3tools/provider-core/server/textGeneration";
20​
21import * as ServerConfig from "../config.ts";
22import * as SqlitePersistence from "../persistence/Sqlite.ts";
23import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
24import * as ProjectService from "../project/ProjectService.ts";
25import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import * as TextGeneration from "../textGeneration/TextGeneration.ts";
28import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
29import * as VcsProcess from "../vcs/VcsProcess.ts";
30import * as PullRequestReviewGuideService from "./PullRequestReviewGuideService.ts";
31import * as PullRequestService from "./PullRequestService.ts";
32​
33const projectId = ProjectId.make("project-1");
34const ACME_APP = {
35 canonicalKey: "github.com/acme/app",
36 locator: {
37 source: "git-remote" as const,
38 remoteName: "origin",
39 remoteUrl: "https://github.com/acme/app.git",
40 },
41 provider: "github",
42 displayName: "acme/app",
43 owner: "acme",
44 name: "app",
45};
46​
47const reference: PullRequestRef = {
48 projectId,
49 host: "github.com",
50 repository: "acme/app",
51 number: 7,
52};
53​
54const git = (cwd: string, args: ReadonlyArray<string>) =>
55 Effect.gen(function* () {
56 const driver = yield* GitVcsDriver.GitVcsDriver;
57 const result = yield* driver.execute({ operation: "test.git", cwd, args, timeoutMs: 10_000 });
58 return result.stdout.trim();
59 });
60​
61const makeRepositories = Effect.gen(function* () {
62 const fs = yield* FileSystem.FileSystem;
63 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-guide-" });
64 const remote = `${root}/remote`;
65 const workspace = `${root}/workspace`;
66 yield* fs.makeDirectory(remote);
67 yield* git(remote, ["init", "--quiet", "--initial-branch=main"]);
68 yield* git(remote, ["config", "user.email", "test@example.com"]);
69 yield* git(remote, ["config", "user.name", "Test"]);
70 const commit = (path: string, message: string, contents = message) =>
71 fs
72 .writeFileString(`${remote}/${path}`, contents)
73 .pipe(
74 Effect.andThen(git(remote, ["add", path])),
75 Effect.andThen(git(remote, ["commit", "--quiet", "-m", message])),
76 Effect.andThen(git(remote, ["rev-parse", "HEAD"])),
77 );
78 yield* commit("base.txt", "base");
79 yield* git(remote, ["checkout", "--quiet", "-b", "stack-base"]);
80 const lowerSha = yield* commit("lower.txt", "lower layer");
81 yield* git(remote, ["checkout", "--quiet", "-b", "feature"]);
82 const headSha = yield* commit(
83 "feature.txt",
84 "the change",
85 Array.from({ length: 10 }, (_, index) => `line ${index + 1}`).join("\n") + "\n",
86 );
87 yield* git(remote, ["checkout", "--quiet", "-b", "upper"]);
88 const upperSha = yield* commit("upper.txt", "upper layer");
89 yield* git(remote, ["checkout", "--quiet", "main"]);
90 yield* commit("unrelated.txt", "main moved on");
91 yield* git(root, ["clone", "--quiet", remote, workspace]);
92 return { root, remote, workspace, headSha, lowerSha, upperSha };
93});
94​
95const detail = (workspaceRoot: string, headSha: string): PullRequestDetail =>
96 ({
97 number: 7,
98 title: "Add the feature",
99 body: "Adds the feature.",
100 baseBranch: "stack-base",
101 headBranch: "feature",
102 headSha,
103 workspaceRoot,
104 }) as PullRequestDetail;
105​
106const activity: PullRequestActivity = {
107 comments: [],
108 commentCount: 0,
109 commentsTruncated: false,
110 reviewThreads: [],
111 commits: [],
112};
113​
114const stack = (repositories: {
115 readonly headSha: string;
116 readonly lowerSha: string;
117 readonly upperSha: string;
118}): PullRequestStack => ({
119 id: "stack",
120 number: 1,
121 url: "https://example.com/stack/1",
122 base: "main",
123 layers: [
124 {
125 number: 6,
126 title: "Lower",
127 headSha: repositories.lowerSha,
128 headBranch: "stack-base",
129 state: "open",
130 },
131 {
132 number: 7,
133 title: "Add the feature",
134 headSha: repositories.headSha,
135 headBranch: "feature",
136 state: "open",
137 },
138 {
139 number: 8,
140 title: "Upper",
141 headSha: repositories.upperSha.slice(0, 12),
142 headBranch: "upper",
143 state: "open",
144 },
145 { number: 9, title: "Unpushed", headSha: "f".repeat(40), headBranch: "gone", state: "open" },
146 ],
147});
148​
149const makeLayer = (input: {
150 readonly root: string;
151 readonly remote: string;
152 readonly workspace: string;
153 readonly headSha: string;
154 readonly lowerSha: string;
155 readonly upperSha: string;
156 readonly generate: TextGeneration.TextGeneration["Service"]["generateReviewGuide"];
157 readonly stored: Deferred.Deferred<void>;
158 readonly enabled?: boolean;
159 readonly currentHead?: Ref.Ref<string>;
160 readonly identity?: typeof ACME_APP;
161}) =>
162 PullRequestReviewGuideService.layer.pipe(
163 Layer.provide(
164 Layer.effect(
165 PullRequestReviewGuides.PullRequestReviewGuideRepository,
166 Effect.gen(function* () {
167 const repository = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
168 return {
169 get: repository.get,
170 put: (key, guide) =>
171 repository
172 .put(key, guide)
173 .pipe(Effect.tap(() => Deferred.succeed(input.stored, undefined))),
174 } satisfies PullRequestReviewGuides.PullRequestReviewGuideRepository["Service"];
175 }),
176 ).pipe(Layer.provide(PullRequestReviewGuides.layer)),
177 ),
178 Layer.provide(
179 Layer.succeed(PullRequestService.PullRequestService, {
180 detail: () =>
181 (input.currentHead === undefined
182 ? Effect.succeed(input.headSha)
183 : Ref.get(input.currentHead)
184 ).pipe(Effect.map((head) => detail(input.workspace, head))),
185 activity: () => Effect.succeed(activity),
186 invalidate: () => Effect.void,
187 stack: () => Effect.succeed(stack(input)),
188 } as unknown as PullRequestService.PullRequestService["Service"]),
189 ),
190 Layer.provide(
191 Layer.succeed(ProjectService.ProjectService, {
192 getShell: () =>
193 Effect.succeedSome({
194 id: projectId,
195 workspaceRoot: input.workspace,
196 repositoryIdentity: {
197 ...(input.identity ?? ACME_APP),
198 locator: { ...ACME_APP.locator, remoteUrl: input.remote },
199 },
200 }),
201 } as unknown as ProjectService.ProjectService["Service"]),
202 ),
203 Layer.provide(
204 Layer.succeed(ProviderRegistry.ProviderRegistry, {
205 getProviders: Effect.succeed([]),
206 } as unknown as ProviderRegistry.ProviderRegistry["Service"]),
207 ),
208 Layer.provide(
209 Layer.succeed(TextGeneration.TextGeneration, {
210 generateReviewGuide: input.generate,
211 } as unknown as TextGeneration.TextGeneration["Service"]),
212 ),
213 Layer.provide(ServerSettings.layerTest({ reviewGuidesEnabled: input.enabled ?? true })),
214 Layer.provide(ServerConfig.layerTest(input.root, { prefix: "t3-review-guide-config-" })),
215 );
216​
217const layerBase = Layer.mergeAll(
218 GitVcsDriver.layer.pipe(
219 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-review-guide-git-" })),
220 Layer.provideMerge(VcsProcess.layer),
221 ),
222 SqlitePersistence.layerMemory,
223).pipe(Layer.provideMerge(NodeServices.layer));
224​
225type Repositories = Effect.Success<typeof makeRepositories>;
226​
227const awaitRunFailure = (
228 service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
229 input: PullRequestRef,
230) =>
231 service.get(input).pipe(
232 Effect.flatMap((result) =>
233 result.run?._tag === "Failed"
234 ? Effect.succeed(result.run.detail)
235 : Effect.fail("still running" as const),
236 ),
237 Effect.retry(Schedule.spaced("20 millis")),
238 );
239​
240const startSingleBranchRun = (input: {
241 readonly repositoryName: string;
242 readonly reportedHead: (repositories: Repositories) => string;
243 readonly refuseCommitFetch: boolean;
244 readonly prepare: (
245 repositories: Repositories,
246 workspace: string,
247 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>;
248 readonly onBranchFetch?:
249 | ((
250 repositories: Repositories,
251 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>)
252 | undefined;
253}) =>
254 Effect.gen(function* () {
255 const repositories = yield* makeRepositories;
256 const workspace = `${repositories.root}/single-branch`;
257 yield* git(repositories.root, [
258 "clone",
259 "--quiet",
260 "--no-local",
261 "--single-branch",
262 "--branch",
263 "main",
264 `${repositories.root}/remote`,
265 workspace,
266 ]);
267 yield* input.prepare(repositories, workspace);
268 const reportedHead = input.reportedHead(repositories);
269 const stored = yield* Deferred.make<void>();
270 const driver = yield* GitVcsDriver.GitVcsDriver;
271 const fetchedRefs: Array<string> = [];
272 const observed: Array<{ cwd: string; head: string; changed: string }> = [];
273 const onBranchFetch = input.onBranchFetch;
274 const observedDriver = {
275 ...driver,
276 execute: (call: GitVcsDriver.ExecuteGitInput) =>
277 Effect.gen(function* () {
278 const ref = call.args.at(-1);
279 if (call.args[0] !== "fetch" || ref === undefined) return yield* driver.execute(call);
280 fetchedRefs.push(ref);
281 if (input.refuseCommitFetch && ref === repositories.headSha) {
282 return yield* new GitCommandError({
283 operation: call.operation,
284 command: "git",
285 cwd: call.cwd,
286 detail: "The test remote refuses fetches by commit.",
287 exitCode: 128,
288 });
289 }
290 if (ref === "refs/heads/feature" && onBranchFetch !== undefined) {
291 yield* onBranchFetch(repositories).pipe(
292 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
293 );
294 }
295 return yield* driver.execute(call);
296 }),
297 };
298 const readCheckout = (cwd: string, args: ReadonlyArray<string>) =>
299 driver
300 .execute({ operation: "test.readCheckout", cwd, args })
301 .pipe(Effect.map((result) => result.stdout.trim()));
302 const context = yield* Layer.build(
303 makeLayer({
304 ...repositories,
305 headSha: reportedHead,
306 workspace,
307 stored,
308 identity: {
309 ...ACME_APP,
310 canonicalKey: `github.com/acme/${input.repositoryName}`,
311 displayName: `acme/${input.repositoryName}`,
312 name: input.repositoryName,
313 },
314 generate: (generation) =>
315 Effect.gen(function* () {
316 observed.push({
317 cwd: generation.cwd,
318 head: yield* readCheckout(generation.cwd, ["rev-parse", "HEAD"]),
319 changed: yield* readCheckout(generation.cwd, [
320 "diff",
321 "--name-only",
322 `${generation.baseCommit}...HEAD`,
323 ]),
324 });
325 return { stops: [] };
326 }).pipe(Effect.orDie),
327 }).pipe(Layer.provide(Layer.succeed(GitVcsDriver.GitVcsDriver, observedDriver))),
328 );
329 const service = Context.get(
330 context,
331 PullRequestReviewGuideService.PullRequestReviewGuideService,
332 );
333 const guideReference = { ...reference, repository: `acme/${input.repositoryName}` };
334 yield* service.generate(guideReference);
335 return {
336 repositories,
337 reportedHead,
338 service,
339 reference: guideReference,
340 stored,
341 fetchedRefs,
342 observed,
343 };
344 });
345​
346// Runs drive real git, which the test clock does not advance, so waits use real time.
347it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
348 it.effect.each([
349 {
350 name: "a short head already fetched",
351 shortHash: true,
352 prepare: "fetch-feature",
353 pushDuringFetch: false,
354 refuseCommitFetch: true,
355 expectedFetches: [],
356 },
357 {
358 name: "a short head on its branch",
359 shortHash: true,
360 prepare: "none",
361 pushDuringFetch: false,
362 refuseCommitFetch: true,
363 expectedFetches: ["refs/heads/feature"],
364 },
365 {
366 name: "a short head whose branch moves during the fetch",
367 shortHash: true,
368 prepare: "none",
369 pushDuringFetch: true,
370 refuseCommitFetch: true,
371 expectedFetches: ["refs/heads/feature"],
372 },
373 {
374 name: "a full head served by commit",
375 shortHash: false,
376 prepare: "none",
377 pushDuringFetch: false,
378 refuseCommitFetch: false,
379 expectedFetches: ["<head>"],
380 },
381 {
382 name: "a full head on its branch",
383 shortHash: false,
384 prepare: "none",
385 pushDuringFetch: false,
386 refuseCommitFetch: true,
387 expectedFetches: ["<head>", "refs/heads/feature"],
388 },
389 {
390 name: "a full head only on its pull ref",
391 shortHash: false,
392 prepare: "refs/pull/7/head",
393 pushDuringFetch: false,
394 refuseCommitFetch: true,
395 expectedFetches: ["<head>", "refs/heads/feature", "refs/pull/7/head"],
396 },
397 {
398 name: "a full head only on its merge request ref",
399 shortHash: false,
400 prepare: "refs/merge-requests/7/head",
401 pushDuringFetch: false,
402 refuseCommitFetch: true,
403 expectedFetches: [
404 "<head>",
405 "refs/heads/feature",
406 "refs/pull/7/head",
407 "refs/merge-requests/7/head",
408 ],
409 },
410 ])(
411 "writes a guide for the reported commit: $name",
412 ({ shortHash, prepare, pushDuringFetch, refuseCommitFetch, expectedFetches }) =>
413 Effect.scoped(
414 Effect.gen(function* () {
415 const run = yield* startSingleBranchRun({
416 repositoryName: "fetched-head",
417 reportedHead: (repositories) =>
418 shortHash ? repositories.headSha.slice(0, 12) : repositories.headSha,
419 refuseCommitFetch,
420 prepare: (repositories, workspace) => {
421 const remote = `${repositories.root}/remote`;
422 if (prepare === "fetch-feature") {
423 return git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe(
424 Effect.asVoid,
425 );
426 }
427 if (prepare === "none") return Effect.void;
428 return git(remote, ["update-ref", prepare, repositories.headSha]).pipe(
429 Effect.andThen(
430 git(remote, ["update-ref", "refs/heads/feature", repositories.lowerSha]),
431 ),
432 Effect.asVoid,
433 );
434 },
435 onBranchFetch: pushDuringFetch
436 ? (repositories) => {
437 const remote = `${repositories.root}/remote`;
438 return git(remote, ["checkout", "--quiet", "feature"]).pipe(
439 Effect.andThen(
440 git(remote, [
441 "commit",
442 "--quiet",
443 "--allow-empty",
444 "-m",
445 "push during fetch",
446 ]),
447 ),
448 Effect.asVoid,
449 );
450 }
451 : undefined,
452 });
453 yield* Effect.raceFirst(
454 Deferred.await(run.stored),
455 awaitRunFailure(run.service, run.reference).pipe(
456 Effect.flatMap((detail) => Effect.die(`run failed: ${detail}`)),
457 ),
458 );
459 const { headSha } = run.repositories;
460 const result = yield* run.service.get(run.reference);
461 assert.strictEqual(result.guide?.headSha, run.reportedHead);
462 assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]);
463 assert.deepStrictEqual(run.observed, [
464 { cwd: run.observed[0]?.cwd, head: headSha, changed: "feature.txt" },
465 ]);
466 const headRefs = new Set([
467 headSha,
468 run.reportedHead,
469 "refs/heads/feature",
470 "refs/pull/7/head",
471 "refs/merge-requests/7/head",
472 ]);
473 assert.deepStrictEqual(
474 run.fetchedRefs.filter((ref) => headRefs.has(ref)),
475 expectedFetches.map((ref) => (ref === "<head>" ? headSha : ref)),
476 );
477 const fs = yield* FileSystem.FileSystem;
478 assert.isFalse(yield* fs.exists(run.observed[0]?.cwd ?? ""));
479 }),
480 ),
481 );
482​
483 it.effect.each([
484 {
485 name: "a branch named like the short head",
486 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
487 shadow: "branch",
488 expected: ["a branch or tag rather than the commit"],
489 },
490 {
491 name: "a tag named like the short head",
492 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
493 shadow: "tag",
494 expected: ["a branch or tag rather than the commit"],
495 },
496 {
497 name: "a head that is not a commit hash",
498 reportedHead: (repositories: Repositories) =>
499 `--upload-pack=touch ${repositories.root}/injected`,
500 shadow: "none",
501 expected: ["not a commit hash"],
502 },
503 {
504 name: "a head no source has",
505 reportedHead: () => "e".repeat(40),
506 shadow: "none",
507 expected: [
508 "local objects:",
509 "the commit:",
510 "branch feature:",
511 "refs/pull/7/head:",
512 "refs/merge-requests/7/head:",
513 ],
514 },
515 ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) =>
516 Effect.scoped(
517 Effect.gen(function* () {
518 const run = yield* startSingleBranchRun({
519 repositoryName: "refused-head",
520 reportedHead,
521 refuseCommitFetch: false,
522 prepare: (repositories, workspace) =>
523 git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe(
524 Effect.andThen(
525 shadow === "none"
526 ? Effect.void
527 : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]),
528 ),
529 Effect.asVoid,
530 ),
531 });
532 const detail = yield* Effect.raceFirst(
533 awaitRunFailure(run.service, run.reference),
534 Deferred.await(run.stored).pipe(Effect.andThen(Effect.die("a guide was written"))),
535 );
536 for (const part of expected) assert.include(detail, part);
537 assert.deepStrictEqual(run.observed, []);
538 assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
539 const fs = yield* FileSystem.FileSystem;
540 assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`));
541 }),
542 ),
543 );
544​
545 it.effect("briefs the change against its own base in a checkout it then removes", () =>
546 Effect.scoped(
547 Effect.gen(function* () {
548 const repositories = yield* makeRepositories;
549 const seen = yield* Deferred.make<{
550 readonly input: ReviewGuideGenerationInput;
551 readonly changed: string;
552 readonly head: string;
553 readonly upper: string;
554 }>();
555 const finish = yield* Deferred.make<void>();
556 const driver = yield* GitVcsDriver.GitVcsDriver;
557 const readCheckout = (cwd: string, args: ReadonlyArray<string>) =>
558 git(cwd, args).pipe(
559 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
560 Effect.orDie,
561 );
562 const stored = yield* Deferred.make<void>();
563​
564 // Built in this test's scope: runs are forked into the service's scope and must outlive
565 // the call that obtains the service.
566 const context = yield* Layer.build(
567 makeLayer({
568 ...repositories,
569 stored,
570 generate: (input) =>
571 Effect.gen(function* () {
572 const changed = yield* readCheckout(input.cwd, [
573 "diff",
574 "--name-only",
575 `${input.baseCommit}...HEAD`,
576 ]);
577 const head = yield* readCheckout(input.cwd, ["rev-parse", "HEAD"]);
578 const upper = yield* readCheckout(input.cwd, [
579 "show",
580 `${repositories.upperSha}:upper.txt`,
581 ]);
582 yield* Deferred.succeed(seen, { input, changed, head, upper });
583 yield* Deferred.await(finish);
584 return {
585 stops: [
586 {
587 title: "The feature",
588 summary: "The change.",
589 attention: null,
590 excerpts: [
591 { path: "feature.txt", side: "new", start: 4, end: 40, caption: "" },
592 ],
593 files: [],
594 notes: [
595 { path: "feature.txt", line: 5, title: "Kept", body: "Inside." },
596 { path: "feature.txt", line: 30, title: "Dropped", body: "Outside." },
597 ],
598 questions: [],
599 },
600 ],
601 };
602 }),
603 }),
604 );
605 const service = Context.get(
606 context,
607 PullRequestReviewGuideService.PullRequestReviewGuideService,
608 );
609​
610 const started = yield* service.generate(reference);
611 assert.strictEqual(started.run?._tag, "Running");
612 assert.strictEqual(started.guide, null);
613 assert.isTrue(started.started);
614​
615 const failedRun = service.get(reference).pipe(
616 Effect.flatMap((result) =>
617 result.run?._tag === "Failed"
618 ? Effect.die(`run failed: ${result.run.detail}`)
619 : Effect.fail("still running" as const),
620 ),
621 Effect.retry(Schedule.spaced("20 millis")),
622 );
623 const observed = yield* Effect.raceFirst(Deferred.await(seen), failedRun);
624 assert.strictEqual(observed.head, repositories.headSha);
625 assert.strictEqual(observed.changed, "feature.txt");
626 assert.strictEqual(observed.input.baseBranch, "stack-base");
627 assert.deepStrictEqual(observed.input.stack, [
628 { number: 6, title: "Lower", state: "open", headSha: repositories.lowerSha },
629 { number: 7, title: "Add the feature", state: "open", headSha: repositories.headSha },
630 { number: 8, title: "Upper", state: "open", headSha: repositories.upperSha },
631 { number: 9, title: "Unpushed", state: "open", headSha: null },
632 ]);
633 assert.strictEqual(observed.upper, "upper layer");
634​
635 const joined = yield* service.generate(reference);
636 assert.strictEqual(joined.run, started.run);
637 assert.isFalse(joined.started);
638​
639 yield* Deferred.succeed(finish, undefined);
640 yield* Deferred.await(stored);
641 const finished = yield* service.get(reference);
642 assert.strictEqual(finished.guide?.headSha, repositories.headSha);
643 const guide = finished.guide;
644 assert.isNotNull(guide);
645 const [story] = guide.stops;
646 assert.deepStrictEqual(story?.excerpts, [
647 { path: "feature.txt", side: "new", start: 4, end: 10, caption: "" },
648 ]);
649 assert.deepStrictEqual(
650 story?.notes.map((note) => note.title),
651 ["Kept"],
652 );
653 assert.strictEqual(guide.stops.length, 1);
654​
655 const fs = yield* FileSystem.FileSystem;
656 assert.isFalse(yield* fs.exists(observed.input.cwd));
657 const worktrees = yield* git(repositories.workspace, ["worktree", "list", "--porcelain"]);
658 assert.notInclude(worktrees, observed.input.cwd);
659 }),
660 ),
661 );
662​
663 it.effect("measures only the PR change using the renamed verified remote's fetch URL", () =>
664 Effect.scoped(
665 Effect.gen(function* () {
666 const repositories = yield* makeRepositories;
667 const fork = `${repositories.root}/fork`;
668 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
669 yield* git(fork, ["branch", "stack-base", "main~1"]);
670 // The cached identity still names origin, which now belongs to the stale fork.
671 yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]);
672 yield* git(repositories.workspace, ["remote", "add", "origin", fork]);
673 yield* git(repositories.workspace, [
674 "config",
675 `url.${repositories.remote}.insteadOf`,
676 "review-upstream:",
677 ]);
678 yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]);
679 const changed = yield* Deferred.make<string>();
680 const driver = yield* GitVcsDriver.GitVcsDriver;
681 const stored = yield* Deferred.make<void>();
682 const context = yield* Layer.build(
683 makeLayer({
684 ...repositories,
685 stored,
686 generate: (input) =>
687 git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe(
688 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
689 Effect.orDie,
690 Effect.flatMap((names) => Deferred.succeed(changed, names)),
691 Effect.as({ stops: [] }),
692 ),
693 }),
694 );
695 const service = Context.get(
696 context,
697 PullRequestReviewGuideService.PullRequestReviewGuideService,
698 );
699 yield* service.generate(reference);
700 assert.strictEqual(yield* Deferred.await(changed), "feature.txt");
701 yield* Deferred.await(stored);
702 const result = yield* service.get(reference);
703 assert.strictEqual(result.guide?.headSha, repositories.headSha);
704 assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]);
705 }),
706 ),
707 );
708​
709 it.effect("refuses generation when the verified remote disappeared despite a usable origin", () =>
710 Effect.scoped(
711 Effect.gen(function* () {
712 const repositories = yield* makeRepositories;
713 const fork = `${repositories.root}/fork`;
714 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
715 yield* git(fork, ["branch", "stack-base", repositories.lowerSha]);
716 yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]);
717 const started = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
718 const stored = yield* Deferred.make<void>();
719 const generated = yield* Ref.make(false);
720 const driver = yield* GitVcsDriver.GitVcsDriver;
721 const context = yield* Layer.build(
722 makeLayer({
723 ...repositories,
724 stored,
725 generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })),
726 }).pipe(
727 Layer.provide(
728 Layer.succeed(GitVcsDriver.GitVcsDriver, {
729 ...driver,
730 execute: (call) =>
731 Effect.withFiber((fiber) =>
732 Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))),
733 ),
734 }),
735 ),
736 ),
737 );
738 const service = Context.get(
739 context,
740 PullRequestReviewGuideService.PullRequestReviewGuideService,
741 );
742 const before = yield* service.get(reference);
743 yield* service.generate(reference);
744 // Join the background run so its failure is visible without polling service state.
745 yield* Fiber.await(yield* Deferred.await(started));
746 const result = yield* service.get(reference);
747 assert.strictEqual(result.run?._tag, "Failed");
748 assert.include(
749 result.run?._tag === "Failed" ? result.run.detail : "",
750 "no longer has a remote for the pull request's repository",
751 );
752 assert.deepStrictEqual(result.guide, before.guide);
753 assert.isFalse(yield* Deferred.isDone(stored));
754 assert.isFalse(yield* Ref.get(generated));
755 }),
756 ),
757 );
758​
759 it.effect("refuses to write a guide while the server has review guides off", () =>
760 Effect.scoped(
761 Effect.gen(function* () {
762 const repositories = yield* makeRepositories;
763 const stored = yield* Deferred.make<void>();
764 const context = yield* Layer.build(
765 makeLayer({
766 ...repositories,
767 stored,
768 enabled: false,
769 generate: () => Effect.die("a guide must not be written while the beta is off"),
770 }),
771 );
772 const service = Context.get(
773 context,
774 PullRequestReviewGuideService.PullRequestReviewGuideService,
775 );
776 const result = yield* Effect.flip(service.generate(reference));
777 assert.include(result.message, "Review guides are off");
778 }),
779 ),
780 );
781​
782 it.effect(
783 "keeps a newer run's guide when an older run for the same pull request finishes late",
784 () =>
785 Effect.scoped(
786 Effect.gen(function* () {
787 const repositories = yield* makeRepositories;
788 const stored = yield* Deferred.make<void>();
789 const currentHead = yield* Ref.make(repositories.headSha);
790 const releaseOld = yield* Deferred.make<void>();
791 const oldStarted = yield* Deferred.make<void>();
792 const answer = (title: string) => ({
793 stops: [
794 {
795 title,
796 summary: "",
797 attention: null,
798 excerpts: [],
799 files: [],
800 notes: [],
801 questions: [],
802 },
803 ],
804 });
805 const context = yield* Layer.build(
806 makeLayer({
807 ...repositories,
808 stored,
809 currentHead,
810 generate: (input) =>
811 input.cwd.length > 0 && input.baseCommit.length > 0
812 ? Ref.get(currentHead).pipe(
813 Effect.flatMap((head) =>
814 head === repositories.headSha
815 ? Deferred.succeed(oldStarted, undefined).pipe(
816 Effect.andThen(Deferred.await(releaseOld)),
817 Effect.as(answer("old head")),
818 )
819 : Effect.succeed(answer("new head")),
820 ),
821 )
822 : Effect.die("unreachable"),
823 }),
824 );
825 const service = Context.get(
826 context,
827 PullRequestReviewGuideService.PullRequestReviewGuideService,
828 );
829​
830 yield* service.generate(reference);
831 const firstFailed = service.get(reference).pipe(
832 Effect.flatMap((result) =>
833 result.run?._tag === "Failed"
834 ? Effect.die(`first run failed: ${result.run.detail}`)
835 : Effect.fail("still running" as const),
836 ),
837 Effect.retry(Schedule.spaced("20 millis")),
838 );
839 yield* Effect.raceFirst(Deferred.await(oldStarted), firstFailed);
840 yield* Ref.set(currentHead, repositories.upperSha);
841 const second = yield* service.generate(reference);
842 assert.strictEqual(second.run?._tag, "Running");
843 assert.strictEqual(second.run?.headSha, repositories.upperSha);
844 const failedRun = service.get(reference).pipe(
845 Effect.flatMap((result) =>
846 result.run?._tag === "Failed"
847 ? Effect.die(`run failed: ${result.run.detail}`)
848 : Effect.fail("still running" as const),
849 ),
850 Effect.retry(Schedule.spaced("20 millis")),
851 );
852 yield* Effect.raceFirst(Deferred.await(stored), failedRun);
853​
854 yield* Deferred.succeed(releaseOld, undefined);
855 const settled = yield* service.get(reference).pipe(
856 Effect.filterOrFail(
857 (result) => result.run === null,
858 () => "still running" as const,
859 ),
860 Effect.retry({ schedule: Schedule.spaced("20 millis"), times: 250 }),
861 );
862 assert.strictEqual(settled.guide?.headSha, repositories.upperSha);
863 yield* Effect.sleep("200 millis");
864 const after = yield* service.get(reference);
865 assert.isNull(after.run);
866 assert.strictEqual(after.guide?.headSha, repositories.upperSha);
867 assert.strictEqual(after.guide?.stops[0]?.title, "new head");
868 }),
869 ),
870 );
871​
872 it.effect("refuses a pull request from a repository the project is not a checkout of", () =>
873 Effect.scoped(
874 Effect.gen(function* () {
875 const repositories = yield* makeRepositories;
876 const stored = yield* Deferred.make<void>();
877 const context = yield* Layer.build(
878 makeLayer({
879 ...repositories,
880 stored,
881 identity: {
882 ...ACME_APP,
883 canonicalKey: "github.com/acme/other",
884 displayName: "acme/other",
885 name: "other",
886 },
887 generate: () =>
888 Effect.die("a guide must not be written from another repository's checkout"),
889 }),
890 );
891 const service = Context.get(
892 context,
893 PullRequestReviewGuideService.PullRequestReviewGuideService,
894 );
895 const result = yield* Effect.flip(service.generate(reference));
896 assert.include(result.message, "in another repository");
897 }),
898 ),
899 );
900});