openapi: 3.1.0
info:
  title: Ogat Review API
  version: 0.4.1
  description: |
    Rule-based per-input review for customer integrations.

    **Auth:** `Authorization: Bearer ogt_…` (app-scoped API key; organization and app
    come from the key). Keep the key server-side.

    **Transport:** `POST` only, `Content-Type: application/json`.

    **HTTP vs decision:** A completed review returns `200` even when checks fail or
    `decision` is `reject` / `needs_review`. Those are product outcomes, not API
    errors. Non-2xx means the request failed (validation, auth, quota, or server).

    **Signals:** (1) check/input `result` (`pass`/`fail`) = whether rule criteria
    matched; (2) `certainty` (0–100) is independent; (3) top-level `decision`
    (`approve`/`reject`/`needs_review`) appears only on `review-submission` and
    webhooks. A `pass` with low certainty can correctly yield `needs_review`.

    **Credits:** New checks consume plan credits. Unchanged cached results on the
    same submission do not. If every input is already cached, finalizing with
    `review-submission` costs no extra credits.

    Human docs: `/developers/docs`. Agent guide: `/for-agents.md`.
servers:
  - url: https://api.ogat.ai/functions/v1
    description: Production (custom domain → Supabase Edge Functions)
tags:
  - name: Submissions
    description: Create draft submissions without running reviews.
  - name: Reviews
    description: Evaluate inputs and finalize submissions.
  - name: Webhooks
    description: Outbound events after review-submission completes.
security:
  - bearerAuth: []
paths:
  /create-submission:
    post:
      tags: [Submissions]
      summary: Create a draft submission (platform-minted id)
      description: >
        Mints a submissionId and stores optional inputs, context, and data.
        Does not run reviews, charge credits, or emit webhooks. Optional when the
        first review call can create the submission by omitting submissionId.
      operationId: createSubmission
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateSubmissionRequest"
            example:
              policy: marketplace-listing
              externalId: listing-1042
              inputs:
                title: Vintage camera
                description: Barely used, ships next day.
              context:
                listingType: physical_goods
              data:
                store_name: Acme Market
      responses:
        "200":
          description: Draft created (HTTP 200). No review was run.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CreateSubmissionResponse"
              example:
                submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                status: draft
                policy: marketplace-listing
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/Error"
  /review-input:
    post:
      tags: [Reviews]
      summary: Review one input against its rules
      description: >
        Evaluates a single input (for example on field blur). Omit submissionId to
        create a draft automatically. Returns per-input results only: no overall
        decision, no status update, no webhooks. New checks consume credits;
        unchanged cached results on the same submission do not. A check fail is
        still HTTP 200.
      operationId: reviewInput
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ReviewInputRequest"
            example:
              policy: marketplace-listing
              submissionId: 8f6a7b3c-1111-2222-3333-444444444444
              input: description
              value: Barely used, ships next day.
      responses:
        "200":
          description: >
            Input result (HTTP 200). Check pass/fail is a review outcome, not an API error.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReviewInputResponse"
              examples:
                pass:
                  summary: Criteria matched
                  value:
                    submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                    input:
                      key: description
                      result: pass
                      checks:
                        - rule: Description must not promote banned items
                          result: pass
                          certainty: 92
                skipped:
                  summary: Waiting for placeholder data
                  description: >
                    Input was not evaluated because a $placeholder could not be
                    resolved. Call again after supplying `data` (or the missing input).
                  value:
                    submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                    input:
                      key: description
                      result: skipped
                      reasonCode: waiting_for_data
                      checks: []
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
  /review-inputs:
    post:
      tags: [Reviews]
      summary: Review multiple inputs without finalizing the submission
      description: >
        Evaluates the provided inputs in parallel (for example a wizard step).
        Only keys present in this request's inputs are reviewed. Does not return
        an overall decision, update submission status, or emit webhooks. Call
        review-submission to finalize. New checks consume credits; unchanged
        cached results do not. Per-input pass/fail is still HTTP 200.
      operationId: reviewInputs
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ReviewInputsRequest"
            example:
              policy: marketplace-listing
              submissionId: 8f6a7b3c-1111-2222-3333-444444444444
              inputs:
                title: Vintage camera
                description: Barely used, ships next day.
      responses:
        "200":
          description: Per-input results (HTTP 200). No overall decision.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReviewInputsResponse"
              example:
                submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                inputs:
                  - key: title
                    result: pass
                    checks:
                      - rule: Title must not promote banned items
                        result: pass
                        certainty: 90
                  - key: description
                    result: pass
                    checks:
                      - rule: Description must not promote banned items
                        result: pass
                        certainty: 92
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"
  /review-submission:
    post:
      tags: [Reviews]
      summary: Review a whole submission (create-and-review if no id)
      description: >
        Final full-submission review. Merges stored input values with this request's
        inputs, reviews every input that has a value, returns top-level decision,
        updates submission status, and emits configured webhooks. Omit submissionId
        to create and review in one call. New checks consume credits; if every input
        is already cached for the same values, finalizing costs no extra credits.
      operationId: reviewSubmission
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ReviewSubmissionRequest"
            example:
              policy: marketplace-listing
              inputs:
                title: Vintage camera
                description: Barely used, ships next day.
              context:
                listingType: physical_goods
              data:
                store_name: Acme Market
      responses:
        "200":
          description: >
            Review completed (HTTP 200). Includes approve, reject, and needs_review
            outcomes. Read `decision`; do not treat 200 as auto-approve.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReviewSubmissionResponse"
              examples:
                approve:
                  summary: "200 approve"
                  value:
                    submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                    decision: approve
                    inputs:
                      - key: description
                        result: pass
                        checks:
                          - rule: Description must not promote banned items
                            result: pass
                            certainty: 92
                needs_review:
                  summary: "200 needs_review (pass is not auto-approve)"
                  description: >
                    Rule criteria matched (result pass) but certainty is below the
                    policy threshold, so decision is needs_review. Not a contradiction.
                  value:
                    submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                    decision: needs_review
                    reasonCode: low_certainty
                    inputs:
                      - key: description
                        result: pass
                        reasonCode: low_certainty
                        checks:
                          - rule: Description accurately describes the item
                            result: pass
                            certainty: 62
                            reasonCode: low_certainty
                reject:
                  summary: "200 reject"
                  description: Required input failed. Still HTTP 200.
                  value:
                    submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                    decision: reject
                    reasonCode: required_input_failed
                    inputs:
                      - key: description
                        result: fail
                        checks:
                          - rule: Do not move payment off-platform
                            result: fail
                            certainty: 88
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/Error"

webhooks:
  reviewEvent:
    post:
      tags: [Webhooks]
      summary: Completed full-submission review
      description: >
        Sent after review-submission completes only. review-input and review-inputs
        do not emit webhooks. Event subscriptions configured in the console are exact
        (review.completed and/or review.needs_review).
        Verify X-Ogat-Signature against the raw request body with the endpoint secret
        using HMAC-SHA256, encoded as lowercase hex. The secret is never sent in the
        POST. Automatic delivery retries are not currently guaranteed.
      parameters:
        - in: header
          name: X-Ogat-Event
          required: true
          schema:
            type: string
            enum: [review.completed, review.needs_review]
        - in: header
          name: X-Ogat-Signature
          required: true
          description: HMAC-SHA256 hex digest of the raw request body.
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/WebhookPayload"
            examples:
              completed_approve:
                summary: review.completed (approve)
                value:
                  event: review.completed
                  submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                  policy: marketplace-listing
                  decision: approve
                  inputs:
                    - key: description
                      result: pass
                      checks:
                        - rule: Description must not promote banned items
                          result: pass
                          certainty: 92
              needs_review:
                summary: review.needs_review
                value:
                  event: review.needs_review
                  submissionId: 8f6a7b3c-1111-2222-3333-444444444444
                  policy: marketplace-listing
                  decision: needs_review
                  reasonCode: low_certainty
                  inputs:
                    - key: description
                      result: pass
                      reasonCode: low_certainty
                      checks:
                        - rule: Description accurately describes the item
                          result: pass
                          certainty: 62
                          reasonCode: low_certainty
      responses:
        "2XX":
          description: Return any 2xx status promptly to acknowledge the event.
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: Ogat API key
      description: App-scoped Ogat API key (`ogt_…`). Keep it in server-side code.
  responses:
    Error:
      description: Error
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    BadRequest:
      description: Invalid request (HTTP 400)
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            policy_required:
              summary: Missing policy
              value:
                error: policy is required
            unknown_input:
              summary: Unknown input key
              value:
                error: "Unknown input 'photos'"
            empty_value:
              summary: Empty input value
              value:
                error: value must be a non-empty string
    Unauthorized:
      description: Missing or invalid API key (HTTP 401)
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: Invalid API key
    Forbidden:
      description: Policy is not in this app (HTTP 403)
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: Policy is not in this app
    RateLimited:
      description: >
        Rate or credit limit (HTTP 429). Inspect `code`: rate_limited or
        credit_quota_exceeded.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          examples:
            rate_limited:
              summary: rate_limited
              value:
                error: Too many reviews. Try again in a moment.
                code: rate_limited
                reviewsPerMinuteLimit: 20
            credit_quota_exceeded:
              summary: credit_quota_exceeded
              value:
                error: Free includes 1000 credits per month. Upgrade to continue.
                code: credit_quota_exceeded
                creditsUsed: 1000
                creditsLimit: 1000
                topupRemaining: 0
                remainingCapacity: 0
                autoTopupEnabled: false
                planSlug: free
                resetsAt: "2026-11-01T00:00:00.000Z"
  schemas:
    Error:
      type: object
      required: [error]
      additionalProperties: true
      properties:
        error: { type: string, description: Human-readable error message }
        code:
          type: string
          description: Machine-readable error code when available.
          examples: [rate_limited, credit_quota_exceeded]
        reviewsPerMinuteLimit: { type: integer }
        creditsUsed: { type: integer }
        creditsLimit: { type: integer }
        topupRemaining: { type: integer }
        remainingCapacity: { type: integer }
        autoTopupEnabled: { type: boolean }
        planSlug: { type: string }
        resetsAt: { type: string, format: date-time }
    SubmissionContext:
      type: object
      additionalProperties: true
      description: >
        Selects which conditional rules run (console Only-when conditions).
        Merged into the submission; later calls overwrite earlier keys.
        Not reviewed as an input.
    SubmissionData:
      type: object
      additionalProperties: true
      description: >
        Values for $placeholders in rule text (and related rule config).
        Merged with input values; if the same key exists in both, the input value
        wins. Missing placeholders can yield skipped inputs with
        reasonCode waiting_for_data.
    SubmissionInputs:
      description: >
        Recommended shape is an object map (keys = input keys, values = non-empty
        strings). Advanced shape is an array of { key, value } objects.
      oneOf:
        - type: object
          additionalProperties:
            type: string
            minLength: 1
          description: Recommended. Object keys are input keys; values are reviewed strings.
        - type: array
          description: Advanced. Array of { key, value } objects.
          items:
            type: object
            required: [key, value]
            properties:
              key: { type: string }
              value: { type: string, minLength: 1 }
    CreateSubmissionRequest:
      type: object
      required: [policy]
      properties:
        policy: { type: string, description: Policy handle or id (unique within the app) }
        externalId: { type: string, description: Customer reconciliation reference }
        context: { $ref: "#/components/schemas/SubmissionContext" }
        data: { $ref: "#/components/schemas/SubmissionData" }
        inputs: { $ref: "#/components/schemas/SubmissionInputs" }
    ReviewInputRequest:
      type: object
      required: [policy, input, value]
      properties:
        policy: { type: string, description: Policy handle or id }
        submissionId: { type: string, format: uuid, description: Omit to create a new draft submission }
        input: { type: string, minLength: 1, description: Input key }
        value: { type: string, minLength: 1, description: Non-empty string to review }
        context: { $ref: "#/components/schemas/SubmissionContext" }
        data: { $ref: "#/components/schemas/SubmissionData" }
    ReviewSubmissionRequest:
      type: object
      required: [policy]
      properties:
        policy: { type: string, description: Policy handle or id }
        submissionId: { type: string, format: uuid, description: Omit to create and review in one call }
        externalId: { type: string, description: Used when creating a new submission }
        context: { $ref: "#/components/schemas/SubmissionContext" }
        data: { $ref: "#/components/schemas/SubmissionData" }
        inputs: { $ref: "#/components/schemas/SubmissionInputs" }
    ReviewInputsRequest:
      type: object
      required: [policy, inputs]
      description: >
        Same inputs/context/data shape as review-submission, but only the provided
        keys are reviewed and the call does not finalize. `inputs` must include at
        least one key.
      properties:
        policy: { type: string, description: Policy handle or id }
        submissionId: { type: string, format: uuid, description: Omit to create a new draft submission }
        externalId: { type: string, description: Used when creating a new submission }
        context: { $ref: "#/components/schemas/SubmissionContext" }
        data: { $ref: "#/components/schemas/SubmissionData" }
        inputs:
          description: At least one input required.
          oneOf:
            - type: object
              minProperties: 1
              additionalProperties:
                type: string
                minLength: 1
              description: Recommended. Object keys are input keys; values are reviewed strings.
            - type: array
              minItems: 1
              description: Advanced. Array of { key, value } objects.
              items:
                type: object
                required: [key, value]
                properties:
                  key: { type: string }
                  value: { type: string, minLength: 1 }
    CreateSubmissionResponse:
      type: object
      required: [submissionId, status, policy]
      properties:
        submissionId: { type: string, format: uuid }
        status: { type: string, enum: [draft] }
        policy: { type: string, description: Policy handle }
    Decision:
      type: string
      enum: [approve, reject, needs_review]
      description: >
        Product decision for the whole submission after combining rule outcomes
        with policy (including certainty thresholds). This is separate from per-check
        `result`. A check can be `pass` while `decision` is `needs_review` when
        certainty is too low to auto-approve. `needs_review` means a human should look
        (e.g. low certainty or a Needs-review input failure).
    ReasonCode:
      type: string
      description: >
        Machine-readable context for the decision or a check/input result.
        Common submission values: required_input_failed (Reject input failed),
        optional_input_failed (Needs-review input failed), low_certainty.
        Omitted when it would only be "ok". Advanced: too_many_optional_failures
        when a stored optional-failure limit escalates to reject.
        On a check or input, `low_certainty` means the rule criteria matched
        (`result` is still `pass`) but confidence is below the policy threshold.
        Input/check may also use waiting_for_data (skipped).
      examples:
        - required_input_failed
        - optional_input_failed
        - low_certainty
        - waiting_for_data
        - too_many_optional_failures
    CheckResult:
      type: object
      required: [rule, result, certainty]
      description: >
        One rule evaluation. `result` is the rule outcome (criteria matched or not).
        `certainty` is an independent confidence score (0–100). A `pass` with low
        certainty can still cause top-level `decision: needs_review`.
      properties:
        rule: { type: string, description: Interpolated rule text that was evaluated }
        result:
          type: string
          enum: [pass, fail]
          description: >
            Whether the rule criteria matched (`pass`) or not (`fail`).
            Does not mean "confident enough to accept"; that is decided at the
            submission `decision` level using `certainty` and policy thresholds.
        certainty:
          type: integer
          minimum: 0
          maximum: 100
          description: Confidence in this check outcome (0–100). Independent of `result`.
        reasonCode:
          $ref: "#/components/schemas/ReasonCode"
    InputResult:
      type: object
      required: [key, result, checks]
      description: >
        Aggregate of checks for one submitted input. `result` is pass if every
        check passed (criteria matched), fail if any check failed, skipped if
        the input was not evaluated. Like checks, `pass` is not an auto-approve
        signal; low certainty can still yield submission `needs_review`.
      properties:
        key: { type: string, description: Input key from the policy }
        result:
          type: string
          enum: [pass, fail, skipped]
          description: >
            Rule-outcome aggregate for this input. `pass` = criteria matched on
            all checks; not the same as submission `decision: approve`.
            `skipped` typically pairs with reasonCode waiting_for_data and empty checks.
        reasonCode:
          $ref: "#/components/schemas/ReasonCode"
        checks:
          type: array
          description: Empty when result is skipped.
          items:
            $ref: "#/components/schemas/CheckResult"
    ReviewSubmissionResponse:
      type: object
      required: [submissionId, decision, inputs]
      description: >
        Returned with HTTP 200 when the review completes, including reject and
        needs_review. Distinguish three signals: (1) inputs[].checks[].result
        (did each rule's criteria match); (2) certainty (confidence in that result);
        (3) decision (product action after applying policy, including certainty
        thresholds). Example: checks may all be pass with reasonCode low_certainty
        while decision is needs_review.
      properties:
        submissionId: { type: string, format: uuid }
        decision: { $ref: "#/components/schemas/Decision" }
        reasonCode: { $ref: "#/components/schemas/ReasonCode" }
        inputs:
          type: array
          description: One entry per submitted input that was reviewed
          items:
            $ref: "#/components/schemas/InputResult"
    ReviewInputResponse:
      type: object
      required: [submissionId, input]
      description: >
        Per-input result only (HTTP 200). No top-level decision. A check fail is
        still a successful API response.
      properties:
        submissionId: { type: string, format: uuid }
        input: { $ref: "#/components/schemas/InputResult" }
    ReviewInputsResponse:
      type: object
      required: [submissionId, inputs]
      description: >
        Batch of per-input results without a top-level decision (HTTP 200). Call
        review-submission to finalize and obtain approve/reject/needs_review.
      properties:
        submissionId: { type: string, format: uuid }
        inputs:
          type: array
          description: One entry per input key supplied in the request
          items:
            $ref: "#/components/schemas/InputResult"
    WebhookPayload:
      type: object
      description: >
        Posted to registered webhook URLs when a subscribed event fires after
        review-submission. Same public field set as review-submission, plus event
        and policy. Event is review.completed (approve/reject) or
        review.needs_review.
      required: [event, submissionId, policy, decision, inputs]
      properties:
        event: { type: string, enum: [review.completed, review.needs_review] }
        submissionId: { type: string, format: uuid }
        policy: { type: string, description: Policy handle }
        decision: { $ref: "#/components/schemas/Decision" }
        reasonCode: { $ref: "#/components/schemas/ReasonCode" }
        inputs:
          type: array
          items:
            $ref: "#/components/schemas/InputResult"
