# Automation

Automation lets a plugin act without a foreground user action: auto-replies,
moderation, scheduled messages and chat-admin workflows. It is a critical capability,
off at install, and gated by the global **Allow automation** switch.

## 1. Permission and toggles

A package declares `messages.automation` and `minHost`. The user grants the permission,
then enables the per-plugin automation toggle. Both the global switch and the per-plugin
toggle must be on. `messages.automation` never substitutes for the permission of the
action being executed: sending still needs `messages.send`, deleting needs
`messages.modify`, reactions need `messages.react`, admin actions need `chats.admin`,
and notifications need `notifications.manage`.

A rule with a destructive action (`DELETE_FOR_ALL`, ban, kick, promote, demote, clear
history, delete chat) requires a one-time confirmation that names the action group. The
manager can revoke it. The manual "Do not ask again" choice does not carry over to
automation.

## 2. Rule shape

```java
AutomationRule rule = AutomationRule.builder()
        .id("welcome")
        .enabled(true)
        .trigger(RuleTrigger.builder()
                .type(TriggerType.MEMBER_JOINED)
                .dialogIds(new long[]{dialogId})
                .build())
        .filter(RuleFilter.builder()
                .dialogTypes(new DialogType[]{DialogType.GROUP})
                .build())
        .actions(Arrays.asList(RuleAction.builder()
                .type(ActionType.SEND_TEXT)
                .text("Welcome!")
                .build()))
        .limits(RuleLimits.builder()
                .maxRunsPerMinute(5)
                .stopOnError(false)
                .build())
        .build();
context.automation().addRule(rule);
```

| Part | Values |
| --- | --- |
| Trigger | `MESSAGE_RECEIVED`, `MESSAGE_SENT`, `MESSAGE_EDITED`, `MESSAGE_DELETED`, `MEMBER_JOINED`, `MEMBER_LEFT`, `MEMBER_BANNED`, `SCHEDULE`, `MANUAL` |
| Filter | account ids, dialog ids, dialog types, sender ids, message kinds, outgoing flag, condition tree |
| Condition | `ALL`, `ANY`, `NOT`, `EQUALS`, `PREFIX`, `CONTAINS`, `WILDCARD` |
| Action | `SEND_TEXT`, `SEND_MEDIA`, `DELETE`, `DELETE_FOR_ALL`, `FORWARD`, `REACT`, `NOTIFY`, `CALL_HANDLER` |

There is no regex engine. `WILDCARD` supports `*` and `?`, a pattern length of 256 and a
bounded match budget, so catastrophic backtracking is impossible.

`CALL_HANDLER` invokes the TypeScript handler or Java method with a bounded snapshot and
a 2 s budget. It returns a list of actions or `null`. Actions run serially per rule; a
failure is logged and the next action runs unless `stopOnError` is set.

## 3. Schedule rules

Interval rules have a 60 s minimum. Wall-clock times use the device time zone and fire
once at the local time across a DST change. A run missed while the process was dead is
not replayed. Automation runs only while the app process is alive in v1; WorkManager is
a separate future task.

## 4. Safety

- Secret chats, protected surfaces and disabled accounts never match. A match is
  skipped and audited without message text.
- Global limits: 20 sends/min and 500 sends/day; 60 deletes/min and 2,000 deletes/day
  per plugin and account. A rule can lower a limit, never raise it.
- A flood-wait pauses the rule for the server-provided duration. The host never spins.
- `runRule` obeys the same gates: it fails with `E_AUTOMATION_DISABLED` when the global
  switch is off, `E_PERMISSION` when the per-plugin toggle is off, still applies rate
  limits and still skips secret chats.
- The manager shows rule count, last run, next run, rate-limit status, the last 100 audit
  entries and a kernel-owned automation switch.

## 5. Audit

An audit entry records the rule id, action count, error code, account, dialog id, target
id, message ids, timestamp and result. It never records message text, phone numbers,
auth keys or secret-chat data.

## 6. API

```java
Registration addRule(AutomationRule rule);
List<RuleStatus> rules();
void setRuleEnabled(String ruleId, boolean enabled);
void removeRule(String ruleId);
CompletableFuture<RuleRunResult> runRule(String ruleId);
```

Rules are stored per plugin, survive a restart, and stay inert while disabled.
