openapi: 3.0.3
info:
  title: ETHRAEON CoRIx API
  description: |
    Constitutional AI orchestration with NIST ARIA 0.1 compliance.
    
    ## Overview
    The CoRIx API generates hierarchical measurement trees that evaluate AI system outputs
    against NIST ARIA (AI Risk and Impact Assessment) standards.
    
    ## Authentication
    All endpoints except `/health` and `/schema` require Bearer token authentication.
    Include your API key in the Authorization header:
    ```
    Authorization: Bearer your-api-key
    ```
    
    ## Constitutional Compliance
    All responses include constitutional headers:
    - `X-Constitutional-Compliance`: Verification status
    - `X-DELTASUM-Version`: Telemetry store version
    - `X-CoRIx-Version`: CoRIx specification version
    - `X-ETHRAEON-Trace`: Request trace ID
    - `X-ETHRAEON-Attribution`: SHA256 attribution token
    
    ## CoRIx 6-Level Hierarchy
    | Level | Name | Purpose |
    |-------|------|---------|
    | 1 | Interpret & Contextualize | High-level summary with validity score |
    | 2 | Risks — Validity & Reliability | Risk assessment and reliability metrics |
    | 3 | Testing Level | Model/Red Team/Field categorization |
    | 4 | Annotator Responses | ARIA 5-category automated annotation |
    | 5 | Response Collation | Aggregated measurements and statistics |
    | 6 | Raw Data | Complete telemetry and provenance |
    
    © 2025 S. Jason Prohaska (ingombrante©) — ETHRAEON Systems
  version: 1.0.0
  contact:
    name: ETHRAEON Systems
    url: https://ethraeon.ai
    email: api@ethraeon.systems
  license:
    name: Schedule A+ Enhanced IP Firewall
    url: https://ethraeon.ai/legal/ip-firewall

servers:
  - url: https://api.ethraeon.ai/api/aria/corix
    description: Production
  - url: http://localhost:5001/api/aria/corix
    description: Local Development

tags:
  - name: Health
    description: Service health and status
  - name: CoRIx
    description: CoRIx tree generation
  - name: Traces
    description: ΔSUM trace management
  - name: Statistics
    description: Aggregate statistics

paths:
  /health:
    get:
      tags: [Health]
      summary: Health check
      description: Returns service status and version information. No authentication required.
      operationId: getHealth
      responses:
        '200':
          description: Service healthy
          headers:
            X-Constitutional-Compliance:
              schema:
                type: string
                example: verified
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HealthResponse'

  /schema:
    get:
      tags: [Health]
      summary: NIST ARIA schema information
      description: Returns the CoRIx schema specification. No authentication required. Cacheable.
      operationId: getSchema
      responses:
        '200':
          description: Schema information
          headers:
            Cache-Control:
              schema:
                type: string
                example: public, max-age=3600
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SchemaResponse'

  /generate:
    post:
      tags: [CoRIx]
      summary: Generate CoRIx tree
      description: |
        Generates a complete 6-level CoRIx measurement tree from a ΔSUM trace.
        
        The trace must exist in the store before calling this endpoint.
        Use `POST /traces` to store telemetry first.
      operationId: generateCoRIx
      security:
        - BearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateRequest'
            examples:
              basic:
                summary: Basic generation
                value:
                  trace_id: "ETH-abc123def456-1701234567890"
              withOptions:
                summary: With options
                value:
                  trace_id: "ETH-abc123def456-1701234567890"
                  options:
                    include_raw: false
                    depth: 6
      responses:
        '200':
          description: CoRIx tree generated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CoRIxResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/TraceNotFound'
        '429':
          $ref: '#/components/responses/RateLimited'

  /traces:
    post:
      tags: [Traces]
      summary: Store a new trace
      description: Store telemetry data as a new ΔSUM trace. Returns generated trace_id.
      operationId: createTrace
      security:
        - BearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TraceInput'
            examples:
              lowRisk:
                summary: Low risk trace
                value:
                  system_source: "FactPulse Pro"
                  risk_score: 15
                  risk_level: "LOW"
                  confidence: 0.92
                  flags: []
                  recommendation: "Content appears within acceptable parameters"
                  constitutional_compliance: true
              highRisk:
                summary: High risk trace
                value:
                  system_source: "FactPulse Pro"
                  risk_score: 75
                  risk_level: "HIGH"
                  confidence: 0.68
                  flags: ["Confabulation detected", "Source missing", "Manipulation indicators"]
                  recommendation: "Manual review required"
                  constitutional_compliance: false
                  adversarial_test: true
      responses:
        '201':
          description: Trace created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TraceCreatedResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'

    get:
      tags: [Traces]
      summary: List traces
      description: List traces with optional filtering by system source and risk level.
      operationId: listTraces
      security:
        - BearerAuth: []
      parameters:
        - name: system_source
          in: query
          schema:
            type: string
          description: Filter by system source
        - name: risk_level
          in: query
          schema:
            type: string
            enum: [LOW, MEDIUM, HIGH]
          description: Filter by risk level
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 1000
            default: 100
          description: Maximum number of results
        - name: offset
          in: query
          schema:
            type: integer
            minimum: 0
            default: 0
          description: Number of results to skip
      responses:
        '200':
          description: List of traces
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TraceListResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /traces/{trace_id}:
    get:
      tags: [Traces]
      summary: Get a specific trace
      description: Retrieve a single trace by its ID.
      operationId: getTrace
      security:
        - BearerAuth: []
      parameters:
        - name: trace_id
          in: path
          required: true
          schema:
            type: string
            pattern: ^ETH-[a-zA-Z0-9]+-[0-9]+$
          description: The trace ID (format ETH-{uuid}-{timestamp})
      responses:
        '200':
          description: Trace details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Trace'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/TraceNotFound'

  /stats:
    get:
      tags: [Statistics]
      summary: Get aggregate statistics
      description: Returns aggregate statistics from the ΔSUM store.
      operationId: getStatistics
      security:
        - BearerAuth: []
      responses:
        '200':
          description: Statistics
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StatisticsResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: API key authentication

  schemas:
    HealthResponse:
      type: object
      required:
        - status
        - constitutional_compliance
      properties:
        status:
          type: string
          example: healthy
        timestamp:
          type: string
          format: date-time
        version:
          type: object
          properties:
            api:
              type: string
              example: "1.0"
            deltasum:
              type: string
              example: "1.0"
            corix:
              type: string
              example: "1.0"
        constitutional_compliance:
          type: boolean
          example: true

    SchemaResponse:
      type: object
      properties:
        schema_version:
          type: string
          example: "NIST ARIA 0.1"
        corix_version:
          type: string
          example: "1.0"
        levels:
          type: object
          additionalProperties:
            type: object
            properties:
              name:
                type: string
              purpose:
                type: string

    GenerateRequest:
      type: object
      required:
        - trace_id
      properties:
        trace_id:
          type: string
          pattern: ^ETH-[a-zA-Z0-9]+-[0-9]+$
          description: The ΔSUM trace ID
          example: "ETH-abc123def456-1701234567890"
        options:
          type: object
          properties:
            include_raw:
              type: boolean
              default: true
              description: Include raw data in Level 6
            depth:
              type: integer
              minimum: 1
              maximum: 6
              default: 6
              description: Number of levels to generate

    CoRIxResponse:
      type: object
      properties:
        corix_tree:
          $ref: '#/components/schemas/CoRIxTree'
        metadata:
          type: object
          properties:
            trace_id:
              type: string
            generated_at:
              type: string
              format: date-time
            validity_score:
              type: number
              minimum: 0
              maximum: 100
            schema_version:
              type: string

    CoRIxTree:
      type: object
      properties:
        level_1:
          type: object
          description: Interpret & Contextualize
          properties:
            interpretation:
              type: object
            summary:
              type: object
        level_2:
          type: object
          description: Risks — Validity & Reliability
          properties:
            validity:
              type: object
            reliability:
              type: object
            risks:
              type: object
        level_3:
          type: object
          description: Testing Level
          properties:
            test_category:
              type: string
              enum: [model, red_team, field]
            trinity_layer:
              type: string
        level_4:
          type: object
          description: Annotator Responses & User Perception
          properties:
            annotations:
              type: object
              properties:
                response_quality:
                  type: object
                appropriateness:
                  type: object
                factuality:
                  type: object
                safety:
                  type: object
                user_experience:
                  type: object
        level_5:
          type: object
          description: Response Collation
          properties:
            aggregated_measurements:
              type: object
            flag_summary:
              type: object
            temporal_metrics:
              type: object
        level_6:
          type: object
          description: Raw Data
          properties:
            telemetry:
              type: object
            constitutional_compliance:
              type: object
            system_telemetry:
              type: object

    TraceInput:
      type: object
      required:
        - risk_score
        - risk_level
        - confidence
      properties:
        system_source:
          type: string
          default: "unknown"
        risk_score:
          type: number
          minimum: 0
          maximum: 100
        risk_level:
          type: string
          enum: [LOW, MEDIUM, HIGH]
        confidence:
          type: number
          minimum: 0
          maximum: 1
        flags:
          type: array
          items:
            type: string
        recommendation:
          type: string
        constitutional_compliance:
          type: boolean
          default: true
        trinity_layer:
          type: string
        testing_mode:
          type: string
          enum: [model, red_team, field]
        adversarial_test:
          type: boolean
        field_conditions:
          type: boolean
        processing_time_ms:
          type: integer
        metadata:
          type: object

    Trace:
      allOf:
        - $ref: '#/components/schemas/TraceInput'
        - type: object
          properties:
            trace_id:
              type: string
            attribution_token:
              type: string
            timestamp:
              type: string
              format: date-time
            created_at:
              type: string
              format: date-time

    TraceCreatedResponse:
      type: object
      properties:
        trace_id:
          type: string
          example: "ETH-abc123def456-1701234567890"
        message:
          type: string
          example: "Trace stored successfully"

    TraceListResponse:
      type: object
      properties:
        traces:
          type: array
          items:
            $ref: '#/components/schemas/Trace'
        total:
          type: integer
        limit:
          type: integer
        offset:
          type: integer

    StatisticsResponse:
      type: object
      properties:
        total_traces:
          type: integer
        unique_systems:
          type: integer
        average_risk_score:
          type: number
        compliant_count:
          type: integer
        non_compliant_count:
          type: integer
        risk_distribution:
          type: object
          properties:
            LOW:
              type: integer
            MEDIUM:
              type: integer
            HIGH:
              type: integer
        average_processing_time_ms:
          type: number

    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: string
            message:
              type: string
            details:
              type: object

  responses:
    BadRequest:
      description: Invalid request
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: INVALID_REQUEST
              message: "Missing required field: risk_score"

    Unauthorized:
      description: Missing or invalid authentication
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: INVALID_API_KEY
              message: "Invalid API key"

    TraceNotFound:
      description: Trace not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: TRACE_NOT_FOUND
              message: "Trace ETH-xxx-123 not found"

    RateLimited:
      description: Rate limit exceeded
      headers:
        Retry-After:
          schema:
            type: integer
          description: Seconds until rate limit resets
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: RATE_LIMIT_EXCEEDED
              message: "Rate limit exceeded. Retry after 60 seconds."
