openapi: 3.1.0
info:
  title: Risotto Public API
  version: 1.0.0
  description: |
    The Risotto Public API provides programmatic access to manage tickets and workflows.

    ## Authentication

    All API requests require authentication using an API key. You can obtain an API key from
    the Risotto dashboard under Settings > API > Keys.

    Include your API key in requests using one of these methods:
    - **X-API-Key header**: `X-API-Key: rso_live_...`
    - **Authorization header**: `Authorization: Bearer rso_live_...`

    ## Rate Limiting

    API requests are rate limited per organization. The default limit is 1000 requests per hour.
    Rate limit information is included in response headers:
    - `X-RateLimit-Limit`: Maximum requests allowed per hour
    - `X-RateLimit-Remaining`: Remaining requests in the current window
    - `X-RateLimit-Reset`: Unix timestamp when the rate limit resets

    ## Pagination

    List endpoints support pagination using `limit` and `offset` query parameters.
    Responses include pagination metadata:
    - `count`: Total number of items
    - `next`: URL for the next page (null if no more pages)
    - `previous`: URL for the previous page (null if on first page)

    ## Error Handling

    The API uses standard HTTP status codes and returns errors in a consistent format.
    See the Error schema for details.

    ## Webhooks

    Risotto can POST events to an HTTPS endpoint you register in the dashboard
    (Settings > API > Webhooks). Every delivery is a signed JSON envelope:

    ```
    { "id": "<uuid>", "type": "<event>", "created_at": "<iso8601>", "data": { ... } }
    ```

    `data` is the affected resource in the same shape the REST API returns it.
    See the **Webhooks** section below for each event's payload.

    Every delivery carries three headers:
    - `Webhook-Id`: the event `id` — stable across retries, so use it to dedupe
    - `Webhook-Timestamp`: Unix timestamp of the delivery
    - `Webhook-Signature`: `v1,<base64 HMAC-SHA256>`

    **Verifying the signature.** Compute HMAC-SHA256 over
    `{id}.{timestamp}.{raw-body}` keyed by your endpoint's signing secret
    (shown once at creation, prefixed `whsec_`), base64-encode it, and compare
    against the value after `v1,` in `Webhook-Signature`. Sign the exact bytes
    you received, before any parsing.

    **Retries.** A delivery that doesn't return a 2xx within 10 seconds is
    retried on a fixed backoff (5s, 5m, 30m, 2h, 5h, 10h, 10h) spanning roughly
    a day, then marked failed. An endpoint that fails continuously for 3 days is
    auto-disabled and its admins are notified.
  contact:
    name: Risotto Support
    url: https://tryrisotto.com/support
    email: support@tryrisotto.com
  license:
    name: Proprietary
    url: https://tryrisotto.com/terms

servers:
  - url: /v1

tags:
  - name: tickets
    description: Operations for managing IT tickets
  - name: comments
    description: Operations for managing ticket comments
  - name: departments
    description: Operations for listing departments
  - name: runbooks
    description: Operations for managing runbooks (CRUD, history, duplication)
  - name: audit
    description: Read the organization audit log (e.g. for SIEM ingestion)
  - name: webhooks
    description: Outbound event payloads Risotto POSTs to your registered endpoints

security:
  - ApiKeyAuth: []
  - BearerAuth: []

paths:
  /audit-events:
    get:
      summary: List audit-log events
      description: |
        Retrieve a paginated list of organization configuration-change audit
        events. Designed for streaming the Risotto audit trail into a SIEM
        (such as Panther): poll with `created_after=<last_seen>` plus
        `ordering=created` to fetch new events incrementally. `created_after`
        is inclusive (at-least-once delivery, so no event is ever dropped at a
        timestamp boundary) — dedupe by event `id` when advancing the window.
        Results carry a stable `id` tiebreaker so pagination is deterministic
        even when events share a timestamp.

        Each event includes the acting user and a short `summary` of what
        changed. Pass `include_changes=true` to also receive the full
        field-level before/after diff in `changes`.
      operationId: listAuditEvents
      tags:
        - audit
      parameters:
        - $ref: "#/components/parameters/LimitParam"
        - $ref: "#/components/parameters/OffsetParam"
        - name: event
          in: query
          required: false
          description: Filter by exact event key (e.g. `org_runbook_updated`).
          schema:
            type: string
        - name: created_after
          in: query
          required: false
          description: |
            Filter to events created at or after this timestamp (ISO 8601,
            inclusive). The inclusive bound means events sharing the boundary
            timestamp are never dropped, making incremental polling
            at-least-once — dedupe by event `id` when advancing the window.
          schema:
            type: string
            format: date-time
        - name: created_before
          in: query
          required: false
          description: Filter to events created before this timestamp (ISO 8601 format).
          schema:
            type: string
            format: date-time
        - name: ordering
          in: query
          required: false
          description: |
            Sort order by creation time. Use `created` for oldest-first
            (recommended for incremental polling) or `-created` for
            newest-first.
          schema:
            type: string
            enum:
              - created
              - -created
            default: "-created"
        - name: include_changes
          in: query
          required: false
          description: |
            Include the full field-level before/after diff for each event.
            Defaults to false to keep the payload lightweight.
          schema:
            type: boolean
            default: false
      responses:
        "200":
          description: Successful response with paginated list of audit events
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AuditEventListResponse"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /departments:
    get:
      summary: List departments
      description: |
        Retrieve a paginated list of departments for your organization.
        Results are ordered alphabetically by name.
      operationId: listDepartments
      tags:
        - departments
      parameters:
        - $ref: "#/components/parameters/LimitParam"
        - $ref: "#/components/parameters/OffsetParam"
      responses:
        "200":
          description: Successful response with paginated list of departments
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DepartmentListResponse"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /tickets:
    get:
      summary: List tickets
      description: |
        Retrieve a paginated list of tickets for your organization.
        Results can be filtered by status, department, requestor, assignee, and date ranges.
      operationId: listTickets
      tags:
        - tickets
      parameters:
        - $ref: "#/components/parameters/LimitParam"
        - $ref: "#/components/parameters/OffsetParam"
        - $ref: "#/components/parameters/StatusFilter"
        - $ref: "#/components/parameters/DeptIdFilter"
        - $ref: "#/components/parameters/RequestorEmailFilter"
        - $ref: "#/components/parameters/AssigneeEmailFilter"
        - $ref: "#/components/parameters/CreatedAfterFilter"
        - $ref: "#/components/parameters/CreatedBeforeFilter"
        - $ref: "#/components/parameters/ModifiedAfterFilter"
        - $ref: "#/components/parameters/ModifiedBeforeFilter"
        - $ref: "#/components/parameters/OrderingParam"
        - $ref: "#/components/parameters/IncludeDeletedFilter"
      responses:
        "200":
          description: Successful response with paginated list of tickets
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TicketListResponse"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      summary: Create a ticket
      description: |
        Create a new ticket in your organization. The requestor is identified by
        their email address and is created automatically if they don't already
        exist.

        The response contains the full ticket, including its comments and, when
        your workspace is connected to an external ticketing system (such as
        Jira), the linked `external_ticket_id` and `external_ticket_url`. These
        reference fields are usually returned right away, but can be `null` if
        your workspace isn't set up to create an external ticket for this
        request, or if the external system couldn't be reached in time. When
        they're `null`, fetch the ticket again with `GET /tickets/{ticket_id}`
        to retrieve them once they become available.
      operationId: createTicket
      tags:
        - tickets
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TicketCreate"
      responses:
        "201":
          description: Ticket created successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TicketDetail"
          headers:
            Idempotency-Key:
              $ref: "#/components/headers/Idempotency-Key"
            Idempotency-Replayed:
              $ref: "#/components/headers/Idempotency-Replayed"
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          $ref: "#/components/responses/IdempotencyConflict"
        "422":
          $ref: "#/components/responses/UnprocessableEntity"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /tickets/{ticket_id}:
    get:
      summary: Get a ticket
      description: Retrieve details of a specific ticket by its ticket ID (e.g., "IT-123").
      operationId: getTicket
      tags:
        - tickets
      parameters:
        - $ref: "#/components/parameters/TicketIdPath"
      responses:
        "200":
          description: Successful response with ticket details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TicketDetail"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      summary: Update a ticket
      description: |
        Update an existing ticket. Only provided fields will be updated.

        **Status Transitions**:
        - `open` can transition to: `in_progress`, `paused`, `resolved`, `closed`
        - `in_progress` can transition to: `paused`, `resolved`, `closed`, `waiting_for_response`, `waiting_for_support`
        - `waiting_for_response` can transition to: `open`, `in_progress`, `resolved`, `closed`
        - `waiting_for_support` can transition to: `in_progress`, `resolved`, `closed`
        - `waiting_for_approval` can transition to: `resolved`, `closed`
        - `paused` can transition to: `open`, `in_progress`, `resolved`, `closed`
        - `resolved` can transition to: `open` (reopen), `closed`
        - `closed` cannot transition to any other status via API

        `waiting_for_approval` reflects an inflight approval flow. It is set
        only by internal approval processes and cannot be set via the API. A
        ticket holding it may only be closed out (`resolved` or `closed`,
        which ends the approval); any other move is reserved for the
        approval flow.
      operationId: updateTicket
      tags:
        - tickets
      parameters:
        - $ref: "#/components/parameters/TicketIdPath"
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TicketUpdate"
      responses:
        "200":
          description: Ticket updated successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Ticket"
          headers:
            Idempotency-Key:
              $ref: "#/components/headers/Idempotency-Key"
            Idempotency-Replayed:
              $ref: "#/components/headers/Idempotency-Replayed"
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/IdempotencyConflict"
        "422":
          $ref: "#/components/responses/UnprocessableEntity"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      summary: Delete a ticket
      description: |
        Delete a ticket. Deleted tickets are excluded from list results by default.
      operationId: deleteTicket
      tags:
        - tickets
      parameters:
        - $ref: "#/components/parameters/TicketIdPath"
      responses:
        "204":
          description: Ticket deleted successfully
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /tickets/{ticket_id}/comments:
    get:
      summary: List ticket comments
      description: |
        Retrieve a paginated list of comments for a specific ticket.
        Internal comments are excluded by default unless `include_internal=true` is specified.
      operationId: listTicketComments
      tags:
        - comments
      parameters:
        - $ref: "#/components/parameters/TicketIdPath"
        - $ref: "#/components/parameters/LimitParam"
        - $ref: "#/components/parameters/OffsetParam"
        - name: include_internal
          in: query
          description: Include internal comments in the response
          schema:
            type: boolean
            default: false
      responses:
        "200":
          description: Successful response with paginated list of comments
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CommentListResponse"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      summary: Add a comment
      description: Add a new comment to a ticket.
      operationId: createTicketComment
      tags:
        - comments
      parameters:
        - $ref: "#/components/parameters/TicketIdPath"
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CommentCreate"
      responses:
        "201":
          description: Comment created successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Comment"
          headers:
            Idempotency-Key:
              $ref: "#/components/headers/Idempotency-Key"
            Idempotency-Replayed:
              $ref: "#/components/headers/Idempotency-Replayed"
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/IdempotencyConflict"
        "422":
          $ref: "#/components/responses/UnprocessableEntity"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /tickets/{ticket_id}/runbooks:
    get:
      summary: List a ticket's runbook history
      description: |
        Return the runbook history for a ticket — every runbook that was
        matched against this ticket, in creation order. `applied_at` is
        null for rows the agent matched but did not act on, and populated
        with a timestamp + `reason` for rows the agent followed.
      operationId: listTicketRunbookHistory
      tags:
        - runbooks
      parameters:
        - $ref: "#/components/parameters/TicketIdPath"
      responses:
        "200":
          description: Successful response with the ticket's runbook history
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/TicketRunbookHistoryRow"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /runbooks:
    get:
      summary: List runbooks
      description: |
        Retrieve a paginated list of runbooks for your organization, with
        filtering and ordering.
      operationId: listRunbooks
      tags:
        - runbooks
      parameters:
        - $ref: "#/components/parameters/LimitParam"
        - $ref: "#/components/parameters/OffsetParam"
        - $ref: "#/components/parameters/RunbookSearchFilter"
        - $ref: "#/components/parameters/RunbookEnabledFilter"
        - $ref: "#/components/parameters/RunbookMatchTypeFilter"
        - $ref: "#/components/parameters/DeptIdFilter"
        - $ref: "#/components/parameters/RunbookOrderingParam"
      responses:
        "200":
          description: Successful response with paginated list of runbooks
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RunbookListResponse"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      summary: Create a runbook
      description: |
        Create a new runbook. Triggers indexing when `enabled=true` and
        `match_type="semantic"`. Department-matched runbooks require
        `dept_id` and conflict with any other enabled department-matched
        runbook on the same department.
      operationId: createRunbook
      tags:
        - runbooks
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RunbookCreate"
      responses:
        "201":
          description: Runbook created successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Runbook"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /runbooks/{runbook_id}:
    get:
      summary: Get a runbook
      description: Retrieve a runbook's current version by UUID.
      operationId: getRunbook
      tags:
        - runbooks
      parameters:
        - $ref: "#/components/parameters/RunbookIdPath"
      responses:
        "200":
          description: Successful response with runbook details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Runbook"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      summary: Update a runbook
      description: |
        Partial update. Only provided fields are changed. Pass
        `?confirm_enable=true` to bypass the 409 returned when enabling
        a duplicated runbook whose department + conditions still match
        the source.
      operationId: updateRunbook
      tags:
        - runbooks
      parameters:
        - $ref: "#/components/parameters/RunbookIdPath"
        - name: confirm_enable
          in: query
          required: false
          description: |
            When set to `true`, bypasses the 409 conflict raised when
            enabling a duplicated runbook whose department and
            conditions still match the source runbook.
          schema:
            type: boolean
            default: false
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RunbookUpdate"
      responses:
        "200":
          description: Runbook updated successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Runbook"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          description: |
            Enabling a duplicated runbook whose department + conditions
            still match the source. Resubmit with `?confirm_enable=true`
            to override.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
          headers:
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      summary: Delete a runbook
      description: |
        Soft-delete a runbook. The version history remains available via
        the `versions` sub-resource.
      operationId: deleteRunbook
      tags:
        - runbooks
      parameters:
        - $ref: "#/components/parameters/RunbookIdPath"
      responses:
        "204":
          description: Runbook deleted successfully
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /runbooks/{runbook_id}/versions:
    get:
      summary: List runbook revisions
      description: |
        Return every version of a runbook, newest first. Includes
        soft-deleted prior versions so callers can inspect the audit
        trail.
      operationId: listRunbookVersions
      tags:
        - runbooks
      parameters:
        - $ref: "#/components/parameters/RunbookIdPath"
      responses:
        "200":
          description: Successful response with the runbook's version history
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/RunbookRevision"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

  /runbooks/{runbook_id}/duplicate:
    post:
      summary: Duplicate a runbook
      description: |
        Create a copy of an existing runbook. The copy starts disabled
        with a ` (Copy)`-suffixed title and `duplicated_from_runbook_id`
        set to the source's `runbook_id`.
      operationId: duplicateRunbook
      tags:
        - runbooks
      parameters:
        - $ref: "#/components/parameters/RunbookIdPath"
      responses:
        "201":
          description: Runbook duplicated successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Runbook"
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
            X-Request-ID:
              $ref: "#/components/headers/X-Request-ID"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/InternalError"

webhooks:
  ticket.created:
    post:
      summary: Ticket created
      description: |
        Sent when a new ticket is created. `data` is the full ticket,
        identical to the `GET /tickets/{ticket_id}` response.
      operationId: webhookTicketCreated
      tags:
        - webhooks
      requestBody:
        description: Signed event envelope.
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - type: object
                  properties:
                    type:
                      const: ticket.created
                    data:
                      $ref: "#/components/schemas/TicketDetail"
            examples:
              default:
                $ref: "#/components/examples/TicketCreatedEvent"
      responses:
        "2XX":
          description: |
            Return any 2xx to acknowledge receipt. A non-2xx response (or no
            response within 10 seconds) is retried on the schedule described
            above.
  ticket.escalated:
    post:
      summary: Ticket escalated
      description: |
        Sent when a ticket is escalated to human support — by the agent, an
        API caller, or a dashboard user. `data` is the full ticket (identical
        to the `GET /tickets/{ticket_id}` response) plus `escalated_at` and
        the escalation `reason`.
      operationId: webhookTicketEscalated
      tags:
        - webhooks
      requestBody:
        description: Signed event envelope.
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - type: object
                  properties:
                    type:
                      const: ticket.escalated
                    data:
                      $ref: "#/components/schemas/TicketEscalatedEvent"
            examples:
              default:
                $ref: "#/components/examples/TicketEscalatedEvent"
      responses:
        "2XX":
          description: Return any 2xx to acknowledge receipt.
  ticket.closed:
    post:
      summary: Ticket closed
      description: |
        Sent once when a ticket reaches a terminal state. `data` is the full
        ticket (identical to the `GET /tickets/{ticket_id}` response) plus
        `closure_state`, which says how it closed: `resolved` (the request
        was fulfilled), `closed` (closed without resolution, including
        duplicates), or `canceled` (the requestor withdrew it).
      operationId: webhookTicketClosed
      tags:
        - webhooks
      requestBody:
        description: Signed event envelope.
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - type: object
                  properties:
                    type:
                      const: ticket.closed
                    data:
                      $ref: "#/components/schemas/TicketClosedEvent"
            examples:
              default:
                $ref: "#/components/examples/TicketClosedEvent"
      responses:
        "2XX":
          description: Return any 2xx to acknowledge receipt.
  comment.added:
    post:
      summary: Comment added
      description: |
        Sent when a public comment is added to a ticket. Internal notes are
        never delivered. `data` extends the comment resource with the parent
        `ticket_id` and `department` so it can be correlated to its ticket
        without a follow-up request.
      operationId: webhookCommentAdded
      tags:
        - webhooks
      requestBody:
        description: Signed event envelope.
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - type: object
                  properties:
                    type:
                      const: comment.added
                    data:
                      $ref: "#/components/schemas/CommentEvent"
            examples:
              default:
                $ref: "#/components/examples/CommentAddedEvent"
      responses:
        "2XX":
          description: Return any 2xx to acknowledge receipt.
  access.requests.completed:
    post:
      summary: Access requests completed
      description: |
        Sent once per ticket when every access request on it has reached a
        terminal state. Batches all requests on the ticket into a single event
        — built for SIEM and access auditing. `granted` means the access was
        actually provisioned, not merely approved.
      operationId: webhookAccessRequestsCompleted
      tags:
        - webhooks
      requestBody:
        description: Signed event envelope.
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WebhookEnvelope"
                - type: object
                  properties:
                    type:
                      const: access.requests.completed
                    data:
                      $ref: "#/components/schemas/AccessRequestsCompletedPayload"
            examples:
              default:
                $ref: "#/components/examples/AccessRequestsCompletedEvent"
      responses:
        "2XX":
          description: Return any 2xx to acknowledge receipt.

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: |
        API key with format `rso_...`.
        Obtain your API key from the Risotto dashboard under Settings > API > Keys.
    BearerAuth:
      type: http
      scheme: bearer
      description: |
        API key as Bearer token. Use the same API key format as X-API-Key.
        Example: `Authorization: Bearer rso_...`

  headers:
    X-RateLimit-Limit:
      description: Maximum number of requests allowed per hour
      schema:
        type: integer
        example: 1000
    X-RateLimit-Remaining:
      description: Number of requests remaining in the current rate limit window
      schema:
        type: integer
        example: 999
    X-RateLimit-Reset:
      description: Unix timestamp when the rate limit window resets
      schema:
        type: integer
        example: 1704067200
    X-Request-ID:
      description: Unique identifier for this request, useful for debugging
      schema:
        type: string
        format: uuid
        example: "550e8400-e29b-41d4-a716-446655440000"
    Idempotency-Key:
      description: Echo of the client-provided idempotency key
      schema:
        type: string
        example: "req_abc123"
    Idempotency-Replayed:
      description: Indicates this response was replayed from a previous request
      schema:
        type: string
        enum: ["true"]
        example: "true"

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: |
        Optional idempotency key for safe retries of write operations.
        If provided, the server caches the response and returns it for
        subsequent requests with the same key and API key within 24 hours.
        Must be at most 255 characters. UUIDs are recommended.
      schema:
        type: string
        maxLength: 255
      examples:
        empty:
          value: ""
          summary: "No idempotency key"
        uuid:
          value: "550e8400-e29b-41d4-a716-446655440000"
          summary: "Example UUID"
    TicketIdPath:
      name: ticket_id
      in: path
      required: true
      description: |
        The ticket identifier in PREFIX-NUMBER format (e.g., "IT-123", "HR-456").
        The prefix is determined by the department configuration.
      schema:
        type: string
        pattern: '^[A-Z]+(?:-[A-Z]+)*-\d+$'
        example: "IT-123"
    LimitParam:
      name: limit
      in: query
      description: Maximum number of items to return per page
      schema:
        type: integer
        default: 50
        minimum: 1
        maximum: 100
    OffsetParam:
      name: offset
      in: query
      description: Number of items to skip before starting to return results
      schema:
        type: integer
        default: 0
        minimum: 0
    StatusFilter:
      name: status
      in: query
      description: |
        Filter by ticket status. Can be a single status or comma-separated list.
        Example: `status=open` or `status=open,in_progress`
      schema:
        type: string
    DeptIdFilter:
      name: dept_id
      in: query
      description: Filter by department UUID
      schema:
        type: string
        format: uuid
    RequestorEmailFilter:
      name: requestor_email
      in: query
      description: Filter by requestor's email address
      schema:
        type: string
        format: email
    AssigneeEmailFilter:
      name: assignee_email
      in: query
      description: Filter by assignee's email address
      schema:
        type: string
        format: email
    CreatedAfterFilter:
      name: created_after
      in: query
      description: Filter tickets created after this timestamp (ISO 8601 format)
      schema:
        type: string
        format: date-time
    CreatedBeforeFilter:
      name: created_before
      in: query
      description: Filter tickets created before this timestamp (ISO 8601 format)
      schema:
        type: string
        format: date-time
    ModifiedAfterFilter:
      name: modified_after
      in: query
      description: Filter tickets modified after this timestamp (ISO 8601 format)
      schema:
        type: string
        format: date-time
    ModifiedBeforeFilter:
      name: modified_before
      in: query
      description: Filter tickets modified before this timestamp (ISO 8601 format)
      schema:
        type: string
        format: date-time
    OrderingParam:
      name: ordering
      in: query
      description: |
        Field to sort results by. Prefix with `-` for descending order.
        Example: `ordering=-created` for newest first.
      schema:
        type: string
        enum:
          - created
          - -created
          - modified
          - -modified
        default: "-created"
    IncludeDeletedFilter:
      name: include_deleted
      in: query
      required: false
      description: Include deleted tickets in results.
      schema:
        type: boolean
        default: false
    RunbookIdPath:
      name: runbook_id
      in: path
      required: true
      description: The runbook's UUID.
      schema:
        type: string
        format: uuid
    RunbookSearchFilter:
      name: search
      in: query
      required: false
      description: |
        Substring matched against `title`, `conditions`, and `content`
        (case-insensitive).
      schema:
        type: string
    RunbookEnabledFilter:
      name: enabled
      in: query
      required: false
      description: Filter to enabled (`true`) or disabled (`false`) runbooks.
      schema:
        type: boolean
    RunbookMatchTypeFilter:
      name: match_type
      in: query
      required: false
      description: Filter by match type.
      schema:
        type: string
        enum:
          - semantic
          - department
          - system
    RunbookOrderingParam:
      name: ordering
      in: query
      required: false
      description: |
        Field to sort runbooks by. Prefix with `-` for descending order.
      schema:
        type: string
        enum:
          - title
          - -title
          - created
          - -created
          - dept__name
          - -dept__name
        default: "-created"

  examples:
    TicketCreatedEvent:
      summary: ticket.created
      value:
        id: "018f9a3c-1b2c-7def-8000-0000000000a1"
        type: ticket.created
        created_at: "2024-01-15T09:30:00Z"
        data:
          ticket_id: "IT-123"
          title: "Cannot access shared drive"
          request_text: "I'm unable to access the marketing shared drive since this morning."
          status: "open"
          source: "slack"
          requestor:
            email: "jane.doe@company.com"
            name: "Jane Doe"
          assignee: null
          department:
            id: "660e8400-e29b-41d4-a716-446655440000"
            name: "IT Support"
            ticket_prefix: "IT"
          tags: []
          created: "2024-01-15T09:30:00Z"
          modified: "2024-01-15T09:30:00Z"
          resolved_at: null
          comments: []
          external_ticket_id: null
          external_ticket_url: null
          message_url: "https://company.slack.com/archives/C123/p1705311000000000"
    TicketEscalatedEvent:
      summary: ticket.escalated
      value:
        id: "018f9a3c-4e5f-7abc-8000-0000000000d4"
        type: ticket.escalated
        created_at: "2024-01-15T09:45:00Z"
        data:
          ticket_id: "IT-123"
          title: "Cannot access shared drive"
          request_text: "I'm unable to access the marketing shared drive since this morning."
          status: "waiting_for_support"
          source: "slack"
          requestor:
            email: "jane.doe@company.com"
            name: "Jane Doe"
          assignee:
            email: "it.admin@company.com"
            name: "IT Admin"
          department:
            id: "660e8400-e29b-41d4-a716-446655440000"
            name: "IT Support"
            ticket_prefix: "IT"
          tags:
            - "Escalated"
          created: "2024-01-15T09:30:00Z"
          modified: "2024-01-15T09:45:00Z"
          resolved_at: null
          comments:
            - content: "I'm unable to access the marketing shared drive since this morning."
              author_name: "Jane Doe"
              author_email: "jane.doe@company.com"
              is_internal: false
              source: "slack"
              created: "2024-01-15T09:30:00Z"
          external_ticket_id: null
          external_ticket_url: null
          message_url: "https://company.slack.com/archives/C123/p1705311000000000"
          escalated_at: "2024-01-15T09:45:00Z"
          reason: "Requestor needs drive permissions no runbook covers."
    TicketClosedEvent:
      summary: ticket.closed
      value:
        id: "018f9a3c-5f6a-7bcd-8000-0000000000e5"
        type: ticket.closed
        created_at: "2024-01-15T11:00:00Z"
        data:
          ticket_id: "IT-123"
          title: "Cannot access shared drive"
          request_text: "I'm unable to access the marketing shared drive since this morning."
          status: "resolved"
          source: "slack"
          requestor:
            email: "jane.doe@company.com"
            name: "Jane Doe"
          assignee: null
          department:
            id: "660e8400-e29b-41d4-a716-446655440000"
            name: "IT Support"
            ticket_prefix: "IT"
          tags:
            - "Auto-Solved"
          created: "2024-01-15T09:30:00Z"
          modified: "2024-01-15T11:00:00Z"
          resolved_at: "2024-01-15T11:00:00Z"
          comments:
            - content: "I'm unable to access the marketing shared drive since this morning."
              author_name: "Jane Doe"
              author_email: "jane.doe@company.com"
              is_internal: false
              source: "slack"
              created: "2024-01-15T09:30:00Z"
            - content: "You've been added to the marketing drive group. Please try again."
              author_name: "Risotto"
              author_email: null
              is_internal: false
              source: "risotto"
              created: "2024-01-15T11:00:00Z"
          external_ticket_id: null
          external_ticket_url: null
          message_url: "https://company.slack.com/archives/C123/p1705311000000000"
          closure_state: "resolved"
    CommentAddedEvent:
      summary: comment.added
      value:
        id: "018f9a3c-2c3d-7abc-8000-0000000000b2"
        type: comment.added
        created_at: "2024-01-15T10:30:00Z"
        data:
          content: "I've reset your password. Please try logging in again."
          author_name: "IT Support"
          author_email: "it.support@company.com"
          is_internal: false
          source: "risotto"
          created: "2024-01-15T10:30:00Z"
          ticket_id: "IT-123"
          department:
            id: "660e8400-e29b-41d4-a716-446655440000"
            name: "IT Support"
            ticket_prefix: "IT"
    AccessRequestsCompletedEvent:
      summary: access.requests.completed
      value:
        id: "018f9a3c-3d4e-7def-8000-0000000000c3"
        type: access.requests.completed
        created_at: "2024-01-15T14:30:00Z"
        data:
          ticket_id: "IT-124"
          requestor:
            email: "jane.doe@company.com"
            name: "Jane Doe"
          completed_at: "2024-01-15T14:30:00Z"
          requests:
            - workflow_id: 90210
              workflow_uuid: "019a3b2c-1d4e-7f00-8a00-000000090210"
              software: "Salesforce"
              status: "granted"
              grantee:
                email: "jane.doe@company.com"
                name: "Jane Doe"
              reason: "Need read-only access for my new role."
              resolved_at: "2024-01-15T14:29:00Z"
              expires_at: "2024-02-15T14:29:00Z"
              granted_by_email: "it.admin@company.com"
              access_rule:
                rule_id: "7c9e6679-7425-40de-944b-e07fc1f90ae7"
                software_name: "Salesforce"
                app_id: "550e8400-e29b-41d4-a716-446655440000"
                app_name: "Salesforce (Production)"
            - workflow_id: 90211
              workflow_uuid: "019a3b2c-1d4e-7f00-8a00-000000090211"
              software: "GitHub"
              status: "denied"
              grantee:
                email: "jane.doe@company.com"
                name: "Jane Doe"
              reason: "Requested admin role."
              resolved_at: "2024-01-15T14:30:00Z"
              expires_at: null
              granted_by_email: null
              access_rule:
                rule_id: "8d0f7780-8536-51ef-a55c-f18fd2f01bf8"
                software_name: "GitHub"
                app_id: null
                app_name: null

  schemas:
    # Ticket Schemas
    Ticket:
      type: object
      description: A ticket representing an IT request or issue
      required:
        - ticket_id
        - title
        - request_text
        - status
        - source
        - created
        - modified
        - department
      properties:
        ticket_id:
          type: string
          description: Human-readable ticket identifier in PREFIX-NUMBER format
          pattern: '^[A-Z]+(?:-[A-Z]+)*-\d+$'
          example: "IT-123"
        title:
          type: string
          description: Brief summary of the ticket
          maxLength: 100
          example: "Cannot access shared drive"
        request_text:
          type: string
          description: Original request text from the ticket
          example: "I'm unable to access the marketing shared drive since this morning."
        status:
          $ref: "#/components/schemas/TicketStatus"
        source:
          type: string
          description: Origin of the ticket
          enum:
            - api
            - slack
            - email
            - jira
            - dashboard
            - zendesk
            - airtable
            - freshsrv
            - servicenow
            - msteams
            - risotto
          example: "api"
        created:
          type: string
          format: date-time
          description: Timestamp when the ticket was created
          example: "2024-01-15T09:30:00Z"
        modified:
          type: string
          format: date-time
          description: Timestamp when the ticket was last modified
          example: "2024-01-15T10:45:00Z"
        resolved_at:
          type: string
          format: date-time
          nullable: true
          description: Timestamp when the ticket was resolved (null if not resolved)
          example: "2024-01-15T14:30:00Z"
        deleted_at:
          type: string
          format: date-time
          nullable: true
          description: Timestamp when the ticket was deleted (null if not deleted). Only present when include_deleted=true.
          example: "2024-01-16T08:00:00Z"
        requestor:
          $ref: "#/components/schemas/UserSummary"
        assignee:
          allOf:
            - $ref: "#/components/schemas/UserSummary"
          nullable: true
          description: The user assigned to handle this ticket (null if unassigned)
        department:
          $ref: "#/components/schemas/DepartmentSummary"
        category:
          allOf:
            - $ref: "#/components/schemas/CategorySummary"
          nullable: true
          description: Effective category of this ticket (confirmed or AI-suggested, null if neither)
        priority:
          allOf:
            - $ref: "#/components/schemas/PrioritySummary"
          nullable: true
          description: Effective priority of this ticket (human-set or AI-suggested, null if neither)
        tags:
          type: array
          description: List of tags applied to this ticket
          items:
            type: string
          example: ["Escalated", "Knowledge"]

    TicketDetail:
      description: Detailed ticket information including comments
      allOf:
        - $ref: "#/components/schemas/Ticket"
        - type: object
          properties:
            comments:
              type: array
              description: List of comments on this ticket (excludes internal comments by default)
              items:
                $ref: "#/components/schemas/Comment"
            external_ticket_id:
              type: string
              nullable: true
              description: ID of linked external ticket (e.g., Jira issue key)
              example: "JIRA-456"
            external_ticket_url:
              type: string
              format: uri
              nullable: true
              description: URL of linked external ticket
              example: "https://company.atlassian.net/browse/JIRA-456"
            message_url:
              type: string
              format: uri
              nullable: true
              description: URL to the original Slack thread or conversation
              example: "https://company.slack.com/archives/C123/p1234567890"

    TicketCreate:
      type: object
      description: Request body for creating a new ticket
      required:
        - request_text
        - requestor_email
      properties:
        title:
          type: string
          description: Optional title (will be auto-generated if not provided)
          maxLength: 100
          example: "Need access to Salesforce"
        request_text:
          type: string
          description: Detailed description of the request or issue (required)
          example: "I need read-only access to Salesforce to view customer data for my new role."
        requestor_email:
          type: string
          format: email
          description: Email address of the person requesting help (required)
          example: "jane.doe@company.com"
        requestor_name:
          type: string
          description: Display name of the requestor (optional)
          maxLength: 200
          example: "Jane Doe"
        dept_id:
          type: string
          format: uuid
          description: UUID of the department to assign the ticket to (will be auto-assigned if not provided)
          example: "550e8400-e29b-41d4-a716-446655440000"
        runbook_id:
          type: string
          format: uuid
          description: |
            Stable UUID of a runbook to force-match. When provided, only this
            runbook is attached and normal runbook matching is skipped. Returns
            422 if the runbook does not belong to your organization.
          example: "7c9e6679-7425-40de-944b-e07fc1f90ae7"
        assignee_email:
          type: string
          format: email
          description: Email address of the user to assign the ticket to (optional)
          example: "it.admin@company.com"
        notify_via_dm:
          type: boolean
          default: false
          description: |
            If true, send the requestor a Slack DM to continue the request over DM.
            Requires the requestor's email to map to a linked Slack identity;
            otherwise the ticket is created without a DM.
          example: false
        escalate:
          type: boolean
          default: false
          description: |
            If true, create the ticket already escalated to human support: it is
            tagged "Escalated", moves to `waiting_for_support`, and the AI agent
            is disabled so it never responds. Cannot be combined with
            `notify_via_dm`.
          example: false

    TicketUpdate:
      type: object
      description: Request body for updating an existing ticket. All fields are optional.
      properties:
        title:
          type: string
          description: Updated title
          maxLength: 100
          example: "Updated: Need access to Salesforce CRM"
        status:
          $ref: "#/components/schemas/TicketStatus"
        assignee_email:
          type: string
          format: email
          nullable: true
          description: |
            Email address of the user to assign the ticket to.
            Set to null to unassign.

    TicketStatus:
      type: string
      description: Current status of the ticket
      enum:
        - open
        - in_progress
        - waiting_for_response
        - waiting_for_support
        - waiting_for_approval
        - paused
        - resolved
        - closed
      example: "open"

    TicketListResponse:
      type: object
      description: Paginated list of tickets
      required:
        - count
        - results
      properties:
        count:
          type: integer
          description: Total number of tickets matching the query
          example: 42
        next:
          type: string
          format: uri
          nullable: true
          description: URL for the next page of results (null if no more pages)
          example: "https://api.tryrisotto.com/v1/tickets?offset=50&limit=50"
        previous:
          type: string
          format: uri
          nullable: true
          description: URL for the previous page of results (null if on first page)
          example: null
        results:
          type: array
          items:
            $ref: "#/components/schemas/Ticket"

    # Comment Schemas
    Comment:
      type: object
      description: A comment on a ticket
      required:
        - content
        - created
        - is_internal
        - source
      properties:
        content:
          type: string
          description: The comment text
          example: "I've reset your password. Please try logging in again."
        author_name:
          type: string
          nullable: true
          description: Display name of the comment author
          example: "IT Support"
        author_email:
          type: string
          format: email
          nullable: true
          description: Email address of the comment author
          example: "it.support@company.com"
        created:
          type: string
          format: date-time
          description: Timestamp when the comment was created
          example: "2024-01-15T10:30:00Z"
        is_internal:
          type: boolean
          description: Whether this is an internal note (not visible to requestor)
          example: false
        source:
          type: string
          description: Origin of the comment
          enum:
            - api
            - slack
            - email
            - jira
            - dashboard
            - zendesk
            - risotto
          example: "api"

    CommentCreate:
      type: object
      description: Request body for creating a new comment
      required:
        - content
      properties:
        content:
          type: string
          description: The comment text
          minLength: 1
          example: "I've escalated this to the security team."
        is_internal:
          type: boolean
          description: Whether this is an internal note (not visible to requestor)
          default: false
          example: true
        author_email:
          type: string
          format: email
          description: |
            Email address of the comment author.
            If not provided, the comment will be attributed to the API integration.
          example: "it.admin@company.com"
        author_name:
          type: string
          maxLength: 50
          description: |
            Display name of the comment author.
            Used when creating a new user identity.
          example: "Jane Smith"

    CommentListResponse:
      type: object
      description: Paginated list of comments
      required:
        - count
        - results
      properties:
        count:
          type: integer
          description: Total number of comments
          example: 5
        next:
          type: string
          format: uri
          nullable: true
          description: URL for the next page of results
        previous:
          type: string
          format: uri
          nullable: true
          description: URL for the previous page of results
        results:
          type: array
          items:
            $ref: "#/components/schemas/Comment"

    # Related Entity Schemas
    UserSummary:
      type: object
      description: Summary of a user (used for requestor, assignee, etc.)
      required:
        - email
      properties:
        email:
          type: string
          format: email
          description: User's email address
          example: "jane.doe@company.com"
        name:
          type: string
          nullable: true
          description: User's display name
          example: "Jane Doe"

    DepartmentSummary:
      type: object
      description: Summary of a department
      required:
        - id
        - name
      properties:
        id:
          type: string
          format: uuid
          description: Department UUID
          example: "660e8400-e29b-41d4-a716-446655440000"
        name:
          type: string
          description: Department name
          example: "IT Support"
        ticket_prefix:
          type: string
          nullable: true
          description: Prefix used for tickets in this department (null if not configured)
          example: "IT"

    CategorySummary:
      type: object
      description: Summary of a ticket's effective category
      required:
        - id
        - name
        - is_suggested
      properties:
        id:
          type: string
          format: uuid
          description: Category UUID (org_category_id)
          example: "770f9511-f30c-52e5-b827-557766551111"
        name:
          type: string
          description: Category name
          example: "Password Reset"
        is_suggested:
          type: boolean
          description: True if AI-suggested, false if human-confirmed
          example: true

    PrioritySummary:
      type: object
      description: Summary of a ticket's effective priority
      required:
        - value
        - is_suggested
      properties:
        value:
          type: string
          description: Priority value
          enum:
            - low
            - medium
            - high
            - urgent
          example: "high"
        is_suggested:
          type: boolean
          description: True if AI-suggested, false if human-set
          example: true

    DepartmentListResponse:
      type: object
      description: Paginated list of departments
      required:
        - count
        - results
      properties:
        count:
          type: integer
          description: Total number of departments
          example: 3
        next:
          type: string
          format: uri
          nullable: true
          description: URL for the next page of results (null if no more pages)
          example: null
        previous:
          type: string
          format: uri
          nullable: true
          description: URL for the previous page of results (null if on first page)
          example: null
        results:
          type: array
          items:
            $ref: "#/components/schemas/DepartmentSummary"

    # Runbook Schemas
    Runbook:
      type: object
      description: A runbook describes when the agent should act and what to do.
      required:
        - runbook_id
        - title
        - content
        - enabled
        - match_type
        - version
        - created
        - modified
      properties:
        runbook_id:
          type: string
          format: uuid
          description: UUID identifying this runbook
        title:
          type: string
          description: Runbook title
          maxLength: 100
          example: "Reset a user's password"
        conditions:
          type: string
          nullable: true
          description: |
            Free-text matching criteria. Null for `match_type=department`.
          example: "When a user reports they cannot sign in."
        content:
          type: string
          description: Instructions the agent will follow when the runbook matches.
        enabled:
          type: boolean
          description: Whether this runbook is currently active.
        match_type:
          type: string
          description: |
            How this runbook matches incoming tickets. `semantic` matches the
            request text against `conditions`; `department` applies to every
            request routed to its department; `system` is never matched at all —
            a system attaches it by naming it via `runbook_id`.
          enum:
            - semantic
            - department
            - system
        version:
          type: integer
          description: Monotonically increasing version number.
          minimum: 1
        duplicated_from_runbook_id:
          type: string
          format: uuid
          nullable: true
          description: UUID of the source runbook if this was created via duplicate.
        department:
          allOf:
            - $ref: "#/components/schemas/DepartmentSummary"
          nullable: true
          description: |
            The department this runbook is scoped to (always set for
            `match_type=department`; may be null otherwise).
        tools:
          type: array
          description: |
            Tool references on this runbook — both built-in `core_*` tools
            and custom OrgTools that the agent may invoke.
          items:
            type: object
            required:
              - tool_id
              - name
            properties:
              tool_id:
                type: string
                description: Tool UUID or `core_*` identifier
              name:
                type: string
                description: Human-readable tool name
        created:
          type: string
          format: date-time
          description: When the runbook was created.
        modified:
          type: string
          format: date-time
          description: When the runbook was last modified.
        created_by:
          type: string
          nullable: true
          description: Email of the user who created the runbook.
        updated_by:
          type: string
          nullable: true
          description: Email of the user who last updated the runbook.

    RunbookRevision:
      description: A single revision (version) of a runbook.
      allOf:
        - $ref: "#/components/schemas/Runbook"

    RunbookCreate:
      type: object
      description: Request body for creating a runbook.
      required:
        - title
        - content
      properties:
        title:
          type: string
          maxLength: 100
          description: Runbook title.
        content:
          type: string
          description: Instructions the agent will follow.
        conditions:
          type: string
          nullable: true
          description: |
            When the runbook should match (free-text criteria). Ignored
            when `match_type=department`.
        enabled:
          type: boolean
          default: false
          description: Whether the runbook is active.
        match_type:
          type: string
          enum:
            - semantic
            - department
            - system
          default: semantic
          description: |
            How this runbook matches incoming tickets.
            `department` requires `dept_id`. `system` takes no matching criteria:
            a system attaches it by naming it via `runbook_id`.
        dept_id:
          type: string
          format: uuid
          description: |
            UUID of the department to scope this runbook to. Required
            when `match_type=department`.
        tool_ids:
          type: array
          description: |
            Tool references the runbook may invoke. Mix of OrgTool UUIDs
            and `core_*` tool names.
          items:
            type: string

    RunbookUpdate:
      type: object
      description: |
        Request body for partially updating a runbook. All fields are
        optional; an empty body is a no-op.
      properties:
        title:
          type: string
          maxLength: 100
        content:
          type: string
        conditions:
          type: string
          nullable: true
        enabled:
          type: boolean
        match_type:
          type: string
          enum:
            - semantic
            - department
            - system
        dept_id:
          type: string
          format: uuid
        tool_ids:
          type: array
          items:
            type: string

    RunbookListResponse:
      type: object
      description: Paginated list of runbooks.
      required:
        - count
        - results
      properties:
        count:
          type: integer
          description: Total number of runbooks matching the query.
        next:
          type: string
          format: uri
          nullable: true
          description: URL for the next page of results (null if no more pages).
        previous:
          type: string
          format: uri
          nullable: true
          description: URL for the previous page of results (null if on first page).
        results:
          type: array
          items:
            $ref: "#/components/schemas/Runbook"

    TicketRunbookHistoryRow:
      type: object
      description: |
        One row of a ticket's runbook history. `applied_at` is null for
        runbooks that were matched but not followed, and populated with
        a timestamp + `reason` for runbooks the agent executed.
      required:
        - runbook_id
        - title
        - version
      properties:
        runbook_id:
          type: string
          format: uuid
        title:
          type: string
        version:
          type: integer
        applied_at:
          type: string
          format: date-time
          nullable: true
        reason:
          type: string
          nullable: true

    # Webhook Schemas
    WebhookEventType:
      type: string
      description: |
        Outbound webhook event catalog.
        * `ticket.created` — a new ticket was created
        * `ticket.escalated` — a ticket was escalated to human support
        * `ticket.closed` — a ticket reached a terminal state (resolved,
          closed, or canceled)
        * `comment.added` — a public comment was added to a ticket
        * `access.requests.completed` — every access request on a ticket
          reached a terminal state
      enum:
        - ticket.created
        - ticket.escalated
        - ticket.closed
        - comment.added
        - access.requests.completed

    WebhookEnvelope:
      type: object
      description: |
        Signed event envelope POSTed to every subscribed endpoint. The shape
        of `data` is determined by `type`.
      required:
        - id
        - type
        - created_at
        - data
      properties:
        id:
          type: string
          format: uuid
          description: Unique event id. Stable across delivery retries — use it to dedupe.
        type:
          $ref: "#/components/schemas/WebhookEventType"
        created_at:
          type: string
          format: date-time
          description: When the event was generated (ISO 8601).
        data:
          type: object
          description: The event payload. Its shape depends on `type`.

    TicketEscalatedEvent:
      description: |
        A ticket as delivered by the `ticket.escalated` webhook: the full
        ticket resource plus the escalation timestamp and reason.
      allOf:
        - $ref: "#/components/schemas/TicketDetail"
        - type: object
          properties:
            escalated_at:
              type: string
              format: date-time
              nullable: true
              description: When the ticket was escalated to human support.
            reason:
              type: string
              nullable: true
              description: Why the ticket was escalated, as stated by the escalator.

    TicketClosedEvent:
      description: |
        A ticket as delivered by the `ticket.closed` webhook: the full ticket
        resource plus the closure state.
      allOf:
        - $ref: "#/components/schemas/TicketDetail"
        - type: object
          required:
            - closure_state
          properties:
            closure_state:
              type: string
              enum:
                - resolved
                - closed
                - canceled
              description: |
                How the ticket closed: `resolved` (the request was fulfilled),
                `closed` (closed without resolution, including duplicates), or
                `canceled` (the requestor withdrew it).

    CommentEvent:
      description: |
        A comment as delivered by the `comment.added` webhook: the public
        comment resource plus the parent ticket's identifier and department.
      allOf:
        - $ref: "#/components/schemas/Comment"
        - type: object
          required:
            - ticket_id
          properties:
            ticket_id:
              type: string
              pattern: '^[A-Z]+(?:-[A-Z]+)*-\d+$'
              description: Human-readable id of the ticket this comment belongs to.
            department:
              allOf:
                - $ref: "#/components/schemas/DepartmentSummary"
              nullable: true
              description: Department handling the ticket this comment belongs to.

    AccessRequestStatus:
      type: string
      description: |
        Terminal outcome of a single access request (one user, one app).
        * `granted` — access was provisioned
        * `denied` — the request was denied
        * `canceled` — the request was canceled before resolution
        * `escalated` — handed off to a human
      enum:
        - granted
        - denied
        - canceled
        - escalated

    AccessGrantUser:
      type: object
      description: A person referenced by an access request.
      required:
        - email
        - name
      properties:
        email:
          type: string
          format: email
          nullable: true
        name:
          type: string
          nullable: true

    AccessGrantRule:
      type: object
      description: The access rule that matched the request.
      required:
        - rule_id
        - software_name
        - app_id
        - app_name
      properties:
        rule_id:
          type: string
          description: UUID of the matched access rule.
        software_name:
          type: string
          nullable: true
        app_id:
          type: string
          nullable: true
          description: UUID of the associated application, if any.
        app_name:
          type: string
          nullable: true

    AccessRequestItem:
      type: object
      description: One app's outcome within a completed access-request ticket.
      required:
        - workflow_id
        - workflow_uuid
        - software
        - status
        - grantee
        - reason
        - resolved_at
        - expires_at
        - granted_by_email
        - access_rule
      properties:
        workflow_id:
          type: integer
          deprecated: true
          description: Deprecated integer id for this request. Use `workflow_uuid`.
        workflow_uuid:
          type: string
          format: uuid
          description: Risotto id for this request, for correlation/dedup.
        software:
          type: string
          nullable: true
          description: Name of the requested software/app.
        status:
          $ref: "#/components/schemas/AccessRequestStatus"
        grantee:
          allOf:
            - $ref: "#/components/schemas/AccessGrantUser"
          nullable: true
          description: The user the access was requested for.
        reason:
          type: string
          nullable: true
          description: Requestor-supplied reason for the request.
        resolved_at:
          type: string
          format: date-time
          nullable: true
        expires_at:
          type: string
          format: date-time
          nullable: true
          description: |
            When time-limited access expires; null for permanent access or a
            non-granted request.
        granted_by_email:
          type: string
          format: email
          nullable: true
          description: Email of the approver; set only for manual grants.
        access_rule:
          allOf:
            - $ref: "#/components/schemas/AccessGrantRule"
          nullable: true

    AccessRequestsCompletedPayload:
      type: object
      description: |
        `data` for the `access.requests.completed` event: a fully-settled
        ticket with every access request on it. `requestor` and `completed_at`
        are ticket-level; per-app outcome, grantee, rule, and expiry live on
        each item in `requests`.
      required:
        - ticket_id
        - requestor
        - completed_at
        - requests
      properties:
        ticket_id:
          type: string
          nullable: true
          pattern: '^[A-Z]+(?:-[A-Z]+)*-\d+$'
        requestor:
          allOf:
            - $ref: "#/components/schemas/AccessGrantUser"
          nullable: true
        completed_at:
          type: string
          format: date-time
          nullable: true
        requests:
          type: array
          items:
            $ref: "#/components/schemas/AccessRequestItem"

    # Audit Log Schemas
    AuditEventActor:
      type: object
      description: The user who performed an audited action (snapshot at event time).
      properties:
        email:
          type: string
          nullable: true
          description: Email of the acting user.
          example: "admin@company.com"
        username:
          type: string
          nullable: true
          description: Username of the acting user.
          example: "admin@company.com"
        first_name:
          type: string
          nullable: true
          description: First name of the acting user.
          example: "Ada"
        last_name:
          type: string
          nullable: true
          description: Last name of the acting user.
          example: "Lovelace"

    AuditEventChange:
      type: object
      description: A single field-level change between the before/after snapshots.
      required:
        - field
      properties:
        field:
          type: string
          description: Name of the changed field.
          example: "enabled"
        old_value:
          nullable: true
          description: Value before the change (null if newly added).
          example: false
        new_value:
          nullable: true
          description: Value after the change (null if removed).
          example: true

    AuditEvent:
      type: object
      description: A single audit-log entry describing an organization configuration change.
      required:
        - id
        - event
        - label
        - created
        - actor
      properties:
        id:
          type: integer
          description: Unique event identifier.
          example: 12345
        event:
          type: string
          description: Machine-readable event key.
          example: "org_runbook_updated"
        label:
          type: string
          description: Human-readable label for the event.
          example: "Runbook Updated"
        created:
          type: string
          format: date-time
          description: When the event occurred.
          example: "2024-01-15T09:30:00Z"
        actor:
          $ref: "#/components/schemas/AuditEventActor"
        summary:
          type: string
          nullable: true
          description: Short human-readable description of what changed (field names).
          example: "Enabled, Content"
        changes:
          type: array
          description: |
            Full field-level diff. Only present when the request includes
            `include_changes=true`.
          items:
            $ref: "#/components/schemas/AuditEventChange"

    AuditEventListResponse:
      type: object
      description: Paginated list of audit-log events.
      required:
        - count
        - results
      properties:
        count:
          type: integer
          description: Total number of audit events matching the query.
          example: 128
        next:
          type: string
          format: uri
          nullable: true
          description: URL for the next page of results (null if no more pages).
        previous:
          type: string
          format: uri
          nullable: true
          description: URL for the previous page of results (null if on first page).
        results:
          type: array
          items:
            $ref: "#/components/schemas/AuditEvent"

    # Error Schemas
    Error:
      type: object
      description: Error response format
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              description: Machine-readable error code
              example: "validation_error"
            message:
              type: string
              description: Human-readable error message
              example: "Invalid request body"
            details:
              type: array
              description: Additional error details for validation errors
              items:
                $ref: "#/components/schemas/ErrorDetail"

    ErrorDetail:
      type: object
      description: Details about a specific validation error
      properties:
        field:
          type: string
          description: The field that caused the error
          example: "requestor_email"
        message:
          type: string
          description: Description of the error
          example: "This field is required."
        code:
          type: string
          description: Machine-readable error code for this field
          example: "required"

  responses:
    BadRequest:
      description: Invalid request parameters or body
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "validation_error"
              message: "Invalid request body"
              details:
                - field: "title"
                  message: "Ensure this field has no more than 100 characters."
                  code: "max_length"
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "authentication_error"
              message: "Invalid or missing API key"
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    Forbidden:
      description: API key lacks required scope for this operation
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "permission_denied"
              message: "API key lacks required scope: tickets:write"
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    NotFound:
      description: Requested resource not found
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "not_found"
              message: "Ticket IT-999 not found"
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    IdempotencyConflict:
      description: A request with this idempotency key is currently being processed
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "idempotency_conflict"
              message: "A request with this Idempotency-Key is currently being processed"
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    IdempotencyKeyReuse:
      description: The idempotency key was already used with a different request method or path
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "idempotency_key_reuse"
              message: "Idempotency-Key has already been used with a different request"
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    UnprocessableEntity:
      description: Request was well-formed but contains semantic errors
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "invalid_status_transition"
              message: "Cannot transition from 'closed' to 'open'"
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    RateLimited:
      description: Rate limit exceeded
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "rate_limit_exceeded"
              message: "Rate limit exceeded. Try again in 3600 seconds."
      headers:
        X-RateLimit-Limit:
          $ref: "#/components/headers/X-RateLimit-Limit"
        X-RateLimit-Remaining:
          schema:
            type: integer
            example: 0
        X-RateLimit-Reset:
          $ref: "#/components/headers/X-RateLimit-Reset"
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"

    InternalError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: "internal_error"
              message: "An unexpected error occurred. Please try again later."
      headers:
        X-Request-ID:
          $ref: "#/components/headers/X-Request-ID"
