"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.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCumulativeCodexUsageEntry = isCumulativeCodexUsageEntry;
exports.resolveOpenAIUsageThreadKey = resolveOpenAIUsageThreadKey;
exports.normalizeOpenAIUsageRowsForCosting = normalizeOpenAIUsageRowsForCosting;
exports.buildAIQaRun = buildAIQaRun;
exports.classifyAIRunOutcome = classifyAIRunOutcome;
exports.buildAIRun = buildAIRun;
exports.buildAIRunCost = buildAIRunCost;
exports.redactAIRunTrainingExample = redactAIRunTrainingExample;
function isoNow(value) {
    if (value instanceof Date) {
        return value.toISOString();
    }
    var parsed = value ? new Date(value) : new Date();
    if (Number.isFinite(parsed.getTime())) {
        return parsed.toISOString();
    }
    return new Date().toISOString();
}
function cleanText(value, max) {
    if (max === void 0) { max = 1000; }
    return String(value || '').replace(/\s+/g, ' ').trim().slice(0, max);
}
function cleanUsageNumber(value) {
    var parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : 0;
}
function cleanUsageDate(value) {
    if (!value) {
        return undefined;
    }
    var date = value instanceof Date ? value : new Date(value);
    return Number.isFinite(date.getTime()) ? date : undefined;
}
function isCumulativeCodexUsageEntry(entry) {
    return cleanText(entry === null || entry === void 0 ? void 0 : entry.category, 180).toLowerCase().startsWith('ai-dashboard-codex:');
}
function resolveOpenAIUsageThreadKey(entry) {
    var _a, _b;
    var conversationId = cleanText((_a = entry === null || entry === void 0 ? void 0 : entry.id_conversation) !== null && _a !== void 0 ? _a : entry === null || entry === void 0 ? void 0 : entry.idConversation, 240);
    if (conversationId) {
        return conversationId;
    }
    return cleanText((_b = entry === null || entry === void 0 ? void 0 : entry.id_request) !== null && _b !== void 0 ? _b : entry === null || entry === void 0 ? void 0 : entry.idRequest, 240);
}
function normalizeOpenAIUsageRowsForCosting(rows) {
    if (rows === void 0) { rows = []; }
    if (!Array.isArray(rows) || !rows.length) {
        return [];
    }
    var sortedRows = rows
        .map(function (row, index) { return (__assign(__assign({}, row), { _sortIndex: index })); })
        .sort(function (a, b) {
        var _a, _b, _c, _d, _e, _f;
        var timeA = ((_a = cleanUsageDate(a.timestamp)) === null || _a === void 0 ? void 0 : _a.getTime()) || 0;
        var timeB = ((_b = cleanUsageDate(b.timestamp)) === null || _b === void 0 ? void 0 : _b.getTime()) || 0;
        if (timeA !== timeB) {
            return timeA - timeB;
        }
        var requestCompare = cleanText((_c = a.id_request) !== null && _c !== void 0 ? _c : a.idRequest, 240)
            .localeCompare(cleanText((_d = b.id_request) !== null && _d !== void 0 ? _d : b.idRequest, 240));
        if (requestCompare) {
            return requestCompare;
        }
        var conversationCompare = cleanText((_e = a.id_conversation) !== null && _e !== void 0 ? _e : a.idConversation, 240)
            .localeCompare(cleanText((_f = b.id_conversation) !== null && _f !== void 0 ? _f : b.idConversation, 240));
        if (conversationCompare) {
            return conversationCompare;
        }
        return cleanUsageNumber(a._sortIndex) - cleanUsageNumber(b._sortIndex);
    });
    var previousByThread = new Map();
    return sortedRows.map(function (row) {
        var _a, _b, _c, _d, _e, _f;
        var inputTokens = cleanUsageNumber((_a = row.input_tokens) !== null && _a !== void 0 ? _a : row.inputTokens);
        var cachedInputTokens = cleanUsageNumber((_b = row.cached_input_tokens) !== null && _b !== void 0 ? _b : row.cachedInputTokens);
        var outputTokens = cleanUsageNumber((_c = row.output_tokens) !== null && _c !== void 0 ? _c : row.outputTokens);
        var totalTokens = cleanUsageNumber((_e = (_d = row.total_tokens) !== null && _d !== void 0 ? _d : row.totalTokens) !== null && _e !== void 0 ? _e : (inputTokens + outputTokens));
        var estimatedUsd = cleanUsageNumber((_f = row.cost_estimate) !== null && _f !== void 0 ? _f : row.estimatedUsd);
        var threadKey = isCumulativeCodexUsageEntry(row) ? resolveOpenAIUsageThreadKey(row) : '';
        var normalizedInputTokens = inputTokens;
        var normalizedCachedInputTokens = cachedInputTokens;
        var normalizedOutputTokens = outputTokens;
        var normalizedTotalTokens = totalTokens;
        var normalizedEstimatedUsd = estimatedUsd;
        if (threadKey) {
            var previous = previousByThread.get(threadKey);
            if (previous
                && inputTokens >= previous.inputTokens
                && cachedInputTokens >= previous.cachedInputTokens
                && outputTokens >= previous.outputTokens
                && totalTokens >= previous.totalTokens
                && estimatedUsd >= previous.estimatedUsd) {
                normalizedInputTokens = Math.max(0, inputTokens - previous.inputTokens);
                normalizedCachedInputTokens = Math.max(0, cachedInputTokens - previous.cachedInputTokens);
                normalizedOutputTokens = Math.max(0, outputTokens - previous.outputTokens);
                normalizedTotalTokens = Math.max(0, totalTokens - previous.totalTokens);
                normalizedEstimatedUsd = Math.max(0, estimatedUsd - previous.estimatedUsd);
            }
            previousByThread.set(threadKey, {
                inputTokens: inputTokens,
                cachedInputTokens: cachedInputTokens,
                outputTokens: outputTokens,
                totalTokens: totalTokens,
                estimatedUsd: estimatedUsd
            });
        }
        var resolvedTotalTokens = normalizedTotalTokens || (normalizedInputTokens + normalizedOutputTokens);
        var resolvedEstimatedUsd = Number(normalizedEstimatedUsd.toFixed(6));
        return __assign(__assign({}, row), { input_tokens: normalizedInputTokens, inputTokens: normalizedInputTokens, cached_input_tokens: normalizedCachedInputTokens, cachedInputTokens: normalizedCachedInputTokens, output_tokens: normalizedOutputTokens, outputTokens: normalizedOutputTokens, total_tokens: resolvedTotalTokens, totalTokens: resolvedTotalTokens, cost_estimate: resolvedEstimatedUsd, estimatedUsd: resolvedEstimatedUsd });
    });
}
function cleanList(values, limit, max) {
    var e_1, _a;
    if (limit === void 0) { limit = 20; }
    if (max === void 0) { max = 500; }
    if (!Array.isArray(values)) {
        return [];
    }
    var result = [];
    try {
        for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
            var value = values_1_1.value;
            var normalized = cleanText(value, max);
            if (normalized && !result.includes(normalized)) {
                result.push(normalized);
            }
            if (result.length >= limit) {
                break;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return result;
}
function normalizeCheckStatus(value) {
    var normalized = cleanText(value, 40).toLowerCase().replace(/[_\s-]+/g, '_');
    if (normalized === 'passed' || normalized === 'ok' || normalized === 'ready') {
        return 'pass';
    }
    if (normalized === 'failed' || normalized === 'error' || normalized === 'fail') {
        return 'fail';
    }
    if (normalized === 'blocked' || normalized === 'dependency_blocked') {
        return 'blocked';
    }
    if (normalized === 'warning') {
        return 'warn';
    }
    if (normalized === 'skipped' || normalized === 'not_applicable') {
        return 'skipped';
    }
    return normalized === 'pass' || normalized === 'warn' ? normalized : 'unknown';
}
function normalizeCompileStatus(value) {
    var normalized = cleanText(value, 40).toLowerCase().replace(/[_\s-]+/g, '_');
    if (normalized === 'passed' || normalized === 'ok') {
        return 'pass';
    }
    if (normalized === 'failed' || normalized === 'error') {
        return 'fail';
    }
    if (normalized === 'blocked') {
        return 'blocked';
    }
    if (normalized === 'stale' || normalized === 'stale_evidence') {
        return 'stale';
    }
    if (normalized === 'skipped' || normalized === 'not_applicable') {
        return 'skipped';
    }
    return normalized === 'pass' || normalized === 'fail' ? normalized : 'unknown';
}
function makeGate(key, label, status, reason, evidenceRefs, now, metadata) {
    if (evidenceRefs === void 0) { evidenceRefs = []; }
    return __assign({ key: key, label: label, status: status, reason: cleanText(reason, 1400), evidenceRefs: cleanList(evidenceRefs, 20, 500), recordedAt: isoNow(now) }, (metadata ? { metadata: metadata } : {}));
}
function failedOrBlocked(status) {
    return status === 'fail' || status === 'blocked';
}
function passed(status) {
    return status === 'pass';
}
function normalizeInfraChecks(values) {
    return (Array.isArray(values) ? values : []).map(function (entry) { return (__assign(__assign({}, entry), { name: cleanText(entry === null || entry === void 0 ? void 0 : entry.name, 120) || 'infra_check', status: normalizeCheckStatus(entry === null || entry === void 0 ? void 0 : entry.status), message: cleanText(entry === null || entry === void 0 ? void 0 : entry.message, 1000), path: cleanText(entry === null || entry === void 0 ? void 0 : entry.path, 500) })); });
}
function normalizeRouteProbes(values) {
    return (Array.isArray(values) ? values : []).map(function (entry) { return (__assign(__assign({}, entry), { route: cleanText(entry === null || entry === void 0 ? void 0 : entry.route, 500) || '/', status: normalizeCheckStatus(entry === null || entry === void 0 ? void 0 : entry.status), screenshot: cleanText(entry === null || entry === void 0 ? void 0 : entry.screenshot, 500), caption: cleanText(entry === null || entry === void 0 ? void 0 : entry.caption, 1000), message: cleanText(entry === null || entry === void 0 ? void 0 : entry.message, 1000), consoleErrors: cleanList(entry === null || entry === void 0 ? void 0 : entry.consoleErrors, 30, 500), networkErrors: cleanList(entry === null || entry === void 0 ? void 0 : entry.networkErrors, 30, 500) })); });
}
function normalizeBusinessAssertions(values) {
    return (Array.isArray(values) ? values : []).map(function (entry) { return (__assign(__assign({}, entry), { assertion: cleanText(entry === null || entry === void 0 ? void 0 : entry.assertion, 1000) || 'business assertion', status: normalizeCheckStatus(entry === null || entry === void 0 ? void 0 : entry.status), workflow: cleanText(entry === null || entry === void 0 ? void 0 : entry.workflow, 400), route: cleanText(entry === null || entry === void 0 ? void 0 : entry.route, 500), action: cleanText(entry === null || entry === void 0 ? void 0 : entry.action, 500), expected: cleanText(entry === null || entry === void 0 ? void 0 : entry.expected, 1000), observed: cleanText(entry === null || entry === void 0 ? void 0 : entry.observed, 1000), dataProof: cleanText(entry === null || entry === void 0 ? void 0 : entry.dataProof, 1400), artifactPaths: cleanList(entry === null || entry === void 0 ? void 0 : entry.artifactPaths, 30, 500), message: cleanText(entry === null || entry === void 0 ? void 0 : entry.message, 1000) })); });
}
function collectBusinessAssertionArtifactPaths(assertions) {
    var e_2, _a, e_3, _b;
    var paths = [];
    try {
        for (var assertions_1 = __values(assertions), assertions_1_1 = assertions_1.next(); !assertions_1_1.done; assertions_1_1 = assertions_1.next()) {
            var assertion = assertions_1_1.value;
            try {
                for (var _c = (e_3 = void 0, __values(assertion.artifactPaths || [])), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var artifactPath = _d.value;
                    if (artifactPath && !paths.includes(artifactPath)) {
                        paths.push(artifactPath);
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                }
                finally { if (e_3) throw e_3.error; }
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (assertions_1_1 && !assertions_1_1.done && (_a = assertions_1.return)) _a.call(assertions_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return paths;
}
function buildAIQaRun(input) {
    if (input === void 0) { input = {}; }
    var now = isoNow(input.now);
    var infraChecks = normalizeInfraChecks(input.infraChecks);
    var compile = input.compile
        ? __assign(__assign({}, input.compile), { status: normalizeCompileStatus(input.compile.status), command: cleanText(input.compile.command, 500), artifactPath: cleanText(input.compile.artifactPath, 500), message: cleanText(input.compile.message, 1000) }) : undefined;
    var routeProbes = normalizeRouteProbes(input.routeProbes);
    var businessAssertions = normalizeBusinessAssertions(input.businessAssertions);
    var artifacts = Array.isArray(input.artifacts) ? input.artifacts : [];
    var gateResults = [];
    var failedInfra = infraChecks.filter(function (check) { return failedOrBlocked(check.status); });
    if (failedInfra.length) {
        gateResults.push(makeGate('qa_infra', 'QA infrastructure', 'blocked', "QA infrastructure failed before model/business validation: ".concat(failedInfra.map(function (check) { return "".concat(check.name, ": ").concat(check.message || check.status); }).join('; ')), failedInfra.map(function (check) { return check.path || ''; }).filter(Boolean), now, { failed_checks: failedInfra.map(function (check) { return check.name; }) }));
        return { outcome: 'infra_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
    }
    if (infraChecks.length) {
        gateResults.push(makeGate('qa_infra', 'QA infrastructure', 'pass', 'QA infrastructure preflight checks passed.', [], now));
    }
    if (compile && (failedOrBlocked(compile.status) || compile.status === 'stale' || compile.staleEvidence === true)) {
        gateResults.push(makeGate('qa_compile', 'Compile/build', 'fail', compile.status === 'stale' || compile.staleEvidence === true
            ? 'Compile/build evidence is stale and cannot be used for acceptance.'
            : (compile.message || 'Compile/build failed before browser QA.'), compile.artifactPath ? [compile.artifactPath] : [], now, { command: compile.command || '' }));
        return { outcome: 'compile_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
    }
    if (compile && passed(compile.status)) {
        gateResults.push(makeGate('qa_compile', 'Compile/build', 'pass', 'Compile/build evidence passed.', compile.artifactPath ? [compile.artifactPath] : [], now));
    }
    var failedRouteProbes = routeProbes.filter(function (probe) { return failedOrBlocked(probe.status) || probe.shellOnly === true; });
    if (failedRouteProbes.length) {
        gateResults.push(makeGate('qa_route_probe', 'Browser route probe', 'fail', "Browser route probe failed or showed shell-only UI: ".concat(failedRouteProbes.map(function (probe) { return "".concat(probe.route, ": ").concat(probe.message || probe.caption || probe.status); }).join('; ')), failedRouteProbes.map(function (probe) { return probe.screenshot || ''; }).filter(Boolean), now));
        return { outcome: 'route_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
    }
    if (routeProbes.some(function (probe) { return passed(probe.status); })) {
        gateResults.push(makeGate('qa_route_probe', 'Browser route probe', 'pass', 'Browser route reached authenticated application content. This is not business acceptance by itself.', routeProbes.map(function (probe) { return probe.screenshot || ''; }).filter(Boolean), now));
    }
    var failedBusinessAssertions = businessAssertions.filter(function (assertion) { return failedOrBlocked(assertion.status); });
    if (failedBusinessAssertions.length) {
        gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'fail', "Issue-specific workflow assertion failed: ".concat(failedBusinessAssertions.map(function (assertion) { return assertion.message || assertion.observed || assertion.assertion; }).join('; ')), collectBusinessAssertionArtifactPaths(failedBusinessAssertions), now));
        return { outcome: 'business_assertion_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
    }
    var passedBusinessAssertions = businessAssertions.filter(function (assertion) { return passed(assertion.status); });
    if (passedBusinessAssertions.length) {
        gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'pass', 'At least one issue-specific workflow/data assertion passed.', collectBusinessAssertionArtifactPaths(passedBusinessAssertions), now, { passed_assertions: passedBusinessAssertions.map(function (assertion) { return assertion.assertion; }) }));
        return { outcome: 'business_assertion_passed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
    }
    if (routeProbes.some(function (probe) { return passed(probe.status); })) {
        gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'blocked', 'Browser route loaded, but no issue-specific business assertion passed. Route-only proof cannot accept the run.', [], now));
        return { outcome: 'route_only_pass', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
    }
    gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'blocked', 'No issue-specific QA assertion was recorded.', [], now));
    return { outcome: 'incomplete', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
}
function normalizeQaRun(input) {
    if (!input) {
        return undefined;
    }
    if (input.outcome && Array.isArray(input.gateResults)) {
        return input;
    }
    return buildAIQaRun(input);
}
function statusLooksFailed(value) {
    var normalized = cleanText(value, 120).toLowerCase();
    return !!normalized && /(fail|failed|error|blocked|missing|empty|stale|skipped|not ready|not_ready|could not|cannot)/i.test(normalized);
}
function statusLooksPassed(value) {
    var normalized = cleanText(value, 120).toLowerCase();
    return !!normalized && /(pass|passed|success|complete|completed|ready|published|deployed|live|merged)/i.test(normalized);
}
function addGateOnce(gates, gate) {
    if (gates.some(function (entry) { return entry.key === gate.key && entry.status === gate.status && entry.reason === gate.reason; })) {
        return;
    }
    gates.push(gate);
}
function classifyAIRunOutcome(input) {
    var e_4, _a;
    var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
    if (input === void 0) { input = {}; }
    var now = isoNow(input.now);
    var gates = Array.isArray(input.gates) ? __spreadArray([], __read(input.gates), false) : [];
    var warnings = [];
    var qa = normalizeQaRun(input.qa);
    if (qa) {
        try {
            for (var _z = __values(qa.gateResults), _0 = _z.next(); !_0.done; _0 = _z.next()) {
                var gate = _0.value;
                addGateOnce(gates, gate);
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_0 && !_0.done && (_a = _z.return)) _a.call(_z);
            }
            finally { if (e_4) throw e_4.error; }
        }
    }
    var supportParkedByStatus = input.source === 'support_ticket'
        && (input.manualHandoff === true || input.stopped === true || /stop|stopped|cancel|cancelled|paused|handoff/i.test("".concat(input.status || '', " ").concat(input.phase || '')));
    if (supportParkedByStatus) {
        var blockedSupportAutoloopNoProgressGate_1 = gates.find(function (gate) { return gate.key === 'support_autoloop_no_progress' && gate.status === 'blocked'; });
        if (blockedSupportAutoloopNoProgressGate_1) {
            return {
                outcome: 'manual_handoff',
                reason: "Support autoloop parked before another repair loop because no new evidence was recorded: ".concat(blockedSupportAutoloopNoProgressGate_1.reason),
                nextAction: 'Collect new material evidence, rerun read-only diagnosis or issue-class proof, then resume only if the blocker fingerprint changes.',
                gates: gates,
                warnings: warnings,
                recordedAt: now
            };
        }
        var blockedSupportAutoloopApprovalGate_1 = gates.find(function (gate) { return gate.key === 'support_autoloop_approval_block' && gate.status === 'blocked'; });
        if (blockedSupportAutoloopApprovalGate_1) {
            var nextAction = cleanText((_b = blockedSupportAutoloopApprovalGate_1.metadata) === null || _b === void 0 ? void 0 : _b.nextAction, 160)
                || cleanText((_c = blockedSupportAutoloopApprovalGate_1.metadata) === null || _c === void 0 ? void 0 : _c.action, 160);
            var elapsedReapproval = ((_d = blockedSupportAutoloopApprovalGate_1.metadata) === null || _d === void 0 ? void 0 : _d.requiresElapsedReapproval) === true;
            return {
                outcome: 'manual_handoff',
                reason: "Support autoloop parked before another repair loop because approval/scope is blocked: ".concat(blockedSupportAutoloopApprovalGate_1.reason),
                nextAction: elapsedReapproval
                    ? 'Approve continued runtime beyond the current wall-clock boundary or park the ticket for manual review; do not run another model/code/QA continuation until that decision is recorded.'
                    : nextAction
                        ? "Run ".concat(nextAction, " or revise the blocked scope, then resume the approved autoloop toward A-grade QA/business proof.")
                        : 'Approve the blocked support autonomy scope or revise the diagnosis, owner files, planned change, estimate, or classification before the autoloop continues.',
                gates: gates,
                warnings: warnings,
                recordedAt: now
            };
        }
        var blockedSupportAutonomyApprovalGate_1 = gates.find(function (gate) { return gate.key === 'support_autonomy_approval' && gate.status === 'blocked'; });
        if (blockedSupportAutonomyApprovalGate_1) {
            return {
                outcome: 'manual_handoff',
                reason: "Support autonomy is waiting on operator approval or revised intake/diagnosis scope: ".concat(blockedSupportAutonomyApprovalGate_1.reason),
                nextAction: ((_e = blockedSupportAutonomyApprovalGate_1.metadata) === null || _e === void 0 ? void 0 : _e.approvalAction)
                    ? "Use ".concat(blockedSupportAutonomyApprovalGate_1.metadata.approvalAction, " or revise the blocked scope, then allow the runner to continue until A-grade QA/business proof.")
                    : 'Approve the bounded support autonomy request or revise classification, estimate, owner files, or diagnosis scope before product-code repair.',
                gates: gates,
                warnings: warnings,
                recordedAt: now
            };
        }
        var blockedSupportProductRepairDispatchGate_1 = gates.find(function (gate) { return gate.key === 'support_product_repair_dispatch_guard' && gate.status === 'blocked'; });
        if (blockedSupportProductRepairDispatchGate_1) {
            return {
                outcome: 'manual_handoff',
                reason: "Support product-code repair dispatch is blocked by the approval/scope guard: ".concat(blockedSupportProductRepairDispatchGate_1.reason),
                nextAction: ((_f = blockedSupportProductRepairDispatchGate_1.metadata) === null || _f === void 0 ? void 0 : _f.nextAction)
                    ? "Run ".concat(blockedSupportProductRepairDispatchGate_1.metadata.nextAction, " before product-code repair continues.")
                    : 'Approve the current support autonomy scope or revise the diagnosis/owner-file set before product-code repair continues.',
                gates: gates,
                warnings: warnings,
                recordedAt: now
            };
        }
        var blockedSupportHumanDecisionGate_1 = gates.find(function (gate) { return gate.key === 'support_human_decision_request' && gate.status === 'blocked'; });
        if (blockedSupportHumanDecisionGate_1) {
            return {
                outcome: 'manual_handoff',
                reason: "Support run is waiting on a specific operator decision: ".concat(blockedSupportHumanDecisionGate_1.reason),
                nextAction: ((_g = blockedSupportHumanDecisionGate_1.metadata) === null || _g === void 0 ? void 0 : _g.preferredChoiceId)
                    ? "Choose ".concat(blockedSupportHumanDecisionGate_1.metadata.preferredChoiceId, " or an equivalent safe console action, then resume the runner.")
                    : 'Answer the requested support runner decision, then resume the runner.',
                gates: gates,
                warnings: warnings,
                recordedAt: now
            };
        }
    }
    if (input.manualHandoff === true) {
        return {
            outcome: 'manual_handoff',
            reason: 'Run requires manual handoff.',
            nextAction: 'Ask a human operator to resolve the blocked run.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if (input.stopped === true || /stop|stopped|cancel|cancelled|paused/i.test("".concat(input.status || '', " ").concat(input.phase || ''))) {
        return {
            outcome: 'stopped',
            reason: 'Run was stopped before accepted evidence was recorded.',
            nextAction: 'Resume or restart only if the request is still active.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if (input.rejected === true) {
        return {
            outcome: 'rejected',
            reason: 'Run was explicitly rejected.',
            nextAction: 'Start a repair run from the failing evidence.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedHotfixCommitGate = gates.find(function (gate) { return gate.key === 'hotfix_commit_proof' && (gate.status === 'blocked' || gate.status === 'fail'); });
    if (blockedHotfixCommitGate) {
        return {
            outcome: 'release_blocked',
            reason: "Hotfix cannot be treated as durable until GitHub commit proof passes: ".concat(blockedHotfixCommitGate.reason),
            nextAction: 'Commit and push the hotfix to GitHub, record sourceCommitSha/githubCommitUrl/gitCommitStatus/gitPushStatus, then rerun the smallest release gate.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedNoBlindLoopGate = gates.find(function (gate) { return gate.key === 'manager_no_blind_loop_policy' && gate.status === 'blocked'; });
    if (blockedNoBlindLoopGate) {
        return {
            outcome: 'manual_handoff',
            reason: "Manager parked the run to avoid a blind loop: ".concat(blockedNoBlindLoopGate.reason),
            nextAction: 'Collect new material evidence or approve the specific recovery decision before any more model/code repair.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportAutoloopNoProgressGate = gates.find(function (gate) { return gate.key === 'support_autoloop_no_progress' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportAutoloopNoProgressGate) {
        return {
            outcome: 'manual_handoff',
            reason: "Support autoloop parked before another repair loop because no new evidence was recorded: ".concat(blockedSupportAutoloopNoProgressGate.reason),
            nextAction: 'Collect new material evidence, rerun read-only diagnosis or issue-class proof, then resume only if the blocker fingerprint changes.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportDiagnosisBeforeRepairGate = gates.find(function (gate) { return gate.key === 'support_diagnosis_before_repair' && gate.status === 'blocked'; });
    if (blockedSupportDiagnosisBeforeRepairGate) {
        return {
            outcome: 'manual_handoff',
            reason: "Support repair is parked until root-cause diagnosis validates: ".concat(blockedSupportDiagnosisBeforeRepairGate.reason),
            nextAction: 'Run read-only support diagnosis, record support_diagnosis_gate with owner_files and before/action/after proof, then retry only the owner-scoped repair.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportOwnerFileScopeGate = gates.find(function (gate) { return gate.key === 'support_owner_file_scope' && gate.status === 'blocked'; });
    if (blockedSupportOwnerFileScopeGate) {
        return {
            outcome: 'manual_handoff',
            reason: "Support repair exceeded the diagnosed owner-file scope: ".concat(blockedSupportOwnerFileScopeGate.reason),
            nextAction: 'Revise the SupportDiagnosisGate with evidence for each new owner file, update failing_path/proof_plan, then run only the bounded owner-scoped repair.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportIntakeRevisionGate = gates.find(function (gate) { return gate.key === 'support_intake_revision_contract' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportIntakeRevisionGate) {
        var requiredOperatorAction = cleanText((_h = blockedSupportIntakeRevisionGate.metadata) === null || _h === void 0 ? void 0 : _h.requiredOperatorAction, 160);
        return {
            outcome: 'manual_handoff',
            reason: "Support intake/classification changed after approval: ".concat(blockedSupportIntakeRevisionGate.reason),
            nextAction: requiredOperatorAction
                ? "Run ".concat(requiredOperatorAction, " to approve the revised intake/scope before product-code repair continues.")
                : 'Approve the revised support intake/scope before product-code repair continues.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportAutoloopApprovalGate = gates.find(function (gate) { return gate.key === 'support_autoloop_approval_block' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportAutoloopApprovalGate) {
        var nextAction = cleanText((_j = blockedSupportAutoloopApprovalGate.metadata) === null || _j === void 0 ? void 0 : _j.nextAction, 160)
            || cleanText((_k = blockedSupportAutoloopApprovalGate.metadata) === null || _k === void 0 ? void 0 : _k.action, 160);
        var elapsedReapproval = ((_l = blockedSupportAutoloopApprovalGate.metadata) === null || _l === void 0 ? void 0 : _l.requiresElapsedReapproval) === true;
        return {
            outcome: 'manual_handoff',
            reason: "Support autoloop parked before another repair loop because approval/scope is blocked: ".concat(blockedSupportAutoloopApprovalGate.reason),
            nextAction: elapsedReapproval
                ? 'Approve continued runtime beyond the current wall-clock boundary or park the ticket for manual review; do not run another model/code/QA continuation until that decision is recorded.'
                : nextAction
                    ? "Run ".concat(nextAction, " or revise the blocked scope, then resume the approved autoloop toward A-grade QA/business proof.")
                    : 'Approve the blocked support autonomy scope or revise the diagnosis, owner files, planned change, estimate, or classification before the autoloop continues.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportAutonomyApprovalGate = gates.find(function (gate) { return gate.key === 'support_autonomy_approval' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportAutonomyApprovalGate) {
        return {
            outcome: 'manual_handoff',
            reason: "Support autonomy is waiting on operator approval or revised intake/diagnosis scope: ".concat(blockedSupportAutonomyApprovalGate.reason),
            nextAction: ((_m = blockedSupportAutonomyApprovalGate.metadata) === null || _m === void 0 ? void 0 : _m.approvalAction)
                ? "Use ".concat(blockedSupportAutonomyApprovalGate.metadata.approvalAction, " or revise the blocked scope, then allow the runner to continue until A-grade QA/business proof.")
                : 'Approve the bounded support autonomy request or revise classification, estimate, owner files, or diagnosis scope before product-code repair.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportProductRepairDispatchGate = gates.find(function (gate) { return gate.key === 'support_product_repair_dispatch_guard' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportProductRepairDispatchGate) {
        return {
            outcome: 'manual_handoff',
            reason: "Support product-code repair dispatch is blocked by the approval/scope guard: ".concat(blockedSupportProductRepairDispatchGate.reason),
            nextAction: ((_o = blockedSupportProductRepairDispatchGate.metadata) === null || _o === void 0 ? void 0 : _o.nextAction)
                ? "Run ".concat(blockedSupportProductRepairDispatchGate.metadata.nextAction, " before product-code repair continues.")
                : 'Approve the current support autonomy scope or revise the diagnosis/owner-file set before product-code repair continues.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportHumanDecisionGate = gates.find(function (gate) { return gate.key === 'support_human_decision_request' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportHumanDecisionGate) {
        return {
            outcome: 'manual_handoff',
            reason: "Support run is waiting on a specific operator decision: ".concat(blockedSupportHumanDecisionGate.reason),
            nextAction: ((_p = blockedSupportHumanDecisionGate.metadata) === null || _p === void 0 ? void 0 : _p.preferredChoiceId)
                ? "Choose ".concat(blockedSupportHumanDecisionGate.metadata.preferredChoiceId, " or an equivalent safe console action, then resume the runner.")
                : 'Answer the requested support runner decision, then resume the runner.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportPostApprovalResumeAttemptGate = gates.find(function (gate) { return gate.key === 'support_post_approval_resume_attempt' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportPostApprovalResumeAttemptGate) {
        var nextAction = cleanText((_q = blockedSupportPostApprovalResumeAttemptGate.metadata) === null || _q === void 0 ? void 0 : _q.nextAction, 160);
        var failureClass = cleanText((_r = blockedSupportPostApprovalResumeAttemptGate.metadata) === null || _r === void 0 ? void 0 : _r.failureClass, 160);
        return {
            outcome: 'manual_handoff',
            reason: "Approved support autoloop resume did not start: ".concat(blockedSupportPostApprovalResumeAttemptGate.reason),
            nextAction: nextAction
                ? "Review ".concat(failureClass || 'resume blocker', " and run ").concat(nextAction, " only after the blocker fingerprint changes; product repair and customer reply remain blocked.")
                : 'Review the approved autoloop resume blocker and require a changed blocker fingerprint before another retry.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportPostApprovalAutostartGate = gates.find(function (gate) { return gate.key === 'support_post_approval_autostart' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportPostApprovalAutostartGate) {
        var nextAction = cleanText((_s = blockedSupportPostApprovalAutostartGate.metadata) === null || _s === void 0 ? void 0 : _s.nextAction, 160);
        var canRetryWithoutReapproval = ((_t = blockedSupportPostApprovalAutostartGate.metadata) === null || _t === void 0 ? void 0 : _t.canRetryWithoutReapproval) === true;
        var safeRetryAction = cleanText((_u = blockedSupportPostApprovalAutostartGate.metadata) === null || _u === void 0 ? void 0 : _u.safeRetryAction, 160);
        return {
            outcome: 'manual_handoff',
            reason: "Support autonomy was approved, but the post-approval autostart did not begin: ".concat(blockedSupportPostApprovalAutostartGate.reason),
            nextAction: canRetryWithoutReapproval && safeRetryAction === 'run_autoloop'
                ? 'Retry the approved auto-improve loop under the same approval/scope fingerprint; no product repair or customer reply is allowed until the loop starts and records proof.'
                : nextAction === 'resolve_autostart_blocker'
                    ? 'Resolve the autostart blocker or clear the active run, then rerun runSupportTicketAutoImproveLoopManual under the approved scope until A-grade PR proof.'
                    : 'Review the post-approval autostart result, then resume the approved auto-improve loop without changing scope.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'infra_failed') {
        return {
            outcome: 'qa_infra_failed',
            reason: 'QA infrastructure failed before product validation.',
            nextAction: 'Repair QA harness dependencies, ports, browser, Mongo, or startup before another model repair loop.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'compile_failed') {
        return {
            outcome: 'build_failed',
            reason: 'Compile/build evidence failed or was stale.',
            nextAction: 'Repair compile/build first, then rerun QA from the same failed step.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'route_failed') {
        return {
            outcome: 'qa_incomplete',
            reason: 'Browser route probe failed before business proof.',
            nextAction: 'Repair route/auth/startup issue and rerun the same browser route probe.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedAICoderJourneyContractGate = gates.find(function (gate) { return gate.key === 'aicoder_journey_contract' && (gate.status === 'blocked' || gate.status === 'fail'); });
    if (blockedAICoderJourneyContractGate) {
        var claimedSuccess = input.explicitAccepted === true || input.scorecardPassed === true || statusLooksPassed(input.scorecardStatus) || statusLooksPassed("".concat(input.status || '', " ").concat(input.phase || ''));
        return {
            outcome: claimedSuccess ? 'false_pass' : 'qa_incomplete',
            reason: claimedSuccess
                ? "AICoder run claimed success without a valid Journey Contract: ".concat(blockedAICoderJourneyContractGate.reason)
                : "AICoder workflow is blocked until the Journey Contract validates: ".concat(blockedAICoderJourneyContractGate.reason),
            nextAction: 'Generate or repair docs/APP_JOURNEY_CONTRACT.md, validate first/next/last workflow/data story/QA assertions, then rerun workflow build and workflow QA.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportNextActionContractGate = gates.find(function (gate) { return gate.key === 'support_next_action_contract' && gate.status === 'blocked'; });
    if (blockedSupportNextActionContractGate
        && (qa === null || qa === void 0 ? void 0 : qa.outcome) !== 'business_assertion_passed'
        && input.scorecardPassed !== true
        && !statusLooksPassed(input.scorecardStatus)) {
        return {
            outcome: 'manual_handoff',
            reason: "Support manager cannot safely continue without a valid next-action contract: ".concat(blockedSupportNextActionContractGate.reason),
            nextAction: 'Record one validated next-action contract with safeToAutoRun, canRunWithoutCodexMonitor, codexFallbackRequired, preconditions, stop conditions, and success evidence before another autonomous recovery.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportIssueClassProbePlanGate = gates.find(function (gate) { return gate.key === 'support_issue_class_probe_plan' && (gate.status === 'blocked' || gate.status === 'fail'); });
    if (input.source === 'support_ticket' && blockedSupportIssueClassProbePlanGate) {
        var claimedSuccess = input.explicitAccepted === true
            || input.scorecardPassed === true
            || statusLooksPassed(input.scorecardStatus)
            || statusLooksPassed("".concat(input.status || '', " ").concat(input.phase || ''));
        return {
            outcome: claimedSuccess ? 'false_pass' : 'qa_incomplete',
            reason: claimedSuccess
                ? "Support run claimed success without a valid issue-class probe plan: ".concat(blockedSupportIssueClassProbePlanGate.reason)
                : "Support business proof is blocked until the issue-class probe plan validates: ".concat(blockedSupportIssueClassProbePlanGate.reason),
            nextAction: 'Generate or repair the Support IssueClassProbePlan from the diagnosis proof_plan, then rerun issue-specific business proof QA.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedAssistantAnswerActionabilityGate = gates.find(function (gate) { return gate.key === 'assistant_answer_actionability' && (gate.status === 'blocked' || gate.status === 'fail'); });
    if (input.source === 'ai_assistant' && blockedAssistantAnswerActionabilityGate) {
        var claimedSuccess = input.explicitAccepted === true
            || statusLooksPassed("".concat(input.status || '', " ").concat(input.phase || ''));
        return {
            outcome: claimedSuccess ? 'false_pass' : 'qa_incomplete',
            reason: claimedSuccess
                ? "Assistant answer was marked accepted without a valid actionability contract: ".concat(blockedAssistantAnswerActionabilityGate.reason)
                : "Assistant answer is blocked until actionability evidence validates: ".concat(blockedAssistantAnswerActionabilityGate.reason),
            nextAction: 'Record verified query/date/permission/citation/confidence evidence and one assistant actionability contract before answering or drafting customer-facing text.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'route_only_pass' || (qa === null || qa === void 0 ? void 0 : qa.outcome) === 'incomplete') {
        return {
            outcome: input.scorecardPassed === true ? 'false_pass' : 'qa_incomplete',
            reason: input.scorecardPassed === true
                ? 'Scorecard or workflow status passed without issue-specific business assertion proof.'
                : 'QA has not recorded issue-specific business assertion proof.',
            nextAction: 'Add before/action/after workflow proof with screenshot/data assertions before acceptance.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'business_assertion_failed') {
        return {
            outcome: input.terminal === true ? 'rejected' : 'qa_incomplete',
            reason: 'Issue-specific business assertion failed.',
            nextAction: 'Repair the product/data defect and rerun the failing assertion.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var hasBusinessPass = (qa === null || qa === void 0 ? void 0 : qa.outcome) === 'business_assertion_passed';
    var scorecardPassed = input.scorecardPassed === true || statusLooksPassed(input.scorecardStatus);
    var releaseBlockers = [];
    if (statusLooksFailed(input.deployStatus)) {
        releaseBlockers.push("deploy=".concat(cleanText(input.deployStatus, 120)));
    }
    if (statusLooksFailed(input.publishStatus)) {
        releaseBlockers.push("publish=".concat(cleanText(input.publishStatus, 120)));
    }
    if (statusLooksFailed(input.sampleDataStatus)) {
        releaseBlockers.push("sample_data=".concat(cleanText(input.sampleDataStatus, 120)));
    }
    if (releaseBlockers.length && (scorecardPassed || hasBusinessPass)) {
        addGateOnce(gates, makeGate('release', 'Release/deploy', 'fail', "Final acceptance is blocked after QA/scorecard because release gates failed: ".concat(releaseBlockers.join(', '), "."), [], now));
        return {
            outcome: 'release_blocked',
            reason: "Release gates failed after QA/scorecard: ".concat(releaseBlockers.join(', '), "."),
            nextAction: 'Repair deploy/publish/sample-data coverage before marking the run accepted.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var failedSupportPrCreationGate = gates.find(function (gate) { return gate.key === 'support_pr_creation_result' && (gate.status === 'fail' || gate.status === 'blocked'); });
    if (input.source === 'support_ticket' && failedSupportPrCreationGate) {
        return {
            outcome: 'release_blocked',
            reason: "Support PR creation is blocked after proof-ready work: ".concat(failedSupportPrCreationGate.reason),
            nextAction: ((_v = failedSupportPrCreationGate.metadata) === null || _v === void 0 ? void 0 : _v.nextAction) === 'repair_pr_creation_blocker'
                ? 'Repair the PR creation/release-safety blocker or route to platform repair; do not rerun product-code repair unless new issue evidence changes.'
                : 'Check PR creation status before another repair loop.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedSupportAutopilotCompletionGate = gates.find(function (gate) { return gate.key === 'support_autopilot_completion_contract' && gate.status === 'blocked'; });
    if (input.source === 'support_ticket' && blockedSupportAutopilotCompletionGate) {
        var nextAction = cleanText((_w = blockedSupportAutopilotCompletionGate.metadata) === null || _w === void 0 ? void 0 : _w.nextAction, 160);
        var missingEvidence = Array.isArray((_x = blockedSupportAutopilotCompletionGate.metadata) === null || _x === void 0 ? void 0 : _x.missingCompletionEvidence)
            ? blockedSupportAutopilotCompletionGate.metadata.missingCompletionEvidence
                .map(function (entry) { return cleanText(entry, 240); })
                .filter(Boolean)
            : [];
        var outcome = nextAction === 'create_pr'
            ? 'release_blocked'
            : (input.explicitAccepted === true || scorecardPassed || statusLooksPassed("".concat(input.status || '', " ").concat(input.phase || '')) || hasBusinessPass)
                ? 'false_pass'
                : 'qa_incomplete';
        return {
            outcome: outcome,
            reason: "Approved support autopilot has not reached A-grade PR proof: ".concat(blockedSupportAutopilotCompletionGate.reason),
            nextAction: nextAction === 'create_pr'
                ? 'Create the proof-backed support PR; merge, release, deploy, and customer reply remain separately gated.'
                : nextAction === 'run_business_proof_qa'
                    ? 'Run issue-specific business proof QA until AIQaBusinessAssertion, before/action/after proof, and screenshot/trace evidence pass.'
                    : nextAction === 'run_a_grade_pr_review'
                        ? 'Run strict A-grade PR review; do not merge, release, deploy, or send the customer reply until execution, artifact, pull_request, business-proof, and screenshot/trace evidence pass.'
                        : 'Continue only the bounded owner-scoped support workflow until PR readiness or a new blocker/scope change.',
            gates: gates,
            warnings: missingEvidence.length
                ? __spreadArray(__spreadArray([], __read(warnings), false), __read(missingEvidence.map(function (entry) { return "missing_completion_evidence:".concat(entry); })), false) : warnings,
            recordedAt: now
        };
    }
    var blockedSupportReleaseCustomerGate = gates.find(function (gate) { return gate.key === 'support_release_customer_acceptance' && (gate.status === 'blocked' || gate.status === 'fail'); });
    if (input.source === 'support_ticket' && blockedSupportReleaseCustomerGate) {
        var nextAction = cleanText((_y = blockedSupportReleaseCustomerGate.metadata) === null || _y === void 0 ? void 0 : _y.nextAction, 160);
        return {
            outcome: 'release_blocked',
            reason: "Support PR proof is ready, but release/customer acceptance is incomplete: ".concat(blockedSupportReleaseCustomerGate.reason),
            nextAction: nextAction === 'draft_or_review_proof_backed_customer_reply'
                ? 'Draft or review the proof-backed customer reply from the accepted QA/release evidence; do not rerun product-code repair unless new issue evidence appears.'
                : 'Complete the release/hotfix gate for the A-grade PR, then generate or review the proof-backed customer reply.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var blockedAICoderNextActionContractGate = gates.find(function (gate) { return gate.key === 'aicoder_next_action_contract' && (gate.status === 'blocked' || gate.status === 'fail'); });
    if (input.source === 'aicoder_app' && blockedAICoderNextActionContractGate) {
        var claimedSuccess = input.explicitAccepted === true
            || input.scorecardPassed === true
            || statusLooksPassed(input.scorecardStatus)
            || statusLooksPassed("".concat(input.status || '', " ").concat(input.phase || ''));
        return {
            outcome: claimedSuccess ? 'false_pass' : 'manual_handoff',
            reason: claimedSuccess
                ? "AICoder run claimed success without a manager-safe next-action contract: ".concat(blockedAICoderNextActionContractGate.reason)
                : "AICoder manager cannot safely continue without a manager-safe next-action contract: ".concat(blockedAICoderNextActionContractGate.reason),
            nextAction: 'Record one validated AICoder next-action contract with safeToAutoRun, canRunWithoutCodexMonitor, codexFallbackRequired, stop conditions, and success evidence before another autonomous loop.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if (scorecardPassed && !hasBusinessPass) {
        warnings.push('scorecard_pass_without_business_assertion');
        addGateOnce(gates, makeGate('business_assertion_required', 'Business assertion', 'blocked', 'Scorecard passed, but no issue-specific business assertion proof was recorded.', [], now));
        return {
            outcome: 'false_pass',
            reason: 'Scorecard-only proof is not acceptance.',
            nextAction: 'Record issue-specific workflow/data proof, then reclassify the run.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    var statusPhase = "".concat(input.status || '', " ").concat(input.phase || '');
    if ((input.explicitAccepted === true || statusLooksPassed(statusPhase) || scorecardPassed) && hasBusinessPass) {
        return {
            outcome: 'accepted',
            reason: 'Run has terminal success signal and issue-specific business assertion proof.',
            nextAction: 'No repair action required.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    if (statusLooksFailed(statusPhase)) {
        return {
            outcome: 'rejected',
            reason: 'Run ended with a failure status and no accepted proof.',
            nextAction: 'Classify the failing gate and rerun the smallest repair step.',
            gates: gates,
            warnings: warnings,
            recordedAt: now
        };
    }
    return {
        outcome: 'unknown',
        reason: 'Run does not have enough normalized evidence for a terminal label.',
        nextAction: 'Ingest QA, deploy, assistant, usage, and commit evidence before using this run for training.',
        gates: gates,
        warnings: warnings,
        recordedAt: now
    };
}
function buildAIRun(input) {
    var decision = input.outcome
        ? {
            outcome: input.outcome,
            gates: input.gates || [],
            warnings: input.warnings || [],
            nextAction: input.nextAction || '',
            reason: '',
            recordedAt: isoNow(input.now)
        }
        : classifyAIRunOutcome({
            source: input.source,
            status: input.status,
            phase: input.phase,
            qa: input.qa,
            gates: input.gates,
            scorecardPassed: input.scorecardPassed,
            deployStatus: input.deployStatus,
            publishStatus: input.publishStatus,
            sampleDataStatus: input.sampleDataStatus,
            manualHandoff: input.manualHandoff,
            stopped: input.stopped,
            rejected: input.rejected,
            explicitAccepted: input.explicitAccepted,
            terminal: input.terminal,
            now: input.now
        });
    return {
        id: input.id,
        source: input.source || 'unknown',
        sourceIds: input.sourceIds || {},
        title: input.title,
        status: input.status,
        phase: input.phase,
        startedAt: input.startedAt,
        completedAt: input.completedAt,
        outcome: decision.outcome,
        events: Array.isArray(input.events) ? input.events : [],
        gates: decision.gates,
        qa: normalizeQaRun(input.qa),
        cost: input.cost,
        nextAction: decision.nextAction,
        warnings: decision.warnings,
        metadata: input.metadata
    };
}
function buildAIRunCost(entries) {
    var e_5, _a, e_6, _b, e_7, _c, e_8, _d;
    var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
    if (entries === void 0) { entries = []; }
    var cost = {
        inputTokens: 0,
        cachedInputTokens: 0,
        outputTokens: 0,
        totalTokens: 0,
        estimatedUsd: 0,
        models: [],
        categories: {},
        sources: {},
        surfaces: {},
        manualEstimatedUsd: 0,
        untrackedEstimatedUsd: 0,
        untrackedWarnings: []
    };
    try {
        for (var _x = __values(normalizeOpenAIUsageRowsForCosting(entries)), _y = _x.next(); !_y.done; _y = _x.next()) {
            var entry = _y.value;
            var category = cleanText(entry.category, 120) || 'unknown';
            var source = cleanText((_e = entry.usage_source) !== null && _e !== void 0 ? _e : entry.usageSource, 80) || 'unknown';
            var surface = cleanText((_f = entry.usage_surface) !== null && _f !== void 0 ? _f : entry.usageSurface, 80) || 'unknown';
            var isManual = entry.is_manual === true || entry.isManual === true || source === 'manual_codex';
            var isUntracked = entry.is_untracked === true || entry.isUntracked === true;
            var untrackedReason = cleanText((_g = entry.untracked_reason) !== null && _g !== void 0 ? _g : entry.untrackedReason, 500);
            var model = cleanText(entry.model, 120);
            var inputTokens = Number((_j = (_h = entry.input_tokens) !== null && _h !== void 0 ? _h : entry.inputTokens) !== null && _j !== void 0 ? _j : 0) || 0;
            var cachedInputTokens = Number((_l = (_k = entry.cached_input_tokens) !== null && _k !== void 0 ? _k : entry.cachedInputTokens) !== null && _l !== void 0 ? _l : 0) || 0;
            var outputTokens = Number((_o = (_m = entry.output_tokens) !== null && _m !== void 0 ? _m : entry.outputTokens) !== null && _o !== void 0 ? _o : 0) || 0;
            var totalTokens = Number((_q = (_p = entry.total_tokens) !== null && _p !== void 0 ? _p : entry.totalTokens) !== null && _q !== void 0 ? _q : (inputTokens + outputTokens)) || 0;
            var estimatedUsd = Number((_s = (_r = entry.cost_estimate) !== null && _r !== void 0 ? _r : entry.estimatedUsd) !== null && _s !== void 0 ? _s : 0) || 0;
            cost.inputTokens += inputTokens;
            cost.cachedInputTokens += cachedInputTokens;
            cost.outputTokens += outputTokens;
            cost.totalTokens += totalTokens;
            cost.estimatedUsd += estimatedUsd;
            if (isManual) {
                cost.manualEstimatedUsd = Number(cost.manualEstimatedUsd || 0) + estimatedUsd;
            }
            if (isUntracked) {
                cost.untrackedEstimatedUsd = Number(cost.untrackedEstimatedUsd || 0) + estimatedUsd;
                var warning = untrackedReason || "".concat(source, " usage is an estimate outside managed runner telemetry.");
                if (warning && !((_t = cost.untrackedWarnings) === null || _t === void 0 ? void 0 : _t.includes(warning))) {
                    (_u = cost.untrackedWarnings) === null || _u === void 0 ? void 0 : _u.push(warning);
                }
            }
            if (model && !cost.models.includes(model)) {
                cost.models.push(model);
            }
            if (!cost.categories[category]) {
                cost.categories[category] = {
                    inputTokens: 0,
                    cachedInputTokens: 0,
                    outputTokens: 0,
                    totalTokens: 0,
                    estimatedUsd: 0,
                    count: 0
                };
            }
            cost.categories[category].inputTokens += inputTokens;
            cost.categories[category].cachedInputTokens += cachedInputTokens;
            cost.categories[category].outputTokens += outputTokens;
            cost.categories[category].totalTokens += totalTokens;
            cost.categories[category].estimatedUsd += estimatedUsd;
            cost.categories[category].count += 1;
            if (!((_v = cost.sources) === null || _v === void 0 ? void 0 : _v[source])) {
                cost.sources[source] = {
                    inputTokens: 0,
                    cachedInputTokens: 0,
                    outputTokens: 0,
                    totalTokens: 0,
                    estimatedUsd: 0,
                    count: 0,
                    manualCount: 0,
                    untrackedCount: 0
                };
            }
            cost.sources[source].inputTokens += inputTokens;
            cost.sources[source].cachedInputTokens += cachedInputTokens;
            cost.sources[source].outputTokens += outputTokens;
            cost.sources[source].totalTokens += totalTokens;
            cost.sources[source].estimatedUsd += estimatedUsd;
            cost.sources[source].count += 1;
            if (isManual) {
                cost.sources[source].manualCount += 1;
            }
            if (isUntracked) {
                cost.sources[source].untrackedCount += 1;
            }
            if (!((_w = cost.surfaces) === null || _w === void 0 ? void 0 : _w[surface])) {
                cost.surfaces[surface] = {
                    totalTokens: 0,
                    estimatedUsd: 0,
                    count: 0
                };
            }
            cost.surfaces[surface].totalTokens += totalTokens;
            cost.surfaces[surface].estimatedUsd += estimatedUsd;
            cost.surfaces[surface].count += 1;
        }
    }
    catch (e_5_1) { e_5 = { error: e_5_1 }; }
    finally {
        try {
            if (_y && !_y.done && (_a = _x.return)) _a.call(_x);
        }
        finally { if (e_5) throw e_5.error; }
    }
    cost.estimatedUsd = Number(cost.estimatedUsd.toFixed(6));
    cost.manualEstimatedUsd = Number(Number(cost.manualEstimatedUsd || 0).toFixed(6));
    cost.untrackedEstimatedUsd = Number(Number(cost.untrackedEstimatedUsd || 0).toFixed(6));
    try {
        for (var _z = __values(Object.keys(cost.categories)), _0 = _z.next(); !_0.done; _0 = _z.next()) {
            var category = _0.value;
            cost.categories[category].estimatedUsd = Number(cost.categories[category].estimatedUsd.toFixed(6));
        }
    }
    catch (e_6_1) { e_6 = { error: e_6_1 }; }
    finally {
        try {
            if (_0 && !_0.done && (_b = _z.return)) _b.call(_z);
        }
        finally { if (e_6) throw e_6.error; }
    }
    try {
        for (var _1 = __values(Object.keys(cost.sources || {})), _2 = _1.next(); !_2.done; _2 = _1.next()) {
            var source = _2.value;
            cost.sources[source].estimatedUsd = Number(cost.sources[source].estimatedUsd.toFixed(6));
        }
    }
    catch (e_7_1) { e_7 = { error: e_7_1 }; }
    finally {
        try {
            if (_2 && !_2.done && (_c = _1.return)) _c.call(_1);
        }
        finally { if (e_7) throw e_7.error; }
    }
    try {
        for (var _3 = __values(Object.keys(cost.surfaces || {})), _4 = _3.next(); !_4.done; _4 = _3.next()) {
            var surface = _4.value;
            cost.surfaces[surface].estimatedUsd = Number(cost.surfaces[surface].estimatedUsd.toFixed(6));
        }
    }
    catch (e_8_1) { e_8 = { error: e_8_1 }; }
    finally {
        try {
            if (_4 && !_4.done && (_d = _3.return)) _d.call(_3);
        }
        finally { if (e_8) throw e_8.error; }
    }
    return cost;
}
function redactAIRunTrainingExample(example) {
    var redact = function (value) { return cleanText(value, 5000)
        .replace(/mongodb(?:\+srv)?:\/\/[^\s"'<>]+/ig, '[redacted-mongo-url]')
        .replace(/\b(?:sk|ghp|xoxb|AKIA)[A-Za-z0-9_\-]{12,}\b/g, '[redacted-secret]')
        .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/ig, '[redacted-email]'); };
    return __assign(__assign({}, example), { inputSummary: redact(example.inputSummary), actionSummary: redact(example.actionSummary), evidence: cleanList(example.evidence, 80, 5000).map(redact) });
}

//# sourceMappingURL=ai-run-evidence.js.map
