Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

handlers.ts

1,473 lines59.5 KB

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