// ── 门控检查函数 ──
// 所有 gate-check 函数的独立模块
import { hasWriteSideEffect, } from "../../engine/contracts/tool_invocation_contract_registry.js";
import { TOOL_DIAGNOSTIC_CODES } from "../../engine/audit/diagnostic_registry.js";
import { lazyInstructionContract, lazyArchitectureDesign, lazyArchitectureWorkshop, lazyExistingSystemAnalysis, lazyCodingReadiness, lazyLocalAcceptance, } from "./lazy_loaders.js";
export function checkWriteToolPlanGate(params) {
    if (!hasWriteSideEffect(params.sideEffects))
        return { allowed: true };
    if (!params.ctx || !params.ctx.plan_proposal_gate) {
        return {
            allowed: false,
            diagnostic_code: TOOL_DIAGNOSTIC_CODES.planGate,
            violation_type: "guard_blocked",
            reason: `工具 ${params.toolName} 执行前缺少 Plan Proposal Gate`,
        };
    }
    return { allowed: true };
}
/**
 * 施工指令契约门 — 写操作前检查施工指令完整性。
 * 通过引擎模块函数真实消费。
 * 调用链 1: registerInstructionIssueCandidate（无契约时创建候选 draft）
 * 调用链 2: enforceInstructionBeforeImplementation → checkInstructionCompleteness → validateInstructionContract
 */
export async function checkInstructionContractGate(params) {
    if (!hasWriteSideEffect(params.sideEffects))
        return { allowed: true };
    if (!params.ctx)
        return { allowed: true };
    let instruction = params.ctx.instruction_contract;
    const instrModule = await lazyInstructionContract();
    // 无契约时消费 registerInstructionIssueCandidate — 创建 draft 候选并保存
    if (!instruction && params.task_id) {
        instruction = instrModule.registerInstructionIssueCandidate({
            task_id: params.task_id,
            description: params.toolName,
            source: "auto_detected",
            suggested_fields: {},
        });
        params.ctx.instruction_contract = instruction;
        if (params.taskContextMgr) {
            await params.taskContextMgr.save(params.ctx);
        }
    }
    if (!instruction)
        return { allowed: true };
    // 消费 enforceInstructionBeforeImplementation（链式消费 checkInstructionCompleteness + validateInstructionContract）
    const result = await instrModule.enforceInstructionBeforeImplementation(instruction, params.toolName);
    // Draft 状态不阻断 — 仅在 confirmed/executing/blocked 状态时强制
    if (instruction?.status === "draft") {
        return { allowed: true, findings: result.allowed ? [] : [result.reason_zh] };
    }
    if (!result.allowed) {
        return {
            allowed: false,
            diagnostic_code: result.diagnostic_code,
            violation_type: "guard_blocked",
            reason: result.reason_zh,
        };
    }
    return { allowed: true };
}
/**
 * 设计产物编码门 — 依赖设计包的任务，在真实复验完成前不得写入业务实现。
 * 仅阻断文件/配置/外部交付写入；任务状态、设计文档复验和讨论本身仍可推进。
 */
export function checkDesignArtifactWriteGate(params) {
    const implementationWrite = params.sideEffects.some((effect) => ["file_write", "config_write", "external_write", "git_commit", "git_push", "pr_create"].includes(effect));
    if (!implementationWrite || !params.ctx?.design_artifact_pack)
        return { allowed: true };
    if (params.ctx.design_artifact_pack.status === "implementation_ready")
        return { allowed: true };
    return {
        allowed: false,
        diagnostic_code: "SF-DESIGN-PACK-NOT-READY",
        reason: `工具 ${params.toolName} 依赖的设计产物包状态为 ${params.ctx.design_artifact_pack.status}，未完成真实复验，不得写入实现或交付`,
    };
}
/**
 * 架构设计门 — 架构设计类任务膨胀前执行 reviewArchitectureDesign。
 * Architecture Design Contract enforcement。
 */
export async function checkArchitectureDesignGate(params) {
    const route = params.route;
    if (route !== "artifact_generation" && route !== "analysis")
        return { allowed: true };
    if (!params.ctx)
        return { allowed: true };
    const expansion = params.ctx.expansion;
    if (!expansion)
        return { allowed: true };
    const archModule = await lazyArchitectureDesign();
    const contract = expansion.architecture_contract;
    if (contract) {
        const result = archModule.reviewArchitectureDesign(contract);
        if (!result.passed) {
            return {
                allowed: false,
                reason_zh: "架构设计审查未通过",
                findings: result.review.missing_sections ?? ["架构设计审查失败"],
            };
        }
    }
    return { allowed: true };
}
/**
 * 架构决策研讨门 — 正式架构设计前六域决策必须闭合。
 * 与是否存在施工指令契约无关，架构设计路由必经此门。
 */
export async function checkArchitectureDecisionWorkshopGate(params) {
    const workshopModule = await lazyArchitectureWorkshop();
    if (!workshopModule.requiresArchitectureDecisionWorkshop(params.workflowIntent, params.ctx.intent)) {
        return { allowed: true };
    }
    const existing = params.ctx.architecture_decision_workshop;
    const contract = existing ?? workshopModule.createArchitectureDecisionWorkshop(params.ctx.task_id, params.projectContext ?? "new_system");
    if (params.projectContext === "existing_system" && contract.project_context !== "existing_system") {
        contract.project_context = "existing_system";
    }
    const evaluatedContract = workshopModule.applyArchitectureWorkshopGate(contract) ?? contract;
    const gate = workshopModule.evaluateArchitectureDecisionWorkshop(evaluatedContract);
    params.ctx.architecture_decision_workshop = evaluatedContract;
    return {
        allowed: gate.allowed,
        findings: gate.blocking_findings,
        next_domain: gate.next_domain,
        contract: evaluatedContract,
    };
}
/**
 * 现有系统分析门 — 现有项目编码前必须先做分析。
 * Existing System Analysis Contract enforcement。
 */
export async function checkExistingSystemAnalysisGate(params) {
    const archModule = await lazyExistingSystemAnalysis();
    const context = archModule.detectProjectContext(params.hasExistingCode, params.hasPackageJson, params.hasSrcDir);
    const gateResult = archModule.checkAnalysisGate(context, params.hasAnalysis, params.hasGapAnalysis);
    if (!gateResult.allowed) {
        return {
            allowed: false,
            reason_zh: gateResult.reason,
            missing_analysis: gateResult.missing_analysis,
        };
    }
    return { allowed: true };
}
/**
 * 编码就绪门 — 编码前必须有测试计划 + 验收标准。
 * Coding Readiness / Test-First enforcement。
 */
export async function checkCodingReadinessGate(params) {
    if (!params.ctx)
        return { allowed: true };
    const readinessModule = await lazyCodingReadiness();
    const contract = params.ctx.coding_readiness_contract;
    if (!contract) {
        return {
            allowed: true,
            reason_zh: "无编码就绪契约（非编码任务），放行",
        };
    }
    const result = readinessModule.evaluateCodingReadiness(contract, false, false, false);
    if (!result.allowed) {
        return {
            allowed: false,
            reason_zh: result.reason,
            missing_preconditions: result.missing_preconditions,
        };
    }
    return { allowed: true };
}
/**
 * 本地验收门 — 前端/全栈交付前必须有本地访问证据。
 * Local Docker / Browser Acceptance enforcement。
 */
export async function checkLocalAcceptanceGate(params) {
    const acceptanceModule = await lazyLocalAcceptance();
    const requirement = acceptanceModule.requiresLocalAcceptance(params.hasFrontend, params.hasBackend, params.hasDockerCompose, params.hasDockerfile);
    if (!requirement.required)
        return { allowed: true };
    if (!params.ctx) {
        return {
            allowed: false,
            reason_zh: "需要本地验收但无任务上下文",
            required_but_missing: ["local_acceptance_evidence"],
        };
    }
    const evidence = params.ctx.local_acceptance_evidence;
    if (!evidence) {
        return {
            allowed: false,
            reason_zh: `项目需要本地验收（模式: ${requirement.run_mode}）但缺少验收证据`,
            required_but_missing: ["local_acceptance_evidence", "final_access_url"],
        };
    }
    if (evidence.run_mode === "not_applicable") {
        return {
            allowed: false,
            reason_zh: "该项目需要本地验收，不得以 not_applicable 代替真实访问证据",
            required_but_missing: ["manual_review", "final_access_url"],
        };
    }
    const finalAccessResult = acceptanceModule.validateFinalAccess(evidence.final_access, requirement.run_mode);
    if (!finalAccessResult.passed) {
        return {
            allowed: false,
            reason_zh: `本地验收证据不完整: ${finalAccessResult.blocking_reasons.join("; ")}`,
            required_but_missing: ["validated_final_access"],
        };
    }
    return { allowed: true };
}
//# sourceMappingURL=gate_checks.js.map