"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.publishWorkingInPrMergeFinalization = exports.resolveWorkflowStateForPublication = exports.publishControlPlaneNeedsHumanUpdate = exports.buildNeedsHumanPostMergeLinkedIssueCloseFailureNextMessage = exports.buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage = exports.buildNeedsHumanMergeRaceNextMessage = exports.buildNeedsHumanMergeRaceMessage = exports.buildNeedsHumanMergeFailureMessage = exports.buildNeedsHumanFailureNextMessage = exports.buildNeedsHumanMergedPullRequestCloseFailureNextMessage = exports.buildNeedsHumanMergedPullRequestCloseFailureMessage = exports.buildDependencyIntegratedSummary = exports.buildDependencyIntegratedNextMessage = exports.buildAutoMergeUnavailableNextMessage = exports.buildAutoMergeUnavailableMessage = exports.buildAutoMergePendingNextMessage = exports.buildAutoMergePendingMessage = exports.buildAutoMergeConflictReplanNextMessage = exports.buildAutoMergeConflictReplanMessage = exports.resolveAutoMergeWorkflowState = void 0;
exports.mergeReadyPullRequest = mergeReadyPullRequest;
exports.retryMergedPullRequestFinalization = retryMergedPullRequestFinalization;
exports.canAutoMergePullRequestNow = canAutoMergePullRequestNow;
exports.preparePullRequestDependenciesBeforeMerge = preparePullRequestDependenciesBeforeMerge;
exports.publishAutoMergePendingUpdate = publishAutoMergePendingUpdate;
exports.publishAutoMergeState = publishAutoMergeState;
exports.publishAutoMergeNeedsHumanUpdate = publishAutoMergeNeedsHumanUpdate;
const errors_1 = require("../../platform/repository-host/errors");
const types_1 = require("../../platform/ticket-tracker/types");
const types_2 = require("../../platform/workflow-state/types");
const constants_1 = require("../../worker/constants");
const auto_merge_state_1 = require("../../workflows/auto-merge-state");
const visible_update_builders_1 = require("../../workflows/visible-update-builders");
const publisher_events_1 = require("../../workflows/publisher-events");
const constants_2 = require("../constants");
const log_text_1 = require("../log-text");
const dependencies_1 = require("./dependencies");
const dependency_publication_1 = require("./dependency-publication");
const effect_log_1 = require("./effect-log");
const event_hook_publication_1 = require("./event-hook-publication");
const effects_1 = require("./effects");
const needs_human_merge_post_merge_1 = require("./needs-human-merge-post-merge");
const needs_human_merge_state_1 = require("./needs-human-merge-state");
const needs_human_merge_support_1 = require("./needs-human-merge-support");
const publisher_factory_1 = require("./publisher-factory");
var needs_human_merge_state_2 = require("./needs-human-merge-state");
Object.defineProperty(exports, "resolveAutoMergeWorkflowState", { enumerable: true, get: function () { return needs_human_merge_state_2.resolveAutoMergeWorkflowState; } });
const pr_publication_1 = require("./pr-publication");
const pull_request_completion_1 = require("./pull-request-completion");
const results_1 = require("./results");
const shared_1 = require("./shared");
const workflow_template_root_1 = require("./workflow-template-root");
var needs_human_merge_support_2 = require("./needs-human-merge-support");
Object.defineProperty(exports, "buildAutoMergeConflictReplanMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildAutoMergeConflictReplanMessage; } });
Object.defineProperty(exports, "buildAutoMergeConflictReplanNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildAutoMergeConflictReplanNextMessage; } });
Object.defineProperty(exports, "buildAutoMergePendingMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildAutoMergePendingMessage; } });
Object.defineProperty(exports, "buildAutoMergePendingNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildAutoMergePendingNextMessage; } });
Object.defineProperty(exports, "buildAutoMergeUnavailableMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildAutoMergeUnavailableMessage; } });
Object.defineProperty(exports, "buildAutoMergeUnavailableNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildAutoMergeUnavailableNextMessage; } });
Object.defineProperty(exports, "buildDependencyIntegratedNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildDependencyIntegratedNextMessage; } });
Object.defineProperty(exports, "buildDependencyIntegratedSummary", { enumerable: true, get: function () { return needs_human_merge_support_2.buildDependencyIntegratedSummary; } });
Object.defineProperty(exports, "buildNeedsHumanMergedPullRequestCloseFailureMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanMergedPullRequestCloseFailureMessage; } });
Object.defineProperty(exports, "buildNeedsHumanMergedPullRequestCloseFailureNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanMergedPullRequestCloseFailureNextMessage; } });
Object.defineProperty(exports, "buildNeedsHumanFailureNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanFailureNextMessage; } });
Object.defineProperty(exports, "buildNeedsHumanMergeFailureMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanMergeFailureMessage; } });
Object.defineProperty(exports, "buildNeedsHumanMergeRaceMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanMergeRaceMessage; } });
Object.defineProperty(exports, "buildNeedsHumanMergeRaceNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanMergeRaceNextMessage; } });
Object.defineProperty(exports, "buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage; } });
Object.defineProperty(exports, "buildNeedsHumanPostMergeLinkedIssueCloseFailureNextMessage", { enumerable: true, get: function () { return needs_human_merge_support_2.buildNeedsHumanPostMergeLinkedIssueCloseFailureNextMessage; } });
Object.defineProperty(exports, "publishControlPlaneNeedsHumanUpdate", { enumerable: true, get: function () { return needs_human_merge_support_2.publishControlPlaneNeedsHumanUpdate; } });
Object.defineProperty(exports, "resolveWorkflowStateForPublication", { enumerable: true, get: function () { return needs_human_merge_support_2.resolveWorkflowStateForPublication; } });
var merge_finalization_closing_1 = require("./merge-finalization-closing");
Object.defineProperty(exports, "publishWorkingInPrMergeFinalization", { enumerable: true, get: function () { return merge_finalization_closing_1.publishWorkingInPrMergeFinalization; } });
async function continueMergedPullRequest(input) {
    const issueComments = await (0, shared_1.loadSortedIssueComments)(input.context.ticketTracker, input.issue.id, { timeline: "issue-only" });
    const linkedIssueId = (0, shared_1.resolveLinkedIssueIdFromPullRequest)({ body: input.issue.body }, issueComments);
    const shouldCloseLinkedIssue = linkedIssueId !== null && linkedIssueId !== input.issue.id;
    if (shouldCloseLinkedIssue && linkedIssueId !== null) {
        const requeuedCount = await (0, dependencies_1.reconcileCompletedDependencyRequeuesAfterMerge)({
            context: input.context,
            sourceIssueId: linkedIssueId,
            locale: input.responseLanguage,
        });
        if (requeuedCount > 0) {
            await (0, effect_log_1.appendEffectResultLog)(input.logger, [
                (0, log_text_1.issueLogField)("effect", input.dependencyRequeueEffect),
                (0, log_text_1.issueLogField)("note", `source_issue:${linkedIssueId}; requeued:${requeuedCount}`),
            ]);
        }
    }
    const pullRequestFinalizeFailure = await (0, needs_human_merge_post_merge_1.finalizeMergedPullRequestOrBuildSummary)({
        context: input.context,
        issue: input.issue,
        issueComments,
        logger: input.logger,
        pullRequest: input.pullRequest,
        responseLanguage: input.responseLanguage,
        ...(input.workflowState !== undefined
            ? { workflowState: input.workflowState }
            : {}),
        previousNeedsHumanReason: input.previousNeedsHumanReason ?? null,
    });
    if (pullRequestFinalizeFailure !== null) {
        return (0, needs_human_merge_support_1.appendFinalSummary)(input.logger, pullRequestFinalizeFailure);
    }
    if (shouldCloseLinkedIssue && linkedIssueId !== null) {
        const linkedIssueFailure = await (0, needs_human_merge_post_merge_1.closeLinkedIssueAfterMergeOrBuildSummary)({
            context: input.context,
            issue: input.issue,
            logger: input.logger,
            branchName: input.branchName,
            pullRequest: input.pullRequest,
            linkedIssueId,
            responseLanguage: input.responseLanguage,
        });
        if (linkedIssueFailure !== null) {
            return (0, needs_human_merge_support_1.appendFinalSummary)(input.logger, linkedIssueFailure);
        }
    }
    await input.appendSuccessLog({ linkedIssueId, shouldCloseLinkedIssue });
    return (0, needs_human_merge_support_1.appendFinalSummary)(input.logger, (0, results_1.buildRunCliSummary)({
        issue: input.issue,
        outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedAi,
        responseLanguage: input.responseLanguage,
        summary: (0, needs_human_merge_support_1.buildNeedsHumanMergeSuccessMessage)(input.responseLanguage),
        commentUrl: null,
        prUrl: input.pullRequest.url,
        nextStep: (0, needs_human_merge_support_1.buildNeedsHumanMergeNextMessage)(input.responseLanguage),
    }));
}
async function mergeReadyPullRequest(input) {
    const { context, issue, logger, branchName, automationState, responseLanguage, } = input;
    const mergeFailure = await mergePullRequestOrBuildSummary({
        context,
        issue,
        logger,
        automationState,
        responseLanguage,
        ...(input.onPushRejected !== undefined
            ? { onPushRejected: input.onPushRejected }
            : {}),
        ...(input.onRetryableMergeFailure !== undefined
            ? { onRetryableMergeFailure: input.onRetryableMergeFailure }
            : {}),
        ...(input.onMergeFailure !== undefined
            ? { onMergeFailure: input.onMergeFailure }
            : {}),
    });
    if (mergeFailure !== null) {
        return (0, needs_human_merge_support_1.appendFinalSummary)(logger, mergeFailure);
    }
    return continueMergedPullRequest({
        context,
        issue,
        logger,
        branchName,
        pullRequest: automationState,
        responseLanguage,
        ...(input.workflowState !== undefined
            ? { workflowState: input.workflowState }
            : {}),
        previousNeedsHumanReason: input.previousNeedsHumanReason ?? null,
        dependencyRequeueEffect: "dependency_completion_requeue_after_merge",
        appendSuccessLog: ({ linkedIssueId, shouldCloseLinkedIssue }) => (0, needs_human_merge_support_1.appendMergeSuccessLog)({
            logger,
            pullRequest: automationState,
            branchName,
            linkedIssueId,
            shouldCloseLinkedIssue,
        }),
    });
}
async function retryMergedPullRequestFinalization(context, issue, logger, branchName, pullRequest, responseLanguage, workflowState, previousNeedsHumanReason, completionReason = pull_request_completion_1.PULL_REQUEST_COMPLETION_REASONS.merged) {
    return continueMergedPullRequest({
        context,
        issue,
        logger,
        branchName,
        pullRequest,
        responseLanguage,
        ...(workflowState !== undefined ? { workflowState } : {}),
        previousNeedsHumanReason: previousNeedsHumanReason ?? null,
        dependencyRequeueEffect: "dependency_completion_requeue_after_merge_retry",
        appendSuccessLog: async () => {
            await (0, effect_log_1.appendEffectResultLog)(logger, [
                (0, log_text_1.issueLogField)("effect", "finalize_pull_request_after_merge_retry"),
                (0, log_text_1.issueLogField)("pr", pullRequest.url),
                (0, log_text_1.issueLogField)("branch", branchName),
                (0, log_text_1.issueLogField)("note", completionReason),
            ]);
        },
    });
}
function canAutoMergePullRequestNow(automationState) {
    return (automationState.reviewDecision !== "CHANGES_REQUESTED" &&
        !automationState.isDraft &&
        automationState.mergeability === "MERGEABLE" &&
        (automationState.mergeStateStatus === undefined ||
            automationState.mergeStateStatus === null ||
            automationState.mergeStateStatus === "CLEAN" ||
            automationState.mergeStateStatus === "HAS_HOOKS"));
}
async function preparePullRequestDependenciesBeforeMerge(input) {
    if (input.context.config.dependencies.strategy !== "auto") {
        return { action: "continue" };
    }
    const dependencyState = await (0, dependencies_1.resolvePullRequestManagedDependencyState)({
        ticketTracker: input.context.ticketTracker,
        issue: input.issue,
        locale: input.responseLanguage,
    });
    const { openDependencies, closedDependencies } = dependencyState;
    if (closedDependencies.length > 0) {
        if (dependencyState.linkedIssueId === null ||
            dependencyState.sourceWorkflowState === null) {
            return { action: "continue" };
        }
        return handleClosedDependenciesBeforeMerge({
            ...input,
            linkedIssue: { id: dependencyState.linkedIssueId },
            sourceWorkflowState: dependencyState.sourceWorkflowState,
            closedDependencies,
        });
    }
    if (openDependencies.length === 0) {
        return { action: "continue" };
    }
    const dependencyIssueIds = sortDependencyIssueIds(openDependencies.map((dependency) => dependency.issueId));
    const summary = (0, needs_human_merge_support_1.buildAutoMergePendingMessage)(input.responseLanguage, dependencyIssueIds);
    const nextStep = (0, needs_human_merge_support_1.buildAutoMergePendingNextMessage)(input.responseLanguage, dependencyIssueIds);
    const autoMergePendingSummary = await publishAutoMergePendingUpdate({
        context: input.context,
        issue: input.issue,
        logger: input.logger,
        responseLanguage: input.responseLanguage,
        workflowState: (0, needs_human_merge_state_1.resolveAutoMergeWorkflowState)({
            workflowState: input.workflowState ?? null,
            autoMergeState: auto_merge_state_1.WORKFLOW_AUTO_MERGE_STATES.pending,
        }),
        summary,
        nextStep,
        prUrl: input.automationState.url,
    });
    await (0, effect_log_1.appendEffectResultLog)(input.logger, [
        (0, log_text_1.issueLogField)("effect", "dependency_open_wait_before_merge"),
        (0, log_text_1.issueLogField)("pr", input.automationState.url),
        (0, log_text_1.issueLogField)("note", `dependencies:${dependencyIssueIds.join(",")}`),
    ]);
    return {
        action: "stop",
        summary: autoMergePendingSummary,
    };
}
async function handleClosedDependenciesBeforeMerge(input) {
    const requeue = await (0, dependency_publication_1.publishDependencyCompletionRequeue)({
        context: input.context,
        targetIssue: input.issue,
        locale: input.responseLanguage,
        completedDependencyIssueIds: input.closedDependencies.map((dependency) => dependency.issueId),
        ...(input.workflowState !== undefined
            ? { currentWorkflowState: input.workflowState }
            : {}),
    });
    if (!requeue.accepted) {
        return handleDeferredDependencyRequeueBeforeMerge(input);
    }
    if (requeue.publication !== null &&
        requeue.publication.targetWorkflowProjection !== null) {
        input.issue.workflowState = {
            ...requeue.publication.targetWorkflowProjection,
        };
    }
    const closedDependencyIssueIds = sortDependencyIssueIds(input.closedDependencies.map((dependency) => dependency.issueId));
    await (0, dependency_publication_1.persistDependencySyncState)({
        context: input.context,
        issueId: input.linkedIssue.id,
        workflowState: (0, dependencies_1.markManagedDependenciesRequeuedInWorkflowState)({
            workflowState: input.sourceWorkflowState,
            dependencyIssueIds: closedDependencyIssueIds,
        }),
        locale: input.responseLanguage,
    });
    const summary = (0, needs_human_merge_support_1.buildDependencyIntegratedSummary)(input.responseLanguage);
    const nextStep = (0, needs_human_merge_support_1.buildDependencyIntegratedNextMessage)(input.responseLanguage);
    await (0, effect_log_1.appendEffectResultLog)(input.logger, [
        (0, log_text_1.issueLogField)("effect", "dependency_completion_requeue_before_merge"),
        (0, log_text_1.issueLogField)("pr", input.automationState.url),
        (0, log_text_1.issueLogField)("note", `dependencies:${closedDependencyIssueIds.join(",")}`),
    ]);
    return {
        action: "stop",
        summary: (0, results_1.buildRunCliSummary)({
            issue: input.issue,
            outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedAi,
            responseLanguage: input.responseLanguage,
            summary,
            commentUrl: (0, publisher_factory_1.resolveRunWorkflowPublicationCommentUrl)(requeue.publication),
            prUrl: input.automationState.url,
            nextStep,
        }),
    };
}
function sortDependencyIssueIds(dependencyIssueIds) {
    return [...new Set(dependencyIssueIds)].sort((left, right) => {
        const leftNumber = Number(left);
        const rightNumber = Number(right);
        if (Number.isFinite(leftNumber) && Number.isFinite(rightNumber)) {
            return leftNumber - rightNumber;
        }
        return left.localeCompare(right);
    });
}
async function handleDeferredDependencyRequeueBeforeMerge(input) {
    const summary = (0, needs_human_merge_support_1.buildDependencyRequeueDeferredSummary)(input.responseLanguage);
    const nextStep = (0, needs_human_merge_support_1.buildDependencyRequeueDeferredNextMessage)(input.responseLanguage);
    await (0, effect_log_1.appendEffectResultLog)(input.logger, [
        (0, log_text_1.issueLogField)("effect", "dependency_completion_requeue_before_merge"),
        (0, log_text_1.issueLogField)("pr", input.automationState.url),
        (0, log_text_1.issueLogField)("note", "requeue_not_accepted_retry_next_cycle"),
    ]);
    return {
        action: "stop",
        summary: (0, results_1.buildRunCliSummary)({
            issue: input.issue,
            outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedAi,
            responseLanguage: input.responseLanguage,
            summary,
            commentUrl: null,
            prUrl: input.automationState.url,
            nextStep,
        }),
    };
}
async function publishAutoMergePendingUpdate(input) {
    const publication = await publishAutoMergeState({
        context: input.context,
        issue: input.issue,
        responseLanguage: input.responseLanguage,
        workflowState: input.workflowState,
        visibleUpdate: (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
            event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.autoMergePending,
            summary: input.summary,
            next: input.nextStep,
            workerOutcome: input.workerOutcome ?? constants_1.WORKER_OUTCOMES.proceed,
        }),
    });
    if (publication.targetWorkflowProjection !== null) {
        input.issue.workflowState = { ...publication.targetWorkflowProjection };
    }
    return (0, results_1.buildRunCliSummary)({
        issue: input.issue,
        outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedAi,
        responseLanguage: input.responseLanguage,
        summary: input.summary,
        commentUrl: (0, publisher_factory_1.resolveRunWorkflowPublicationCommentUrl)(publication),
        prUrl: input.prUrl ?? input.issue.url,
        nextStep: input.nextStep,
    });
}
async function publishAutoMergeState(input) {
    const trackerTitle = (0, effects_1.resolveRenderedTitleIfChanged)({
        issue: input.issue,
        workflowState: input.workflowState,
        locale: input.responseLanguage,
        surface: "pull_request",
        enabled: input.context.config.ticketTracker.showStepProgressInTitles === true,
    });
    const plan = (0, pr_publication_1.buildPullRequestAutoMergePublicationPlan)({
        workflowLabels: input.context.config.ticketTracker.workflowLabels,
        responseLanguage: input.responseLanguage,
        pullRequestIssue: input.issue,
        sourceIssueId: (await (0, shared_1.resolveLinkedIssueIdFromPullRequestTimeline)(input.context.ticketTracker, input.issue)) ?? input.issue.id,
        workflowState: input.workflowState,
        previousNeedsHumanReason: null,
        ...(input.visibleUpdate !== undefined
            ? { visibleUpdate: input.visibleUpdate }
            : {}),
        ...(trackerTitle !== null ? { trackerTitle } : {}),
    });
    if (plan.kind !== "pr_auto_merge") {
        throw new Error("Expected a PR auto-merge publication plan.");
    }
    const request = {
        ...plan.pullRequestThreadRequest,
        ...(input.appendCanonicalWorkflowStateComment !== undefined
            ? {
                appendCanonicalWorkflowStateComment: input.appendCanonicalWorkflowStateComment,
            }
            : {}),
    };
    return (0, event_hook_publication_1.publishRunWorkflowWithEventHooks)({
        context: input.context,
        request,
    });
}
async function publishAutoMergeNeedsHumanUpdate(input) {
    const nextWorkflowState = (0, needs_human_merge_support_1.withWorkflowStateNeedsHumanReason)(input.workflowState, input.needsHumanReason);
    const trackerTitle = (0, effects_1.resolveRenderedTitleIfChanged)({
        issue: input.issue,
        workflowState: nextWorkflowState,
        locale: input.responseLanguage,
        surface: "pull_request",
        enabled: input.context.config.ticketTracker.showStepProgressInTitles === true,
    });
    const plan = (0, pr_publication_1.buildPullRequestHumanAttentionPublicationPlan)({
        workflowLabels: input.context.config.ticketTracker.workflowLabels,
        responseLanguage: input.responseLanguage,
        pullRequestIssue: input.issue,
        sourceIssueId: (await (0, shared_1.resolveLinkedIssueIdFromPullRequestTimeline)(input.context.ticketTracker, input.issue)) ?? input.issue.id,
        workflowState: nextWorkflowState,
        previousNeedsHumanReason: input.workflowState?.needsHumanReason ?? null,
        nextNeedsHumanReason: input.needsHumanReason,
        visibleUpdate: (0, needs_human_merge_support_1.buildNeedsHumanVisibleUpdate)({
            summary: input.summary,
            next: input.next,
            needsHumanReason: input.needsHumanReason,
            ...(input.visibleUpdateEvent !== undefined
                ? { event: input.visibleUpdateEvent }
                : {}),
        }),
        nextSnapshot: {
            status: types_2.WORKFLOW_STATUSES.aiNeedsHuman,
            rules: [...input.issue.workflowState.rules],
        },
        ...(trackerTitle !== null ? { trackerTitle } : {}),
    });
    if (plan.kind !== "pr_human_attention") {
        throw new Error("Expected a PR human-attention publication plan.");
    }
    return (0, event_hook_publication_1.publishRunWorkflowWithEventHooks)({
        context: input.context,
        request: plan.pullRequestThreadRequest,
        origin: "control_plane_error_handoff",
    });
}
async function mergePullRequestOrBuildSummary(input) {
    await restorePullRequestBaseTitleBeforeMerge({
        context: input.context,
        issue: input.issue,
        logger: input.logger,
    });
    try {
        await input.context.repositoryHost.mergePullRequest(input.automationState.number, "squash");
    }
    catch (error) {
        if ((0, needs_human_merge_support_1.isPushRejectedError)(error)) {
            await (0, effect_log_1.appendEffectResultLog)(input.logger, [
                (0, log_text_1.issueLogField)("effect", "merge_pull_request"),
                (0, log_text_1.issueLogField)("pr", input.automationState.url),
                (0, log_text_1.issueLogField)("note", "push_rejected_retry_next_cycle"),
            ]);
            if (input.onPushRejected) {
                return input.onPushRejected();
            }
            return (0, results_1.buildRunCliSummary)({
                issue: input.issue,
                outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedHuman,
                responseLanguage: input.responseLanguage,
                summary: (0, needs_human_merge_support_1.buildNeedsHumanMergeRaceMessage)(input.responseLanguage),
                commentUrl: null,
                prUrl: input.automationState.url,
                nextStep: (0, needs_human_merge_support_1.buildNeedsHumanMergeRaceNextMessage)(input.responseLanguage),
            });
        }
        if (await (0, pull_request_completion_1.isPullRequestHeadIncludedInBase)({
            repositoryHost: input.context.repositoryHost,
            pullRequestNumber: input.automationState.number,
        })) {
            await (0, effect_log_1.appendEffectResultLog)(input.logger, [
                (0, log_text_1.issueLogField)("effect", "merge_pull_request"),
                (0, log_text_1.issueLogField)("pr", input.automationState.url),
                (0, log_text_1.issueLogField)("note", "branch_already_in_target"),
            ]);
            await (0, workflow_template_root_1.refreshWorkflowTemplateRepoRoot)(input.context, { force: true });
            return null;
        }
        if ((0, errors_1.isRetryablePullRequestMergeError)(error)) {
            if (input.onRetryableMergeFailure) {
                return input.onRetryableMergeFailure(error);
            }
        }
        if (input.onMergeFailure) {
            return input.onMergeFailure(error);
        }
        const publication = await (0, needs_human_merge_support_1.publishControlPlaneNeedsHumanUpdate)({
            context: input.context,
            issue: input.issue,
            responseLanguage: input.responseLanguage,
            summary: (0, needs_human_merge_support_1.buildNeedsHumanMergeFailureMessage)(input.responseLanguage),
            next: (0, needs_human_merge_support_1.buildNeedsHumanFailureNextMessage)(input.responseLanguage),
            eventHookOrigin: "control_plane_error_handoff",
            eventHookLogger: input.logger,
        });
        await (0, effect_log_1.appendEffectFailureLog)(input.logger, [
            (0, log_text_1.issueLogField)("effect", "merge_pull_request"),
            (0, results_1.renderFailureDetails)(error, input.logger.locale),
        ]);
        return (0, results_1.buildRunCliSummary)({
            issue: input.issue,
            outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedHuman,
            responseLanguage: input.responseLanguage,
            summary: (0, needs_human_merge_support_1.buildNeedsHumanMergeFailureMessage)(input.responseLanguage),
            commentUrl: publication.visibleUpdateComment?.url ?? null,
            prUrl: input.automationState.url,
            nextStep: (0, needs_human_merge_support_1.buildNeedsHumanFailureNextMessage)(input.responseLanguage),
        });
    }
    await (0, workflow_template_root_1.refreshWorkflowTemplateRepoRoot)(input.context, { force: true });
    return null;
}
async function restorePullRequestBaseTitleBeforeMerge(input) {
    if (input.issue.kind !== types_1.TRACKER_ITEM_KINDS.pullRequest ||
        input.issue.title === input.issue.baseTitle) {
        return;
    }
    try {
        await input.context.ticketTracker.updateIssueTitle(input.issue.id, input.issue.baseTitle);
        input.issue.title = input.issue.baseTitle;
    }
    catch (error) {
        try {
            await (0, effect_log_1.appendEffectFailureLog)(input.logger, [
                (0, log_text_1.issueLogField)("effect", "restore_pull_request_title_before_merge"),
                (0, log_text_1.issueLogField)("note", `issue:${input.issue.displayId}`),
                (0, results_1.renderFailureDetails)(error, input.logger.locale),
            ]);
        }
        catch {
            // Keep auto-merge moving when only the cleanup/logging path fails.
        }
    }
}
