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

# Regras de gravação

> Regras automáticas para sinalizar e marcar gravações que correspondam a condições

Defina regras que avaliam gravações automaticamente e executam ações quando as condições são atendidas. As regras são executadas sobre os dados das gravações recebidas e podem marcar gravações com tags, criar eventos na linha do tempo, sinalizar itens para revisão humana ou disparar notificações -- sem nenhuma intervenção manual.

> [!NOTE]
>
> O Fleet Management está em versão prévia. As APIs e os recursos descritos nesta página podem mudar.

## Como as regras funcionam

1. Você define uma regra com uma **condição** (o que procurar) e uma ou mais **ações** (o que fazer quando encontrar).
2. Quando uma gravação termina de ser processada, todas as regras ativas são avaliadas em relação aos dados dela.
3. Se a condição de uma regra for atendida, suas ações são executadas automaticamente.
4. Os resultados da avaliação das regras são registrados em log para auditoria e depuração.

As regras são avaliadas com base em dados de tópicos, metadados da gravação e padrões de eventos dentro de uma gravação. Elas podem ter como alvo dispositivos específicos, grupos de dispositivos ou ser aplicadas a toda a frota.

## Tipos de regra

| Tipo de regra | Descrição | Exemplo de caso de uso |
| - | - | - |
| `threshold` | Valor numérico que excede ou fica abaixo de um limite | Temperatura do motor > 80C, latência > 100ms |
| `pattern` | Correspondência por regex em dados de tópicos ou campos de metadados | A mensagem de erro contém "timeout", o nome do tópico corresponde a `/sensors/*/error` |
| `frequency` | Evento ocorre mais de N vezes dentro de uma janela de tempo | Mais de 5 erros em 1 minuto, a taxa de heartbeat cai abaixo de 1 Hz |
| `absence` | Dados esperados estão ausentes por uma duração especificada | Nenhum heartbeat por 30 segundos, ausência de quadros da câmera por 5 segundos |
| `composite` | Combinação lógica de outras condições (AND, OR) | Temperatura > 80C AND velocidade do motor > 1000 RPM |

## Criação de regras

### Regra de limite

O tipo de regra mais comum. Monitore um campo numérico em um tópico e dispare quando ele ultrapassar um limite.

```python Python theme={null}
from avala import Client

client = Client()

rule = client.fleet.rules.create(
    name="High Latency Alert",
    description="Triggers when control loop latency exceeds 100ms for more than 1 minute",
    condition={
        "type": "threshold",
        "topic": "/diagnostics/latency",
        "field": "data.value",
        "operator": "gt",
        "value": 100,
        "window": "1m"
    },
    actions=[
        {"type": "tag", "value": "high-latency"},
        {"type": "create_event", "event_type": "warning", "label": "High latency detected"},
        {"type": "notify", "channel_id": "ch_abc123"}
    ]
)

print(f"Rule created: {rule.name} ({rule.uid})")
```

```typescript TypeScript theme={null}
import Avala from "@avala-ai/sdk";

const avala = new Avala();

const rule = await avala.fleet.rules.create({
  name: "High Latency Alert",
  description: "Triggers when control loop latency exceeds 100ms for more than 1 minute",
  condition: {
    type: "threshold",
    topic: "/diagnostics/latency",
    field: "data.value",
    operator: "gt",
    value: 100,
    window: "1m",
  },
  actions: [
    { type: "tag", value: "high-latency" },
    { type: "create_event", eventType: "warning", label: "High latency detected" },
    { type: "notify", channelId: "ch_abc123" },
  ],
});

console.log(`Rule created: ${rule.name} (${rule.uid})`);
```

```bash CLI theme={null}
avala fleet rules create \
  --name "High Latency Alert" \
  --condition '{"type": "threshold", "topic": "/diagnostics/latency", "field": "data.value", "operator": "gt", "value": 100, "window": "1m"}' \
  --action tag:high-latency \
  --action create_event:warning:"High latency detected" \
  --action notify:ch_abc123
```

### Operadores de condição

| Operador | Descrição | Válido para |
| - | - | - |
| `gt` | Maior que | Campos numéricos |
| `gte` | Maior ou igual | Campos numéricos |
| `lt` | Menor que | Campos numéricos |
| `lte` | Menor ou igual | Campos numéricos |
| `eq` | Igual a | Campos numéricos, de string e booleanos |
| `neq` | Diferente de | Campos numéricos, de string e booleanos |
| `between` | Dentro de um intervalo (inclusivo) | Campos numéricos |
| `outside` | Fora de um intervalo | Campos numéricos |

### Regra de padrão

Compare com valores de string em dados de tópicos ou metadados da gravação usando expressões regulares.

```python Python theme={null}
rule = client.fleet.rules.create(
    name="Timeout Error Detector",
    description="Flags recordings containing timeout errors in diagnostics",
    condition={
        "type": "pattern",
        "topic": "/diagnostics/errors",
        "field": "message",
        "regex": "(?i)timeout|timed?\\s*out",
    },
    actions=[
        {"type": "tag", "value": "has-timeout-errors"},
        {"type": "flag_for_review"},
        {"type": "create_event", "event_type": "error", "label": "Timeout error detected"}
    ]
)
```

```typescript TypeScript theme={null}
const rule = await avala.fleet.rules.create({
  name: "Timeout Error Detector",
  description: "Flags recordings containing timeout errors in diagnostics",
  condition: {
    type: "pattern",
    topic: "/diagnostics/errors",
    field: "message",
    regex: "(?i)timeout|timed?\\s*out",
  },
  actions: [
    { type: "tag", value: "has-timeout-errors" },
    { type: "flag_for_review" },
    { type: "create_event", eventType: "error", label: "Timeout error detected" },
  ],
});
```

### Regra de frequência

Dispare quando um evento ou condição ocorrer mais (ou menos) vezes do que um número especificado dentro de uma janela de tempo deslizante.

```python Python theme={null}
rule = client.fleet.rules.create(
    name="Error Burst Detector",
    description="Triggers when more than 5 errors occur within any 1-minute window",
    condition={
        "type": "frequency",
        "topic": "/diagnostics/errors",
        "count_operator": "gt",
        "count": 5,
        "window": "1m"
    },
    actions=[
        {"type": "tag", "value": "error-burst"},
        {"type": "create_event", "event_type": "anomaly", "label": "Error burst detected"},
        {"type": "notify", "channel_id": "ch_abc123"}
    ]
)
```

```typescript TypeScript theme={null}
const rule = await avala.fleet.rules.create({
  name: "Error Burst Detector",
  description: "Triggers when more than 5 errors occur within any 1-minute window",
  condition: {
    type: "frequency",
    topic: "/diagnostics/errors",
    countOperator: "gt",
    count: 5,
    window: "1m",
  },
  actions: [
    { type: "tag", value: "error-burst" },
    { type: "create_event", eventType: "anomaly", label: "Error burst detected" },
    { type: "notify", channelId: "ch_abc123" },
  ],
});
```

### Regra de ausência

Detecte dados ausentes -- útil para monitoramento de heartbeat, feeds de sensores interrompidos e problemas de conectividade.

```python Python theme={null}
rule = client.fleet.rules.create(
    name="Missing Heartbeat",
    description="Triggers when no heartbeat message appears for 30 seconds",
    condition={
        "type": "absence",
        "topic": "/system/heartbeat",
        "timeout": "30s"
    },
    actions=[
        {"type": "create_event", "event_type": "error", "label": "Heartbeat lost"},
        {"type": "notify", "channel_id": "ch_abc123"}
    ]
)
```

```typescript TypeScript theme={null}
const rule = await avala.fleet.rules.create({
  name: "Missing Heartbeat",
  description: "Triggers when no heartbeat message appears for 30 seconds",
  condition: {
    type: "absence",
    topic: "/system/heartbeat",
    timeout: "30s",
  },
  actions: [
    { type: "create_event", eventType: "error", label: "Heartbeat lost" },
    { type: "notify", channelId: "ch_abc123" },
  ],
});
```

### Regra composta

Combine várias condições com operadores lógicos para cenários de detecção complexos.

```python Python theme={null}
rule = client.fleet.rules.create(
    name="Thermal Overload Risk",
    description="Triggers when temperature is high AND motor is under heavy load",
    condition={
        "type": "composite",
        "operator": "and",
        "conditions": [
            {
                "type": "threshold",
                "topic": "/sensors/temperature",
                "field": "temp_c",
                "operator": "gt",
                "value": 80
            },
            {
                "type": "threshold",
                "topic": "/motors/joint_3",
                "field": "current_a",
                "operator": "gt",
                "value": 5.0
            }
        ]
    },
    actions=[
        {"type": "tag", "value": "thermal-overload-risk"},
        {"type": "create_event", "event_type": "warning", "label": "Thermal overload risk"},
        {"type": "flag_for_review"},
        {"type": "notify", "channel_id": "ch_abc123"}
    ]
)
```

```typescript TypeScript theme={null}
const rule = await avala.fleet.rules.create({
  name: "Thermal Overload Risk",
  description: "Triggers when temperature is high AND motor is under heavy load",
  condition: {
    type: "composite",
    operator: "and",
    conditions: [
      {
        type: "threshold",
        topic: "/sensors/temperature",
        field: "temp_c",
        operator: "gt",
        value: 80,
      },
      {
        type: "threshold",
        topic: "/motors/joint_3",
        field: "current_a",
        operator: "gt",
        value: 5.0,
      },
    ],
  },
  actions: [
    { type: "tag", value: "thermal-overload-risk" },
    { type: "create_event", eventType: "warning", label: "Thermal overload risk" },
    { type: "flag_for_review" },
    { type: "notify", channelId: "ch_abc123" },
  ],
});
```

## Ações de regra

Cada regra pode ter uma ou mais ações que são executadas quando sua condição é atendida.

| Ação | Descrição | Parâmetros |
| - | - | - |
| `tag` | Adiciona uma tag à gravação | `value`: string de tag |
| `create_event` | Criar um marcador de evento na linha do tempo da gravação | `event_type`, `label`, `severity` opcional |
| `flag_for_review` | Marcar a gravação para revisão humana no painel | Nenhum |
| `notify` | Enviar uma notificação por meio de um canal de alerta configurado | `channel_id` |
| `auto_label` | Disparar um pipeline de rotulagem automática na gravação | `pipeline_id` |

> [!NOTE]
>
> As ações são executadas na ordem em que foram definidas. Se uma ação `notify` falhar (por exemplo, o webhook do Slack retornar um erro), as ações seguintes ainda serão executadas. As ações com falha são registradas nos resultados da avaliação da regra.

### Ação de tag

Tags são strings pesquisáveis anexadas às gravações. Use tags para categorizar gravações e facilitar a filtragem posterior no navegador de gravações ou em consultas da SDK.

```python theme={null}
{"type": "tag", "value": "high-latency"}
```

### Ação de criar evento

Cria um [marcador de evento](https://avala.ai/docs/pt/visualization/fleet/events-and-markers.md) com carimbo de data e hora na gravação, no ponto em que a condição foi atendida.

```python theme={null}
{"type": "create_event", "event_type": "warning", "label": "High latency detected", "severity": "warning"}
```

### Ação de sinalizar para revisão

Marca a gravação no painel com um sinalizador de revisão. As gravações sinalizadas aparecem no filtro "Needs Review" do navegador de gravações.

```python theme={null}
{"type": "flag_for_review"}
```

### Ação de notificar

Envia uma notificação para um [canal de alerta](https://avala.ai/docs/pt/visualization/fleet/alerts-and-notifications.md) configurado. A notificação inclui o nome da regra, o ID da gravação, o nome do dispositivo e um link para a gravação no visualizador.

```python theme={null}
{"type": "notify", "channel_id": "ch_abc123"}
```

### Ação de rotulagem automática

Dispara um pipeline de rotulagem automática na gravação. Útil para executar inferência de ML em gravações que correspondam a padrões específicos -- por exemplo, rotular automaticamente todas as gravações marcadas com eventos de "near-miss".

```python theme={null}
{"type": "auto_label", "pipeline_id": "pipe_abc123"}
```

## Escopo da regra

Por padrão, as regras se aplicam a todas as gravações da frota. Você pode restringir o escopo de uma regra a dispositivos ou grupos de dispositivos específicos.

```python Python theme={null}
# Rule scoped to a specific device group
rule = client.fleet.rules.create(
    name="Warehouse B Temperature Monitor",
    scope={
        "group_ids": ["grp_abc123"]
    },
    condition={
        "type": "threshold",
        "topic": "/sensors/temperature",
        "field": "temp_c",
        "operator": "gt",
        "value": 45
    },
    actions=[
        {"type": "tag", "value": "high-temp"},
        {"type": "create_event", "event_type": "warning", "label": "High ambient temperature"}
    ]
)

# Rule scoped to specific devices
rule = client.fleet.rules.create(
    name="Robot Arm 01 Force Monitor",
    scope={
        "device_ids": ["dev_abc123", "dev_def456"]
    },
    condition={
        "type": "threshold",
        "topic": "/sensors/force",
        "field": "force_n",
        "operator": "gt",
        "value": 50
    },
    actions=[
        {"type": "create_event", "event_type": "anomaly", "label": "Force spike"}
    ]
)
```

```typescript TypeScript theme={null}
// Rule scoped to a specific device group
const rule = await avala.fleet.rules.create({
  name: "Warehouse B Temperature Monitor",
  scope: {
    groupIds: ["grp_abc123"],
  },
  condition: {
    type: "threshold",
    topic: "/sensors/temperature",
    field: "temp_c",
    operator: "gt",
    value: 45,
  },
  actions: [
    { type: "tag", value: "high-temp" },
    { type: "create_event", eventType: "warning", label: "High ambient temperature" },
  ],
});
```

## Gerenciamento de regras

### Listar regras

```python Python theme={null}
# List all enabled rules
rules = client.fleet.rules.list(enabled=True)
for rule in rules:
    print(f"{rule.name} ({rule.uid}) -- enabled={rule.enabled}")
    print(f"  Hits: {rule.hit_count} | Last hit: {rule.last_hit_at}")

# Filter by condition type
threshold_rules = client.fleet.rules.list(condition_type="threshold")
```

```typescript TypeScript theme={null}
const rules = await avala.fleet.rules.list({ enabled: true });
for (const rule of rules.items) {
  console.log(`${rule.name} (${rule.uid}) -- enabled=${rule.enabled}`);
  console.log(`  Hits: ${rule.hitCount} | Last hit: ${rule.lastHitAt}`);
}
```

```bash CLI theme={null}
avala fleet rules list --enabled
avala fleet rules list --type threshold
```

### Ativar e desativar regras

Pause uma regra sem excluí-la. As regras desativadas são preservadas com sua configuração e histórico de correspondências.

```python Python theme={null}
# Disable a rule
client.fleet.rules.update(rule_id="rul_abc123", enabled=False)

# Re-enable a rule
client.fleet.rules.update(rule_id="rul_abc123", enabled=True)
```

```typescript TypeScript theme={null}
await avala.fleet.rules.update({ ruleId: "rul_abc123", enabled: false });
await avala.fleet.rules.update({ ruleId: "rul_abc123", enabled: true });
```

```bash CLI theme={null}
avala fleet rules disable rul_abc123
avala fleet rules enable rul_abc123
```

### Excluir uma regra

```python Python theme={null}
client.fleet.rules.delete(rule_id="rul_abc123")
```

```typescript TypeScript theme={null}
await avala.fleet.rules.delete({ ruleId: "rul_abc123" });
```

```bash CLI theme={null}
avala fleet rules delete rul_abc123
```

> [!WARNING]
>
> A exclusão de uma regra é permanente. Os eventos e as tags criados anteriormente pela regra não são removidos -- apenas a avaliação futura é interrompida. Se quiser interromper uma regra temporariamente, desative-a.

## Estatísticas da regra

Cada regra acompanha estatísticas de avaliação para ajudar você a ajustar as condições e reduzir falsos positivos.

| Métrica | Descrição |
| - | - |
| `evaluation_count` | Número total de gravações avaliadas em relação a esta regra |
| `hit_count` | Número de gravações que corresponderam à condição da regra |
| `hit_rate` | Porcentagem de avaliações que corresponderam (hit\_count / evaluation\_count) |
| `last_hit_at` | Carimbo de data e hora da correspondência mais recente |
| `avg_evaluation_ms` | Tempo médio para avaliar a regra em uma gravação |

```python Python theme={null}
rule = client.fleet.rules.get(rule_id="rul_abc123")

print(f"Rule: {rule.name}")
print(f"Evaluations: {rule.stats.evaluation_count}")
print(f"Hits: {rule.stats.hit_count} ({rule.stats.hit_rate:.1%})")
print(f"Last hit: {rule.stats.last_hit_at}")
print(f"Avg evaluation time: {rule.stats.avg_evaluation_ms:.0f}ms")
```

```typescript TypeScript theme={null}
const rule = await avala.fleet.rules.get({ ruleId: "rul_abc123" });

console.log(`Rule: ${rule.name}`);
console.log(`Evaluations: ${rule.stats.evaluationCount}`);
console.log(`Hits: ${rule.stats.hitCount} (${(rule.stats.hitRate * 100).toFixed(1)}%)`);
console.log(`Last hit: ${rule.stats.lastHitAt}`);
console.log(`Avg evaluation time: ${rule.stats.avgEvaluationMs.toFixed(0)}ms`);
```

## Painel de regras

O painel de regras em Mission Control exibe todas as regras com suas taxas de correspondência, correspondências recentes e status. No painel, você pode:

* Ver as tendências da taxa de correspondência das regras ao longo do tempo
* Inspecionar as correspondências recentes com links para as gravações correspondentes
* Ativar e desativar regras
* Duplicar regras para usá-las como modelos de novas variações
* Ver os logs de avaliação para depurar condições que correspondem de forma inesperada (ou deixam de corresponder)

> [!TIP]
>
> Se uma regra tiver uma taxa de correspondência alta (acima de 80%), a condição pode estar ampla demais. Se tiver uma taxa muito baixa (abaixo de 1%) em uma amostra significativa, a condição pode estar restrita demais ou apontando para o tópico/campo errado. Use os logs de avaliação para inspecionar correspondências individuais e quase-correspondências.

## Próximos passos

> [card]
>
> Alertas e notificaçõesEncaminhe notificações para Slack, e-mail e webhooks quando as regras forem disparadas.
>
> [Open](https://avala.ai/docs/pt/visualization/fleet/alerts-and-notifications.md)

> [card]
>
> Eventos e marcadoresEntenda os eventos de linha do tempo que as regras podem criar automaticamente.
>
> [Open](https://avala.ai/docs/pt/visualization/fleet/events-and-markers.md)

> [card]
>
> Painel da frotaGerencie dispositivos, gravações e métricas da frota a partir do painel central.
>
> [Open](https://avala.ai/docs/pt/visualization/fleet/fleet-dashboard.md)

> [card]
>
> Exploração de dadosExplore os dados de gravação de forma interativa antes de definir regras.
>
> [Open](https://avala.ai/docs/pt/visualization/guides/data-exploration.md)
