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(ops:marketing): self-healing autopilot — Meta token refresh, GAds OAuth health, multi-sink notify, account-status check, health-check daemon (#263)

Aurora Capital7cee50c01ab7
diff --git a/claude-ops/bin/ops-marketing-autopilot b/claude-ops/bin/ops-marketing-autopilot
index c1dbfaec..7ccd9878 100755
--- a/claude-ops/bin/ops-marketing-autopilot
+++ b/claude-ops/bin/ops-marketing-autopilot
@@ -65,12 +65,14 @@ ONLY_PROJECT=""
ONLY_CHANNEL=""
DO_ONBOARD=0
ONBOARD_URL=""
+DO_HEALTH_CHECK=0
while [ $# -gt 0 ]; do
case "$1" in
- --dry-run) DRY_RUN=1 ;;
- --project) ONLY_PROJECT="${2:-}"; shift ;;
- --channel) ONLY_CHANNEL="${2:-}"; shift ;;
- --onboard) DO_ONBOARD=1 ;;
+ --dry-run) DRY_RUN=1 ;;
+ --project) ONLY_PROJECT="${2:-}"; shift ;;
+ --channel) ONLY_CHANNEL="${2:-}"; shift ;;
+ --onboard) DO_ONBOARD=1 ;;
+ --health-check) DO_HEALTH_CHECK=1 ;;
onboard)
DO_ONBOARD=1
if [ -n "${2:-}" ] && [[ "${2:-}" != --* ]]; then
@@ -109,6 +111,14 @@ chan_cred() {
resolve_cred "$(jq -r --arg p "$1" --arg c "$2" --arg f "$3" \
'.marketing.projects[$p][$c][$f] // empty' "$PREFS" 2>/dev/null)"
}
+chan_cred_strict() {
+ # Like chan_cred but propagates resolve_cred_strict rc (0=ok, 1=not-configured, 2=broken)
+ [ -f "$PREFS" ] || return 1
+ local ref
+ ref="$(jq -r --arg p "$1" --arg c "$2" --arg f "$3" \
+ '.marketing.projects[$p][$c][$f] // empty' "$PREFS" 2>/dev/null)"
+ resolve_cred_strict "$ref"
+}
# ── Report + escalation ───────────────────────────────────────────────────────
REPORT=""
@@ -459,25 +469,179 @@ meta_proof() {
}
meta_get() {
# $1 = path?query (no host). Appends auth + proof.
- local q="$1" sep="?"
+ # Handles rc=190 (token expired) and rc=17/4 (rate limit with backoff).
+ local q="$1" sep="?" proj="${2:-${_META_CURRENT_PROJ:-}}"
case "$q" in *\?*) sep="&";; esac
local url="${GRAPH}/${q}${sep}access_token=${META_TOKEN}"
[ -n "$META_PROOF" ] && url="${url}&appsecret_proof=${META_PROOF}"
- curl -gsS --max-time 12 "$url" 2>/dev/null || echo '{}'
+
+ local resp attempt delay
+ delay=1
+ for attempt in 1 2 3; do
+ resp="$(curl -gsS --max-time 12 "$url" 2>/dev/null || echo '{}')"
+ local err_code
+ err_code="$(printf '%s' "$resp" | jq -r '.error.code // empty' 2>/dev/null || true)"
+ case "$err_code" in
+ 190)
+ # Token expired / invalidated — attempt long-lived refresh
+ if [ -n "$proj" ] && meta_refresh_token "$proj"; then
+ # Update url with new token + proof
+ url="${GRAPH}/${q}${sep}access_token=${META_TOKEN}"
+ [ -n "$META_PROOF" ] && url="${url}&appsecret_proof=${META_PROOF}"
+ resp="$(curl -gsS --max-time 12 "$url" 2>/dev/null || echo '{}')"
+ # If still error 190 after refresh, escalate
+ local err2; err2="$(printf '%s' "$resp" | jq -r '.error.code // empty' 2>/dev/null || true)"
+ if [ "$err2" = "190" ]; then
+ escalate "$proj" "Meta token expired and refresh failed — manual rotation needed"
+ printf '{}'
+ return 0
+ fi
+ else
+ escalate "${proj:-unknown}" "Meta token expired (code 190) and no app_id/app_secret for auto-refresh — manual rotation needed"
+ printf '{}'
+ return 0
+ fi
+ ;;
+ 17|4)
+ # Rate limit — exponential backoff up to 3 retries
+ if [ "$attempt" -lt 3 ]; then
+ log "meta_get: rate limit (code ${err_code}), backoff ${delay}s (attempt ${attempt}/3)"
+ sleep "$delay"
+ delay=$((delay * 4))
+ continue
+ else
+ escalate "${proj:-unknown}" "Meta API rate limit (code ${err_code}) — 3 retries exhausted"
+ printf '{}'
+ return 0
+ fi
+ ;;
+ "") : ;; # no error code — success or unrelated
+ esac
+ break
+ done
+ printf '%s' "$resp"
}
-process_meta() {
+meta_refresh_token() {
+ # Attempt to exchange current META_TOKEN for a new long-lived token.
+ # Requires META_${PROJECT^^}_APP_ID and META_${PROJECT^^}_APP_SECRET in env/Doppler.
+ # On success: updates META_TOKEN in-memory, writes new token to Doppler, returns 0.
+ # On failure: returns 1 (caller should escalate).
local proj="$1"
- META_TOKEN="$(chan_cred "$proj" meta access_token)"
- local acct app_secret
- acct="$(chan_cred "$proj" meta ad_account_id)"
+ local proj_upper; proj_upper="$(printf '%s' "$proj" | tr '[:lower:]' '[:upper:]' | tr '-' '_')"
+
+ local app_id app_secret _env_id_name _env_sec_name
+ app_id="$(chan_cred "$proj" meta app_id)"
app_secret="$(chan_cred "$proj" meta app_secret)"
- if [ -z "$META_TOKEN" ] || [ -z "$acct" ]; then
+ # Fallback to env vars META_<PROJECT>_APP_ID / META_<PROJECT>_APP_SECRET
+ if [ -z "$app_id" ]; then
+ _env_id_name="META_${proj_upper}_APP_ID"
+ app_id="${!_env_id_name:-}"
+ fi
+ if [ -z "$app_secret" ]; then
+ _env_sec_name="META_${proj_upper}_APP_SECRET"
+ app_secret="${!_env_sec_name:-}"
+ fi
+
+ if [ -z "$app_id" ] || [ -z "$app_secret" ]; then
+ log "meta_refresh_token: missing app_id or app_secret for $proj — cannot auto-refresh"
+ return 1
+ fi
+
+ local refresh_resp new_token
+ refresh_resp="$(curl -gsS --max-time 15 \
+ "https://graph.facebook.com/v20.0/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${META_TOKEN}" \
+ 2>/dev/null || echo '{}')"
+ new_token="$(printf '%s' "$refresh_resp" | jq -r '.access_token // empty' 2>/dev/null || true)"
+
+ if [ -z "$new_token" ]; then
+ local err_msg; err_msg="$(printf '%s' "$refresh_resp" | jq -r '.error.message // "unknown error"' 2>/dev/null || echo 'unknown')"
+ log "meta_refresh_token: refresh failed for $proj — $err_msg"
+ return 1
+ fi
+
+ # Write new token to Doppler (best-effort, non-fatal)
+ local doppler_ref
+ doppler_ref="$(jq -r --arg p "$proj" '.marketing.projects[$p].meta.access_token // empty' "$PREFS" 2>/dev/null || true)"
+ if [[ "$doppler_ref" == doppler:* ]]; then
+ local dpath="${doppler_ref#doppler:}"
+ local dproj="${dpath%%/*}"
+ local drest="${dpath#*/}"; local dcfg="${drest%%/*}"; local dsecret="${drest#*/}"
+ if [ -n "$dproj" ] && [ -n "$dcfg" ] && [ -n "$dsecret" ]; then
+ if [ "$DRY_RUN" = "1" ]; then
+ log "[DRY] would write refreshed Meta token to Doppler ${dproj}/${dcfg}/${dsecret}"
+ else
+ printf '%s' "$new_token" | doppler secrets set "$dsecret" --project "$dproj" --config "$dcfg" --no-interactive 2>/dev/null || \
+ log "meta_refresh_token: Doppler write failed for $proj (non-fatal)"
+ fi
+ fi
+ fi
+
+ # Update in-memory token + proof
+ META_TOKEN="$new_token"
+ local app_sec_for_proof; app_sec_for_proof="$(chan_cred "$proj" meta app_secret)"
+ META_PROOF="$(meta_proof "$META_TOKEN" "$app_sec_for_proof")"
+ log "auto-refreshed Meta token for $proj"
+ report "- [token] Meta access token auto-refreshed for $proj"
+ return 0
+}
+
+meta_account_health() {
+ # Check Meta ad account status once per pass. Escalates on non-active states.
+ local proj="$1" acct="$2"
+ local health_resp
+ health_resp="$(meta_get "${acct}?fields=account_status,disable_reason,balance,spend_cap" "$proj")"
+ local status; status="$(printf '%s' "$health_resp" | jq -r '.account_status // empty' 2>/dev/null || true)"
+ [ -z "$status" ] && return 0 # field not returned — skip
+ case "$status" in
+ 1) report "- meta account health: active" ;;
+ 2) escalate "$proj" "Meta ad account disabled (account_status=2, disable_reason=$(printf '%s' "$health_resp" | jq -r '.disable_reason // "unknown"' 2>/dev/null))" ;;
+ 3) escalate "$proj" "Meta ad account unsettled (account_status=3) — outstanding balance" ;;
+ 7) escalate "$proj" "Meta ad account pending review (account_status=7)" ;;
+ 8) report "- meta account health: in grace period (account_status=8)" ;;
+ 9) escalate "$proj" "Meta ad account pending closure (account_status=9)" ;;
+ *) escalate "$proj" "Meta ad account in unexpected state (account_status=${status})" ;;
+ esac
+}
+
+process_meta() {
+ local proj="$1"
+ _META_CURRENT_PROJ="$proj"
+ export _META_CURRENT_PROJ
+
+ # Strict credential resolution — distinguish not-configured vs declared-but-empty
+ local _tok_ref _acct_ref
+ _tok_ref="$(jq -r --arg p "$proj" '.marketing.projects[$p].meta.access_token // empty' "$PREFS" 2>/dev/null)"
+ _acct_ref="$(jq -r --arg p "$proj" '.marketing.projects[$p].meta.ad_account_id // empty' "$PREFS" 2>/dev/null)"
+
+ local _tok_val _acct_val _tok_rc _acct_rc
+ _tok_val="$(resolve_cred_strict "$_tok_ref")"; _tok_rc=$?
+ _acct_val="$(resolve_cred_strict "$_acct_ref")"; _acct_rc=$?
+
+ if [ "$_tok_rc" = "1" ] || [ "$_acct_rc" = "1" ]; then
report "- meta: not configured (missing access_token/ad_account_id) — skipped"
return 0
fi
+ if [ "$_tok_rc" = "2" ]; then
+ escalate "$proj" "Doppler ref declared but empty: meta.access_token ($( jq -r --arg p "$proj" '.marketing.projects[$p].meta.access_token' "$PREFS" 2>/dev/null))"
+ return 0
+ fi
+ if [ "$_acct_rc" = "2" ]; then
+ escalate "$proj" "Doppler ref declared but empty: meta.ad_account_id ($( jq -r --arg p "$proj" '.marketing.projects[$p].meta.ad_account_id' "$PREFS" 2>/dev/null))"
+ return 0
+ fi
+
+ META_TOKEN="$_tok_val"
+ local acct app_secret
+ acct="$_acct_val"
+ app_secret="$(chan_cred "$proj" meta app_secret)"
META_PROOF="$(meta_proof "$META_TOKEN" "$app_secret")"
+ # Account health check (status, disabled, unsettled, etc.)
+ meta_account_health "$proj" "$acct"
+ # If escalated by account health, abort Meta pass
+ [ "$ESCALATED" = "1" ] && return 0
+
local cap; cap="$(ap_get "$proj" '.daily_spend_cap_usd')"
local cpl_mult ctr_floor min_live
cpl_mult="$(ap_get "$proj" '.pause_cpl_multiple')"; cpl_mult="${cpl_mult:-2.0}"
@@ -661,14 +825,48 @@ process_google_ads() {
fi
local cap; cap="$(ap_get "$proj" '.daily_spend_cap_usd')"
- local access
- access="$(curl -gsS --max-time 8 -X POST https://oauth2.googleapis.com/token \
+
+ # Strict credential check for declared-but-empty Doppler refs
+ local _ref_dev _ref_refresh _ref_cid
+ _ref_dev="$(jq -r --arg p "$proj" '.marketing.projects[$p].google_ads.developer_token // empty' "$PREFS" 2>/dev/null)"
+ _ref_refresh="$(jq -r --arg p "$proj" '.marketing.projects[$p].google_ads.refresh_token // empty' "$PREFS" 2>/dev/null)"
+ _ref_cid="$(jq -r --arg p "$proj" '.marketing.projects[$p].google_ads.customer_id // empty' "$PREFS" 2>/dev/null)"
+ local _rc
+ resolve_cred_strict "$_ref_dev" >/dev/null; _rc=$?; [ "$_rc" = "2" ] && { escalate "$proj" "Doppler ref declared but empty: google_ads.developer_token ($_ref_dev)"; return 0; }
+ resolve_cred_strict "$_ref_refresh" >/dev/null; _rc=$?; [ "$_rc" = "2" ] && { escalate "$proj" "Doppler ref declared but empty: google_ads.refresh_token ($_ref_refresh)"; return 0; }
+ resolve_cred_strict "$_ref_cid" >/dev/null; _rc=$?; [ "$_rc" = "2" ] && { escalate "$proj" "Doppler ref declared but empty: google_ads.customer_id ($_ref_cid)"; return 0; }
+
+ local token_resp access gads_err_desc
+ token_resp="$(curl -gsS --max-time 8 -X POST https://oauth2.googleapis.com/token \
--data "client_id=${client_id}&client_secret=${client_secret}&refresh_token=${refresh}&grant_type=refresh_token" \
- 2>/dev/null | jq -r '.access_token // empty')"
+ 2>/dev/null || echo '{}')"
+ access="$(printf '%s' "$token_resp" | jq -r '.access_token // empty' 2>/dev/null)"
+ gads_err_desc="$(printf '%s' "$token_resp" | jq -r '.error // empty' 2>/dev/null)"
+
if [ -z "$access" ]; then
- report "- google_ads: token refresh failed — skipped"
+ local gads_last_ok="${STATE_DIR}/${proj}-google.last_ok"
+ local now_ts; now_ts="$(date +%s)"
+ if [ "$gads_err_desc" = "invalid_grant" ]; then
+ escalate "$proj" "Google Ads OAuth refresh token revoked (invalid_grant) — user must re-authorize"
+ return 0
+ fi
+ # Record outage start time if not already set
+ if [ ! -f "$gads_last_ok" ]; then
+ [ "$DRY_RUN" = "0" ] && printf '%s' "$now_ts" > "$gads_last_ok"
+ else
+ local last_ok_ts; last_ok_ts="$(cat "$gads_last_ok" 2>/dev/null || echo "$now_ts")"
+ local outage_secs; outage_secs=$((now_ts - last_ok_ts))
+ if [ "$outage_secs" -gt 172800 ]; then # 48h
+ escalate "$proj" "Google Ads OAuth outage > 48h for $proj (error: ${gads_err_desc:-unknown}) — token refresh failing"
+ return 0
+ fi
+ fi
+ report "- google_ads: token refresh failed (${gads_err_desc:-unknown}) — skipped"
return 0
fi
+
+ # Token refreshed OK — update last_ok timestamp
+ [ "$DRY_RUN" = "0" ] && date +%s > "${STATE_DIR}/${proj}-google.last_ok"
local H=(-H "Content-Type: application/json" -H "Authorization: Bearer ${access}" -H "developer-token: ${dev}")
[ -n "$login" ] && H+=(-H "login-customer-id: ${login}")
local API="https://googleads.googleapis.com/v23/customers/${cid}"
@@ -1623,22 +1821,244 @@ Return ONLY the JSON, no other text."
done < <(printf '%s' "$strategy" | jq -c '.campaign_scaffold[]? // empty' 2>/dev/null || true)
}
-# ── Optional notify (Rule 6: report file always; notify only if sink set) ─────
+# ── Multi-sink notify (Rule 6: report file always) ────────────────────────────
+# Reads marketing.notify.sinks (array of {type, ref}) from prefs.
+# On ESCALATED=1, ALL configured sinks fire — not optional.
+# Legacy fallback: per-project autopilot.notify_sink=telegram still works.
+#
+# Sink types: telegram | slack | email (Resend) | whatsapp
notify() {
- local proj="$1" sink
- sink="$(ap_get "$proj" '.notify_sink')"
- [ -z "$sink" ] || [ "$sink" = "null" ] && return 0
- local tg_tok tg_chat
- tg_tok="${TELEGRAM_BOT_TOKEN:-$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)}"
- tg_chat="${TELEGRAM_CHAT_ID:-$(doppler secrets get TELEGRAM_CHAT_ID --plain 2>/dev/null || true)}"
- [ "$sink" = "telegram" ] && [ -n "$tg_tok" ] && [ -n "$tg_chat" ] || return 0
+ local proj="$1"
local txt
txt="$(printf '*autopilot — %s — %s*\nmutations: %s escalated: %s\nreport: %s' \
"$proj" "$TODAY" "$MUTATIONS" "$ESCALATED" "$REPORT")"
- curl -s --max-time 12 -X POST "https://api.telegram.org/bot${tg_tok}/sendMessage" \
- -H 'Content-Type: application/json' \
- -d "$(jq -n --arg c "$tg_chat" --arg t "$txt" '{chat_id:$c,text:$t,parse_mode:"Markdown"}')" \
- >/dev/null 2>&1 || true
+
+ # Build effective sinks: global marketing.notify.sinks + legacy per-project fallback
+ local sinks_json
+ sinks_json="$(jq -c '.marketing.notify.sinks // []' "$PREFS" 2>/dev/null || echo '[]')"
+
+ # Legacy per-project fallback
+ local legacy_sink; legacy_sink="$(ap_get "$proj" '.notify_sink')"
+ if [ -n "$legacy_sink" ] && [ "$legacy_sink" != "null" ]; then
+ # Only add legacy if not already covered by global sinks
+ local already; already="$(printf '%s' "$sinks_json" | jq --arg t "$legacy_sink" '[.[] | select(.type==$t)] | length' 2>/dev/null || echo 0)"
+ if [ "$already" = "0" ]; then
+ sinks_json="$(printf '%s' "$sinks_json" | jq --arg t "$legacy_sink" '. + [{"type":$t,"ref":""}]' 2>/dev/null || echo '[]')"
+ fi
+ fi
+
+ local num_sinks; num_sinks="$(printf '%s' "$sinks_json" | jq 'length' 2>/dev/null || echo 0)"
+ [ "$num_sinks" = "0" ] && return 0
+
+ # For non-escalated passes, only notify if escalated or sinks configured
+ # (escalated=1 forces ALL sinks; escalated=0 still fires for summary)
+ local i=0
+ while [ "$i" -lt "$num_sinks" ]; do
+ local sink_type sink_ref
+ sink_type="$(printf '%s' "$sinks_json" | jq -r ".[$i].type // empty" 2>/dev/null)"
+ sink_ref="$(printf '%s' "$sinks_json" | jq -r ".[$i].ref // empty" 2>/dev/null)"
+ i=$((i+1))
+ [ -z "$sink_type" ] && continue
+ case "$sink_type" in
+ telegram)
+ local tg_tok tg_chat
+ tg_tok="$(resolve_cred "${sink_ref:-env:TELEGRAM_BOT_TOKEN}")"
+ [ -z "$tg_tok" ] && tg_tok="${TELEGRAM_BOT_TOKEN:-$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)}"
+ local tg_chat_ref; tg_chat_ref="$(printf '%s' "$sinks_json" | jq -r ".[$((i-1))].chat_ref // empty" 2>/dev/null)"
+ tg_chat="$(resolve_cred "${tg_chat_ref:-env:TELEGRAM_CHAT_ID}")"
+ [ -z "$tg_chat" ] && tg_chat="${TELEGRAM_CHAT_ID:-$(doppler secrets get TELEGRAM_CHAT_ID --plain 2>/dev/null || true)}"
+ [ -n "$tg_tok" ] && [ -n "$tg_chat" ] || continue
+ curl -s --max-time 12 -X POST "https://api.telegram.org/bot${tg_tok}/sendMessage" \
+ -H 'Content-Type: application/json' \
+ -d "$(jq -n --arg c "$tg_chat" --arg t "$txt" '{chat_id:$c,text:$t,parse_mode:"Markdown"}')" \
+ >/dev/null 2>&1 || true
+ ;;
+ slack)
+ local slack_url; slack_url="$(resolve_cred "$sink_ref")"
+ [ -n "$slack_url" ] || continue
+ curl -s --max-time 12 -X POST "$slack_url" \
+ -H 'Content-Type: application/json' \
+ -d "$(jq -n --arg t "$txt" '{text:$t}')" \
+ >/dev/null 2>&1 || true
+ ;;
+ email)
+ local resend_key; resend_key="$(resolve_cred "$sink_ref")"
+ [ -z "$resend_key" ] && resend_key="${RESEND_API_KEY:-$(doppler secrets get RESEND_API_KEY --plain 2>/dev/null || true)}"
+ [ -n "$resend_key" ] || continue
+ local email_to; email_to="$(printf '%s' "$sinks_json" | jq -r ".[$((i-1))].to // empty" 2>/dev/null)"
+ [ -z "$email_to" ] && continue
+ local email_from; email_from="$(printf '%s' "$sinks_json" | jq -r ".[$((i-1))].from // \"[email protected]\"" 2>/dev/null)"
+ curl -s --max-time 12 -X POST "https://api.resend.com/emails" \
+ -H "Authorization: Bearer ${resend_key}" \
+ -H 'Content-Type: application/json' \
+ -d "$(jq -n --arg to "$email_to" --arg from "$email_from" \
+ --arg sub "autopilot — ${proj} — ${TODAY}" --arg body "$txt" \
+ '{from:$from,to:[$to],subject:$sub,text:$body}')" \
+ >/dev/null 2>&1 || true
+ ;;
+ whatsapp)
+ # Send via mcp__whatsapp if available in environment (Claude context only)
+ # In daemon context this is a no-op — skip silently
+ local wa_to; wa_to="$(printf '%s' "$sinks_json" | jq -r ".[$((i-1))].to // empty" 2>/dev/null)"
+ [ -n "$wa_to" ] || continue
+ # Best-effort: wacli send if available
+ if command -v wacli >/dev/null 2>&1; then
+ wacli send --to "$wa_to" --message "$txt" 2>/dev/null || true
+ fi
+ ;;
+ esac
+ done
+}
+
+# ── Health-check subcommand ────────────────────────────────────────────────────
+# Run read-only probes across all surfaces for a project; emit JSON results.
+# Usage: ops-marketing-autopilot --health-check [--project <key>]
+run_health_check() {
+ local proj="$1"
+ local checks='[]'
+
+ _hc_add() {
+ # $1=surface $2=healthy(true/false) $3=issue(or "")
+ checks="$(printf '%s' "$checks" | jq \
+ --arg s "$1" --argjson h "$2" --arg i "$3" \
+ '. + [{"surface":$s,"healthy":$h,"issue":$i}]' 2>/dev/null || printf '%s' "$checks")"
+ }
+
+ # --- Meta token TTL ---
+ local meta_tok; meta_tok="$(chan_cred "$proj" meta access_token)"
+ local meta_acct; meta_acct="$(chan_cred "$proj" meta ad_account_id)"
+ if [ -n "$meta_tok" ] && [ -n "$meta_acct" ]; then
+ local dbg_resp dbg_err dbg_exp
+ dbg_resp="$(curl -gsS --max-time 10 \
+ "https://graph.facebook.com/v20.0/debug_token?input_token=${meta_tok}&access_token=${meta_tok}" \
+ 2>/dev/null || echo '{}')"
+ dbg_err="$(printf '%s' "$dbg_resp" | jq -r '.error.code // empty' 2>/dev/null)"
+ dbg_exp="$(printf '%s' "$dbg_resp" | jq -r '.data.expires_at // empty' 2>/dev/null)"
+ if [ -n "$dbg_err" ]; then
+ _hc_add "meta_token" false "debug_token error code $dbg_err"
+ elif [ -n "$dbg_exp" ] && [ "$dbg_exp" != "0" ]; then
+ local now_ts; now_ts="$(date +%s)"
+ local ttl_days; ttl_days=$(( (dbg_exp - now_ts) / 86400 ))
+ if [ "$ttl_days" -lt 7 ]; then
+ _hc_add "meta_token" false "token expires in ${ttl_days}d — refresh soon"
+ else
+ _hc_add "meta_token" true ""
+ fi
+ else
+ _hc_add "meta_token" true "non-expiring or unverifiable token"
+ fi
+
+ # Meta account status
+ local acct_resp acct_status
+ acct_resp="$(curl -gsS --max-time 10 \
+ "${GRAPH}/${meta_acct}?fields=account_status&access_token=${meta_tok}" 2>/dev/null || echo '{}')"
+ acct_status="$(printf '%s' "$acct_resp" | jq -r '.account_status // empty' 2>/dev/null)"
+ if [ "$acct_status" = "1" ] || [ -z "$acct_status" ]; then
+ _hc_add "meta_account" true ""
+ else
+ _hc_add "meta_account" false "account_status=$acct_status"
+ fi
+ else
+ _hc_add "meta_token" false "not configured"
+ _hc_add "meta_account" false "not configured"
+ fi
+
+ # --- Google Ads OAuth health ---
+ local gads_dev; gads_dev="$(chan_cred "$proj" google_ads developer_token)"
+ local gads_refresh; gads_refresh="$(chan_cred "$proj" google_ads refresh_token)"
+ local gads_cid; gads_cid="$(chan_cred "$proj" google_ads client_id)"
+ local gads_csec; gads_csec="$(chan_cred "$proj" google_ads client_secret)"
+ if [ -n "$gads_refresh" ] && [ -n "$gads_cid" ] && [ -n "$gads_csec" ]; then
+ local tok_resp tok_acc tok_err
+ tok_resp="$(curl -gsS --max-time 8 -X POST https://oauth2.googleapis.com/token \
+ --data "client_id=${gads_cid}&client_secret=${gads_csec}&refresh_token=${gads_refresh}&grant_type=refresh_token" \
+ 2>/dev/null || echo '{}')"
+ tok_acc="$(printf '%s' "$tok_resp" | jq -r '.access_token // empty' 2>/dev/null)"
+ tok_err="$(printf '%s' "$tok_resp" | jq -r '.error // empty' 2>/dev/null)"
+ if [ -n "$tok_acc" ]; then
+ _hc_add "google_ads_oauth" true ""
+ else
+ _hc_add "google_ads_oauth" false "${tok_err:-token refresh failed}"
+ fi
+ else
+ _hc_add "google_ads_oauth" false "not configured"
+ fi
+
+ # --- Doppler secrets freshness ---
+ local all_refs
+ all_refs="$(jq -r --arg p "$proj" '
+ .marketing.projects[$p] | .. | strings | select(startswith("doppler:") or startswith("env:"))
+ ' "$PREFS" 2>/dev/null || true)"
+ local broken_refs=0
+ while IFS= read -r ref; do
+ [ -z "$ref" ] && continue
+ local _v _rc
+ _v="$(resolve_cred_strict "$ref")"; _rc=$?
+ [ "$_rc" = "2" ] && broken_refs=$((broken_refs+1))
+ done <<< "$all_refs"
+ if [ "$broken_refs" = "0" ]; then
+ _hc_add "doppler_secrets" true ""
+ else
+ _hc_add "doppler_secrets" false "${broken_refs} declared ref(s) returning empty"
+ fi
+
+ # --- GA4 SA key validity ---
+ local ga4_prop; ga4_prop="$(chan_cred "$proj" ga4 property_id)"
+ if [ -n "$ga4_prop" ]; then
+ local ga4_tok
+ ga4_tok="$(gcloud auth application-default print-access-token 2>/dev/null || true)"
+ if [ -n "$ga4_tok" ]; then
+ local ga4_resp
+ ga4_resp="$(curl -gsS --max-time 10 -X POST \
+ "https://analyticsdata.googleapis.com/v1beta/properties/${ga4_prop}:runReport" \
+ -H "Authorization: Bearer ${ga4_tok}" \
+ -H 'Content-Type: application/json' \
+ -d '{"dateRanges":[{"startDate":"yesterday","endDate":"yesterday"}],"metrics":[{"name":"sessions"}],"limit":1}' \
+ 2>/dev/null || echo '{}')"
+ local ga4_err; ga4_err="$(printf '%s' "$ga4_resp" | jq -r '.error.message // empty' 2>/dev/null)"
+ if [ -n "$ga4_err" ]; then
+ _hc_add "ga4_sa_key" false "$ga4_err"
+ else
+ _hc_add "ga4_sa_key" true ""
+ fi
+ else
+ _hc_add "ga4_sa_key" false "no gcloud ADC token"
+ fi
+ else
+ _hc_add "ga4_sa_key" false "not configured"
+ fi
+
+ # --- GSC site authorization ---
+ local gsc_site; gsc_site="$(chan_cred "$proj" gsc site_url)"
+ if [ -n "$gsc_site" ]; then
+ local gsc_tok
+ gsc_tok="$(gcloud auth application-default print-access-token 2>/dev/null || true)"
+ if [ -n "$gsc_tok" ]; then
+ local gsc_resp
+ gsc_resp="$(curl -gsS --max-time 10 \
+ "https://searchconsole.googleapis.com/webmasters/v3/sites/$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1],safe='')); " "$gsc_site" 2>/dev/null)" \
+ -H "Authorization: Bearer ${gsc_tok}" 2>/dev/null || echo '{}')"
+ local gsc_err; gsc_err="$(printf '%s' "$gsc_resp" | jq -r '.error.message // empty' 2>/dev/null)"
+ if [ -n "$gsc_err" ]; then
+ _hc_add "gsc_auth" false "$gsc_err"
+ else
+ _hc_add "gsc_auth" true ""
+ fi
+ else
+ _hc_add "gsc_auth" false "no gcloud ADC token"
+ fi
+ else
+ _hc_add "gsc_auth" false "not configured"
+ fi
+
+ # Compute overall health
+ local all_healthy
+ all_healthy="$(printf '%s' "$checks" | jq 'all(.healthy)' 2>/dev/null || echo false)"
+ local out
+ out="$(jq -n --argjson checks "$checks" --argjson healthy "$all_healthy" \
+ --arg proj "$proj" --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
+ '{project:$proj,ts:$ts,healthy:$healthy,checks:$checks}')"
+ printf '%s\n' "$out"
}
# ── Main ──────────────────────────────────────────────────────────────────────
@@ -1656,10 +2076,10 @@ mapfile -t PROJECTS < <(jq -r '
# An explicit --project may target a configured-but-disabled project (used by
# the dry-run verification path); still requires an autopilot block.
if [ -n "$ONLY_PROJECT" ]; then
- if jq -e --arg p "$ONLY_PROJECT" '.marketing.projects[$p].autopilot != null' "$PREFS" >/dev/null 2>&1; then
+ if jq -e --arg p "$ONLY_PROJECT" '.marketing.projects[$p] != null' "$PREFS" >/dev/null 2>&1; then
PROJECTS=("$ONLY_PROJECT")
else
- log "project '$ONLY_PROJECT' has no autopilot config — nothing to do"
+ log "project '$ONLY_PROJECT' not found — nothing to do"
exit 0
fi
fi
@@ -1669,6 +2089,17 @@ if [ "${#PROJECTS[@]}" -eq 0 ]; then
exit 0
fi
+# ── health-check dispatch (read-only, exits after output) ─────────────────────
+if [ "$DO_HEALTH_CHECK" = "1" ]; then
+ HC_OUTPUT='[]'
+ for proj in "${PROJECTS[@]}"; do
+ [ -z "$proj" ] && continue
+ HC_OUTPUT="$(printf '%s' "$HC_OUTPUT" | jq ". + [$(run_health_check "$proj")]" 2>/dev/null || printf '%s' "$HC_OUTPUT")"
+ done
+ printf '%s\n' "$HC_OUTPUT"
+ exit 0
+fi
+
# Fix F: project key sanitization — block path/prompt injection from operator-
# controlled preferences.json keys. Accept only [A-Za-z0-9._-] and reject
# bare "." or ".." components. Skip + log any key that fails the pattern.
diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.json
index 48fed144..b5da8e14 100644
--- a/claude-ops/scripts/daemon-services.default.json
+++ b/claude-ops/scripts/daemon-services.default.json
@@ -85,6 +85,12 @@
"cron": "0 9 * * 1",
"_note": "Weekly Autopilot Studio self-learning calibration (Monday 09:00 UTC ~= 11:00 Europe/Amsterdam, after the 08:00 daily pass). Joins each project's autopilot_state/<project>/creatives.jsonl pre-scores to realized KPIs (kpi.jsonl) and fits a monotone score->predicted_CPL calibrator.json consumed by the next daily pass. python3 stdlib only, no metered calls. Disabled by default; enabled alongside the autopilot block via /ops:setup marketing."
},
+ "marketing-health-check": {
+ "enabled": false,
+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-marketing-health-check.sh",
+ "cron": "0 8 * * 0",
+ "_note": "Weekly read-only health probe (Sunday 08:00 UTC) for all autopilot-enabled projects: Meta token TTL, Google Ads OAuth, ad account status, Doppler secret freshness, GA4 SA key, GSC site auth. Outputs JSON per project to reports/marketing-autopilot/<project>-health-<date>.json. Enable after credentials are configured. No mutations, no metered calls, OPS_DRY_RUN-safe."
+ },
"content-seo-blog": {
"enabled": false,
"cron": "0 9 * * 1",
diff --git a/claude-ops/scripts/lib/ga4-resolve.sh b/claude-ops/scripts/lib/ga4-resolve.sh
index b8064440..74bed89e 100755
--- a/claude-ops/scripts/lib/ga4-resolve.sh
+++ b/claude-ops/scripts/lib/ga4-resolve.sh
@@ -51,6 +51,35 @@ resolve_cred() {
esac
}
+# ---------------------------------------------------------------------------
+# resolve_cred_strict — like resolve_cred but distinguishes three states:
+# rc=0 + stdout value — resolved and non-empty (healthy)
+# rc=1 + empty stdout — ref is empty/null (not configured — expected)
+# rc=2 + empty stdout — ref is declared but resolver returned empty (broken)
+#
+# Usage:
+# val="$(resolve_cred_strict "$ref")"; rc=$?
+# case $rc in
+# 0) use "$val" ;;
+# 1) skip ;; # not configured — expected
+# 2) escalate "Doppler ref declared but empty: $ref" ;;
+# esac
+# ---------------------------------------------------------------------------
+resolve_cred_strict() {
+ local ref="${1:-}"
+ if [ -z "$ref" ] || [ "$ref" = "null" ]; then
+ return 1
+ fi
+ local val
+ val="$(resolve_cred "$ref")"
+ if [ -n "$val" ]; then
+ printf '%s' "$val"
+ return 0
+ fi
+ # ref declared but resolver returned empty — broken configuration
+ return 2
+}
+
# ---------------------------------------------------------------------------
# _prefs_marketing — read a field from preferences.json marketing.projects.<p>.<c>.<f>
# $1=project $2=channel $3=field
diff --git a/claude-ops/scripts/ops-cron-marketing-health-check.sh b/claude-ops/scripts/ops-cron-marketing-health-check.sh
new file mode 100755
index 00000000..19fa57cc
--- /dev/null
+++ b/claude-ops/scripts/ops-cron-marketing-health-check.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+# ops-cron-marketing-health-check.sh — weekly read-only health probe for all
+# autopilot-enabled projects. Runs ops-marketing-autopilot --health-check,
+# writes per-project JSON to reports/marketing-autopilot/, and fires notify
+# sinks for any unhealthy result.
+#
+# Registered in daemon-services.default.json as "marketing-health-check"
+# (enabled: false by default). Cron: 0 8 * * 0 (Sunday 08:00 UTC).
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+OPS_PLUGIN_ROOT_FALLBACK="${SCRIPT_DIR}/.." . "${SCRIPT_DIR}/lib/registry-path.sh"
+
+AUTOPILOT="${SCRIPT_DIR}/../bin/ops-marketing-autopilot"
+REPORT_DIR="${OPS_DATA_DIR}/reports/marketing-autopilot"
+TODAY="$(date +%Y-%m-%d)"
+mkdir -p "$REPORT_DIR"
+
+log() { printf '%s [health-check] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >&2; }
+
+log "starting weekly marketing health-check"
+
+# Run health-check (exits after printing JSON array)
+HC_JSON="$("$AUTOPILOT" --health-check 2>/dev/null || echo '[]')"
+
+# Write results and surface any unhealthy checks
+total=0; unhealthy=0
+while IFS= read -r proj_result; do
+ proj="$(printf '%s' "$proj_result" | jq -r '.project // "unknown"' 2>/dev/null)"
+ healthy="$(printf '%s' "$proj_result" | jq -r '.healthy' 2>/dev/null)"
+ total=$((total+1))
+ [ "$healthy" = "false" ] && unhealthy=$((unhealthy+1))
+
+ out="${REPORT_DIR}/${proj}-health-${TODAY}.json"
+ printf '%s\n' "$proj_result" > "$out"
+ log "project=$proj healthy=$healthy → $out"
+done < <(printf '%s' "$HC_JSON" | jq -c '.[]' 2>/dev/null || true)
+
+log "done — ${total} project(s) checked, ${unhealthy} unhealthy"
diff --git a/claude-ops/skills/ops-marketing/SKILL.md b/claude-ops/skills/ops-marketing/SKILL.md
index 18ce5fc2..ed6890b2 100644
--- a/claude-ops/skills/ops-marketing/SKILL.md
+++ b/claude-ops/skills/ops-marketing/SKILL.md
@@ -2469,4 +2469,112 @@ Save via userConfig (preferred) or Doppler. Report: `[service] ✓ connected` or
# Full dashboard
/ops:marketing
+
+# Run read-only health probe (all projects)
+/ops:marketing autopilot --health-check
+
+# Run health probe for one project
+/ops:marketing autopilot --health-check --project <your-project>
+```
+
+---
+
+## P6 — Self-Healing Autopilot: Schema Reference
+
+### `marketing.notify.sinks` (global, array)
+
+Replaces per-project `autopilot.notify_sink`. On `ESCALATED=1` all sinks fire.
+
+```jsonc
+{
+ "marketing": {
+ "notify": {
+ "sinks": [
+ // Telegram
+ {
+ "type": "telegram",
+ "ref": "doppler:claude-ops/prd/TELEGRAM_BOT_TOKEN", // or "env:TELEGRAM_BOT_TOKEN"
+ "chat_ref": "doppler:claude-ops/prd/TELEGRAM_CHAT_ID" // optional; falls back to env
+ },
+ // Slack incoming webhook
+ {
+ "type": "slack",
+ "ref": "doppler:claude-ops/prd/SLACK_AUTOPILOT_WEBHOOK"
+ },
+ // Email via Resend
+ {
+ "type": "email",
+ "ref": "doppler:claude-ops/prd/RESEND_API_KEY",
+ "from": "[email protected]"
+ },
+ // WhatsApp (daemon context: wacli send; Claude context: mcp__whatsapp)
+ {
+ "type": "whatsapp",
+ "to": "+1234567890"
+ }
+ ]
+ }
+ }
+}
+```
+
+**Legacy fallback:** `marketing.projects.<key>.autopilot.notify_sink = "telegram"` still works if
+`marketing.notify.sinks` is empty. Prefer the global sinks array for new setups.
+
+---
+
+### `marketing.projects.<key>.meta` — auto-refresh fields (P6)
+
+Auto-refresh requires `app_id` and `app_secret` in addition to `access_token`:
+
+```jsonc
+{
+ "marketing": {
+ "projects": {
+ "my-project": {
+ "meta": {
+ "access_token": "doppler:claude-ops/prd/META_MY_PROJECT_ACCESS_TOKEN",
+ "ad_account_id": "doppler:claude-ops/prd/META_MY_PROJECT_AD_ACCOUNT_ID",
+ "app_id": "doppler:claude-ops/prd/META_MY_PROJECT_APP_ID", // NEW — required for auto-refresh
+ "app_secret": "doppler:claude-ops/prd/META_MY_PROJECT_APP_SECRET" // NEW — required for auto-refresh
+ }
+ }
+ }
+ }
+}
```
+
+**Migration:** if you only have `access_token` (P1–P5 config), auto-refresh is disabled and
+a 190 error triggers a manual-rotation escalation instead. No existing behaviour changes — add
+`app_id` + `app_secret` to opt in to auto-refresh.
+
+**Env var fallback:** if Doppler refs are absent, the autopilot also checks
+`META_<PROJECT_UPPER>_APP_ID` and `META_<PROJECT_UPPER>_APP_SECRET` environment variables
+(e.g. `META_MY_PROJECT_APP_ID`).
+
+---
+
+### `--health-check` output schema
+
+`ops-marketing-autopilot --health-check [--project <key>]` exits after printing a JSON array:
+
+```jsonc
+[
+ {
+ "project": "my-project",
+ "ts": "2026-01-01T08:00:00Z",
+ "healthy": false,
+ "checks": [
+ { "surface": "meta_token", "healthy": true, "issue": "" },
+ { "surface": "meta_account", "healthy": false, "issue": "account_status=2" },
+ { "surface": "google_ads_oauth","healthy": true, "issue": "" },
+ { "surface": "doppler_secrets","healthy": true, "issue": "" },
+ { "surface": "ga4_sa_key", "healthy": true, "issue": "" },
+ { "surface": "gsc_auth", "healthy": true, "issue": "" }
+ ]
+ }
+]
+```
+
+`healthy` at the top level is `true` only when all checks pass. Pipe to `jq '.[] | select(.healthy==false)'` to filter unhealthy projects.
diff --git a/claude-ops/tests/test-meta-token-refresh.sh b/claude-ops/tests/test-meta-token-refresh.sh
new file mode 100755
index 00000000..6d955c12
--- /dev/null
+++ b/claude-ops/tests/test-meta-token-refresh.sh
@@ -0,0 +1,196 @@
+#!/usr/bin/env bash
+# test-meta-token-refresh.sh — assert Meta token refresh (error 190) behaviour:
+# 1. meta_get returns {} and calls meta_refresh_token when code=190
+# 2. On successful refresh: META_TOKEN updated in-memory, Doppler write attempted
+# 3. On failed refresh: escalate() called with human-readable reason
+# 4. DRY_RUN=1 skips Doppler write but still refreshes in-memory
+set -euo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BIN="$PLUGIN_ROOT/bin/ops-marketing-autopilot"
+
+pass=0; fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1 — $2"; fail=$((fail+1)); }
+
+echo "Testing Meta token refresh (error 190) in $BIN"
+echo ""
+
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+STATE_DIR="$WORK/state"
+REPORT_DIR="$WORK/reports"
+mkdir -p "$STATE_DIR" "$REPORT_DIR"
+
+# Minimal preferences.json with meta configured using doppler ref
+cat > "$WORK/prefs.json" <<'JSON'
+{
+ "marketing": {
+ "projects": {
+ "test-proj": {
+ "autopilot": {
+ "enabled": true,
+ "daily_spend_cap_usd": 50,
+ "campaign_ids": { "meta": [] }
+ },
+ "meta": {
+ "access_token": "doppler:claude-ops/prd/META_TEST_PROJ_ACCESS_TOKEN",
+ "ad_account_id": "act_123456789",
+ "app_id": "doppler:claude-ops/prd/META_TEST_PROJ_APP_ID",
+ "app_secret": "doppler:claude-ops/prd/META_TEST_PROJ_APP_SECRET"
+ }
+ }
+ }
+ }
+}
+JSON
+
+# Doppler stub — always returns non-empty for `secrets get`, records `secrets set` calls
+DOPPLER_SHIM="$WORK/doppler"
+DOPPLER_SET_SENTINEL="$WORK/doppler_set_called"
+cat > "$DOPPLER_SHIM" <<SHIM
+#!/usr/bin/env bash
+if [ "\${1:-}" = "secrets" ] && [ "\${2:-}" = "set" ]; then
+ printf '1' > "$DOPPLER_SET_SENTINEL"
+ exit 0
+fi
+# secrets get — return a non-empty stub value
+printf 'stub-doppler-value'
+exit 0
+SHIM
+chmod +x "$DOPPLER_SHIM"
+
+# ── Test harness — extract and source meta_refresh_token from binary ──────────
+HELPERS="$WORK/helpers.sh"
+{
+ echo '#!/usr/bin/env bash'
+ echo 'set -uo pipefail'
+ echo "PREFS=\"$WORK/prefs.json\""
+ echo "STATE_DIR=\"$WORK/state\""
+ echo "REPORT=\"$WORK/report.md\""
+ echo ': > "$REPORT"'
+ echo 'GRAPH="https://graph.facebook.com/v23.0"'
+ echo 'DRY_RUN="${DRY_RUN:-0}"'
+ echo 'META_TOKEN="expired-token-abc123"'
+ echo 'META_PROOF=""'
+ echo 'ESCALATED=0'
+ echo 'ESCALATE_REASON=""'
+ echo 'log() { :; }'
+ echo 'report() { :; }'
+ echo 'escalate() { ESCALATED=1; ESCALATE_REASON="${2:-}"; }'
+ # Stub resolve_cred — doppler: returns stub-doppler-value, env: expands, else literal
+ echo 'resolve_cred() { local r="${1:-}"; case "$r" in doppler:*) printf "stub-doppler-value" ;; env:*) local v="${r#env:}"; printf "%s" "${!v:-}" ;; *) printf "%s" "$r" ;; esac; }'
+ echo 'chan_cred() { resolve_cred "$(jq -r --arg p "$1" --arg c "$2" --arg f "$3" '"'"'.marketing.projects[$p][$c][$f] // empty'"'"' "$PREFS" 2>/dev/null)"; }'
+ echo 'meta_proof() { :; }'
+ # Mock curl: controlled via CURL_MOCK_RESPONSE env var
+ echo 'curl() { printf "%s" "${CURL_MOCK_RESPONSE:-{}}"; }'
+ # Extract meta_refresh_token function verbatim from binary
+ awk '/^meta_refresh_token\(\)/{p=1} p{print} p && /^}$/{p=0; exit}' "$BIN"
+} > "$HELPERS"
+chmod +x "$HELPERS"
+
+# ── Test 1: successful refresh updates META_TOKEN in-memory ───────────────────
+# Write result to file to avoid stdout mixing with any function side-effects
+T1_OUT="$WORK/t1.out"
+env \
+ PATH="$WORK:$PATH" \
+ CURL_MOCK_RESPONSE='{"access_token":"new-long-lived-token-xyz"}' \
+ DRY_RUN=0 \
+ bash -c ". '$HELPERS' && meta_refresh_token 'test-proj' >/dev/null 2>&1; printf '%s' \"\$META_TOKEN\"" \
+ > "$T1_OUT" 2>/dev/null || true
+result="$(cat "$T1_OUT")"
+if [ "$result" = "new-long-lived-token-xyz" ]; then
+ ok "successful refresh: META_TOKEN updated in-memory"
+else
+ err "successful refresh: META_TOKEN not updated" "got '$result'"
+fi
+
+# ── Test 2: failed refresh → returns rc=1 so caller knows to escalate ─────────
+# meta_refresh_token returns 1 on failure; the caller (meta_get) escalates.
+# Here we assert rc=1 from the function itself.
+T2_RC=0
+env \
+ PATH="$WORK:$PATH" \
+ CURL_MOCK_RESPONSE='{"error":{"message":"Invalid OAuth access token","type":"OAuthException","code":190}}' \
+ DRY_RUN=0 \
+ bash -c ". '$HELPERS'; meta_refresh_token 'test-proj' >/dev/null 2>&1; printf '%s' \$?" \
+ > "$WORK/t2.out" 2>/dev/null || true
+T2_RC="$(cat "$WORK/t2.out")"
+if [ "$T2_RC" = "1" ]; then
+ ok "failed refresh: returns rc=1 (caller escalates)"
+else
+ err "failed refresh: expected rc=1" "rc=$T2_RC"
+fi
+
+# ── Test 2b: meta_get with 190 + no app_id/secret → escalate called ──────────
+# Build a harness that includes meta_get + meta_refresh_token + the escalate stub
+HELPERS2="$WORK/helpers2.sh"
+{
+ echo '#!/usr/bin/env bash'
+ # No -e so non-zero rc from internal functions does not abort the test script
+ echo 'set -uo pipefail'
+ echo "PREFS=\"$WORK/prefs.json\""
+ echo "STATE_DIR=\"$WORK/state\""
+ echo "REPORT=\"$WORK/report2.md\""
+ echo ': > "$REPORT"'
+ echo 'DRY_RUN=0'
+ echo 'META_TOKEN="expired-token-abc123"'
+ echo 'META_PROOF=""'
+ echo 'ESCALATED=0'
+ echo '_META_CURRENT_PROJ="test-proj"'
+ echo 'GRAPH="https://graph.facebook.com/v23.0"'
+ echo 'log() { :; }'
+ echo 'report() { :; }'
+ echo 'escalate() { ESCALATED=1; }'
+ # chan_cred returns empty for app_id/app_secret → no-app-id path in meta_refresh_token
+ echo 'chan_cred() { case "${3:-}" in app_id|app_secret) printf "" ;; *) printf "stub-val" ;; esac; }'
+ echo 'meta_proof() { :; }'
+ echo 'sleep() { :; }'
+ echo 'CURL_MOCK_RESPONSE='"'"'{"error":{"code":190,"message":"token expired"}}'"'"
+ echo 'curl() { printf "%s" "$CURL_MOCK_RESPONSE"; }'
+ awk '/^meta_refresh_token\(\)/{p=1} p{print} p && /^}$/{p=0; exit}' "$BIN"
+ awk '/^meta_get\(\)/{p=1} p{print} p && /^}$/{p=0; exit}' "$BIN"
+ echo 'meta_get "me?fields=id" "test-proj" >/dev/null 2>&1 || true'
+ echo 'printf "%s" "$ESCALATED"'
+} > "$HELPERS2"
+T2B_OUT="$WORK/t2b.out"
+bash "$HELPERS2" > "$T2B_OUT" 2>/dev/null || true
+result="$(cat "$T2B_OUT")"
+if [ "$result" = "1" ]; then
+ ok "meta_get 190 + no app_id: escalate() fired"
+else
+ err "meta_get 190 + no app_id: escalate not fired" "ESCALATED='$result'"
+fi
+
+# ── Test 3: DRY_RUN=1 skips Doppler write (doppler secrets set NOT called) ────
+rm -f "$DOPPLER_SET_SENTINEL"
+env \
+ PATH="$WORK:$PATH" \
+ CURL_MOCK_RESPONSE='{"access_token":"refreshed-dry-token"}' \
+ DRY_RUN=1 \
+ bash -c ". '$HELPERS' && meta_refresh_token 'test-proj'" >/dev/null 2>&1 || true
+if [ ! -f "$DOPPLER_SET_SENTINEL" ]; then
+ ok "DRY_RUN=1: Doppler write skipped"
+else
+ err "DRY_RUN=1: Doppler write should be skipped" "doppler secrets set was called"
+fi
+
+# ── Test 4: in-memory token updated even in DRY_RUN=1 ─────────────────────────
+T4_OUT="$WORK/t4.out"
+env \
+ PATH="$WORK:$PATH" \
+ CURL_MOCK_RESPONSE='{"access_token":"dry-run-in-memory-token"}' \
+ DRY_RUN=1 \
+ bash -c ". '$HELPERS' && meta_refresh_token 'test-proj' >/dev/null 2>&1; printf '%s' \"\$META_TOKEN\"" \
+ > "$T4_OUT" 2>/dev/null || true
+result="$(cat "$T4_OUT")"
+if [ "$result" = "dry-run-in-memory-token" ]; then
+ ok "DRY_RUN=1: in-memory META_TOKEN still updated"
+else
+ err "DRY_RUN=1: in-memory META_TOKEN not updated" "got '$result'"
+fi
+
+echo ""
+echo "Results: ${pass} passed, ${fail} failed"
+[ "$fail" -eq 0 ]
diff --git a/claude-ops/tests/test-multi-sink-notify.sh b/claude-ops/tests/test-multi-sink-notify.sh
new file mode 100755
index 00000000..4491529a
--- /dev/null
+++ b/claude-ops/tests/test-multi-sink-notify.sh
@@ -0,0 +1,183 @@
+#!/usr/bin/env bash
+# test-multi-sink-notify.sh — assert all configured notify sinks fire on ESCALATED=1
+#
+# Strategy: extract the notify() function, stub HTTP sinks (curl shim writes to
+# per-sink sentinel files), drive with ESCALATED=1, assert each sentinel exists.
+set -euo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BIN="$PLUGIN_ROOT/bin/ops-marketing-autopilot"
+
+pass=0; fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1 — $2"; fail=$((fail+1)); }
+
+echo "Testing multi-sink notify() in $BIN"
+echo ""
+
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+TODAY="$(date +%Y-%m-%d)"
+
+# Preferences with all four sink types configured
+cat > "$WORK/prefs.json" <<JSON
+{
+ "marketing": {
+ "notify": {
+ "sinks": [
+ {"type": "telegram", "ref": "env:_TEST_TG_TOKEN", "chat_ref": "env:_TEST_TG_CHAT"},
+ {"type": "slack", "ref": "env:_TEST_SLACK_URL"},
+ {"type": "email", "ref": "env:_TEST_RESEND_KEY", "to": "[email protected]", "from": "[email protected]"},
+ {"type": "whatsapp", "to": "+1234567890"}
+ ]
+ },
+ "projects": {
+ "test-proj": {
+ "autopilot": {
+ "enabled": true,
+ "daily_spend_cap_usd": 50
+ }
+ }
+ }
+ }
+}
+JSON
+
+# Stub environment values for sinks
+export _TEST_TG_TOKEN="tg-bot-token"
+export _TEST_TG_CHAT="tg-chat-id"
+export _TEST_SLACK_URL="https://hooks.slack.example.com/test"
+export _TEST_RESEND_KEY="re_testkey"
+
+# Build a curl shim that writes sentinel files keyed by URL pattern
+CURL_SHIM="$WORK/curl"
+cat > "$CURL_SHIM" <<SH
+#!/usr/bin/env bash
+# Parse the URL from args to identify which sink fired
+url=""
+for arg in "\$@"; do
+ case "\$arg" in
+ https://api.telegram.org/*) printf '1' > "$WORK/sink_telegram" ;;
+ https://hooks.slack.example.com/*) printf '1' > "$WORK/sink_slack" ;;
+ https://api.resend.com/*) printf '1' > "$WORK/sink_email" ;;
+ esac
+done
+exit 0
+SH
+chmod +x "$CURL_SHIM"
+
+# wacli shim to detect whatsapp sink
+WACLI_SHIM="$WORK/wacli"
+cat > "$WACLI_SHIM" <<SH
+#!/usr/bin/env bash
+printf '1' > "$WORK/sink_whatsapp"
+exit 0
+SH
+chmod +x "$WACLI_SHIM"
+
+# Build harness that sources only the notify() function
+HARNESS="$WORK/harness.sh"
+{
+ echo '#!/usr/bin/env bash'
+ echo 'set -uo pipefail'
+ echo "PREFS=\"$WORK/prefs.json\""
+ echo "TODAY=\"$TODAY\""
+ echo 'MUTATIONS=3'
+ echo 'ESCALATED=1'
+ echo 'REPORT="/dev/null"'
+ echo 'log() { :; }'
+ echo 'resolve_cred() { local r="${1:-}"; case "$r" in env:*) local v="${r#env:}"; printf "%s" "${!v:-}" ;; *) printf "%s" "$r" ;; esac; }'
+ echo 'ap_get() { :; }'
+ # Extract notify() from binary
+ awk '/^notify\(\)/{p=1} p{print} p && /^}$/{p=0; exit}' "$BIN"
+ echo ''
+ echo "notify 'test-proj'"
+} > "$HARNESS"
+chmod +x "$HARNESS"
+
+# Run with PATH shimmed
+env \
+ PATH="$WORK:$PATH" \
+ _TEST_TG_TOKEN="tg-bot-token" \
+ _TEST_TG_CHAT="tg-chat-id" \
+ _TEST_SLACK_URL="https://hooks.slack.example.com/test" \
+ _TEST_RESEND_KEY="re_testkey" \
+ bash "$HARNESS" 2>/dev/null || true
+
+# Assert sentinels
+if [ -f "$WORK/sink_telegram" ]; then
+ ok "telegram sink fired on ESCALATED=1"
+else
+ err "telegram sink NOT fired" "sentinel file missing"
+fi
+
+if [ -f "$WORK/sink_slack" ]; then
+ ok "slack sink fired on ESCALATED=1"
+else
+ err "slack sink NOT fired" "sentinel file missing"
+fi
+
+if [ -f "$WORK/sink_email" ]; then
+ ok "email (Resend) sink fired on ESCALATED=1"
+else
+ err "email (Resend) sink NOT fired" "sentinel file missing"
+fi
+
+if [ -f "$WORK/sink_whatsapp" ]; then
+ ok "whatsapp sink fired on ESCALATED=1"
+else
+ err "whatsapp sink NOT fired" "sentinel file missing"
+fi
+
+# ── Test legacy fallback: per-project notify_sink=telegram still fires ─────────
+cat > "$WORK/prefs_legacy.json" <<JSON
+{
+ "marketing": {
+ "projects": {
+ "legacy-proj": {
+ "autopilot": {
+ "enabled": true,
+ "daily_spend_cap_usd": 50,
+ "notify_sink": "telegram"
+ }
+ }
+ }
+ }
+}
+JSON
+rm -f "$WORK/sink_telegram"
+
+HARNESS2="$WORK/harness_legacy.sh"
+{
+ echo '#!/usr/bin/env bash'
+ echo 'set -uo pipefail'
+ echo "PREFS=\"$WORK/prefs_legacy.json\""
+ echo "TODAY=\"$TODAY\""
+ echo 'MUTATIONS=1'
+ echo 'ESCALATED=1'
+ echo 'REPORT="/dev/null"'
+ echo 'log() { :; }'
+ echo 'resolve_cred() { local r="${1:-}"; case "$r" in env:*) local v="${r#env:}"; printf "%s" "${!v:-}" ;; *) printf "%s" "$r" ;; esac; }'
+ echo 'ap_get() { local p="$1" q="$2"; jq -r --arg pp "$p" ".marketing.projects[\$pp].autopilot${q} // empty" "$PREFS" 2>/dev/null; }'
+ awk '/^notify\(\)/{p=1} p{print} p && /^}$/{p=0; exit}' "$BIN"
+ echo ''
+ echo "notify 'legacy-proj'"
+} > "$HARNESS2"
+chmod +x "$HARNESS2"
+
+env \
+ PATH="$WORK:$PATH" \
+ TELEGRAM_BOT_TOKEN="tg-bot-token" \
+ TELEGRAM_CHAT_ID="tg-chat-id" \
+ bash "$HARNESS2" 2>/dev/null || true
+
+if [ -f "$WORK/sink_telegram" ]; then
+ ok "legacy notify_sink=telegram fallback fires"
+else
+ err "legacy notify_sink=telegram fallback NOT fired" "sentinel file missing"
+fi
+
+echo ""
+echo "Results: ${pass} passed, ${fail} failed"
+[ "$fail" -eq 0 ]
diff --git a/claude-ops/tests/test-resolve-cred-strict.sh b/claude-ops/tests/test-resolve-cred-strict.sh
new file mode 100755
index 00000000..93cd6744
--- /dev/null
+++ b/claude-ops/tests/test-resolve-cred-strict.sh
@@ -0,0 +1,121 @@
+#!/usr/bin/env bash
+# test-resolve-cred-strict.sh — golden table for resolve_cred_strict rc=0/1/2
+#
+# rc=0: ref declared + resolver returns non-empty value
+# rc=1: ref is empty / null / not set (not configured — expected)
+# rc=2: ref is declared but resolver returns empty (broken)
+set -euo pipefail
+
+LIB="$(cd "$(dirname "$0")/.." && pwd)/scripts/lib/ga4-resolve.sh"
+
+pass=0; fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1 — expected rc=$2 got rc=$3${4:+ val='$4'}"; fail=$((fail+1)); }
+
+echo "Testing resolve_cred_strict golden table in $LIB"
+echo ""
+
+# Stub OPS_DATA_DIR so the guard doesn't bail
+export OPS_DATA_DIR="${TMPDIR:-/tmp}"
+# Guard against double-source (reset for test)
+unset _GA4_RESOLVE_LOADED
+# shellcheck disable=SC1090
+. "$LIB"
+
+# Helper: capture both stdout and rc without triggering set -e on non-zero rc
+_strict() { local _r; _r="$(resolve_cred_strict "$1" 2>/dev/null)" && { printf '%s' "$_r"; return 0; } || return $?; }
+
+# ── Case 1: empty ref → rc=1 (not configured) ────────────────────────────────
+val=""; rc=0
+val="$(_strict "" 2>/dev/null)" || rc=$?
+if [ "$rc" = "1" ] && [ -z "$val" ]; then
+ ok "empty ref → rc=1"
+else
+ err "empty ref → rc=1" 1 "$rc" "$val"
+fi
+
+# ── Case 2: null string ref → rc=1 (not configured) ──────────────────────────
+val=""; rc=0
+val="$(_strict "null" 2>/dev/null)" || rc=$?
+if [ "$rc" = "1" ] && [ -z "$val" ]; then
+ ok "'null' string ref → rc=1"
+else
+ err "'null' string ref → rc=1" 1 "$rc" "$val"
+fi
+
+# ── Case 3: inline literal ref (non-empty) → rc=0 ────────────────────────────
+val=""; rc=0
+val="$(_strict "my-literal-value" 2>/dev/null)" || rc=$?
+if [ "$rc" = "0" ] && [ "$val" = "my-literal-value" ]; then
+ ok "inline literal → rc=0, val=my-literal-value"
+else
+ err "inline literal → rc=0" 0 "$rc" "$val"
+fi
+
+# ── Case 4: env:VAR where VAR is set → rc=0 ──────────────────────────────────
+export _TEST_RC_STRICT_VAR="hello-from-env"
+val=""; rc=0
+val="$(_strict "env:_TEST_RC_STRICT_VAR" 2>/dev/null)" || rc=$?
+if [ "$rc" = "0" ] && [ "$val" = "hello-from-env" ]; then
+ ok "env:VAR (set) → rc=0"
+else
+ err "env:VAR (set) → rc=0" 0 "$rc" "$val"
+fi
+unset _TEST_RC_STRICT_VAR
+
+# ── Case 5: env:VAR where VAR is unset → rc=2 (declared but empty) ───────────
+unset _TEST_RC_STRICT_MISSING 2>/dev/null || true
+val=""; rc=0
+val="$(_strict "env:_TEST_RC_STRICT_MISSING" 2>/dev/null)" || rc=$?
+if [ "$rc" = "2" ] && [ -z "$val" ]; then
+ ok "env:VAR (unset) → rc=2 (broken)"
+else
+ err "env:VAR (unset) → rc=2" 2 "$rc" "$val"
+fi
+
+# ── Case 6: doppler: ref but doppler returns empty (stubbed) ──────────────────
+_orig_path="$PATH"
+STUB_DIR="$(mktemp -d)"
+trap 'rm -rf "$STUB_DIR"' EXIT
+cat > "$STUB_DIR/doppler" <<'SH'
+#!/usr/bin/env bash
+printf ''
+exit 0
+SH
+chmod +x "$STUB_DIR/doppler"
+export PATH="$STUB_DIR:$PATH"
+
+# Re-source with stubbed doppler in PATH
+unset _GA4_RESOLVE_LOADED
+# shellcheck disable=SC1090
+. "$LIB"
+_strict() { local _r; _r="$(resolve_cred_strict "$1" 2>/dev/null)" && { printf '%s' "$_r"; return 0; } || return $?; }
+
+val=""; rc=0
+val="$(_strict "doppler:myproject/prd/MY_SECRET" 2>/dev/null)" || rc=$?
+if [ "$rc" = "2" ] && [ -z "$val" ]; then
+ ok "doppler: ref (empty result) → rc=2 (broken)"
+else
+ err "doppler: ref (empty result) → rc=2" 2 "$rc" "$val"
+fi
+
+# ── Case 7: doppler: ref with real value (stubbed) ───────────────────────────
+cat > "$STUB_DIR/doppler" <<'SH'
+#!/usr/bin/env bash
+printf 'real-secret-value'
+exit 0
+SH
+
+val=""; rc=0
+val="$(_strict "doppler:myproject/prd/MY_SECRET" 2>/dev/null)" || rc=$?
+if [ "$rc" = "0" ] && [ "$val" = "real-secret-value" ]; then
+ ok "doppler: ref (non-empty result) → rc=0"
+else
+ err "doppler: ref (non-empty result) → rc=0" 0 "$rc" "$val"
+fi
+
+export PATH="$_orig_path"
+
+echo ""
+echo "Results: ${pass} passed, ${fail} failed"
+[ "$fail" -eq 0 ]
diff --git a/claude-ops/tests/test-stripe-rescue-gate.sh b/claude-ops/tests/test-stripe-rescue-gate.sh
index a94c2ded..cc7f33ad 100755
--- a/claude-ops/tests/test-stripe-rescue-gate.sh
+++ b/claude-ops/tests/test-stripe-rescue-gate.sh
@@ -101,6 +101,82 @@ d7="$(bash "$HELPERS" "$STATE_DIR" ad_A 30 1.0)"
&& ok "no stripe file → no rescue, ad paused" \
|| err "no stripe file" "expected 'yes', got '$d7'"
+echo ""
+echo "--- token-expired ad account extension ---"
+echo ""
+
+# ── P6 extension: assert Meta token-expired (code 190) escalates correctly ────
+# We drive meta_account_health() directly to assert non-active account_status
+# values escalate with the right messages.
+
+ACCT_HELPERS="$WORK/acct_helpers.sh"
+{
+ echo '#!/usr/bin/env bash'
+ echo 'set -uo pipefail'
+ echo 'PREFS="/dev/null"'
+ echo 'DRY_RUN=0'
+ echo 'ESCALATED=0'
+ echo 'ESCALATE_REASON=""'
+ echo 'REPORT="$1"; shift'
+ echo 'STATE_DIR="'"$STATE_DIR"'"'
+ echo ': > "$REPORT"'
+ echo 'log() { :; }'
+ echo 'report() { printf "%s\n" "$1" >> "$REPORT"; }'
+ echo 'escalate() { ESCALATED=1; ESCALATE_REASON="$2"; }'
+ # stub meta_get to return our mock JSON
+ echo 'MOCK_JSON="$1"; shift'
+ echo 'meta_get() { printf "%s" "$MOCK_JSON"; }'
+ # Extract meta_account_health from binary
+ awk '/^meta_account_health\(\)/{p=1} p{print} p && /^}$/{p=0; exit}' "$BIN"
+ echo 'meta_account_health "$1" "$2"'
+ echo 'printf "%s:%s\n" "$ESCALATED" "${ESCALATE_REASON}"'
+} > "$ACCT_HELPERS"
+chmod +x "$ACCT_HELPERS"
+
+REPORT_A="$WORK/report_acct.md"
+
+# account_status=1 (active) → no escalation
+res1="$(bash "$ACCT_HELPERS" "$REPORT_A" '{"account_status":1}' "test-proj" "act_123")"
+e1="${res1%%:*}"
+[ "$e1" = "0" ] \
+ && ok "account_status=1 (active) → no escalation" \
+ || err "account_status=1" "ESCALATED=$e1, reason=${res1#*:}"
+
+# account_status=2 (disabled) → escalate
+res2="$(bash "$ACCT_HELPERS" "$REPORT_A" '{"account_status":2,"disable_reason":3}' "test-proj" "act_123")"
+e2="${res2%%:*}"
+[ "$e2" = "1" ] \
+ && ok "account_status=2 (disabled) → escalated" \
+ || err "account_status=2" "ESCALATED=$e2"
+
+# account_status=3 (unsettled) → escalate
+res3="$(bash "$ACCT_HELPERS" "$REPORT_A" '{"account_status":3}' "test-proj" "act_123")"
+e3="${res3%%:*}"
+[ "$e3" = "1" ] \
+ && ok "account_status=3 (unsettled) → escalated" \
+ || err "account_status=3" "ESCALATED=$e3"
+
+# account_status=7 (pending review) → escalate
+res7="$(bash "$ACCT_HELPERS" "$REPORT_A" '{"account_status":7}' "test-proj" "act_123")"
+e7="${res7%%:*}"
+[ "$e7" = "1" ] \
+ && ok "account_status=7 (pending review) → escalated" \
+ || err "account_status=7" "ESCALATED=$e7"
+
+# account_status=8 (grace period) → no escalation (informational)
+res8="$(bash "$ACCT_HELPERS" "$REPORT_A" '{"account_status":8}' "test-proj" "act_123")"
+e8="${res8%%:*}"
+[ "$e8" = "0" ] \
+ && ok "account_status=8 (grace period) → no escalation" \
+ || err "account_status=8" "ESCALATED=$e8"
+
+# missing account_status field → no escalation (field not returned — skip)
+res_empty="$(bash "$ACCT_HELPERS" "$REPORT_A" '{}' "test-proj" "act_123")"
+e_empty="${res_empty%%:*}"
+[ "$e_empty" = "0" ] \
+ && ok "empty account_status → no escalation (skipped)" \
+ || err "empty account_status" "ESCALATED=$e_empty"
+
echo ""
echo "---"
echo "Results: $pass passed, $fail failed"