Skip to content

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.

feat(daemon): phase 16 - parallel pre-warm, self-heal notify, rate limits, credential alerts

auroracapital934db13744e4
diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.json
index 4d10d1a1..b9e55b24 100644
--- a/claude-ops/scripts/daemon-services.default.json
+++ b/claude-ops/scripts/daemon-services.default.json
@@ -54,6 +54,12 @@
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-competitor-intel.sh",
"cron": "0 10 * * 1",
"_note": "Weekly competitor intelligence report every Monday at 10am. Script not yet landed — re-enable when ops-cron-competitor-intel.sh is added."
+ },
+ "marketing-prewarm": {
+ "enabled": false,
+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-marketing-prewarm.sh",
+ "cron": "*/15 * * * *",
+ "_note": "Pre-warms /ops:marketing cache every 15 minutes. Requires marketing credentials (Klaviyo, Meta Ads, GA4, GSC, Google Ads). Enable with /ops:setup marketing after credentials are configured."
}
}
}
diff --git a/claude-ops/scripts/ops-cron-marketing-prewarm.sh b/claude-ops/scripts/ops-cron-marketing-prewarm.sh
new file mode 100755
index 00000000..2438d52f
--- /dev/null
+++ b/claude-ops/scripts/ops-cron-marketing-prewarm.sh
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+# ops-cron-marketing-prewarm.sh — thin cron wrapper that invokes
+# bin/ops-marketing-dash and caches its JSON output so /ops:marketing
+# loads instantly from cache. Phase 16 INFR-04.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_DIR/..}"
+DATA_DIR="${DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"
+CACHE_DIR="$DATA_DIR/cache"
+mkdir -p "$CACHE_DIR"
+
+MARKETING_BIN="$PLUGIN_ROOT/bin/ops-marketing-dash"
+[[ -x "$MARKETING_BIN" ]] || exit 0
+
+TMP="$CACHE_DIR/marketing.json.tmp.$$"
+if "$MARKETING_BIN" --json > "$TMP" 2>/dev/null; then
+ python3 - "$TMP" <<'PY' 2>/dev/null || true
+import json, sys, datetime
+p = sys.argv[1]
+try:
+ d = json.load(open(p))
+ d["cached_at"] = datetime.datetime.utcnow().isoformat() + "Z"
+ json.dump(d, open(p, "w"))
+except Exception:
+ pass
+PY
+ mv "$TMP" "$CACHE_DIR/marketing.json"
+else
+ rm -f "$TMP" 2>/dev/null || true
+fi
diff --git a/claude-ops/scripts/ops-daemon.sh b/claude-ops/scripts/ops-daemon.sh
index 893e1d85..72110861 100755
--- a/claude-ops/scripts/ops-daemon.sh
+++ b/claude-ops/scripts/ops-daemon.sh
@@ -86,6 +86,11 @@ declare -A SERVICE_LAST_RUN # service name → last run epoch (cron services)
declare -A SERVICE_STATUS # service name → status string
declare -A SERVICE_LAST_HEALTH # service name → last health string
declare -A SERVICE_LAST_RESTART_EPOCH # service name → epoch of last restart attempt
+declare -A SERVICE_LATENCY_MS # service name → last run latency in ms (warm/cron services)
+declare -A SERVICE_LAST_SUCCESS # service name → ISO-8601 UTC of last clean run
+declare -A SERVICE_ERROR_COUNT # service name → cumulative errors since daemon start
+declare -A SERVICE_LAST_ERROR # service name → last error message (truncated)
+declare -A SERVICE_NOTIFIED_CRASH # service name → set to 1 after persistent-failure notify (deduped)
RESTART_COOLDOWN=1800 # Reset restart counter after 30 min of stability
ACTION_NEEDED="null"
@@ -249,6 +254,10 @@ check_health() {
;;
connected|running|ok)
SERVICE_STATUS["$name"]="running"
+ # Phase 16 INFR-03: reset crash-notify dedup on recovery
+ if [[ -n "${SERVICE_NOTIFIED_CRASH[$name]:-}" ]]; then
+ unset "SERVICE_NOTIFIED_CRASH[$name]"
+ fi
;;
*)
SERVICE_STATUS["$name"]="${file_status:-running}"
@@ -290,6 +299,17 @@ restart_service() {
if [[ $count -ge $max_restarts ]]; then
log "RESTART: $name hit max_restarts=$max_restarts — not restarting (resets after ${RESTART_COOLDOWN}s cooldown)"
SERVICE_STATUS["$name"]="max_restarts_exceeded"
+ # Phase 16 INFR-03: notify on persistent failure (deduped)
+ if [[ -z "${SERVICE_NOTIFIED_CRASH[$name]:-}" ]]; then
+ local _notify_script="$SCRIPT_DIR/scripts/ops-notify.sh"
+ if [[ -f "$_notify_script" ]]; then
+ bash "$_notify_script" HIGH \
+ "ops-daemon: $name crashed (persistent)" \
+ "Service '$name' hit max_restarts=$max_restarts. Manual intervention required." \
+ >/dev/null 2>&1 &
+ fi
+ SERVICE_NOTIFIED_CRASH["$name"]=1
+ fi
return
fi
@@ -319,6 +339,17 @@ write_daemon_health() {
local pid="${SERVICE_PIDS[$name]:-null}"
local restarts="${SERVICE_RESTARTS[$name]:-0}"
local health="${SERVICE_LAST_HEALTH[$name]:-unknown}"
+ local latency_ms="${SERVICE_LATENCY_MS[$name]:-0}"
+ local last_success="${SERVICE_LAST_SUCCESS[$name]:-}"
+ local error_count="${SERVICE_ERROR_COUNT[$name]:-0}"
+ local last_error_raw="${SERVICE_LAST_ERROR[$name]:-}"
+ local last_error_json="null"
+ if [[ -n "$last_error_raw" ]]; then
+ last_error_json=$(python3 -c "
+import json, sys
+print(json.dumps(sys.argv[1]))
+" "$last_error_raw" 2>/dev/null || echo "null")
+ fi
[[ $first -eq 0 ]] && services_json+=","
first=0
@@ -329,7 +360,7 @@ write_daemon_health() {
local next_iso="" last_iso=""
[[ -n "$next_run" ]] && next_iso=$(_date_from_epoch "$next_run" 2>/dev/null || echo "")
[[ -n "$last_run" ]] && last_iso=$(_date_from_epoch "$last_run" 2>/dev/null || echo "")
- services_json+="\"$name\": {\"status\": \"$status\", \"next_run\": \"$next_iso\", \"last_run\": \"$last_iso\"}"
+ services_json+="\"$name\": {\"status\": \"$status\", \"next_run\": \"$next_iso\", \"last_run\": \"$last_iso\", \"latency_ms\": $latency_ms, \"last_success\": \"$last_success\", \"error_count\": $error_count, \"last_error\": $last_error_json}"
else
local pid_val
if [[ "$pid" == "null" ]] || [[ -z "$pid" ]]; then
@@ -348,11 +379,42 @@ write_daemon_health() {
else
pid_val="$pid"
fi
- services_json+="\"$name\": {\"status\": \"$status\", \"pid\": $pid_val, \"last_health\": \"$health\", \"restarts\": $restarts}"
+ services_json+="\"$name\": {\"status\": \"$status\", \"pid\": $pid_val, \"last_health\": \"$health\", \"restarts\": $restarts, \"latency_ms\": $latency_ms, \"last_success\": \"$last_success\", \"error_count\": $error_count, \"last_error\": $last_error_json}"
fi
done
services_json+="}"
+ # Top-level credential_warnings + rate_limit_warnings (Phase 16)
+ local cred_warn_json="[]"
+ if [[ -f "$DATA_DIR/cache/cred-expiry-warnings.json" ]]; then
+ cred_warn_json=$(python3 -c "
+import json
+try:
+ d = json.load(open('$DATA_DIR/cache/cred-expiry-warnings.json'))
+ print(json.dumps(d.get('warnings', [])))
+except Exception:
+ print('[]')
+" 2>/dev/null || echo "[]")
+ fi
+
+ local rate_warn_json="[]"
+ if [[ -f "$DATA_DIR/rate-limits.json" ]]; then
+ rate_warn_json=$(python3 -c "
+import json
+warns = []
+try:
+ d = json.load(open('$DATA_DIR/rate-limits.json'))
+ for integ, v in d.items():
+ q = v.get('quota', 0)
+ c = v.get('calls', 0)
+ if q and (c / q) >= 0.8:
+ warns.append(f\"{integ}: {c}/{q}\")
+except Exception:
+ pass
+print(json.dumps(warns))
+" 2>/dev/null || echo "[]")
+ fi
+
# Read brain cache metadata
local brain_briefing_cached_at=""
local brain_urgent_count=0
@@ -400,6 +462,8 @@ except: print('')
"version": "$daemon_version",
"services": $services_json,
"action_needed": $ACTION_NEEDED,
+ "credential_warnings": $cred_warn_json,
+ "rate_limit_warnings": $rate_warn_json,
"brain": {
"briefing_cached_at": "$brain_briefing_cached_at",
"urgent_count": $brain_urgent_count,
@@ -765,6 +829,287 @@ PYEOF
log "BRAIN: project health cache updated"
}
+# ── Phase 16: marketing pre-warm ─────────────────────────────────────────
+# Fetches cross-platform marketing snapshot (Klaviyo, Meta Ads, GA4, GSC,
+# Google Ads) via bin/ops-marketing-dash and caches to marketing.json so
+# /ops:marketing loads instantly. Throttled to 15 min.
+prefetch_marketing_cache() {
+ local LAST_FETCH="$DATA_DIR/cache/.marketing_ts"
+ local now; now=$(date +%s)
+ local MARKETING_INTERVAL=900 # 15 min
+ if [[ -f "$LAST_FETCH" ]]; then
+ local last; last=$(cat "$LAST_FETCH" 2>/dev/null || echo 0)
+ if (( now - last < MARKETING_INTERVAL )); then return 0; fi
+ fi
+
+ local marketing_bin="$SCRIPT_DIR/bin/ops-marketing-dash"
+ [[ -x "$marketing_bin" ]] || return 0
+
+ mkdir -p "$DATA_DIR/cache" 2>/dev/null || true
+ local cache_file="$DATA_DIR/cache/marketing.json"
+ local tmp_file="${cache_file}.tmp.$$"
+ if "$marketing_bin" --json > "$tmp_file" 2>/dev/null; then
+ python3 - "$tmp_file" <<'PY' 2>/dev/null || true
+import json, sys, datetime
+p = sys.argv[1]
+try:
+ d = json.load(open(p))
+ d["cached_at"] = datetime.datetime.utcnow().isoformat() + "Z"
+ json.dump(d, open(p, "w"))
+except Exception:
+ pass
+PY
+ mv "$tmp_file" "$cache_file"
+ date +%s > "$LAST_FETCH"
+ log "BRAIN: marketing cache updated"
+ else
+ rm -f "$tmp_file" 2>/dev/null || true
+ return 1
+ fi
+}
+
+# ── Phase 16: parallel warm wrapper ──────────────────────────────────────
+# Runs all intelligence prefetch functions concurrently. Each subshell writes
+# latency to a tmpdir file; parent merges into SERVICE_LATENCY_MS after wait.
+# Source: extended from prefetch_briefing_cache PID-array pattern.
+_run_parallel_warm() {
+ local tmpdir
+ tmpdir=$(mktemp -d 2>/dev/null) || return 0
+ local _pids=()
+ local _fn_names=(prefetch_briefing_cache prefetch_calendar prefetch_project_health build_contact_activity_index prefetch_marketing_cache)
+
+ local fn
+ for fn in "${_fn_names[@]}"; do
+ if ! declare -F "$fn" >/dev/null 2>&1; then continue; fi
+ (
+ local _t0 _t1
+ _t0=$(python3 -c 'import time;print(int(time.time()*1000))' 2>/dev/null || echo 0)
+ local _err_file="$tmpdir/${fn}.err"
+ if "$fn" 2>"$_err_file" >/dev/null; then
+ _t1=$(python3 -c 'import time;print(int(time.time()*1000))' 2>/dev/null || echo 0)
+ echo $(( _t1 - _t0 )) > "$tmpdir/${fn}.ms"
+ date -u +"%Y-%m-%dT%H:%M:%SZ" > "$tmpdir/${fn}.ok"
+ else
+ tail -c 300 "$_err_file" 2>/dev/null | tr -d '\n' > "$tmpdir/${fn}.fail" 2>/dev/null || true
+ fi
+ ) &
+ _pids+=($!)
+ done
+
+ wait "${_pids[@]}" 2>/dev/null || true
+
+ for fn in "${_fn_names[@]}"; do
+ if [[ -f "$tmpdir/${fn}.ms" ]]; then
+ SERVICE_LATENCY_MS["$fn"]=$(cat "$tmpdir/${fn}.ms")
+ fi
+ if [[ -f "$tmpdir/${fn}.ok" ]]; then
+ SERVICE_LAST_SUCCESS["$fn"]=$(cat "$tmpdir/${fn}.ok")
+ fi
+ if [[ -f "$tmpdir/${fn}.fail" ]]; then
+ SERVICE_ERROR_COUNT["$fn"]=$(( ${SERVICE_ERROR_COUNT[$fn]:-0} + 1 ))
+ SERVICE_LAST_ERROR["$fn"]=$(cat "$tmpdir/${fn}.fail")
+ fi
+ done
+ rm -rf "$tmpdir" 2>/dev/null || true
+}
+
+# ── Phase 16: rate-limit tracking ────────────────────────────────────────
+# Counts API calls per integration, reads quotas from preferences.json (or
+# bundled defaults), warns once per window at 80% via ops-notify.sh. Window
+# resets reset warned_80pct too.
+RATE_LIMITS_FILE="$DATA_DIR/rate-limits.json"
+
+_seed_rate_limit_defaults() {
+ [[ -f "$RATE_LIMITS_FILE" ]] && return 0
+ mkdir -p "$(dirname "$RATE_LIMITS_FILE")" 2>/dev/null || true
+ python3 - "$RATE_LIMITS_FILE" <<'PY' 2>/dev/null || true
+import json, sys, datetime
+now = datetime.datetime.utcnow().isoformat() + "Z"
+defaults = {
+ "meta_ads": {"quota": 200, "window_seconds": 3600, "calls": 0, "window_start": now, "warned_80pct": False},
+ "klaviyo": {"quota": 75, "window_seconds": 60, "calls": 0, "window_start": now, "warned_80pct": False},
+ "google_ads": {"quota": 1000, "window_seconds": 60, "calls": 0, "window_start": now, "warned_80pct": False},
+ "ga4": {"quota": 1000, "window_seconds": 60, "calls": 0, "window_start": now, "warned_80pct": False},
+ "stripe": {"quota": 100, "window_seconds": 1, "calls": 0, "window_start": now, "warned_80pct": False},
+ "github": {"quota": 5000, "window_seconds": 3600, "calls": 0, "window_start": now, "warned_80pct": False}
+}
+json.dump(defaults, open(sys.argv[1], "w"), indent=2)
+PY
+}
+
+track_api_call() {
+ local integration="$1" count="${2:-1}"
+ [[ -n "$integration" ]] || return 0
+ _seed_rate_limit_defaults
+ local notify_script="$SCRIPT_DIR/scripts/ops-notify.sh"
+ python3 - "$RATE_LIMITS_FILE" "$integration" "$count" "$notify_script" <<'PY' 2>/dev/null || true
+import json, sys, os, subprocess, datetime
+path, integ, inc, notify = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
+try:
+ data = json.load(open(path))
+except Exception:
+ sys.exit(0)
+entry = data.get(integ)
+if entry is None:
+ sys.exit(0)
+now = datetime.datetime.utcnow()
+try:
+ ws = datetime.datetime.fromisoformat(entry["window_start"].replace("Z",""))
+except Exception:
+ ws = now
+age = (now - ws).total_seconds()
+if age >= entry.get("window_seconds", 60):
+ entry["calls"] = 0
+ entry["window_start"] = now.isoformat() + "Z"
+ entry["warned_80pct"] = False
+entry["calls"] = entry.get("calls", 0) + inc
+quota = entry.get("quota", 0)
+ratio = (entry["calls"] / quota) if quota else 0
+if ratio >= 0.8 and not entry.get("warned_80pct") and os.path.isfile(notify):
+ subprocess.Popen(["bash", notify, "MEDIUM",
+ f"ops-daemon: {integ} rate limit 80%",
+ f"{integ}: {entry['calls']}/{quota} ({ratio*100:.0f}%) in current window"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ entry["warned_80pct"] = True
+data[integ] = entry
+tmp = path + ".tmp." + str(os.getpid())
+json.dump(data, open(tmp, "w"), indent=2)
+os.replace(tmp, path)
+PY
+}
+
+# Called every 5 min from monitor loop. Resets rollover windows so
+# warned_80pct clears when the window advances without any new calls.
+check_rate_limits() {
+ local LAST_CHECK="$DATA_DIR/cache/.rate_limits_check_ts"
+ local now; now=$(date +%s)
+ mkdir -p "$DATA_DIR/cache" 2>/dev/null || true
+ if [[ -f "$LAST_CHECK" ]]; then
+ local last; last=$(cat "$LAST_CHECK" 2>/dev/null || echo 0)
+ if (( now - last < 300 )); then return 0; fi
+ fi
+ _seed_rate_limit_defaults
+ python3 - "$RATE_LIMITS_FILE" <<'PY' 2>/dev/null || true
+import json, sys, os, datetime
+path = sys.argv[1]
+try:
+ data = json.load(open(path))
+except Exception:
+ sys.exit(0)
+now = datetime.datetime.utcnow()
+changed = False
+for k, v in data.items():
+ try:
+ ws = datetime.datetime.fromisoformat(v["window_start"].replace("Z",""))
+ except Exception:
+ continue
+ if (now - ws).total_seconds() >= v.get("window_seconds", 60):
+ v["calls"] = 0
+ v["window_start"] = now.isoformat() + "Z"
+ v["warned_80pct"] = False
+ changed = True
+if changed:
+ tmp = path + ".tmp." + str(os.getpid())
+ json.dump(data, open(tmp, "w"), indent=2)
+ os.replace(tmp, path)
+PY
+ date +%s > "$LAST_CHECK"
+}
+
+# ── Phase 16: credential expiry (offline) ────────────────────────────────
+# Reads *_expires_at / *_created_at from preferences.json and warns:
+# - expires within WARN_DAYS (7)
+# - keys older than MAX_KEY_AGE_DAYS (180) — rotation recommended
+# Strictly offline — never makes a network call. Dedups per (credential, day).
+check_credential_expiry() {
+ local LAST_CHECK="$DATA_DIR/cache/.cred_expiry_ts"
+ local now; now=$(date +%s)
+ mkdir -p "$DATA_DIR/cache" 2>/dev/null || true
+ if [[ -f "$LAST_CHECK" ]]; then
+ local last; last=$(cat "$LAST_CHECK" 2>/dev/null || echo 0)
+ if (( now - last < 3600 )); then return 0; fi
+ fi
+
+ local prefs="${PREFS_PATH:-$DATA_DIR/preferences.json}"
+ local warn_file="$DATA_DIR/cache/cred-expiry-warnings.json"
+ if [[ ! -f "$prefs" ]]; then
+ date +%s > "$LAST_CHECK"
+ return 0
+ fi
+
+ python3 - "$prefs" "$warn_file" <<'PY' 2>/dev/null || true
+import json, sys, os, datetime
+prefs_path, warn_path = sys.argv[1], sys.argv[2]
+WARN_DAYS = 7
+MAX_KEY_AGE_DAYS = 180
+try:
+ prefs = json.load(open(prefs_path))
+except Exception:
+ sys.exit(0)
+now = datetime.datetime.now(datetime.timezone.utc)
+warnings = []
+for key, val in prefs.items():
+ if not isinstance(val, str) or not val:
+ continue
+ if key.endswith("_expires_at") and val != "never":
+ try:
+ expiry = datetime.datetime.fromisoformat(val.replace("Z", "+00:00"))
+ days_left = (expiry - now).days
+ if days_left <= WARN_DAYS:
+ cred_name = key[:-len("_expires_at")].replace("_", " ")
+ warnings.append(f"{cred_name}: expires in {days_left}d")
+ except Exception:
+ pass
+ if key.endswith("_created_at"):
+ try:
+ created = datetime.datetime.fromisoformat(val.replace("Z", "+00:00"))
+ age_days = (now - created).days
+ if age_days >= MAX_KEY_AGE_DAYS:
+ cred_name = key[:-len("_created_at")].replace("_", " ")
+ warnings.append(f"{cred_name}: {age_days}d old (rotate recommended)")
+ except Exception:
+ pass
+os.makedirs(os.path.dirname(warn_path), exist_ok=True)
+if warnings:
+ out = {"checked_at": now.isoformat(), "warnings": warnings}
+ tmp = warn_path + ".tmp." + str(os.getpid())
+ json.dump(out, open(tmp, "w"), indent=2)
+ os.replace(tmp, warn_path)
+else:
+ if os.path.exists(warn_path):
+ os.remove(warn_path)
+PY
+
+ # Dispatch notifications (dedup per credential-line per day)
+ local notify_script="$SCRIPT_DIR/scripts/ops-notify.sh"
+ local dedup_dir="$DATA_DIR/cache/.cred_notify_sent"
+ mkdir -p "$dedup_dir" 2>/dev/null || true
+ if [[ -f "$warn_file" ]] && [[ -f "$notify_script" ]]; then
+ local today
+ today=$(date -u +%Y-%m-%d)
+ while IFS= read -r line; do
+ [[ -n "$line" ]] || continue
+ local dedup_key
+ dedup_key=$(printf '%s' "$line" | python3 -c "import sys,re;print(re.sub(r'[^a-zA-Z0-9_-]+','_',sys.stdin.read().strip())[:80])" 2>/dev/null || echo "unknown")
+ local sent_marker="$dedup_dir/${today}_${dedup_key}"
+ if [[ ! -f "$sent_marker" ]]; then
+ bash "$notify_script" MEDIUM "ops-daemon: credential expiry" "$line" >/dev/null 2>&1 &
+ touch "$sent_marker"
+ fi
+ done < <(python3 -c "
+import json
+try:
+ d = json.load(open('$warn_file'))
+ for w in d.get('warnings', []):
+ print(w)
+except Exception:
+ pass
+" 2>/dev/null)
+ fi
+
+ date +%s > "$LAST_CHECK"
+}
+
# ── Daemon registration (cross-OS) ────────────────────────────────────────
# On macOS we load a launchd agent; on Linux a systemd --user unit + timer;
# on Windows a Task Scheduler (schtasks) entry. Each path is best-effort and
@@ -1303,13 +1648,18 @@ while true; do
ensure_all_services # Every 5 min: verify all launchd/systemd services
# ── Intelligence pass (smart brain) ──────────────────────────────────────
- # These run with their own internal throttles — safe to call every loop
- prefetch_briefing_cache # Every 5 min: WA/email/PR counts for ops-go
+ # Parallel warm — all prefetch fns run concurrently via _run_parallel_warm
+ # (Phase 16). detect_urgent_messages + trigger_smart_memory_extraction keep
+ # their own internal throttles and run inline (not warm-parallel).
+ _run_parallel_warm # prefetch_briefing_cache + prefetch_calendar
+ # + prefetch_project_health + build_contact_activity_index
+ # + prefetch_marketing_cache (all parallel)
detect_urgent_messages # Every 5 min: keyword scan for time-sensitive msgs
trigger_smart_memory_extraction # Every 10 min: haiku extraction if new msgs arrived
- build_contact_activity_index # Every 15 min: cross-channel contact scoring
- prefetch_calendar # Every 15 min: today's meetings for context
- prefetch_project_health # Every 10 min: git/branch status per registered repo
+
+ # ── Phase 16: infrastructure hardening ───────────────────────────────────
+ check_rate_limits # Every 5 min: reset rollover windows + warnings
+ check_credential_expiry # Hourly: offline check of *_expires_at / *_created_at
write_daemon_health
diff --git a/claude-ops/scripts/ops-install-git-hooks.sh b/claude-ops/scripts/ops-install-git-hooks.sh
new file mode 100755
index 00000000..7b9a73dc
--- /dev/null
+++ b/claude-ops/scripts/ops-install-git-hooks.sh
@@ -0,0 +1,194 @@
+#!/usr/bin/env bash
+# ops-install-git-hooks.sh — installs post-commit/post-merge invalidation
+# hooks into every repo registered in scripts/registry.json. The hooks
+# remove stale cache timestamp files so the next daemon warm cycle refreshes
+# only those specific caches, without waiting for the normal throttle window.
+#
+# Phase 16 INFR-02: smart cache invalidation.
+#
+# Usage:
+# ops-install-git-hooks.sh # install/update hooks in all registered repos
+# ops-install-git-hooks.sh --dry-run # show what would change, write nothing
+# ops-install-git-hooks.sh --uninstall # remove only the guarded block, keep the rest
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REGISTRY="$SCRIPT_DIR/registry.json"
+
+MODE="install"
+for arg in "$@"; do
+ case "$arg" in
+ --dry-run) MODE="dry-run" ;;
+ --uninstall) MODE="uninstall" ;;
+ -h|--help)
+ echo "Usage: $0 [--dry-run|--uninstall]"
+ exit 0
+ ;;
+ esac
+done
+
+if [[ ! -f "$REGISTRY" ]]; then
+ echo "registry.json not found at $REGISTRY" >&2
+ exit 0
+fi
+
+# Extract repo paths from registry.json (supports both top-level
+# projects[].paths[] and the simpler {path: ...} shape).
+mapfile -t REPO_PATHS < <(python3 - "$REGISTRY" <<'PY'
+import json, sys, os
+try:
+ data = json.load(open(sys.argv[1]))
+except Exception:
+ sys.exit(0)
+
+def _paths_from(item):
+ out = []
+ if not isinstance(item, dict):
+ return out
+ if isinstance(item.get("paths"), list):
+ out.extend([p for p in item["paths"] if isinstance(p, str)])
+ if isinstance(item.get("path"), str):
+ out.append(item["path"])
+ return out
+
+paths = []
+if isinstance(data, dict):
+ if isinstance(data.get("projects"), list):
+ for item in data["projects"]:
+ paths.extend(_paths_from(item))
+ elif isinstance(data.get("projects"), dict):
+ for _, v in data["projects"].items():
+ paths.extend(_paths_from(v))
+ else:
+ paths.extend(_paths_from(data))
+elif isinstance(data, list):
+ for item in data:
+ paths.extend(_paths_from(item))
+
+seen = set()
+for p in paths:
+ expanded = os.path.expanduser(p)
+ if expanded in seen: continue
+ seen.add(expanded)
+ print(expanded)
+PY
+)
+
+BEGIN_MARK="# BEGIN ops-daemon-invalidate"
+END_MARK="# END ops-daemon-invalidate"
+
+HOOK_BODY=$(cat <<'HOOK'
+# Invalidate ops-daemon caches so the next warm pass regenerates them fresh.
+STALE_TS=(
+ "$HOME/.claude/plugins/data/ops-ops-marketplace/cache/.briefing_ts"
+ "$HOME/.claude/plugins/data/ops-ops-marketplace/cache/.projects_ts"
+ "$HOME/.claude/plugins/data/ops-ops-marketplace/cache/.marketing_ts"
+ "$HOME/.claude/plugins/data/ops-ops-marketplace/cache/.prs_ts"
+ "$HOME/.claude/plugins/data/ops-ops-marketplace/cache/.ci_ts"
+)
+for _f in "${STALE_TS[@]}"; do
+ rm -f "$_f" 2>/dev/null || true
+done
+HOOK
+)
+
+_write_hook() {
+ local hook_file="$1" mode="$2"
+ local new_block
+ new_block=$(printf '%s\n%s\n%s' "$BEGIN_MARK" "$HOOK_BODY" "$END_MARK")
+
+ if [[ "$mode" == "uninstall" ]]; then
+ [[ -f "$hook_file" ]] || { echo "skip"; return 0; }
+ python3 - "$hook_file" "$BEGIN_MARK" "$END_MARK" <<'PY'
+import re, sys
+path, begin, end = sys.argv[1], sys.argv[2], sys.argv[3]
+content = open(path).read()
+content = re.sub(
+ re.escape(begin) + r'.*?' + re.escape(end) + r'\n?',
+ '',
+ content,
+ flags=re.DOTALL,
+)
+open(path, 'w').write(content)
+PY
+ echo "uninstalled"
+ return 0
+ fi
+
+ if [[ ! -f "$hook_file" ]]; then
+ if [[ "$mode" == "dry-run" ]]; then echo "would-create"; return 0; fi
+ {
+ printf '#!/usr/bin/env bash\n'
+ printf '%s\n' "$new_block"
+ } > "$hook_file"
+ chmod +x "$hook_file"
+ echo "installed"
+ return 0
+ fi
+
+ if grep -q "$BEGIN_MARK" "$hook_file" 2>/dev/null; then
+ if [[ "$mode" == "dry-run" ]]; then echo "would-update"; return 0; fi
+ python3 - "$hook_file" "$BEGIN_MARK" "$END_MARK" "$new_block" <<'PY'
+import re, sys
+path, begin, end, block = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
+content = open(path).read()
+content = re.sub(
+ re.escape(begin) + r'.*?' + re.escape(end),
+ block,
+ content,
+ flags=re.DOTALL,
+)
+open(path, 'w').write(content)
+PY
+ echo "updated"
+ return 0
+ fi
+
+ if [[ "$mode" == "dry-run" ]]; then echo "would-append"; return 0; fi
+ {
+ printf '\n'
+ printf '%s\n' "$new_block"
+ } >> "$hook_file"
+ chmod +x "$hook_file" 2>/dev/null || true
+ echo "appended"
+}
+
+installed=0
+updated=0
+appended=0
+skipped=0
+uninstalled=0
+
+if [[ "${#REPO_PATHS[@]}" -eq 0 ]]; then
+ echo "No repos with path fields in $REGISTRY — nothing to do."
+ exit 0
+fi
+
+for repo in "${REPO_PATHS[@]}"; do
+ if [[ ! -d "$repo/.git/hooks" ]]; then
+ skipped=$((skipped+1))
+ echo " $repo: skip (no .git/hooks)"
+ continue
+ fi
+ for hook_name in post-commit post-merge; do
+ hook_file="$repo/.git/hooks/$hook_name"
+ result=$(_write_hook "$hook_file" "$MODE")
+ case "$result" in
+ installed) installed=$((installed+1)) ;;
+ updated) updated=$((updated+1)) ;;
+ appended) appended=$((appended+1)) ;;
+ uninstalled) uninstalled=$((uninstalled+1)) ;;
+ esac
+ echo " $repo/.git/hooks/$hook_name: $result"
+ done
+done
+
+echo ""
+if [[ "$MODE" == "uninstall" ]]; then
+ echo "Summary: uninstalled=$uninstalled"
+elif [[ "$MODE" == "dry-run" ]]; then
+ echo "Summary (dry-run): previewed ${#REPO_PATHS[@]} repos"
+else
+ echo "Summary: installed=$installed updated=$updated appended=$appended skipped=$skipped"
+fi
diff --git a/claude-ops/skills/ops-daemon/SKILL.md b/claude-ops/skills/ops-daemon/SKILL.md
index 94b40100..df841cd1 100644
--- a/claude-ops/skills/ops-daemon/SKILL.md
+++ b/claude-ops/skills/ops-daemon/SKILL.md
@@ -52,20 +52,86 @@ Accepts `--plugin-root PATH` to override auto-detection and `--dry-run` to previ
"uptime_seconds": <int>,
"services": {
"<name>": {
- "status": "running|polling|scheduled|dead|needs_reauth",
+ "status": "running|polling|scheduled|dead|needs_reauth|max_restarts_exceeded",
"pid": <int|null>,
"last_health": "<string|null>",
"last_run": "<ISO-8601|empty>",
"next_run": "<ISO-8601|empty>",
- "restarts": <int>
+ "restarts": <int>,
+ "latency_ms": <int>,
+ "last_success": "<ISO-8601|empty>",
+ "error_count": <int>,
+ "last_error": "<string|null>"
}
},
- "action_needed": null | {"kind": "...", "service": "...", "message": "..."}
+ "action_needed": null | {"kind": "...", "service": "...", "message": "..."},
+ "credential_warnings": ["<string>", ...],
+ "rate_limit_warnings": ["<string>", ...]
}
```
A healthy daemon refreshes this file every 30s. An `mtime` older than 120s is a strong fail signal.
+**Per-service fields (Phase 16 additions):**
+
+- `latency_ms` — duration of the most recent run for warm/cron services, in milliseconds. 0 when no run has occurred yet.
+- `last_success` — ISO-8601 UTC of the last clean run (no errors). Empty until the first success.
+- `error_count` — cumulative error count since daemon start. Reset on daemon restart.
+- `last_error` — truncated (≤300 chars) message from the most recent failure. `null` when there have been no failures.
+
+**Top-level fields (Phase 16 additions):**
+
+- `credential_warnings` — list of credentials that are expiring within 7 days or are keys older than 180 days. Populated from offline inspection of `preferences.json` (never a live API call).
+- `rate_limit_warnings` — list of integrations currently at ≥80% of their quota window. Populated from `rate-limits.json` counters.
+
+**Persistent service failure:** a service that hits `max_restarts_exceeded` status dispatches a one-shot `HIGH` severity push notification via `ops-notify.sh` to every configured sink (Telegram / Discord / ntfy / Pushover / macOS). The notification is re-armed the moment the service returns to `running`, so subsequent regressions still notify.
+
+### Smart Cache Invalidation (git hooks)
+
+Cache timestamp files (`.briefing_ts`, `.projects_ts`, `.marketing_ts`, `.prs_ts`, `.ci_ts`) are deleted on local `git commit` and `git merge` so the next daemon warm cycle refreshes those specific caches without waiting for the normal throttle window.
+
+Install:
+
+ bash ${CLAUDE_PLUGIN_ROOT}/scripts/ops-install-git-hooks.sh
+
+Preview without writing:
+
+ bash ${CLAUDE_PLUGIN_ROOT}/scripts/ops-install-git-hooks.sh --dry-run
+
+Remove:
+
+ bash ${CLAUDE_PLUGIN_ROOT}/scripts/ops-install-git-hooks.sh --uninstall
+
+The installer is idempotent and only touches the block between `# BEGIN ops-daemon-invalidate` and `# END ops-daemon-invalidate` — existing husky / lefthook / pre-commit content in `.git/hooks/post-commit` or `.git/hooks/post-merge` is preserved.
+
+### Marketing Pre-Warm
+
+The opt-in `marketing-prewarm` cron service pre-fetches cross-platform marketing data (Klaviyo, Meta Ads, GA4, GSC, Google Ads) every 15 minutes so `/ops:marketing` loads instantly from cache. Disabled by default; enable with `/ops:setup marketing` once marketing credentials are configured.
+
+### Rate Limit Tracking
+
+Per-integration counters in `${CLAUDE_PLUGIN_DATA_DIR}/rate-limits.json` — `{quota, calls, window_start, warned_80pct}` per integration. On each tracked API call the daemon advances the rolling window, increments the counter, and sends a single `MEDIUM` push notification when the ratio crosses 80%. Windows reset automatically on rollover, which re-arms the 80% warning.
+
+Override the seeded defaults by setting `rate_limit_quotas` in `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json`:
+
+```json
+{
+ "rate_limit_quotas": {
+ "meta_ads": {"quota": 200, "window_seconds": 3600},
+ "klaviyo": {"quota": 75, "window_seconds": 60}
+ }
+}
+```
+
+### Credential Rotation Alerts
+
+The daemon checks `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` once an hour for:
+
+- `<integration>_expires_at` — ISO-8601 timestamp or the literal string `"never"`. Warns when within 7 days of expiry.
+- `<integration>_created_at` — ISO-8601 timestamp of when an API key was last created/rotated. Warns once the key is 180 days old.
+
+The check is **entirely offline** — it never makes a network call. Warnings surface in `daemon-health.json` as `credential_warnings` and trigger a `MEDIUM` push notification once per `(credential, day)` tuple. `/ops:fires` lists them alongside Sentry / infra / CI issues.
+
---
## Your task
diff --git a/claude-ops/skills/ops-fires/SKILL.md b/claude-ops/skills/ops-fires/SKILL.md
index fe105b19..366859fc 100644
--- a/claude-ops/skills/ops-fires/SKILL.md
+++ b/claude-ops/skills/ops-fires/SKILL.md
@@ -225,3 +225,16 @@ When diagnosing fires, use `WebFetch` to check AWS status page (`https://health.
### WebSearch — known outage patterns
Use `WebSearch` to find if the error pattern matches a known AWS/infrastructure issue (e.g., "ECS task stopped CannotPullContainerError" → known ECR throttling).
+
+
+---
+
+## Credential Expiry & Rate Limit Warnings (Phase 16)
+
+The ops-daemon surfaces two additional fire categories in `daemon-health.json`:
+
+- `credential_warnings` — tokens/keys expiring within 7 days OR API keys older than 180 days. Fed by offline inspection of `preferences.json` (`*_expires_at`, `*_created_at` fields). No live API calls are made to validate credentials.
+- `rate_limit_warnings` — integrations currently at ≥80% of their quota window. Fed by counters in `rate-limits.json`. Resets automatically when the window rolls over.
+
+`/ops:fires` lists both alongside Sentry / infra / CI issues. Push notifications are dispatched by the daemon on the first crossing of the threshold — not re-sent until the next day (credentials) or window rollover (rate limits).
+