asyncapi: 2.6.0

info:
  title: AIBrain Service Kafka Events
  version: 1.0.0
  description: |
    AsyncAPI specification for the aibrain-svc Kafka event interface.

    aibrain-svc is the AI Brain / ZAR ensemble orchestration service for the
    EventZR platform. It runs on AWS ECS Fargate and communicates with other
    services via Amazon MSK Serverless (Kafka) using the CloudEvents 1.0
    envelope format.

    All events are partitioned by tenant_id for multi-tenant isolation and
    use the transactional outbox pattern for reliable delivery.
  contact:
    name: EventZR Platform Team
    url: https://eventzr.com
  license:
    name: Proprietary

servers:
  staging:
    url: boot-gpm4u49z.c2.kafka-serverless.us-east-1.amazonaws.com:9098
    protocol: kafka-secure
    description: Amazon MSK Serverless (staging, us-east-1)
    security:
      - mskIamAuth: []
    bindings:
      kafka:
        schemaRegistryUrl: false

defaultContentType: application/json

channels:
  # =========================================================================
  # PRODUCED CHANNELS — Events published by aibrain-svc
  # =========================================================================

  eventzr.aibrain.request.initiated.v1:
    description: |
      Published when an AI orchestration request begins processing.
      Consumers: analytics-svc, wallet-svc, audit-logger.
    publish:
      operationId: publishRequestInitiated
      summary: AI request initiated
      message:
        $ref: '#/components/messages/AIRequestInitiated'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.response.generated.v1:
    description: |
      Published when AI response generation completes successfully.
      Consumers: analytics-svc, wallet-svc, search-svc, notify-svc, audit-logger.
    publish:
      operationId: publishResponseGenerated
      summary: AI response generated
      message:
        $ref: '#/components/messages/AIResponseGenerated'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.streaming.chunk.v1:
    description: |
      Published for each streaming response chunk (high-volume, optional).
      Enable only when streaming analytics are required.
      Consumers: notify-svc (real-time streaming notifications).
    publish:
      operationId: publishStreamingChunk
      summary: AI streaming response chunk
      message:
        $ref: '#/components/messages/AIStreamingChunk'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.consensus.failed.v1:
    description: |
      Published when the ZAR ensemble AI fails to achieve consensus
      across the Planner, Doer, and Stylist models.
      Consumers: analytics-svc, notify-svc, audit-logger.
    publish:
      operationId: publishConsensusFailed
      summary: Ensemble consensus failure
      message:
        $ref: '#/components/messages/ConsensusFailed'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.budget.exceeded.v1:
    description: |
      Published when a tenant exceeds their AI budget limit.
      Consumers: wallet-svc, notify-svc, analytics-svc.
    publish:
      operationId: publishBudgetExceeded
      summary: Budget limit exceeded
      message:
        $ref: '#/components/messages/BudgetExceeded'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.cost.incurred.v1:
    description: |
      Published when an AI operation completes and cost is calculated.
      Consumers: wallet-svc, analytics-svc, audit-logger.
    publish:
      operationId: publishCostIncurred
      summary: AI operation cost tracked
      message:
        $ref: '#/components/messages/CostIncurred'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.policy.violated.v1:
    description: |
      Published when an AI operation violates a content, data privacy,
      or compliance policy.
      Consumers: notify-svc, security-svc, audit-logger.
    publish:
      operationId: publishPolicyViolated
      summary: Policy violation detected
      message:
        $ref: '#/components/messages/PolicyViolated'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.model.degraded.v1:
    description: |
      Published when AI model performance drops below acceptable thresholds.
      Consumers: notify-svc, analytics-svc, ops-dashboard.
    publish:
      operationId: publishModelDegraded
      summary: Model performance degradation detected
      message:
        $ref: '#/components/messages/ModelDegraded'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.anomaly.detected.v1:
    description: |
      Published when the anomaly detection system identifies unusual patterns
      in AI usage, costs, or quality.
      Consumers: notify-svc, security-svc, analytics-svc.
    publish:
      operationId: publishAnomalyDetected
      summary: Anomaly detected in AI operations
      message:
        $ref: '#/components/messages/AnomalyDetected'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  eventzr.aibrain.feedback.submitted.v1:
    description: |
      Published when user feedback on an AI response is submitted.
      Consumers: eventml-svc (training data), analytics-svc.
    publish:
      operationId: publishFeedbackSubmitted
      summary: AI feedback submitted
      message:
        $ref: '#/components/messages/FeedbackSubmitted'
      bindings:
        kafka:
          groupId: false
          clientId:
            type: string
            enum:
              - aibrain-svc

  # =========================================================================
  # CONSUMED CHANNELS — Events consumed by aibrain-svc
  # =========================================================================

  eventzr.events.completed.v1:
    description: |
      Consumed from event-svc when an event finishes. Used to analyze
      attendee behavior and update recommendation models.
    subscribe:
      operationId: handleEventCompleted
      summary: Event completed
      message:
        $ref: '#/components/messages/EventCompleted'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.rag.knowledge.updated.v1:
    description: |
      Consumed from rag-svc when a knowledge base is updated. Triggers
      cache invalidation for cached embeddings and vector search results.
    subscribe:
      operationId: handleKnowledgeUpdated
      summary: RAG knowledge base updated
      message:
        $ref: '#/components/messages/RAGKnowledgeUpdated'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.rules.policy.updated.v1:
    description: |
      Consumed from the rules engine when policy rules are updated.
      Refreshes local policy cache for real-time enforcement.
    subscribe:
      operationId: handlePolicyUpdated
      summary: Policy rules updated
      message:
        $ref: '#/components/messages/RulesPolicyUpdated'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.tour.leg.completed.v1:
    description: |
      Consumed from tour-svc when a tour leg/show completes. Used to
      analyze tour performance and update venue recommendation models.
    subscribe:
      operationId: handleTourLegCompleted
      summary: Tour leg completed
      message:
        $ref: '#/components/messages/TourLegCompleted'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.users.created.v1:
    description: |
      Consumed from user-svc when a new user registers. Initializes
      user AI preferences and quota tracking.
    subscribe:
      operationId: handleUserCreated
      summary: User created
      message:
        $ref: '#/components/messages/UserCreated'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.users.deleted.v1:
    description: |
      Consumed from user-svc when a user account is deleted. Triggers
      GDPR-compliant cleanup of conversations, messages, KG relationships,
      and cache entries.
    subscribe:
      operationId: handleUserDeleted
      summary: User deleted
      message:
        $ref: '#/components/messages/UserDeleted'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.wallet.subscription.updated.v1:
    description: |
      Consumed from wallet-svc when a tenant subscription tier changes.
      Updates local tier and credit limit caches.
    subscribe:
      operationId: handleSubscriptionUpdated
      summary: Subscription tier updated
      message:
        $ref: '#/components/messages/WalletSubscriptionUpdated'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.wallet.credits.updated.v1:
    description: |
      Consumed from wallet-svc when credit balance changes. Maintains
      a local credit balance cache for fast credit checks.
    subscribe:
      operationId: handleCreditsUpdated
      summary: Credit balance updated
      message:
        $ref: '#/components/messages/WalletCreditsUpdated'
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  # =========================================================================
  # CONSUMED CHANNELS — AI workflow tracking (from kafka.config.ts)
  # =========================================================================

  eventzr.llmorch.response.generated.v1:
    description: |
      Consumed from llm-orch-svc after an LLM completion is generated.
      Tracks which workflows triggered LLM calls and records latency.
    subscribe:
      operationId: handleLLMResponseGenerated
      summary: LLM orchestration response generated
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.llmorch.streaming.chunk.v1:
    description: |
      Consumed from llm-orch-svc for streaming response chunks.
    subscribe:
      operationId: handleLLMStreamingChunk
      summary: LLM streaming chunk received
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.llmorch.error.v1:
    description: |
      Consumed from llm-orch-svc when an LLM operation fails.
    subscribe:
      operationId: handleLLMError
      summary: LLM orchestration error
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.rag.knowledge.retrieved.v1:
    description: |
      Consumed from rag-svc when knowledge retrieval completes.
      Tracks RAG retrieval latency and document counts.
    subscribe:
      operationId: handleRAGKnowledgeRetrieved
      summary: RAG knowledge retrieved
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.mcp.tool.executed.v1:
    description: |
      Consumed from mcp-svc when a tool execution completes.
      Tracks MCP tool execution latency and success rate.
    subscribe:
      operationId: handleMCPToolExecuted
      summary: MCP tool executed
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.rules.policy.validated.v1:
    description: |
      Consumed from the rules engine when a policy validation completes.
    subscribe:
      operationId: handleRulesPolicyValidated
      summary: Policy validation completed
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.wallet.credits.deducted.v1:
    description: |
      Consumed from wallet-svc when credits are deducted for an operation.
    subscribe:
      operationId: handleWalletCreditsDeducted
      summary: Wallet credits deducted
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.wallet.balance.updated.v1:
    description: |
      Consumed from wallet-svc when wallet balance changes.
    subscribe:
      operationId: handleWalletBalanceUpdated
      summary: Wallet balance updated
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.user.deleted.v1:
    description: |
      Consumed from user-svc on user deletion (alternate topic name
      from kafka.config.ts consumed topics).
    subscribe:
      operationId: handleUserDeletedAlt
      summary: User deleted (config topic)
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.user.profile.updated.v1:
    description: |
      Consumed from user-svc when a user profile is updated.
    subscribe:
      operationId: handleUserProfileUpdated
      summary: User profile updated
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

  eventzr.tenant.suspended.v1:
    description: |
      Consumed when a tenant is suspended. Should halt all AI operations
      for the tenant.
    subscribe:
      operationId: handleTenantSuspended
      summary: Tenant suspended
      bindings:
        kafka:
          groupId:
            type: string
            enum:
              - aibrain-svc-group

components:
  securitySchemes:
    mskIamAuth:
      type: plain
      description: AWS MSK IAM authentication via SASL mechanism 'aws'

  messages:
    # =====================================================================
    # PRODUCED MESSAGES
    # =====================================================================

    AIRequestInitiated:
      name: AIRequestInitiated
      title: AI Request Initiated
      summary: Published when an AI orchestration request begins processing.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_AIRequestInitiatedData'

    AIResponseGenerated:
      name: AIResponseGenerated
      title: AI Response Generated
      summary: Published when AI response generation completes successfully.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_AIResponseGeneratedData'

    AIStreamingChunk:
      name: AIStreamingChunk
      title: AI Streaming Chunk
      summary: Published for each streaming response chunk (high-volume).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_AIStreamingChunkData'

    ConsensusFailed:
      name: ConsensusFailed
      title: Consensus Failed
      summary: Published when ZAR ensemble fails to reach consensus.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_ConsensusFailedData'

    BudgetExceeded:
      name: BudgetExceeded
      title: Budget Exceeded
      summary: Published when a tenant exceeds their AI budget limit.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_BudgetExceededData'

    CostIncurred:
      name: CostIncurred
      title: Cost Incurred
      summary: Published when AI operation completes and cost is calculated.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_CostIncurredData'

    PolicyViolated:
      name: PolicyViolated
      title: Policy Violated
      summary: Published when AI operation violates a policy rule.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_PolicyViolatedData'

    ModelDegraded:
      name: ModelDegraded
      title: Model Degraded
      summary: Published when model performance drops below thresholds.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_ModelDegradedData'

    AnomalyDetected:
      name: AnomalyDetected
      title: Anomaly Detected
      summary: Published when unusual patterns are detected in AI operations.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_AnomalyDetectedData'

    FeedbackSubmitted:
      name: FeedbackSubmitted
      title: Feedback Submitted
      summary: Published when user feedback on an AI response is submitted.
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_FeedbackSubmittedData'

    # =====================================================================
    # CONSUMED MESSAGES
    # =====================================================================

    EventCompleted:
      name: EventCompleted
      title: Event Completed
      summary: Event finished (from event-svc).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_EventCompletedData'

    RAGKnowledgeUpdated:
      name: RAGKnowledgeUpdated
      title: RAG Knowledge Updated
      summary: Knowledge base updated (from rag-svc).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_RAGKnowledgeUpdatedData'

    RulesPolicyUpdated:
      name: RulesPolicyUpdated
      title: Rules Policy Updated
      summary: Policy rules updated (from rules engine).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_RulesPolicyUpdatedData'

    TourLegCompleted:
      name: TourLegCompleted
      title: Tour Leg Completed
      summary: Tour leg/show completed (from tour-svc).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_TourLegCompletedData'

    UserCreated:
      name: UserCreated
      title: User Created
      summary: New user registered (from user-svc).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_UserCreatedData'

    UserDeleted:
      name: UserDeleted
      title: User Deleted
      summary: User account deleted (from user-svc).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_UserDeletedData'

    WalletSubscriptionUpdated:
      name: WalletSubscriptionUpdated
      title: Wallet Subscription Updated
      summary: Subscription tier changed (from wallet-svc).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_WalletSubscriptionUpdatedData'

    WalletCreditsUpdated:
      name: WalletCreditsUpdated
      title: Wallet Credits Updated
      summary: Credit balance changed (from wallet-svc).
      contentType: application/json
      traits:
        - $ref: '#/components/messageTraits/cloudEventHeaders'
      payload:
        $ref: '#/components/schemas/CloudEvent_WalletCreditsUpdatedData'

  messageTraits:
    cloudEventHeaders:
      headers:
        type: object
        required:
          - ce_specversion
          - ce_type
          - ce_source
          - ce_id
        properties:
          ce_specversion:
            type: string
            const: '1.0'
            description: CloudEvents spec version.
          ce_type:
            type: string
            description: CloudEvents event type identifier.
          ce_source:
            type: string
            description: CloudEvents source URI.
          ce_id:
            type: string
            description: Unique event ID (ULID).
          content-type:
            type: string
            const: application/cloudevents+json

  schemas:
    # =====================================================================
    # CloudEvents Envelope (reusable base)
    # =====================================================================

    CloudEventBase:
      type: object
      required:
        - specversion
        - type
        - source
        - id
        - time
        - datacontenttype
        - data
      properties:
        specversion:
          type: string
          const: '1.0'
          description: CloudEvents specification version.
        type:
          type: string
          description: Event type (e.g. com.eventzr.aibrain.request.initiated.v1).
        source:
          type: string
          description: Event source URI (e.g. /aibrain-svc/orchestration).
        id:
          type: string
          format: ulid
          description: Unique event ID (ULID).
        time:
          type: string
          format: date-time
          description: Event timestamp (ISO 8601).
        datacontenttype:
          type: string
          const: application/json
        subject:
          type: string
          description: Optional event subject.
        tenantid:
          type: string
          format: uuid
          description: Tenant ID for multi-tenancy (CloudEvents extension).
        correlationid:
          type: string
          description: Correlation ID for distributed tracing (CloudEvents extension).

    # =====================================================================
    # PRODUCED EVENT PAYLOADS
    # =====================================================================

    CloudEvent_AIRequestInitiatedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.request.initiated.v1
            source:
              const: /aibrain-svc/orchestration
            data:
              $ref: '#/components/schemas/AIRequestInitiatedData'

    AIRequestInitiatedData:
      type: object
      required:
        - requestId
        - tenantId
        - userId
        - model
        - modelProvider
        - orchestrationType
        - enableStreaming
        - enableRag
        - enableKGEnrichment
        - initiatedAt
      properties:
        requestId:
          type: string
          description: Unique request identifier.
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        conversationId:
          type: string
          format: uuid
        messageId:
          type: string
          format: uuid
        model:
          type: string
          description: AI model name (e.g. claude-3-5-sonnet).
        modelProvider:
          type: string
          description: Provider name (e.g. BEDROCK, OPENAI).
        orchestrationType:
          type: string
          enum:
            - BASIC
            - ENSEMBLE
            - AGENT
        enableStreaming:
          type: boolean
        enableRag:
          type: boolean
        enableKGEnrichment:
          type: boolean
        temperature:
          type: number
          minimum: 0
          maximum: 2
        maxTokens:
          type: integer
        estimatedCredits:
          type: number
        initiatedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_AIResponseGeneratedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.response.generated.v1
            source:
              const: /aibrain-svc/orchestration
            data:
              $ref: '#/components/schemas/AIResponseGeneratedData'

    AIResponseGeneratedData:
      type: object
      required:
        - requestId
        - responseId
        - tenantId
        - userId
        - conversationId
        - messageId
        - model
        - modelProvider
        - orchestrationType
        - inputTokens
        - outputTokens
        - totalTokens
        - cost
        - currency
        - creditsDeducted
        - latencyMs
        - kgEnriched
        - ragEnriched
        - toolCallsCount
        - citationsCount
        - generatedAt
      properties:
        requestId:
          type: string
        responseId:
          type: string
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        conversationId:
          type: string
          format: uuid
        messageId:
          type: string
          format: uuid
        model:
          type: string
        modelProvider:
          type: string
        orchestrationType:
          type: string
          enum:
            - BASIC
            - ENSEMBLE
            - AGENT
        inputTokens:
          type: integer
        outputTokens:
          type: integer
        totalTokens:
          type: integer
        cost:
          type: number
          description: Cost in USD.
        currency:
          type: string
          const: USD
        creditsDeducted:
          type: number
        latencyMs:
          type: integer
        confidenceScore:
          type: number
          minimum: 0
          maximum: 1
        kgEnriched:
          type: boolean
          description: Whether Knowledge Graph enrichment was applied.
        ragEnriched:
          type: boolean
          description: Whether RAG retrieval was applied.
        toolCallsCount:
          type: integer
        citationsCount:
          type: integer
        ensembleMetadata:
          type: object
          properties:
            plannerModel:
              type: string
            doerModel:
              type: string
            stylistModel:
              type: string
            consensusAchieved:
              type: boolean
            consensusScore:
              type: number
              minimum: 0
              maximum: 1
        generatedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_AIStreamingChunkData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.streaming.chunk.v1
            source:
              const: /aibrain-svc/streaming
            data:
              $ref: '#/components/schemas/AIStreamingChunkData'

    AIStreamingChunkData:
      type: object
      required:
        - requestId
        - chunkId
        - tenantId
        - userId
        - conversationId
        - sequenceNumber
        - chunkContent
        - chunkTokens
        - cumulativeTokens
        - isComplete
        - streamedAt
      properties:
        requestId:
          type: string
        chunkId:
          type: string
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        conversationId:
          type: string
          format: uuid
        sequenceNumber:
          type: integer
        chunkContent:
          type: string
        chunkTokens:
          type: integer
        cumulativeTokens:
          type: integer
        isComplete:
          type: boolean
          description: True when this is the final chunk.
        streamedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_ConsensusFailedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.consensus.failed.v1
            source:
              const: /aibrain-svc/ensemble
            data:
              $ref: '#/components/schemas/ConsensusFailedData'

    ConsensusFailedData:
      type: object
      required:
        - requestId
        - tenantId
        - userId
        - plannerModel
        - doerModel
        - stylistModel
        - consensusThreshold
        - actualConsensus
        - plannerResponse
        - doerResponse
        - stylistResponse
        - divergenceReason
        - fallbackAction
        - failedAt
      properties:
        requestId:
          type: string
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        conversationId:
          type: string
          format: uuid
        plannerModel:
          type: string
        doerModel:
          type: string
        stylistModel:
          type: string
        consensusThreshold:
          type: number
          description: Required semantic similarity threshold (default 0.80).
        actualConsensus:
          type: number
          description: Achieved consensus score.
        plannerResponse:
          type: object
          required:
            - content
            - confidence
          properties:
            content:
              type: string
            confidence:
              type: number
        doerResponse:
          type: object
          required:
            - content
            - confidence
          properties:
            content:
              type: string
            confidence:
              type: number
        stylistResponse:
          type: object
          required:
            - content
            - confidence
          properties:
            content:
              type: string
            confidence:
              type: number
        divergenceReason:
          type: string
        fallbackAction:
          type: string
          enum:
            - USE_PLANNER
            - USE_DOER
            - USE_STYLIST
            - ERROR
        failedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_BudgetExceededData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.budget.exceeded.v1
            source:
              const: /aibrain-svc/budget
            data:
              $ref: '#/components/schemas/BudgetExceededData'

    BudgetExceededData:
      type: object
      required:
        - tenantId
        - budgetType
        - limit
        - currentUsage
        - overage
        - timeframe
        - triggeredAt
      properties:
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        budgetType:
          type: string
          enum:
            - DAILY
            - MONTHLY
            - TOTAL
        limit:
          type: number
        currentUsage:
          type: number
        overage:
          type: number
        timeframe:
          type: string
          description: Budget timeframe window.
        triggeredAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_CostIncurredData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.cost.incurred.v1
            source:
              const: /aibrain-svc/costs
            data:
              $ref: '#/components/schemas/CostIncurredData'

    CostIncurredData:
      type: object
      required:
        - tenantId
        - requestId
        - provider
        - model
        - inputTokens
        - outputTokens
        - totalTokens
        - cost
        - currency
        - incurredAt
      properties:
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        conversationId:
          type: string
          format: uuid
        requestId:
          type: string
        provider:
          type: string
        model:
          type: string
        inputTokens:
          type: integer
        outputTokens:
          type: integer
        totalTokens:
          type: integer
        cost:
          type: number
          description: Cost in USD.
        currency:
          type: string
          const: USD
        incurredAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_PolicyViolatedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.policy.violated.v1
            source:
              const: /aibrain-svc/policy-enforcement
            data:
              $ref: '#/components/schemas/PolicyViolatedData'

    PolicyViolatedData:
      type: object
      required:
        - violationId
        - tenantId
        - requestId
        - policyType
        - severity
        - policyRule
        - violation
        - action
        - violatedAt
      properties:
        violationId:
          type: string
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        requestId:
          type: string
        conversationId:
          type: string
          format: uuid
        policyType:
          type: string
          enum:
            - CONTENT
            - DATA_PRIVACY
            - RATE_LIMIT
            - COMPLIANCE
            - SECURITY
        severity:
          type: string
          enum:
            - LOW
            - MEDIUM
            - HIGH
            - CRITICAL
        policyRule:
          type: string
          description: Name or ID of the violated policy rule.
        violation:
          type: string
          description: Human-readable description of the violation.
        inputContent:
          type: string
          description: The input that triggered the violation (may be redacted).
        outputContent:
          type: string
          description: The output that triggered the violation (may be redacted).
        action:
          type: string
          enum:
            - BLOCKED
            - FLAGGED
            - SANITIZED
        violatedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_ModelDegradedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.model.degraded.v1
            source:
              const: /aibrain-svc/monitoring
            data:
              $ref: '#/components/schemas/ModelDegradedData'

    ModelDegradedData:
      type: object
      required:
        - tenantId
        - provider
        - model
        - degradationType
        - severity
        - currentMetric
        - threshold
        - degradationPercent
        - timeWindow
        - sampleSize
        - detectedAt
      properties:
        tenantId:
          type: string
          format: uuid
        provider:
          type: string
          enum:
            - OPENAI
            - ANTHROPIC
            - GEMINI
            - AZURE_OPENAI
            - BEDROCK
            - ENSEMBLE
        model:
          type: string
        degradationType:
          type: string
          enum:
            - LATENCY
            - ERROR_RATE
            - QUALITY
            - AVAILABILITY
        severity:
          type: string
          enum:
            - WARNING
            - CRITICAL
        currentMetric:
          type: number
          description: Current observed metric value.
        threshold:
          type: number
          description: SLA threshold value.
        degradationPercent:
          type: number
          description: Percentage of degradation relative to threshold.
        timeWindow:
          type: string
          description: Observation time window (e.g. 5m, 1h).
        sampleSize:
          type: integer
        detectedAt:
          type: string
          format: date-time
        metadata:
          type: object
          properties:
            avgLatencyMs:
              type: number
            errorRate:
              type: number
            qualityScore:
              type: number
            availabilityPercent:
              type: number
            affectedRequests:
              type: integer
            ensembleRole:
              type: string
            failureReason:
              type: string

    CloudEvent_AnomalyDetectedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.anomaly.detected.v1
            source:
              const: /aibrain-svc/anomaly-detection
            data:
              $ref: '#/components/schemas/AnomalyDetectedData'

    AnomalyDetectedData:
      type: object
      required:
        - anomalyId
        - tenantId
        - anomalyType
        - severity
        - description
        - confidence
        - detectedAt
        - timeWindow
        - baseline
        - anomaly
      properties:
        anomalyId:
          type: string
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        anomalyType:
          type: string
          enum:
            - USAGE_SPIKE
            - UNUSUAL_PATTERN
            - COST_ANOMALY
            - QUALITY_DROP
            - SECURITY_THREAT
        severity:
          type: string
          enum:
            - LOW
            - MEDIUM
            - HIGH
            - CRITICAL
        description:
          type: string
        confidence:
          type: number
          minimum: 0
          maximum: 1
        detectedAt:
          type: string
          format: date-time
        timeWindow:
          type: string
        baseline:
          type: object
          required:
            - metric
            - normalValue
            - normalRange
          properties:
            metric:
              type: string
            normalValue:
              type: number
            normalRange:
              type: object
              required:
                - min
                - max
              properties:
                min:
                  type: number
                max:
                  type: number
        anomaly:
          type: object
          required:
            - metric
            - observedValue
            - deviationPercent
          properties:
            metric:
              type: string
            observedValue:
              type: number
            deviationPercent:
              type: number
        impact:
          type: object
          properties:
            affectedUsers:
              type: integer
            affectedRequests:
              type: integer
            estimatedCost:
              type: number
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_FeedbackSubmittedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            type:
              const: com.eventzr.aibrain.feedback.submitted
            source:
              const: aibrain-svc
            data:
              $ref: '#/components/schemas/FeedbackSubmittedData'

    FeedbackSubmittedData:
      type: object
      required:
        - feedbackId
        - sessionId
        - tenantId
        - userId
        - feedbackType
        - timestamp
      properties:
        feedbackId:
          type: string
        sessionId:
          type: string
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        feedbackType:
          type: string
          enum:
            - EXPLICIT
            - IMPLICIT
            - SUPERADMIN_REVIEW
        rating:
          type: number
          description: Numeric rating (e.g. 1-5).
        thumbs:
          type: string
          enum:
            - UP
            - DOWN
        correctness:
          type: string
          enum:
            - CORRECT
            - INCORRECT
            - PARTIAL
        weight:
          type: number
          description: Feedback weight for training.
        timeToActionMs:
          type: integer
          description: Time between AI response and user feedback action.
        actionTaken:
          type: string
          description: What the user did after receiving the response.
        addToPlatformTraining:
          type: boolean
          description: Whether this feedback should be used for platform-wide model training.
        timestamp:
          type: string
          format: date-time

    # =====================================================================
    # CONSUMED EVENT PAYLOADS
    # =====================================================================

    CloudEvent_EventCompletedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/EventCompletedData'

    EventCompletedData:
      type: object
      required:
        - eventId
        - tenantId
        - eventName
        - eventType
        - venueId
        - startDate
        - endDate
        - actualAttendees
        - expectedAttendees
        - revenue
        - completedAt
        - outcomes
      properties:
        eventId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        eventName:
          type: string
        eventType:
          type: string
        venueId:
          type: string
          format: uuid
        startDate:
          type: string
          format: date-time
        endDate:
          type: string
          format: date-time
        actualAttendees:
          type: integer
        expectedAttendees:
          type: integer
        revenue:
          type: number
        completedAt:
          type: string
          format: date-time
        outcomes:
          type: object
          properties:
            rating:
              type: number
            feedback:
              type: string
            npsScore:
              type: number
            repeatAttendanceRate:
              type: number
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_RAGKnowledgeUpdatedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/RAGKnowledgeUpdatedData'

    RAGKnowledgeUpdatedData:
      type: object
      required:
        - knowledgeBaseId
        - tenantId
        - updateType
        - documentCount
        - vectorCount
        - updatedAt
      properties:
        knowledgeBaseId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        documentId:
          type: string
          format: uuid
        updateType:
          type: string
          enum:
            - DOCUMENT_ADDED
            - DOCUMENT_UPDATED
            - DOCUMENT_DELETED
            - INDEX_REBUILT
        documentCount:
          type: integer
        vectorCount:
          type: integer
        namespace:
          type: string
        updatedAt:
          type: string
          format: date-time
        metadata:
          type: object
          properties:
            documentTitle:
              type: string
            documentType:
              type: string
            chunkCount:
              type: integer
            indexStatus:
              type: string

    CloudEvent_RulesPolicyUpdatedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/RulesPolicyUpdatedData'

    RulesPolicyUpdatedData:
      type: object
      required:
        - policyId
        - tenantId
        - policyType
        - policyName
        - rules
        - version
        - updatedAt
        - updatedBy
      properties:
        policyId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        policyType:
          type: string
          enum:
            - CONTENT_FILTER
            - RATE_LIMIT
            - COMPLIANCE
            - SECURITY
            - CUSTOM
        policyName:
          type: string
        rules:
          type: array
          items:
            type: object
            required:
              - ruleId
              - ruleName
              - condition
              - action
              - enabled
            properties:
              ruleId:
                type: string
              ruleName:
                type: string
              condition:
                type: string
              action:
                type: string
                enum:
                  - ALLOW
                  - DENY
                  - FLAG
                  - SANITIZE
              enabled:
                type: boolean
        version:
          type: integer
        updatedAt:
          type: string
          format: date-time
        updatedBy:
          type: string
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_TourLegCompletedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/TourLegCompletedData'

    TourLegCompletedData:
      type: object
      required:
        - tourLegId
        - tourId
        - tenantId
        - artistId
        - venueId
        - venueName
        - city
        - country
        - performanceDate
        - ticketsSold
        - capacity
        - revenue
        - expenses
        - netProfit
        - completedAt
        - outcomes
      properties:
        tourLegId:
          type: string
          format: uuid
        tourId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        artistId:
          type: string
          format: uuid
        venueId:
          type: string
          format: uuid
        venueName:
          type: string
        city:
          type: string
        country:
          type: string
        performanceDate:
          type: string
          format: date-time
        ticketsSold:
          type: integer
        capacity:
          type: integer
        revenue:
          type: number
        expenses:
          type: number
        netProfit:
          type: number
        completedAt:
          type: string
          format: date-time
        outcomes:
          type: object
          properties:
            audienceRating:
              type: number
            soundQuality:
              type: number
            venueRating:
              type: number
            weatherConditions:
              type: string
            technicalIssues:
              type: array
              items:
                type: string
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_UserCreatedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/UserCreatedData'

    UserCreatedData:
      type: object
      required:
        - userId
        - tenantId
        - email
        - role
        - createdAt
      properties:
        userId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        email:
          type: string
          format: email
        role:
          type: string
        subscriptionTier:
          type: string
        createdAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_UserDeletedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/UserDeletedData'

    UserDeletedData:
      type: object
      required:
        - userId
        - tenantId
        - deletedAt
      properties:
        userId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        deletedAt:
          type: string
          format: date-time
        reason:
          type: string
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_WalletSubscriptionUpdatedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WalletSubscriptionUpdatedData'

    WalletSubscriptionUpdatedData:
      type: object
      required:
        - tenantId
        - subscriptionId
        - tier
        - creditLimit
        - updatedAt
      properties:
        tenantId:
          type: string
          format: uuid
        subscriptionId:
          type: string
          format: uuid
        tier:
          type: string
          enum:
            - FREE
            - BASIC
            - PREMIUM
            - ENTERPRISE
        previousTier:
          type: string
        creditLimit:
          type: number
        updatedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true

    CloudEvent_WalletCreditsUpdatedData:
      allOf:
        - $ref: '#/components/schemas/CloudEventBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WalletCreditsUpdatedData'

    WalletCreditsUpdatedData:
      type: object
      required:
        - tenantId
        - walletId
        - previousBalance
        - currentBalance
        - change
        - reason
        - updatedAt
      properties:
        tenantId:
          type: string
          format: uuid
        walletId:
          type: string
          format: uuid
        previousBalance:
          type: number
        currentBalance:
          type: number
        change:
          type: number
        reason:
          type: string
        transactionId:
          type: string
        updatedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true
