/**
 * Core Experience Principle — 问题五十六核心机制。
 *
 * 核心原则: 机制强，路径短；规则硬，体验轻；证据足，不啰嗦；能自动修复，不假装完成。
 *
 * 约束所有机制的最终使用形态，防止系统在"治理更强"的同时
 * 退化成用户路径复杂、输出冗长、规则软化或假完成。
 */
// ── 诊断码 ──
export const CORE_EXPERIENCE_DIAGNOSTIC_CODES = {
    "SF-EXP-5601": "机制未接入真实主链路",
    "SF-EXP-5602": "用户路径过长或要求用户理解内部 contract",
    "SF-EXP-5603": "硬规则被降级为 warning",
    "SF-EXP-5604": "低风险任务体验过重",
    "SF-EXP-5605": "证据不足但输出完成",
    "SF-EXP-5606": "用户输出冗长且缺少清晰结论",
    "SF-EXP-5607": "失败未进入 repair_reverify 或 manual_required",
    "SF-EXP-5608": "自动修复越过 scope 或用户确认",
    "SF-EXP-5609": "修复后缺少重新验证",
    "SF-EXP-5610": "用户项目 adapter 未注入核心体验原则",
};
// ── 核心函数 ──
/**
 * 评估核心体验原则 — 检查任务执行是否遵守四条核心原则。
 */
export function evaluateCoreExperiencePrinciple(params) {
    const { has_mainline_hooks, requires_internal_contract_knowledge, user_path_steps, has_failures, hard_fail_downgraded, forced_heavy_process, has_sufficient_evidence, output_too_long_no_summary, report_only_no_repair, failed_but_marked_done, auto_repair_overreach, repair_reverified, outputs_raw_noise, } = params;
    const violations = [];
    // 原则 1: 机制强，路径短
    if (!has_mainline_hooks) {
        violations.push({
            principle: "strong_mechanism_short_path",
            severity: "blocking",
            reason_zh: "机制未接入真实主链路，只存在于文档、模板或测试中",
            evidence_refs: [],
            required_action: "block_delivery",
        });
    }
    if (requires_internal_contract_knowledge) {
        violations.push({
            principle: "strong_mechanism_short_path",
            severity: "blocking",
            reason_zh: "用户路径要求用户理解内部 contract 名称才能触发核心 workflow",
            evidence_refs: [],
            required_action: "simplify_output",
        });
    }
    if (user_path_steps > 5) {
        violations.push({
            principle: "strong_mechanism_short_path",
            severity: "warning",
            reason_zh: `用户路径过长 (${user_path_steps} 步)，应简化入口`,
            evidence_refs: [],
            required_action: "simplify_output",
        });
    }
    // 原则 2: 规则硬，体验轻
    if (hard_fail_downgraded) {
        violations.push({
            principle: "hard_rules_light_experience",
            severity: "blocking",
            reason_zh: "硬规则被降级为 warning 后继续执行",
            evidence_refs: [],
            required_action: "block_delivery",
        });
    }
    if (forced_heavy_process) {
        violations.push({
            principle: "hard_rules_light_experience",
            severity: "blocking",
            reason_zh: "低风险任务被强制要求长篇方案或全量审查",
            evidence_refs: [],
            required_action: "simplify_output",
        });
    }
    // 原则 3: 证据足，不啰嗦
    if (!has_sufficient_evidence) {
        violations.push({
            principle: "sufficient_evidence_concise_output",
            severity: "blocking",
            reason_zh: "证据不足但输出完成 — 只有一句[已完成]但无 evidence refs",
            evidence_refs: [],
            required_action: "block_delivery",
        });
    }
    if (output_too_long_no_summary) {
        violations.push({
            principle: "sufficient_evidence_concise_output",
            severity: "blocking",
            reason_zh: "用户输出冗长且缺少清晰结论",
            evidence_refs: [],
            required_action: "simplify_output",
        });
    }
    if (outputs_raw_noise) {
        violations.push({
            principle: "sufficient_evidence_concise_output",
            severity: "warning",
            reason_zh: "输出包含原始日志或内部流水账，未脱敏或摘要化",
            evidence_refs: [],
            required_action: "simplify_output",
        });
    }
    // 原则 4: 能自动修复，不假装完成
    if (failed_but_marked_done) {
        violations.push({
            principle: "auto_repair_no_fake_completion",
            severity: "blocking",
            reason_zh: "验证失败但标记为 completed/delivered，假完成",
            evidence_refs: [],
            required_action: "回退",
        });
    }
    if (report_only_no_repair) {
        violations.push({
            principle: "auto_repair_no_fake_completion",
            severity: "blocking",
            reason_zh: "只报告发现问题，未进入 repair_reverify 或 manual_required",
            evidence_refs: [],
            required_action: "回退",
        });
    }
    if (auto_repair_overreach) {
        violations.push({
            principle: "auto_repair_no_fake_completion",
            severity: "blocking",
            reason_zh: "自动修复越过用户确认或扩大 scope",
            evidence_refs: [],
            required_action: "manual_required",
        });
    }
    if (has_failures && !repair_reverified) {
        violations.push({
            principle: "auto_repair_no_fake_completion",
            severity: "blocking",
            reason_zh: "修复后缺少重新验证",
            evidence_refs: [],
            required_action: "回退",
        });
    }
    const blockingViolations = violations.filter((v) => v.severity === "blocking");
    const passed = blockingViolations.length === 0;
    return {
        task_id: params.task_id,
        workflow_id: params.workflow_id,
        evaluated_principles: [
            "strong_mechanism_short_path",
            "hard_rules_light_experience",
            "sufficient_evidence_concise_output",
            "auto_repair_no_fake_completion",
        ],
        violations,
        user_facing_summary_zh: passed
            ? "核心体验原则评估通过"
            : `核心体验原则评估未通过: ${blockingViolations.map((v) => v.reason_zh).join("; ")}`,
        internal_trace_refs: [],
        passed,
    };
}
/**
 * 评估用户可见输出质量。
 */
export function evaluateUserVisibleOutput(params) {
    const issues = [];
    if (!params.has_conclusion_first)
        issues.push("用户可见输出未先给结论");
    if (!params.has_clear_summary)
        issues.push("用户可见输出缺少清晰摘要");
    if (!params.has_actionable_next_step)
        issues.push("用户可见输出缺少可执行的下一步");
    if (params.exposes_internal_noise)
        issues.push("用户可见输出暴露内部流水账");
    if (params.hides_critical_failure)
        issues.push("用户可见输出隐藏了关键失败");
    if (!params.chinese_semantic_first)
        issues.push("用户可见输出未中文语义优先");
    return { passed: issues.length === 0, issues_zh: issues };
}
/**
 * 评估是否假完成 — 验证失败时是否错误标记为 completed。
 */
export function evaluateNoFalseCompletion(params) {
    const failures = [];
    if (!params.verification_passed)
        failures.push("验证失败");
    if (!params.build_passed)
        failures.push("构建失败");
    if (!params.browser_acceptance_passed)
        failures.push("浏览器验收失败");
    if (!params.guard_passed)
        failures.push("guard 阻断");
    if (!params.evidence_sufficient)
        failures.push("证据不足");
    if (failures.length === 0) {
        return {
            task_id: "",
            decision: "completed",
            reason_zh: "所有验证通过，可完成",
            auto_repairable: false,
            repair_scope: [],
            evidence_refs: [],
        };
    }
    const isCompleted = ["completed", "delivered", "implemented_verified", "done"].includes(params.current_status);
    if (isCompleted) {
        return {
            task_id: "",
            decision: "blocked",
            reason_zh: `假完成检测: ${failures.join(", ")}，但状态为 ${params.current_status}`,
            auto_repairable: false,
            repair_scope: [],
            manual_required_reason: "不得将失败伪装成完成",
            evidence_refs: [],
        };
    }
    return {
        task_id: "",
        decision: "回退",
        reason_zh: `${failures.join(", ")}，需进入 repair_reverify`,
        auto_repairable: true,
        repair_scope: [],
        evidence_refs: [],
    };
}
/**
 * 评估机制摩擦 — 新增机制是否过度增加了任务复杂度。
 */
export function evaluateMechanismFriction(params) {
    const addedRatio = params.added_steps / Math.max(params.baseline_steps, 1);
    let tooMuchFriction = false;
    if (params.risk_level === "low" && addedRatio > 0.5)
        tooMuchFriction = true;
    if (params.risk_level === "medium" && addedRatio > 1.0 && !params.has_lightweight_path)
        tooMuchFriction = true;
    if (tooMuchFriction && !params.has_necessity_justification) {
        return {
            passed: false,
            friction_score: Math.round(addedRatio * 100),
            reason_zh: `新增机制增加 ${params.added_steps} 步 (${Math.round(addedRatio * 100)}% 增长)，对 ${params.risk_level} 风险任务过度，需说明必要性或提供轻量路径`,
        };
    }
    return {
        passed: true,
        friction_score: Math.round(addedRatio * 100),
        reason_zh: "摩擦在可接受范围",
    };
}
/**
 * 创建核心体验原则契约实例。
 */
export function createCoreExperiencePrincipleContract(overrides) {
    const base = {
        contract_id: "CoreExperiencePrinciple",
        mechanism_strength: {
            real_mainline_hooks: [
                "PlanProposalFirstGate",
                "WorkflowContract",
                "ToolInvocation",
                "VerificationPlan",
                "DeliveryReadiness",
                "FailureReport",
                "RepairLoop",
            ],
            hard_fail_rules: [
                "无计划不得执行写入动作",
                "高风险无确认不得执行",
                "验证失败不得标记完成",
                "guard 阻断不得继续",
            ],
            owner_contracts: [
                "PlanProposalFirstGate",
                "WorkflowContract",
                "GuardEvaluationReport",
                "VerificationPlan",
                "DeliveryReadinessReport",
                "FailureReport",
            ],
            evidence_required: ["plan_evidence", "execution_evidence", "verification_evidence", "delivery_evidence"],
        },
        path_shortness: {
            user_entrypoints: ["自然语言意图", "CLI 命令"],
            hidden_internal_steps: ["RouteDecision", "WorkflowContract解析", "ContractRegistry查询", "KnowledgeIndex构建"],
            max_user_required_decisions: 3,
            no_internal_contract_required: true,
            natural_language_supported: true,
        },
        rule_hardness: {
            hard_fail_conditions: ["安全边界突破", "scope 越权", "用户资产风险", "证据缺失", "核心契约违反"],
            manual_required_conditions: ["用户选择方案", "scope 扩大", "高风险确认", "外部副作用", "不可自动修复"],
            cannot_downgrade_to_warning: [
                "安全/隐私违反",
                "scope 越权",
                "用户资产破坏性操作",
                "证据链断裂",
                "核心护栏穿透",
            ],
        },
        experience_lightness: {
            risk_based_detail_level: "normal",
            user_visible_summary_required: true,
            internal_trace_hidden_by_default: true,
            avoid_repeated_confirmation: true,
        },
        evidence_sufficiency: {
            required_refs: ["plan", "execution", "verification", "delivery"],
            user_visible_evidence_summary: ["做了什么", "验证了什么", "还有什么风险"],
            audit_trace_refs: ["plan_id", "verification_id", "delivery_id", "evidence_refs"],
            no_raw_noise: true,
        },
        repair_truthfulness: {
            auto_repair_allowed: true,
            repair_reverify_required: true,
            manual_required_when_unfixable: true,
            cannot_mark_done_on_failure: true,
        },
    };
    if (overrides) {
        return {
            ...base,
            ...overrides,
            mechanism_strength: { ...base.mechanism_strength, ...overrides.mechanism_strength },
            path_shortness: { ...base.path_shortness, ...overrides.path_shortness },
            rule_hardness: { ...base.rule_hardness, ...overrides.rule_hardness },
            experience_lightness: { ...base.experience_lightness, ...overrides.experience_lightness },
            evidence_sufficiency: { ...base.evidence_sufficiency, ...overrides.evidence_sufficiency },
            repair_truthfulness: { ...base.repair_truthfulness, ...overrides.repair_truthfulness },
        };
    }
    return base;
}
// ── CEP 集成追踪 — 真实接入路径证明 ──
const _cepIntegrations = new Map();
/** 记录 CEP 在真实主链路中的调用 */
export function recordCepIntegration(entryPoint, result) {
    _cepIntegrations.set(entryPoint, {
        passed: result.passed,
        violations_count: result.violations.length,
        recorded_at: new Date().toISOString(),
    });
}
/** 获取所有已记录的 CEP 集成 */
export function getCepIntegrations() {
    return Object.fromEntries(_cepIntegrations);
}
/** 清空 CEP 集成记录 */
export function clearCepIntegrations() {
    _cepIntegrations.clear();
}
//# sourceMappingURL=core_experience_principle.js.map