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