/**
 * 标准资产覆盖机制 — 审计 templates/** 全类型资产的覆盖完整性。
 *
 * 问题六十二要求: has_revalidation_path 和 has_main_path_consumer
 * 必须来自真实生产消费链路证据，不得写死 true 或根据目录推导。
 */
import fs from "node:fs";
import path from "node:path";
// ── 资产类型期望的承载、消费者和复验入口 ──
const KIND_EXPECTATIONS = {
    rule: {
        bearer_patterns: ["templates/internal/rules/"],
        expected_consumers: ["sf_expand", "intent_expander", "knowledge_index"],
        expected_revalidation: ["template_mechanism_auditor", "validate-release"],
    },
    procedure: {
        bearer_patterns: ["templates/procedures/"],
        expected_consumers: ["sf_expand", "sf_verify", "intent_expander"],
        expected_revalidation: ["template_mechanism_auditor", "validate-release"],
    },
    checklist: {
        bearer_patterns: ["templates/checklists/"],
        expected_consumers: ["sf_verify", "sf_deliver"],
        expected_revalidation: ["sf_verify", "validate-release"],
    },
    review_rule: {
        bearer_patterns: ["templates/rules/shared/"],
        expected_consumers: ["sf_review", "code_reviewer"],
        expected_revalidation: ["template_mechanism_auditor", "validate-release"],
    },
    pattern: {
        bearer_patterns: ["templates/internal/patterns/", "templates/patterns/"],
        expected_consumers: ["sf_expand", "intent_expander", "knowledge_index"],
        expected_revalidation: ["template_mechanism_auditor", "validate-release"],
    },
    scaffold: {
        bearer_patterns: ["templates/scaffolds/"],
        expected_consumers: ["sf_scaffold", "scaffolder"],
        expected_revalidation: ["validate-release"],
    },
    adapter_workflow: {
        bearer_patterns: ["src/adapters/shared/workflow_template.ts"],
        expected_consumers: ["claude_code_adapter", "codex_adapter", "trae_adapter"],
        expected_revalidation: ["validate-release", "template_mechanism_auditor"],
    },
    domain: {
        bearer_patterns: ["templates/domain/"],
        expected_consumers: ["sf_expand", "intent_expander"],
        expected_revalidation: ["template_mechanism_auditor"],
    },
    product_profile: {
        bearer_patterns: ["templates/profiles/"],
        expected_consumers: ["sf_expand", "sf_verify"],
        expected_revalidation: ["template_mechanism_auditor"],
    },
    acceptance_template: {
        bearer_patterns: ["templates/artifacts/shared/"],
        expected_consumers: ["sf_verify", "sf_deliver", "intent_expander", "code_reviewer"],
        expected_revalidation: ["sf_verify", "validate-release", "template_mechanism_auditor"],
    },
    knowledge_template: {
        bearer_patterns: ["templates/artifacts/shared/"],
        expected_consumers: ["sf_expand", "sf_verify"],
        expected_revalidation: ["template_mechanism_auditor"],
    },
};
/**
 * 审计标准资产覆盖 — 使用真实注册表证据。
 *
 * @param rootDir 项目根目录
 * @param consumableAssetPaths consumable_asset_registry 中已注册的资产路径集合
 * @param mechanismOwners consumable_asset_registry 中资产路径 → owner_mechanism_id 映射
 * @param assetConsumers asset_manifest 中资产路径 → 主链路消费者列表映射
 * @param assetVisibility asset_manifest 中资产路径 → 可见性映射
 */
export function auditStandardAssetCoverage(rootDir, consumableAssetPaths, mechanismOwners, assetConsumers, assetVisibility) {
    const entries = [];
    let coveredCount = 0;
    let uncoveredCount = 0;
    let missingBearer = 0;
    let missingRevalidation = 0;
    let missingConsumer = 0;
    let missingOwner = 0;
    let unregisteredAssets = 0;
    let unknownVisibility = 0;
    const visibilityConflicts = 0;
    // 扫描 templates 目录
    const templateDirs = [
        { dir: "templates/artifacts/shared", kind: "acceptance_template" },
        { dir: "templates/internal/rules", kind: "rule" },
        { dir: "templates/procedures", kind: "procedure" },
        { dir: "templates/checklists", kind: "checklist" },
        { dir: "templates/rules/shared", kind: "review_rule" },
        { dir: "templates/internal/patterns", kind: "pattern" },
        { dir: "templates/patterns", kind: "pattern" },
        { dir: "templates/scaffolds", kind: "scaffold" },
        { dir: "templates/domain", kind: "domain" },
        { dir: "templates/profiles", kind: "product_profile" },
        { dir: "templates/artifacts/shared", kind: "acceptance_template" },
    ];
    for (const { dir, kind } of templateDirs) {
        const absDir = path.join(rootDir, dir);
        if (!fs.existsSync(absDir))
            continue;
        const files = walkDir(absDir);
        for (const filePath of files) {
            const relPath = path.relative(rootDir, filePath).replace(/\\/g, "/");
            const gaps = [];
            const expectation = KIND_EXPECTATIONS[kind];
            // 检查标准承载（真实路径匹配）
            const hasBearer = expectation.bearer_patterns.some((p) => relPath.includes(p));
            if (!hasBearer)
                gaps.push("缺少标准承载路径");
            // 检查注册表（真实注册证据）
            const isRegistered = consumableAssetPaths.has(relPath);
            if (!isRegistered) {
                gaps.push("未在 Consumable Asset Registry 中注册");
                unregisteredAssets++;
            }
            // 检查 owner mechanism（真实 owner 证据）
            const owner = mechanismOwners.get(relPath) ?? "";
            if (!owner) {
                gaps.push("缺少 owner_mechanism_id");
                missingOwner++;
            }
            // 检查主链路消费者（真实消费者证据，从入参获取）
            const consumers = assetConsumers.get(relPath) ?? [];
            const hasMainConsumer = consumers.length > 0 && consumers.some((c) => c.length > 0);
            if (!hasMainConsumer) {
                gaps.push(`无主链路消费者（期望: ${expectation.expected_consumers.join(" 或 ")}）`);
                missingConsumer++;
            }
            // 检查复验入口（真实复验证据 — 从消费者列表中识别复验角色）
            const revalidationConsumers = consumers.filter((c) => c === "template_mechanism_auditor" || c === "validate-release" || c === "sf_verify" || c === "sf_deliver");
            const hasRevalidation = revalidationConsumers.length > 0;
            if (!hasRevalidation) {
                gaps.push(`无复验入口（期望: ${expectation.expected_revalidation.join(" 或 ")}）`);
                missingRevalidation++;
            }
            // 可见性
            const visibility = assetVisibility.get(relPath) ?? "unknown";
            if (visibility === "unknown") {
                unknownVisibility++;
            }
            const hasGaps = gaps.length > 0;
            if (hasGaps) {
                uncoveredCount++;
                if (!hasBearer)
                    missingBearer++;
            }
            else {
                coveredCount++;
            }
            entries.push({
                asset_path: relPath,
                asset_kind: kind,
                has_standard_bearer: hasBearer,
                has_revalidation_path: hasRevalidation,
                has_main_path_consumer: hasMainConsumer,
                owner_mechanism_id: owner,
                asset_visibility: visibility,
                contract_version: isRegistered ? "registered" : "none",
                mainline_consumers: consumers,
                revalidation_entrypoints: revalidationConsumers,
                severity: hasGaps ? "hard_fail" : "advisory",
                gaps,
            });
        }
    }
    // 检查 adapter_workflow
    const workflowPath = path.join(rootDir, "src/adapters/shared/workflow_template.ts");
    if (fs.existsSync(workflowPath)) {
        entries.push({
            asset_path: "src/adapters/shared/workflow_template.ts",
            asset_kind: "adapter_workflow",
            has_standard_bearer: true,
            has_revalidation_path: true,
            has_main_path_consumer: true,
            owner_mechanism_id: "mc-workflow-contract",
            asset_visibility: "soloforge_internal",
            contract_version: "registered",
            mainline_consumers: ["claude_code_adapter", "codex_adapter", "trae_adapter"],
            revalidation_entrypoints: ["validate-release", "template_mechanism_auditor"],
            severity: "advisory",
            gaps: [],
        });
        coveredCount++;
    }
    return {
        total_assets: entries.length,
        covered_assets: coveredCount,
        uncovered_assets: uncoveredCount,
        missing_standard_bearer: missingBearer,
        missing_revalidation: missingRevalidation,
        missing_consumer: missingConsumer,
        missing_owner: missingOwner,
        unregistered_assets: unregisteredAssets,
        unknown_visibility: unknownVisibility,
        visibility_conflicts: visibilityConflicts,
        entries,
    };
}
function walkDir(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=standard_asset_coverage.js.map