The best way to control Claude Code, Codex and more from any computer or phone

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