import { generateWorkflowRules } from "../shared/workflow_template.js";
import { recordConsumptionTrace, CONSUMER_FIELD_CONTRACTS } from "../../engine/templates/consumption_trace_store.js";
import { listConsumableAssetsByConsumer } from "../../engine/templates/consumable_asset_registry.js";
import { getContractByPath } from "../../engine/templates/template_asset_contract_registry.js";
import { debug } from "../../engine/core/logger.js";
/** 计算章节内容 hash: 字符数:行数:首尾字符码 */
function computeSectionHash(text, sectionHeader) {
    const idx = text.indexOf(sectionHeader);
    if (idx === -1)
        return "missing";
    const nextSection = text.indexOf("\n## ", idx + sectionHeader.length);
    const sectionContent = nextSection === -1 ? text.substring(idx) : text.substring(idx, nextSection);
    const lines = sectionContent.split("\n");
    return `${sectionContent.length}c:${lines.length}l:${sectionContent.charCodeAt(0)}:${sectionContent.charCodeAt(sectionContent.length - 1)}`;
}
/** 资产 ID → 章节/hash 级内容检查 */
const ASSET_CONTENT_CHECKS = {
    "adapter-workflow-template": (t) => {
        const hasWorkflow = /^## 强制工作流/m.test(t) && /@sf-hard-rule/.test(t);
        const hasSteps = /### 步骤 \d+/.test(t);
        const hash = computeSectionHash(t, "## 强制工作流");
        return { pass: hasWorkflow && hasSteps, proof: `section=强制工作流 hash=${hash}` };
    },
    "adapter-claude-md": (t) => {
        const hasTitle = /^# SoloForge 集成规则/m.test(t);
        const hash = computeSectionHash(t, "# SoloForge 集成规则");
        return { pass: hasTitle, proof: `section=集成规则 hash=${hash}` };
    },
};
/**
 * 生成 CLAUDE.md 项目指令文件内容。
 * 只记录生成文本实际包含对应内容的资产 trace，trace 含章节 hash 证明。
 */
export function generateClaudeMd(config) {
    debug("ClaudeMD生成", "开始生成 CLAUDE.md");
    const result = generateWorkflowRules(config) + "\n";
    // 只记录生成文本实际包含对应内容的资产 trace（章节/hash 级验证）
    const registeredAssets = listConsumableAssetsByConsumer("generateClaudeMd");
    for (const asset of registeredAssets) {
        const checker = ASSET_CONTENT_CHECKS[asset.id];
        const checkResult = checker ? checker(result) : { pass: result.length > 0, proof: `length=${result.length}` };
        if (checkResult.pass) {
            const contract = getContractByPath(asset.path);
            recordConsumptionTrace({
                consumer: "adapter_prompt",
                asset_id: asset.id,
                asset_path: asset.path,
                fields_consumed: CONSUMER_FIELD_CONTRACTS.adapter_prompt,
                matched_reason: `CLAUDE.md content_verified consumed ${asset.id} ${checkResult.proof}`,
                task_id_or_route: "claude-md",
                consumed_at: new Date().toISOString(),
                declared_consumer: contract?.mainline_consumer,
            });
        }
    }
    return result;
}
//# sourceMappingURL=claude_md.js.map