/**
 * Dual-Layer Mechanism Registry — aliases, query functions, completeness check, governance validation.
 *
 * 每个机制都必须有"模板层 + 机制层"双层承载:
 * - 模板层: 告诉 AI 应该怎么做
 * - 机制层: 验证 AI 是否真的做到
 *
 * 模板层降低走偏概率；机制层负责发现、阻断、记录证据并驱动回到修复。
 *
 * 完成定义:
 * Mechanism Done = template_declared + template_consumable
 *                + code_enforced + evidence_recorded + regression_guarded
 */
import fs from "node:fs";
import path from "node:path";
import { listBuiltinConsumableAssets } from "../../templates/consumable_asset_registry/index.js";
import { listMechanismContracts } from "../mechanism_contract_registry/index.js";
import { listWorkflowContracts } from "../../workflow/workflow_contract_registry.js";
import { getAllCapabilities } from "../capability_registry.js";
import { contractToLayerMap, KNOWN_REGISTRIES, INFRASTRUCTURE_EXCEPTIONS } from "./shared.js";
import { MECHANISM_CONTRACTS_CORE } from "./mechanisms_core.js";
import { MECHANISM_CONTRACTS_INFRA } from "./mechanisms_infra.js";
import { MECHANISM_CONTRACTS_EXTENSION } from "./mechanisms_extension.js";
import { MECHANISM_CONTRACTS_RELEASE } from "./mechanisms_release.js";
import { MECHANISM_CONTRACTS_PLATFORM } from "./mechanisms_platform.js";
import { MECHANISM_CONTRACTS_GOVERNANCE } from "./mechanisms_governance.js";
import { MECHANISM_CONTRACTS_AUDIT } from "./mechanisms_audit.js";
import { MECHANISM_CONTRACTS_AUDIT_TAIL } from "./mechanisms_audit_tail.js";
// ── 合并后的机制契约数组 ──
const MECHANISM_CONTRACTS = [
    ...MECHANISM_CONTRACTS_CORE,
    ...MECHANISM_CONTRACTS_INFRA,
    ...MECHANISM_CONTRACTS_EXTENSION,
    ...MECHANISM_CONTRACTS_RELEASE,
    ...MECHANISM_CONTRACTS_PLATFORM,
    ...MECHANISM_CONTRACTS_GOVERNANCE,
    ...MECHANISM_CONTRACTS_AUDIT,
    ...MECHANISM_CONTRACTS_AUDIT_TAIL,
];
// ── 已废弃机制 ID 别名映射 ──
// 旧 ID → 正式 ID。旧 ID 在 MC 中标记为 deprecated，模板/知识资产必须指向正式 ID。
export const MECHANISM_ALIASES = {
    "mc-classifier": "mc-intent-router",
    "mc-knowledge-matching": "mc-knowledge-injection-boundary",
    "mc-workspace-resumer": "mc-task-context-lifecycle",
    "mc-delivery": "mc-delivery-gate",
    "mc-metric-contract": "mc-metric-governance",
    "evidence-grounding": "mc-evidence-grounding",
    "门禁引擎": "mc-stage-gate-engine",
    "回退路由": "mc-rollback-router",
    "切片执行器": "mc-slice-executor",
};
/** 将机制 ID 解析为正式 ID（处理别名） */
export function resolveMechanismId(id) {
    return MECHANISM_ALIASES[id] ?? id;
}
/** 获取所有正式机制 ID 集合 */
export function getAllCanonicalMechanismIds() {
    return new Set(MECHANISM_CONTRACTS.map((c) => c.mechanism_id));
}
// ── 查询函数 ──
/**
 * 列出所有机制的层级映射。
 * @returns 机制层级映射列表
 */
export function listMechanismLayerMaps() {
    return MECHANISM_CONTRACTS.map(contractToLayerMap);
}
/**
 * 根据机制 ID 查找层级映射。
 * @param id - 机制 ID
 * @returns 机制层级映射，未找到时返回 undefined
 */
export function findLayerMapByMechanismId(id) {
    return MECHANISM_CONTRACTS.map(contractToLayerMap).find((m) => m.mechanism_id === id);
}
/**
 * 按优先级列出机制层级映射。
 * @param priority - 优先级（P0/P1/P2/P3）
 * @returns 指定优先级的机制层级映射列表
 */
export function listLayerMapsByPriority(priority) {
    return MECHANISM_CONTRACTS.map(contractToLayerMap).filter((m) => m.priority === priority);
}
/**
 * 按状态列出机制层级映射。
 * @param status - 双层机制状态
 * @returns 指定状态的机制层级映射列表
 */
export function listLayerMapsByStatus(status) {
    return MECHANISM_CONTRACTS.map(contractToLayerMap).filter((m) => m.status === status);
}
/**
 * 检查机制的双层完整性。
 * 验证模板层、代码层、证据、测试和注册表是否齐全。
 * @param map - 机制层级映射
 * @returns 双层完整性检查结果
 */
export function checkDualLayerCompleteness(map) {
    const missing = [];
    const has_template_layer = map.template_assets.length > 0;
    const has_code_layer = map.code_enforcers.length > 0;
    const has_evidence = map.evidence_outputs.length > 0;
    const has_tests = map.tests.length > 0;
    const has_registries = map.registries.length > 0;
    if (!has_template_layer)
        missing.push("template_layer");
    if (!has_code_layer)
        missing.push("code_layer");
    if (!has_evidence)
        missing.push("evidence");
    if (!has_tests)
        missing.push("tests");
    if (!has_registries)
        missing.push("registries");
    if (missing.length > 0) {
        // 完整性缺失仅通过返回值传达，不输出噪音日志
    }
    return {
        mechanism_id: map.mechanism_id,
        has_template_layer,
        has_code_layer,
        has_evidence,
        has_tests,
        has_registries,
        is_complete: missing.length === 0,
        missing,
    };
}
// ── 治理验证 ──
/**
 * 验证机制层级映射的合规性。
 * 检查 ID 唯一性、模板/代码缺口、文件存在性、入口点等。
 * @param maps - 机制层级映射列表（默认使用所有契约）
 * @param rootDir - 项目根目录（默认当前目录）
 * @returns 治理发现列表
 */
export function validateMechanismLayerMaps(maps = MECHANISM_CONTRACTS.map(contractToLayerMap), rootDir = process.cwd(), _options) {
    const findings = [];
    const seenIds = new Set();
    // 预加载消费资产路径用于交叉验证
    const consumablePaths = new Set(listBuiltinConsumableAssets().map((a) => a.path));
    // 预加载已知机制 ID 用于孤立执行器检查
    const knownMechanismIds = new Set(listMechanismContracts().map((c) => c.id));
    const knownCapabilityIds = new Set(getAllCapabilities().map((c) => c.id));
    for (const m of maps) {
        // P0/P1 实验性机制必须被标记为未达 dual_layer_enforced
        if (m.status === "experimental_dual_layer" && (m.priority === "P0" || m.priority === "P1")) {
            findings.push({
                severity: "hard_fail",
                mechanism_id: m.mechanism_id,
                finding_type: "p0_not_dual_layer",
                message: `P0/P1 机制 ${m.mechanism_id} 必须为 dual_layer_enforced，当前: ${m.status}`,
            });
            seenIds.add(m.mechanism_id);
            continue;
        }
        // 非 P0/P1 实验性机制跳过深度验证
        if (m.status === "experimental_dual_layer") {
            seenIds.add(m.mechanism_id);
            continue;
        }
        // 重复 ID
        if (seenIds.has(m.mechanism_id)) {
            findings.push({
                severity: "hard_fail",
                mechanism_id: m.mechanism_id,
                finding_type: "drift_gap",
                message: `Duplicate mechanism_id: ${m.mechanism_id}`,
            });
        }
        seenIds.add(m.mechanism_id);
        // 模板缺口: 有代码执行器但无模板资产
        if (m.code_enforcers.length > 0 && m.template_assets.length === 0) {
            findings.push({
                severity: m.status === "code_only_enforced" ? "advisory" : "hard_fail",
                mechanism_id: m.mechanism_id,
                finding_type: "template_gap",
                message: `机制 ${m.mechanism_id} 有代码执行器但无模板资产 (template_gap)`,
            });
        }
        // 代码缺口: 有模板资产但无代码执行器
        if (m.template_assets.length > 0 && m.code_enforcers.length === 0) {
            findings.push({
                severity: "hard_fail",
                mechanism_id: m.mechanism_id,
                finding_type: "code_gap",
                message: `机制 ${m.mechanism_id} 有模板资产但无代码执行器 (code_gap)`,
            });
        }
        // 证据缺口
        if (m.code_enforcers.length > 0 && m.evidence_outputs.length === 0) {
            findings.push({
                severity: "advisory",
                mechanism_id: m.mechanism_id,
                finding_type: "evidence_gap",
                message: `机制 ${m.mechanism_id} 有代码执行器但无证据输出`,
            });
        }
        // 测试缺口: 未声明测试
        if (m.code_enforcers.length > 0 && m.tests.length === 0) {
            findings.push({
                severity: "hard_fail",
                mechanism_id: m.mechanism_id,
                finding_type: "test_gap",
                message: `机制 ${m.mechanism_id} 有代码执行器但无测试`,
            });
        }
        // 模板资产: 检查文件是否存在 + 消费资产注册表交叉验证
        for (const ta of m.template_assets) {
            // P0/P1/dual_layer_enforced 的资产文件必须存在
            if (!fs.existsSync(path.join(rootDir, ta.path))) {
                const severity = (m.priority === "P0" || m.priority === "P1" || m.status === "dual_layer_enforced")
                    ? "hard_fail" : "advisory";
                findings.push({
                    severity,
                    mechanism_id: m.mechanism_id,
                    finding_type: "asset_unconsumed",
                    message: `模板资产文件不存在: ${ta.path}${severity === "hard_fail" ? " (P0/P1/dual_layer_enforced 必须)" : ""}`,
                });
            }
            // 与消费资产注册表交叉验证
            if (!consumablePaths.has(ta.path)) {
                findings.push({
                    severity: "hard_fail",
                    mechanism_id: m.mechanism_id,
                    finding_type: "asset_unconsumed",
                    message: `模板资产 ${ta.path} 存在但未在 Consumable Asset Registry 中注册`,
                });
            }
        }
        // 检查代码执行器文件是否存在于磁盘
        for (const ce of m.code_enforcers) {
            if (!fs.existsSync(path.join(rootDir, ce))) {
                findings.push({
                    severity: "hard_fail",
                    mechanism_id: m.mechanism_id,
                    finding_type: "code_gap",
                    message: `代码执行器文件不存在: ${ce}`,
                });
            }
        }
        // 检查测试文件是否存在于磁盘 — dual_layer_enforced 为 hard_fail
        for (const t of m.tests) {
            if (!fs.existsSync(path.join(rootDir, t))) {
                const severity = m.status === "dual_layer_enforced" ? "hard_fail" : "advisory";
                findings.push({
                    severity,
                    mechanism_id: m.mechanism_id,
                    finding_type: "test_gap",
                    message: `测试文件不存在: ${t}${severity === "hard_fail" ? " (dual_layer_enforced 必须)" : ""}`,
                });
            }
        }
        // 检查代码入口点是否存在于执行器文件中
        if (m.code_entrypoints.length > 0 && m.code_enforcers.length > 0) {
            for (const ep of m.code_entrypoints) {
                let found = false;
                for (const enforcer of m.code_enforcers) {
                    const enforcerPath = path.join(rootDir, enforcer);
                    if (fs.existsSync(enforcerPath)) {
                        const content = fs.readFileSync(enforcerPath, "utf-8");
                        if (content.includes(ep) && /export\s+(function|const|async\s+function|class)\s+/.test(content.split(ep)[0].slice(-50) + "export " + ep)) {
                            found = true;
                            break;
                        }
                        // 简单检查: 仅查找导出名称
                        const exportPattern = new RegExp(`export\\s+(async\\s+)?(function|const|class|type|interface)\\s+${ep}\\b`);
                        if (exportPattern.test(content)) {
                            found = true;
                            break;
                        }
                        // 更简单: 仅检查名称是否作为导出存在
                        if (content.includes(ep)) {
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    findings.push({
                        severity: "hard_fail",
                        mechanism_id: m.mechanism_id,
                        finding_type: "entrypoint_not_found",
                        message: `代码入口点 ${ep} 在所有强制层文件中未找到`,
                    });
                }
            }
        }
        // 注册表名称验证: 注册表必须是已知名称
        for (const reg of m.registries) {
            if (!KNOWN_REGISTRIES.has(reg)) {
                findings.push({
                    severity: "hard_fail",
                    mechanism_id: m.mechanism_id,
                    finding_type: "drift_gap",
                    message: `registry "${reg}" 不是已知 registry，机制 ${m.mechanism_id} 声明了不存在的 registry`,
                });
            }
        }
        // 孤立执行器检查: 不可达的代码执行器文件
        // 来自机制契约注册表、能力注册表或工作流注册表
        const workflowMechanismIds = new Set(listWorkflowContracts().flatMap((w) => w.required_mechanisms));
        for (const ce of m.code_enforcers) {
            const ceNorm = ce.replace(/\\/g, "/");
            const isKnown = knownMechanismIds.size > 0 && listMechanismContracts().some((mc) => mc.owner_module.replace(/\\/g, "/") === ceNorm
                || (mc.owner_files ?? []).some((ownerFile) => ownerFile.replace(/\\/g, "/") === ceNorm));
            const isCapKnown = knownCapabilityIds.size > 0 && getAllCapabilities().some((cap) => cap.code_files.some((cf) => cf.replace(/\\/g, "/") === ceNorm));
            // 检查此机制是否被任何工作流的 required_mechanisms 引用
            const isWorkflowKnown = workflowMechanismIds.has(m.mechanism_id);
            // 如果执行器文件存在但未在任何注册表中找到，则为孤立
            if (fs.existsSync(path.join(rootDir, ce)) && !isKnown && !isCapKnown && !isWorkflowKnown && !INFRASTRUCTURE_EXCEPTIONS.has(ceNorm)) {
                const orphanSeverity = (m.priority === "P0" || m.priority === "P1" || m.status === "dual_layer_enforced")
                    ? "hard_fail" : "advisory";
                findings.push({
                    severity: orphanSeverity,
                    mechanism_id: m.mechanism_id,
                    finding_type: "orphan_enforcer",
                    message: `代码执行器 ${ce} 不在 Mechanism Contract Registry、Capability Registry 或 Workflow Registry 中${orphanSeverity === "hard_fail" ? " (P0/P1/dual_layer_enforced 必须)" : ""}`,
                });
            }
        }
        // P0/P1 必须为 dual_layer_enforced 或 code_only_enforced（审计补注册机制）
        if ((m.priority === "P0" || m.priority === "P1") && m.status !== "dual_layer_enforced" && m.status !== "code_only_enforced") {
            findings.push({
                severity: "hard_fail",
                mechanism_id: m.mechanism_id,
                finding_type: "p0_not_dual_layer",
                message: `P0/P1 机制 ${m.mechanism_id} 必须为 dual_layer_enforced，当前: ${m.status}`,
            });
        }
        // template_only_advisory 不能有代码执行器
        if (m.status === "template_only_advisory" && m.code_enforcers.length > 0) {
            findings.push({
                severity: "hard_fail",
                mechanism_id: m.mechanism_id,
                finding_type: "template_mechanism_drift",
                message: `机制 ${m.mechanism_id} 状态为 template_only_advisory 但存在代码执行器，状态与实际不一致`,
            });
        }
        // code_only_enforced 必须产生 template_gap 发现
        if (m.status === "code_only_enforced") {
            findings.push({
                severity: "advisory",
                mechanism_id: m.mechanism_id,
                finding_type: "template_gap",
                message: `机制 ${m.mechanism_id} 为 code_only_enforced，必须补充模板层`,
            });
        }
    }
    return findings;
}
//# sourceMappingURL=validation.js.map