/**
 * 统一契约注册表 — 运行时注册表、查询、动态注册
 *
 * 问题二十 (Unified Contract Registry) 核心实现:
 * - 统一登记 workflow、guard、verification、delivery、failure、degradation、
 *   metric、language_policy 等所有核心契约
 * - contract_id 作为一等治理身份
 * - policy_id 到 contract_id 的映射
 * - Runtime hard fail gating
 *
 * Capability Registry 保留为能力状态事实源，此表覆盖更广泛的契约类型。
 */
import { getRegistry, cloneEntry } from "./registry_internal.js";
// 重导出校验函数
export { validateContractRegistry, validateWorkflowContractRefs } from "./validation.js";
// 从内部模块重导出 resetRegistry
export { resetRegistry } from "./registry_internal.js";
// ── 查询函数 ──
/** 获取所有契约条目 */
export function getAllContracts() {
    return [...getRegistry().values()].map(cloneEntry);
}
/** 按 contract_id 获取 */
export function getContractById(id) {
    const entry = getRegistry().get(id);
    return entry ? cloneEntry(entry) : undefined;
}
/** 按 policy_id 查找对应 contract_id */
export function getContractByPolicyId(policyId) {
    for (const entry of getRegistry().values()) {
        if (entry.policy_id === policyId)
            return cloneEntry(entry);
    }
    return undefined;
}
/** 按类型列出契约 */
export function listContractsByKind(kind) {
    return [...getRegistry().values()]
        .filter((e) => e.kind === kind)
        .map(cloneEntry);
}
/** 按状态列出契约 */
export function listContractsByState(state) {
    return [...getRegistry().values()]
        .filter((e) => e.state === state)
        .map(cloneEntry);
}
/** 列出所有契约 */
export function listContracts() {
    return getAllContracts();
}
/** 注册表汇总统计 */
export function getContractRegistrySummary() {
    const entries = [...getRegistry().values()];
    const ALL_KINDS = [
        "capability", "mechanism_family", "workflow", "guard",
        "knowledge_injection", "verification", "delivery", "failure",
        "degradation", "metric", "language_policy", "technology_decision",
        "task_context", "knowledge_evolution", "knowledge_lifecycle",
        "template_sync", "adapter_prompt", "documentation_governance",
        "user_promise", "release_compatibility", "chinese_semantic",
        "extension", "platform_compatibility", "governance_action",
        "decision_sovereignty", "brainstorm", "detail_discipline",
        "first_principles", "architecture_design", "existing_system_analysis",
        "coding_readiness", "local_acceptance", "workflow_template_pack",
        "evolution_regression", "plan_proposal_gate", "core_experience_principle",
        "knowledge_asset_governance",
    ];
    const ALL_STATES = [
        "draft", "advisory", "enforced", "experimental", "deprecated", "removed",
    ];
    const by_kind = Object.fromEntries(ALL_KINDS.map((k) => [k, entries.filter((e) => e.kind === k).length]));
    const by_state = Object.fromEntries(ALL_STATES.map((s) => [s, entries.filter((e) => e.state === s).length]));
    const canHardFail = entries.filter((e) => e.hard_fail_allowed && e.state === "enforced");
    const cannotHardFail = entries.filter((e) => !(e.hard_fail_allowed && e.state === "enforced"));
    return {
        total: entries.length,
        by_kind,
        by_state,
        can_hard_fail: canHardFail.map((e) => e.contract_id),
        cannot_hard_fail: cannotHardFail.map((e) => e.contract_id),
    };
}
// ── 运行时硬失败门控 ──
/**
 * 判断契约是否允许 hard fail。
 * 只有 state=enforced 且 hard_fail_allowed=true 的契约才能阻断。
 */
export function canContractHardFail(contractId) {
    const entry = getRegistry().get(contractId);
    if (!entry)
        return false;
    return entry.state === "enforced" && entry.hard_fail_allowed;
}
/**
 * Runtime hard fail gate — 未登记的契约不得 hard fail。
 * 用于运行时检查 workflow 是否引用了合法的 guard/verification/failure 契约。
 */
export function runtimeHardFailGate(contractId, context) {
    const entry = getRegistry().get(contractId);
    if (!entry) {
        return {
            allowed: false,
            reason: `契约 ${contractId} 未在 Unified Contract Registry 登记，不得 hard fail`,
        };
    }
    if (entry.state === "removed") {
        return {
            allowed: false,
            reason: `契约 ${contractId} 已移除，${context} 不得引用已移除契约`,
        };
    }
    if (entry.state === "deprecated") {
        if (entry.replacement_contract_id) {
            return {
                allowed: false,
                reason: `契约 ${contractId} 已废弃，替代契约: ${entry.replacement_contract_id}，请迁移到替代契约`,
            };
        }
        if (entry.migration_note) {
            return {
                allowed: false,
                reason: `契约 ${contractId} 已废弃，迁移说明: ${entry.migration_note}`,
            };
        }
        return {
            allowed: false,
            reason: `契约 ${contractId} 已废弃且无替代/迁移说明，${context} 不得引用`,
        };
    }
    if (entry.state === "advisory" || entry.state === "experimental" || entry.state === "draft") {
        return {
            allowed: false,
            reason: `契约 ${contractId} 状态为 ${entry.state}，advisory/experimental/draft 契约只能 warning/advisory，不能阻断主流程`,
        };
    }
    if (entry.state === "enforced" && !entry.hard_fail_allowed) {
        return {
            allowed: false,
            reason: `契约 ${contractId} enforced 但 hard_fail_allowed=false，不得阻断`,
        };
    }
    if (entry.state === "enforced" && entry.hard_fail_allowed) {
        return { allowed: true, reason: "契约已强制登记且允许 hard fail" };
    }
    return { allowed: false, reason: `契约 ${contractId} 状态为 ${entry.state}，不允许 hard fail` };
}
// ── 动态注册（用于测试和扩展） ──
/** 注册新契约（运行时） */
export function registerContract(entry) {
    const registry = getRegistry();
    if (registry.has(entry.contract_id)) {
        return { success: false, error: `contract_id ${entry.contract_id} 已存在` };
    }
    registry.set(entry.contract_id, cloneEntry(entry));
    return { success: true };
}
/**
 * 内部 helper: 只允许通过 ContractStateStore.apply 调用。
 * 此函数不导出。ContractStateStore 通过 createContractStateApplier 获取闭包引用。
 */
function applyContractStateOverride(override) {
    const registry = getRegistry();
    const entry = registry.get(override.contract_id);
    if (!entry)
        return;
    const updated = cloneEntry(entry);
    updated.state = override.new_state;
    if (override.replacement_contract_id) {
        updated.replacement_contract_id = override.replacement_contract_id;
    }
    if (override.migration_note) {
        updated.migration_note = override.migration_note;
    }
    registry.set(override.contract_id, updated);
}
/** 工厂函数: 返回 applyContractStateOverride 闭包引用，仅供 ContractStateStore 使用 */
export function createContractStateApplier() {
    return applyContractStateOverride;
}
/** 获取所有 policy_id → contract_id 映射 */
export function getPolicyToContractMapping() {
    const result = [];
    for (const entry of getRegistry().values()) {
        if (entry.policy_id) {
            result.push({ policy_id: entry.policy_id, contract_id: entry.contract_id });
        }
    }
    return result;
}
//# sourceMappingURL=registry.js.map