@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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