Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(daemon): fires-watcher + push notification sinks (Telegram/Discord/ntfy/Pushover) (#21)
Aurora Capitalca18de8b05af
diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.jsonindex 56d645bd..b46d5d3b 100644--- a/claude-ops/.claude-plugin/plugin.json+++ b/claude-ops/.claude-plugin/plugin.json@@ -224,6 +224,34 @@"type": "string","sensitive": false,"default": ""+ },+ "telegram_notify_chat_id": {+ "title": "Telegram Notification Chat ID",+ "description": "Chat ID to receive fire alerts. Defaults to telegram_phone's DM if unset.",+ "type": "string",+ "sensitive": false,+ "default": ""+ },+ "ntfy_topic": {+ "title": "ntfy.sh Topic",+ "description": "Topic name (e.g., claude-ops-fires-<random>) for ntfy.sh pushes. Free, no account required.",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "pushover_user_key": {+ "title": "Pushover User Key",+ "description": "From https://pushover.net/ — paired with pushover_app_token.",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "pushover_app_token": {+ "title": "Pushover App Token",+ "description": "App-specific token from https://pushover.net/apps/build",+ "type": "string",+ "sensitive": true,+ "default": ""}}}diff --git a/claude-ops/docs/notifications.md b/claude-ops/docs/notifications.mdnew file mode 100644index 00000000..2ca474f3--- /dev/null+++ b/claude-ops/docs/notifications.md@@ -0,0 +1,151 @@+# Push Notifications (`fires-watcher`)++`claude-ops` ships a background service called `fires-watcher` that replaces+the old polling workflow of `/ops:fires`. Instead of you having to remember to+ask for fires, the daemon polls your fire sources every 60 seconds and pushes+a notification the moment a new CRITICAL or HIGH incident appears.++> Related issue: [#21 — push notifications for P0s](https://github.com/Lifecycle-Innovations-Limited/claude-ops/issues/21).++## What `fires-watcher` does++Every 60 seconds (configurable via `FIRES_WATCHER_INTERVAL`), the watcher:++1. Runs `bin/ops-infra` and inspects ECS cluster health. A cluster in+ `degraded` state produces a **HIGH** event; a cluster that is fully+ `down` produces a **CRITICAL** event.+2. Queries the Sentry API (`organizations/<org>/issues/?query=is:unresolved`)+ for unresolved issues at `level=error` (**HIGH**) or `level=fatal`+ (**CRITICAL**) — only when `$SENTRY_AUTH_TOKEN` and `sentry_org` are both+ configured.+3. Diffs the result against the previous state file at+ `~/.claude/plugins/data/ops-ops-marketplace/fires-watcher.state.json`.+4. For every new or escalated incident, calls+ `scripts/ops-notify.sh <severity> <title> <body> [--link <url>]`, which+ fans out to every configured sink.+5. Updates a health file at+ `~/.claude/plugins/data/ops-ops-marketplace/fires-watcher.health` so the+ main daemon can monitor it.++The watcher is **read-only** — it never mutates infrastructure (Rule 5).++## The six sink options++`ops-notify.sh` tries sinks in this order and fans out to **all** that are+configured (there is no "pick one" — you get alerts everywhere you want them):++| Priority | Sink | Trigger env / pref |+| -------- | ----------------- | ----------------------------------------------------------------------------------- |+| 1 | Telegram bot | `$TELEGRAM_BOT_TOKEN` + `$TELEGRAM_NOTIFY_CHAT_ID` (falls back to `$TELEGRAM_OWNER_ID`) |+| 2 | Discord webhook | `$DISCORD_WEBHOOK_URL` (shared with `/ops:comms discord send`) |+| 3 | ntfy.sh | `$NTFY_TOPIC` (optionally `$NTFY_SERVER` for a self-hosted instance) |+| 4 | Pushover | `$PUSHOVER_USER` + `$PUSHOVER_TOKEN` |+| 5 | macOS `osascript` | Local desktop notification (macOS only — guarded behind a Darwin check) |+| 6 | stderr log | Always runs if nothing else is configured — written to `logs/ops-notify.log` |++Every env var above also has a `$PREFS_PATH` fallback (the dispatch script+reads `~/.claude/plugins/data/ops-ops-marketplace/preferences.json` when the+env var isn't set), so you don't have to export secrets globally.++### Severity-to-emoji mapping++| Severity | Emoji | Notes |+| -------- | ----- | -------------------------------------- |+| CRITICAL | 🔴 | Pushover priority `1`, ntfy priority `5` |+| HIGH | 🟠 | Pushover priority `1`, ntfy priority `4` |+| MEDIUM | 🟡 | Pushover priority `0`, ntfy priority `3` |+| LOW | 🟢 | Pushover priority `-1`, ntfy priority `2` |++## How to choose a sink++- **Most users →** Telegram. You already set up a Telegram bot to use+ `/ops:comms`, so this is zero extra work.+- **No account, free →** ntfy.sh. Pick a random topic name like+ `claude-ops-fires-<random>`, subscribe from the ntfy mobile app, done.+- **Premium iOS/Android →** Pushover. ~$5 one-time per platform, fastest and+ most reliable delivery with priority bypass for CRITICAL.+- **Team channel →** Discord webhook. Drops the alert into an existing+ `#incidents` channel where your team already lives.+- **Desktop only →** macOS `osascript`. Silent fallback; fine for a dev+ laptop but don't rely on it as your only sink.++Configure multiple — if your laptop is offline, a Pushover push still reaches+you; if Telegram's API is flaky, Discord still works.++## Debounce rules++To avoid waking you up every minute about the same fire:++- **New incident** — notify immediately, record fingerprint + severity ++ timestamp.+- **Same fingerprint, same severity** — suppress for **30 minutes** from the+ last notification. Override with `FIRES_WATCHER_DEBOUNCE` (seconds).+- **Same fingerprint, higher severity** — re-notify immediately (e.g., ECS+ cluster went from `degraded` → `down`). The stored severity is bumped so+ the next HIGH event doesn't re-trigger until the 30-minute window elapses.+- **Incident resolves** — the fingerprint simply stops appearing in the probe+ output; no "all clear" ping is sent (noise vs signal tradeoff).++Fingerprints are stable across ticks:+- Infra: `infra:<cluster>:<status>`+- Sentry: `sentry:<issue_id>`++State lives at `~/.claude/plugins/data/ops-ops-marketplace/fires-watcher.state.json`+and survives daemon restarts.++## Testing your setup++Send a test event through every configured sink:++```bash+scripts/ops-notify.sh CRITICAL "test" "is this thing on"+```++You should see a red-dot alert on every sink you've wired up. Check+`logs/ops-notify.log` under your data dir for a per-sink status line.++To verify the watcher loop, run it in the foreground for 2-3 ticks:++```bash+FIRES_WATCHER_INTERVAL=10 scripts/ops-fires-watcher.sh+```++Tail the log with `tail -f ~/.claude/plugins/data/ops-ops-marketplace/logs/fires-watcher.log`.++## Enabling / disabling the watcher++`fires-watcher` is **disabled by default**. Opt in either way:++1. **Guided:** `/ops:setup notifications` — walks you through sink selection+ and enables the service.+2. **Manual:** edit+ `~/.claude/plugins/data/ops-ops-marketplace/daemon-services.json` and flip+ `services.fires-watcher.enabled` to `true`, then restart the daemon.++To disable it again without losing config:++- Run `/ops:setup notifications --skip`, **or**+- Flip `enabled` back to `false` in `daemon-services.json` and restart the+ daemon (`scripts/ops-daemon.sh restart`).++## Polling vs event-driven — tradeoffs++This design uses 60-second polling rather than webhooks. Rationale:++- Sentry + AWS both support webhooks, but receiving them would require the+ user to run (and expose) an HTTP listener — a hard ask for a CLI plugin+ that runs on random laptops behind NAT.+- 60 s worst-case latency is acceptable for CRITICAL P0s; most on-call+ rotations already tolerate ≥ 1 minute of alert lag.+- Polling works uniformly across any fire source (Sentry, AWS, Datadog, New+ Relic, custom CloudWatch) without per-source webhook handlers.+- If sub-minute latency becomes important later, the watcher can be swapped+ for a webhook listener without changing the notification surface —+ `ops-notify.sh` is the stable boundary.++## Files++- `scripts/ops-fires-watcher.sh` — the daemon poll loop+- `scripts/ops-notify.sh` — the sink dispatcher+- `scripts/daemon-services.default.json` — service registration+- `skills/setup/SKILL.md` §3m — guided setup flowdiff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.jsonindex d0e77735..b9875fe4 100644--- a/claude-ops/scripts/daemon-services.default.json+++ b/claude-ops/scripts/daemon-services.default.json@@ -19,6 +19,14 @@"health_file": "~/.claude/plugins/data/ops-ops-marketplace/memories/.health","restart_delay": 3600,"cron": "*/30 * * * *"+ },+ "fires-watcher": {+ "enabled": false,+ "command": "__SCRIPTS_DIR__/ops-fires-watcher.sh",+ "health_file": "~/.claude/plugins/data/ops-ops-marketplace/fires-watcher.health",+ "restart_delay": 60,+ "max_restarts": 20,+ "_note": "Polls ops-infra + Sentry every 60s; pushes notifications on new CRITICAL/HIGH incidents. Requires at least one notify sink (Telegram bot, Discord webhook, ntfy, Pushover, or macOS). Run /ops:setup notifications to enable."}}}diff --git a/claude-ops/scripts/ops-fires-watcher.sh b/claude-ops/scripts/ops-fires-watcher.shnew file mode 100755index 00000000..bb9d9f1f--- /dev/null+++ b/claude-ops/scripts/ops-fires-watcher.sh@@ -0,0 +1,237 @@+#!/usr/bin/env bash+# ops-fires-watcher.sh — Daemon loop that polls fire sources every 60s and+# pushes notifications for new CRITICAL/HIGH incidents.+#+# Sources polled each tick:+# - bin/ops-infra (ECS cluster health — 'down' / 'degraded' → HIGH/CRITICAL)+# - Sentry API (unresolved issues at level:error/fatal when+# $SENTRY_AUTH_TOKEN + sentry_org are configured)+#+# State file: ${DATA_DIR}/fires-watcher.state.json — keyed by incident+# fingerprint, tracks { severity, last_notified_at, first_seen_at }.+#+# Debounce policy:+# - Don't re-notify for the same fingerprint within 30 minutes+# - UNLESS the severity *rises* (e.g. degraded → down), in which case we+# re-notify immediately and update the stored severity.+#+# Rule 5: read-only polling — this watcher never mutates infra.++set -euo pipefail++# ─── Paths ───────────────────────────────────────────────────────────────────+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+# shellcheck disable=SC1091+[ -r "$PLUGIN_ROOT/lib/os-detect.sh" ] && . "$PLUGIN_ROOT/lib/os-detect.sh"+# shellcheck disable=SC1091+[ -r "$PLUGIN_ROOT/lib/credential-store.sh" ] && . "$PLUGIN_ROOT/lib/credential-store.sh"++DATA_DIR="${OPS_DATA_DIR:-${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/fires-watcher.log"+STATE_FILE="${FIRES_WATCHER_STATE:-$DATA_DIR/fires-watcher.state.json}"+HEALTH_FILE="${FIRES_WATCHER_HEALTH:-$DATA_DIR/fires-watcher.health}"+NOTIFY="$PLUGIN_ROOT/scripts/ops-notify.sh"+OPS_INFRA="$PLUGIN_ROOT/bin/ops-infra"+PREFS_PATH="${PREFS_PATH:-$DATA_DIR/preferences.json}"++POLL_INTERVAL="${FIRES_WATCHER_INTERVAL:-60}"+DEBOUNCE_SECS="${FIRES_WATCHER_DEBOUNCE:-1800}" # 30 minutes++mkdir -p "$LOG_DIR"+mkdir -p "$(dirname "$STATE_FILE")"++# ─── Logging ────────────────────────────────────────────────────────────────+log() {+ printf '%s [fires-watcher] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$LOG"+}++# ─── Severity rank (higher = worse) ─────────────────────────────────────────+sev_rank() {+ case "$1" in+ CRITICAL) echo 4 ;;+ HIGH) echo 3 ;;+ MEDIUM) echo 2 ;;+ LOW) echo 1 ;;+ *) echo 0 ;;+ esac+}++# ─── State I/O ──────────────────────────────────────────────────────────────+ensure_state() {+ if [ ! -f "$STATE_FILE" ]; then+ echo '{"incidents":{}}' > "$STATE_FILE"+ fi+}++# Decide if we should notify given a fingerprint + new severity.+# Echoes "notify" or "skip"; on notify, updates the state file.+should_notify() {+ local fp="$1" new_sev="$2" now_epoch+ now_epoch="$(date +%s)"+ ensure_state++ command -v jq >/dev/null 2>&1 || { echo "notify"; return 0; }++ local prev_sev prev_notified+ prev_sev="$(jq -r --arg fp "$fp" '.incidents[$fp].severity // empty' "$STATE_FILE")"+ prev_notified="$(jq -r --arg fp "$fp" '.incidents[$fp].last_notified_at // 0' "$STATE_FILE")"++ local decision="skip"+ if [ -z "$prev_sev" ]; then+ decision="notify" # brand new incident+ elif [ "$(sev_rank "$new_sev")" -gt "$(sev_rank "$prev_sev")" ]; then+ decision="notify" # severity escalated+ else+ local age=$(( now_epoch - prev_notified ))+ if [ "$age" -ge "$DEBOUNCE_SECS" ]; then+ decision="notify" # debounce window elapsed+ fi+ fi++ if [ "$decision" = "notify" ]; then+ local tmp+ tmp="$(mktemp)"+ jq --arg fp "$fp" \+ --arg sev "$new_sev" \+ --argjson now "$now_epoch" \+ '.incidents[$fp] = {+ severity: $sev,+ last_notified_at: $now,+ first_seen_at: (.incidents[$fp].first_seen_at // $now)+ }' "$STATE_FILE" > "$tmp" && mv "$tmp" "$STATE_FILE"+ fi++ echo "$decision"+}++# ─── Notify wrapper ─────────────────────────────────────────────────────────+dispatch() {+ local severity="$1" title="$2" body="$3" link="${4:-}"+ if [ ! -x "$NOTIFY" ]; then+ log "WARN: $NOTIFY not executable — skipping dispatch"+ return 0+ fi+ if [ -n "$link" ]; then+ "$NOTIFY" "$severity" "$title" "$body" --link "$link" || \+ log "dispatch failed for title=$title"+ else+ "$NOTIFY" "$severity" "$title" "$body" || \+ log "dispatch failed for title=$title"+ fi+}++# ─── Source: ops-infra ──────────────────────────────────────────────────────+probe_infra() {+ [ -x "$OPS_INFRA" ] || return 0+ command -v jq >/dev/null 2>&1 || return 0++ local output+ output="$("$OPS_INFRA" 2>/dev/null || echo '{}')"+ [ -z "$output" ] && return 0++ # Emit lines: "SEV<TAB>fingerprint<TAB>title<TAB>body"+ echo "$output" | jq -r '+ (.clusters // [])[]+ | select(.status == "down" or .status == "degraded")+ | "\(if .status == "down" then "CRITICAL" else "HIGH" end)\t" ++ "infra:\(.cluster):\(.status)\t" ++ "ECS \(.cluster) \(.status)\t" ++ "Cluster \(.cluster) is \(.status). Services: \((.services // []) | map(select(.running != .desired)) | map("\(.name) \(.running)/\(.desired)") | join(", "))"+ ' 2>/dev/null || true+}++# ─── Source: Sentry ─────────────────────────────────────────────────────────+probe_sentry() {+ local token="${SENTRY_AUTH_TOKEN:-}"+ local org="${SENTRY_ORG:-}"+ if [ -z "$token" ] && [ -f "$PREFS_PATH" ] && command -v jq >/dev/null 2>&1; then+ token="$(jq -r '.sentry_auth_token // empty' "$PREFS_PATH" 2>/dev/null || true)"+ fi+ if [ -z "$org" ] && [ -f "$PREFS_PATH" ] && command -v jq >/dev/null 2>&1; then+ org="$(jq -r '.sentry_org // empty' "$PREFS_PATH" 2>/dev/null || true)"+ fi++ if [ -z "$token" ] || [ -z "$org" ]; then+ return 0+ fi+ command -v curl >/dev/null 2>&1 || return 0+ command -v jq >/dev/null 2>&1 || return 0++ local response+ response="$(curl -s --max-time 15 \+ -H "Authorization: Bearer ${token}" \+ "https://sentry.io/api/0/organizations/${org}/issues/?query=is:unresolved+level:[error,fatal]&limit=25" \+ 2>/dev/null || echo '[]')"++ # Defensively fall back if response is not valid JSON array+ if ! echo "$response" | jq -e 'type == "array"' >/dev/null 2>&1; then+ return 0+ fi++ echo "$response" | jq -r '+ .[]+ | select(.level == "error" or .level == "fatal")+ | "\(if .level == "fatal" then "CRITICAL" else "HIGH" end)\t" ++ "sentry:\(.id)\t" ++ "Sentry: \((.title // "issue") | .[0:80])\t" ++ "Project: \(.project.slug // "unknown"). Events: \(.count // "?"). Users: \(.userCount // "?"). URL: \(.permalink // "")"+ ' 2>/dev/null || true+}++# ─── Health writer ──────────────────────────────────────────────────────────+write_health() {+ local status="$1" msg="${2:-}"+ cat > "$HEALTH_FILE" <<EOF+{+ "status": "${status}",+ "message": "${msg}",+ "last_tick": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",+ "poll_interval": ${POLL_INTERVAL},+ "state_file": "${STATE_FILE}"+}+EOF+}++# ─── Main tick ──────────────────────────────────────────────────────────────+tick() {+ local events new_count=0 seen_count=0+ events="$( (probe_infra; probe_sentry) 2>/dev/null || true )"+ if [ -z "$events" ]; then+ write_health "ok" "no events"+ return 0+ fi++ while IFS=$'\t' read -r sev fp title body; do+ [ -z "${fp:-}" ] && continue+ seen_count=$((seen_count + 1))+ local decision+ decision="$(should_notify "$fp" "$sev")"+ if [ "$decision" = "notify" ]; then+ local link=""+ # Prefer an explicit URL embedded in the body (e.g., Sentry permalink)+ link="$(printf '%s' "$body" | sed -n 's#.*URL: \(https\?://[^ ]*\).*#\1#p' | head -1)"+ if [ -n "$link" ]; then+ dispatch "$sev" "$title" "$body" "$link"+ else+ dispatch "$sev" "$title" "$body"+ fi+ new_count=$((new_count + 1))+ log "NEW $sev $fp :: $title"+ fi+ done <<< "$events"++ write_health "ok" "seen=${seen_count} notified=${new_count}"+}++# ─── Loop ───────────────────────────────────────────────────────────────────+log "START fires-watcher (interval=${POLL_INTERVAL}s, debounce=${DEBOUNCE_SECS}s)"+write_health "starting" "booting fires-watcher"++trap 'log "STOP SIGTERM"; write_health "stopped" "received SIGTERM"; exit 0' TERM+trap 'log "STOP SIGINT"; write_health "stopped" "received SIGINT"; exit 0' INT++while true; do+ tick || log "TICK ERROR (continuing)"+ sleep "$POLL_INTERVAL"+donediff --git a/claude-ops/scripts/ops-notify.sh b/claude-ops/scripts/ops-notify.shnew file mode 100755index 00000000..59f921c6--- /dev/null+++ b/claude-ops/scripts/ops-notify.sh@@ -0,0 +1,273 @@+#!/usr/bin/env bash+# ops-notify.sh — Fan-out notification dispatcher for claude-ops.+#+# Usage:+# scripts/ops-notify.sh <severity> <title> <body> [--link <url>]+#+# <severity> is one of: CRITICAL | HIGH | MEDIUM | LOW (case-insensitive).+# Delivery sinks (all optional, all fanned out when configured):+# 1. Telegram bot — $TELEGRAM_BOT_TOKEN + $TELEGRAM_NOTIFY_CHAT_ID (or $TELEGRAM_OWNER_ID)+# 2. Discord webhook — $DISCORD_WEBHOOK_URL+# 3. ntfy.sh — $NTFY_TOPIC (optionally $NTFY_SERVER, default https://ntfy.sh)+# 4. Pushover — $PUSHOVER_USER + $PUSHOVER_TOKEN+# 5. macOS osascript — local desktop notification (only on macOS)+# 6. stderr log — always runs if nothing else is configured+#+# Rule 0: no hardcoded tokens, chat IDs, or webhooks live in this file — every+# credential is read from the environment or $PREFS_PATH.++set -euo pipefail++# ─── Paths + library sourcing ───────────────────────────────────────────────+SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"+# shellcheck disable=SC1091+[ -r "$SCRIPT_DIR/lib/os-detect.sh" ] && . "$SCRIPT_DIR/lib/os-detect.sh"+# shellcheck disable=SC1091+[ -r "$SCRIPT_DIR/lib/credential-store.sh" ] && . "$SCRIPT_DIR/lib/credential-store.sh"++DATA_DIR="${OPS_DATA_DIR:-${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/ops-notify.log"+PREFS_PATH="${PREFS_PATH:-$DATA_DIR/preferences.json}"++mkdir -p "$LOG_DIR"++# ─── Portable OS check (matches bin/ops-autofix pattern) ────────────────────+IS_MACOS=false+[ "$(uname -s)" = "Darwin" ] && IS_MACOS=true++# ─── Logging ────────────────────────────────────────────────────────────────+log() {+ printf '%s [ops-notify] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$LOG"+}++# ─── Argument parsing ───────────────────────────────────────────────────────+if [[ $# -lt 3 ]]; then+ echo "Usage: $0 <CRITICAL|HIGH|MEDIUM|LOW> <title> <body> [--link <url>]" >&2+ exit 2+fi++SEVERITY="$(echo "$1" | tr '[:lower:]' '[:upper:]')"+TITLE="$2"+BODY="$3"+shift 3+LINK=""+while [[ $# -gt 0 ]]; do+ case "$1" in+ --link)+ LINK="${2:-}"; shift 2 ;;+ *)+ shift ;;+ esac+done++case "$SEVERITY" in+ CRITICAL|HIGH|MEDIUM|LOW) : ;;+ *)+ echo "ops-notify: invalid severity '$SEVERITY' (expected CRITICAL|HIGH|MEDIUM|LOW)" >&2+ exit 2+ ;;+esac++# ─── Severity emoji mapping ─────────────────────────────────────────────────+severity_emoji() {+ case "$1" in+ CRITICAL) echo "🔴" ;;+ HIGH) echo "🟠" ;;+ MEDIUM) echo "🟡" ;;+ LOW) echo "🟢" ;;+ *) echo "⚪" ;;+ esac+}++severity_color_hex() {+ # Decimal RGB values for Discord embed color field+ case "$1" in+ CRITICAL) echo "15158332" ;; # red+ HIGH) echo "15105570" ;; # orange+ MEDIUM) echo "15844367" ;; # yellow+ LOW) echo "3066993" ;; # green+ *) echo "9807270" ;; # gray+ esac+}++EMOJI="$(severity_emoji "$SEVERITY")"+FULL_TITLE="${EMOJI} [${SEVERITY}] ${TITLE}"++# ─── Pref loading helper ────────────────────────────────────────────────────+# Pulls a top-level key from $PREFS_PATH if the file exists. Caller may+# use this to provide fallbacks when env vars aren't set.+pref_get() {+ local key="$1"+ [ -f "$PREFS_PATH" ] || return 0+ command -v jq >/dev/null 2>&1 || return 0+ jq -r --arg k "$key" '.[$k] // empty' "$PREFS_PATH" 2>/dev/null || true+}++# ─── Sink: Telegram bot ─────────────────────────────────────────────────────+send_telegram() {+ local token="${TELEGRAM_BOT_TOKEN:-$(pref_get telegram_bot_token)}"+ local chat_id="${TELEGRAM_NOTIFY_CHAT_ID:-${TELEGRAM_OWNER_ID:-$(pref_get telegram_notify_chat_id)}}"+ if [ -z "$token" ] || [ -z "$chat_id" ]; then+ return 1+ fi+ local text+ if [ -n "$LINK" ]; then+ text="${FULL_TITLE}"$'\n\n'"${BODY}"$'\n\n'"${LINK}"+ else+ text="${FULL_TITLE}"$'\n\n'"${BODY}"+ fi+ curl -s -o /dev/null -w '%{http_code}' \+ -X POST "https://api.telegram.org/bot${token}/sendMessage" \+ --data-urlencode "chat_id=${chat_id}" \+ --data-urlencode "text=${text}" \+ --max-time 10 || echo "000"+}++# ─── Sink: Discord webhook ──────────────────────────────────────────────────+send_discord() {+ local url="${DISCORD_WEBHOOK_URL:-$(pref_get discord_webhook_url)}"+ if [ -z "$url" ]; then+ return 1+ fi+ local color payload+ color="$(severity_color_hex "$SEVERITY")"+ # Build JSON via jq to handle special characters safely+ if command -v jq >/dev/null 2>&1; then+ payload="$(jq -n \+ --arg title "$FULL_TITLE" \+ --arg body "$BODY" \+ --arg link "$LINK" \+ --argjson color "$color" \+ '{+ embeds: [{+ title: $title,+ description: $body,+ color: $color,+ url: (if $link == "" then null else $link end)+ }]+ }')"+ else+ # Fallback: minimal escape of double quotes + newlines+ local esc_title esc_body+ esc_title="$(printf '%s' "$FULL_TITLE" | sed 's/"/\\"/g')"+ esc_body="$(printf '%s' "$BODY" | sed 's/"/\\"/g' | tr '\n' ' ')"+ payload="{\"embeds\":[{\"title\":\"${esc_title}\",\"description\":\"${esc_body}\",\"color\":${color}}]}"+ fi+ curl -s -o /dev/null -w '%{http_code}' \+ -X POST "$url" \+ -H 'Content-Type: application/json' \+ --data "$payload" \+ --max-time 10 || echo "000"+}++# ─── Sink: ntfy.sh ──────────────────────────────────────────────────────────+send_ntfy() {+ local topic="${NTFY_TOPIC:-$(pref_get ntfy_topic)}"+ if [ -z "$topic" ]; then+ return 1+ fi+ local server="${NTFY_SERVER:-https://ntfy.sh}"+ local priority+ case "$SEVERITY" in+ CRITICAL) priority="5" ;;+ HIGH) priority="4" ;;+ MEDIUM) priority="3" ;;+ LOW) priority="2" ;;+ *) priority="3" ;;+ esac+ local body_with_link="$BODY"+ [ -n "$LINK" ] && body_with_link="${BODY}"$'\n\n'"${LINK}"+ local sev_lc+ sev_lc="$(echo "$SEVERITY" | tr '[:upper:]' '[:lower:]')"+ curl -s -o /dev/null -w '%{http_code}' \+ -X POST "${server}/${topic}" \+ -H "Title: ${FULL_TITLE}" \+ -H "Priority: ${priority}" \+ -H "Tags: warning,${sev_lc}" \+ --data "$body_with_link" \+ --max-time 10 || echo "000"+}++# ─── Sink: Pushover ─────────────────────────────────────────────────────────+send_pushover() {+ local user="${PUSHOVER_USER:-$(pref_get pushover_user_key)}"+ local token="${PUSHOVER_TOKEN:-$(pref_get pushover_app_token)}"+ if [ -z "$user" ] || [ -z "$token" ]; then+ return 1+ fi+ local priority+ case "$SEVERITY" in+ CRITICAL) priority="1" ;; # high-priority, bypass quiet hours+ HIGH) priority="1" ;;+ MEDIUM) priority="0" ;;+ LOW) priority="-1" ;;+ *) priority="0" ;;+ esac+ local url_args=()+ if [ -n "$LINK" ]; then+ url_args+=(--data-urlencode "url=${LINK}")+ fi+ curl -s -o /dev/null -w '%{http_code}' \+ -X POST "https://api.pushover.net/1/messages.json" \+ --data-urlencode "token=${token}" \+ --data-urlencode "user=${user}" \+ --data-urlencode "title=${FULL_TITLE}" \+ --data-urlencode "message=${BODY}" \+ --data-urlencode "priority=${priority}" \+ "${url_args[@]}" \+ --max-time 10 || echo "000"+}++# ─── Sink: macOS osascript ──────────────────────────────────────────────────+send_macos() {+ $IS_MACOS || return 1+ command -v osascript >/dev/null 2>&1 || return 1+ # Escape double quotes for AppleScript literal+ local esc_title esc_body+ esc_title="$(printf '%s' "$FULL_TITLE" | sed 's/"/\\"/g')"+ esc_body="$(printf '%s' "$BODY" | sed 's/"/\\"/g')"+ osascript -e "display notification \"${esc_body}\" with title \"${esc_title}\"" >/dev/null 2>&1 || true+ echo "200"+}++# ─── Sink: stderr ───────────────────────────────────────────────────────────+send_stderr() {+ {+ printf '%s\n' "$FULL_TITLE"+ printf '%s\n' "$BODY"+ [ -n "$LINK" ] && printf 'link: %s\n' "$LINK"+ } >&2+ echo "200"+}++# ─── Dispatch ───────────────────────────────────────────────────────────────+delivered=0++run_sink() {+ local name="$1" fn="$2"+ local result+ result="$($fn 2>/dev/null || true)"+ if [ -n "$result" ] && [ "$result" != "000" ]; then+ log "SINK ${name}: status=${result}"+ delivered=$((delivered + 1))+ else+ log "SINK ${name}: skipped (not configured or failed)"+ fi+}++run_sink telegram send_telegram+run_sink discord send_discord+run_sink ntfy send_ntfy+run_sink pushover send_pushover+run_sink macos send_macos++if [ "$delivered" -eq 0 ]; then+ log "SINK stderr: fallback (no sinks configured)"+ send_stderr >/dev/null 2>&1 || true+ printf '%s [ops-notify] %s | %s\n' \+ "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$FULL_TITLE" "$BODY" >> "$LOG"+fi++log "DISPATCHED severity=${SEVERITY} delivered=${delivered} title=\"${TITLE}\""+exit 0diff --git a/claude-ops/skills/setup/SKILL.md b/claude-ops/skills/setup/SKILL.mdindex c74940d1..6232a5da 100644--- a/claude-ops/skills/setup/SKILL.md+++ b/claude-ops/skills/setup/SKILL.md@@ -2055,6 +2055,114 @@ Prefer a Doppler reference (`doppler:STRIPE_SECRET_KEY`, `doppler:REVENUECAT_API---+### 3m — Notifications (fires-watcher sinks)++Sets up push notifications for CRITICAL/HIGH fires so the user stops having to poll `/ops:fires` manually. Gated behind the `fires-watcher` daemon service (disabled by default).++**Before prompting**, run the sink auto-scan **in background** (Rule 4 — all parallel):++```bash+# Already-configured sinks (env + $PREFS_PATH)+printenv TELEGRAM_BOT_TOKEN TELEGRAM_NOTIFY_CHAT_ID TELEGRAM_OWNER_ID \+ DISCORD_WEBHOOK_URL NTFY_TOPIC PUSHOVER_USER PUSHOVER_TOKEN 2>/dev/null++jq -r 'to_entries+ | map(select(.key | test("telegram_bot_token|telegram_notify_chat_id|discord_webhook_url|ntfy_topic|pushover_user_key|pushover_app_token")))+ | .[] | "\(.key)=\(.value | if type == "string" and length > 6 then .[0:6] + "***" else . end)"' \+ "$PREFS_PATH" 2>/dev/null++# Macro: is the Telegram bot already configured via /ops:setup telegram?+jq -r '.telegram.bot_token // empty, .telegram.owner_id // empty' "$PREFS_PATH" 2>/dev/null+```++Cache the results. Then **filter the option list to what isn't already configured** (Rule 1 — max 4).++Present via `AskUserQuestion` (≤4 options). Typical first batch:++| Option | Header | Description |+| ------------------------------------- | ---------- | ------------------------------------------------------------------------------ |+| Use Telegram (recommended) | telegram | Reuse the bot you already configured in 3a. Zero extra setup. |+| Configure ntfy.sh | ntfy | Free, no account. Pick a random topic, install the app on your phone. |+| Configure Pushover | pushover | ~$5 one-time. Highest-reliability mobile delivery with priority bypass for P0. |+| Skip — poll with /ops:fires instead | skip | Leaves `fires-watcher` disabled. You'll keep asking for fires manually. |++If Telegram's bot token + owner ID aren't already in `$PREFS_PATH`, swap `[Use Telegram]` for `[Configure Telegram bot — jump to 3a]` and re-enter 3a before returning here. Per Rule 3, don't silently skip — always offer an explicit `[Skip]`.++For anyone who wants Discord on top (many users want both team + personal delivery), run a second `AskUserQuestion`:++| Option | Header | Description |+| --------------------------------- | ---------- | --------------------------------------------------- |+| Also add Discord webhook | discord | Fan out to a #incidents channel in addition to X. |+| No — just the sink I picked | done | Single-sink setup. |++#### Per-sink capture++**Telegram** — if `$TELEGRAM_NOTIFY_CHAT_ID` is empty, default it to `$TELEGRAM_OWNER_ID` (the bot will DM the owner) and save `{"telegram_notify_chat_id": "<owner_id>"}` to `$PREFS_PATH`. Smoke-test in background (Rule 4):++```bash+scripts/ops-notify.sh LOW "setup test" "fires-watcher Telegram sink is live" &+```++**ntfy.sh** — generate a random topic if the user has none:++```bash+TOPIC="claude-ops-fires-$(openssl rand -hex 6 2>/dev/null || head -c 12 /dev/urandom | base64 | tr -dc 'a-z0-9' | head -c 12)"+echo "$TOPIC"+```++Show the topic and install instructions (`open https://ntfy.sh/<topic>` in a browser, or scan the QR in the ntfy mobile app). Save to `$PREFS_PATH` under `ntfy_topic`.++**Pushover** — per Rule 3 offer: `[Paste user key + app token]` / `[Deep hunt — spawn agent]` / `[Skip]`. On paste, validate with a smoke-test in background (Rule 4):++```bash+curl -s -X POST https://api.pushover.net/1/messages.json \+ --data-urlencode "token=$PUSHOVER_TOKEN" \+ --data-urlencode "user=$PUSHOVER_USER" \+ --data-urlencode "title=claude-ops setup test" \+ --data-urlencode "message=fires-watcher Pushover sink is live" &+```++Expect `{"status":1,...}` within 5 s.++**Discord** — if the user already set `discord_default_webhook_url` via a prior run (or issue #20's work), reuse it; otherwise Rule-3-prompt for a webhook URL (`https://discord.com/api/webhooks/...`).++#### Save + enable daemon service++Write to `$PREFS_PATH` (merge, never overwrite unrelated keys):++```json+{+ "notifications": {+ "configured_sinks": ["telegram", "ntfy"],+ "configured_at": "<ISO timestamp>"+ },+ "telegram_notify_chat_id": "<chat_id>",+ "ntfy_topic": "<topic>"+}+```++Then **enable the daemon service** in background (Rule 4):++```bash+jq '.services["fires-watcher"].enabled = true' \+ ~/.claude/plugins/data/ops-ops-marketplace/daemon-services.json \+ > /tmp/daemon-services.json.new && \+ mv /tmp/daemon-services.json.new ~/.claude/plugins/data/ops-ops-marketplace/daemon-services.json && \+ scripts/ops-daemon.sh restart &+```++Confirm the watcher is alive after restart:++```bash+cat ~/.claude/plugins/data/ops-ops-marketplace/fires-watcher.health 2>/dev/null+```++Expect `{"status": "ok", ...}` within 60 seconds.++> **Deep-dive:** see `${CLAUDE_PLUGIN_ROOT}/docs/notifications.md`, `${CLAUDE_PLUGIN_ROOT}/scripts/ops-fires-watcher.sh`, and `${CLAUDE_PLUGIN_ROOT}/scripts/ops-notify.sh` for sink priority rationale, debounce rules, and a troubleshooting walk-through.++---+## Step 4 — Configure MCPs (if selected)For each MCP that isn't in `mcp_configured`, offer bulk setup first: