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("rejects a target that names neither a URL nor repository and number", () =>
269 Effect.gen(function* () {
270 const harness = yield* makeHarness();
271 const error = yield* harness
272 .call("link_pull_request", { repository: "x/y" })
273 .pipe(Effect.flip);
274 expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" });
275 const unknown = yield* harness
276 .call("link_pull_request", {
277 url: "https://github.com/t3tools/t3code/issues/1?token=private-value",
278 })
279 .pipe(Effect.flip);
280 expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" });
281 expect(unknown.message).not.toContain("private-value");
282 expect(yield* Ref.get(harness.commands)).toEqual([]);
283 }),
284 );
285
286 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
287 Effect.gen(function* () {
288 const harness = yield* makeHarness({
289 thread: makeThread([makeLink(123)]),
290 reject: (command) =>
291 command.type === "thread.pull-request.link"
292 ? new OrchestrationCommandInvariantError({
293 commandType: command.type,
294 detail: "already linked",
295 })
296 : null,
297 });
298 const result = yield* harness.call("link_pull_request", {
299 url: "https://github.com/t3tools/t3code/pull/123",
300 });
301 expect(result.alreadyLinked).toBe(true);
302 }),
303 );
304
305 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
306 Effect.gen(function* () {
307 const harness = yield* makeHarness({
308 thread: makeThread([makeLink(5)]),
309 reject: (command) =>
310 command.type === "thread.pull-request.unlink" && command.number !== 5
311 ? new OrchestrationCommandInvariantError({
312 commandType: command.type,
313 detail: "not linked",
314 })
315 : null,
316 });
317 const linked = yield* harness.call("unlink_pull_request", {
318 repository: "t3tools/t3code",
319 number: 5,
320 });
321 expect(linked).toEqual({
322 host: "github.com",
323 repository: "t3tools/t3code",
324 number: 5,
325 wasLinked: true,
326 });
327 const missing = yield* harness.call("unlink_pull_request", {
328 url: "https://github.com/t3tools/t3code/pull/9",
329 });
330 expect(missing.wasLinked).toBe(false);
331 expect(yield* Ref.get(harness.commands)).toMatchObject([
332 { type: "thread.pull-request.unlink", number: 5 },
333 ]);
334 }),
335 );
336
337 it.effect("fails cleanly when the token's thread no longer exists", () =>
338 Effect.gen(function* () {
339 const harness = yield* makeHarness({ thread: null });
340 const error = yield* harness.call("list_thread_pull_requests", {}).pipe(Effect.flip);
341 expect(error).toMatchObject({ _tag: "PullRequestThreadNotFoundError", threadId: THREAD_ID });
342 }),
343 );
344
345 it.effect("lists visible links with host state and derived chain order", () =>
346 Effect.gen(function* () {
347 const harness = yield* makeHarness({
348 thread: makeThread([
349 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
350 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
351 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
352 makeLink(9, { source: "stack-dismissed" }),
353 makeLink(10),
354 ]),
355 });
356 const result = yield* harness.call("list_thread_pull_requests", {});
357 expect(result.pullRequests.map((entry) => entry.number)).toEqual([3, 1, 2, 10]);
358 expect(result.pullRequests[0]).toEqual({
359 host: "github.com",
360 repository: "t3tools/t3code",
361 number: 3,
362 url: "https://github.com/t3tools/t3code/pull/3",
363 source: "agent",
364 state: "open",
365 title: "PR 3",
366 headBranch: "feat-c",
367 baseBranch: "feat-b",
368 isDraft: false,
369 stack: { kind: "derived", position: 3, size: 3 },
370 });
371 expect(result.pullRequests[3]).toMatchObject({
372 number: 10,
373 state: null,
374 title: null,
375 headBranch: null,
376 stack: null,
377 });
378 expect(result.chains).toEqual([
379 { kind: "derived", numbers: [1, 2, 3] },
380 { kind: "derived", numbers: [10] },
381 ]);
382 }),
383 );
384});
385
386describe("listThreadPullRequests", () => {
387 it("reports a native stack position for each member", () => {
388 const stack = {
389 kind: "native" as const,
390 id: "stack-1",
391 number: 1,
392 url: "https://github.com/t3tools/t3code/stack/1",
393 base: "main",
394 layers: [
395 { number: 1, headBranch: "a", state: "open" as const },
396 { number: 2, headBranch: "b", state: "open" as const },
397 ],
398 };
399 const result = listThreadPullRequests({
400 pullRequests: [
401 makeLink(2, { stack, source: "stack" }),
402 makeLink(1, { stack, source: "created" }),
403 ],
404 });
405 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
406 [2, { kind: "native", position: 2, size: 2 }],
407 [1, { kind: "native", position: 1, size: 2 }],
408 ]);
409 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
410 });
411});
412
413it("keeps failure diagnostics as the cause rather than exposing them in the tool message", () => {
414 const cause = new Error("database internals");
415 const failure = new PullRequestLinkFailedError({ cause });
416 expect(failure.message).toBe("Could not link the pull request.");
417 expect(failure.cause).toBe(cause);
418});