"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkflowDecisionValidationError = exports.WORKFLOW_DECISION_VALIDATION_ERROR_CODES = exports.isWorkflowDecisionValidationError = exports.buildPersistedWorkflowState = exports.createDefaultWorkflowExecutionContract = exports.createDefaultWorkflowContract = exports.buildPrePlanWorkflowState = void 0;
exports.isHumanInputResumeProjection = isHumanInputResumeProjection;
exports.isHumanInputResumeReason = isHumanInputResumeReason;
exports.resetHumanInputResumeState = resetHumanInputResumeState;
exports.coercePersistedWorkflowStateValue = coercePersistedWorkflowStateValue;
exports.coerceWorkflowMergeContext = coerceWorkflowMergeContext;
// biome-ignore lint/nursery/noExcessiveLinesPerFile: Persisted workflow-state coercion stays centralized so version upgrades remain auditable.
const types_1 = require("../../platform/workflow-state/types");
const auto_merge_state_1 = require("../auto-merge-state");
const config_override_validation_1 = require("../config-override-validation");
const publisher_events_1 = require("../publisher-events");
const recurring_auto_stop_1 = require("../recurring-auto-stop");
const scheduled_run_1 = require("../scheduled-run");
const types_2 = require("../types");
const coercion_support_1 = require("./coercion-support");
const pending_planning_validation_1 = require("./pending-planning-validation");
const persisted_state_builders_1 = require("./persisted-state-builders");
const plan_support_1 = require("./plan-support");
var pre_plan_state_1 = require("../pre-plan-state");
Object.defineProperty(exports, "buildPrePlanWorkflowState", { enumerable: true, get: function () { return pre_plan_state_1.buildPrePlanWorkflowState; } });
var workflow_contract_1 = require("../workflow-contract");
Object.defineProperty(exports, "createDefaultWorkflowContract", { enumerable: true, get: function () { return workflow_contract_1.createDefaultWorkflowContract; } });
Object.defineProperty(exports, "createDefaultWorkflowExecutionContract", { enumerable: true, get: function () { return workflow_contract_1.createDefaultWorkflowExecutionContract; } });
var build_1 = require("./build");
Object.defineProperty(exports, "buildPersistedWorkflowState", { enumerable: true, get: function () { return build_1.buildPersistedWorkflowState; } });
var errors_1 = require("./errors");
Object.defineProperty(exports, "isWorkflowDecisionValidationError", { enumerable: true, get: function () { return errors_1.isWorkflowDecisionValidationError; } });
Object.defineProperty(exports, "WORKFLOW_DECISION_VALIDATION_ERROR_CODES", { enumerable: true, get: function () { return errors_1.WORKFLOW_DECISION_VALIDATION_ERROR_CODES; } });
Object.defineProperty(exports, "WorkflowDecisionValidationError", { enumerable: true, get: function () { return errors_1.WorkflowDecisionValidationError; } });
const PERSISTED_WORKFLOW_STATE_FIELD_NAMES = new Set([
    "version",
    "workflowSurface",
    "workflowTemplates",
    "baseBranch",
    "parentLink",
    "originLink",
    "executionContract",
    "priorityRank",
    "schedule",
    "scheduledRun",
    "recurring",
    "nextRunAt",
    "lastRunAt",
    "lastOutcome",
    "plan",
    "planRevision",
    "parentContractRevision",
    "parentStepContractSnapshot",
    "pendingChildIssueDecisions",
    "detachedFromParentReason",
    "cancelledChildReason",
    "finalResult",
    "executionGuidance",
    "predictedTouchedPaths",
    "configOverrides",
    "dependencySyncState",
    "executionOwnership",
    "foreignInputApproval",
    "needsHumanReason",
    "pendingWorkflowStartApprovalIntent",
    "pendingPlanningIntent",
    "pendingPlanningReason",
    "pendingPlanningSource",
    "autoMergeState",
    "mergeContext",
    "pullRequestReviewNecessity",
    "followup",
    "consecutiveAiRuns",
    "totalAiRunHours",
    "lastScannedCommentCursor",
]);
const HUMAN_INPUT_RESUME_REASONS = new Set([
    publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.question,
    publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.runLimit,
    publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.reviewReady,
    publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.systemError,
]);
function isHumanInputResumeProjection(input) {
    return (input.workflowState !== null &&
        (input.snapshot.status === types_1.WORKFLOW_STATUSES.aiReady ||
            input.snapshot.status === types_1.WORKFLOW_STATUSES.aiRunning) &&
        isHumanInputResumeReason(input.workflowState.needsHumanReason));
}
function isHumanInputResumeReason(needsHumanReason) {
    return (needsHumanReason !== undefined &&
        needsHumanReason !== null &&
        HUMAN_INPUT_RESUME_REASONS.has(needsHumanReason));
}
function resetHumanInputResumeState(workflowState) {
    return {
        ...workflowState,
        consecutiveAiRuns: 0,
        totalAiRunHours: 0,
        needsHumanReason: null,
    };
}
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: State coercion stays centralized so persisted-state validation remains aligned.
// biome-ignore lint/complexity/noExcessiveLinesPerFunction: State coercion stays centralized so persisted-state validation remains aligned.
function coercePersistedWorkflowStateValue(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    if (!(0, coercion_support_1.hasOnlyRecordKeys)(value, PERSISTED_WORKFLOW_STATE_FIELD_NAMES)) {
        return null;
    }
    const workflowState = value;
    if (workflowState.version !== types_2.WORKFLOW_STATE_VERSION) {
        return null;
    }
    const workflowTemplates = (0, coercion_support_1.coerceWorkflowTemplateBindings)(workflowState.workflowTemplates);
    const workflowSurface = (0, coercion_support_1.coerceWorkflowSurface)(workflowState.workflowSurface);
    const parentLink = (0, coercion_support_1.coerceWorkflowParentLink)(workflowState.parentLink);
    const originLink = (0, coercion_support_1.coerceWorkflowOriginLink)(workflowState.originLink);
    const executionContract = (0, coercion_support_1.coerceWorkflowExecutionContract)(workflowState.executionContract);
    const priorityRank = (0, coercion_support_1.coerceWorkflowPriorityRank)(workflowState.priorityRank);
    const schedule = (0, coercion_support_1.coerceWorkflowScheduleState)(workflowState.schedule);
    const scheduledRun = (0, coercion_support_1.coerceWorkflowScheduledRunState)(workflowState.scheduledRun);
    const plan = (0, plan_support_1.coerceWorkflowPlanValue)(workflowState.plan);
    const planRevision = coerceNonNegativeSafeInteger(workflowState.planRevision);
    const parentContractRevision = workflowState.parentContractRevision === undefined
        ? undefined
        : coerceNonNegativeSafeInteger(workflowState.parentContractRevision);
    const parentStepContractSnapshot = workflowState.parentStepContractSnapshot === undefined
        ? undefined
        : (0, coercion_support_1.coerceWorkflowExecutionContract)(workflowState.parentStepContractSnapshot);
    const pendingChildIssueDecisions = workflowState.pendingChildIssueDecisions === undefined
        ? undefined
        : coercePendingChildIssueDecisions(workflowState.pendingChildIssueDecisions);
    const detachedFromParentReason = workflowState.detachedFromParentReason === undefined
        ? undefined
        : (0, coercion_support_1.coerceNullableString)(workflowState.detachedFromParentReason);
    const cancelledChildReason = workflowState.cancelledChildReason === undefined
        ? undefined
        : (0, coercion_support_1.coerceNullableString)(workflowState.cancelledChildReason);
    const configOverrides = workflowState.configOverrides === undefined
        ? undefined
        : coerceIssueConfigOverridePatch(workflowState.configOverrides);
    const dependencySyncState = workflowState.dependencySyncState === undefined
        ? undefined
        : coerceWorkflowDependencySyncState(workflowState.dependencySyncState);
    const executionOwnership = workflowState.executionOwnership === undefined
        ? undefined
        : coerceWorkflowExecutionOwnership(workflowState.executionOwnership);
    const foreignInputApproval = workflowState.foreignInputApproval === undefined
        ? undefined
        : coerceWorkflowForeignInputApprovalState(workflowState.foreignInputApproval);
    const recurring = workflowState.recurring === undefined
        ? undefined
        : coerceWorkflowRecurringState(workflowState.recurring);
    const lastOutcome = workflowState.lastOutcome === undefined
        ? undefined
        : (0, coercion_support_1.coerceWorkflowResultOutcome)(workflowState.lastOutcome);
    const nextRunAt = workflowState.nextRunAt === undefined
        ? undefined
        : (0, coercion_support_1.coerceNullableString)(workflowState.nextRunAt);
    const lastRunAt = workflowState.lastRunAt === undefined
        ? undefined
        : (0, coercion_support_1.coerceNullableString)(workflowState.lastRunAt);
    const needsHumanReason = workflowState.needsHumanReason === undefined
        ? undefined
        : workflowState.needsHumanReason === null
            ? null
            : (0, publisher_events_1.isWorkflowNeedsHumanReason)(workflowState.needsHumanReason)
                ? workflowState.needsHumanReason
                : undefined;
    const pendingWorkflowStartApprovalIntent = (0, coercion_support_1.coerceWorkflowStartApprovalIntent)(workflowState.pendingWorkflowStartApprovalIntent);
    const pendingPlanningIntent = (0, coercion_support_1.coerceWorkflowPendingPlanningIntent)(workflowState.pendingPlanningIntent);
    const pendingPlanningReason = workflowState.pendingPlanningReason === undefined
        ? undefined
        : (0, coercion_support_1.coerceNullableString)(workflowState.pendingPlanningReason);
    const pendingPlanningSource = (0, coercion_support_1.coerceWorkflowPendingPlanningSource)(workflowState.pendingPlanningSource);
    const autoMergeState = workflowState.autoMergeState === undefined
        ? undefined
        : (0, auto_merge_state_1.isWorkflowAutoMergeState)(workflowState.autoMergeState)
            ? workflowState.autoMergeState
            : undefined;
    const mergeContext = coerceWorkflowMergeContext(workflowState.mergeContext);
    const pullRequestReviewNecessity = coercePullRequestReviewNecessityState(workflowState.pullRequestReviewNecessity);
    const followup = workflowState.followup === undefined
        ? null
        : coerceWorkflowFollowupState(workflowState.followup);
    const finalResult = (0, coercion_support_1.coerceWorkflowFinalResult)(workflowState.finalResult);
    const predictedTouchedPaths = workflowState.predictedTouchedPaths === undefined
        ? []
        : ((0, coercion_support_1.coerceStringArray)(workflowState.predictedTouchedPaths) ?? []);
    const executionGuidance = workflowState.executionGuidance === undefined
        ? undefined
        : (0, coercion_support_1.coerceStringArray)(workflowState.executionGuidance);
    const lastScannedCommentCursor = coerceWorkflowCommentCursor(workflowState.lastScannedCommentCursor) ?? null;
    if (workflowTemplates === null ||
        workflowSurface === null ||
        workflowState.workflowSurface === undefined ||
        workflowState.workflowTemplates === undefined ||
        typeof workflowState.baseBranch !== "string" ||
        workflowState.baseBranch.length === 0 ||
        (workflowState.parentLink !== undefined && parentLink === null) ||
        (workflowState.originLink !== undefined && originLink === null) ||
        workflowState.executionContract === undefined ||
        executionContract === null ||
        (workflowState.priorityRank !== undefined && priorityRank === undefined) ||
        (workflowState.schedule !== undefined && schedule === null) ||
        (workflowState.scheduledRun !== undefined && scheduledRun === null) ||
        (workflowState.nextRunAt !== undefined &&
            !(0, coercion_support_1.isNullableString)(workflowState.nextRunAt)) ||
        (workflowState.lastRunAt !== undefined &&
            !(0, coercion_support_1.isNullableString)(workflowState.lastRunAt)) ||
        workflowState.plan === undefined ||
        (workflowState.plan !== null && plan === null) ||
        workflowState.planRevision === undefined ||
        planRevision === undefined ||
        (workflowState.parentContractRevision !== undefined &&
            parentContractRevision === undefined) ||
        (workflowState.parentStepContractSnapshot !== undefined &&
            parentStepContractSnapshot === null) ||
        (workflowState.pendingChildIssueDecisions !== undefined &&
            pendingChildIssueDecisions === null) ||
        (workflowState.detachedFromParentReason !== undefined &&
            !(0, coercion_support_1.isNullableString)(workflowState.detachedFromParentReason)) ||
        (workflowState.cancelledChildReason !== undefined &&
            !(0, coercion_support_1.isNullableString)(workflowState.cancelledChildReason)) ||
        (workflowState.lastOutcome !== undefined &&
            lastOutcome === null &&
            workflowState.lastOutcome !== null) ||
        (workflowState.executionGuidance !== undefined &&
            executionGuidance === null) ||
        (workflowState.predictedTouchedPaths !== undefined &&
            (0, coercion_support_1.coerceStringArray)(workflowState.predictedTouchedPaths) === null) ||
        (workflowState.configOverrides !== undefined && configOverrides === null) ||
        (workflowState.dependencySyncState !== undefined &&
            dependencySyncState === null) ||
        (workflowState.executionOwnership !== undefined &&
            executionOwnership === null) ||
        (workflowState.foreignInputApproval !== undefined &&
            foreignInputApproval === null) ||
        (workflowState.needsHumanReason !== undefined &&
            workflowState.needsHumanReason !== null &&
            !(0, publisher_events_1.isWorkflowNeedsHumanReason)(workflowState.needsHumanReason)) ||
        (workflowState.pendingWorkflowStartApprovalIntent !== undefined &&
            pendingWorkflowStartApprovalIntent === null) ||
        (workflowState.pendingPlanningIntent !== undefined &&
            pendingPlanningIntent === null) ||
        (workflowState.pendingPlanningReason !== undefined &&
            !(0, coercion_support_1.isNullableString)(workflowState.pendingPlanningReason)) ||
        (workflowState.pendingPlanningSource !== undefined &&
            pendingPlanningSource === null) ||
        (workflowState.autoMergeState !== undefined &&
            !(0, auto_merge_state_1.isWorkflowAutoMergeState)(workflowState.autoMergeState)) ||
        (workflowState.mergeContext !== undefined && mergeContext === null) ||
        (workflowState.pullRequestReviewNecessity !== undefined &&
            pullRequestReviewNecessity === null) ||
        workflowState.followup === undefined ||
        followup === null ||
        (workflowState.recurring !== undefined && recurring === null) ||
        !isValidTotalAiRunHours(workflowState.totalAiRunHours) ||
        (workflowState.lastScannedCommentCursor !== undefined &&
            coerceWorkflowCommentCursor(workflowState.lastScannedCommentCursor) ===
                undefined)) {
        return null;
    }
    if (parentLink !== undefined && originLink !== undefined) {
        return null;
    }
    if (parentLink !== undefined &&
        ((schedule !== undefined && schedule !== null && schedule.mode !== "off") ||
            (scheduledRun !== undefined &&
                !(0, scheduled_run_1.isCooldownScheduledRunState)(scheduledRun)) ||
            recurring !== undefined)) {
        return null;
    }
    if (recurring !== undefined &&
        (schedule === undefined ||
            schedule === null ||
            schedule.mode === "off" ||
            scheduledRun !== undefined)) {
        return null;
    }
    if (schedule !== undefined &&
        schedule !== null &&
        schedule.mode !== "off" &&
        scheduledRun === undefined &&
        recurring === undefined) {
        return null;
    }
    if ((0, pending_planning_validation_1.getPendingPlanningValidationError)({
        pendingPlanningIntent: pendingPlanningIntent ?? undefined,
        pendingPlanningReason,
        pendingPlanningSource: pendingPlanningSource ?? undefined,
        pendingWorkflowStartApprovalIntent: pendingWorkflowStartApprovalIntent ?? undefined,
    }) !== null) {
        return null;
    }
    const requiredExecutionContract = executionContract;
    if (requiredExecutionContract === undefined) {
        return null;
    }
    const persistedState = (0, persisted_state_builders_1.buildCoercedPersistedWorkflowStateBase)({
        workflowState,
        workflowSurface,
        workflowTemplates,
        baseBranch: workflowState.baseBranch,
        priorityRank,
        schedule,
        scheduledRun: scheduledRun ?? undefined,
        nextRunAt,
        lastRunAt,
        lastOutcome,
        plan,
        planRevision,
        finalResult,
        executionGuidance: executionGuidance ?? undefined,
        predictedTouchedPaths,
        lastScannedCommentCursor,
    });
    (0, persisted_state_builders_1.assignCoercedPersistedWorkflowStateHierarchyFields)(persistedState, {
        workflowState,
        parentLink: parentLink ?? undefined,
        originLink: originLink ?? undefined,
        executionContract: requiredExecutionContract,
    });
    (0, persisted_state_builders_1.assignCoercedPersistedWorkflowStateSupplementalFields)(persistedState, {
        workflowState,
        configOverrides,
        parentContractRevision,
        parentStepContractSnapshot: parentStepContractSnapshot ?? undefined,
        pendingChildIssueDecisions: pendingChildIssueDecisions ?? undefined,
        detachedFromParentReason,
        cancelledChildReason,
        dependencySyncState,
        executionOwnership,
        foreignInputApproval,
        needsHumanReason,
        pendingWorkflowStartApprovalIntent: pendingWorkflowStartApprovalIntent ?? undefined,
        pendingPlanningIntent: pendingPlanningIntent ?? undefined,
        recurring,
        pendingPlanningReason,
        pendingPlanningSource: pendingPlanningSource ?? undefined,
        autoMergeState,
        mergeContext: mergeContext ?? undefined,
        pullRequestReviewNecessity: pullRequestReviewNecessity ?? undefined,
        followup: followup ?? undefined,
    });
    return persistedState;
}
function isValidTotalAiRunHours(value) {
    return typeof value === "number" && Number.isFinite(value) && value >= 0;
}
function coerceNonNegativeSafeInteger(value) {
    return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
        ? value
        : undefined;
}
function coercePendingChildIssueDecisions(value) {
    return (0, coercion_support_1.coerceArrayItems)(value, coercePendingChildIssueDecision);
}
function coercePendingChildIssueDecision(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const decision = value;
    if (!(0, coercion_support_1.hasOnlyRecordKeys)(value, PENDING_CHILD_ISSUE_DECISION_FIELD_NAMES) ||
        typeof decision.childKey !== "string" ||
        decision.childKey.length === 0 ||
        typeof decision.childIssueRef !== "string" ||
        decision.childIssueRef.length === 0 ||
        typeof decision.reason !== "string" ||
        decision.reason.length === 0 ||
        (decision.action !== "queue_child_issue_replan" &&
            decision.action !== "detach_child_issue" &&
            decision.action !== "cancel_child_issue")) {
        return null;
    }
    const childIssueRef = (0, coercion_support_1.coerceNullableString)(decision.childIssueRef);
    if (childIssueRef === undefined || childIssueRef === null) {
        return null;
    }
    return {
        childKey: decision.childKey,
        childIssueRef,
        action: decision.action,
        reason: decision.reason,
    };
}
function coerceWorkflowMergeContext(value) {
    if (value === undefined) {
        return undefined;
    }
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const mergeContext = value;
    const conflictedFiles = (0, coercion_support_1.coerceStringArray)(mergeContext.conflictedFiles);
    if (typeof mergeContext.baseBranch !== "string" ||
        typeof mergeContext.baseCommitOid !== "string" ||
        (mergeContext.status !== "clean" && mergeContext.status !== "conflicted") ||
        conflictedFiles === null) {
        return null;
    }
    return {
        baseBranch: mergeContext.baseBranch,
        baseCommitOid: mergeContext.baseCommitOid,
        status: mergeContext.status,
        conflictedFiles,
    };
}
function coercePullRequestReviewNecessityState(value) {
    if (value === undefined) {
        return undefined;
    }
    if (!(0, coercion_support_1.isRecord)(value) ||
        !(0, coercion_support_1.hasOnlyRecordKeys)(value, PULL_REQUEST_REVIEW_NECESSITY_FIELD_NAMES)) {
        return null;
    }
    const state = value;
    const evidence = (0, coercion_support_1.coerceStringArray)(state.evidence);
    const reviewTriggers = (0, coercion_support_1.coerceStringArray)(state.reviewTriggers);
    const effectivePolicy = coercePullRequestReviewNecessityEffectivePolicy(state.effectivePolicy);
    const evaluationInput = coercePullRequestReviewNecessityEvaluationInput(state.evaluationInput);
    if ((state.action !== "run_review" && state.action !== "skip_review") ||
        typeof state.reason !== "string" ||
        state.reason.trim().length === 0 ||
        evidence === null ||
        evidence.length === 0 ||
        reviewTriggers === null ||
        (state.action === "run_review" && reviewTriggers.length === 0) ||
        (state.action === "skip_review" && reviewTriggers.length > 0) ||
        typeof state.evaluatedAt !== "string" ||
        state.evaluatedAt.trim().length === 0 ||
        effectivePolicy === null ||
        evaluationInput === null) {
        return null;
    }
    return {
        action: state.action,
        reason: state.reason,
        evidence,
        reviewTriggers,
        evaluatedAt: state.evaluatedAt,
        effectivePolicy,
        evaluationInput,
    };
}
function coercePullRequestReviewNecessityEffectivePolicy(value) {
    if (!(0, coercion_support_1.isRecord)(value) ||
        !(0, coercion_support_1.hasOnlyRecordKeys)(value, PULL_REQUEST_REVIEW_NECESSITY_EFFECTIVE_POLICY_FIELD_NAMES)) {
        return null;
    }
    const policy = value;
    if (policy.reviewPolicy !== "if_needed" ||
        (policy.mergePolicy !== "manual" && policy.mergePolicy !== "auto")) {
        return null;
    }
    return {
        reviewPolicy: "if_needed",
        mergePolicy: policy.mergePolicy,
    };
}
function coercePullRequestReviewNecessityEvaluationInput(value) {
    if (!(0, coercion_support_1.isRecord)(value) ||
        !(0, coercion_support_1.hasOnlyRecordKeys)(value, PULL_REQUEST_REVIEW_NECESSITY_EVALUATION_INPUT_FIELD_NAMES)) {
        return null;
    }
    const input = value;
    const commentCursor = input.commentCursor === null
        ? null
        : coerceWorkflowCommentCursor(input.commentCursor);
    const sourceCommentCursor = input.sourceCommentCursor === undefined ||
        input.sourceCommentCursor === null
        ? input.sourceCommentCursor
        : coerceWorkflowCommentCursor(input.sourceCommentCursor);
    if (typeof input.digest !== "string" ||
        input.digest.trim().length === 0 ||
        typeof input.pullRequestNumber !== "number" ||
        !Number.isSafeInteger(input.pullRequestNumber) ||
        input.pullRequestNumber <= 0 ||
        (input.headRefOid !== null && typeof input.headRefOid !== "string") ||
        commentCursor === undefined ||
        (input.sourceIssueId !== undefined &&
            input.sourceIssueId !== null &&
            typeof input.sourceIssueId !== "string") ||
        (input.sourceCommentCursor !== undefined &&
            input.sourceCommentCursor !== null &&
            sourceCommentCursor === undefined)) {
        return null;
    }
    const result = {
        digest: input.digest,
        pullRequestNumber: input.pullRequestNumber,
        headRefOid: input.headRefOid,
        commentCursor,
        ...(input.sourceIssueId !== undefined
            ? { sourceIssueId: input.sourceIssueId }
            : {}),
    };
    if (input.sourceCommentCursor !== undefined) {
        result.sourceCommentCursor = sourceCommentCursor ?? null;
    }
    return result;
}
function coerceWorkflowFollowupState(value) {
    if (value === undefined) {
        return undefined;
    }
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const followup = value;
    if (!(0, coercion_support_1.hasOnlyRecordKeys)(value, FOLLOWUP_STATE_FIELD_NAMES)) {
        return null;
    }
    if (followup.proposalPolicy !== "off" &&
        followup.proposalPolicy !== "if_needed" &&
        followup.proposalPolicy !== "always") {
        return null;
    }
    if (followup.proposalApproval !== "auto" &&
        followup.proposalApproval !== "confirm" &&
        followup.proposalApproval !== "confirm_if_needed") {
        return null;
    }
    const recommendation = coerceWorkflowFollowupRecommendation(followup.recommendation);
    const recommendationSource = coerceWorkflowFollowupRecommendationSource(followup.recommendationSource);
    const publications = followup.publications === undefined
        ? undefined
        : (0, coercion_support_1.coerceArrayItems)(followup.publications, coerceWorkflowFollowupPublication);
    const proposal = followup.proposal === undefined
        ? undefined
        : coerceWorkflowFollowupProposal(followup.proposal);
    if ((followup.recommendation !== undefined &&
        followup.recommendation !== null &&
        recommendation === null) ||
        (followup.recommendationSource !== undefined &&
            followup.recommendationSource !== null &&
            recommendationSource === null) ||
        (followup.publications !== undefined && publications === null) ||
        (followup.proposal !== undefined &&
            followup.proposal !== null &&
            proposal === null)) {
        return null;
    }
    return {
        proposalPolicy: followup.proposalPolicy,
        proposalApproval: followup.proposalApproval,
        ...(followup.recommendation !== undefined
            ? { recommendation: recommendation ?? null }
            : {}),
        ...(followup.recommendationSource !== undefined
            ? { recommendationSource: recommendationSource ?? null }
            : {}),
        ...(followup.publications !== undefined
            ? { publications: publications ?? [] }
            : {}),
        ...(followup.proposal !== undefined ? { proposal: proposal ?? null } : {}),
    };
}
function coerceWorkflowFollowupProposal(value) {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }
    if (!(0, coercion_support_1.isRecord)(value) ||
        !(0, coercion_support_1.hasOnlyRecordKeys)(value, FOLLOWUP_PROPOSAL_FIELD_NAMES)) {
        return null;
    }
    const proposal = value;
    const items = (0, coercion_support_1.coerceArrayItems)(proposal.items, coerceWorkflowFollowupRecommendationItem);
    if (proposal.status !== "pending" ||
        typeof proposal.commentId !== "string" ||
        typeof proposal.createdAt !== "string" ||
        typeof proposal.sourceRecommendationDigest !== "string" ||
        items === null) {
        return null;
    }
    return {
        status: proposal.status,
        commentId: proposal.commentId,
        createdAt: proposal.createdAt,
        sourceRecommendationDigest: proposal.sourceRecommendationDigest,
        items,
    };
}
function coerceWorkflowFollowupRecommendationSource(value) {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }
    if (!(0, coercion_support_1.isRecord)(value) ||
        !(0, coercion_support_1.hasOnlyRecordKeys)(value, FOLLOWUP_RECOMMENDATION_SOURCE_FIELD_NAMES)) {
        return null;
    }
    const source = value;
    if (source.kind !== "workflow_closing" ||
        typeof source.freshnessVerified !== "boolean" ||
        typeof source.workspaceHeadCommitOid !== "string" ||
        (source.expectedCommitOid !== undefined &&
            source.expectedCommitOid !== null &&
            typeof source.expectedCommitOid !== "string") ||
        (source.expectedCommitKind !== undefined &&
            source.expectedCommitKind !== "pull_request_head" &&
            source.expectedCommitKind !== "pull_request_merge" &&
            source.expectedCommitKind !== "pull_request_commits") ||
        (source.pullRequestNumber !== undefined &&
            (source.pullRequestNumber === null ||
                typeof source.pullRequestNumber !== "number" ||
                !Number.isSafeInteger(source.pullRequestNumber) ||
                source.pullRequestNumber <= 0)) ||
        (source.pullRequestUrl !== undefined &&
            typeof source.pullRequestUrl !== "string")) {
        return null;
    }
    return {
        kind: "workflow_closing",
        freshnessVerified: source.freshnessVerified,
        workspaceHeadCommitOid: source.workspaceHeadCommitOid,
        ...(source.expectedCommitOid !== undefined
            ? { expectedCommitOid: source.expectedCommitOid }
            : {}),
        ...(source.expectedCommitKind !== undefined
            ? { expectedCommitKind: source.expectedCommitKind }
            : {}),
        ...(source.pullRequestNumber !== undefined
            ? { pullRequestNumber: source.pullRequestNumber }
            : {}),
        ...(source.pullRequestUrl !== undefined
            ? { pullRequestUrl: source.pullRequestUrl }
            : {}),
    };
}
function coerceWorkflowFollowupRecommendation(value) {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const recommendation = value;
    if (!(0, coercion_support_1.hasOnlyRecordKeys)(value, FOLLOWUP_RECOMMENDATION_FIELD_NAMES)) {
        return null;
    }
    const items = (0, coercion_support_1.coerceArrayItems)(recommendation.items, coerceWorkflowFollowupRecommendationItem);
    if (typeof recommendation.recommended !== "boolean" ||
        typeof recommendation.reason !== "string" ||
        items === null) {
        return null;
    }
    return {
        recommended: recommendation.recommended,
        reason: recommendation.reason,
        items,
    };
}
function coerceWorkflowFollowupRecommendationItem(value) {
    if (!(0, coercion_support_1.isRecord)(value) ||
        !(0, coercion_support_1.hasOnlyRecordKeys)(value, FOLLOWUP_ITEM_FIELD_NAMES)) {
        return null;
    }
    const item = value;
    const category = types_2.WORKFLOW_FOLLOWUP_RECOMMENDATION_CATEGORIES.find((candidate) => item.category === candidate);
    if (category === undefined ||
        typeof item.title !== "string" ||
        item.title.trim().length === 0 ||
        typeof item.body !== "string" ||
        item.body.trim().length === 0 ||
        typeof item.reason !== "string" ||
        item.reason.trim().length === 0) {
        return null;
    }
    const workflowTemplate = typeof item.workflowTemplate === "string"
        ? (0, types_2.normalizeFollowupWorkflowTemplateCandidate)(item.workflowTemplate)
        : undefined;
    if (workflowTemplate === null) {
        return null;
    }
    if (item.proposalApproval !== undefined &&
        item.proposalApproval !== "auto" &&
        item.proposalApproval !== "confirm") {
        return null;
    }
    return {
        category,
        title: item.title,
        body: item.body,
        reason: item.reason,
        ...(workflowTemplate !== undefined ? { workflowTemplate } : {}),
        ...(item.proposalApproval !== undefined
            ? { proposalApproval: item.proposalApproval }
            : {}),
    };
}
function coerceWorkflowFollowupPublication(value) {
    if (!(0, coercion_support_1.isRecord)(value) ||
        !(0, coercion_support_1.hasOnlyRecordKeys)(value, FOLLOWUP_PUBLICATION_FIELD_NAMES)) {
        return null;
    }
    const publication = value;
    const category = publication.category === undefined
        ? undefined
        : types_2.WORKFLOW_FOLLOWUP_RECOMMENDATION_CATEGORIES.find((candidate) => publication.category === candidate);
    if (typeof publication.at !== "string" ||
        (publication.requestTitle !== undefined &&
            typeof publication.requestTitle !== "string") ||
        (publication.requestDigest !== undefined &&
            typeof publication.requestDigest !== "string") ||
        (publication.category !== undefined && category === undefined)) {
        return null;
    }
    const requestFields = {
        ...(publication.requestTitle !== undefined
            ? { requestTitle: publication.requestTitle }
            : {}),
        ...(publication.requestDigest !== undefined
            ? { requestDigest: publication.requestDigest }
            : {}),
        ...(category !== undefined ? { category } : {}),
    };
    if (publication.status === "created" || publication.status === "reused") {
        if (typeof publication.issueId !== "string" ||
            typeof publication.issueDisplayId !== "string" ||
            typeof publication.url !== "string") {
            return null;
        }
        return {
            status: publication.status,
            issueId: publication.issueId,
            issueDisplayId: publication.issueDisplayId,
            url: publication.url,
            at: publication.at,
            ...requestFields,
        };
    }
    if (publication.status === "failed" || publication.status === "skipped") {
        if (typeof publication.reason !== "string") {
            return null;
        }
        return {
            status: publication.status,
            reason: publication.reason,
            at: publication.at,
            ...requestFields,
        };
    }
    return null;
}
const FOLLOWUP_STATE_FIELD_NAMES = new Set([
    "proposalPolicy",
    "proposalApproval",
    "recommendation",
    "recommendationSource",
    "publications",
    "proposal",
]);
const FOLLOWUP_PROPOSAL_FIELD_NAMES = new Set([
    "status",
    "commentId",
    "createdAt",
    "sourceRecommendationDigest",
    "items",
]);
const PULL_REQUEST_REVIEW_NECESSITY_FIELD_NAMES = new Set([
    "action",
    "reason",
    "evidence",
    "reviewTriggers",
    "evaluatedAt",
    "effectivePolicy",
    "evaluationInput",
]);
const PULL_REQUEST_REVIEW_NECESSITY_EFFECTIVE_POLICY_FIELD_NAMES = new Set([
    "reviewPolicy",
    "mergePolicy",
]);
const PULL_REQUEST_REVIEW_NECESSITY_EVALUATION_INPUT_FIELD_NAMES = new Set([
    "digest",
    "pullRequestNumber",
    "headRefOid",
    "commentCursor",
    "sourceIssueId",
    "sourceCommentCursor",
]);
const FOLLOWUP_RECOMMENDATION_SOURCE_FIELD_NAMES = new Set([
    "kind",
    "freshnessVerified",
    "workspaceHeadCommitOid",
    "expectedCommitOid",
    "expectedCommitKind",
    "pullRequestNumber",
    "pullRequestUrl",
]);
const FOLLOWUP_RECOMMENDATION_FIELD_NAMES = new Set([
    "recommended",
    "reason",
    "items",
]);
const FOLLOWUP_ITEM_FIELD_NAMES = new Set([
    "category",
    "title",
    "body",
    "reason",
    "workflowTemplate",
    "proposalApproval",
]);
const FOLLOWUP_PUBLICATION_FIELD_NAMES = new Set([
    "status",
    "issueId",
    "issueDisplayId",
    "url",
    "reason",
    "at",
    "requestTitle",
    "requestDigest",
    "category",
]);
const PENDING_CHILD_ISSUE_DECISION_FIELD_NAMES = new Set([
    "childKey",
    "childIssueRef",
    "action",
    "reason",
]);
function coerceWorkflowForeignInputApprovalState(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const approval = value;
    const approvedThroughCursor = coerceWorkflowCommentCursor(approval.approvedThroughCursor);
    if (typeof approval.approvedBy !== "string" ||
        typeof approval.approvedAssignee !== "string" ||
        typeof approval.approvedAt !== "string" ||
        (approval.approvedDigest !== undefined &&
            typeof approval.approvedDigest !== "string") ||
        approvedThroughCursor === undefined) {
        return null;
    }
    const foreignInputApproval = {
        approvedBy: approval.approvedBy,
        approvedAssignee: approval.approvedAssignee,
        approvedAt: approval.approvedAt,
        approvedThroughCursor,
    };
    if (typeof approval.approvedDigest === "string") {
        foreignInputApproval.approvedDigest = approval.approvedDigest;
    }
    return foreignInputApproval;
}
function coerceWorkflowCommentCursor(value) {
    if (value === null || value === undefined) {
        return null;
    }
    if (!(0, coercion_support_1.isRecord)(value)) {
        return undefined;
    }
    const cursor = value;
    if (typeof cursor.commentId !== "string" ||
        typeof cursor.createdAt !== "string") {
        return undefined;
    }
    return {
        commentId: cursor.commentId,
        createdAt: cursor.createdAt,
    };
}
function coerceIssueConfigOverridePatch(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const patch = value;
    const entries = (0, coercion_support_1.coerceArrayItems)(patch.entries, coerceIssueConfigOverrideEntry);
    if (entries === null) {
        return null;
    }
    return { entries };
}
function coerceIssueConfigOverrideEntry(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const entry = value;
    if (typeof entry.path !== "string" ||
        entry.path.length === 0 ||
        (entry.op !== "set" && entry.op !== "inherit" && entry.op !== "disable")) {
        return null;
    }
    const overrideEntry = {
        path: entry.path,
        op: entry.op,
    };
    if (Object.hasOwn(entry, "value")) {
        overrideEntry.value = entry.value;
    }
    return (0, config_override_validation_1.isConfigOverrideEntryValid)(overrideEntry) ? overrideEntry : null;
}
function coerceWorkflowDependencySyncState(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const state = value;
    const managedDependencies = coerceWorkflowManagedDependencies(state.managedDependencies);
    const appliedAutoBlockers = coerceWorkflowDependencySyncEntries(state.appliedAutoBlockers);
    if (managedDependencies === null || appliedAutoBlockers === null) {
        return null;
    }
    return {
        managedDependencies,
        appliedAutoBlockers,
    };
}
function coerceWorkflowManagedDependencies(value) {
    return (0, coercion_support_1.coerceArrayItems)(value, coerceWorkflowManagedDependency);
}
function coerceWorkflowDependencySyncEntries(value) {
    return (0, coercion_support_1.coerceArrayItems)(value, coerceWorkflowDependencySyncEntry);
}
function coerceWorkflowManagedDependency(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const dependency = value;
    const overlappingPaths = (0, coercion_support_1.coerceStringArray)(dependency.overlappingPaths);
    if (typeof dependency.issueId !== "string" ||
        typeof dependency.scopeDigest !== "string" ||
        overlappingPaths === null ||
        typeof dependency.recordedAt !== "string" ||
        !(0, coercion_support_1.isNullableString)(dependency.completionRequeuedAt)) {
        return null;
    }
    return {
        issueId: dependency.issueId,
        scopeDigest: dependency.scopeDigest,
        overlappingPaths,
        recordedAt: dependency.recordedAt,
        completionRequeuedAt: (0, coercion_support_1.coerceNullableString)(dependency.completionRequeuedAt),
    };
}
function coerceWorkflowExecutionOwnership(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const ownership = value;
    if (typeof ownership.workerId !== "string" ||
        ownership.workerId.length === 0 ||
        typeof ownership.runId !== "string" ||
        ownership.runId.length === 0 ||
        typeof ownership.claimedAt !== "string" ||
        ownership.claimedAt.length === 0 ||
        typeof ownership.heartbeatAt !== "string" ||
        ownership.heartbeatAt.length === 0 ||
        typeof ownership.expiresAt !== "string" ||
        ownership.expiresAt.length === 0) {
        return null;
    }
    return {
        workerId: ownership.workerId,
        runId: ownership.runId,
        claimedAt: ownership.claimedAt,
        heartbeatAt: ownership.heartbeatAt,
        expiresAt: ownership.expiresAt,
    };
}
function coerceWorkflowRecurringState(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const recurring = value;
    if (recurring.kind !== "parent") {
        return null;
    }
    const autoStop = recurring.autoStop === undefined
        ? undefined
        : coerceWorkflowRecurringAutoStopState(recurring.autoStop);
    if (autoStop === null) {
        return null;
    }
    if (autoStop === undefined) {
        return { kind: "parent" };
    }
    return { kind: "parent", autoStop };
}
function coerceWorkflowRecurringAutoStopState(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    if (!(0, coercion_support_1.hasOnlyRecordKeys)(value, new Set(["stopAt", "stopAfterRuns", "createdChildIssueCount"]))) {
        return null;
    }
    const autoStop = value;
    if (!(0, coercion_support_1.isNullableString)(autoStop.stopAt) ||
        !isNullablePositiveInteger(autoStop.stopAfterRuns) ||
        !isNonNegativeSafeInteger(autoStop.createdChildIssueCount)) {
        return null;
    }
    return (0, recurring_auto_stop_1.normalizeRecurringAutoStopState)({
        stopAt: (0, coercion_support_1.coerceNullableString)(autoStop.stopAt),
        stopAfterRuns: autoStop.stopAfterRuns,
        createdChildIssueCount: autoStop.createdChildIssueCount,
    });
}
function isNullablePositiveInteger(value) {
    return value === null || (isNonNegativeSafeInteger(value) && value > 0);
}
function isNonNegativeSafeInteger(value) {
    return Number.isSafeInteger(value) && Number(value) >= 0;
}
function coerceWorkflowDependencySyncEntry(value) {
    if (!(0, coercion_support_1.isRecord)(value)) {
        return null;
    }
    const dependency = value;
    if (typeof dependency.issueId !== "string" ||
        typeof dependency.scopeDigest !== "string" ||
        (0, coercion_support_1.coerceStringArray)(dependency.overlappingPaths) === null ||
        typeof dependency.recordedAt !== "string") {
        return null;
    }
    return {
        issueId: dependency.issueId,
        scopeDigest: dependency.scopeDigest,
        overlappingPaths: (0, coercion_support_1.coerceStringArray)(dependency.overlappingPaths) ?? [],
        recordedAt: dependency.recordedAt,
    };
}
