/**
 * Tool Invocation Contract Registry
 *
 * MCP 工具 / 适配器边界受控自由契约。
 * 每个工具声明类别 (strict_controlled / read_only_bypass / normal_controlled)、
 * 副作用、授权要求、允许/禁止后续工具。
 * 适配器必须遵守 Adapter Workflow Policy。
 * 治理检查防止 8 类退化。
 */
import { debug } from "../core/logger.js";
// ── 类型定义（保留本地别名供运行时使用） ──
// 注意: 以下类型已移至 types/pipeline.ts，此处通过 import 获取
// ── 适配器工作流策略 ──
/** 适配器工作流策略规则集 */
export const ADAPTER_WORKFLOW_POLICY = [
    {
        id: "awp-01",
        rule: "工具返回的 next_allowed_tools 是下一步默认允许集合",
        enforcement: "hard_fail",
        description: "适配器必须使用工具返回的 next_allowed_tools 作为下一步调用的允许集合",
    },
    {
        id: "awp-02",
        rule: "适配器不得隐式调用 strict controlled 工具",
        enforcement: "hard_fail",
        description: "strict controlled 工具必须在 next_allowed_tools 中且显式授权才能调用",
    },
    {
        id: "awp-03",
        rule: "适配器不得把 read-only bypass 结果当成完成态",
        enforcement: "hard_fail",
        description: "read-only bypass 工具的输出只能作为参考，不能作为任务完成标志",
    },
    {
        id: "awp-04",
        rule: "适配器不得把 advisory warning 当成 enforced gate",
        enforcement: "warning",
        description: "advisory warning 不应阻止正常流程，除非用户明确要求",
    },
    {
        id: "awp-05",
        rule: "适配器遇到 ToolInvocationViolation 必须按 severity 处理",
        enforcement: "hard_fail",
        description: "hard_fail 违规必须停止执行，require_human 必须等待用户确认，warning 必须记录",
    },
    {
        id: "awp-06",
        rule: "适配器最终输出必须中文优先，暴露 warning、degraded、manual_required",
        enforcement: "advisory",
        description: "最终输出应暴露必要 warning、degraded、manual_required 信息",
    },
];
// ── MCP 工具契约 ──
const TOOL_INVOCATION_CONTRACTS = [
    // ── read_only_bypass（20 个工具） ──
    {
        tool_name: "sf_classify",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: false,
        description: "意图分类，确定任务类型、风险、复杂度和执行策略",
        default_next_tools: ["sf_expand", "sf_plan", "sf_explore", "sf_analyze", "sf_status", "sf_debug", "sf_feasibility_check"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold", "sf_verify", "sf_learn", "sf_knowledge_add", "sf_knowledge_update", "sf_capability_update"],
    },
    {
        tool_name: "sf_status",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: false,
        description: "查询任务/系统状态",
        default_next_tools: ["sf_classify", "sf_plan", "sf_explore", "sf_debug", "sf_knowledge_audit", "sf_governance_report", "sf_observability", "sf_team_status"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_plan",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: false,
        description: "任务规划，拆解子任务和执行顺序",
        default_next_tools: ["sf_plan_advance", "sf_expand", "sf_status", "sf_explore", "sf_debug", "sf_classify"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_analyze",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "影响分析，评估变更范围和风险",
        default_next_tools: ["sf_plan", "sf_expand", "sf_status", "sf_explore", "sf_debug", "sf_classify"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_explore",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "方案探索，只读分析可选方案",
        default_next_tools: ["sf_plan", "sf_expand", "sf_status", "sf_analyze", "sf_debug", "sf_classify"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_feasibility_check",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "可行性预判",
        default_next_tools: ["sf_plan", "sf_status", "sf_debug", "sf_classify"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_review",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: false,
        description: "代码审查，只读分析代码质量、安全和风险",
        default_next_tools: ["sf_verify", "sf_status", "sf_debug", "sf_contract_check", "sf_deliver"],
        forbidden_next_tools: ["sf_scaffold"],
    },
    {
        tool_name: "sf_test_guide",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "测试生成指南",
        default_next_tools: ["sf_verify", "sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_test_quality",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "测试质量报告",
        default_next_tools: ["sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_dependency_scan",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "依赖漏洞扫描",
        default_next_tools: ["sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_debt_report",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "技术债务报告",
        default_next_tools: ["sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_coord_check",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "变更协调检查，冲突风险和跨仓库关联",
        default_next_tools: ["sf_verify", "sf_status", "sf_debug", "sf_review", "sf_contract_check"],
        forbidden_next_tools: ["sf_scaffold"],
    },
    {
        tool_name: "sf_contract_check",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "契约变更检查",
        default_next_tools: ["sf_verify", "sf_status", "sf_debug", "sf_review"],
        forbidden_next_tools: ["sf_scaffold"],
    },
    {
        tool_name: "sf_onboard",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "新人引导",
        default_next_tools: ["sf_status", "sf_plan", "sf_explore", "sf_debug", "sf_classify"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_team_status",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "团队状态查询",
        default_next_tools: ["sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_debug",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "智能排障，只读诊断",
        default_next_tools: ["sf_status", "sf_classify", "sf_explore", "sf_analyze", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_observability",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "系统可观测性报告",
        default_next_tools: ["sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_migration_check",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "数据库迁移安全检查",
        default_next_tools: ["sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_knowledge_audit",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "知识审计，只读检查知识状态",
        default_next_tools: ["sf_status", "sf_debug", "sf_knowledge_update", "sf_knowledge_add"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_governance_report",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "治理报告",
        default_next_tools: ["sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_audit_integration",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "主链路集成审计，检测孤岛模块（只读分析）",
        default_next_tools: ["sf_status", "sf_debug", "sf_governance_report"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_navigation",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "工作流导航：查询当前项目阶段、任务阶段、下一步操作和禁止操作",
        default_next_tools: ["sf_classify", "sf_expand", "sf_verify", "sf_deliver"],
        forbidden_next_tools: [],
    },
    // ── normal_controlled（2 个工具） ──
    {
        tool_name: "sf_expand",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: true,
        description: "意图扩展，生成执行 prompt、scope、验收条件",
        default_next_tools: ["sf_verify", "sf_review", "sf_deliver", "sf_status", "sf_plan", "sf_debug", "sf_scaffold", "sf_coord_check"],
        forbidden_next_tools: ["sf_classify", "sf_expand"],
    },
    {
        tool_name: "sf_plan_advance",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: true,
        description: "推进规划到下一步",
        default_next_tools: ["sf_expand", "sf_plan", "sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_verify", "sf_scaffold", "sf_deliver"],
    },
    // ── strict_controlled（10 个工具） ──
    {
        tool_name: "sf_verify",
        category: "strict_controlled",
        side_effects: ["command_execution", "task_context_write"],
        requires_authorization: true,
        requires_workflow: true,
        description: "验证，执行构建/测试命令，生成验证报告（含只读计划模式）",
        default_next_tools: ["sf_record_verification_execution", "sf_learn", "sf_review", "sf_status", "sf_debug", "sf_deliver"],
        forbidden_next_tools: ["sf_classify", "sf_expand"],
    },
    {
        tool_name: "sf_record_verification_execution",
        category: "strict_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: true,
        requires_workflow: true,
        description: "录入真实验证执行结果，VerificationResult passed 的唯一合法入口",
        default_next_tools: ["sf_accept", "sf_verify", "sf_learn", "sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_classify", "sf_expand"],
    },
    {
        tool_name: "sf_learn",
        category: "strict_controlled",
        side_effects: ["knowledge_write", "task_context_write"],
        requires_authorization: true,
        requires_workflow: true,
        description: "学习，从任务结果提取新知识",
        default_next_tools: ["sf_verify", "sf_deliver", "sf_status", "sf_knowledge_audit", "sf_knowledge_update"],
        forbidden_next_tools: ["sf_classify", "sf_expand"],
    },
    {
        tool_name: "sf_accept",
        category: "strict_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: true,
        requires_workflow: true,
        description: "记录任务验收证据（本地验收 + 产物确认），解除 sf_deliver 的本地验收门和产物状态门",
        default_next_tools: ["sf_deliver", "sf_status", "sf_verify", "sf_learn"],
        forbidden_next_tools: ["sf_classify", "sf_expand", "sf_scaffold"],
    },
    {
        tool_name: "sf_deliver",
        category: "strict_controlled",
        side_effects: ["git_commit", "git_push", "pr_create", "task_context_write"],
        requires_authorization: true,
        requires_workflow: true,
        description: "交付，执行 git commit/push/PR，需要显式用户授权",
        default_next_tools: ["sf_status", "sf_knowledge_audit", "sf_knowledge_update", "sf_governance_report"],
        forbidden_next_tools: ["sf_verify", "sf_scaffold", "sf_classify", "sf_expand", "sf_deliver"],
    },
    {
        tool_name: "sf_scaffold",
        category: "strict_controlled",
        side_effects: ["file_write", "task_context_write"],
        requires_authorization: true,
        requires_workflow: true,
        description: "脚手架生成，写入新文件到项目",
        default_next_tools: ["sf_verify", "sf_status", "sf_debug"],
        forbidden_next_tools: ["sf_scaffold", "sf_deliver"],
    },
    {
        tool_name: "sf_knowledge_add",
        category: "strict_controlled",
        side_effects: ["knowledge_write"],
        requires_authorization: true,
        requires_workflow: false,
        description: "添加知识条目到知识库",
        default_next_tools: ["sf_status", "sf_knowledge_audit", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_knowledge_update",
        category: "strict_controlled",
        side_effects: ["knowledge_write"],
        requires_authorization: true,
        requires_workflow: false,
        description: "更新知识条目",
        default_next_tools: ["sf_status", "sf_knowledge_audit", "sf_debug"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_audit_sample",
        category: "read_only_bypass",
        side_effects: ["none"],
        requires_authorization: false,
        requires_workflow: false,
        description: "审计抽样，从审计池按风险加权抽样生成抽检清单（只读）",
        default_next_tools: ["sf_status", "sf_debug", "sf_governance_report"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_escape_report",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: false,
        description: "逃逸报告，记录逃逸/误伤/工具故障",
        default_next_tools: ["sf_status", "sf_debug", "sf_governance_report"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_capability_update",
        category: "normal_controlled",
        side_effects: ["task_context_write", "config_write"],
        requires_authorization: true,
        requires_workflow: false,
        description: "能力状态更新，需要 confirm=true、confirmed_by 非空、evidence_ids 匹配 escape report。支持 dry_run 校验",
        default_next_tools: ["sf_status", "sf_debug", "sf_governance_report"],
        forbidden_next_tools: ["sf_deliver", "sf_scaffold"],
    },
    {
        tool_name: "sf_resume_workspace",
        category: "normal_controlled",
        side_effects: ["task_context_write"],
        requires_authorization: false,
        requires_workflow: false,
        description: "恢复工作区，扫描中断工单并播报当前进度",
        default_next_tools: ["sf_status", "sf_classify", "sf_debug"],
        forbidden_next_tools: ["sf_verify", "sf_scaffold", "sf_deliver", "sf_learn"],
    },
];
// ── 查询函数 ──
/** 列出所有已注册的工具调用契约 */
export function listToolInvocationContracts() {
    debug("工具调用契约", "列出所有工具契约");
    return TOOL_INVOCATION_CONTRACTS;
}
/** 按工具名称查找对应的调用契约 */
export function findToolInvocationContractByName(toolName) {
    debug("工具调用契约", "按名称查找契约 ", toolName);
    return TOOL_INVOCATION_CONTRACTS.find((c) => c.tool_name === toolName);
}
/** 查找所有严格受控工具的契约 */
export function findStrictControlledTools() {
    debug("工具调用契约", "查找严格受控工具");
    return TOOL_INVOCATION_CONTRACTS.filter((c) => c.category === "strict_controlled");
}
/** 查找所有只读旁路工具的契约 */
export function findReadOnlyBypassTools() {
    debug("工具调用契约", "查找只读旁路工具");
    return TOOL_INVOCATION_CONTRACTS.filter((c) => c.category === "read_only_bypass");
}
/** 按类别查找工具调用契约 */
export function findByCategory(category) {
    debug("工具调用契约", "按类别查找工具 ", category);
    return TOOL_INVOCATION_CONTRACTS.filter((c) => c.category === category);
}
// ── 副作用辅助函数 ──
const WRITE_SIDE_EFFECTS = [
    "file_write",
    "knowledge_write",
    "config_write",
    "command_execution",
    "git_commit",
    "git_push",
    "pr_create",
    "external_write",
];
/** 检查副作用列表是否包含写入类副作用 */
export function hasWriteSideEffect(effects) {
    debug("工具调用契约", "检查写入副作用 ", effects);
    return effects.some((e) => WRITE_SIDE_EFFECTS.includes(e));
}
// ── 运行时: 创建工具追踪 ──
/** 创建工具调用追踪记录 */
export function createToolTrace(params) {
    debug("工具调用契约", "创建工具追踪 ", { tool_name: params.tool_name, invocation_id: params.invocation_id });
    const contract = findToolInvocationContractByName(params.tool_name);
    if (!contract) {
        debug("工具调用契约", "未找到契约定义，使用默认值 ", params.tool_name);
    }
    return {
        tool_name: params.tool_name,
        invocation_id: params.invocation_id,
        task_id: params.task_id,
        workflow_id: params.workflow_id,
        route: params.route,
        execution_shape: params.execution_shape,
        contract_ids: params.contract_ids ?? [],
        capability_ids: params.capability_ids ?? [],
        guard_report_id: params.guard_report_id,
        degraded: params.degraded ?? false,
        warnings: params.warnings ?? [],
        side_effects: params.actual_side_effects,
        next_allowed_tools: params.next_allowed_tools ?? contract?.default_next_tools ?? [],
        forbidden_tools: params.forbidden_tools ?? contract?.forbidden_next_tools ?? [],
        authorization: params.authorization,
        bypass: params.bypass,
    };
}
// ── 运行时: 创建违规记录 ──
/** 创建工具调用违规记录 */
export function createViolation(params) {
    debug("工具调用契约", "创建违规记录 ", { tool_name: params.tool_name, violation_type: params.violation_type });
    const contract = findToolInvocationContractByName(params.tool_name);
    const severity = classifyViolationSeverity(params.violation_type, contract?.category);
    return {
        invocation_id: params.invocation_id,
        tool_name: params.tool_name,
        violation_type: params.violation_type,
        severity,
        reason: params.reason,
        recovery: params.recovery,
    };
}
// ── 运行时: 分类违规严重度 ──
/** 根据违规类型和工具类别分类违规严重级别 */
export function classifyViolationSeverity(violationType, toolCategory) {
    debug("工具调用契约", "分类违规严重度 ", { violationType, toolCategory });
    switch (violationType) {
        case "not_allowed_next_tool":
            debug("工具调用契约", "不允许的后续工具 ", toolCategory);
            return toolCategory === "strict_controlled"
                ? "hard_fail"
                : toolCategory === "read_only_bypass"
                    ? "warning"
                    : "require_human";
        case "side_effect_exceeded":
            return "hard_fail";
        case "missing_authorization":
            return toolCategory === "strict_controlled"
                ? "hard_fail"
                : "require_human";
        case "guard_blocked":
            return "hard_fail";
        case "read_only_bypass_write":
            return "hard_fail";
        case "contract_state_mismatch":
            return "hard_fail";
        case "trace_missing":
            return "warning";
    }
}
/** 验证工具调用是否符合契约约束，返回违规列表 */
export function validateToolInvocation(params) {
    debug("工具调用契约", "验证工具调用 ", { tool_name: params.tool_name, workflow_id: params.workflow_id });
    const violations = [];
    const iid = `violation-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
    const baseContract = findToolInvocationContractByName(params.tool_name);
    const contract = params._contractOverride ?? baseContract;
    if (params._contractOverride) {
        debug("工具调用契约", "使用覆盖契约 ", params.tool_name);
    }
    else if (!baseContract) {
        debug("工具调用契约", "未找到契约定义 ", params.tool_name);
    }
    // 1. 检查工具是否在 next_allowed 列表中
    debug("工具调用契约", "检查后续工具允许列表");
    if (params.current_next_allowed.length > 0 &&
        !params.current_next_allowed.includes(params.tool_name)) {
        const bypassAllowed = contract?.category === "read_only_bypass" &&
            params.bypass?.allowed === true;
        if (!bypassAllowed) {
            debug("工具调用契约", "后续工具不在允许列表且未旁路 ", params.tool_name);
            violations.push(createViolation({
                invocation_id: iid,
                tool_name: params.tool_name,
                violation_type: "not_allowed_next_tool",
                reason: `工具 ${params.tool_name} 不在 next_allowed_tools [${params.current_next_allowed.join(", ")}] 中`,
                recovery: "回到 workflow contract 确认工具调用顺序",
            }));
        }
    }
    // 2. 检查禁止列表
    debug("工具调用契约", "检查禁止工具列表");
    if (params.current_forbidden.includes(params.tool_name)) {
        debug("工具调用契约", "工具在禁止列表中 ", params.tool_name);
        violations.push(createViolation({
            invocation_id: iid,
            tool_name: params.tool_name,
            violation_type: "not_allowed_next_tool",
            reason: `工具 ${params.tool_name} 在 forbidden_tools 中`,
            recovery: "确认 workflow 状态，选择允许的工具",
        }));
    }
    // 3. 需要授权的工具必须检查授权
    debug("工具调用契约", "检查授权要求");
    if (contract?.requires_authorization) {
        if (!params.authorization || !params.authorization.granted) {
            debug("工具调用契约", "缺少必要授权 ", params.tool_name);
            violations.push(createViolation({
                invocation_id: iid,
                tool_name: params.tool_name,
                violation_type: "missing_authorization",
                reason: `工具 ${params.tool_name} 需要授权但缺少授权`,
                recovery: "获取用户显式授权后再调用",
            }));
        }
    }
    // 4. 只读旁路工具不得产生写入副作用
    debug("工具调用契约", "检查只读旁路工具写入副作用");
    if (contract?.category === "read_only_bypass") {
        if (hasWriteSideEffect(params.actual_side_effects)) {
            debug("工具调用契约", "只读旁路工具产生写入副作用 ", params.tool_name);
            violations.push(createViolation({
                invocation_id: iid,
                tool_name: params.tool_name,
                violation_type: "read_only_bypass_write",
                reason: `read-only bypass 工具 ${params.tool_name} 产生了写入副作用: ${params.actual_side_effects.join(", ")}`,
                recovery: "回到 workflow contract，通过 strict controlled 工具执行写入",
            }));
        }
    }
    // 5. 副作用不得超过契约声明
    debug("工具调用契约", "检查未声明副作用");
    if (contract) {
        const undeclared = params.actual_side_effects.filter((e) => !contract.side_effects.includes(e));
        if (undeclared.length > 0) {
            debug("工具调用契约", "发现未声明副作用 ", { tool_name: params.tool_name, undeclared });
            violations.push(createViolation({
                invocation_id: iid,
                tool_name: params.tool_name,
                violation_type: "side_effect_exceeded",
                reason: `工具 ${params.tool_name} 产生未声明的副作用: ${undeclared.join(", ")}`,
                recovery: "检查工具实现是否与契约一致",
            }));
        }
    }
    // 6. 严格受控工具必须要求工作流
    debug("工具调用契约", "检查严格受控工具工作流要求");
    if (contract?.category === "strict_controlled" && contract.requires_workflow && !params.workflow_id) {
        debug("工具调用契约", "严格受控工具缺少工作流ID ", params.tool_name);
        violations.push(createViolation({
            invocation_id: iid,
            tool_name: params.tool_name,
            violation_type: "contract_state_mismatch",
            reason: `strict controlled 工具 ${params.tool_name} 需要 workflow 但未提供 workflow_id`,
            recovery: "先完成 classify/expand 流程再调用此工具",
        }));
    }
    if (violations.length > 0) {
        debug("工具调用契约", "验证发现违规 ", violations.length, "项");
    }
    else {
        debug("工具调用契约", "验证通过，无违规");
    }
    return violations;
}
// ── 治理验证 ──
/** 治理验证所有工具调用契约的结构完整性 */
export function validateToolInvocationContracts(contracts = TOOL_INVOCATION_CONTRACTS) {
    debug("工具调用契约", "治理验证 ", { contractCount: contracts.length });
    const findings = [];
    const allNames = new Set(contracts.map((c) => c.tool_name));
    for (const tc of contracts) {
        // 规则 1: every tool must have default_next_tools (trace requirement implies this)
        if (tc.default_next_tools.length === 0 && tc.category !== "read_only_bypass") {
            findings.push({
                severity: "hard_fail",
                tool_name: tc.tool_name,
                rule: "gc-next-tools-missing",
                message: `工具 ${tc.tool_name} 没有声明 default_next_tools`,
            });
        }
        // 规则 2: strict controlled must require authorization
        if (tc.category === "strict_controlled" && !tc.requires_authorization) {
            findings.push({
                severity: "hard_fail",
                tool_name: tc.tool_name,
                rule: "gc-strict-no-auth",
                message: `strict controlled 工具 ${tc.tool_name} 未声明 requires_authorization`,
            });
        }
        // 规则 3: read-only bypass must not have write side effects
        if (tc.category === "read_only_bypass" && hasWriteSideEffect(tc.side_effects)) {
            findings.push({
                severity: "hard_fail",
                tool_name: tc.tool_name,
                rule: "gc-readonly-write-effect",
                message: `read-only bypass 工具 ${tc.tool_name} 有写入副作用: ${tc.side_effects.join(", ")}`,
            });
        }
        // 规则 4: strict controlled must either be workflow-bound or explicitly authorized as a standalone write.
        if (tc.category === "strict_controlled" && !tc.requires_workflow && !tc.requires_authorization) {
            findings.push({
                severity: "hard_fail",
                tool_name: tc.tool_name,
                rule: "gc-strict-standalone-no-auth",
                message: `standalone strict controlled 工具 ${tc.tool_name} 未声明 requires_authorization`,
            });
        }
        // 规则 5: side_effects must match category (sf_status exempt: dynamic cancel)
        if (tc.category === "read_only_bypass" &&
            tc.tool_name !== "sf_status" &&
            tc.side_effects.length > 0 &&
            !tc.side_effects.every((e) => e === "none")) {
            findings.push({
                severity: "hard_fail",
                tool_name: tc.tool_name,
                rule: "gc-side-effect-category-mismatch",
                message: `read-only bypass 工具 ${tc.tool_name} 的 side_effects 包含非 none 值`,
            });
        }
        // 规则 6: strict controlled must have forbidden_next_tools
        if (tc.category === "strict_controlled" && tc.forbidden_next_tools.length === 0) {
            findings.push({
                severity: "advisory",
                tool_name: tc.tool_name,
                rule: "gc-strict-no-forbidden",
                message: `strict controlled 工具 ${tc.tool_name} 没有声明 forbidden_next_tools`,
            });
        }
        // 规则 7: description must not be empty
        if (!tc.description) {
            findings.push({
                severity: "hard_fail",
                tool_name: tc.tool_name,
                rule: "gc-no-description",
                message: `工具 ${tc.tool_name} 没有描述`,
            });
        }
        // 规则 8: referenced next tools must exist
        for (const next of tc.default_next_tools) {
            if (!allNames.has(next)) {
                findings.push({
                    severity: "hard_fail",
                    tool_name: tc.tool_name,
                    rule: "gc-invalid-next-tool",
                    message: `工具 ${tc.tool_name} 引用了不存在的 next tool: ${next}`,
                });
            }
        }
        for (const forbidden of tc.forbidden_next_tools) {
            if (!allNames.has(forbidden)) {
                findings.push({
                    severity: "advisory",
                    tool_name: tc.tool_name,
                    rule: "gc-invalid-forbidden-tool",
                    message: `工具 ${tc.tool_name} 引用了不存在的 forbidden tool: ${forbidden}`,
                });
            }
        }
        // 规则 9: no duplicate tool in default_next_tools
        const uniqueNext = new Set(tc.default_next_tools);
        if (uniqueNext.size !== tc.default_next_tools.length) {
            findings.push({
                severity: "advisory",
                tool_name: tc.tool_name,
                rule: "gc-duplicate-next-tool",
                message: `工具 ${tc.tool_name} 的 default_next_tools 包含重复项`,
            });
        }
    }
    // 跨注册表: 检查重复工具名
    const nameCounts = new Map();
    for (const tc of contracts) {
        nameCounts.set(tc.tool_name, (nameCounts.get(tc.tool_name) ?? 0) + 1);
    }
    for (const [name, count] of nameCounts) {
        if (count > 1) {
            findings.push({
                severity: "hard_fail",
                tool_name: name,
                rule: "gc-duplicate-tool-name",
                message: `工具名 ${name} 注册了 ${count} 次`,
            });
        }
    }
    if (findings.length > 0) {
        debug("工具调用契约", "治理验证发现 ", findings.length, "项问题");
    }
    else {
        debug("工具调用契约", "治理验证通过，无问题");
    }
    return findings;
}
//# sourceMappingURL=tool_invocation_contract_registry.js.map