Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationV2ServerCommand as OrchestrationCommand,
7 PullRequestOperationError,
8 type OrchestrationProjectShell,
9 type PullRequestRef,
10 type PullRequestReviewGuideResult,
11 type ThreadPullRequestLink,
12 SourceControlProviderKind,
13} from "@t3tools/contracts";
14import { describe, expect, it } from "@effect/vitest";
15import * as SecureRandom from "effect/crypto/SecureRandom";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Ref from "effect/Ref";
20import * as Stream from "effect/Stream";
21import type { Tool } from "effect/ai";
22
23import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
24import {
25 type PullRequestTestThread,
26 v2PullRequestThread,
27} from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
28import * as ProjectService from "../../../project/ProjectService.ts";
29import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
30import * as McpInvocationContext from "../../McpInvocationContext.ts";
31import * as McpToolAccess from "../../McpToolAccess.ts";
32import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
33import { listThreadPullRequests } from "./handlers.ts";
34import * as PullRequestsHandlers from "./handlers.ts";
35import { CHILD_PULL_REQUEST_REPORT_NEXT, PullRequestsToolkit } from "./tools.ts";
36
37const PROJECT_ID = ProjectId.make("project-1");
38const THREAD_ID = ThreadId.make("thread-1");
39
40const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(7));
41
42const invocation = (
43 capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
44): McpInvocationContext.McpInvocationScope => ({
45 environmentId: EnvironmentId.make("environment-1"),
46 requestNamespace: "provider-session-1",
47 thread: {
48 threadId: THREAD_ID,
49 providerSessionId: "provider-session-1",
50 providerInstanceId: ProviderInstanceId.make("codex"),
51 },
52 client: undefined,
53 capabilities: new Set(capabilities),
54 issuedAt: 1,
55});
56
57function makeProject(
58 repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
59 canonicalKey: "github.com/t3tools/t3code",
60 locator: {
61 source: "git-remote",
62 remoteName: "origin",
63 remoteUrl: "git@github.com:T3Tools/T3Code.git",
64 },
65 provider: SourceControlProviderKind.make("github"),
66 displayName: "T3Tools/T3Code",
67 owner: "T3Tools",
68 name: "T3Code",
69 },
70): OrchestrationProjectShell {
71 return {
72 id: PROJECT_ID,
73 title: "Project",
74 workspaceRoot: "/workspace/project",
75 defaultModelSelection: null,
76 scripts: [],
77 repositoryIdentity,
78 createdAt: "2026-08-01T00:00:00.000Z",
79 updatedAt: "2026-08-01T00:00:00.000Z",
80 };
81}
82
83function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): PullRequestTestThread {
84 return {
85 id: THREAD_ID,
86 projectId: PROJECT_ID,
87 title: "Thread",
88 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
89 runtimeMode: "full-access",
90 interactionMode: "default",
91 branch: null,
92 worktreePath: null,
93 pullRequests,
94 createdAt: "2026-08-01T00:00:00.000Z",
95 updatedAt: "2026-08-20T00:00:00.000Z",
96 archivedAt: null,
97 settledOverride: null,
98 settledAt: null,
99 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
100 };
101}
102
103function makeLink(
104 number: number,
105 overrides: Partial<ThreadPullRequestLink> & {
106 readonly headBranch?: string;
107 readonly baseBranch?: string;
108 } = {},
109): ThreadPullRequestLink {
110 const { headBranch, baseBranch, ...rest } = overrides;
111 return {
112 host: "github.com",
113 repository: "t3tools/t3code",
114 number,
115 url: `https://github.com/t3tools/t3code/pull/${number}`,
116 source: "manual",
117 linkedAt: "2026-08-10T00:00:00.000Z",
118 snapshot:
119 headBranch === undefined
120 ? null
121 : {
122 state: "open",
123 title: `PR ${number}`,
124 headBranch,
125 baseBranch: baseBranch ?? "main",
126 isDraft: false,
127 updatedAt: null,
128 syncedAt: "2026-08-27T00:00:00.000Z",
129 },
130 stack: null,
131 ...rest,
132 };
133}
134
135interface HarnessOptions {
136 readonly thread?: PullRequestTestThread | null;
137 readonly project?: OrchestrationProjectShell | null;
138 readonly reject?: (command: OrchestrationCommand) => string | null;
139 readonly projects?: ReadonlyArray<OrchestrationProjectShell>;
140 readonly generate?: (
141 input: PullRequestRef,
142 ) => Effect.Effect<
143 PullRequestReviewGuideResult & { started: boolean },
144 PullRequestOperationError
145 >;
146}
147
148const NO_GUIDE: PullRequestReviewGuideResult = { guide: null, run: null, currentHeadSha: "head-1" };
149
150const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
151 options: HarnessOptions = {},
152) {
153 const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
154 const guideRequests = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
155 const thread = options.thread === undefined ? makeThread([]) : options.thread;
156 const project = options.project === undefined ? makeProject() : options.project;
157 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) =>
158 Effect.gen(function* () {
159 const rejection = options.reject?.(command) ?? null;
160 if (rejection !== null)
161 return yield* new Orchestrator.OrchestratorDispatchError({
162 commandId: command.commandId,
163 commandType: command.type,
164 cause: rejection,
165 });
166 yield* Ref.update(commands, (recorded) => [...recorded, command]);
167 return { sequence: 1, storedEvents: [] };
168 });
169 const layerDependencies = Layer.mergeAll(
170 Layer.mock(ProjectService.ProjectService)({
171 getShell: () => Effect.succeed(Option.fromNullishOr(project)),
172 listShells: () => Effect.succeed(options.projects ?? (project ? [project] : [])),
173 }),
174 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({
175 get: () => Effect.succeed(NO_GUIDE),
176 generate: (input) =>
177 Ref.update(guideRequests, (recorded) => [...recorded, input]).pipe(
178 Effect.andThen(
179 options.generate?.(input) ??
180 Effect.succeed({
181 ...NO_GUIDE,
182 run: {
183 _tag: "Running" as const,
184 headSha: "head-1",
185 startedAt: "2026-10-11T00:00:00.000Z",
186 },
187 started: true,
188 }),
189 ),
190 ),
191 }),
192 Layer.mock(Orchestrator.OrchestratorV2)({
193 getThreadShell: (id) =>
194 Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null),
195 dispatch,
196 }),
197 Layer.succeed(SecureRandom.SecureRandom, testCrypto),
198 McpToolAccessTestkit.liveThreadsLayer,
199 );
200 const toolkit = yield* PullRequestsToolkit.pipe(
201 Effect.provide(
202 McpToolAccess.HandlersLayer.layer(PullRequestsHandlers.layer).pipe(
203 Layer.provide(layerDependencies),
204 ),
205 ),
206 );
207 const call = <Name extends keyof typeof PullRequestsToolkit.tools>(
208 name: Name,
209 params: Parameters<typeof toolkit.handle<Name>>[1],
210 capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["pull-requests"],
211 ) =>
212 toolkit.handle(name, params).pipe(
213 Stream.unwrap,
214 Stream.runCollect,
215 Effect.map(
216 (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof PullRequestsToolkit.tools)[Name]>,
217 ),
218 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
219 Effect.provide(layerDependencies),
220 );
221 return { commands, guideRequests, call };
222});
223
224describe("pull request toolkit handlers", () => {
225 it.effect("refuses a credential without the pull-requests capability", () =>
226 Effect.gen(function* () {
227 const harness = yield* makeHarness();
228 const error = yield* harness
229 .call("list_thread_pull_requests", {}, ["preview"])
230 .pipe(Effect.flip);
231 expect(error).toMatchObject({
232 _tag: "McpCapabilityUnavailableError",
233 capability: "pull-requests",
234 threadId: THREAD_ID,
235 });
236 expect(yield* Ref.get(harness.commands)).toEqual([]);
237 }),
238 );
239
240 it.effect("points a bare thread uuid at the mcp: thread it belongs to", () =>
241 Effect.gen(function* () {
242 const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04");
243 const harness = yield* makeHarness({
244 thread: { ...makeThread([]), id: ThreadId.make(`mcp:${bareId}`) },
245 });
246 const error = yield* harness
247 .call("link_pull_request", { threadId: bareId, number: 123 })
248 .pipe(Effect.flip);
249 expect(error.message).toBe(`Thread ${bareId} was not found. Did you mean \`mcp:${bareId}\`?`);
250 expect(error).toMatchObject({ _tag: "OrchestratorMcpFailure", code: "thread_not_found" });
251 expect(yield* Ref.get(harness.commands)).toEqual([]);
252 }),
253 );
254
255 it.effect("links by URL with source agent on the token's thread", () =>
256 Effect.gen(function* () {
257 const harness = yield* makeHarness();
258 const result = yield* harness.call("link_pull_request", {
259 url: "https://github.com/T3Tools/T3Code/pull/123/files",
260 });
261 expect(result).toEqual({
262 host: "github.com",
263 repository: "t3tools/t3code",
264 number: 123,
265 url: "https://github.com/T3Tools/T3Code/pull/123/files",
266 alreadyLinked: false,
267 });
268 expect(yield* Ref.get(harness.commands)).toMatchObject([
269 {
270 type: "thread.pull-request.link",
271 threadId: THREAD_ID,
272 host: "github.com",
273 repository: "t3tools/t3code",
274 number: 123,
275 source: "agent",
276 },
277 ]);
278 }),
279 );
280
281 it.effect("watching an unlinked pull request links it first", () =>
282 Effect.gen(function* () {
283 const harness = yield* makeHarness();
284 const result = yield* harness.call("watch_pull_request", {
285 url: "https://github.com/t3tools/t3code/pull/9",
286 });
287 expect(result).toMatchObject({ number: 9, watching: false, wasWatching: false });
288 expect(yield* Ref.get(harness.commands)).toMatchObject([
289 {
290 type: "thread.pull-request.watch",
291 number: 9,
292 watching: true,
293 link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" },
294 },
295 ]);
296 }),
297 );
298
299 it.effect("refuses to watch a merged pull request and stops an existing watch", () =>
300 Effect.gen(function* () {
301 const watch = {
302 startedAt: "2026-08-20T00:00:00.000Z",
303 headSha: null,
304 failedChecks: [],
305 passed: false,
306 passedChecks: [],
307 remarksThrough: "2026-08-20T00:00:00.000Z",
308 remarkIds: [],
309 conflicting: false,
310 wakes: 0,
311 };
312 const merged = makeLink(1, { headBranch: "done" });
313 const harness = yield* makeHarness({
314 thread: makeThread([
315 { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } },
316 makeLink(2, { headBranch: "idle" }),
317 makeLink(3, { headBranch: "watched", watch }),
318 ]),
319 });
320 const error = yield* harness
321 .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 })
322 .pipe(Effect.flip);
323 expect(error).toMatchObject({ _tag: "PullRequestNotOpenError", state: "merged" });
324 expect(
325 yield* harness.call("unwatch_pull_request", { repository: "t3tools/t3code", number: 3 }),
326 ).toMatchObject({ wasWatching: true });
327 expect(yield* Ref.get(harness.commands)).toMatchObject([
328 { type: "thread.pull-request.watch", number: 3, watching: false },
329 ]);
330 }),
331 );
332
333 it.effect("watches a pull request saved as closed, since it may have reopened", () =>
334 Effect.gen(function* () {
335 const closed = makeLink(1, { headBranch: "closed" });
336 const harness = yield* makeHarness({
337 thread: makeThread([
338 { ...closed, snapshot: closed.snapshot && { ...closed.snapshot, state: "closed" } },
339 ]),
340 });
341 yield* harness.call("watch_pull_request", { repository: "t3tools/t3code", number: 1 });
342 expect(yield* Ref.get(harness.commands)).toMatchObject([
343 { type: "thread.pull-request.watch", number: 1, watching: true },
344 ]);
345 }),
346 );
347
348 it.effect("refuses a watch from a subagent thread, whose parent owns the pull request", () =>
349 Effect.gen(function* () {
350 const harness = yield* makeHarness({
351 thread: {
352 ...makeThread([makeLink(1, { headBranch: "feature" })]),
353 lineage: {
354 rootThreadId: ThreadId.make("parent"),
355 parentThreadId: ThreadId.make("parent"),
356 relationshipToParent: "subagent",
357 },
358 },
359 });
360 const error = yield* harness
361 .call("watch_pull_request", { repository: "t3tools/t3code", number: 1 })
362 .pipe(Effect.flip);
363 expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" });
364 expect(yield* Ref.get(harness.commands)).toEqual([]);
365 }),
366 );
367
368 it.effect("asks a subagent thread to end with its PR report after it links", () =>
369 Effect.gen(function* () {
370 const harness = yield* makeHarness({
371 thread: {
372 ...makeThread([]),
373 lineage: {
374 rootThreadId: ThreadId.make("parent"),
375 parentThreadId: ThreadId.make("parent"),
376 relationshipToParent: "subagent",
377 },
378 },
379 });
380 const result = yield* harness.call("link_pull_request", {
381 url: "https://github.com/t3tools/t3code/pull/124",
382 });
383 expect(result).toMatchObject({ number: 124, next: CHILD_PULL_REQUEST_REPORT_NEXT });
384 }),
385 );
386
387 it.effect("canonicalizes GitCafe links independently of the thread's project host", () =>
388 Effect.gen(function* () {
389 for (const host of ["git.cafe", "staging.git.cafe"]) {
390 for (const project of [makeProject(), makeProject(null)]) {
391 for (const target of [
392 { host, repository: "PingDotGG/T3Code", number: 21353 },
393 { url: `https://${host}/PingDotGG/T3Code/pull/21353` },
394 { url: `https://${host}/PingDotGG/T3Code/pulls/21353` },
395 ]) {
396 const harness = yield* makeHarness({ project });
397 const result = yield* harness.call("link_pull_request", target);
398 const url = `https://${host}/pingdotgg/t3code/pulls/21353`;
399 expect(result).toMatchObject({
400 host,
401 repository: "pingdotgg/t3code",
402 number: 21353,
403 url,
404 });
405 expect(yield* Ref.get(harness.commands)).toMatchObject([
406 {
407 type: "thread.pull-request.link",
408 host,
409 repository: "pingdotgg/t3code",
410 number: 21353,
411 url,
412 },
413 ]);
414 }
415 }
416 }
417 }),
418 );
419
420 it.effect("builds the URL in the project host's own shape", () =>
421 Effect.gen(function* () {
422 const harness = yield* makeHarness({
423 project: makeProject({
424 canonicalKey: "gitlab.com/group/sub/project",
425 locator: {
426 source: "git-remote",
427 remoteName: "origin",
428 remoteUrl: "git@gitlab.com:group/sub/project.git",
429 },
430 provider: SourceControlProviderKind.make("gitlab"),
431 displayName: "group/sub/project",
432 }),
433 });
434 const result = yield* harness.call("link_pull_request", {
435 repository: "group/sub/project",
436 number: 42,
437 });
438 expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
439 expect(result.host).toBe("gitlab.com");
440 const other = yield* harness.call("link_pull_request", {
441 host: "gitlab.example.test",
442 repository: "team/repo",
443 number: 7,
444 });
445 expect(other.url).toBe("https://gitlab.example.test/team/repo/-/merge_requests/7");
446 const onGitHub = yield* harness.call("link_pull_request", {
447 host: "github.com",
448 repository: "acme/web",
449 number: 9,
450 });
451 expect(onGitHub.url).toBe("https://github.com/acme/web/pull/9");
452 }),
453 );
454
455 it.effect("links a URL but not a bare number when the project's host is unknown", () =>
456 Effect.gen(function* () {
457 const harness = yield* makeHarness({
458 project: makeProject({
459 canonicalKey: "scm.example.test/tfs/collection/project/_git/repo",
460 locator: {
461 source: "git-remote",
462 remoteName: "origin",
463 remoteUrl: "http://dummy:secret@scm.example.test:8080/tfs/Collection/Project/_git/Repo",
464 },
465 provider: SourceControlProviderKind.make("unknown"),
466 displayName: "tfs/collection/project/_git/repo",
467 }),
468 });
469 const error = yield* harness
470 .call("link_pull_request", { repository: "tfs/Collection/Project/_git/Repo", number: 124 })
471 .pipe(Effect.flip);
472 expect(error).toMatchObject({ _tag: "PullRequestUrlUnavailableError" });
473
474 const supplied = "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/123";
475 const fromUrl = yield* harness.call("link_pull_request", { url: supplied });
476 expect(fromUrl).toEqual({
477 host: "scm.example.test",
478 repository: "tfs/collection/project/_git/repo",
479 number: 123,
480 url: supplied,
481 alreadyLinked: false,
482 });
483 expect(yield* Ref.get(harness.commands)).toMatchObject([
484 { type: "thread.pull-request.link", number: 123, url: supplied },
485 ]);
486 }),
487 );
488
489 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
490 Effect.gen(function* () {
491 const harness = yield* makeHarness({
492 thread: makeThread([makeLink(123)]),
493 reject: (command) =>
494 command.type === "thread.pull-request.link" ? "already linked" : null,
495 });
496 const result = yield* harness.call("link_pull_request", {
497 url: "https://github.com/t3tools/t3code/pull/123",
498 });
499 expect(result.alreadyLinked).toBe(true);
500 }),
501 );
502
503 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
504 Effect.gen(function* () {
505 const harness = yield* makeHarness({
506 thread: makeThread([makeLink(5)]),
507 reject: (command) =>
508 command.type === "thread.pull-request.unlink" && command.number !== 5
509 ? "not linked"
510 : null,
511 });
512 const linked = yield* harness.call("unlink_pull_request", {
513 repository: "t3tools/t3code",
514 number: 5,
515 });
516 expect(linked).toEqual({
517 host: "github.com",
518 repository: "t3tools/t3code",
519 number: 5,
520 wasLinked: true,
521 });
522 const missing = yield* harness.call("unlink_pull_request", {
523 url: "https://github.com/t3tools/t3code/pull/9",
524 });
525 expect(missing.wasLinked).toBe(false);
526 expect(yield* Ref.get(harness.commands)).toMatchObject([
527 { type: "thread.pull-request.unlink", number: 5 },
528 ]);
529 }),
530 );
531
532 it.effect("reports a dismissed stack member as not linked and leaves it dismissed", () =>
533 Effect.gen(function* () {
534 const harness = yield* makeHarness({
535 thread: makeThread([makeLink(9, { source: "stack-dismissed" })]),
536 });
537 const result = yield* harness.call("unlink_pull_request", {
538 repository: "t3tools/t3code",
539 number: 9,
540 });
541 expect(result.wasLinked).toBe(false);
542 expect(yield* Ref.get(harness.commands)).toEqual([]);
543 }),
544 );
545
546 it.effect("links several pull requests in one call", () =>
547 Effect.gen(function* () {
548 const harness = yield* makeHarness({
549 thread: makeThread([makeLink(1), { ...makeLink(2), source: "stack-dismissed" }]),
550 });
551 const url = (number: number) => `https://github.com/t3tools/t3code/pull/${number}`;
552 const result = yield* harness.call("link_pull_requests", {
553 urls: [url(1), url(2), url(3), url(3), "https://example.com/not-a-pr"],
554 });
555 expect(result).toEqual({
556 linked: [{ host: "github.com", repository: "t3tools/t3code", numbers: [2, 3] }],
557 alreadyLinked: [{ host: "github.com", repository: "t3tools/t3code", numbers: [1] }],
558 linkedCount: 3,
559 invalidUrls: ["https://example.com/not-a-pr"],
560 });
561 expect(yield* Ref.get(harness.commands)).toMatchObject([
562 { type: "thread.pull-request.link", number: 2, source: "agent" },
563 { type: "thread.pull-request.link", number: 3, source: "agent" },
564 ]);
565 }),
566 );
567
568 it.effect("unlinks every visible pull request in the given states in one call", () =>
569 Effect.gen(function* () {
570 const withState = (number: number, state: "open" | "closed" | "merged") => {
571 const link = makeLink(number, { headBranch: `branch-${number}` });
572 return { ...link, snapshot: { ...link.snapshot!, state } };
573 };
574 const harness = yield* makeHarness({
575 thread: makeThread([
576 withState(1, "merged"),
577 withState(2, "open"),
578 withState(3, "closed"),
579 makeLink(4),
580 { ...withState(5, "merged"), source: "stack-dismissed" },
581 ]),
582 });
583 const result = yield* harness.call("unlink_pull_requests", {
584 states: ["closed", "merged"],
585 });
586 expect(result).toEqual({
587 unlinked: [
588 { host: "github.com", repository: "t3tools/t3code", state: "merged", numbers: [1] },
589 { host: "github.com", repository: "t3tools/t3code", state: "closed", numbers: [3] },
590 ],
591 unlinkedCount: 2,
592 remaining: 2,
593 });
594 expect(yield* Ref.get(harness.commands)).toMatchObject([
595 { type: "thread.pull-request.unlink", number: 1 },
596 { type: "thread.pull-request.unlink", number: 3 },
597 ]);
598 }),
599 );
600
601 it("reports an older Forgejo link's HTTP port when listing thread links", () => {
602 const result = listThreadPullRequests(
603 makeThread([
604 makeLink(42, {
605 host: "forge.example",
606 url: "http://forge.example:3000/t3tools/t3code/pulls/42",
607 }),
608 ]),
609 );
610 expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
611 });
612
613 it.effect("lists visible links with host state and derived chain order", () =>
614 Effect.gen(function* () {
615 const harness = yield* makeHarness({
616 thread: makeThread([
617 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
618 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
619 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
620 makeLink(9, { source: "stack-dismissed" }),
621 makeLink(10),
622 ]),
623 });
624 const result = yield* harness.call("list_thread_pull_requests", {});
625 expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]);
626 expect(result.pullRequests[0]).toEqual({
627 host: "github.com",
628 repository: "t3tools/t3code",
629 number: 3,
630 url: "https://github.com/t3tools/t3code/pull/3",
631 source: "agent",
632 watching: false,
633 state: "open",
634 title: "PR 3",
635 headBranch: "feat-c",
636 baseBranch: "feat-b",
637 isDraft: false,
638 stack: { kind: "derived", position: 3, size: 3 },
639 });
640 expect(result.pullRequests[3]).toMatchObject({
641 number: 10,
642 state: null,
643 title: null,
644 headBranch: null,
645 stack: null,
646 });
647 expect(result.chains).toEqual([
648 { kind: "derived", numbers: [1, 2, 3] },
649 { kind: "derived", numbers: [10] },
650 ]);
651 }),
652 );
653});
654
655describe("listThreadPullRequests", () => {
656 it("reports a native stack position for each member", () => {
657 const stack = {
658 kind: "native" as const,
659 id: "stack-1",
660 number: 1,
661 url: "https://github.com/t3tools/t3code/stack/1",
662 base: "main",
663 layers: [
664 { number: 1, headBranch: "a", state: "open" as const },
665 { number: 2, headBranch: "b", state: "open" as const },
666 ],
667 };
668 const result = listThreadPullRequests({
669 pullRequests: [
670 makeLink(2, { stack, source: "stack" }),
671 makeLink(1, { stack, source: "created" }),
672 ],
673 });
674 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
675 [2, { kind: "native", position: 2, size: 2 }],
676 [1, { kind: "native", position: 1, size: 2 }],
677 ]);
678 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
679 });
680
681 it("gives pull requests built on the same one the same position", () => {
682 const result = listThreadPullRequests({
683 pullRequests: [
684 makeLink(1, { headBranch: "feat-a", baseBranch: "main" }),
685 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a" }),
686 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-a" }),
687 ],
688 });
689 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
690 [1, { kind: "derived", position: 1, size: 3 }],
691 [2, { kind: "derived", position: 2, size: 3 }],
692 [3, { kind: "derived", position: 2, size: 3 }],
693 ]);
694 expect(result.chains).toEqual([{ kind: "derived", numbers: [1, 2, 3] }]);
695 });
696});
697
698describe("pull request guide tools", () => {
699 it.effect(
700 "writes guides through the project whose checkout is each pull request's repository",
701 () =>
702 Effect.gen(function* () {
703 const other = {
704 ...makeProject({
705 canonicalKey: "github.com/acme/web",
706 locator: {
707 source: "git-remote",
708 remoteName: "origin",
709 remoteUrl: "git@github.com:acme/web.git",
710 },
711 provider: SourceControlProviderKind.make("github"),
712 displayName: "acme/web",
713 owner: "acme",
714 name: "web",
715 }),
716 id: ProjectId.make("project-web"),
717 };
718 const harness = yield* makeHarness({ projects: [makeProject(), other] });
719 const result = yield* harness.call("write_pull_request_guides", {
720 pullRequests: [
721 { url: "https://github.com/acme/web/pull/7" },
722 { repository: "t3tools/t3code", number: 12 },
723 { url: "https://github.com/someone/else/pull/1" },
724 ],
725 });
726 expect(
727 result.guides.map((guide) => [guide.repository, guide.number, guide.outcome]),
728 ).toEqual([
729 ["acme/web", 7, "started"],
730 ["t3tools/t3code", 12, "started"],
731 ["someone/else", 1, "failed"],
732 ]);
733 expect(result.guides[2]?.detail).toContain("No project in this environment");
734 expect(
735 (yield* Ref.get(harness.guideRequests)).map((ref) => [ref.projectId, ref.number]),
736 ).toEqual([
737 ["project-web", 7],
738 [PROJECT_ID, 12],
739 ]);
740 }),
741 );
742
743 it.effect("reports an unreadable entry on its own and still writes the rest of the batch", () =>
744 Effect.gen(function* () {
745 const harness = yield* makeHarness();
746 const result = yield* harness.call("write_pull_request_guides", {
747 pullRequests: [
748 { url: "https://example.com/not-a-pull-request" },
749 { repository: "t3tools/t3code" },
750 { repository: "t3tools/t3code", number: 5 },
751 ],
752 });
753 expect(result.guides.map((guide) => guide.outcome)).toEqual(["failed", "failed", "started"]);
754 expect(result.guides[0]?.detail).toContain("not a recognised pull request URL");
755 expect(result.guides[1]?.detail).toContain("Pass either url");
756 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.number)).toEqual([5]);
757 }),
758 );
759
760 it.effect("finds an Azure DevOps checkout for a pull request named by its full path", () =>
761 Effect.gen(function* () {
762 const azure = {
763 ...makeProject({
764 canonicalKey: "dev.azure.com/org/project/_git/web",
765 locator: {
766 source: "git-remote",
767 remoteName: "origin",
768 remoteUrl: "https://dev.azure.com/org/project/_git/web",
769 },
770 provider: SourceControlProviderKind.make("azure-devops"),
771 displayName: "org/project/_git/web",
772 owner: "org",
773 name: "web",
774 }),
775 id: ProjectId.make("project-azure"),
776 };
777 const harness = yield* makeHarness({ projects: [makeProject(), azure] });
778 const result = yield* harness.call("write_pull_request_guides", {
779 pullRequests: [{ host: "dev.azure.com", repository: "org/project/_git/web", number: 9 }],
780 });
781 expect(result.guides.map((guide) => guide.outcome)).toEqual(["started"]);
782 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.projectId)).toEqual([
783 "project-azure",
784 ]);
785 }),
786 );
787});