@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 623 lines 23 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, it } from "@effect/vitest";
4 import * as Context from "effect/Context";
5 import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as Ref from "effect/Ref";
11 import * as Queue from "effect/Queue";
12 import * as Tracer from "effect/Tracer";
13 import {
14 ProjectId,
15 GitCommandError,
16 type PullRequestActivity,
17 type PullRequestDetail,
18 type PullRequestStack,
19 type PullRequestRef,
20 type RepositoryOrigin,
21 } from "@t3tools/contracts";
22
23 import * as ServerConfig from "../config.ts";
24 import * as SqlitePersistence from "../persistence/Sqlite.ts";
25 import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
26 import * as ProjectService from "../project/ProjectService.ts";
27 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
28 import * as ServerSettings from "../serverSettings.ts";
29 import * as TextGeneration from "../textGeneration/TextGeneration.ts";
30 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
31 import * as VcsProcess from "../vcs/VcsProcess.ts";
32 import * as PullRequestReviewGuideService from "./PullRequestReviewGuideService.ts";
33 import * as PullRequestService from "./PullRequestService.ts";
34
35 const projectId = ProjectId.make("project-1");
36 const ACME_APP = {
37 canonicalKey: "github.com/acme/app",
38 locator: {
39 source: "git-remote" as const,
40 remoteName: "origin",
41 remoteUrl: "https://github.com/acme/app.git",
42 },
43 provider: "github",
44 displayName: "acme/app",
45 owner: "acme",
46 name: "app",
47 };
48
49 const reference: PullRequestRef = {
50 projectId,
51 host: "github.com",
52 repository: "acme/app",
53 number: 7,
54 };
55
56 const git = (cwd: string, args: ReadonlyArray<string>) =>
57 Effect.gen(function* () {
58 const driver = yield* GitVcsDriver.GitVcsDriver;
59 const result = yield* driver.execute({ operation: "test.git", cwd, args, timeoutMs: 10_000 });
60 return result.stdout.trim();
61 });
62
63 const makeRepositories = Effect.gen(function* () {
64 const fs = yield* FileSystem.FileSystem;
65 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-guide-" });
66 const remote = `${root}/remote`;
67 const workspace = `${root}/workspace`;
68 yield* fs.makeDirectory(remote);
69 yield* git(remote, ["init", "--quiet", "--initial-branch=main"]);
70 yield* git(remote, ["config", "user.email", "test@example.com"]);
71 yield* git(remote, ["config", "user.name", "Test"]);
72 const commit = (path: string, message: string, contents = message) =>
73 fs
74 .writeFileString(`${remote}/${path}`, contents)
75 .pipe(
76 Effect.andThen(git(remote, ["add", path])),
77 Effect.andThen(git(remote, ["commit", "--quiet", "-m", message])),
78 Effect.andThen(git(remote, ["rev-parse", "HEAD"])),
79 );
80 yield* commit("base.txt", "base");
81 yield* git(remote, ["checkout", "--quiet", "-b", "stack-base"]);
82 const lowerSha = yield* commit("lower.txt", "lower layer");
83 yield* git(remote, ["checkout", "--quiet", "-b", "feature"]);
84 const headSha = yield* commit(
85 "feature.txt",
86 "the change",
87 Array.from({ length: 10 }, (_, index) => `line ${index + 1}`).join("\n") + "\n",
88 );
89 yield* git(remote, ["checkout", "--quiet", "-b", "upper"]);
90 const upperSha = yield* commit("upper.txt", "upper layer");
91 yield* git(remote, ["checkout", "--quiet", "main"]);
92 yield* commit("unrelated.txt", "main moved on");
93 yield* git(root, ["clone", "--quiet", remote, workspace]);
94 return { root, remote, workspace, headSha, lowerSha, upperSha };
95 });
96
97 const detail = (workspaceRoot: string, headSha: string): PullRequestDetail =>
98 ({
99 provider: "github",
100 number: 7,
101 title: "Add the feature",
102 body: "Adds the feature.",
103 baseBranch: "stack-base",
104 headBranch: "feature",
105 headSha,
106 workspaceRoot,
107 }) as PullRequestDetail;
108
109 const activity: PullRequestActivity = {
110 comments: [],
111 commentCount: 0,
112 commentsTruncated: false,
113 reviewThreads: [],
114 commits: [],
115 };
116
117 const stack = (repositories: {
118 readonly headSha: string;
119 readonly lowerSha: string;
120 readonly upperSha: string;
121 }): PullRequestStack => ({
122 id: "stack",
123 number: 1,
124 url: "https://example.com/stack/1",
125 base: "main",
126 layers: [
127 {
128 number: 6,
129 title: "Lower",
130 headSha: repositories.lowerSha,
131 headBranch: "stack-base",
132 state: "open",
133 },
134 {
135 number: 7,
136 title: "Add the feature",
137 headSha: repositories.headSha,
138 headBranch: "feature",
139 state: "open",
140 },
141 {
142 number: 8,
143 title: "Upper",
144 headSha: repositories.upperSha.slice(0, 12),
145 headBranch: "upper",
146 state: "open",
147 },
148 { number: 9, title: "Unpushed", headSha: "f".repeat(40), headBranch: "gone", state: "open" },
149 ],
150 });
151
152 const makeLayer = (input: {
153 readonly root: string;
154 readonly remote: string;
155 readonly workspace: string;
156 readonly headSha: string;
157 readonly lowerSha: string;
158 readonly upperSha: string;
159 readonly generate: TextGeneration.TextGeneration["Service"]["generateReviewGuide"];
160 readonly stored: Deferred.Deferred<void>;
161 readonly enabled?: boolean;
162 readonly currentHead?: Ref.Ref<string>;
163 readonly identity?: typeof ACME_APP & { readonly origin?: RepositoryOrigin };
164 readonly locator?: typeof ACME_APP.locator;
165 }) =>
166 PullRequestReviewGuideService.layer.pipe(
167 Layer.provide(
168 Layer.effect(
169 PullRequestReviewGuides.PullRequestReviewGuideRepository,
170 Effect.gen(function* () {
171 const repository = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
172 return {
173 get: repository.get,
174 put: (key, guide) =>
175 repository
176 .put(key, guide)
177 .pipe(Effect.tap(() => Deferred.succeed(input.stored, undefined))),
178 } satisfies PullRequestReviewGuides.PullRequestReviewGuideRepository["Service"];
179 }),
180 ).pipe(Layer.provide(PullRequestReviewGuides.layer)),
181 ),
182 Layer.provide(
183 Layer.succeed(PullRequestService.PullRequestService, {
184 detail: () =>
185 (input.currentHead === undefined
186 ? Effect.succeed(input.headSha)
187 : Ref.get(input.currentHead)
188 ).pipe(Effect.map((head) => detail(input.workspace, head))),
189 activity: () => Effect.succeed(activity),
190 invalidate: () => Effect.void,
191 stack: () => Effect.succeed(stack(input)),
192 } as unknown as PullRequestService.PullRequestService["Service"]),
193 ),
194 Layer.provide(
195 Layer.succeed(ProjectService.ProjectService, {
196 getShell: () =>
197 Effect.succeedSome({
198 id: projectId,
199 workspaceRoot: input.workspace,
200 repositoryIdentity: {
201 ...(input.identity ?? ACME_APP),
202 locator: input.locator ?? { ...ACME_APP.locator, remoteUrl: input.remote },
203 },
204 }),
205 } as unknown as ProjectService.ProjectService["Service"]),
206 ),
207 Layer.provide(
208 Layer.succeed(ProviderRegistry.ProviderRegistry, {
209 getProviders: Effect.succeed([]),
210 } as unknown as ProviderRegistry.ProviderRegistry["Service"]),
211 ),
212 Layer.provide(
213 Layer.succeed(TextGeneration.TextGeneration, {
214 generateReviewGuide: input.generate,
215 } as unknown as TextGeneration.TextGeneration["Service"]),
216 ),
217 Layer.provide(ServerSettings.layerTest({ reviewGuidesEnabled: input.enabled ?? true })),
218 Layer.provide(ServerConfig.layerTest(input.root, { prefix: "t3-review-guide-config-" })),
219 );
220
221 const layerBase = Layer.mergeAll(
222 GitVcsDriver.layer.pipe(
223 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-review-guide-git-" })),
224 Layer.provideMerge(VcsProcess.layer),
225 ),
226 SqlitePersistence.layerMemory,
227 ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
228
229 type Repositories = Effect.Success<typeof makeRepositories>;
230
231 // A run forks into the service's scope, so a test learns it settled when the run's `write` span
232 // ends; the run records its outcome synchronously right after.
233 const watchRuns = Effect.gen(function* () {
234 const ended = yield* Queue.unbounded<void>();
235 const tracer = Tracer.make({
236 span: (options) => {
237 const span = new Tracer.NativeSpan(options);
238 if (options.name !== "PullRequestReviewGuideService.write") return span;
239 const end = span.end.bind(span);
240 span.end = (endTime, exit) => {
241 end(endTime, exit);
242 Queue.offerUnsafe(ended, undefined);
243 };
244 return span;
245 },
246 });
247 return {
248 generate: (
249 service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
250 input: PullRequestRef,
251 ) => service.generate(input).pipe(Effect.withTracer(tracer)),
252 settled: (
253 service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
254 input: PullRequestRef,
255 ) => Queue.take(ended).pipe(Effect.andThen(service.get(input))),
256 };
257 });
258
259 const startSingleBranchRun = (input: {
260 readonly repositoryName: string;
261 readonly reportedHead: (repositories: Repositories) => string;
262 readonly refuseCommitFetch: boolean;
263 readonly prepare: (
264 repositories: Repositories,
265 workspace: string,
266 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>;
267 readonly onBranchFetch?:
268 | ((
269 repositories: Repositories,
270 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>)
271 | undefined;
272 }) =>
273 Effect.gen(function* () {
274 const repositories = yield* makeRepositories;
275 const workspace = `${repositories.root}/single-branch`;
276 yield* git(repositories.root, [
277 "clone",
278 "--quiet",
279 "--no-local",
280 "--single-branch",
281 "--branch",
282 "main",
283 `${repositories.root}/remote`,
284 workspace,
285 ]);
286 yield* input.prepare(repositories, workspace);
287 const reportedHead = input.reportedHead(repositories);
288 const stored = yield* Deferred.make<void>();
289 const driver = yield* GitVcsDriver.GitVcsDriver;
290 const fetchedRefs: Array<string> = [];
291 const observed: Array<{ cwd: string; head: string; changed: string }> = [];
292 const onBranchFetch = input.onBranchFetch;
293 const observedDriver = {
294 ...driver,
295 execute: (call: GitVcsDriver.ExecuteGitInput) =>
296 Effect.gen(function* () {
297 const ref = call.args.at(-1);
298 if (call.args[0] !== "fetch" || ref === undefined) return yield* driver.execute(call);
299 fetchedRefs.push(ref);
300 if (input.refuseCommitFetch && ref === repositories.headSha) {
301 return yield* new GitCommandError({
302 operation: call.operation,
303 command: "git",
304 cwd: call.cwd,
305 detail: "The test remote refuses fetches by commit.",
306 exitCode: 128,
307 });
308 }
309 if (ref === "refs/heads/feature" && onBranchFetch !== undefined) {
310 yield* onBranchFetch(repositories).pipe(
311 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
312 );
313 }
314 return yield* driver.execute(call);
315 }),
316 };
317 const readCheckout = (cwd: string, args: ReadonlyArray<string>) =>
318 driver
319 .execute({ operation: "test.readCheckout", cwd, args })
320 .pipe(Effect.map((result) => result.stdout.trim()));
321 const context = yield* Layer.build(
322 makeLayer({
323 ...repositories,
324 headSha: reportedHead,
325 workspace,
326 stored,
327 identity: {
328 ...ACME_APP,
329 canonicalKey: `github.com/acme/${input.repositoryName}`,
330 displayName: `acme/${input.repositoryName}`,
331 name: input.repositoryName,
332 },
333 generate: (generation) =>
334 Effect.gen(function* () {
335 observed.push({
336 cwd: generation.cwd,
337 head: yield* readCheckout(generation.cwd, ["rev-parse", "HEAD"]),
338 changed: yield* readCheckout(generation.cwd, [
339 "diff",
340 "--name-only",
341 `${generation.baseCommit}...HEAD`,
342 ]),
343 });
344 return { stops: [] };
345 }).pipe(Effect.orDie),
346 }).pipe(Layer.provide(Layer.succeed(GitVcsDriver.GitVcsDriver, observedDriver))),
347 );
348 const service = Context.get(
349 context,
350 PullRequestReviewGuideService.PullRequestReviewGuideService,
351 );
352 const guideReference = { ...reference, repository: `acme/${input.repositoryName}` };
353 const runs = yield* watchRuns;
354 yield* runs.generate(service, guideReference);
355 return {
356 repositories,
357 reportedHead,
358 service,
359 reference: guideReference,
360 stored,
361 fetchedRefs,
362 observed,
363 settled: runs.settled(service, guideReference),
364 };
365 });
366
367 it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
368 it.effect.each([
369 {
370 name: "a branch named like the short head",
371 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
372 shadow: "branch",
373 expected: ["a branch or tag rather than the commit"],
374 },
375 {
376 name: "a tag named like the short head",
377 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
378 shadow: "tag",
379 expected: ["a branch or tag rather than the commit"],
380 },
381 {
382 name: "a head that is not a commit hash",
383 reportedHead: (repositories: Repositories) =>
384 `--upload-pack=touch ${repositories.root}/injected`,
385 shadow: "none",
386 expected: ["not a commit hash"],
387 },
388 {
389 name: "a head no source has",
390 reportedHead: () => "e".repeat(40),
391 shadow: "none",
392 expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"],
393 },
394 ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) =>
395 Effect.gen(function* () {
396 const run = yield* startSingleBranchRun({
397 repositoryName: "refused-head",
398 reportedHead,
399 refuseCommitFetch: false,
400 prepare: (repositories, workspace) =>
401 git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe(
402 Effect.andThen(
403 shadow === "none"
404 ? Effect.void
405 : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]),
406 ),
407 Effect.asVoid,
408 ),
409 });
410 const result = yield* run.settled;
411 assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written");
412 assert.strictEqual(result.run?._tag, "Failed");
413 const detail = result.run?._tag === "Failed" ? result.run.detail : "";
414 for (const part of expected) assert.include(detail, part);
415 // Only the host's own head ref is tried.
416 assert.notInclude(detail, "refs/merge-requests/");
417 assert.deepStrictEqual(run.observed, []);
418 assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
419 const fs = yield* FileSystem.FileSystem;
420 assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`));
421 }),
422 );
423
424 it.effect("measures only the PR change using the renamed verified remote's fetch URL", () =>
425 Effect.gen(function* () {
426 const repositories = yield* makeRepositories;
427 const fork = `${repositories.root}/fork`;
428 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
429 yield* git(fork, ["branch", "stack-base", "main~1"]);
430 // The cached identity still names origin, which now belongs to the stale fork.
431 yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]);
432 yield* git(repositories.workspace, ["remote", "add", "origin", fork]);
433 yield* git(repositories.workspace, [
434 "config",
435 `url.${repositories.remote}.insteadOf`,
436 "review-upstream:",
437 ]);
438 yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]);
439 const changed = yield* Deferred.make<string>();
440 const driver = yield* GitVcsDriver.GitVcsDriver;
441 const stored = yield* Deferred.make<void>();
442 const context = yield* Layer.build(
443 makeLayer({
444 ...repositories,
445 stored,
446 generate: (input) =>
447 git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe(
448 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
449 Effect.orDie,
450 Effect.flatMap((names) => Deferred.succeed(changed, names)),
451 Effect.as({ stops: [] }),
452 ),
453 }),
454 );
455 const service = Context.get(
456 context,
457 PullRequestReviewGuideService.PullRequestReviewGuideService,
458 );
459 yield* service.generate(reference);
460 assert.strictEqual(yield* Deferred.await(changed), "feature.txt");
461 yield* Deferred.await(stored);
462 const result = yield* service.get(reference);
463 assert.strictEqual(result.guide?.headSha, repositories.headSha);
464 assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]);
465 }),
466 );
467
468 it.effect("keeps excerpts despite the checkout's diff driver and a failing hook", () =>
469 Effect.gen(function* () {
470 const repositories = yield* makeRepositories;
471 const fs = yield* FileSystem.FileSystem;
472 yield* fs.writeFileString(
473 `${repositories.workspace}/.git/info/attributes`,
474 "feature.txt diff=blank\n",
475 );
476 yield* git(repositories.workspace, ["config", "diff.blank.textconv", "true"]);
477 const hook = `${repositories.workspace}/.git/hooks/post-checkout`;
478 yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n");
479 yield* fs.chmod(hook, 0o755);
480 const stored = yield* Deferred.make<void>();
481 const context = yield* Layer.build(
482 makeLayer({
483 ...repositories,
484 stored,
485 generate: () =>
486 Effect.succeed({
487 stops: [
488 {
489 title: "The feature",
490 summary: "The change.",
491 attention: null,
492 excerpts: [{ path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }],
493 files: [],
494 notes: [],
495 questions: [],
496 },
497 ],
498 }),
499 }),
500 );
501 const service = Context.get(
502 context,
503 PullRequestReviewGuideService.PullRequestReviewGuideService,
504 );
505 const runs = yield* watchRuns;
506 yield* runs.generate(service, reference);
507 const result = yield* runs.settled(service, reference);
508 assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run));
509 assert.deepStrictEqual(result.guide?.stops[0]?.excerpts, [
510 { path: "feature.txt", side: "new", start: 1, end: 3, caption: "" },
511 ]);
512 }),
513 );
514
515 it.effect("refuses generation when the verified remote disappeared despite a usable origin", () =>
516 Effect.gen(function* () {
517 const repositories = yield* makeRepositories;
518 const fork = `${repositories.root}/fork`;
519 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
520 yield* git(fork, ["branch", "stack-base", repositories.lowerSha]);
521 yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]);
522 const started = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
523 const stored = yield* Deferred.make<void>();
524 const generated = yield* Ref.make(false);
525 const driver = yield* GitVcsDriver.GitVcsDriver;
526 const context = yield* Layer.build(
527 makeLayer({
528 ...repositories,
529 stored,
530 generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })),
531 }).pipe(
532 Layer.provide(
533 Layer.succeed(GitVcsDriver.GitVcsDriver, {
534 ...driver,
535 execute: (call) =>
536 Effect.withFiber((fiber) =>
537 Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))),
538 ),
539 }),
540 ),
541 ),
542 );
543 const service = Context.get(
544 context,
545 PullRequestReviewGuideService.PullRequestReviewGuideService,
546 );
547 const before = yield* service.get(reference);
548 yield* service.generate(reference);
549 // Join the background run so its failure is visible without polling service state.
550 yield* Fiber.await(yield* Deferred.await(started));
551 const result = yield* service.get(reference);
552 assert.strictEqual(result.run?._tag, "Failed");
553 assert.include(
554 result.run?._tag === "Failed" ? result.run.detail : "",
555 "no longer has a remote for the pull request's repository",
556 );
557 assert.deepStrictEqual(result.guide, before.guide);
558 assert.isFalse(yield* Deferred.isDone(stored));
559 assert.isFalse(yield* Ref.get(generated));
560 }),
561 );
562
563 it.effect("writes a guide for a pull request on a fork whose canonical key is its upstream", () =>
564 Effect.gen(function* () {
565 const repositories = yield* makeRepositories;
566 const parent = `${repositories.root}/parent`;
567 yield* git(repositories.root, ["clone", "--quiet", "--bare", repositories.remote, parent]);
568 yield* git(repositories.workspace, ["remote", "add", "upstream", parent]);
569 const stored = yield* Deferred.make<void>();
570 const context = yield* Layer.build(
571 makeLayer({
572 ...repositories,
573 stored,
574 identity: {
575 ...ACME_APP,
576 canonicalKey: "github.com/parent/app",
577 displayName: "parent/app",
578 owner: "parent",
579 origin: { canonicalKey: "github.com/acme/app", remoteUrl: repositories.remote },
580 },
581 locator: { source: "git-remote", remoteName: "upstream", remoteUrl: parent },
582 generate: () => Effect.succeed({ stops: [] }),
583 }),
584 );
585 const service = Context.get(
586 context,
587 PullRequestReviewGuideService.PullRequestReviewGuideService,
588 );
589 const runs = yield* watchRuns;
590 yield* runs.generate(service, reference);
591 const result = yield* runs.settled(service, reference);
592 assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run));
593 assert.strictEqual(result.guide?.headSha, repositories.headSha);
594 }),
595 );
596
597 it.effect("refuses a pull request from a repository the project is not a checkout of", () =>
598 Effect.gen(function* () {
599 const repositories = yield* makeRepositories;
600 const stored = yield* Deferred.make<void>();
601 const context = yield* Layer.build(
602 makeLayer({
603 ...repositories,
604 stored,
605 identity: {
606 ...ACME_APP,
607 canonicalKey: "github.com/acme/other",
608 displayName: "acme/other",
609 name: "other",
610 },
611 generate: () =>
612 Effect.die("a guide must not be written from another repository's checkout"),
613 }),
614 );
615 const service = Context.get(
616 context,
617 PullRequestReviewGuideService.PullRequestReviewGuideService,
618 );
619 const result = yield* Effect.flip(service.generate(reference));
620 assert.include(result.message, "in another repository");
621 }),
622 );
623 });