> ## Documentation Index
> Fetch the complete documentation index at: https://chatcli.edilsonfreitas.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Resolver Incidente

> Resolve manualmente um incidente — essencial quando o sistema escala para ação humana ou quando um operador confirma que o problema foi corrigido

<ParamField path="name" type="string" required>
  Nome único do incidente (ex.: `INC-20260319-001`)
</ParamField>

<ParamField query="namespace" type="string" default="default">
  Namespace Kubernetes do incidente
</ParamField>

<ParamField body="resolution" type="string">
  Descrição de como o incidente foi resolvido. Se omitido, assume o valor padrão `"Manually resolved via dashboard"`.

  Boa prática: sempre forneça uma mensagem de resolução significativa para postmortem e trilha de auditoria.
</ParamField>

## Quando Usar Este Endpoint

Este endpoint é crítico nos seguintes cenários:

### 1. Incidentes Escalados (Ação Humana Necessária)

Quando a plataforma AIOps esgota todas as tentativas de remediação automática (padrão: 3 tentativas), o incidente transiciona para o estado **Escalated**. Neste ponto:

* O sistema de notificação alerta a equipe de plantão pelos canais configurados (Slack, PagerDuty, etc.)
* A política de escalação progride através dos níveis (L1 → L2 → L3) com base nos tempos limite
* **Nenhuma remediação automática adicional será tentada**
* O incidente permanece no estado `Escalated` até que um humano o resolva por este endpoint, pelo painel web ou pela CLI

### 2. Verificação Manual Após Remediação Automatica

Mesmo quando a remediação automática e bem-sucedida, operadores podem querer verificar manualmente e fechar o incidente com contexto adicional.

### 3. Falsos Positivos

Quando um incidente e detectado mas o operador determina que e um falso positivo, use este endpoint com uma resolução como `"False positive — metric spike caused by scheduled batch job"`.

## Fluxo de Resolução para Incidentes Escalados

```
Incidente Detectado
      ↓
  Análise IA → Remediação Runbook/Agentica
      ↓                    ↓
  Sucesso → Resolvido    Falha (retry até 3x)
                           ↓
                    Todas tentativas esgotadas
                           ↓
                      ESCALADO ← Você está aqui
                           ↓
         ┌─────────────────┼──────────────────┐
         ↓                 ↓                  ↓
    API Resolver      Botao Dashboard     Comando CLI
  POST /resolve      Botao "Resolver"   (versão futura)
         ↓                 ↓                  ↓
         └─────────────────┼──────────────────┘
                           ↓
                    Estado: Resolvido
                    PostMortem gerado
                    Cache de dedup limpo
                    Evento de auditoria registrado
```

## O Que Acontece Após a Resolução

1. **Mudança de Estado**: O incidente transiciona de `Escalated` (ou qualquer estado ativo) para `Resolved`
2. **Anotações Adicionadas**:
   * `aiops.chatcli.io/resolved-by` — o papel/usuário autenticado
   * `aiops.chatcli.io/resolved-at` — timestamp da resolução
   * `aiops.chatcli.io/manual-resolution` — definido como `"true"`
3. **Cache de Dedup Limpo**: A entrada de deduplicação do recurso é invalidada, permitindo que novas anomalias sejam detectadas para o mesmo recurso
4. **PostMortem Gerado**: Um postmortem automático é criado com os detalhes da resolução
5. **Evento de Auditoria**: Um evento de auditoria imutável é registrado para conformidade

<ResponseExample>
  ```json Response 200 theme={"system"}
  {
    "apiVersion": "v1",
    "kind": "Incident",
    "metadata": {
      "name": "INC-20260319-001",
      "namespace": "production",
      "annotations": {
        "aiops.chatcli.io/resolved-by": "operator",
        "aiops.chatcli.io/resolved-at": "2026-03-19T16:45:00Z",
        "aiops.chatcli.io/manual-resolution": "true"
      }
    },
    "spec": {
      "resourceRef": {
        "kind": "Deployment",
        "name": "payment-service",
        "namespace": "production"
      },
      "severity": "critical",
      "signalType": "oom_kill"
    },
    "status": {
      "state": "Resolved",
      "resolution": "Memory leak fixed in payment-service v2.4.1 hotfix deployed manually. Verified stable for 15 minutes.",
      "resolvedAt": "2026-03-19T16:45:00Z",
      "detectedAt": "2026-03-19T14:30:00Z",
      "remediationAttempts": 3,
      "escalatedAt": "2026-03-19T15:15:00Z"
    }
  }
  ```
</ResponseExample>

<ResponseExample>
  ```json Response 404 theme={"system"}
  {
    "apiVersion": "v1",
    "kind": "Error",
    "error": {
      "code": 404,
      "message": "Incident not found",
      "details": "No incident named 'INC-20260319-999' found in namespace 'production'"
    }
  }
  ```
</ResponseExample>

<ResponseExample>
  ```json Response 409 theme={"system"}
  {
    "apiVersion": "v1",
    "kind": "Error",
    "error": {
      "code": 409,
      "message": "Incident already resolved",
      "details": "The incident 'INC-20260319-001' was already resolved at 2026-03-19T16:45:00Z"
    }
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /incidents/{name}/resolve
openapi: 3.1.0
info:
  title: ChatCLI AIOps Platform API
  description: >-
    REST API for the ChatCLI AIOps Platform — incidents, SLOs, runbooks,
    approvals, postmortems, analytics, audit, federation and health.


    The playground below uses **editable server variables** so you can point
    requests at your own self-hosted instance. Adjust `host`, `port` and
    `basePath` to match your deployment, then click **Try it**.
  version: 1.0.0
  contact:
    name: ChatCLI
    url: https://github.com/diillson/chatcli
  license:
    name: Apache-2.0
    identifier: Apache-2.0
servers:
  - url: http://{host}:{port}/{basePath}
    description: >-
      Self-hosted ChatCLI AIOps Platform — adjust host, port and basePath to
      match your deployment.
    variables:
      host:
        default: localhost
        description: >-
          Hostname or IP of your ChatCLI operator. For Kubernetes, use the
          Service DNS (e.g. chatcli-api.chatcli-system.svc) or your Ingress
          host.
      port:
        default: '8090'
        description: >-
          Port the API listens on. Default is 8090; configurable via Helm value
          `apiPort` or env var CHATCLI_API_PORT.
      basePath:
        default: api/v1
        description: >-
          API base path. Always `api/v1` unless you have a custom proxy rewrite
          in front of the operator.
security:
  - ApiKeyAuth: []
tags:
  - name: Incidents
    description: >-
      Incident lifecycle: list, fetch, acknowledge, resolve, snooze, timeline
      and remediation views.
  - name: Runbooks
    description: Remediation runbooks (list, create, update, delete).
  - name: SLOs
    description: Service Level Objectives and error budgets.
  - name: Approvals
    description: Approval workflow for risky remediations.
  - name: Postmortems
    description: Auto-generated postmortems with review, feedback and close.
  - name: Remediations
    description: Remediation plans and agentic execution history.
  - name: AI Insights
    description: AI root-cause analysis and recommendations per incident.
  - name: Analytics
    description: 'Operational analytics: MTTD, MTTR, trends, capacity, compliance.'
  - name: Audit
    description: Immutable audit log and exports.
  - name: Federation
    description: 'Multi-cluster federation: clusters, status and cross-cluster correlations.'
  - name: Health
    description: Liveness and readiness probes.
paths:
  /incidents/{name}/resolve:
    post:
      tags:
        - Incidents
      summary: Resolve Incident
      description: >-
        Manually resolves an incident — used when the system escalates to human
        action or an operator confirms the issue is fixed.
      operationId: resolveIncident
      parameters:
        - name: name
          in: path
          required: true
          description: Unique incident name.
          schema:
            type: string
            example: INC-20260319-001
        - name: namespace
          in: query
          required: false
          description: Kubernetes namespace of the incident.
          schema:
            type: string
            default: default
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                resolution:
                  type: string
                  description: >-
                    Description of how the incident was resolved. Defaults to
                    `"Manually resolved via dashboard"` when omitted.
            example:
              resolution: >-
                Memory leak fixed in payment-service v2.4.1 hotfix deployed
                manually. Verified stable for 15 minutes.
      responses:
        '200':
          description: Incident resolved
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Incident'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/RateLimited'
components:
  schemas:
    Incident:
      type: object
      properties:
        apiVersion:
          type: string
          example: v1
        kind:
          type: string
          example: Incident
        metadata:
          type: object
          properties:
            name:
              type: string
            namespace:
              type: string
            createdAt:
              type: string
              format: date-time
            annotations:
              type: object
              additionalProperties:
                type: string
            labels:
              type: object
              additionalProperties:
                type: string
        spec:
          type: object
          properties:
            resource:
              type: string
            resourceRef:
              type: object
              properties:
                kind:
                  type: string
                name:
                  type: string
                namespace:
                  type: string
            severity:
              type: string
            description:
              type: string
            detectionSource:
              type: string
            correlationId:
              type: string
            runbook:
              type: string
            escalationPolicy:
              type: string
            signalType:
              type: string
        status:
          type: object
          properties:
            state:
              type: string
              enum:
                - Detected
                - Analyzing
                - Remediating
                - Contained
                - Resolved
                - Escalated
                - Failed
              description: >-
                Lifecycle state. Contained (GAP-03 fix) indicates the workload
                was silenced via a containment action and human intervention is
                required to restore service.
            riskScore:
              type: integer
            analysisResult:
              type: object
              properties:
                rootCause:
                  type: string
                recommendation:
                  type: string
                confidence:
                  type: number
                relatedEvents:
                  type: array
                  items:
                    type: string
            acknowledged:
              type: boolean
            acknowledgedBy:
              type: string
            acknowledgedAt:
              type: string
              format: date-time
            message:
              type: string
            snoozed:
              type: boolean
            snoozedBy:
              type: string
            snoozedAt:
              type: string
              format: date-time
            snoozeUntil:
              type: string
              format: date-time
            snoozeReason:
              type: string
            assignedTo:
              type: string
            detectedAt:
              type: string
              format: date-time
            resolvedAt:
              type: string
              format: date-time
            escalatedAt:
              type: string
              format: date-time
            lastUpdated:
              type: string
              format: date-time
            timelineCount:
              type: integer
            remediationAttempts:
              type: integer
            resolution:
              type: string
            requiresHumanAction:
              type: boolean
              description: >-
                True when the Issue is in Contained state OR carries the
                RequiresHumanAction condition. GAP-07 fix promoted this to a
                typed status field on the Issue CRD itself so `kubectl get issue
                -o jsonpath='{.status.requiresHumanAction}'` works without
                parsing conditions.
            requiredAction:
              type: string
              description: >-
                Concrete follow-up action the operator must perform when
                requiresHumanAction=true (e.g., 'restore the deployment's
                replicas to the desired count after fixing the root cause').
                GAP-07 fix.
            chaosInduced:
              type: boolean
              description: >-
                True when the Issue was correlated with an active
                ChaosExperiment at creation time (label
                platform.chatcli.io/source=chaos-experiment). GAP-04 fix.
            chaosExperiment:
              type: string
              description: >-
                Name of the correlated ChaosExperiment CR when
                chaosInduced=true. GAP-04 fix.
    Error:
      type: object
      required:
        - apiVersion
        - kind
        - error
      properties:
        apiVersion:
          type: string
          example: v1
        kind:
          type: string
          example: Error
        error:
          oneOf:
            - type: object
              required:
                - code
                - message
              properties:
                code:
                  type: integer
                  example: 404
                message:
                  type: string
                  example: Resource not found
                details:
                  type: string
            - type: string
        code:
          type: integer
          description: Top-level code (only used by some endpoints).
          example: 400
  responses:
    Unauthorized:
      description: Missing or invalid API token
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Conflict:
      description: Conflict with current state of the resource
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    RateLimited:
      description: Rate limit exceeded for this token's role
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        Bearer token issued by the operator. Format: `Authorization: Bearer
        <token>`.

````