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

PullRequestReviewGuideService.ts

489 lines20.1 KB

1/**
2 * Guided reviews: a maintainer-facing brief on a pull request, written by the environment's
3 * source-control writer model. See `PullRequestReviewGuide` in contracts for what a guide is for.
4 *
5 * The model reads the change itself, read-only, from a disposable checkout of the head, so a
6 * guide has no size limit. That takes minutes on a large change, so a run belongs to the server
7 * rather than to the request that started it: Generate returns as soon as the run is under way
8 * and readers watch its state through `get`.
9 *
10 * Generation is explicit and the result is stored per pull request, so opening a guide never
11 * spends a model run. A push leaves the stored guide in place and the reader sees it as stale.
12 *
13 * @module pullRequest/PullRequestReviewGuideService
14 */
15import * as Cause from "effect/Cause";
16import * as Clock from "effect/Clock";
17import * as Context from "effect/Context";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Ref from "effect/Ref";
24import * as Semaphore from "effect/Semaphore";
25​
26import {
27 PullRequestOperationError,
28 type PullRequestDetail,
29 type PullRequestRef,
30 type PullRequestReviewGuide,
31 type PullRequestReviewGuideResult,
32 type PullRequestReviewGuideRun,
33 type PullRequestStack,
34 ProjectId,
35 type RepositoryIdentity,
36 type ThreadPullRequestKey,
37} from "@t3tools/contracts";
38import type { ReviewGuideStackLayer } from "@t3tools/provider-core/server/textGeneration";
39import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
40import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
41​
42import * as ServerConfig from "../config.ts";
43import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
44import * as ProjectService from "../project/ProjectService.ts";
45import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
46import * as ServerSettings from "../serverSettings.ts";
47import * as TextGeneration from "../textGeneration/TextGeneration.ts";
48import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
49import { PATCH_RENDER_PREFIX_ARGS } from "../vcs/GitVcsDriverCore.ts";
50import * as PullRequestService from "./PullRequestService.ts";
51import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";
52import { reviewGuideInputFromPullRequest } from "./pullRequestReviewGuideInput.ts";
53import { normalizeReviewGuide, parseReviewGuideChange } from "./pullRequestReviewGuideNormalize.ts";
54​
55export class PullRequestReviewGuideService extends Context.Service<
56 PullRequestReviewGuideService,
57 {
58 /** The stored guide, any run in progress, and the head now. Never runs a model. */
59 readonly get: (
60 input: PullRequestRef,
61 ) => Effect.Effect<PullRequestReviewGuideResult, PullRequestService.PullRequestError>;
62 /**
63 * Start writing a guide for the current head and return once it is under way. Joins a run
64 * already going for that head. A stored guide stays readable until the new one replaces it,
65 * so a reader can rewrite one after changing the guide model or instructions. `started` says
66 * whether this call began the run or joined one already going.
67 */
68 readonly generate: (
69 input: PullRequestRef,
70 ) => Effect.Effect<
71 PullRequestReviewGuideResult & { readonly started: boolean },
72 PullRequestService.PullRequestError
73 >;
74 }
75>()("t3/pullRequest/PullRequestReviewGuideService") {}
76​
77const keyString = (key: ThreadPullRequestKey) => `${key.host}/${key.repository}#${key.number}`;
78​
79const nowIso = Clock.currentTimeMillis.pipe(
80 Effect.map((millis) => DateTime.formatIso(DateTime.makeUnsafe(millis))),
81);
82​
83const make = Effect.gen(function* () {
84 const pullRequests = yield* PullRequestService.PullRequestService;
85 const guides = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
86 const projects = yield* ProjectService.ProjectService;
87 const serverSettings = yield* ServerSettings.ServerSettingsService;
88 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
89 const textGeneration = yield* TextGeneration.TextGeneration;
90 const git = yield* GitVcsDriver.GitVcsDriver;
91 const fileSystem = yield* FileSystem.FileSystem;
92 const config = yield* ServerConfig.ServerConfig;
93 // Runs outlive the request that started them and end with the server.
94 const serviceScope = yield* Effect.scope;
95 // In memory on purpose: a restart drops a run in progress, and a reader presses Generate again.
96 const runs = yield* Ref.make<ReadonlyMap<string, PullRequestReviewGuideRun>>(new Map());
97 // Names each run's private git refs; unique for the server's lifetime, like the runs map.
98 let runCounter = 0;
99 // Claiming a run and storing a finished guide take turns, so a run that still owns its pull
100 // request when it checks is the one whose guide is stored: a newer claim cannot land between.
101 const ownership = yield* Semaphore.make(1);
102​
103 const keyFor = Effect.fn("PullRequestReviewGuideService.keyFor")(function* (
104 input: PullRequestRef,
105 ) {
106 const project = Option.getOrUndefined(
107 yield* projects.getShell(input.projectId).pipe(Effect.orElseSucceed(() => Option.none())),
108 );
109 const key = pullRequestSyncKey(input, project?.repositoryIdentity ?? undefined);
110 if (key === null || project === undefined) {
111 return yield* new PullRequestOperationError({
112 operation: "reviewGuide",
113 detail: "Could not identify this pull request's host.",
114 });
115 }
116 return { key, workspaceRoot: project.workspaceRoot, identity: project.repositoryIdentity };
117 });
118​
119 /**
120 * A guide reads the change in a checkout fetched from the project's own remote, so the pull
121 * request has to be in that repository. One from another repository is refused rather than
122 * measured against commits that are not its own.
123 */
124 const requireOwnRepository = Effect.fn("PullRequestReviewGuideService.requireOwnRepository")(
125 function* (key: ThreadPullRequestKey, identity: RepositoryIdentity | null | undefined) {
126 const own =
127 identity == null
128 ? null
129 : pullRequestSyncKey(
130 {
131 projectId: ProjectId.make("own"),
132 number: key.number,
133 repository: sourceControlRepositorySelector(identity) ?? "",
134 },
135 identity,
136 );
137 if (own === null || own.host !== key.host || own.repository !== key.repository) {
138 return yield* new PullRequestOperationError({
139 operation: "generateReviewGuide",
140 detail:
141 "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.",
142 });
143 }
144 },
145 );
146​
147 const readStored = (key: ThreadPullRequestKey) =>
148 guides.get(key).pipe(
149 Effect.mapError(
150 (cause) =>
151 new PullRequestOperationError({
152 operation: "reviewGuide",
153 detail: "Could not read the stored review guide.",
154 cause,
155 }),
156 ),
157 Effect.map(Option.getOrNull),
158 );
159​
160 const get: PullRequestReviewGuideService["Service"]["get"] = Effect.fn(
161 "PullRequestReviewGuideService.get",
162 )(function* (input) {
163 const { key } = yield* keyFor(input);
164 const [guide, detail, current] = yield* Effect.all(
165 [readStored(key), pullRequests.detail(input), Ref.get(runs)],
166 { concurrency: "unbounded" },
167 );
168 return {
169 guide,
170 run: current.get(keyString(key)) ?? null,
171 currentHeadSha: detail.headSha ?? null,
172 };
173 });
174​
175 /**
176 * A detached checkout of the head beside the project, removed when the run ends. Fetched by
177 * commit rather than by branch so a fork's head and a branch checked out elsewhere both work,
178 * and so the checkout is exactly what the host reported.
179 */
180 const checkoutHead = Effect.fn("PullRequestReviewGuideService.checkoutHead")(function* (
181 workspaceRoot: string,
182 detail: PullRequestDetail,
183 headSha: string,
184 stack: PullRequestStack | null,
185 runId: string,
186 ) {
187 const remote = yield* git.resolvePrimaryRemoteName(workspaceRoot);
188 const fetch = (args: ReadonlyArray<string>) =>
189 git.execute({
190 operation: "PullRequestReviewGuideService.fetch",
191 cwd: workspaceRoot,
192 args: ["fetch", "--quiet", "--no-tags", remote, ...args],
193 timeoutMs: 5 * 60_000,
194 });
195 // The base branch is what the change is measured from; the head commit is the change. Hosts
196 // that do not serve an unadvertised commit still serve their pull refs, which GitHub and
197 // Forgejo name the same way.
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 = (number: number, sha: string) =>
231 fetch([sha]).pipe(Effect.catch(() => fetch([`refs/pull/${number}/head`])));
232 yield* fetchHead(detail.number, headSha);
233 // The other layers of a stack are context the model may read across a seam. A layer that
234 // cannot be fetched is still named in the prompt, without a head to read.
235 const layers: ReadonlyArray<ReviewGuideStackLayer> = yield* Effect.forEach(
236 stack?.layers ?? [],
237 (layer) => {
238 const described = { number: layer.number, title: layer.title ?? null, state: layer.state };
239 if (layer.number === detail.number) return Effect.succeed({ ...described, headSha });
240 const sha = layer.headSha;
241 if (sha === undefined) return Effect.succeed({ ...described, headSha: null });
242 return fetchHead(layer.number, sha).pipe(
243 Effect.andThen(git.resolveCommit({ cwd: workspaceRoot, revision: sha })),
244 Effect.as({ ...described, headSha: sha }),
245 Effect.orElseSucceed(() => ({ ...described, headSha: null })),
246 );
247 },
248 { concurrency: 4 },
249 );
250 const directory = yield* fileSystem.makeTempDirectoryScoped({
251 directory: config.worktreesDir,
252 prefix: "review-guide-",
253 });
254 const path = `${directory}/checkout`;
255 yield* git.execute({
256 operation: "PullRequestReviewGuideService.addWorktree",
257 cwd: workspaceRoot,
258 args: ["worktree", "add", "--detach", "--quiet", path, headSha],
259 timeoutMs: 5 * 60_000,
260 });
261 yield* Effect.addFinalizer(() =>
262 git
263 .removeWorktree({ cwd: workspaceRoot, path, force: true })
264 .pipe(Effect.ignore({ log: true })),
265 );
266 // Measured from where the head left the base, so a stacked change is briefed alone rather
267 // than with everything below it that the base has not taken yet.
268 const mergeBase = yield* git.execute({
269 operation: "PullRequestReviewGuideService.mergeBase",
270 cwd: path,
271 args: ["merge-base", baseTip.commitSha, "HEAD"],
272 });
273 return { path, baseCommit: mergeBase.stdout.trim(), stack: layers };
274 });
275​
276 /** The changed paths and their hunks, which a generated guide is held to. */
277 const readChange = Effect.fn("PullRequestReviewGuideService.readChange")(function* (
278 cwd: string,
279 baseCommit: string,
280 ) {
281 const diff = (args: ReadonlyArray<string>) =>
282 git
283 .execute({
284 operation: "PullRequestReviewGuideService.readChange",
285 cwd,
286 // Fixed prefixes: a user's diff.noPrefix or custom prefixes would hide the headers the
287 // parser reads.
288 args: [
289 "-c",
290 "core.quotePath=false",
291 "diff",
292 ...PATCH_RENDER_PREFIX_ARGS,
293 ...args,
294 `${baseCommit}...HEAD`,
295 ],
296 timeoutMs: 60_000,
297 // Hunk headers only, but a large change still has many of them.
298 maxOutputBytes: 64 * 1024 * 1024,
299 })
300 .pipe(Effect.map((result) => result.stdout));
301 const [nameOnly, patch] = yield* Effect.all(
302 [diff(["--name-only", "-z"]), diff(["--unified=0", "--no-color", "--no-ext-diff"])],
303 { concurrency: "unbounded" },
304 );
305 return parseReviewGuideChange(nameOnly, patch);
306 });
307​
308 const write = Effect.fn("PullRequestReviewGuideService.write")(function* (
309 input: PullRequestRef,
310 key: ThreadPullRequestKey,
311 workspaceRoot: string,
312 detail: PullRequestDetail,
313 headSha: string,
314 runId: string,
315 owns: Effect.Effect<boolean>,
316 ) {
317 const [activity, settings, providers, stack] = yield* Effect.all(
318 [
319 pullRequests.activity(input),
320 serverSettings.getSettings,
321 providerRegistry.getProviders,
322 // A guide without its stack is still a guide; the stack only adds seams to point at.
323 pullRequests.stack(input).pipe(Effect.orElseSucceed(() => null)),
324 ],
325 { concurrency: "unbounded" },
326 );
327 const projectSettings = resolveProjectSettings(settings, input.projectId).settings;
328 const modelSelection = ServerSettings.resolveReviewGuideModelSelection(
329 projectSettings,
330 providers,
331 input.projectId,
332 );
333 // The checkout lives only as long as the model is reading it. The change's hunks are read
334 // from it too, so the guide can be held to the lines the change actually touched.
335 const { generated, change } = yield* checkoutHead(
336 workspaceRoot,
337 detail,
338 headSha,
339 stack,
340 runId,
341 ).pipe(
342 Effect.flatMap((checkout) =>
343 Effect.all(
344 {
345 generated: textGeneration.generateReviewGuide({
346 ...reviewGuideInputFromPullRequest(detail, activity, checkout.baseCommit),
347 cwd: checkout.path,
348 modelSelection,
349 instructions: projectSettings.reviewGuideInstructions,
350 stack: checkout.stack,
351 }),
352 change: readChange(checkout.path, checkout.baseCommit),
353 },
354 { concurrency: "unbounded" },
355 ),
356 ),
357 Effect.scoped,
358 );
359 const guide: PullRequestReviewGuide = {
360 headSha,
361 generatedAt: yield* nowIso,
362 modelSelection,
363 ...normalizeReviewGuide(generated, change),
364 };
365 // A newer run for this pull request, say after a push, owns its guide now; this one's result
366 // is for an older head and is dropped rather than written over it.
367 yield* ownership.withPermits(1)(
368 Effect.gen(function* () {
369 if (yield* owns) yield* guides.put(key, guide);
370 }),
371 );
372 });
373​
374 /** What a reader is told when a run fails; the full cause goes to the log. */
375 const failureDetail = (cause: Cause.Cause<unknown>): string => {
376 const error = Cause.squash(cause);
377 if (error instanceof Error && "detail" in error && typeof error.detail === "string") {
378 return error.detail;
379 }
380 return "The review guide could not be written.";
381 };
382​
383 const generate: PullRequestReviewGuideService["Service"]["generate"] = Effect.fn(
384 "PullRequestReviewGuideService.generate",
385 )(function* (input) {
386 // A beta the server owns, so every client and agent sees the same answer.
387 const settings = yield* serverSettings.getSettings.pipe(
388 Effect.mapError(
389 (cause) =>
390 new PullRequestOperationError({
391 operation: "generateReviewGuide",
392 detail: "Could not read the server settings.",
393 cause,
394 }),
395 ),
396 );
397 if (!settings.reviewGuidesEnabled) {
398 return yield* new PullRequestOperationError({
399 operation: "generateReviewGuide",
400 detail: "Review guides are off. Turn them on in Settings → Source Control.",
401 });
402 }
403 const { key, workspaceRoot, identity } = yield* keyFor(input);
404 yield* requireOwnRepository(key, identity);
405 const runKey = keyString(key);
406 // A press asks for the head as it is now, not a read shared from the last minute, so a guide
407 // is never started for a commit the pull request has already moved past.
408 yield* pullRequests.invalidate({ reference: input });
409 const [detail, stored] = yield* Effect.all([pullRequests.detail(input), readStored(key)], {
410 concurrency: "unbounded",
411 });
412 const currentHeadSha = detail.headSha ?? null;
413 if (currentHeadSha === null) {
414 return yield* new PullRequestOperationError({
415 operation: "generateReviewGuide",
416 detail: "This host did not report the pull request's head commit.",
417 });
418 }
419 const running: PullRequestReviewGuideRun = {
420 _tag: "Running",
421 headSha: currentHeadSha,
422 startedAt: yield* nowIso,
423 };
424 // Claimed atomically, so two readers pressing Generate start one run between them. The head
425 // is read again under the claim: a press that read an older head before a push must not
426 // replace a run another press started for the new one, so it asks to be pressed again.
427 const claimed = yield* ownership.withPermits(1)(
428 pullRequests.detail(input).pipe(
429 Effect.flatMap((latest) =>
430 (latest.headSha ?? null) !== currentHeadSha
431 ? Effect.fail(
432 new PullRequestOperationError({
433 operation: "generateReviewGuide",
434 detail: "The pull request changed while the guide was starting. Try again.",
435 }),
436 )
437 : Ref.modify(runs, (current) => {
438 const existing = current.get(runKey);
439 if (existing?._tag === "Running" && existing.headSha === currentHeadSha) {
440 return [existing, current] as const;
441 }
442 return [running, new Map(current).set(runKey, running)] as const;
443 }),
444 ),
445 ),
446 );
447 if (claimed !== running) return { guide: stored, run: claimed, currentHeadSha, started: false };
448​
449 // The run is identified by its own Running value: a later claim replaces it, and from then
450 // on this run's completion leaves the newer run's state and guide alone.
451 const owns = Ref.get(runs).pipe(Effect.map((current) => current.get(runKey) === running));
452 const finish = (next: PullRequestReviewGuideRun | null) =>
453 Ref.update(runs, (current) => {
454 if (current.get(runKey) !== running) return current;
455 const updated = new Map(current);
456 if (next === null) updated.delete(runKey);
457 else updated.set(runKey, next);
458 return updated;
459 });
460 const runId = `${runCounter++}`;
461 yield* write(input, key, workspaceRoot, detail, currentHeadSha, runId, owns).pipe(
462 Effect.andThen(finish(null)),
463 Effect.catchCause((cause) =>
464 Cause.hasInterruptsOnly(cause)
465 ? finish(null)
466 : Effect.logWarning("Review guide generation failed", {
467 key: runKey,
468 cause: Cause.pretty(cause),
469 }).pipe(
470 Effect.andThen(nowIso),
471 Effect.flatMap((failedAt) =>
472 finish({
473 _tag: "Failed",
474 headSha: currentHeadSha,
475 failedAt,
476 detail: failureDetail(cause),
477 }),
478 ),
479 ),
480 ),
481 Effect.forkIn(serviceScope),
482 );
483 return { guide: stored, run: running, currentHeadSha, started: true };
484 });
485​
486 return PullRequestReviewGuideService.of({ get, generate });
487});
488​
489export const layer = Layer.effect(PullRequestReviewGuideService, make);