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