/**
 * Knowledge Asset Audit — 问题五十七核心机制之二。
 *
 * 扫描所有知识资产，输出审计报告，识别:
 * - frontmatter 缺失字段
 * - 重复 ID / canonical 冲突
 * - owner/evidence 缺失
 * - deprecated/draft/quarantine 注入风险
 * - checklist 硬规则越权
 * - 消费链路不可追踪
 */
import { validateKnowledgeAssetFrontmatter } from "./knowledge_asset_schema.js";
import matter from "gray-matter";
// ── YAML 解析 ──
/**
 * 使用 gray-matter 解析知识资产文件的 frontmatter。
 * 返回正确类型的 frontmatter（数组是数组，不是字符串）。
 */
export function parseKnowledgeAssetFrontmatter(rawContent) {
    try {
        const parsed = matter(rawContent);
        const data = parsed.data;
        // gray-matter 返回的数组字段已经是真正的数组
        return data;
    }
    catch {
        return {};
    }
}
/**
 * 解析文件并返回可审计的资产对象。
 */
export function parseAssetFile(filePath, rawContent) {
    const fm = parseKnowledgeAssetFrontmatter(rawContent);
    const body = rawContent.replace(/^---\n[\s\S]*?\n---\n?/, "");
    return {
        frontmatter: fm,
        file_path: filePath,
        body,
    };
}
// ── 核心函数 ──
/**
 * 执行知识资产全量审计。
 * 接受已解析的 frontmatter 对象（推荐使用 parseAssetFile 预处理）。
 */
export function auditKnowledgeAssets(assets) {
    const allFindings = [];
    const idSet = new Set();
    const canonicalSubjects = new Map();
    const deprecatedWithRoutes = [];
    for (const asset of assets) {
        // 1. Schema 校验
        const schemaFindings = validateKnowledgeAssetFrontmatter(asset.frontmatter, asset.file_path);
        for (const sf of schemaFindings) {
            allFindings.push({
                asset_id: sf.asset_id,
                file_path: sf.file_path,
                severity: sf.severity,
                kind: sf.field === "owner_mechanism_id" ? "owner_missing"
                    : sf.field === "required_evidence" ? "required_evidence_missing"
                        : sf.message_zh.includes("deprecated") ? "deprecated_injected"
                            : "missing_required_field",
                detail: sf.message_zh,
                suggested_action: sf.field === "owner_mechanism_id" ? "repair"
                    : sf.field === "required_evidence" ? "repair"
                        : "manual_required",
            });
        }
        const id = asset.frontmatter.id;
        if (!id)
            continue;
        // 2. 重复 ID
        if (idSet.has(id)) {
            allFindings.push({
                asset_id: id,
                file_path: asset.file_path,
                severity: "hard_fail",
                kind: "duplicate_id",
                detail: `知识资产 ID 重复: ${id} (SF-KA-5702)`,
                suggested_action: "merge",
            });
        }
        idSet.add(id);
        // 3. canonical 冲突
        if (asset.frontmatter.authority === "canonical" && asset.frontmatter.name) {
            const subject = asset.frontmatter.name;
            const existing = canonicalSubjects.get(subject) ?? [];
            existing.push(id);
            canonicalSubjects.set(subject, existing);
        }
        // 4. deprecated/draft/quarantine 注入检测
        const status = asset.frontmatter.lifecycle_status;
        if (status && ["deprecated", "draft", "quarantine"].includes(status)) {
            if (asset.frontmatter.routes && asset.frontmatter.routes.length > 0) {
                deprecatedWithRoutes.push(id);
                allFindings.push({
                    asset_id: id,
                    file_path: asset.file_path,
                    severity: "hard_fail",
                    kind: "deprecated_injected",
                    detail: `${status} 资产 ${id} 有活跃路由，可能被注入 prompt (SF-KA-5705)`,
                    suggested_action: "repair",
                });
            }
        }
        // 5. hard_rule/workflow 无 owner
        const kind = asset.frontmatter.asset_kind;
        if (kind && ["hard_rule", "workflow", "procedure", "pipeline"].includes(kind)) {
            if (!asset.frontmatter.owner_mechanism_id) {
                allFindings.push({
                    asset_id: id,
                    file_path: asset.file_path,
                    severity: "hard_fail",
                    kind: "owner_missing",
                    detail: `${kind} ${id} 缺少 owner_mechanism_id (SF-KA-5704)`,
                    suggested_action: "repair",
                });
            }
        }
        // 6. P0/P1 缺 required_evidence
        if (asset.frontmatter.priority && ["P0", "P1"].includes(asset.frontmatter.priority)) {
            if (!asset.frontmatter.required_evidence || asset.frontmatter.required_evidence.length === 0) {
                allFindings.push({
                    asset_id: id,
                    file_path: asset.file_path,
                    severity: "hard_fail",
                    kind: "required_evidence_missing",
                    detail: `P0/P1 资产 ${id} 缺少 required_evidence (SF-KA-5706)`,
                    suggested_action: "repair",
                });
            }
        }
        // 7. checklist 硬规则越权
        if (kind === "checklist" && asset.frontmatter.hard_blocks && asset.frontmatter.hard_blocks.length > 0) {
            allFindings.push({
                asset_id: id,
                file_path: asset.file_path,
                severity: "hard_fail",
                kind: "semantic_conflict",
                detail: `checklist ${id} 平行定义了硬规则，只能引用 canonical (SF-KA-5704)`,
                suggested_action: "mark_supporting",
            });
        }
        // 8. 消费路径检查
        if (kind && ["hard_rule", "workflow", "procedure"].includes(kind)) {
            if (!asset.frontmatter.consumes || asset.frontmatter.consumes.length === 0) {
                allFindings.push({
                    asset_id: id,
                    file_path: asset.file_path,
                    severity: "warning",
                    kind: "consumption_path_missing",
                    detail: `${kind} ${id} 未声明 consumes，消费链路不可追踪 (SF-KA-5709)`,
                    suggested_action: "repair",
                });
            }
        }
        // 9. 中文质量门
        if (asset.body) {
            const zhIssues = checkChineseQuality(asset.body, asset.frontmatter.name ?? "");
            for (const issue of zhIssues) {
                allFindings.push({
                    asset_id: id,
                    file_path: asset.file_path,
                    severity: "warning",
                    kind: "language_quality_issue",
                    detail: issue,
                    suggested_action: "repair",
                });
            }
        }
    }
    // canonical 重复汇总
    for (const [subject, ids] of canonicalSubjects) {
        if (ids.length > 1) {
            for (const dupId of ids) {
                allFindings.push({
                    asset_id: dupId,
                    file_path: "",
                    severity: "hard_fail",
                    kind: "duplicate_canonical",
                    detail: `主题 "${subject}" 存在多个 canonical: ${ids.join(", ")} (SF-KA-5703)`,
                    suggested_action: "mark_supporting",
                });
            }
        }
    }
    const hardFails = allFindings.filter((f) => f.severity === "hard_fail");
    const warnings = allFindings.filter((f) => f.severity === "warning");
    return {
        report_id: `ka-audit-${Date.now()}`,
        generated_at: new Date().toISOString(),
        total_assets: assets.length,
        findings: allFindings,
        hard_fail_count: hardFails.length,
        warning_count: warnings.length,
        info_count: allFindings.filter((f) => f.severity === "info").length,
        passed: hardFails.length === 0,
        summary_zh: hardFails.length === 0
            ? `审计通过: ${assets.length} 个资产，${warnings.length} 个警告`
            : `审计未通过: ${hardFails.length} 个 hard_fail, ${warnings.length} 个警告`,
    };
}
/**
 * 中文质量检查 — 发现明显的质量问题。
 */
function checkChineseQuality(body, assetName) {
    const issues = [];
    // 含糊词检测
    const vagueWords = ["适当", "酌情", "尽量", "可能", "应该可以", "大概"];
    for (const word of vagueWords) {
        if (body.includes(word)) {
            issues.push(`${assetName}: 包含含糊词 "${word}"，建议改为具体标准`);
        }
    }
    // 异常中英文混杂
    const mixedPattern = /[a-zA-Z]{3,}\s*的\s*[a-zA-Z]{3,}/g;
    if (mixedPattern.test(body)) {
        issues.push(`${assetName}: 可能存在不必要的技术名词中英混杂`);
    }
    return issues;
}
/**
 * 快速审计 — 对已有资产做最小化检查，返回是否通过。
 */
export function quickAuditPassed(assets) {
    const report = auditKnowledgeAssets(assets);
    return report.passed;
}
//# sourceMappingURL=knowledge_asset_audit.js.map