openapi: 3.1.0
info:
  title: ClawdRules Agent API
  version: 1.0.0
  description: |
    ClawdRules is an ACP-compatible AI agent governance platform.

    Agents connect via API keys, operate under configurable rules and soul directives, and
    undergo governance evaluation (allow/deny/escalate) before purchasing externally. After
    governance approval, the agent pays through its own payment method and reports the receipt.

    ## Authentication
    All `/api/v1/agent/*` endpoints require a Bearer token:
    ```
    Authorization: Bearer clr_live_{64_hex_chars}
    ```
    Test-mode keys use the prefix `clr_test_`.

    ## Checkout Lifecycle (Governance-Only Mode)
    ```
    NOT_READY_FOR_PAYMENT -> READY_FOR_PAYMENT -> APPROVED -> COMPLETED (after receipt)
                                                           \-> CANCELED
    ```
    Payment processing is handled externally by the agent. ClawdRules evaluates governance
    rules and records receipts.

    ## ACP Error Codes
    | Code    | Meaning              |
    |---------|----------------------|
    | ACP_001 | not_found            |
    | ACP_002 | expired              |
    | ACP_003 | invalid_state        |
    | ACP_004 | payment_failed       |
    | ACP_005 | denied (rules)       |
    | ACP_006 | no_payment_method    |
    | ACP_007 | validation_error     |
    | ACP_008 | already_completed    |

    ## Multi-Platform AI Discovery
    This spec is designed for consumption by agents built on OpenAI, Anthropic Claude,
    Google Gemini, xAI Grok, and any platform that supports OpenAPI 3.1 tool definitions.
  termsOfService: https://clawdrules.com/terms
  contact:
    name: ClawdRules Support
    url: https://clawdrules.com
    email: support@clawdrules.com
  license:
    name: Proprietary
    url: https://clawdrules.com/terms
  x-agent-protocol: acp-v1
  x-anthropic-tool-use: true
  x-google-gemini-actions: true
  x-xai-grok-actions: true

servers:
  - url: https://clawdrules.com
    description: Production
    x-agent-protocol: acp-v1

tags:
  - name: Agent
    description: Agent connection, context retrieval, and rule/soul inspection
  - name: Checkout
    description: ACP checkout lifecycle — create, update, complete (governance), report receipt, cancel
  - name: Agent Checkout
    description: Receipt reporting after external purchase
  - name: Health
    description: Service health

security:
  - AgentBearerAuth: []

paths:
  # ----------------------------------------------
  # Agent endpoints
  # ----------------------------------------------
  /api/v1/agent/connect:
    post:
      operationId: agentConnect
      summary: Connect agent and get full context
      description: |
        Authenticates the agent and returns its complete operating context including
        governance rules, soul profile (personality and directives), and trusted/blocked
        merchant lists. Call this once at session start.
      tags: [Agent]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentConnectRequest"
            examples:
              minimal:
                summary: Minimal connect
                value:
                  agent_name: shopper-bot
              full:
                summary: Full connect with capabilities
                value:
                  agent_name: shopper-bot
                  agent_type: purchasing
                  platform: claude
                  capabilities:
                    - web_browsing
                    - checkout
                    - price_comparison
      responses:
        "200":
          description: Agent connected successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentConnectResponse"
              examples:
                connected:
                  summary: Successful connection
                  value:
                    agent_id: agt_abc123
                    agent_name: shopper-bot
                    status: connected
                    rules:
                      max_transaction_amount: 500
                      allowed_categories:
                        - electronics
                        - books
                      require_escalation_above: 200
                      auto_deny_categories:
                        - gambling
                        - weapons
                    soul:
                      personality: frugal and cautious
                      directives:
                        - Always compare at least 3 prices before purchasing
                        - Prefer merchants with free returns
                      greeting: "Ready to shop responsibly."
                    merchants:
                      trusted:
                        - name: Amazon
                          domain: amazon.com
                        - name: Best Buy
                          domain: bestbuy.com
                      blocked:
                        - name: ScamStore
                          domain: scamstore.example.com
        "401":
          $ref: "#/components/responses/Unauthorized"
        "422":
          $ref: "#/components/responses/ValidationError"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/check:
    post:
      operationId: agentCheck
      summary: Check if a transaction would be allowed
      description: |
        Evaluates the agent's rules against a proposed transaction without creating a
        checkout. Returns allow, deny, or escalate with the matched rule and reason.
        Use this for pre-flight checks before committing to a purchase flow.
      tags: [Agent]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentCheckRequest"
            examples:
              simple:
                summary: Simple amount check
                value:
                  action: purchase
                  amount: 49.99
                  currency: usd
                  merchant_name: Amazon
              detailed:
                summary: Detailed check with items
                value:
                  action: purchase
                  amount: 299.99
                  currency: usd
                  merchant_name: Best Buy
                  merchant_domain: bestbuy.com
                  category: electronics
                  items:
                    - name: USB-C Hub
                      unit_amount: 29999
                      quantity: 1
      responses:
        "200":
          description: Rule evaluation result
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentCheckResponse"
              examples:
                allowed:
                  summary: Transaction allowed
                  value:
                    result: allow
                    reason: Transaction within limits
                    evaluated_rules:
                      - rule_id: rule_max_amount
                        result: pass
                        description: Max transaction amount $500
                      - rule_id: rule_category
                        result: pass
                        description: Category "electronics" is allowed
                denied:
                  summary: Transaction denied
                  value:
                    result: deny
                    rule_id: rule_blocked_merchant
                    reason: Merchant is on blocked list
                    evaluated_rules:
                      - rule_id: rule_blocked_merchant
                        result: fail
                        description: scamstore.example.com is blocked
                escalate:
                  summary: Escalation required
                  value:
                    result: escalate
                    rule_id: rule_escalation_threshold
                    reason: Amount $350.00 exceeds escalation threshold of $200.00
                    evaluated_rules:
                      - rule_id: rule_max_amount
                        result: pass
                        description: Max transaction amount $500
                      - rule_id: rule_escalation_threshold
                        result: escalate
                        description: Require human approval above $200
        "401":
          $ref: "#/components/responses/Unauthorized"
        "422":
          $ref: "#/components/responses/ValidationError"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/rules:
    get:
      operationId: agentGetRules
      summary: Get agent's rule configuration
      description: |
        Returns the full set of governance rules configured for this agent. Rules control
        spending limits, allowed/denied categories, merchant restrictions, and escalation
        thresholds.
      tags: [Agent]
      responses:
        "200":
          description: Agent rules
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentRulesResponse"
              examples:
                rules:
                  summary: Typical rule set
                  value:
                    rules:
                      max_transaction_amount: 500
                      max_daily_amount: 2000
                      allowed_categories:
                        - electronics
                        - books
                        - office_supplies
                      auto_deny_categories:
                        - gambling
                        - weapons
                        - adult
                      require_escalation_above: 200
                      require_escalation_categories:
                        - luxury
                      allow_recurring: false
                    updated_at: "2026-02-22T12:00:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/soul:
    get:
      operationId: agentGetSoul
      summary: Get agent's soul profile
      description: |
        Returns the agent's soul — its personality configuration and behavioral directives.
        The soul shapes how the agent communicates and makes decisions within its rule boundaries.
      tags: [Agent]
      responses:
        "200":
          description: Agent soul profile
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentSoulResponse"
              examples:
                soul:
                  summary: Typical soul profile
                  value:
                    soul:
                      personality: frugal and cautious
                      directives:
                        - Always compare at least 3 prices before purchasing
                        - Prefer merchants with free returns
                        - Never buy extended warranties without asking
                      greeting: "Ready to shop responsibly."
                      tone: professional
                      risk_tolerance: low
                    updated_at: "2026-02-22T12:00:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/stores:
    get:
      operationId: agentGetStores
      summary: Get trusted and blocked merchant lists
      description: |
        Returns the agent's configured merchant lists. Trusted merchants receive
        preferential treatment in rule evaluation. Blocked merchants are automatically
        denied.
      tags: [Agent]
      responses:
        "200":
          description: Merchant lists
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentStoresResponse"
              examples:
                stores:
                  summary: Merchant lists
                  value:
                    trusted:
                      - name: Amazon
                        domain: amazon.com
                        added_at: "2026-01-15T00:00:00Z"
                      - name: Best Buy
                        domain: bestbuy.com
                        added_at: "2026-02-01T00:00:00Z"
                    blocked:
                      - name: ScamStore
                        domain: scamstore.example.com
                        reason: Reported for fraud
                        added_at: "2026-02-10T00:00:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"

  # ----------------------------------------------
  # ACP Checkout endpoints
  # ----------------------------------------------
  /api/v1/agent/checkout:
    post:
      operationId: checkoutCreate
      summary: Create a new checkout
      description: |
        Creates a new ACP checkout session. The checkout starts in NOT_READY_FOR_PAYMENT
        status and transitions to READY_FOR_PAYMENT once all required fields are present.
        Items are rule-checked at creation time — if any rule denies the transaction,
        the checkout is not created and an ACP_005 error is returned.

        Checkouts expire after 30 minutes if not completed.
      tags: [Checkout]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CheckoutCreateRequest"
            examples:
              single_item:
                summary: Single item checkout
                value:
                  items:
                    - name: USB-C Hub
                      unit_amount: 2999
                      quantity: 1
                      sku: "USBC-HUB-7P"
                      category: electronics
                  currency: usd
                  merchant_name: Amazon
                  merchant_domain: amazon.com
                  category: electronics
              multi_item:
                summary: Multi-item checkout
                value:
                  items:
                    - name: Mechanical Keyboard
                      unit_amount: 14999
                      quantity: 1
                      category: electronics
                    - name: Desk Mat
                      unit_amount: 2499
                      quantity: 2
                      category: office_supplies
                  currency: usd
                  merchant_name: Best Buy
                  merchant_domain: bestbuy.com
                  metadata:
                    order_ref: "ORD-2026-0042"
      responses:
        "201":
          description: Checkout created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CheckoutResponse"
              examples:
                created:
                  summary: Checkout created successfully
                  value:
                    id: chk_abc123def456
                    status: READY_FOR_PAYMENT
                    items:
                      - name: USB-C Hub
                        unit_amount: 2999
                        quantity: 1
                        sku: "USBC-HUB-7P"
                        category: electronics
                    currency: usd
                    total: 2999
                    merchant_name: Amazon
                    merchant_domain: amazon.com
                    category: electronics
                    created_at: "2026-02-22T14:30:00Z"
                    expires_at: "2026-02-22T15:00:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "422":
          $ref: "#/components/responses/ValidationError"
        "409":
          description: Denied by rules
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
              examples:
                denied:
                  summary: Denied by spending rules
                  value:
                    error:
                      code: ACP_005
                      type: denied
                      message: "Transaction denied: amount $600.00 exceeds max_transaction_amount of $500.00"
                      rule_id: rule_max_amount
        "500":
          $ref: "#/components/responses/InternalError"

    get:
      operationId: checkoutGet
      summary: Get checkout status
      description: |
        Retrieves the current state of a checkout session including its status,
        items, total, governance result, and receipt (if reported).
      tags: [Checkout]
      parameters:
        - name: checkout_id
          in: query
          required: true
          schema:
            type: string
            pattern: "^chk_[a-zA-Z0-9]+"
          description: The checkout session ID
          example: chk_abc123def456
      responses:
        "200":
          description: Checkout details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CheckoutResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Checkout not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
              examples:
                not_found:
                  value:
                    error:
                      code: ACP_001
                      type: not_found
                      message: Checkout not found
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/checkout/update:
    put:
      operationId: checkoutUpdate
      summary: Update checkout items or metadata
      description: |
        Updates an existing checkout session. Only checkouts in NOT_READY_FOR_PAYMENT
        or READY_FOR_PAYMENT status can be updated. Updated items are re-evaluated
        against the agent's rules.
      tags: [Checkout]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CheckoutUpdateRequest"
            examples:
              update_items:
                summary: Update items and merchant
                value:
                  checkout_id: chk_abc123def456
                  items:
                    - name: USB-C Hub (Upgraded)
                      unit_amount: 3999
                      quantity: 1
                      sku: "USBC-HUB-10P"
                      category: electronics
                  merchant_name: Amazon
              update_metadata:
                summary: Update metadata only
                value:
                  checkout_id: chk_abc123def456
                  metadata:
                    order_ref: "ORD-2026-0042-v2"
                    notes: "Customer requested upgrade"
      responses:
        "200":
          description: Checkout updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CheckoutResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Checkout not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
        "409":
          description: Invalid state for update or denied by rules
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
              examples:
                invalid_state:
                  value:
                    error:
                      code: ACP_003
                      type: invalid_state
                      message: "Cannot update checkout in COMPLETED state"
        "422":
          $ref: "#/components/responses/ValidationError"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/checkout/cancel:
    post:
      operationId: checkoutCancel
      summary: Cancel a checkout
      description: |
        Cancels an active checkout session. Checkouts in COMPLETED status cannot be
        canceled. Canceling an APPROVED checkout will revoke the governance approval.
      tags: [Checkout]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CheckoutCancelRequest"
            examples:
              cancel:
                value:
                  checkout_id: chk_abc123def456
      responses:
        "200":
          description: Checkout canceled
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CheckoutResponse"
              examples:
                canceled:
                  value:
                    id: chk_abc123def456
                    status: CANCELED
                    items:
                      - name: USB-C Hub
                        unit_amount: 2999
                        quantity: 1
                    currency: usd
                    total: 2999
                    canceled_at: "2026-02-22T14:45:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Checkout not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
        "409":
          description: Cannot cancel in current state
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
              examples:
                already_completed:
                  value:
                    error:
                      code: ACP_008
                      type: already_completed
                      message: "Cannot cancel a completed checkout"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/checkout/complete:
    post:
      operationId: checkoutComplete
      summary: Complete checkout governance evaluation
      description: |
        Re-evaluates governance rules and returns allow/deny/escalate. Agent then pays
        externally and reports receipt via /api/v1/agent/checkout/receipt.

        In governance-only mode, this endpoint does NOT process payment. It confirms
        the checkout passes all rules and transitions it to APPROVED status. The agent
        is then responsible for completing payment through its own payment method and
        reporting the receipt back.
      tags: [Checkout]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CheckoutCompleteRequest"
            examples:
              complete:
                summary: Request governance approval
                value:
                  checkout_id: chk_abc123def456
      responses:
        "200":
          description: Governance evaluation result
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CheckoutResponse"
              examples:
                approved:
                  summary: Checkout approved by governance
                  value:
                    id: chk_abc123def456
                    status: APPROVED
                    governance_result: allow
                    items:
                      - name: USB-C Hub
                        unit_amount: 2999
                        quantity: 1
                        sku: "USBC-HUB-7P"
                        category: electronics
                    currency: usd
                    total: 2999
                    merchant_name: Amazon
                    merchant_domain: amazon.com
                    approved_at: "2026-02-22T14:35:00Z"
                    receipt: null
                escalated:
                  summary: Checkout requires human escalation
                  value:
                    id: chk_abc123def456
                    status: READY_FOR_PAYMENT
                    governance_result: escalate
                    governance_reason: "Amount $350.00 exceeds escalation threshold of $200.00"
                    items:
                      - name: USB-C Hub
                        unit_amount: 34999
                        quantity: 1
                    currency: usd
                    total: 34999
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Checkout not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
        "409":
          description: Invalid state, denied by rules, or already completed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
              examples:
                invalid_state:
                  value:
                    error:
                      code: ACP_003
                      type: invalid_state
                      message: "Checkout must be in READY_FOR_PAYMENT state to complete"
                denied:
                  value:
                    error:
                      code: ACP_005
                      type: denied
                      message: "Transaction denied: amount $600.00 exceeds max_transaction_amount of $500.00"
                      rule_id: rule_max_amount
                already_completed:
                  value:
                    error:
                      code: ACP_008
                      type: already_completed
                      message: "Checkout has already been completed"
        "422":
          $ref: "#/components/responses/ValidationError"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/checkout/receipt:
    post:
      operationId: checkoutReportReceipt
      summary: Report receipt after external purchase
      description: |
        ACP-compatible receipt reporting. After governance approval, agent pays externally
        then reports receipt details including card brand, last 4, amount, and merchant info.
        Card brand and last 4 digits are NOT PCI sensitive.

        This endpoint transitions the checkout from APPROVED to COMPLETED status upon
        successful receipt. If the purchase failed, set success=false with a failure_reason
        and the checkout returns to READY_FOR_PAYMENT.
      tags: [Agent Checkout]
      security:
        - AgentBearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - checkout_id
                - total_amount
                - success
              properties:
                checkout_id:
                  type: string
                  pattern: "^chk_[a-zA-Z0-9]+"
                  description: The checkout session ID
                  example: chk_abc123def456
                external_order_id:
                  type: string
                  description: Order ID from the external merchant
                  example: "AMZ-2026-0042"
                external_transaction_id:
                  type: string
                  description: Transaction/payment ID from external payment processor
                  example: "txn_abc123def456"
                merchant_name:
                  type: string
                  description: Merchant where purchase was made
                  example: Amazon
                merchant_domain:
                  type: string
                  description: Domain of the merchant
                  example: amazon.com
                total_amount:
                  type: integer
                  description: Amount in cents
                  example: 2999
                currency:
                  type: string
                  default: "USD"
                  description: ISO 4217 currency code
                  example: "USD"
                card_brand:
                  type: string
                  description: "visa, mastercard, etc. (NOT PCI sensitive)"
                  example: visa
                card_last4:
                  type: string
                  pattern: "^\\d{4}$"
                  description: "Last 4 digits (NOT PCI sensitive)"
                  example: "4242"
                payment_method:
                  type: string
                  description: "card, bank_transfer, digital_wallet"
                  example: card
                  enum:
                    - card
                    - bank_transfer
                    - digital_wallet
                success:
                  type: boolean
                  description: Whether the external purchase succeeded
                  example: true
                failure_reason:
                  type: string
                  description: Reason for failure (when success=false)
                  example: "Card declined"
                items:
                  type: array
                  items:
                    $ref: "#/components/schemas/LineItem"
                  description: Itemized receipt (may differ from original checkout items)
                metadata:
                  type: object
                  additionalProperties:
                    type: string
                  description: Additional receipt metadata
            examples:
              successful_receipt:
                summary: Successful purchase receipt
                value:
                  checkout_id: chk_abc123def456
                  external_order_id: "AMZ-2026-0042"
                  external_transaction_id: "txn_abc123def456"
                  merchant_name: Amazon
                  merchant_domain: amazon.com
                  total_amount: 2999
                  currency: "USD"
                  card_brand: visa
                  card_last4: "4242"
                  payment_method: card
                  success: true
                  items:
                    - name: USB-C Hub
                      unit_amount: 2999
                      quantity: 1
                      sku: "USBC-HUB-7P"
                      category: electronics
              failed_receipt:
                summary: Failed purchase receipt
                value:
                  checkout_id: chk_abc123def456
                  total_amount: 2999
                  success: false
                  failure_reason: "Card declined: insufficient funds"
      responses:
        "200":
          description: Receipt reported, checkout completed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CheckoutResponse"
              examples:
                completed:
                  summary: Checkout completed with receipt
                  value:
                    id: chk_abc123def456
                    status: COMPLETED
                    items:
                      - name: USB-C Hub
                        unit_amount: 2999
                        quantity: 1
                        sku: "USBC-HUB-7P"
                        category: electronics
                    currency: usd
                    total: 2999
                    merchant_name: Amazon
                    merchant_domain: amazon.com
                    receipt:
                      external_order_id: "AMZ-2026-0042"
                      external_transaction_id: "txn_abc123def456"
                      card_brand: visa
                      card_last4: "4242"
                      payment_method: card
                      total_amount: 2999
                      success: true
                      reported_at: "2026-02-22T14:40:00Z"
                    completed_at: "2026-02-22T14:40:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Checkout not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
        "409":
          description: Checkout not in APPROVED state
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
              examples:
                not_approved:
                  value:
                    error:
                      code: ACP_003
                      type: invalid_state
                      message: "Checkout must be in APPROVED state to report receipt"
        "422":
          $ref: "#/components/responses/ValidationError"
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/checkout/mandate:
    get:
      operationId: checkoutGetMandate
      summary: Get AP2 mandates for a checkout
      description: |
        Retrieves the Stripe AP2 (Agentic Payments v2) mandates associated with a
        checkout. Mandates define the authorized payment parameters and are required
        for recurring or pre-authorized agent payments.
      tags: [Checkout]
      parameters:
        - name: checkout_id
          in: query
          required: true
          schema:
            type: string
            pattern: "^chk_[a-zA-Z0-9]+"
          description: The checkout session ID
          example: chk_abc123def456
        - name: type
          in: query
          required: false
          schema:
            type: string
            enum: [all, active, expired]
            default: all
          description: Filter mandates by status
      responses:
        "200":
          description: Mandate details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MandateResponse"
              examples:
                mandates:
                  value:
                    checkout_id: chk_abc123def456
                    mandates:
                      - mandate_id: mandate_abc123
                        status: active
                        amount: 2999
                        currency: usd
                        payment_method_type: card
                        created_at: "2026-02-22T14:30:00Z"
                        expires_at: "2026-03-22T14:30:00Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Checkout not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ACPError"
        "500":
          $ref: "#/components/responses/InternalError"

  # ----------------------------------------------
  # Governance
  # ----------------------------------------------
  /api/v1/agent/kill-switch:
    post:
      operationId: agentKillSwitch
      summary: Activate kill switch (freeze all agent activity)
      description: |
        EMERGENCY endpoint. Instantly freezes all agent activity. This cannot be
        undone via the API — unfreeze through the ClawdRules dashboard only.

        Requires `confirm: true` to prevent accidental activation.
      tags: [Governance]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - confirm
                - reason
              properties:
                confirm:
                  type: boolean
                  description: Must be true to activate
                  example: true
                reason:
                  type: string
                  maxLength: 500
                  description: Reason for activating kill switch
                  example: "Suspicious activity detected"
      responses:
        "200":
          description: Kill switch activated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: "Kill switch activated. All agent activity frozen."
                  activated_at:
                    type: string
                    format: date-time
        "400":
          description: Missing confirm or reason
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          description: Kill switch already active
        "500":
          $ref: "#/components/responses/InternalError"

  /api/v1/agent/approval/{approvalId}:
    get:
      operationId: agentPollApproval
      summary: Poll approval status
      description: |
        Poll the status of a pending approval request. Use after a transaction
        check or checkout/complete returns "escalate" with an approval_id.
      tags: [Governance]
      parameters:
        - name: approvalId
          in: path
          required: true
          schema:
            type: string
          description: The approval ID from an escalated transaction
      responses:
        "200":
          description: Approval status
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    enum: [pending, approved, denied, expired]
                  resolvedAt:
                    type: string
                    format: date-time
                    nullable: true
                  reason:
                    type: string
                    nullable: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Approval not found
        "500":
          $ref: "#/components/responses/InternalError"

  # ----------------------------------------------
  # Health
  # ----------------------------------------------
  /api/health:
    get:
      operationId: healthCheck
      summary: Service health check
      description: Returns the current health status of the ClawdRules API.
      tags: [Health]
      security: []
      responses:
        "200":
          description: Service is healthy
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/HealthResponse"
              examples:
                healthy:
                  value:
                    status: ok
                    timestamp: "2026-02-22T14:30:00Z"
                    version: "1.0.0"

# ==============================================
# Components
# ==============================================
components:
  securitySchemes:
    AgentBearerAuth:
      type: http
      scheme: bearer
      bearerFormat: "clr_live_{64_hex} or clr_test_{64_hex}"
      description: |
        Agent API key issued from the ClawdRules dashboard. Live keys use prefix
        `clr_live_` and test keys use prefix `clr_test_`, each followed by 64
        hexadecimal characters.

  schemas:
    # -- Request Schemas ----------------------------

    AgentConnectRequest:
      type: object
      required:
        - agent_name
      properties:
        agent_name:
          type: string
          minLength: 1
          maxLength: 128
          description: A human-readable name for this agent instance
          example: shopper-bot
        agent_type:
          type: string
          description: The functional type of agent
          example: purchasing
          enum:
            - purchasing
            - browsing
            - research
            - assistant
            - custom
        platform:
          type: string
          description: The AI platform powering this agent
          example: claude
          enum:
            - openai
            - claude
            - gemini
            - grok
            - custom
        capabilities:
          type: array
          items:
            type: string
          description: List of capabilities this agent supports
          example:
            - web_browsing
            - checkout
            - price_comparison

    AgentCheckRequest:
      type: object
      required:
        - action
        - amount
      properties:
        action:
          type: string
          description: The type of action being checked
          example: purchase
          enum:
            - purchase
            - subscribe
            - donate
            - tip
            - refund
        amount:
          type: number
          format: double
          minimum: 0
          description: Transaction amount in major currency units (e.g., dollars, not cents)
          example: 49.99
        currency:
          type: string
          minLength: 3
          maxLength: 3
          default: usd
          description: ISO 4217 currency code (lowercase)
          example: usd
        merchant_name:
          type: string
          description: Display name of the merchant
          example: Amazon
        merchant_domain:
          type: string
          format: hostname
          description: Domain of the merchant website
          example: amazon.com
        category:
          type: string
          description: Product or merchant category
          example: electronics
        items:
          type: array
          items:
            $ref: "#/components/schemas/LineItem"
          description: Optional itemized list for detailed rule evaluation

    CheckoutCreateRequest:
      type: object
      required:
        - items
      properties:
        items:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/LineItem"
          description: Line items for this checkout
        currency:
          type: string
          minLength: 3
          maxLength: 3
          default: usd
          description: ISO 4217 currency code (lowercase)
          example: usd
        merchant_name:
          type: string
          description: Display name of the merchant
          example: Amazon
        merchant_domain:
          type: string
          format: hostname
          description: Domain of the merchant website
          example: amazon.com
        category:
          type: string
          description: Top-level category for the entire checkout
          example: electronics
        metadata:
          type: object
          additionalProperties:
            type: string
          description: Arbitrary key-value metadata for this checkout
          example:
            order_ref: "ORD-2026-0042"

    CheckoutUpdateRequest:
      type: object
      required:
        - checkout_id
      properties:
        checkout_id:
          type: string
          pattern: "^chk_[a-zA-Z0-9]+"
          description: The checkout session ID to update
          example: chk_abc123def456
        items:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/LineItem"
          description: Replacement items (replaces entire item list)
        merchant_name:
          type: string
          description: Updated merchant name
        merchant_domain:
          type: string
          format: hostname
          description: Updated merchant domain
        category:
          type: string
          description: Updated category
        metadata:
          type: object
          additionalProperties:
            type: string
          description: Updated metadata (merged with existing)

    CheckoutCancelRequest:
      type: object
      required:
        - checkout_id
      properties:
        checkout_id:
          type: string
          pattern: "^chk_[a-zA-Z0-9]+"
          description: The checkout session ID to cancel
          example: chk_abc123def456

    CheckoutCompleteRequest:
      type: object
      required:
        - checkout_id
      properties:
        checkout_id:
          type: string
          pattern: "^chk_[a-zA-Z0-9]+"
          description: The checkout session ID to evaluate for governance approval
          example: chk_abc123def456

    # -- Response Schemas ---------------------------

    AgentConnectResponse:
      type: object
      required:
        - agent_id
        - agent_name
        - status
        - rules
        - soul
        - merchants
      properties:
        agent_id:
          type: string
          description: Unique agent identifier
          example: agt_abc123
        agent_name:
          type: string
          description: The agent's display name
          example: shopper-bot
        status:
          type: string
          enum: [connected, suspended, rate_limited]
          description: Current connection status
          example: connected
        rules:
          $ref: "#/components/schemas/RuleSet"
        soul:
          $ref: "#/components/schemas/SoulProfile"
        merchants:
          $ref: "#/components/schemas/MerchantLists"

    AgentCheckResponse:
      type: object
      required:
        - result
        - evaluated_rules
      properties:
        result:
          type: string
          enum: [allow, deny, escalate]
          description: The overall rule evaluation result
          example: allow
        rule_id:
          type: string
          description: ID of the rule that determined the result (for deny/escalate)
          example: rule_max_amount
        reason:
          type: string
          description: Human-readable explanation of the result
          example: Transaction within limits
        evaluated_rules:
          type: array
          items:
            $ref: "#/components/schemas/EvaluatedRule"
          description: All rules that were evaluated

    AgentRulesResponse:
      type: object
      required:
        - rules
      properties:
        rules:
          $ref: "#/components/schemas/RuleSet"
        updated_at:
          type: string
          format: date-time
          description: When the rules were last updated

    AgentSoulResponse:
      type: object
      required:
        - soul
      properties:
        soul:
          $ref: "#/components/schemas/SoulProfile"
        updated_at:
          type: string
          format: date-time
          description: When the soul was last updated

    AgentStoresResponse:
      type: object
      required:
        - trusted
        - blocked
      properties:
        trusted:
          type: array
          items:
            $ref: "#/components/schemas/Merchant"
          description: Merchants this agent trusts
        blocked:
          type: array
          items:
            $ref: "#/components/schemas/Merchant"
          description: Merchants this agent blocks

    CheckoutResponse:
      type: object
      required:
        - id
        - status
        - items
        - currency
        - total
      properties:
        id:
          type: string
          pattern: "^chk_[a-zA-Z0-9]+"
          description: Checkout session ID
          example: chk_abc123def456
        status:
          $ref: "#/components/schemas/CheckoutStatus"
        items:
          type: array
          items:
            $ref: "#/components/schemas/LineItem"
          description: Line items in the checkout
        currency:
          type: string
          description: ISO 4217 currency code
          example: usd
        total:
          type: integer
          description: Total amount in smallest currency unit (cents)
          example: 2999
        merchant_name:
          type: string
          description: Merchant display name
          example: Amazon
        merchant_domain:
          type: string
          description: Merchant domain
          example: amazon.com
        category:
          type: string
          description: Checkout category
          example: electronics
        metadata:
          type: object
          additionalProperties:
            type: string
          description: Checkout metadata
        # payment_status — disabled in governance-only mode
        # spt_token — disabled in governance-only mode
        governance_result:
          type: string
          enum: [allow, deny, escalate]
          description: Result of governance evaluation (present after /checkout/complete)
          example: allow
        governance_reason:
          type: string
          description: Human-readable explanation of governance result
          example: "Transaction within limits"
        approved_at:
          type: string
          format: date-time
          description: When governance approval was granted (if applicable)
        receipt:
          $ref: "#/components/schemas/Receipt"
        created_at:
          type: string
          format: date-time
          description: When the checkout was created
        expires_at:
          type: string
          format: date-time
          description: When the checkout expires (30 minutes after creation)
        completed_at:
          type: string
          format: date-time
          description: When the checkout was completed (if applicable)
        canceled_at:
          type: string
          format: date-time
          description: When the checkout was canceled (if applicable)

    MandateResponse:
      type: object
      required:
        - checkout_id
        - mandates
      properties:
        checkout_id:
          type: string
          description: The associated checkout ID
          example: chk_abc123def456
        mandates:
          type: array
          items:
            $ref: "#/components/schemas/Mandate"

    HealthResponse:
      type: object
      required:
        - status
      properties:
        status:
          type: string
          enum: [ok, degraded, down]
          example: ok
        timestamp:
          type: string
          format: date-time
          example: "2026-02-22T14:30:00Z"
        version:
          type: string
          example: "1.0.0"

    # -- Shared / Embedded Schemas ------------------

    LineItem:
      type: object
      required:
        - name
        - unit_amount
        - quantity
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 256
          description: Display name of the item
          example: USB-C Hub
        unit_amount:
          type: integer
          minimum: 0
          description: Price per unit in smallest currency unit (cents)
          example: 2999
        quantity:
          type: integer
          minimum: 1
          description: Number of units
          example: 1
        sku:
          type: string
          maxLength: 128
          description: Optional SKU or product identifier
          example: "USBC-HUB-7P"
        category:
          type: string
          description: Item-level category
          example: electronics

    # PaymentData — disabled in governance-only mode. Agent handles payment externally.
    # PaymentData:
    #   type: object
    #   required:
    #     - token
    #     - payment_method_type
    #   properties:
    #     token:
    #       type: string
    #       pattern: "^spt_"
    #       description: Stripe Payment Token
    #       example: "spt_1abc2def3ghi4jkl"
    #     payment_method_type:
    #       type: string
    #       enum: [card, us_bank_account, link]
    #       description: The type of payment method
    #       example: card

    Receipt:
      type: object
      description: External purchase receipt reported by the agent after governance approval
      properties:
        external_order_id:
          type: string
          description: Order ID from the external merchant
          example: "AMZ-2026-0042"
        external_transaction_id:
          type: string
          description: Transaction/payment ID from external payment processor
          example: "txn_abc123def456"
        merchant_name:
          type: string
          description: Merchant where purchase was made
          example: Amazon
        merchant_domain:
          type: string
          description: Domain of the merchant
          example: amazon.com
        card_brand:
          type: string
          description: "Card brand (NOT PCI sensitive)"
          example: visa
        card_last4:
          type: string
          pattern: "^\\d{4}$"
          description: "Last 4 digits of card (NOT PCI sensitive)"
          example: "4242"
        payment_method:
          type: string
          description: Payment method used
          enum: [card, bank_transfer, digital_wallet]
          example: card
        total_amount:
          type: integer
          description: Amount in cents
          example: 2999
        currency:
          type: string
          description: ISO 4217 currency code
          example: "USD"
        success:
          type: boolean
          description: Whether the external purchase succeeded
          example: true
        failure_reason:
          type: string
          description: Reason for failure (when success=false)
        reported_at:
          type: string
          format: date-time
          description: When the receipt was reported

    RuleSet:
      type: object
      description: The complete set of governance rules for an agent
      properties:
        max_transaction_amount:
          type: number
          format: double
          description: Maximum amount for a single transaction (in major currency units)
          example: 500
        max_daily_amount:
          type: number
          format: double
          description: Maximum total spend per day
          example: 2000
        allowed_categories:
          type: array
          items:
            type: string
          description: Categories the agent is allowed to purchase from
          example:
            - electronics
            - books
        auto_deny_categories:
          type: array
          items:
            type: string
          description: Categories that are automatically denied
          example:
            - gambling
            - weapons
        require_escalation_above:
          type: number
          format: double
          description: Amount threshold that triggers human escalation
          example: 200
        require_escalation_categories:
          type: array
          items:
            type: string
          description: Categories that always require human escalation
          example:
            - luxury
        allow_recurring:
          type: boolean
          description: Whether the agent can create recurring/subscription payments
          example: false

    SoulProfile:
      type: object
      description: The agent's personality and behavioral directives
      properties:
        personality:
          type: string
          description: Short personality description
          example: frugal and cautious
        directives:
          type: array
          items:
            type: string
          description: Ordered list of behavioral directives
          example:
            - Always compare at least 3 prices before purchasing
            - Prefer merchants with free returns
        greeting:
          type: string
          description: Default greeting message
          example: "Ready to shop responsibly."
        tone:
          type: string
          description: Communication tone
          enum: [professional, casual, friendly, formal]
          example: professional
        risk_tolerance:
          type: string
          description: Risk tolerance level
          enum: [low, medium, high]
          example: low

    MerchantLists:
      type: object
      description: Trusted and blocked merchant groupings
      required:
        - trusted
        - blocked
      properties:
        trusted:
          type: array
          items:
            $ref: "#/components/schemas/Merchant"
        blocked:
          type: array
          items:
            $ref: "#/components/schemas/Merchant"

    Merchant:
      type: object
      required:
        - name
        - domain
      properties:
        name:
          type: string
          description: Merchant display name
          example: Amazon
        domain:
          type: string
          format: hostname
          description: Merchant domain
          example: amazon.com
        reason:
          type: string
          description: Reason for trusted/blocked status
          example: Reported for fraud
        added_at:
          type: string
          format: date-time
          description: When the merchant was added to the list

    EvaluatedRule:
      type: object
      required:
        - rule_id
        - result
      properties:
        rule_id:
          type: string
          description: Rule identifier
          example: rule_max_amount
        result:
          type: string
          enum: [pass, fail, escalate, skipped]
          description: Result of evaluating this rule
          example: pass
        description:
          type: string
          description: Human-readable description of the rule
          example: "Max transaction amount $500"

    Mandate:
      type: object
      required:
        - mandate_id
        - status
      properties:
        mandate_id:
          type: string
          description: Stripe mandate ID
          example: mandate_abc123
        status:
          type: string
          enum: [active, expired, revoked, pending]
          description: Mandate status
          example: active
        amount:
          type: integer
          description: Authorized amount in smallest currency unit
          example: 2999
        currency:
          type: string
          description: Currency code
          example: usd
        payment_method_type:
          type: string
          description: Payment method type
          example: card
        created_at:
          type: string
          format: date-time
          description: When the mandate was created
        expires_at:
          type: string
          format: date-time
          description: When the mandate expires

    CheckoutStatus:
      type: string
      enum:
        - NOT_READY_FOR_PAYMENT
        - READY_FOR_PAYMENT
        - APPROVED
        - COMPLETED
        - CANCELED
      description: |
        Checkout lifecycle status (governance-only mode):
        - `NOT_READY_FOR_PAYMENT` — Checkout created but missing required fields
        - `READY_FOR_PAYMENT` — All fields present, awaiting governance evaluation
        - `APPROVED` — Governance approved, agent should pay externally and report receipt
        - `COMPLETED` — Receipt reported, checkout finalized
        - `CANCELED` — Checkout was canceled
      example: READY_FOR_PAYMENT

    ACPError:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - type
            - message
          properties:
            code:
              type: string
              description: ACP error code
              enum:
                - ACP_001
                - ACP_002
                - ACP_003
                - ACP_004
                - ACP_005
                - ACP_006
                - ACP_007
                - ACP_008
              example: ACP_005
            type:
              type: string
              description: Error type slug
              enum:
                - not_found
                - expired
                - invalid_state
                - payment_failed
                - denied
                - no_payment_method
                - validation_error
                - already_completed
              example: denied
            message:
              type: string
              description: Human-readable error message
              example: "Transaction denied: amount exceeds limit"
            rule_id:
              type: string
              description: Rule that caused the error (for ACP_005 denied)
              example: rule_max_amount
            details:
              type: object
              additionalProperties: true
              description: Additional error context

    ValidationErrorResponse:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
            - issues
          properties:
            code:
              type: string
              const: ACP_007
            message:
              type: string
              example: Validation failed
            issues:
              type: array
              items:
                type: object
                properties:
                  field:
                    type: string
                    example: items[0].unit_amount
                  message:
                    type: string
                    example: "Expected integer, received string"
                  code:
                    type: string
                    example: invalid_type

  responses:
    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: object
                properties:
                  code:
                    type: string
                    example: unauthorized
                  message:
                    type: string
                    example: Invalid or missing API key
          examples:
            missing_key:
              value:
                error:
                  code: unauthorized
                  message: "Authorization header required"
            invalid_key:
              value:
                error:
                  code: unauthorized
                  message: "Invalid API key"

    ValidationError:
      description: Request validation failed
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ValidationErrorResponse"
          examples:
            validation:
              value:
                error:
                  code: ACP_007
                  message: Validation failed
                  issues:
                    - field: items
                      message: "Array must contain at least 1 element(s)"
                      code: too_small

    InternalError:
      description: Internal server error
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: object
                properties:
                  code:
                    type: string
                    example: internal_error
                  message:
                    type: string
                    example: An unexpected error occurred
