Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Ref from "effect/Ref";
10import * as Result from "effect/Result";
11import * as Semaphore from "effect/Semaphore";
12
13import {
14 PullRequestOperationError,
15 type PullRequestDetail,
16 type PullRequestRef,
17 type PullRequestReviewGuide,
18 type PullRequestReviewGuideResult,
19 type PullRequestReviewGuideRun,
20 type PullRequestStack,
21 ProjectId,
22 type RepositoryIdentity,
23 type ThreadPullRequestKey,
24} from "@t3tools/contracts";
25import type { ReviewGuideStackLayer } from "@t3tools/provider-core/server/textGeneration";
26import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
27import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
28
29import * as ServerConfig from "../config.ts";
30import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
31import * as ProjectService from "../project/ProjectService.ts";
32import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as TextGeneration from "../textGeneration/TextGeneration.ts";
35import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
36import { PATCH_RENDER_PREFIX_ARGS } from "../vcs/GitVcsDriverCore.ts";
37import * as PullRequestService from "./PullRequestService.ts";
38import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";
39import { reviewGuideInputFromPullRequest } from "./pullRequestReviewGuideInput.ts";
40import { normalizeReviewGuide, parseReviewGuideChange } from "./pullRequestReviewGuideNormalize.ts";
41
42const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,64}$/;
43
44export class PullRequestReviewGuideService extends Context.Service<
45 PullRequestReviewGuideService,
46 {
47 readonly get: (
48 input: PullRequestRef,
49 ) => Effect.Effect<PullRequestReviewGuideResult, PullRequestService.PullRequestError>;
50 readonly generate: (
51 input: PullRequestRef,
52 ) => Effect.Effect<
53 PullRequestReviewGuideResult & { readonly started: boolean },
54 PullRequestService.PullRequestError
55 >;
56 }
57>()("t3/pullRequest/PullRequestReviewGuideService") {}
58
59const keyString = (key: ThreadPullRequestKey) => `${key.host}/${key.repository}#${key.number}`;
60
61const nowIso = Clock.currentTimeMillis.pipe(
62 Effect.map((millis) => DateTime.formatIso(DateTime.makeUnsafe(millis))),
63);
64
65const make = Effect.gen(function* () {
66 const pullRequests = yield* PullRequestService.PullRequestService;
67 const guides = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
68 const projects = yield* ProjectService.ProjectService;
69 const serverSettings = yield* ServerSettings.ServerSettingsService;
70 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
71 const textGeneration = yield* TextGeneration.TextGeneration;
72 const git = yield* GitVcsDriver.GitVcsDriver;
73 const fileSystem = yield* FileSystem.FileSystem;
74 const config = yield* ServerConfig.ServerConfig;
75 const serviceScope = yield* Effect.scope;
76 const runs = yield* Ref.make<ReadonlyMap<string, PullRequestReviewGuideRun>>(new Map());
77 let runCounter = 0;
78 // Claiming a run and storing a finished guide take turns, so a run that still owns its pull
79 // request when it checks is the one whose guide is stored: a newer claim cannot land between.
80 const ownership = yield* Semaphore.make(1);
81
82 const keyFor = Effect.fn("PullRequestReviewGuideService.keyFor")(function* (
83 input: PullRequestRef,
84 ) {
85 const project = Option.getOrUndefined(
86 yield* projects.getShell(input.projectId).pipe(Effect.orElseSucceed(() => Option.none())),
87 );
88 const key = pullRequestSyncKey(input, project?.repositoryIdentity ?? undefined);
89 if (key === null || project === undefined) {
90 return yield* new PullRequestOperationError({
91 operation: "reviewGuide",
92 detail: "Could not identify this pull request's host.",
93 });
94 }
95 return { key, workspaceRoot: project.workspaceRoot, identity: project.repositoryIdentity };
96 });
97
98 const requireOwnRepository = Effect.fn("PullRequestReviewGuideService.requireOwnRepository")(
99 function* (key: ThreadPullRequestKey, identity: RepositoryIdentity | null | undefined) {
100 const own =
101 identity == null
102 ? null
103 : pullRequestSyncKey(
104 {
105 projectId: ProjectId.make("own"),
106 number: key.number,
107 repository: sourceControlRepositorySelector(identity) ?? "",
108 },
109 identity,
110 );
111 if (
112 identity == null ||
113 own === null ||
114 own.host !== key.host ||
115 own.repository !== key.repository
116 ) {
117 return yield* new PullRequestOperationError({
118 operation: "generateReviewGuide",
119 detail:
120 "Guides are written from this project's checkout, and this pull request is in another repository. Write it from a project that is a checkout of that repository.",
121 });
122 }
123 return identity.locator;
124 },
125 );
126
127 const readStored = (key: ThreadPullRequestKey) =>
128 guides.get(key).pipe(
129 Effect.mapError(
130 (cause) =>
131 new PullRequestOperationError({
132 operation: "reviewGuide",
133 detail: "Could not read the stored review guide.",
134 cause,
135 }),
136 ),
137 Effect.map(Option.getOrNull),
138 );
139
140 const get: PullRequestReviewGuideService["Service"]["get"] = Effect.fn(
141 "PullRequestReviewGuideService.get",
142 )(function* (input) {
143 const { key } = yield* keyFor(input);
144 const [guide, detail, current] = yield* Effect.all(
145 [readStored(key), pullRequests.detail(input), Ref.get(runs)],
146 { concurrency: "unbounded" },
147 );
148 return {
149 guide,
150 run: current.get(keyString(key)) ?? null,
151 currentHeadSha: detail.headSha ?? null,
152 };
153 });
154
155 const checkoutHead = Effect.fn("PullRequestReviewGuideService.checkoutHead")(function* (
156 workspaceRoot: string,
157 locator: RepositoryIdentity["locator"],
158 detail: PullRequestDetail,
159 headSha: string,
160 stack: PullRequestStack | null,
161 runId: string,
162 ) {
163 // Identity names can be stale; match effective fetch URLs, including insteadOf rewrites.
164 const names = yield* git
165 .execute({
166 operation: "PullRequestReviewGuideService.listRemotes",
167 cwd: workspaceRoot,
168 args: ["remote"],
169 })
170 .pipe(Effect.map((result) => result.stdout.split("\n").filter((name) => name.length > 0)));
171 const remote = yield* Effect.findFirst(
172 [locator.remoteName, ...names.filter((name) => name !== locator.remoteName)],
173 (name) =>
174 git
175 .execute({
176 operation: "PullRequestReviewGuideService.remoteUrl",
177 cwd: workspaceRoot,
178 args: ["remote", "get-url", "--", name],
179 })
180 .pipe(
181 Effect.map((result) => result.stdout.trim() === locator.remoteUrl),
182 Effect.orElseSucceed(() => false),
183 ),
184 ).pipe(Effect.map(Option.getOrUndefined));
185 if (remote === undefined) {
186 return yield* new PullRequestOperationError({
187 operation: "generateReviewGuide",
188 detail: "This project's checkout no longer has a remote for the pull request's repository.",
189 });
190 }
191 const fetch = (args: ReadonlyArray<string>) =>
192 git.execute({
193 operation: "PullRequestReviewGuideService.fetch",
194 cwd: workspaceRoot,
195 args: ["fetch", "--quiet", "--no-tags", "--", remote, ...args],
196 timeoutMs: 5 * 60_000,
197 });
198 // The host names the base branch. A name git rejects, or one that would change the refspec
199 // (a leading `+`, a `:`), is refused before it reaches `git fetch`.
200 yield* git
201 .execute({
202 operation: "PullRequestReviewGuideService.checkBaseBranch",
203 cwd: workspaceRoot,
204 args: ["check-ref-format", "--branch", detail.baseBranch],
205 })
206 .pipe(
207 Effect.filterOrFail(
208 () => !detail.baseBranch.startsWith("+") && !detail.baseBranch.includes(":"),
209 () =>
210 new PullRequestOperationError({
211 operation: "generateReviewGuide",
212 detail: "The pull request's base branch name is not one git can fetch.",
213 }),
214 ),
215 );
216 // Fetched into a ref of this run's own: FETCH_HEAD is shared by every fetch in the
217 // workspace, so a concurrent run could otherwise measure this change from its base.
218 const baseRef = `refs/t3/review-guide/${runId}/base`;
219 yield* fetch([`+refs/heads/${detail.baseBranch}:${baseRef}`]);
220 yield* Effect.addFinalizer(() =>
221 git
222 .execute({
223 operation: "PullRequestReviewGuideService.dropBaseRef",
224 cwd: workspaceRoot,
225 args: ["update-ref", "-d", baseRef],
226 })
227 .pipe(Effect.ignore({ log: true })),
228 );
229 const baseTip = yield* git.resolveCommit({ cwd: workspaceRoot, revision: baseRef });
230 const fetchHead = Effect.fn("PullRequestReviewGuideService.fetchHead")(function* (
231 number: number,
232 reportedSha: string,
233 branch: string,
234 ) {
235 const sha = reportedSha.toLowerCase();
236 if (!COMMIT_HASH_PATTERN.test(sha)) {
237 return yield* new PullRequestOperationError({
238 operation: "generateReviewGuide",
239 detail: `The host reported a head for #${number} that is not a commit hash.`,
240 });
241 }
242 // Not redundant: rev-parse prefers a branch or tag named like a short hash over the commit.
243 const resolveHead = git.resolveCommit({ cwd: workspaceRoot, revision: sha }).pipe(
244 Effect.filterOrFail(
245 ({ commitSha }) => commitSha.startsWith(sha),
246 ({ commitSha }) =>
247 new PullRequestOperationError({
248 operation: "generateReviewGuide",
249 detail: `${sha} names ${commitSha} here, a branch or tag rather than the commit.`,
250 }),
251 ),
252 );
253 const fetchAndResolve = (ref: string) => fetch([ref]).pipe(Effect.andThen(resolveHead));
254 const branchRef = `refs/heads/${branch}`;
255 const checkBranch = git.execute({
256 operation: "PullRequestReviewGuideService.checkHeadBranch",
257 cwd: workspaceRoot,
258 args: ["check-ref-format", branchRef],
259 });
260 const sources = [
261 { source: "local objects", head: resolveHead },
262 ...(sha.length === 40 || sha.length === 64
263 ? [{ source: "the commit", head: fetchAndResolve(sha) }]
264 : []),
265 {
266 source: `branch ${branch}`,
267 head: checkBranch.pipe(Effect.andThen(fetchAndResolve(branchRef))),
268 },
269 { source: `refs/pull/${number}/head`, head: fetchAndResolve(`refs/pull/${number}/head`) },
270 {
271 source: `refs/merge-requests/${number}/head`,
272 head: fetchAndResolve(`refs/merge-requests/${number}/head`),
273 },
274 ];
275 const failures: Array<string> = [];
276 for (const { source, head } of sources) {
277 const result = yield* Effect.result(head);
278 if (Result.isSuccess(result)) return result.success;
279 failures.push(`${source}: ${result.failure.detail}`);
280 }
281 return yield* new PullRequestOperationError({
282 operation: "generateReviewGuide",
283 detail: `Could not find head ${sha} of #${number}. ${failures.join(" ")}`,
284 });
285 });
286 const resolvedHead = yield* fetchHead(detail.number, headSha, detail.headBranch);
287 const layers: ReadonlyArray<ReviewGuideStackLayer> = yield* Effect.forEach(
288 stack?.layers ?? [],
289 (layer) => {
290 const described = { number: layer.number, title: layer.title ?? null, state: layer.state };
291 if (layer.number === detail.number) return Effect.succeed({ ...described, headSha });
292 const sha = layer.headSha;
293 if (sha === undefined) return Effect.succeed({ ...described, headSha: null });
294 return fetchHead(layer.number, sha, layer.headBranch).pipe(
295 Effect.map(({ commitSha }) => ({ ...described, headSha: commitSha })),
296 Effect.catch((error) =>
297 Effect.logInfo("Review guide could not read a stack layer's head", {
298 layer: layer.number,
299 detail: error.detail,
300 }).pipe(Effect.as({ ...described, headSha: null })),
301 ),
302 );
303 },
304 { concurrency: 4 },
305 );
306 const directory = yield* fileSystem.makeTempDirectoryScoped({
307 directory: config.worktreesDir,
308 prefix: "review-guide-",
309 });
310 const path = `${directory}/checkout`;
311 yield* git.execute({
312 operation: "PullRequestReviewGuideService.addWorktree",
313 cwd: workspaceRoot,
314 args: ["worktree", "add", "--detach", "--quiet", path, resolvedHead.commitSha],
315 timeoutMs: 5 * 60_000,
316 });
317 yield* Effect.addFinalizer(() =>
318 git
319 .removeWorktree({ cwd: workspaceRoot, path, force: true })
320 .pipe(Effect.ignore({ log: true })),
321 );
322 const mergeBase = yield* git.execute({
323 operation: "PullRequestReviewGuideService.mergeBase",
324 cwd: path,
325 args: ["merge-base", baseTip.commitSha, "HEAD"],
326 });
327 return { path, baseCommit: mergeBase.stdout.trim(), stack: layers };
328 });
329
330 const readChange = Effect.fn("PullRequestReviewGuideService.readChange")(function* (
331 cwd: string,
332 baseCommit: string,
333 ) {
334 const diff = (args: ReadonlyArray<string>) =>
335 git
336 .execute({
337 operation: "PullRequestReviewGuideService.readChange",
338 cwd,
339 // Fixed prefixes: a user's diff.noPrefix or custom prefixes would hide the headers the
340 // parser reads.
341 args: [
342 "-c",
343 "core.quotePath=false",
344 "diff",
345 ...PATCH_RENDER_PREFIX_ARGS,
346 ...args,
347 `${baseCommit}...HEAD`,
348 ],
349 timeoutMs: 60_000,
350 maxOutputBytes: 64 * 1024 * 1024,
351 })
352 .pipe(Effect.map((result) => result.stdout));
353 const [nameOnly, patch] = yield* Effect.all(
354 [diff(["--name-only", "-z"]), diff(["--unified=0", "--no-color", "--no-ext-diff"])],
355 { concurrency: "unbounded" },
356 );
357 return parseReviewGuideChange(nameOnly, patch);
358 });
359
360 const write = Effect.fn("PullRequestReviewGuideService.write")(function* (
361 input: PullRequestRef,
362 key: ThreadPullRequestKey,
363 workspaceRoot: string,
364 locator: RepositoryIdentity["locator"],
365 detail: PullRequestDetail,
366 headSha: string,
367 runId: string,
368 owns: Effect.Effect<boolean>,
369 ) {
370 const [activity, settings, providers, stack] = yield* Effect.all(
371 [
372 pullRequests.activity(input),
373 serverSettings.getSettings,
374 providerRegistry.getProviders,
375 pullRequests.stack(input).pipe(Effect.orElseSucceed(() => null)),
376 ],
377 { concurrency: "unbounded" },
378 );
379 const projectSettings = resolveProjectSettings(settings, input.projectId).settings;
380 const modelSelection = ServerSettings.resolveReviewGuideModelSelection(
381 projectSettings,
382 providers,
383 input.projectId,
384 );
385 const { generated, change } = yield* checkoutHead(
386 workspaceRoot,
387 locator,
388 detail,
389 headSha,
390 stack,
391 runId,
392 ).pipe(
393 Effect.flatMap((checkout) =>
394 Effect.all(
395 {
396 generated: textGeneration.generateReviewGuide({
397 ...reviewGuideInputFromPullRequest(detail, activity, checkout.baseCommit),
398 cwd: checkout.path,
399 modelSelection,
400 instructions: projectSettings.reviewGuideInstructions,
401 stack: checkout.stack,
402 }),
403 change: readChange(checkout.path, checkout.baseCommit),
404 },
405 { concurrency: "unbounded" },
406 ),
407 ),
408 Effect.scoped,
409 );
410 const guide: PullRequestReviewGuide = {
411 headSha,
412 generatedAt: yield* nowIso,
413 modelSelection,
414 ...normalizeReviewGuide(generated, change),
415 };
416 yield* ownership.withPermits(1)(
417 Effect.gen(function* () {
418 if (yield* owns) yield* guides.put(key, guide);
419 }),
420 );
421 });
422
423 const failureDetail = (cause: Cause.Cause<unknown>): string => {
424 const error = Cause.squash(cause);
425 if (error instanceof Error && "detail" in error && typeof error.detail === "string") {
426 return error.detail;
427 }
428 return "The review guide could not be written.";
429 };
430
431 const generate: PullRequestReviewGuideService["Service"]["generate"] = Effect.fn(
432 "PullRequestReviewGuideService.generate",
433 )(function* (input) {
434 const settings = yield* serverSettings.getSettings.pipe(
435 Effect.mapError(
436 (cause) =>
437 new PullRequestOperationError({
438 operation: "generateReviewGuide",
439 detail: "Could not read the server settings.",
440 cause,
441 }),
442 ),
443 );
444 if (!settings.reviewGuidesEnabled) {
445 return yield* new PullRequestOperationError({
446 operation: "generateReviewGuide",
447 detail: "Review guides are off. Turn them on in Settings → Source Control.",
448 });
449 }
450 const { key, workspaceRoot, identity } = yield* keyFor(input);
451 const locator = yield* requireOwnRepository(key, identity);
452 const runKey = keyString(key);
453 yield* pullRequests.invalidate({ reference: input });
454 const [detail, stored] = yield* Effect.all([pullRequests.detail(input), readStored(key)], {
455 concurrency: "unbounded",
456 });
457 const currentHeadSha = detail.headSha ?? null;
458 if (currentHeadSha === null) {
459 return yield* new PullRequestOperationError({
460 operation: "generateReviewGuide",
461 detail: "This host did not report the pull request's head commit.",
462 });
463 }
464 const running: PullRequestReviewGuideRun = {
465 _tag: "Running",
466 headSha: currentHeadSha,
467 startedAt: yield* nowIso,
468 };
469 // Claimed atomically, so two readers pressing Generate start one run between them. The head
470 // is read again under the claim: a press that read an older head before a push must not
471 // replace a run another press started for the new one, so it asks to be pressed again.
472 const claimed = yield* ownership.withPermits(1)(
473 pullRequests.detail(input).pipe(
474 Effect.flatMap((latest) =>
475 (latest.headSha ?? null) !== currentHeadSha
476 ? Effect.fail(
477 new PullRequestOperationError({
478 operation: "generateReviewGuide",
479 detail: "The pull request changed while the guide was starting. Try again.",
480 }),
481 )
482 : Ref.modify(runs, (current) => {
483 const existing = current.get(runKey);
484 if (existing?._tag === "Running" && existing.headSha === currentHeadSha) {
485 return [existing, current] as const;
486 }
487 return [running, new Map(current).set(runKey, running)] as const;
488 }),
489 ),
490 ),
491 );
492 if (claimed !== running) return { guide: stored, run: claimed, currentHeadSha, started: false };
493
494 const owns = Ref.get(runs).pipe(Effect.map((current) => current.get(runKey) === running));
495 const finish = (next: PullRequestReviewGuideRun | null) =>
496 Ref.update(runs, (current) => {
497 if (current.get(runKey) !== running) return current;
498 const updated = new Map(current);
499 if (next === null) updated.delete(runKey);
500 else updated.set(runKey, next);
501 return updated;
502 });
503 const runId = `${runCounter++}`;
504 yield* write(input, key, workspaceRoot, locator, detail, currentHeadSha, runId, owns).pipe(
505 Effect.andThen(finish(null)),
506 Effect.catchCause((cause) =>
507 Cause.hasInterruptsOnly(cause)
508 ? finish(null)
509 : Effect.logWarning("Review guide generation failed", {
510 key: runKey,
511 cause: Cause.pretty(cause),
512 }).pipe(
513 Effect.andThen(nowIso),
514 Effect.flatMap((failedAt) =>
515 finish({
516 _tag: "Failed",
517 headSha: currentHeadSha,
518 failedAt,
519 detail: failureDetail(cause),
520 }),
521 ),
522 ),
523 ),
524 Effect.forkIn(serviceScope),
525 );
526 return { guide: stored, run: running, currentHeadSha, started: true };
527 });
528
529 return PullRequestReviewGuideService.of({ get, generate });
530});
531
532export const layer = Layer.effect(PullRequestReviewGuideService, make);