import { debug } from "../core/logger.js";
import { isPathInScope } from "../core/path_scope_utils.js";
const PRINCIPLES = [
    {
        id: "think_before_coding",
        name: "Think Before Coding",
        chinese_name: "编码前先思考",
        rule: "编码前先明确问题、目标、输入、约束和不确定性。不假设、不隐藏困惑、不把模糊需求直接转成代码。",
        applies_to_routes: ["code_execution", "multi_stage_plan", "single_artifact", "source_extraction", "read_only_analysis"],
        applies_to_workflows: ["code_change", "planning", "debugging", "review"],
        template_assets: [
            "templates/internal/rules/核心工程执行原则.md",
            "templates/procedures/编码前澄清流程.md",
        ],
        enforcement_checks: [
            "check_missing_required_inputs",
            "check_unclear_write_scope",
            "check_unauthorized_side_effects",
            "check_undocumented_assumptions",
            "check_hidden_business_rules",
        ],
        evidence_outputs: ["ClarificationNeed", "AssumptionRecord", "InputCompletenessReport"],
        hard_fail_conditions: [
            "缺少必要输入却开始写代码",
            "写入 scope 不明确却修改文件",
            "外部副作用权限不明确却执行命令",
            "把未知事实写成确定结论",
            "隐藏需要用户确认的业务口径",
        ],
        advisory_conditions: [
            "存在 material 级不确定但已记录假设",
            "存在 minor 级不确定且使用合理默认",
        ],
    },
    {
        id: "simplicity_first",
        name: "Simplicity First",
        chinese_name: "简单优先",
        rule: "优先用最少代码、最少抽象、最少新增文件解决已确认目标。不为了未来可能性提前设计复杂结构。",
        applies_to_routes: ["code_execution", "multi_stage_plan", "single_artifact"],
        applies_to_workflows: ["code_change", "planning", "review"],
        template_assets: [
            "templates/internal/rules/核心工程执行原则.md",
        ],
        enforcement_checks: [
            "check_new_dependencies",
            "check_new_abstractions",
            "check_public_api_expansion",
            "check_config_expansion",
            "check_over_engineering",
        ],
        evidence_outputs: ["ComplexityJustification", "OverEngineeringFinding", "diff_complexity_summary"],
        hard_fail_conditions: [
            "为局部问题引入无必要新依赖",
            "为简单修复新增大范围架构层",
            "没有用户目标支撑却扩展公共 API/配置/registry",
            "使用复杂方案绕过已有简单本地模式",
        ],
        advisory_conditions: [
            "新增 1-2 个文件但已说明理由",
            "引入新抽象但已说明必要性",
        ],
    },
    {
        id: "surgical_changes",
        name: "Surgical Changes",
        chinese_name: "精准修改",
        rule: "只改必须改的内容，不顺便重构、不无关格式化、不扩大 scope、不污染用户已有改动。",
        applies_to_routes: ["code_execution", "multi_stage_plan"],
        applies_to_workflows: ["code_change", "review"],
        template_assets: [
            "templates/internal/rules/核心工程执行原则.md",
        ],
        enforcement_checks: [
            "check_scope_violation",
            "check_diff_ownership",
            "check_unrelated_changes",
            "check_formatting_masking",
            "check_assertion_weakening",
        ],
        evidence_outputs: ["DiffOwnershipReport", "ScopeLease", "UnrelatedChangeFinding"],
        hard_fail_conditions: [
            "修改 scope 外文件",
            "修改与目标无关的文件或行为",
            "未经确认回滚用户已有改动",
            "大范围格式化掩盖真实变更",
            "为了让测试过而删除断言或降低覆盖率",
        ],
        advisory_conditions: [
            "存在必要联动修改（类型/调用方/schema）",
            "存在必要的适配层变更",
        ],
    },
    {
        id: "goal_driven_execution",
        name: "Goal-Driven Execution",
        chinese_name: "目标驱动执行",
        rule: "先定义可验证目标，再执行；执行后必须验证；验证失败要修复并重新验证，直到通过或明确阻塞。",
        applies_to_routes: ["code_execution", "multi_stage_plan", "single_artifact", "source_extraction", "read_only_analysis"],
        applies_to_workflows: ["code_change", "verification", "delivery"],
        template_assets: [
            "templates/internal/rules/核心工程执行原则.md",
            "templates/checklists/核心工程执行验收清单.md",
        ],
        enforcement_checks: [
            "check_goal_definition",
            "check_verification_plan",
            "check_verification_evidence",
            "check_repair_reverify",
            "check_hidden_unverified_items",
        ],
        evidence_outputs: ["GoalDefinition", "AcceptanceCriteria", "VerificationPlan", "VerificationEvidence"],
        hard_fail_conditions: [
            "没有可验证目标就开始实现",
            "没有 VerificationPlan 就标记完成",
            "未执行验证却输出全部通过",
            "验证失败仍进入 completed/delivery_ready",
            "隐藏未验证项",
        ],
        advisory_conditions: [
            "存在人工验收项但已显式列出",
            "部分验证项标记为 manual_required",
        ],
    },
];
// ── 任务等级映射 ──
const TASK_LEVEL_ENFORCEMENT = {
    L0: {
        think_before_coding: "advisory",
        simplicity_first: "not_applicable",
        surgical_changes: "not_applicable",
        goal_driven_execution: "not_applicable",
    },
    L1: {
        think_before_coding: "required",
        simplicity_first: "advisory",
        surgical_changes: "advisory",
        goal_driven_execution: "required",
    },
    L2: {
        think_before_coding: "required",
        simplicity_first: "required",
        surgical_changes: "required",
        goal_driven_execution: "required",
    },
    L3: {
        think_before_coding: "required",
        simplicity_first: "required",
        surgical_changes: "required",
        goal_driven_execution: "required",
    },
    L4: {
        think_before_coding: "required",
        simplicity_first: "advisory",
        surgical_changes: "advisory",
        goal_driven_execution: "required",
    },
};
// ── 路由到任务等级映射 ──
const ROUTE_TO_TASK_LEVEL = {
    direct_answer: "L0",
    skip_chat: "L0",
    analysis: "L1",
    read_only_analysis: "L1",
    planning: "L1",
    review: "L1",
    code_change: "L2",
    code_execution: "L2",
    artifact_generation: "L2",
    single_artifact: "L2",
    source_extraction: "L2",
    multi_stage_plan: "L3",
    operation: "L1",
};
// ── 冲突优先级 ──
/** 原则冲突优先级 — 原则冲突时按此顺序裁定，越靠前优先级越高 */
export const PRINCIPLE_PRIORITY = [
    "goal_driven_execution",
    "think_before_coding",
    "surgical_changes",
    "simplicity_first",
];
// ── 查询函数 ──
/**
 * 获取所有核心工程原则列表。
 * @returns 核心工程原则数组
 */
export function listCorePrinciples() {
    return PRINCIPLES;
}
/**
 * 根据 ID 获取核心工程原则定义。
 * @param id - 原则 ID
 * @returns 原则定义，不存在时返回 undefined
 */
export function getCorePrinciple(id) {
    return PRINCIPLES.find((p) => p.id === id);
}
/**
 * 根据路由或执行形状获取任务等级。
 * @param route - 路由标识（可选）
 * @param executionShape - 执行形状（可选）
 * @returns 任务等级（L0-L4）
 */
export function getTaskLevel(route, executionShape) {
    const key = executionShape || route || "";
    // 路由未知时不强制原则，等价于 L0
    return ROUTE_TO_TASK_LEVEL[key] ?? "L0";
}
/**
 * 获取指定原则在给定任务等级下的执行强度。
 * @param principleId - 原则 ID
 * @param taskLevel - 任务等级
 * @returns 执行强度（required/advisory/not_applicable）
 */
export function getEnforcementLevel(principleId, taskLevel) {
    return TASK_LEVEL_ENFORCEMENT[taskLevel]?.[principleId] ?? "advisory";
}
/**
 * 获取指定任务等级下所有 required 级别的原则 ID 列表。
 * @param taskLevel - 任务等级
 * @returns required 级原则 ID 数组
 */
export function getRequiredPrinciples(taskLevel) {
    const enforcement = TASK_LEVEL_ENFORCEMENT[taskLevel];
    return Object.keys(enforcement).filter((id) => enforcement[id] === "required");
}
/**
 * 检查"编码前先思考"原则 — 验证是否存在未解决的阻塞性澄清和未确认的假设。
 * @param ctx - 原则检查上下文
 * @returns 原则检查结果
 */
export function checkThinkBeforeCoding(ctx) {
    const findings = [];
    const evidence_refs = [];
    const blockingClarifications = (ctx.clarifications ?? []).filter((c) => c.blocking);
    if (blockingClarifications.length > 0) {
        findings.push(`存在 ${blockingClarifications.length} 个阻塞性澄清需求未解决`);
        evidence_refs.push("ClarificationNeed");
    }
    const hasAssumptions = (ctx.assumptions ?? []).length > 0;
    if (hasAssumptions) {
        const undocumentedAssumptions = (ctx.assumptions ?? []).filter((a) => a.uncertainty_level === "blocking" && !a.needs_manual_confirm);
        if (undocumentedAssumptions.length > 0) {
            findings.push(`存在 ${undocumentedAssumptions.length} 个 blocking 级假设未标记需人工确认`);
            evidence_refs.push("AssumptionRecord");
        }
    }
    if (ctx.changed_files.length > 0 && blockingClarifications.length > 0) {
        findings.push("存在未解决的阻塞性澄清，但已开始修改文件");
        evidence_refs.push("ClarificationNeed");
    }
    const status = findings.length > 0 ? "failed" : "passed";
    return {
        principle_id: "think_before_coding",
        status,
        findings,
        evidence_refs: evidence_refs.length > 0 ? evidence_refs : ["InputCompletenessReport"],
        required_action: status === "failed" ? "clarify" : undefined,
    };
}
/**
 * 检查"简单优先"原则 — 验证复杂度引入是否有用户目标支撑。
 * @param ctx - 原则检查上下文
 * @returns 原则检查结果
 */
export function checkSimplicityFirst(ctx) {
    const findings = [];
    const evidence_refs = [];
    const justifications = ctx.complexity_justifications ?? [];
    const unjustified = justifications.filter((j) => !j.user_goal_alignment || j.user_goal_alignment.trim() === "");
    if (unjustified.length > 0) {
        findings.push(`存在 ${unjustified.length} 个未说明与用户目标对齐的复杂度引入`);
        evidence_refs.push("ComplexityJustification");
    }
    const newFiles = justifications.reduce((sum, j) => sum + (j.new_files_count ?? 0), 0);
    if (newFiles > 5 && justifications.length === 0) {
        findings.push(`新增 ${newFiles} 个文件但无复杂度说明`);
        evidence_refs.push("diff_complexity_summary");
    }
    // 大量文件变更且无复杂度说明 = 复杂度风险
    if (ctx.changed_files.length >= 10 && justifications.length === 0) {
        findings.push(`${ctx.changed_files.length} 个文件变更但无复杂度说明`);
        evidence_refs.push("changed_files_count");
    }
    const status = findings.length > 0 ? "failed" : "passed";
    return {
        principle_id: "simplicity_first",
        status,
        findings,
        evidence_refs: evidence_refs.length > 0 ? evidence_refs : ["ComplexityJustification"],
        required_action: status === "failed" ? "simplify" : undefined,
    };
}
/**
 * 检查"精准修改"原则 — 验证是否存在 scope 外修改。
 * @param ctx - 原则检查上下文
 * @returns 原则检查结果
 */
export function checkSurgicalChanges(ctx) {
    const findings = [];
    const evidence_refs = [];
    const scopeViolations = ctx.changed_files.filter((f) => ctx.declared_scope.length > 0 && !ctx.declared_scope.some((s) => isPathInScope(f, s, { caseSensitive: true })));
    if (scopeViolations.length > 0) {
        findings.push(`存在 ${scopeViolations.length} 个 scope 外修改: ${scopeViolations.slice(0, 3).join(", ")}${scopeViolations.length > 3 ? " ..." : ""}`);
        evidence_refs.push("DiffOwnershipReport");
    }
    const status = findings.length > 0 ? "failed" : "passed";
    return {
        principle_id: "surgical_changes",
        status,
        findings,
        evidence_refs: evidence_refs.length > 0 ? evidence_refs : ["ScopeLease"],
        required_action: status === "failed" ? "reduce_diff" : undefined,
    };
}
/**
 * 检查"目标驱动执行"原则 — 验证是否有可验证目标、验证计划，以及验证是否已执行且通过。
 * @param ctx - 原则检查上下文
 * @returns 原则检查结果
 */
export function checkGoalDrivenExecution(ctx) {
    const findings = [];
    const evidence_refs = [];
    if (ctx.changed_files.length > 0 && !ctx.has_goal_definition) {
        findings.push("已修改文件但没有可验证目标定义");
        evidence_refs.push("GoalDefinition");
    }
    if (ctx.changed_files.length > 0 && !ctx.has_verification_plan) {
        findings.push("已修改文件但没有验证计划");
        evidence_refs.push("VerificationPlan");
    }
    if (ctx.verification_executed === false && ctx.changed_files.length > 0) {
        findings.push("已修改文件但未执行验证");
        evidence_refs.push("VerificationEvidence");
    }
    if (ctx.verification_passed === false) {
        findings.push("验证未通过");
        evidence_refs.push("VerificationResult");
    }
    if (ctx.changed_files.length === 0 && !ctx.has_goal_definition && !ctx.has_verification_plan) {
        return {
            principle_id: "goal_driven_execution",
            status: "not_applicable",
            findings: [],
            evidence_refs: [],
        };
    }
    const status = findings.length > 0 ? "failed" : "passed";
    return {
        principle_id: "goal_driven_execution",
        status,
        findings,
        evidence_refs: evidence_refs.length > 0 ? evidence_refs : ["GoalDefinition", "VerificationPlan"],
        required_action: status === "failed" ? "add_verification" : undefined,
    };
}
// ── 完整检查 ──
/**
 * 执行完整的核心工程原则检查 — 对所有四条原则进行检查，根据任务等级覆盖不适用原则的状态。
 * @param ctx - 原则检查上下文
 * @returns 核心原则检查报告，包含各原则检查结果和总体是否通过
 */
export function checkCorePrinciples(ctx) {
    debug("核心原则检查", `开始执行，任务等级 ${getTaskLevel(ctx.route, ctx.execution_shape)}`);
    const taskLevel = getTaskLevel(ctx.route, ctx.execution_shape);
    const enforcement = TASK_LEVEL_ENFORCEMENT[taskLevel];
    const results = [
        checkThinkBeforeCoding(ctx),
        checkSimplicityFirst(ctx),
        checkSurgicalChanges(ctx),
        checkGoalDrivenExecution(ctx),
    ];
    // 对不适用原则的状态覆盖
    for (const r of results) {
        if (enforcement[r.principle_id] === "not_applicable") {
            r.status = "not_applicable";
            r.findings = [];
            r.required_action = undefined;
        }
    }
    const overallPassed = results.every((r) => {
        if (r.status === "not_applicable")
            return true;
        if (r.status === "warning")
            return true;
        if (r.status === "passed")
            return true;
        // failed 仅在原则为 required 时才阻断
        return enforcement[r.principle_id] === "advisory";
    });
    debug("核心原则检查", `完成，总体${overallPassed ? "通过" : "未通过"}，任务等级 ${taskLevel}`);
    return {
        task_level: taskLevel,
        principles: results,
        overall_passed: overallPassed,
        generated_at: new Date().toISOString(),
    };
}
// ── 防伪验证 ──
/**
 * 防伪验证 — 检查原则检查报告中是否存在伪满足（声称通过但无证据引用）。
 * @param report - 核心原则检查报告
 * @returns 违规列表，每项描述伪满足的具体问题
 */
export function validateAntiCircumvention(report) {
    debug("防伪验证", `开始验证原则检查报告的真实性`);
    const violations = [];
    for (const pr of report.principles) {
        // 检查声称 passed 但无证据引用的伪满足
        if (pr.status === "passed" && pr.evidence_refs.length === 0) {
            violations.push(`原则 ${pr.principle_id} 声称 passed 但无证据引用 (伪满足)`);
        }
    }
    return violations;
}
//# sourceMappingURL=core_engineering_principles.js.map