Open History to see the last commit
1import {
2 CommandId,
3 NonNegativeInt,
4 type PullRequestActivity,
5 PullRequestListCursors,
6 type PullRequestRef,
7 type PullRequestReviewCommentDraft,
8 type PullRequestCheck,
9 type PullRequestReviewThread,
10 type OrchestrationProjectShell,
11 type PullRequestState,
12 type PullRequestWatchUntil,
13 type OrchestrationV2ThreadShell,
14 type ThreadId,
15 type ThreadPullRequestLink,
16 TrimmedNonEmptyString,
17} from "@t3tools/contracts";
18import * as Cause from "effect/Cause";
19import * as SecureRandom from "effect/crypto/SecureRandom";
20import * as Effect from "effect/Effect";
21import * as Base64Url from "effect/encoding/Base64Url";
22import * as Option from "effect/Option";
23import * as Schema from "effect/Schema";
24
25import * as GitManager from "../../../git/GitManager.ts";
26import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
27import * as ProjectService from "../../../project/ProjectService.ts";
28import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
29import { resolveTarget, type ResolvedTarget } from "../../../pullRequest/pullRequestTarget.ts";
30import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
31import * as PullRequestService from "../../../pullRequest/PullRequestService.ts";
32import { reviewPositionInPatch } from "../../../pullRequest/pullRequestReviewPosition.ts";
33import {
34 ownPullRequestRepositories,
35 pullRequestSyncKey,
36} from "../../../pullRequest/pullRequestSyncKey.ts";
37import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts";
38import {
39 normalizeThreadPullRequestKey,
40 resolveThreadPullRequestChains,
41 threadPullRequestKeyOf,
42 threadPullRequestKeysEqual,
43 threadPullRequestsOf,
44 visibleThreadPullRequests,
45} from "../../../sourceControl/threadPullRequests.ts";
46import * as McpInvocationContext from "../../McpInvocationContext.ts";
47import * as McpToolAccess from "../../McpToolAccess.ts";
48import { threadNotFound } from "../../threadAccess.ts";
49import {
50 type ListThreadPullRequestsResult,
51 PullRequestBranchHasNoneError,
52 PullRequestCursorInvalidError,
53 PullRequestForgeError,
54 PullRequestNothingToDoError,
55 type PullRequestReadSection,
56 type ReadPullRequestResult,
57 type ReviewLineComment,
58 type ThreadPullRequestInput,
59 PullRequestLinkFailedError,
60 PullRequestUnlinkFailedError,
61 PullRequestListFailedError,
62 type PullRequestTargetInput,
63 PullRequestThreadRequiredError,
64 PullRequestGuideFailedError,
65 PullRequestProjectNotFoundError,
66 PullRequestsToolkit,
67 type ThreadPullRequestEntry,
68 alreadyEndedWatchNext,
69 CHECKS_ALREADY_PASSED_WATCH_NEXT,
70 CHILD_PULL_REQUEST_REPORT_NEXT,
71} from "./tools.ts";
72
73const ReadCursor = Schema.Union([
74 Schema.Struct({ diff: TrimmedNonEmptyString }),
75 // Null marks a list the read did not ask for.
76 Schema.Struct({
77 threads: Schema.NullOr(NonNegativeInt),
78 comments: Schema.NullOr(NonNegativeInt),
79 includeResolved: Schema.Boolean,
80 }),
81]);
82type ReadCursor = typeof ReadCursor.Type;
83
84const ReadCursorJson = Schema.fromJsonString(ReadCursor);
85const ListCursorsJson = Schema.fromJsonString(PullRequestListCursors);
86const encodeReadCursorJson = Schema.encodeSync(ReadCursorJson);
87const encodeListCursorsJson = Schema.encodeSync(ListCursorsJson);
88const decodeReadCursorJson = Schema.decodeUnknownEffect(ReadCursorJson);
89const decodeListCursorsJson = Schema.decodeUnknownEffect(ListCursorsJson);
90
91const decodeCursorText = (cursor: string) =>
92 Effect.fromResult(Base64Url.decodeString(cursor)).pipe(
93 Effect.mapError(() => new PullRequestCursorInvalidError({})),
94 );
95
96const readCursors = {
97 encode: (value: ReadCursor) => Base64Url.encode(encodeReadCursorJson(value)),
98 decode: (cursor: string) =>
99 decodeCursorText(cursor).pipe(
100 Effect.flatMap(decodeReadCursorJson),
101 Effect.mapError(() => new PullRequestCursorInvalidError({})),
102 ),
103};
104
105const listCursors = {
106 encode: (value: PullRequestListCursors) => Base64Url.encode(encodeListCursorsJson(value)),
107 decode: (cursor: string) =>
108 decodeCursorText(cursor).pipe(
109 Effect.flatMap(decodeListCursorsJson),
110 Effect.mapError(() => new PullRequestCursorInvalidError({})),
111 ),
112};
113
114/** Keeps one conversation page near the size of a capped CI log. */
115const CONVERSATION_PAGE_CHARS = 32_000;
116const THREAD_COMMENT_PAGES = 4;
117/** Diff pages searched for review comment lines; a PR past this is too big to review by line. */
118const REVIEW_DIFF_PAGES = 10;
119
120function conversationPage(
121 activity: PullRequestActivity,
122 start: { readonly threads: number | null; readonly comments: number | null },
123 includeResolved: boolean,
124) {
125 // Offsets index the unfiltered lists, whose order resolving a thread does not change.
126 const { reviewThreads, comments } = activity;
127 const pageThreads: Array<PullRequestReviewThread> = [];
128 const pageComments: Array<PullRequestActivity["comments"][number]> = [];
129 let size = 0;
130 let thread = start.threads === null ? null : Math.min(start.threads, reviewThreads.length);
131 let comment = start.comments === null ? null : Math.min(start.comments, comments.length);
132 const fits = (item: unknown) => {
133 const next = size + JSON.stringify(item).length;
134 if (next > CONVERSATION_PAGE_CHARS && pageThreads.length + pageComments.length > 0) {
135 return false;
136 }
137 size = next;
138 return true;
139 };
140 // Review threads come first: they hold the feedback an agent acts on.
141 while (thread !== null && thread < reviewThreads.length) {
142 const next = reviewThreads[thread]!;
143 if (includeResolved || !next.isResolved) {
144 if (!fits(next)) break;
145 pageThreads.push(next);
146 }
147 thread += 1;
148 }
149 const threadsDone = thread === null || thread === reviewThreads.length;
150 if (threadsDone) {
151 while (comment !== null && comment < comments.length && fits(comments[comment])) {
152 pageComments.push(comments[comment++]!);
153 }
154 }
155 const done = threadsDone && (comment === null || comment === comments.length);
156 return {
157 threads: pageThreads,
158 comments: pageComments,
159 next: done ? null : { threads: thread, comments: comment, includeResolved },
160 };
161}
162
163function checksSummary(checks: ReadonlyArray<PullRequestCheck>) {
164 let passed = 0;
165 let pending = 0;
166 let incomplete = false;
167 const failed: Array<string> = [];
168 for (const check of checks) {
169 if (check.placeholder === true) incomplete = true;
170 else if (check.status === "failure" || check.status === "cancelled") failed.push(check.name);
171 else if (check.status === "pending" || check.status === "action-required") pending += 1;
172 else passed += 1;
173 }
174 return { passed, pending, failed, ...(incomplete ? { incomplete: true as const } : {}) };
175}
176
177function entryOf(
178 link: ThreadPullRequestLink,
179 chains: ReturnType<typeof resolveThreadPullRequestChains>,
180): ThreadPullRequestEntry {
181 const key = threadPullRequestKeyOf(link);
182 let stack: ThreadPullRequestEntry["stack"] = null;
183 for (const chain of chains) {
184 if (chain.layers.length < 2) continue;
185 const index = chain.layers.findIndex((layer) => threadPullRequestKeyOf(layer) === key);
186 if (index !== -1) {
187 stack = { kind: chain.kind, position: chain.depths[index]! + 1, size: chain.layers.length };
188 break;
189 }
190 }
191 return {
192 host: normalizeThreadPullRequestKey(link).host,
193 repository: link.repository,
194 number: link.number,
195 url: link.url,
196 source: link.source,
197 watching: link.watch !== undefined,
198 state: link.snapshot?.state ?? null,
199 title: link.snapshot?.title ?? null,
200 headBranch: link.snapshot?.headBranch ?? null,
201 baseBranch: link.snapshot?.baseBranch ?? null,
202 isDraft: link.snapshot?.isDraft ?? null,
203 stack,
204 };
205}
206
207const PULL_REQUEST_LIST_PAGE_SIZE = 50;
208
209// A total order that survives unlinking: the cursor names a position, not an index, so removing
210// PRs already returned cannot skip later ones. PRs linked in one call share `linkedAt`.
211function pullRequestListPosition(link: ThreadPullRequestLink): string {
212 return [link.linkedAt, link.host, link.repository, String(link.number).padStart(10, "0")].join(
213 " ",
214 );
215}
216
217export function listThreadPullRequests(
218 thread: Pick<OrchestrationV2ThreadShell, "pullRequests">,
219 cursor?: string,
220 states?: ReadonlyArray<PullRequestState>,
221): ListThreadPullRequestsResult {
222 const chains = resolveThreadPullRequestChains(thread.pullRequests ?? []);
223 const after = visibleThreadPullRequests(thread.pullRequests ?? [])
224 .filter((link) => states === undefined || states.includes(link.snapshot?.state ?? "open"))
225 .map((link) => ({ link, position: pullRequestListPosition(link) }))
226 .filter(({ position }) => cursor === undefined || position > cursor)
227 .toSorted((left, right) => (left.position < right.position ? -1 : 1));
228 const page = after.slice(0, PULL_REQUEST_LIST_PAGE_SIZE);
229 const pageKeys = new Set(page.map(({ link }) => threadPullRequestKeyOf(link)));
230 return {
231 pullRequests: page.map(({ link }) => entryOf(link, chains)),
232 // Stacks with a pull request on this page, whole.
233 chains: chains
234 .filter((chain) => chain.layers.some((layer) => pageKeys.has(threadPullRequestKeyOf(layer))))
235 .map((chain) => ({
236 kind: chain.kind,
237 numbers: chain.layers.map((layer) => layer.number),
238 })),
239 nextCursor: after.length > page.length ? page.at(-1)!.position : null,
240 };
241}
242
243function projectForPullRequest(
244 projects: ReadonlyArray<OrchestrationProjectShell>,
245 target: { readonly host: string; readonly repository: string },
246 preferred: OrchestrationProjectShell | undefined,
247): OrchestrationProjectShell | undefined {
248 // Match the guide service's host-level repository key, including Azure DevOps org/project/_git/repo.
249 const matches = (project: OrchestrationProjectShell) => {
250 const own = pullRequestSyncKey(
251 { projectId: project.id, host: target.host, repository: target.repository, number: 1 },
252 project.repositoryIdentity ?? undefined,
253 );
254 return (
255 own !== null &&
256 ownPullRequestRepositories(project.repositoryIdentity).some(
257 ({ key }) => own.host === key.host && own.repository === key.repository,
258 )
259 );
260 };
261 if (preferred !== undefined && matches(preferred)) return preferred;
262 return projects.find(matches);
263}
264
265const make = Effect.gen(function* () {
266 const engine = yield* Orchestrator.OrchestratorV2;
267 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
268 const watches = yield* PullRequestWatchService.PullRequestWatchService;
269 const pullRequests = yield* PullRequestService.PullRequestService;
270 const git = yield* GitManager.GitManager;
271
272 const projects = yield* ProjectService.ProjectService;
273 const random = yield* SecureRandom.SecureRandom;
274
275 const commandId = (tag: string, threadId: ThreadId) =>
276 random.uuidV4().pipe(
277 Effect.orDie,
278 Effect.map((uuid) => CommandId.make(`server:${tag}:${threadId}:${uuid}`)),
279 );
280
281 const requireThread = Effect.fn("PullRequestsToolkit.requireThread")(function* (
282 Failure:
283 | typeof PullRequestLinkFailedError
284 | typeof PullRequestUnlinkFailedError
285 | typeof PullRequestListFailedError
286 | typeof PullRequestForgeError,
287 requested: ThreadId | undefined,
288 ) {
289 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
290 const threadId = requested ?? scope.thread?.threadId;
291 if (threadId === undefined) {
292 return yield* new PullRequestThreadRequiredError();
293 }
294 const thread = yield* engine.getThreadShell(threadId).pipe(
295 Effect.map(Option.fromNullishOr),
296 Effect.mapError((cause) => new Failure({ cause })),
297 );
298 if (Option.isNone(thread) || thread.value.deletedAt !== null) {
299 return yield* threadNotFound(engine, scope, threadId, `Thread ${threadId} was not found.`);
300 }
301 return thread.value;
302 });
303
304 const projectOf = (
305 thread: OrchestrationV2ThreadShell,
306 Failure:
307 | typeof PullRequestLinkFailedError
308 | typeof PullRequestUnlinkFailedError
309 | typeof PullRequestForgeError,
310 ) =>
311 pullRequests
312 .addressedProject(thread.projectId)
313 .pipe(Effect.mapError((cause) => new Failure({ cause })));
314
315 const dispatchFailure =
316 (Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) =>
317 <E>(
318 cause: Cause.Cause<E>,
319 ): Effect.Effect<never, PullRequestLinkFailedError | PullRequestUnlinkFailedError> =>
320 Cause.hasInterruptsOnly(cause)
321 ? Effect.failCause(cause as Cause.Cause<never>)
322 : Effect.fail(new Failure({ cause }));
323
324 // The domain service owns the registration span.
325 const setWatching = Effect.fnUntraced(function* (
326 input: PullRequestTargetInput & { readonly until?: PullRequestWatchUntil | undefined },
327 watching: boolean,
328 ) {
329 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
330 const threadId = input.threadId ?? scope.thread?.threadId;
331 if (threadId === undefined) return yield* new PullRequestThreadRequiredError();
332 return yield* watches
333 .setWatching({ threadId, target: input, watching, until: input.until })
334 .pipe(
335 Effect.map((result) =>
336 result.state !== undefined
337 ? { ...result, next: alreadyEndedWatchNext(result.state) }
338 : result.checksState === "passing"
339 ? { ...result, next: CHECKS_ALREADY_PASSED_WATCH_NEXT }
340 : result,
341 ),
342 Effect.catchTags({
343 PullRequestWatchThreadNotFoundError: (error) =>
344 threadNotFound(engine, scope, error.threadId, error.message),
345 }),
346 );
347 });
348
349 const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
350 targets: ReadonlyArray<Omit<PullRequestTargetInput, "threadId">>,
351 ) {
352 const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
353 const callerThread =
354 scope.thread === undefined
355 ? undefined
356 : yield* engine.getThreadShell(scope.thread.threadId).pipe(
357 Effect.orElseSucceed(() => null),
358 Effect.map((shell) => shell ?? undefined),
359 );
360 const known = yield* projects
361 .listShells()
362 .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause })));
363 const callerProject =
364 callerThread === undefined
365 ? undefined
366 : yield* pullRequests
367 .addressedProject(callerThread.projectId)
368 .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause })));
369 // A pull request named by host and repository builds its URL through the project that holds
370 // it, which need not be the caller's.
371 const urlProject = (input: PullRequestTargetInput) =>
372 input.url === undefined && input.host !== undefined && input.repository !== undefined
373 ? (projectForPullRequest(
374 known,
375 { host: input.host, repository: input.repository },
376 callerProject,
377 ) ?? callerProject)
378 : callerProject;
379 return yield* Effect.forEach(targets, (input) =>
380 resolveTarget(input, urlProject(input)).pipe(
381 Effect.map((target) => ({
382 input,
383 target,
384 project: projectForPullRequest(known, target, callerProject),
385 callerProject,
386 failure: null,
387 })),
388 Effect.catch((error) =>
389 Effect.succeed({
390 input,
391 target: null,
392 project: undefined,
393 callerProject,
394 failure: error.message,
395 }),
396 ),
397 ),
398 );
399 });
400
401 const guideReference = (
402 project: OrchestrationProjectShell,
403 target: { readonly host: string; readonly repository: string; readonly number: number },
404 ) => ({
405 projectId: project.id,
406 host: target.host,
407 repository: target.repository,
408 number: target.number,
409 });
410
411 const guideFailureDetail = (error: { readonly message: string }) =>
412 "detail" in error && typeof error.detail === "string" ? error.detail : error.message;
413
414 const writesThread = <P extends { readonly threadId?: ThreadId | undefined }, A, E, R>(
415 handle: (params: P) => Effect.Effect<A, E, R>,
416 ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
417
418 const forgeFailure = (error: { readonly message: string }) =>
419 new PullRequestForgeError({ detail: error.message, cause: error });
420
421 // Layers below the target are pinned to the heads read here; the host refuses if any moved.
422 const stackMergeScope = Effect.fnUntraced(function* (
423 ref: PullRequestRef,
424 input: { readonly expectedHeadSha: string },
425 ) {
426 const stack = yield* pullRequests
427 .stack(ref, { bypassCache: true })
428 .pipe(Effect.mapError(forgeFailure));
429 const end = stack?.layers.findIndex((layer) => layer.number === ref.number) ?? -1;
430 if (stack === null || end === -1)
431 return yield* new PullRequestForgeError({
432 detail: `PR #${ref.number} is not in a stack this host can merge. Merge it without stack.`,
433 });
434 const expectedStackHeads: Array<{ readonly number: number; readonly headSha: string }> = [];
435 for (const layer of stack.layers.slice(0, end + 1)) {
436 if (layer.state === "merged") continue;
437 const headSha =
438 layer.number !== ref.number
439 ? layer.headSha
440 : layer.headSha !== undefined &&
441 PullRequestService.isHeadSha(layer.headSha, input.expectedHeadSha)
442 ? layer.headSha
443 : input.expectedHeadSha;
444 if (headSha === undefined)
445 return yield* new PullRequestForgeError({
446 detail: `The host did not report PR #${layer.number}'s head, so the stack cannot be pinned. Try again.`,
447 });
448 expectedStackHeads.push({ number: layer.number, headSha });
449 }
450 return { stackNumber: stack.number, expectedStackHeads };
451 });
452
453 /** A login or org/team, matched to the host's own reviewer id. */
454 const reviewerNamed = (ref: PullRequestRef, name: string) =>
455 pullRequests.reviewerCandidates({ ...ref, query: name }).pipe(
456 Effect.mapError(forgeFailure),
457 Effect.flatMap(({ candidates }) => {
458 const wanted = name.toLowerCase();
459 const match = candidates.find(
460 (candidate) =>
461 candidate.login.toLowerCase() === wanted || candidate.id.toLowerCase() === wanted,
462 );
463 return match === undefined
464 ? Effect.fail(
465 new PullRequestForgeError({
466 detail: `No reviewer named ${name} can be requested on this PR.`,
467 }),
468 )
469 : Effect.succeed({ id: match.id, kind: match.kind });
470 }),
471 );
472
473 /** Line comments placed by the PR's diff, which says whether each line was added, removed, or kept. */
474 const reviewComments = Effect.fn("PullRequestsToolkit.reviewComments")(function* (
475 ref: PullRequestRef,
476 comments: ReadonlyArray<ReviewLineComment>,
477 ) {
478 const placed = new Map<ReviewLineComment, PullRequestReviewCommentDraft>();
479 // Comments whose end line some page showed, so a failure names the line that is missing.
480 const lineShown = new Set<ReviewLineComment>();
481 const unplaced = () => comments.filter((comment) => !placed.has(comment));
482 let cursor: string | undefined;
483 for (let page = 0; page < REVIEW_DIFF_PAGES && unplaced().length > 0; page += 1) {
484 const diff = yield* pullRequests
485 .diff({ ...ref, ...(cursor === undefined ? {} : { cursor }) })
486 .pipe(Effect.mapError(forgeFailure));
487 for (const comment of unplaced()) {
488 const side = comment.side ?? "new";
489 const position = reviewPositionInPatch(diff.patch, comment.path, comment.line, side);
490 const start =
491 comment.startLine === undefined
492 ? undefined
493 : reviewPositionInPatch(diff.patch, comment.path, comment.startLine, side);
494 if (position !== null) lineShown.add(comment);
495 if (position === null || start === null) continue;
496 placed.set(comment, {
497 path: comment.path,
498 position,
499 ...(start === undefined ? {} : { startPosition: start }),
500 body: comment.body,
501 });
502 }
503 if (diff.nextCursor === null) break;
504 cursor = diff.nextCursor;
505 }
506 const missing = unplaced()[0];
507 if (missing !== undefined) {
508 const missingLine =
509 missing.startLine !== undefined && lineShown.has(missing)
510 ? missing.startLine
511 : missing.line;
512 return yield* new PullRequestForgeError({
513 detail: `${missing.path} line ${missingLine} (${missing.side ?? "new"} side) is not in this PR's diff. Comment on a changed line or one shown around it.`,
514 });
515 }
516 return comments.map((comment) => placed.get(comment)!);
517 });
518
519 /** The thread's checkout, its project, and the PR the input names (default: the branch's). */
520 const locate = Effect.fn("PullRequestsToolkit.locate")(function* (input: ThreadPullRequestInput) {
521 const thread = yield* requireThread(PullRequestForgeError, undefined);
522 const project = yield* projectOf(thread, PullRequestForgeError);
523 if (project === undefined) {
524 return yield* new PullRequestProjectNotFoundError({ repository: input.repository ?? "" });
525 }
526 // Status sync sets branchPullRequest later, so a PR this thread just opened counts too,
527 // unless it is another branch's.
528 const opened =
529 thread.branchPullRequest === null || thread.branchPullRequest === undefined
530 ? threadPullRequestsOf(thread).findLast(
531 (link) =>
532 link.source === "created" &&
533 (link.snapshot === null || link.snapshot.headBranch === thread.branch),
534 )
535 : undefined;
536 const branchPullRequest = thread.branchPullRequest ?? opened ?? null;
537 const branchRepository =
538 project.repositoryIdentity == null
539 ? undefined
540 : (sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? undefined);
541 const named =
542 input.number !== undefined
543 ? { number: input.number, repository: input.repository ?? branchRepository }
544 : branchPullRequest === null
545 ? null
546 : { number: branchPullRequest.number, repository: branchPullRequest.repository };
547 if (named === null) return yield* new PullRequestBranchHasNoneError();
548 const target = yield* resolveTarget(named, project);
549 const ref: PullRequestRef = {
550 projectId: project.id,
551 host: target.host,
552 repository: target.repository,
553 number: target.number,
554 };
555 if (input.number === undefined && opened !== undefined && opened.snapshot === null) {
556 // Not synced yet, so only the host knows which branch it was opened from.
557 const summary = yield* pullRequests.summary(ref).pipe(Effect.mapError(forgeFailure));
558 if (summary.headBranch !== thread.branch) return yield* new PullRequestBranchHasNoneError();
559 }
560 return { thread, project, target, ref };
561 });
562
563 const identityOf = (target: ResolvedTarget) => ({
564 host: target.host,
565 repository: target.repository,
566 number: target.number,
567 url: target.url,
568 });
569
570 /** The thread's comments past its first page, when the host pages them. */
571 const restOfThread = Effect.fn("PullRequestsToolkit.restOfThread")(function* (
572 ref: PullRequestRef,
573 thread: PullRequestReviewThread,
574 ) {
575 const comments: Array<PullRequestReviewThread["comments"][number]> = [];
576 let cursor = thread.nextCommentsCursor;
577 for (let page = 0; cursor !== undefined && page < THREAD_COMMENT_PAGES; page += 1) {
578 const read = yield* pullRequests
579 .threadComments({ ...ref, threadId: thread.id, cursor })
580 .pipe(Effect.option);
581 if (Option.isNone(read)) break;
582 comments.push(...read.value.comments);
583 cursor = read.value.nextCursor ?? undefined;
584 }
585 return { comments, moreComments: cursor !== undefined };
586 });
587
588 const readSections = Effect.fn("PullRequestsToolkit.readSections")(function* (
589 ref: PullRequestRef,
590 sections: ReadonlyArray<PullRequestReadSection>,
591 includeResolved: boolean,
592 cursor: ReadCursor | undefined,
593 ) {
594 const wants = (section: PullRequestReadSection) => sections.includes(section);
595 const diffCursor = cursor !== undefined && "diff" in cursor ? cursor.diff : undefined;
596 const [detail, activity, diff] = yield* Effect.all(
597 [
598 // Agents pin merges to this headSha, so it must not come from a stale snapshot.
599 pullRequests.detail({ ...ref, allowStale: false }),
600 pullRequests.activity(ref),
601 wants("diff")
602 ? pullRequests
603 .diff({ ...ref, ...(diffCursor === undefined ? {} : { cursor: diffCursor }) })
604 .pipe(Effect.asSome)
605 : Effect.succeedNone,
606 ],
607 { concurrency: "unbounded" },
608 ).pipe(Effect.mapError(forgeFailure));
609 const wantsThreads = wants("threads");
610 const wantsComments = wants("comments");
611 const page =
612 wantsThreads || wantsComments
613 ? Option.some(
614 conversationPage(
615 activity,
616 cursor !== undefined && "threads" in cursor
617 ? cursor
618 : { threads: wantsThreads ? 0 : null, comments: wantsComments ? 0 : null },
619 includeResolved,
620 ),
621 )
622 : Option.none();
623 const threadRests = Option.isSome(page)
624 ? yield* Effect.forEach(page.value.threads, (thread) => restOfThread(ref, thread), {
625 concurrency: 4,
626 })
627 : [];
628 const result: Omit<ReadPullRequestResult, "host" | "repository" | "number" | "url"> = {
629 title: detail.title,
630 state: detail.state,
631 isDraft: detail.isDraft,
632 ...(detail.visibility === undefined ? {} : { visibility: detail.visibility }),
633 author: detail.author?.login ?? null,
634 headBranch: detail.headBranch,
635 baseBranch: detail.baseBranch,
636 headSha: detail.headSha ?? null,
637 mergeability: detail.mergeability,
638 behindBy: detail.behindBy ?? null,
639 autoMergeEnabled: detail.autoMergeEnabled ?? null,
640 checks: checksSummary(detail.checks),
641 unresolvedThreads: activity.reviewThreads.filter((thread) => !thread.isResolved).length,
642 ...(activity.reviewThreadsTruncated === true ? { unresolvedThreadsTruncated: true } : {}),
643 ...(wants("body") ? { body: detail.body } : {}),
644 ...(wants("checks") ? { checkRuns: detail.checks } : {}),
645 ...(Option.isSome(page)
646 ? {
647 conversation: {
648 ...(wantsThreads
649 ? {
650 reviewThreads: page.value.threads.map((thread, index) => ({
651 id: thread.id,
652 path: thread.path,
653 line: thread.line,
654 isResolved: thread.isResolved,
655 isOutdated: thread.isOutdated,
656 comments: [...thread.comments, ...threadRests[index]!.comments].map(
657 (comment) => ({
658 author: comment.author?.login ?? null,
659 body: comment.body,
660 createdAt: comment.createdAt,
661 }),
662 ),
663 moreComments: threadRests[index]!.moreComments,
664 })),
665 }
666 : {}),
667 ...(wantsComments
668 ? {
669 comments: page.value.comments.map((comment) => ({
670 id: comment.id,
671 kind: comment.kind,
672 author: comment.author?.login ?? null,
673 body: comment.body,
674 createdAt: comment.createdAt,
675 path: comment.path,
676 reviewState: comment.reviewState,
677 })),
678 }
679 : {}),
680 truncated:
681 (wantsComments && activity.commentsTruncated) ||
682 (wantsThreads && activity.reviewThreadsTruncated === true),
683 nextCursor: page.value.next === null ? null : readCursors.encode(page.value.next),
684 },
685 }
686 : {}),
687 ...(Option.isSome(diff)
688 ? {
689 diff: {
690 patch: diff.value.patch,
691 truncated: diff.value.truncated,
692 nextCursor:
693 diff.value.nextCursor === null
694 ? null
695 : readCursors.encode({ diff: diff.value.nextCursor }),
696 },
697 }
698 : {}),
699 };
700 return result;
701 });
702
703 const linkToThread = Effect.fn("PullRequestsToolkit.linkToThread")(function* (
704 thread: OrchestrationV2ThreadShell,
705 target: ResolvedTarget,
706 ) {
707 if (
708 threadPullRequestsOf(thread).some(
709 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
710 )
711 ) {
712 return;
713 }
714 yield* engine
715 .dispatch({
716 type: "thread.pull-request.link",
717 commandId: yield* commandId("mcp-pr-create", thread.id),
718 threadId: thread.id,
719 host: target.host,
720 repository: target.repository,
721 number: target.number,
722 url: target.url,
723 source: "created",
724 })
725 .pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)));
726 });
727
728 return {
729 link_pull_request: writesThread((input) =>
730 Effect.gen(function* () {
731 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
732 const next =
733 thread.lineage.relationshipToParent === "subagent"
734 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
735 : {};
736 const project = yield* projectOf(thread, PullRequestLinkFailedError);
737 const target = yield* resolveTarget(input, project);
738 const existing = threadPullRequestsOf(thread).find((link) =>
739 threadPullRequestKeysEqual(link, target),
740 );
741 if (existing && existing.source !== "stack-dismissed")
742 return { ...target, alreadyLinked: true, ...next };
743 const alreadyLinked = yield* engine
744 .dispatch({
745 type: "thread.pull-request.link",
746 commandId: yield* commandId("mcp-pr-link", thread.id),
747 threadId: thread.id,
748 host: target.host,
749 repository: target.repository,
750 number: target.number,
751 url: target.url,
752 source: "agent",
753 })
754 .pipe(
755 Effect.as(false),
756
757 Effect.catchCause(dispatchFailure(PullRequestLinkFailedError)),
758 );
759 return { ...target, alreadyLinked, ...next };
760 }),
761 ),
762 link_pull_requests: writesThread((input) =>
763 Effect.gen(function* () {
764 const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId);
765 const targets: Array<ResolvedTarget> = [];
766 const invalidUrls: Array<string> = [];
767 for (const url of input.urls) {
768 const target = yield* resolveTarget({ url }, undefined).pipe(Effect.option);
769 if (Option.isNone(target)) invalidUrls.push(url);
770 else if (!targets.some((seen) => threadPullRequestKeysEqual(seen, target.value)))
771 targets.push(target.value);
772 }
773 const links = threadPullRequestsOf(thread);
774 const isLinked = (target: ResolvedTarget) =>
775 links.some(
776 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
777 );
778 const fresh = targets.filter((target) => !isLinked(target));
779 const alreadyLinked = targets.filter(isLinked);
780 yield* Effect.forEach(fresh, (target) =>
781 Effect.gen(function* () {
782 yield* engine.dispatch({
783 type: "thread.pull-request.link",
784 commandId: yield* commandId("mcp-pr-link", thread.id),
785 threadId: thread.id,
786 host: target.host,
787 repository: target.repository,
788 number: target.number,
789 url: target.url,
790 source: "agent",
791 });
792 }).pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError))),
793 );
794 const byRepository = (prs: ReadonlyArray<ResolvedTarget>) =>
795 [...Map.groupBy(prs, (pr) => `${pr.host}/${pr.repository}`).values()].map((group) => ({
796 host: group[0]!.host,
797 repository: group[0]!.repository,
798 numbers: group.map((pr) => pr.number),
799 }));
800 return {
801 linked: byRepository(fresh),
802 alreadyLinked: byRepository(alreadyLinked),
803 linkedCount: targets.length,
804 ...(invalidUrls.length > 0 ? { invalidUrls } : {}),
805 ...(thread.lineage.relationshipToParent === "subagent"
806 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
807 : {}),
808 };
809 }),
810 ),
811 unlink_pull_request: writesThread((input) =>
812 Effect.gen(function* () {
813 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
814 const project = yield* projectOf(thread, PullRequestUnlinkFailedError);
815 const target = yield* resolveTarget(input, project);
816 if (
817 !threadPullRequestsOf(thread).some(
818 (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),
819 )
820 )
821 return {
822 host: target.host,
823 repository: target.repository,
824 number: target.number,
825 wasLinked: false,
826 };
827 const wasLinked = yield* engine
828 .dispatch({
829 type: "thread.pull-request.unlink",
830 commandId: yield* commandId("mcp-pr-unlink", thread.id),
831 threadId: thread.id,
832 host: target.host,
833 repository: target.repository,
834 number: target.number,
835 })
836 .pipe(
837 Effect.as(true),
838
839 Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError)),
840 );
841 return {
842 host: target.host,
843 repository: target.repository,
844 number: target.number,
845 wasLinked,
846 };
847 }),
848 ),
849 unlink_pull_requests: writesThread((input) =>
850 Effect.gen(function* () {
851 const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId);
852 const visible = visibleThreadPullRequests(threadPullRequestsOf(thread));
853 const matching = visible.flatMap((link) => {
854 const state = link.snapshot?.state;
855 return state !== undefined && input.states.includes(state)
856 ? [{ ...normalizeThreadPullRequestKey(link), state }]
857 : [];
858 });
859 yield* Effect.forEach(matching, ({ host, repository, number }) =>
860 Effect.gen(function* () {
861 yield* engine.dispatch({
862 type: "thread.pull-request.unlink",
863 commandId: yield* commandId("mcp-pr-unlink", thread.id),
864 threadId: thread.id,
865 host,
866 repository,
867 number,
868 });
869 }).pipe(Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError))),
870 );
871 // Numbers grouped by repository and state keep a large batch's result small.
872 const groups = Map.groupBy(matching, (pr) => `${pr.host}/${pr.repository}/${pr.state}`);
873 return {
874 unlinked: [...groups.values()].map((prs) => ({
875 host: prs[0]!.host,
876 repository: prs[0]!.repository,
877 state: prs[0]!.state,
878 numbers: prs.map((pr) => pr.number),
879 })),
880 unlinkedCount: matching.length,
881 remaining: visible.length - matching.length,
882 };
883 }),
884 ),
885 list_thread_pull_requests: McpToolAccess.reads((input) =>
886 requireThread(PullRequestListFailedError, input.threadId).pipe(
887 Effect.map((thread) => listThreadPullRequests(thread, input.cursor, input.states)),
888 ),
889 ),
890 watch_pull_request: writesThread((input) => setWatching(input, true)),
891 unwatch_pull_request: writesThread((input) => setWatching(input, false)),
892 write_pull_request_guides: McpToolAccess.writesWithCapability((input) =>
893 Effect.gen(function* () {
894 const located = yield* locateAll(input.pullRequests);
895 const guides = yield* Effect.forEach(
896 located,
897 (entry) =>
898 Effect.gen(function* () {
899 if (entry.target === null) {
900 return {
901 host: entry.input.host ?? "",
902 repository: entry.input.repository ?? "",
903 number: entry.input.number ?? 0,
904 url: entry.input.url ?? "",
905 outcome: "failed" as const,
906 detail: entry.failure,
907 };
908 }
909 const identity = {
910 host: entry.target.host,
911 repository: entry.target.repository,
912 number: entry.target.number,
913 url: entry.target.url,
914 };
915 if (entry.project === undefined) {
916 return {
917 ...identity,
918 outcome: "failed" as const,
919 detail: new PullRequestProjectNotFoundError({
920 repository: entry.target.repository,
921 }).message,
922 };
923 }
924 return yield* reviewGuides.generate(guideReference(entry.project, entry.target)).pipe(
925 Effect.map((result) => ({
926 ...identity,
927 outcome: result.started ? ("started" as const) : ("running" as const),
928 detail: null,
929 })),
930 Effect.catch((error) =>
931 Effect.succeed({
932 ...identity,
933 outcome: "failed" as const,
934 detail: guideFailureDetail(error),
935 }),
936 ),
937 );
938 }),
939 { concurrency: 4 },
940 );
941 return { guides };
942 }),
943 ),
944 read_pull_request_guide: McpToolAccess.reads((input) =>
945 Effect.gen(function* () {
946 const [entry] = yield* locateAll([input]);
947 if (entry !== undefined && entry.target === null) {
948 return yield* new PullRequestGuideFailedError({ detail: entry.failure ?? "" });
949 }
950 // Hosts readable without a checkout (GitHub, Bitbucket, Forgejo) are read through the
951 // caller's project; PullRequestService decides whether the host allows that.
952 const project = entry?.project ?? entry?.callerProject;
953 if (entry === undefined || entry.target === null || project === undefined) {
954 return yield* new PullRequestProjectNotFoundError({
955 repository: entry?.target.repository ?? input.repository ?? "",
956 });
957 }
958 const target = entry.target;
959 const result = yield* reviewGuides.get(guideReference(project, target)).pipe(
960 Effect.mapError((error) =>
961 entry.project === undefined &&
962 error._tag === "PullRequestUnavailableError" &&
963 (error.reason === "provider-unsupported" ||
964 error.reason === "repository-without-project")
965 ? new PullRequestProjectNotFoundError({ repository: target.repository })
966 : new PullRequestGuideFailedError({
967 detail: guideFailureDetail(error),
968 cause: error,
969 }),
970 ),
971 );
972 return {
973 host: entry.target.host,
974 repository: entry.target.repository,
975 number: entry.target.number,
976 url: entry.target.url,
977 guide: result.guide,
978 run: result.run,
979 currentHeadSha: result.currentHeadSha,
980 stale:
981 result.guide !== null &&
982 result.currentHeadSha !== null &&
983 result.guide.headSha !== result.currentHeadSha,
984 };
985 }),
986 ),
987 pull_request_read: McpToolAccess.reads((input) =>
988 Effect.gen(function* () {
989 const cursor =
990 input.cursor === undefined ? undefined : yield* readCursors.decode(input.cursor);
991 const { target, ref } = yield* locate(input);
992 // A cursor continues the one section it came from, with that read's options.
993 const sections: ReadonlyArray<PullRequestReadSection> =
994 cursor === undefined
995 ? (input.include ?? [])
996 : "diff" in cursor
997 ? ["diff"]
998 : [
999 ...(cursor.threads === null ? [] : (["threads"] as const)),
1000 ...(cursor.comments === null ? [] : (["comments"] as const)),
1001 ];
1002 const includeResolved =
1003 cursor !== undefined && "includeResolved" in cursor
1004 ? cursor.includeResolved
1005 : input.includeResolved === true;
1006 return {
1007 ...identityOf(target),
1008 ...(yield* readSections(ref, sections, includeResolved, cursor)),
1009 };
1010 }),
1011 ),
1012 pull_request_list: McpToolAccess.reads((input) =>
1013 Effect.gen(function* () {
1014 const thread = yield* requireThread(PullRequestForgeError, undefined);
1015 const listed = yield* pullRequests
1016 .list({
1017 projectId: thread.projectId,
1018 state: input.state ?? "open",
1019 involvement: input.involvement ?? "all",
1020 limit: input.limit ?? 30,
1021 ...(input.query === undefined ? {} : { query: input.query }),
1022 ...(input.cursor === undefined
1023 ? {}
1024 : { cursors: yield* listCursors.decode(input.cursor) }),
1025 })
1026 .pipe(Effect.mapError(forgeFailure));
1027 const failure = listed.errors[0];
1028 if (listed.entries.length === 0 && failure !== undefined) {
1029 return yield* new PullRequestForgeError({ detail: failure.message });
1030 }
1031 return {
1032 pullRequests: listed.entries.map((entry) => ({
1033 number: entry.number,
1034 title: entry.title,
1035 url: entry.url,
1036 author: entry.author?.login ?? null,
1037 headBranch: entry.headBranch,
1038 baseBranch: entry.baseBranch,
1039 state: entry.state,
1040 isDraft: entry.isDraft,
1041 reviewDecision: entry.reviewDecision ?? null,
1042 checksState: entry.checksState ?? null,
1043 updatedAt: entry.updatedAt,
1044 })),
1045 truncated: listed.truncated,
1046 nextCursor:
1047 Object.keys(listed.nextCursors).length === 0
1048 ? null
1049 : listCursors.encode(listed.nextCursors),
1050 };
1051 }),
1052 ),
1053 pull_request_create: McpToolAccess.writesWithCapability((input) =>
1054 Effect.gen(function* () {
1055 const thread = yield* requireThread(PullRequestForgeError, undefined);
1056 const project = yield* projectOf(thread, PullRequestForgeError);
1057 if (project === undefined) {
1058 return yield* new PullRequestProjectNotFoundError({ repository: "" });
1059 }
1060 const created = yield* git
1061 .createPullRequest({
1062 cwd: thread.worktreePath ?? project.workspaceRoot,
1063 projectId: project.id,
1064 title: input.title,
1065 body: input.body,
1066 baseBranch: input.base,
1067 draft: input.draft,
1068 private: input.private,
1069 })
1070 .pipe(Effect.mapError(forgeFailure));
1071 if (created.url === undefined) {
1072 return yield* new PullRequestForgeError({
1073 detail:
1074 "The host accepted the PR but does not list it yet. Find it with pull_request_list.",
1075 });
1076 }
1077 const target = yield* resolveTarget({ url: created.url }, project);
1078 yield* linkToThread(thread, target);
1079 return {
1080 ...identityOf(target),
1081 created: created.status === "created",
1082 ...(thread.lineage.relationshipToParent === "subagent"
1083 ? { next: CHILD_PULL_REQUEST_REPORT_NEXT }
1084 : {}),
1085 };
1086 }),
1087 ),
1088 pull_request_update: McpToolAccess.writesWithCapability((input) =>
1089 Effect.gen(function* () {
1090 if (
1091 input.title === undefined &&
1092 input.body === undefined &&
1093 input.ready === undefined &&
1094 input.state === undefined &&
1095 input.addLabels === undefined &&
1096 input.removeLabels === undefined &&
1097 input.requestReviewers === undefined
1098 ) {
1099 return yield* new PullRequestNothingToDoError({
1100 detail: "Pass title, body, ready, state, addLabels, removeLabels, or requestReviewers.",
1101 });
1102 }
1103 const { target, ref } = yield* locate(input);
1104 if (input.title !== undefined || input.body !== undefined) {
1105 yield* pullRequests
1106 .update({
1107 ...ref,
1108 ...(input.title === undefined ? {} : { title: input.title }),
1109 ...(input.body === undefined ? {} : { body: input.body }),
1110 })
1111 .pipe(Effect.mapError(forgeFailure));
1112 }
1113 for (const [labels, applied] of [
1114 [input.addLabels, true],
1115 [input.removeLabels, false],
1116 ] as const) {
1117 if (labels !== undefined) {
1118 yield* pullRequests
1119 .setLabels({ ...ref, labels, applied })
1120 .pipe(Effect.mapError(forgeFailure));
1121 }
1122 }
1123 if (input.requestReviewers !== undefined) {
1124 const reviewers = yield* Effect.forEach(input.requestReviewers, (name) =>
1125 reviewerNamed(ref, name),
1126 );
1127 yield* pullRequests
1128 .requestReviewers({ ...ref, reviewers, requested: true })
1129 .pipe(Effect.mapError(forgeFailure));
1130 }
1131 if (input.ready !== undefined) {
1132 yield* pullRequests
1133 .runAction({ ...ref, action: input.ready ? "ready" : "draft" })
1134 .pipe(Effect.mapError(forgeFailure));
1135 }
1136 if (input.state !== undefined) {
1137 yield* pullRequests
1138 .runAction({ ...ref, action: input.state === "closed" ? "close" : "reopen" })
1139 .pipe(Effect.mapError(forgeFailure));
1140 }
1141 return identityOf(target);
1142 }),
1143 ),
1144 pull_request_respond: McpToolAccess.writesWithCapability((input) =>
1145 Effect.gen(function* () {
1146 if (
1147 input.body === undefined &&
1148 (input.reviewThreadId === undefined || input.resolved === undefined)
1149 ) {
1150 return yield* new PullRequestNothingToDoError({
1151 detail: "Pass body, or reviewThreadId with resolved.",
1152 });
1153 }
1154 if (input.reviewThreadId === undefined && input.resolved !== undefined) {
1155 return yield* new PullRequestNothingToDoError({
1156 detail: "resolved needs reviewThreadId.",
1157 });
1158 }
1159 const { target, ref } = yield* locate(input);
1160 const reviewThreadId = input.reviewThreadId;
1161 if (input.body !== undefined) {
1162 yield* (
1163 reviewThreadId === undefined
1164 ? pullRequests.comment({ ...ref, body: input.body })
1165 : pullRequests.replyToThread({ ...ref, threadId: reviewThreadId, body: input.body })
1166 ).pipe(Effect.mapError(forgeFailure));
1167 }
1168 if (reviewThreadId !== undefined && input.resolved !== undefined) {
1169 yield* pullRequests
1170 .setThreadResolution({ ...ref, threadId: reviewThreadId, resolved: input.resolved })
1171 .pipe(
1172 Effect.mapError((error) =>
1173 input.body === undefined
1174 ? forgeFailure(error)
1175 : new PullRequestForgeError({
1176 // A retry with the body would post the reply twice.
1177 detail: `The reply was posted, but setting resolved failed: ${error.message} Retry without body.`,
1178 cause: error,
1179 }),
1180 ),
1181 );
1182 }
1183 return {
1184 ...identityOf(target),
1185 replied: input.body !== undefined,
1186 resolved: input.resolved ?? null,
1187 };
1188 }),
1189 ),
1190 pull_request_review: McpToolAccess.writesWithCapability((input) =>
1191 Effect.gen(function* () {
1192 if (input.verdict === "approve" && input.expectedHeadSha === undefined) {
1193 return yield* new PullRequestForgeError({
1194 detail:
1195 "Approving needs expectedHeadSha: the headSha pull_request_read reported for the commits you reviewed.",
1196 });
1197 }
1198 const { target, ref } = yield* locate(input);
1199 const comments = yield* reviewComments(ref, input.comments ?? []);
1200 yield* pullRequests
1201 .submitReview({
1202 ...ref,
1203 verdict: input.verdict,
1204 body: input.body ?? "",
1205 comments,
1206 ...(input.expectedHeadSha === undefined
1207 ? {}
1208 : { expectedHeadSha: input.expectedHeadSha }),
1209 })
1210 .pipe(Effect.mapError(forgeFailure));
1211 return identityOf(target);
1212 }),
1213 ),
1214 pull_request_merge: McpToolAccess.writesWithCapability((input) =>
1215 Effect.gen(function* () {
1216 const { target, ref } = yield* locate(input);
1217 const stack = input.stack === true ? yield* stackMergeScope(ref, input) : {};
1218 yield* pullRequests
1219 .runAction({
1220 ...ref,
1221 action: input.auto === true ? "enable-auto-merge" : "merge",
1222 expectedHeadSha: input.expectedHeadSha,
1223 ...(input.method === undefined ? {} : { mergeMethod: input.method }),
1224 ...stack,
1225 })
1226 .pipe(Effect.mapError(forgeFailure));
1227 const after = yield* pullRequests
1228 .summary({ ...ref, allowStale: false })
1229 .pipe(Effect.mapError(forgeFailure));
1230 return { ...identityOf(target), state: after.state };
1231 }),
1232 ),
1233 ci_logs: McpToolAccess.reads((input) =>
1234 Effect.gen(function* () {
1235 const { target, ref } = yield* locate(input);
1236 const checks = yield* pullRequests
1237 .checkLogs({
1238 ...ref,
1239 tailLines: input.tailLines ?? 200,
1240 ...(input.check === undefined ? {} : { check: input.check }),
1241 })
1242 .pipe(Effect.mapError(forgeFailure));
1243 return { ...identityOf(target), checks };
1244 }),
1245 ),
1246 ci_rerun: McpToolAccess.writesWithCapability((input) =>
1247 Effect.gen(function* () {
1248 const { thread, target, ref } = yield* locate(input);
1249 const checks = yield* pullRequests
1250 .rerunChecks({ ...ref, ...(input.check === undefined ? {} : { check: input.check }) })
1251 .pipe(Effect.mapError(forgeFailure));
1252 // Like a push, a rerun makes a watch's finished checks stale, so the thread keeps working
1253 // until a read sees them run. The rerun already happened, so a failed reopen only logs.
1254 if (
1255 checks.some((check) => check.rerun) &&
1256 threadPullRequestsOf(thread).some((link) => link.watch?.checksPending !== undefined)
1257 ) {
1258 yield* engine
1259 .dispatch({
1260 type: "thread.pull-request-watch.checks-reopen",
1261 commandId: yield* commandId("mcp-ci-rerun-checks", thread.id),
1262 threadId: thread.id,
1263 })
1264 .pipe(
1265 Effect.catchCause((cause) =>
1266 Effect.logWarning("reopening a watch's checks after a rerun failed", cause),
1267 ),
1268 );
1269 }
1270 return { ...identityOf(target), checks };
1271 }),
1272 ),
1273 } satisfies McpToolAccess.Handlers<typeof PullRequestsToolkit.tools>;
1274});
1275
1276export const layer = McpToolAccess.toLayer(PullRequestsToolkit, make);