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