/**
 * 知识生命周期管理 — 问题七 (Knowledge Lifecycle)。
 *
 * 管理知识条目的生命周期状态、主权和健康检查。
 * - knowledge_lifecycle_status 使用规范字段名（draft/quarantine/active/pending_review/deprecated）
 * - sovereignty 使用 normal / core（与问题正文和 Batch 1 一致）
 * - staged 不再作为生命周期主状态，改为 knowledge_write_stage
 * - core 不再作为生命周期状态，改为 sovereignty=core
 */
import { readFile } from "node:fs/promises";
// 从独立模块导入漂移分类器，消除与 knowledge_evolution 的循环依赖
import { classifyDrift } from "./drift_classifier.js";
// ── 状态转移规则 ──
/** 可自动执行的转移（只能收紧，不能放权） */
const AUTO_TRANSITIONS = new Set([
    "active->pending_review",
    "pending_review->quarantine",
    "draft->quarantine",
]);
/** 必须人工确认的转移 */
const HUMAN_REQUIRED_TRANSITIONS = new Set([
    "draft->active",
    "quarantine->active",
    "pending_review->active",
    "pending_review->deprecated",
    "active->deprecated",
]);
// ── 核心函数 ──
/**
 * 评估知识晋级请求。
 * 硬规则：
 * - AI inference 不得直接晋级到 active/core
 * - core 知识变更必须人工确认
 * - draft/quarantine 不得自动晋级 active/core
 * - 无 evidence 不得晋级
 */
export function evaluatePromotion(request) {
    // 规则 1: AI inference 不得直接晋级到 active
    if (request.requested_by === "ai_inference" && request.to_status === "active") {
        return {
            allowed: false,
            reason: "AI inference 不得直接将知识晋级为 active",
            blocked_by: "ai_inference_promotion_blocked",
            requires_human: true,
        };
    }
    // 规则 2: AI inference 不得修改 sovereignty=core
    if (request.requested_by === "ai_inference" && request.to_sovereignty === "core") {
        return {
            allowed: false,
            reason: "AI inference 不得将知识主权设为 core",
            blocked_by: "ai_inference_sovereignty_blocked",
            requires_human: true,
        };
    }
    // 规则 3: draft/quarantine 不得自动晋级到 active（必须人工）
    if ((request.from_status === "draft" || request.from_status === "quarantine") &&
        request.to_status === "active" &&
        request.requested_by !== "human") {
        return {
            allowed: false,
            reason: `draft/quarantine 晋级 active 必须人工确认，当前来源: ${request.requested_by}`,
            blocked_by: "auto_promotion_to_active_blocked",
            requires_human: true,
        };
    }
    // 规则 4: core 主权变更必须人工确认
    if (request.to_sovereignty === "core" &&
        request.from_sovereignty !== "core" &&
        request.requested_by !== "human") {
        return {
            allowed: false,
            reason: "normal 到 core 的主权变更必须人工确认",
            blocked_by: "sovereignty_upgrade_requires_human",
            requires_human: true,
        };
    }
    // 规则 5: 无 evidence 不得晋级
    if (request.evidence_ids.length === 0 && request.to_status === "active") {
        return {
            allowed: false,
            reason: "晋级 active 必须提供证据",
            blocked_by: "evidence_required",
            requires_human: true,
        };
    }
    // 规则 6: deprecated 禁止回到 active（完全禁止，包括人工）
    if (request.from_status === "deprecated" &&
        request.to_status === "active") {
        return {
            allowed: false,
            reason: "deprecated 知识不可复活，禁止回到 active",
            blocked_by: "deprecated_resurrection_forbidden",
            requires_human: false,
        };
    }
    // 规则 7: 自动转移检查
    const transitionKey = `${request.from_status}->${request.to_status}`;
    if (AUTO_TRANSITIONS.has(transitionKey) &&
        request.requested_by !== "ai_inference") {
        return {
            allowed: true,
            reason: "自动转移：只能收紧，不能放权",
            requires_human: false,
        };
    }
    // 规则 8: 人工确认的转移
    if (HUMAN_REQUIRED_TRANSITIONS.has(transitionKey)) {
        if (request.requested_by === "human") {
            return {
                allowed: true,
                reason: "人工确认的转移",
                requires_human: false,
            };
        }
        return {
            allowed: false,
            reason: `${transitionKey} 必须人工确认`,
            blocked_by: "human_required_transition",
            requires_human: true,
        };
    }
    return {
        allowed: false,
        reason: `未识别的状态转移: ${transitionKey}`,
        blocked_by: "unknown_transition",
        requires_human: true,
    };
}
/**
 * 判断知识条目是否可注入。
 * 硬规则：
 * - active 可注入
 * - draft/quarantine/deprecated 不注入
 * - pending_review 默认不注入，advisory 例外
 * - core + active 可注入
 * - core + pending_review 不自动降级
 */
export function isInjectable(status, advisory) {
    if (status === "active") {
        return { injectable: true, reason: "active 知识默认可注入" };
    }
    if (status === "draft") {
        return { injectable: false, reason: "draft 知识不注入" };
    }
    if (status === "quarantine") {
        return { injectable: false, reason: "quarantine 知识不注入" };
    }
    if (status === "deprecated") {
        return { injectable: false, reason: "deprecated 知识不注入" };
    }
    if (status === "pending_review") {
        if (advisory) {
            return {
                injectable: true,
                reason: "pending_review advisory 注入，带风险提示",
            };
        }
        return { injectable: false, reason: "pending_review 默认不注入" };
    }
    return { injectable: false, reason: `未识别的 lifecycle_status: ${status}` };
}
/**
 * 知识健康检查 — 覆盖 8 类 category。
 * 异步版本: 漂移检测改用 fs.promises.readFile 消除同步 I/O。
 */
export async function checkKnowledgeHealth(entries, evidenceMap) {
    const findings = [];
    for (const entry of entries) {
        // lifecycle 类检查
        if (entry.knowledge_lifecycle_status === "draft" ||
            entry.knowledge_lifecycle_status === "quarantine") {
            // 这些状态不应被注入
        }
        if (entry.knowledge_lifecycle_status === "deprecated") {
            findings.push({
                id: `health-${entry.id}-deprecated`,
                severity: "info",
                category: "lifecycle",
                entry_id: entry.id,
                message: `知识条目 ${entry.id} 已废弃`,
                recommendation: "检查是否需要移除或迁移到替代条目",
                requires_human: false,
            });
        }
        // sovereignty 类检查
        if (entry.sovereignty === "core" && entry.knowledge_lifecycle_status === "pending_review") {
            findings.push({
                id: `health-${entry.id}-core-pending`,
                severity: "warning",
                category: "sovereignty",
                entry_id: entry.id,
                message: `core 知识 ${entry.id} 处于 pending_review 状态，不自动降级`,
                recommendation: "人工裁决 core 知识状态",
                requires_human: true,
            });
        }
        // evidence 类检查
        const evidences = evidenceMap.get(entry.id) ?? [];
        if (entry.knowledge_lifecycle_status === "active" &&
            evidences.length === 0) {
            findings.push({
                id: `health-${entry.id}-no-evidence`,
                severity: "warning",
                category: "evidence",
                entry_id: entry.id,
                message: `active 知识 ${entry.id} 无关联证据`,
                recommendation: "补充证据或降级为 pending_review",
                requires_human: false,
            });
        }
        // staleness 类检查 — 长期未更新
        const updatedAt = new Date(entry.updated_at);
        const staleThreshold = 90 * 24 * 60 * 60 * 1000; // 90 天
        if (Date.now() - updatedAt.getTime() > staleThreshold && entry.knowledge_lifecycle_status === "active") {
            findings.push({
                id: `health-${entry.id}-stale`,
                severity: "info",
                category: "staleness",
                entry_id: entry.id,
                message: `active 知识 ${entry.id} 超过 90 天未更新`,
                recommendation: "人工检查知识是否仍然准确",
                auto_action: "mark_pending_review",
                requires_human: false,
            });
        }
        // drift 类检查 — 知识与代码漂移（需要 content_summary 和 source_path）
        if (entry.content_summary && entry.source_path && entry.knowledge_lifecycle_status === "active") {
            let codeContent;
            try {
                codeContent = await readFile(entry.source_path, "utf-8");
            }
            catch {
                // source_path 对应文件不存在或不可读，跳过漂移检测
            }
            if (codeContent !== undefined) {
                const drift = classifyDrift(entry.id, entry.content_summary, codeContent);
                if (drift.classification === "knowledge_outdated") {
                    findings.push({
                        id: `health-${entry.id}-drift`,
                        severity: "warning",
                        category: "staleness",
                        entry_id: entry.id,
                        message: drift.description_zh,
                        recommendation: "人工检查知识内容是否与当前代码一致",
                        auto_action: "mark_pending_review",
                        requires_human: drift.requires_human,
                    });
                }
            }
        }
    }
    return findings;
}
/**
 * 列出所有知识条目（空实现，实际由上层 knowledge loader 提供）。
 */
export function listKnowledgeEntries() {
    return [];
}
/**
 * 从旧路径推断 sovereignty。
 * patterns/core/ 下的旧知识默认推断为 sovereignty=core。
 */
export function inferSovereigntyFromPath(sourcePath) {
    if (sourcePath.includes("patterns/core/") || sourcePath.includes("/core/")) {
        return "core";
    }
    return "normal";
}
/**
 * 执行 auto_action — 根据 health check 的自动动作建议修改知识状态。
 * 仅 mark_pending_review: 将 active 条目自动降级为 pending_review。
 *
 * @param findings - health check 产出
 * @param getEntry - 获取条目的回调（由调用方注入 KnowledgeIndexManager.getEntry）
 * @param updateStatus - 更新条目状态的回调
 * @returns 被执行的条目 ID 列表
 */
export function executeAutoActions(findings, getEntry, updateStatus) {
    const executed = [];
    for (const f of findings) {
        if (!f.auto_action || f.auto_action === "none")
            continue;
        if (f.auto_action === "mark_pending_review") {
            const entry = getEntry(f.entry_id);
            if (!entry)
                continue;
            // 统一使用 knowledge_lifecycle_status，fallback 到 status
            const currentStatus = entry.knowledge_lifecycle_status ?? entry.status;
            if (currentStatus === "active") {
                updateStatus(f.entry_id, "pending_review");
                executed.push(f.entry_id);
            }
        }
    }
    return executed;
}
//# sourceMappingURL=knowledge_lifecycle.js.map