/**
 * 问题三十九: Extension Contract — 扩展生命周期、权限授权与审计。
 *
 * 强制执行:
 * - 第三方扩展不得自称 enforced
 * - 扩展权限必须显式授权、最小权限、可撤销
 * - 扩展不能绕过 Contract Registry / Guard / Language Policy
 */
/** 扩展生命周期合法转移表 */
const LIFECYCLE_TRANSITIONS = {
    draft: ["installed", "deprecated"],
    installed: ["active", "disabled", "deprecated"],
    active: ["disabled", "deprecated"],
    disabled: ["active", "deprecated", "blocked"],
    deprecated: ["blocked"],
    blocked: [],
};
/** 扩展可申请的权限白名单 */
const ALLOWED_PERMISSIONS = new Set([
    "read_project", "read_soloforge_state", "write_artifact",
    "write_knowledge", "write_config", "execute_command",
    "network_access", "external_write", "delivery_action", "contract_state_update",
]);
/** 高风险权限需要人类审批 */
const HIGH_RISK_PERMISSIONS = new Set([
    "execute_command", "network_access", "external_write",
    "delivery_action", "contract_state_update",
]);
/**
 * 创建默认扩展清单。
 */
export function createExtensionManifest(overrides) {
    return {
        name: overrides.extension_id,
        version: "1.0.0",
        provider: "unknown",
        extension_type: "workflow",
        contract_ids: [],
        capability_ids: [],
        permissions: [],
        entrypoints: [],
        outputs: [],
        default_state: "disabled",
        compatibility: { min_soloforge_version: "1.0.0" },
        ...overrides,
    };
}
/**
 * 验证扩展清单。
 * - 第三方扩展不得使用 enforced 状态
 * - 权限必须在白名单内
 * - 必须声明 contract_ids 和 capability_ids
 */
export function validateExtensionManifest(manifest, declaredCapabilities) {
    const violations = [];
    const warnings = [];
    // 第三方扩展不得自称 enforced
    if (declaredCapabilities.third_party && declaredCapabilities.claimed_enforcement === "enforced_by_host") {
        violations.push("第三方扩展不得自称 enforced_by_host");
    }
    // 权限白名单检查
    for (const perm of manifest.permissions) {
        if (!ALLOWED_PERMISSIONS.has(perm)) {
            violations.push(`权限不在白名单: ${perm}`);
        }
    }
    // 必须声明 contract_ids
    if (manifest.contract_ids.length === 0) {
        warnings.push("未声明任何 contract_ids，扩展可能绕过 Contract Registry");
    }
    // 必须声明 capability_ids
    if (manifest.capability_ids.length === 0) {
        warnings.push("未声明任何 capability_ids");
    }
    return { valid: violations.length === 0, violations, warnings };
}
/**
 * 评估扩展生命周期转移是否合法。
 */
export function evaluateExtensionLifecycle(_extensionId, fromStatus, toStatus) {
    const allowedTargets = LIFECYCLE_TRANSITIONS[fromStatus];
    if (!allowedTargets) {
        return { allowed: false, from_status: fromStatus, to_status: toStatus, reason: `未知状态: ${fromStatus}` };
    }
    if (!allowedTargets.includes(toStatus)) {
        return { allowed: false, from_status: fromStatus, to_status: toStatus, reason: `${fromStatus} → ${toStatus} 不允许` };
    }
    return { allowed: true, from_status: fromStatus, to_status: toStatus, reason: "合法转移" };
}
/**
 * 授权扩展权限。
 * - 高风险权限需要 human approval
 * - 权限必须是最小集
 */
export function grantExtensionPermissions(extensionId, requestedPermissions, grantedBy, purpose, humanApproved) {
    const granted = [];
    const denied = [];
    for (const perm of requestedPermissions) {
        if (!ALLOWED_PERMISSIONS.has(perm)) {
            denied.push(perm);
            continue;
        }
        if (HIGH_RISK_PERMISSIONS.has(perm) && !humanApproved) {
            denied.push(perm);
            continue;
        }
        granted.push(perm);
    }
    return {
        extension_id: extensionId,
        granted_permissions: granted,
        granted_by: grantedBy,
        purpose,
        granted_at: new Date().toISOString(),
        revoked: false,
        extension_grant_status: denied.length === 0 ? "granted" : "granted",
    };
}
/**
 * 撤销扩展权限授权。
 */
export function revokeExtensionGrant(grant, _reason) {
    return {
        ...grant,
        revoked: true,
        extension_grant_status: "revoked",
    };
}
/**
 * 生成扩展审计报告。
 */
export function auditExtension(manifest, grant, capabilityDecl) {
    const violations = [];
    const findings = [];
    if (capabilityDecl.third_party && capabilityDecl.claimed_enforcement === "enforced_by_host") {
        violations.push("第三方扩展非法自称 enforced");
    }
    if (grant.granted_permissions.some(p => !manifest.permissions.includes(p))) {
        violations.push("授权权限超出清单声明范围");
    }
    if (grant.revoked) {
        findings.push("权限已被撤销");
    }
    if (manifest.contract_ids.length === 0) {
        findings.push("未绑定任何契约，可能绕过 Contract Registry");
    }
    return {
        extension_id: manifest.extension_id,
        audited_at: new Date().toISOString(),
        lifecycle_status: "installed",
        enforcement_status: capabilityDecl.claimed_enforcement,
        permissions_used: grant.granted_permissions,
        contract_registry_entries: manifest.contract_ids,
        violations,
        findings,
    };
}
//# sourceMappingURL=extension_contract.js.map