Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestReviewGuideService.ts

496 lines19.0 KB

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 (own === null || own.host !== key.host || own.repository !== key.repository) {
112 return yield* new PullRequestOperationError({
113 operation: "generateReviewGuide",
114 detail:
115 "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.",
116 });
117 }
118 },
119 );
120​
121 const readStored = (key: ThreadPullRequestKey) =>
122 guides.get(key).pipe(
123 Effect.mapError(
124 (cause) =>
125 new PullRequestOperationError({
126 operation: "reviewGuide",
127 detail: "Could not read the stored review guide.",
128 cause,
129 }),
130 ),
131 Effect.map(Option.getOrNull),
132 );
133​
134 const get: PullRequestReviewGuideService["Service"]["get"] = Effect.fn(
135 "PullRequestReviewGuideService.get",
136 )(function* (input) {
137 const { key } = yield* keyFor(input);
138 const [guide, detail, current] = yield* Effect.all(
139 [readStored(key), pullRequests.detail(input), Ref.get(runs)],
140 { concurrency: "unbounded" },
141 );
142 return {
143 guide,
144 run: current.get(keyString(key)) ?? null,
145 currentHeadSha: detail.headSha ?? null,
146 };
147 });
148​
149 const checkoutHead = Effect.fn("PullRequestReviewGuideService.checkoutHead")(function* (
150 workspaceRoot: string,
151 detail: PullRequestDetail,
152 headSha: string,
153 stack: PullRequestStack | null,
154 runId: string,
155 ) {
156 const remote = yield* git.resolvePrimaryRemoteName(workspaceRoot);
157 const fetch = (args: ReadonlyArray<string>) =>
158 git.execute({
159 operation: "PullRequestReviewGuideService.fetch",
160 cwd: workspaceRoot,
161 args: ["fetch", "--quiet", "--no-tags", "--", remote, ...args],
162 timeoutMs: 5 * 60_000,
163 });
164 // The host names the base branch. A name git rejects, or one that would change the refspec
165 // (a leading `+`, a `:`), is refused before it reaches `git fetch`.
166 yield* git
167 .execute({
168 operation: "PullRequestReviewGuideService.checkBaseBranch",
169 cwd: workspaceRoot,
170 args: ["check-ref-format", "--branch", detail.baseBranch],
171 })
172 .pipe(
173 Effect.filterOrFail(
174 () => !detail.baseBranch.startsWith("+") && !detail.baseBranch.includes(":"),
175 () =>
176 new PullRequestOperationError({
177 operation: "generateReviewGuide",
178 detail: "The pull request's base branch name is not one git can fetch.",
179 }),
180 ),
181 );
182 // Fetched into a ref of this run's own: FETCH_HEAD is shared by every fetch in the
183 // workspace, so a concurrent run could otherwise measure this change from its base.
184 const baseRef = `refs/t3/review-guide/${runId}/base`;
185 yield* fetch([`+refs/heads/${detail.baseBranch}:${baseRef}`]);
186 yield* Effect.addFinalizer(() =>
187 git
188 .execute({
189 operation: "PullRequestReviewGuideService.dropBaseRef",
190 cwd: workspaceRoot,
191 args: ["update-ref", "-d", baseRef],
192 })
193 .pipe(Effect.ignore({ log: true })),
194 );
195 const baseTip = yield* git.resolveCommit({ cwd: workspaceRoot, revision: baseRef });
196 const fetchHead = Effect.fn("PullRequestReviewGuideService.fetchHead")(function* (
197 number: number,
198 reportedSha: string,
199 branch: string,
200 ) {
201 const sha = reportedSha.toLowerCase();
202 if (!COMMIT_HASH_PATTERN.test(sha)) {
203 return yield* new PullRequestOperationError({
204 operation: "generateReviewGuide",
205 detail: `The host reported a head for #${number} that is not a commit hash.`,
206 });
207 }
208 // Not redundant: rev-parse prefers a branch or tag named like a short hash over the commit.
209 const resolveHead = git.resolveCommit({ cwd: workspaceRoot, revision: sha }).pipe(
210 Effect.filterOrFail(
211 ({ commitSha }) => commitSha.startsWith(sha),
212 ({ commitSha }) =>
213 new PullRequestOperationError({
214 operation: "generateReviewGuide",
215 detail: `${sha} names ${commitSha} here, a branch or tag rather than the commit.`,
216 }),
217 ),
218 );
219 const fetchAndResolve = (ref: string) => fetch([ref]).pipe(Effect.andThen(resolveHead));
220 const branchRef = `refs/heads/${branch}`;
221 const checkBranch = git.execute({
222 operation: "PullRequestReviewGuideService.checkHeadBranch",
223 cwd: workspaceRoot,
224 args: ["check-ref-format", branchRef],
225 });
226 const sources = [
227 { source: "local objects", head: resolveHead },
228 ...(sha.length === 40 || sha.length === 64
229 ? [{ source: "the commit", head: fetchAndResolve(sha) }]
230 : []),
231 {
232 source: `branch ${branch}`,
233 head: checkBranch.pipe(Effect.andThen(fetchAndResolve(branchRef))),
234 },
235 { source: `refs/pull/${number}/head`, head: fetchAndResolve(`refs/pull/${number}/head`) },
236 {
237 source: `refs/merge-requests/${number}/head`,
238 head: fetchAndResolve(`refs/merge-requests/${number}/head`),
239 },
240 ];
241 const failures: Array<string> = [];
242 for (const { source, head } of sources) {
243 const result = yield* Effect.result(head);
244 if (Result.isSuccess(result)) return result.success;
245 failures.push(`${source}: ${result.failure.detail}`);
246 }
247 return yield* new PullRequestOperationError({
248 operation: "generateReviewGuide",
249 detail: `Could not find head ${sha} of #${number}. ${failures.join(" ")}`,
250 });
251 });
252 const resolvedHead = yield* fetchHead(detail.number, headSha, detail.headBranch);
253 const layers: ReadonlyArray<ReviewGuideStackLayer> = yield* Effect.forEach(
254 stack?.layers ?? [],
255 (layer) => {
256 const described = { number: layer.number, title: layer.title ?? null, state: layer.state };
257 if (layer.number === detail.number) return Effect.succeed({ ...described, headSha });
258 const sha = layer.headSha;
259 if (sha === undefined) return Effect.succeed({ ...described, headSha: null });
260 return fetchHead(layer.number, sha, layer.headBranch).pipe(
261 Effect.map(({ commitSha }) => ({ ...described, headSha: commitSha })),
262 Effect.catch((error) =>
263 Effect.logInfo("Review guide could not read a stack layer's head", {
264 layer: layer.number,
265 detail: error.detail,
266 }).pipe(Effect.as({ ...described, headSha: null })),
267 ),
268 );
269 },
270 { concurrency: 4 },
271 );
272 const directory = yield* fileSystem.makeTempDirectoryScoped({
273 directory: config.worktreesDir,
274 prefix: "review-guide-",
275 });
276 const path = `${directory}/checkout`;
277 yield* git.execute({
278 operation: "PullRequestReviewGuideService.addWorktree",
279 cwd: workspaceRoot,
280 args: ["worktree", "add", "--detach", "--quiet", path, resolvedHead.commitSha],
281 timeoutMs: 5 * 60_000,
282 });
283 yield* Effect.addFinalizer(() =>
284 git
285 .removeWorktree({ cwd: workspaceRoot, path, force: true })
286 .pipe(Effect.ignore({ log: true })),
287 );
288 const mergeBase = yield* git.execute({
289 operation: "PullRequestReviewGuideService.mergeBase",
290 cwd: path,
291 args: ["merge-base", baseTip.commitSha, "HEAD"],
292 });
293 return { path, baseCommit: mergeBase.stdout.trim(), stack: layers };
294 });
295​
296 const readChange = Effect.fn("PullRequestReviewGuideService.readChange")(function* (
297 cwd: string,
298 baseCommit: string,
299 ) {
300 const diff = (args: ReadonlyArray<string>) =>
301 git
302 .execute({
303 operation: "PullRequestReviewGuideService.readChange",
304 cwd,
305 // Fixed prefixes: a user's diff.noPrefix or custom prefixes would hide the headers the
306 // parser reads.
307 args: [
308 "-c",
309 "core.quotePath=false",
310 "diff",
311 ...PATCH_RENDER_PREFIX_ARGS,
312 ...args,
313 `${baseCommit}...HEAD`,
314 ],
315 timeoutMs: 60_000,
316 maxOutputBytes: 64 * 1024 * 1024,
317 })
318 .pipe(Effect.map((result) => result.stdout));
319 const [nameOnly, patch] = yield* Effect.all(
320 [diff(["--name-only", "-z"]), diff(["--unified=0", "--no-color", "--no-ext-diff"])],
321 { concurrency: "unbounded" },
322 );
323 return parseReviewGuideChange(nameOnly, patch);
324 });
325​
326 const write = Effect.fn("PullRequestReviewGuideService.write")(function* (
327 input: PullRequestRef,
328 key: ThreadPullRequestKey,
329 workspaceRoot: string,
330 detail: PullRequestDetail,
331 headSha: string,
332 runId: string,
333 owns: Effect.Effect<boolean>,
334 ) {
335 const [activity, settings, providers, stack] = yield* Effect.all(
336 [
337 pullRequests.activity(input),
338 serverSettings.getSettings,
339 providerRegistry.getProviders,
340 pullRequests.stack(input).pipe(Effect.orElseSucceed(() => null)),
341 ],
342 { concurrency: "unbounded" },
343 );
344 const projectSettings = resolveProjectSettings(settings, input.projectId).settings;
345 const modelSelection = ServerSettings.resolveReviewGuideModelSelection(
346 projectSettings,
347 providers,
348 input.projectId,
349 );
350 const { generated, change } = yield* checkoutHead(
351 workspaceRoot,
352 detail,
353 headSha,
354 stack,
355 runId,
356 ).pipe(
357 Effect.flatMap((checkout) =>
358 Effect.all(
359 {
360 generated: textGeneration.generateReviewGuide({
361 ...reviewGuideInputFromPullRequest(detail, activity, checkout.baseCommit),
362 cwd: checkout.path,
363 modelSelection,
364 instructions: projectSettings.reviewGuideInstructions,
365 stack: checkout.stack,
366 }),
367 change: readChange(checkout.path, checkout.baseCommit),
368 },
369 { concurrency: "unbounded" },
370 ),
371 ),
372 Effect.scoped,
373 );
374 const guide: PullRequestReviewGuide = {
375 headSha,
376 generatedAt: yield* nowIso,
377 modelSelection,
378 ...normalizeReviewGuide(generated, change),
379 };
380 yield* ownership.withPermits(1)(
381 Effect.gen(function* () {
382 if (yield* owns) yield* guides.put(key, guide);
383 }),
384 );
385 });
386​
387 const failureDetail = (cause: Cause.Cause<unknown>): string => {
388 const error = Cause.squash(cause);
389 if (error instanceof Error && "detail" in error && typeof error.detail === "string") {
390 return error.detail;
391 }
392 return "The review guide could not be written.";
393 };
394​
395 const generate: PullRequestReviewGuideService["Service"]["generate"] = Effect.fn(
396 "PullRequestReviewGuideService.generate",
397 )(function* (input) {
398 const settings = yield* serverSettings.getSettings.pipe(
399 Effect.mapError(
400 (cause) =>
401 new PullRequestOperationError({
402 operation: "generateReviewGuide",
403 detail: "Could not read the server settings.",
404 cause,
405 }),
406 ),
407 );
408 if (!settings.reviewGuidesEnabled) {
409 return yield* new PullRequestOperationError({
410 operation: "generateReviewGuide",
411 detail: "Review guides are off. Turn them on in Settings → Source Control.",
412 });
413 }
414 const { key, workspaceRoot, identity } = yield* keyFor(input);
415 yield* requireOwnRepository(key, identity);
416 const runKey = keyString(key);
417 yield* pullRequests.invalidate({ reference: input });
418 const [detail, stored] = yield* Effect.all([pullRequests.detail(input), readStored(key)], {
419 concurrency: "unbounded",
420 });
421 const currentHeadSha = detail.headSha ?? null;
422 if (currentHeadSha === null) {
423 return yield* new PullRequestOperationError({
424 operation: "generateReviewGuide",
425 detail: "This host did not report the pull request's head commit.",
426 });
427 }
428 const running: PullRequestReviewGuideRun = {
429 _tag: "Running",
430 headSha: currentHeadSha,
431 startedAt: yield* nowIso,
432 };
433 // Claimed atomically, so two readers pressing Generate start one run between them. The head
434 // is read again under the claim: a press that read an older head before a push must not
435 // replace a run another press started for the new one, so it asks to be pressed again.
436 const claimed = yield* ownership.withPermits(1)(
437 pullRequests.detail(input).pipe(
438 Effect.flatMap((latest) =>
439 (latest.headSha ?? null) !== currentHeadSha
440 ? Effect.fail(
441 new PullRequestOperationError({
442 operation: "generateReviewGuide",
443 detail: "The pull request changed while the guide was starting. Try again.",
444 }),
445 )
446 : Ref.modify(runs, (current) => {
447 const existing = current.get(runKey);
448 if (existing?._tag === "Running" && existing.headSha === currentHeadSha) {
449 return [existing, current] as const;
450 }
451 return [running, new Map(current).set(runKey, running)] as const;
452 }),
453 ),
454 ),
455 );
456 if (claimed !== running) return { guide: stored, run: claimed, currentHeadSha, started: false };
457​
458 const owns = Ref.get(runs).pipe(Effect.map((current) => current.get(runKey) === running));
459 const finish = (next: PullRequestReviewGuideRun | null) =>
460 Ref.update(runs, (current) => {
461 if (current.get(runKey) !== running) return current;
462 const updated = new Map(current);
463 if (next === null) updated.delete(runKey);
464 else updated.set(runKey, next);
465 return updated;
466 });
467 const runId = `${runCounter++}`;
468 yield* write(input, key, workspaceRoot, detail, currentHeadSha, runId, owns).pipe(
469 Effect.andThen(finish(null)),
470 Effect.catchCause((cause) =>
471 Cause.hasInterruptsOnly(cause)
472 ? finish(null)
473 : Effect.logWarning("Review guide generation failed", {
474 key: runKey,
475 cause: Cause.pretty(cause),
476 }).pipe(
477 Effect.andThen(nowIso),
478 Effect.flatMap((failedAt) =>
479 finish({
480 _tag: "Failed",
481 headSha: currentHeadSha,
482 failedAt,
483 detail: failureDetail(cause),
484 }),
485 ),
486 ),
487 ),
488 Effect.forkIn(serviceScope),
489 );
490 return { guide: stored, run: running, currentHeadSha, started: true };
491 });
492​
493 return PullRequestReviewGuideService.of({ get, generate });
494});
495​
496export const layer = Layer.effect(PullRequestReviewGuideService, make);