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 FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Ref from "effect/Ref";
9import * as Schedule from "effect/Schedule";
10import {
11 ProjectId,
12 type PullRequestActivity,
13 type PullRequestDetail,
14 type PullRequestStack,
15 type PullRequestRef,
16} from "@t3tools/contracts";
17import type { ReviewGuideGenerationInput } from "@t3tools/provider-core/server/textGeneration";
18
19import * as ServerConfig from "../config.ts";
20import * as SqlitePersistence from "../persistence/Sqlite.ts";
21import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
22import * as ProjectService from "../project/ProjectService.ts";
23import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
24import * as ServerSettings from "../serverSettings.ts";
25import * as TextGeneration from "../textGeneration/TextGeneration.ts";
26import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
27import * as VcsProcess from "../vcs/VcsProcess.ts";
28import * as PullRequestReviewGuideService from "./PullRequestReviewGuideService.ts";
29import * as PullRequestService from "./PullRequestService.ts";
30
31const projectId = ProjectId.make("project-1");
32/** The test project is a checkout of the repository its pull requests come from. */
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
60/**
61 * A remote whose `main` has moved on past where the change's base branch left it, with the
62 * change stacked on that base branch. A guide for the change must see only its own commit.
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 // Ten lines, so an excerpt reaching past them has something to be clamped to.
86 const headSha = yield* commit(
87 "feature.txt",
88 "the change",
89 Array.from({ length: 10 }, (_, index) => `line ${index + 1}`).join("\n") + "\n",
90 );
91 // A layer above the change, which uses what the change adds.
92 yield* git(remote, ["checkout", "--quiet", "-b", "upper"]);
93 const upperSha = yield* commit("upper.txt", "upper layer");
94 yield* git(remote, ["checkout", "--quiet", "main"]);
95 yield* commit("unrelated.txt", "main moved on");
96 yield* git(root, ["clone", "--quiet", remote, workspace]);
97 return { root, workspace, headSha, lowerSha, upperSha };
98});
99
100const detail = (workspaceRoot: string, headSha: string): PullRequestDetail =>
101 ({
102 number: 7,
103 title: "Add the feature",
104 body: "Adds the feature.",
105 baseBranch: "stack-base",
106 headBranch: "feature",
107 headSha,
108 workspaceRoot,
109 }) as PullRequestDetail;
110
111const activity: PullRequestActivity = {
112 comments: [],
113 commentCount: 0,
114 commentsTruncated: false,
115 reviewThreads: [],
116 commits: [],
117};
118
119/** The change as the middle layer of three; the top layer's head is not on any fetched branch. */
120const stack = (repositories: {
121 readonly headSha: string;
122 readonly lowerSha: string;
123 readonly upperSha: string;
124}): PullRequestStack => ({
125 id: "stack",
126 number: 1,
127 url: "https://example.com/stack/1",
128 base: "main",
129 layers: [
130 {
131 number: 6,
132 title: "Lower",
133 headSha: repositories.lowerSha,
134 headBranch: "stack-base",
135 state: "open",
136 },
137 {
138 number: 7,
139 title: "Add the feature",
140 headSha: repositories.headSha,
141 headBranch: "feature",
142 state: "open",
143 },
144 {
145 number: 8,
146 title: "Upper",
147 headSha: repositories.upperSha,
148 headBranch: "upper",
149 state: "open",
150 },
151 { number: 9, title: "Unpushed", headSha: "f".repeat(40), headBranch: "gone", state: "open" },
152 ],
153});
154
155const makeLayer = (input: {
156 readonly root: string;
157 readonly workspace: string;
158 readonly headSha: string;
159 readonly lowerSha: string;
160 readonly upperSha: string;
161 readonly generate: TextGeneration.TextGeneration["Service"]["generateReviewGuide"];
162 /** Completed when a run stores its guide, which is the last thing a run does but forget it. */
163 readonly stored: Deferred.Deferred<void>;
164 /** The server's beta switch; on unless a test is about it being off. */
165 readonly enabled?: boolean;
166 /** The head the host reports now, for a test that pushes between runs. */
167 readonly currentHead?: Ref.Ref<string>;
168 /** The project's own repository; defaults to the one the test reference names. */
169 readonly identity?: typeof ACME_APP;
170}) =>
171 PullRequestReviewGuideService.layer.pipe(
172 Layer.provide(
173 Layer.effect(
174 PullRequestReviewGuides.PullRequestReviewGuideRepository,
175 Effect.gen(function* () {
176 const repository = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
177 return {
178 get: repository.get,
179 put: (key, guide) =>
180 repository
181 .put(key, guide)
182 .pipe(Effect.tap(() => Deferred.succeed(input.stored, undefined))),
183 } satisfies PullRequestReviewGuides.PullRequestReviewGuideRepository["Service"];
184 }),
185 ).pipe(Layer.provide(PullRequestReviewGuides.layer)),
186 ),
187 Layer.provide(
188 Layer.succeed(PullRequestService.PullRequestService, {
189 detail: () =>
190 (input.currentHead === undefined
191 ? Effect.succeed(input.headSha)
192 : Ref.get(input.currentHead)
193 ).pipe(Effect.map((head) => detail(input.workspace, head))),
194 activity: () => Effect.succeed(activity),
195 invalidate: () => Effect.void,
196 stack: () => Effect.succeed(stack(input)),
197 } as unknown as PullRequestService.PullRequestService["Service"]),
198 ),
199 Layer.provide(
200 Layer.succeed(ProjectService.ProjectService, {
201 getShell: () =>
202 Effect.succeedSome({
203 id: projectId,
204 workspaceRoot: input.workspace,
205 repositoryIdentity: input.identity ?? ACME_APP,
206 }),
207 } as unknown as ProjectService.ProjectService["Service"]),
208 ),
209 Layer.provide(
210 Layer.succeed(ProviderRegistry.ProviderRegistry, {
211 getProviders: Effect.succeed([]),
212 } as unknown as ProviderRegistry.ProviderRegistry["Service"]),
213 ),
214 Layer.provide(
215 Layer.succeed(TextGeneration.TextGeneration, {
216 generateReviewGuide: input.generate,
217 } as unknown as TextGeneration.TextGeneration["Service"]),
218 ),
219 Layer.provide(ServerSettings.layerTest({ reviewGuidesEnabled: input.enabled ?? true })),
220 Layer.provide(ServerConfig.layerTest(input.root, { prefix: "t3-review-guide-config-" })),
221 );
222
223const layerBase = Layer.mergeAll(
224 GitVcsDriver.layer.pipe(
225 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-review-guide-git-" })),
226 Layer.provideMerge(VcsProcess.layer),
227 ),
228 SqlitePersistence.layerMemory,
229).pipe(Layer.provideMerge(NodeServices.layer));
230
231// Runs drive real git, which the test clock does not advance, so waits use real time.
232it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
233 it.effect("briefs the change against its own base in a checkout it then removes", () =>
234 Effect.scoped(
235 Effect.gen(function* () {
236 const repositories = yield* makeRepositories;
237 const seen = yield* Deferred.make<{
238 readonly input: ReviewGuideGenerationInput;
239 readonly changed: string;
240 readonly head: string;
241 readonly upper: string;
242 }>();
243 const finish = yield* Deferred.make<void>();
244 // The fake model reads the checkout with the same driver, captured so it needs nothing.
245 const driver = yield* GitVcsDriver.GitVcsDriver;
246 const readCheckout = (cwd: string, args: ReadonlyArray<string>) =>
247 git(cwd, args).pipe(
248 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
249 Effect.orDie,
250 );
251 const stored = yield* Deferred.make<void>();
252
253 // Built in this test's scope: runs are forked into the service's scope and must outlive
254 // the call that obtains the service.
255 const context = yield* Layer.build(
256 makeLayer({
257 ...repositories,
258 stored,
259 generate: (input) =>
260 Effect.gen(function* () {
261 const changed = yield* readCheckout(input.cwd, [
262 "diff",
263 "--name-only",
264 `${input.baseCommit}...HEAD`,
265 ]);
266 const head = yield* readCheckout(input.cwd, ["rev-parse", "HEAD"]);
267 // Another layer's head is readable from the checkout, to check a seam.
268 const upper = yield* readCheckout(input.cwd, [
269 "show",
270 `${repositories.upperSha}:upper.txt`,
271 ]);
272 yield* Deferred.succeed(seen, { input, changed, head, upper });
273 yield* Deferred.await(finish);
274 // Written the way a model gets it wrong: an excerpt past the end of the file, a
275 // note outside what is left of it, and a changed file left off the tour.
276 return {
277 stops: [
278 {
279 title: "The feature",
280 summary: "The change.",
281 attention: null,
282 excerpts: [
283 { path: "feature.txt", side: "new", start: 4, end: 40, caption: "" },
284 ],
285 files: [],
286 notes: [
287 { path: "feature.txt", line: 5, title: "Kept", body: "Inside." },
288 { path: "feature.txt", line: 30, title: "Dropped", body: "Outside." },
289 ],
290 questions: [],
291 },
292 ],
293 };
294 }),
295 }),
296 );
297 const service = Context.get(
298 context,
299 PullRequestReviewGuideService.PullRequestReviewGuideService,
300 );
301
302 // Generate returns while the run is still reading the change.
303 const started = yield* service.generate(reference);
304 assert.strictEqual(started.run?._tag, "Running");
305 assert.strictEqual(started.guide, null);
306 assert.isTrue(started.started);
307
308 // A run that fails before reaching the model reports why rather than leaving this waiting.
309 const failedRun = service.get(reference).pipe(
310 Effect.flatMap((result) =>
311 result.run?._tag === "Failed"
312 ? Effect.die(`run failed: ${result.run.detail}`)
313 : Effect.fail("still running" as const),
314 ),
315 Effect.retry(Schedule.spaced("20 millis")),
316 );
317 const observed = yield* Effect.raceFirst(Deferred.await(seen), failedRun);
318 assert.strictEqual(observed.head, repositories.headSha);
319 assert.strictEqual(observed.changed, "feature.txt");
320 assert.strictEqual(observed.input.baseBranch, "stack-base");
321 // The stack comes along, bottom first; a layer whose head could not be fetched is named
322 // without one.
323 assert.deepStrictEqual(observed.input.stack, [
324 { number: 6, title: "Lower", state: "open", headSha: repositories.lowerSha },
325 { number: 7, title: "Add the feature", state: "open", headSha: repositories.headSha },
326 { number: 8, title: "Upper", state: "open", headSha: repositories.upperSha },
327 { number: 9, title: "Unpushed", state: "open", headSha: null },
328 ]);
329 assert.strictEqual(observed.upper, "upper layer");
330
331 // A second press while running joins the run instead of starting another.
332 const joined = yield* service.generate(reference);
333 assert.strictEqual(joined.run, started.run);
334 assert.isFalse(joined.started);
335
336 yield* Deferred.succeed(finish, undefined);
337 yield* Deferred.await(stored);
338 const finished = yield* service.get(reference);
339 assert.strictEqual(finished.guide?.headSha, repositories.headSha);
340 const guide = finished.guide;
341 assert.isNotNull(guide);
342 const [story] = guide.stops;
343 assert.deepStrictEqual(story?.excerpts, [
344 { path: "feature.txt", side: "new", start: 4, end: 10, caption: "" },
345 ]);
346 assert.deepStrictEqual(
347 story?.notes.map((note) => note.title),
348 ["Kept"],
349 );
350 // lower.txt is below the change's base, so it is neither in the change nor on the tour.
351 assert.strictEqual(guide.stops.length, 1);
352
353 const fs = yield* FileSystem.FileSystem;
354 assert.isFalse(yield* fs.exists(observed.input.cwd));
355 const worktrees = yield* git(repositories.workspace, ["worktree", "list", "--porcelain"]);
356 assert.notInclude(worktrees, observed.input.cwd);
357 }),
358 ),
359 );
360
361 it.effect("refuses to write a guide while the server has review guides off", () =>
362 Effect.scoped(
363 Effect.gen(function* () {
364 const repositories = yield* makeRepositories;
365 const stored = yield* Deferred.make<void>();
366 const context = yield* Layer.build(
367 makeLayer({
368 ...repositories,
369 stored,
370 enabled: false,
371 generate: () => Effect.die("a guide must not be written while the beta is off"),
372 }),
373 );
374 const service = Context.get(
375 context,
376 PullRequestReviewGuideService.PullRequestReviewGuideService,
377 );
378 const result = yield* Effect.flip(service.generate(reference));
379 assert.include(result.message, "Review guides are off");
380 }),
381 ),
382 );
383
384 it.effect(
385 "keeps a newer run's guide when an older run for the same pull request finishes late",
386 () =>
387 Effect.scoped(
388 Effect.gen(function* () {
389 const repositories = yield* makeRepositories;
390 const stored = yield* Deferred.make<void>();
391 const currentHead = yield* Ref.make(repositories.headSha);
392 // The old run waits on this; the new one answers at once.
393 const releaseOld = yield* Deferred.make<void>();
394 const oldStarted = yield* Deferred.make<void>();
395 const answer = (title: string) => ({
396 stops: [
397 {
398 title,
399 summary: "",
400 attention: null,
401 excerpts: [],
402 files: [],
403 notes: [],
404 questions: [],
405 },
406 ],
407 });
408 const context = yield* Layer.build(
409 makeLayer({
410 ...repositories,
411 stored,
412 currentHead,
413 generate: (input) =>
414 input.cwd.length > 0 && input.baseCommit.length > 0
415 ? Ref.get(currentHead).pipe(
416 Effect.flatMap((head) =>
417 head === repositories.headSha
418 ? Deferred.succeed(oldStarted, undefined).pipe(
419 Effect.andThen(Deferred.await(releaseOld)),
420 Effect.as(answer("old head")),
421 )
422 : Effect.succeed(answer("new head")),
423 ),
424 )
425 : Effect.die("unreachable"),
426 }),
427 );
428 const service = Context.get(
429 context,
430 PullRequestReviewGuideService.PullRequestReviewGuideService,
431 );
432
433 yield* service.generate(reference);
434 const firstFailed = service.get(reference).pipe(
435 Effect.flatMap((result) =>
436 result.run?._tag === "Failed"
437 ? Effect.die(`first run failed: ${result.run.detail}`)
438 : Effect.fail("still running" as const),
439 ),
440 Effect.retry(Schedule.spaced("20 millis")),
441 );
442 yield* Effect.raceFirst(Deferred.await(oldStarted), firstFailed);
443 // A push: the host reports the upper layer's commit as the head now, and a new run starts.
444 yield* Ref.set(currentHead, repositories.upperSha);
445 const second = yield* service.generate(reference);
446 assert.strictEqual(second.run?._tag, "Running");
447 assert.strictEqual(second.run?.headSha, repositories.upperSha);
448 // A run that fails reports why rather than leaving this waiting.
449 const failedRun = service.get(reference).pipe(
450 Effect.flatMap((result) =>
451 result.run?._tag === "Failed"
452 ? Effect.die(`run failed: ${result.run.detail}`)
453 : Effect.fail("still running" as const),
454 ),
455 Effect.retry(Schedule.spaced("20 millis")),
456 );
457 yield* Effect.raceFirst(Deferred.await(stored), failedRun);
458
459 // The old run finishes last. Its guide is for a head nobody is looking at any more.
460 yield* Deferred.succeed(releaseOld, undefined);
461 const settled = yield* service.get(reference).pipe(
462 Effect.filterOrFail(
463 (result) => result.run === null,
464 () => "still running" as const,
465 ),
466 Effect.retry({ schedule: Schedule.spaced("20 millis"), times: 250 }),
467 );
468 assert.strictEqual(settled.guide?.headSha, repositories.upperSha);
469 // Give the late run every chance to write over the newer guide; it must not.
470 yield* Effect.sleep("200 millis");
471 const after = yield* service.get(reference);
472 assert.isNull(after.run);
473 assert.strictEqual(after.guide?.headSha, repositories.upperSha);
474 assert.strictEqual(after.guide?.stops[0]?.title, "new head");
475 }),
476 ),
477 );
478
479 it.effect("refuses a pull request from a repository the project is not a checkout of", () =>
480 Effect.scoped(
481 Effect.gen(function* () {
482 const repositories = yield* makeRepositories;
483 const stored = yield* Deferred.make<void>();
484 const context = yield* Layer.build(
485 makeLayer({
486 ...repositories,
487 stored,
488 identity: {
489 ...ACME_APP,
490 canonicalKey: "github.com/acme/other",
491 displayName: "acme/other",
492 name: "other",
493 },
494 generate: () =>
495 Effect.die("a guide must not be written from another repository's checkout"),
496 }),
497 );
498 const service = Context.get(
499 context,
500 PullRequestReviewGuideService.PullRequestReviewGuideService,
501 );
502 const result = yield* Effect.flip(service.generate(reference));
503 assert.include(result.message, "in another repository");
504 }),
505 ),
506 );
507});