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