{
  "openapi": "3.1.0",
  "info": {
    "title": "docmatch API",
    "version": "1.0.0",
    "summary": "Conciliação de documentos, planilhas, e-mails, áudios e vídeos com evidência.",
    "description": "API pública da docmatch (v1). Tudo em pt-BR; identificadores e enums em inglês.\n\n## Convenções\n\n- **Envelope de erro.** Toda resposta 4xx/5xx é `{code, message, request_id, details?}`.\n  `code` é um código estável de `errors.yaml` (snake_case); `message` é a frase em pt-BR\n  para mostrar ao usuário; `request_id` aparece também no header `X-Request-Id`.\n- **Dinheiro** é inteiro em centavos (ou na menor unidade da moeda) com `currency` ISO 4217.\n  **Créditos** (tokens docmatch) são inteiros.\n- **Limites de texto** vêm de `limits.yaml`: cada `maxLength` aqui carrega `x-limit` com a\n  chave correspondente, e o CI falha se discordarem.\n- **Idempotência.** Toda operação que pode gastar créditos exige o header `Idempotency-Key`\n  (chave única por tentativa, até 128 caracteres). A mesma chave com o mesmo corpo devolve\n  a mesma resposta; com corpo diferente devolve `409 idempotency_key_reused`.\n- **Limite de requisições.** Toda resposta traz `RateLimit-Limit`, `RateLimit-Remaining` e\n  `RateLimit-Reset`; um `429 rate_limited` traz também `Retry-After`.\n- **Autenticação.** Sessão em cookie `HttpOnly` (apps e site) ou chave de API no header\n  `Authorization: Bearer dm_live_<id>_<secret>` (integrações). Endpoints públicos têm\n  `security: []`.\n- **Conta escolhida.** `X-Docmatch-Org` seleciona a conta por requisição; nunca altera outras abas.\n  Sem o header, clientes antigos usam a conta da sessão. Chaves de API continuam presas à sua conta.\n- **Paginação** por cursor opaco: `cursor` + `limit` na consulta, `next_cursor` na resposta\n  (nulo na última página).\n- **Eventos em tempo real** por SSE em `GET /runs/{id}/events`; cada evento tem `id`\n  (sequência) para retomar com `Last-Event-ID`.\n- **Webhooks de saída** assinados com `DM-Signature: t=<unix>,v1=<hmac-sha256-hex>`\n  (ver a seção *webhooks*).\n",
    "license": {
      "name": "AGPL-3.0-only",
      "identifier": "AGPL-3.0-only"
    }
  },
  "servers": [
    {
      "url": "{baseUrl}/v1",
      "description": "Base da API (DM_API_BASE_URL) + prefixo da versão.",
      "variables": {
        "baseUrl": {
          "default": "http://localhost:8080",
          "description": "Valor de DM_API_BASE_URL, sem barra final."
        }
      }
    }
  ],
  "security": [
    {
      "cookieSession": []
    },
    {
      "apiKey": []
    }
  ],
  "tags": [
    {
      "name": "extensions",
      "description": "Autorização com PKCE e sessões revogáveis das extensões oficiais."
    },
    {
      "name": "teams",
      "description": "Equipes e convites com aceite, sem cobrança adicional por assento."
    },
    {
      "name": "projects",
      "description": "Projetos salvos, versões e conciliação sem repetição de cobranças."
    },
    {
      "name": "auth",
      "description": "Login com Google, Apple ou e-mail; sessão em cookie HttpOnly."
    },
    {
      "name": "account",
      "description": "Conta e organização do usuário autenticado (LGPD incluída)."
    },
    {
      "name": "uploads",
      "description": "Envio de documentos (S3, POST pré-assinado) e mídia (R2, PUT pré-assinado), com verificação de segurança."
    },
    {
      "name": "runs",
      "description": "Estimativas, execuções, achados, eventos em tempo real e exportação."
    },
    {
      "name": "workflows",
      "description": "Fluxos de conciliação reutilizáveis."
    },
    {
      "name": "rules",
      "description": "Regras como hipóteses executáveis, versionadas e promovíveis."
    },
    {
      "name": "billing",
      "description": "Assinaturas, recargas e webhook do Stripe."
    },
    {
      "name": "credits",
      "description": "Saldo de créditos e ledger."
    },
    {
      "name": "customizations",
      "description": "Personalização da interface a partir de um pedido em linguagem natural."
    },
    {
      "name": "api-keys",
      "description": "Chaves de API para integrações."
    },
    {
      "name": "webhooks",
      "description": "Endpoints de webhook de saída e os eventos que a docmatch envia."
    },
    {
      "name": "public",
      "description": "Planos, saúde e versão. Sem autenticação."
    }
  ],
  "paths": {
    "/team": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "get": {
        "operationId": "getTeam",
        "tags": [
          "teams"
        ],
        "summary": "Consulta a equipe e a própria permissão",
        "description": "Somente responsáveis e administradores recebem a lista de pessoas e convites. Outros participantes recebem listas vazias.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Team"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      },
      "post": {
        "operationId": "createTeam",
        "tags": [
          "teams"
        ],
        "summary": "Transforma a conta paga em equipe",
        "description": "Requer responsável e assinatura ativa. Preserva a conta, assinatura, saldo e projetos existentes; cria uma conta pessoal vazia se necessário. Não altera quantidades de cobrança. Projetos continuam privados.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TeamCreate"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Team"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/team/invitations": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "post": {
        "operationId": "inviteTeamMember",
        "tags": [
          "teams"
        ],
        "summary": "Convida uma pessoa pelo e-mail",
        "description": "Requer gestão da conta e plano ativo. Sem cobrança adicional por assento. Um convite pendente para o mesmo e-mail é reutilizado sem reenvio automático. O acesso exige aceite com e-mail verificado.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TeamInvite"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TeamInvitation"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/team/invitations/{invitation}/resend": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/InvitationPath"
        }
      ],
      "post": {
        "operationId": "resendTeamInvitation",
        "tags": [
          "teams"
        ],
        "summary": "Reenvia e invalida o link anterior",
        "description": "Intervalo mínimo de um minuto e limite de envios por hora. O novo link vence em sete dias.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/team/invitations/{invitation}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/InvitationPath"
        }
      ],
      "delete": {
        "operationId": "revokeTeamInvitation",
        "tags": [
          "teams"
        ],
        "summary": "Revoga um convite pendente",
        "description": "Revoga um convite pendente",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/team/members/{user}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/TeamUserPath"
        }
      ],
      "patch": {
        "operationId": "changeTeamMemberRole",
        "tags": [
          "teams"
        ],
        "summary": "Altera a permissão de projetos",
        "description": "Altera a permissão de projetos",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TeamRoleChange"
              }
            }
          }
        },
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      },
      "delete": {
        "operationId": "removeTeamMember",
        "tags": [
          "teams"
        ],
        "summary": "Remove o acesso à equipe",
        "description": "Revoga o vínculo sem excluir a identidade, conta pessoal ou assinatura da pessoa. Não permite remover o responsável por este caminho.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/team/owner": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "post": {
        "operationId": "transferTeamOwnership",
        "tags": [
          "teams"
        ],
        "summary": "Transfere a responsabilidade pela conta",
        "description": "Somente o responsável atual pode transferir para um participante aceito com acesso completo. O novo responsável é promovido antes de reduzir o acesso do anterior.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TeamTransfer"
              }
            }
          }
        },
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/team/leave": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "post": {
        "operationId": "leaveTeam",
        "tags": [
          "teams"
        ],
        "summary": "Sai da equipe preservando a conta pessoal",
        "description": "O responsável precisa transferir a função antes de sair.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/invitations/preview": {
      "post": {
        "operationId": "previewTeamInvitation",
        "tags": [
          "teams"
        ],
        "summary": "Lê um convite sem aceitá-lo",
        "description": "O token chega no corpo. A abertura do link só exibe este resumo; não adiciona nenhum vínculo. O e-mail é mascarado. email_matches considera a identidade autenticada, quando houver.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/InvitationPreviewRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvitationPreview"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/invitations/respond": {
      "post": {
        "operationId": "answerTeamInvitation",
        "tags": [
          "teams"
        ],
        "summary": "Aceita ou recusa explicitamente um convite",
        "description": "Requer sessão válida e o e-mail convidado verificado. Não depende da antiga conta selecionada. Repetir um aceite é seguro enquanto o vínculo existe; o link não recria um acesso removido.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/InvitationAnswer"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvitationAnswerResult"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/me/invitations": {
      "get": {
        "operationId": "listPendingInvitations",
        "tags": [
          "teams"
        ],
        "summary": "Lista convites pendentes para o e-mail verificado do login",
        "description": "Não aceita convites nem retorna tokens. Independe da conta selecionada. Até 50 convites por página.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "schema": {
              "$ref": "#/components/schemas/InvitationId"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Convites pendentes, ordenados por ID. next_cursor aparece quando há outra página.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvitationInbox"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      }
    },
    "/me/invitations/{invitation}/respond": {
      "parameters": [
        {
          "name": "invitation",
          "in": "path",
          "required": true,
          "schema": {
            "$ref": "#/components/schemas/InvitationId"
          }
        }
      ],
      "post": {
        "operationId": "answerPendingInvitation",
        "tags": [
          "teams"
        ],
        "summary": "Responde a um convite da caixa de entrada",
        "description": "Requer sessão válida e o e-mail convidado verificado. Não depende da antiga conta selecionada. Repetir um aceite é seguro enquanto o vínculo existe; o link não recria um acesso removido.",
        "security": [
          {
            "cookieSession": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PendingInvitationAnswer"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvitationAnswerResult"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/projects": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "listProjects",
        "tags": [
          "projects"
        ],
        "summary": "Lista projetos acessíveis",
        "description": "Lista projetos acessíveis. Permissões e vínculo são verificados no servidor.",
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectList"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/Limit"
          },
          {
            "name": "archived",
            "in": "query",
            "schema": {
              "type": "boolean",
              "default": false
            }
          }
        ]
      },
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "createProject",
        "tags": [
          "projects"
        ],
        "summary": "Cria um projeto privado",
        "description": "Cria um projeto privado. Permissões e vínculo são verificados no servidor.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectCreate"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Project"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/projects/from-run": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "importRunAsProject",
        "tags": [
          "projects"
        ],
        "summary": "Salva uma conciliação anterior como projeto privado",
        "description": "Preserva arquivos, resultado e retenção sem nova execução ou cobrança. Repetir retorna o mesmo projeto. Chaves exigem projects:write e runs:read. Versões antigas de regras não são reconstruídas; o projeto informa essa origem.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "run_id",
                  "name"
                ],
                "properties": {
                  "run_id": {
                    "$ref": "#/components/schemas/RunId"
                  },
                  "name": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 120,
                    "x-limit": "text.project_name"
                  }
                },
                "additionalProperties": false
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Projeto criado ou retomado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Project"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/projects/{project}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ],
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "getProject",
        "tags": [
          "projects"
        ],
        "summary": "Retoma documentos e opções do projeto",
        "description": "Retoma documentos e opções do projeto. Permissões e vínculo são verificados no servidor.",
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectDetail"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      },
      "patch": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "updateProject",
        "tags": [
          "projects"
        ],
        "summary": "Salva nome, opções ou arquivamento",
        "description": "Salva nome, opções ou arquivamento. Permissões e vínculo são verificados no servidor.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectPatch"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectDetail"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      },
      "delete": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "deleteProject",
        "tags": [
          "projects"
        ],
        "summary": "Remove o projeto",
        "description": "Remove o projeto. Permissões e vínculo são verificados no servidor.",
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ProjectVersion"
          }
        ]
      }
    },
    "/projects/dashboard": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "get": {
        "operationId": "workspaceDashboard",
        "tags": [
          "projects"
        ],
        "summary": "Resume os projetos e as execuções acessíveis da conta",
        "description": "Métricas por período de criação, comparação anterior de mesma duração e séries diárias no horário de Brasília. Exige sessão com acesso a resultados. Totais incluem reprocessamentos e respeitam a retenção e a visibilidade de cada projeto.",
        "security": [
          {
            "cookieSession": []
          },
          {
            "extensionSession": []
          }
        ],
        "parameters": [
          {
            "name": "days",
            "in": "query",
            "description": "Duração do período, em dias corridos até o momento da consulta.",
            "schema": {
              "type": "integer",
              "enum": [
                7,
                30,
                90
              ],
              "default": 30
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Visão geral da conta; nunca armazenar em cache.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WorkspaceDashboard"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      }
    },
    "/projects/activity": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        }
      ],
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "accountActivity",
        "tags": [
          "projects"
        ],
        "summary": "Lista conciliações acessíveis da conta",
        "description": "Lista conciliações acessíveis da conta. Permissões e vínculo são verificados no servidor.",
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RunList"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/Limit"
          }
        ]
      }
    },
    "/projects/{project}/documents/{document}/replace": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        },
        {
          "$ref": "#/components/parameters/DocumentPath"
        }
      ],
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "replaceProjectDocument",
        "tags": [
          "projects"
        ],
        "summary": "Promove uma nova versão verificada mantendo o histórico",
        "description": "Promove uma nova versão verificada mantendo o histórico. Permissões e vínculo são verificados no servidor.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectReplacement"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectDetail"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/projects/{project}/sharing": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ],
      "put": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "shareProject",
        "tags": [
          "projects"
        ],
        "summary": "Compartilha com a equipe ou pessoas escolhidas",
        "description": "Compartilha com a equipe ou pessoas escolhidas. Permissões e vínculo são verificados no servidor.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectSharing"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectDetail"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/projects/{project}/activity": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ],
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectActivity",
        "tags": [
          "projects"
        ],
        "summary": "Lista alterações recentes do projeto",
        "description": "Lista alterações recentes do projeto. Permissões e vínculo são verificados no servidor.",
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectActivity"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/projects/{project}/documents": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ],
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "attachProjectDocument",
        "tags": [
          "projects"
        ],
        "summary": "Adiciona um upload ou substitui uma versão",
        "description": "Adiciona um upload ou substitui uma versão. Permissões e vínculo são verificados no servidor.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectAttach"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectAttachment"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/projects/{project}/documents/{document}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        },
        {
          "$ref": "#/components/parameters/DocumentPath"
        }
      ],
      "delete": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "removeProjectDocument",
        "tags": [
          "projects"
        ],
        "summary": "Retira uma versão da próxima conciliação",
        "description": "Retira uma versão da próxima conciliação. Permissões e vínculo são verificados no servidor.",
        "responses": {
          "204": {
            "description": "Operação concluída."
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/ProjectVersion"
          }
        ]
      }
    },
    "/projects/{project}/uploads": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ],
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "createProjectUpload",
        "summary": "Pede uma URL pré-assinada para enviar um arquivo",
        "description": "Gera o envio na conta e no projeto escolhidos. O arquivo aparece como pendente até chegar e passar pela verificação.",
        "tags": [
          "projects"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectUploadRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Ticket de envio.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UploadTicket"
                }
              }
            }
          },
          "400": {
            "description": "Nome inválido ou campos faltando.",
            "x-error-codes": [
              "validation_failed",
              "upload_rejected_name"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "413": {
            "description": "Arquivo maior que o permitido pelo plano.",
            "x-error-codes": [
              "file_too_large",
              "upload_rejected_size"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "415": {
            "description": "Tipo não suportado.",
            "x-error-codes": [
              "upload_rejected_type"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/projects/{project}/uploads/{upload}/complete": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        },
        {
          "$ref": "#/components/parameters/ProjectUploadPath"
        }
      ],
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "completeProjectUpload",
        "summary": "Confirma o envio e dispara a verificação",
        "description": "Confirma o recebimento do próprio upload no projeto e retorna a situação da verificação.",
        "tags": [
          "projects"
        ],
        "parameters": [],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UploadCompleteRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Verificação concluída (arquivo pronto ou rejeitado).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Upload"
                }
              }
            }
          },
          "202": {
            "description": "Verificação em andamento.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Upload"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "description": "O objeto ainda não chegou ao storage.",
            "x-error-codes": [
              "upload_incomplete"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Ticket expirado.",
            "x-error-codes": [
              "upload_expired"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "description": "Conteúdo rejeitado.",
            "x-error-codes": [
              "upload_checksum_mismatch",
              "upload_rejected_malware",
              "upload_rejected_bomb",
              "upload_rejected_playlist"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/projects/{project}/runs/estimate": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ],
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "estimateProject",
        "tags": [
          "projects"
        ],
        "summary": "Estima alterações ou devolve o resultado existente",
        "description": "Estima alterações ou devolve o resultado existente. Permissões e vínculo são verificados no servidor.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectAnalysisRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectAnalysis"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/projects/{project}/runs": {
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ],
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "listProjectRuns",
        "tags": [
          "projects"
        ],
        "summary": "Lista resultados e versões anteriores",
        "description": "Lista resultados e versões anteriores. Permissões e vínculo são verificados no servidor.",
        "responses": {
          "200": {
            "description": "Operação concluída.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RunList"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/Limit"
          }
        ]
      },
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "reconcileProject",
        "tags": [
          "projects"
        ],
        "summary": "Concilia alterações aprovadas sem duplicar reservas",
        "description": "Concilia alterações aprovadas sem duplicar reservas. Permissões e vínculo são verificados no servidor.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProjectAnalysisRequest"
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "Execução existente ou nova. Sem alterações, nenhum crédito é reservado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProjectAnalysis"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "410": {
            "description": "Orçamento expirado.",
            "x-error-codes": [
              "quote_expired"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "429": {
            "description": "Execuções simultâneas do plano esgotadas ou limite de requisições.",
            "x-error-codes": [
              "concurrent_runs_exceeded",
              "rate_limited"
            ],
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "x-spends-credits": true
      }
    },
    "/projects/{project}/runs/{id}": {
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectGetRun",
        "summary": "Consulta uma execução",
        "description": "Estado, progresso, créditos reservados e gastos, resumo quando concluída.",
        "tags": [
          "projects"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          }
        ],
        "responses": {
          "200": {
            "description": "A execução.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Run"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/runs/{id}/cancel": {
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectCancelRun",
        "summary": "Cancela uma execução",
        "description": "Para a execução e devolve os créditos não gastos. Execuções já terminadas não mudam.",
        "tags": [
          "projects"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          }
        ],
        "responses": {
          "200": {
            "description": "Execução cancelada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Run"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "A execução já terminou.",
            "x-error-codes": [
              "run_already_finished"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/runs/{id}/events": {
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectStreamRunEvents",
        "summary": "Eventos da execução em tempo real (SSE)",
        "description": "Fluxo `text/event-stream`. Cada mensagem tem `id` (sequência monotônica), `event` (um dos\nnomes abaixo) e `data` (JSON com o esquema do evento). O servidor envia `: ping` a cada\n15 s; a conexão fecha após `completed`, `failed` ou `needs_approval`. Para retomar, envie\n`Last-Event-ID` com a última sequência recebida.\n",
        "tags": [
          "projects"
        ],
        "x-sse-events": {
          "stage_started": "#/components/schemas/RunEventStageStarted",
          "progress": "#/components/schemas/RunEventProgress",
          "token_usage": "#/components/schemas/RunEventTokenUsage",
          "finding": "#/components/schemas/RunEventFinding",
          "match": "#/components/schemas/RunEventMatch",
          "needs_approval": "#/components/schemas/RunEventNeedsApproval",
          "completed": "#/components/schemas/RunEventCompleted",
          "failed": "#/components/schemas/RunEventFailed"
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "name": "Last-Event-ID",
            "in": "header",
            "required": false,
            "description": "Última sequência recebida; o fluxo recomeça do evento seguinte.",
            "schema": {
              "type": "integer",
              "minimum": 0
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Fluxo de eventos.",
            "content": {
              "text/event-stream": {
                "schema": {
                  "$ref": "#/components/schemas/RunEvent"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/runs/{id}/findings": {
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectListFindings",
        "summary": "Lista os achados de uma execução",
        "description": "Ordenados por severidade e valor em risco. Disponível enquanto a execução roda (parcial) e depois.",
        "tags": [
          "projects"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/Limit"
          },
          {
            "name": "severity",
            "in": "query",
            "description": "Uma ou mais severidades, separadas por vírgula.",
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/Severity"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "status",
            "in": "query",
            "schema": {
              "$ref": "#/components/schemas/FindingStatus"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Página de achados.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FindingList"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/runs/{id}/findings/{fid}/feedback": {
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectGiveFindingFeedback",
        "summary": "Confirma, descarta ou resolve um achado",
        "description": "O feedback alimenta a calibração da confiança e, nos planos com aprendizado, a proposta de regras.",
        "tags": [
          "projects"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "$ref": "#/components/parameters/FindingId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FindingFeedbackRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Achado atualizado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Finding"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução ou achado não encontrado.",
            "x-error-codes": [
              "run_not_found",
              "finding_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/Unprocessable"
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/runs/{id}/export": {
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectExportRun",
        "summary": "Exporta os resultados (xlsx, csv ou pdf)",
        "description": "Planilha com achados, casamentos e evidências; CSV só com achados; PDF com o relatório.\nSó para execuções concluídas. O arquivo é gerado sob demanda e cacheado.\n",
        "tags": [
          "projects"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "name": "format",
            "in": "query",
            "required": true,
            "schema": {
              "$ref": "#/components/schemas/ExportFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "O arquivo.",
            "headers": {
              "Content-Disposition": {
                "description": "`attachment; filename=\"docmatch-<run_id>.<ext>\"`",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
                "schema": {
                  "$ref": "#/components/schemas/BinaryFile"
                }
              },
              "text/csv": {
                "schema": {
                  "type": "string"
                }
              },
              "application/pdf": {
                "schema": {
                  "$ref": "#/components/schemas/BinaryFile"
                }
              }
            }
          },
          "400": {
            "description": "Formato não suportado.",
            "x-error-codes": [
              "export_format_unsupported"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "A execução ainda não terminou, ou o arquivo ainda está sendo gerado (tente de novo em instantes).",
            "x-error-codes": [
              "run_not_completed",
              "export_not_ready"
            ],
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/runs/{id}/approve-quote": {
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectApproveRunQuote",
        "summary": "Aprova o orçamento adicional de uma execução parada",
        "description": "Quando a execução para em `needs_approval` (ferramentas novas, teto atingido), o cliente\naprova o novo orçamento recebido no evento. Reserva a diferença e retoma do checkpoint.\n",
        "tags": [
          "projects"
        ],
        "x-spends-credits": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApproveQuoteRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Execução retomada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Run"
                }
              }
            }
          },
          "400": {
            "description": "Orçamento adulterado ou header ausente.",
            "x-error-codes": [
              "quote_invalid_signature",
              "missing_idempotency_key",
              "validation_failed"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para a diferença.",
            "x-error-codes": [
              "insufficient_credits"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Execução ou orçamento não encontrado.",
            "x-error-codes": [
              "run_not_found",
              "quote_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "A execução não está aguardando aprovação.",
            "x-error-codes": [
              "run_not_awaiting_approval",
              "idempotency_key_reused",
              "quote_mismatch"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Orçamento expirado; a execução foi cancelada e os créditos devolvidos.",
            "x-error-codes": [
              "quote_expired"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/rules": {
      "get": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectListRules",
        "summary": "Busca regras",
        "description": "Regras da organização e regras globais, filtradas por texto (`q`) e estado.",
        "tags": [
          "projects"
        ],
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "description": "Busca por título e corpo.",
            "schema": {
              "type": "string",
              "maxLength": 100,
              "x-limit": "text.rule_picker_search"
            }
          },
          {
            "name": "status",
            "in": "query",
            "schema": {
              "$ref": "#/components/schemas/RuleStatus"
            }
          },
          {
            "name": "scope",
            "in": "query",
            "schema": {
              "$ref": "#/components/schemas/RuleScope"
            }
          },
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/Limit"
          }
        ],
        "responses": {
          "200": {
            "description": "Página de regras.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RuleList"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "422": {
            "$ref": "#/components/responses/Unprocessable"
          }
        }
      },
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectCreateRule",
        "summary": "Cria uma regra",
        "description": "Salva a regra em linguagem natural e, por padrão, compila para SQL e avalia contra o\nhistórico confirmado (gasta créditos de modelo). Nasce `draft` sem compilar ou\n`candidate` compilada.\n",
        "tags": [
          "projects"
        ],
        "x-spends-credits": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RuleCreateRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Regra criada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Rule"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "422": {
            "description": "Texto fora do limite ou regra que não compila.",
            "x-error-codes": [
              "text_too_long",
              "rule_compile_failed"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/rules/{id}/versions": {
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectCreateRuleVersion",
        "summary": "Cria uma nova versão da regra",
        "description": "Mantém o `id`, incrementa `version`, recompila e reavalia. A versão anterior continua ativa até a nova ser promovida.",
        "tags": [
          "projects"
        ],
        "x-spends-credits": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/RuleId"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RuleVersionRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Nova versão.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Rule"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/PaymentRequired"
          },
          "403": {
            "description": "Regras globais são só leitura para organizações.",
            "x-error-codes": [
              "rule_read_only"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Regra não encontrada.",
            "x-error-codes": [
              "rule_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "422": {
            "description": "Texto fora do limite ou regra que não compila.",
            "x-error-codes": [
              "text_too_long",
              "rule_compile_failed"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/projects/{project}/rules/{id}/promote": {
      "post": {
        "security": [
          {
            "cookieSession": []
          },
          {
            "apiKey": []
          },
          {
            "extensionSession": []
          }
        ],
        "operationId": "projectPromoteRule",
        "summary": "Promove uma regra",
        "description": "`candidate` → `verified` exige histórico sem falsos positivos; `verified` → `trusted`\npassa a aplicar a regra automaticamente em toda execução. Só administradores promovem\nregras globais (API admin).\n",
        "tags": [
          "projects"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RuleId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RulePromoteRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Regra promovida.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Rule"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "Regra global.",
            "x-error-codes": [
              "rule_read_only"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Regra não encontrada.",
            "x-error-codes": [
              "rule_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Sem histórico suficiente.",
            "x-error-codes": [
              "rule_not_promotable"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "parameters": [
        {
          "$ref": "#/components/parameters/OrgContext"
        },
        {
          "$ref": "#/components/parameters/ProjectPath"
        }
      ]
    },
    "/uploads": {
      "post": {
        "operationId": "createUpload",
        "summary": "Pede uma URL pré-assinada para enviar um arquivo",
        "description": "Documentos vão para o S3 com um POST pré-assinado (política limita tipo e tamanho);\nmídia vai para o Cloudflare R2 com um PUT pré-assinado. O tamanho é validado contra o\nplano antes de emitir o ticket. O arquivo só fica utilizável depois de\n`POST /uploads/{id}/complete` e da verificação de segurança.\n",
        "tags": [
          "uploads"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UploadRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Ticket de envio.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UploadTicket"
                }
              }
            }
          },
          "400": {
            "description": "Nome inválido ou campos faltando.",
            "x-error-codes": [
              "validation_failed",
              "upload_rejected_name"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "413": {
            "description": "Arquivo maior que o permitido pelo plano.",
            "x-error-codes": [
              "file_too_large",
              "upload_rejected_size"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "415": {
            "description": "Tipo não suportado.",
            "x-error-codes": [
              "upload_rejected_type"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/uploads/{id}/complete": {
      "post": {
        "operationId": "completeUpload",
        "summary": "Confirma o envio e dispara a verificação",
        "description": "Confere tamanho e hash, sniffa o tipo pelo conteúdo e põe o arquivo na fila do scanner\n(antivírus, bomba de descompactação, listas de reprodução). Responde `202` enquanto a\nverificação roda; o estado final aparece em `status`.\n",
        "tags": [
          "uploads"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/UploadId"
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UploadCompleteRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Verificação concluída (arquivo pronto ou rejeitado).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Upload"
                }
              }
            }
          },
          "202": {
            "description": "Verificação em andamento.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Upload"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "description": "O objeto ainda não chegou ao storage.",
            "x-error-codes": [
              "upload_incomplete"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Ticket expirado.",
            "x-error-codes": [
              "upload_expired"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "description": "Conteúdo rejeitado.",
            "x-error-codes": [
              "upload_checksum_mismatch",
              "upload_rejected_malware",
              "upload_rejected_bomb",
              "upload_rejected_playlist"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/runs/estimate": {
      "post": {
        "operationId": "estimateRun",
        "summary": "Estima o custo de uma execução",
        "description": "Devolve um orçamento assinado (`Quote`) com o custo esperado, o teto e o detalhamento.\nNão gasta créditos. O orçamento vale por `quote_ttl_minutes` (config/pricing.yaml).\nTraz também a duração esperada (`expected_seconds`, fila incluída) e `large`: nenhum\npedido é recusado pelo tamanho; um pedido grande avisa quanto deve levar, e quem o iniciou\nrecebe um e-mail quando ele terminar.\n",
        "tags": [
          "runs"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EstimateRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Orçamento.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Quote"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "Faixa não permitida no plano.",
            "x-error-codes": [
              "lane_not_allowed",
              "plan_limit_reached"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Algum arquivo ainda não está pronto.",
            "x-error-codes": [
              "upload_not_ready"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "413": {
            "description": "Execução maior que o plano permite.",
            "x-error-codes": [
              "run_too_large"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "description": "Limites de arquivos, duração ou texto.",
            "x-error-codes": [
              "too_many_files",
              "media_too_long",
              "text_too_long"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/runs": {
      "get": {
        "operationId": "listRuns",
        "summary": "Lista execuções da organização",
        "description": "Mais recentes primeiro. Filtra por estado e por fluxo.",
        "tags": [
          "runs"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/Limit"
          },
          {
            "name": "status",
            "in": "query",
            "schema": {
              "$ref": "#/components/schemas/RunStatus"
            }
          },
          {
            "name": "workflow_id",
            "in": "query",
            "schema": {
              "$ref": "#/components/schemas/WorkflowId"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Página de execuções.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RunList"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          }
        }
      },
      "post": {
        "operationId": "createRun",
        "summary": "Cria uma execução a partir de um orçamento aprovado",
        "description": "Reserva `cap_credits` no ledger e enfileira a execução. Exige `Idempotency-Key`. Se o\norçamento tiver `requires_approval`, o cliente já está aprovando ao chamar. Se a execução\nprecisar de mais do que o teto, ela para em `needs_approval` e emite um novo orçamento.\n",
        "tags": [
          "runs"
        ],
        "x-spends-credits": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RunCreateRequest"
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "Execução enfileirada.",
            "headers": {
              "Location": {
                "description": "URL da execução.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Run"
                }
              }
            }
          },
          "400": {
            "description": "Corpo inválido, orçamento adulterado ou header ausente.",
            "x-error-codes": [
              "validation_failed",
              "quote_invalid_signature",
              "missing_idempotency_key"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para reservar o teto.",
            "x-error-codes": [
              "insufficient_credits",
              "subscription_required"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Orçamento não encontrado.",
            "x-error-codes": [
              "quote_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "Orçamento não corresponde ao pedido, chave reutilizada ou arquivo não pronto.",
            "x-error-codes": [
              "quote_mismatch",
              "idempotency_key_reused",
              "idempotency_in_progress",
              "upload_not_ready"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Orçamento expirado.",
            "x-error-codes": [
              "quote_expired"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "429": {
            "description": "Execuções simultâneas do plano esgotadas ou limite de requisições.",
            "x-error-codes": [
              "concurrent_runs_exceeded",
              "rate_limited"
            ],
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "503": {
            "$ref": "#/components/responses/ServiceUnavailable"
          }
        }
      }
    },
    "/runs/{id}": {
      "get": {
        "operationId": "getRun",
        "summary": "Consulta uma execução",
        "description": "Estado, progresso, créditos reservados e gastos, resumo quando concluída.",
        "tags": [
          "runs"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          }
        ],
        "responses": {
          "200": {
            "description": "A execução.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Run"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/runs/{id}/cancel": {
      "post": {
        "operationId": "cancelRun",
        "summary": "Cancela uma execução",
        "description": "Para a execução e devolve os créditos não gastos. Execuções já terminadas não mudam.",
        "tags": [
          "runs"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          }
        ],
        "responses": {
          "200": {
            "description": "Execução cancelada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Run"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "A execução já terminou.",
            "x-error-codes": [
              "run_already_finished"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/runs/{id}/events": {
      "get": {
        "operationId": "streamRunEvents",
        "summary": "Eventos da execução em tempo real (SSE)",
        "description": "Fluxo `text/event-stream`. Cada mensagem tem `id` (sequência monotônica), `event` (um dos\nnomes abaixo) e `data` (JSON com o esquema do evento). O servidor envia `: ping` a cada\n15 s; a conexão fecha após `completed`, `failed` ou `needs_approval`. Para retomar, envie\n`Last-Event-ID` com a última sequência recebida.\n",
        "tags": [
          "runs"
        ],
        "x-sse-events": {
          "stage_started": "#/components/schemas/RunEventStageStarted",
          "progress": "#/components/schemas/RunEventProgress",
          "token_usage": "#/components/schemas/RunEventTokenUsage",
          "finding": "#/components/schemas/RunEventFinding",
          "match": "#/components/schemas/RunEventMatch",
          "needs_approval": "#/components/schemas/RunEventNeedsApproval",
          "completed": "#/components/schemas/RunEventCompleted",
          "failed": "#/components/schemas/RunEventFailed"
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "name": "Last-Event-ID",
            "in": "header",
            "required": false,
            "description": "Última sequência recebida; o fluxo recomeça do evento seguinte.",
            "schema": {
              "type": "integer",
              "minimum": 0
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Fluxo de eventos.",
            "content": {
              "text/event-stream": {
                "schema": {
                  "$ref": "#/components/schemas/RunEvent"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/runs/{id}/findings": {
      "get": {
        "operationId": "listFindings",
        "summary": "Lista os achados de uma execução",
        "description": "Ordenados por severidade e valor em risco. Disponível enquanto a execução roda (parcial) e depois.",
        "tags": [
          "runs"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/Limit"
          },
          {
            "name": "severity",
            "in": "query",
            "description": "Uma ou mais severidades, separadas por vírgula.",
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/Severity"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "status",
            "in": "query",
            "schema": {
              "$ref": "#/components/schemas/FindingStatus"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Página de achados.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FindingList"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/runs/{id}/findings/{fid}/feedback": {
      "post": {
        "operationId": "giveFindingFeedback",
        "summary": "Confirma, descarta ou resolve um achado",
        "description": "O feedback alimenta a calibração da confiança e, nos planos com aprendizado, a proposta de regras.",
        "tags": [
          "runs"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "$ref": "#/components/parameters/FindingId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FindingFeedbackRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Achado atualizado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Finding"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução ou achado não encontrado.",
            "x-error-codes": [
              "run_not_found",
              "finding_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/Unprocessable"
          }
        }
      }
    },
    "/runs/{id}/export": {
      "get": {
        "operationId": "exportRun",
        "summary": "Exporta os resultados (xlsx, csv ou pdf)",
        "description": "Planilha com achados, casamentos e evidências; CSV só com achados; PDF com o relatório.\nSó para execuções concluídas. O arquivo é gerado sob demanda e cacheado.\n",
        "tags": [
          "runs"
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "name": "format",
            "in": "query",
            "required": true,
            "schema": {
              "$ref": "#/components/schemas/ExportFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "O arquivo.",
            "headers": {
              "Content-Disposition": {
                "description": "`attachment; filename=\"docmatch-<run_id>.<ext>\"`",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
                "schema": {
                  "$ref": "#/components/schemas/BinaryFile"
                }
              },
              "text/csv": {
                "schema": {
                  "type": "string"
                }
              },
              "application/pdf": {
                "schema": {
                  "$ref": "#/components/schemas/BinaryFile"
                }
              }
            }
          },
          "400": {
            "description": "Formato não suportado.",
            "x-error-codes": [
              "export_format_unsupported"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Execução não encontrada.",
            "x-error-codes": [
              "run_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "A execução ainda não terminou, ou o arquivo ainda está sendo gerado (tente de novo em instantes).",
            "x-error-codes": [
              "run_not_completed",
              "export_not_ready"
            ],
            "headers": {
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/runs/{id}/approve-quote": {
      "post": {
        "operationId": "approveRunQuote",
        "summary": "Aprova o orçamento adicional de uma execução parada",
        "description": "Quando a execução para em `needs_approval` (ferramentas novas, teto atingido), o cliente\naprova o novo orçamento recebido no evento. Reserva a diferença e retoma do checkpoint.\n",
        "tags": [
          "runs"
        ],
        "x-spends-credits": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/RunId"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApproveQuoteRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Execução retomada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Run"
                }
              }
            }
          },
          "400": {
            "description": "Orçamento adulterado ou header ausente.",
            "x-error-codes": [
              "quote_invalid_signature",
              "missing_idempotency_key",
              "validation_failed"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "description": "Créditos insuficientes para a diferença.",
            "x-error-codes": [
              "insufficient_credits"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Execução ou orçamento não encontrado.",
            "x-error-codes": [
              "run_not_found",
              "quote_not_found"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "A execução não está aguardando aprovação.",
            "x-error-codes": [
              "run_not_awaiting_approval",
              "idempotency_key_reused",
              "quote_mismatch"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "410": {
            "description": "Orçamento expirado; a execução foi cancelada e os créditos devolvidos.",
            "x-error-codes": [
              "quote_expired"
            ],
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "extensionSession": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "dmxA1_<session>.<secret>",
        "description": "Sessão da extensão. Permite contas, projetos e resultados conforme o vínculo atual; não administra cobrança, pessoas, senhas ou chaves. Não é uma chave de API e usa preços do app."
      },
      "cookieSession": {
        "type": "apiKey",
        "in": "cookie",
        "name": "dm_session",
        "description": "Sessão aberta pelo login (HttpOnly, Secure, SameSite=Lax). Renovada em `POST /auth/refresh`."
      },
      "apiKey": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "dm_live_<id>_<secret>",
        "description": "Chave de API criada em `POST /api-keys`. O servidor guarda só o HMAC da chave."
      }
    },
    "parameters": {
      "InvitationPath": {
        "name": "invitation",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/InvitationId"
        }
      },
      "TeamUserPath": {
        "name": "user",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/UserId"
        }
      },
      "OrgContext": {
        "name": "X-Docmatch-Org",
        "in": "header",
        "required": false,
        "description": "Conta escolhida nesta requisição. A sessão precisa de vínculo ativo. Uma chave de API só aceita sua própria conta. Não modifica outras abas.",
        "schema": {
          "$ref": "#/components/schemas/OrgId"
        }
      },
      "ProjectPath": {
        "name": "project",
        "in": "path",
        "required": true,
        "description": "Projeto da conta selecionada.",
        "schema": {
          "$ref": "#/components/schemas/ProjectId"
        }
      },
      "DocumentPath": {
        "name": "document",
        "in": "path",
        "required": true,
        "description": "Versão do documento no projeto.",
        "schema": {
          "$ref": "#/components/schemas/DocumentId"
        }
      },
      "ProjectUploadPath": {
        "name": "upload",
        "in": "path",
        "required": true,
        "description": "Upload recebido no projeto.",
        "schema": {
          "$ref": "#/components/schemas/UploadId"
        }
      },
      "ProjectVersion": {
        "name": "version",
        "in": "query",
        "required": true,
        "description": "Última versão recebida; uma edição concorrente retorna conflito.",
        "schema": {
          "type": "integer",
          "minimum": 1
        }
      },
      "IdempotencyKey": {
        "name": "Idempotency-Key",
        "in": "header",
        "required": true,
        "description": "Chave única por tentativa (UUID, por exemplo). Obrigatória em operações que gastam créditos; guardada por 24 h.",
        "schema": {
          "type": "string",
          "minLength": 1,
          "maxLength": 128,
          "x-limit": "ids.idempotency_key_max"
        }
      },
      "Cursor": {
        "name": "cursor",
        "in": "query",
        "description": "Cursor opaco devolvido em `next_cursor`.",
        "schema": {
          "type": "string",
          "maxLength": 128,
          "x-limit": "ids.idempotency_key_max"
        }
      },
      "Limit": {
        "name": "limit",
        "in": "query",
        "description": "Itens por página.",
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 100,
          "default": 25
        }
      },
      "RunId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/RunId"
        }
      },
      "FindingId": {
        "name": "fid",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/FindingId"
        }
      },
      "UploadId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/UploadId"
        }
      },
      "WorkflowId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/WorkflowId"
        }
      },
      "RuleId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/RuleId"
        }
      },
      "CustomizationId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/CustomizationId"
        }
      },
      "ApiKeyId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/ApiKeyId"
        }
      },
      "WebhookEndpointId": {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/WebhookEndpointId"
        }
      },
      "DmSignature": {
        "name": "DM-Signature",
        "in": "header",
        "required": true,
        "description": "`t=<unix>,v1=<hex>` onde `v1` é HMAC-SHA256 (segredo do endpoint) de `<t>.<corpo bruto>`.\nRejeite se `|agora - t|` > 5 minutos.\n",
        "schema": {
          "type": "string",
          "pattern": "^t=[0-9]{10},v1=[0-9a-f]{64}$"
        }
      },
      "DmEventId": {
        "name": "DM-Event-Id",
        "in": "header",
        "required": true,
        "description": "Id do evento (para deduplicar reenvios).",
        "schema": {
          "$ref": "#/components/schemas/EventId"
        }
      },
      "DmEventType": {
        "name": "DM-Event-Type",
        "in": "header",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/WebhookEventType"
        }
      }
    },
    "headers": {
      "RateLimitLimit": {
        "description": "Requisições permitidas na janela atual.",
        "schema": {
          "type": "integer"
        }
      },
      "RateLimitRemaining": {
        "description": "Requisições restantes na janela atual.",
        "schema": {
          "type": "integer"
        }
      },
      "RateLimitReset": {
        "description": "Segundos até a janela reiniciar.",
        "schema": {
          "type": "integer"
        }
      },
      "RetryAfter": {
        "description": "Segundos a esperar antes de tentar de novo.",
        "schema": {
          "type": "integer"
        }
      },
      "RequestId": {
        "description": "Id da requisição (o mesmo de `request_id` no envelope de erro).",
        "schema": {
          "type": "string"
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Entrada inválida.",
        "x-status": 400,
        "x-error-codes": [
          "validation_failed",
          "invalid_json",
          "control_characters",
          "missing_idempotency_key"
        ],
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/RequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "validation": {
                "value": {
                  "code": "validation_failed",
                  "message": "Alguns campos estão inválidos. Confira os detalhes.",
                  "request_id": "req_01JBXKEN8R4S9T0V1W2X3Y4Z5A",
                  "details": {
                    "fields": [
                      {
                        "path": "/display_name",
                        "code": "text_too_long",
                        "max": 80
                      }
                    ]
                  }
                }
              }
            }
          }
        }
      },
      "Unauthorized": {
        "description": "Sem sessão ou chave válida.",
        "x-status": 401,
        "x-error-codes": [
          "unauthenticated",
          "session_expired",
          "invalid_api_key"
        ],
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "PaymentRequired": {
        "description": "Créditos insuficientes ou assinatura necessária.",
        "x-status": 402,
        "x-error-codes": [
          "insufficient_credits",
          "subscription_required",
          "subscription_inactive"
        ],
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Forbidden": {
        "description": "Sem permissão.",
        "x-status": 403,
        "x-error-codes": [
          "forbidden",
          "api_key_scope_denied",
          "account_suspended",
          "account_deletion_pending",
          "plan_limit_reached"
        ],
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "NotFound": {
        "description": "Não encontrado.",
        "x-status": 404,
        "x-error-codes": [
          "not_found",
          "upload_not_found"
        ],
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Conflict": {
        "description": "Conflito com o estado atual ou chave de idempotência reutilizada.",
        "x-status": 409,
        "x-error-codes": [
          "conflict",
          "idempotency_key_reused",
          "idempotency_in_progress",
          "feature_paused"
        ],
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Unprocessable": {
        "description": "Texto fora dos limites.",
        "x-status": 422,
        "x-error-codes": [
          "text_too_long"
        ],
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "TooManyRequests": {
        "description": "Limite de requisições.",
        "x-status": 429,
        "x-error-codes": [
          "rate_limited",
          "too_many_attempts"
        ],
        "headers": {
          "Retry-After": {
            "$ref": "#/components/headers/RetryAfter"
          },
          "RateLimit-Limit": {
            "$ref": "#/components/headers/RateLimitLimit"
          },
          "RateLimit-Remaining": {
            "$ref": "#/components/headers/RateLimitRemaining"
          },
          "RateLimit-Reset": {
            "$ref": "#/components/headers/RateLimitReset"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "ServiceUnavailable": {
        "description": "Dependência indisponível ou função desativada.",
        "x-status": 503,
        "x-error-codes": [
          "service_unavailable",
          "harness_unavailable",
          "storage_unavailable",
          "model_unavailable",
          "kill_switch_enabled",
          "maintenance"
        ],
        "headers": {
          "Retry-After": {
            "$ref": "#/components/headers/RetryAfter"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      }
    },
    "schemas": {
      "DashboardMetrics": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "runs",
          "completed",
          "failed",
          "cancelled",
          "queued",
          "running",
          "needs_approval",
          "credits_spent",
          "lines_total",
          "lines_matched",
          "findings",
          "high_findings",
          "median_seconds"
        ],
        "properties": {
          "runs": {
            "type": "integer",
            "minimum": 0
          },
          "completed": {
            "type": "integer",
            "minimum": 0
          },
          "failed": {
            "type": "integer",
            "minimum": 0
          },
          "cancelled": {
            "type": "integer",
            "minimum": 0
          },
          "queued": {
            "type": "integer",
            "minimum": 0
          },
          "running": {
            "type": "integer",
            "minimum": 0
          },
          "needs_approval": {
            "type": "integer",
            "minimum": 0
          },
          "credits_spent": {
            "type": "integer",
            "minimum": 0
          },
          "lines_total": {
            "type": "integer",
            "minimum": 0
          },
          "lines_matched": {
            "type": "integer",
            "minimum": 0
          },
          "findings": {
            "type": "integer",
            "minimum": 0
          },
          "high_findings": {
            "type": "integer",
            "minimum": 0
          },
          "median_seconds": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0
          }
        }
      },
      "DashboardDay": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "date",
          "runs",
          "completed",
          "failed",
          "credits_spent"
        ],
        "properties": {
          "date": {
            "type": "string",
            "format": "date"
          },
          "runs": {
            "type": "integer",
            "minimum": 0
          },
          "completed": {
            "type": "integer",
            "minimum": 0
          },
          "failed": {
            "type": "integer",
            "minimum": 0
          },
          "credits_spent": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "DashboardRun": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "project_id",
          "project_name",
          "status",
          "created_at",
          "expired",
          "findings"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "project_id": {
            "type": "string"
          },
          "project_name": {
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/RunStatus"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "expired": {
            "type": "boolean"
          },
          "findings": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "DashboardProject": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "name",
          "documents",
          "updated_at",
          "last_status",
          "findings"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "documents": {
            "type": "integer",
            "minimum": 0
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "last_status": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/RunStatus"
              },
              {
                "type": "null"
              }
            ]
          },
          "findings": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "WorkspaceDashboard": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "from",
          "previous_from",
          "days",
          "time_zone",
          "current",
          "previous",
          "portfolio",
          "series",
          "recent",
          "attention",
          "projects"
        ],
        "properties": {
          "generated_at": {
            "type": "string",
            "format": "date-time"
          },
          "from": {
            "type": "string",
            "format": "date-time"
          },
          "previous_from": {
            "type": "string",
            "format": "date-time"
          },
          "days": {
            "type": "integer",
            "enum": [
              7,
              30,
              90
            ]
          },
          "time_zone": {
            "type": "string",
            "enum": [
              "America/Sao_Paulo"
            ]
          },
          "current": {
            "$ref": "#/components/schemas/DashboardMetrics"
          },
          "previous": {
            "$ref": "#/components/schemas/DashboardMetrics"
          },
          "portfolio": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "active",
              "archived",
              "documents",
              "unavailable_documents"
            ],
            "properties": {
              "active": {
                "type": "integer",
                "minimum": 0
              },
              "archived": {
                "type": "integer",
                "minimum": 0
              },
              "documents": {
                "type": "integer",
                "minimum": 0
              },
              "unavailable_documents": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "series": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DashboardDay"
            }
          },
          "recent": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DashboardRun"
            }
          },
          "attention": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DashboardRun"
            }
          },
          "projects": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DashboardProject"
            }
          }
        }
      },
      "ProjectUploadRequest": {
        "type": "object",
        "required": [
          "kind",
          "file_name",
          "size_bytes",
          "mime"
        ],
        "properties": {
          "kind": {
            "$ref": "#/components/schemas/UploadKind"
          },
          "file_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255,
            "x-limit": "files.uploaded_file_name_bytes",
            "description": "Nome original. O limite é em bytes UTF-8 após NFC; sem `/`, `\\` nem caracteres de controle."
          },
          "size_bytes": {
            "type": "integer",
            "minimum": 1
          },
          "mime": {
            "type": "string",
            "pattern": "^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$",
            "description": "Tipo declarado; o scanner sniffa o real e pode rejeitar."
          },
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Opcional; conferido em `complete`."
          },
          "role": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,39}$",
            "description": "Papel no fluxo (ex.: `bank_statement`)."
          },
          "replaces_id": {
            "$ref": "#/components/schemas/DocumentId",
            "description": "Prepara uma substituição sem retirar a versão anterior. Após a verificação, confirme pelo endpoint documents/{document}/replace."
          }
        },
        "additionalProperties": false
      },
      "Email": {
        "type": "string",
        "format": "email",
        "maxLength": 254,
        "x-limit": "text.email"
      },
      "InvitationId": {
        "type": "string",
        "pattern": "^inv_[0-9A-Z]{26}$"
      },
      "SeatRole": {
        "type": "string",
        "enum": [
          "uploader",
          "reconciler"
        ]
      },
      "InvitationStatus": {
        "type": "string",
        "enum": [
          "pending",
          "accepted",
          "declined",
          "expired",
          "revoked"
        ]
      },
      "TeamMember": {
        "type": "object",
        "required": [
          "id",
          "name",
          "email",
          "role",
          "joined_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/UserId"
          },
          "name": {
            "type": "string"
          },
          "email": {
            "$ref": "#/components/schemas/Email"
          },
          "role": {
            "$ref": "#/components/schemas/MembershipRole"
          },
          "joined_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "TeamInvitation": {
        "type": "object",
        "required": [
          "id",
          "email",
          "role",
          "status",
          "expires_at",
          "sent_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/InvitationId"
          },
          "email": {
            "$ref": "#/components/schemas/Email"
          },
          "role": {
            "$ref": "#/components/schemas/SeatRole"
          },
          "status": {
            "$ref": "#/components/schemas/InvitationStatus"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "sent_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "Team": {
        "type": "object",
        "required": [
          "id",
          "name",
          "kind",
          "role",
          "capabilities",
          "members",
          "invitations",
          "member_limit",
          "seat_price",
          "can_invite"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/OrgId"
          },
          "name": {
            "type": "string"
          },
          "kind": {
            "type": "string",
            "enum": [
              "personal",
              "team"
            ]
          },
          "role": {
            "$ref": "#/components/schemas/MembershipRole"
          },
          "capabilities": {
            "$ref": "#/components/schemas/AccountCapabilities"
          },
          "members": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/TeamMember"
            },
            "maxItems": 100,
            "x-limit": "ids.account_members_max"
          },
          "invitations": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/TeamInvitation"
            },
            "maxItems": 100,
            "x-limit": "ids.account_members_max"
          },
          "member_limit": {
            "type": "integer",
            "minimum": 1,
            "description": "Limite operacional de membros e convites pendentes; inclui o responsável."
          },
          "seat_price": {
            "type": "integer",
            "const": 0,
            "description": "Sem cobrança adicional por assento nesta versão."
          },
          "can_invite": {
            "type": "boolean"
          },
          "features": {
            "$ref": "#/components/schemas/AccountFeatures"
          }
        },
        "additionalProperties": false
      },
      "TeamCreate": {
        "type": "object",
        "required": [
          "name"
        ],
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120,
            "x-limit": "text.company_name"
          }
        },
        "additionalProperties": false
      },
      "TeamInvite": {
        "type": "object",
        "required": [
          "email",
          "role"
        ],
        "properties": {
          "email": {
            "$ref": "#/components/schemas/Email"
          },
          "role": {
            "$ref": "#/components/schemas/SeatRole"
          }
        },
        "additionalProperties": false
      },
      "TeamRoleChange": {
        "type": "object",
        "required": [
          "role"
        ],
        "properties": {
          "role": {
            "$ref": "#/components/schemas/SeatRole"
          }
        },
        "additionalProperties": false
      },
      "TeamTransfer": {
        "type": "object",
        "required": [
          "user_id"
        ],
        "properties": {
          "user_id": {
            "$ref": "#/components/schemas/UserId"
          }
        },
        "additionalProperties": false
      },
      "PendingInvitationAnswer": {
        "type": "object",
        "required": [
          "accept"
        ],
        "properties": {
          "accept": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "InvitationInbox": {
        "type": "object",
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/InvitationPreview"
            }
          },
          "next_cursor": {
            "$ref": "#/components/schemas/InvitationId"
          }
        },
        "additionalProperties": false
      },
      "InvitationPreviewRequest": {
        "type": "object",
        "required": [
          "token"
        ],
        "properties": {
          "token": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]{43}$",
            "description": "Segredo do convite recebido por e-mail. Enviar somente no corpo; nunca em URLs da API."
          }
        },
        "additionalProperties": false
      },
      "InvitationPreview": {
        "type": "object",
        "required": [
          "id",
          "organization",
          "email_hint",
          "role",
          "status",
          "expires_at",
          "email_matches"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/InvitationId"
          },
          "organization": {
            "type": "string"
          },
          "email_hint": {
            "type": "string"
          },
          "role": {
            "$ref": "#/components/schemas/SeatRole"
          },
          "status": {
            "$ref": "#/components/schemas/InvitationStatus"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "email_matches": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "InvitationAnswer": {
        "type": "object",
        "required": [
          "token",
          "accept"
        ],
        "properties": {
          "token": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]{43}$",
            "description": "Segredo do convite recebido por e-mail. Enviar somente no corpo; nunca em URLs da API."
          },
          "accept": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "InvitationAnswerResult": {
        "type": "object",
        "required": [
          "organization_id",
          "accepted"
        ],
        "properties": {
          "organization_id": {
            "$ref": "#/components/schemas/OrgId"
          },
          "accepted": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "ProjectId": {
        "type": "string",
        "pattern": "^prj_[0-9A-Z]{26}$"
      },
      "DocumentId": {
        "type": "string",
        "pattern": "^doc_[0-9A-Z]{26}$"
      },
      "MembershipRole": {
        "type": "string",
        "enum": [
          "owner",
          "admin",
          "member",
          "viewer",
          "uploader",
          "reconciler"
        ]
      },
      "AccountCapabilities": {
        "type": "object",
        "required": [
          "manage_account",
          "create_project",
          "reconcile",
          "read_results",
          "upload"
        ],
        "properties": {
          "manage_account": {
            "type": "boolean"
          },
          "create_project": {
            "type": "boolean"
          },
          "reconcile": {
            "type": "boolean"
          },
          "read_results": {
            "type": "boolean"
          },
          "upload": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "AccountFeatures": {
        "type": "object",
        "description": "Disponibilidade por conta; não substitui as permissões do participante.",
        "required": [
          "projects",
          "invitations",
          "extensions"
        ],
        "properties": {
          "projects": {
            "type": "boolean"
          },
          "invitations": {
            "type": "boolean"
          },
          "extensions": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "OrganizationMembership": {
        "type": "object",
        "required": [
          "id",
          "name",
          "kind",
          "role",
          "plan",
          "capabilities"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/OrgId"
          },
          "name": {
            "type": "string"
          },
          "kind": {
            "type": "string",
            "enum": [
              "personal",
              "team"
            ]
          },
          "role": {
            "$ref": "#/components/schemas/MembershipRole"
          },
          "plan": {
            "$ref": "#/components/schemas/PlanCode"
          },
          "capabilities": {
            "$ref": "#/components/schemas/AccountCapabilities"
          },
          "features": {
            "$ref": "#/components/schemas/AccountFeatures"
          }
        },
        "additionalProperties": false
      },
      "OrganizationList": {
        "type": "object",
        "required": [
          "user_id",
          "items"
        ],
        "properties": {
          "user_id": {
            "$ref": "#/components/schemas/UserId"
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OrganizationMembership"
            }
          }
        },
        "additionalProperties": false
      },
      "ProjectSettings": {
        "type": "object",
        "required": [
          "use_rules",
          "web_search"
        ],
        "properties": {
          "rules_text": {
            "type": "string",
            "maxLength": 4000,
            "x-limit": "text.rules_text"
          },
          "use_rules": {
            "type": "boolean",
            "default": true
          },
          "rule_ids": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/RuleId"
            },
            "maxItems": 50,
            "x-limit": "ids.project_rules_max"
          },
          "llm_mode": {
            "type": "string",
            "enum": [
              "",
              "off",
              "local",
              "openrouter"
            ]
          },
          "web_search": {
            "type": "boolean",
            "default": false
          }
        },
        "additionalProperties": false
      },
      "Project": {
        "type": "object",
        "required": [
          "id",
          "name",
          "visibility",
          "version",
          "revision",
          "document_count",
          "created_at",
          "updated_at",
          "archived_at",
          "capabilities"
        ],
        "properties": {
          "imported_run_id": {
            "$ref": "#/components/schemas/RunId",
            "description": "Resultado original preservado ao salvar o histórico; suas versões efetivas de regras podem não estar disponíveis."
          },
          "id": {
            "$ref": "#/components/schemas/ProjectId"
          },
          "name": {
            "type": "string",
            "maxLength": 120,
            "x-limit": "text.project_name",
            "minLength": 1
          },
          "visibility": {
            "type": "string",
            "enum": [
              "private",
              "team"
            ]
          },
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "revision": {
            "type": "integer",
            "minimum": 1
          },
          "settings": {
            "$ref": "#/components/schemas/ProjectSettings"
          },
          "document_count": {
            "type": "integer",
            "minimum": 0
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "updated_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "archived_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "capabilities": {
            "$ref": "#/components/schemas/AccountCapabilities"
          }
        },
        "additionalProperties": false
      },
      "ProjectDocument": {
        "type": "object",
        "required": [
          "id",
          "upload_id",
          "file_name",
          "role",
          "status",
          "size_bytes",
          "created_at",
          "expires_at",
          "removed_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/DocumentId"
          },
          "upload_id": {
            "$ref": "#/components/schemas/UploadId"
          },
          "replaces_id": {
            "$ref": "#/components/schemas/DocumentId"
          },
          "pending_replacement_id": {
            "$ref": "#/components/schemas/DocumentId"
          },
          "file_name": {
            "type": "string"
          },
          "role": {
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/UploadStatus"
          },
          "size_bytes": {
            "type": "integer",
            "minimum": 0
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "expires_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "removed_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          }
        },
        "additionalProperties": false
      },
      "ProjectList": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Project"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "additionalProperties": false
      },
      "ProjectCreate": {
        "type": "object",
        "required": [
          "name"
        ],
        "properties": {
          "name": {
            "type": "string",
            "maxLength": 120,
            "x-limit": "text.project_name",
            "minLength": 1
          }
        },
        "additionalProperties": false
      },
      "ProjectPatch": {
        "type": "object",
        "required": [
          "version"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "name": {
            "type": "string",
            "maxLength": 120,
            "x-limit": "text.project_name",
            "minLength": 1
          },
          "archived": {
            "type": "boolean"
          },
          "settings": {
            "$ref": "#/components/schemas/ProjectSettings"
          }
        },
        "additionalProperties": false
      },
      "ProjectSharing": {
        "type": "object",
        "required": [
          "version",
          "visibility",
          "user_ids"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "visibility": {
            "type": "string",
            "enum": [
              "private",
              "team"
            ]
          },
          "user_ids": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/UserId"
            },
            "maxItems": 100,
            "x-limit": "ids.project_members_max"
          }
        },
        "additionalProperties": false
      },
      "ProjectAttach": {
        "type": "object",
        "required": [
          "upload_id"
        ],
        "properties": {
          "upload_id": {
            "$ref": "#/components/schemas/UploadId"
          },
          "replaces_id": {
            "$ref": "#/components/schemas/DocumentId"
          },
          "role": {
            "type": "string",
            "pattern": "^([a-z][a-z0-9_]{0,39})?$"
          }
        },
        "additionalProperties": false
      },
      "ProjectAttachment": {
        "type": "object",
        "required": [
          "id"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/DocumentId"
          }
        },
        "additionalProperties": false
      },
      "ProjectReplacement": {
        "type": "object",
        "required": [
          "version",
          "replacement_id"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "replacement_id": {
            "$ref": "#/components/schemas/DocumentId"
          }
        },
        "additionalProperties": false
      },
      "ProjectActivity": {
        "type": "object",
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "id",
                "action",
                "created_at"
              ],
              "properties": {
                "id": {
                  "type": "integer",
                  "minimum": 1
                },
                "action": {
                  "type": "string"
                },
                "created_at": {
                  "$ref": "#/components/schemas/Timestamp"
                }
              },
              "additionalProperties": false
            }
          }
        },
        "additionalProperties": false
      },
      "ProjectAnalysisRequest": {
        "type": "object",
        "required": [
          "revision"
        ],
        "properties": {
          "revision": {
            "type": "integer",
            "minimum": 1
          },
          "lane": {
            "$ref": "#/components/schemas/Lane"
          },
          "reprocess_reason": {
            "type": "string",
            "maxLength": 500,
            "x-limit": "text.reprocess_reason"
          },
          "quote_id": {
            "$ref": "#/components/schemas/QuoteId"
          },
          "quote_signature": {
            "type": "string"
          }
        },
        "additionalProperties": false
      },
      "ProjectAnalysis": {
        "type": "object",
        "required": [
          "state",
          "revision"
        ],
        "properties": {
          "historical": {
            "type": "boolean",
            "description": "O resultado é o original importado, sem nova análise; não representa uma reconstrução das regras antigas."
          },
          "state": {
            "type": "string",
            "enum": [
              "ready",
              "unchanged",
              "queued",
              "running",
              "needs_approval",
              "completed",
              "failed",
              "cancelled",
              "expired"
            ]
          },
          "revision": {
            "type": "integer",
            "minimum": 1
          },
          "quote": {
            "$ref": "#/components/schemas/Quote"
          },
          "run": {
            "$ref": "#/components/schemas/Run"
          }
        },
        "additionalProperties": false
      },
      "ProjectDetail": {
        "type": "object",
        "required": [
          "id",
          "name",
          "visibility",
          "version",
          "revision",
          "document_count",
          "created_at",
          "updated_at",
          "archived_at",
          "capabilities",
          "documents"
        ],
        "properties": {
          "imported_run_id": {
            "$ref": "#/components/schemas/RunId",
            "description": "Resultado original preservado ao salvar o histórico; suas versões efetivas de regras podem não estar disponíveis."
          },
          "id": {
            "$ref": "#/components/schemas/ProjectId"
          },
          "name": {
            "type": "string",
            "maxLength": 120,
            "x-limit": "text.project_name",
            "minLength": 1
          },
          "visibility": {
            "type": "string",
            "enum": [
              "private",
              "team"
            ]
          },
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "revision": {
            "type": "integer",
            "minimum": 1
          },
          "settings": {
            "$ref": "#/components/schemas/ProjectSettings"
          },
          "document_count": {
            "type": "integer",
            "minimum": 0
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "updated_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "archived_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "capabilities": {
            "$ref": "#/components/schemas/AccountCapabilities"
          },
          "shared_with": {
            "type": "array",
            "description": "Pessoas escolhidas para um projeto privado; visível somente aos responsáveis.",
            "items": {
              "$ref": "#/components/schemas/UserId"
            },
            "maxItems": 100,
            "x-limit": "ids.project_members_max"
          },
          "documents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProjectDocument"
            }
          }
        },
        "additionalProperties": false
      },
      "Error": {
        "type": "object",
        "description": "Envelope de erro de toda resposta 4xx/5xx. Os códigos e mensagens vêm de `errors.yaml`.",
        "required": [
          "code",
          "message",
          "request_id"
        ],
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]*$",
            "description": "Código estável (ver `errors.yaml`)."
          },
          "message": {
            "type": "string",
            "description": "Mensagem em pt-BR para o usuário."
          },
          "request_id": {
            "type": "string",
            "description": "Id da requisição para suporte."
          },
          "details": {
            "type": "object",
            "description": "Dados estruturados do erro (ex.: `fields` em `validation_failed`, `reason` em `customization_refused`, `retry_after_s` em `rate_limited`).",
            "additionalProperties": true
          }
        },
        "additionalProperties": false,
        "examples": [
          {
            "code": "insufficient_credits",
            "message": "Créditos insuficientes para esta execução. Faça uma recarga ou reduza o escopo.",
            "request_id": "req_01JBXKEN8R4S9T0V1W2X3Y4Z5A",
            "details": {
              "required": 293,
              "available": 120
            }
          }
        ]
      },
      "Money": {
        "type": "object",
        "description": "Dinheiro como inteiro na menor unidade da moeda (centavos).",
        "required": [
          "amount",
          "currency"
        ],
        "properties": {
          "amount": {
            "type": "integer"
          },
          "currency": {
            "type": "string",
            "pattern": "^[A-Z]{3}$"
          }
        },
        "additionalProperties": false
      },
      "Timestamp": {
        "type": "string",
        "format": "date-time",
        "description": "RFC 3339 em UTC."
      },
      "RunId": {
        "type": "string",
        "pattern": "^run_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "UploadId": {
        "type": "string",
        "pattern": "^upl_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "FindingId": {
        "type": "string",
        "pattern": "^fnd_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "MatchId": {
        "type": "string",
        "pattern": "^mtc_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "QuoteId": {
        "type": "string",
        "pattern": "^qte_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "WorkflowId": {
        "type": "string",
        "pattern": "^wfl_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "RuleId": {
        "type": "string",
        "pattern": "^rul_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "OrgId": {
        "type": "string",
        "pattern": "^org_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "UserId": {
        "type": "string",
        "pattern": "^usr_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "CustomizationId": {
        "type": "string",
        "pattern": "^cst_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "ApiKeyId": {
        "type": "string",
        "pattern": "^key_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "WebhookEndpointId": {
        "type": "string",
        "pattern": "^whe_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "LedgerEntryId": {
        "type": "string",
        "pattern": "^ldg_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "EventId": {
        "type": "string",
        "pattern": "^evt_[0-9A-HJKMNP-TV-Z]{26}$"
      },
      "BinaryFile": {
        "type": "string",
        "format": "binary"
      },
      "Severity": {
        "type": "string",
        "enum": [
          "info",
          "low",
          "medium",
          "high",
          "critical"
        ]
      },
      "FindingStatus": {
        "type": "string",
        "enum": [
          "open",
          "confirmed",
          "dismissed",
          "resolved"
        ]
      },
      "RunStatus": {
        "type": "string",
        "enum": [
          "queued",
          "running",
          "needs_approval",
          "completed",
          "failed",
          "cancelled"
        ]
      },
      "Lane": {
        "type": "string",
        "enum": [
          "app",
          "api_batch",
          "api_standard",
          "api_priority"
        ],
        "description": "Faixa de prioridade (multiplicadores em config/pricing.yaml). Chaves de API só usam as faixas do plano."
      },
      "LlmMode": {
        "type": "string",
        "enum": [
          "openrouter",
          "local",
          "off"
        ]
      },
      "ExportFormat": {
        "type": "string",
        "enum": [
          "xlsx",
          "csv",
          "pdf"
        ]
      },
      "RuleStatus": {
        "type": "string",
        "enum": [
          "draft",
          "candidate",
          "verified",
          "trusted",
          "retired"
        ]
      },
      "RuleScope": {
        "type": "string",
        "enum": [
          "tenant",
          "global"
        ]
      },
      "PlanCode": {
        "type": "string",
        "enum": [
          "starter",
          "pro",
          "business"
        ]
      },
      "AuthStartRequest": {
        "type": "object",
        "properties": {
          "redirect_to": {
            "type": "string",
            "pattern": "^/[^/\\\\].*$|^/$",
            "description": "Caminho relativo no site para onde voltar depois do login (nunca uma URL absoluta)."
          },
          "platform": {
            "type": "string",
            "enum": [
              "web",
              "android",
              "ios"
            ],
            "default": "web"
          }
        },
        "additionalProperties": false
      },
      "AuthStartResponse": {
        "type": "object",
        "required": [
          "authorization_url",
          "state",
          "expires_at"
        ],
        "properties": {
          "authorization_url": {
            "type": "string",
            "format": "uri"
          },
          "state": {
            "type": "string"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "AppleCallbackForm": {
        "type": "object",
        "description": "Campos do `form_post` da Apple.",
        "required": [
          "code",
          "id_token",
          "state"
        ],
        "properties": {
          "code": {
            "type": "string"
          },
          "id_token": {
            "type": "string"
          },
          "state": {
            "type": "string"
          },
          "user": {
            "type": "string",
            "description": "JSON com nome e e-mail, só no primeiro login."
          }
        },
        "additionalProperties": false
      },
      "AppleNativeCallback": {
        "type": "object",
        "description": "Token obtido pelo app iOS com AuthenticationServices.",
        "required": [
          "identity_token",
          "authorization_code"
        ],
        "properties": {
          "identity_token": {
            "type": "string"
          },
          "authorization_code": {
            "type": "string"
          },
          "full_name": {
            "type": "string",
            "maxLength": 80,
            "x-limit": "text.display_name"
          }
        },
        "additionalProperties": false
      },
      "EmailStartRequest": {
        "type": "object",
        "required": [
          "email"
        ],
        "properties": {
          "email": {
            "type": "string",
            "format": "email",
            "maxLength": 254,
            "x-limit": "text.email"
          }
        },
        "additionalProperties": false
      },
      "EmailStartResponse": {
        "type": "object",
        "required": [
          "challenge_id",
          "expires_at",
          "resend_after_s"
        ],
        "properties": {
          "challenge_id": {
            "type": "string"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "resend_after_s": {
            "type": "integer",
            "minimum": 0
          }
        },
        "additionalProperties": false
      },
      "EmailVerifyRequest": {
        "type": "object",
        "required": [
          "challenge_id",
          "code"
        ],
        "properties": {
          "challenge_id": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "pattern": "^[0-9]{6}$|^[A-Za-z0-9_-]{43}$",
            "description": "O código de 6 dígitos digitado pelo usuário ou o token do link mágico recebido no mesmo e-mail (32 bytes em base64url)."
          }
        },
        "additionalProperties": false
      },
      "AuthMethods": {
        "type": "object",
        "required": [
          "email",
          "google",
          "apple",
          "password",
          "dev"
        ],
        "properties": {
          "email": {
            "type": "boolean"
          },
          "google": {
            "type": "boolean"
          },
          "apple": {
            "type": "boolean"
          },
          "password": {
            "type": "boolean"
          },
          "dev": {
            "type": "boolean",
            "description": "Login local sem provedor (só em desenvolvimento)."
          }
        },
        "additionalProperties": false
      },
      "GoogleNativeRequest": {
        "type": "object",
        "required": [
          "id_token"
        ],
        "properties": {
          "id_token": {
            "type": "string",
            "minLength": 1
          }
        },
        "additionalProperties": false
      },
      "DevLoginRequest": {
        "type": "object",
        "properties": {
          "email": {
            "type": "string",
            "format": "email",
            "maxLength": 254,
            "x-limit": "text.email",
            "description": "Vazio usa dev@docmatch.test."
          },
          "name": {
            "type": "string",
            "maxLength": 80,
            "x-limit": "text.display_name"
          }
        },
        "additionalProperties": false
      },
      "Device": {
        "type": "object",
        "required": [
          "id",
          "platform",
          "name",
          "created_at",
          "last_seen_at",
          "current"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^ses_[0-9A-Z]{26}$"
          },
          "platform": {
            "type": "string",
            "enum": [
              "web",
              "android",
              "ios"
            ]
          },
          "name": {
            "type": "string",
            "description": "Nome curto do aparelho (navegador e sistema, ou app e modelo)."
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "last_seen_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "ip_prefix": {
            "type": "string"
          },
          "current": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "DeviceList": {
        "type": "object",
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Device"
            }
          }
        },
        "additionalProperties": false
      },
      "PasswordLoginRequest": {
        "type": "object",
        "required": [
          "email",
          "password"
        ],
        "properties": {
          "email": {
            "type": "string",
            "format": "email",
            "maxLength": 254,
            "x-limit": "text.email"
          },
          "password": {
            "type": "string",
            "maxLength": 128,
            "x-limit": "text.password_max"
          },
          "totp_code": {
            "type": "string",
            "pattern": "^[0-9]{6}$",
            "description": "Reservado para o segundo fator (ainda não ativado)."
          }
        },
        "additionalProperties": false
      },
      "PasswordChangeRequest": {
        "type": "object",
        "required": [
          "new_password"
        ],
        "properties": {
          "current_password": {
            "type": "string",
            "maxLength": 128,
            "x-limit": "text.password_max"
          },
          "new_password": {
            "type": "string",
            "minLength": 12,
            "maxLength": 128,
            "x-limit": "text.password_max",
            "description": "Entre `text.password_min` e `text.password_max` caracteres de `limits.yaml`."
          }
        },
        "additionalProperties": false
      },
      "Session": {
        "type": "object",
        "required": [
          "user",
          "org",
          "expires_at"
        ],
        "properties": {
          "user": {
            "$ref": "#/components/schemas/User"
          },
          "org": {
            "$ref": "#/components/schemas/Org"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "User": {
        "type": "object",
        "required": [
          "id",
          "email",
          "display_name",
          "role",
          "locale",
          "created_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/UserId"
          },
          "email": {
            "type": "string",
            "format": "email"
          },
          "display_name": {
            "type": "string",
            "maxLength": 80,
            "x-limit": "text.display_name"
          },
          "membership_role": {
            "$ref": "#/components/schemas/MembershipRole"
          },
          "role": {
            "type": "string",
            "enum": [
              "owner",
              "member"
            ]
          },
          "locale": {
            "type": "string",
            "const": "pt-BR"
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "Org": {
        "type": "object",
        "required": [
          "id",
          "name",
          "plan",
          "plan_status",
          "created_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/OrgId"
          },
          "name": {
            "type": "string",
            "maxLength": 120,
            "x-limit": "text.company_name"
          },
          "plan": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PlanCode"
              },
              {
                "type": "null"
              }
            ],
            "description": "Nulo sem assinatura."
          },
          "plan_status": {
            "type": "string",
            "enum": [
              "none",
              "trialing",
              "active",
              "past_due",
              "cancelled"
            ]
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "Entitlements": {
        "type": "object",
        "description": "Limites efetivos do plano (config/pricing.yaml), já aplicados os overrides administrativos.",
        "required": [
          "document_files_per_run",
          "document_file_mb",
          "document_run_mb",
          "media_files_per_run",
          "media_run_gb",
          "media_run_hours",
          "concurrent_runs",
          "api_keys",
          "api_lanes",
          "auto_rule_learning",
          "ui_customizations_per_month",
          "escalation_model",
          "retention_days"
        ],
        "properties": {
          "document_files_per_run": {
            "type": "integer",
            "minimum": 0
          },
          "document_file_mb": {
            "type": "integer",
            "minimum": 0
          },
          "document_run_mb": {
            "type": "integer",
            "minimum": 0
          },
          "media_files_per_run": {
            "type": "integer",
            "minimum": 0
          },
          "media_run_gb": {
            "type": "integer",
            "minimum": 0
          },
          "media_run_hours": {
            "type": "integer",
            "minimum": 0
          },
          "concurrent_runs": {
            "type": "integer",
            "minimum": 0
          },
          "api_keys": {
            "type": "integer",
            "minimum": 0
          },
          "api_lanes": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Lane"
            }
          },
          "auto_rule_learning": {
            "type": "boolean"
          },
          "ui_customizations_per_month": {
            "type": "integer",
            "minimum": -1,
            "description": "-1 é ilimitado."
          },
          "escalation_model": {
            "type": "boolean"
          },
          "retention_days": {
            "type": "integer",
            "minimum": 1
          }
        },
        "additionalProperties": false
      },
      "Me": {
        "type": "object",
        "required": [
          "user",
          "org",
          "credits",
          "entitlements"
        ],
        "properties": {
          "user": {
            "$ref": "#/components/schemas/User"
          },
          "org": {
            "$ref": "#/components/schemas/Org"
          },
          "credits": {
            "$ref": "#/components/schemas/CreditSummary"
          },
          "entitlements": {
            "$ref": "#/components/schemas/Entitlements"
          },
          "notifications": {
            "$ref": "#/components/schemas/NotificationPrefs"
          }
        },
        "additionalProperties": false
      },
      "NotificationPrefs": {
        "type": "object",
        "properties": {
          "run_completed": {
            "type": "boolean",
            "default": true
          },
          "credits_low": {
            "type": "boolean",
            "default": true
          },
          "product_news": {
            "type": "boolean",
            "default": false
          }
        },
        "additionalProperties": false
      },
      "MeUpdate": {
        "type": "object",
        "minProperties": 1,
        "properties": {
          "display_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 80,
            "x-limit": "text.display_name"
          },
          "company_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120,
            "x-limit": "text.company_name"
          },
          "notifications": {
            "$ref": "#/components/schemas/NotificationPrefs"
          }
        },
        "additionalProperties": false
      },
      "DeletionScheduled": {
        "type": "object",
        "required": [
          "scheduled_for"
        ],
        "properties": {
          "scheduled_for": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "ExportStatus": {
        "type": "object",
        "required": [
          "status",
          "requested_at"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "ready",
              "expired"
            ]
          },
          "requested_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "download_url": {
            "type": "string",
            "format": "uri",
            "description": "URL assinada, presente quando `ready`."
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "UploadKind": {
        "type": "string",
        "enum": [
          "document",
          "media"
        ]
      },
      "UploadRequest": {
        "type": "object",
        "required": [
          "kind",
          "file_name",
          "size_bytes",
          "mime"
        ],
        "properties": {
          "kind": {
            "$ref": "#/components/schemas/UploadKind"
          },
          "file_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255,
            "x-limit": "files.uploaded_file_name_bytes",
            "description": "Nome original. O limite é em bytes UTF-8 após NFC; sem `/`, `\\` nem caracteres de controle."
          },
          "size_bytes": {
            "type": "integer",
            "minimum": 1
          },
          "mime": {
            "type": "string",
            "pattern": "^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$",
            "description": "Tipo declarado; o scanner sniffa o real e pode rejeitar."
          },
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Opcional; conferido em `complete`."
          },
          "role": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,39}$",
            "description": "Papel no fluxo (ex.: `bank_statement`)."
          }
        },
        "additionalProperties": false
      },
      "UploadTicket": {
        "oneOf": [
          {
            "$ref": "#/components/schemas/DocumentUploadTicket"
          },
          {
            "$ref": "#/components/schemas/MediaUploadTicket"
          }
        ],
        "discriminator": {
          "propertyName": "kind",
          "mapping": {
            "document": "#/components/schemas/DocumentUploadTicket",
            "media": "#/components/schemas/MediaUploadTicket"
          }
        }
      },
      "DocumentUploadTicket": {
        "type": "object",
        "description": "POST pré-assinado para o S3 (`multipart/form-data` com `fields` + `file`).",
        "required": [
          "id",
          "kind",
          "method",
          "url",
          "fields",
          "expires_at",
          "max_size_bytes"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/UploadId"
          },
          "kind": {
            "type": "string",
            "const": "document"
          },
          "method": {
            "type": "string",
            "const": "POST"
          },
          "url": {
            "type": "string",
            "format": "uri"
          },
          "fields": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "max_size_bytes": {
            "type": "integer"
          }
        },
        "additionalProperties": false
      },
      "MediaUploadTicket": {
        "type": "object",
        "description": "PUT pré-assinado para o Cloudflare R2; envie o corpo bruto com os `headers`.",
        "required": [
          "id",
          "kind",
          "method",
          "url",
          "headers",
          "expires_at",
          "max_size_bytes"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/UploadId"
          },
          "kind": {
            "type": "string",
            "const": "media"
          },
          "method": {
            "type": "string",
            "const": "PUT"
          },
          "url": {
            "type": "string",
            "format": "uri"
          },
          "headers": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "max_size_bytes": {
            "type": "integer"
          }
        },
        "additionalProperties": false
      },
      "UploadCompleteRequest": {
        "type": "object",
        "properties": {
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "etag": {
            "type": "string"
          }
        },
        "additionalProperties": false
      },
      "UploadStatus": {
        "type": "string",
        "enum": [
          "pending",
          "scanning",
          "ready",
          "rejected",
          "expired"
        ]
      },
      "UploadRejectedReason": {
        "type": "string",
        "enum": [
          "type",
          "size",
          "malware",
          "bomb",
          "playlist",
          "name",
          "checksum"
        ],
        "description": "Motivo da rejeição; corresponde aos códigos `upload_rejected_*` e `upload_checksum_mismatch`."
      },
      "Upload": {
        "type": "object",
        "required": [
          "id",
          "kind",
          "file_name",
          "size_bytes",
          "status",
          "created_at",
          "expires_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/UploadId"
          },
          "kind": {
            "$ref": "#/components/schemas/UploadKind"
          },
          "file_name": {
            "type": "string"
          },
          "size_bytes": {
            "type": "integer"
          },
          "mime": {
            "type": "string",
            "description": "Tipo detectado pelo conteúdo (após a verificação)."
          },
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "status": {
            "$ref": "#/components/schemas/UploadStatus"
          },
          "rejected_reason": {
            "$ref": "#/components/schemas/UploadRejectedReason"
          },
          "duration_ms": {
            "type": "integer",
            "minimum": 0,
            "description": "Só mídia."
          },
          "role": {
            "type": "string"
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp",
            "description": "Retenção do plano."
          }
        },
        "additionalProperties": false
      },
      "LocatorHints": {
        "$ref": "./schemas/workflow-config.json#/$defs/LocatorHints"
      },
      "RunSource": {
        "type": "object",
        "required": [
          "upload_id"
        ],
        "properties": {
          "upload_id": {
            "$ref": "#/components/schemas/UploadId"
          },
          "role": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,39}$"
          },
          "hints": {
            "$ref": "#/components/schemas/LocatorHints"
          }
        },
        "additionalProperties": false
      },
      "RunOptions": {
        "type": "object",
        "properties": {
          "llm_mode": {
            "$ref": "#/components/schemas/LlmMode"
          },
          "web_search": {
            "type": "boolean",
            "default": false
          },
          "use_rules": {
            "type": "boolean",
            "default": true
          },
          "rule_ids": {
            "type": "array",
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/RuleId"
            }
          },
          "lane": {
            "$ref": "#/components/schemas/Lane"
          },
          "escalation": {
            "type": "boolean",
            "default": false,
            "description": "Permite o modelo de escalonamento (plano business)."
          }
        },
        "additionalProperties": false
      },
      "EstimateRequest": {
        "type": "object",
        "required": [
          "sources"
        ],
        "properties": {
          "sources": {
            "type": "array",
            "minItems": 1,
            "maxItems": 100,
            "x-limit": "ids.files_per_run_hard_max",
            "items": {
              "$ref": "#/components/schemas/RunSource"
            },
            "description": "Documentos e planilhas. O plano pode permitir menos que o teto."
          },
          "media_sources": {
            "type": "array",
            "maxItems": 50000,
            "x-limit": "ids.media_files_per_run_hard_max",
            "items": {
              "$ref": "#/components/schemas/RunSource"
            },
            "description": "Áudios e vídeos."
          },
          "workflow_id": {
            "$ref": "#/components/schemas/WorkflowId"
          },
          "rules_text": {
            "type": "string",
            "maxLength": 4000,
            "x-limit": "text.rules_text",
            "description": "Regras avulsas em linguagem natural para esta execução."
          },
          "options": {
            "$ref": "#/components/schemas/RunOptions"
          }
        },
        "additionalProperties": false
      },
      "RunCreateRequest": {
        "allOf": [
          {
            "$ref": "#/components/schemas/EstimateRequest"
          },
          {
            "type": "object",
            "required": [
              "quote_id",
              "quote_signature"
            ],
            "properties": {
              "quote_id": {
                "$ref": "#/components/schemas/QuoteId"
              },
              "quote_signature": {
                "type": "string",
                "pattern": "^v1=[0-9a-f]{64}$"
              }
            }
          }
        ],
        "description": "O mesmo pedido da estimativa mais o orçamento aceito. Fontes ou opções diferentes do orçamento devolvem `quote_mismatch`."
      },
      "ApproveQuoteRequest": {
        "type": "object",
        "required": [
          "quote_id",
          "quote_signature"
        ],
        "properties": {
          "quote_id": {
            "$ref": "#/components/schemas/QuoteId"
          },
          "quote_signature": {
            "type": "string",
            "pattern": "^v1=[0-9a-f]{64}$"
          }
        },
        "additionalProperties": false
      },
      "Quote": {
        "$ref": "./schemas/quote.json"
      },
      "RunCredits": {
        "type": "object",
        "required": [
          "reserved",
          "spent",
          "refunded"
        ],
        "properties": {
          "reserved": {
            "type": "integer",
            "minimum": 0
          },
          "spent": {
            "type": "integer",
            "minimum": 0
          },
          "refunded": {
            "type": "integer",
            "minimum": 0
          }
        },
        "additionalProperties": false
      },
      "RunStage": {
        "type": "string",
        "enum": [
          "scan",
          "ingest",
          "normalize",
          "match",
          "discover",
          "adjudicate",
          "verify",
          "toolsmith",
          "report"
        ]
      },
      "RunProgress": {
        "type": "object",
        "required": [
          "stage",
          "percent"
        ],
        "properties": {
          "stage": {
            "$ref": "#/components/schemas/RunStage"
          },
          "percent": {
            "type": "integer",
            "minimum": 0,
            "maximum": 100
          },
          "message": {
            "type": "string",
            "description": "Em pt-BR, para o painel de progresso."
          }
        },
        "additionalProperties": false
      },
      "RunSummary": {
        "type": "object",
        "required": [
          "findings_total",
          "findings_by_severity",
          "amount_at_risk",
          "currency",
          "matches_total",
          "lines_total",
          "lines_matched"
        ],
        "properties": {
          "findings_total": {
            "type": "integer",
            "minimum": 0
          },
          "findings_by_severity": {
            "type": "object",
            "properties": {
              "info": {
                "type": "integer"
              },
              "low": {
                "type": "integer"
              },
              "medium": {
                "type": "integer"
              },
              "high": {
                "type": "integer"
              },
              "critical": {
                "type": "integer"
              }
            },
            "additionalProperties": false
          },
          "amount_at_risk": {
            "type": "integer",
            "minimum": 0,
            "description": "Soma em centavos."
          },
          "currency": {
            "type": "string",
            "pattern": "^[A-Z]{3}$"
          },
          "matches_total": {
            "type": "integer",
            "minimum": 0
          },
          "lines_total": {
            "type": "integer",
            "minimum": 0
          },
          "lines_matched": {
            "type": "integer",
            "minimum": 0
          },
          "new_tool_ids": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "proposed_rule_ids": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/RuleId"
            }
          },
          "source_warnings": {
            "type": "array",
            "maxItems": 100,
            "x-limit": "ids.source_warnings_per_run",
            "description": "Em pt-BR, por arquivo, o que não entrou na conciliação (PDF digitalizado, carteira sem títulos em aberto, arquivo não reconhecido).",
            "items": {
              "type": "string",
              "maxLength": 500,
              "x-limit": "text.source_warning"
            }
          },
          "reconciliation": {
            "$ref": "#/components/schemas/ReconciliationDocument"
          }
        },
        "additionalProperties": false
      },
      "ReconciliationDocument": {
        "type": "object",
        "description": "Documento conciliado das fontes enviadas. Valores em centavos; propostas não reduzem o saldo confirmado. Disponível em novas execuções.",
        "required": [
          "version",
          "title",
          "currency",
          "period_start",
          "period_end",
          "receivables",
          "bank_entries",
          "totals"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "enum": [
              1
            ]
          },
          "title": {
            "type": "string"
          },
          "currency": {
            "type": "string",
            "enum": [
              "BRL"
            ]
          },
          "period_start": {
            "type": "string"
          },
          "period_end": {
            "type": "string"
          },
          "receivables": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ReconciledReceivable"
            }
          },
          "bank_entries": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ReconciledBankEntry"
            }
          },
          "totals": {
            "type": "object",
            "required": [
              "original_amount",
              "duplicate_excluded",
              "received_confirmed",
              "principal_confirmed",
              "open_balance",
              "proposed_amount",
              "projected_open_balance",
              "unapplied_cash",
              "bank_fees",
              "fines_received",
              "withholding_pending"
            ],
            "properties": {
              "original_amount": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "duplicate_excluded": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "received_confirmed": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "principal_confirmed": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "open_balance": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "proposed_amount": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "projected_open_balance": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "unapplied_cash": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "bank_fees": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "fines_received": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              },
              "withholding_pending": {
                "type": "integer",
                "format": "int64",
                "description": "Valor em centavos."
              }
            },
            "additionalProperties": false
          }
        },
        "additionalProperties": false
      },
      "ReconciledReceivable": {
        "type": "object",
        "required": [
          "id",
          "source_id",
          "source_name",
          "reference",
          "customer",
          "tax_id",
          "due_date",
          "paid_on",
          "status",
          "duplicate_of",
          "source_row",
          "original_amount",
          "received_amount",
          "applied_principal",
          "open_amount",
          "proposed_amount",
          "fine_received",
          "withholding_pending",
          "bank_rows",
          "flags"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "source_id": {
            "type": "string"
          },
          "source_name": {
            "type": "string"
          },
          "reference": {
            "type": "string"
          },
          "customer": {
            "type": "string"
          },
          "tax_id": {
            "type": "string"
          },
          "due_date": {
            "type": "string"
          },
          "paid_on": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "duplicate_of": {
            "type": "string"
          },
          "source_row": {
            "type": "integer",
            "minimum": 1
          },
          "original_amount": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "received_amount": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "applied_principal": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "open_amount": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "proposed_amount": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "fine_received": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "withholding_pending": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "bank_rows": {
            "type": "array",
            "items": {
              "type": "integer"
            }
          },
          "flags": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "additionalProperties": false
      },
      "ReconciledBankEntry": {
        "type": "object",
        "required": [
          "date",
          "description",
          "kind",
          "rule",
          "source_id",
          "source_name",
          "row",
          "amount",
          "proposed",
          "matched_ids"
        ],
        "properties": {
          "date": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "kind": {
            "type": "string"
          },
          "rule": {
            "type": "string"
          },
          "source_id": {
            "type": "string"
          },
          "source_name": {
            "type": "string"
          },
          "row": {
            "type": "integer"
          },
          "amount": {
            "type": "integer",
            "format": "int64",
            "description": "Valor em centavos."
          },
          "proposed": {
            "type": "boolean"
          },
          "matched_ids": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "additionalProperties": false
      },
      "RunError": {
        "type": "object",
        "description": "Falha de uma execução (código de `errors.yaml`).",
        "required": [
          "code",
          "message",
          "retryable"
        ],
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]*$"
          },
          "message": {
            "type": "string"
          },
          "retryable": {
            "type": "boolean"
          },
          "details": {
            "type": "object",
            "additionalProperties": true
          }
        },
        "additionalProperties": false
      },
      "Run": {
        "type": "object",
        "required": [
          "id",
          "status",
          "lane",
          "sources",
          "credits",
          "created_at",
          "expires_at"
        ],
        "properties": {
          "can_save_as_project": {
            "type": "boolean",
            "description": "Na atividade da conta, indica se a pessoa pode salvar esta conciliação anterior como projeto. A permissão é revalidada ao salvar."
          },
          "project_id": {
            "$ref": "#/components/schemas/ProjectId"
          },
          "id": {
            "$ref": "#/components/schemas/RunId"
          },
          "status": {
            "$ref": "#/components/schemas/RunStatus"
          },
          "workflow_id": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/WorkflowId"
              },
              {
                "type": "null"
              }
            ]
          },
          "lane": {
            "$ref": "#/components/schemas/Lane"
          },
          "sources": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Upload"
            }
          },
          "quote": {
            "$ref": "#/components/schemas/Quote"
          },
          "pending_quote": {
            "$ref": "#/components/schemas/Quote",
            "description": "Orçamento adicional aguardando aprovação (só em `needs_approval`)."
          },
          "credits": {
            "$ref": "#/components/schemas/RunCredits"
          },
          "progress": {
            "$ref": "#/components/schemas/RunProgress"
          },
          "summary": {
            "$ref": "#/components/schemas/RunSummary"
          },
          "error": {
            "$ref": "#/components/schemas/RunError"
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "started_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "finished_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp",
            "description": "Fim da retenção do plano; depois disso arquivos e resultados são apagados."
          }
        },
        "additionalProperties": false
      },
      "RunList": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Run"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "additionalProperties": false
      },
      "Finding": {
        "$ref": "./schemas/finding.json"
      },
      "Evidence": {
        "$ref": "./schemas/finding.json#/$defs/Evidence"
      },
      "FindingList": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Finding"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "additionalProperties": false
      },
      "FindingFeedbackRequest": {
        "type": "object",
        "required": [
          "status"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "confirmed",
              "dismissed",
              "resolved"
            ]
          },
          "reason": {
            "type": "string",
            "enum": [
              "false_positive",
              "already_known",
              "wrong_amount",
              "duplicate",
              "other"
            ]
          },
          "note": {
            "type": "string",
            "maxLength": 500,
            "x-limit": "text.finding_feedback_note"
          }
        },
        "additionalProperties": false
      },
      "Match": {
        "type": "object",
        "description": "Casamento entre linhas de fontes diferentes (ou grupo um-para-muitos).",
        "required": [
          "id",
          "run_id",
          "kind",
          "left",
          "right",
          "confidence",
          "created_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/MatchId"
          },
          "run_id": {
            "$ref": "#/components/schemas/RunId"
          },
          "kind": {
            "type": "string",
            "enum": [
              "exact",
              "tolerance",
              "sum",
              "fuzzy",
              "rule",
              "model"
            ]
          },
          "left": {
            "type": "array",
            "minItems": 1,
            "items": {
              "$ref": "#/components/schemas/Evidence"
            }
          },
          "right": {
            "type": "array",
            "minItems": 1,
            "items": {
              "$ref": "#/components/schemas/Evidence"
            }
          },
          "confidence": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
          },
          "amount": {
            "type": "integer",
            "description": "Centavos."
          },
          "currency": {
            "type": "string",
            "pattern": "^[A-Z]{3}$"
          },
          "rule_id": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/RuleId"
              },
              {
                "type": "null"
              }
            ]
          },
          "explanation": {
            "type": "string"
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "RunEvent": {
        "type": "object",
        "description": "Um evento do fluxo `text/event-stream`: `id` é a sequência (use em `Last-Event-ID`),\n`event` é o nome e `data` segue o esquema do evento (também listados em `x-sse-events`\nda operação). No fio, cada evento é serializado como:\n\n```\nid: 42\nevent: finding\ndata: {\"finding\": {...}}\n```\n",
        "required": [
          "id",
          "event",
          "data"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "event": {
            "type": "string",
            "enum": [
              "stage_started",
              "progress",
              "token_usage",
              "finding",
              "match",
              "needs_approval",
              "completed",
              "failed"
            ]
          },
          "data": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/RunEventStageStarted"
              },
              {
                "$ref": "#/components/schemas/RunEventProgress"
              },
              {
                "$ref": "#/components/schemas/RunEventTokenUsage"
              },
              {
                "$ref": "#/components/schemas/RunEventFinding"
              },
              {
                "$ref": "#/components/schemas/RunEventMatch"
              },
              {
                "$ref": "#/components/schemas/RunEventNeedsApproval"
              },
              {
                "$ref": "#/components/schemas/RunEventCompleted"
              },
              {
                "$ref": "#/components/schemas/RunEventFailed"
              }
            ]
          }
        },
        "additionalProperties": false
      },
      "RunEventStageStarted": {
        "type": "object",
        "required": [
          "stage"
        ],
        "properties": {
          "stage": {
            "$ref": "#/components/schemas/RunStage"
          },
          "message": {
            "type": "string"
          },
          "total_steps": {
            "type": "integer",
            "minimum": 0
          }
        },
        "additionalProperties": false
      },
      "RunEventProgress": {
        "type": "object",
        "required": [
          "stage",
          "done",
          "total"
        ],
        "properties": {
          "stage": {
            "$ref": "#/components/schemas/RunStage"
          },
          "done": {
            "type": "integer",
            "minimum": 0
          },
          "total": {
            "type": "integer",
            "minimum": 0
          },
          "message": {
            "type": "string"
          },
          "credits_spent": {
            "type": "integer",
            "minimum": 0
          }
        },
        "additionalProperties": false
      },
      "RunEventTokenUsage": {
        "type": "object",
        "required": [
          "role",
          "model",
          "prompt_tokens",
          "completion_tokens",
          "credits",
          "credits_spent_total"
        ],
        "properties": {
          "role": {
            "type": "string",
            "description": "Papel de config/models.yaml."
          },
          "model": {
            "type": "string"
          },
          "prompt_tokens": {
            "type": "integer",
            "minimum": 0
          },
          "completion_tokens": {
            "type": "integer",
            "minimum": 0
          },
          "cached_tokens": {
            "type": "integer",
            "minimum": 0
          },
          "credits": {
            "type": "integer",
            "minimum": 0
          },
          "credits_spent_total": {
            "type": "integer",
            "minimum": 0
          },
          "cached": {
            "type": "boolean"
          }
        },
        "additionalProperties": false
      },
      "RunEventFinding": {
        "type": "object",
        "required": [
          "finding"
        ],
        "properties": {
          "finding": {
            "$ref": "#/components/schemas/Finding"
          }
        },
        "additionalProperties": false
      },
      "RunEventMatch": {
        "type": "object",
        "required": [
          "match"
        ],
        "properties": {
          "match": {
            "$ref": "#/components/schemas/Match"
          }
        },
        "additionalProperties": false
      },
      "RunEventNeedsApproval": {
        "type": "object",
        "required": [
          "quote",
          "reasons",
          "credits_spent_so_far"
        ],
        "properties": {
          "quote": {
            "$ref": "#/components/schemas/Quote"
          },
          "reasons": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "new_tools",
                "over_default_budget",
                "media_heavy",
                "web_search",
                "escalation_model"
              ]
            }
          },
          "message": {
            "type": "string"
          },
          "credits_spent_so_far": {
            "type": "integer",
            "minimum": 0
          }
        },
        "additionalProperties": false
      },
      "RunEventCompleted": {
        "type": "object",
        "required": [
          "summary",
          "credits_spent",
          "credits_refunded"
        ],
        "properties": {
          "summary": {
            "$ref": "#/components/schemas/RunSummary"
          },
          "credits_spent": {
            "type": "integer",
            "minimum": 0
          },
          "credits_refunded": {
            "type": "integer",
            "minimum": 0
          }
        },
        "additionalProperties": false
      },
      "RunEventFailed": {
        "type": "object",
        "required": [
          "error",
          "credits_spent"
        ],
        "properties": {
          "error": {
            "$ref": "#/components/schemas/RunError"
          },
          "credits_spent": {
            "type": "integer",
            "minimum": 0
          }
        },
        "additionalProperties": false
      },
      "WorkflowConfig": {
        "$ref": "./schemas/workflow-config.json"
      },
      "WorkflowPatch": {
        "type": "object",
        "description": "Seções de `WorkflowConfig`, todas opcionais; as enviadas substituem as atuais por inteiro.",
        "minProperties": 1,
        "properties": {
          "name": {
            "$ref": "./schemas/workflow-config.json#/properties/name"
          },
          "sources": {
            "$ref": "./schemas/workflow-config.json#/properties/sources"
          },
          "matching": {
            "$ref": "./schemas/workflow-config.json#/$defs/Matching"
          },
          "rules": {
            "$ref": "./schemas/workflow-config.json#/$defs/Rules"
          },
          "llm": {
            "$ref": "./schemas/workflow-config.json#/properties/llm"
          },
          "budget": {
            "$ref": "./schemas/workflow-config.json#/properties/budget"
          },
          "outputs": {
            "$ref": "./schemas/workflow-config.json#/properties/outputs"
          }
        },
        "additionalProperties": false
      },
      "Workflow": {
        "type": "object",
        "required": [
          "id",
          "org_id",
          "config",
          "runs_count",
          "created_at",
          "updated_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/WorkflowId"
          },
          "org_id": {
            "$ref": "#/components/schemas/OrgId"
          },
          "config": {
            "$ref": "#/components/schemas/WorkflowConfig"
          },
          "runs_count": {
            "type": "integer",
            "minimum": 0
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "updated_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "WorkflowList": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Workflow"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "additionalProperties": false
      },
      "Rule": {
        "$ref": "./schemas/rule.json"
      },
      "RuleList": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Rule"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "additionalProperties": false
      },
      "RuleCreateRequest": {
        "type": "object",
        "required": [
          "title",
          "body"
        ],
        "properties": {
          "title": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120,
            "x-limit": "text.saved_rule_title"
          },
          "body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "x-limit": "text.saved_rule_body"
          },
          "applies_to": {
            "$ref": "./schemas/rule.json#/properties/applies_to"
          },
          "compile": {
            "type": "boolean",
            "default": true,
            "description": "Falso salva como `draft` sem gastar créditos."
          }
        },
        "additionalProperties": false
      },
      "RuleVersionRequest": {
        "type": "object",
        "required": [
          "body"
        ],
        "properties": {
          "title": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120,
            "x-limit": "text.saved_rule_title"
          },
          "body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "x-limit": "text.saved_rule_body"
          }
        },
        "additionalProperties": false
      },
      "RulePromoteRequest": {
        "type": "object",
        "required": [
          "to"
        ],
        "properties": {
          "to": {
            "type": "string",
            "enum": [
              "verified",
              "trusted",
              "retired"
            ]
          }
        },
        "additionalProperties": false
      },
      "BillingStatus": {
        "type": "object",
        "required": [
          "enabled",
          "test_mode",
          "can_manage",
          "has_customer",
          "blocked",
          "minimum_topup_credits",
          "maximum_topup_credits",
          "token_brl",
          "subscription"
        ],
        "properties": {
          "enabled": {
            "type": "boolean"
          },
          "test_mode": {
            "type": "boolean"
          },
          "can_manage": {
            "type": "boolean"
          },
          "has_customer": {
            "type": "boolean"
          },
          "blocked": {
            "type": "boolean"
          },
          "minimum_topup_credits": {
            "type": "integer"
          },
          "maximum_topup_credits": {
            "type": "integer"
          },
          "token_brl": {
            "type": "number"
          },
          "subscription": {
            "type": [
              "object",
              "null"
            ],
            "required": [
              "plan",
              "status",
              "current_period_end",
              "cancel_at"
            ],
            "properties": {
              "plan": {
                "$ref": "#/components/schemas/PlanCode"
              },
              "status": {
                "type": "string",
                "enum": [
                  "active",
                  "trialing",
                  "past_due",
                  "canceled",
                  "unpaid",
                  "incomplete",
                  "incomplete_expired",
                  "paused"
                ]
              },
              "current_period_end": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time"
              },
              "cancel_at": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time"
              }
            },
            "additionalProperties": false
          }
        },
        "additionalProperties": false
      },
      "CheckoutRequest": {
        "type": "object",
        "required": [
          "plan"
        ],
        "properties": {
          "plan": {
            "$ref": "#/components/schemas/PlanCode"
          },
          "coupon_code": {
            "type": "string",
            "minLength": 1,
            "maxLength": 32,
            "x-limit": "text.coupon_code"
          },
          "success_path": {
            "type": "string",
            "pattern": "^/[^/\\\\].*$|^/$"
          },
          "cancel_path": {
            "type": "string",
            "pattern": "^/[^/\\\\].*$|^/$"
          }
        },
        "additionalProperties": false
      },
      "CheckoutResponse": {
        "type": "object",
        "required": [
          "checkout_url",
          "session_id",
          "expires_at"
        ],
        "properties": {
          "checkout_url": {
            "type": "string",
            "format": "uri"
          },
          "session_id": {
            "type": "string"
          },
          "expires_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "PortalResponse": {
        "type": "object",
        "required": [
          "portal_url"
        ],
        "properties": {
          "portal_url": {
            "type": "string",
            "format": "uri"
          }
        },
        "additionalProperties": false
      },
      "TopupRequest": {
        "type": "object",
        "required": [
          "credits"
        ],
        "properties": {
          "credits": {
            "type": "integer",
            "minimum": 1,
            "description": "Quantidade de créditos; o preço unitário vem de `GET /plans`."
          },
          "success_path": {
            "type": "string",
            "pattern": "^/[^/\\\\].*$|^/$"
          },
          "cancel_path": {
            "type": "string",
            "pattern": "^/[^/\\\\].*$|^/$"
          }
        },
        "additionalProperties": false
      },
      "CreditSummary": {
        "type": "object",
        "required": [
          "balance",
          "reserved",
          "available",
          "plan_credits",
          "topup_credits"
        ],
        "properties": {
          "token_exempt": {
            "type": "boolean",
            "readOnly": true,
            "default": false,
            "description": "Conta de teste autorizada pelo operador; execuções não debitam tokens."
          },
          "balance": {
            "type": "integer",
            "minimum": 0
          },
          "reserved": {
            "type": "integer",
            "minimum": 0,
            "description": "Reservados por execuções ativas."
          },
          "available": {
            "type": "integer",
            "minimum": 0,
            "description": "`balance - reserved`."
          },
          "plan_credits": {
            "type": "integer",
            "minimum": 0,
            "description": "Parcela do ciclo do plano (expira no fim do ciclo seguinte)."
          },
          "topup_credits": {
            "type": "integer",
            "minimum": 0,
            "description": "Parcela comprada avulsa (expira em 12 meses)."
          },
          "plan_cycle_ends_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "next_expiry_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "LedgerEntry": {
        "type": "object",
        "required": [
          "id",
          "kind",
          "credits",
          "balance_after",
          "description",
          "created_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/LedgerEntryId"
          },
          "kind": {
            "type": "string",
            "enum": [
              "plan_grant",
              "topup",
              "reserve",
              "spend",
              "release",
              "refund",
              "expire",
              "adjustment",
              "bounty"
            ]
          },
          "credits": {
            "type": "integer",
            "description": "Positivo entra, negativo sai."
          },
          "balance_after": {
            "type": "integer",
            "minimum": 0
          },
          "run_id": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/RunId"
              },
              {
                "type": "null"
              }
            ]
          },
          "description": {
            "type": "string",
            "description": "Em pt-BR."
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "LedgerList": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LedgerEntry"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "additionalProperties": false
      },
      "StripeEvent": {
        "type": "object",
        "description": "Evento do Stripe (`checkout.session.completed`, `invoice.paid`, `customer.subscription.updated`, ...). Processado a partir do corpo bruto.",
        "required": [
          "id",
          "type",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "type": {
            "type": "string"
          },
          "data": {
            "type": "object",
            "additionalProperties": true
          }
        },
        "additionalProperties": true
      },
      "UiManifest": {
        "$ref": "./schemas/ui-manifest.json"
      },
      "CustomizationRequest": {
        "type": "object",
        "required": [
          "request"
        ],
        "additionalProperties": false,
        "properties": {
          "request": {
            "type": "string",
            "minLength": 3,
            "maxLength": 2000,
            "x-limit": "text.ui_customization_request"
          }
        }
      },
      "CustomizationStatus": {
        "type": "string",
        "enum": [
          "pending",
          "planned",
          "applied",
          "rejected",
          "failed"
        ]
      },
      "Customization": {
        "type": "object",
        "required": [
          "id",
          "status",
          "request",
          "base_version",
          "credits",
          "created_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/CustomizationId"
          },
          "status": {
            "$ref": "#/components/schemas/CustomizationStatus"
          },
          "request": {
            "type": "string"
          },
          "base_version": {
            "type": "integer"
          },
          "manifest": {
            "$ref": "#/components/schemas/WorkspaceManifest"
          },
          "reason": {
            "type": "string"
          },
          "credits": {
            "type": "integer",
            "const": 0
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ApiKeyScope": {
        "type": "string",
        "enum": [
          "runs:read",
          "runs:write",
          "uploads:write",
          "workflows:read",
          "workflows:write",
          "rules:read",
          "rules:write",
          "projects:read",
          "projects:write",
          "credits:read",
          "webhooks:write"
        ]
      },
      "ApiKey": {
        "type": "object",
        "required": [
          "id",
          "label",
          "prefix",
          "scopes",
          "lane",
          "created_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/ApiKeyId"
          },
          "label": {
            "type": "string",
            "maxLength": 60,
            "x-limit": "text.api_key_label"
          },
          "prefix": {
            "type": "string",
            "description": "`dm_live_<id>`, para identificar a chave sem o segredo."
          },
          "scopes": {
            "type": "array",
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/ApiKeyScope"
            }
          },
          "lane": {
            "$ref": "#/components/schemas/Lane"
          },
          "last_used_at": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/Timestamp"
              },
              {
                "type": "null"
              }
            ]
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "revoked_at": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/Timestamp"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "additionalProperties": false
      },
      "ApiKeyCreateRequest": {
        "type": "object",
        "required": [
          "label",
          "scopes"
        ],
        "properties": {
          "label": {
            "type": "string",
            "minLength": 1,
            "maxLength": 60,
            "x-limit": "text.api_key_label"
          },
          "scopes": {
            "type": "array",
            "minItems": 1,
            "maxItems": 10,
            "x-limit": "ids.api_key_scopes_max",
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/ApiKeyScope"
            }
          },
          "lane": {
            "$ref": "#/components/schemas/Lane",
            "description": "Padrão `api_batch`; as demais dependem do plano."
          }
        },
        "additionalProperties": false
      },
      "ApiKeyCreated": {
        "type": "object",
        "required": [
          "id",
          "label",
          "prefix",
          "scopes",
          "lane",
          "created_at",
          "key"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/ApiKey/properties/id"
          },
          "label": {
            "$ref": "#/components/schemas/ApiKey/properties/label"
          },
          "prefix": {
            "$ref": "#/components/schemas/ApiKey/properties/prefix"
          },
          "scopes": {
            "$ref": "#/components/schemas/ApiKey/properties/scopes"
          },
          "lane": {
            "$ref": "#/components/schemas/ApiKey/properties/lane"
          },
          "created_at": {
            "$ref": "#/components/schemas/ApiKey/properties/created_at"
          },
          "last_used_at": {
            "$ref": "#/components/schemas/ApiKey/properties/last_used_at"
          },
          "key": {
            "type": "string",
            "pattern": "^dm_live_[0-9A-HJKMNP-TV-Z]{26}_[A-Za-z0-9_-]{32,64}$",
            "description": "Segredo completo, mostrado uma única vez."
          }
        },
        "additionalProperties": false
      },
      "ApiKeyList": {
        "type": "object",
        "required": [
          "items",
          "access"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ApiKey"
            }
          },
          "access": {
            "type": "object",
            "required": [
              "can_create",
              "eligible",
              "limit",
              "lanes",
              "scopes"
            ],
            "properties": {
              "can_create": {
                "type": "boolean"
              },
              "eligible": {
                "type": "boolean"
              },
              "limit": {
                "type": "integer"
              },
              "lanes": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/Lane"
                }
              },
              "scopes": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/ApiKeyScope"
                }
              }
            },
            "additionalProperties": false
          }
        },
        "additionalProperties": false
      },
      "WebhookEventType": {
        "type": "string",
        "enum": [
          "run.completed",
          "run.failed",
          "run.needs_approval",
          "credits.low"
        ]
      },
      "WebhookEndpoint": {
        "type": "object",
        "required": [
          "id",
          "url",
          "events",
          "status",
          "created_at"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/WebhookEndpointId"
          },
          "url": {
            "type": "string",
            "format": "uri",
            "pattern": "^https://"
          },
          "events": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/WebhookEventType"
            }
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "disabled"
            ],
            "description": "Desativado automaticamente após 7 dias de falhas consecutivas."
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "WebhookEndpointCreateRequest": {
        "type": "object",
        "required": [
          "url",
          "events"
        ],
        "properties": {
          "url": {
            "type": "string",
            "format": "uri",
            "pattern": "^https://"
          },
          "events": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/WebhookEventType"
            }
          }
        },
        "additionalProperties": false
      },
      "WebhookEndpointCreated": {
        "allOf": [
          {
            "$ref": "#/components/schemas/WebhookEndpoint"
          },
          {
            "type": "object",
            "required": [
              "secret"
            ],
            "properties": {
              "secret": {
                "type": "string",
                "description": "Segredo de assinatura (`whsec_dm_...`), mostrado uma única vez."
              }
            }
          }
        ]
      },
      "WebhookEndpointList": {
        "type": "object",
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/WebhookEndpoint"
            }
          }
        },
        "additionalProperties": false
      },
      "WebhookEnvelope": {
        "type": "object",
        "description": "Envelope comum a todo evento de saída.",
        "required": [
          "id",
          "type",
          "created_at",
          "org_id"
        ],
        "properties": {
          "id": {
            "$ref": "#/components/schemas/EventId"
          },
          "type": {
            "$ref": "#/components/schemas/WebhookEventType"
          },
          "created_at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "org_id": {
            "$ref": "#/components/schemas/OrgId"
          }
        }
      },
      "WebhookRunCompleted": {
        "allOf": [
          {
            "$ref": "#/components/schemas/WebhookEnvelope"
          },
          {
            "type": "object",
            "required": [
              "data"
            ],
            "properties": {
              "type": {
                "const": "run.completed"
              },
              "data": {
                "type": "object",
                "required": [
                  "run"
                ],
                "properties": {
                  "run": {
                    "$ref": "#/components/schemas/Run"
                  }
                },
                "additionalProperties": false
              }
            }
          }
        ]
      },
      "WebhookRunFailed": {
        "allOf": [
          {
            "$ref": "#/components/schemas/WebhookEnvelope"
          },
          {
            "type": "object",
            "required": [
              "data"
            ],
            "properties": {
              "type": {
                "const": "run.failed"
              },
              "data": {
                "type": "object",
                "required": [
                  "run",
                  "error"
                ],
                "properties": {
                  "run": {
                    "$ref": "#/components/schemas/Run"
                  },
                  "error": {
                    "$ref": "#/components/schemas/RunError"
                  }
                },
                "additionalProperties": false
              }
            }
          }
        ]
      },
      "WebhookRunNeedsApproval": {
        "allOf": [
          {
            "$ref": "#/components/schemas/WebhookEnvelope"
          },
          {
            "type": "object",
            "required": [
              "data"
            ],
            "properties": {
              "type": {
                "const": "run.needs_approval"
              },
              "data": {
                "type": "object",
                "required": [
                  "run",
                  "quote"
                ],
                "properties": {
                  "run": {
                    "$ref": "#/components/schemas/Run"
                  },
                  "quote": {
                    "$ref": "#/components/schemas/Quote"
                  }
                },
                "additionalProperties": false
              }
            }
          }
        ]
      },
      "WebhookCreditsLow": {
        "allOf": [
          {
            "$ref": "#/components/schemas/WebhookEnvelope"
          },
          {
            "type": "object",
            "required": [
              "data"
            ],
            "properties": {
              "type": {
                "const": "credits.low"
              },
              "data": {
                "type": "object",
                "required": [
                  "credits",
                  "threshold"
                ],
                "properties": {
                  "credits": {
                    "$ref": "#/components/schemas/CreditSummary"
                  },
                  "threshold": {
                    "type": "integer",
                    "minimum": 0
                  }
                },
                "additionalProperties": false
              }
            }
          }
        ]
      },
      "Plan": {
        "type": "object",
        "required": [
          "code",
          "name",
          "price",
          "interval",
          "credits",
          "entitlements",
          "available"
        ],
        "properties": {
          "code": {
            "$ref": "#/components/schemas/PlanCode"
          },
          "name": {
            "type": "string"
          },
          "price": {
            "$ref": "#/components/schemas/Money"
          },
          "interval": {
            "type": "string",
            "enum": [
              "month"
            ]
          },
          "credits": {
            "type": "integer",
            "minimum": 0,
            "description": "Créditos por ciclo."
          },
          "topup_price_per_credit": {
            "$ref": "#/components/schemas/Money"
          },
          "entitlements": {
            "$ref": "#/components/schemas/Entitlements"
          },
          "available": {
            "type": "boolean",
            "description": "Falso quando o plano não é vendido no país informado."
          }
        },
        "additionalProperties": false
      },
      "PlansResponse": {
        "type": "object",
        "required": [
          "country",
          "plans"
        ],
        "properties": {
          "country": {
            "type": "string",
            "pattern": "^[A-Z]{2}$"
          },
          "plans": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Plan"
            }
          }
        },
        "additionalProperties": false
      },
      "Health": {
        "type": "object",
        "required": [
          "status"
        ],
        "properties": {
          "status": {
            "type": "string",
            "const": "ok"
          }
        },
        "additionalProperties": false
      },
      "Readiness": {
        "type": "object",
        "required": [
          "status",
          "checks"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "ok",
              "degraded",
              "unavailable"
            ]
          },
          "checks": {
            "type": "object",
            "required": [
              "database",
              "storage",
              "harness"
            ],
            "properties": {
              "database": {
                "type": "string",
                "enum": [
                  "ok",
                  "failed"
                ]
              },
              "storage": {
                "type": "string",
                "enum": [
                  "ok",
                  "failed"
                ]
              },
              "harness": {
                "type": "string",
                "enum": [
                  "ok",
                  "degraded",
                  "failed"
                ]
              }
            },
            "additionalProperties": false
          }
        },
        "additionalProperties": false
      },
      "Version": {
        "type": "object",
        "required": [
          "version",
          "commit",
          "built_at"
        ],
        "properties": {
          "version": {
            "type": "string"
          },
          "commit": {
            "type": "string",
            "pattern": "^[0-9a-f]{7,40}$"
          },
          "built_at": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "additionalProperties": false
      },
      "WorkspaceManifest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "version",
          "mode",
          "density",
          "findings_label",
          "group_by",
          "sort_by",
          "export_format"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "const": 1
          },
          "mode": {
            "type": "string",
            "enum": [
              "system",
              "light",
              "dark"
            ]
          },
          "density": {
            "type": "string",
            "enum": [
              "comfortable",
              "compact"
            ]
          },
          "findings_label": {
            "type": "string",
            "description": "Texto puro, de 1 a 40 caracteres; sem HTML, URLs ou controles."
          },
          "group_by": {
            "type": "string",
            "enum": [
              "none",
              "severity",
              "kind"
            ]
          },
          "sort_by": {
            "type": "string",
            "enum": [
              "severity",
              "amount_at_risk",
              "confidence"
            ]
          },
          "export_format": {
            "type": "string",
            "enum": [
              "xlsx",
              "csv",
              "pdf"
            ]
          }
        }
      },
      "Workspace": {
        "type": "object",
        "required": [
          "version",
          "manifest",
          "access",
          "history",
          "endpoints"
        ],
        "properties": {
          "version": {
            "type": "integer"
          },
          "manifest": {
            "$ref": "#/components/schemas/WorkspaceManifest"
          },
          "access": {
            "type": "object",
            "properties": {
              "eligible": {
                "type": "boolean"
              },
              "can_request": {
                "type": "boolean"
              },
              "limit": {
                "type": "integer"
              },
              "used": {
                "type": "integer"
              }
            }
          },
          "history": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "version": {
                  "type": "integer"
                },
                "created_at": {
                  "type": "string",
                  "format": "date-time"
                }
              }
            }
          },
          "endpoints": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "operation": {
                  "type": "string"
                },
                "method": {
                  "type": "string"
                },
                "path": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    }
  }
}