/**
 * 发布就绪门禁 — CLI 和 npm 共用的正式发布检查逻辑。
 *
 * 本模块是 validate-release 的唯一正式入口。
 * 各 phase 已拆分至 gate_checks/ 目录下的独立模块。
 *
 * 检查项（共 14 项）：
 * 1. dist 旧产物风险 (checkDistFreshness)
 * 2. npm pack 验证 (checkNpmPack)
 * 3. 依赖漏洞扫描 (checkDependencyAudit)
 * 4. MCP 控制面可信与受控生成链路验证 (checkControlPlaneTrust)
 * 5. 关键问题消费验证 (checkCriticalProblemConsumption)
 * 6. 主链路真实消费 (checkMainlineConsumption)
 * 7. P0/P1 知识资产 schema (checkKnowledgeAssetSchemaP0)
 * 8. 模板卫生与项目知识消费验证 (checkTemplateKnowledgeHygiene)
 * 9. 工作流导航契约行为验证 (checkWorkflowNavigation)
 * 10. TypeScript 编译检查 (checkTypeScriptCompile)
 * 11. 发布问题场景矩阵执行 (executeReleaseIssueScenarios)
 * 12. 代码质量门禁 (check:quality)
 * 13. 架构边界回归 (tests/architecture/)
 * 14. 模板消费覆盖率 (template_consumption_coverage)
 */
import { buildGateContext } from "./gate_checks/helpers.js";
// ── 导入检查模块 ──
import { check as checkDistFreshness } from "./gate_checks/checkDistFreshness.js";
import { check as checkMainlineConsumption } from "./gate_checks/checkMainlineConsumption.js";
import { check as checkDependencyAudit } from "./gate_checks/checkDependencyAudit.js";
import { check as checkKnowledgeAssetSchemaP0 } from "./gate_checks/checkKnowledgeAssetSchemaP0.js";
import { check as checkCriticalProblemConsumption } from "./gate_checks/checkCriticalProblemConsumption.js";
import { check as checkControlPlaneTrust } from "./gate_checks/checkControlPlaneTrust.js";
import { check as checkTemplateKnowledgeHygiene } from "./gate_checks/checkTemplateKnowledgeHygiene.js";
import { check as checkWorkflowNavigation } from "./gate_checks/checkWorkflowNavigation.js";
import { check as checkNpmPack } from "./gate_checks/checkNpmPack.js";
import { executeReleaseIssueScenarios } from "./release_issue_scenario_registry/registry.js";
import { errorMessage } from "../core/helpers.js";
import { execFileSync } from "node:child_process";
import fss from "node:fs";
// ── Phase 10: TypeScript 编译检查 ──
/**
 * TypeScript 编译检查 — 仅在 dist/ 目录存在时执行 tsc --noEmit。
 * 验证 TypeScript 源码零编译错误。
 */
function checkTypeScriptCompile(ctx, hardFail) {
    const distDir = fss.existsSync(ctx.rootDir) ? ctx.rootDir : process.cwd();
    // 检测 dist 目录是否存在
    if (!fss.existsSync(distDir + "/dist")) {
        return; // 无 dist 目录则跳过（不影响发布门禁通过）
    }
    // 检测 tsconfig.json 是否存在
    if (!fss.existsSync(distDir + "/tsconfig.json")) {
        return;
    }
    try {
        execFileSync("npx", ["tsc", "--noEmit"], { cwd: distDir, encoding: "utf-8", timeout: 120_000, stdio: ["pipe", "pipe", "pipe"] });
    }
    catch (e) {
        const err = e;
        hardFail("TSC_COMPILE_ERROR", `TypeScript 编译检查失败: ${err.stderr?.trim() || err.message || "未知错误"}`, ["src/"], "TypeScript 编译检查", "旧门禁不检查 TypeScript 编译", "修复 TypeScript 编译错误后重新构建");
    }
}
// ── 主入口 ──
export async function runReleaseReadinessGate(rootDir) {
    const hardFails = [];
    const phases = [];
    // 初始化日志器为静默模式
    const { initLogger, resetLogger } = await import("../core/logger.js");
    initLogger({ silent: true });
    // 兜底: 拦截 console.error，捕获噪音
    const origConsoleError = console.error;
    const noiseLogs = [];
    console.error = (...args) => { noiseLogs.push(args.map(String).join(" ")); };
    try {
        // 构建共享上下文
        const ctx = buildGateContext(rootDir);
        const info = () => { };
        // ── 并行执行组 1: 静态检查（不依赖 dist/） ──
        await Promise.all([
            runPhase("dist 旧产物风险", (hf) => checkDistFreshness(ctx, hf)),
            runPhase("主链路真实消费", (hf) => checkMainlineConsumption(ctx, hf, info)),
            runPhase("依赖漏洞扫描", (hf) => checkDependencyAudit(ctx, hf, info)),
            runPhase("P0/P1 知识资产 schema", (hf) => checkKnowledgeAssetSchemaP0(ctx, hf, info)),
            runPhase("TypeScript 编译检查", (hf) => checkTypeScriptCompile(ctx, hf)),
        ]);
        // ── 并行执行组 2: 动态/行为级检查 ──
        await Promise.all([
            runPhase("关键问题消费验证", (hf) => checkCriticalProblemConsumption(ctx, hf, info)),
            runPhase("MCP 控制面可信与受控生成链路验证", (hf) => checkControlPlaneTrust(ctx, hf)),
            runPhase("模板卫生与项目知识消费验证", (hf) => checkTemplateKnowledgeHygiene(ctx, hf, info)),
            runPhase("工作流导航契约行为验证", (hf) => checkWorkflowNavigation(ctx, hf, info)),
            runPhase("npm pack 验证", (hf) => checkNpmPack(ctx, hf, info)),
        ]);
        // ── Phase 10: 发布问题场景矩阵执行 ──
        await runPhase("发布问题场景矩阵", async (hf) => {
            try {
                const results = await executeReleaseIssueScenarios();
                const failed = results.filter((r) => r.status === "fail");
                if (failed.length > 0) {
                    hf("RELEASE_SCENARIO_MATRIX_FAILURE", `场景矩阵有 ${failed.length} 个失败: ${failed.map((f) => `${f.scenario_id}: ${f.error ?? "unknown"}`).join("; ")}`, ["src/engine/release/release_issue_scenario_registry/"], "发布问题场景矩阵", "旧门禁不验证场景矩阵完整性", "修复失败场景对应的生产代码");
                }
            }
            catch (e) {
                hf("RELEASE_SCENARIO_MATRIX_ERROR", `场景矩阵执行异常: ${errorMessage(e)}`, ["src/engine/release/release_issue_scenario_registry/registry.ts"], "发布问题场景矩阵", "场景矩阵执行器不可用", "修复 executeReleaseIssueScenarios");
            }
        });
        // ── Phase 12: 代码质量门禁 ──
        await runPhase("代码质量门禁", async (hf) => {
            try {
                const result = execFileSync("node", ["scripts/check_lazy_patterns.mjs"], {
                    cwd: ctx.rootDir,
                    encoding: "utf-8",
                    timeout: 60_000,
                });
                if (result.includes("check:quality 失败")) {
                    hf("CODE_QUALITY_GATE_FAILURE", "check:quality 检测到代码偷懒模式（空函数体/空 catch/TODO/未实现占位）", ["scripts/check_lazy_patterns.mjs"], "代码质量门禁", "旧门禁不检查代码偷懒模式", "修复 check:quality 报告的 hard_fail 项");
                }
            }
            catch (e) {
                // execFileSync 非零退出码抛异常 — 即 check:quality 发现 hard_fail
                hf("CODE_QUALITY_GATE_FAILURE", `check:quality 失败: ${errorMessage(e)}`, ["scripts/check_lazy_patterns.mjs"], "代码质量门禁", "旧门禁不检查代码偷懒模式", "修复 check:quality 报告的 hard_fail 项");
            }
        });
        // ── Phase 13: 架构边界回归 ──
        await runPhase("架构边界回归", async (hf) => {
            try {
                const result = execFileSync("npx", ["vitest", "run", "tests/architecture/"], {
                    cwd: ctx.rootDir,
                    encoding: "utf-8",
                    timeout: 120_000,
                });
                if (result.includes("failed")) {
                    hf("ARCHITECTURE_BOUNDARY_FAILURE", "架构边界回归测试失败 — 21 条硬规则或边界不变量违反", ["tests/architecture/"], "架构边界回归", "旧门禁不验证架构边界不变量", "修复 architecture_boundary/adapter_consistency/template_integrity 测试失败项");
                }
            }
            catch (e) {
                // vitest 非零退出码 → 有测试失败
                hf("ARCHITECTURE_BOUNDARY_FAILURE", `架构边界回归测试失败: ${errorMessage(e)}`, ["tests/architecture/"], "架构边界回归", "旧门禁不验证架构边界不变量", "修复 architecture_boundary/adapter_consistency/template_integrity 测试失败项");
            }
        });
    }
    finally {
        // 恢复 console.error 和日志器
        console.error = origConsoleError;
        resetLogger();
    }
    // ── Phase 14: 模板消费覆盖率 ──
    await runPhase("模板消费覆盖率", async (hf) => {
        try {
            const result = execFileSync("npx", ["vitest", "run",
                "tests/architecture/template_consumption_coverage.test.ts",
                "tests/architecture/template_integrity.test.ts",
            ], {
                cwd: rootDir,
                encoding: "utf-8",
                timeout: 120_000,
            });
            if (result.includes("failed")) {
                hf("TEMPLATE_CONSUMPTION_COVERAGE_FAILURE", "模板消费覆盖率测试失败 — 存在无法被任何 stage×shape 组合消费的模板文件", ["tests/architecture/template_consumption_coverage.test.ts"], "模板消费覆盖率", "旧门禁不验证模板文件的消费可达性", "检查失败测试列出的文件是否已注册并配置正确的 type/stages/shape");
            }
        }
        catch (e) {
            hf("TEMPLATE_CONSUMPTION_COVERAGE_EXCEPTION", `模板消费覆盖率测试执行异常: ${errorMessage(e)}`, ["tests/architecture/template_consumption_coverage.test.ts"], "模板消费覆盖率", "旧门禁不验证模板文件的消费可达性", "修复测试异常");
        }
    });
    // 噪音检测
    const capturedNoiseCount = noiseLogs.filter((l) => l.includes("[soloForge]")).length;
    if (capturedNoiseCount > 0) {
        hardFails.push({
            code: "OUTPUT_NOISE",
            message: `发布门禁运行时产生 ${capturedNoiseCount} 条模块噪音日志`,
            files: ["src/engine/core/logger.ts"],
            issueOrMech: "发布门禁输出质量",
            oldGateMissed: "旧 gate 不检查自身输出噪音",
            nextStep: "日志治理",
        });
    }
    return {
        passed: hardFails.length === 0,
        hard_fail_count: hardFails.length,
        hard_fails: hardFails,
        phases: phases.map((p) => ({ name: p.name, hard_fail_count: p.hard_fail_count })),
        noise_log_count: capturedNoiseCount,
    };
    // ── 辅助: 运行单个 phase 并记录结果 ──
    async function runPhase(name, fn) {
        const phaseFails = [];
        const phaseHardFail = (code, message, files, issueOrMech, oldGateMissed, nextStep) => {
            const finding = { code, message, files, issueOrMech, oldGateMissed, nextStep };
            hardFails.push(finding);
            phaseFails.push(finding);
        };
        try {
            await fn(phaseHardFail);
        }
        catch (e) {
            const finding = {
                code: "PHASE_EXCEPTION",
                message: `Phase "${name}" 执行异常: ${errorMessage(e)}`,
                files: [],
                issueOrMech: name,
                oldGateMissed: "phase 执行异常",
                nextStep: "修复异常",
            };
            hardFails.push(finding);
            phaseFails.push(finding);
        }
        phases.push({ name, hard_fail_count: phaseFails.length });
    }
}
//# sourceMappingURL=release_readiness_gate.js.map