# Approval Gate

> Configura la compuerta de aprobación de una tarea creada por un nodo Create Task anterior.

Source: https://docs.sommatic.ai/es/nodes/human.approval.gate/

- Slug: `human.approval.gate`
- Familia: Human in the loop
- Versión: 1.0.0
- Estado: Parcial. Configura la compuerta de aprobación en una tarea existente y luego sale de inmediato por el puerto `accepted`. No suspende el workflow ni espera la decisión humana; `rejected` y `timeout` nunca se emiten.
- Ejecución: sync

Configura la compuerta de aprobación de una tarea creada por un nodo Create Task anterior. Escribe payload.hitl + execution.app_slug en el backend mediante PATCH.

## Configuración

- `approval_type` (object, obligatorio): Binaria | Herramienta | Revisión de plan | Selección única | Selección múltiple | Revisar/Editar/Rechazar
- `title` (string, obligatorio, acepta expresiones): Se muestra a quien aprueba cuando toma la tarea. Admite expresiones como {{ $json.entity_name }}.
- `description` (string, opcional, acepta expresiones): Contexto que se muestra a quien aprueba dentro del detalle de la tarea. Admite expresiones y texto de varias líneas.
- `hitl_config` (object, opcional): Campos específicos de cada subtipo (tool, plan, options, content, min_selection, etc.)

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `accepted` (por defecto): Se emite cuando quien aprueba confirma la acción (Aprobar / Permitir / Confirmar / Enviar cambios).
- `rejected`: Se emite cuando quien aprueba deniega o cancela (Rechazar / Denegar / Cancelar).
- `timeout`: Se emite cuando la tarea vence sin una decisión (SLA incumplido).
- `error`: Se emite ante fallos técnicos al configurar la compuerta de aprobación.

## Contrato de entrada

- `task_id` (string, opcional): Se propaga desde el nodo Create Task anterior
- `approval_type` (object, opcional)
- `title` (string, opcional)
- `description` (string, opcional)
- `hitl_config` (object, opcional)

## Contrato de salida

- `task_id` (string, opcional)
- `approval_type` (object, opcional)
- `decision` (string, opcional): La decisión humana real. Se llenará cuando se implemente la suspensión y reanudación; es null en el modo actual de disparar y olvidar. Valores permitidos: `approved`, `rejected`, `edited`, `timeout`.
- `selected` (array, opcional): Se llena en los tipos de aprobación single_select / multi_select.
- `edited_content` (object, opcional): Se llena cuando quien aprueba editó los pasos del plan o el contenido en revisión antes de aprobar.
- `comment` (string, opcional)
- `approver` (string, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Approval Gate").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Approval Gate`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `accepted`, según la salida que muestra Puertos.

- `$("Approval Gate").item.json.task_id` (string) = `"task-xxxxxxxxxxxxxxx"`
- `$("Approval Gate").item.json.approval_type` (object) = `{…}`
- `$("Approval Gate").item.json.decision` (string) = `null`: La decisión humana real. Se llenará cuando se implemente la suspensión y reanudación; es null en el modo actual de disparar y olvidar.
- `$("Approval Gate").item.json.selected` (array): Se llena en los tipos de aprobación single_select / multi_select. **El worker no la devuelve: se lee como undefined.**
- `$("Approval Gate").item.json.edited_content` (object): Se llena cuando quien aprueba editó los pasos del plan o el contenido en revisión antes de aprobar. **El worker no la devuelve: se lee como undefined.**
- `$("Approval Gate").item.json.comment` (string) **El worker no la devuelve: se lee como undefined.**
- `$("Approval Gate").item.json.approver` (string) **El worker no la devuelve: se lee como undefined.**
- `$("Approval Gate").item.json.port` (string) = `"accepted"` (El editor no la sugiere)
- `$("Approval Gate").item.json.approval_type.id` (number) = `1` (El editor no la sugiere)
- `$("Approval Gate").item.json.approval_type.name` (string) = `"binary_approval"` (El editor no la sugiere)
- `$("Approval Gate").item.json.approval_type.title` (string) = `"Binary Approval"` (El editor no la sugiere)
- `$("Approval Gate").item.json.approval_type.color` (string) = `"#1976d2"` (El editor no la sugiere)


## Cómo funciona

Parcial. Agrega una configuración de aprobación a una tarea existente para que la bandeja de tareas la abra con la app de compuerta de aprobación humana, y continúa de inmediato por `accepted`; no espera la decisión.

1. Resuelve la configuración y la combina sobre el payload de entrada (gana la configuración).
2. Lee `task_id` de la configuración o del payload de entrada, normalmente la salida del `human.task.create` anterior.
3. Comprueba `task_id`, `approval_type.name` y `title`, y arma `hitl` como `{ approval_type, title, description, ...hitl_config }`.
4. Lee la tarea de la API de Work Management; falla si no existe.
5. Escribe la tarea completa con `payload.hitl` y `execution` `{ app_slug: "human-approval-gate", launch_mode: "embedded" }` combinados con los valores existentes.
6. Devuelve `{ task_id, approval_type, decision: null }` por `accepted`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-approve-refund",
  "label": "Approve refund",
  "operator_slug": "human.approval.gate",
  "operator_version": "1.0.0",
  "config": {
    "approval_type": {
      "id": 1,
      "name": "binary_approval",
      "title": "Binary Approval",
      "color": "#1976d2"
    },
    "title": "Approve refund for {{ $json.task_title }}",
    "description": "Confirm the refund before it is issued.",
    "hitl_config": {}
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "accepted",
  "task_id": "task-xxxxxxxxxxxxxxx",
  "approval_type": {
    "id": 1,
    "name": "binary_approval",
    "title": "Binary Approval",
    "color": "#1976d2"
  },
  "decision": null
}
```

## Puertos de salida (comportamiento en el código)

### `accepted`

La compuerta se configuró en la tarea. No significa que alguien haya aprobado.

```json
{
  "port": "accepted",
  "task_id": "task-xxxxxxxxxxxxxxx",
  "approval_type": {
    "id": 1,
    "name": "binary_approval",
    "title": "Binary Approval",
    "color": "#1976d2"
  },
  "decision": null
}
```

### `rejected`

Nunca se emite: el worker no espera la decisión.

### `timeout`

Nunca se emite.

### `error`

Faltan datos, la tarea no existe o la llamada al backend falló.

```json
{
  "port": "error",
  "error": "Missing 'approval_type' or invalid approval type object"
}
```

## Comportamiento en el código

- `approval_type`: Uno de `binary_approval` (1), `tool_approval` (2), `plan_review` (3), `single_select_decision` (4), `multi_select_decision` (5), `review_edit_reject` (6), como `{ id, name, title, color }`.
- `hitl_config`: Se expande dentro de `hitl`, así que sus claves pueden sustituir `approval_type`, `title` y `description`. Formas por tipo: `tool_approval` `{ tool: { name, args, risk_level } }`; `plan_review` `{ plan: { steps: [{ id, title, detail }] } }`; tipos de selección `{ options: [{ id, name, title }] }`; `review_edit_reject` `{ content: { text, editable } }`.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing 'task_id'. This node must be chained after a Human Task Create node. If you are testing with 'Execute step', run the preceding Create Task node first or provide sample data that includes task_id.` | `error` | No hay `task_id` en la configuración ni en el payload. |
| `Missing 'approval_type' or invalid approval type object` | `error` | `approval_type` falta o no tiene `name`. |
| `Missing 'title'` | `error` | `title` queda vacío tras resolver las expresiones. |
| `Task '<task_id>' not found. Cannot configure approval gate on a non-existent task.` | `error` | El id de tarea no existe en Work Management. |
| `Backend rejected the update` | `error` | La actualización respondió sin `success`; se usa el mensaje del backend si existe. |
| `Request failed with status code <status>` | `error` | El backend rechazó la lectura o la actualización. |
| `services.apiManager.uri is not resolved in dependencies.config — check Link Loom Cloud environment config.` | `error` | El orquestador no tiene configurada la dirección del backend. Es un problema de configuración del servicio, no del nodo. |

## Notas y límites

- No implementado: suspender la ejecución y enrutar la decisión. `decision` siempre es `null`; `selected`, `edited_content`, `comment` y `approver` del contrato de salida nunca se devuelven; `rejected` y `timeout` nunca se activan.
- La actualización lee, modifica y escribe la tarea completa: los cambios hechos a la tarea entre la lectura y la escritura se sobrescriben. El estado de la tarea no cambia.
- El worker devuelve sus campos en el nivel superior del sobre, sin `data`, así que el motor usa el sobre completo (incluida la clave `port`) como payload del siguiente nodo.
- El worker no define `ok` (el ejemplo muestra `true`); el motor enruta solo por `port`.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "human.approval.gate",
  "name": "Approval Gate",
  "category": "hitl",
  "version": "1.0.0",
  "description": "Configures the approval gate on a task created by a preceding Create Task node. Writes payload.hitl + execution.app_slug via PATCH to the backend.",
  "capabilities": [
    "approval",
    "gate",
    "human"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "approval_type",
      "title"
    ],
    "properties": {
      "approval_type": {
        "type": "object",
        "title": "Approval Type",
        "ui_widget": "hitl_approval_type_picker",
        "description": "Binary | Tool | Plan Review | Single-Select | Multi-Select | Review/Edit/Reject"
      },
      "title": {
        "type": "string",
        "title": "Title",
        "format": "expression",
        "description": "Shown to the approver when the task is claimed. Supports expressions like {{ $json.entity_name }}."
      },
      "description": {
        "type": "string",
        "title": "Description",
        "format": "expression",
        "description": "Context shown to the approver inside the task detail. Supports expressions and multi-line text."
      },
      "hitl_config": {
        "type": "object",
        "title": "Approval configuration",
        "ui_widget": "hitl_config",
        "ui_options": {
          "depends_on": "approval_type"
        },
        "description": "Subtype-specific fields (tool, plan, options, content, min_selection, etc.)"
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "task_id": {
        "type": "string",
        "description": "Propagated from preceding Create Task node"
      },
      "approval_type": {
        "type": "object"
      },
      "title": {
        "type": "string"
      },
      "description": {
        "type": "string"
      },
      "hitl_config": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "task_id": {
        "type": "string"
      },
      "approval_type": {
        "type": "object"
      },
      "decision": {
        "type": "string",
        "enum": [
          "approved",
          "rejected",
          "edited",
          "timeout"
        ],
        "description": "The actual human decision. Populated when suspend/resume is implemented; null in the current fire-and-forget mode."
      },
      "selected": {
        "type": "array",
        "description": "Populated for single_select / multi_select approval types."
      },
      "edited_content": {
        "type": "object",
        "description": "Populated when the approver edited plan steps or review content before approving."
      },
      "comment": {
        "type": "string"
      },
      "approver": {
        "type": "string"
      }
    }
  },
  "ports": [
    {
      "port_id": "accepted",
      "label": "Accepted",
      "is_default": true,
      "description": "Emitted when the approver confirms the action (Approve / Allow / Confirm / Submit edits)."
    },
    {
      "port_id": "rejected",
      "label": "Rejected",
      "description": "Emitted when the approver denies or cancels (Reject / Deny / Cancel)."
    },
    {
      "port_id": "timeout",
      "label": "Timeout",
      "description": "Emitted when the task expires without a decision (SLA breached)."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Emitted on technical failures during approval gate configuration."
    }
  ],
  "chain_constraints": {
    "prev": {
      "required_slug": "human.task.create",
      "message": "Human Approval Gate requires a preceding Create Task node to receive the task_id."
    }
  },
  "execution_mode": "sync",
  "tags": [
    "approval",
    "gate",
    "human",
    "hitl"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "approval_type",
    "title"
  ],
  "properties": {
    "approval_type": {
      "type": "object",
      "title": "Approval Type",
      "ui_widget": "hitl_approval_type_picker",
      "description": "Binary | Tool | Plan Review | Single-Select | Multi-Select | Review/Edit/Reject"
    },
    "title": {
      "type": "string",
      "title": "Title",
      "format": "expression",
      "description": "Shown to the approver when the task is claimed. Supports expressions like {{ $json.entity_name }}."
    },
    "description": {
      "type": "string",
      "title": "Description",
      "format": "expression",
      "description": "Context shown to the approver inside the task detail. Supports expressions and multi-line text."
    },
    "hitl_config": {
      "type": "object",
      "title": "Approval configuration",
      "ui_widget": "hitl_config",
      "ui_options": {
        "depends_on": "approval_type"
      },
      "description": "Subtype-specific fields (tool, plan, options, content, min_selection, etc.)"
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "task_id": {
      "type": "string",
      "description": "Propagated from preceding Create Task node"
    },
    "approval_type": {
      "type": "object"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "hitl_config": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "task_id": {
      "type": "string"
    },
    "approval_type": {
      "type": "object"
    },
    "decision": {
      "type": "string",
      "enum": [
        "approved",
        "rejected",
        "edited",
        "timeout"
      ],
      "description": "The actual human decision. Populated when suspend/resume is implemented; null in the current fire-and-forget mode."
    },
    "selected": {
      "type": "array",
      "description": "Populated for single_select / multi_select approval types."
    },
    "edited_content": {
      "type": "object",
      "description": "Populated when the approver edited plan steps or review content before approving."
    },
    "comment": {
      "type": "string"
    },
    "approver": {
      "type": "string"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "accepted",
    "label": "Accepted",
    "is_default": true,
    "description": "Emitted when the approver confirms the action (Approve / Allow / Confirm / Submit edits)."
  },
  {
    "port_id": "rejected",
    "label": "Rejected",
    "description": "Emitted when the approver denies or cancels (Reject / Deny / Cancel)."
  },
  {
    "port_id": "timeout",
    "label": "Timeout",
    "description": "Emitted when the task expires without a decision (SLA breached)."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Emitted on technical failures during approval gate configuration."
  }
]
```
