{
  "openapi": "3.1.0",
  "info": {
    "title": "AtendroZAP — monitoramento central de servidores",
    "version": "2026-09-19",
    "description": "Contrato separado da API de instâncias. Consulta somente servidores previamente cadastrados no console; o console usa o admintoken mantido no backend e retorna uma projeção tipada validada. Bearer CONSOLE_MONITORING_TOKEN dá acesso somente a estes GETs, sem login administrativo, mutações ou credenciais dos workers. Não aceitar URLs de consulta do cliente. Implementação local testada; disponibilidade em uma instalação depende de publicação/configuração. Não representa teste de carga, recuperação completa de backup ou homologação de chamadas reais."
  },
  "servers": [
    {
      "url": "http://127.0.0.1:8092",
      "description": "Console local."
    },
    {
      "url": "https://wpp.atendro.cloud",
      "description": "Endereço central; requer versão publicada com monitoramento habilitado."
    }
  ],
  "tags": [
    {
      "name": "Monitoramento"
    }
  ],
  "security": [
    {
      "BearerMonitoringToken": []
    }
  ],
  "paths": {
    "/api/v1/servers/status": {
      "get": {
        "operationId": "getFleetStatus",
        "tags": [
          "Monitoramento"
        ],
        "summary": "Consultar saúde da frota",
        "description": "Somente leitura. Mantém o último sucesso marcado dataStale quando o worker falha. Consulta com limite global de 8 workers concorrentes, orçamento total de 5 s incluindo espera, redirects recusados e resposta limitada a 256 KiB. Campos desconhecidos são descartados; campos conhecidos inválidos, strings fora das listas permitidas ou schema não suportado fazem a resposta inteira ser recusada. HTTP 200 pode conter worker indisponível. Nenhuma reinicialização, limpeza ou ação operacional é executada.",
        "security": [
          {
            "BearerMonitoringToken": []
          }
        ],
        "parameters": [],
        "responses": {
          "200": {
            "description": "Estado observado, incluindo falhas e amostras anteriores identificadas.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FleetStatus"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Monitoring401"
          },
          "503": {
            "$ref": "#/components/responses/Monitoring503"
          }
        },
        "x-implemented": true,
        "x-contract-tests": [
          "TestMonitoringAuthenticationAndReadOnlyScope",
          "TestMonitoringFleetIncludesFailuresAndDoesNotLeakSecrets",
          "TestMonitoringConcurrentReadsCoalesceAndRetainLastSuccess"
        ]
      }
    },
    "/api/v1/servers/{server}/status": {
      "get": {
        "operationId": "getMonitoredServerStatus",
        "tags": [
          "Monitoramento"
        ],
        "summary": "Consultar saúde de um servidor",
        "description": "Somente leitura. Mantém o último sucesso marcado dataStale quando o worker falha. Consulta com limite global de 8 workers concorrentes, orçamento total de 5 s incluindo espera, redirects recusados e resposta limitada a 256 KiB. Campos desconhecidos são descartados; campos conhecidos inválidos, strings fora das listas permitidas ou schema não suportado fazem a resposta inteira ser recusada. HTTP 200 pode conter worker indisponível. Nenhuma reinicialização, limpeza ou ação operacional é executada.",
        "security": [
          {
            "BearerMonitoringToken": []
          }
        ],
        "parameters": [
          {
            "name": "server",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Nome lógico já registrado no console; não é URL, host nem endereço de destino."
          }
        ],
        "responses": {
          "200": {
            "description": "Estado observado, incluindo falhas e amostras anteriores identificadas.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MonitoredServer"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Monitoring401"
          },
          "503": {
            "$ref": "#/components/responses/Monitoring503"
          },
          "404": {
            "description": "Servidor não cadastrado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MonitoringError"
                }
              }
            }
          }
        },
        "x-implemented": true,
        "x-contract-tests": [
          "TestMonitoringAuthenticationAndReadOnlyScope",
          "TestMonitoringFleetIncludesFailuresAndDoesNotLeakSecrets",
          "TestMonitoringRedirectStaleAndInvalidPayload"
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "BearerMonitoringToken": {
        "type": "http",
        "scheme": "bearer",
        "description": "CONSOLE_MONITORING_TOKEN separado (32–256 caracteres sem espaços), somente leitura. Somente header Authorization: Bearer; cookie de sessão, query token, instance token e admintoken não substituem este token."
      }
    },
    "schemas": {
      "HostHealthCPU": {
        "additionalProperties": true,
        "properties": {
          "ioWaitPercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "logicalCPUs": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "stealPercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "usagePercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "logicalCPUs",
          "usagePercent",
          "ioWaitPercent",
          "stealPercent"
        ],
        "type": "object"
      },
      "HostHealthDirectory": {
        "additionalProperties": true,
        "properties": {
          "auxiliaryBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "auxiliaryFiles": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "bytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "complete": {
            "description": "false identifica varredura parcial/interrompida: os bytes/arquivos observados são um limite inferior, não um total completo.",
            "type": "boolean"
          },
          "compressedBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "compressedFiles": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "files": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "incompleteBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "incompleteFiles": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "latestAgeSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "oldestAgeSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "rawBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "rawFiles": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "complete",
          "bytes",
          "files",
          "rawBytes",
          "rawFiles",
          "compressedBytes",
          "compressedFiles",
          "incompleteBytes",
          "incompleteFiles",
          "auxiliaryBytes",
          "auxiliaryFiles",
          "oldestAgeSeconds",
          "latestAgeSeconds"
        ],
        "type": "object"
      },
      "HostHealthDiskIO": {
        "additionalProperties": true,
        "properties": {
          "busyPercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "inFlight": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "readBytesPerSecond": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "readsPerSecond": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "scope": {
            "enum": [
              "root_device"
            ],
            "type": "string"
          },
          "writeBytesPerSecond": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "writesPerSecond": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "scope",
          "inFlight",
          "readBytesPerSecond",
          "writeBytesPerSecond",
          "readsPerSecond",
          "writesPerSecond",
          "busyPercent"
        ],
        "type": "object"
      },
      "HostHealthDocker": {
        "additionalProperties": true,
        "properties": {
          "available": {
            "type": "boolean"
          },
          "services": {
            "anyOf": [
              {
                "additionalProperties": {
                  "$ref": "#/components/schemas/HostHealthService"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "available",
          "services"
        ],
        "type": "object"
      },
      "HostHealthFilesystem": {
        "additionalProperties": true,
        "properties": {
          "availableBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "availablePercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "freeBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "inodesFree": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "inodesTotal": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "inodesUsedPercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "reservedBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "totalBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "usedBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "usedPercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "totalBytes",
          "freeBytes",
          "availableBytes",
          "reservedBytes",
          "usedBytes",
          "usedPercent",
          "availablePercent",
          "inodesTotal",
          "inodesFree",
          "inodesUsedPercent"
        ],
        "type": "object"
      },
      "HostHealthLoad": {
        "additionalProperties": true,
        "properties": {
          "fifteen": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "fifteenPerCPU": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "five": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "fivePerCPU": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "one": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "onePerCPU": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "one",
          "five",
          "fifteen",
          "onePerCPU",
          "fivePerCPU",
          "fifteenPerCPU"
        ],
        "type": "object"
      },
      "HostHealthMemory": {
        "additionalProperties": true,
        "properties": {
          "availableBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "totalBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "usedBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "usedPercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "totalBytes",
          "availableBytes",
          "usedBytes",
          "usedPercent"
        ],
        "type": "object"
      },
      "HostHealthNetwork": {
        "additionalProperties": true,
        "properties": {
          "interfaces": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "receivedBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "receivedBytesPerSecond": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "scope": {
            "description": "Agrega interfaces não loopback, incluindo interfaces virtuais; não equivale ao tráfego externo faturado pelo provedor.",
            "enum": [
              "all_non_loopback"
            ],
            "type": "string"
          },
          "transmittedBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "transmittedBytesPerSecond": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "scope",
          "interfaces",
          "receivedBytes",
          "transmittedBytes",
          "receivedBytesPerSecond",
          "transmittedBytesPerSecond"
        ],
        "type": "object"
      },
      "HostHealthOperations": {
        "additionalProperties": true,
        "properties": {
          "backupVerification": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/HostHealthVerification"
              },
              {
                "type": "null"
              }
            ]
          },
          "docker": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/HostHealthDocker"
              },
              {
                "type": "null"
              }
            ]
          },
          "storage": {
            "anyOf": [
              {
                "additionalProperties": {
                  "$ref": "#/components/schemas/HostHealthDirectory"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "docker",
          "storage",
          "backupVerification"
        ],
        "type": "object"
      },
      "HostHealthResult": {
        "additionalProperties": true,
        "properties": {
          "ageSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "errors": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ]
          },
          "snapshot": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/HostHealthSnapshot"
              },
              {
                "type": "null"
              }
            ]
          },
          "status": {
            "enum": [
              "ok",
              "degraded",
              "stale",
              "unavailable"
            ],
            "type": "string"
          }
        },
        "required": [
          "status",
          "ageSeconds",
          "snapshot",
          "errors"
        ],
        "type": "object"
      },
      "HostHealthService": {
        "additionalProperties": true,
        "properties": {
          "containers": {
            "minimum": 0,
            "type": "integer"
          },
          "health": {
            "enum": [
              "unknown",
              "none",
              "healthy",
              "starting",
              "unhealthy"
            ],
            "type": "string"
          },
          "oomKilled": {
            "minimum": 0,
            "type": "integer"
          },
          "restarting": {
            "minimum": 0,
            "type": "integer"
          },
          "restarts": {
            "minimum": 0,
            "type": "integer"
          },
          "running": {
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "containers",
          "running",
          "restarting",
          "oomKilled",
          "restarts",
          "health"
        ],
        "type": "object"
      },
      "HostHealthSnapshot": {
        "additionalProperties": true,
        "properties": {
          "cpu": {
            "$ref": "#/components/schemas/HostHealthCPU"
          },
          "diskIO": {
            "$ref": "#/components/schemas/HostHealthDiskIO"
          },
          "errors": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ]
          },
          "intervalSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "load": {
            "$ref": "#/components/schemas/HostHealthLoad"
          },
          "memory": {
            "$ref": "#/components/schemas/HostHealthMemory"
          },
          "network": {
            "$ref": "#/components/schemas/HostHealthNetwork"
          },
          "operations": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/HostHealthOperations"
              },
              {
                "type": "null"
              }
            ]
          },
          "rootFilesystem": {
            "$ref": "#/components/schemas/HostHealthFilesystem"
          },
          "sampledAt": {
            "format": "date-time",
            "type": "string"
          },
          "schemaVersion": {
            "const": 1,
            "minimum": 0,
            "type": "integer"
          },
          "source": {
            "enum": [
              "host"
            ],
            "type": "string"
          },
          "swap": {
            "$ref": "#/components/schemas/HostHealthSwap"
          },
          "uptimeSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "validForSeconds": {
            "maximum": 3600,
            "minimum": 1,
            "type": "integer"
          }
        },
        "required": [
          "schemaVersion",
          "source",
          "sampledAt",
          "validForSeconds",
          "intervalSeconds",
          "uptimeSeconds",
          "cpu",
          "memory",
          "swap",
          "load",
          "rootFilesystem",
          "network",
          "diskIO",
          "errors"
        ],
        "type": "object"
      },
      "HostHealthSwap": {
        "additionalProperties": true,
        "properties": {
          "freeBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "totalBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "usedBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "usedPercent": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "totalBytes",
          "freeBytes",
          "usedBytes",
          "usedPercent"
        ],
        "type": "object"
      },
      "HostHealthVerification": {
        "additionalProperties": true,
        "properties": {
          "ageSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "verified": {
            "description": "Indica marcador local de pg_verifybackup bem-sucedido. Não comprova sozinho teste de restauração, cópia externa ou continuidade de toda a cadeia PITR.",
            "type": "boolean"
          },
          "verifiedAt": {
            "anyOf": [
              {
                "format": "date-time",
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "verified",
          "verifiedAt",
          "ageSeconds"
        ],
        "type": "object"
      },
      "SystemStatus": {
        "additionalProperties": true,
        "properties": {
          "database": {
            "$ref": "#/components/schemas/SystemStatusDatabase"
          },
          "host": {
            "$ref": "#/components/schemas/HostHealthResult"
          },
          "process": {
            "$ref": "#/components/schemas/SystemStatusProcess",
            "description": "Processo Go/API: heap e runtimeSys não são RAM usada da VPS; gomaxprocs não mede núcleos físicos nem CPU do host."
          },
          "sampledAt": {
            "description": "Instante UTC da amostragem do worker. O host tem sampledAt e idade próprios.",
            "format": "date-time",
            "type": "string"
          },
          "schemaVersion": {
            "const": 1,
            "minimum": 0,
            "type": "integer"
          },
          "status": {
            "description": "HTTP 200 significa que o observador respondeu. Verificar available/status em cada bloco; valores indisponíveis não representam consumo zero.",
            "enum": [
              "ok",
              "degraded"
            ],
            "type": "string"
          },
          "version": {
            "type": "string"
          },
          "workerId": {
            "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$",
            "type": "string"
          },
          "workload": {
            "$ref": "#/components/schemas/SystemStatusWorkload"
          }
        },
        "required": [
          "schemaVersion",
          "sampledAt",
          "status",
          "workerId",
          "process",
          "database",
          "workload",
          "host"
        ],
        "type": "object"
      },
      "SystemStatusArchiver": {
        "additionalProperties": true,
        "properties": {
          "archiveTimeoutSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "archivedCount": {
            "minimum": 0,
            "type": "integer"
          },
          "available": {
            "type": "boolean"
          },
          "backlogErrorCode": {
            "enum": [
              "archiver_backlog_unavailable"
            ],
            "type": "string"
          },
          "commandSource": {
            "description": "Origem enumerada de pg_settings.source; nunca o comando, caminho ou conteúdo da configuração.",
            "enum": [
              "unknown",
              "default",
              "environment variable",
              "configuration file",
              "command line",
              "global",
              "database",
              "user",
              "database user",
              "client",
              "override",
              "interactive",
              "test",
              "session"
            ],
            "type": "string"
          },
          "errorCode": {
            "enum": [
              "database_unavailable",
              "archiver_stats_unavailable",
              "monitoring_unsupported"
            ],
            "type": "string"
          },
          "failedCount": {
            "description": "Falhas acumuladas desde statsResetAt; não indica, isoladamente, falha atual.",
            "minimum": 0,
            "type": "integer"
          },
          "lastArchivedAt": {
            "anyOf": [
              {
                "format": "date-time",
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "lastFailedAt": {
            "anyOf": [
              {
                "format": "date-time",
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "mode": {
            "enum": [
              "off",
              "on",
              "always"
            ],
            "type": "string"
          },
          "readyFiles": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "segmentBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          },
          "statsResetAt": {
            "anyOf": [
              {
                "format": "date-time",
                "type": "string"
              },
              {
                "type": "null"
              }
            ]
          },
          "status": {
            "description": "blocked: última falha posterior ao último sucesso e readyFiles>0. failedCount é cumulativo e sozinho não dispara alarme. disabled corresponde a archive_mode=off. degraded indica backlog não consultável.",
            "enum": [
              "ok",
              "disabled",
              "degraded",
              "blocked",
              "unavailable"
            ],
            "type": "string"
          },
          "timeoutSource": {
            "description": "Origem enumerada de pg_settings.source; nunca o comando, caminho ou conteúdo da configuração.",
            "enum": [
              "unknown",
              "default",
              "environment variable",
              "configuration file",
              "command line",
              "global",
              "database",
              "user",
              "database user",
              "client",
              "override",
              "interactive",
              "test",
              "session"
            ],
            "type": "string"
          },
          "walBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "available",
          "status",
          "archivedCount",
          "failedCount"
        ],
        "type": "object"
      },
      "SystemStatusCallCounts": {
        "additionalProperties": true,
        "properties": {
          "active": {
            "minimum": 0,
            "type": "integer"
          },
          "connecting": {
            "minimum": 0,
            "type": "integer"
          },
          "live": {
            "description": "Chamadas persistidas abertas com lease vigente deste worker. Exclui snapshots cujo lease expirou ou mudou; não mede fluxo RTP/saúde de mídia.",
            "minimum": 0,
            "type": "integer"
          },
          "persistedOpen": {
            "minimum": 0,
            "type": "integer"
          },
          "ringing": {
            "minimum": 0,
            "type": "integer"
          },
          "scope": {
            "enum": [
              "worker"
            ],
            "type": "string"
          },
          "source": {
            "enum": [
              "database_snapshot"
            ],
            "type": "string"
          },
          "stale": {
            "minimum": 0,
            "type": "integer"
          },
          "video": {
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "source",
          "scope",
          "persistedOpen",
          "live",
          "stale",
          "ringing",
          "connecting",
          "active",
          "video"
        ],
        "type": "object"
      },
      "SystemStatusDatabase": {
        "additionalProperties": true,
        "properties": {
          "archiver": {
            "$ref": "#/components/schemas/SystemStatusArchiver"
          },
          "available": {
            "type": "boolean"
          },
          "errorCode": {
            "enum": [
              "database_unavailable",
              "database_size_unavailable",
              "monitoring_unsupported"
            ],
            "type": "string"
          },
          "pool": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/SystemStatusPool"
              },
              {
                "type": "null"
              }
            ]
          },
          "sizeBytes": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "available",
          "archiver"
        ],
        "type": "object"
      },
      "SystemStatusInstanceCounts": {
        "additionalProperties": true,
        "properties": {
          "callSlotsConfigured": {
            "description": "Soma dos limites de instâncias calls; valores herdados usam o padrão deste worker. Não é capacidade física medida.",
            "minimum": 0,
            "type": "integer"
          },
          "callSlotsOwned": {
            "description": "Soma dos limites das instâncias calls sob lease vigente deste worker.",
            "minimum": 0,
            "type": "integer"
          },
          "calls": {
            "$ref": "#/components/schemas/SystemStatusInstanceState"
          },
          "ownedByWorker": {
            "description": "Leases deste worker ainda não expirados.",
            "minimum": 0,
            "type": "integer"
          },
          "scope": {
            "enum": [
              "database"
            ],
            "type": "string"
          },
          "staleConnected": {
            "description": "Status persistido connected sem lease vigente. Os totais por estado são snapshots persistidos, não sondas da conexão WhatsApp.",
            "minimum": 0,
            "type": "integer"
          },
          "total": {
            "description": "Instâncias não excluídas neste banco. Bancos compartilhados entre workers duplicam esse total: não somar os nós sem considerar o escopo.",
            "minimum": 0,
            "type": "integer"
          },
          "whatsapp": {
            "$ref": "#/components/schemas/SystemStatusInstanceState"
          },
          "workerSessionLimit": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "integer"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "scope",
          "total",
          "whatsapp",
          "calls",
          "ownedByWorker",
          "staleConnected",
          "callSlotsConfigured",
          "callSlotsOwned"
        ],
        "type": "object"
      },
      "SystemStatusInstanceState": {
        "additionalProperties": true,
        "properties": {
          "connected": {
            "minimum": 0,
            "type": "integer"
          },
          "connecting": {
            "minimum": 0,
            "type": "integer"
          },
          "disconnected": {
            "minimum": 0,
            "type": "integer"
          },
          "total": {
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "total",
          "connected",
          "connecting",
          "disconnected"
        ],
        "type": "object"
      },
      "SystemStatusPool": {
        "additionalProperties": true,
        "properties": {
          "idle": {
            "minimum": 0,
            "type": "integer"
          },
          "inUse": {
            "minimum": 0,
            "type": "integer"
          },
          "maxIdleClosed": {
            "minimum": 0,
            "type": "integer"
          },
          "maxLifetimeClosed": {
            "minimum": 0,
            "type": "integer"
          },
          "maxOpenConnections": {
            "minimum": 0,
            "type": "integer"
          },
          "openConnections": {
            "minimum": 0,
            "type": "integer"
          },
          "waitCount": {
            "minimum": 0,
            "type": "integer"
          },
          "waitDurationSeconds": {
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "maxOpenConnections",
          "openConnections",
          "inUse",
          "idle",
          "waitCount",
          "waitDurationSeconds",
          "maxIdleClosed",
          "maxLifetimeClosed"
        ],
        "type": "object"
      },
      "SystemStatusProcess": {
        "additionalProperties": true,
        "properties": {
          "goVersion": {
            "type": "string"
          },
          "gomaxprocs": {
            "minimum": 0,
            "type": "integer"
          },
          "goroutines": {
            "minimum": 0,
            "type": "integer"
          },
          "heapAllocBytes": {
            "minimum": 0,
            "type": "integer"
          },
          "heapInuseBytes": {
            "minimum": 0,
            "type": "integer"
          },
          "runtimeSysBytes": {
            "minimum": 0,
            "type": "integer"
          },
          "startedAt": {
            "format": "date-time",
            "type": "string"
          },
          "uptimeSeconds": {
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "startedAt",
          "uptimeSeconds",
          "goVersion",
          "gomaxprocs",
          "goroutines",
          "heapAllocBytes",
          "heapInuseBytes",
          "runtimeSysBytes"
        ],
        "type": "object"
      },
      "SystemStatusWebhookCounts": {
        "additionalProperties": true,
        "properties": {
          "dead": {
            "description": "Eventos mortos de instâncias não excluídas, inclusive se o webhook foi desabilitado.",
            "minimum": 0,
            "type": "integer"
          },
          "enabledDestinations": {
            "minimum": 0,
            "type": "integer"
          },
          "failingDestinations": {
            "minimum": 0,
            "type": "integer"
          },
          "oldestPendingAgeSeconds": {
            "anyOf": [
              {
                "minimum": 0,
                "type": "number"
              },
              {
                "type": "null"
              }
            ]
          },
          "pausedDestinations": {
            "minimum": 0,
            "type": "integer"
          },
          "pending": {
            "description": "Eventos sem entrega nem dead_at, posteriores ao start_seq, com webhook habilitado e instância não excluída. Inclui destinos temporariamente pausados.",
            "minimum": 0,
            "type": "integer"
          },
          "retriedPending": {
            "description": "Eventos elegíveis pendentes com attempts>0; não é contador histórico de todas as falhas.",
            "minimum": 0,
            "type": "integer"
          },
          "scope": {
            "enum": [
              "database"
            ],
            "type": "string"
          }
        },
        "required": [
          "scope",
          "pending",
          "dead",
          "retriedPending",
          "enabledDestinations",
          "failingDestinations",
          "pausedDestinations"
        ],
        "type": "object"
      },
      "SystemStatusWorkload": {
        "additionalProperties": true,
        "properties": {
          "available": {
            "type": "boolean"
          },
          "calls": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/SystemStatusCallCounts"
              },
              {
                "type": "null"
              }
            ]
          },
          "errorCode": {
            "enum": [
              "database_unavailable",
              "workload_unavailable",
              "monitoring_unsupported"
            ],
            "type": "string"
          },
          "instances": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/SystemStatusInstanceCounts"
              },
              {
                "type": "null"
              }
            ]
          },
          "webhooks": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/SystemStatusWebhookCounts"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "available"
        ],
        "type": "object"
      },
      "MonitoringError": {
        "type": "object",
        "properties": {
          "error": {
            "type": "string",
            "enum": [
              "unauthorized",
              "monitoring_disabled",
              "server_not_found"
            ]
          }
        },
        "required": [
          "error"
        ],
        "additionalProperties": true
      },
      "MonitoringAlert": {
        "type": "object",
        "properties": {
          "code": {
            "type": "string",
            "description": "Código fixo do observador, sem erro bruto do worker. service_<papel>_unhealthy usa somente api/db/backup/console/caddy."
          },
          "severity": {
            "type": "string",
            "enum": [
              "warning",
              "critical"
            ]
          }
        },
        "required": [
          "code",
          "severity"
        ],
        "additionalProperties": true
      },
      "MonitoredServer": {
        "type": "object",
        "properties": {
          "server": {
            "type": "string",
            "description": "Nome lógico previamente cadastrado no console; nenhuma URL de acesso é retornada."
          },
          "observedAt": {
            "type": "string",
            "format": "date-time",
            "description": "Momento da última tentativa; em cache pode preceder generatedAt."
          },
          "lastSuccessAt": {
            "anyOf": [
              {
                "type": "string",
                "format": "date-time"
              },
              {
                "type": "null"
              }
            ]
          },
          "availability": {
            "type": "string",
            "enum": [
              "online",
              "offline",
              "cancelled",
              "invalid_configuration",
              "unavailable",
              "unauthorized",
              "unsupported",
              "invalid_response",
              "stale"
            ],
            "description": "unsupported identifica worker antigo (404/501); offline identifica falha de transporte. O resumo unavailable engloba os demais estados diferentes de online/offline."
          },
          "health": {
            "type": "string",
            "enum": [
              "ok",
              "warning",
              "critical",
              "unknown"
            ]
          },
          "latencyMilliseconds": {
            "anyOf": [
              {
                "type": "integer",
                "minimum": 0
              },
              {
                "type": "null"
              }
            ],
            "description": "Tempo até os headers da resposta HTTP do worker, não latência da rede WhatsApp nem duração da consulta completa."
          },
          "dataStale": {
            "type": "boolean",
            "description": "true quando data contém o último sucesso retido após falha, ou quando ainda não existe amostra válida. Nunca interpretar data retida como leitura atual."
          },
          "data": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/SystemStatus"
              },
              {
                "type": "null"
              }
            ]
          },
          "alerts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MonitoringAlert"
            }
          }
        },
        "required": [
          "server",
          "observedAt",
          "lastSuccessAt",
          "availability",
          "health",
          "latencyMilliseconds",
          "dataStale",
          "data",
          "alerts"
        ],
        "additionalProperties": true
      },
      "FleetSummary": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "minimum": 0
          },
          "online": {
            "type": "integer",
            "minimum": 0
          },
          "offline": {
            "type": "integer",
            "minimum": 0
          },
          "unavailable": {
            "type": "integer",
            "minimum": 0
          },
          "ok": {
            "type": "integer",
            "minimum": 0
          },
          "warning": {
            "type": "integer",
            "minimum": 0
          },
          "critical": {
            "type": "integer",
            "minimum": 0
          },
          "unknown": {
            "type": "integer",
            "minimum": 0
          }
        },
        "required": [
          "total",
          "online",
          "offline",
          "unavailable",
          "ok",
          "warning",
          "critical",
          "unknown"
        ],
        "additionalProperties": true,
        "description": "Contagem de servidores. Não soma instâncias ou chamadas entre bancos potencialmente compartilhados."
      },
      "FleetStatus": {
        "type": "object",
        "properties": {
          "schemaVersion": {
            "type": "integer",
            "const": 1
          },
          "generatedAt": {
            "type": "string",
            "format": "date-time"
          },
          "cacheSeconds": {
            "type": "integer",
            "const": 15
          },
          "summary": {
            "$ref": "#/components/schemas/FleetSummary"
          },
          "servers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MonitoredServer"
            }
          }
        },
        "required": [
          "schemaVersion",
          "generatedAt",
          "cacheSeconds",
          "summary",
          "servers"
        ],
        "additionalProperties": true,
        "description": "Frota ordenada pelo nome lógico, incluindo servidores indisponíveis. Cache compartilhado entre as duas rotas por 15 s; consultas concorrentes ao mesmo nó compartilham a coleta."
      }
    },
    "responses": {
      "Monitoring401": {
        "description": "Token de monitoramento ausente ou inválido.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/MonitoringError"
            }
          }
        }
      },
      "Monitoring503": {
        "description": "Monitoramento não configurado no console.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/MonitoringError"
            }
          }
        }
      }
    }
  }
}
