/**
 * 门禁检查模块 — Phase 22: MCP 控制面可信与受控生成链路验证。
 *
 * 验证控制面矩阵完整性、旁路拦截、工具契约有效性、
 * 受控生成链路 must-pass/must-fail、CLI 入口与反旁路硬规则。
 */
import path from "node:path";
import { safeReadCached } from "./helpers.js";
import { errorMessage } from "../../core/helpers.js";
export async function check(ctx, hardFail, _info) {
    try {
        const control = await import("../../contracts/control_plane_contract.js");
        const toolContracts = await import("../../contracts/tool_invocation_contract_registry.js");
        const matrix = control.CONTROL_PLANE_MATRIX ?? [];
        const branchDetails = control.CONTROL_PLANE_BRANCH_DETAILS ?? [];
        if (matrix.length !== 15) {
            hardFail("CONTROL_PLANE_MATRIX_INCOMPLETE", `控制面矩阵数量应为 15，实际为 ${matrix.length}`, ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不覆盖 MCP 控制面可用性与旁路", "补齐控制面矩阵");
        }
        if (branchDetails.length < 30) {
            hardFail("CONTROL_PLANE_BRANCH_DETAILS_INCOMPLETE", `控制面枝叶细节至少 30 条，实际为 ${branchDetails.length}`, ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不覆盖枝叶防回归细节", "补齐枝叶细节");
        }
        if (!control.isSoloforgeStateBypassCommand("rm -rf .soloforge/state/current-task.json")) {
            hardFail("CONTROL_PLANE_BYPASS_GUARD_FALSE_NEGATIVE", "Bash 直接删除 .soloforge/state 未被识别为旁路", ["src/engine/contracts/control_plane_contract.ts", "src/bin/soloforge.ts"], "problem-72", "旧 gate 不验证 Bash/Edit/Write 旁路", "修复旁路拦截");
        }
        if (control.isSoloforgeStateBypassCommand("cat .soloforge/state/current-task.json")) {
            hardFail("CONTROL_PLANE_BYPASS_GUARD_FALSE_POSITIVE", "只读查看 .soloforge/state 被误判为写旁路", ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不检查旁路误拦", "修复旁路判断");
        }
        const contractFindings = control.validateControlPlaneToolContracts(toolContracts.listToolInvocationContracts());
        const hardContractFindings = contractFindings.filter((finding) => finding.severity === "hard_fail");
        if (hardContractFindings.length > 0) {
            hardFail("CONTROL_PLANE_TOOL_CONTRACT_INVALID", `工具控制面契约存在 ${hardContractFindings.length} 个 hard_fail: ${hardContractFindings.map((f) => f.code).join(", ")}`, ["src/engine/contracts/tool_invocation_contract_registry.ts"], "problem-72", "旧 gate 不检查工具错标和死链路", "修复工具契约");
        }
        const fakeContractFindings = control.validateControlPlaneToolContracts([{
                tool_name: "sf_fake_readonly_writer",
                category: "read_only_bypass",
                side_effects: ["task_context_write"],
                requires_authorization: false,
                requires_workflow: false,
                description: "错误契约",
                default_next_tools: [],
                forbidden_next_tools: [],
            }]);
        if (!fakeContractFindings.some((finding) => finding.code === "CONTROL_PLANE_READ_ONLY_HAS_SIDE_EFFECT")) {
            hardFail("CONTROL_PLANE_TOOL_CONTRACT_FALSE_PASS", "read_only_bypass 写状态的假契约未被阻断", ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不验证契约错标 must-fail", "修复工具契约验证");
        }
        const bypassAssessment = control.assessControlledGenerationChain({
            changed_files: ["src/Foo.java"],
            verified_files: ["src/Foo.java"],
            traces: [{ tool_name: "Bash", status: "passed", evidence_kind: "command_execution" }],
            delivery_status: "delivered",
        });
        if (bypassAssessment.accepted || !bypassAssessment.findings.some((finding) => finding.code === "CONTROLLED_GENERATION_MISSING_MCP_PROVENANCE")) {
            hardFail("CONTROLLED_GENERATION_BYPASS_FALSE_PASS", "非 MCP 生成代码被错误接受为完整可信交付", ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不验证来源归因", "修复受控生成链路");
        }
        const partialAssessment = control.assessControlledGenerationChain({
            changed_files: ["src/Foo.java", "src/Bar.java"],
            verified_files: ["src/Foo.java"],
            traces: [
                { tool_name: "sf_classify", task_id: "t1", status: "passed" },
                { tool_name: "sf_expand", task_id: "t1", status: "passed" },
                { tool_name: "sf_verify", task_id: "t1", status: "passed", evidence_kind: "command_execution" },
            ],
            delivery_status: "delivered",
        });
        if (partialAssessment.accepted || !partialAssessment.findings.some((finding) => finding.code === "CONTROLLED_GENERATION_CHANGED_FILE_UNVERIFIED")) {
            hardFail("CONTROLLED_GENERATION_SCOPE_FALSE_PASS", "changed_files 子集验证被错误接受", ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不验证范围完整性", "修复验证范围对账");
        }
        const passAssessment = control.assessControlledGenerationChain({
            changed_files: ["src/Foo.java"],
            verified_files: ["src/Foo.java"],
            traces: [
                { tool_name: "sf_classify", task_id: "t1", status: "passed" },
                { tool_name: "sf_expand", task_id: "t1", status: "passed" },
                { tool_name: "sf_verify", task_id: "t1", status: "passed", evidence_kind: "command_execution" },
                { tool_name: "sf_deliver", task_id: "t1", status: "passed" },
            ],
            delivery_status: "delivered",
        });
        if (!passAssessment.accepted || passAssessment.confidence !== "full") {
            hardFail("CONTROLLED_GENERATION_VALID_CHAIN_BLOCKED", "完整 MCP 受控生成链路被误阻断", ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不验证 must-pass", "修复受控生成链路");
        }
        const cliText = safeReadCached(path.join(ctx.rootDir, "src", "bin", "soloforge.ts"), ctx.readCache) ?? "";
        const validateCmdText = safeReadCached(path.join(ctx.rootDir, "src", "bin", "commands", "validate.ts"), ctx.readCache) ?? "";
        const combinedCliText = cliText + "\n" + validateCmdText;
        if (!combinedCliText.includes("case \"doctor\"") || !combinedCliText.includes("auditControlPlaneProject")) {
            hardFail("CONTROL_PLANE_DOCTOR_MISSING", "CLI 未提供 soloforge doctor 控制面诊断入口", ["src/bin/soloforge.ts"], "problem-72", "旧 gate 没有 MCP 控制面恢复入口", "补 soloforge doctor");
        }
        const checkWriteText = safeReadCached(path.join(ctx.rootDir, "src", "bin", "commands", "check_write.ts"), ctx.readCache) ?? "";
        const checkBashText = safeReadCached(path.join(ctx.rootDir, "src", "bin", "commands", "check_bash.ts"), ctx.readCache) ?? "";
        const combinedGateText = checkWriteText + "\n" + checkBashText;
        const allGateText = combinedGateText + "\n" + combinedCliText;
        if (!allGateText.includes("仍处于 ${currentTask.status}") ||
            !allGateText.includes("缺少 design_artifact_pack") ||
            !allGateText.includes("没有受控 SoloForge 任务") ||
            !allGateText.includes("不得取消/归档当前任务后改用 Bash/Edit/Write") ||
            !allGateText.includes("禁止通过 Bash 直接写业务实现文件")) {
            hardFail("CONTROLLED_IMPLEMENTATION_WRITE_GATE_MISSING", "check-write/check-bash 未覆盖 expanding 卡死、设计产物存在但缺 design_artifact_pack、无受控任务和 Bash 直接编码旁路", ["src/bin/soloforge.ts"], "problem-72", "旧 gate 只在交付层发现非 MCP 来源，未在写入入口阻断真实用户项目旁路", "在 check-write/check-bash 对业务实现文件增加受控任务与设计产物包前置门");
        }
        const assetManifestText = safeReadCached(path.join(ctx.rootDir, "src", "engine", "templates", "asset_manifest.ts"), ctx.readCache) ?? "";
        const workflowRuleText = safeReadCached(path.join(ctx.rootDir, "templates", "internal", "rules", "工作流导航契约规则.md"), ctx.readCache) ?? "";
        const lifecycleProcedureText = safeReadCached(path.join(ctx.rootDir, "templates", "procedures", "全生命周期工作流导航.md"), ctx.readCache) ?? "";
        const antiBypassNeedles = [
            "不得建议取消任务后直接写",
            "不得建议\u201C先用 Bash 直接修改业务代码\u201D",
            "不得手动删除 `.soloforge/state`",
            "归档后仍必须重新 `sf_classify -> sf_expand`",
        ];
        const antiBypassText = `${assetManifestText}\n${workflowRuleText}\n${lifecycleProcedureText}`;
        const missingAntiBypassNeedles = antiBypassNeedles.filter((needle) => !antiBypassText.includes(needle));
        if (missingAntiBypassNeedles.length > 0) {
            hardFail("CONTROL_PLANE_BLOCKED_RECOVERY_PROMPT_MISSING", `适配器/知识规则缺少阻断恢复反旁路硬规则: ${missingAntiBypassNeedles.join(", ")}`, ["src/engine/templates/asset_manifest.ts", "templates/internal/rules/工作流导航契约规则.md", "templates/procedures/全生命周期工作流导航.md"], "problem-72", "运行时 hook 能拦截写入，但模型仍可能口头建议取消任务、Bash 直写或手动清状态", "把阻断恢复反旁路协议注入 adapter workflow 和工作流导航知识资产");
        }
    }
    catch (e) {
        hardFail("CONTROL_PLANE_BEHAVIOR_EXCEPTION", `控制面可信行为验证异常: ${errorMessage(e)}`, ["src/engine/contracts/control_plane_contract.ts"], "problem-72", "旧 gate 不验证控制面可信", "修复控制面契约模块");
    }
}
//# sourceMappingURL=checkControlPlaneTrust.js.map