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(marketing): auto-provision Instagram + Google Ads + appsecret_proof + portfolio dashboard (#266)

Aurora Capital8ee520c07743
diff --git a/claude-ops/bin/ops-marketing-dash b/claude-ops/bin/ops-marketing-dash
index 23dafacf..98d4db3c 100755
--- a/claude-ops/bin/ops-marketing-dash
+++ b/claude-ops/bin/ops-marketing-dash
@@ -75,6 +75,18 @@ GADS_REFRESH_TOKEN="$(get_cred 'google_ads.refresh_token' GOOGLE_ADS_REFRESH_TOK
GADS_CUSTOMER_ID="$(get_cred 'google_ads.customer_id' GOOGLE_ADS_CUSTOMER_ID google_ads_customer_id)"
GADS_LOGIN_CUSTOMER_ID="${GOOGLE_ADS_LOGIN_CUSTOMER_ID:-$(claude plugin config get google_ads_login_customer_id 2>/dev/null || echo "")}"
INSTAGRAM_ACCOUNT_ID="$(get_cred 'instagram.account_id' INSTAGRAM_ACCOUNT_ID instagram_account_id)"
+META_APP_SECRET="$(get_cred 'meta.app_secret' META_APP_SECRET meta_app_secret META_APP_SECRET)"
+
+# Compute appsecret_proof for projects that require it (Meta system-user tokens
+# and any project with app_secret configured). Empty string when no secret.
+META_PROOF=""
+if [ -n "$META_TOKEN" ] && [ -n "$META_APP_SECRET" ]; then
+ META_PROOF=$(printf '%s' "$META_TOKEN" | openssl dgst -sha256 -hmac "$META_APP_SECRET" -hex 2>/dev/null | awk '{print $NF}')
+fi
+
+# Build query-string fragment to append. Empty when no proof.
+META_PROOF_QS=""
+[ -n "$META_PROOF" ] && META_PROOF_QS="&appsecret_proof=${META_PROOF}"
# Strip dashes from customer ID (API requires no dashes)
GADS_CUSTOMER_ID="${GADS_CUSTOMER_ID//-/}"
@@ -130,7 +142,7 @@ gather_meta() {
return
fi
- INSIGHTS=$(curl -gsS --max-time 5 "https://graph.facebook.com/v18.0/${META_ACCOUNT}/insights?fields=spend,impressions,clicks,ctr,cpc,actions,action_values&date_preset=last_7d&level=account" \
+ INSIGHTS=$(curl -gsS --max-time 5 "https://graph.facebook.com/v18.0/${META_ACCOUNT}/insights?fields=spend,impressions,clicks,ctr,cpc,actions,action_values&date_preset=last_7d&level=account${META_PROOF_QS}" \
-H "Authorization: Bearer ${META_TOKEN}" 2>/dev/null)
SPEND=$(echo "$INSIGHTS" | jq -r '.data[0].spend // "0"' 2>/dev/null || echo "0")
@@ -252,7 +264,7 @@ gather_instagram() {
# Resolve IG account ID if not cached
IG_ID="$INSTAGRAM_ACCOUNT_ID"
if [ -z "$IG_ID" ]; then
- IG_ID=$(curl -gsS --max-time 5 "https://graph.facebook.com/v21.0/me/accounts?fields=instagram_business_account" \
+ IG_ID=$(curl -gsS --max-time 5 "https://graph.facebook.com/v21.0/me/accounts?fields=instagram_business_account${META_PROOF_QS}" \
-H "Authorization: Bearer ${META_TOKEN}" 2>/dev/null | jq -r '.data[0].instagram_business_account.id // empty')
[ -n "$IG_ID" ] && claude plugin config set instagram_account_id "$IG_ID" 2>/dev/null
fi
@@ -263,7 +275,7 @@ gather_instagram() {
fi
# Account stats
- ACCOUNT=$(curl -gsS --max-time 5 "https://graph.facebook.com/v21.0/${IG_ID}?fields=followers_count,media_count" \
+ ACCOUNT=$(curl -gsS --max-time 5 "https://graph.facebook.com/v21.0/${IG_ID}?fields=followers_count,media_count${META_PROOF_QS}" \
-H "Authorization: Bearer ${META_TOKEN}" 2>/dev/null)
FOLLOWERS=$(echo "$ACCOUNT" | jq -r '.followers_count // 0')
MEDIA_COUNT=$(echo "$ACCOUNT" | jq -r '.media_count // 0')
@@ -273,7 +285,7 @@ gather_instagram() {
START_DATE=$(date -v-7d +%Y-%m-%d 2>/dev/null || date -d '7 days ago' +%Y-%m-%d 2>/dev/null || echo "")
REACH=0
if [ -n "$START_DATE" ]; then
- INSIGHTS=$(curl -gsS --max-time 5 "https://graph.facebook.com/v21.0/${IG_ID}/insights?metric=reach&period=day&since=${START_DATE}&until=${END_DATE}" \
+ INSIGHTS=$(curl -gsS --max-time 5 "https://graph.facebook.com/v21.0/${IG_ID}/insights?metric=reach&period=day&since=${START_DATE}&until=${END_DATE}${META_PROOF_QS}" \
-H "Authorization: Bearer ${META_TOKEN}" 2>/dev/null)
REACH=$(echo "$INSIGHTS" | jq '[.data[]?.values[]?.value | tonumber] | add // 0' 2>/dev/null || echo "0")
fi
diff --git a/claude-ops/bin/ops-marketing-portfolio b/claude-ops/bin/ops-marketing-portfolio
new file mode 100755
index 00000000..1ef598ff
--- /dev/null
+++ b/claude-ops/bin/ops-marketing-portfolio
@@ -0,0 +1,232 @@
+#!/usr/bin/env bash
+# ops-marketing-portfolio — visual portfolio dashboard for ALL marketing projects.
+#
+# Reads marketing.projects.* from preferences.json and surfaces every configured
+# channel per project — including ones the single-project dash never showed:
+# - Resend (transactional/marketing email)
+# - AWS SNS (push/SMS)
+# - ShipBob (fulfillment)
+# - Meta Page / Business Manager
+# - GA4 Measurement Protocol
+# - Autopilot status (enabled / cap / kill_switch / autonomy_level)
+#
+# Pure config-state read. No external API calls — fast across 9+ projects.
+# Pair with `ops-marketing-dash --project <name>` for live KPI data.
+#
+# Usage:
+# ops-marketing-portfolio # rendered table (auto mobile-aware)
+# ops-marketing-portfolio --json # raw JSON, one row per project
+# ops-marketing-portfolio --project X # single-project deep config view
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+OPS_PLUGIN_ROOT_FALLBACK="${SCRIPT_DIR}/.." . "${SCRIPT_DIR}/../lib/registry-path.sh"
+PREFS="${OPS_DATA_DIR}/preferences.json"
+
+JSON_OUT=0
+FILTER_PROJECT=""
+for ((i=1; i<=$#; i++)); do
+ case "${!i}" in
+ --json) JSON_OUT=1 ;;
+ --project)
+ j=$((i+1)); FILTER_PROJECT="${!j:-}"
+ i=$((i+1))
+ ;;
+ esac
+done
+
+if [ ! -f "$PREFS" ]; then
+ echo "preferences.json not found at $PREFS" >&2
+ exit 1
+fi
+
+# Mobile-mode detection (Rule 7)
+MOBILE=0
+if [ -n "${SSH_CONNECTION:-}${SSH_CLIENT:-}${SSH_TTY:-}" ] || [ "${OPS_MOBILE:-}" = "1" ]; then
+ MOBILE=1
+fi
+COLS="${COLUMNS:-$(tput cols 2>/dev/null || echo 120)}"
+[ "$COLS" -lt 80 ] && MOBILE=1
+
+# Build the JSON portfolio.
+build_portfolio() {
+ local project_list
+ if [ -n "$FILTER_PROJECT" ]; then
+ project_list="$FILTER_PROJECT"
+ else
+ project_list=$(jq -r '.marketing.projects | keys[]' "$PREFS" 2>/dev/null)
+ fi
+
+ local rows="[]"
+ while IFS= read -r project; do
+ [ -z "$project" ] && continue
+ local row
+ row=$(jq -r --arg p "$project" '
+ .marketing.projects[$p] as $pc |
+ {
+ project: $p,
+ domain: ($pc.domain // null),
+ autopilot: {
+ enabled: ($pc.autopilot.enabled // false),
+ autonomy: ($pc.autopilot.autonomy_level // null),
+ cap_usd: ($pc.autopilot.daily_spend_cap_usd // 0),
+ kill_switch: ($pc.autopilot.envelope.kill_switch // false),
+ max_daily_usd: ($pc.autopilot.envelope.max_daily_budget_usd // null)
+ },
+ meta: (
+ if $pc.meta then {
+ configured: (($pc.meta.access_token // "") != ""),
+ ad_account_id: ($pc.meta.ad_account_id // null),
+ page_id: ($pc.meta.page_id // null),
+ page_name: ($pc.meta.page_name // null),
+ business_id: ($pc.meta.business_id // null),
+ app_id: ($pc.meta.app_id // null)
+ } else null end
+ ),
+ instagram: ($pc.instagram // null),
+ ga4: (
+ if $pc.ga4 then {
+ property_id: ($pc.ga4.property_id // null),
+ measurement_id: ($pc.ga4.measurement_id // null),
+ api_secret_set: (($pc.ga4.api_secret // "") != ""),
+ status: ($pc.ga4.status // null)
+ } else null end
+ ),
+ gsc: (
+ if $pc.gsc then {
+ site_url: ($pc.gsc.site_url // null),
+ verified: ($pc.gsc.verified // false)
+ } else null end
+ ),
+ google_ads: (
+ if $pc.google_ads then {
+ configured: (($pc.google_ads.refresh_token // "") != ""),
+ customer_id: ($pc.google_ads.customer_id // null)
+ } else null end
+ ),
+ email_marketing: {
+ resend: (
+ if $pc.email_marketing.resend then {
+ enabled: ($pc.email_marketing.resend.enabled // false),
+ from_address: ($pc.email_marketing.resend.from_address // null),
+ api_key_set: (($pc.email_marketing.resend.api_key // "") != "")
+ } else null end
+ ),
+ sns: (
+ if $pc.email_marketing.sns then {
+ enabled: ($pc.email_marketing.sns.enabled // false),
+ topic_arn: ($pc.email_marketing.sns.topic_arn // null),
+ region: ($pc.email_marketing.sns.region // null)
+ } else null end
+ ),
+ klaviyo: (
+ if $pc.klaviyo then {
+ configured: (($pc.klaviyo.private_key // "") != "")
+ } else null end
+ )
+ },
+ shipbob: (
+ if $pc.shipbob then {
+ configured: (($pc.shipbob.access_token // "") != "")
+ } else null end
+ )
+ }
+ ' "$PREFS")
+ rows=$(jq --argjson r "$row" '. + [$r]' <<< "$rows")
+ done <<< "$project_list"
+
+ echo "$rows"
+}
+
+PORTFOLIO=$(build_portfolio)
+
+if [ "$JSON_OUT" = "1" ]; then
+ echo "$PORTFOLIO" | jq .
+ exit 0
+fi
+
+# Render — mobile-aware
+PROJECT_COUNT=$(echo "$PORTFOLIO" | jq 'length')
+AUTOPILOT_ON=$(echo "$PORTFOLIO" | jq '[.[] | select(.autopilot.enabled == true)] | length')
+KILLED=$(echo "$PORTFOLIO" | jq '[.[] | select(.autopilot.kill_switch == true)] | length')
+RESEND_ON=$(echo "$PORTFOLIO" | jq '[.[] | select(.email_marketing.resend.enabled == true)] | length')
+SNS_ON=$(echo "$PORTFOLIO" | jq '[.[] | select(.email_marketing.sns.enabled == true)] | length')
+META_OK=$(echo "$PORTFOLIO" | jq '[.[] | select(.meta.configured == true)] | length')
+GADS_OK=$(echo "$PORTFOLIO" | jq '[.[] | select(.google_ads.configured == true)] | length')
+GA4_OK=$(echo "$PORTFOLIO" | jq '[.[] | select(.ga4.property_id != null and .ga4.property_id != "")] | length')
+
+if [ "$MOBILE" = "1" ]; then
+ echo "marketing portfolio — ${PROJECT_COUNT} projects"
+ echo "autopilot: ${AUTOPILOT_ON} on, ${KILLED} killswitched"
+ echo "channels: meta ${META_OK}, gads ${GADS_OK}, ga4 ${GA4_OK}, resend ${RESEND_ON}, sns ${SNS_ON}"
+ echo ""
+ echo "$PORTFOLIO" | jq -r '.[] |
+ "\(.project): " +
+ (if .autopilot.kill_switch then "KILLED" elif .autopilot.enabled then "live(cap $\(.autopilot.cap_usd))" else "off" end) +
+ " | " +
+ ([
+ (if .meta.configured then "meta" else null end),
+ (if .google_ads.configured then "gads" else null end),
+ (if .ga4.property_id then "ga4" else null end),
+ (if .gsc.site_url then "gsc" else null end),
+ (if .email_marketing.resend.enabled then "resend" else null end),
+ (if .email_marketing.sns.enabled then "sns" else null end),
+ (if .instagram.account_id then "ig" else null end),
+ (if .shipbob.configured then "shipbob" else null end)
+ ] | map(select(. != null)) | join(","))'
+ exit 0
+fi
+
+# Desktop render
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+echo " MARKETING PORTFOLIO — $(date +%Y-%m-%d)"
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+echo " Projects: ${PROJECT_COUNT} Autopilot live: ${AUTOPILOT_ON} Kill-switched: ${KILLED}"
+echo " Channels configured — Meta: ${META_OK}/${PROJECT_COUNT} Google Ads: ${GADS_OK}/${PROJECT_COUNT} GA4: ${GA4_OK}/${PROJECT_COUNT} Resend: ${RESEND_ON}/${PROJECT_COUNT} SNS: ${SNS_ON}/${PROJECT_COUNT}"
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+printf " %-13s %-10s %-7s %-5s %-4s %-4s %-3s %-3s %-6s %-3s %-3s %-7s\n" \
+ "Project" "Autopilot" "Cap/day" "Auton" "Meta" "GAds" "GA4" "GSC" "Resend" "SNS" "IG" "ShipBob"
+printf " %-13s %-10s %-7s %-5s %-4s %-4s %-3s %-3s %-6s %-3s %-3s %-7s\n" \
+ "-------------" "----------" "-------" "-----" "----" "----" "---" "---" "------" "---" "---" "-------"
+
+echo "$PORTFOLIO" | jq -c '.[]' | while IFS= read -r row; do
+ P=$(echo "$row" | jq -r '.project')
+ AP_EN=$(echo "$row" | jq -r '.autopilot.enabled')
+ AP_KS=$(echo "$row" | jq -r '.autopilot.kill_switch')
+ AP_CAP=$(echo "$row" | jq -r '.autopilot.cap_usd')
+ AP_AUT=$(echo "$row" | jq -r '.autopilot.autonomy // "—"')
+ META_OK=$(echo "$row"| jq -r 'if .meta.configured then "y" else "·" end')
+ GADS_OK=$(echo "$row"| jq -r 'if .google_ads.configured then "y" else "·" end')
+ GA4_OK=$(echo "$row" | jq -r 'if .ga4.property_id != null then "y" else "·" end')
+ GSC_OK=$(echo "$row" | jq -r 'if .gsc.site_url != null then (if .gsc.verified then "y" else "?" end) else "·" end')
+ RES_OK=$(echo "$row" | jq -r 'if .email_marketing.resend.enabled then "ON" else (if .email_marketing.resend.api_key_set then "off" else "·" end) end')
+ SNS_OK=$(echo "$row" | jq -r 'if .email_marketing.sns.enabled then "ON" else (if .email_marketing.sns.topic_arn then "rdy" else "·" end) end')
+ IG_OK=$(echo "$row" | jq -r 'if .instagram.account_id then "y" else "·" end')
+ SHB_OK=$(echo "$row" | jq -r 'if .shipbob.configured then "y" else "·" end')
+
+ if [ "$AP_KS" = "true" ]; then
+ AP_STATE="KILLED"
+ elif [ "$AP_EN" = "true" ]; then
+ AP_STATE="live"
+ else
+ AP_STATE="off"
+ fi
+ CAP_STR="\$${AP_CAP}"
+ printf " %-13s %-10s %-7s %-5s %-4s %-4s %-3s %-3s %-6s %-3s %-3s %-7s\n" \
+ "${P:0:13}" "$AP_STATE" "$CAP_STR" "${AP_AUT:0:5}" "$META_OK" "$GADS_OK" "$GA4_OK" "$GSC_OK" "$RES_OK" "$SNS_OK" "$IG_OK" "$SHB_OK"
+done
+
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+echo " Legend: y=configured · · =absent GSC: y=verified, ?=unverified Resend/SNS: ON=enabled, off/rdy=configured but disabled"
+echo " Drill in: ops-marketing-portfolio --project <name> (full config dump for one project)"
+echo " ops-marketing-dash --project <name> (live KPI pull — Meta/GA4/GSC/IG)"
+echo " ops-marketing-autopilot --health-check (per-project credential health probe)"
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+
+# If single-project filter was applied, also dump the full row JSON for deep inspection
+if [ -n "$FILTER_PROJECT" ]; then
+ echo ""
+ echo " Full config for ${FILTER_PROJECT}:"
+ echo "$PORTFOLIO" | jq '.[0]'
+fi
diff --git a/claude-ops/bin/ops-marketing-provision b/claude-ops/bin/ops-marketing-provision
index 150fcc0b..6df97dc4 100755
--- a/claude-ops/bin/ops-marketing-provision
+++ b/claude-ops/bin/ops-marketing-provision
@@ -2,11 +2,13 @@
# ops-marketing-provision — self-provision marketing channels for a project
#
# Subcommands:
-# provision-ga4 --project <key> [--domain <d>] [--account-id <acc>]
-# [--display-name <name>] [--industry SHOPPING|TECHNOLOGY]
-# provision-gsc --project <key> [--site sc-domain:<d>|https://<d>/]
-# provision-all --project <key>
-# status --project <key> [--json]
+# provision-ga4 --project <key> [--domain <d>] [--account-id <acc>]
+# [--display-name <name>] [--industry SHOPPING|TECHNOLOGY]
+# provision-gsc --project <key> [--site sc-domain:<d>|https://<d>/]
+# provision-instagram --project <key> [--force]
+# provision-google-ads --project <key> [--skip-if-pending]
+# provision-all --project <key> | --all-projects
+# status --project <key> [--json]
# --help
#
# Idempotent: GET-first, reuse existing matches before creating.
@@ -175,6 +177,28 @@ prefs_set_marketing() {
log "prefs: marketing.projects.$proj.$channel.$field = $value"
}
+# Apply multiple field updates atomically via a single jq pipeline.
+# Args: <proj> <channel> <field1> <value1> [<field2> <value2> ...]
+# Empty value strings are skipped (use prefs_unset_marketing to delete).
+prefs_set_marketing_multi() {
+ local proj="$1" channel="$2"; shift 2
+ [ -f "$PREFS" ] || echo '{}' > "$PREFS"
+
+ local tmp filter='.'
+ local jq_args=(--arg p "$proj" --arg c "$channel")
+ local i=0
+ while [ $# -ge 2 ]; do
+ local f="$1" v="$2"; shift 2
+ [ -z "$v" ] && continue
+ jq_args+=(--arg "f${i}" "$f" --arg "v${i}" "$v")
+ filter+=" | .marketing.projects[\$p][\$c][\$f${i}] = \$v${i}"
+ i=$((i+1))
+ done
+ tmp="$(mktemp)"
+ jq "${jq_args[@]}" "$filter" "$PREFS" > "$tmp" && mv "$tmp" "$PREFS"
+ log "prefs: marketing.projects.$proj.$channel updated ($i fields)"
+}
+
prefs_set_marketing_status() {
local proj="$1" channel="$2" status="$3"
prefs_set_marketing "$proj" "$channel" "status" "$status"
@@ -590,39 +614,448 @@ cmd_provision_gsc() {
[ -n "$verify_token" ] && info " verify_token: $verify_token"
}
+# ---------------------------------------------------------------------------
+# Meta appsecret_proof — required when "Require App Secret" is on (default for
+# all our system-user tokens). HMAC-SHA256(access_token, app_secret).
+# Echoes the hex digest (empty on missing inputs).
+# ---------------------------------------------------------------------------
+meta_appsecret_proof() {
+ local token="$1" secret="$2"
+ { [ -z "$token" ] || [ -z "$secret" ]; } && return 0
+ printf '%s' "$token" | openssl dgst -sha256 -hmac "$secret" -hex 2>/dev/null | awk '{print $NF}'
+}
+
+# ---------------------------------------------------------------------------
+# provision-instagram — resolve IG Business Account ID from Meta token.
+# Idempotent: skips API call if instagram.account_id already populated and
+# smoke-tests it before declaring success. Requires meta.access_token in prefs.
+# ---------------------------------------------------------------------------
+cmd_provision_instagram() {
+ local project="" force=0
+
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --project) project="${2:-}"; shift ;;
+ --force) force=1 ;;
+ *) die "Unknown argument to provision-instagram: $1" ;;
+ esac
+ shift
+ done
+
+ [ -n "$project" ] || die "--project is required"
+ need_cmd jq
+ need_cmd openssl
+ need_cmd curl
+
+ log "Provisioning Instagram for project: $project"
+
+ local meta_token_ref meta_secret_ref page_id existing
+ meta_token_ref="$(prefs_get_project_field "$project" "meta" "access_token")"
+ meta_secret_ref="$(prefs_get_project_field "$project" "meta" "app_secret")"
+ page_id="$(prefs_get_project_field "$project" "meta" "page_id")"
+ existing="$(prefs_get_project_field "$project" "instagram" "account_id")"
+
+ local meta_token meta_secret
+ meta_token="$(resolve_cred "$meta_token_ref")"
+ meta_secret="$(resolve_cred "$meta_secret_ref")"
+
+ if [ -z "$meta_token" ]; then
+ log "Meta access token not configured for $project — required before Instagram"
+ log "Configure marketing.projects.$project.meta.access_token in preferences.json first"
+ exit 2
+ fi
+
+ local proof
+ proof="$(meta_appsecret_proof "$meta_token" "$meta_secret")"
+ local proof_qs=""
+ [ -n "$proof" ] && proof_qs="&appsecret_proof=$proof"
+
+ # Idempotent short-circuit: if account_id already set and not --force, verify
+ # it still works against the API and exit clean.
+ if [ -n "$existing" ] && [ "$existing" != "null" ] && [ "$force" = "0" ]; then
+ log "Already configured: instagram.account_id=$existing — running smoke test"
+ if dry_notice "GET graph.facebook.com/v22.0/$existing?fields=username,followers_count"; then
+ info "[Instagram] dry-run: existing id=$existing"
+ return 0
+ fi
+ local probe
+ probe=$(http_call_allow_fail GET \
+ "https://graph.facebook.com/v22.0/$existing?fields=username,followers_count,media_count${proof_qs}" \
+ -H "Authorization: Bearer $meta_token" 2>/dev/null || echo "{}")
+ local username followers
+ username=$(printf '%s' "$probe" | jq -r '.username // empty' 2>/dev/null)
+ followers=$(printf '%s' "$probe" | jq -r '.followers_count // empty' 2>/dev/null)
+ if [ -n "$username" ]; then
+ info "[Instagram] ✓ verified @${username} (${followers:-0} followers) — id=$existing"
+ return 0
+ fi
+ log "Existing id $existing failed verification — re-resolving"
+ fi
+
+ # Resolve via Page if page_id known, else /me/accounts.
+ local ig_id=""
+ if [ -n "$page_id" ] && [ "$page_id" != "null" ]; then
+ if dry_notice "GET graph.facebook.com/v22.0/$page_id?fields=instagram_business_account,connected_instagram_account"; then
+ info "[DRY-RUN] would resolve IG via page $page_id"
+ return 0
+ fi
+ local page_resp
+ page_resp=$(http_call_allow_fail GET \
+ "https://graph.facebook.com/v22.0/$page_id?fields=instagram_business_account,connected_instagram_account,name${proof_qs}" \
+ -H "Authorization: Bearer $meta_token" 2>/dev/null || echo "{}")
+ ig_id=$(printf '%s' "$page_resp" | jq -r '.instagram_business_account.id // .connected_instagram_account.id // empty' 2>/dev/null)
+ fi
+
+ if [ -z "$ig_id" ]; then
+ if dry_notice "GET graph.facebook.com/v22.0/me/accounts?fields=id,name,instagram_business_account"; then
+ info "[DRY-RUN] would fall back to /me/accounts"
+ return 0
+ fi
+ local me_resp
+ me_resp=$(http_call_allow_fail GET \
+ "https://graph.facebook.com/v22.0/me/accounts?fields=id,name,instagram_business_account${proof_qs}" \
+ -H "Authorization: Bearer $meta_token" 2>/dev/null || echo "{}")
+ ig_id=$(printf '%s' "$me_resp" | jq -r '.data[0].instagram_business_account.id // empty' 2>/dev/null)
+ fi
+
+ if [ -z "$ig_id" ]; then
+ die "Could not resolve Instagram Business Account ID — ensure the Facebook Page is linked to an IG Business account in Meta Business Manager"
+ fi
+
+ # Smoke-test resolved ID
+ local probe username followers
+ probe=$(http_call GET \
+ "https://graph.facebook.com/v22.0/$ig_id?fields=username,followers_count,media_count${proof_qs}" \
+ -H "Authorization: Bearer $meta_token")
+ username=$(printf '%s' "$probe" | jq -r '.username // empty')
+ followers=$(printf '%s' "$probe" | jq -r '.followers_count // 0')
+
+ # Atomic prefs write
+ local now
+ now=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
+ prefs_set_marketing_multi "$project" "instagram" \
+ "account_id" "$ig_id" \
+ "username" "$username" \
+ "resolved_at" "$now"
+
+ info "[Instagram] ✓ resolved — @${username} (${followers} followers) — id=$ig_id"
+}
+
+# ---------------------------------------------------------------------------
+# Helper: scan env / Doppler for an existing Google Ads credential.
+# Args: <doppler_key> [env_var]
+# Echoes value if found (env first, then doppler), empty otherwise.
+# Always returns 0 — errexit-safe (callers check empty string, not exit code).
+# ---------------------------------------------------------------------------
+gads_scan_credential() {
+ local doppler_key="$1"
+ local env_var="${2:-$doppler_key}"
+ local val="${!env_var:-}"
+ if [ -n "$val" ]; then
+ printf '%s' "$val"
+ return 0
+ fi
+ if command -v doppler >/dev/null 2>&1; then
+ # Suppress non-zero exit when key is missing (set -e safety).
+ val="$(doppler secrets get "$doppler_key" --plain \
+ --project "$DOPPLER_PROJECT" --config "$DOPPLER_CONFIG" 2>/dev/null || true)"
+ printf '%s' "$val"
+ fi
+ return 0
+}
+
+# ---------------------------------------------------------------------------
+# provision-google-ads — 4-step Google Ads setup flow.
+# Step A: developer token (manual approval pathway with pending-state)
+# Step B: OAuth2 client (Cloud Console — shared across projects)
+# Step C: refresh token via browser OAuth callback
+# Step D: customer ID resolution (auto-MCC detection)
+# ---------------------------------------------------------------------------
+cmd_provision_google_ads() {
+ local project="" skip_if_pending=0
+
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --project) project="${2:-}"; shift ;;
+ --skip-if-pending) skip_if_pending=1 ;;
+ *) die "Unknown argument to provision-google-ads: $1" ;;
+ esac
+ shift
+ done
+
+ [ -n "$project" ] || die "--project is required"
+ need_cmd jq
+ need_cmd curl
+
+ local pending_dir="${OPS_DATA_DIR}/state/marketing-provision"
+ mkdir -p "$pending_dir"
+ local pending_file="${pending_dir}/${project}-google-ads-pending.json"
+
+ if [ "$skip_if_pending" = "1" ] && [ -f "$pending_file" ]; then
+ log "Google Ads still pending for $project (dev token approval) — skipping per --skip-if-pending"
+ return 0
+ fi
+
+ log "Provisioning Google Ads for project: $project"
+
+ # ── Step A: Developer Token ───────────────────────────────────────────
+ local dev_token
+ dev_token=$(gads_scan_credential GOOGLE_ADS_DEVELOPER_TOKEN)
+
+ if [ -z "$dev_token" ]; then
+ if [ "$DRY_RUN" = "1" ]; then
+ info "[DRY-RUN] dev token missing — would create pending state at $pending_file"
+ printf '{"project":"%s","stage":"developer_token","instructions":"Apply at ads.google.com/aw/apicenter","dry_run":true,"created_at":"%s"}\n' \
+ "$project" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$pending_file"
+ info "[Google Ads] DRY-RUN — pending file written ($pending_file). Apply for dev token at https://ads.google.com/aw/apicenter."
+ return 1
+ fi
+ log "GOOGLE_ADS_DEVELOPER_TOKEN not found in env or Doppler"
+ log "Apply for a developer token: https://ads.google.com/aw/apicenter"
+ log "Approval typically takes 24-48 hours. Re-run this command after approval."
+ printf '{"project":"%s","stage":"developer_token","instructions":"Apply at https://ads.google.com/aw/apicenter — re-run provision-google-ads --project %s after approval","created_at":"%s"}\n' \
+ "$project" "$project" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$pending_file"
+ log "Pending state written: $pending_file"
+ exit 1
+ fi
+ log "Developer token: present"
+
+ # ── Step B: OAuth2 Client ─────────────────────────────────────────────
+ local client_id client_secret
+ client_id=$(gads_scan_credential GOOGLE_ADS_CLIENT_ID)
+ client_secret=$(gads_scan_credential GOOGLE_ADS_CLIENT_SECRET)
+
+ if [ -z "$client_id" ] || [ -z "$client_secret" ]; then
+ if [ "$DRY_RUN" = "1" ]; then
+ info "[DRY-RUN] OAuth client missing — would create pending state"
+ printf '{"project":"%s","stage":"oauth_client","dry_run":true}\n' "$project" > "$pending_file"
+ return 1
+ fi
+ log "OAuth2 client credentials not found"
+ log "Create a Desktop OAuth client at: https://console.cloud.google.com/apis/credentials"
+ log " - Application type: Desktop app"
+ log " - Enabled API: Google Ads API"
+ log "Store as Doppler secrets: GOOGLE_ADS_CLIENT_ID, GOOGLE_ADS_CLIENT_SECRET"
+ printf '{"project":"%s","stage":"oauth_client","created_at":"%s"}\n' \
+ "$project" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$pending_file"
+ exit 1
+ fi
+ log "OAuth2 client: present"
+
+ # Source OAuth helper lib
+ # shellcheck disable=SC1091
+ . "${PLUGIN_ROOT}/scripts/lib/google-ads-oauth.sh"
+
+ # ── Step C: Refresh Token ─────────────────────────────────────────────
+ local refresh_token
+ refresh_token=$(gads_scan_credential "GOOGLE_ADS_${project^^}_REFRESH_TOKEN")
+ [ -z "$refresh_token" ] && refresh_token=$(gads_scan_credential GOOGLE_ADS_REFRESH_TOKEN)
+
+ if [ -z "$refresh_token" ]; then
+ if [ "$DRY_RUN" = "1" ]; then
+ info "[DRY-RUN] would launch localhost OAuth callback on :8080 (120s)"
+ printf '{"project":"%s","stage":"refresh_token","dry_run":true}\n' "$project" > "$pending_file"
+ return 1
+ fi
+ log "Starting OAuth browser flow on http://localhost:8080 (120s timeout)"
+ local auth_url
+ auth_url=$(gads_authorize_url "$client_id")
+ log "Open: $auth_url"
+ log "(opens automatically — Sam should authorize on the consent screen)"
+
+ # Open + capture in parallel; capture writes the code to a temp file.
+ local code_file
+ code_file=$(mktemp)
+ ( gads_localhost_capture 8080 120 > "$code_file" 2>/dev/null ) &
+ local capture_pid=$!
+ sleep 1
+ # Best-effort open (silent if `open` missing or on SSH per Rule 7)
+ if command -v open >/dev/null 2>&1 && [ -z "${SSH_CONNECTION:-}${SSH_CLIENT:-}${SSH_TTY:-}" ]; then
+ open "$auth_url" >/dev/null 2>&1 || true
+ fi
+ wait "$capture_pid" || true
+ local code
+ code=$(cat "$code_file" 2>/dev/null)
+ rm -f "$code_file"
+
+ [ -n "$code" ] || die "OAuth flow timed out — no authorization code received"
+ log "Authorization code received (${#code} chars)"
+
+ local token_resp
+ token_resp=$(gads_exchange_code "$code" "$client_id" "$client_secret")
+ refresh_token=$(printf '%s' "$token_resp" | jq -r '.refresh_token // empty')
+ [ -n "$refresh_token" ] || die "Token exchange failed: $(printf '%s' "$token_resp" | jq -r '.error_description // .error // "no refresh_token in response"')"
+
+ log "Refresh token obtained — writing to Doppler"
+ doppler_set "GOOGLE_ADS_${project^^}_REFRESH_TOKEN" "$refresh_token"
+ prefs_set_marketing "$project" "google_ads" "refresh_token" \
+ "doppler:${DOPPLER_PROJECT}/${DOPPLER_CONFIG}/GOOGLE_ADS_${project^^}_REFRESH_TOKEN"
+ else
+ log "Refresh token: present"
+ fi
+
+ # ── Step D: Customer ID ──────────────────────────────────────────────
+ local existing_customer
+ existing_customer="$(prefs_get_project_field "$project" "google_ads" "customer_id")"
+ if [ -n "$existing_customer" ] && [ "$existing_customer" != "null" ]; then
+ log "Customer ID already configured: $existing_customer"
+ rm -f "$pending_file"
+ info "[Google Ads] ✓ already configured — customer_id=$existing_customer"
+ return 0
+ fi
+
+ if dry_notice "POST oauth2.googleapis.com/token (refresh); GET v24/customers:listAccessibleCustomers"; then
+ info "[DRY-RUN] would resolve customer ID"
+ return 0
+ fi
+
+ local access_token
+ access_token=$(gads_refresh_access_token "$refresh_token" "$client_id" "$client_secret")
+ [ -n "$access_token" ] || die "Access token refresh failed — check client_id/client_secret/refresh_token"
+
+ local accessible
+ accessible=$(gads_list_accessible_customers "$access_token" "$dev_token")
+ local resource_names
+ resource_names=$(printf '%s' "$accessible" | jq -r '.resourceNames[]? // empty' 2>/dev/null)
+ [ -n "$resource_names" ] || die "No accessible customers — $(printf '%s' "$accessible" | jq -r '.error.message // "unknown error"')"
+
+ # Single account: auto-select. Multiple: log all and pick first non-manager.
+ local customer_count chosen_customer login_customer=""
+ customer_count=$(printf '%s\n' "$resource_names" | wc -l | tr -d ' ')
+ log "Accessible customers ($customer_count):"
+ printf '%s\n' "$resource_names" | sed 's/^/ - /' >&2
+
+ if [ "$customer_count" = "1" ]; then
+ local rn_single cid_single info_resp_single is_manager_single
+ rn_single=$(printf '%s\n' "$resource_names" | head -n1)
+ cid_single="${rn_single##customers/}"
+ info_resp_single=$(gads_get_customer_info "$cid_single" "$access_token" "$dev_token" 2>/dev/null || echo "{}")
+ is_manager_single=$(printf '%s' "$info_resp_single" | jq -r '.results[0].customer.manager // false' 2>/dev/null)
+ if [ "$is_manager_single" = "true" ]; then
+ login_customer="$cid_single"
+ log " (sole accessible account is MCC manager: $cid_single)"
+ fi
+ chosen_customer="$cid_single"
+ else
+ # Walk accounts, find first non-manager. Manager accounts become login_customer_id.
+ while IFS= read -r rn; do
+ [ -z "$rn" ] && continue
+ local cid info_resp is_manager
+ cid="${rn##customers/}"
+ info_resp=$(gads_get_customer_info "$cid" "$access_token" "$dev_token" 2>/dev/null || echo "{}")
+ is_manager=$(printf '%s' "$info_resp" | jq -r '.results[0].customer.manager // false' 2>/dev/null)
+ if [ "$is_manager" = "true" ] && [ -z "$login_customer" ]; then
+ login_customer="$cid"
+ log " (MCC manager: $cid)"
+ elif [ "$is_manager" = "false" ] && [ -z "$chosen_customer" ]; then
+ chosen_customer="$cid"
+ fi
+ done <<< "$resource_names"
+ [ -z "$chosen_customer" ] && chosen_customer=$(printf '%s\n' "$resource_names" | head -n1 | sed 's#^customers/##')
+ fi
+
+ log "Selected customer: $chosen_customer${login_customer:+ (login-customer-id: $login_customer)}"
+
+ # Atomic prefs write
+ prefs_set_marketing_multi "$project" "google_ads" \
+ "customer_id" "$chosen_customer" \
+ "developer_token" "doppler:${DOPPLER_PROJECT}/${DOPPLER_CONFIG}/GOOGLE_ADS_DEVELOPER_TOKEN" \
+ "client_id" "doppler:${DOPPLER_PROJECT}/${DOPPLER_CONFIG}/GOOGLE_ADS_CLIENT_ID" \
+ "client_secret" "doppler:${DOPPLER_PROJECT}/${DOPPLER_CONFIG}/GOOGLE_ADS_CLIENT_SECRET" \
+ "login_customer_id" "$login_customer" \
+ "configured_at" "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
+
+ rm -f "$pending_file"
+ info "[Google Ads] ✓ configured — customer_id=$chosen_customer"
+}
+
# ---------------------------------------------------------------------------
# provision-all
# ---------------------------------------------------------------------------
cmd_provision_all() {
- local project="" site_for_gsc="" ga4_remaining=()
+ local project="" site_for_gsc="" all_projects=0 ga4_remaining=()
while [ $# -gt 0 ]; do
case "$1" in
--project) project="${2:-}"; shift ;;
--site) site_for_gsc="${2:-}"; shift ;;
+ --all-projects) all_projects=1 ;;
*) ga4_remaining+=("$1") ;;
esac
shift
done
- [ -n "$project" ] || die "--project is required"
+ if [ "$all_projects" = "1" ]; then
+ [ -f "$PREFS" ] || die "preferences.json not found — cannot iterate projects"
+ local project_list
+ project_list=$(jq -r '.marketing.projects | keys[]' "$PREFS")
+ [ -n "$project_list" ] || die "no projects in marketing.projects"
+ local failed=0
+ while IFS= read -r p; do
+ info "════════════════════════════════════════════════════════════════"
+ info " $p"
+ info "════════════════════════════════════════════════════════════════"
+ cmd_provision_all --project "$p" || failed=$((failed+1))
+ info ""
+ done <<< "$project_list"
+ [ "$failed" = "0" ] || log "$failed project(s) had failures — see logs above"
+ return $failed
+ fi
+
+ [ -n "$project" ] || die "--project is required (or use --all-projects)"
info "Provisioning all channels for project: $project"
info ""
+ local provision_failures=0
+ # Each sub-call runs in a subshell so a downstream `die`/`exit` only kills
+ # that subshell — the chain continues to the next channel. Failures are
+ # logged but do not abort provision-all.
info "--- GA4 ---"
- cmd_provision_ga4 --project "$project" "${ga4_remaining[@]+"${ga4_remaining[@]}"}"
+ ( cmd_provision_ga4 --project "$project" "${ga4_remaining[@]+"${ga4_remaining[@]}"}" ) || {
+ log "GA4 provisioning failed for $project (continuing with other channels)"
+ provision_failures=$((provision_failures + 1))
+ }
info ""
info "--- Google Search Console ---"
if [ -n "$site_for_gsc" ]; then
- cmd_provision_gsc --project "$project" --site "$site_for_gsc"
+ ( cmd_provision_gsc --project "$project" --site "$site_for_gsc" ) || {
+ log "GSC provisioning failed for $project (continuing)"
+ provision_failures=$((provision_failures + 1))
+ }
+ else
+ ( cmd_provision_gsc --project "$project" ) || {
+ log "GSC provisioning failed for $project (continuing)"
+ provision_failures=$((provision_failures + 1))
+ }
+ fi
+ info ""
+
+ info "--- Instagram ---"
+ # IG is best-effort: silent no-op if Meta token not configured.
+ local meta_tok_ref
+ meta_tok_ref="$(prefs_get_project_field "$project" "meta" "access_token")"
+ if [ -n "$meta_tok_ref" ] && [ "$meta_tok_ref" != "null" ]; then
+ ( cmd_provision_instagram --project "$project" ) || {
+ log "Instagram provisioning failed for $project (continuing)"
+ provision_failures=$((provision_failures + 1))
+ }
else
- cmd_provision_gsc --project "$project"
+ log "Skipping Instagram — meta.access_token not configured"
fi
info ""
+ info "--- Google Ads ---"
+ # Skip if pending (dev token approval in progress).
+ ( cmd_provision_google_ads --project "$project" --skip-if-pending ) || {
+ log "Google Ads provisioning incomplete for $project (likely awaiting dev token approval)"
+ provision_failures=$((provision_failures + 1))
+ }
+ info ""
+
info "Done. Run: $0 status --project $project"
+ return "$provision_failures"
}
# ---------------------------------------------------------------------------
@@ -659,10 +1092,12 @@ cmd_help() {
ops-marketing-provision — self-provision marketing channels
Usage:
- ops-marketing-provision provision-ga4 --project <key> [options]
- ops-marketing-provision provision-gsc --project <key> [--site <url>]
- ops-marketing-provision provision-all --project <key> [options]
- ops-marketing-provision status --project <key> [--json]
+ ops-marketing-provision provision-ga4 --project <key> [options]
+ ops-marketing-provision provision-gsc --project <key> [--site <url>]
+ ops-marketing-provision provision-instagram --project <key> [--force]
+ ops-marketing-provision provision-google-ads --project <key> [--skip-if-pending]
+ ops-marketing-provision provision-all (--project <key> | --all-projects)
+ ops-marketing-provision status --project <key> [--json]
ops-marketing-provision --help
provision-ga4 options:
@@ -676,6 +1111,29 @@ provision-gsc options:
--project <key> Project key
--site <url> Site URL: sc-domain:example.com or https://example.com/
+provision-instagram options:
+ --project <key> Project key
+ --force Re-resolve even if instagram.account_id is already set
+ Requires marketing.projects.<key>.meta.access_token (token + optional app_secret
+ for appsecret_proof signing). Idempotent — smoke-tests existing IDs before re-API.
+
+provision-google-ads options:
+ --project <key> Project key
+ --skip-if-pending Exit 0 if dev-token approval is pending (for provision-all chains)
+
+ Four-step flow (each step is no-op if cred already present):
+ A. GOOGLE_ADS_DEVELOPER_TOKEN — scan env+Doppler. If missing, writes a pending
+ state file at $OPS_DATA_DIR/state/marketing-provision/<key>-google-ads-pending.json
+ and exits 1 with instructions to apply at https://ads.google.com/aw/apicenter
+ (24-48h approval).
+ B. GOOGLE_ADS_CLIENT_ID/CLIENT_SECRET — scan env+Doppler. If missing, prints
+ Cloud Console URL to create a Desktop OAuth client.
+ C. Refresh token — launches a localhost OAuth callback on :8080 (120s timeout),
+ opens the consent URL, captures the auth code, exchanges for refresh_token,
+ writes to Doppler GOOGLE_ADS_<KEY_UPPER>_REFRESH_TOKEN.
+ D. Customer ID — calls v24/customers:listAccessibleCustomers, auto-detects MCC
+ manager accounts (sets login_customer_id), writes customer_id to prefs.
+
Environment variables:
OPS_MARKETING_DRY_RUN=1 Print planned actions, no network calls
OPS_MARKETING_BACKGROUND=1 Suppress interactive prompts
@@ -715,10 +1173,12 @@ SUBCMD="${1:-}"
shift
case "$SUBCMD" in
- provision-ga4) cmd_provision_ga4 "$@" ;;
- provision-gsc) cmd_provision_gsc "$@" ;;
- provision-all) cmd_provision_all "$@" ;;
- status) cmd_status "$@" ;;
- --help|-h|help) cmd_help ;;
+ provision-ga4) cmd_provision_ga4 "$@" ;;
+ provision-gsc) cmd_provision_gsc "$@" ;;
+ provision-instagram) cmd_provision_instagram "$@" ;;
+ provision-google-ads) cmd_provision_google_ads "$@" ;;
+ provision-all) cmd_provision_all "$@" ;;
+ status) cmd_status "$@" ;;
+ --help|-h|help) cmd_help ;;
*) die "Unknown subcommand: $SUBCMD — run '$0 --help' for usage" ;;
esac
diff --git a/claude-ops/scripts/lib/ga4-resolve.sh b/claude-ops/scripts/lib/ga4-resolve.sh
index 74bed89e..7cfb1c7c 100755
--- a/claude-ops/scripts/lib/ga4-resolve.sh
+++ b/claude-ops/scripts/lib/ga4-resolve.sh
@@ -154,12 +154,13 @@ marketing_channels_status() {
[ -n "$val" ] && [ "$val" != "null" ] && echo "true" || echo "false"
}
- local ga4_ok gsc_ok meta_ok gads_ok klaviyo_ok
+ local ga4_ok gsc_ok meta_ok gads_ok klaviyo_ok ig_ok
ga4_ok="$(_chan_set "ga4" "property_id")"
gsc_ok="$(_chan_set "gsc" "site_url")"
meta_ok="$(_chan_set "meta" "access_token")"
gads_ok="$(_chan_set "google_ads" "developer_token")"
klaviyo_ok="$(_chan_set "klaviyo" "private_key")"
+ ig_ok="$(_chan_set "instagram" "account_id")"
_label() { [ "$1" = "true" ] && echo "configured" || echo "missing"; }
@@ -170,12 +171,14 @@ marketing_channels_status() {
--arg meta "$(_label "$meta_ok")" \
--arg google_ads "$(_label "$gads_ok")" \
--arg klaviyo "$(_label "$klaviyo_ok")" \
- '{ga4: $ga4, gsc: $gsc, meta: $meta, google_ads: $google_ads, klaviyo: $klaviyo}'
+ --arg instagram "$(_label "$ig_ok")" \
+ '{ga4: $ga4, gsc: $gsc, meta: $meta, google_ads: $google_ads, klaviyo: $klaviyo, instagram: $instagram}'
else
echo "ga4: $(_label "$ga4_ok")"
echo "gsc: $(_label "$gsc_ok")"
echo "meta: $(_label "$meta_ok")"
echo "google_ads: $(_label "$gads_ok")"
echo "klaviyo: $(_label "$klaviyo_ok")"
+ echo "instagram: $(_label "$ig_ok")"
fi
}
diff --git a/claude-ops/scripts/lib/google-ads-oauth.sh b/claude-ops/scripts/lib/google-ads-oauth.sh
new file mode 100644
index 00000000..a201bd13
--- /dev/null
+++ b/claude-ops/scripts/lib/google-ads-oauth.sh
@@ -0,0 +1,172 @@
+#!/usr/bin/env bash
+# google-ads-oauth.sh — Google Ads OAuth helper for ops-marketing-provision.
+#
+# Exports:
+# gads_authorize_url <client_id> <redirect_uri>
+# → echoes the full authorization URL to send the user through Google.
+#
+# gads_localhost_capture <port> <timeout_seconds>
+# → starts a tiny Node HTTP server in the background, blocks until the
+# OAuth callback hits, echoes the captured `code` param to stdout,
+# then exits. Returns non-zero if the timeout elapses or Node is missing.
+#
+# gads_exchange_code <code> <client_id> <client_secret> <redirect_uri>
+# → POSTs to https://oauth2.googleapis.com/token to exchange the
+# authorization code for { access_token, refresh_token, ... }.
+# Echoes the full JSON response.
+#
+# gads_refresh_access_token <refresh_token> <client_id> <client_secret>
+# → POSTs grant_type=refresh_token to get a fresh access_token.
+# Echoes the access token (string only, no JSON).
+#
+# gads_list_accessible_customers <access_token> <developer_token> [login_customer_id]
+# → GETs /v24/customers:listAccessibleCustomers. Echoes JSON response.
+#
+# gads_get_customer_info <customer_id> <access_token> <developer_token> [login_customer_id]
+# → GETs /v24/customers/<id>:search with the customer.manager field so
+# the caller can decide whether to set login-customer-id for sub-calls.
+# Echoes JSON response.
+#
+# Endpoints validated against:
+# - Google OIDC discovery doc (accounts.google.com/.well-known/openid-configuration)
+# - Google Ads API OAuth Internals (developers.google.com/google-ads/api/docs/oauth/internals)
+# - List Accessible Customers v24 (developers.google.com/google-ads/api/docs/account-management/listing-accounts)
+#
+# All functions are side-effect-free except gads_localhost_capture which binds
+# port 8080 by default. Caller is responsible for credentials (no secrets logged).
+
+set -u
+
+# ---------------------------------------------------------------------------
+# Canonical endpoints (validated via openid-configuration on 2026-05-20)
+# ---------------------------------------------------------------------------
+GADS_AUTH_ENDPOINT="${GADS_AUTH_ENDPOINT:-https://accounts.google.com/o/oauth2/v2/auth}"
+GADS_TOKEN_ENDPOINT="${GADS_TOKEN_ENDPOINT:-https://oauth2.googleapis.com/token}"
+GADS_API_BASE="${GADS_API_BASE:-https://googleads.googleapis.com/v24}"
+GADS_SCOPE="${GADS_SCOPE:-https://www.googleapis.com/auth/adwords}"
+
+# ---------------------------------------------------------------------------
+# gads_authorize_url <client_id> [redirect_uri]
+# ---------------------------------------------------------------------------
+gads_authorize_url() {
+ local client_id="$1"
+ local redirect_uri="${2:-http://localhost:8080}"
+ local encoded_scope
+ encoded_scope=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1], safe=''))" "$GADS_SCOPE" 2>/dev/null \
+ || printf '%s' "$GADS_SCOPE" | sed 's|:|%3A|g; s|/|%2F|g')
+ printf '%s?client_id=%s&redirect_uri=%s&response_type=code&scope=%s&access_type=offline&prompt=consent' \
+ "$GADS_AUTH_ENDPOINT" \
+ "$client_id" \
+ "$redirect_uri" \
+ "$encoded_scope"
+}
+
+# ---------------------------------------------------------------------------
+# gads_localhost_capture <port> <timeout_seconds>
+# Blocks until OAuth callback is received or timeout elapses.
+# Echoes the `code` query param on success; non-zero exit on failure.
+# ---------------------------------------------------------------------------
+gads_localhost_capture() {
+ local port="${1:-8080}"
+ local timeout="${2:-120}"
+
+ command -v node >/dev/null 2>&1 || {
+ printf '[google-ads-oauth] Node.js required for localhost OAuth capture\n' >&2
+ return 2
+ }
+
+ # Single-shot HTTP server: accepts first request, extracts ?code=, exits.
+ # Writes the code to stdout; exits 0 on success, 1 on timeout.
+ node -e "
+ const http = require('http');
+ const server = http.createServer((req, res) => {
+ const code = new URL(req.url, 'http://localhost').searchParams.get('code');
+ const err = new URL(req.url, 'http://localhost').searchParams.get('error');
+ if (err) {
+ res.writeHead(400, {'Content-Type': 'text/html'});
+ res.end('<html><body><h1>OAuth error: ' + err + '</h1>You can close this tab.</body></html>');
+ server.close();
+ process.exit(1);
+ }
+ if (code) {
+ res.writeHead(200, {'Content-Type': 'text/html'});
+ res.end('<html><body><h1>Authorization received.</h1>You can close this tab and return to the terminal.</body></html>');
+ process.stdout.write(code);
+ server.close();
+ process.exit(0);
+ }
+ res.writeHead(200);
+ res.end('Waiting...');
+ });
+ server.listen($port, '127.0.0.1');
+ setTimeout(() => { server.close(); process.exit(1); }, $timeout * 1000);
+ "
+}
+
+# ---------------------------------------------------------------------------
+# gads_exchange_code <code> <client_id> <client_secret> [redirect_uri]
+# Echoes JSON: { access_token, refresh_token, expires_in, scope, token_type }
+# ---------------------------------------------------------------------------
+gads_exchange_code() {
+ local code="$1"
+ local client_id="$2"
+ local client_secret="$3"
+ local redirect_uri="${4:-http://localhost:8080}"
+
+ curl -sS --max-time 15 -X POST "$GADS_TOKEN_ENDPOINT" \
+ --data-urlencode "code=$code" \
+ --data-urlencode "client_id=$client_id" \
+ --data-urlencode "client_secret=$client_secret" \
+ --data-urlencode "redirect_uri=$redirect_uri" \
+ --data-urlencode "grant_type=authorization_code"
+}
+
+# ---------------------------------------------------------------------------
+# gads_refresh_access_token <refresh_token> <client_id> <client_secret>
+# Echoes the access_token string (or empty on failure).
+# ---------------------------------------------------------------------------
+gads_refresh_access_token() {
+ local refresh_token="$1"
+ local client_id="$2"
+ local client_secret="$3"
+
+ curl -sS --max-time 15 -X POST "$GADS_TOKEN_ENDPOINT" \
+ --data-urlencode "client_id=$client_id" \
+ --data-urlencode "client_secret=$client_secret" \
+ --data-urlencode "refresh_token=$refresh_token" \
+ --data-urlencode "grant_type=refresh_token" \
+ | jq -r '.access_token // empty' 2>/dev/null
+}
+
+# ---------------------------------------------------------------------------
+# gads_list_accessible_customers <access_token> <developer_token> [login_customer_id]
+# Echoes JSON: { resourceNames: ["customers/1234567890", ...] }
+# ---------------------------------------------------------------------------
+gads_list_accessible_customers() {
+ local access_token="$1"
+ local developer_token="$2"
+ local login_customer_id="${3:-}"
+
+ local headers=(-H "Authorization: Bearer $access_token" -H "developer-token: $developer_token")
+ [ -n "$login_customer_id" ] && headers+=(-H "login-customer-id: $login_customer_id")
+
+ curl -sS --max-time 15 -X GET "$GADS_API_BASE/customers:listAccessibleCustomers" "${headers[@]}"
+}
+
+# ---------------------------------------------------------------------------
+# gads_get_customer_info <customer_id> <access_token> <developer_token> [login_customer_id]
+# Returns customer.manager + customer.descriptive_name + customer.currency_code
+# Echoes JSON response (use jq downstream).
+# ---------------------------------------------------------------------------
+gads_get_customer_info() {
+ local customer_id="$1"
+ local access_token="$2"
+ local developer_token="$3"
+ local login_customer_id="${4:-}"
+
+ local headers=(-H "Authorization: Bearer $access_token" -H "developer-token: $developer_token" -H "Content-Type: application/json")
+ [ -n "$login_customer_id" ] && headers+=(-H "login-customer-id: $login_customer_id")
+
+ curl -sS --max-time 15 -X POST "$GADS_API_BASE/customers/$customer_id/googleAds:search" "${headers[@]}" \
+ --data-binary '{"query": "SELECT customer.id, customer.manager, customer.descriptive_name, customer.currency_code, customer.time_zone FROM customer LIMIT 1"}'
+}
diff --git a/claude-ops/skills/ops-marketing/SKILL.md b/claude-ops/skills/ops-marketing/SKILL.md
index ed6890b2..3603b6bf 100644
--- a/claude-ops/skills/ops-marketing/SKILL.md
+++ b/claude-ops/skills/ops-marketing/SKILL.md
@@ -153,20 +153,34 @@ Run `/ops:marketing <project>` to point-and-go:
Provision a brand-new project end-to-end:
```bash
-# One-shot: GA4 + GSC together
+# One-shot: GA4 + GSC + Instagram + Google Ads — sequential, idempotent
ops-marketing-provision provision-all --project <project>
+# Iterate every project in prefs
+ops-marketing-provision provision-all --all-projects
+
# Or individually:
-ops-marketing-provision provision-ga4 --project <project> \
+ops-marketing-provision provision-ga4 --project <project> \
--domain <domain> --account-id <YOUR_GA4_ACCOUNT_ID>
-ops-marketing-provision provision-gsc --project <project> \
- --site https://<domain>/
+ops-marketing-provision provision-gsc --project <project> --site https://<domain>/
+ops-marketing-provision provision-instagram --project <project> # auto-resolves via Meta token
+ops-marketing-provision provision-google-ads --project <project> # 4-step OAuth flow
# Check results
ops-marketing-provision status --project <project> --json
ops-marketing-dash --project <project>
```
+`provision-instagram` requires `marketing.projects.<key>.meta.access_token` (and optional `meta.app_secret` for `appsecret_proof` signing — required when the app's "Require App Secret" setting is on, which is the default for all system-user tokens). The verb is fully idempotent: smoke-tests an existing `instagram.account_id` before making any API calls; pass `--force` to re-resolve.
+
+`provision-google-ads` is a 4-step flow (each step is a no-op if the credential already exists):
+1. **Developer token** — scans env + Doppler. If missing, writes a pending-state JSON at `${OPS_DATA_DIR}/state/marketing-provision/<project>-google-ads-pending.json` and exits 1. Apply at <https://ads.google.com/aw/apicenter> (24–48h approval) then re-run.
+2. **OAuth client** — scans env + Doppler. If missing, prints Cloud Console URL for creating a Desktop OAuth client.
+3. **Refresh token** — launches a localhost HTTP server on `:8080` (120s timeout), opens the Google consent URL, captures the auth code, exchanges for `refresh_token`, writes to Doppler as `GOOGLE_ADS_<PROJECT_UPPER>_REFRESH_TOKEN`.
+4. **Customer ID** — calls `v24/customers:listAccessibleCustomers`, auto-detects MCC manager accounts (sets `login_customer_id`), writes `customer_id` to prefs.
+
+Pass `--skip-if-pending` to skip when a dev-token application is in-flight (used by `provision-all` to keep the chain unblocked).
+
Set `OPS_MARKETING_DRY_RUN=1` to print planned API calls without executing.
## Runtime Context
@@ -340,7 +354,9 @@ Route `$ARGUMENTS` to the correct section below:
| Input | Action |
|---|---|
-| (empty), dashboard | Run full marketing dashboard |
+| (empty), dashboard, portfolio | Visual portfolio dashboard — all projects × all configured channels (Meta, Google Ads, GA4, GSC, Resend, SNS, IG, ShipBob, autopilot state). See ## dashboard section. |
+| portfolio --json | Machine-readable portfolio JSON (one row per project, full channel config) |
+| portfolio --project `<name>` | Full single-project config dump (every channel block) |
| `<project>` | If `marketing.projects.<project>.autopilot.enabled == true` → run live autopilot pass for that project. Otherwise → run `bin/ops-marketing-provision provision-all --project <project>` then `bin/ops-marketing-autopilot --project <project> --dry-run` (see ## project entry-point section) |
| email, klaviyo | Klaviyo email metrics |
| ads, meta | Meta Ads performance (read-only overview) |
@@ -353,6 +369,10 @@ Route `$ARGUMENTS` to the correct section below:
| instagram, instagram post, instagram reel, instagram story, instagram insights, instagram demographics | Instagram publishing + insights (see ## instagram section) |
| campaigns | Cross-channel campaign overview (all platforms) |
| optimize | Cross-platform ad optimization agent |
+| `provision <project>` | Idempotent full sweep — provisions GA4, GSC, Instagram, Google Ads in order. Each step is no-op if already configured. Aliases: `provision-all <project>` |
+| `provision-instagram <project>` | Auto-resolves `instagram.account_id` from Meta token (uses `appsecret_proof` when `meta.app_secret` configured). |
+| `provision-google-ads <project>` | 4-step OAuth flow — developer token + OAuth client + refresh token (localhost callback :8080) + customer ID resolution with auto-MCC detection. |
+| `provision --all-projects` | Iterate every project in prefs, run `provision-all` per project. |
| autopilot | Autonomous per-project daily ad management (see ## autopilot section) |
| autopilot onboard `<url>` | Cold-start: scrape URL, derive strategy, scaffold/stage campaigns (see ## autopilot → Autonomous onboarding) |
| `autopilot enable <project> [--cap <usd>]` | Enable autopilot for a project (see ## autopilot-enable section) |
@@ -2315,13 +2335,30 @@ printf "| %-14s | \$%-9s | %-12s | \$%-11s | %-8s |\n" "TOTAL (ads)" "$TOTAL_AD_
## dashboard (default — no args)
-Run ALL sections in parallel, then render unified dashboard.
+The default `/ops:marketing` view is the **portfolio dashboard** — every configured project across every channel (Meta, Google Ads, GA4, GSC, Resend, SNS, Instagram, ShipBob, autopilot status). No API spam — pure config-state read, fast across 9+ projects.
```bash
-# Run the pre-gathered data script
-"${CLAUDE_PLUGIN_ROOT}/bin/ops-marketing-dash" 2>/dev/null
+"${CLAUDE_PLUGIN_ROOT}/bin/ops-marketing-portfolio" 2>/dev/null
```
+For a **live KPI pull** on a single project (Meta spend, GA4 sessions, GSC clicks, IG reach), use the per-project dash:
+
+```bash
+"${CLAUDE_PLUGIN_ROOT}/bin/ops-marketing-dash" --project <name> 2>/dev/null
+```
+
+Routing summary:
+
+| Input | Action |
+|---|---|
+| `/ops:marketing` (no args) | Portfolio: all projects × all channels (configured/enabled state) |
+| `/ops:marketing dashboard` | Same as no args |
+| `/ops:marketing <project>` | If autopilot enabled → live pass; else provision + dry-run + per-project KPI dash |
+| `/ops:marketing portfolio --json` | Machine-readable portfolio dump |
+| `/ops:marketing portfolio --project <name>` | Single-project full config dump |
+
+The portfolio surfaces channels the per-project dash never showed: **Resend** (transactional/marketing email — `email_marketing.resend`), **AWS SNS** (push/SMS — `email_marketing.sns`), **ShipBob** (fulfillment — `shipbob`), **Meta Page/Business** (`meta.page_id`/`business_id`), and **GA4 Measurement Protocol** (`ga4.measurement_id`/`api_secret`). It also exposes per-project autopilot state (enabled / autonomy_level / cap_usd / kill_switch) at-a-glance — the kill-switch column is the answer to "which projects are stage-only right now".
+
### Competitor signals (gather before rendering)
```bash
diff --git a/claude-ops/skills/setup/channels/marketing.md b/claude-ops/skills/setup/channels/marketing.md
index 8a27c2e2..6144a5b0 100644
--- a/claude-ops/skills/setup/channels/marketing.md
+++ b/claude-ops/skills/setup/channels/marketing.md
@@ -81,98 +81,100 @@ curl -s "https://graph.facebook.com/v20.0/$AD_ACCOUNT_ID/campaigns?access_token=
#### Google Ads
-Google Ads requires three credential groups. Guide the user through each step sequentially.
+**Primary path — delegate to the provision binary:**
-**Step A — Developer Token:**
-If `GOOGLE_ADS_DEVELOPER_TOKEN` was found in auto-scan, present it and offer `[Keep]` / `[Reconfigure]`.
-Otherwise, ask via free text:
-> Your Google Ads developer token (found in Google Ads → Tools & Settings → API Center).
-> Note: New developer tokens start in "test" mode — they work against test accounts only. For production data, apply for Basic Access at https://ads.google.com/home/tools/manager-accounts/
+```bash
+ops-marketing-provision provision-google-ads --project <project>
+```
-**Step B — OAuth2 Client Credentials:**
-If `GOOGLE_ADS_CLIENT_ID` and `GOOGLE_ADS_CLIENT_SECRET` were found in auto-scan, present and offer `[Keep]` / `[Reconfigure]`.
-Otherwise, ask via free text (two prompts):
-1. OAuth2 Client ID (from Google Cloud Console → APIs & Services → Credentials → OAuth 2.0 Client ID, type: Desktop app, Google Ads API must be enabled)
-2. OAuth2 Client Secret (shown alongside the client ID)
+This is now a callable 4-step flow (each step is a no-op if already configured):
-**Step C — Refresh Token (browser OAuth flow):**
-If `GOOGLE_ADS_REFRESH_TOKEN` was found in auto-scan, present and offer `[Keep]` / `[Reconfigure]`.
-Otherwise, generate the auth URL and run the OAuth flow:
+- **Step A — Developer token.** Scans env + Doppler. If missing, writes a pending-state file at `${OPS_DATA_DIR}/state/marketing-provision/<project>-google-ads-pending.json` with the application URL <https://ads.google.com/aw/apicenter>, then exits 1. Approval takes 24–48h.
+- **Step B — OAuth2 client.** Scans env + Doppler for `GOOGLE_ADS_CLIENT_ID` + `GOOGLE_ADS_CLIENT_SECRET`. If missing, prints the Cloud Console URL for creating a Desktop OAuth client.
+- **Step C — Refresh token.** Starts a Node HTTP server on `:8080` (120s timeout), opens the consent URL, captures the `code` query param, POSTs to `https://oauth2.googleapis.com/token` to exchange for `refresh_token`, writes to Doppler as `GOOGLE_ADS_<PROJECT_UPPER>_REFRESH_TOKEN`.
+- **Step D — Customer ID.** Calls `v24/customers:listAccessibleCustomers`. Auto-detects MCC manager accounts via the `customer.manager` field (sets `login_customer_id`). Writes everything to `marketing.projects.<project>.google_ads` as Doppler cred-refs.
-```bash
-AUTH_URL="https://accounts.google.com/o/oauth2/auth?client_id=${GADS_CLIENT_ID}&redirect_uri=http://localhost:8080&response_type=code&scope=https://www.googleapis.com/auth/adwords&access_type=offline&prompt=consent"
-open "$AUTH_URL" # macOS
-```
+**Test-mode caveat:** if the Google Cloud OAuth app is in "Testing" publishing status, refresh tokens expire in 7 days. Surface this to the user; recommend "Publish App" in Cloud Console → OAuth consent screen.
-Start a temporary localhost server to catch the redirect:
-```bash
-# One-liner node HTTP server to capture the auth code
-node -e "require('http').createServer((req,res)=>{const code=new URL(req.url,'http://localhost').searchParams.get('code');if(code){res.end('Authorization code received. You can close this tab.');process.stdout.write(code);process.exit(0)}else{res.end('Waiting for auth...')}}).listen(8080)"
-```
+**Manual fallback path** (when the binary errors and the user wants to step through manually):
-Run the server via Bash with `run_in_background: true`. Wait up to 120 seconds for the auth code.
+The endpoints (validated 2026-05-20 against Google's OIDC discovery doc):
+- Auth: `https://accounts.google.com/o/oauth2/v2/auth`
+- Token: `https://oauth2.googleapis.com/token`
+- Scope: `https://www.googleapis.com/auth/adwords`
+- API: `https://googleads.googleapis.com/v24` (v24 became GA October 2025)
-If the localhost approach fails, fall back to asking the user to paste the code from the browser URL bar (the `code=` parameter).
+Auth URL pattern:
+```bash
+AUTH_URL="https://accounts.google.com/o/oauth2/v2/auth?client_id=${GADS_CLIENT_ID}&redirect_uri=http://localhost:8080&response_type=code&scope=https://www.googleapis.com/auth/adwords&access_type=offline&prompt=consent"
+```
-Exchange code for refresh token:
+Code → refresh-token exchange:
```bash
TOKEN_RESP=$(curl -s -X POST https://oauth2.googleapis.com/token \
- --data "code=${AUTH_CODE}" \
- --data "client_id=${GADS_CLIENT_ID}" \
- --data "client_secret=${GADS_CLIENT_SECRET}" \
- --data "redirect_uri=http://localhost:8080" \
- --data "grant_type=authorization_code")
+ --data-urlencode "code=${AUTH_CODE}" \
+ --data-urlencode "client_id=${GADS_CLIENT_ID}" \
+ --data-urlencode "client_secret=${GADS_CLIENT_SECRET}" \
+ --data-urlencode "redirect_uri=http://localhost:8080" \
+ --data-urlencode "grant_type=authorization_code")
GADS_REFRESH_TOKEN=$(echo "$TOKEN_RESP" | jq -r '.refresh_token')
```
-If `GADS_REFRESH_TOKEN` is null or empty, print error and offer retry.
-
-Warning: If the user's Google Cloud project is in "testing" publishing status, the refresh token expires in 7 days. Warn: "Your OAuth app is in testing mode — tokens expire in 7 days. To get long-lived tokens, publish the app in Google Cloud Console → OAuth consent screen → Publish App."
-
-**Step D — Customer ID:**
-Use the refresh token to get an access token, then list accessible customers:
+List accessible customers (for picking `customer_id` + auto-detecting MCC):
```bash
ACCESS_TOKEN=$(curl -s -X POST https://oauth2.googleapis.com/token \
- --data "client_id=${GADS_CLIENT_ID}&client_secret=${GADS_CLIENT_SECRET}&refresh_token=${GADS_REFRESH_TOKEN}&grant_type=refresh_token" | jq -r '.access_token')
+ --data-urlencode "client_id=${GADS_CLIENT_ID}&client_secret=${GADS_CLIENT_SECRET}&refresh_token=${GADS_REFRESH_TOKEN}&grant_type=refresh_token" | jq -r '.access_token')
-CUSTOMERS=$(curl -s -X GET \
- "https://googleads.googleapis.com/v23/customers:listAccessibleCustomers" \
+curl -s -X GET "https://googleads.googleapis.com/v24/customers:listAccessibleCustomers" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
- -H "developer-token: ${GADS_DEV_TOKEN}")
+ -H "developer-token: ${GADS_DEV_TOKEN}"
```
-If multiple accounts returned, present as `AskUserQuestion` options (max 4 per Rule 1 — paginate if more). If single account, auto-select. Store as `customer_id` (strip "customers/" prefix and dashes).
-
-If any account is a manager (MCC) account, also store `login_customer_id`. Auto-detect by checking if `listAccessibleCustomers` returns both manager and client accounts.
-
-**Step E — Smoke Test:**
+Detect manager accounts (set `login_customer_id` to the manager when calling sub-accounts):
```bash
-curl -s -X GET "https://googleads.googleapis.com/v23/customers:listAccessibleCustomers" \
+curl -s -X POST "https://googleads.googleapis.com/v24/customers/${CID}/googleAds:search" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
- -H "developer-token: ${GADS_DEV_TOKEN}"
+ -H "developer-token: ${GADS_DEV_TOKEN}" \
+ -H "Content-Type: application/json" \
+ --data-binary '{"query":"SELECT customer.manager FROM customer LIMIT 1"}'
```
-Expect JSON with `resourceNames` array. If error, print the error and offer `[Retry]` / `[Skip]`.
-**Step F — Save to preferences:**
+**Save to preferences (Doppler cred-refs preferred):**
```json
{
"marketing": {
- "google_ads": {
- "developer_token": "<YOUR_DEVELOPER_TOKEN>",
- "client_id": "<YOUR_CLIENT_ID>.apps.googleusercontent.com",
- "client_secret": "GOCSPX-<YOUR_SECRET>",
- "refresh_token": "1//<YOUR_REFRESH_TOKEN>",
- "customer_id": "1234567890",
- "login_customer_id": "9876543210"
+ "projects": {
+ "<project>": {
+ "google_ads": {
+ "developer_token": "doppler:claude-ops/prd/GOOGLE_ADS_DEVELOPER_TOKEN",
+ "client_id": "doppler:claude-ops/prd/GOOGLE_ADS_CLIENT_ID",
+ "client_secret": "doppler:claude-ops/prd/GOOGLE_ADS_CLIENT_SECRET",
+ "refresh_token": "doppler:claude-ops/prd/GOOGLE_ADS_<PROJECT_UPPER>_REFRESH_TOKEN",
+ "customer_id": "1234567890",
+ "login_customer_id": "9876543210"
+ }
+ }
}
}
}
```
-Same Doppler-reference pattern as Step 3i — prefer `doppler:KEY_NAME` over raw tokens when Doppler is configured.
-
Print: `[Google Ads] ✓ connected — customer ID: XXXXXXXXXX`
+#### Instagram
+
+**Primary path — delegate to the provision binary:**
+
+```bash
+ops-marketing-provision provision-instagram --project <project>
+```
+
+Auto-resolves `instagram.account_id` from the Meta access token by reading `instagram_business_account.id` off the configured Facebook Page (or `/me/accounts` fallback). When `marketing.projects.<project>.meta.app_secret` is configured, the verb computes `appsecret_proof = HMAC-SHA256(access_token, app_secret)` and appends it to every Graph API call — required when the Meta app's "Require App Secret" setting is on (default for all system-user tokens).
+
+Idempotent: re-runs smoke-test the existing `account_id` before re-resolving. Pass `--force` to bypass.
+
+Requires `marketing.projects.<project>.meta.access_token` to be configured first (via setup or manual prefs edit). Exits 2 if the Meta token is missing — does not fabricate.
+
#### Google Analytics 4
**Branch A — property already exists:** If `GA4_PROPERTY_ID` or `GA_MEASUREMENT_ID` was found in the auto-scan (or already set under the project's GA4 config in prefs — `marketing.projects[<key>].ga4` with a `property_id` field), present it and offer `[Keep]` / `[Reconfigure]`. On Keep, write the property ID directly to prefs and continue.
diff --git a/claude-ops/tests/test-ops-marketing-provision.sh b/claude-ops/tests/test-ops-marketing-provision.sh
index 01ea5647..bca28ee5 100755
--- a/claude-ops/tests/test-ops-marketing-provision.sh
+++ b/claude-ops/tests/test-ops-marketing-provision.sh
@@ -221,10 +221,128 @@ else
fi
# ---------------------------------------------------------------------------
-# 11. Missing --project arg exits non-zero
+# 11. provision-instagram: missing Meta token exits 2
# ---------------------------------------------------------------------------
echo ""
-echo "--- 11. missing --project arg ---"
+echo "--- 11. provision-instagram cold-start (no Meta token) ---"
+ig_cold_out="$("$BIN" provision-instagram --project fresh 2>&1 || true)"
+ig_cold_rc=$?
+if echo "$ig_cold_out" | grep -qi "meta access token not configured"; then
+ ok "provision-instagram exits with diagnostic when meta.access_token missing"
+else
+ err "provision-instagram cold-start" "expected 'meta access token' diagnostic, got: $ig_cold_out"
+fi
+
+# ---------------------------------------------------------------------------
+# 12. provision-instagram with fixture meta.access_token in dry-run
+# ---------------------------------------------------------------------------
+echo ""
+echo "--- 12. provision-instagram dry-run with stub Meta token ---"
+# Patch fixture to add a meta token + page_id to the 'fresh' project
+TMP_PREFS="$(mktemp)"
+jq '.marketing.projects.fresh.meta = {
+ "access_token": "env:FAKE_META_TOKEN",
+ "page_id": "1234567890"
+ } | .marketing.projects.fresh.instagram = {"account_id": "stub-ig-id-already-set"}' \
+ "$FIXTURE_PREFS" > "$TMP_PREFS" && mv "$TMP_PREFS" "$FIXTURE_PREFS"
+export FAKE_META_TOKEN="fake-token-for-dry-run"
+ig_dry_out="$("$BIN" provision-instagram --project fresh 2>&1 || true)"
+# Idempotent path should mention "Already configured" + dry-run notice
+if echo "$ig_dry_out" | grep -q "Already configured" && echo "$ig_dry_out" | grep -q "DRY-RUN"; then
+ ok "provision-instagram dry-run idempotent — recognizes pre-set account_id"
+else
+ err "provision-instagram dry-run" "expected 'Already configured' + DRY-RUN markers: $ig_dry_out"
+fi
+unset FAKE_META_TOKEN
+
+# ---------------------------------------------------------------------------
+# 13. provision-google-ads dry-run writes pending state file
+# ---------------------------------------------------------------------------
+echo ""
+echo "--- 13. provision-google-ads dry-run (no dev token) creates pending file ---"
+PENDING_FILE="${FIXTURE_DIR}/state/marketing-provision/acme-google-ads-pending.json"
+rm -f "$PENDING_FILE"
+gads_out="$("$BIN" provision-google-ads --project acme 2>&1 || true)"
+if [ -f "$PENDING_FILE" ] && jq -e '.stage == "developer_token"' "$PENDING_FILE" >/dev/null 2>&1; then
+ ok "provision-google-ads writes pending-state file with stage=developer_token"
+else
+ err "provision-google-ads pending file" "expected $PENDING_FILE with stage=developer_token, output: $gads_out"
+fi
+
+# ---------------------------------------------------------------------------
+# 14. provision-google-ads --skip-if-pending respects pending state
+# ---------------------------------------------------------------------------
+echo ""
+echo "--- 14. provision-google-ads --skip-if-pending ---"
+skip_out="$("$BIN" provision-google-ads --project acme --skip-if-pending 2>&1 || true)"
+skip_rc=$?
+if echo "$skip_out" | grep -qi "still pending" || echo "$skip_out" | grep -qi "skipping"; then
+ ok "provision-google-ads --skip-if-pending exits 0 when pending file exists"
+else
+ err "provision-google-ads skip" "expected 'still pending' / 'skipping', got: $skip_out"
+fi
+
+# ---------------------------------------------------------------------------
+# 15. provision-all dry-run chains GA4 + GSC + Instagram + Google Ads
+# ---------------------------------------------------------------------------
+echo ""
+echo "--- 15. provision-all chains all 4 channels ---"
+all_out="$("$BIN" provision-all --project acme 2>&1 || true)"
+if echo "$all_out" | grep -q -- "--- GA4 ---" && \
+ echo "$all_out" | grep -q -- "--- Google Search Console ---" && \
+ echo "$all_out" | grep -q -- "--- Instagram ---" && \
+ echo "$all_out" | grep -q -- "--- Google Ads ---" && \
+ echo "$all_out" | grep -q "Done"; then
+ ok "provision-all chains all four channels in order"
+else
+ err "provision-all chain" "missing one or more channel headers: $all_out"
+fi
+
+# ---------------------------------------------------------------------------
+# 16. marketing_channels_status includes 'instagram' field
+# ---------------------------------------------------------------------------
+echo ""
+echo "--- 16. marketing_channels_status surfaces instagram ---"
+ig_json=$(
+ # shellcheck disable=SC1090
+ . "$LIB"
+ marketing_channels_status "fresh" --json
+) || true
+if printf '%s' "$ig_json" | jq -e '.instagram == "configured"' >/dev/null 2>&1; then
+ ok "marketing_channels_status reports instagram as configured for 'fresh'"
+else
+ err "marketing_channels_status instagram" "expected .instagram=configured, got: $ig_json"
+fi
+
+# ---------------------------------------------------------------------------
+# 17. google-ads-oauth.sh helper lib syntax + endpoint vars
+# ---------------------------------------------------------------------------
+echo ""
+echo "--- 17. google-ads-oauth.sh helper lib ---"
+OAUTH_LIB="${PLUGIN_ROOT}/scripts/lib/google-ads-oauth.sh"
+if [ -f "$OAUTH_LIB" ] && bash -n "$OAUTH_LIB" 2>/dev/null; then
+ # Source and verify the endpoint constants are set
+ url=$(
+ # shellcheck disable=SC1090
+ . "$OAUTH_LIB"
+ gads_authorize_url "fake-client" "http://localhost:8080"
+ )
+ if echo "$url" | grep -q "accounts.google.com/o/oauth2/v2/auth" && \
+ echo "$url" | grep -q "scope=" && \
+ echo "$url" | grep -q "access_type=offline"; then
+ ok "google-ads-oauth.sh gads_authorize_url generates valid URL"
+ else
+ err "gads_authorize_url" "URL missing required params: $url"
+ fi
+else
+ err "google-ads-oauth.sh" "lib missing or has syntax errors"
+fi
+
+# ---------------------------------------------------------------------------
+# 18. Missing --project arg exits non-zero
+# ---------------------------------------------------------------------------
+echo ""
+echo "--- 18. missing --project arg ---"
if "$BIN" status 2>&1 | grep -qi "required\|error"; then
ok "status without --project exits with error message"
else