Open History to see the last commit
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 Queue from "effect/Queue";
11import * as Tracer from "effect/Tracer";
12import {
13 ProjectId,
14 GitCommandError,
15 type PullRequestActivity,
16 type PullRequestDetail,
17 type PullRequestStack,
18 type PullRequestRef,
19 type RepositoryIdentity,
20} from "@t3tools/contracts";
21
22import * as ServerConfig from "../config.ts";
23import * as SqlitePersistence from "../persistence/Sqlite.ts";
24import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
25import * as ProjectService from "../project/ProjectService.ts";
26import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
27import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
28import * as ServerSettings from "../serverSettings.ts";
29import * as TextGeneration from "../textGeneration/TextGeneration.ts";
30import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
31import * as VcsProcess from "../vcs/VcsProcess.ts";
32import * as WorkspaceRepositories from "../workspace/WorkspaceRepositories.ts";
33import * as PullRequestReviewGuideService from "./PullRequestReviewGuideService.ts";
34import * as PullRequestService from "./PullRequestService.ts";
35
36const projectId = ProjectId.make("project-1");
37const ACME_APP = {
38 canonicalKey: "github.com/acme/app",
39 locator: {
40 source: "git-remote" as const,
41 remoteName: "origin",
42 remoteUrl: "https://github.com/acme/app.git",
43 },
44 provider: "github",
45 displayName: "acme/app",
46 owner: "acme",
47 name: "app",
48};
49
50const reference: PullRequestRef = {
51 projectId,
52 host: "github.com",
53 repository: "acme/app",
54 number: 7,
55};
56
57const git = (cwd: string, args: ReadonlyArray<string>) =>
58 Effect.gen(function* () {
59 const driver = yield* GitVcsDriver.GitVcsDriver;
60 const result = yield* driver.execute({ operation: "test.git", cwd, args, timeoutMs: 10_000 });
61 return result.stdout.trim();
62 });
63
64const makeRepositories = Effect.gen(function* () {
65 const fs = yield* FileSystem.FileSystem;
66 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-guide-" });
67 const remote = `${root}/remote`;
68 const workspace = `${root}/workspace`;
69 yield* fs.makeDirectory(remote);
70 yield* git(remote, ["init", "--quiet", "--initial-branch=main"]);
71 yield* git(remote, ["config", "user.email", "test@example.com"]);
72 yield* git(remote, ["config", "user.name", "Test"]);
73 const commit = (path: string, message: string, contents = message) =>
74 fs
75 .writeFileString(`${remote}/${path}`, contents)
76 .pipe(
77 Effect.andThen(git(remote, ["add", path])),
78 Effect.andThen(git(remote, ["commit", "--quiet", "-m", message])),
79 Effect.andThen(git(remote, ["rev-parse", "HEAD"])),
80 );
81 yield* commit("base.txt", "base");
82 yield* git(remote, ["checkout", "--quiet", "-b", "stack-base"]);
83 const lowerSha = yield* commit("lower.txt", "lower layer");
84 yield* git(remote, ["checkout", "--quiet", "-b", "feature"]);
85 const headSha = yield* commit(
86 "feature.txt",
87 "the change",
88 Array.from({ length: 10 }, (_, index) => `line ${index + 1}`).join("\n") + "\n",
89 );
90 yield* git(remote, ["checkout", "--quiet", "-b", "upper"]);
91 const upperSha = yield* commit("upper.txt", "upper layer");
92 yield* git(remote, ["checkout", "--quiet", "main"]);
93 yield* commit("unrelated.txt", "main moved on");
94 yield* git(root, ["clone", "--quiet", remote, workspace]);
95 return { root, remote, workspace, headSha, lowerSha, upperSha };
96});
97
98const detail = (workspaceRoot: string, headSha: string): PullRequestDetail =>
99 ({
100 provider: "github",
101 number: 7,
102 title: "Add the feature",
103 body: "Adds the feature.",
104 baseBranch: "stack-base",
105 headBranch: "feature",
106 headSha,
107 workspaceRoot,
108 }) as PullRequestDetail;
109
110const activity: PullRequestActivity = {
111 comments: [],
112 commentCount: 0,
113 commentsTruncated: false,
114 reviewThreads: [],
115 commits: [],
116};
117
118const stack = (repositories: {
119 readonly headSha: string;
120 readonly lowerSha: string;
121 readonly upperSha: string;
122}): PullRequestStack => ({
123 id: "stack",
124 number: 1,
125 url: "https://example.com/stack/1",
126 base: "main",
127 layers: [
128 {
129 number: 6,
130 title: "Lower",
131 headSha: repositories.lowerSha,
132 headBranch: "stack-base",
133 state: "open",
134 },
135 {
136 number: 7,
137 title: "Add the feature",
138 headSha: repositories.headSha,
139 headBranch: "feature",
140 state: "open",
141 },
142 {
143 number: 8,
144 title: "Upper",
145 headSha: repositories.upperSha.slice(0, 12),
146 headBranch: "upper",
147 state: "open",
148 },
149 { number: 9, title: "Unpushed", headSha: "f".repeat(40), headBranch: "gone", state: "open" },
150 ],
151});
152
153const makeLayer = (input: {
154 readonly root: string;
155 readonly remote: string;
156 readonly workspace: string;
157 readonly headSha: string;
158 readonly lowerSha: string;
159 readonly upperSha: string;
160 readonly generate: TextGeneration.TextGeneration["Service"]["generateReviewGuide"];
161 readonly stored: Deferred.Deferred<void>;
162 readonly enabled?: boolean;
163 readonly currentHead?: Ref.Ref<string>;
164 readonly identity?: typeof ACME_APP;
165 /** Opens the clones' parent folder as a multi-repo workspace project instead of the clone. */
166 readonly multiRepo?: boolean;
167}) =>
168 PullRequestReviewGuideService.layer.pipe(
169 Layer.provide(
170 Layer.effect(
171 PullRequestReviewGuides.PullRequestReviewGuideRepository,
172 Effect.gen(function* () {
173 const repository = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
174 return {
175 get: repository.get,
176 put: (key, guide) =>
177 repository
178 .put(key, guide)
179 .pipe(Effect.tap(() => Deferred.succeed(input.stored, undefined))),
180 } satisfies PullRequestReviewGuides.PullRequestReviewGuideRepository["Service"];
181 }),
182 ).pipe(Layer.provide(PullRequestReviewGuides.layer)),
183 ),
184 Layer.provide(
185 Layer.succeed(PullRequestService.PullRequestService, {
186 detail: () =>
187 (input.currentHead === undefined
188 ? Effect.succeed(input.headSha)
189 : Ref.get(input.currentHead)
190 ).pipe(Effect.map((head) => detail(input.workspace, head))),
191 activity: () => Effect.succeed(activity),
192 invalidate: () => Effect.void,
193 stack: () => Effect.succeed(stack(input)),
194 } as unknown as PullRequestService.PullRequestService["Service"]),
195 ),
196 Layer.provide(
197 Layer.succeed(ProjectService.ProjectService, {
198 getShell: () =>
199 Effect.succeedSome(
200 input.multiRepo === true
201 ? { id: projectId, workspaceRoot: input.root, repositoryIdentity: null }
202 : {
203 id: projectId,
204 workspaceRoot: input.workspace,
205 repositoryIdentity: {
206 ...(input.identity ?? ACME_APP),
207 locator: { ...ACME_APP.locator, remoteUrl: input.remote },
208 },
209 },
210 ),
211 } as unknown as ProjectService.ProjectService["Service"]),
212 ),
213 Layer.provide(
214 Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
215 resolve: (cwd) =>
216 Effect.succeed(
217 cwd === input.workspace
218 ? ({
219 ...ACME_APP,
220 locator: { ...ACME_APP.locator, remoteUrl: input.remote },
221 } as RepositoryIdentity)
222 : null,
223 ),
224 }),
225 ),
226 Layer.provide(WorkspaceRepositories.layer),
227 Layer.provide(
228 Layer.succeed(ProviderRegistry.ProviderRegistry, {
229 getProviders: Effect.succeed([]),
230 } as unknown as ProviderRegistry.ProviderRegistry["Service"]),
231 ),
232 Layer.provide(
233 Layer.succeed(TextGeneration.TextGeneration, {
234 generateReviewGuide: input.generate,
235 } as unknown as TextGeneration.TextGeneration["Service"]),
236 ),
237 Layer.provide(ServerSettings.layerTest({ reviewGuidesEnabled: input.enabled ?? true })),
238 Layer.provide(ServerConfig.layerTest(input.root, { prefix: "t3-review-guide-config-" })),
239 );
240
241const layerBase = Layer.mergeAll(
242 GitVcsDriver.layer.pipe(
243 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-review-guide-git-" })),
244 Layer.provideMerge(VcsProcess.layer),
245 ),
246 SqlitePersistence.layerMemory,
247).pipe(Layer.provideMerge(NodeServices.layer));
248
249type Repositories = Effect.Success<typeof makeRepositories>;
250
251// A run forks into the service's scope, so a test learns it settled when the run's `write` span
252// ends; the run records its outcome synchronously right after.
253const watchRuns = Effect.gen(function* () {
254 const ended = yield* Queue.unbounded<void>();
255 const tracer = Tracer.make({
256 span: (options) => {
257 const span = new Tracer.NativeSpan(options);
258 if (options.name !== "PullRequestReviewGuideService.write") return span;
259 const end = span.end.bind(span);
260 span.end = (endTime, exit) => {
261 end(endTime, exit);
262 Queue.offerUnsafe(ended, undefined);
263 };
264 return span;
265 },
266 });
267 return {
268 generate: (
269 service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
270 input: PullRequestRef,
271 ) => service.generate(input).pipe(Effect.withTracer(tracer)),
272 settled: (
273 service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
274 input: PullRequestRef,
275 ) => Queue.take(ended).pipe(Effect.andThen(service.get(input))),
276 };
277});
278
279const startSingleBranchRun = (input: {
280 readonly repositoryName: string;
281 readonly reportedHead: (repositories: Repositories) => string;
282 readonly refuseCommitFetch: boolean;
283 readonly prepare: (
284 repositories: Repositories,
285 workspace: string,
286 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>;
287 readonly onBranchFetch?:
288 | ((
289 repositories: Repositories,
290 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>)
291 | undefined;
292}) =>
293 Effect.gen(function* () {
294 const repositories = yield* makeRepositories;
295 const workspace = `${repositories.root}/single-branch`;
296 yield* git(repositories.root, [
297 "clone",
298 "--quiet",
299 "--no-local",
300 "--single-branch",
301 "--branch",
302 "main",
303 `${repositories.root}/remote`,
304 workspace,
305 ]);
306 yield* input.prepare(repositories, workspace);
307 const reportedHead = input.reportedHead(repositories);
308 const stored = yield* Deferred.make<void>();
309 const driver = yield* GitVcsDriver.GitVcsDriver;
310 const fetchedRefs: Array<string> = [];
311 const observed: Array<{ cwd: string; head: string; changed: string }> = [];
312 const onBranchFetch = input.onBranchFetch;
313 const observedDriver = {
314 ...driver,
315 execute: (call: GitVcsDriver.ExecuteGitInput) =>
316 Effect.gen(function* () {
317 const ref = call.args.at(-1);
318 if (call.args[0] !== "fetch" || ref === undefined) return yield* driver.execute(call);
319 fetchedRefs.push(ref);
320 if (input.refuseCommitFetch && ref === repositories.headSha) {
321 return yield* new GitCommandError({
322 operation: call.operation,
323 command: "git",
324 cwd: call.cwd,
325 detail: "The test remote refuses fetches by commit.",
326 exitCode: 128,
327 });
328 }
329 if (ref === "refs/heads/feature" && onBranchFetch !== undefined) {
330 yield* onBranchFetch(repositories).pipe(
331 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
332 );
333 }
334 return yield* driver.execute(call);
335 }),
336 };
337 const readCheckout = (cwd: string, args: ReadonlyArray<string>) =>
338 driver
339 .execute({ operation: "test.readCheckout", cwd, args })
340 .pipe(Effect.map((result) => result.stdout.trim()));
341 const context = yield* Layer.build(
342 makeLayer({
343 ...repositories,
344 headSha: reportedHead,
345 workspace,
346 stored,
347 identity: {
348 ...ACME_APP,
349 canonicalKey: `github.com/acme/${input.repositoryName}`,
350 displayName: `acme/${input.repositoryName}`,
351 name: input.repositoryName,
352 },
353 generate: (generation) =>
354 Effect.gen(function* () {
355 observed.push({
356 cwd: generation.cwd,
357 head: yield* readCheckout(generation.cwd, ["rev-parse", "HEAD"]),
358 changed: yield* readCheckout(generation.cwd, [
359 "diff",
360 "--name-only",
361 `${generation.baseCommit}...HEAD`,
362 ]),
363 });
364 return { stops: [] };
365 }).pipe(Effect.orDie),
366 }).pipe(Layer.provide(Layer.succeed(GitVcsDriver.GitVcsDriver, observedDriver))),
367 );
368 const service = Context.get(
369 context,
370 PullRequestReviewGuideService.PullRequestReviewGuideService,
371 );
372 const guideReference = { ...reference, repository: `acme/${input.repositoryName}` };
373 const runs = yield* watchRuns;
374 yield* runs.generate(service, guideReference);
375 return {
376 repositories,
377 reportedHead,
378 service,
379 reference: guideReference,
380 stored,
381 fetchedRefs,
382 observed,
383 settled: runs.settled(service, guideReference),
384 };
385 });
386
387it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
388 it.effect.each([
389 {
390 name: "a branch named like the short head",
391 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
392 shadow: "branch",
393 expected: ["a branch or tag rather than the commit"],
394 },
395 {
396 name: "a tag named like the short head",
397 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
398 shadow: "tag",
399 expected: ["a branch or tag rather than the commit"],
400 },
401 {
402 name: "a head that is not a commit hash",
403 reportedHead: (repositories: Repositories) =>
404 `--upload-pack=touch ${repositories.root}/injected`,
405 shadow: "none",
406 expected: ["not a commit hash"],
407 },
408 {
409 name: "a head no source has",
410 reportedHead: () => "e".repeat(40),
411 shadow: "none",
412 expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"],
413 },
414 ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) =>
415 Effect.scoped(
416 Effect.gen(function* () {
417 const run = yield* startSingleBranchRun({
418 repositoryName: "refused-head",
419 reportedHead,
420 refuseCommitFetch: false,
421 prepare: (repositories, workspace) =>
422 git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe(
423 Effect.andThen(
424 shadow === "none"
425 ? Effect.void
426 : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]),
427 ),
428 Effect.asVoid,
429 ),
430 });
431 const result = yield* run.settled;
432 assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written");
433 assert.strictEqual(result.run?._tag, "Failed");
434 const detail = result.run?._tag === "Failed" ? result.run.detail : "";
435 for (const part of expected) assert.include(detail, part);
436 // Only the host's own head ref is tried.
437 assert.notInclude(detail, "refs/merge-requests/");
438 assert.deepStrictEqual(run.observed, []);
439 assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
440 const fs = yield* FileSystem.FileSystem;
441 assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`));
442 }),
443 ),
444 );
445
446 it.effect("measures only the PR change using the renamed verified remote's fetch URL", () =>
447 Effect.scoped(
448 Effect.gen(function* () {
449 const repositories = yield* makeRepositories;
450 const fork = `${repositories.root}/fork`;
451 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
452 yield* git(fork, ["branch", "stack-base", "main~1"]);
453 // The cached identity still names origin, which now belongs to the stale fork.
454 yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]);
455 yield* git(repositories.workspace, ["remote", "add", "origin", fork]);
456 yield* git(repositories.workspace, [
457 "config",
458 `url.${repositories.remote}.insteadOf`,
459 "review-upstream:",
460 ]);
461 yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]);
462 const changed = yield* Deferred.make<string>();
463 const driver = yield* GitVcsDriver.GitVcsDriver;
464 const stored = yield* Deferred.make<void>();
465 const context = yield* Layer.build(
466 makeLayer({
467 ...repositories,
468 stored,
469 generate: (input) =>
470 git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe(
471 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
472 Effect.orDie,
473 Effect.flatMap((names) => Deferred.succeed(changed, names)),
474 Effect.as({ stops: [] }),
475 ),
476 }),
477 );
478 const service = Context.get(
479 context,
480 PullRequestReviewGuideService.PullRequestReviewGuideService,
481 );
482 yield* service.generate(reference);
483 assert.strictEqual(yield* Deferred.await(changed), "feature.txt");
484 yield* Deferred.await(stored);
485 const result = yield* service.get(reference);
486 assert.strictEqual(result.guide?.headSha, repositories.headSha);
487 assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]);
488 }),
489 ),
490 );
491
492 it.effect("refuses generation when the verified remote disappeared despite a usable origin", () =>
493 Effect.scoped(
494 Effect.gen(function* () {
495 const repositories = yield* makeRepositories;
496 const fork = `${repositories.root}/fork`;
497 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
498 yield* git(fork, ["branch", "stack-base", repositories.lowerSha]);
499 yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]);
500 const started = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
501 const stored = yield* Deferred.make<void>();
502 const generated = yield* Ref.make(false);
503 const driver = yield* GitVcsDriver.GitVcsDriver;
504 const context = yield* Layer.build(
505 makeLayer({
506 ...repositories,
507 stored,
508 generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })),
509 }).pipe(
510 Layer.provide(
511 Layer.succeed(GitVcsDriver.GitVcsDriver, {
512 ...driver,
513 execute: (call) =>
514 Effect.withFiber((fiber) =>
515 Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))),
516 ),
517 }),
518 ),
519 ),
520 );
521 const service = Context.get(
522 context,
523 PullRequestReviewGuideService.PullRequestReviewGuideService,
524 );
525 const before = yield* service.get(reference);
526 yield* service.generate(reference);
527 // Join the background run so its failure is visible without polling service state.
528 yield* Fiber.await(yield* Deferred.await(started));
529 const result = yield* service.get(reference);
530 assert.strictEqual(result.run?._tag, "Failed");
531 assert.include(
532 result.run?._tag === "Failed" ? result.run.detail : "",
533 "no longer has a remote for the pull request's repository",
534 );
535 assert.deepStrictEqual(result.guide, before.guide);
536 assert.isFalse(yield* Deferred.isDone(stored));
537 assert.isFalse(yield* Ref.get(generated));
538 }),
539 ),
540 );
541
542 it.effect("writes the guide from the matching repository of a multi-repo workspace", () =>
543 Effect.scoped(
544 Effect.gen(function* () {
545 const repositories = yield* makeRepositories;
546 const generatedIn = yield* Deferred.make<string>();
547 const stored = yield* Deferred.make<void>();
548 const context = yield* Layer.build(
549 makeLayer({
550 ...repositories,
551 stored,
552 multiRepo: true,
553 generate: (input) =>
554 Deferred.succeed(generatedIn, input.cwd).pipe(Effect.as({ stops: [] })),
555 }),
556 );
557 const service = Context.get(
558 context,
559 PullRequestReviewGuideService.PullRequestReviewGuideService,
560 );
561 yield* service.generate(reference);
562 yield* Deferred.await(stored);
563 assert.notStrictEqual(yield* Deferred.await(generatedIn), repositories.root);
564 const result = yield* service.get(reference);
565 assert.strictEqual(result.guide?.headSha, repositories.headSha);
566 }),
567 ),
568 );
569
570 it.effect("refuses a pull request from a repository the project is not a checkout of", () =>
571 Effect.scoped(
572 Effect.gen(function* () {
573 const repositories = yield* makeRepositories;
574 const stored = yield* Deferred.make<void>();
575 const context = yield* Layer.build(
576 makeLayer({
577 ...repositories,
578 stored,
579 identity: {
580 ...ACME_APP,
581 canonicalKey: "github.com/acme/other",
582 displayName: "acme/other",
583 name: "other",
584 },
585 generate: () =>
586 Effect.die("a guide must not be written from another repository's checkout"),
587 }),
588 );
589 const service = Context.get(
590 context,
591 PullRequestReviewGuideService.PullRequestReviewGuideService,
592 );
593 const result = yield* Effect.flip(service.generate(reference));
594 assert.include(result.message, "in another repository");
595 }),
596 ),
597 );
598});