/**
 * intent_expander — uncertainty triggers and circuit breaker.
 *
 * The uncertainty protocol identifies risky patterns in intent text and
 * generates decision triggers. The circuit breaker evaluates overall
 * confidence and can produce a brainstorm output when confidence is low.
 */
import { extractKeywords } from "./helpers.js";
// ── 能力 4: 不确定性协议 ──
export const UNCERTAINTY_PATTERNS = [
    {
        pattern: /(?:表结构|DDL|加字段|删字段|改字段|索引|migration)/i,
        trigger_type: "ddl_change",
        description: "涉及数据库结构变更，可能影响现有数据",
        options: [
            { label: "向前兼容变更", tradeoff: "需额外兼容逻辑，但可平滑迁移" },
            { label: "破坏性变更（需迁移脚本）", tradeoff: "直接但需停机或分步迁移" },
        ],
        recommendation: "优先向前兼容方案",
    },
    {
        pattern: /(?:权限|角色|授权|鉴权|permission|auth)/i,
        trigger_type: "permission_change",
        description: "涉及权限/角色变更，影响用户访问控制",
        options: [
            { label: "收紧权限", tradeoff: "安全但可能阻断合法用户" },
            { label: "放宽权限", tradeoff: "便利但增加安全风险" },
        ],
        recommendation: "默认收紧，逐案放开",
    },
    {
        pattern: /(?:金额|价格|费用|支付|退款|计算|结算)/i,
        trigger_type: "amount_logic",
        description: "涉及金额计算逻辑，需要精确性验证",
        options: [
            { label: "复用现有计算逻辑", tradeoff: "安全但可能不适用新场景" },
            { label: "新建计算逻辑", tradeoff: "灵活但需全面测试（含边界值/精度/并发）" },
        ],
        recommendation: "复用现有逻辑优先",
    },
    {
        pattern: /(?:跨系统|外部接口|第三方|回调|同步|推送)/i,
        trigger_type: "cross_system",
        description: "涉及跨系统交互，需要幂等和补偿机制",
        options: [
            { label: "同步调用", tradeoff: "简单但强耦合" },
            { label: "异步+补偿", tradeoff: "解耦但复杂度高" },
        ],
        recommendation: "异步+补偿优先",
    },
    {
        pattern: /(?:状态机|状态流转|审批|审核|工作流)/i,
        trigger_type: "state_transition",
        description: "涉及状态流转逻辑，需要完整的守卫条件",
        options: [
            { label: "扩展现有状态机", tradeoff: "一致但需理解现有流转" },
            { label: "新建独立流程", tradeoff: "独立但可能重复" },
        ],
        recommendation: "扩展现有状态机优先",
    },
    {
        pattern: /(?:删除|清理|归档|批量操作)/i,
        trigger_type: "destructive_operation",
        description: "涉及破坏性操作，需要可恢复机制",
        options: [
            { label: "软删除（可恢复）", tradeoff: "安全但占存储" },
            { label: "硬删除+备份", tradeoff: "干净但恢复成本高" },
        ],
        recommendation: "优先软删除",
    },
    {
        pattern: /(?:并发|锁|竞争|原子|分布式事务)/i,
        trigger_type: "concurrency",
        description: "涉及并发控制，需要确定并发策略",
        options: [
            { label: "乐观锁", tradeoff: "高性能但需冲突重试" },
            { label: "悲观锁", tradeoff: "安全但降低吞吐" },
        ],
        recommendation: "乐观锁优先",
    },
    {
        pattern: /(?:敏感信息|加密|解密|脱敏|密码|token)/i,
        trigger_type: "sensitive_data",
        description: "涉及敏感数据处理，需要安全策略",
        options: [
            { label: "传输+存储加密", tradeoff: "安全但性能有开销" },
            { label: "仅传输加密", tradeoff: "轻量但存储风险" },
        ],
        recommendation: "传输+存储均加密",
    },
];
export function buildUncertaintyTriggers(classification, intent) {
    const triggers = [];
    for (const pattern of UNCERTAINTY_PATTERNS) {
        if (pattern.pattern.test(intent)) {
            triggers.push({
                trigger_type: pattern.trigger_type,
                description: pattern.description,
                options: pattern.options,
                recommendation: pattern.recommendation,
            });
        }
    }
    if (classification.risk === "high" && classification.ambiguity === "high") {
        triggers.push({
            trigger_type: "high_risk_high_ambiguity",
            description: "高风险 + 高歧义任务，意图可能存在多种解读",
            options: [
                { label: "按最保守方案执行", tradeoff: "安全但可能不满足全部需求" },
                { label: "先澄清再执行", tradeoff: "准确但增加前置时间" },
            ],
            recommendation: "先澄清再执行",
        });
    }
    return triggers;
}
// ── 机制 1: 意图熔断器 ──
export const CONFIDENCE_THRESHOLD = 0.95;
/**
 * 意图熔断器 — 评估意图理解置信度，低于阈值时触发熔断并生成头脑风暴辅助决策。
 * @param params - 熔断器参数，包含意图、分类结果、匹配知识条目和降级标记
 * @returns 熔断结果，包含是否触发、置信度、原因和头脑风暴输出
 */
export function checkCircuitBreaker(params) {
    const { intent, classification, matchedEntries, degraded } = params;
    let confidence = 1.0;
    if (degraded || matchedEntries.length === 0) {
        confidence -= 0.35;
    }
    else if (matchedEntries.length < 2) {
        confidence -= 0.15;
    }
    if (classification.ambiguity === "high") {
        confidence -= 0.35;
    }
    else if (classification.ambiguity === "medium") {
        confidence -= 0.15;
    }
    const keywords = extractKeywords(intent);
    if (keywords.length < 2) {
        confidence -= 0.20;
    }
    else if (keywords.length < 3) {
        confidence -= 0.10;
    }
    // degraded 已在上方扣除 -0.35，此处不重复扣分
    confidence = Math.max(0, Math.min(1, confidence));
    if (confidence < CONFIDENCE_THRESHOLD) {
        return {
            tripped: true,
            confidence,
            reason: `意图置信度 ${confidence.toFixed(2)} 低于阈值 ${CONFIDENCE_THRESHOLD}`,
            brainstorm: generateBrainstorm(intent, classification, matchedEntries),
        };
    }
    return { tripped: false, confidence };
}
function generateBrainstorm(_intent, classification, _matchedEntries) {
    const taskLabel = classification.task_type === "feature" ? "新功能" :
        classification.task_type === "bugfix" ? "缺陷修复" :
            classification.task_type === "refactor" ? "重构" : "任务";
    return {
        blind_spots: [
            `【${taskLabel}】是否存在未声明的隐性依赖？`,
            `执行后是否有副作用波及非目标模块？`,
            `极端场景（空数据/并发/超量）是否有防护？`,
        ],
        evolution_tracks: {
            minimal: "极简验证路径: 最小可运行实现 + 核心断言验证",
            industrial: "工业级标准路径: 完整实现 + 边界测试 + 异常处理 + 日志埋点",
            radical: "激进重构路径: 重新审视现有架构，考虑是否需结构级调整",
        },
        decision_questions: [
            {
                question: "优先交付速度还是健壮性？",
                option_a: "极简路径 — 快速验证核心逻辑",
                option_b: "工业级路径 — 含完整边界和异常处理",
            },
            {
                question: "实现范围是否需要扩大？",
                option_a: "限定当前声明范围，后续迭代补充",
                option_b: "现在就处理关联模块，避免技术债积累",
            },
        ],
    };
}
//# sourceMappingURL=uncertainty_circuit.js.map