import { z } from "zod";
import { repoDb, stmt } from "../../scoped-db";
import { registerLocators, type LocatorKind } from "../../scoped-db/locators";
import { scopedId } from "../../scoped-db/ids";
import { badRequest, conflict, forbidden, HttpError, notFoundError } from "../../errors";
import { createPull, getPull, listPulls, mergePull, updatePullBranch } from "../../api/pulls";
import { headBranchConflicts, requireHeadPush, updateHeadBranch } from "../../pull-merge";
import { pullDiff } from "../../pull-files";
import { loadPull, MergeError } from "../../pulls";
import type { PullRow } from "../../pulls";
import { pullUrl } from "../../pull-access";
import { hasPermission, loadRepoById } from "../../repos";
import { scopedRepoPermission } from "../../token-scope";
import { kickMergeAutomation } from "../../merge-automation";
import { emitNotification, emitWebhook } from "../../events/emit";
import { limitHeavy, limitWrite } from "../../limits";
import { markdownBody, title } from "~/lib/validation";
import type { McpCaller } from "../protocol";
import {
apiCtx,
apiJson,
attributionFooter,
attributionNote,
canConfirmWithHuman,
confirmWithHuman,
defineTool,
repoArgs,
scopedRepo,
truncateText,
} from "./base";
import { agentReview, requireHumanForMerge } from "./review-outcome";
import { issuesChanged } from "../../repo-state";
const number = z.number().int().positive();
const MAX_PATCH_CHARS = 48 * 1024;
const MAX_RESOLVED_CHARS = 1024 * 1024;
const HTTP_CONFLICT = 409;
async function pullFor(
caller: McpCaller,