# Vectry Log

> Emite un evento causal estructurado a Vectry Operational Intelligence Platform.

Source: https://docs.sommatic.ai/es/nodes/vectry.log/

- Slug: `vectry.log`
- Familia: Operación
- Versión: 1.0.0
- Estado: Experimental. Hoy siempre falla: el worker llama a `logger.debug`, que el logger del runtime no tiene, así que toda ejecución sale por `error` con "logger.debug is not a function". No lo uses hasta que se corrija.
- Ejecución: fire-and-forget

Emite un evento causal estructurado a Vectry Operational Intelligence Platform.

Vectry usa estos eventos para construir un grafo causal de tu sistema, lo que habilita XAI (IA explicable) avanzada, detección de anomalías y análisis de causa raíz. A diferencia de los logs estándar, los eventos de Vectry se vinculan por entidades y operaciones para modelar *causa y efecto*.

**Conceptos clave:**
- **Entidad:** El sustantivo (p. ej., "Order", "User").
- **Operación:** El verbo (p. ej., "Created", "Updated").
- **Contexto:** Datos del payload que ayudan a explicar el evento.

**Casos de uso:**
- Reportar hitos de negocio relevantes (p. ej., "LoanApproved").
- Registrar los pasos de razonamiento interno de la IA (integración con SpikingBrain).
- Seguir las interacciones entre sistemas distribuidos.

## Configuración

- `api_key` (string, obligatorio)
- `endpoint` (string, opcional): Por defecto: `https://api.vectry.io`.
- `system_domain` (string, opcional)
- `system_entity` (string, opcional)

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

- `success` (por defecto): Logged
- `error`: Error

## Contrato de entrada

- `operation` (string, obligatorio): Nombre del evento
- `system_entity_id` (string, opcional): ID único de la entidad
- `severity` (string, opcional): Valores permitidos: `info`, `warn`, `error`, `debug`.
- `payload` (object, opcional): Contexto del evento
- `tags` (array<string>, opcional)

## Contrato de salida

- `success` (boolean, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Vectry Log").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Vectry Log`). **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 `success`, según la salida que muestra Puertos.

- `$("Vectry Log").item.json.success` (boolean) = `true`
- `$("Vectry Log").item.json.port` (string) = `"success"` (El editor no la sugiere)


## Cómo funciona

Pensado para enviar un evento a la API de ingesta de Vectry (`POST <endpoint>/v1/ingest`). En el runtime actual sale por `error` con `logger.debug is not a function` justo antes de la petición, así que no se envía ningún evento.

1. Combina el ítem de entrada con la configuración resuelta (gana la configuración).
2. Sale por `error` con `Missing 'api_key' for Vectry` cuando no hay clave de API disponible, y con `Missing 'operation'` cuando `operation` está vacío.
3. Construye el nombre del evento `<system_domain>.<system_entity>.<operation>` (ambos valen `default` por defecto) y el cuerpo `{ dataset, event, level, timestamp, data, tags, source: "sommatic-orchestrator" }`, donde `data` es `payload` más `entity_id` y `operation`.
4. Llama a `logger.debug()`, que lanza una excepción; el worker la captura y sale por `error`. El paso siguiente no se alcanza hoy.
5. Envía el cuerpo con `Authorization: Bearer <api_key>` y devuelve `{ port: "success", success: true }`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-log-order-shipped",
  "label": "Log order shipped",
  "operator_slug": "vectry.log",
  "operator_version": "1.0.0",
  "config": {
    "api_key": "<vectry_api_key>",
    "endpoint": "https://api.example.com",
    "system_domain": "sales",
    "system_entity": "order",
    "operation": "shipped",
    "system_entity_id": "{{ $json.order_id }}",
    "severity": "info"
  }
}
```

### Envelope

```json
{
  "ok": false,
  "port": "error",
  "data": {
    "port": "error",
    "success": false,
    "error": "logger.debug is not a function"
  }
}
```

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

### `success`

No se alcanza en el runtime actual: la llamada a `logger.debug()` falla antes. Se muestra con la forma que construye el código.

```json
{
  "port": "success",
  "success": true
}
```

### `error`

Cada ejecución hoy. La salida es todo el objeto devuelto, `{ port, success, error }`.

```json
{
  "port": "error",
  "success": false,
  "error": "logger.debug is not a function"
}
```

## Comportamiento en el código

- `api_key`: Un secreto literal: el nodo no tiene `connection_id`, así que la clave queda guardada en el flujo, su historial de versiones y Git.
- `endpoint`: URL base; se le añade `/v1/ingest`.
- `operation`: No figuran en el esquema de configuración (solo en el contrato de entrada), pero se leen de la configuración del nodo o, si no están ahí, del ítem de entrada: `operation`, `system_entity_id`, `severity` (por defecto `info`), `tags` (por defecto `[]`) y `payload`.
- `payload`: El `payload` configurado o, si no hay ninguno, el ítem de entrada del nodo. Sus claves se expanden dentro de `data`.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `logger.debug is not a function` | `error` | El worker llama a `logger.debug()`, que el logger del runtime no ofrece. Ocurre en cada ejecución; ninguna configuración lo evita. |
| `Missing 'api_key' for Vectry` | `error` | No hay clave de API disponible para la llamada. Define `api_key`. |
| `Missing 'operation'` | `error` | `operation` no está definido ni en el nodo ni en el ítem de entrada. |
| `Request failed with status code <status>` | `error` | No se alcanza hoy. Indicaría que Vectry rechazó el evento (por ejemplo, clave o endpoint incorrectos). |

## Notas y límites

- El worker llama a `logger.debug()`, que el logger del runtime no ofrece (tiene `info`, `warning`, `error`, `log` y `success`). La llamada falla en cada ejecución.
- Mientras no se corrija, envía los eventos con `io.http` al mismo endpoint de ingesta y con el mismo cuerpo.
- Salir por `error` no hace fallar la ejecución: el motor sigue las conexiones de `error` y, si no hay ninguna, la rama simplemente termina.
- Los ajustes de `execution` (`retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `timeout_ms`) se aceptan, pero ni este worker ni el motor los aplican.


## Contratos (JSON Schema)

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

```json
{
  "slug": "vectry.log",
  "name": "Vectry Log",
  "category": "ops",
  "version": "1.0.0",
  "description": "Emits a structured causal event to the Vectry Operational Intelligence Platform.\n\n  Vectry uses these events to construct a Causal Graph of your system, enabling advanced XAI (Explainable AI), anomaly detection, and root cause analysis. Unlike standard logs, Vectry events are linked by entities and operations to model *cause and effect*.\n\n  **Key Concepts:**\n  - **Entity:** The noun (e.g., \"Order\", \"User\").\n  - **Operation:** The verb (e.g., \"Created\", \"Updated\").\n  - **Context:** Payload data that helps explain the event.\n\n  **Use Cases:**\n  - Reporting significant business milestones (e.g., \"LoanApproved\").\n  - Logging internal AI reasoning steps (SpikingBrain integration).\n  - Tracking distributed system interactions.",
  "capabilities": [
    "observability",
    "causal-ai",
    "vectry",
    "xai"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "api_key"
    ],
    "properties": {
      "api_key": {
        "type": "string",
        "title": "Vectry API Key",
        "format": "password"
      },
      "endpoint": {
        "type": "string",
        "default": "https://api.vectry.io",
        "title": "API Endpoint"
      },
      "system_domain": {
        "type": "string",
        "title": "Domain (e.g. Sales)"
      },
      "system_entity": {
        "type": "string",
        "title": "Entity Type (e.g. Order)"
      },
      "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": {
      "operation": {
        "type": "string",
        "description": "Event Name"
      },
      "system_entity_id": {
        "type": "string",
        "description": "Unique Entity ID"
      },
      "severity": {
        "type": "string",
        "enum": [
          "info",
          "warn",
          "error",
          "debug"
        ]
      },
      "payload": {
        "type": "object",
        "description": "Event Context"
      },
      "tags": {
        "type": "array",
        "items": {
          "type": "string"
        }
      }
    },
    "required": [
      "operation"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "success": {
        "type": "boolean"
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Logged",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "fire-and-forget",
  "tags": [
    "observability",
    "vectry",
    "ai"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_vectry",
    "profile": {
      "name": "Vectry Analytics",
      "verified": true,
      "url": "https://me.veripass.com/vectry",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "api_key"
  ],
  "properties": {
    "api_key": {
      "type": "string",
      "title": "Vectry API Key",
      "format": "password"
    },
    "endpoint": {
      "type": "string",
      "default": "https://api.vectry.io",
      "title": "API Endpoint"
    },
    "system_domain": {
      "type": "string",
      "title": "Domain (e.g. Sales)"
    },
    "system_entity": {
      "type": "string",
      "title": "Entity Type (e.g. Order)"
    },
    "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": {
    "operation": {
      "type": "string",
      "description": "Event Name"
    },
    "system_entity_id": {
      "type": "string",
      "description": "Unique Entity ID"
    },
    "severity": {
      "type": "string",
      "enum": [
        "info",
        "warn",
        "error",
        "debug"
      ]
    },
    "payload": {
      "type": "object",
      "description": "Event Context"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  },
  "required": [
    "operation"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "success": {
      "type": "boolean"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Logged",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
