/**
 * 生命周期 + 项目知识 + 证据消费统一合同。
 *
 * 这是 next、sf_expand、sf_review、sf_verify、sf_deliver、审计和发布门禁共享的决策包。
 * 任何入口不得绕过本合同临时新增生命周期文件、知识选择规则或交付阻断口径。
 */
import { assessControlledGenerationChain } from "./control_plane_contract.js";
import { createDesignArtifactPack, defaultDesignArtifactPaths, verifyDesignArtifactPack, } from "./design_artifact_pack.js";
import { getDesignLifecycleArtifactPaths, getDesignLifecycleStageContract, } from "./design_lifecycle_contract.js";
import { auditProjectKnowledge, selectProjectKnowledgeForTaskWithReasons, } from "./project_knowledge_contract.js";
import { auditDesignImplementationTraceability, } from "./traceability.js";
import { recordConsumptionTrace } from "../templates/consumption_trace_store.js";
function consumerToTraceConsumer(consumer) {
    switch (consumer) {
        case "sf_expand":
            return "expander";
        case "sf_review":
            return "reviewer";
        case "sf_verify":
            return "verifier";
        case "sf_deliver":
            return "deliverer";
        case "soloforge_next":
        case "release_gate":
        case "hook":
        case "audit":
            return "knowledge_selection";
    }
}
function consumerAction(consumer) {
    switch (consumer) {
        case "sf_expand":
            return "injected";
        case "sf_review":
            return "reviewed";
        case "sf_verify":
            return "verified";
        case "sf_deliver":
            return "delivery_blocked";
        case "audit":
            return "indexed";
        default:
            return "selected";
    }
}
function unique(values) {
    return [...new Set(values.filter((value) => !!value && value.trim().length > 0))];
}
function collectTraceabilityIds(input) {
    return unique([
        ...(input.traceability_ids ?? []),
        ...((input.intent.match(/\b(?:REQ|PROTO|ARCH|DD|PHASE|SLICE|AC)-(?:[A-Z]+)?\d{2,}\b/g) ?? [])),
    ]);
}
function shouldEnforceTraceability(input, traceabilityIds) {
    if (input.require_design_audit || traceabilityIds.length > 0)
        return true;
    const stageRequiresTraceability = ["implementation", "testing", "acceptance", "delivery"].includes(input.lifecycle_stage ?? "");
    if (!stageRequiresTraceability)
        return false;
    return (input.changed_files ?? []).some((file) => /\.(java|kt|ts|tsx|js|jsx|py|go|rs|sql|yaml|yml)$/i.test(file) &&
        !file.startsWith("templates/") &&
        !file.startsWith("docs/") &&
        !file.includes(".test.") &&
        !file.endsWith(".test.ts") &&
        !file.endsWith(".test.tsx"));
}
export function evaluateLifecycleKnowledgeDecision(input) {
    const authoritativePaths = getDesignLifecycleArtifactPaths();
    const projectKnowledge = auditProjectKnowledge(input.projectPath, input.config);
    const traceability = auditDesignImplementationTraceability(input.projectPath, authoritativePaths.traceability_matrix);
    const lifecycleStageContract = input.lifecycle_stage
        ? getDesignLifecycleStageContract(input.lifecycle_stage)
        : undefined;
    const traceabilityIds = collectTraceabilityIds(input);
    const selection = selectProjectKnowledgeForTaskWithReasons(projectKnowledge, {
        intent: input.intent,
        route: input.route,
        tech_stack: input.tech_stack,
        lifecycle_stage: input.lifecycle_stage,
        changed_files: input.changed_files,
        business_domains: input.business_domains,
        traceability_ids: traceabilityIds,
        limit: input.selection_limit ?? 8,
    });
    const findings = [];
    for (const asset of projectKnowledge.assets) {
        for (const finding of asset.findings) {
            if (finding.severity === "hard_fail") {
                findings.push({
                    severity: "hard_fail",
                    code: finding.code,
                    message_zh: `${asset.rel_path}: ${finding.message_zh}`,
                    recovery_command: "soloforge audit-project-knowledge",
                    source: "project_knowledge",
                });
            }
        }
    }
    if (shouldEnforceTraceability(input, traceabilityIds)) {
        for (const finding of traceability.findings) {
            findings.push({
                severity: finding.severity,
                code: finding.code,
                message_zh: finding.message_zh,
                recovery_command: finding.recovery_command,
                source: "traceability",
            });
        }
    }
    let designArtifactPack;
    if (input.require_design_audit) {
        designArtifactPack = verifyDesignArtifactPack(input.projectPath, createDesignArtifactPack(input.task_id ?? "lifecycle-knowledge-decision", defaultDesignArtifactPaths()));
        for (const finding of designArtifactPack.findings) {
            findings.push({
                severity: finding.severity,
                code: finding.code,
                message_zh: finding.message_zh,
                recovery_command: finding.recovery_command ?? "soloforge audit-design-artifacts",
                source: "design_artifact_pack",
            });
        }
    }
    if (input.enforce_control_plane !== false) {
        const controlPlane = assessControlledGenerationChain({
            changed_files: input.changed_files ?? [],
            verified_files: input.verified_files ?? input.changed_files ?? [],
            traces: input.generation_traces ?? [],
            delivery_status: input.delivery_status,
        });
        for (const finding of controlPlane.findings) {
            findings.push({
                severity: finding.severity,
                code: finding.code,
                message_zh: finding.message,
                recovery_command: finding.recovery,
                source: "control_plane",
            });
        }
    }
    const requiredGate = lifecycleStageContract?.gates.find((gate) => gate.owner === input.consumer || (input.consumer === "hook" && gate.owner === "cli"));
    if (requiredGate && requiredGate.required_evidence.length === 0) {
        findings.push({
            severity: "hard_fail",
            code: "LIFECYCLE_GATE_WITHOUT_EVIDENCE",
            message_zh: `生命周期门禁 ${requiredGate.id} 缺少 required_evidence`,
            recovery_command: requiredGate.recovery_command,
            source: "lifecycle",
        });
    }
    if (input.record_trace !== false) {
        const traceConsumer = consumerToTraceConsumer(input.consumer);
        const action = consumerAction(input.consumer);
        for (const decision of selection.decisions) {
            recordConsumptionTrace({
                consumer: traceConsumer,
                asset_id: decision.asset.id,
                asset_path: decision.asset.rel_path,
                fields_consumed: ["asset_path", "contract_decision", "lifecycle_stage", "matched_signals", "excluded_reasons"],
                matched_reason: decision.reason_zh,
                matched_signals: decision.matched_signals,
                excluded_reasons: decision.excluded_reasons,
                task_id_or_route: input.task_id ?? input.route ?? input.consumer,
                consumed_at: new Date().toISOString(),
                lifecycle_stage: input.lifecycle_stage,
                action,
                contract_decision: decision.status === "blocked" ? "denied" : decision.status === "selected" ? "allowed" : "unregistered",
            });
        }
    }
    const hardFailCount = findings.filter((finding) => finding.severity === "hard_fail").length;
    const warningCount = findings.filter((finding) => finding.severity === "warning").length;
    const recoveryCommands = unique(findings.map((finding) => finding.recovery_command));
    return {
        contract_id: "lifecycle_knowledge_contract/v1",
        consumer: input.consumer,
        lifecycle_stage: input.lifecycle_stage,
        lifecycle_stage_contract: lifecycleStageContract,
        authoritative_paths: authoritativePaths,
        project_knowledge: projectKnowledge,
        knowledge_selection: selection,
        traceability,
        design_artifact_pack: designArtifactPack,
        findings,
        hard_fail_count: hardFailCount,
        warning_count: warningCount,
        decision_summary_zh: hardFailCount > 0
            ? `统一生命周期知识合同阻断 ${hardFailCount} 项`
            : `统一生命周期知识合同通过，选中 ${selection.selected.length} 条项目知识规则`,
        recovery_commands: recoveryCommands,
    };
}
export function summarizeLifecycleKnowledgeDecision(bundle) {
    const selected = bundle.knowledge_selection.selected
        .map((decision) => `${decision.asset.rel_path}: ${decision.reason_zh}`)
        .join("；");
    const blockers = bundle.findings
        .filter((finding) => finding.severity === "hard_fail")
        .map((finding) => `[${finding.code}] ${finding.message_zh}`)
        .join("；");
    return blockers || selected || bundle.decision_summary_zh;
}
//# sourceMappingURL=lifecycle_knowledge_contract.js.map