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