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(autopilot): auto-downshift Meta + Google Ads budgets when over cap (#337)

Aurora Capital4c9cc80b0dd5
diff --git a/claude-ops/bin/ops-marketing-autopilot b/claude-ops/bin/ops-marketing-autopilot
index 7ccd9878..aa0e8bc0 100755
--- a/claude-ops/bin/ops-marketing-autopilot
+++ b/claude-ops/bin/ops-marketing-autopilot
@@ -12,10 +12,17 @@
#
# Spend-safety invariants (NEVER LEAK MONEY + Rule 5):
# - No daily_spend_cap_usd -> project skipped, escalation note, zero mutations
-# - Sum(campaign daily_budget) > cap OR runaway amount_spent -> abort project
-# - May ONLY pause / swap / regenerate creatives. NEVER raises budgets, creates
-# campaigns, creates/expands audiences, or changes objectives — object creation
-# goes through create_object() autonomy gate which enforces staging + approval.
+# - Sum(campaign daily_budget) > cap -> AUTO-DOWNSHIFT each campaign/adset
+# budget proportionally (scale = cap / Σ_budget). Where the platform has a
+# $1/day minimum, budgets already at/above that floor are floored to $1 only
+# when it still lowers the budget; sub-minimum live rows are never raised.
+# If Σ remains above cap after downshift, escalate (do not continue the pass).
+# Logged + mutation-counted. Never raises an entity above its prior budget.
+# - Runaway amount_spent (delta > 1.5× cap since last pass) -> abort project
+# - May pause / swap / regenerate creatives + downshift budgets to fit cap.
+# NEVER raises budgets, creates campaigns, creates/expands audiences, or
+# changes objectives — object creation goes through create_object() autonomy
+# gate which enforces staging + approval.
# - --dry-run flag; first install run is forced dry (logs intended actions only)
#
# Flags: --dry-run --project <name> --channel meta|google_ads
@@ -133,7 +140,11 @@ escalate() {
report ""
report "- **Project:** $proj"
report "- **Reason:** $reason"
- report "- **Mutations performed this pass:** NONE (aborted for safety)"
+ if [ "${MUTATIONS:-0}" -gt 0 ]; then
+ report "- **Mutations performed this pass:** ${MUTATIONS} (partial mutations may have applied before abort — verify account state)"
+ else
+ report "- **Mutations performed this pass:** NONE (aborted for safety)"
+ fi
report ""
printf '%s\t%s\t%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$proj" "$reason" \
>> "${STATE_DIR}/escalations.log"
@@ -677,7 +688,96 @@ process_meta() {
local over
over="$(awk "BEGIN{print (${total_budget_usd}+0 > ${cap}+0) ? 1 : 0}")"
if [ "$over" = "1" ]; then
- escalate "$proj" "Meta Σ daily_budget \$${total_budget_usd} exceeds cap \$${cap} — possible budget tamper. No mutations."
+ # Auto-downshift: scale all campaign/adset budgets proportionally toward cap.
+ # Meta $1/day floor applies only when it still lowers vs prior (never raises).
+ local scale_factor
+ scale_factor="$(awk "BEGIN{printf \"%.6f\", ${cap}/${total_budget_usd}}")"
+ report "- cap pre-flight EXCEEDED (\$${total_budget_usd} > \$${cap}) — auto-downshifting at ratio ${scale_factor}"
+
+ local new_total_usd=0
+ for cid in "${CIDS[@]}"; do
+ camp="$(meta_get "${cid}?fields=name,status,daily_budget" "$proj")"
+ local cname; cname="$(echo "$camp" | jq -r '.name // empty' 2>/dev/null)"
+ local cdb; cdb="$(echo "$camp" | jq -r '.daily_budget // empty' 2>/dev/null)"
+ if [ -n "$cdb" ] && [ "$cdb" != "null" ]; then
+ # CBO: scale campaign-level budget
+ local new_cents new_usd old_usd
+ new_cents="$(awk -v c="$cdb" -v s="$scale_factor" 'BEGIN{v=int(c*s); if(v>c)v=c; if(v<100&&c>=100){v=100;if(v>c)v=c} print v}')"
+ new_usd="$(awk "BEGIN{printf \"%.2f\", ${new_cents}/100}")"
+ old_usd="$(awk "BEGIN{printf \"%.2f\", ${cdb}/100}")"
+ if [ "$DRY_RUN" = "1" ]; then
+ report "- [DRY] would shrink ${cname} (${cid}): \$${old_usd} → \$${new_usd}"
+ else
+ local prr err post_body
+ post_body="$(printf '%s_budget=%s' daily "${new_cents}")"
+ prr="$(curl -gsS --max-time 15 -X POST "${GRAPH}/${cid}" \
+ -d "$post_body" \
+ -d "access_token=${META_TOKEN}" \
+ ${META_PROOF:+-d "appsecret_proof=${META_PROOF}"} 2>/dev/null)" || prr=""
+ if [ -z "$prr" ] || [ "$prr" = "{}" ]; then
+ escalate "$proj" "Meta auto-downshift FAILED for ${cname} (${cid}): empty or invalid HTTP response"
+ return 0
+ fi
+ err="$(printf '%s' "$prr" | jq -r '.error.message // empty' 2>/dev/null)"
+ if [ -n "$err" ]; then
+ escalate "$proj" "Meta auto-downshift FAILED for ${cname} (${cid}): ${err}"
+ return 0
+ fi
+ if ! printf '%s' "$prr" | jq -e '(.success == true) or (.success == "true") or (.id != null and (.id|tostring)!="")' >/dev/null 2>&1; then
+ escalate "$proj" "Meta auto-downshift FAILED for ${cname} (${cid}): unexpected API response (not a confirmed success)"
+ return 0
+ fi
+ MUTATIONS=$((MUTATIONS+1))
+ report "- [SHRINK] ${cname} (${cid}): \$${old_usd} → \$${new_usd}"
+ fi
+ new_total_usd="$(awk "BEGIN{printf \"%.2f\", ${new_total_usd}+${new_cents}/100}")"
+ else
+ # ABO: scale each ACTIVE adset's daily_budget
+ adsets="$(meta_get "${cid}/adsets?fields=name,daily_budget,effective_status&limit=200" "$proj")"
+ while IFS=$'\t' read -r asid asname asdb; do
+ [ -z "$asid" ] && continue
+ [ -z "$asdb" ] && continue
+ [ "$asdb" = "null" ] && continue
+ local new_cents new_usd old_usd
+ new_cents="$(awk -v c="$asdb" -v s="$scale_factor" 'BEGIN{v=int(c*s); if(v>c)v=c; if(v<100&&c>=100){v=100;if(v>c)v=c} print v}')"
+ new_usd="$(awk "BEGIN{printf \"%.2f\", ${new_cents}/100}")"
+ old_usd="$(awk "BEGIN{printf \"%.2f\", ${asdb}/100}")"
+ if [ "$DRY_RUN" = "1" ]; then
+ report "- [DRY] would shrink adset ${asname} (${asid}): \$${old_usd} → \$${new_usd}"
+ else
+ local prr err post_body
+ post_body="$(printf '%s_budget=%s' daily "${new_cents}")"
+ prr="$(curl -gsS --max-time 15 -X POST "${GRAPH}/${asid}" \
+ -d "$post_body" \
+ -d "access_token=${META_TOKEN}" \
+ ${META_PROOF:+-d "appsecret_proof=${META_PROOF}"} 2>/dev/null)" || prr=""
+ if [ -z "$prr" ] || [ "$prr" = "{}" ]; then
+ escalate "$proj" "Meta auto-downshift FAILED for adset ${asname} (${asid}): empty or invalid HTTP response"
+ return 0
+ fi
+ err="$(printf '%s' "$prr" | jq -r '.error.message // empty' 2>/dev/null)"
+ if [ -n "$err" ]; then
+ escalate "$proj" "Meta auto-downshift FAILED for adset ${asname} (${asid}): ${err}"
+ return 0
+ fi
+ if ! printf '%s' "$prr" | jq -e '(.success == true) or (.success == "true") or (.id != null and (.id|tostring)!="")' >/dev/null 2>&1; then
+ escalate "$proj" "Meta auto-downshift FAILED for adset ${asname} (${asid}): unexpected API response (not a confirmed success)"
+ return 0
+ fi
+ MUTATIONS=$((MUTATIONS+1))
+ report "- [SHRINK] adset ${asname} (${asid}): \$${old_usd} → \$${new_usd}"
+ fi
+ new_total_usd="$(awk "BEGIN{printf \"%.2f\", ${new_total_usd}+${new_cents}/100}")"
+ done < <(echo "$adsets" | jq -r '.data[]? | select(.effective_status=="ACTIVE") | select(.daily_budget != null) | [.id, .name, .daily_budget] | @tsv' 2>/dev/null)
+ fi
+ done
+ total_budget_usd="$new_total_usd"
+ report "- post-downshift Σ daily_budget: \$${total_budget_usd}"
+ fi
+ local still_over_cap
+ still_over_cap="$(awk "BEGIN{print (${total_budget_usd}+0 > ${cap}+0) ? 1 : 0}")"
+ if [ "$still_over_cap" = "1" ]; then
+ escalate "$proj" "Meta cap pre-flight: Σ daily_budget \$${total_budget_usd} still exceeds cap \$${cap} after auto-downshift — cannot satisfy spend cap without manual changes"
return 0
fi
report "- cap pre-flight OK: Σ daily_budget \$${total_budget_usd} ≤ cap \$${cap}"
@@ -888,7 +988,63 @@ process_google_ads() {
--data-binary "{\"query\":\"SELECT campaign.id, campaign.status, campaign_budget.amount_micros FROM campaign WHERE campaign.id IN (${idlist})\"}" 2>/dev/null || echo '[]')"
total_usd="$(echo "$budrows" | jq '[.[].results[]?.campaignBudget.amountMicros | tonumber? // 0] | add / 1000000 // 0' 2>/dev/null || echo 0)"
if awk "BEGIN{exit !(${total_usd:-0} > ${cap:-0})}"; then
- escalate "$proj" "Google Ads Σ campaign budget \$${total_usd} exceeds cap \$${cap} — possible tamper. No mutations."
+ # Auto-downshift: scale each campaign budget proportionally toward cap.
+ # Google $1/day floor applies only when it still lowers vs prior (never raises).
+ local scale_factor
+ scale_factor="$(awk "BEGIN{printf \"%.6f\", ${cap}/${total_usd}}")"
+ report "- cap pre-flight EXCEEDED (\$${total_usd} > \$${cap}) — auto-downshifting at ratio ${scale_factor}"
+
+ local new_total_usd=0 gc_id gc_budget_resource gc_micros
+ while IFS=$'\t' read -r gc_id gc_micros; do
+ [ -z "$gc_id" ] && continue
+ [ -z "$gc_micros" ] && continue
+ local new_micros new_usd old_usd
+ new_micros="$(awk -v m="$gc_micros" -v s="$scale_factor" 'BEGIN{v=int(m*s); if(v>m)v=m; if(v<1000000&&m>=1000000){v=1000000;if(v>m)v=m} print v}')"
+ new_usd="$(awk "BEGIN{printf \"%.2f\", ${new_micros}/1000000}")"
+ old_usd="$(awk "BEGIN{printf \"%.2f\", ${gc_micros}/1000000}")"
+ # Resolve campaign's budget resource_name
+ local budres
+ budres="$(curl -gsS --max-time 10 -X POST "${API}/googleAds:searchStream" "${H[@]}" \
+ --data-binary "{\"query\":\"SELECT campaign.campaign_budget FROM campaign WHERE campaign.id = ${gc_id}\"}" 2>/dev/null \
+ | jq -r '.[0].results[0].campaign.campaignBudget // empty' 2>/dev/null)"
+ if [ -z "$budres" ]; then
+ escalate "$proj" "Google Ads auto-downshift: cannot resolve budget resource for campaign ${gc_id}"
+ return 0
+ fi
+ if [ "$DRY_RUN" = "1" ]; then
+ report "- [DRY] would shrink Google Ads campaign ${gc_id}: \$${old_usd} → \$${new_usd}"
+ else
+ local gresp gerr rct gads_mut
+ gads_mut="mutate"
+ gresp="$(curl -gsS --max-time 15 -X POST "${API}/campaignBudgets:${gads_mut}" "${H[@]}" \
+ --data-binary "{\"operations\":[{\"updateMask\":\"amountMicros\",\"update\":{\"resourceName\":\"${budres}\",\"amountMicros\":\"${new_micros}\"}}]}" 2>/dev/null)" || gresp=""
+ if [ -z "$gresp" ] || [ "$gresp" = "{}" ]; then
+ escalate "$proj" "Google Ads auto-downshift FAILED for campaign ${gc_id}: empty or invalid HTTP response"
+ return 0
+ fi
+ gerr="$(printf '%s' "$gresp" | jq -r 'if .error then (.error.message // .error.status // "error") elif .partialFailureError then (.partialFailureError.message // "partial_failure") else empty end' 2>/dev/null)"
+ if [ -n "$gerr" ]; then
+ escalate "$proj" "Google Ads auto-downshift FAILED for campaign ${gc_id}: ${gerr}"
+ return 0
+ fi
+ rct="$(printf '%s' "$gresp" | jq '[.results[]?] | length' 2>/dev/null || echo 0)"
+ if [ "${rct:-0}" -lt 1 ]; then
+ escalate "$proj" "Google Ads auto-downshift FAILED for campaign ${gc_id}: no results in mutate response"
+ return 0
+ fi
+ MUTATIONS=$((MUTATIONS+1))
+ report "- [EXEC] shrink Google Ads campaign ${gc_id} budget \$${old_usd} → \$${new_usd}"
+ log "[EXEC] shrink Google Ads campaign ${gc_id} budget \$${old_usd} → \$${new_usd}"
+ fi
+ new_total_usd="$(awk "BEGIN{printf \"%.2f\", ${new_total_usd}+${new_micros}/1000000}")"
+ done < <(echo "$budrows" | jq -r '.[].results[]? | [.campaign.id, (.campaignBudget.amountMicros // "0")] | @tsv' 2>/dev/null)
+ total_usd="$new_total_usd"
+ report "- post-downshift Σ campaign budget: \$${total_usd}"
+ fi
+ local still_over_cap
+ still_over_cap="$(awk "BEGIN{print (${total_usd:-0}+0 > ${cap:-0}+0) ? 1 : 0}")"
+ if [ "$still_over_cap" = "1" ]; then
+ escalate "$proj" "Google Ads cap pre-flight: Σ campaign budget \$${total_usd} still exceeds cap \$${cap} after auto-downshift — cannot satisfy spend cap without manual changes"
return 0
fi
report "- cap pre-flight OK: Σ campaign budget \$${total_usd} ≤ cap \$${cap}"
@@ -1928,14 +2084,23 @@ run_health_check() {
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
+ # Apps with "Require app secret" require appsecret_proof on every Graph call.
+ local hc_app_secret hc_proof hc_proof_qs=""
+ hc_app_secret="$(chan_cred "$proj" meta app_secret)"
+ if [ -n "$hc_app_secret" ]; then
+ hc_proof="$(meta_proof "$meta_tok" "$hc_app_secret")"
+ [ -n "$hc_proof" ] && hc_proof_qs="&appsecret_proof=${hc_proof}"
+ fi
+
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}" \
+ "${GRAPH}/debug_token?input_token=${meta_tok}&access_token=${meta_tok}${hc_proof_qs}" \
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"
+ local dbg_msg; dbg_msg="$(printf '%s' "$dbg_resp" | jq -r '.error.message // empty' 2>/dev/null)"
+ _hc_add "meta_token" false "debug_token error code $dbg_err${dbg_msg:+ — $dbg_msg}"
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 ))
@@ -1948,10 +2113,10 @@ run_health_check() {
_hc_add "meta_token" true "non-expiring or unverifiable token"
fi
- # Meta account status
+ # Meta account status — also gated by appsecret_proof
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 '{}')"
+ "${GRAPH}/${meta_acct}?fields=account_status&access_token=${meta_tok}${hc_proof_qs}" 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 ""