/**
 * 扩展平台场景注册表 — A-M 场景定义与运行器。
 *
 * 13 个场景覆盖 13 个扩展平台问题。
 * 每个场景通过真实函数调用产生 evidence，不硬编码 PASS。
 */
// 从独立模块导入场景定义，消除与 workflow_template_pack 的循环依赖
export { EXTENSION_SCENARIOS } from "./extension_scenario_definitions.js";
import { validateExtensionManifest, createExtensionManifest, evaluateExtensionLifecycle, grantExtensionPermissions } from "./extension_contract.js";
import { normalizePathRef, checkPathSafety, createTestPlatformContext } from "./platform_context.js";
import { createMetricContract, evaluateMetrics, createGovernanceFinding, evaluateGovernanceAction } from "./metric_governance.js";
import { createTechnologyDecision, validateTechnologyDecision, evaluateDecisionExecution, createDecisionRecord } from "./technology_decision.js";
import { createBrainstormSession, createOptionRecord, validateBrainstormSession, canBrainstormAutoExecute, createTradeoffMatrix } from "./brainstorm_contract.js";
import { createDetailDisciplineContract, performDetailCheck, checkDetailGateIntegration } from "./detail_discipline.js";
import { createFirstPrinciplesFrame, performFirstPrinciplesCheck, validateFirstPrinciplesForHighImpact } from "./first_principles.js";
import { createArchitectureDesignContract, reviewArchitectureDesign, validateOutputDirectoryDecision, validateMermaidDiagrams } from "./architecture_design_contract.js";
import { detectProjectContext, checkAnalysisGate } from "./existing_system_analysis.js";
import { createCodingReadinessContract, createTestFirstPlan, evaluateCodingReadiness, performMainlineConsumptionCheck } from "./coding_readiness_gate.js";
import { createLocalDockerAcceptanceContract, requiresLocalAcceptance, validateFinalAccess, performBrowserAcceptance, executeHttpAcceptanceWithTransport, realResultToBrowserEvidence, validateLocalAcceptanceEvidence } from "./local_docker_acceptance.js";
import { createWorkflowTemplatePackContract, createWorkflowTemplateEntry, createTemplateConsumptionEvidence, validateWorkflowTemplatePack, advanceTemplateConsumptionStatus } from "./workflow_template_pack.js";
import { createNewIssueRegressionGate, checkDuplicateIssue, analyzeTemplateEvolutionImpact, performEvolutionGate } from "./evolution_regression_gate.js";
// ── 场景运行器 ──
function runScenarioA() {
    const evidence = [];
    const failures = [];
    // 第三方扩展自称 enforced 被阻断
    const manifest = createExtensionManifest({ extension_id: "ext-1", permissions: ["read_project"] });
    const capDecl = { extension_id: "ext-1", claimed_capabilities: [], claimed_enforcement: "enforced_by_host", third_party: true };
    const v1 = validateExtensionManifest(manifest, capDecl);
    if (!v1.valid && v1.violations.some(v => v.includes("第三方"))) {
        evidence.push("第三方扩展不得自称 enforced");
    }
    else {
        failures.push("第三方扩展自称 enforced 应被阻断");
    }
    // 合法生命周期转移
    const lc1 = evaluateExtensionLifecycle("ext-1", "draft", "installed");
    if (lc1.allowed)
        evidence.push("合法生命周期转移通过");
    else
        failures.push("draft→installed 应允许");
    const lc2 = evaluateExtensionLifecycle("ext-1", "active", "draft");
    if (!lc2.allowed)
        evidence.push("非法转移被阻断");
    else
        failures.push("active→draft 应被阻断");
    // 高风险权限需人类审批
    const grant1 = grantExtensionPermissions("ext-1", ["execute_command", "read_project"], "system", "test", false);
    if (!grant1.granted_permissions.includes("execute_command"))
        evidence.push("高风险权限需人类审批");
    else
        failures.push("execute_command 未审批不应被授权");
    const grant2 = grantExtensionPermissions("ext-1", ["execute_command"], "human", "test", true);
    if (grant2.granted_permissions.includes("execute_command"))
        evidence.push("人类审批后高风险权限被授权");
    else
        failures.push("审批后 execute_command 应被授权");
    return { scenario_id: "scenario-A", scenario_name: "扩展生命周期与权限管控", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioB() {
    const evidence = [];
    const failures = [];
    // skipped 不算 passed
    const eval1 = evaluateMetrics([
        { metric_id: "m1", value: 1, sampled_at: "", sample_status: "passed" },
        { metric_id: "m2", value: 0, sampled_at: "", sample_status: "skipped" },
    ]);
    if (!eval1.passed)
        evidence.push("skipped 不算 passed");
    else
        failures.push("含 skipped 样本不应算全部通过");
    if (eval1.skipped_count === 1)
        evidence.push("skipped 计数正确");
    else
        failures.push(`skipped 计数应为 1，实际 ${eval1.skipped_count}`);
    // degraded 不算 passed
    const eval2 = evaluateMetrics([
        { metric_id: "m3", value: 0, sampled_at: "", sample_status: "degraded" },
    ]);
    if (!eval2.passed && eval2.degraded_count === 1)
        evidence.push("degraded 不算 passed");
    else
        failures.push("degraded 应不算 passed");
    // 高风险动作不自动触发
    const metric = createMetricContract({ id: "m-gov", metric_type: "governance" });
    const finding = createGovernanceFinding(metric, "critical", ["ev-1"]);
    const action1 = evaluateGovernanceAction(finding, "downgrade");
    if (action1.requires_human && !action1.auto_triggered)
        evidence.push("高风险动作需人类确认不自动触发");
    else
        failures.push("高风险动作应需人类确认");
    return { scenario_id: "scenario-B", scenario_name: "指标真实性与治理动作", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioC() {
    const evidence = [];
    const failures = [];
    // 1. 创建高风险架构决策（仅 heuristic 证据）
    const contract = createTechnologyDecision({
        decision_id: "dec-c-1",
        decision_scope: "architecture",
        options: [
            { option_id: "opt-a", title: "微服务架构", description: "拆分为独立微服务" },
            { option_id: "opt-b", title: "单体模块化", description: "保持单体但模块化" },
            { option_id: "opt-c", title: "事件驱动架构", description: "基于消息队列的事件驱动" },
        ],
        recommended_option: "opt-b",
        human_gate_required: true,
        executable_without_human: false,
        evidence: [{ source_type: "heuristic", source_ref: "行业趋势", confidence: 0.6 }],
        falsification: ["微服务增加运维复杂度", "事件驱动带来最终一致性挑战"],
        failure_conditions: ["团队规模不支持微服务", "性能不达标"],
        validation_plan: ["概念验证 POC"],
        rollback_or_exit_plan: ["保留单体代码作为回退基线"],
    });
    // 2. 验证架构范围需要 human gate
    const v1 = validateTechnologyDecision(contract);
    if (v1.valid)
        evidence.push("高风险决策需 human gate");
    else
        failures.push(`高风险决策校验失败: ${v1.violations.join("; ")}`);
    // 3. 创建脑暴会话并验证
    const session = createBrainstormSession({
        session_id: "bs-c-1",
        problem_statement: "选择后端架构方案",
        trigger: "technology_choice",
        options: [
            createOptionRecord({ option_id: "opt-a", title: "微服务架构", pros: ["独立部署", "技术栈灵活"], cons: ["运维复杂", "网络延迟"], failure_conditions: ["团队规模不足", "分布式事务"] }),
            createOptionRecord({ option_id: "opt-b", title: "单体模块化", pros: ["简单", "部署快"], cons: ["扩展性有限"], failure_conditions: ["模块边界不清"] }),
            createOptionRecord({ option_id: "opt-c", title: "事件驱动架构", pros: ["解耦", "可扩展"], cons: ["最终一致性", "调试困难"], failure_conditions: ["消息堆积", "调试复杂度高"] }),
        ],
        recommended_option_id: "opt-b",
        rejected_option_ids: ["opt-a", "opt-c"],
        brainstorm_status: "options_ready",
        human_gate_required: true,
        evidence_refs: ["dec-c-1"],
    });
    const v2 = validateBrainstormSession(session);
    if (v2.valid)
        evidence.push("脑暴必须产生候选方案");
    else
        failures.push(`脑暴校验失败: ${v2.violations.join("; ")}`);
    // 4. 验证脑暴推荐不能自动执行
    if (!canBrainstormAutoExecute(session))
        evidence.push("脑暴推荐不能自动执行");
    else
        failures.push("脑暴推荐不应自动执行");
    // 5. 创建 recommended 决策记录，验证不可执行
    const record1 = createDecisionRecord("dec-c-1", { decision_status: "recommended" });
    const exec1 = evaluateDecisionExecution(contract, record1);
    if (!exec1.allowed)
        evidence.push("recommended 状态不可执行");
    else
        failures.push("推荐状态不应允许执行");
    // 6. 创建 approved 决策记录，验证可执行
    const record2 = createDecisionRecord("dec-c-1", { decision_status: "approved", approved_by: "human" });
    const exec2 = evaluateDecisionExecution(contract, record2);
    if (exec2.allowed)
        evidence.push("approved 可执行");
    else
        failures.push("已批准应允许执行");
    return { scenario_id: "scenario-C", scenario_name: "决策主权与脑暴联动", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioD() {
    const evidence = [];
    const failures = [];
    const contract = createDetailDisciplineContract({ contract_id: "dd-1" });
    // 缺失维度被检测
    const check1 = performDetailCheck(contract, "target-1", "implementation", {});
    if (check1.missing_details.length > 0 && check1.blocking)
        evidence.push("缺失维度被检测为 blocking");
    else
        failures.push("缺失维度应被检测");
    // 检查接入交付 gate
    const gate1 = checkDetailGateIntegration(check1, true);
    if (gate1.allowed)
        evidence.push("检查接入交付 gate");
    else
        failures.push("有交付 gate 应允许");
    const gate2 = checkDetailGateIntegration(check1, false);
    if (!gate2.allowed)
        evidence.push("未接入交付 gate 被阻断");
    else
        failures.push("blocking 检查未接入交付 gate 应被阻断");
    // 完整检查通过
    const check2 = performDetailCheck(contract, "target-2", "design", {
        edge_cases: ["边界1"], defaults: ["默认1"], failure_paths: ["失败1"],
        cleanup: ["清理1"], idempotency: ["幂等1"], overwrite_behavior: ["覆盖1"],
        rollback: ["回滚1"], evidence: ["证据1"],
    });
    if (check2.detail_check_status === "passed")
        evidence.push("完整维度检查通过");
    else
        failures.push(`完整维度应通过，实际 ${check2.detail_check_status}`);
    return { scenario_id: "scenario-D", scenario_name: "细节纪律", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioE() {
    const evidence = [];
    const failures = [];
    // 缺少 fundamental_need 被阻断
    const frame1 = createFirstPrinciplesFrame({ problem_id: "p1", user_goal: "目标" });
    const check1 = performFirstPrinciplesCheck(frame1);
    if (!check1.passed && check1.failures.some(f => f.includes("fundamental_need"))) {
        evidence.push("缺少 fundamental_need 被阻断");
    }
    else {
        failures.push("缺少 fundamental_need 应被阻断");
    }
    // 缺少证伪被检测
    if (check1.failures.some(f => f.includes("falsification")))
        evidence.push("缺少证伪被检测");
    else
        failures.push("缺少证伪问题应被检测");
    // 完整框架通过
    const frame2 = createFirstPrinciplesFrame({
        problem_id: "p2",
        user_goal: "实现缓存方案",
        fundamental_need: "高可用缓存",
        known_facts: ["当前使用 Redis", "QPS 约 1000"],
        assumptions: ["Redis 不会宕机"],
        candidate_solutions: ["Redis 集群", "本地缓存 + Redis"],
        simplest_viable_solution: "单节点 Redis + 本地缓存降级",
        falsification_questions: ["如果 Redis 宕机怎么办？"],
        chosen_solution: "单节点 Redis + 本地缓存降级",
        why_not_legacy_path: "旧方案无降级策略",
        first_principles_status: "framed",
    });
    const check2 = performFirstPrinciplesCheck(frame2);
    if (check2.passed)
        evidence.push("完整框架通过");
    else
        failures.push(`完整框架应通过: ${check2.failures.join("; ")}`);
    // high impact 校验
    const hp = validateFirstPrinciplesForHighImpact(frame2);
    if (hp.passed)
        evidence.push("high impact 校验通过");
    else
        failures.push(`完整框架 high impact 应通过: ${hp.violations.join("; ")}`);
    return { scenario_id: "scenario-E", scenario_name: "第一性原理", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioF() {
    const evidence = [];
    const failures = [];
    const platform = createTestPlatformContext();
    const scope = "/tmp/test-workspace";
    // 工作区内路径安全
    const ref1 = normalizePathRef("/tmp/test-workspace/src/main.ts", platform, scope);
    if (ref1.path_safety_status === "safe")
        evidence.push("工作区内路径安全");
    else
        failures.push(`工作区内路径应安全，实际 ${ref1.path_safety_status}`);
    // .. 路径逃逸
    const ref2 = normalizePathRef("/tmp/test-workspace/../../../etc/passwd", platform, scope);
    if (ref2.path_safety_status !== "safe")
        evidence.push(".. 路径逃逸被检测");
    else
        failures.push(".. 路径应被检测为不安全");
    // scope 外路径
    const safety = checkPathSafety(ref2, scope);
    if (!safety.passes)
        evidence.push("scope 外路径被阻断");
    else
        failures.push("scope 外路径应被阻断");
    // 大小写检测
    const macPlatform = createTestPlatformContext({ path_case_sensitive: false, os: "darwin" });
    const ref3 = normalizePathRef("/tmp/test-workspace/SRC/Main.ts", macPlatform, scope);
    if (ref3.case_normalized || ref3.path_safety_status === "safe")
        evidence.push("大小写处理正确");
    else
        failures.push("macOS 大小写处理异常");
    return { scenario_id: "scenario-F", scenario_name: "跨平台路径安全", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioG() {
    const evidence = [];
    const failures = [];
    // 1. 创建脑暴会话：3+ 选项、取舍、失败条件
    const options = [
        createOptionRecord({
            option_id: "g-o1", title: "Redis 集群",
            pros: ["高可用", "自动故障转移", "数据分片"],
            cons: ["运维复杂", "内存成本高", "集群配置复杂"],
            failure_conditions: ["脑裂导致数据不一致", "内存不足时 OOM", "网络分区时写入失败"],
        }),
        createOptionRecord({
            option_id: "g-o2", title: "本地缓存 + Redis 单节点",
            pros: ["简单", "成本低", "读取快"],
            cons: ["多实例不一致", "单点故障", "缓存穿透"],
            failure_conditions: ["Redis 宕机全站不可用", "缓存击穿", "本地缓存脏数据"],
        }),
        createOptionRecord({
            option_id: "g-o3", title: "多级缓存 + 消息队列",
            pros: ["高可用", "高性能", "解耦"],
            cons: ["架构复杂", "一致性挑战", "延迟较高"],
            failure_conditions: ["消息堆积", "多级缓存不一致", "队列服务不可用"],
        }),
    ];
    const session = createBrainstormSession({
        session_id: "bs-g-1",
        problem_statement: "选择高可用缓存方案",
        trigger: "high_impact_change",
        options,
        recommended_option_id: "g-o1",
        rejected_option_ids: ["g-o2", "g-o3"],
        brainstorm_status: "options_ready",
        human_gate_required: true,
        evidence_refs: ["dec-g-1"],
    });
    // 2. 验证脑暴会话
    const v1 = validateBrainstormSession(session);
    if (v1.valid)
        evidence.push("脑暴产生 3+ 候选方案");
    else
        failures.push(`脑暴校验失败: ${v1.violations.join("; ")}`);
    // 3. 验证有推荐和拒绝项
    if (session.recommended_option_id && session.rejected_option_ids.length > 0) {
        evidence.push("脑暴有推荐方案和拒绝方案");
    }
    else {
        failures.push("脑暴缺少推荐方案或拒绝方案");
    }
    // 4. 验证脑暴推荐不能自动执行
    if (!canBrainstormAutoExecute(session))
        evidence.push("脑暴推荐不绕过 Decision Sovereignty");
    else
        failures.push("脑暴推荐不应自动执行");
    // 5. 创建取舍矩阵
    const matrix = createTradeoffMatrix({
        matrix_id: "tm-g-1",
        criteria: ["可用性", "复杂度", "成本", "一致性"],
        selected_option_id: "g-o1",
        why_selected_zh: "Redis 集群在高可用场景下综合得分最高",
        why_rejected_zh: [
            { option_id: "g-o2", reason: "单点故障风险过高，不适合生产环境" },
            { option_id: "g-o3", reason: "架构过于复杂，当前团队规模不支持" },
        ],
    }, options);
    if (matrix.selected_option_id === "g-o1" && matrix.why_rejected_zh.length === 2) {
        evidence.push("取舍矩阵生成");
    }
    else {
        failures.push("取舍矩阵内容不完整");
    }
    // 6. 创建第一性原理框架
    const frame = createFirstPrinciplesFrame({
        problem_id: "p-g-1",
        user_goal: "实现高可用缓存",
        fundamental_need: "保证服务在缓存层故障时仍可用",
        known_facts: ["当前 QPS 约 5000", "数据量约 50GB", "团队 3 人"],
        assumptions: ["网络延迟 < 1ms", "读写比 10:1"],
        candidate_solutions: ["Redis 集群", "本地缓存 + Redis", "多级缓存 + MQ"],
        simplest_viable_solution: "Redis 集群 + 本地缓存降级",
        falsification_questions: ["如果 Redis 集群全部宕机怎么办？", "如果网络分区导致脑裂怎么办？"],
        chosen_solution: "Redis 集群 + 本地缓存降级",
        why_not_legacy_path: "当前无缓存方案，不是改造场景",
        first_principles_status: "framed",
    });
    const check1 = performFirstPrinciplesCheck(frame);
    if (check1.passed)
        evidence.push("第一性原理框架完整");
    else
        failures.push(`第一性原理框架不完整: ${check1.failures.join("; ")}`);
    // 7. 创建细节纪律契约并检查
    const ddContract = createDetailDisciplineContract({ contract_id: "dd-g-1" });
    const ddCheck = performDetailCheck(ddContract, "cache-impl", "implementation", {
        edge_cases: ["缓存穿透", "缓存击穿", "缓存雪崩"],
        defaults: ["空缓存默认回源", "连接超时默认 3s"],
        failure_paths: ["Redis 宕机", "网络分区", "内存溢出"],
        cleanup: ["过期 key 自动清理", "宕机后本地缓存自动过期"],
        idempotency: ["相同 key 写入幂等", "删除操作幂等"],
        overwrite_behavior: ["同 key 覆盖写入", "版本号校验"],
        rollback: ["降级到本地缓存", "直接查数据库"],
        evidence: ["压力测试报告", "故障恢复验证"],
    });
    if (ddCheck.detail_check_status === "passed")
        evidence.push("细节纪律检查接入");
    else
        failures.push(`细节纪律检查失败: ${ddCheck.detail_check_status}`);
    // 8. 验证三个契约联动
    if (session.evidence_refs.length > 0 && frame.chosen_solution && ddCheck.detail_check_status === "passed") {
        evidence.push("三个契约联动");
    }
    else {
        failures.push("三个契约联动验证失败");
    }
    return { scenario_id: "scenario-G", scenario_name: "脑暴多方案探索与原则联动", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioH() {
    const evidence = [];
    const failures = [];
    // 输出目录未确认阻断 delivered
    const contract = createArchitectureDesignContract({
        contract_id: "arch-1",
        architecture_design_status: "delivered",
        output_directory_decision: { recommended_name: "output", recommendation_reason_zh: "原因", architecture_output_directory_status: "recommended" },
    });
    const dirCheck = validateOutputDirectoryDecision(contract.output_directory_decision, contract.architecture_design_status);
    if (!dirCheck.allowed)
        evidence.push("输出目录未确认阻断 delivered");
    else
        failures.push("未确认目录不应允许 delivered");
    // Mermaid 渲染失败被检测
    const mermaidCheck = validateMermaidDiagrams([{
            diagram_id: "d1", diagram_type: "sequenceDiagram", required_for: "test",
            mermaid_source: "invalid", render_check_status: "failed",
        }]);
    if (!mermaidCheck.allRenderable)
        evidence.push("Mermaid 渲染失败被检测");
    else
        failures.push("渲染失败应被检测");
    // 架构设计审查
    const goodContract = createArchitectureDesignContract({
        contract_id: "arch-2",
        architecture_design_status: "completed",
        input_set: { task_ids: ["t1"], required_source_artifacts: ["prototype_description"], consumed_files: ["f1"], missing_required_files: [], all_clients_covered: true },
        output_directory_decision: { recommended_name: "output", recommendation_reason_zh: "原因", architecture_output_directory_status: "confirmed", confirmed_name: "output" },
        mermaid_diagram_requirements: [],
    });
    const review = reviewArchitectureDesign(goodContract);
    if (review.passed)
        evidence.push("合规架构设计审查通过");
    else
        failures.push(`合规架构设计应通过: ${review.review.failed_rules.join("; ")}`);
    return { scenario_id: "scenario-H", scenario_name: "架构设计审查", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioI() {
    const evidence = [];
    const failures = [];
    // existing_system 必须先分析
    const ctx1 = detectProjectContext(true, true, true);
    if (ctx1.project_context_type === "existing_system")
        evidence.push("existing_system 正确检测");
    else
        failures.push("应检测为 existing_system");
    const gate1 = checkAnalysisGate(ctx1, false, false);
    if (!gate1.allowed)
        evidence.push("existing_system 必须先分析");
    else
        failures.push("existing_system 未分析不应允许");
    // 有分析后通过
    const gate2 = checkAnalysisGate(ctx1, true, true);
    if (gate2.allowed)
        evidence.push("有分析后通过");
    else
        failures.push("已有分析应允许");
    // empty_project 不要求分析
    const ctx2 = detectProjectContext(false, false, false);
    const gate3 = checkAnalysisGate(ctx2, false, false);
    if (gate3.allowed)
        evidence.push("empty_project 不强制分析");
    else
        failures.push("empty_project 不应强制分析");
    return { scenario_id: "scenario-I", scenario_name: "现有系统分析与差距分析", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioJ() {
    const evidence = [];
    const failures = [];
    // 编码不是第一步 — 缺少验证计划应被阻断
    const contract1 = createCodingReadinessContract({
        task_id: "t1",
        required_preconditions: ["gap_analysis"],
        consumed_constraints: ["gap_analysis"],
        test_first_plan: { ...createTestFirstPlan(true, true, "feature"), test_first_status: "planned" },
        verification_plan_ref: "",
    });
    const eval1 = evaluateCodingReadiness(contract1, true, false, false);
    if (!eval1.allowed)
        evidence.push("缺少验证计划被阻断");
    else
        failures.push("缺少验证计划应被阻断");
    // 完整条件通过
    evaluateCodingReadiness(contract1, true, false, true);
    // 使用完整前置条件
    const contract2 = createCodingReadinessContract({
        task_id: "t2",
        project_context_type: "existing_system",
        required_preconditions: [],
        consumed_constraints: [],
        test_first_plan: { ...createTestFirstPlan(true, true, "feature"), test_first_status: "written" },
        verification_plan_ref: "vp-2",
    });
    const eval3 = evaluateCodingReadiness(contract2, true, false, true);
    if (eval3.allowed)
        evidence.push("完整条件通过编码准备门");
    else
        failures.push(`完整条件应通过: ${eval3.missing_preconditions.join("; ")}`);
    // 主线消费检查
    const mainline = performMainlineConsumptionCheck(["src/new.ts"], ["new"], ["api/new"]);
    if (mainline.orphan_findings.length === 0)
        evidence.push("主线消费检查通过");
    else
        failures.push(`主线孤立: ${mainline.orphan_findings.join("; ")}`);
    return { scenario_id: "scenario-J", scenario_name: "编码准备门与测试优先", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
// runScenarioK (已删除): 使用 runScenarioKAsync 代替
function runScenarioL() {
    const evidence = [];
    const failures = [];
    // 模板必须走完消费 pipeline — 使用真实 owner_mechanism_id
    const workflowEntry = createWorkflowTemplateEntry("architecture_design", "templates/procedures/架构设计工作流.md");
    workflowEntry.owner_mechanism_ids = ["mc-architecture-design"];
    const pack = createWorkflowTemplatePackContract({
        workflows: [workflowEntry],
        mechanism_consumption_map: [{ template_path: "templates/procedures/架构设计工作流.md", consumed_mechanism_id: "mc-architecture-design", consumption_type: "route_trigger", evidence_required: true }],
    });
    // 消费停在中间被检测
    const evidences = [createTemplateConsumptionEvidence("templates/procedures/架构设计工作流.md")];
    evidences[0].template_consumption_status = "file_created";
    const v1 = validateWorkflowTemplatePack(pack, evidences);
    if (!v1.valid)
        evidence.push("停在中间状态被检测");
    else
        failures.push("停在 file_created 应不合规");
    // 走完 pipeline 通过 — 必须有真实链路证据
    evidences[0].template_consumption_status = "verified";
    evidences[0].workflow_template_refs = ["wf-architecture-design"];
    evidences[0].route_trigger_refs = ["架构设计"];
    evidences[0].adapter_prompt_refs = [];
    evidences[0].sync_migration_refs = ["manifest:templates/procedures/架构设计工作流.md"];
    evidences[0].scenario_refs = ["scenario-H"];
    const v2 = validateWorkflowTemplatePack(pack, evidences);
    if (v2.valid)
        evidence.push("走完 pipeline 通过");
    else
        failures.push(`走完 pipeline 应通过: ${v2.violations.join("; ")}`);
    // pipeline 顺序正确
    const adv1 = advanceTemplateConsumptionStatus("missing");
    if (adv1.allowed && adv1.next === "file_created")
        evidence.push("pipeline 顺序正确");
    else
        failures.push("missing → file_created 应允许");
    // 手工置绿必须被检测
    const fakeEvidences = [createTemplateConsumptionEvidence("templates/procedures/架构设计工作流.md")];
    fakeEvidences[0].template_consumption_status = "verified";
    const v3 = validateWorkflowTemplatePack(pack, fakeEvidences);
    if (!v3.valid)
        evidence.push("手工置绿被检测");
    else
        failures.push("手工设置 verified 但无链路引用应不合规");
    return { scenario_id: "scenario-L", scenario_name: "工作流模板包消费", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
function runScenarioM() {
    const evidence = [];
    const failures = [];
    // 重复问题被检测
    const dup = checkDuplicateIssue("实现缓存方案", [
        { id: "issue-1", title: "实现缓存方案", status: "open" },
    ]);
    if (dup.possible_duplicates.length > 0 && dup.can_merge_into_existing_issue) {
        evidence.push("重复问题被检测");
    }
    else {
        failures.push("重复问题应被检测");
    }
    // 模板演进影响被分析
    const impact = analyzeTemplateEvolutionImpact(["extension_contracts"], ["architecture_design"]);
    if (impact.template_update_required)
        evidence.push("模板演进影响被分析");
    else
        failures.push("有 contract 变更应需要模板更新");
    // 未通过门控不得 accepted
    const gate = createNewIssueRegressionGate({
        issue_candidate_id: "new-1",
        candidate_title: "新问题",
        evolution_gate_status: "pending",
    });
    const result = performEvolutionGate(gate);
    if (!result.allowed)
        evidence.push("未通过门控不得 accepted");
    else
        failures.push("pending 状态不应被接受");
    // 通过门控
    const gate2 = createNewIssueRegressionGate({
        issue_candidate_id: "new-2",
        candidate_title: "全新问题",
        evolution_gate_status: "accepted",
        decision: "create_new_batch",
    });
    const result2 = performEvolutionGate(gate2);
    if (result2.allowed)
        evidence.push("通过门控被接受");
    else
        failures.push(`合规门控应通过: ${result2.reasons.join("; ")}`);
    return { scenario_id: "scenario-M", scenario_name: "演进回归与新问题门控", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
/** 运行全部 A-M 场景（场景 K 使用 transport-level 内存验收） */
export async function runAllExtensionScenarios() {
    return [
        runScenarioA(), runScenarioB(), runScenarioC(), runScenarioD(),
        runScenarioE(), runScenarioF(), runScenarioG(), runScenarioH(),
        runScenarioI(), runScenarioJ(),
        await runScenarioKAsync(),
        runScenarioL(), runScenarioM(),
    ];
}
/**
 * 异步版本场景 K: 使用 executeHttpAcceptanceWithTransport() 执行 transport-level 验收。
 * 不启动真实本地 HTTP 服务，使用内存 transport。
 * PASS 证据包含 target_url、health_check_output、browser_steps、assertion_results、run_hash。
 * executeRealHttpAcceptance() 属于实际运行/集成验收能力，不属于默认 gate。
 */
export async function runScenarioKAsync() {
    const evidence = [];
    const failures = [];
    // ── 步骤 1: 评估是否需要本地验收 ──
    const req1 = requiresLocalAcceptance(true, true, true, false);
    if (req1.required && req1.run_mode === "docker_compose")
        evidence.push("docker_compose 项目需要本地验收");
    else
        failures.push("docker_compose 项目应需要本地验收");
    // ── 步骤 2: 内存 transport 验收（不绑定端口） ──
    const targetUrl = "http://127.0.0.1:1/memory-acceptance";
    const transport = async (_url) => ({
        status: 200,
        text: async () => "<html><head><title>SoloForge Test</title></head><body><h1>OK</h1></body></html>",
    });
    // ── 步骤 3: 执行 transport-level HTTP 验收 ──
    const realResult = await executeHttpAcceptanceWithTransport(targetUrl, [
        { name: "状态码 200", check: (status) => status === 200 },
        { name: "body 含 OK", check: (_s, body) => body.includes("OK") },
    ], transport);
    if (realResult.health_check_ok && realResult.http_status === 200) {
        evidence.push(`transport-level 验收通过: ${realResult.health_check_output}`);
    }
    else {
        failures.push(`transport-level 验收失败: ${realResult.health_check_output}`);
    }
    if (realResult.assertion_results.length >= 2 && realResult.assertion_results.every(r => r.endsWith(": PASS"))) {
        evidence.push("transport 断言全部通过");
    }
    else {
        failures.push(`transport 断言失败: ${realResult.assertion_results.join(", ")}`);
    }
    if (realResult.timestamp && realResult.run_hash) {
        evidence.push(`运行证据: ts=${realResult.timestamp}, hash=${realResult.run_hash.slice(0, 20)}...`);
    }
    else {
        failures.push("缺少运行时间戳或 hash");
    }
    // ── 步骤 4: 构造浏览器验收证据 ──
    const browserEvidence = realResultToBrowserEvidence(realResult, "场景K transport-level 验收");
    if (browserEvidence.acceptance_status === "passed") {
        evidence.push("浏览器验收证据状态为 passed");
    }
    else {
        failures.push(`浏览器验收证据状态为 ${browserEvidence.acceptance_status}，期望 passed`);
    }
    if (browserEvidence.browser_steps.length > 0 && browserEvidence.assertion_results.length > 0) {
        evidence.push(`browser_steps: ${browserEvidence.browser_steps[0]}`);
    }
    else {
        failures.push("浏览器验收证据缺少 browser_steps 或 assertion_results");
    }
    // ── 步骤 5: 完整本地验收契约验证 ──
    const contract = createLocalDockerAcceptanceContract({
        project_run_mode: "local_dev_server",
        local_runtime_evidence: {
            build_command: "npm run build",
            image_ids: [],
            build_artifacts: ["dist/bundle.js"],
            container_ids: [],
            service_urls: [targetUrl],
            health_check_outputs: [realResult.health_check_output],
            logs_summary_zh: ["内存 transport 服务正常"],
        },
        browser_acceptance_evidence: [browserEvidence],
        final_access: {
            frontend_urls: [targetUrl],
            backend_urls: [],
            docs_or_swagger_urls: [],
            start_commands: ["npm run dev"],
            stop_commands: ["Ctrl+C"],
            running_status: "running",
            manual_review_steps_zh: [],
            known_limits_zh: [],
        },
    });
    const fullResult = validateLocalAcceptanceEvidence(contract);
    if (fullResult.passed) {
        evidence.push("完整本地验收契约验证通过");
    }
    else {
        failures.push(`完整本地验收契约验证失败: ${fullResult.blocking_reasons.join("; ")}`);
    }
    // ── 步骤 6: 首次验收失败 → 修复循环 ──
    const firstAttempt = performBrowserAcceptance({ target_urls: [targetUrl], user_flows: ["首页"], viewport_matrix: ["desktop"], required_assertions: [], screenshot_or_trace_required: false }, ["TypeError: 模拟错误"], { max_iterations: 3, rebuild_required_after_fix: true, redeploy_required_after_fix: true, retest_required_after_fix: true, stop_conditions: ["retry_budget_exhausted"] });
    if (firstAttempt.needsRepair && firstAttempt.evidence.acceptance_status === "failed") {
        evidence.push("首次验收失败被捕获（capture）");
    }
    else {
        failures.push("首次验收失败应触发修复");
    }
    // 空 errors 被 rejected
    const emptyAttempt = performBrowserAcceptance({ target_urls: [targetUrl], user_flows: ["首页"], viewport_matrix: ["desktop"], required_assertions: [], screenshot_or_trace_required: false }, [], { max_iterations: 3, rebuild_required_after_fix: true, redeploy_required_after_fix: true, retest_required_after_fix: true, stop_conditions: ["retry_budget_exhausted"] });
    if (emptyAttempt.evidence.acceptance_status === "failed" && emptyAttempt.stopReason?.includes("executeRealHttpAcceptance")) {
        evidence.push("空 errors 被正确拒绝");
    }
    else {
        failures.push("空 errors 不应直接判定 passed");
    }
    // 无 URL 不得 delivered
    const noUrlResult = validateFinalAccess({
        frontend_urls: [], backend_urls: [], docs_or_swagger_urls: [],
        start_commands: [], stop_commands: [], running_status: "not_started",
        manual_review_steps_zh: [], known_limits_zh: [],
    }, "docker_compose");
    if (!noUrlResult.passed)
        evidence.push("无 URL 不得 delivered");
    else
        failures.push("无 URL 应被阻断");
    return { scenario_id: "scenario-K", scenario_name: "本地 Docker/浏览器验收（transport-level acceptance）", status: failures.length === 0 ? "PASS" : "FAIL", evidence, failures };
}
//# sourceMappingURL=extension_scenario_registry.js.map