"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildResolveIOAIManagerAutopilotSnapshot = buildResolveIOAIManagerAutopilotSnapshot;
var ai_runner_manager_policy_1 = require("./ai-runner-manager-policy");
function cleanText(value, max) {
    if (max === void 0) { max = 1000; }
    return String(value || '').replace(/\s+/g, ' ').trim().slice(0, max);
}
function cleanList(value, limit, max) {
    var e_1, _a;
    if (limit === void 0) { limit = 20; }
    if (max === void 0) { max = 500; }
    var raw = Array.isArray(value) ? value : [];
    var output = [];
    try {
        for (var raw_1 = __values(raw), raw_1_1 = raw_1.next(); !raw_1_1.done; raw_1_1 = raw_1.next()) {
            var entry = raw_1_1.value;
            var cleaned = cleanText(entry, max);
            if (cleaned && !output.includes(cleaned)) {
                output.push(cleaned);
            }
            if (output.length >= limit) {
                break;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (raw_1_1 && !raw_1_1.done && (_a = raw_1.return)) _a.call(raw_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return output;
}
function cleanNumber(value) {
    var parsed = Number(value);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
}
function isoNow(value) {
    if (value instanceof Date) {
        return value.toISOString();
    }
    var parsed = value ? new Date(value) : new Date();
    return Number.isFinite(parsed.getTime()) ? parsed.toISOString() : new Date().toISOString();
}
function stableHash(prefix, value) {
    var normalized = typeof value === 'string'
        ? cleanText(value, 12000)
        : JSON.stringify(value || {});
    var hash = 0;
    for (var index = 0; index < normalized.length; index += 1) {
        hash = ((hash << 5) - hash + normalized.charCodeAt(index)) | 0;
    }
    return "".concat(prefix, "-").concat(Math.abs(hash).toString(36) || '0');
}
function defaultLabelForAction(action) {
    switch (action) {
        case 'run_evidence_probe':
            return 'Collect New Evidence';
        case 'run_read_only_diagnosis':
            return 'Run Diagnosis';
        case 'run_infra_repair':
            return 'Repair Infra';
        case 'run_compile_repair':
            return 'Repair Compile';
        case 'run_journey_contract_repair':
            return 'Repair Journey';
        case 'run_business_assertion_repair':
            return 'Repair Business Proof';
        case 'run_release_repair':
            return 'Repair Release';
        case 'run_targeted_product_repair':
            return 'Run Targeted Repair';
        case 'advance':
            return 'Advance';
        case 'continue_gate':
            return 'Continue Gate';
        case 'park_manual':
            return 'Attach New Evidence';
        default:
            return action ? cleanText(action.replace(/_/g, ' '), 120) : 'Review Manager State';
    }
}
function expectedResultForAction(action, evidenceOnly) {
    if (action === 'park_manual') {
        return 'Runner stays parked until new evidence, operator approval, or a changed blocker is recorded.';
    }
    if (evidenceOnly || action === 'run_evidence_probe' || action === 'run_read_only_diagnosis') {
        return 'Runner records a new artifact path or changed evidence hash before any more product repair.';
    }
    if (action === 'run_infra_repair' || action === 'run_compile_repair' || action === 'run_release_repair') {
        return 'Runner repairs only the named deterministic gate and reruns that gate.';
    }
    if (action === 'run_targeted_product_repair') {
        return 'Runner performs one bounded owner-scope repair and then returns to deterministic proof.';
    }
    return 'Runner advances only after the current gate has proof.';
}
function autonomyModeLabel(mode) {
    switch (mode) {
        case 'monitor_only':
            return 'Monitor Only';
        case 'auto_retry_within_budget':
            return 'Auto Retry Within Budget';
        case 'manual_only':
        default:
            return 'Manual Only';
    }
}
function autonomyModeDescription(mode) {
    switch (mode) {
        case 'monitor_only':
            return 'Watch the runner and record evidence, but do not dispatch recovery, repair, QA, release, or customer actions.';
        case 'auto_retry_within_budget':
            return 'Auto-dispatch only evidence-backed actions with positive expected value inside the configured budget.';
        case 'manual_only':
        default:
            return 'Show the safest next action, but require an operator to dispatch it.';
    }
}
function controlAction(input) {
    var action = cleanText(input.action, 120) || 'review';
    return {
        action: action,
        label: cleanText(input.label, 160) || defaultLabelForAction(action),
        group: input.group,
        enabled: input.enabled !== false,
        autoRunnable: input.autoRunnable === true,
        requiresConfirmation: input.requiresConfirmation === true,
        confirmationReason: cleanText(input.confirmationReason, 500),
        safety: input.safety || 'medium',
        reason: cleanText(input.reason, 1000),
        nextCommand: cleanText(input.nextCommand || action, 160),
        expectedResult: cleanText(input.expectedResult || expectedResultForAction(action, false), 500),
        costCeilingUsd: cleanNumber(input.costCeilingUsd)
    };
}
function safetyFor(input) {
    if (!input.enabled || input.action === 'park_manual') {
        return 'blocked';
    }
    if (input.evidenceOnly || input.action === 'run_evidence_probe' || input.action === 'run_read_only_diagnosis') {
        return 'low';
    }
    if (input.expensiveModelAllowed || input.action === 'run_targeted_product_repair') {
        return 'high';
    }
    if (input.productRepairAllowed) {
        return 'medium';
    }
    return 'medium';
}
function buildControlPolicy(input) {
    var recommended = input.recommendedAction;
    var autonomy = input.autonomyPolicy;
    var blocked = recommended.enabled === false || autonomy.blocked === true || recommended.action === 'park_manual';
    var primaryAction = controlAction({
        action: recommended.action,
        label: recommended.label,
        group: 'primary',
        enabled: recommended.enabled,
        autoRunnable: recommended.autoRunnable,
        requiresConfirmation: recommended.safety === 'high'
            || recommended.canRunExpensiveModel
            || recommended.action === 'run_targeted_product_repair'
            || recommended.action === 'run_release_repair',
        confirmationReason: recommended.safety === 'high'
            ? 'This can spend model tokens or modify product code; confirm the diagnosis/proof gate is current.'
            : recommended.action === 'run_release_repair'
                ? 'This can affect release state; confirm hotfix/release evidence first.'
                : '',
        safety: recommended.safety,
        reason: recommended.reason,
        nextCommand: recommended.allowedDispatchAction || recommended.dispatchAction || recommended.action,
        expectedResult: recommended.expectedResult,
        costCeilingUsd: recommended.costCeilingUsd
    });
    var policyActions = ['manual_only', 'monitor_only', 'auto_retry_within_budget'].map(function (mode) { return controlAction({
        action: "set_mode:".concat(mode),
        label: autonomyModeLabel(mode),
        group: 'policy',
        enabled: autonomy.mode !== mode,
        autoRunnable: false,
        requiresConfirmation: mode === 'auto_retry_within_budget',
        confirmationReason: mode === 'auto_retry_within_budget'
            ? 'Auto retry will dispatch only evidence-backed actions inside budget, but can still spend runner tokens.'
            : '',
        safety: mode === 'auto_retry_within_budget' ? 'medium' : 'low',
        reason: mode === autonomy.mode ? 'Current manager mode.' : autonomyModeDescription(mode),
        nextCommand: "set_manager_mode_".concat(mode),
        expectedResult: mode === autonomy.mode ? 'Mode is unchanged.' : "Manager switches to ".concat(autonomyModeLabel(mode), "."),
        costCeilingUsd: 0
    }); });
    var choiceActions = (input.humanDecision.choices || [])
        .filter(function (choice) { return choice.action !== recommended.action; })
        .map(function (choice) { return controlAction({
        action: choice.action,
        label: choice.label,
        group: choice.action === 'record_hotfix_evidence' ? 'release' : (choice.action === 'park_manual' ? 'danger' : 'evidence'),
        enabled: true,
        autoRunnable: false,
        requiresConfirmation: choice.requiresConfirmation || choice.action === 'park_manual',
        confirmationReason: choice.requiresConfirmation
            ? choice.description
            : choice.action === 'park_manual'
                ? 'Parking stops automated progress until new evidence or operator policy changes.'
                : '',
        safety: choice.safety,
        reason: choice.description,
        nextCommand: choice.nextCommand,
        expectedResult: choice.expectedResult,
        costCeilingUsd: 0
    }); });
    if (recommended.requiresNewEvidence && !choiceActions.some(function (action) { return action.action === 'run_evidence_probe'; })) {
        choiceActions.unshift(controlAction({
            action: 'run_evidence_probe',
            label: 'Collect New Evidence',
            group: 'evidence',
            enabled: true,
            autoRunnable: false,
            requiresConfirmation: false,
            safety: 'low',
            reason: 'Collect deterministic evidence before another repair loop.',
            nextCommand: 'run_evidence_probe',
            expectedResult: 'A new artifact path or changed evidence hash is recorded.',
            costCeilingUsd: 0.25
        }));
    }
    var grouped = [
        { groupId: 'policy', label: 'Mode', actions: policyActions },
        { groupId: 'evidence', label: 'Evidence', actions: choiceActions.filter(function (action) { return action.group === 'evidence'; }) },
        { groupId: 'release', label: 'Release', actions: choiceActions.filter(function (action) { return action.group === 'release'; }) },
        { groupId: 'danger', label: 'Danger Zone', actions: choiceActions.filter(function (action) { return action.group === 'danger'; }) }
    ].filter(function (group) { return group.actions.length > 0; });
    return {
        mode: autonomy.mode,
        modeLabel: autonomyModeLabel(autonomy.mode),
        modeDescription: autonomyModeDescription(autonomy.mode),
        onePrimaryActionOnly: true,
        blocked: blocked,
        blockedReason: blocked ? cleanText(autonomy.reason || recommended.reason, 1000) : '',
        canAutoDispatch: recommended.autoRunnable === true && autonomy.canAutoDispatch === true,
        requiresHumanDecision: input.humanDecision.required === true || recommended.autoRunnable !== true,
        primaryAction: primaryAction,
        secondaryActionGroups: grouped,
        budget: {
            currentRunUsd: input.currentRunUsd,
            totalUsd: input.totalUsd,
            projectedActionCostUsd: autonomy.projectedActionCostUsd,
            projectedSpendUsd: autonomy.projectedSpendUsd,
            budgetSoftUsd: autonomy.budgetSoftUsd,
            budgetHardUsd: autonomy.budgetHardUsd,
            softBudgetExceeded: autonomy.softBudgetExceeded,
            hardBudgetExceeded: autonomy.hardBudgetExceeded,
            untrackedWarning: input.untrackedWarning
        }
    };
}
function resolveDispatchAction(input) {
    var _a, _b, _c;
    var directiveAction = cleanText((_a = input.recoveryDirective) === null || _a === void 0 ? void 0 : _a.dispatchAction, 120);
    if (directiveAction) {
        return directiveAction;
    }
    var actionMode = cleanText((_b = input.recoveryAction) === null || _b === void 0 ? void 0 : _b.mode, 120);
    switch (actionMode) {
        case 'collect_evidence':
            return 'run_evidence_probe';
        case 'read_only_diagnosis':
            return 'run_read_only_diagnosis';
        case 'repair_infra':
            return 'run_infra_repair';
        case 'repair_compile':
            return 'run_compile_repair';
        case 'repair_journey_contract':
            return 'run_journey_contract_repair';
        case 'repair_business_assertion':
            return 'run_business_assertion_repair';
        case 'repair_release':
            return 'run_release_repair';
        case 'targeted_product_repair':
            return 'run_targeted_product_repair';
        case 'advance':
            return 'advance';
        case 'continue_gate':
            return 'continue_gate';
        case 'manual_review':
            return 'park_manual';
        default:
            return ((_c = input.recoveryCheckpoint) === null || _c === void 0 ? void 0 : _c.status) === 'parked' ? 'run_evidence_probe' : 'continue_gate';
    }
}
function countSameEvidenceDispatches(input, dispatchAction) {
    var _a, _b, _c, _d, _e, _f, _g;
    var checkpointId = cleanText(((_a = input.recoveryCheckpoint) === null || _a === void 0 ? void 0 : _a.checkpointId) || ((_b = input.recoveryAction) === null || _b === void 0 ? void 0 : _b.checkpointId), 160);
    var actionId = cleanText((_c = input.recoveryAction) === null || _c === void 0 ? void 0 : _c.actionId, 160);
    var evidenceHash = cleanText(((_d = input.current) === null || _d === void 0 ? void 0 : _d.evidenceHash) || ((_e = input.recoveryCheckpoint) === null || _e === void 0 ? void 0 : _e.evidenceHash), 160);
    var blockerFingerprint = cleanText(((_f = input.current) === null || _f === void 0 ? void 0 : _f.blockerFingerprint) || ((_g = input.recoveryCheckpoint) === null || _g === void 0 ? void 0 : _g.blockerFingerprint), 160);
    var history = Array.isArray(input.recoveryDispatchHistory) ? input.recoveryDispatchHistory : [];
    return history.filter(function (entry) {
        var sameCheckpoint = checkpointId && cleanText(entry === null || entry === void 0 ? void 0 : entry.checkpointId, 160) === checkpointId;
        var sameAction = actionId && cleanText(entry === null || entry === void 0 ? void 0 : entry.actionId, 160) === actionId;
        var sameEvidence = !evidenceHash || cleanText(entry === null || entry === void 0 ? void 0 : entry.evidenceHash, 160) === evidenceHash;
        var sameBlocker = !blockerFingerprint || cleanText(entry === null || entry === void 0 ? void 0 : entry.blockerFingerprint, 160) === blockerFingerprint;
        var sameDispatchAction = !dispatchAction
            || dispatchAction === 'park_manual'
            || cleanText(entry === null || entry === void 0 ? void 0 : entry.dispatchAction, 120) === dispatchAction
            || cleanText(entry === null || entry === void 0 ? void 0 : entry.dispatchAction, 120) === 'park_manual';
        return (sameCheckpoint || sameAction) && sameEvidence && sameBlocker && sameDispatchAction;
    }).length;
}
function normalizeRecentDispatches(history) {
    var source = Array.isArray(history) ? history.filter(Boolean) : [];
    return source.slice(-5).reverse().map(function (entry) { return ({
        dispatchId: cleanText(entry === null || entry === void 0 ? void 0 : entry.dispatchId, 160),
        actionId: cleanText(entry === null || entry === void 0 ? void 0 : entry.actionId, 160),
        checkpointId: cleanText(entry === null || entry === void 0 ? void 0 : entry.checkpointId, 160),
        probeId: cleanText(entry === null || entry === void 0 ? void 0 : entry.probeId, 160),
        mode: cleanText(entry === null || entry === void 0 ? void 0 : entry.mode, 120),
        dispatchAction: cleanText(entry === null || entry === void 0 ? void 0 : entry.dispatchAction, 120),
        status: cleanText(entry === null || entry === void 0 ? void 0 : entry.status, 80),
        reason: cleanText(entry === null || entry === void 0 ? void 0 : entry.reason, 500),
        evidenceHash: cleanText(entry === null || entry === void 0 ? void 0 : entry.evidenceHash, 160),
        blockerFingerprint: cleanText(entry === null || entry === void 0 ? void 0 : entry.blockerFingerprint, 160),
        artifactPaths: cleanList(entry === null || entry === void 0 ? void 0 : entry.artifactPaths, 8, 500),
        startedAt: cleanText(entry === null || entry === void 0 ? void 0 : entry.startedAt, 80),
        completedAt: cleanText(entry === null || entry === void 0 ? void 0 : entry.completedAt, 80),
        createdAt: cleanText(entry === null || entry === void 0 ? void 0 : entry.createdAt, 80)
    }); });
}
function humanDecisionChoice(choiceId, label, action, description, safety, nextCommand, expectedResult, requiresConfirmation) {
    if (requiresConfirmation === void 0) { requiresConfirmation = false; }
    return {
        choiceId: choiceId,
        label: label,
        action: action,
        description: cleanText(description, 500),
        safety: safety,
        requiresConfirmation: requiresConfirmation,
        nextCommand: nextCommand,
        expectedResult: cleanText(expectedResult, 500)
    };
}
function buildHumanDecisionRequest(input) {
    var _a, _b, _c, _d, _e;
    var checkpoint = input.snapshot.recoveryCheckpoint;
    var current = input.snapshot.current || {};
    var recoveryClass = cleanText((checkpoint === null || checkpoint === void 0 ? void 0 : checkpoint.recoveryClass) || ((_a = input.snapshot.recoveryAction) === null || _a === void 0 ? void 0 : _a.recoveryClass) || ((_b = input.snapshot.recoveryPlan) === null || _b === void 0 ? void 0 : _b.recoveryClass), 120);
    var failureClass = cleanText(current.failureClass, 120);
    var blocker = cleanText(current.blocker || current.summary || input.reason, 1000);
    var evidenceHash = cleanText(current.evidenceHash || (checkpoint === null || checkpoint === void 0 ? void 0 : checkpoint.evidenceHash), 160);
    var blockerFingerprint = cleanText(current.blockerFingerprint || (checkpoint === null || checkpoint === void 0 ? void 0 : checkpoint.blockerFingerprint), 160);
    var checkpointId = cleanText((checkpoint === null || checkpoint === void 0 ? void 0 : checkpoint.checkpointId) || ((_c = input.snapshot.recoveryAction) === null || _c === void 0 ? void 0 : _c.checkpointId), 160);
    var recentArtifactPaths = cleanList(((_d = current.artifactPaths) === null || _d === void 0 ? void 0 : _d.length)
        ? current.artifactPaths
        : input.recentDispatches.flatMap(function (entry) { return entry.artifactPaths || []; }), 12, 500);
    var required = input.sameEvidenceAlreadyAttempted
        || input.loopState === 'parked'
        || input.loopState === 'manual_handoff'
        || input.recommendedAction.enabled === false
        || input.recommendedAction.action === 'park_manual';
    var baseEvidence = {
        failureClass: failureClass,
        blocker: blocker,
        blockerFingerprint: blockerFingerprint,
        evidenceHash: evidenceHash,
        checkpointId: checkpointId,
        recoveryClass: recoveryClass,
        dispatchAction: input.dispatchAction,
        requiredArtifacts: input.requiredArtifacts,
        forbiddenActions: input.forbiddenActions,
        recentArtifactPaths: recentArtifactPaths
    };
    var blockedUntil = input.requiresNewEvidence
        ? Array.from(new Set([
            'new material evidence changes the evidenceHash or blockerFingerprint',
            'new artifact path is recorded from the failed deterministic gate',
            'operator updates scope, diagnosis, budget, or retry policy'
        ]))
        : [];
    if (!required) {
        return {
            requestId: stableHash('mgr-human', {
                checkpointId: checkpointId,
                evidenceHash: evidenceHash,
                blockerFingerprint: blockerFingerprint,
                required: false
            }),
            required: false,
            status: 'not_required',
            reason: 'No human decision is required for the current bounded next action.',
            question: '',
            preferredChoiceId: '',
            evidence: baseEvidence,
            choices: [],
            blockedUntil: [],
            createdAt: isoNow(input.updatedAt)
        };
    }
    var choices = [];
    if (input.requiresNewEvidence || input.sameEvidenceAlreadyAttempted || input.loopState === 'parked') {
        choices.push(humanDecisionChoice('attach_new_evidence', 'Attach New Evidence', 'run_evidence_probe', 'Collect a new deterministic artifact before allowing another model/code loop.', 'low', 'run_evidence_probe', 'The runner records a new artifact path or changed evidence hash, then re-evaluates the same gate.'));
    }
    if (/diagnosis|owner|scope|product_code|business|unknown/i.test("".concat(recoveryClass, " ").concat(failureClass))) {
        choices.push(humanDecisionChoice('revise_diagnosis', 'Revise Diagnosis', 'run_read_only_diagnosis', 'Run a read-only diagnosis revision to change owner files or proof plan with evidence.', 'low', 'run_read_only_diagnosis', 'The diagnosis gate is updated before any product-code repair is allowed.'));
    }
    if (/infra|compile/i.test("".concat(recoveryClass, " ").concat(failureClass))) {
        choices.push(humanDecisionChoice('repair_named_gate', /compile/i.test("".concat(recoveryClass, " ").concat(failureClass)) ? 'Repair Compile Gate' : 'Repair Infra Gate', /compile/i.test("".concat(recoveryClass, " ").concat(failureClass)) ? 'run_compile_repair' : 'run_infra_repair', 'Repair only the deterministic gate that failed; do not count this as product-code failure.', 'medium', /compile/i.test("".concat(recoveryClass, " ").concat(failureClass)) ? 'run_compile_repair' : 'run_infra_repair', 'The named infra/compile gate passes or returns a new blocker hash.', true));
    }
    if (/release/i.test("".concat(recoveryClass, " ").concat(failureClass))) {
        choices.push(humanDecisionChoice('record_hotfix_evidence', 'Record Hotfix Evidence', 'record_hotfix_evidence', 'Record commit, checksum, restart, health, and self-test proof before continuing release repair.', 'low', 'record_hotfix_evidence', 'Hotfix evidence validates and the runner reruns the smallest release gate.'));
    }
    choices.push(humanDecisionChoice('keep_parked', 'Keep Parked', 'park_manual', 'Leave the run parked until a human changes the evidence, scope, budget, or retry policy.', 'blocked', 'park_manual', 'No additional model, QA, repair, publish, or deploy work is queued.'));
    var dedupedChoices = choices.filter(function (choice, index, source) {
        return source.findIndex(function (candidate) { return candidate.choiceId === choice.choiceId; }) === index;
    }).slice(0, 4);
    return {
        requestId: stableHash('mgr-human', {
            checkpointId: checkpointId,
            evidenceHash: evidenceHash,
            blockerFingerprint: blockerFingerprint,
            choices: dedupedChoices.map(function (choice) { return choice.choiceId; })
        }),
        required: true,
        status: 'waiting_for_operator',
        reason: cleanText(input.reason || input.recommendedAction.reason, 1000),
        question: 'Choose the one evidence-backed action that should unblock this runner.',
        preferredChoiceId: ((_e = dedupedChoices[0]) === null || _e === void 0 ? void 0 : _e.choiceId) || 'keep_parked',
        evidence: baseEvidence,
        choices: dedupedChoices,
        blockedUntil: blockedUntil,
        createdAt: isoNow(input.updatedAt)
    };
}
function buildResolveIOAIManagerAutopilotSnapshot(input) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78;
    var dispatchAction = resolveDispatchAction(input);
    var directiveAllowed = input.recoveryDirective
        ? input.recoveryDirective.allowed === true
        : ((_a = input.recoveryAction) === null || _a === void 0 ? void 0 : _a.autoRunnable) === true;
    var evidenceOnly = ((_b = input.recoveryDirective) === null || _b === void 0 ? void 0 : _b.evidenceOnly) === true
        || ((_c = input.recoveryAction) === null || _c === void 0 ? void 0 : _c.evidenceOnly) === true
        || ((_d = input.recoveryEvidenceProbe) === null || _d === void 0 ? void 0 : _d.evidenceOnly) === true
        || ((_e = input.recoveryCheckpoint) === null || _e === void 0 ? void 0 : _e.status) === 'parked';
    var productRepairAllowed = ((_l = (_j = (_g = (_f = input.recoveryDirective) === null || _f === void 0 ? void 0 : _f.canRunProductRepair) !== null && _g !== void 0 ? _g : (_h = input.recoveryDirective) === null || _h === void 0 ? void 0 : _h.productRepairAllowed) !== null && _j !== void 0 ? _j : (_k = input.recoveryAction) === null || _k === void 0 ? void 0 : _k.productRepairAllowed) !== null && _l !== void 0 ? _l : (_m = input.recoveryCheckpoint) === null || _m === void 0 ? void 0 : _m.productRepairAllowed) === true;
    var expensiveModelAllowed = ((_t = (_r = (_p = (_o = input.recoveryDirective) === null || _o === void 0 ? void 0 : _o.canRunExpensiveModel) !== null && _p !== void 0 ? _p : (_q = input.recoveryDirective) === null || _q === void 0 ? void 0 : _q.expensiveModelAllowed) !== null && _r !== void 0 ? _r : (_s = input.recoveryAction) === null || _s === void 0 ? void 0 : _s.expensiveModelAllowed) !== null && _t !== void 0 ? _t : (_u = input.recoveryCheckpoint) === null || _u === void 0 ? void 0 : _u.expensiveModelAllowed) === true;
    var requiresNewEvidence = ((_v = input.recoveryDirective) === null || _v === void 0 ? void 0 : _v.requiresNewEvidence) === true
        || ((_x = (_w = input.recoveryAction) === null || _w === void 0 ? void 0 : _w.retryPolicy) === null || _x === void 0 ? void 0 : _x.requireNewEvidence) === true
        || ((_y = input.recoveryCheckpoint) === null || _y === void 0 ? void 0 : _y.status) === 'parked';
    var sameEvidenceDispatchCount = countSameEvidenceDispatches(input, dispatchAction);
    var sameEvidenceAlreadyAttempted = requiresNewEvidence && sameEvidenceDispatchCount > 0 && ((_z = input.recoveryDirective) === null || _z === void 0 ? void 0 : _z.newEvidence) !== true;
    var checkpointStatus = cleanText((_0 = input.recoveryCheckpoint) === null || _0 === void 0 ? void 0 : _0.status, 80);
    var evidenceAssessment = input.recoveryCheckpoint && input.current
        ? (0, ai_runner_manager_policy_1.assessResolveIOAIManagerEvidenceChange)(input.recoveryCheckpoint, input.current, input.recoveryCheckpoint.objective)
        : {
            changed: false,
            material: false,
            strength: 'none',
            signals: []
        };
    var loopState = checkpointStatus === 'manual_handoff'
        ? 'manual_handoff'
        : checkpointStatus === 'complete'
            ? 'complete'
            : sameEvidenceAlreadyAttempted || ((_1 = input.recoveryDirective) === null || _1 === void 0 ? void 0 : _1.allowed) === false
                ? 'parked'
                : evidenceOnly && requiresNewEvidence
                    ? 'collecting_evidence'
                    : 'clear';
    var enabled = directiveAllowed && !sameEvidenceAlreadyAttempted && loopState !== 'manual_handoff';
    var recommendedAction = sameEvidenceAlreadyAttempted || ((_2 = input.recoveryDirective) === null || _2 === void 0 ? void 0 : _2.allowed) === false
        ? 'park_manual'
        : dispatchAction;
    var label = cleanText(sameEvidenceAlreadyAttempted
        ? 'Attach New Evidence'
        : ((_3 = input.recoveryDirective) === null || _3 === void 0 ? void 0 : _3.nextActionLabel) || ((_4 = input.recoveryAction) === null || _4 === void 0 ? void 0 : _4.label) || defaultLabelForAction(recommendedAction), 140);
    var reason = cleanText(sameEvidenceAlreadyAttempted
        ? 'The same recovery action already ran against the same evidence; a new artifact path or changed evidence hash is required.'
        : ((_5 = input.recoveryDirective) === null || _5 === void 0 ? void 0 : _5.reason) || ((_6 = input.recoveryAction) === null || _6 === void 0 ? void 0 : _6.blockedReason) || ((_7 = input.recoveryPlan) === null || _7 === void 0 ? void 0 : _7.objective) || ((_8 = input.current) === null || _8 === void 0 ? void 0 : _8.blocker) || 'Manager can continue the current gate.', 1000);
    var canResetLoopAfterEvidence = ((_9 = input.recoveryDirective) === null || _9 === void 0 ? void 0 : _9.canResetLoopAfterEvidence) === true
        || ((_10 = input.recoveryAction) === null || _10 === void 0 ? void 0 : _10.canResetLoopAfterEvidence) === true
        || cleanList((_11 = input.recoveryCheckpoint) === null || _11 === void 0 ? void 0 : _11.loopResetEvidence, 20, 500).length > 0;
    var resetRequires = cleanList(((_14 = (_13 = (_12 = input.recoveryAction) === null || _12 === void 0 ? void 0 : _12.retryPolicy) === null || _13 === void 0 ? void 0 : _13.resetLoopWhen) === null || _14 === void 0 ? void 0 : _14.length)
        ? input.recoveryAction.retryPolicy.resetLoopWhen
        : (_15 = input.recoveryCheckpoint) === null || _15 === void 0 ? void 0 : _15.loopResetEvidence, 20, 500);
    var recoveryRequiredArtifacts = cleanList(((_17 = (_16 = input.recoveryDirective) === null || _16 === void 0 ? void 0 : _16.requiredArtifacts) === null || _17 === void 0 ? void 0 : _17.length) ? input.recoveryDirective.requiredArtifacts : (_18 = input.recoveryAction) === null || _18 === void 0 ? void 0 : _18.requiredArtifacts, 20, 500);
    var recoveryForbiddenActions = cleanList(((_20 = (_19 = input.recoveryDirective) === null || _19 === void 0 ? void 0 : _19.forbiddenActions) === null || _20 === void 0 ? void 0 : _20.length) ? input.recoveryDirective.forbiddenActions : (_22 = (_21 = input.recoveryAction) === null || _21 === void 0 ? void 0 : _21.retryPolicy) === null || _22 === void 0 ? void 0 : _22.stopWhen, 20, 500);
    var singleActionOnly = ((_23 = input.recoveryDirective) === null || _23 === void 0 ? void 0 : _23.singleActionOnly) !== false && ((_24 = input.recoveryAction) === null || _24 === void 0 ? void 0 : _24.singleActionOnly) !== false;
    var allowedDispatchAction = cleanText(((_25 = input.recoveryDirective) === null || _25 === void 0 ? void 0 : _25.allowedDispatchAction) || ((_26 = input.recoveryAction) === null || _26 === void 0 ? void 0 : _26.allowedDispatchAction) || dispatchAction, 120);
    var costCeilingUsd = cleanNumber(((_27 = input.recoveryDirective) === null || _27 === void 0 ? void 0 : _27.costCeilingUsd) || ((_28 = input.recoveryAction) === null || _28 === void 0 ? void 0 : _28.costCeilingUsd));
    var requiredStateTransition = cleanText(((_29 = input.recoveryDirective) === null || _29 === void 0 ? void 0 : _29.requiredStateTransition) || ((_30 = input.recoveryAction) === null || _30 === void 0 ? void 0 : _30.requiredStateTransition), 500);
    var proofRequiredBeforeContinuation = ((_31 = input.recoveryDirective) === null || _31 === void 0 ? void 0 : _31.proofRequiredBeforeContinuation) === true || ((_32 = input.recoveryAction) === null || _32 === void 0 ? void 0 : _32.proofRequiredBeforeContinuation) === true;
    var exitCriteria = cleanList(((_34 = (_33 = input.recoveryDirective) === null || _33 === void 0 ? void 0 : _33.exitCriteria) === null || _34 === void 0 ? void 0 : _34.length) ? input.recoveryDirective.exitCriteria : (_35 = input.recoveryAction) === null || _35 === void 0 ? void 0 : _35.exitCriteria, 30, 500);
    var currentRunUsd = cleanNumber(input.currentRunUsd);
    var totalUsd = cleanNumber(input.totalUsd);
    var autonomyPolicy = (0, ai_runner_manager_policy_1.decideResolveIOAIManagerAutonomyPolicy)(__assign(__assign({}, (input.autonomyPolicy || {})), { currentSpendUsd: (_37 = (_36 = input.autonomyPolicy) === null || _36 === void 0 ? void 0 : _36.currentSpendUsd) !== null && _37 !== void 0 ? _37 : totalUsd, projectedActionCostUsd: (_39 = (_38 = input.autonomyPolicy) === null || _38 === void 0 ? void 0 : _38.projectedActionCostUsd) !== null && _39 !== void 0 ? _39 : costCeilingUsd, dispatchAction: dispatchAction, newEvidence: (_41 = (_40 = input.autonomyPolicy) === null || _40 === void 0 ? void 0 : _40.newEvidence) !== null && _41 !== void 0 ? _41 : evidenceAssessment.changed, materialEvidence: (_43 = (_42 = input.autonomyPolicy) === null || _42 === void 0 ? void 0 : _42.materialEvidence) !== null && _43 !== void 0 ? _43 : evidenceAssessment.material, evidenceStrength: (_45 = (_44 = input.autonomyPolicy) === null || _44 === void 0 ? void 0 : _44.evidenceStrength) !== null && _45 !== void 0 ? _45 : evidenceAssessment.strength, evidenceSignals: (_47 = (_46 = input.autonomyPolicy) === null || _46 === void 0 ? void 0 : _46.evidenceSignals) !== null && _47 !== void 0 ? _47 : evidenceAssessment.signals, sameEvidenceAlreadyAttempted: (_49 = (_48 = input.autonomyPolicy) === null || _48 === void 0 ? void 0 : _48.sameEvidenceAlreadyAttempted) !== null && _49 !== void 0 ? _49 : sameEvidenceAlreadyAttempted }));
    var recentDispatches = normalizeRecentDispatches(input.recoveryDispatchHistory);
    var recommendedActionPacket = {
        action: recommendedAction,
        label: label,
        reason: reason,
        safety: safetyFor({
            action: recommendedAction,
            enabled: enabled,
            evidenceOnly: evidenceOnly,
            productRepairAllowed: productRepairAllowed,
            expensiveModelAllowed: expensiveModelAllowed
        }),
        enabled: enabled,
        autoRunnable: enabled && ((_50 = input.recoveryAction) === null || _50 === void 0 ? void 0 : _50.autoRunnable) !== false && autonomyPolicy.canAutoDispatch === true,
        expectedResult: expectedResultForAction(recommendedAction, evidenceOnly),
        requiresNewEvidence: requiresNewEvidence,
        canRunProductRepair: enabled && productRepairAllowed,
        canRunExpensiveModel: enabled && expensiveModelAllowed,
        canResetLoopAfterEvidence: canResetLoopAfterEvidence,
        singleActionOnly: singleActionOnly,
        allowedDispatchAction: allowedDispatchAction,
        costCeilingUsd: costCeilingUsd,
        requiredStateTransition: requiredStateTransition,
        proofRequiredBeforeContinuation: proofRequiredBeforeContinuation,
        autonomyMode: autonomyPolicy.mode,
        autonomyCanAutoDispatch: autonomyPolicy.canAutoDispatch,
        autonomyBlocked: autonomyPolicy.blocked,
        expectedValueScore: autonomyPolicy.expectedValueScore,
        expectedValueSource: autonomyPolicy.expectedValueSource,
        expectedValuePositive: autonomyPolicy.expectedValuePositive,
        evidenceBacked: autonomyPolicy.evidenceBacked,
        evidenceStrength: autonomyPolicy.evidenceStrength,
        dispatchAction: dispatchAction
    };
    var humanDecision = buildHumanDecisionRequest({
        snapshot: input,
        recommendedAction: recommendedActionPacket,
        loopState: loopState,
        reason: reason,
        dispatchAction: dispatchAction,
        sameEvidenceAlreadyAttempted: sameEvidenceAlreadyAttempted,
        requiresNewEvidence: requiresNewEvidence,
        requiredArtifacts: recoveryRequiredArtifacts,
        forbiddenActions: recoveryForbiddenActions,
        recentDispatches: recentDispatches,
        updatedAt: input.updatedAt
    });
    var untrackedWarning = cleanText(input.untrackedCostWarning || 'Manual Codex sessions outside this runner are not included unless recorded in the usage ledger.', 500);
    var controlPolicy = buildControlPolicy({
        recommendedAction: recommendedActionPacket,
        autonomyPolicy: autonomyPolicy,
        humanDecision: humanDecision,
        recoveryRequiredArtifacts: recoveryRequiredArtifacts,
        recoveryForbiddenActions: recoveryForbiddenActions,
        currentRunUsd: currentRunUsd,
        totalUsd: totalUsd,
        untrackedWarning: untrackedWarning
    });
    return {
        surface: cleanText(input.surface || 'unknown', 120),
        runId: cleanText(input.runId, 160),
        title: cleanText(input.title, 240),
        status: cleanText(input.status || ((_51 = input.recoveryCheckpoint) === null || _51 === void 0 ? void 0 : _51.status), 80),
        phase: cleanText(input.phase || ((_52 = input.recoveryDirective) === null || _52 === void 0 ? void 0 : _52.phase), 80),
        lane: cleanText(input.lane || ((_53 = input.recoveryDirective) === null || _53 === void 0 ? void 0 : _53.lane) || ((_54 = input.recoveryCheckpoint) === null || _54 === void 0 ? void 0 : _54.lane) || ((_55 = input.current) === null || _55 === void 0 ? void 0 : _55.lane), 120),
        stepType: cleanText(input.stepType || ((_56 = input.recoveryDirective) === null || _56 === void 0 ? void 0 : _56.stepType) || ((_57 = input.recoveryCheckpoint) === null || _57 === void 0 ? void 0 : _57.stepType) || ((_58 = input.current) === null || _58 === void 0 ? void 0 : _58.stepType), 120),
        runKind: cleanText(input.runKind, 120),
        recommendedAction: recommendedActionPacket,
        controlPolicy: controlPolicy,
        loopGuard: {
            state: loopState,
            blocked: loopState === 'parked' || loopState === 'manual_handoff',
            reason: reason,
            failureClass: cleanText((_59 = input.current) === null || _59 === void 0 ? void 0 : _59.failureClass, 120),
            blocker: cleanText(((_60 = input.current) === null || _60 === void 0 ? void 0 : _60.blocker) || ((_61 = input.current) === null || _61 === void 0 ? void 0 : _61.summary), 1000),
            blockerFingerprint: cleanText(((_62 = input.current) === null || _62 === void 0 ? void 0 : _62.blockerFingerprint) || ((_63 = input.recoveryCheckpoint) === null || _63 === void 0 ? void 0 : _63.blockerFingerprint), 160),
            evidenceHash: cleanText(((_64 = input.current) === null || _64 === void 0 ? void 0 : _64.evidenceHash) || ((_65 = input.recoveryCheckpoint) === null || _65 === void 0 ? void 0 : _65.evidenceHash), 160),
            materialEvidence: evidenceAssessment.material === true,
            evidenceStrength: cleanText(evidenceAssessment.strength, 40),
            evidenceSignals: cleanList(evidenceAssessment.signals, 12, 120),
            sameEvidenceDispatchCount: sameEvidenceDispatchCount,
            sameEvidenceAlreadyAttempted: sameEvidenceAlreadyAttempted,
            loopCount: cleanNumber(input.loopCount),
            maxLoopCount: cleanNumber(input.maxLoopCount),
            attempts: cleanNumber((_66 = input.recoveryCheckpoint) === null || _66 === void 0 ? void 0 : _66.attempts),
            maxAttemptsBeforePark: cleanNumber((_67 = input.recoveryCheckpoint) === null || _67 === void 0 ? void 0 : _67.maxAttemptsBeforePark),
            canResetLoopAfterEvidence: canResetLoopAfterEvidence,
            resetRequires: resetRequires
        },
        recovery: {
            checkpointId: cleanText(((_68 = input.recoveryCheckpoint) === null || _68 === void 0 ? void 0 : _68.checkpointId) || ((_69 = input.recoveryAction) === null || _69 === void 0 ? void 0 : _69.checkpointId), 160),
            recoveryClass: cleanText(((_70 = input.recoveryCheckpoint) === null || _70 === void 0 ? void 0 : _70.recoveryClass) || ((_71 = input.recoveryAction) === null || _71 === void 0 ? void 0 : _71.recoveryClass) || ((_72 = input.recoveryPlan) === null || _72 === void 0 ? void 0 : _72.recoveryClass), 120),
            dispatchAction: dispatchAction,
            singleActionOnly: singleActionOnly,
            allowedDispatchAction: allowedDispatchAction,
            directiveAllowed: directiveAllowed,
            evidenceOnly: evidenceOnly,
            productRepairAllowed: productRepairAllowed,
            expensiveModelAllowed: expensiveModelAllowed,
            costCeilingUsd: costCeilingUsd,
            requiredStateTransition: requiredStateTransition,
            proofRequiredBeforeContinuation: proofRequiredBeforeContinuation,
            requiredArtifacts: recoveryRequiredArtifacts,
            nextCommands: cleanList(((_74 = (_73 = input.recoveryDirective) === null || _73 === void 0 ? void 0 : _73.nextCommands) === null || _74 === void 0 ? void 0 : _74.length) ? input.recoveryDirective.nextCommands : (_75 = input.recoveryAction) === null || _75 === void 0 ? void 0 : _75.nextCommands, 20, 500),
            successCriteria: cleanList(((_77 = (_76 = input.recoveryDirective) === null || _76 === void 0 ? void 0 : _76.successCriteria) === null || _77 === void 0 ? void 0 : _77.length) ? input.recoveryDirective.successCriteria : (_78 = input.recoveryAction) === null || _78 === void 0 ? void 0 : _78.successCriteria, 20, 500),
            exitCriteria: exitCriteria,
            forbiddenActions: recoveryForbiddenActions
        },
        autonomyPolicy: autonomyPolicy,
        recentDispatches: recentDispatches,
        humanDecision: humanDecision,
        cost: {
            currentRunUsd: currentRunUsd,
            totalUsd: totalUsd,
            currentRunTokens: cleanNumber(input.currentRunTokens),
            totalTokens: cleanNumber(input.totalTokens),
            untrackedWarning: untrackedWarning
        },
        updatedAt: isoNow(input.updatedAt)
    };
}

//# sourceMappingURL=ai-runner-manager-autopilot.js.map
