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

handlers.test.ts

753 lines26.4 KB

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 };
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 };
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 };
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 >;
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("rejects a target that names neither a URL nor repository and number", () =>
430 Effect.gen(function* () {
431 const harness = yield* makeHarness();
432 const error = yield* harness
433 .call("link_pull_request", { repository: "x/y" })
434 .pipe(Effect.flip);
435 expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" });
436 const unknown = yield* harness
437 .call("link_pull_request", {
438 url: "https://github.com/t3tools/t3code/issues/1?token=private-value",
439 })
440 .pipe(Effect.flip);
441 expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" });
442 expect(unknown.message).not.toContain("private-value");
443 expect(yield* Ref.get(harness.commands)).toEqual([]);
444 }),
445 );
446​
447 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
448 Effect.gen(function* () {
449 const harness = yield* makeHarness({
450 thread: makeThread([makeLink(123)]),
451 reject: (command) =>
452 command.type === "thread.pull-request.link" ? "already linked" : null,
453 });
454 const result = yield* harness.call("link_pull_request", {
455 url: "https://github.com/t3tools/t3code/pull/123",
456 });
457 expect(result.alreadyLinked).toBe(true);
458 }),
459 );
460​
461 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
462 Effect.gen(function* () {
463 const harness = yield* makeHarness({
464 thread: makeThread([makeLink(5)]),
465 reject: (command) =>
466 command.type === "thread.pull-request.unlink" && command.number !== 5
467 ? "not linked"
468 : null,
469 });
470 const linked = yield* harness.call("unlink_pull_request", {
471 repository: "t3tools/t3code",
472 number: 5,
473 });
474 expect(linked).toEqual({
475 host: "github.com",
476 repository: "t3tools/t3code",
477 number: 5,
478 wasLinked: true,
479 });
480 const missing = yield* harness.call("unlink_pull_request", {
481 url: "https://github.com/t3tools/t3code/pull/9",
482 });
483 expect(missing.wasLinked).toBe(false);
484 expect(yield* Ref.get(harness.commands)).toMatchObject([
485 { type: "thread.pull-request.unlink", number: 5 },
486 ]);
487 }),
488 );
489​
490 it("reports an older Forgejo link's HTTP port when listing thread links", () => {
491 const result = listThreadPullRequests(
492 makeThread([
493 makeLink(42, {
494 host: "forge.example",
495 url: "http://forge.example:3000/t3tools/t3code/pulls/42",
496 }),
497 ]),
498 );
499 expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
500 });
501​
502 it.effect("fails cleanly when the token's thread no longer exists", () =>
503 Effect.gen(function* () {
504 const harness = yield* makeHarness({ thread: null });
505 const error = yield* harness.call("list_thread_pull_requests", {}).pipe(Effect.flip);
506 expect(error).toMatchObject({ _tag: "PullRequestThreadNotFoundError", threadId: THREAD_ID });
507 }),
508 );
509​
510 it.effect("lists visible links with host state and derived chain order", () =>
511 Effect.gen(function* () {
512 const harness = yield* makeHarness({
513 thread: makeThread([
514 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
515 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
516 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
517 makeLink(9, { source: "stack-dismissed" }),
518 makeLink(10),
519 ]),
520 });
521 const result = yield* harness.call("list_thread_pull_requests", {});
522 expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]);
523 expect(result.pullRequests[0]).toEqual({
524 host: "github.com",
525 repository: "t3tools/t3code",
526 number: 3,
527 url: "https://github.com/t3tools/t3code/pull/3",
528 source: "agent",
529 watching: false,
530 state: "open",
531 title: "PR 3",
532 headBranch: "feat-c",
533 baseBranch: "feat-b",
534 isDraft: false,
535 stack: { kind: "derived", position: 3, size: 3 },
536 });
537 expect(result.pullRequests[3]).toMatchObject({
538 number: 10,
539 state: null,
540 title: null,
541 headBranch: null,
542 stack: null,
543 });
544 expect(result.chains).toEqual([
545 { kind: "derived", numbers: [1, 2, 3] },
546 { kind: "derived", numbers: [10] },
547 ]);
548 }),
549 );
550});
551​
552describe("listThreadPullRequests", () => {
553 it("reports a native stack position for each member", () => {
554 const stack = {
555 kind: "native" as const,
556 id: "stack-1",
557 number: 1,
558 url: "https://github.com/t3tools/t3code/stack/1",
559 base: "main",
560 layers: [
561 { number: 1, headBranch: "a", state: "open" as const },
562 { number: 2, headBranch: "b", state: "open" as const },
563 ],
564 };
565 const result = listThreadPullRequests({
566 pullRequests: [
567 makeLink(2, { stack, source: "stack" }),
568 makeLink(1, { stack, source: "created" }),
569 ],
570 });
571 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
572 [2, { kind: "native", position: 2, size: 2 }],
573 [1, { kind: "native", position: 1, size: 2 }],
574 ]);
575 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
576 });
577​
578 it("gives pull requests built on the same one the same position", () => {
579 const result = listThreadPullRequests({
580 pullRequests: [
581 makeLink(1, { headBranch: "feat-a", baseBranch: "main" }),
582 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a" }),
583 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-a" }),
584 ],
585 });
586 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
587 [1, { kind: "derived", position: 1, size: 3 }],
588 [2, { kind: "derived", position: 2, size: 3 }],
589 [3, { kind: "derived", position: 2, size: 3 }],
590 ]);
591 expect(result.chains).toEqual([{ kind: "derived", numbers: [1, 2, 3] }]);
592 });
593});
594​
595describe("pull request guide tools", () => {
596 it.effect(
597 "writes guides through the project whose checkout is each pull request's repository",
598 () =>
599 Effect.gen(function* () {
600 const other = {
601 ...makeProject({
602 canonicalKey: "github.com/acme/web",
603 locator: {
604 source: "git-remote",
605 remoteName: "origin",
606 remoteUrl: "git@github.com:acme/web.git",
607 },
608 provider: "github",
609 displayName: "acme/web",
610 owner: "acme",
611 name: "web",
612 }),
613 id: ProjectId.make("project-web"),
614 };
615 const harness = yield* makeHarness({ projects: [makeProject(), other] });
616 const result = yield* harness.call("write_pull_request_guides", {
617 pullRequests: [
618 { url: "https://github.com/acme/web/pull/7" },
619 { repository: "t3tools/t3code", number: 12 },
620 { url: "https://github.com/someone/else/pull/1" },
621 ],
622 });
623 expect(
624 result.guides.map((guide) => [guide.repository, guide.number, guide.outcome]),
625 ).toEqual([
626 ["acme/web", 7, "started"],
627 ["t3tools/t3code", 12, "started"],
628 ["someone/else", 1, "failed"],
629 ]);
630 expect(result.guides[2]?.detail).toContain("No project in this environment");
631 expect(
632 (yield* Ref.get(harness.guideRequests)).map((ref) => [ref.projectId, ref.number]),
633 ).toEqual([
634 ["project-web", 7],
635 [PROJECT_ID, 12],
636 ]);
637 }),
638 );
639​
640 it.effect("reports a refused run on its own pull request without failing the rest", () =>
641 Effect.gen(function* () {
642 const harness = yield* makeHarness({
643 generate: (input) =>
644 input.number === 1
645 ? Effect.fail(
646 new PullRequestOperationError({
647 operation: "generateReviewGuide",
648 detail: "Review guides are off. Turn them on in Settings → Source Control.",
649 }),
650 )
651 : Effect.succeed({
652 ...NO_GUIDE,
653 run: {
654 _tag: "Running" as const,
655 headSha: "head-1",
656 startedAt: "2026-10-11T00:00:00.000Z",
657 },
658 started: true,
659 }),
660 });
661 const result = yield* harness.call("write_pull_request_guides", {
662 pullRequests: [
663 { repository: "t3tools/t3code", number: 1 },
664 { repository: "t3tools/t3code", number: 2 },
665 ],
666 });
667 expect(result.guides.map((guide) => [guide.number, guide.outcome, guide.detail])).toEqual([
668 [1, "failed", "Review guides are off. Turn them on in Settings → Source Control."],
669 [2, "started", null],
670 ]);
671 }),
672 );
673​
674 it.effect("reports an unreadable entry on its own and still writes the rest of the batch", () =>
675 Effect.gen(function* () {
676 const harness = yield* makeHarness();
677 const result = yield* harness.call("write_pull_request_guides", {
678 pullRequests: [
679 { url: "https://example.com/not-a-pull-request" },
680 { repository: "t3tools/t3code" },
681 { repository: "t3tools/t3code", number: 5 },
682 ],
683 });
684 expect(result.guides.map((guide) => guide.outcome)).toEqual(["failed", "failed", "started"]);
685 expect(result.guides[0]?.detail).toContain("not a recognised pull request URL");
686 expect(result.guides[1]?.detail).toContain("Pass either url");
687 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.number)).toEqual([5]);
688 }),
689 );
690​
691 it.effect("reports a run the service joined as running, not as a new one", () =>
692 Effect.gen(function* () {
693 const harness = yield* makeHarness({
694 generate: () =>
695 Effect.succeed({
696 ...NO_GUIDE,
697 run: { _tag: "Running", headSha: "head-1", startedAt: "2026-10-11T00:00:00.000Z" },
698 started: false,
699 }),
700 });
701 const result = yield* harness.call("write_pull_request_guides", {
702 pullRequests: [{ repository: "t3tools/t3code", number: 4 }],
703 });
704 expect(result.guides.map((guide) => guide.outcome)).toEqual(["running"]);
705 }),
706 );
707​
708 it.effect("finds an Azure DevOps checkout for a pull request named by its full path", () =>
709 Effect.gen(function* () {
710 const azure = {
711 ...makeProject({
712 canonicalKey: "dev.azure.com/org/project/_git/web",
713 locator: {
714 source: "git-remote",
715 remoteName: "origin",
716 remoteUrl: "https://dev.azure.com/org/project/_git/web",
717 },
718 provider: "azure-devops",
719 displayName: "org/project/_git/web",
720 owner: "org",
721 name: "web",
722 }),
723 id: ProjectId.make("project-azure"),
724 };
725 const harness = yield* makeHarness({ projects: [makeProject(), azure] });
726 const result = yield* harness.call("write_pull_request_guides", {
727 pullRequests: [{ host: "dev.azure.com", repository: "org/project/_git/web", number: 9 }],
728 });
729 expect(result.guides.map((guide) => guide.outcome)).toEqual(["started"]);
730 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.projectId)).toEqual([
731 "project-azure",
732 ]);
733 }),
734 );
735​
736 it.effect("reads a stored guide and says when a push left it behind", () =>
737 Effect.gen(function* () {
738 const harness = yield* makeHarness();
739 const result = yield* harness.call("read_pull_request_guide", {
740 repository: "t3tools/t3code",
741 number: 3,
742 });
743 expect(result).toMatchObject({ number: 3, guide: null, run: null, stale: false });
744 }),
745 );
746});
747​
748it("keeps failure diagnostics as the cause rather than exposing them in the tool message", () => {
749 const cause = new Error("database internals");
750 const failure = new PullRequestLinkFailedError({ cause });
751 expect(failure.message).toBe("Could not link the pull request.");
752 expect(failure.cause).toBe(cause);
753});