# Agent Publish-Subscribe Schema
# Based on REF-013 MetaGPT Research
# Issue: #172

$schema: "https://json-schema.org/draft/2020-12/schema"
$id: "https://aiwg.io/schemas/agent-pubsub/v1"
title: "Agent Publish-Subscribe Schema"
description: |
  Schema for publish-subscribe pattern enabling decentralized agent
  coordination based on artifact publication per REF-013 MetaGPT.

type: object
required:
  - version
  - event_bus
  - subscriptions

properties:
  version:
    type: string
    pattern: "^\\d+\\.\\d+\\.\\d+$"
    default: "1.0.0"

  event_bus:
    $ref: "#/$defs/EventBusConfig"

  subscriptions:
    $ref: "#/$defs/SubscriptionRegistry"

  artifact_types:
    $ref: "#/$defs/ArtifactTypes"

$defs:
  EventBusConfig:
    type: object
    description: "Event bus configuration"
    properties:
      enabled:
        type: boolean
        default: true

      persistence:
        type: object
        properties:
          enabled:
            type: boolean
            default: true
          path:
            type: string
            default: ".aiwg/events/"
          retention_days:
            type: integer
            default: 30

      delivery:
        type: object
        properties:
          mode:
            type: string
            enum: [sync, async, queue]
            default: async
          retry_count:
            type: integer
            default: 3
          timeout_ms:
            type: integer
            default: 30000

      logging:
        type: object
        properties:
          log_publishes:
            type: boolean
            default: true
          log_subscriptions:
            type: boolean
            default: true
          log_activations:
            type: boolean
            default: true

  SubscriptionRegistry:
    type: object
    description: "Agent subscription definitions"
    properties:
      agents:
        type: array
        items:
          $ref: "#/$defs/AgentSubscription"

  AgentSubscription:
    type: object
    required:
      - agent_name
      - subscribes_to
      - publishes
    properties:
      agent_name:
        type: string
      subscribes_to:
        type: array
        items:
          type: string
        description: "Artifact types this agent listens for"
      publishes:
        type: array
        items:
          type: string
        description: "Artifact types this agent produces"
      priority:
        type: integer
        default: 100
        description: "Lower = higher priority for parallel subscribers"
      activation_mode:
        type: string
        enum: [auto, manual, conditional]
        default: auto

  ArtifactTypes:
    type: object
    description: "Defined artifact types for publish-subscribe"
    additionalProperties:
      type: object
      properties:
        description:
          type: string
        schema_ref:
          type: string
        publishers:
          type: array
          items:
            type: string
        subscribers:
          type: array
          items:
            type: string

# Default agent subscriptions
default_subscriptions:
  agents:
    - agent_name: architect
      subscribes_to:
        - PRD
        - RequirementsUpdate
      publishes:
        - SystemDesign
        - ADR
      priority: 100

    - agent_name: requirements-analyst
      subscribes_to:
        - ProjectIntake
        - ChangeRequest
      publishes:
        - PRD
        - UserStory
        - UseCase
      priority: 50

    - agent_name: software-implementer
      subscribes_to:
        - SystemDesign
        - TaskAssignment
        - BugReport
      publishes:
        - Implementation
        - CodeChange
      priority: 100

    - agent_name: test-engineer
      subscribes_to:
        - Implementation
        - CodeChange
        - TestRequest
      publishes:
        - TestSuite
        - TestReport
        - CoverageReport
      priority: 100

    - agent_name: security-auditor
      subscribes_to:
        - SystemDesign
        - Implementation
        - SecurityRequest
      publishes:
        - ThreatModel
        - SecurityReport
        - VulnerabilityReport
      priority: 90

    - agent_name: code-reviewer
      subscribes_to:
        - Implementation
        - CodeChange
      publishes:
        - CodeReview
        - ReviewFeedback
      priority: 100

    - agent_name: technical-writer
      subscribes_to:
        - Implementation
        - SystemDesign
        - APIContract
      publishes:
        - Documentation
        - APIDoc
        - UserGuide
      priority: 150

    - agent_name: devops-engineer
      subscribes_to:
        - Implementation
        - DeploymentRequest
      publishes:
        - DeploymentPlan
        - PipelineConfig
        - InfrastructureChange
      priority: 120

# Artifact event schema
artifact_event:
  type: object
  required:
    - event_id
    - type
    - path
    - publisher
    - timestamp
  properties:
    event_id:
      type: string
      format: uuid
    type:
      type: string
      description: "Artifact type (PRD, SystemDesign, etc.)"
    path:
      type: string
      description: "Path to artifact file"
    content_hash:
      type: string
      description: "Hash for change detection"
    metadata:
      type: object
      additionalProperties: true
    publisher:
      type: string
      description: "Agent that published"
    timestamp:
      type: string
      format: date-time
    correlation_id:
      type: string
      description: "Links related events"
    parent_event:
      type: string
      description: "Event that triggered this publication"

# Activation record schema
activation_record:
  type: object
  required:
    - activation_id
    - agent
    - trigger_event
    - status
  properties:
    activation_id:
      type: string
      format: uuid
    agent:
      type: string
    trigger_event:
      type: string
      description: "Event ID that triggered activation"
    status:
      type: string
      enum: [pending, running, completed, failed, skipped]
    started_at:
      type: string
      format: date-time
    completed_at:
      type: string
      format: date-time
    outputs:
      type: array
      items:
        type: string
        description: "Event IDs of published outputs"
    error:
      type: string

# Workflow example
workflow_example:
  description: "Example SDLC workflow using pub-sub"
  flow:
    - step: 1
      trigger: "Human submits project intake"
      event:
        type: ProjectIntake
        path: ".aiwg/intake/project-intake.md"
      subscribers: [requirements-analyst]

    - step: 2
      trigger: "Requirements Analyst publishes PRD"
      event:
        type: PRD
        path: ".aiwg/requirements/prd.md"
      subscribers: [architect]

    - step: 3
      trigger: "Architect publishes System Design"
      event:
        type: SystemDesign
        path: ".aiwg/architecture/sad.md"
      subscribers: [software-implementer, security-auditor, test-engineer]
      note: "Multiple agents activate in parallel"

    - step: 4
      trigger: "Software Implementer publishes Implementation"
      event:
        type: Implementation
        path: "src/**/*.ts"
      subscribers: [test-engineer, code-reviewer, technical-writer]

# Agent protocol
agent_protocol:
  publish:
    description: "Publish artifact to event bus"
    steps:
      - generate_event_id
      - hash_content
      - create_event_record
      - persist_artifact
      - emit_to_event_bus
      - log_publication
      - notify_subscribers

  subscribe:
    description: "Register agent subscription"
    steps:
      - load_subscription_config
      - register_with_event_bus
      - set_activation_handler

  on_event:
    description: "Handle incoming event"
    steps:
      - receive_event
      - check_subscription_match
      - if_subscribed:
          - queue_activation
          - load_agent
          - inject_event_context
          - run_agent
          - collect_outputs
          - publish_outputs

  parallel_activation:
    description: "Handle multiple subscribers"
    steps:
      - identify_all_subscribers
      - sort_by_priority
      - if_same_priority:
          - run_in_parallel
      - else:
          - run_in_priority_order
      - await_all_completions
      - collect_all_outputs

# CLI integration
cli_options:
  pubsub_mode:
    name: "--pubsub"
    type: boolean
    default: true
    help: "Enable publish-subscribe orchestration"

  show_events:
    name: "--show-events"
    type: boolean
    default: false
    help: "Display event bus activity"

  manual_activation:
    name: "--manual"
    type: boolean
    default: false
    help: "Require manual approval for each activation"

# Storage
storage:
  events_path: ".aiwg/events/"
  subscriptions_path: ".aiwg/config/subscriptions.yaml"
  activation_log_path: ".aiwg/events/activations.jsonl"

# Research targets (from REF-013)
research_targets:
  coordination_overhead_reduction: "Significant vs procedural"
  parallelization_benefit: "Multiple agents activate simultaneously"
  extensibility: "New agents added without orchestrator changes"
  debugging: "Event log enables replay and analysis"

# References
references:
  research:
    - "@.aiwg/research/findings/REF-013-metagpt.md"
  implementation:
    - "#172"
  related:
    - "@agentic/code/frameworks/sdlc-complete/schemas/flows/sdlc-output-schemas.yaml"
    - "@agentic/code/frameworks/sdlc-complete/docs/orchestrator-architecture.md"
    - "@.claude/rules/conversable-agent-interface.md"
