/**
 * intent_expander — scope resolution, acceptance generation,
 * template data building, and execution contract helpers.
 */
import { resolveTaskScope } from "../scope_resolver.js";
import { getAffectedRepos, matchesOutputTemplate } from "./helpers.js";
/**
 * 解析 scope: 非代码任务使用简化 scope。
 */
export function resolveScope(config, classification, degraded, routeDecision) {
    return resolveTaskScope({
        projectPath: config._projectPath ?? process.cwd(),
        config,
        classification,
        degraded,
        routeDecision,
    });
}
/**
 * 生成验收标准: 根据执行形态选择不同验收。
 */
export function generateAcceptance(_intent, classification, matchedEntries, _config, degraded, routeDecision) {
    const automated = [];
    const manual = [];
    // 非代码任务: 产物验收而非编译/测试
    if (routeDecision && routeDecision.execution_shape !== "code_execution") {
        if (routeDecision.output_artifact?.path) {
            automated.push({
                id: "A-artifact-exists",
                description: `产物文件已生成: ${routeDecision.output_artifact.path}`,
                type: "automated",
            });
        }
        automated.push({
            id: "A-completeness",
            description: "产物结构完整，无空白占位",
            type: "automated",
        });
        manual.push({
            id: "M-quality",
            description: "产物质量满足可交接标准",
            type: "manual",
        });
        // 从知识中解析验收项
        for (const entry of matchedEntries) {
            if (entry.body) {
                const items = parseAcceptanceItems(entry.body);
                automated.push(...items);
            }
        }
        return { automated, manual };
    }
    // 代码修改任务: 原有逻辑
    if (degraded) {
        automated.push({
            id: "A-build",
            description: "编译通过，无类型错误",
            type: "automated",
        });
        automated.push({
            id: "A-test",
            description: "测试通过",
            type: "automated",
        });
        return { automated, manual };
    }
    automated.push({
        id: "A-build",
        description: "编译通过，无类型错误",
        type: "automated",
    });
    for (const entry of matchedEntries) {
        if (entry.body) {
            const items = parseAcceptanceItems(entry.body);
            automated.push(...items);
        }
    }
    if (classification.task_type === "feature") {
        manual.push({
            id: "M-ux",
            description: "新增功能的交互是否符合设计规范",
            type: "manual",
        });
    }
    if (classification.task_type === "bugfix") {
        manual.push({
            id: "M-root",
            description: "修复是否针对了根本原因而非症状",
            type: "manual",
        });
    }
    return { automated, manual };
}
export function parseAcceptanceItems(body) {
    const items = [];
    if (!body.includes("## 验收项"))
        return items;
    const lines = body.split("\n");
    let inSection = false;
    for (const line of lines) {
        if (line.startsWith("## 验收项")) {
            inSection = true;
            continue;
        }
        if (inSection && line.startsWith("## "))
            break;
        if (inSection) {
            const match = line.match(/- \[([A-Z]+-\d+)\]\s*(.+?)(?:\s*\(check:\s*(.+)\))?$/);
            if (match) {
                const item = { id: match[1], description: match[2].trim(), type: "automated" };
                if (match[3])
                    item.check_command = match[3].trim();
                items.push(item);
            }
        }
    }
    return items;
}
// ── 能力 1: 执行契约 ──
export function buildExecutionContract(intent, classification, scope, acceptance, routeDecision) {
    const constraints = [];
    const stopConditions = [];
    // 路由级约束优先（如 no_mutation）
    if (routeDecision?.constraints?.length) {
        constraints.push(...routeDecision.constraints);
    }
    if (classification.risk === "high") {
        constraints.push("高风险任务：每个变更文件必须有明确来源（任务卡/缺陷/设计锚点）");
        constraints.push("禁止顺手重构或范围外变更");
        constraints.push("修复循环上限 3 轮，超过必须升级");
        stopConditions.push("修复循环超过 3 轮");
        stopConditions.push("变更文件超出 scope.allowed_paths 范围");
    }
    else if (classification.risk === "medium") {
        constraints.push("中等风险：核心逻辑变更需有回归测试");
        stopConditions.push("编译失败 2 次以上");
    }
    else {
        constraints.push("低风险：标准变更流程");
    }
    if (classification.complexity === "high") {
        constraints.push("高复杂度：必须先定位根因再编码，禁止试错");
        constraints.push("一次只修一个问题，禁止跨层大重构");
    }
    return {
        goal: intent.slice(0, 200),
        scope: scope.allowed_paths,
        constraints,
        verification: acceptance.automated.map((a) => `[${a.id}] ${a.description}`),
        stop_conditions: stopConditions,
    };
}
/**
 * 根据执行形态构建模板数据。
 */
export function buildTemplateData(intent, techStack, config, classification, scope, matchedEntries, legacyConventions, isLegacyCode, acceptance, degraded, routeDecision, injectionReport) {
    const base = {
        intent,
        tech_stack: techStack,
        product_profile: config.product_profile,
        affected_repos: getAffectedRepos(classification).join(", "),
        matched_knowledge: matchedEntries.map((e) => ({
            name: e.name,
            content: e.body || e.when,
        })),
        relevant_files: scope.allowed_paths.slice(0, 10).map((p) => ({ path: p, reason: "scope 允许路径" })),
        is_legacy_code: isLegacyCode,
        legacy_conventions: legacyConventions,
        scope: {
            allowed_paths: scope.allowed_paths.join(", "),
            new_files_allowed: scope.new_files_allowed,
            new_file_patterns: scope.new_file_patterns?.join(", "),
        },
        acceptance,
        degraded,
    };
    if (routeDecision) {
        base.output_artifact = routeDecision.output_artifact;
        base.input_materials = routeDecision.input_materials;
        // 根据 ingestion_status 构建 input_material_contract_notes
        const contractTemplateNotes = [];
        for (const m of routeDecision.input_materials) {
            if (m.ingestion_status === "forbidden")
                contractTemplateNotes.push("FORBIDDEN: " + (m.path ?? "") + " 禁止读取");
            else if (m.ingestion_status === "requires_confirmation")
                contractTemplateNotes.push("REQUIRES_CONFIRMATION: " + (m.path ?? "") + " 需确认");
        }
        base.input_material_contract_notes = contractTemplateNotes.length > 0 ? contractTemplateNotes : undefined;
        base.pipeline_hint = routeDecision.pipeline_hint;
    }
    // ── 产物 Schema / ProcessRules 独立注入 ──
    if (injectionReport?.artifact_schema_injection) {
        base.artifact_schema = injectionReport.artifact_schema_injection.schema_text || undefined;
        base.process_rules = injectionReport.artifact_schema_injection.process_rules_text || undefined;
    }
    return base;
}
/**
 * 注入计划阶段上下文（P2 + P3）
 */
export function injectPlanContext(prompt, planContext, knowledgeIndex) {
    const { current_step, previous_outputs } = planContext;
    const sections = [];
    const prevEntries = Object.entries(previous_outputs);
    if (prevEntries.length > 0) {
        sections.push("## 前序阶段产出");
        for (const [stepId, content] of prevEntries) {
            if (content) {
                sections.push(`### ${stepId}\n${content.slice(0, 3000)}`);
            }
        }
    }
    if (current_step.output_template) {
        const templateEntries = knowledgeIndex.query({
            type: "acceptance_template",
            keywords: [],
        });
        const matched = templateEntries.find((e) => matchesOutputTemplate(e, current_step.output_template));
        if (matched?.body) {
            sections.push(`## 输出格式参考（模板: ${current_step.output_template}）\n${matched.body}`);
        }
    }
    if (current_step.output_path) {
        sections.push(`## 产出保存\n将本阶段产出写入: ${current_step.output_path}`);
    }
    if (current_step.suggested_tools && current_step.suggested_tools.length > 0) {
        sections.push(`## 建议工具（可选）\n${current_step.suggested_tools.map((t) => `- ${t}`).join("\n")}`);
    }
    if (sections.length === 0)
        return prompt;
    return `${prompt}\n\n---\n\n## 当前计划阶段\n正在执行: **${current_step.title}**\n${current_step.description}\n\n${sections.join("\n\n")}`;
}
//# sourceMappingURL=scope_acceptance.js.map