Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationCommand,
7 type OrchestrationProjectShell,
8 type OrchestrationThreadShell,
9 type ThreadPullRequestLink,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "@effect/vitest";
12import * as Crypto from "effect/Crypto";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Ref from "effect/Ref";
17import * as Stream from "effect/Stream";
18import type { Tool } from "effect/unstable/ai";
19
20import { OrchestrationCommandInvariantError } from "../../../orchestration/Errors.ts";
21import {
22 OrchestrationEngineService,
23 type OrchestrationEngineShape,
24} from "../../../orchestration/Services/OrchestrationEngine.ts";
25import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
26import * as McpInvocationContext from "../../McpInvocationContext.ts";
27import { listThreadPullRequests, PullRequestsToolkitHandlersLive } from "./handlers.ts";
28import { PullRequestLinkFailedError, PullRequestsToolkit } from "./tools.ts";
29
30const PROJECT_ID = ProjectId.make("project-1");
31const THREAD_ID = ThreadId.make("thread-1");
32
33const testCrypto = Crypto.make({
34 randomBytes: (size) => new Uint8Array(size).fill(7),
35 digest: (_algorithm, data) => Effect.succeed(data),
36});
37
38const invocation = (
39 capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
40): McpInvocationContext.McpInvocationScope => ({
41 environmentId: EnvironmentId.make("environment-1"),
42 threadId: THREAD_ID,
43 providerSessionId: "provider-session-1",
44 providerInstanceId: ProviderInstanceId.make("codex"),
45 capabilities: new Set(capabilities),
46 issuedAt: 1,
47});
48
49function makeProject(
50 repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
51 canonicalKey: "github.com/t3tools/t3code",
52 locator: {
53 source: "git-remote",
54 remoteName: "origin",
55 remoteUrl: "git@github.com:T3Tools/T3Code.git",
56 },
57 provider: "github",
58 displayName: "T3Tools/T3Code",
59 owner: "T3Tools",
60 name: "T3Code",
61 },
62): OrchestrationProjectShell {
63 return {
64 id: PROJECT_ID,
65 title: "Project",
66 workspaceRoot: "/workspace/project",
67 defaultModelSelection: null,
68 scripts: [],
69 repositoryIdentity,
70 createdAt: "2026-08-01T00:00:00.000Z",
71 updatedAt: "2026-08-01T00:00:00.000Z",
72 };
73}
74
75function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): OrchestrationThreadShell {
76 return {
77 id: THREAD_ID,
78 projectId: PROJECT_ID,
79 title: "Thread",
80 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
81 runtimeMode: "full-access",
82 interactionMode: "default",
83 branch: null,
84 worktreePath: null,
85 pullRequests,
86 latestTurn: null,
87 createdAt: "2026-08-01T00:00:00.000Z",
88 updatedAt: "2026-08-20T00:00:00.000Z",
89 archivedAt: null,
90 settledOverride: null,
91 settledAt: null,
92 session: null,
93 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
94 hasPendingApprovals: false,
95 hasPendingUserInput: false,
96 hasActionableProposedPlan: false,
97 };
98}
99
100function makeLink(
101 number: number,
102 overrides: Partial<ThreadPullRequestLink> & {
103 readonly headBranch?: string;
104 readonly baseBranch?: string;
105 } = {},
106): ThreadPullRequestLink {
107 const { headBranch, baseBranch, ...rest } = overrides;
108 return {
109 host: "github.com",
110 repository: "t3tools/t3code",
111 number,
112 url: `https://github.com/t3tools/t3code/pull/${number}`,
113 source: "manual",
114 linkedAt: "2026-08-10T00:00:00.000Z",
115 snapshot:
116 headBranch === undefined
117 ? null
118 : {
119 state: "open",
120 title: `PR ${number}`,
121 headBranch,
122 baseBranch: baseBranch ?? "main",
123 isDraft: false,
124 updatedAt: null,
125 syncedAt: "2026-08-27T00:00:00.000Z",
126 },
127 stack: null,
128 ...rest,
129 };
130}
131
132interface HarnessOptions {
133 readonly thread?: OrchestrationThreadShell | null;
134 readonly project?: OrchestrationProjectShell | null;
135 readonly reject?: (command: OrchestrationCommand) => OrchestrationCommandInvariantError | null;
136}
137
138const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
139 options: HarnessOptions = {},
140) {
141 const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
142 const thread = options.thread === undefined ? makeThread([]) : options.thread;
143 const project = options.project === undefined ? makeProject() : options.project;
144 const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
145 Effect.gen(function* () {
146 const rejection = options.reject?.(command) ?? null;
147 if (rejection !== null) return yield* rejection;
148 yield* Ref.update(commands, (recorded) => [...recorded, command]);
149 return { sequence: 1 };
150 });
151 const dependencies = Layer.mergeAll(
152 Layer.mock(ProjectionSnapshotQuery)({
153 getThreadShellById: (threadId) =>
154 Effect.succeed(threadId === THREAD_ID ? Option.fromNullishOr(thread) : Option.none()),
155 getProjectShellById: () => Effect.succeed(Option.fromNullishOr(project)),
156 }),
157 Layer.mock(OrchestrationEngineService)({
158 readEvents: () => Stream.empty,
159 dispatch,
160 streamDomainEvents: Stream.empty,
161 latestSequence: Effect.succeed(0),
162 }),
163 Layer.succeed(Crypto.Crypto, testCrypto),
164 );
165 const toolkit = yield* PullRequestsToolkit.pipe(
166 Effect.provide(PullRequestsToolkitHandlersLive.pipe(Layer.provide(dependencies))),
167 );
168 const call = <Name extends keyof typeof PullRequestsToolkit.tools>(
169 name: Name,
170 params: Parameters<typeof toolkit.handle<Name>>[1],
171 capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["pull-requests"],
172 ) =>
173 toolkit.handle(name, params).pipe(
174 Stream.unwrap,
175 Stream.runCollect,
176 // Failure mode is "error", so a delivered result is always the success shape.
177 Effect.map(
178 (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof PullRequestsToolkit.tools)[Name]>,
179 ),
180 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
181 Effect.provide(dependencies),
182 );
183 return { commands, call };
184});
185
186describe("pull request toolkit handlers", () => {
187 it.effect("refuses a credential without the pull-requests capability", () =>
188 Effect.gen(function* () {
189 const harness = yield* makeHarness();
190 const error = yield* harness
191 .call("list_thread_pull_requests", {}, ["preview"])
192 .pipe(Effect.flip);
193 expect(error).toMatchObject({
194 _tag: "McpCapabilityUnavailableError",
195 capability: "pull-requests",
196 threadId: THREAD_ID,
197 });
198 expect(yield* Ref.get(harness.commands)).toEqual([]);
199 }),
200 );
201
202 it.effect("links by URL with source agent on the token's thread", () =>
203 Effect.gen(function* () {
204 const harness = yield* makeHarness();
205 const result = yield* harness.call("link_pull_request", {
206 url: "https://github.com/T3Tools/T3Code/pull/123/files",
207 });
208 expect(result).toEqual({
209 host: "github.com",
210 repository: "t3tools/t3code",
211 number: 123,
212 url: "https://github.com/T3Tools/T3Code/pull/123/files",
213 alreadyLinked: false,
214 });
215 expect(yield* Ref.get(harness.commands)).toMatchObject([
216 {
217 type: "thread.pull-request.link",
218 threadId: THREAD_ID,
219 host: "github.com",
220 repository: "t3tools/t3code",
221 number: 123,
222 source: "agent",
223 },
224 ]);
225 }),
226 );
227
228 it.effect("links by repository and number, defaulting the host to the project's", () =>
229 Effect.gen(function* () {
230 const harness = yield* makeHarness();
231 const result = yield* harness.call("link_pull_request", {
232 repository: "T3Tools/Other",
233 number: 7,
234 });
235 expect(result).toEqual({
236 host: "github.com",
237 repository: "t3tools/other",
238 number: 7,
239 url: "https://github.com/t3tools/other/pull/7",
240 alreadyLinked: false,
241 });
242 }),
243 );
244
245 it.effect("builds the URL in the project host's own shape", () =>
246 Effect.gen(function* () {
247 const harness = yield* makeHarness({
248 project: makeProject({
249 canonicalKey: "gitlab.com/group/sub/project",
250 locator: {
251 source: "git-remote",
252 remoteName: "origin",
253 remoteUrl: "git@gitlab.com:group/sub/project.git",
254 },
255 provider: "gitlab",
256 displayName: "group/sub/project",
257 }),
258 });
259 const result = yield* harness.call("link_pull_request", {
260 repository: "group/sub/project",
261 number: 42,
262 });
263 expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
264 expect(result.host).toBe("gitlab.com");
265 }),
266 );
267
268 it.effect("links a numeric Forgejo reference with its remote's web origin and mount path", () =>
269 Effect.gen(function* () {
270 const harness = yield* makeHarness({
271 project: makeProject({
272 canonicalKey: "forge.example/git/owner/repo",
273 locator: {
274 source: "git-remote",
275 remoteName: "origin",
276 remoteUrl: "http://forge.example:3000/git/owner/repo.git",
277 },
278 provider: "forgejo",
279 displayName: "git/owner/repo",
280 }),
281 });
282 const result = yield* harness.call("link_pull_request", {
283 repository: "git/owner/repo",
284 number: 42,
285 });
286 expect(result).toEqual({
287 host: "forge.example:3000",
288 repository: "git/owner/repo",
289 number: 42,
290 url: "http://forge.example:3000/git/owner/repo/pulls/42",
291 alreadyLinked: false,
292 });
293 const other = yield* harness.call("link_pull_request", {
294 host: "other.example",
295 repository: "owner/repo",
296 number: 42,
297 });
298 expect(other.url).toBe("https://other.example/owner/repo/pull/42");
299 }),
300 );
301
302 it.effect("rejects a target that names neither a URL nor repository and number", () =>
303 Effect.gen(function* () {
304 const harness = yield* makeHarness();
305 const error = yield* harness
306 .call("link_pull_request", { repository: "x/y" })
307 .pipe(Effect.flip);
308 expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" });
309 const unknown = yield* harness
310 .call("link_pull_request", {
311 url: "https://github.com/t3tools/t3code/issues/1?token=private-value",
312 })
313 .pipe(Effect.flip);
314 expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" });
315 expect(unknown.message).not.toContain("private-value");
316 expect(yield* Ref.get(harness.commands)).toEqual([]);
317 }),
318 );
319
320 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
321 Effect.gen(function* () {
322 const harness = yield* makeHarness({
323 thread: makeThread([makeLink(123)]),
324 reject: (command) =>
325 command.type === "thread.pull-request.link"
326 ? new OrchestrationCommandInvariantError({
327 commandType: command.type,
328 detail: "already linked",
329 })
330 : null,
331 });
332 const result = yield* harness.call("link_pull_request", {
333 url: "https://github.com/t3tools/t3code/pull/123",
334 });
335 expect(result.alreadyLinked).toBe(true);
336 }),
337 );
338
339 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
340 Effect.gen(function* () {
341 const harness = yield* makeHarness({
342 thread: makeThread([makeLink(5)]),
343 reject: (command) =>
344 command.type === "thread.pull-request.unlink" && command.number !== 5
345 ? new OrchestrationCommandInvariantError({
346 commandType: command.type,
347 detail: "not linked",
348 })
349 : null,
350 });
351 const linked = yield* harness.call("unlink_pull_request", {
352 repository: "t3tools/t3code",
353 number: 5,
354 });
355 expect(linked).toEqual({
356 host: "github.com",
357 repository: "t3tools/t3code",
358 number: 5,
359 wasLinked: true,
360 });
361 const missing = yield* harness.call("unlink_pull_request", {
362 url: "https://github.com/t3tools/t3code/pull/9",
363 });
364 expect(missing.wasLinked).toBe(false);
365 expect(yield* Ref.get(harness.commands)).toMatchObject([
366 { type: "thread.pull-request.unlink", number: 5 },
367 ]);
368 }),
369 );
370
371 it("reports an older Forgejo link's HTTP port when listing thread links", () => {
372 const result = listThreadPullRequests(
373 makeThread([
374 makeLink(42, {
375 host: "forge.example",
376 url: "http://forge.example:3000/t3tools/t3code/pulls/42",
377 }),
378 ]),
379 );
380 expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
381 });
382
383 it.effect("fails cleanly when the token's thread no longer exists", () =>
384 Effect.gen(function* () {
385 const harness = yield* makeHarness({ thread: null });
386 const error = yield* harness.call("list_thread_pull_requests", {}).pipe(Effect.flip);
387 expect(error).toMatchObject({ _tag: "PullRequestThreadNotFoundError", threadId: THREAD_ID });
388 }),
389 );
390
391 it.effect("lists visible links with host state and derived chain order", () =>
392 Effect.gen(function* () {
393 const harness = yield* makeHarness({
394 thread: makeThread([
395 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
396 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
397 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
398 makeLink(9, { source: "stack-dismissed" }),
399 makeLink(10),
400 ]),
401 });
402 const result = yield* harness.call("list_thread_pull_requests", {});
403 expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]);
404 expect(result.pullRequests[0]).toEqual({
405 host: "github.com",
406 repository: "t3tools/t3code",
407 number: 3,
408 url: "https://github.com/t3tools/t3code/pull/3",
409 source: "agent",
410 state: "open",
411 title: "PR 3",
412 headBranch: "feat-c",
413 baseBranch: "feat-b",
414 isDraft: false,
415 stack: { kind: "derived", position: 3, size: 3 },
416 });
417 expect(result.pullRequests[3]).toMatchObject({
418 number: 10,
419 state: null,
420 title: null,
421 headBranch: null,
422 stack: null,
423 });
424 expect(result.chains).toEqual([
425 { kind: "derived", numbers: [1, 2, 3] },
426 { kind: "derived", numbers: [10] },
427 ]);
428 }),
429 );
430});
431
432describe("listThreadPullRequests", () => {
433 it("reports a native stack position for each member", () => {
434 const stack = {
435 kind: "native" as const,
436 id: "stack-1",
437 number: 1,
438 url: "https://github.com/t3tools/t3code/stack/1",
439 base: "main",
440 layers: [
441 { number: 1, headBranch: "a", state: "open" as const },
442 { number: 2, headBranch: "b", state: "open" as const },
443 ],
444 };
445 const result = listThreadPullRequests({
446 pullRequests: [
447 makeLink(2, { stack, source: "stack" }),
448 makeLink(1, { stack, source: "created" }),
449 ],
450 });
451 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
452 [2, { kind: "native", position: 2, size: 2 }],
453 [1, { kind: "native", position: 1, size: 2 }],
454 ]);
455 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
456 });
457});
458
459it("keeps failure diagnostics as the cause rather than exposing them in the tool message", () => {
460 const cause = new Error("database internals");
461 const failure = new PullRequestLinkFailedError({ cause });
462 expect(failure.message).toBe("Could not link the pull request.");
463 expect(failure.cause).toBe(cause);
464});