/**
 * Phase 8: 关键问题消费验证 (problem-17/38/57/60)
 */
import fs from "node:fs";
import path from "node:path";
import { safeReadCached } from "./helpers.js";
import { sourceContainsIdentifier } from "../../source_code_matcher.js";
import { errorMessage } from "../../core/helpers.js";
export async function check(ctx, hardFail, info) {
    const rootDir = ctx.rootDir;
    const taskContextPath = path.join(rootDir, "src/engine/pipeline/task_context.ts");
    const cliPath = path.join(rootDir, "src/bin/soloforge.ts");
    // 巨石拆分后 task_context.ts 是薄 re-export 入口，
    // 实际实现在 task_context/ 子目录。此函数将两者内容合并。
    const readTaskContextSources = () => {
        const parts = [];
        const stub = safeReadCached(taskContextPath, ctx.readCache);
        if (stub)
            parts.push(stub);
        const subDir = path.join(rootDir, "src/engine/pipeline/task_context");
        if (fs.existsSync(subDir)) {
            for (const f of fs.readdirSync(subDir).filter((n) => n.endsWith(".ts"))) {
                const c = safeReadCached(path.join(subDir, f), ctx.readCache);
                if (c)
                    parts.push(c);
            }
        }
        return parts.join("\n");
    };
    const tcSources = readTaskContextSources();
    // problem-17: StateFact 分区 — save() 必须调用 validateStateFactPartition，hard_fail 必须 throw
    const stateFactPath = path.join(rootDir, "src/engine/state_fact_classifier.ts");
    if (!fs.existsSync(stateFactPath)) {
        hardFail("CRITICAL_PROBLEM_FILE_MISSING", "problem-17: state_fact_classifier.ts 不存在", ["src/engine/state_fact_classifier.ts"], "problem-17", "发布门禁不检查 problem-17 实现", "创建 state_fact_classifier.ts");
    }
    else {
        const sfContent = safeReadCached(stateFactPath, ctx.readCache);
        if (!sfContent || !sourceContainsIdentifier(sfContent, "validateStateFactPartition")) {
            hardFail("CRITICAL_PROBLEM_EXPORT_MISSING", "problem-17: state_fact_classifier.ts 未导出 validateStateFactPartition", ["src/engine/state_fact_classifier.ts"], "problem-17", "StateFact 分类器缺少核心导出函数", "添加 validateStateFactPartition 导出");
        }
        if (!sourceContainsIdentifier(tcSources, "validateStateFactPartition")) {
            hardFail("CRITICAL_PROBLEM_NOT_CONSUMED", "problem-17: task_context.ts save() 未调用 validateStateFactPartition", ["src/engine/pipeline/task_context.ts", "src/engine/state_fact_classifier.ts"], "problem-17", "StateFact 分区定义存在但未接入 TaskContext 保存路径", "在 task_context.ts save() 中接入 validateStateFactPartition");
        }
        else {
            // 验证 hard_fail 时 throw（不是静默跳过）
            const tcLines = tcSources.split("\n");
            const vspLine = tcLines.findIndex(l => l.includes("validateStateFactPartition"));
            if (vspLine === -1) {
                hardFail("CRITICAL_PROBLEM_NOT_CONSUMED", "problem-17: task_context.ts save() 未调用 validateStateFactPartition", ["src/engine/pipeline/task_context.ts"], "problem-17", "StateFact 分区定义存在但未接入 TaskContext 保存路径", "接入 validateStateFactPartition");
            }
            else {
                // 检查调用后有 hard_fail throw 路径
                const afterVsp = tcLines.slice(vspLine, vspLine + 15).join("\n");
                if (!(afterVsp.includes("throw") || afterVsp.includes("hardFails") || afterVsp.includes("hard_fail"))) {
                    hardFail("CRITICAL_PROBLEM_SOFT_ENFORCEMENT", "problem-17: task_context.ts 中 validateStateFactPartition 调用后缺少 hard_fail throw 路径", ["src/engine/pipeline/task_context.ts"], "problem-17", "StateFact 校验结果被忽略而非阻断", "校验 hard_fail 时 throw Error");
                }
            }
        }
    }
    // problem-38: Retention Policy — cleanup 必须调用 evaluateCleanup/checkForbiddenContent，存在 referenced evidence 保护
    const retentionPath = path.join(rootDir, "src/engine/retention_policy.ts");
    if (!fs.existsSync(retentionPath)) {
        hardFail("CRITICAL_PROBLEM_FILE_MISSING", "problem-38: retention_policy.ts 不存在", ["src/engine/retention_policy.ts"], "problem-38", "发布门禁不检查 problem-38 实现", "创建 retention_policy.ts");
    }
    else {
        const retContent = safeReadCached(retentionPath, ctx.readCache);
        if (!retContent || !retContent.includes("evaluateCleanup") || !retContent.includes("checkForbiddenContent")) {
            hardFail("CRITICAL_PROBLEM_EXPORT_MISSING", "problem-38: retention_policy.ts 未导出 evaluateCleanup 或 checkForbiddenContent", ["src/engine/retention_policy.ts"], "problem-38", "Retention Policy 缺少核心清理函数", "添加 evaluateCleanup 和 checkForbiddenContent 导出");
        }
        const cliContent = safeReadCached(cliPath, ctx.readCache);
        const tcHasCleanup = tcSources.includes("evaluateCleanup");
        const cliHasCleanup = cliContent?.includes("evaluateCleanup") ?? false;
        if (!tcHasCleanup && !cliHasCleanup) {
            hardFail("CRITICAL_PROBLEM_NOT_CONSUMED", "problem-38: evaluateCleanup 未被 task_context.ts 或 soloforge.ts 调用", ["src/engine/pipeline/task_context.ts", "src/bin/soloforge.ts", "src/engine/retention_policy.ts"], "problem-38", "Retention Policy 定义存在但无清理消费者", "将 evaluateCleanup 接入 TaskContext cleanup 或 CLI cleanup 命令");
        }
        // 验证 CLI cleanup 中有 referenced evidence 保护逻辑
        if (cliContent) {
            const cliLines = cliContent.split("\n");
            const cleanupFn = cliLines.findIndex(l => l.match(/^(async\s+)?function\s+cmdCleanup/));
            if (cleanupFn !== -1) {
                // 搜索到下一个顶层函数或文件末尾
                let cleanupEnd = cliLines.length;
                for (let i = cleanupFn + 3; i < cliLines.length; i++) {
                    if (cliLines[i].match(/^async function\s+\w+|^function\s+\w+/)) {
                        cleanupEnd = i;
                        break;
                    }
                }
                const cleanupBody = cliLines.slice(cleanupFn, cleanupEnd).join("\n");
                if (!cleanupBody.includes("referencedEvidenceIds") || !cleanupBody.includes("is_referenced")) {
                    hardFail("CRITICAL_PROBLEM_SOFT_ENFORCEMENT", "problem-38: CLI cleanup 缺少真实 evidence 引用扫描（无 referencedEvidenceIds 或 is_referenced 逻辑）", ["src/bin/soloforge.ts"], "problem-38", "cleanup 未扫描 task context / governance report 中的 evidence 引用", "添加真实引用扫描");
                }
                // 验证策略异常导致非零退出
                if (!cleanupBody.includes("process.exit(1)")) {
                    hardFail("CRITICAL_PROBLEM_SOFT_ENFORCEMENT", "problem-38: CLI cleanup 策略异常时未非零退出", ["src/bin/soloforge.ts"], "problem-38", "策略异常被吞而非阻断", "添加 process.exit(1) 在 catch 中");
                }
            }
        }
    }
    // problem-57: Knowledge Asset Audit — audit-template-mechanisms 必须调用 auditKnowledgeAssets 且 hard_fail/异常 process.exit(1)
    const kaAuditPath = path.join(rootDir, "src/engine/knowledge/knowledge_asset_audit.ts");
    if (!fs.existsSync(kaAuditPath)) {
        hardFail("CRITICAL_PROBLEM_FILE_MISSING", "problem-57: knowledge_asset_audit.ts 不存在", ["src/engine/knowledge/knowledge_asset_audit.ts"], "problem-57", "发布门禁不检查 problem-57 实现", "创建 knowledge_asset_audit.ts");
    }
    else {
        const kaContent = safeReadCached(kaAuditPath, ctx.readCache);
        if (!kaContent || !kaContent.includes("auditKnowledgeAssets")) {
            hardFail("CRITICAL_PROBLEM_EXPORT_MISSING", "problem-57: knowledge_asset_audit.ts 未导出 auditKnowledgeAssets", ["src/engine/knowledge/knowledge_asset_audit.ts"], "problem-57", "Knowledge Asset Audit 缺少核心审计函数", "添加 auditKnowledgeAssets 导出");
        }
        const cliContent = safeReadCached(cliPath, ctx.readCache);
        const auditCmdContent = safeReadCached(path.join(rootDir, "src", "bin", "commands", "audit.ts"), ctx.readCache) ?? "";
        const combinedCliForKa = (cliContent ?? "") + "\n" + auditCmdContent;
        if (!combinedCliForKa.includes("auditKnowledgeAssets")) {
            hardFail("CRITICAL_PROBLEM_NOT_CONSUMED", "problem-57: auditKnowledgeAssets 未被 soloforge.ts CLI 消费", ["src/bin/soloforge.ts", "src/engine/knowledge/knowledge_asset_audit.ts"], "problem-57", "Knowledge Asset Audit 定义存在但未接入 CLI", "将 auditKnowledgeAssets 接入 audit-template-mechanisms 命令");
        }
        else {
            // 验证 hard_fail 阻断路径
            const cliLines = combinedCliForKa.split("\n");
            const kaCallLine = cliLines.findIndex(l => l.includes("auditKnowledgeAssets") && l.includes("await"));
            if (kaCallLine !== -1) {
                // 搜索到函数末尾（下一个 export async function 或 async function 或文件末尾）
                let kaEnd = cliLines.length;
                for (let i = kaCallLine + 1; i < cliLines.length; i++) {
                    if (cliLines[i].match(/^(export\s+)?(async\s+)?function\s+\w+/)) {
                        kaEnd = i;
                        break;
                    }
                }
                const afterKaCall = cliLines.slice(kaCallLine, kaEnd).join("\n");
                if (!afterKaCall.includes("hard_fail_count") || !afterKaCall.includes("process.exit(1)")) {
                    hardFail("CRITICAL_PROBLEM_SOFT_ENFORCEMENT", "problem-57: auditKnowledgeAssets 调用后 hard_fail 未阻断（缺少 process.exit(1)）", ["src/bin/soloforge.ts"], "problem-57", "知识资产审计 hard_fail 未阻断命令", "添加 hard_fail_count > 0 时 process.exit(1)");
                }
                // 验证异常也阻断（搜索整个函数体中的 catch 块）
                const catchBlocks = afterKaCall.match(/catch\s*\(e[^)]*\)\s*\{[^}]+\}/g);
                const hasKaAudit = afterKaCall.includes("auditKnowledgeAssets");
                if (catchBlocks && hasKaAudit) {
                    for (const cb of catchBlocks) {
                        // 只检查紧跟 auditKnowledgeAssets 的 catch
                        if (cb.includes("process.exit(1)"))
                            continue;
                        // 检查是否是 auditKnowledgeAssets 的 catch（通过位置判断）
                    }
                }
                // 简化: 检查 auditKnowledgeAssets 后面的 catch 块中是否有 process.exit(1)
                const kaCatchIdx = afterKaCall.lastIndexOf("catch");
                if (kaCatchIdx !== -1) {
                    const afterCatch = afterKaCall.slice(kaCatchIdx);
                    if (!afterCatch.includes("process.exit(1)")) {
                        hardFail("CRITICAL_PROBLEM_SOFT_ENFORCEMENT", "problem-57: auditKnowledgeAssets 异常时未阻断（catch 中缺少 process.exit(1)）", ["src/bin/soloforge.ts"], "problem-57", "知识资产审计异常被吞而非阻断", "catch 中添加 process.exit(1)");
                    }
                }
            }
        }
    }
    info?.("  problem-17/38/57 消费验证完成");
    // 问题六十：证据驱动与反幻觉契约 — 行为级检查
    {
        const evidenceGroundingPath = path.join(rootDir, "src/engine/contracts/evidence_grounding_contract.ts");
        if (!fs.existsSync(evidenceGroundingPath)) {
            hardFail("CRITICAL_PROBLEM_FILE_MISSING", "problem-60: evidence_grounding_contract.ts 不存在", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "发布门禁不检查 problem-60 实现", "创建 evidence_grounding_contract.ts");
        }
        else {
            // 行为级检查：动态导入并验证核心门禁行为
            try {
                const eg = await import(path.join(rootDir, "dist", "engine", "contracts", "evidence_grounding_contract.js"));
                const sys = eg.createEvidenceGroundingSystem();
                // 检查 1：无证据高风险 claim 必须被 blocked
                {
                    const noEvClaims = [{
                            id: "gate-test-no-ev", claim_text: "项目使用 React", category: "project_fact",
                            evidence_ids: [], is_uncertain: false, risk_level: "high",
                        }];
                    const noEvResult = sys.verifier.verify(noEvClaims, "high");
                    if (noEvResult.unsupported.length === 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: 无证据高风险 claim 未被 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 未阻断无证据声明", "验证 classify 逻辑");
                    }
                }
                // 检查 2：generated_inference 单独支撑 project_fact 必须被 blocked
                {
                    const infEv = sys.registry.register({
                        source_type: "generated_inference", authority: "weak", freshness: "unknown",
                        permission: "allowed", scope: "test", description: "推理",
                    });
                    const infClaims = [{
                            id: "gate-test-inference", claim_text: "项目使用 Vue", category: "tech_stack",
                            evidence_ids: [infEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const infResult = sys.verifier.verify(infClaims, "high");
                    if (infResult.unsupported.length === 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: generated_inference 单独支撑 project_fact 未被 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 未阻断推理自证", "验证 isSelfAttestation 逻辑");
                    }
                }
                // 检查 3：validation_plan 冒充 validation_result 必须被 blocked
                {
                    const planEv = sys.registry.register({
                        source_type: "generated_inference", authority: "weak", freshness: "unknown",
                        permission: "allowed", scope: "test", description: "验证计划",
                    });
                    const planClaims = [{
                            id: "gate-test-plan-as-result", claim_text: "验证已通过",
                            category: "validation_result",
                            evidence_ids: [planEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const planResult = sys.verifier.verify(planClaims, "high");
                    if (planResult.unsupported.length === 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: validation_plan 冒充 validation_result 未被 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 未阻断验证计划冒充", "验证 validation_result 检查逻辑");
                    }
                }
                // 检查 4：forbidden source 必须被 blocked
                {
                    const matrix = sys.builder.buildContext([], {
                        target_claims: [], source_types: [], keywords: [], max_results: 10,
                    });
                    matrix.evidence.push({
                        id: "ev-forbidden-test", source_type: "project_file",
                        authority: "authoritative", freshness: "current",
                        permission: "forbidden", scope: "sensitive",
                        description: "敏感数据", timestamp: new Date().toISOString(),
                    });
                    matrix.risk_summary = { low: 0, medium: 0, high: 0, critical: 1 };
                    const forbiddenResult = sys.gate.evaluate(matrix, "high");
                    if (forbiddenResult.allowed) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: forbidden source 未被 UnsupportedClaimGate 阻断", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "UnsupportedClaimGate 允许 forbidden 证据通过", "验证 forbidden 检查逻辑");
                    }
                }
                // 检查 5：conflict unresolved 必须被 blocked（高风险）
                {
                    const confMatrix = sys.builder.buildContext([], {
                        target_claims: [], source_types: [], keywords: [], max_results: 10,
                    });
                    confMatrix.conflicts.push({
                        claim_id: "claim-conflict-test",
                        conflicting_evidence_ids: ["ev-a", "ev-b"],
                        description: "矛盾",
                        resolution_status: "unresolved",
                    });
                    confMatrix.risk_summary = { low: 0, medium: 0, high: 1, critical: 0 };
                    const confResult = sys.gate.evaluate(confMatrix, "high");
                    if (confResult.allowed) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: unresolved conflict 未被 UnsupportedClaimGate 阻断", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "UnsupportedClaimGate 允许未裁决冲突通过", "验证 conflict 检查逻辑");
                    }
                }
                // 检查 6：classification-only 证据不得支撑 architecture 声明
                {
                    sys.registry.clear();
                    const clsOnlyEv = sys.registry.register({
                        source_type: "task_context", authority: "authoritative", freshness: "current",
                        permission: "allowed", scope: "classification", description: "任务分类结果",
                    });
                    const clsOnlyClaims = [{
                            id: "gate-test-cls-only", claim_text: "技术方案基于现有系统分析",
                            category: "architecture",
                            evidence_ids: [clsOnlyEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const clsOnlyResult = sys.verifier.verify(clsOnlyClaims, "high");
                    if (clsOnlyResult.unsupported.length === 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: classification-only 证据支撑 architecture 声明未被 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 允许 task_context:classification 支撑项目事实声明", "验证 CATEGORY_REQUIRED_SOURCES 逻辑");
                    }
                }
                // 检查 7：project_file + project_source_file 证据可以支撑 architecture 声明
                {
                    sys.registry.clear();
                    const pfEv = sys.registry.register({
                        source_type: "project_file", evidence_role: "project_source_file",
                        authority: "authoritative", freshness: "current",
                        permission: "allowed", scope: "src/", description: "项目源码文件",
                    });
                    const pfClaims = [{
                            id: "gate-test-pf-ok", claim_text: "技术方案基于现有系统分析",
                            category: "architecture",
                            evidence_ids: [pfEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const pfResult = sys.verifier.verify(pfClaims, "high");
                    if (pfResult.unsupported.length > 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: project_source_file 证据支撑 architecture 声明被错误 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 误阻断了有效证据", "验证 CATEGORY_REQUIRED_ROLES 逻辑");
                    }
                }
                // 检查 8：template_guidance 证据不得支撑 architecture 声明
                {
                    sys.registry.clear();
                    const tgEv = sys.registry.register({
                        source_type: "knowledge_asset", evidence_role: "template_guidance",
                        authority: "trusted", freshness: "current",
                        permission: "allowed", scope: "knowledge", description: "默认模板",
                    });
                    const tgClaims = [{
                            id: "gate-test-tg-block", claim_text: "技术方案基于现有系统分析",
                            category: "architecture",
                            evidence_ids: [tgEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const tgResult = sys.verifier.verify(tgClaims, "high");
                    if (tgResult.unsupported.length === 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: template_guidance 证据支撑 architecture 声明未被 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 允许 template_guidance 支撑项目事实声明", "验证 CATEGORY_REQUIRED_ROLES 逻辑");
                    }
                }
                // 检查 9：project_source_file 证据角色可以支撑 architecture 声明
                {
                    sys.registry.clear();
                    const psfEv = sys.registry.register({
                        source_type: "project_file", evidence_role: "project_source_file",
                        authority: "authoritative", freshness: "current",
                        permission: "allowed", scope: "src/", description: "项目源码文件",
                    });
                    const psfClaims = [{
                            id: "gate-test-psf-ok", claim_text: "技术方案基于现有系统分析",
                            category: "architecture",
                            evidence_ids: [psfEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const psfResult = sys.verifier.verify(psfClaims, "high");
                    if (psfResult.unsupported.length > 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: project_source_file 角色支撑 architecture 声明被错误 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 误阻断了有效 project_source_file 证据", "验证 CATEGORY_REQUIRED_ROLES 逻辑");
                    }
                }
                // 检查 10：普通 code_change 不应因无 project_source_file 被 blocked（无 architecture claim 时）
                {
                    sys.registry.clear();
                    const clsEv = sys.registry.register({
                        source_type: "task_context", evidence_role: "classification",
                        authority: "authoritative", freshness: "current",
                        permission: "allowed", scope: "classification", description: "任务分类结果",
                    });
                    // 普通 code_change 只有 user_confirmation claim（无 architecture claim）
                    const ccClaims = [{
                            id: "gate-test-cc-ok", claim_text: "任务路由和执行范围已确认",
                            category: "user_confirmation",
                            evidence_ids: [clsEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const ccResult = sys.verifier.verify(ccClaims, "high");
                    if (ccResult.unsupported.length > 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: 普通 code_change 的 user_confirmation claim 被 classification 证据错误 blocked", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 误阻断了不需要项目事实的普通任务", "验证 claim 语义逻辑");
                    }
                }
                // 检查 11：architecture_design 无真实项目证据必须 blocked
                {
                    sys.registry.clear();
                    const clsOnlyEv = sys.registry.register({
                        source_type: "task_context", evidence_role: "classification",
                        authority: "authoritative", freshness: "current",
                        permission: "allowed", scope: "classification", description: "任务分类结果",
                    });
                    const tgOnlyEv = sys.registry.register({
                        source_type: "knowledge_asset", evidence_role: "template_guidance",
                        authority: "trusted", freshness: "current",
                        permission: "allowed", scope: "knowledge", description: "默认模板",
                    });
                    const archClaims = [{
                            id: "gate-test-arch-block", claim_text: "技术方案基于现有系统分析",
                            category: "architecture",
                            evidence_ids: [clsOnlyEv.id, tgOnlyEv.id], is_uncertain: false, risk_level: "high",
                        }];
                    const archResult = sys.verifier.verify(archClaims, "high");
                    if (archResult.unsupported.length === 0) {
                        hardFail("CRITICAL_PROBLEM_BEHAVIOR", "problem-60: architecture_design 无真实项目证据未被 blocked（classification + template_guidance 不够）", ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "FactClaimVerifier 允许非项目证据支撑架构声明", "验证 CATEGORY_REQUIRED_ROLES + claim 语义逻辑");
                    }
                }
            }
            catch (behaviorErr) {
                hardFail("CRITICAL_PROBLEM_BEHAVIOR", `problem-60: 行为级检查执行失败: ${errorMessage(behaviorErr)}`, ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "证据驱动机制行为检查不可执行", "修复 import 或机制代码");
            }
        }
        // 静态检查：导出完整性
        const egContent = safeReadCached(evidenceGroundingPath, ctx.readCache);
        if (egContent) {
            const requiredExports = ["createEvidenceGroundingSystem", "assessTaskRisk", "EvidenceSourceRegistry", "FactClaimVerifier", "UnsupportedClaimGate"];
            for (const exp of requiredExports) {
                if (!egContent.includes(exp)) {
                    hardFail("CRITICAL_PROBLEM_EXPORT_MISSING", `problem-60: evidence_grounding_contract.ts 缺少导出: ${exp}`, ["src/engine/contracts/evidence_grounding_contract.ts"], "problem-60", "证据驱动机制缺少核心导出", `添加 ${exp} 导出`);
                }
            }
        }
        // 静态检查：InstructionContract schema 必须包含 evidence 字段
        const instrContractPath = path.join(rootDir, "src/engine/contracts/instruction_contract.ts");
        const instrContent = safeReadCached(instrContractPath, ctx.readCache);
        if (instrContent) {
            const evidenceFields = ["evidence_matrix", "unsupported_claim_policy", "uncertainty_policy", "conflict_resolution_policy"];
            for (const field of evidenceFields) {
                if (!instrContent.includes(field)) {
                    hardFail("CRITICAL_PROBLEM_SCHEMA_INCOMPLETE", `problem-60: instruction_contract.ts schema 缺少证据字段: ${field}`, ["src/engine/contracts/instruction_contract.ts"], "problem-60", "施工指令契约缺少证据驱动字段", `添加 ${field} 字段`);
                }
            }
        }
        // 静态检查：主链路必须有 runtime 阻断（不能只是 advisory）
        const toolsPath = path.join(rootDir, "src/server/tools/index.ts");
        const toolsContent = safeReadCached(toolsPath, ctx.readCache);
        const toolsGroupPaths = [
            "src/server/tools/tool_groups/classify_expand.ts",
            "src/server/tools/tool_groups/verify_learn.ts",
            "src/server/tools/tool_groups/scaffold_accept_deliver.ts",
        ];
        const toolsGroupContent = toolsGroupPaths.map(p => safeReadCached(path.join(rootDir, p), ctx.readCache) ?? "").join("\n");
        const allToolsContent = (toolsContent ?? "") + "\n" + toolsGroupContent;
        if (!allToolsContent.includes("evidence_grounding_contract")) {
            hardFail("CRITICAL_PROBLEM_NOT_CONSUMED", "problem-60: tools.ts 未消费 evidence_grounding_contract", ["src/server/tools/index.ts"], "problem-60", "证据驱动机制未接入主链路", "在 sf_expand/sf_verify/sf_deliver 中接入");
        }
        // sf_expand 必须有 blocked/manual_required 分支
        if (!allToolsContent.includes("_evGate.allowed") && !allToolsContent.includes("evidence_blocked")) {
            hardFail("CRITICAL_PROBLEM_ADVISORY_ONLY", "problem-60: sf_expand 证据检查只有 advisory，缺少 blocked 分支", ["src/server/tools/index.ts"], "problem-60", "sf_expand 证据门禁不阻断", "添加 evidence gate blocked 分支");
        }
        // sf_verify: 验证计划描述行中不得包含 source_type: "validation_result"
        {
            // 找到 sf_verify handler 中问题六十部分
            const verifyStart = allToolsContent.indexOf("问题六十：验证结论必须经过 FactClaimVerifier");
            const verifyEnd = allToolsContent.indexOf("// 验证后核心体验评估", verifyStart);
            if (verifyStart >= 0 && verifyEnd >= 0) {
                const verifySection = allToolsContent.substring(verifyStart, verifyEnd);
                // 检查验证计划注册调用中是否使用了 validation_result
                const planRegMatch = verifySection.match(/register\(\{[^}]*验证计划:[^}]*\}\)/s);
                if (planRegMatch && planRegMatch[0].includes("source_type: \"validation_result\"")) {
                    hardFail("CRITICAL_PROBLEM_PLAN_AS_RESULT", "problem-60: sf_verify 把验证计划注册为 validation_result", ["src/server/tools/index.ts"], "problem-60", "验证计划冒充验证结果", "验证计划应注册为 task_context 类型");
                }
            }
        }
        // 静态检查：负向测试
        const testPath = path.join(rootDir, "tests/engine/evidence_grounding_contract.test.ts");
        if (!fs.existsSync(testPath)) {
            hardFail("CRITICAL_PROBLEM_TEST_MISSING", "problem-60: 缺少负向测试文件", ["tests/engine/evidence_grounding_contract.test.ts"], "problem-60", "证据驱动机制缺少测试覆盖", "创建 evidence_grounding_contract.test.ts");
        }
        // 静态检查：知识规则
        const kaRulePath = path.join(rootDir, "templates/internal/rules/证据驱动与反幻觉规则.md");
        if (!fs.existsSync(kaRulePath)) {
            hardFail("CRITICAL_PROBLEM_ASSET_MISSING", "problem-60: 缺少知识规则文件 证据驱动与反幻觉规则.md", ["templates/internal/rules/证据驱动与反幻觉规则.md"], "problem-60", "证据驱动知识规则缺失", "创建知识规则文件");
        }
        // 静态检查：workflow_template 或 workflow_rule_generator（规则已提取至 engine 层）
        const wfPath = path.join(rootDir, "src/adapters/shared/workflow_template.ts");
        const wrgPath = path.join(rootDir, "src/engine/templates/workflow_rule_generator.ts");
        const wfContent = (safeReadCached(wfPath, ctx.readCache) ?? "") + (safeReadCached(wrgPath, ctx.readCache) ?? "");
        if (!wfContent.includes("wf-evidence-grounding")) {
            hardFail("CRITICAL_PROBLEM_TEMPLATE_MISSING", "problem-60: workflow_template.ts 缺少 wf-evidence-grounding 硬规则", ["src/adapters/shared/workflow_template.ts"], "problem-60", "工作流模板未包含证据驱动规则", "添加 wf-evidence-grounding 硬规则");
        }
        // 静态检查：TaskContext 类型必须有证据字段
        const typesPath = path.join(rootDir, "src/types/task.ts");
        const typesContent = safeReadCached(typesPath, ctx.readCache);
        if (typesContent && !typesContent.includes("evidence_matrix?:") && !typesContent.includes("evidence_gate_result?:")) {
            hardFail("CRITICAL_PROBLEM_TASKCTX_MISSING", "problem-60: TaskContext 缺少 evidence_matrix/evidence_gate_result 字段", ["src/types/task.ts"], "problem-60", "TaskContext 未保存证据结果", "添加 evidence_matrix 和 evidence_gate_result 字段");
        }
        // 静态检查：task_context.ts 必须有 setEvidenceGroundingResult 写入方法
        if (!sourceContainsIdentifier(tcSources, "setEvidenceGroundingResult")) {
            hardFail("CRITICAL_PROBLEM_NO_WRITEBACK", "problem-60: task_context.ts 缺少 setEvidenceGroundingResult 写入方法", ["src/engine/pipeline/task_context.ts"], "problem-60", "TaskContext 只有类型字段没有写入方法", "添加 setEvidenceGroundingResult 方法");
        }
        // 静态检查：tools.ts 主链路必须调用 setEvidenceGroundingResult
        if (!allToolsContent.includes("setEvidenceGroundingResult")) {
            hardFail("CRITICAL_PROBLEM_NO_RUNTIME_WRITEBACK", "problem-60: tools.ts 未调用 setEvidenceGroundingResult 写回 TaskContext", ["src/server/tools/index.ts"], "problem-60", "主链路不写回证据结果到 TaskContext", "在 sf_expand/sf_verify/sf_deliver 中调用 setEvidenceGroundingResult");
        }
        // 静态检查：tools.ts 不得出现 registry.query({}).map() 无差别证据绑定
        {
            const toolsLines = allToolsContent.split("\n");
            for (let i = 0; i < toolsLines.length; i++) {
                if (/registry\.query\(\{\}\)\.map/.test(toolsLines[i])) {
                    hardFail("CRITICAL_PROBLEM_INDISCRIMINATE_BINDING", `problem-60: tools.ts:${i + 1} 使用 registry.query({}).map() 无差别绑定证据到所有 claim`, ["src/server/tools/index.ts"], "problem-60", "所有 registry 证据被无差别绑定到所有 claim，不区分语义", "按 claim 语义筛选 evidence_ids");
                }
            }
        }
        // 行为检查：setEvidenceGroundingResult 写入后 load 能读回
        try {
            const tcModule = await import(path.join(rootDir, "dist", "engine", "pipeline", "task_context.js"));
            const tmpStateDir = path.join(rootDir, ".soloforge", "state");
            const fsModule = await import("node:fs");
            if (!fsModule.existsSync(tmpStateDir)) {
                fsModule.mkdirSync(tmpStateDir, { recursive: true });
            }
            const tmpMgr = new tcModule.TaskContextManager(tmpStateDir);
            const tmpCtx = await tmpMgr.create("gate-evidence-writeback-test", "test");
            const testMatrix = {
                task_id: tmpCtx.task_id, claims: [], evidence: [],
                conflicts: [], unsupported_claims: ["test-claim"],
                risk_summary: { low: 0, medium: 0, high: 1, critical: 0 },
                created_at: new Date().toISOString(),
            };
            const testGate = {
                allowed: false, reason_zh: "测试", diagnostic_code: "SF-EVIDENCE-TEST",
                unsupported_claims: ["test-claim"], unresolved_conflicts: [],
                missing_evidence: [], risk_level: "high",
                requires_user_confirmation: [],
            };
            await tmpMgr.setEvidenceGroundingResult(tmpCtx.task_id, {
                evidence_matrix: testMatrix,
                evidence_gate_result: testGate,
                unsupported_claims: ["test-claim"],
            });
            const loaded = await tmpMgr.load(tmpCtx.task_id);
            if (!loaded?.evidence_matrix || !loaded?.evidence_gate_result) {
                hardFail("CRITICAL_PROBLEM_WRITEBACK_FAILED", "problem-60: setEvidenceGroundingResult 写入后 load 无法读回", ["src/engine/pipeline/task_context.ts"], "problem-60", "TaskContext 写入方法不工作", "修复 setEvidenceGroundingResult 或 save/load");
            }
            if (loaded.evidence_gate_result?.allowed !== false) {
                hardFail("CRITICAL_PROBLEM_WRITEBACK_CORRUPT", "problem-60: setEvidenceGroundingResult 写入的 gate result 数据损坏", ["src/engine/pipeline/task_context.ts"], "problem-60", "写入的 allowed=false 被读回为 true", "检查序列化逻辑");
            }
            // 清理测试任务
            try {
                fsModule.rmSync(path.join(tmpStateDir, `${tmpCtx.task_id}.json`), { force: true });
            }
            catch { }
        }
        catch (wbErr) {
            hardFail("CRITICAL_PROBLEM_WRITEBACK_ERROR", `problem-60: setEvidenceGroundingResult 行为检查失败: ${errorMessage(wbErr)}`, ["src/engine/pipeline/task_context.ts"], "problem-60", "TaskContext 写入方法不可用", "修复 import 或方法实现");
        }
    }
    info?.("  problem-60 证据驱动消费验证完成");
}
//# sourceMappingURL=checkCriticalProblemConsumption.js.map