
# 自动化

Rudel 的自动化可防止临时沙盒不断累积。每小时触发一次的 WP-Cron 事件 `rudel_scheduled_cleanup` 可用于：

- 执行清理策略（过期时间、使用时长和空闲时长）
- 清理已合并分支
- 报告已过期或即将过期的沙盒

## 配置

自动化会从 `rudel_config` 选项中读取这些键。完整列表见 [配置](https://rudel.inline0.dev/zh/docs/configuration)。

| 键 | 用途 | 默认值 |
|-----|---------|---------|
| `auto_cleanup_enabled` | 每次事件运行清理策略 | `1` |
| `auto_cleanup_merged` | 同时移除分支已合并的沙盒 Git 工作树 | `0` |
| `expiring_environment_notice_days` | 报告 N 天内即将过期的沙盒 | `0` |
| `max_age_days` | 清理策略使用的使用时长上限 | `0` |
| `max_idle_days` | 清理策略使用的空闲时长上限 | `0` |
| `default_ttl_days` | 新沙盒的过期时间 | `0` |

使用默认值时，事件虽已安排，但只会移除明确设置了过期时间且已过期的沙盒，因为未设置使用时长或空闲时长上限，也未设置默认 TTL。

## WP-Cron

启用时会安排该事件，每个请求也会重新检查安排状态：只要 `auto_cleanup_enabled`、`auto_cleanup_merged` 或 `expiring_environment_notice_days` 任一值非零，事件就会存在；否则会被移除。停用时会移除该事件。

没有自动化命令。请在 `rudel_config` 中更改设置：

```bash
wp option update rudel_config '{"auto_cleanup_enabled":1,"max_idle_days":7,"expiring_environment_notice_days":2}' --format=json
wp rudel status
```

`wp rudel status` 会显示 `Auto cleanup`、`Auto cleanup merged`、`Expiry notice days` 和 `Automation scheduled`。

## 过期报告

设置 `expiring_environment_notice_days` 后，每次运行都会收集 `expires_at` 在相应天数内到期的沙盒，并将其传递给 `rudel_after_automation_expiring_environments` 操作，分为 `expiring` 和 `expired`。Rudel 本身不会发送通知；请将该操作挂接到通知所有者的逻辑。

```php
add_action(
    'rudel_after_automation_expiring_environments',
    function ( array $report ): void {
        foreach ( $report['expiring'] as $sandbox ) {
            error_log( $sandbox['id'] . ' expires at ' . $sandbox['expires_at'] );
        }
    }
);
```

## 立即运行

使用手动清理进行可预测的本地或 CI 运行：

```bash
wp rudel cleanup --dry-run
wp rudel cleanup
```

在 PHP 中，`Rudel::run_automation()` 会执行与 cron 事件相同的任务。
