commit 826b723223beb1c9b5d80d16b5c61b069f2a6d30 Author: Guardian Date: Mon Mar 2 02:04:42 2026 +0000 Initial release: curated skill collection framework + openclaw-guardian as first skill diff --git a/.github/ISSUE_TEMPLATE/submit-skill.md b/.github/ISSUE_TEMPLATE/submit-skill.md new file mode 100644 index 00000000..59200fc0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/submit-skill.md @@ -0,0 +1,31 @@ +--- +name: Submit a Skill +about: Submit an OpenClaw skill for inclusion in the master collection +title: "[SKILL] " +labels: skill-submission +assignees: '' +--- + +## Skill Info + +**Name:** +**Description:** +**Category:** + +## Source + +- [ ] This is my own skill +- [ ] This is a skill I found and recommend + +**Link:** + +## Checklist + +- [ ] Has a valid `SKILL.md` with `name` and `description` frontmatter +- [ ] No hardcoded API keys or personal credentials +- [ ] Tested on a standard OpenClaw setup +- [ ] Clear and useful purpose + +## Notes + + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..a098437b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +All notable changes to the OpenClaw Master Skills collection are documented here. +Updated every Monday. + +--- + +## [Week 1] — 2026-03-02 + +### 🎉 Initial Release + +**New Skills Added:** + +| Skill | Description | Source | +|---|---|---| +| `openclaw-guardian` | 🛡️ Gateway watchdog with auto-repair, git rollback, and Discord alerts | [LeoYeAI/openclaw-guardian](https://github.com/LeoYeAI/openclaw-guardian) | + +--- + +*Next update: 2026-03-09* diff --git a/README.md b/README.md new file mode 100644 index 00000000..319d8206 --- /dev/null +++ b/README.md @@ -0,0 +1,160 @@ +# 🧠 OpenClaw Master Skills + +
+ + + Powered by MyClaw.ai + +Weekly Updates +Curated + +**A curated collection of the best OpenClaw skills from around the web.** +Reviewed, tested, and updated every week by the [MyClaw.ai](https://myclaw.ai) team. + +[Browse Skills](#-skill-index) · [Submit a Skill](#-submit-a-skill) · [Weekly Updates](#-weekly-updates) · [Install Guide](#-how-to-install) + +
+ +--- + +## 🤖 What is This? + +[OpenClaw](https://openclaw.ai) agents are powered by **Skills** — modular packages that teach your AI how to do specific tasks. This repo is the community's best collection, hand-curated from: + +- [ClaWHub](https://clawhub.ai) — the official skill registry +- GitHub repos tagged `openclaw-skill` +- Community submissions via Issues +- MyClaw.ai's internal production skill library + +Every skill in this collection has been **reviewed for quality, tested for correctness, and is kept up to date**. + +> 🌐 **Want a fully-managed AI agent?** Try [MyClaw.ai](https://myclaw.ai) + +--- + +## 📦 Skill Index + +| Skill | Description | Category | Source | Added | +|---|---|---|---|---| +| [openclaw-guardian](skills/openclaw-guardian/) | 🛡️ Gateway watchdog with auto-repair & git rollback | DevOps | [GitHub](https://github.com/LeoYeAI/openclaw-guardian) | 2026-03-02 | + +> More skills added every week. [Submit yours →](#-submit-a-skill) + +--- + +## 🚀 How to Install + +### Install a single skill + +```bash +# Via ClaWHub CLI +clawhub install + +# Or clone this repo and copy manually +git clone https://github.com/LeoYeAI/openclaw-master-skills.git +cp -r openclaw-master-skills/skills/ ~/.openclaw/workspace/skills/ +``` + +### Install all skills at once + +```bash +git clone https://github.com/LeoYeAI/openclaw-master-skills.git +cp -r openclaw-master-skills/skills/. ~/.openclaw/workspace/skills/ +``` + +### Stay up to date + +```bash +cd openclaw-master-skills +git pull +cp -r skills/. ~/.openclaw/workspace/skills/ +``` + +--- + +## 📬 Submit a Skill + +Have a skill you'd like to share? There are two ways: + +### Option 1: GitHub Issue (easiest) + +[Open a "Submit Skill" issue](../../issues/new?template=submit-skill.md) and fill in the template. We'll review and add it within a week. + +### Option 2: Pull Request + +1. Fork this repo +2. Add your skill folder under `skills//` +3. Make sure it has a valid `SKILL.md` with frontmatter +4. Open a PR with a brief description + +**Review criteria:** +- ✅ Valid `SKILL.md` with `name` and `description` +- ✅ Clear, useful purpose +- ✅ No hardcoded credentials or personal data +- ✅ Works on a standard OpenClaw setup + +--- + +## 📅 Weekly Updates + +We publish a weekly digest every **Monday** summarizing: +- New skills added +- Skills updated +- Community highlights + +See [CHANGELOG.md](CHANGELOG.md) for the full history. + +--- + +## 📁 Repo Structure + +``` +openclaw-master-skills/ +├── skills/ # ✅ Curated, ready-to-use skills +│ └── / +│ ├── SKILL.md +│ ├── scripts/ +│ └── references/ +├── pending/ # 🔍 Skills under review +├── scripts/ +│ └── collect.sh # Weekly collection & sync script +├── CHANGELOG.md # Weekly update log +└── README.md +``` + +--- + +## 🔍 How We Collect Skills + +Every week, our collection script: + +1. **Scans ClaWHub** for newly published/updated skills +2. **Scans GitHub** for repos tagged `openclaw-skill` +3. **Reviews community submissions** from Issues +4. **Tests and validates** each skill +5. **Merges approved skills** into `skills/` and publishes the weekly digest + +Want to automate collection for your own fork? See [scripts/collect.sh](scripts/collect.sh). + +--- + +## 🌟 Categories + +| Category | Description | +|---|---| +| `devops` | Deployment, monitoring, infrastructure | +| `productivity` | Calendar, email, task management | +| `coding` | Code generation, review, debugging | +| `data` | Database, analytics, data processing | +| `communication` | Messaging, notifications, social | +| `media` | Image, video, audio processing | +| `finance` | Budgeting, trading, accounting | +| `research` | Web search, summarization, knowledge | + +--- + +## License + +All skills retain their original licenses. This collection is MIT licensed. + +© [MyClaw.ai](https://myclaw.ai) — Making AI agents accessible to everyone. diff --git a/scripts/collect.sh b/scripts/collect.sh new file mode 100644 index 00000000..075a5dfc --- /dev/null +++ b/scripts/collect.sh @@ -0,0 +1,51 @@ +#!/bin/bash +# collect.sh - Weekly OpenClaw Master Skills collection script +# Scans ClaWHub + GitHub for new skills, outputs candidates for review + +SKILLS_DIR="$(dirname "$0")/../skills" +PENDING_DIR="$(dirname "$0")/../pending" +LOG_FILE="/tmp/openclaw-collect-$(date +%Y-%m-%d).log" + +log() { echo "[$(date '+%H:%M:%S')] $1" | tee -a "$LOG_FILE"; } + +log "=== OpenClaw Master Skills Weekly Collector ===" +log "Date: $(date '+%Y-%m-%d')" + +# ── 1. Scan ClaWHub for latest skills ──────────────────────────────────────── +log "Scanning ClaWHub..." +if command -v clawhub &>/dev/null; then + clawhub explore --limit 50 2>/dev/null | tee -a "$LOG_FILE" || log "ClaWHub explore failed" +else + log "clawhub CLI not installed, skipping" +fi + +# ── 2. Scan GitHub for repos tagged openclaw-skill ─────────────────────────── +log "Scanning GitHub (openclaw-skill topic)..." +GH_TOKEN="${GITHUB_TOKEN:-}" +if [ -n "$GH_TOKEN" ]; then + curl -s \ + -H "Authorization: token $GH_TOKEN" \ + "https://api.github.com/search/repositories?q=topic:openclaw-skill&sort=updated&per_page=20" \ + | python3 -c " +import sys, json +data = json.load(sys.stdin) +for r in data.get('items', []): + print(f\" {r['full_name']} — {r['description']} ({r['stargazers_count']} ⭐)\") +" 2>/dev/null | tee -a "$LOG_FILE" +else + log "GITHUB_TOKEN not set, skipping GitHub scan" +fi + +# ── 3. Validate existing skills ────────────────────────────────────────────── +log "Validating existing skills in collection..." +for skill_dir in "$SKILLS_DIR"/*/; do + skill_name=$(basename "$skill_dir") + if [ -f "$skill_dir/SKILL.md" ]; then + log " ✅ $skill_name — OK" + else + log " ❌ $skill_name — missing SKILL.md!" + fi +done + +log "=== Done. Review $LOG_FILE for candidates ===" +log "Add approved skills to $SKILLS_DIR/ and update CHANGELOG.md" diff --git a/skills/README.md b/skills/README.md new file mode 100644 index 00000000..72d927df --- /dev/null +++ b/skills/README.md @@ -0,0 +1,367 @@ +# 🛡️ OpenClaw Guardian + +
+ + + Powered by MyClaw.ai + + +**[English](#english) · [中文](#中文) · [Français](#français) · [Deutsch](#deutsch) · [Русский](#русский) · [日本語](#日本語) · [Italiano](#italiano) · [Español](#español)** + +
+ +--- + +## 🤖 Powered by [MyClaw.ai](https://myclaw.ai) + +**[MyClaw.ai](https://myclaw.ai)** is an AI personal assistant platform that gives every user a fully-featured AI agent running on a dedicated server — with complete code control, internet access, and tool integrations. Think of it as your own private AI that can actually *do* things, not just answer questions. + +OpenClaw Guardian is an open-source project born from MyClaw.ai's production infrastructure. We run thousands of AI agent instances 24/7, and Guardian is the hardening layer that keeps them alive. We're open-sourcing it so everyone can benefit. + +> 🌐 **Try MyClaw.ai**: [https://myclaw.ai](https://myclaw.ai) + +--- + + +## 🇬🇧 English + +> A standalone watchdog that keeps your [OpenClaw](https://openclaw.ai) Gateway alive 24/7 — with automatic repair, git-based rollback, and optional Discord alerts. + +### Features + +- **Auto-monitor** — checks Gateway health every 30 seconds +- **Auto-repair** — runs `openclaw doctor --fix` on failure (up to 3 attempts) +- **Auto-rollback** — resets workspace to last stable git commit if repair fails +- **Daily snapshots** — automatic daily `git commit` of your workspace +- **Discord alerts** — optional webhook notifications on failures and recovery + +### How It Works + +``` +Gateway down detected + │ + ▼ + doctor --fix ──→ success? ──→ ✅ Done + (up to 3x) + │ all failed + ▼ + git rollback ──→ success? ──→ ✅ Done + │ failed + ▼ + cooldown 300s → resume monitoring +``` + +### Quick Start + +```bash +# 1. Initialize git in workspace +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. Install +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. Start +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### Configuration + +| Variable | Default | Description | +|---|---|---| +| `GUARDIAN_WORKSPACE` | `$HOME/.openclaw/workspace` | Workspace git repo path | +| `GUARDIAN_CHECK_INTERVAL` | `30` | Health check interval (seconds) | +| `GUARDIAN_MAX_REPAIR` | `3` | Max repair attempts before rollback | +| `GUARDIAN_COOLDOWN` | `300` | Cooldown after all repairs fail (seconds) | +| `DISCORD_WEBHOOK_URL` | _(unset)_ | Discord webhook for alerts (optional) | + +### Install as OpenClaw Skill + +```bash +clawhub install openclaw-guardian +``` + +--- + + +## 🇨🇳 中文 + +> 一个独立运行的守护进程,确保你的 [OpenClaw](https://openclaw.ai) Gateway 全天候稳定运行 —— 支持自动修复、基于 git 的回滚,以及可选的 Discord 告警通知。 + +### 功能特性 + +- **自动监控** — 每 30 秒检测 Gateway 状态 +- **自动修复** — 异常时执行 `openclaw doctor --fix`(最多 3 次) +- **自动回滚** — 修复失败后自动回滚到上一个稳定的 git commit +- **每日快照** — 每天自动对 workspace 创建 git 备份 +- **Discord 告警** — 可选的故障与恢复 Webhook 通知 + +### 工作流程 + +``` +检测到 Gateway 停止运行 + │ + ▼ + doctor --fix ──→ 成功? ──→ ✅ 完成 + (最多 3 次) + │ 全部失败 + ▼ + git 回滚 ──→ 成功? ──→ ✅ 完成 + │ 失败 + ▼ + 冷却 300s → 继续监控 +``` + +### 快速开始 + +```bash +# 1. 初始化 workspace git 仓库 +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. 安装 +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. 启动 +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### 配置项 + +| 环境变量 | 默认值 | 说明 | +|---|---|---| +| `GUARDIAN_WORKSPACE` | `$HOME/.openclaw/workspace` | workspace git 仓库路径 | +| `GUARDIAN_CHECK_INTERVAL` | `30` | 检测间隔(秒) | +| `GUARDIAN_MAX_REPAIR` | `3` | 最大修复次数 | +| `GUARDIAN_COOLDOWN` | `300` | 全部失败后冷却时长(秒) | +| `DISCORD_WEBHOOK_URL` | _(未设置)_ | Discord 告警 Webhook(可选) | + +### 作为 OpenClaw Skill 安装 + +```bash +clawhub install openclaw-guardian +``` + +--- + + +## 🇫🇷 Français + +> Un processus de surveillance autonome qui maintient votre passerelle [OpenClaw](https://openclaw.ai) opérationnelle 24h/24 — avec réparation automatique, retour arrière Git et alertes Discord optionnelles. + +### Fonctionnalités + +- **Surveillance automatique** — vérifie l'état de la passerelle toutes les 30 secondes +- **Réparation automatique** — exécute `openclaw doctor --fix` en cas de panne (jusqu'à 3 tentatives) +- **Retour arrière automatique** — réinitialise le workspace au dernier commit Git stable si la réparation échoue +- **Instantanés quotidiens** — sauvegarde Git automatique quotidienne du workspace +- **Alertes Discord** — notifications webhook optionnelles en cas de panne ou de rétablissement + +### Démarrage rapide + +```bash +# 1. Initialiser le dépôt Git +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. Installer +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. Démarrer +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### Installer en tant que Skill OpenClaw + +```bash +clawhub install openclaw-guardian +``` + +--- + + +## 🇩🇪 Deutsch + +> Ein eigenständiger Watchdog-Prozess, der Ihr [OpenClaw](https://openclaw.ai) Gateway rund um die Uhr am Laufen hält — mit automatischer Reparatur, Git-basiertem Rollback und optionalen Discord-Benachrichtigungen. + +### Funktionen + +- **Automatische Überwachung** — prüft den Gateway-Status alle 30 Sekunden +- **Automatische Reparatur** — führt `openclaw doctor --fix` bei Ausfall aus (bis zu 3 Versuche) +- **Automatischer Rollback** — setzt den Workspace auf den letzten stabilen Git-Commit zurück, wenn die Reparatur fehlschlägt +- **Tägliche Snapshots** — automatisches tägliches Git-Backup des Workspaces +- **Discord-Benachrichtigungen** — optionale Webhook-Benachrichtigungen bei Ausfällen und Wiederherstellungen + +### Schnellstart + +```bash +# 1. Git-Repository initialisieren +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. Installieren +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. Starten +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### Als OpenClaw Skill installieren + +```bash +clawhub install openclaw-guardian +``` + +--- + + +## 🇷🇺 Русский + +> Автономный сторожевой процесс, обеспечивающий круглосуточную работу вашего шлюза [OpenClaw](https://openclaw.ai) — с автоматическим восстановлением, откатом на основе Git и опциональными уведомлениями в Discord. + +### Возможности + +- **Автоматический мониторинг** — проверяет состояние шлюза каждые 30 секунд +- **Автоматическое восстановление** — запускает `openclaw doctor --fix` при сбое (до 3 попыток) +- **Автоматический откат** — сбрасывает рабочую область до последнего стабильного коммита Git при неудаче восстановления +- **Ежедневные снимки** — автоматическое ежедневное резервное копирование рабочей области через Git +- **Уведомления Discord** — опциональные webhook-уведомления о сбоях и восстановлении + +### Быстрый старт + +```bash +# 1. Инициализация Git-репозитория +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. Установка +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. Запуск +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### Установить как OpenClaw Skill + +```bash +clawhub install openclaw-guardian +``` + +--- + + +## 🇯🇵 日本語 + +> [OpenClaw](https://openclaw.ai) ゲートウェイを24時間365日稼働させる自律型ウォッチドッグプロセス — 自動修復、Gitベースのロールバック、オプションのDiscordアラート機能付き。 + +### 機能 + +- **自動監視** — 30秒ごとにゲートウェイの状態を確認 +- **自動修復** — 障害時に `openclaw doctor --fix` を実行(最大3回) +- **自動ロールバック** — 修復失敗時に最後の安定したGitコミットにリセット +- **日次スナップショット** — ワークスペースの自動日次Gitバックアップ +- **Discordアラート** — 障害・復旧時のオプションWebhook通知 + +### クイックスタート + +```bash +# 1. Gitリポジトリの初期化 +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. インストール +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. 起動 +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### OpenClaw Skillとしてインストール + +```bash +clawhub install openclaw-guardian +``` + +--- + + +## 🇮🇹 Italiano + +> Un processo watchdog autonomo che mantiene il tuo gateway [OpenClaw](https://openclaw.ai) operativo 24 ore su 24 — con riparazione automatica, rollback basato su Git e avvisi Discord opzionali. + +### Funzionalità + +- **Monitoraggio automatico** — controlla lo stato del gateway ogni 30 secondi +- **Riparazione automatica** — esegue `openclaw doctor --fix` in caso di guasto (fino a 3 tentativi) +- **Rollback automatico** — ripristina il workspace all'ultimo commit Git stabile se la riparazione fallisce +- **Snapshot giornalieri** — backup Git automatico giornaliero del workspace +- **Avvisi Discord** — notifiche webhook opzionali per guasti e ripristini + +### Avvio rapido + +```bash +# 1. Inizializza il repository Git +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. Installa +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. Avvia +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### Installa come OpenClaw Skill + +```bash +clawhub install openclaw-guardian +``` + +--- + + +## 🇪🇸 Español + +> Un proceso watchdog autónomo que mantiene tu gateway de [OpenClaw](https://openclaw.ai) funcionando las 24 horas del día — con reparación automática, reversión basada en Git y alertas opcionales de Discord. + +### Características + +- **Monitoreo automático** — comprueba el estado del gateway cada 30 segundos +- **Reparación automática** — ejecuta `openclaw doctor --fix` en caso de fallo (hasta 3 intentos) +- **Reversión automática** — restaura el workspace al último commit Git estable si la reparación falla +- **Instantáneas diarias** — copia de seguridad Git automática diaria del workspace +- **Alertas de Discord** — notificaciones webhook opcionales para fallos y recuperaciones + +### Inicio rápido + +```bash +# 1. Inicializar repositorio Git +cd ~/.openclaw/workspace +git init && git add -A && git commit -m "initial" + +# 2. Instalar +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh + +# 3. Iniciar +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### Instalar como OpenClaw Skill + +```bash +clawhub install openclaw-guardian +``` + +--- + +## License + +MIT © [LeoYeAI](https://github.com/LeoYeAI) diff --git a/skills/SKILL.md b/skills/SKILL.md new file mode 100644 index 00000000..4390e90c --- /dev/null +++ b/skills/SKILL.md @@ -0,0 +1,80 @@ +--- +name: openclaw-guardian +description: Deploy and manage a Guardian watchdog process for OpenClaw Gateway. Provides automated health monitoring, self-repair via `doctor --fix`, git-based workspace rollback, daily snapshots, and optional Discord alerting. Use when a user wants to harden their OpenClaw instance against crashes, config corruption, or bad workspace edits — or when setting up Guardian for the first time on a new server/container. +--- + +# OpenClaw Guardian + +Guardian is a standalone bash watchdog that keeps OpenClaw Gateway alive 24/7. + +**Repair ladder:** +1. Detect Gateway down (every 30s) +2. Run `openclaw doctor --fix` (up to 3 attempts) +3. If still down → `git reset --hard` to last stable commit, restart Gateway +4. If all fails → cooldown 300s, resume monitoring +5. Daily automatic git snapshot of workspace + +## Setup Steps + +### 1. Initialize git (required for rollback) + +```bash +cd ~/.openclaw/workspace +git config --global user.email "guardian@example.com" +git config --global user.name "Guardian" +git init && git add -A && git commit -m "initial" +``` + +Skip if repo already exists. Without git, doctor --fix still works; rollback is skipped. + +### 2. Install guardian.sh + +Copy `scripts/guardian.sh` from this skill to `~/.openclaw/guardian.sh`: + +```bash +cp scripts/guardian.sh ~/.openclaw/guardian.sh +chmod +x ~/.openclaw/guardian.sh +``` + +### 3. Start Guardian + +**Container / no systemd (nohup):** +```bash +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +**Linux VPS with systemd:** See `references/setup.md` → Pattern B. + +### 4. Auto-start on container restart + +Add to `~/.openclaw/start-gateway.sh` (before the final `exec` line): +```bash +pkill -f "guardian.sh" 2>/dev/null || true +nohup /home/ubuntu/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### 5. Optional: Discord alerts + +```bash +export DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/..." +``` + +Or add to `start-gateway.sh` as a persistent export. + +## Verify + +```bash +pgrep -a -f "guardian.sh" # confirm process running +tail -f /tmp/openclaw-guardian.log # watch live logs +``` + +## Configuration + +All settings via environment variables. Defaults work out of the box. +See `references/setup.md` for full variable reference, systemd config, and architecture diagram. + +## Notes + +- Guardian coexists with `gw-watchdog.sh` — run both for layered resilience +- Rollback targets the 2nd-newest non-auto commit (skips daily-backup, rollback, auto-backup commits) +- Log path: `/tmp/openclaw-guardian.log` diff --git a/skills/references/setup.md b/skills/references/setup.md new file mode 100644 index 00000000..1887e42d --- /dev/null +++ b/skills/references/setup.md @@ -0,0 +1,116 @@ +# OpenClaw Guardian - Setup & Configuration Reference + +## Environment Variables + +All variables are optional with sensible defaults: + +| Variable | Default | Description | +|---|---|---| +| `GUARDIAN_WORKSPACE` | `$HOME/.openclaw/workspace` | Path to workspace git repo | +| `GUARDIAN_LOG` | `/tmp/openclaw-guardian.log` | Log file path | +| `GUARDIAN_CHECK_INTERVAL` | `30` | Health check interval in seconds | +| `GUARDIAN_MAX_REPAIR` | `3` | Max doctor --fix attempts before rollback | +| `GUARDIAN_COOLDOWN` | `300` | Cooldown period (seconds) after all repairs fail | +| `DISCORD_WEBHOOK_URL` | _(unset)_ | Discord webhook URL for alerts (optional) | +| `OPENCLAW_CMD` | `openclaw` | OpenClaw CLI command | + +## Deployment Patterns + +### Pattern A: nohup (container / no systemd) +Used when systemd user sessions are unavailable (e.g., Docker containers). + +```bash +nohup ~/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +Integrate into `start-gateway.sh` so it auto-starts on container restart: +```bash +pkill -f "guardian.sh" 2>/dev/null || true +nohup /home/ubuntu/.openclaw/guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & +``` + +### Pattern B: systemd user service (Linux desktop / VPS) + +Create `~/.config/systemd/user/openclaw-guardian.service`: +```ini +[Unit] +Description=OpenClaw Guardian + +[Service] +ExecStart=/path/to/guardian.sh +Restart=always + +[Install] +WantedBy=default.target +``` + +Enable: +```bash +systemctl --user daemon-reload +systemctl --user enable --now openclaw-guardian.service +``` + +## Git Initialization (Required for Rollback) + +Guardian's rollback feature requires a git repo in the workspace: + +```bash +cd ~/.openclaw/workspace +git config --global user.email "guardian@example.com" +git config --global user.name "Guardian" +git init && git add -A && git commit -m "initial" +``` + +Without git, Guardian still monitors and runs `doctor --fix` — rollback is simply skipped. + +## How Repair Works + +``` +Gateway down detected + │ + ▼ + doctor --fix ──→ success? ──→ Done ✅ + (up to N times) + │ all failed + ▼ + git rollback ──→ success? ──→ Done ✅ + │ failed + ▼ + cooldown period + │ + ▼ + resume monitoring +``` + +## Daily Backup + +Guardian creates a daily git snapshot automatically: +- Commit message: `daily-backup: auto snapshot YYYY-MM-DD` +- Tracked in `/tmp/guardian-last-backup` +- These commits are excluded from rollback targets + +## Coexistence with gw-watchdog + +Guardian is designed to complement, not replace, `gw-watchdog.sh`: + +| | gw-watchdog | guardian | +|---|---|---| +| Check interval | 15s | 30s | +| Action | Fast restart | doctor --fix → rollback | +| Git rollback | No | Yes | +| Discord alerts | No | Yes | +| Daily backup | No | Yes | + +Run both for layered resilience. + +## Viewing Logs + +```bash +tail -f /tmp/openclaw-guardian.log +``` + +## Checking Status + +```bash +pgrep -a -f "guardian.sh" +``` diff --git a/skills/scripts/guardian.sh b/skills/scripts/guardian.sh new file mode 100755 index 00000000..817ad591 --- /dev/null +++ b/skills/scripts/guardian.sh @@ -0,0 +1,149 @@ +#!/bin/bash +# guardian.sh - OpenClaw Guardian 守护进程 +# 功能:监控 Gateway → doctor --fix → git 回滚 → Discord 通知 +# 用法:chmod +x guardian.sh && nohup ./guardian.sh >> /tmp/openclaw-guardian.log 2>&1 & + +WORKSPACE="${GUARDIAN_WORKSPACE:-$HOME/.openclaw/workspace}" +LOG_FILE="${GUARDIAN_LOG:-/tmp/openclaw-guardian.log}" +CHECK_INTERVAL="${GUARDIAN_CHECK_INTERVAL:-30}" # 检测间隔(秒) +MAX_REPAIR_ATTEMPTS="${GUARDIAN_MAX_REPAIR:-3}" # 连续修复最大次数 +COOLDOWN_PERIOD="${GUARDIAN_COOLDOWN:-300}" # 失败后冷却期(秒) +OPENCLAW_CMD="${OPENCLAW_CMD:-openclaw}" +DISCORD_WEBHOOK="${DISCORD_WEBHOOK_URL:-}" # 可选,设置环境变量启用通知 + +log() { + echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE" +} + +# 发送 Discord 通知(可选) +notify() { + local msg="$1" + if [ -n "$DISCORD_WEBHOOK" ]; then + curl -s -X POST "$DISCORD_WEBHOOK" \ + -H "Content-Type: application/json" \ + -d "{\"content\": \"🚨 **OpenClaw Guardian**: $msg\"}" \ + >/dev/null 2>&1 || true + fi + log "[NOTIFY] $msg" +} + +# 检查 Gateway 是否运行 +is_gateway_running() { + if pgrep -f "openclaw-gateway" >/dev/null 2>&1; then + return 0 + fi + return 1 +} + +# 获取上一个稳定版本的 commit(排除自动提交) +get_stable_commit() { + git -C "$WORKSPACE" log --all --oneline -50 2>/dev/null | \ + grep -v -E "rollback|daily-backup|auto-backup|guardian-auto" | \ + sed -n '2p' | awk '{print $1}' +} + +# 尝试 doctor --fix 修复 +try_doctor_fix() { + log "尝试 doctor --fix 修复..." + $OPENCLAW_CMD doctor --fix >> "$LOG_FILE" 2>&1 + sleep 10 + if is_gateway_running; then + log "doctor --fix 修复成功,Gateway 已恢复" + return 0 + fi + return 1 +} + +# 执行 git 回滚 +do_rollback() { + log "开始执行 git 回滚..." + local CURRENT_COMMIT + CURRENT_COMMIT=$(git -C "$WORKSPACE" rev-parse HEAD 2>/dev/null) + local STABLE_COMMIT + STABLE_COMMIT=$(get_stable_commit) + + if [ -z "$STABLE_COMMIT" ]; then + log "❌ 无法找到稳定版本,跳过回滚" + return 1 + fi + + log "回滚目标: $STABLE_COMMIT (当前: $CURRENT_COMMIT)" + git -C "$WORKSPACE" reset --hard "$STABLE_COMMIT" >> "$LOG_FILE" 2>&1 + git -C "$WORKSPACE" commit --allow-empty \ + -m "rollback: guardian auto rollback from $CURRENT_COMMIT to $STABLE_COMMIT at $(date '+%Y-%m-%d %H:%M:%S')" \ + >> "$LOG_FILE" 2>&1 + + # 重启 Gateway + pkill -f "openclaw-gateway" 2>/dev/null || true + sleep 3 + nohup $OPENCLAW_CMD gateway >> "$LOG_FILE" 2>&1 & + sleep 15 + + if is_gateway_running; then + log "✅ 回滚成功,Gateway 已恢复" + notify "回滚成功!从 $CURRENT_COMMIT 回滚到 $STABLE_COMMIT" + return 0 + else + log "❌ 回滚后 Gateway 仍未启动" + return 1 + fi +} + +# 每日自动备份(创建 git 快照) +daily_backup() { + local today + today=$(date '+%Y-%m-%d') + local last_backup_file="/tmp/guardian-last-backup" + local last_backup="" + [ -f "$last_backup_file" ] && last_backup=$(cat "$last_backup_file") + + if [ "$last_backup" != "$today" ]; then + cd "$WORKSPACE" && git add -A && \ + git commit -m "daily-backup: auto snapshot $today" >> "$LOG_FILE" 2>&1 || true + echo "$today" > "$last_backup_file" + log "📦 每日备份完成: $today" + fi +} + +# 主修复流程 +repair_gateway() { + local attempt=0 + notify "Gateway 异常,开始修复流程..." + + # 第一步:doctor --fix + while [ $attempt -lt $MAX_REPAIR_ATTEMPTS ]; do + attempt=$((attempt + 1)) + log "修复尝试 $attempt/$MAX_REPAIR_ATTEMPTS" + if try_doctor_fix; then + notify "✅ doctor --fix 修复成功(第 $attempt 次尝试)" + return 0 + fi + sleep 10 + done + + # 第二步:git 回滚 + log "doctor --fix 失败,尝试 git 回滚..." + notify "doctor --fix 失败,尝试 git 回滚..." + if do_rollback; then + return 0 + fi + + # 最终:冷却 + notify "❌ 所有修复手段均失败,冷却 ${COOLDOWN_PERIOD}s 后继续监控" + log "进入冷却期 ${COOLDOWN_PERIOD}s" + sleep "$COOLDOWN_PERIOD" +} + +# ===== 主循环 ===== +log "🚀 Guardian 守护进程启动 (check=${CHECK_INTERVAL}s, max_repair=${MAX_REPAIR_ATTEMPTS})" +notify "Guardian 守护进程已启动" + +while true; do + daily_backup + + if ! is_gateway_running; then + repair_gateway + fi + + sleep "$CHECK_INTERVAL" +done