/**
 * intent_expander — 主 expand() 函数。
 *
 * 编排完整的意图膨胀管线，委托给
 * 门控阶段 (privacy_gates.ts)、知识解析
 * (knowledge_resolution.ts)、prompt 渲染 (templates.ts)、
 * 范围/验收 (scope_acceptance.ts) 和熔断器
 * (uncertainty_circuit.ts)。
 */
import { debugLog } from "../../core/logger.js";
import { selectPromptTemplate } from "../intent_router.js";
import { createExpandRoutePhasePolicy } from "../expand_pipeline.js";
import { detectConventions } from "../../convention_detector.js";
import { selectAnalysisLevel, analyzeExistingSystem } from "../../contracts/existing_system_analyzer.js";
import { getTaskLevel, getRequiredPrinciples, getEnforcementLevel, listCorePrinciples } from "../../audit/core_engineering_principles.js";
import { validateTechnologyDecision } from "../../contracts/technology_decision.js";
import { validateBrainstormSession } from "../../contracts/brainstorm_contract.js";
import { chooseTemplate } from "./templates.js";
import { CONFIDENCE_THRESHOLD } from "./uncertainty_circuit.js";
import { renderPromptInjectionPlan, buildBlockedResult, resolveClarificationAnswers, getExpandContractTools, buildCheckedItems, getAffectedRepos, buildTechStackLabel, } from "./helpers.js";
import { resolveScope, generateAcceptance, buildExecutionContract, buildTemplateData, injectPlanContext, } from "./scope_acceptance.js";
import { buildUncertaintyTriggers, checkCircuitBreaker, } from "./uncertainty_circuit.js";
import { resolveConfigWarnings, runPrivacyGate, createOutputArtifactRecord, resolveWorkflowContract, resolveInputMaterials, checkPrivacyHardGate, } from "./privacy_gates.js";
import { resolveKnowledge, resolveDualLayerMechanisms, } from "./knowledge_resolution.js";
/**
 * 将分类结果扩展为完整的 AI 执行 prompt 和配套元数据。
 */
export async function expand(input) {
    debugLog("意图膨胀: 开始扩展，路由=%s", input.route_decision?.route ?? input.classification?.task_type ?? "unknown");
    const { intent, classification, projectPath, config, knowledgeIndex } = input;
    let routeDecision = input.route_decision ?? classification.route_decision;
    const templateName = routeDecision ? selectPromptTemplate(routeDecision) : "code_execution_prompt";
    const phasePolicy = createExpandRoutePhasePolicy(routeDecision);
    const skipWorkflowContractStrict = phasePolicy.skip_workflow_contract_strict;
    const skipInputMaterialHardBlock = phasePolicy.skip_input_material_hard_block;
    const skipProjectKnowledgeHardBlock = phasePolicy.skip_project_knowledge_hard_block;
    const skipHeavyContractGates = phasePolicy.skip_heavy_contract_gates;
    const skipPreImplementationGates = phasePolicy.skip_pre_implementation_gates;
    const skipHeavyAnalysis = classification.strategy === "quick_fix";
    // ── 配置警告 ──
    const { warnings: configWarnings, configResolution } = await resolveConfigWarnings(projectPath);
    // ── 澄清回答 ──
    if (input.clarificationAnswers && input.clarificationAnswers.length > 0 && routeDecision) {
        routeDecision = resolveClarificationAnswers(routeDecision, intent, input.clarificationAnswers);
    }
    // ── 隐私门控 ──
    const { safeIntent, safeGoal, privacyGate } = runPrivacyGate(intent, phasePolicy, input);
    // ── 输出产物记录 ──
    const artifactResult = createOutputArtifactRecord(input, routeDecision, safeIntent, safeGoal);
    if (artifactResult.blockedResult)
        return artifactResult.blockedResult;
    const outputArtifactRecord = artifactResult.outputArtifactRecord;
    // ── 工作流合同 ──
    const wfResult = resolveWorkflowContract(routeDecision, input, safeIntent, safeGoal, skipWorkflowContractStrict, outputArtifactRecord);
    if (wfResult.blockedResult)
        return wfResult.blockedResult;
    const workflowContract = wfResult.workflowContract;
    const workflowGovernanceFindings = wfResult.workflowGovernanceFindings;
    // prompt_template 一致性检查（需要来自 selectPromptTemplate 的 templateName）
    if (routeDecision && !skipWorkflowContractStrict && workflowContract && workflowContract.prompt_template !== templateName) {
        return buildBlockedResult(`## 阻塞：prompt_template 不一致\n\n任务: ${safeIntent}\n\n工作流 "${workflowContract.id}" 要求 prompt_template="${workflowContract.prompt_template}"，但 selectPromptTemplate 返回 "${templateName}"。`, safeGoal, {
            constraints: ["prompt_template 不一致"], stopConditions: ["prompt_template 不一致"],
            workflowTrace: {
                workflow_id: workflowContract.id, route: routeDecision.route,
                execution_shape: routeDecision.execution_shape, mutation_allowed: workflowContract.mutation_allowed,
                required_mechanisms: workflowContract.required_mechanisms,
                governance_findings: [{ severity: "hard_fail", rule: "gc-prompt-template-mismatch", message: `prompt_template mismatch: workflow="${workflowContract.prompt_template}" selected="${templateName}"` }],
                degraded: true, state_transition_target: "none",
            },
        });
    }
    // ── 缺少必需输入 ──
    if (routeDecision && routeDecision.missing_required_inputs.length > 0) {
        debugLog("意图膨胀: 缺少必需输入 %d 项，返回澄清请求", routeDecision.missing_required_inputs.length);
        const { buildClarificationResult } = await import("./helpers.js");
        return buildClarificationResult(intent, routeDecision, config, workflowContract, safeIntent, safeGoal);
    }
    // ── 输入材料 ──
    const matResult = resolveInputMaterials(routeDecision, input, safeIntent, safeGoal, skipInputMaterialHardBlock, workflowContract, projectPath);
    if (matResult.blockedResult)
        return matResult.blockedResult;
    const { inputMaterials, ingestionEvidences, promptInjectionPlan, contractNotes } = matResult;
    // ── 隐私硬门控 ──
    const privResult = checkPrivacyHardGate(privacyGate, safeGoal, inputMaterials, ingestionEvidences, promptInjectionPlan, outputArtifactRecord, workflowContract, routeDecision);
    if (privResult.blockedResult)
        return privResult.blockedResult;
    const privacyLabels = privResult.labels;
    const privacyRedactions = privResult.redactions;
    const privacyFindings = privResult.findings;
    // ── 知识解析 ──
    const knowResult = await resolveKnowledge(projectPath, intent, classification, config, knowledgeIndex, routeDecision, skipProjectKnowledgeHardBlock, safeIntent, safeGoal, workflowContract, inputMaterials, ingestionEvidences, promptInjectionPlan, outputArtifactRecord, workflowGovernanceFindings, input.task_stage);
    if (knowResult.blockedResult)
        return knowResult.blockedResult;
    const { projectKnowledgeReport, projectKnowledgeFindings, projectKnowledgeSelection, selectedProjectKnowledge, filteredEntries, injectionReport, degraded, } = knowResult;
    // ── 遗留惯例检测（仅 code_execution） ──
    const affectedRepos = getAffectedRepos(classification);
    const legacyConventions = [];
    let isLegacyCode = false;
    if (templateName === "code_execution_prompt" && !skipHeavyAnalysis && !degraded && affectedRepos.length > 0) {
        try {
            const repoDirs = affectedRepos
                .map((r) => config.repos.find((repo) => repo.name === r)?.path)
                .filter(Boolean);
            const conventions = await detectConventions(repoDirs.map((d) => `${d}/src`).slice(0, 3), projectPath, config.conventions_file);
            if (conventions.length > 0) {
                isLegacyCode = true;
                legacyConventions.push(...conventions.map((c) => c.convention));
            }
        }
        catch (e) {
            debugLog("意图扩展: 惯例检测失败 —", e);
        }
    }
    // ── 范围、验收、prompt 组装 ──
    const scope = resolveScope(config, classification, degraded, routeDecision);
    const acceptance = generateAcceptance(intent, classification, filteredEntries, config, degraded, routeDecision);
    const techStack = buildTechStackLabel(config);
    const template = chooseTemplate(templateName);
    const templateData = buildTemplateData(safeIntent, techStack, config, classification, scope, filteredEntries, legacyConventions, isLegacyCode, acceptance, degraded, routeDecision, injectionReport);
    if (promptInjectionPlan)
        templateData.prompt_injection_plan = promptInjectionPlan;
    // ── 双层机制注入 ──
    const { dlRules } = resolveDualLayerMechanisms(routeDecision, workflowContract);
    if (dlRules.length > 0) {
        templateData.dual_layer_rules = dlRules;
        const existing = templateData.matched_knowledge;
        if (existing) {
            existing.push({ name: "强制机制规则（双层注入）", content: dlRules.join("\n\n") });
        }
    }
    let prompt = template(templateData);
    debugLog("意图膨胀: Prompt 模板渲染完成，模板=%s", templateName);
    // ── R8: gap_analysis 系统分析注入 ──
    if (templateName === "gap_analysis_prompt" && projectPath) {
        try {
            const level = selectAnalysisLevel(projectPath);
            const analysisResult = analyzeExistingSystem(projectPath, level);
            const summaryLines = [`\n## 自动化现有系统分析结果 (分析等级: ${level})`];
            if (analysisResult.level === "L1") {
                summaryLines.push(`- 项目路径: ${analysisResult.project_path}`);
                summaryLines.push(`- 源文件数: ${analysisResult.source_file_count}`);
                summaryLines.push(`- 技术栈: ${analysisResult.tech_stack.map(t => t.name).join(", ") || "未检测到"}`);
                summaryLines.push(`- 目录: ${analysisResult.directories.slice(0, 20).join(", ")}`);
            }
            else if (analysisResult.level === "L2") {
                summaryLines.push(`- 模块数: ${analysisResult.modules.length}`);
                summaryLines.push(`- 依赖边数: ${analysisResult.dependency_graph.length}`);
            }
            else if (analysisResult.level === "L3") {
                summaryLines.push(`- 数据模型数: ${analysisResult.data_models.length}`);
                summaryLines.push(`- API 调用链数: ${analysisResult.api_call_chains.length}`);
            }
            prompt += summaryLines.join("\n") + "\n";
        }
        catch (e) {
            debugLog("意图膨胀: 现有系统分析注入失败 —", e);
        }
    }
    if (input.plan_context)
        prompt = injectPlanContext(prompt, input.plan_context, knowledgeIndex);
    const contract = buildExecutionContract(safeIntent, classification, scope, acceptance, routeDecision);
    const uncertaintyTriggers = skipHeavyAnalysis ? [] : buildUncertaintyTriggers(classification, intent);
    // ── 熔断器 ──
    const breakerResult = skipPreImplementationGates ? { tripped: false, confidence: 1.0 } : checkCircuitBreaker({ intent, classification, matchedEntries: filteredEntries, degraded });
    let circuitBreakerOutput;
    if (breakerResult.tripped) {
        circuitBreakerOutput = breakerResult;
        const bs = breakerResult.brainstorm;
        if (bs) {
            prompt += `\n\n---\n## ⚠ 意图熔断触发（置信度: ${breakerResult.confidence.toFixed(2)}）\n当前需求理解置信度低于 ${CONFIDENCE_THRESHOLD}，以下为分析辅助:\n\n### 【逻辑盲区】\n${bs.blind_spots.map((s) => `- ${s}`).join("\n")}\n\n### 【三轨演进】\n- **极简验证路径**: ${bs.evolution_tracks.minimal}\n- **工业级标准路径**: ${bs.evolution_tracks.industrial}\n- **激进重构路径**: ${bs.evolution_tracks.radical}\n\n### 【闭环逼问】\n${bs.decision_questions.map((q, i) => `${i + 1}. ${q.question}\n   A) ${q.option_a}\n   B) ${q.option_b}`).join("\n\n")}\n\n**注意**: ${routeDecision?.execution_shape === "code_execution" ? "请等待人类决策后再输出执行代码。" : "请先补齐阻塞输入，或在产物中标记 [Manual Confirm] 后再生成产物。"}\n`;
        }
    }
    // ── 技术选型决策校验 ──
    let techDecisionRequiresManual = false;
    if (!skipHeavyContractGates && routeDecision?.execution_shape === "code_execution" && classification.complexity === "high") {
        const decisionContract = {
            decision_id: `td-${input.task_id ?? "unknown"}`, decision_scope: "architecture",
            options: [], recommended_option: "", rejected_options: [], evidence: [], falsification: [],
            failure_conditions: [], validation_plan: [], rollback_or_exit_plan: [],
            human_gate_required: true, human_gate_reason: "高复杂度架构变更需要人工确认", executable_without_human: false,
        };
        const decisionResult = validateTechnologyDecision(decisionContract);
        if (!decisionResult.valid) {
            for (const violation of decisionResult.violations) {
                workflowGovernanceFindings.push({ severity: "hard_fail", rule: "technology_decision_human_gate", message: `技术决策校验: ${violation}` });
            }
            techDecisionRequiresManual = true;
            prompt += `\n\n---\n\n## ⚠ 技术决策校验\n技术决策校验: 需要人工确认 (${decisionResult.violations.join(", ")})\n> 高复杂度架构变更需要人工确认后方可执行。`;
        }
        else {
            workflowGovernanceFindings.push({ severity: "info", rule: "technology_decision_human_gate", message: "技术决策校验通过: 已确认 human gate 合规" });
        }
    }
    // ── 脑暴完整性校验 ──
    let brainstormRequiresClarification = false;
    if (!skipHeavyContractGates && (input.brainstorm_session || circuitBreakerOutput?.brainstorm)) {
        let session;
        if (input.brainstorm_session) {
            session = input.brainstorm_session;
        }
        else {
            const bs = circuitBreakerOutput?.brainstorm;
            if (bs) {
                session = {
                    session_id: `bs-${input.task_id ?? "unknown"}`, trigger: "ambiguous_goal",
                    problem_statement: input.intent,
                    options: bs.decision_questions.map((q, i) => ({
                        option_id: `opt-${i}`, title: q.question, description: `${q.option_a} vs ${q.option_b}`,
                        pros: [q.option_a], cons: [q.option_b], applicable_when: [], not_applicable_when: [],
                        failure_conditions: [`选择 ${q.option_a} 失败的条件: ${q.option_a} 的局限性场景`, `选择 ${q.option_b} 失败的条件: ${q.option_b} 的局限性场景`],
                        verification_method: [], estimated_risk: "medium", reversibility: "partially_reversible", required_human_decisions: [],
                    })),
                    recommended_option_id: "opt-0", rejected_option_ids: [], human_gate_required: true, evidence_refs: [], brainstorm_status: "options_ready",
                };
            }
        }
        if (session) {
            const brainstormResult = validateBrainstormSession(session);
            if (!brainstormResult.valid) {
                for (const violation of brainstormResult.violations) {
                    workflowGovernanceFindings.push({ severity: "hard_fail", rule: "brainstorm_completeness", message: `脑暴完整性校验: ${violation}` });
                }
                brainstormRequiresClarification = true;
                prompt += `\n\n---\n\n## ⚠ 脑暴完整性校验\n脑暴校验: ${brainstormResult.violations.join(", ")}`;
            }
            else {
                workflowGovernanceFindings.push({ severity: "info", rule: "brainstorm_completeness", message: "脑暴完整性校验通过: 候选方案已就绪" });
            }
        }
    }
    // ── 最终 prompt 增强 ──
    const expandTools = getExpandContractTools();
    if (contractNotes.length > 0)
        prompt += "\n\n---\n\n## 输入材料契约检查\n" + contractNotes.join("\n");
    if (configWarnings.length > 0)
        prompt += "\n\n---\n\n## 配置优先级警告\n" + configWarnings.join("\n");
    if (selectedProjectKnowledge.length > 0) {
        const projectRuleLines = projectKnowledgeSelection.selected.map((decision) => `- ${decision.asset.name} (${decision.asset.rel_path}, ${decision.enforcement}, ${decision.asset.identity})\n  选中原因: ${decision.reason_zh}\n  复验命令: ${decision.user_visible.verification_command ?? "soloforge audit-project-knowledge"}`);
        prompt += "\n\n---\n\n## 用户项目规则\n" + projectRuleLines.join("\n");
        prompt += "\n> 以上规则来自当前项目 .soloforge/knowledge。hard_rule 必须满足；injectable 用于当前任务执行；audit_only/index_only 不进入 prompt 注入。";
    }
    const coreTaskLevel = getTaskLevel(routeDecision?.route, routeDecision?.execution_shape);
    const coreRequiredPrinciples = getRequiredPrinciples(coreTaskLevel);
    if (coreRequiredPrinciples.length > 0) {
        const principleLines = listCorePrinciples()
            .filter((p) => getEnforcementLevel(p.id, coreTaskLevel) !== "not_applicable")
            .map((p) => `- **${getEnforcementLevel(p.id, coreTaskLevel) === "required" ? "[REQUIRED]" : "[advisory]"} ${p.name} (${p.chinese_name})**: ${p.rule}`);
        prompt += "\n\n---\n\n## 核心工程执行原则 (任务等级: " + coreTaskLevel + ")\n" + principleLines.join("\n");
        prompt += "\n\n> 以上原则中 [REQUIRED] 为硬性要求，违反将导致验证失败。[advisory] 为建议性要求。";
    }
    if (promptInjectionPlan) {
        const rendered = renderPromptInjectionPlan(promptInjectionPlan);
        if (rendered)
            prompt += "\n\n" + rendered;
    }
    // ── 丰富产物记录 ──
    if (outputArtifactRecord) {
        outputArtifactRecord.knowledge_refs = filteredEntries.map((e) => e.id);
        if (ingestionEvidences && ingestionEvidences.length > 0) {
            outputArtifactRecord.evidence_refs = ingestionEvidences
                .filter((ie) => ie.access_mode !== "forbidden")
                .map((ie) => `ingestion:${ie.material_id}:${ie.source_ref}`);
        }
        if (workflowContract)
            outputArtifactRecord.workflow_id = workflowContract.id;
    }
    debugLog("意图膨胀: 扩展完成，degraded=%s, 匹配知识=%d 条", degraded ? "true" : "false", filteredEntries.length);
    return {
        task_id: "", prompt, scope, scope_resolution: scope.resolution, acceptance,
        matched_patterns: filteredEntries.map((e) => e.name), matched_knowledge: filteredEntries.map((e) => e.name),
        injection_report: injectionReport,
        project_knowledge: {
            total: projectKnowledgeReport.total, hard_fail_count: projectKnowledgeReport.hard_fail_count,
            warning_count: projectKnowledgeReport.warning_count,
            selected: selectedProjectKnowledge.map((asset) => ({ id: asset.id, name: asset.name, rel_path: asset.rel_path, consumption: asset.consumption, identity: asset.identity })),
            selection_decisions: projectKnowledgeSelection.decisions.map((decision) => ({
                id: decision.asset.id, name: decision.asset.name, rel_path: decision.asset.rel_path,
                status: decision.status, enforcement: decision.enforcement, reason_zh: decision.reason_zh,
                matched_signals: decision.matched_signals, excluded_reasons: decision.excluded_reasons,
                verification_command: decision.user_visible.verification_command,
            })),
            findings: projectKnowledgeFindings,
        },
        is_legacy_code: isLegacyCode,
        legacy_conventions: legacyConventions.length > 0 ? legacyConventions : undefined,
        degraded, contract,
        uncertainty_triggers: uncertaintyTriggers.length > 0 ? uncertaintyTriggers : undefined,
        circuit_breaker: circuitBreakerOutput,
        next_allowed_tools: expandTools.next_allowed_tools, forbidden_tools: expandTools.forbidden_tools,
        input_materials: inputMaterials, ingestion_evidences: ingestionEvidences,
        prompt_injection_plan: promptInjectionPlan, output_artifact_record: outputArtifactRecord,
        sensitivity_labels: privacyLabels.length > 0 ? privacyLabels : undefined,
        redaction_records: privacyRedactions.length > 0 ? privacyRedactions : undefined,
        privacy_findings: privacyFindings.length > 0 ? privacyFindings : undefined,
        config_resolution_reports: configResolution.reports.length > 0 ? configResolution.reports : undefined,
        workflow_trace: workflowContract ? {
            workflow_id: workflowContract.id, route: routeDecision?.route ?? "",
            execution_shape: routeDecision?.execution_shape ?? "",
            mutation_allowed: workflowContract.mutation_allowed,
            required_mechanisms: workflowContract.required_mechanisms,
            governance_findings: workflowGovernanceFindings, degraded,
            state_transition_target: techDecisionRequiresManual || brainstormRequiresClarification
                ? "manual_required" : (workflowContract.allowed_state_transitions[0] ?? "none"),
            checked_items: buildCheckedItems(workflowContract, routeDecision),
        } : undefined,
    };
}
//# sourceMappingURL=expand.js.map