/**
 * 知识演进引擎 — 问题十四 (Evidence-based Knowledge Promotion)。
 *
 * 基于证据的知识晋级评估，包含候选信任分级、证据验证、
 * 漂移分类和 AI 推理写入限制。
 */
import { evaluatePromotion } from "./knowledge_lifecycle.js";
// 从独立模块导入漂移分类器，消除与 knowledge_lifecycle 的循环依赖
export { classifyDrift } from "./drift_classifier.js";
// ── 来源信任级别映射 ──
const SOURCE_TRUST_CONFIG = {
    senior_practice: {
        trust_level: "high",
        allowed_max_status: "pending_review",
    },
    failure_analysis: {
        trust_level: "low",
        allowed_max_status: "draft",
    },
    drift_detection: {
        trust_level: "low",
        allowed_max_status: "draft",
    },
    repeated_success: {
        trust_level: "medium",
        allowed_max_status: "pending_review",
    },
    user_instruction: {
        trust_level: "medium",
        allowed_max_status: "pending_review",
    },
    ai_inference: {
        trust_level: "low",
        allowed_max_status: "draft",
    },
};
// ── 核心函数 ──
/**
 * 评估知识候选来源的信任级别。
 * 不同来源有不同的信任上限，决定该来源产生的知识能晋升到的最高状态。
 *
 * - senior_practice: 高信任，允许晋级到 pending_review（快速审查路径）
 * - failure_analysis: 低信任，仅允许 draft（单次失败不足以产生高信任知识）
 * - drift_detection: 低信任，必须生成漂移报告，不可直接修改 active/core 知识
 * - repeated_success: 中信任，允许晋级到 pending_review
 * - user_instruction: 中信任，允许晋级到 pending_review（active 仍需确认）
 * - ai_inference: 低信任，仅允许 draft/quarantine，永远不可 active/core
 */
export function evaluateCandidateTrust(source) {
    const config = SOURCE_TRUST_CONFIG[source];
    return {
        trust_level: config.trust_level,
        allowed_max_status: config.allowed_max_status,
    };
}
/**
 * 验证知识候选的证据是否充分。
 *
 * 规则：
 * - 至少需要 1 条证据
 * - 证据置信度必须 >= 0.5
 * - core 主权必须有 user_confirmed 或 review_approved 类型的证据
 * - 来源信任度必须足够支撑目标状态
 */
export function validatePromotionEvidence(candidate, evidences) {
    const missing = [];
    // 检查 1: 至少需要 1 条证据
    if (evidences.length === 0) {
        missing.push("至少需要 1 条晋级证据");
    }
    // 检查 2: 证据置信度必须 >= 0.5
    const lowConfidenceEvidence = evidences.filter((e) => e.confidence < 0.5);
    if (lowConfidenceEvidence.length > 0) {
        missing.push(`${lowConfidenceEvidence.length} 条证据置信度低于 0.5: ${lowConfidenceEvidence.map((e) => e.id).join(", ")}`);
    }
    // 检查 3: core 主权必须有 user_confirmed 或 review_approved 证据
    if (candidate.proposed_sovereignty === "core") {
        const hasHumanApproval = evidences.some((e) => e.source_type === "user_confirmed" || e.source_type === "review_approved");
        if (!hasHumanApproval) {
            missing.push("core 主权晋级必须包含 user_confirmed 或 review_approved 类型的证据");
        }
    }
    // 检查 4: 来源信任度是否足够
    const trust = evaluateCandidateTrust(candidate.source);
    const statusHierarchy = [
        "draft",
        "quarantine",
        "pending_review",
        "active",
        "deprecated",
    ];
    const candidateIndex = statusHierarchy.indexOf(candidate.proposed_status);
    const maxIndex = statusHierarchy.indexOf(trust.allowed_max_status);
    if (candidateIndex > maxIndex) {
        missing.push(`来源 ${candidate.source} 信任不足，允许的最高状态为 ${trust.allowed_max_status}，目标状态为 ${candidate.proposed_status}`);
    }
    return {
        sufficient: missing.length === 0,
        missing,
    };
}
/**
 * 创建知识晋级报告。
 * 整合候选信息、证据和人工审批结果，生成标准晋级报告。
 */
export function createPromotionReport(candidate, from_status, from_sovereignty, evidences, human_approved_by) {
    // 构造晋级请求，复用 knowledge_lifecycle 的评估逻辑
    const promotionRequest = {
        entry_id: candidate.id,
        from_status,
        to_status: candidate.proposed_status,
        from_sovereignty,
        to_sovereignty: candidate.proposed_sovereignty,
        evidence_ids: candidate.evidence_ids,
        requested_by: mapSourceToRequester(candidate.source),
    };
    const result = evaluatePromotion(promotionRequest);
    // 确定晋级状态
    let promotion_status;
    if (!result.allowed) {
        promotion_status = "rejected";
    }
    else if (human_approved_by) {
        promotion_status = "human_reviewed";
    }
    else if (evidences.length > 0) {
        promotion_status = "evidence_gathered";
    }
    else {
        promotion_status = "pending";
    }
    return {
        entry_id: candidate.id,
        from_status,
        to_status: candidate.proposed_status,
        from_sovereignty,
        to_sovereignty: candidate.proposed_sovereignty,
        evidence_ids: candidate.evidence_ids,
        conflicts_checked: true,
        product_scope_checked: true,
        human_approved_by,
        rollback_path: `${from_status}:${from_sovereignty}`,
        promotion_status,
    };
}
/**
 * 验证 AI 推理写入权限。
 * 硬规则：AI 推理只能创建 draft/quarantine 级别的知识，不能写入 core 或 active。
 *
 * - ai_inference 不可写入 sovereignty=core
 * - ai_inference 不可设置 status=active
 * - ai_inference 只能创建 draft/quarantine
 */
export function validateAiInferenceWrite(source, target_sovereignty, target_status) {
    // 仅对 ai_inference 来源执行硬性限制
    if (source !== "ai_inference") {
        return { allowed: true, reason: "非 AI 推理来源，不受此限制" };
    }
    // 规则 1: ai_inference 不可写入 sovereignty=core
    if (target_sovereignty === "core") {
        return {
            allowed: false,
            reason: "AI 推理不可将知识主权设为 core，core 知识只能由人工或高信任来源创建",
        };
    }
    // 规则 2: ai_inference 不可设置 status=active
    if (target_status === "active") {
        return {
            allowed: false,
            reason: "AI 推理不可将知识状态设为 active，active 需要人工确认或充分证据晋级",
        };
    }
    // 规则 3: ai_inference 只能创建 draft/quarantine
    if (target_status !== "draft" && target_status !== "quarantine") {
        return {
            allowed: false,
            reason: `AI 推理只能创建 draft/quarantine 状态的知识，目标状态 ${target_status} 不在允许范围内`,
        };
    }
    return {
        allowed: true,
        reason: "AI 推理写入权限验证通过：sovereignty=normal, status=draft/quarantine",
    };
}
// ── 内部辅助函数 ──
/** 将候选来源映射为晋级请求的 requester 类型 */
function mapSourceToRequester(source) {
    switch (source) {
        case "senior_practice":
        case "repeated_success":
        case "user_instruction":
            return "human";
        case "failure_analysis":
        case "drift_detection":
            return "drift_detection";
        case "ai_inference":
            return "ai_inference";
    }
}
//# sourceMappingURL=knowledge_evolution.js.map