// ── CEP 评估与 S4 门控函数 ──
// 从 tools.ts 提取: 触发常量、触发函数、S4 门控检查、CEP 评估函数。
function createLazy(loader) {
    const mod = { loaded: null, promise: null };
    return () => {
        if (mod.loaded)
            return Promise.resolve(mod.loaded);
        if (!mod.promise)
            mod.promise = loader().then(m => { mod.loaded = m; return m; });
        return mod.promise;
    };
}
const lazyTechnologyDecision = createLazy(() => import("../../engine/contracts/technology_decision.js"));
const lazyDetailDiscipline = createLazy(() => import("../../engine/contracts/detail_discipline.js"));
const lazyFirstPrinciples = createLazy(() => import("../../engine/contracts/first_principles.js"));
const lazyBrainstormContract = createLazy(() => import("../../engine/contracts/brainstorm_contract.js"));
// ── S4 触发判定函数 ──
// 不依赖 hasInstructionContract，基于 route + intent 风险信号判断是否需要 enforcement。
// 关键设计: 不是所有 code_change 都触发，只有 intent 含高风险/复杂信号时才触发。
// 低风险场景（skip_chat / direct_answer / 无风险信号的 code_change）不触发。
const HIGH_IMPACT_KEYWORDS = /架构|技术选型|数据库|框架|多端|跨模块|高影响|高风险|migration|技术路线|选型|rework/i;
const UNCERTAINTY_KEYWORDS = /不确定|方案选择|多选项|权衡|脑暴|brainstorm|多方案|选型|比较/i;
const DETAIL_INTENSIVE_KEYWORDS = /多步骤|复杂|跨模块|高风险|多端|分布式|微服务/i;
const LOW_RISK_ROUTES = new Set(["skip_chat", "direct_answer", "operation", "planning", "review", "source_extraction", "acceptance"]);
/** 技术选型/架构/数据库/框架/高影响决策 → 需 decision sovereignty gate */
export function requiresDecisionSovereignty(ctx, route) {
    if (!ctx)
        return false;
    const routeVal = route ?? ctx.classification?.route_decision?.route ?? ctx.route_decision?.route;
    if (!routeVal || LOW_RISK_ROUTES.has(routeVal))
        return false;
    // 所有路由都要求 intent 含高影响信号
    const hasHighImpact = ctx.intent && HIGH_IMPACT_KEYWORDS.test(ctx.intent);
    if (!hasHighImpact) {
        // instruction_contract 的 risk/high_impact 也可作为信号
        const ic = ctx.instruction_contract;
        if (!ic || (!ic.risk && !ic.high_impact))
            return false;
        if (ic.risk !== "high" && !ic.high_impact)
            return false;
    }
    // artifact_generation / analysis / code_change + 高影响 intent → 触发
    return true;
}
/** 多步骤/不确定/高风险任务 → 需 detail discipline gate */
export function requiresDetailDiscipline(ctx, route) {
    if (!ctx)
        return false;
    const routeVal = route ?? ctx.classification?.route_decision?.route ?? ctx.route_decision?.route;
    if (!routeVal || LOW_RISK_ROUTES.has(routeVal))
        return false;
    // 复杂 intent 触发
    const hasComplexSignals = ctx.intent && DETAIL_INTENSIVE_KEYWORDS.test(ctx.intent);
    if (!hasComplexSignals) {
        const ic = ctx.instruction_contract;
        if (!ic || (!ic.risk && !ic.high_impact))
            return false;
        if (ic.risk !== "high" && !ic.high_impact)
            return false;
    }
    return true;
}
/** 高影响任务/架构设计/复杂编码/跨模块变更 → 需 first principles gate */
export function requiresFirstPrinciples(ctx, route) {
    if (!ctx)
        return false;
    const routeVal = route ?? ctx.classification?.route_decision?.route ?? ctx.route_decision?.route;
    if (!routeVal || LOW_RISK_ROUTES.has(routeVal))
        return false;
    // 所有路由都要求 intent 含高影响信号
    const hasHighImpact = ctx.intent && HIGH_IMPACT_KEYWORDS.test(ctx.intent);
    if (!hasHighImpact) {
        const ic = ctx.instruction_contract;
        if (!ic || (!ic.risk && !ic.high_impact))
            return false;
        if (ic.risk !== "high" && !ic.high_impact)
            return false;
    }
    return true;
}
/** 不确定项/方案选择/多选项 → 需 brainstorm gate */
export function requiresBrainstorm(ctx, route) {
    if (!ctx)
        return false;
    const routeVal = route ?? ctx.classification?.route_decision?.route ?? ctx.route_decision?.route;
    if (!routeVal || LOW_RISK_ROUTES.has(routeVal))
        return false;
    // 仅当 intent 含不确定性信号时才触发
    const hasUncertainty = ctx.intent && UNCERTAINTY_KEYWORDS.test(ctx.intent);
    if (!hasUncertainty)
        return false;
    if (routeVal === "analysis" || routeVal === "artifact_generation")
        return true;
    if (routeVal === "code_change")
        return true;
    const ic = ctx.instruction_contract;
    if (ic && ic.uncertainty)
        return true;
    return false;
}
/**
 * 技术选型决策门 — 高影响技术决策需用户确认。
 * Decision Sovereignty enforcement。
 * 不依赖 hasInstructionContract — 触发由 requiresDecisionSovereignty 判定。
 */
export async function checkDecisionSovereigntyGate(params) {
    if (!params.ctx)
        return { allowed: true, not_applicable_with_reason: "无任务上下文" };
    const triggered = requiresDecisionSovereignty(params.ctx, params.route);
    if (!triggered) {
        return { allowed: true, not_applicable_with_reason: "非高影响技术决策场景，跳过 decision sovereignty gate" };
    }
    const decisionContract = params.ctx.technology_decision_contract;
    if (!decisionContract) {
        return { allowed: false, reason_zh: "高影响技术决策场景缺 technology_decision_contract，无法执行决策主权校验" };
    }
    const decisionModule = await lazyTechnologyDecision();
    const validation = decisionModule.validateTechnologyDecision(decisionContract);
    if (!validation.valid) {
        return { allowed: false, reason_zh: `技术选型决策校验失败: ${validation.violations.join("; ")}`, expected_schema: validation.expected_schema };
    }
    // 有决策记录时评估执行状态
    const decisionRecord = params.ctx.technology_decision_record;
    if (decisionRecord) {
        const evaluation = decisionModule.evaluateDecisionExecution(decisionContract, decisionRecord);
        if (evaluation.requires_human_gate && !decisionContract.human_gate_evidence) {
            return { allowed: false, reason_zh: "高影响技术决策需用户确认（human gate），请提供确认证据", requires_human_gate: true };
        }
        if (!evaluation.allowed) {
            return { allowed: false, reason_zh: evaluation.reason };
        }
    }
    else {
        // 无决策记录: 契约已验证通过，但需 human_gate_evidence 确认（如有高范围决策）
        if (decisionContract.human_gate_required && !decisionContract.human_gate_evidence) {
            return { allowed: false, reason_zh: "高影响技术决策需用户确认（human gate），请提供确认证据", requires_human_gate: true };
        }
    }
    return { allowed: true };
}
/**
 * 细节纪律门 — 复杂任务缺关键细节维度时阻断。
 * Detail Discipline enforcement。
 * 不依赖 hasInstructionContract — 触发由 requiresDetailDiscipline 判定。
 */
export async function checkDetailDisciplineGate(params) {
    if (!params.ctx)
        return { allowed: true, not_applicable_with_reason: "无任务上下文" };
    const triggered = requiresDetailDiscipline(params.ctx, params.route);
    if (!triggered) {
        return { allowed: true, not_applicable_with_reason: "非复杂/多步骤任务场景，跳过 detail discipline gate" };
    }
    const detailContract = params.ctx.detail_discipline_contract;
    if (!detailContract) {
        return { allowed: false, reason_zh: "多步骤/复杂任务缺 detail_discipline_contract，无法执行细节纪律校验" };
    }
    const detailModule = await lazyDetailDiscipline();
    const check = detailModule.performDetailCheck(detailContract, detailContract.contract_id ?? "unknown", "implementation", params.ctx.provided_details ?? {});
    if (check.blocking) {
        const riskItems = detailModule.generateRiskItems(check);
        const blockingLabels = riskItems.filter(r => r.severity === "blocking").map(r => r.dimension ?? r.description);
        return { allowed: false, reason_zh: `任务方案缺关键细节: ${blockingLabels.join("; ")}`, missing_details: blockingLabels };
    }
    return { allowed: true };
}
/**
 * 第一性原理门 — 高影响任务需目标/约束/本质问题/权衡。
 * First Principles enforcement。
 * 不依赖 hasInstructionContract — 触发由 requiresFirstPrinciples 判定。
 */
export async function checkFirstPrinciplesGate(params) {
    if (!params.ctx)
        return { allowed: true, not_applicable_with_reason: "无任务上下文" };
    const triggered = requiresFirstPrinciples(params.ctx, params.route);
    if (!triggered) {
        return { allowed: true, not_applicable_with_reason: "非高影响任务场景，跳过 first principles gate" };
    }
    const fpFrame = params.ctx.first_principles_frame;
    if (!fpFrame) {
        return { allowed: false, reason_zh: "高影响任务缺 first_principles_frame，无法执行第一性原理校验" };
    }
    const fpModule = await lazyFirstPrinciples();
    const validation = fpModule.validateFirstPrinciplesForHighImpact(fpFrame);
    if (!validation.passed) {
        return { allowed: false, reason_zh: `高影响任务缺第一性原理推理: ${validation.violations.join("; ")}`, failures: validation.violations, expected_schema: validation.expected_schema };
    }
    return { allowed: true };
}
/**
 * 脑暴/方案探索门 — 不确定项需多方案+推荐理由+用户确认。
 * Brainstorm Contract enforcement。
 * 不依赖 hasInstructionContract — 触发由 requiresBrainstorm 判定。
 */
export async function checkBrainstormGate(params) {
    if (!params.ctx)
        return { allowed: true, not_applicable_with_reason: "无任务上下文" };
    const triggered = requiresBrainstorm(params.ctx, params.route);
    if (!triggered) {
        return { allowed: true, not_applicable_with_reason: "非不确定/方案选择场景，跳过 brainstorm gate" };
    }
    const brainstormSession = params.ctx.brainstorm_session;
    if (!brainstormSession) {
        return { allowed: false, reason_zh: "不确定项/方案选择缺 brainstorm_session，无法执行方案探索校验" };
    }
    const brainstormModule = await lazyBrainstormContract();
    const validation = brainstormModule.validateBrainstormSession(brainstormSession);
    if (!validation.valid) {
        return { allowed: false, reason_zh: `方案探索不完整: ${validation.violations.join("; ")}`, violations: validation.violations, expected_schema: validation.expected_schema };
    }
    // 脑暴推荐永远不能自动执行 — 需 Decision Sovereignty human gate
    const canAutoExec = brainstormModule.canBrainstormAutoExecute(brainstormSession);
    if (canAutoExec) {
        return { allowed: false, reason_zh: "脑暴推荐不能绕过用户确认，需通过 Decision Sovereignty human gate" };
    }
    return { allowed: true };
}
/**
 */
export async function assessCepAfterVerification(params) {
    const cepModule = await import("../../engine/audit/core_experience_principle.js");
    const result = cepModule.evaluateCoreExperiencePrinciple({
        task_id: params.task_id,
        workflow_id: "sf_verify",
        has_mainline_hooks: true,
        has_owner_contracts: true,
        natural_language_entry: true,
        requires_internal_contract_knowledge: false,
        user_path_steps: 3,
        has_failures: params.has_failures ?? false,
        hard_fail_downgraded: params.hard_fail_downgraded ?? false,
        forced_heavy_process: false,
        has_sufficient_evidence: params.has_verification_evidence,
        output_too_long_no_summary: false,
        report_only_no_repair: false,
        failed_but_marked_done: params.failed_but_marked_done ?? false,
        auto_repair_overreach: false,
        repair_reverified: false,
        outputs_raw_noise: false,
    });
    return {
        passed: result.passed,
        violations: result.violations.map((v) => ({
            principle: v.principle,
            severity: v.severity,
            reason_zh: v.reason_zh,
            required_action: v.required_action,
        })),
        evaluated_principles: result.evaluated_principles,
    };
}
/**
 * CEP 集成: 交付前 false completion 检查 — 从 sf_deliver handler 提取的真实主链路函数。
 * 返回 CEP 决策（blocked/repair_reverify/allowed），由 handler 和 gate 共用。
 */
export async function assessCepBeforeDelivery(params) {
    const cepModule = await import("../../engine/audit/core_experience_principle.js");
    const nfcResult = cepModule.evaluateNoFalseCompletion({
        verification_passed: params.verification_passed,
        build_passed: params.build_passed,
        browser_acceptance_passed: params.browser_acceptance_passed,
        guard_passed: params.guard_passed,
        evidence_sufficient: params.evidence_sufficient,
        current_status: params.current_status,
    });
    return {
        decision: nfcResult.decision,
        reason_zh: nfcResult.reason_zh ?? "",
        passed: nfcResult.decision === "completed",
    };
}
/**
 * CEP 集成: 工作流解析后评估 — 检查机制是否接入真实主链路、用户路径是否过短。
 */
export async function assessCepAfterWorkflowResolve(params) {
    const cepModule = await import("../../engine/audit/core_experience_principle.js");
    const result = cepModule.evaluateCoreExperiencePrinciple({
        task_id: params.task_id,
        workflow_id: "workflow_resolve",
        has_mainline_hooks: params.workflow_resolved,
        has_owner_contracts: params.workflow_resolved,
        natural_language_entry: true,
        requires_internal_contract_knowledge: false,
        user_path_steps: 3,
        has_failures: !params.workflow_resolved,
        hard_fail_downgraded: false,
        forced_heavy_process: false,
        has_sufficient_evidence: params.workflow_resolved,
        output_too_long_no_summary: false,
        report_only_no_repair: false,
        failed_but_marked_done: false,
        auto_repair_overreach: false,
        repair_reverified: false,
        outputs_raw_noise: false,
    });
    return {
        passed: result.passed,
        violations: result.violations.map((v) => ({
            principle: v.principle,
            severity: v.severity,
            reason_zh: v.reason_zh,
        })),
        evaluated_principles: result.evaluated_principles,
    };
}
/**
 * CEP 集成: 护栏评估后检查 — 硬规则是否被降级、低风险是否过重。
 */
export async function assessCepAfterGuardEvaluation(params) {
    const cepModule = await import("../../engine/audit/core_experience_principle.js");
    const result = cepModule.evaluateCoreExperiencePrinciple({
        task_id: params.task_id,
        workflow_id: "guard_evaluation",
        has_mainline_hooks: true,
        has_owner_contracts: true,
        natural_language_entry: true,
        requires_internal_contract_knowledge: false,
        user_path_steps: 3,
        has_failures: !params.guard_passed,
        hard_fail_downgraded: params.hard_fail_downgraded,
        forced_heavy_process: params.is_low_risk && !params.guard_passed,
        has_sufficient_evidence: params.guard_passed,
        output_too_long_no_summary: false,
        report_only_no_repair: false,
        failed_but_marked_done: false,
        auto_repair_overreach: false,
        repair_reverified: false,
        outputs_raw_noise: false,
    });
    return {
        passed: result.passed,
        violations: result.violations.map((v) => ({
            principle: v.principle,
            severity: v.severity,
            reason_zh: v.reason_zh,
        })),
        evaluated_principles: result.evaluated_principles,
    };
}
/**
 * CEP 集成: 修复重验证决策 — 检查是否假完成、是否进入正确修复路径。
 */
export async function assessCepForRepairReverify(params) {
    const cepModule = await import("../../engine/audit/core_experience_principle.js");
    const nfcResult = cepModule.evaluateNoFalseCompletion({
        verification_passed: params.verification_passed,
        build_passed: params.build_passed,
        browser_acceptance_passed: true,
        guard_passed: true,
        evidence_sufficient: params.evidence_sufficient,
        current_status: params.current_status,
    });
    return {
        decision: nfcResult.decision,
        reason_zh: nfcResult.reason_zh ?? "",
        passed: nfcResult.decision === "completed",
    };
}
/**
 * CEP 集成: 用户反馈输出质量 — 检查结论优先、摘要清晰、不隐藏失败、中文语义。
 */
export async function assessCepForUserFeedback(params) {
    const cepModule = await import("../../engine/audit/core_experience_principle.js");
    const cep = cepModule.evaluateUserVisibleOutput({
        has_conclusion_first: params.has_conclusion_first,
        has_clear_summary: params.has_clear_summary,
        has_actionable_next_step: params.has_actionable_next_step,
        exposes_internal_noise: params.exposes_internal_noise,
        hides_critical_failure: params.hides_critical_failure,
        chinese_semantic_first: params.chinese_semantic_first,
    });
    const logGov = await import("../../engine/core/log_governance.js");
    const logReport = logGov.evaluateFeedbackOutputQuality({
        output: [
            params.has_conclusion_first ? "结论优先" : "缺少结论",
            params.has_clear_summary ? "摘要清晰" : "摘要不足",
            params.has_actionable_next_step ? "下一步明确" : "下一步缺失",
        ].join("；"),
        critical_failure_hidden: params.hides_critical_failure,
    });
    return {
        passed: cep.passed && logReport.passed,
        issues_zh: [
            ...cep.issues_zh,
            ...logReport.findings.map((f) => f.message_zh),
        ],
    };
}
//# sourceMappingURL=cep_assessment.js.map