/**
 * 全模板资产权威合同注册表 — 214 资产单一权威元数据体系。
 *
 * 合同由显式资产注册表 (explicit_asset_registry.ts) 驱动，
 * 每个资产逐一注册，新增文件必须新增条目，否则 validate-release hard_fail。
 * DRAFT_CATEGORY_DEFAULTS 仅用于生成待审草稿/诊断建议，不作为发布态合同。
 */
import fs from "node:fs";
import path from "node:path";
import { debug } from "../core/logger.js";
import { EXPLICIT_ASSET_REGISTRY } from "./explicit_asset_registry.js";
/**
 * 诊断用草稿默认值 — 用于为新资产生成待审合同建议，不作为发布态合同。
 * 新增模板文件应先通过此生成草稿，审阅后写入 explicit_asset_registry.ts。
 */
export const DRAFT_CATEGORY_DEFAULTS = [
    {
        prefix: "templates/模版贡献指南.md",
        defaults: {
            asset_kind: "governance_rule",
            owner_mechanism_id: "mc-core-engineering-principles",
            asset_visibility: "soloforge_internal",
            sync_to_user_project: false,
            sync_target: "none",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only_pipeline",
            mainline_consumer: "",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/artifacts/shared/",
        defaults: {
            asset_kind: "acceptance_template",
            owner_mechanism_id: "mc-standard-asset-contract",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["artifact_generation", "operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/checklists/",
        defaults: {
            asset_kind: "checklist",
            owner_mechanism_id: "mc-verifier",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["review", "operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "knowledge_manager.addKnowledge",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/domain/",
        defaults: {
            asset_kind: "domain",
            owner_mechanism_id: "mc-knowledge-injection-boundary",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/internal/patterns/",
        defaults: {
            asset_kind: "pattern_core",
            owner_mechanism_id: "mc-core-engineering-principles",
            asset_visibility: "soloforge_internal",
            sync_to_user_project: false,
            sync_target: "none",
            runtime_visibility: "internal_only",
            evidence_role: "template_guidance",
            user_visible: false,
            applicable_routes: [],
            applicable_tech_stack: [],
            lifecycle_status: "internal_only",
            consume_category: "internal_runtime",
            mainline_consumer: "knowledge_config_loader.loadKnowledgeConfig",
            validation_entrypoint: "validate-release",
        },
    },
    {
        prefix: "templates/procedures/",
        defaults: {
            asset_kind: "procedure",
            owner_mechanism_id: "mc-workflow-contract",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["operation", "planning"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/profiles/",
        defaults: {
            asset_kind: "product_profile",
            owner_mechanism_id: "mc-zero-config-init",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "classification",
            user_visible: true,
            applicable_routes: ["operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "knowledge_manager.addKnowledge",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/rules/shared/",
        defaults: {
            asset_kind: "review_rule",
            owner_mechanism_id: "mc-standard-asset-contract",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/internal/rules/",
        defaults: {
            asset_kind: "governance_rule",
            owner_mechanism_id: "mc-workflow-contract",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/artifacts/shared/",
        defaults: {
            asset_kind: "knowledge_template",
            owner_mechanism_id: "mc-standard-asset-contract",
            asset_visibility: "user_project",
            sync_to_user_project: true,
            sync_target: "project_knowledge",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "knowledge_manager.addKnowledge",
            validation_entrypoint: "template_mechanism_auditor",
        },
    },
    {
        prefix: "templates/patterns/",
        defaults: {
            asset_kind: "global_pattern",
            owner_mechanism_id: "mc-core-engineering-principles",
            asset_visibility: "global_pattern",
            sync_to_user_project: false,
            sync_target: "global_patterns",
            runtime_visibility: "index_only",
            evidence_role: "template_guidance",
            user_visible: true,
            applicable_routes: ["operation"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "copy_only",
            mainline_consumer: "soloforge.copyGlobalPatterns",
            validation_entrypoint: "validate-release",
        },
    },
    {
        prefix: "templates/scaffolds/",
        defaults: {
            asset_kind: "scaffold",
            owner_mechanism_id: "mc-zero-config-init",
            asset_visibility: "scaffold_only",
            sync_to_user_project: false,
            sync_target: "none",
            runtime_visibility: "scaffold_only",
            evidence_role: "template_guidance",
            user_visible: false,
            applicable_routes: ["scaffold"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "scaffold_only",
            mainline_consumer: "scaffolder.generateScaffold",
            validation_entrypoint: "validate-release",
        },
    },
    {
        prefix: "src/adapters/shared/workflow_template.ts",
        defaults: {
            asset_kind: "adapter_workflow",
            owner_mechanism_id: "mc-workflow-contract",
            asset_visibility: "soloforge_internal",
            sync_to_user_project: false,
            sync_target: "none",
            runtime_visibility: "internal_only",
            evidence_role: "template_guidance",
            user_visible: false,
            applicable_routes: ["operation", "planning", "review"],
            applicable_tech_stack: [],
            lifecycle_status: "active",
            consume_category: "internal_runtime",
            mainline_consumer: "claude_md.generateClaudeMd",
            validation_entrypoint: "validate-release",
        },
    },
];
// ── 可验证消费证据 — 每类资产对应真实生产消费链 ──
const CONSUMPTION_EVIDENCE_MAP = {
    acceptance_template: {
        asset_kind: "acceptance_template",
        selected_by_entrypoint: "queryKnowledgeForRoute",
        selection_rule_or_matcher: "output_artifact.kind + template name matching",
        production_consumer_file: "src/engine/pipeline/intent_expander.ts",
        production_consumer_export: "queryKnowledgeForRoute",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/intent_expander_integration.test.ts",
    },
    checklist: {
        asset_kind: "checklist",
        selected_by_entrypoint: "addKnowledge",
        selection_rule_or_matcher: "type=checklist → checklist directory",
        production_consumer_file: "src/engine/knowledge/knowledge_manager.ts",
        production_consumer_export: "addKnowledge",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/knowledge_manager.test.ts",
    },
    domain: {
        asset_kind: "domain",
        selected_by_entrypoint: "addKnowledge",
        selection_rule_or_matcher: "type=domain → domain directory",
        production_consumer_file: "src/engine/knowledge/knowledge_manager.ts",
        production_consumer_export: "addKnowledge",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/knowledge_manager.test.ts",
    },
    governance_rule: {
        asset_kind: "governance_rule",
        selected_by_entrypoint: "consumeForRouter",
        selection_rule_or_matcher: "routes + primary_triggers from frontmatter",
        production_consumer_file: "src/engine/knowledge/knowledge_asset_consumer.ts",
        production_consumer_export: "consumeForRouter",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/contract_fail_closed.test.ts",
    },
    procedure: {
        asset_kind: "procedure",
        selected_by_entrypoint: "loadBuiltinByPipeline",
        selection_rule_or_matcher: "pipeline_hint → fileName mapping",
        production_consumer_file: "src/engine/pipeline/intent_expander.ts",
        production_consumer_export: "loadBuiltinByPipeline",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/intent_expander_integration.test.ts",
    },
    pipeline_procedure: {
        asset_kind: "pipeline_procedure",
        selected_by_entrypoint: "loadBuiltinByPipeline",
        selection_rule_or_matcher: "pipeline_hint → fileName mapping",
        production_consumer_file: "src/engine/pipeline/intent_expander.ts",
        production_consumer_export: "loadBuiltinByPipeline",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/intent_expander_integration.test.ts",
    },
    review_rule: {
        asset_kind: "review_rule",
        selected_by_entrypoint: "classifyFindingsByTrust",
        selection_rule_or_matcher: "knowledgeIndex.query({ type: 'review_rule' })",
        production_consumer_file: "src/engine/audit/code_reviewer.ts",
        production_consumer_export: "classifyFindingsByTrust",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/code_reviewer.test.ts",
    },
    pattern_core: {
        asset_kind: "pattern_core",
        selected_by_entrypoint: "loadKnowledgeConfig",
        selection_rule_or_matcher: "direct path reference (e.g. patterns/core/决策网关.md)",
        production_consumer_file: "src/engine/knowledge/knowledge_config_loader.ts",
        production_consumer_export: "loadKnowledgeConfig",
        validation_entrypoint: "validate-release",
        runtime_test_or_scenario_ref: "tests/engine/knowledge_coupling.test.ts",
    },
    product_profile: {
        asset_kind: "product_profile",
        selected_by_entrypoint: "addKnowledge",
        selection_rule_or_matcher: "type=product_profile → product_profiles directory",
        production_consumer_file: "src/engine/knowledge/knowledge_manager.ts",
        production_consumer_export: "addKnowledge",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/knowledge_manager.test.ts",
    },
    knowledge_template: {
        asset_kind: "knowledge_template",
        selected_by_entrypoint: "addKnowledge",
        selection_rule_or_matcher: "type=knowledge_template → templates directory",
        production_consumer_file: "src/engine/knowledge/knowledge_manager.ts",
        production_consumer_export: "addKnowledge",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/knowledge_manager.test.ts",
    },
    global_pattern: {
        asset_kind: "global_pattern",
        selected_by_entrypoint: "copyGlobalPatterns",
        selection_rule_or_matcher: "*.md in templates/patterns/ → ~/.soloforge/patterns/",
        production_consumer_file: "src/bin/commands/init.ts",
        production_consumer_export: "copyGlobalPatterns",
        validation_entrypoint: "validate-release",
        runtime_test_or_scenario_ref: "tests/engine/template_asset_contract_registry.test.ts",
    },
    scaffold: {
        asset_kind: "scaffold",
        selected_by_entrypoint: "generateScaffold",
        selection_rule_or_matcher: "tech_stack.framework → templateSet → *.hbs files",
        production_consumer_file: "src/engine/templates/scaffolder.ts",
        production_consumer_export: "generateScaffold",
        validation_entrypoint: "validate-release",
        runtime_test_or_scenario_ref: "tests/engine/scaffolder.test.ts",
    },
    adapter_workflow: {
        asset_kind: "adapter_workflow",
        selected_by_entrypoint: "generateClaudeMd",
        selection_rule_or_matcher: "adapter init → generateWorkflowRules → inject into CLAUDE.md",
        production_consumer_file: "src/adapters/claude_code/claude_md.ts",
        production_consumer_export: "generateClaudeMd",
        validation_entrypoint: "validate-release",
        runtime_test_or_scenario_ref: "tests/adapters/workflow_rules.test.ts",
    },
    pipeline_artifact: {
        asset_kind: "pipeline_artifact",
        selected_by_entrypoint: "copyPipelineTemplatesToProject",
        selection_rule_or_matcher: "templates/{shared,new-system,existing-system}/artifacts/ → .soloforge/templates/",
        production_consumer_file: "src/engine/templates/template_init_sync.ts",
        production_consumer_export: "copyPipelineTemplatesToProject",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/template_asset_contract_registry.test.ts",
    },
    pipeline_rule: {
        asset_kind: "pipeline_rule",
        selected_by_entrypoint: "copyPipelineTemplatesToProject",
        selection_rule_or_matcher: "templates/{shared,new-system,existing-system}/rules/ → .soloforge/templates/",
        production_consumer_file: "src/engine/templates/template_init_sync.ts",
        production_consumer_export: "copyPipelineTemplatesToProject",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/template_asset_contract_registry.test.ts",
    },
    stage_gate: {
        asset_kind: "stage_gate",
        selected_by_entrypoint: "copyPipelineTemplatesToProject",
        selection_rule_or_matcher: "templates/{shared,existing-system}/gates/ → .soloforge/templates/",
        production_consumer_file: "src/engine/templates/template_init_sync.ts",
        production_consumer_export: "copyPipelineTemplatesToProject",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/template_asset_contract_registry.test.ts",
    },
    knowledge_rule: {
        asset_kind: "knowledge_rule",
        selected_by_entrypoint: "filterInjectable",
        selection_rule_or_matcher: "type=knowledge_rule → EXECUTION_SHAPE_ALLOWED_TYPES 过滤",
        production_consumer_file: "src/engine/knowledge/knowledge_injection_boundary.ts",
        production_consumer_export: "filterInjectable",
        validation_entrypoint: "template_mechanism_auditor",
        runtime_test_or_scenario_ref: "tests/engine/knowledge_injection_boundary.test.ts",
    },
};
/**
 * 获取指定资产类型的真实消费证据。
 */
export function getConsumptionEvidence(assetKind) {
    return CONSUMPTION_EVIDENCE_MAP[assetKind];
}
/**
 * 验证消费证据中声明的生产消费者文件是否真实存在于源码中。
 */
export function verifyConsumptionEvidence(rootDir) {
    const results = [];
    const srcDir = path.join(rootDir, "src");
    const testsDir = path.join(rootDir, "tests");
    for (const [kind, evidence] of Object.entries(CONSUMPTION_EVIDENCE_MAP)) {
        const consumerPath = path.join(srcDir, evidence.production_consumer_file.replace("src/", ""));
        const consumerExists = fs.existsSync(consumerPath);
        let exportFound = false;
        if (consumerExists) {
            const content = fs.readFileSync(consumerPath, "utf-8");
            exportFound = content.includes(evidence.production_consumer_export) ||
                content.includes(`function ${evidence.production_consumer_export}`) ||
                content.includes(`${evidence.production_consumer_export}(`);
        }
        const testPath = path.join(testsDir, evidence.runtime_test_or_scenario_ref.replace("tests/", ""));
        const testExists = fs.existsSync(testPath);
        results.push({
            asset_kind: kind,
            evidence,
            consumer_exists: consumerExists,
            consumer_export_found: exportFound,
            test_exists: testExists,
        });
    }
    return results;
}
function generateAssetId(relPath) {
    return relPath.replace(/\//g, "-").replace(/\.(md|yaml|yml|hbs|json)$/, "");
}
/**
 * 构建全模板资产权威合同列表 — 由显式注册表驱动。
 * 只为 EXPLICIT_ASSET_REGISTRY 中注册的资产生成合同，未注册文件不计入。
 */
export function buildTemplateAssetContracts(_rootDir) {
    const contracts = [];
    for (const [relPath, entry] of Object.entries(EXPLICIT_ASSET_REGISTRY)) {
        // 注册但文件不存在 → 仍生成合同（由 auditContractCoverage 报告文件缺失）
        contracts.push({
            asset_id: generateAssetId(relPath),
            path: relPath,
            asset_kind: entry.asset_kind,
            contract_version: "1.0.0",
            owner_mechanism_id: entry.owner_mechanism_id,
            asset_visibility: entry.asset_visibility,
            sync_to_user_project: entry.sync_to_user_project,
            sync_target: entry.sync_target,
            runtime_visibility: entry.runtime_visibility,
            evidence_role: entry.evidence_role,
            user_visible: entry.user_visible,
            applicable_routes: [...entry.applicable_routes],
            applicable_tech_stack: [...entry.applicable_tech_stack],
            lifecycle_status: entry.lifecycle_status,
            consume_category: entry.consume_category,
            mainline_consumer: entry.mainline_consumer,
            validation_entrypoint: entry.validation_entrypoint,
            applicable_languages: entry.applicable_languages ? [...entry.applicable_languages] : undefined,
            applicable_frameworks: entry.applicable_frameworks ? [...entry.applicable_frameworks] : undefined,
            applicable_file_patterns: entry.applicable_file_patterns ? [...entry.applicable_file_patterns] : undefined,
            excluded_file_patterns: entry.excluded_file_patterns ? [...entry.excluded_file_patterns] : undefined,
            verification_strategy: entry.verification_strategy,
            failure_severity: entry.failure_severity,
            required_template_vars: entry.required_template_vars ? [...entry.required_template_vars] : undefined,
        });
    }
    debug("权威合同", "构建完成，共 %d 条合同（显式注册表驱动）", contracts.length);
    return contracts;
}
// ── 缓存 ──
let _cachedContracts = null;
/**
 * 列出全模板资产权威合同（带缓存）。
 */
export function listTemplateAssetContracts() {
    if (_cachedContracts)
        return _cachedContracts;
    const rootDir = path.resolve(new URL(import.meta.url).pathname, "..", "..", "..");
    _cachedContracts = buildTemplateAssetContracts(rootDir);
    return _cachedContracts;
}
/**
 * 清除缓存（测试用）。
 */
export function clearContractCache() {
    _cachedContracts = null;
}
/**
 * 按路径查询合同。
 */
export function getContractByPath(relPath) {
    return listTemplateAssetContracts().find((c) => c.path === relPath);
}
/**
 * 合同决策 — 返回 allowed/denied/unregistered。
 * allowed: 注册且允许访问
 * denied: 注册但禁止（内部/脚手架资产）
 * unregistered: 未在显式注册表中注册 → fail-closed
 */
export function getContractDecision(relPath) {
    const normalized = relPath.replace(/\\/g, "/");
    const contract = getContractByPath(normalized);
    if (!contract) {
        return { decision: "unregistered" };
    }
    if (contract.asset_visibility === "soloforge_internal" || contract.asset_visibility === "scaffold_only") {
        return { decision: "denied", contract };
    }
    if (contract.runtime_visibility === "internal_only") {
        return { decision: "denied", contract };
    }
    return { decision: "allowed", contract };
}
/**
 * 按可见性筛选。
 */
export function getContractsByVisibility(visibility) {
    return listTemplateAssetContracts().filter((c) => c.asset_visibility === visibility);
}
/**
 * 获取应同步到用户项目的资产路径列表。
 */
export function getSyncableAssetPaths() {
    return listTemplateAssetContracts()
        .filter((c) => c.sync_to_user_project)
        .map((c) => c.path);
}
/**
 * 获取内部资产路径集合。
 */
export function getInternalAssetPaths() {
    return new Set(listTemplateAssetContracts()
        .filter((c) => c.asset_visibility === "soloforge_internal" || c.asset_visibility === "scaffold_only")
        .map((c) => c.path));
}
/**
 * 生成合同覆盖统计，验证真实消费证据，检测未注册文件。
 */
export function auditContractCoverage(rootDir) {
    const contracts = buildTemplateAssetContracts(rootDir);
    const report = {
        total_templates: 0,
        total_contracts: contracts.length,
        contract_covered: 0,
        uncovered: 0,
        unregistered_files: [],
        missing_from_registry: 0,
        visibility_unknown: 0,
        consumer_missing: 0,
        validation_missing: 0,
        owner_missing: 0,
        internal_count: 0,
        user_visible_count: 0,
        consume_category_breakdown: { mainline: 0, audit_only: 0, internal_runtime: 0, scaffold_only: 0, copy_only: 0, copy_only_pipeline: 0 },
        consumption_evidence_verified: true,
        consumption_evidence_failures: [],
    };
    // 检测文件系统中存在但未注册的文件
    const templatesDir = path.join(rootDir, "templates");
    const registeredPaths = new Set(contracts.map((c) => c.path));
    if (fs.existsSync(templatesDir)) {
        const fsFiles = walkTemplates(templatesDir);
        for (const absPath of fsFiles) {
            const relPath = path.relative(rootDir, absPath).replace(/\\/g, "/");
            report.total_templates++;
            if (!registeredPaths.has(relPath)) {
                report.unregistered_files.push(relPath);
                report.missing_from_registry++;
            }
        }
    }
    // 验证消费证据
    const evidenceResults = verifyConsumptionEvidence(rootDir);
    for (const r of evidenceResults) {
        if (!r.consumer_exists) {
            report.consumption_evidence_failures.push(`${r.asset_kind}: consumer file ${r.evidence.production_consumer_file} not found`);
            report.consumption_evidence_verified = false;
        }
        if (!r.consumer_export_found) {
            report.consumption_evidence_failures.push(`${r.asset_kind}: export ${r.evidence.production_consumer_export} not found in ${r.evidence.production_consumer_file}`);
            report.consumption_evidence_verified = false;
        }
        if (!r.test_exists) {
            report.consumption_evidence_failures.push(`${r.asset_kind}: test file ${r.evidence.runtime_test_or_scenario_ref} not found`);
            report.consumption_evidence_verified = false;
        }
    }
    for (const c of contracts) {
        const needsMainlineConsumer = c.consume_category === "mainline";
        const hasGaps = (needsMainlineConsumer && !c.mainline_consumer) || !c.validation_entrypoint || !c.owner_mechanism_id;
        if (hasGaps) {
            report.uncovered++;
            if (!c.mainline_consumer)
                report.consumer_missing++;
            if (!c.validation_entrypoint)
                report.validation_missing++;
            if (!c.owner_mechanism_id)
                report.owner_missing++;
        }
        else {
            report.contract_covered++;
        }
        if (c.asset_visibility === "soloforge_internal" || c.asset_visibility === "scaffold_only") {
            report.internal_count++;
        }
        else {
            report.user_visible_count++;
        }
        if (c.asset_visibility !== "user_project" && c.asset_visibility !== "soloforge_internal" &&
            c.asset_visibility !== "scaffold_only" && c.asset_visibility !== "global_pattern") {
            report.visibility_unknown++;
        }
        report.consume_category_breakdown[c.consume_category] = (report.consume_category_breakdown[c.consume_category] ?? 0) + 1;
    }
    return report;
}
// ── 工具函数 ──
function walkTemplates(dir) {
    const results = [];
    const stack = [dir];
    while (stack.length > 0) {
        const current = stack.pop();
        for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
            const absPath = path.join(current, entry.name);
            if (entry.isDirectory()) {
                stack.push(absPath);
            }
            else if (/\.(md|yaml|yml|hbs|json)$/.test(entry.name)) {
                results.push(absPath);
            }
        }
    }
    return results;
}
//# sourceMappingURL=template_asset_contract_registry.js.map