/**
 * 工作流契约注册表 — 管线双层架构。
 *
 * 顶层：管线契约（新系统管线 / 老系统管线），管控阶段流转。
 * 底层：阶段契约（每个 TaskStage 一个），管控阶段内部执行。
 * 快捷路径：wf-direct-answer / wf-single-artifact 不走管线。
 */
import { debug } from "../core/logger.js";
// ── 支持的路由（除 skip_chat 外） ──
const ROUTES_REQUIRING_WORKFLOW = [
    "direct_answer",
    "artifact_generation",
    "source_extraction",
    "code_change",
    "analysis",
    "review",
    "acceptance",
    "planning",
    "operation",
];
// ── 必需的路由+执行形态覆盖 ──
const REQUIRED_ROUTE_SHAPE_COMBOS = [
    ["direct_answer", "none"],
    ["artifact_generation", "single_artifact"],
    ["artifact_generation", "multi_stage_plan"],
    ["source_extraction", "single_artifact"],
    ["code_change", "code_execution"],
    ["code_change", "multi_stage_plan"],
    ["analysis", "read_only_analysis"],
    ["analysis", "multi_stage_plan"],
    ["review", "read_only_analysis"],
    ["review", "verification_only"],
    ["acceptance", "read_only_analysis"],
    ["planning", "single_artifact"],
    ["planning", "multi_stage_plan"],
    ["operation", "verification_only"],
    ["operation", "read_only_analysis"],
];
// ══════════════════════════════════════════════════
// 管线契约
// ══════════════════════════════════════════════════
export const PIPELINE_CONTRACTS = [
    {
        id: "pipeline-new-system",
        name: "新系统管线",
        system_type: "新系统",
        stages: ["需求分析", "架构设计", "详细设计", "任务规划", "编码与单元测试", "代码审查", "联调验证"],
        governance_checks: ["gc-pipeline-coverage", "gc-stage-gate-consistency"],
    },
    {
        id: "pipeline-existing-system",
        name: "老系统管线",
        system_type: "老系统",
        stages: ["需求分析", "现有系统分析", "架构设计", "详细设计", "任务规划", "编码与单元测试", "代码审查", "联调验证"],
        governance_checks: ["gc-pipeline-coverage", "gc-stage-gate-consistency"],
    },
];
// ══════════════════════════════════════════════════
// 阶段契约
// ══════════════════════════════════════════════════
export const STAGE_CONTRACTS = [
    // ── 1. 需求分析 ──
    {
        id: "stage-需求分析",
        task_stage: "需求分析",
        pipeline_scope: "*",
        required_mechanisms: ["意图路由器", "模板引擎", "意图扩展器"],
        advisory_mechanisms: [],
        required_inputs: ["intent", "route_decision", "原型源码包或需求文档"],
        produced_outputs: ["原型说明或增量边界界定文档"],
        gate_checks: [],
        rollback_targets: [],
        rollback_annotate_targets: [],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
    },
    // ── 2. 现有系统分析（仅老系统） ──
    {
        id: "stage-现有系统分析",
        task_stage: "现有系统分析",
        pipeline_scope: ["老系统"],
        required_mechanisms: ["意图扩展器", "模板引擎", "验证器"],
        advisory_mechanisms: [],
        required_inputs: ["增量边界界定文档", "运行日志或数据库变更日志"],
        produced_outputs: ["全链路数据血缘图", "历史遗留雷区清单"],
        gate_checks: [],
        rollback_targets: ["需求分析"],
        rollback_annotate_targets: [],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
    },
    // ── 3. 架构设计 ──
    {
        id: "stage-架构设计",
        task_stage: "架构设计",
        pipeline_scope: "*",
        required_mechanisms: ["意图路由器", "模板引擎", "意图扩展器"],
        advisory_mechanisms: ["验证器"],
        required_inputs: ["需求文档", "原型说明或数据血缘图"],
        produced_outputs: ["ADR", "架构设计文档"],
        gate_checks: [],
        rollback_targets: ["需求分析"],
        rollback_annotate_targets: [],
        degradation_policy: "block_execution",
        human_gate: ["architecture_decisions_require_user_confirm"],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
    },
    // ── 4. 详细设计 ──
    {
        id: "stage-详细设计",
        task_stage: "详细设计",
        pipeline_scope: "*",
        required_mechanisms: ["意图扩展器", "模板引擎"],
        advisory_mechanisms: ["验证器"],
        required_inputs: ["架构设计文档"],
        produced_outputs: ["数据库设计文档", "接口规格文档", "openapi.yaml"],
        gate_checks: [],
        rollback_targets: ["架构设计"],
        rollback_annotate_targets: ["需求分析"],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
    },
    // ── 5. 任务规划 ──
    {
        id: "stage-任务规划",
        task_stage: "任务规划",
        pipeline_scope: "*",
        required_mechanisms: ["意图扩展器", "模板引擎", "门禁引擎"],
        advisory_mechanisms: [],
        required_inputs: ["详细设计文档"],
        produced_outputs: ["开发任务切片计划"],
        gate_checks: ["一致性校验"],
        rollback_targets: [],
        rollback_annotate_targets: [],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
    },
    // ── 6. 编码与单元测试 ──
    {
        id: "stage-编码与单元测试",
        task_stage: "编码与单元测试",
        pipeline_scope: "*",
        required_mechanisms: ["切片执行器", "模板引擎", "核心工程原则"],
        advisory_mechanisms: [],
        required_inputs: ["切片计划", "详细设计文档"],
        produced_outputs: ["功能代码", "自动化测试覆盖率报告"],
        gate_checks: ["覆盖率校验"],
        rollback_targets: ["详细设计"],
        rollback_annotate_targets: [],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-scope-regression"],
    },
    // ── 7. 代码审查 ──
    {
        id: "stage-代码审查",
        task_stage: "代码审查",
        pipeline_scope: "*",
        required_mechanisms: ["验证器", "模板引擎"],
        advisory_mechanisms: [],
        required_inputs: ["功能代码", "测试覆盖率报告"],
        produced_outputs: ["代码审核通过凭证"],
        gate_checks: ["代码规范审查"],
        rollback_targets: ["编码与单元测试"],
        rollback_annotate_targets: [],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
    },
    // ── 8. 联调验证 ──
    {
        id: "stage-联调验证",
        task_stage: "联调验证",
        pipeline_scope: "*",
        required_mechanisms: ["验证器", "模板引擎", "回退路由"],
        advisory_mechanisms: [],
        required_inputs: ["代码审核通过凭证"],
        produced_outputs: ["联调通过"],
        gate_checks: ["端到端验证"],
        rollback_targets: ["编码与单元测试", "架构设计"],
        rollback_annotate_targets: [],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-verification-regression"],
    },
];
// ══════════════════════════════════════════════════
// 快捷路径（不走管线）
// ══════════════════════════════════════════════════
const SHORTCUT_CONTRACTS = [
    {
        id: "wf-direct-answer",
        routes: ["direct_answer"],
        execution_shapes: ["none"],
        mutation_allowed: false,
        required_mechanisms: ["意图路由器", "模板引擎"],
        prompt_template: "direct_answer_prompt",
        verification_strategy: "text_review",
    },
    {
        id: "wf-single-artifact",
        routes: ["artifact_generation"],
        execution_shapes: ["single_artifact"],
        mutation_allowed: false,
        required_mechanisms: ["意图路由器", "模板引擎", "意图扩展器"],
        prompt_template: "single_artifact_prompt",
        verification_strategy: "template_conformance",
    },
];
// ══════════════════════════════════════════════════
// 兼容旧接口 — 由新管线/阶段契约派生的 route+shape 视图
// ══════════════════════════════════════════════════
/**
 * 旧的 WorkflowContract API 仍被 intent_expander、场景矩阵和若干发布门使用。
 *
 * 这里保留的是“路由兼容视图”，不是新的单真源：项目级流转以
 * PIPELINE_CONTRACTS / STAGE_CONTRACTS 为准。兼容视图只负责把现有
 * route+execution_shape 入口稳定映射到对应阶段能力，避免重构期间入口断链。
 */
function makeWorkflowContract(input) {
    return input;
}
const DEFAULT_STATE_TRANSITIONS = ["classifying→expanding→executing→verifying→learning→done"];
const CODE_STATE_TRANSITIONS = [
    "classifying→expanding→executing→verifying→learning→done",
    "classifying→expanding→clarifying→expanding→executing→verifying→learning→done",
    "verifying→retrying→expanding→executing→verifying→learning→done",
];
const WORKFLOW_CONTRACTS = [
    makeWorkflowContract({
        id: "wf-direct-answer",
        routes: ["direct_answer"],
        execution_shapes: ["none"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary"],
        advisory_mechanisms: [],
        required_inputs: ["intent", "route_decision"],
        produced_outputs: ["answer_text"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: [],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "direct_answer_prompt",
        verification_strategy: "text_review",
    }),
    makeWorkflowContract({
        id: "wf-single-artifact",
        routes: ["artifact_generation"],
        execution_shapes: ["single_artifact"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary", "mc-intent-expander"],
        advisory_mechanisms: ["mc-verifier"],
        required_inputs: ["intent", "route_decision", "output_artifact_spec", "matched_knowledge"],
        produced_outputs: ["artifact_document", "acceptance_checklist"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: ["artifact_completeness", "template_match"],
        degradation_policy: "conservative_output",
        human_gate: ["template_missing_requires_review"],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-orchestration-regression"],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "single_artifact_prompt",
        verification_strategy: "template_conformance",
    }),
    makeWorkflowContract({
        id: "wf-source-extraction",
        routes: ["source_extraction"],
        execution_shapes: ["single_artifact"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary", "mc-intent-expander"],
        advisory_mechanisms: ["mc-verifier"],
        required_inputs: ["intent", "route_decision", "source_materials", "output_path"],
        produced_outputs: ["extracted_artifact"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: ["source_material_read_only", "output_path_confined"],
        degradation_policy: "block_execution",
        human_gate: [],
        governance_checks: [
            "gc-entry-regression",
            "gc-knowledge-regression",
            "gc-permission-regression",
            "gc-source-extraction-constraints",
        ],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "source_extraction_prompt",
        verification_strategy: "source_read_only_confined_output",
    }),
    makeWorkflowContract({
        id: "wf-code-change",
        routes: ["code_change"],
        execution_shapes: ["code_execution"],
        mutation_allowed: true,
        required_mechanisms: [
            "mc-intent-router",
            "mc-knowledge-injection-boundary",
            "mc-intent-expander",
            "mc-verifier",
            "mc-task-context-lifecycle",
        ],
        advisory_mechanisms: ["mc-task-context-lifecycle"],
        required_inputs: ["intent", "route_decision", "scope_confirmation", "matched_knowledge", "verification_plan"],
        produced_outputs: ["code_changes", "diff_attribution", "verification_result"],
        allowed_state_transitions: CODE_STATE_TRANSITIONS,
        required_evidence: ["scope_confirmation", "verification_plan", "diff_attribution", "rollback_path"],
        degradation_policy: "block_execution",
        human_gate: ["scope_uncertain_requires_human_confirm", "delivery_requires_explicit_trigger"],
        governance_checks: [
            "gc-entry-regression",
            "gc-knowledge-regression",
            "gc-scope-regression",
            "gc-verification-regression",
            "gc-rollback-regression",
            "gc-delivery-regression",
            "gc-permission-regression",
        ],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "code_execution_prompt",
        verification_strategy: "build_and_test",
    }),
    makeWorkflowContract({
        id: "wf-multi-stage-plan",
        routes: ["planning"],
        execution_shapes: ["multi_stage_plan"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary", "mc-intent-expander"],
        advisory_mechanisms: ["mc-verifier"],
        required_inputs: ["intent", "route_decision", "matched_knowledge"],
        produced_outputs: ["task_breakdown", "execution_order", "acceptance_criteria"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: ["plan_completeness"],
        degradation_policy: "advisory_only",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "single_artifact_prompt",
        verification_strategy: "plan_review",
    }),
    makeWorkflowContract({
        id: "wf-planning-single-artifact",
        routes: ["planning"],
        execution_shapes: ["single_artifact"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary", "mc-intent-expander"],
        advisory_mechanisms: ["mc-verifier"],
        required_inputs: ["intent", "route_decision", "output_artifact_spec", "matched_knowledge"],
        produced_outputs: ["artifact_document", "planning_notes"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: ["artifact_completeness"],
        degradation_policy: "conservative_output",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression"],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "single_artifact_prompt",
        verification_strategy: "template_conformance",
    }),
    makeWorkflowContract({
        id: "wf-review",
        routes: ["review", "analysis"],
        execution_shapes: ["read_only_analysis"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary", "mc-intent-expander"],
        advisory_mechanisms: ["mc-verifier"],
        required_inputs: ["intent", "route_decision", "target_files_or_diff", "matched_knowledge"],
        produced_outputs: ["review_report", "findings", "risk_assessment"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: [],
        degradation_policy: "advisory_only",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-permission-regression"],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "read_only_analysis_prompt",
        verification_strategy: "manual_review",
    }),
    makeWorkflowContract({
        id: "wf-verification-only",
        routes: ["review", "operation"],
        execution_shapes: ["verification_only"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary", "mc-verifier"],
        advisory_mechanisms: [],
        required_inputs: ["intent", "route_decision", "verification_target"],
        produced_outputs: ["verification_commands", "verification_result"],
        allowed_state_transitions: ["classifying→expanding→verifying→learning→done"],
        required_evidence: [],
        degradation_policy: "human_confirmation_required",
        human_gate: ["verification_uncertain_requires_human"],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-verification-regression"],
        tests: ["tests/engine/workflow_contract_registry.test.ts"],
        prompt_template: "verification_only_prompt",
        verification_strategy: "command_execution",
    }),
    makeWorkflowContract({
        id: "wf-acceptance",
        routes: ["acceptance"],
        execution_shapes: ["read_only_analysis"],
        mutation_allowed: false,
        required_mechanisms: ["mc-intent-router", "mc-knowledge-injection-boundary", "mc-intent-expander", "mc-verifier"],
        advisory_mechanisms: [],
        required_inputs: ["intent", "route_decision", "acceptance_targets"],
        produced_outputs: ["acceptance_readiness_report", "findings", "next_actions"],
        allowed_state_transitions: ["classifying→expanding→verifying→learning→done", "classifying→expanding→done"],
        required_evidence: ["checked_items"],
        degradation_policy: "advisory_only",
        human_gate: [],
        governance_checks: ["gc-entry-regression", "gc-permission-regression"],
        tests: ["tests/engine/acceptance_route.test.ts"],
        prompt_template: "acceptance_prompt",
        verification_strategy: "read_only_acceptance",
    }),
    makeWorkflowContract({
        id: "wf-architecture-design",
        routes: ["artifact_generation"],
        execution_shapes: ["multi_stage_plan"],
        mutation_allowed: false,
        required_mechanisms: [
            "mc-intent-router",
            "mc-knowledge-injection-boundary",
            "mc-intent-expander",
            "mc-architecture-design",
            "mc-decision-sovereignty",
            "mc-brainstorm-contract",
            "mc-first-principles",
            "mc-detail-discipline",
            "mc-architecture-decision-workshop",
            "mc-design-artifact-pack",
        ],
        advisory_mechanisms: [],
        required_inputs: ["intent", "route_decision", "task_inputs", "output_artifact_spec"],
        produced_outputs: ["architecture_decision_workshop", "architecture_design_contract", "design_artifact_pack", "architecture_design_review"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: ["architecture_decisions_confirmed", "design_artifact_pack_ready"],
        degradation_policy: "block_execution",
        human_gate: ["architecture_decisions_require_user_confirm"],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-orchestration-regression"],
        tests: ["tests/engine/extension_scenario_matrix.test.ts"],
        prompt_template: "architecture_design_prompt",
        verification_strategy: "template_conformance",
    }),
    makeWorkflowContract({
        id: "wf-existing-system-gap-analysis",
        routes: ["analysis"],
        execution_shapes: ["multi_stage_plan"],
        mutation_allowed: false,
        required_mechanisms: [
            "mc-intent-router",
            "mc-knowledge-injection-boundary",
            "mc-intent-expander",
            "mc-existing-system-analysis",
            "mc-architecture-design",
            "mc-decision-sovereignty",
            "mc-brainstorm-contract",
            "mc-first-principles",
            "mc-detail-discipline",
        ],
        advisory_mechanisms: [],
        required_inputs: ["intent", "route_decision", "project_context", "existing_system_sources"],
        produced_outputs: ["existing_system_analysis", "requirement_gap_analysis", "mainline_integration_plan"],
        allowed_state_transitions: DEFAULT_STATE_TRANSITIONS,
        required_evidence: ["project_context_detected", "gap_analysis_complete", "mainline_integration_plan"],
        degradation_policy: "human_confirmation_required",
        human_gate: ["unknown_project_type_requires_human", "gap_analysis_requires_human_review"],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-verification-regression"],
        tests: ["tests/engine/extension_scenario_matrix.test.ts"],
        prompt_template: "gap_analysis_prompt",
        verification_strategy: "manual_review",
    }),
    makeWorkflowContract({
        id: "wf-test-first-coding",
        routes: ["code_change"],
        execution_shapes: ["multi_stage_plan"],
        mutation_allowed: true,
        required_mechanisms: [
            "mc-intent-router",
            "mc-knowledge-injection-boundary",
            "mc-intent-expander",
            "mc-verifier",
            "mc-task-context-lifecycle",
            "mc-coding-readiness",
            "mc-existing-system-analysis",
            "mc-architecture-design",
            "mc-detail-discipline",
            "mc-first-principles",
        ],
        advisory_mechanisms: ["mc-task-context-lifecycle"],
        required_inputs: ["intent", "route_decision", "scope_confirmation", "coding_readiness_gate", "test_first_plan"],
        produced_outputs: ["code_changes", "test_first_evidence", "verification_result"],
        allowed_state_transitions: CODE_STATE_TRANSITIONS,
        required_evidence: ["coding_readiness_allowed", "test_first_plan_written", "scope_confirmation", "verification_plan", "rollback_path"],
        degradation_policy: "block_execution",
        human_gate: ["scope_uncertain_requires_human_confirm", "blocked_readiness_requires_human"],
        governance_checks: [
            "gc-entry-regression",
            "gc-knowledge-regression",
            "gc-scope-regression",
            "gc-verification-regression",
            "gc-rollback-regression",
            "gc-delivery-regression",
            "gc-permission-regression",
        ],
        tests: ["tests/engine/extension_scenario_matrix.test.ts"],
        prompt_template: "test_first_coding_prompt",
        verification_strategy: "build_and_test",
    }),
    makeWorkflowContract({
        id: "wf-local-browser-acceptance",
        routes: ["operation"],
        execution_shapes: ["read_only_analysis"],
        mutation_allowed: false,
        required_mechanisms: [
            "mc-intent-router",
            "mc-knowledge-injection-boundary",
            "mc-verifier",
            "mc-local-acceptance",
            "mc-coding-readiness",
            "mc-detail-discipline",
        ],
        advisory_mechanisms: [],
        required_inputs: ["intent", "route_decision", "local_docker_acceptance_contract", "service_runtime_spec"],
        produced_outputs: ["browser_acceptance_evidence", "final_local_access", "verification_result"],
        allowed_state_transitions: ["classifying→expanding→verifying→learning→done", "classifying→expanding→verifying→retrying→executing→verifying→learning→done"],
        required_evidence: ["services_running", "browser_acceptance_completed", "final_urls_provided"],
        degradation_policy: "human_confirmation_required",
        human_gate: ["retry_budget_exhausted_requires_human", "missing_credentials_requires_human", "external_service_unavailable_requires_human"],
        governance_checks: ["gc-entry-regression", "gc-knowledge-regression", "gc-verification-regression"],
        tests: ["tests/engine/extension_scenario_matrix.test.ts"],
        prompt_template: "local_acceptance_prompt",
        verification_strategy: "command_execution",
    }),
];
// ── 管线查询函数 ──
/** 根据系统类型获取管线契约 */
export function findPipelineBySystemType(systemType) {
    return PIPELINE_CONTRACTS.find((p) => p.system_type === systemType);
}
/** 根据任务阶段获取阶段契约 */
export function findStageContract(taskStage) {
    return STAGE_CONTRACTS.find((s) => s.task_stage === taskStage);
}
/** 根据路由决策解析管线或快捷路径 */
export function resolveWorkflowFromRoute(routeDecision) {
    // 检查快捷路径
    const shortcut = SHORTCUT_CONTRACTS.find((sc) => sc.routes.includes(routeDecision.route) && sc.execution_shapes.includes(routeDecision.execution_shape));
    if (shortcut) {
        return { type: "shortcut", contract: shortcut };
    }
    // 按系统类型解析管线
    const systemType = routeDecision.system_type ?? "新系统";
    const pipeline = findPipelineBySystemType(systemType);
    if (!pipeline)
        return undefined;
    // 获取当前阶段（默认从第一个阶段开始）
    const currentStage = pipeline.stages[0];
    if (!currentStage)
        return undefined;
    const stageContract = findStageContract(currentStage);
    if (!stageContract)
        return undefined;
    return { type: "pipeline", pipeline, stage: stageContract };
}
// ── 兼容旧接口的查询函数 ──
export function listWorkflowContracts() {
    return WORKFLOW_CONTRACTS;
}
export function findWorkflowContractById(id) {
    debug("工作流契约", "findWorkflowContractById() 查找契约, id=%s", id);
    return WORKFLOW_CONTRACTS.find((c) => c.id === id);
}
export function findWorkflowContractByRoute(route, shape) {
    debug("工作流契约", "findWorkflowContractByRoute() 查找契约, route=%s, shape=%s", route, shape ?? "any");
    if (shape) {
        return WORKFLOW_CONTRACTS.find((c) => c.routes.includes(route) && c.execution_shapes.includes(shape));
    }
    return WORKFLOW_CONTRACTS.find((c) => c.routes.includes(route));
}
export function resolveWorkflow(routeDecision) {
    const wf = findWorkflowContractByRoute(routeDecision.route, routeDecision.execution_shape);
    if (wf) {
        debug("工作流契约", "解析工作流 %s, 路由 %s", wf.id, routeDecision.route);
    }
    else {
        debug("工作流契约", "未找到匹配的工作流契约, 路由 %s, 形态 %s", routeDecision.route, routeDecision.execution_shape);
    }
    return wf;
}
// ── 治理验证 ──
export function validateWorkflowContracts(contracts = WORKFLOW_CONTRACTS) {
    const findings = [];
    debug("工作流契约", "validateWorkflowContracts() 开始治理验证, 待检查契约数=%d", contracts.length);
    // 1. 入口回退: 每个支持的路由必须解析到至少一个工作流
    for (const route of ROUTES_REQUIRING_WORKFLOW) {
        const matching = contracts.filter((c) => c.routes.includes(route));
        if (matching.length === 0) {
            findings.push({
                severity: "hard_fail",
                workflow_id: "registry",
                rule: "gc-entry-regression",
                message: `Route "${route}" has no workflow contract — entry regression risk`,
            });
        }
    }
    // 2. 编排回退: 并非所有工作流应有相同的必需机制列表
    const mechanismSets = contracts.map((c) => [...c.required_mechanisms].sort().join(","));
    const uniqueSets = new Set(mechanismSets);
    if (uniqueSets.size === 1 && contracts.length > 1) {
        findings.push({
            severity: "hard_fail",
            workflow_id: "registry",
            rule: "gc-orchestration-regression",
            message: "All workflows have identical required_mechanisms — orchestration regression risk",
        });
    }
    // 3. 权限回退
    for (const c of contracts) {
        if (!c.mutation_allowed &&
            c.produced_outputs.some((o) => o.includes("source_code") || o.includes("code_mutation"))) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-permission-regression",
                message: `Read-only workflow "${c.id}" produces source code mutation output — permission regression`,
            });
        }
    }
    // 4. 知识回退
    for (const c of contracts) {
        const hasKnowledgeMechanism = c.required_mechanisms.some((m) => m === "模板引擎" || m === "mc-knowledge-injection-boundary");
        if (!hasKnowledgeMechanism) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-knowledge-regression",
                message: `Workflow "${c.id}" does not reference knowledge injection mechanism — knowledge regression risk`,
            });
        }
    }
    // 5. 范围回退: 允许变更的工作流必须有范围证据
    for (const c of contracts) {
        if (c.mutation_allowed && !c.required_evidence.some((e) => e.includes("scope"))) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-scope-regression",
                message: `Mutable workflow "${c.id}" has no scope-related required_evidence — scope regression risk`,
            });
        }
    }
    // 6. 状态回退
    for (const c of contracts) {
        if (c.allowed_state_transitions.length === 0) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-state-regression",
                message: `Workflow "${c.id}" has no allowed_state_transitions — state regression risk`,
            });
        }
    }
    // 7. 验证回退
    for (const c of contracts) {
        if (c.mutation_allowed && !c.required_evidence.includes("verification_plan")) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-verification-regression",
                message: `Mutable workflow "${c.id}" does not require verification_plan — verification regression risk`,
            });
        }
    }
    // 8. 交付回退
    for (const c of contracts) {
        if (c.produced_outputs.includes("auto_delivery")) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-delivery-regression",
                message: `Workflow "${c.id}" produces auto_delivery — delivery regression risk`,
            });
        }
    }
    // 9. 回退证据回归
    for (const c of contracts) {
        if (c.mutation_allowed && !c.required_evidence.some((e) => e.includes("rollback"))) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-rollback-regression",
                message: `Mutable workflow "${c.id}" has no rollback-related required_evidence — rollback regression risk`,
            });
        }
    }
    // 10. 源码提取约束
    for (const c of contracts) {
        if (c.routes.includes("source_extraction") &&
            (!c.required_evidence.includes("source_material_read_only") ||
                !c.required_evidence.includes("output_path_confined"))) {
            findings.push({
                severity: "hard_fail",
                workflow_id: c.id,
                rule: "gc-source-extraction-constraints",
                message: `Source extraction workflow "${c.id}" must require source_material_read_only and output_path_confined evidence`,
            });
        }
    }
    // 11. 路由+形态唯一性
    const comboMap = new Map();
    for (const c of contracts) {
        for (const r of c.routes) {
            for (const s of c.execution_shapes) {
                const key = `${r}+${s}`;
                if (!comboMap.has(key))
                    comboMap.set(key, []);
                comboMap.get(key).push(c.id);
            }
        }
    }
    for (const [combo, wfIds] of comboMap) {
        if (wfIds.length > 1) {
            findings.push({
                severity: "hard_fail",
                workflow_id: "registry",
                rule: "gc-route-shape-uniqueness",
                message: `Route+shape "${combo}" resolves to multiple workflows: ${wfIds.join(", ")} — must be unique`,
            });
        }
    }
    // 12. 必需路由+形态覆盖
    for (const [route, shape] of REQUIRED_ROUTE_SHAPE_COMBOS) {
        const hasMatch = contracts.some((c) => c.routes.includes(route) && c.execution_shapes.includes(shape));
        if (!hasMatch) {
            findings.push({
                severity: "hard_fail",
                workflow_id: "registry",
                rule: "gc-route-shape-coverage",
                message: `Required route+shape "${route}+${shape}" is not covered by any workflow — coverage gap`,
            });
        }
    }
    // 13. 提示模板多样性
    const templates = contracts.map((c) => c.prompt_template);
    if (new Set(templates).size === 1 && contracts.length > 1) {
        findings.push({
            severity: "hard_fail",
            workflow_id: "registry",
            rule: "gc-prompt-template-diversity",
            message: "All workflows have identical prompt_template — prompt diversity regression",
        });
    }
    // 14. 关键工作流验证策略多样性
    const keyStrategies = ["wf-source-extraction", "wf-code-change", "wf-verification-only"]
        .map((id) => contracts.find((c) => c.id === id)?.verification_strategy)
        .filter(Boolean);
    if (keyStrategies.length >= 2 && new Set(keyStrategies).size === 1) {
        findings.push({
            severity: "hard_fail",
            workflow_id: "registry",
            rule: "gc-verification-strategy-diversity",
            message: "source_extraction, code_change, and verification_only share identical verification_strategy",
        });
    }
    const knownIds = new Set([
        "mc-intent-router",
        "mc-intent-expander",
        "mc-knowledge-injection-boundary",
        "mc-task-context-lifecycle",
        "mc-verifier",
        "mc-architecture-design",
        "mc-decision-sovereignty",
        "mc-brainstorm-contract",
        "mc-first-principles",
        "mc-detail-discipline",
        "mc-architecture-decision-workshop",
        "mc-design-artifact-pack",
        "mc-existing-system-analysis",
        "mc-coding-readiness",
        "mc-local-acceptance",
    ]);
    for (const c of contracts) {
        for (const mId of [...c.required_mechanisms, ...c.advisory_mechanisms]) {
            if (!knownIds.has(mId)) {
                findings.push({
                    severity: "advisory",
                    workflow_id: c.id,
                    rule: "gc-mechanism-reference",
                    message: `Workflow "${c.id}" references unknown mechanism "${mId}"`,
                });
            }
        }
    }
    for (const c of contracts) {
        if (c.advisory_mechanisms.length === 0) {
            findings.push({
                severity: "advisory",
                workflow_id: c.id,
                rule: "gc-advisory-mechanisms",
                message: `Workflow "${c.id}" has no advisory_mechanisms`,
            });
        }
    }
    for (const c of contracts) {
        if (c.tests.length === 0) {
            findings.push({
                severity: "advisory",
                workflow_id: c.id,
                rule: "gc-tests",
                message: `Workflow "${c.id}" has no test files`,
            });
        }
    }
    for (let i = 0; i < contracts.length; i++) {
        for (let j = i + 1; j < contracts.length; j++) {
            const a = [...contracts[i].required_inputs].sort().join(",");
            const b = [...contracts[j].required_inputs].sort().join(",");
            if (a === b) {
                findings.push({
                    severity: "advisory",
                    workflow_id: contracts[i].id,
                    rule: "gc-inputs-duplication",
                    message: `Workflow "${contracts[i].id}" and "${contracts[j].id}" have identical required_inputs`,
                });
            }
        }
    }
    const hardFails = findings.filter(f => f.severity === "hard_fail").length;
    debug("工作流契约", "validateWorkflowContracts() 治理验证完成, %d 个硬性失败, %d 个建议性警告", hardFails, findings.length - hardFails);
    return findings;
}
//# sourceMappingURL=workflow_contract_registry.js.map