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