Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat: direct channel wiring — free API fallback for Windsor.ai (#678)
hypehouseagencyc9548df6ec4a
diff --git a/claude-ops/scripts/lib/organic-metrics-aggregator.sh b/claude-ops/scripts/lib/organic-metrics-aggregator.shnew file mode 100755index 00000000..14abe611--- /dev/null+++ b/claude-ops/scripts/lib/organic-metrics-aggregator.sh@@ -0,0 +1,420 @@+#!/usr/bin/env bash+# scripts/lib/organic-metrics-aggregator.sh — normalized organic + merchant pulls across free surfaces+#+# Public functions:+# organic_meta <project> — Facebook Page + Instagram Business via Graph API (fans, followers, IG reach 7d)+# organic_youtube <project> — YouTube Analytics API v2 (views, watch time, net subscribers, last 7d)+# organic_searchconsole <project> — Search Console searchAnalytics/query (clicks, impressions, 7d)+# merchant_status <project> — Google Merchant Content API v2.1 accountstatuses (approved/disapproved counts)+# organic_tiktok <project> — stub (configured_but_not_implemented or null)+# organic_all <project> — fan out + aggregate to {"project","window_days","surfaces":[...]}+#+# Sourcing convention:+# PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+# . "${PLUGIN_ROOT}/lib/registry-path.sh"+# . "${PLUGIN_ROOT}/scripts/lib/organic-metrics-aggregator.sh"+#+# Contract (same as ad-spend-aggregator.sh):+# - All HTTP via `curl -sS --max-time 12 ...`, errors swallowed.+# - Every function returns 0 (errexit-safe — libs may be sourced by callers).+# - Missing cred -> echo `null`. Configured-but-stub -> echo {"status":"configured_but_not_implemented"}.+# - Successful pull -> echo a JSON object with at least: surface, project, window_days.+# - PUBLIC REPO: no hardcoded project names / tokens / account IDs.+#+# These surfaces are all free direct APIs — they exist as a fallback/alternative+# when a paid aggregator (e.g. Windsor.ai) is not connected or returns dead zeros.+#+# Requires: bash, jq, curl.++[ -n "${_ORGANIC_METRICS_AGGREGATOR_LOADED:-}" ] && return 0+_ORGANIC_METRICS_AGGREGATOR_LOADED=1++set -u++# Source resolve_cred + _prefs_marketing helpers from ga4-resolve.sh.+_ORGANIC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# shellcheck disable=SC1091+. "${_ORGANIC_DIR}/ga4-resolve.sh"++# Source google-ads-oauth.sh if present (provides gads_refresh_access_token —+# the Google OAuth token endpoint is identical for YouTube / Merchant scopes).+if [ -f "${_ORGANIC_DIR}/google-ads-oauth.sh" ]; then+ # shellcheck disable=SC1091+ . "${_ORGANIC_DIR}/google-ads-oauth.sh"+fi++# ── PREFS resolution ──────────────────────────────────────────────────────────+_organic_prefs_path() {+ printf '%s' "${OPS_AUTOPILOT_PREFS:-${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json}"+}++# ── Inline Google OAuth refresh fallback ──────────────────────────────────────+# Used only when google-ads-oauth.sh is not present in scripts/lib/.+# Arg order matches google-ads-oauth.sh: <refresh_token> <client_id> <client_secret>.+if ! declare -f gads_refresh_access_token >/dev/null 2>&1; then+ gads_refresh_access_token() {+ local refresh_token="${1:-}" client_id="${2:-}" client_secret="${3:-}"+ if [ -z "$refresh_token" ] || [ -z "$client_id" ] || [ -z "$client_secret" ]; then+ return 0+ fi+ local resp+ resp="$(curl -sS --max-time 12 -X POST https://oauth2.googleapis.com/token \+ --data-urlencode "client_id=${client_id}" \+ --data-urlencode "client_secret=${client_secret}" \+ --data-urlencode "refresh_token=${refresh_token}" \+ --data-urlencode "grant_type=refresh_token" 2>/dev/null || echo '{}')"+ printf '%s' "$resp" | jq -r '.access_token // empty' 2>/dev/null || true+ }+fi++# ── Date helpers (portable BSD/GNU) ───────────────────────────────────────────+_organic_date_days_ago() {+ local days="${1:-7}"+ date -v-"${days}"d +%F 2>/dev/null \+ || date --date="${days} days ago" +%F 2>/dev/null \+ || date +%F+}++# ── Google OAuth access token for a prefs channel ─────────────────────────────+# $1=project $2=channel — reads refresh_token/client_id/client_secret from that+# channel and mints an access token. Empty output when not configured.+_organic_google_token() {+ local proj="${1:-}" channel="${2:-}"+ local refresh_token client_id client_secret+ refresh_token="$(resolve_cred "$(_prefs_marketing "$proj" "$channel" "refresh_token")")"+ client_id="$(resolve_cred "$(_prefs_marketing "$proj" "$channel" "client_id")")"+ client_secret="$(resolve_cred "$(_prefs_marketing "$proj" "$channel" "client_secret")")"+ if [ -z "$refresh_token" ] || [ -z "$client_id" ] || [ -z "$client_secret" ]; then+ return 0+ fi+ gads_refresh_access_token "$refresh_token" "$client_id" "$client_secret" 2>/dev/null || true+}++# ── organic_meta ──────────────────────────────────────────────────────────────+# Facebook Page + Instagram Business metrics via Graph API.+# Prefs keys (marketing.projects.<p>.meta.*): access_token (or env+# META_ACCESS_TOKEN / FACEBOOK_ACCESS_TOKEN), page_id, instagram_business_id.+organic_meta() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi++ local prefs; prefs="$(_organic_prefs_path)"+ [ -f "$prefs" ] || { printf 'null'; return 0; }++ local tok page_id ig_id+ tok="$(resolve_cred "$(_prefs_marketing "$proj" "meta" "access_token")")"+ [ -z "$tok" ] && tok="${META_ACCESS_TOKEN:-${FACEBOOK_ACCESS_TOKEN:-}}"+ page_id="$(resolve_cred "$(_prefs_marketing "$proj" "meta" "page_id")")"+ ig_id="$(resolve_cred "$(_prefs_marketing "$proj" "meta" "instagram_business_id")")"++ if [ -z "$tok" ] || { [ -z "$page_id" ] && [ -z "$ig_id" ]; }; then+ printf 'null'+ return 0+ fi++ local page_fans="null" page_followers="null"+ if [ -n "$page_id" ]; then+ local page_resp+ page_resp="$(curl -gsS --max-time 12 \+ "https://graph.facebook.com/v18.0/${page_id}?fields=fan_count,followers_count&access_token=${tok}" \+ 2>/dev/null || echo '{}')"+ if [ -z "$(printf '%s' "$page_resp" | jq -r '.error.code // empty' 2>/dev/null)" ]; then+ page_fans="$(printf '%s' "$page_resp" | jq '.fan_count // null' 2>/dev/null || echo null)"+ page_followers="$(printf '%s' "$page_resp" | jq '.followers_count // null' 2>/dev/null || echo null)"+ fi+ fi++ local ig_followers="null" ig_media="null" ig_reach="null"+ if [ -n "$ig_id" ]; then+ local ig_resp+ ig_resp="$(curl -gsS --max-time 12 \+ "https://graph.facebook.com/v18.0/${ig_id}?fields=followers_count,media_count&access_token=${tok}" \+ 2>/dev/null || echo '{}')"+ if [ -z "$(printf '%s' "$ig_resp" | jq -r '.error.code // empty' 2>/dev/null)" ]; then+ ig_followers="$(printf '%s' "$ig_resp" | jq '.followers_count // null' 2>/dev/null || echo null)"+ ig_media="$(printf '%s' "$ig_resp" | jq '.media_count // null' 2>/dev/null || echo null)"+ fi+ local reach_resp+ reach_resp="$(curl -gsS --max-time 12 \+ "https://graph.facebook.com/v18.0/${ig_id}/insights?metric=reach&period=day&access_token=${tok}" \+ 2>/dev/null || echo '{}')"+ ig_reach="$(printf '%s' "$reach_resp" \+ | jq '[.data[]? | select(.name == "reach") | .values[]?.value // 0] | if length == 0 then null else add end' \+ 2>/dev/null || echo null)"+ [ -z "$ig_reach" ] && ig_reach="null"+ fi++ jq -nc \+ --arg p "$proj" \+ --argjson pf "${page_fans:-null}" \+ --argjson pfl "${page_followers:-null}" \+ --argjson igf "${ig_followers:-null}" \+ --argjson igm "${ig_media:-null}" \+ --argjson igr "${ig_reach:-null}" '+ {+ surface: "meta_organic",+ project: $p,+ page_fans: $pf,+ page_followers: $pfl,+ ig_followers: $igf,+ ig_media_count: $igm,+ ig_reach_7d: $igr,+ window_days: 7+ }+ ' 2>/dev/null || printf 'null'+}++# ── organic_youtube ───────────────────────────────────────────────────────────+# YouTube Analytics API v2, last 7 days. Requires an OAuth refresh token minted+# with scope https://www.googleapis.com/auth/yt-analytics.readonly (plus+# youtube.readonly for the subscriber count).+# Prefs keys (marketing.projects.<p>.youtube.*): refresh_token, client_id,+# client_secret, channel_id (optional — defaults to the authorized channel).+organic_youtube() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi++ local prefs; prefs="$(_organic_prefs_path)"+ [ -f "$prefs" ] || { printf 'null'; return 0; }++ local access_token+ access_token="$(_organic_google_token "$proj" "youtube")"+ if [ -z "$access_token" ]; then+ printf 'null'+ return 0+ fi++ local channel_id ids="channel%3D%3DMINE"+ channel_id="$(resolve_cred "$(_prefs_marketing "$proj" "youtube" "channel_id")")"+ [ -n "$channel_id" ] && ids="channel%3D%3D${channel_id}"++ local start_date end_date+ end_date="$(date +%F)"+ start_date="$(_organic_date_days_ago 7)"++ local resp+ resp="$(curl -gsS --max-time 12 \+ "https://youtubeanalytics.googleapis.com/v2/reports?ids=${ids}&startDate=${start_date}&endDate=${end_date}&metrics=views,estimatedMinutesWatched,subscribersGained,subscribersLost" \+ -H "Authorization: Bearer ${access_token}" 2>/dev/null || echo '{}')"++ if [ -n "$(printf '%s' "$resp" | jq -r '.error.code // empty' 2>/dev/null)" ]; then+ printf 'null'+ return 0+ fi++ local views minutes subs_gained subs_lost+ views="$(printf '%s' "$resp" | jq '[.rows[]?[0] // 0] | add // 0' 2>/dev/null || echo 0)"+ minutes="$(printf '%s' "$resp" | jq '[.rows[]?[1] // 0] | add // 0' 2>/dev/null || echo 0)"+ subs_gained="$(printf '%s' "$resp" | jq '[.rows[]?[2] // 0] | add // 0' 2>/dev/null || echo 0)"+ subs_lost="$(printf '%s' "$resp" | jq '[.rows[]?[3] // 0] | add // 0' 2>/dev/null || echo 0)"++ # Total subscriber count via Data API v3 (best effort — null if scope missing).+ local subs_total="null" chan_param="mine=true"+ [ -n "$channel_id" ] && chan_param="id=${channel_id}"+ local chan_resp+ chan_resp="$(curl -gsS --max-time 12 \+ "https://www.googleapis.com/youtube/v3/channels?part=statistics&${chan_param}" \+ -H "Authorization: Bearer ${access_token}" 2>/dev/null || echo '{}')"+ subs_total="$(printf '%s' "$chan_resp" \+ | jq '.items[0].statistics.subscriberCount // null | if . == null then null else tonumber end' \+ 2>/dev/null || echo null)"+ [ -z "$subs_total" ] && subs_total="null"++ jq -nc \+ --arg p "$proj" \+ --argjson v "${views:-0}" \+ --argjson m "${minutes:-0}" \+ --argjson sg "${subs_gained:-0}" \+ --argjson sl "${subs_lost:-0}" \+ --argjson st "${subs_total:-null}" '+ {+ surface: "youtube",+ project: $p,+ views: $v,+ watch_minutes: $m,+ subscribers_gained: $sg,+ subscribers_lost: $sl,+ subscribers_net: ($sg - $sl),+ subscribers_total: $st,+ window_days: 7+ }+ ' 2>/dev/null || printf 'null'+}++# ── organic_searchconsole ─────────────────────────────────────────────────────+# Search Console searchAnalytics/query totals, last 7 days. Site URL comes from+# prefs (marketing.projects.<p>.gsc.site_url — same key gsc_resolve uses).+# Auth mirrors scripts/ops-cron-seo-blog-gen.sh: gcloud ADC first, then+# $GOOGLE_ACCESS_TOKEN.+organic_searchconsole() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi++ local prefs; prefs="$(_organic_prefs_path)"+ [ -f "$prefs" ] || { printf 'null'; return 0; }++ local site_url+ site_url="$(resolve_cred "$(_prefs_marketing "$proj" "gsc" "site_url")")"+ if [ -z "$site_url" ]; then+ printf 'null'+ return 0+ fi++ local access_token+ access_token="$(gcloud auth application-default print-access-token 2>/dev/null || true)"+ [ -z "$access_token" ] && access_token="${GOOGLE_ACCESS_TOKEN:-}"+ if [ -z "$access_token" ]; then+ printf 'null'+ return 0+ fi++ local site_enc+ site_enc="$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1], safe=''))" "$site_url" 2>/dev/null \+ || printf '%s' "$site_url" | sed 's|:|%3A|g; s|/|%2F|g')"++ local start_date end_date+ end_date="$(date +%F)"+ start_date="$(_organic_date_days_ago 7)"++ local payload+ payload="$(jq -n --arg start "$start_date" --arg end "$end_date" \+ '{startDate: $start, endDate: $end, rowLimit: 1}')"++ local resp+ resp="$(curl -gsS --max-time 12 -X POST \+ "https://searchconsole.googleapis.com/webmasters/v3/sites/${site_enc}/searchAnalytics/query" \+ -H "Authorization: Bearer ${access_token}" \+ -H "Content-Type: application/json" \+ -d "$payload" 2>/dev/null || echo '{}')"++ if [ -n "$(printf '%s' "$resp" | jq -r '.error.code // empty' 2>/dev/null)" ]; then+ printf 'null'+ return 0+ fi++ printf '%s' "$resp" | jq -c --arg p "$proj" '+ (.rows[0] // {}) as $r |+ {+ surface: "search_console",+ project: $p,+ clicks: ($r.clicks // 0),+ impressions: ($r.impressions // 0),+ ctr: ((($r.ctr // 0) * 10000 | round) / 100),+ avg_position: ((($r.position // 0) * 100 | round) / 100),+ window_days: 7+ }+ ' 2>/dev/null || printf 'null'+}++# ── merchant_status ───────────────────────────────────────────────────────────+# Google Merchant Content API v2.1 accountstatuses — product approval counts.+# Prefs keys (marketing.projects.<p>.merchant_center.*): merchant_id, plus+# either OAuth refresh creds (refresh_token/client_id/client_secret with scope+# https://www.googleapis.com/auth/content) or gcloud ADC / $GOOGLE_ACCESS_TOKEN.+merchant_status() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi++ local prefs; prefs="$(_organic_prefs_path)"+ [ -f "$prefs" ] || { printf 'null'; return 0; }++ local merchant_id+ merchant_id="$(resolve_cred "$(_prefs_marketing "$proj" "merchant_center" "merchant_id")")"+ if [ -z "$merchant_id" ]; then+ printf 'null'+ return 0+ fi++ local access_token+ access_token="$(_organic_google_token "$proj" "merchant_center")"+ [ -z "$access_token" ] && access_token="$(gcloud auth application-default print-access-token 2>/dev/null || true)"+ [ -z "$access_token" ] && access_token="${GOOGLE_ACCESS_TOKEN:-}"+ if [ -z "$access_token" ]; then+ printf 'null'+ return 0+ fi++ local resp+ resp="$(curl -gsS --max-time 12 \+ "https://shoppingcontent.googleapis.com/content/v2.1/${merchant_id}/accountstatuses/${merchant_id}" \+ -H "Authorization: Bearer ${access_token}" 2>/dev/null || echo '{}')"++ if [ -n "$(printf '%s' "$resp" | jq -r '.error.code // empty' 2>/dev/null)" ]; then+ printf 'null'+ return 0+ fi++ printf '%s' "$resp" | jq -c --arg p "$proj" '+ ([.products[]?.statistics] | map({+ active: ((.active // 0) | tonumber),+ pending: ((.pending // 0) | tonumber),+ disapproved: ((.disapproved // 0) | tonumber),+ expiring: ((.expiring // 0) | tonumber)+ })) as $stats |+ {+ surface: "merchant_center",+ project: $p,+ approved: ([$stats[].active] | add // 0),+ pending: ([$stats[].pending] | add // 0),+ disapproved: ([$stats[].disapproved] | add // 0),+ expiring: ([$stats[].expiring] | add // 0),+ item_issues: ([.products[]?.itemLevelIssues[]?] | length)+ }+ ' 2>/dev/null || printf 'null'+}++# ── Stub: tiktok organic ──────────────────────────────────────────────────────+# TikTok organic metrics need an approved TikTok developer app — emit the+# configured_but_not_implemented sentinel when creds are declared.+_organic_stub_surface() {+ local surface="$1" proj="$2" field="$3"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi+ local prefs; prefs="$(_organic_prefs_path)"+ [ -f "$prefs" ] || { printf 'null'; return 0; }++ local ref+ ref="$(_prefs_marketing "$proj" "$surface" "$field")"+ if [ -z "$ref" ] || [ "$ref" = "null" ]; then+ printf 'null'+ return 0+ fi+ jq -nc --arg s "$surface" --arg p "$proj" \+ '{surface:$s, project:$p, status:"configured_but_not_implemented"}' 2>/dev/null \+ || printf 'null'+}++organic_tiktok() { _organic_stub_surface "tiktok_organic" "${1:-}" "access_token"; }++# ── organic_all ───────────────────────────────────────────────────────────────+organic_all() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then+ jq -nc '{project:"", window_days:7, surfaces:[]}'+ return 0+ fi++ local results=()+ local out+ for fn in organic_meta organic_youtube organic_searchconsole merchant_status organic_tiktok; do+ out="$("$fn" "$proj" 2>/dev/null || printf 'null')"+ [ -z "$out" ] && out="null"+ if [ "$out" != "null" ]; then+ results+=("$out")+ fi+ done++ local surfaces_json="[]"+ if [ ${#results[@]} -gt 0 ]; then+ surfaces_json="$(printf '%s\n' "${results[@]}" | jq -s '.' 2>/dev/null || echo '[]')"+ fi++ jq -nc \+ --arg p "$proj" \+ --argjson surfaces "$surfaces_json" '+ {+ project: $p,+ window_days: 7,+ surfaces: $surfaces+ }+ ' 2>/dev/null || jq -nc --arg p "$proj" '{project:$p, window_days:7, surfaces:[]}'+}diff --git a/claude-ops/skills/ops-dash/SKILL.md b/claude-ops/skills/ops-dash/SKILL.mdindex 5e9b2072..2c01bec0 100644--- a/claude-ops/skills/ops-dash/SKILL.md+++ b/claude-ops/skills/ops-dash/SKILL.md@@ -419,3 +419,10 @@ Data sanity: if Windsor returns only zeros across sources (Meta + Google spend/iInstagram reach all exactly 0 over 30d while accounts are connected), treat the data as unavailable —the plan may be expired (check `get_current_user` → `is_paid`) — warn the user, and never presentzeros as real metrics. `scripts/windsor-data-sanity.sh` automates the check.++Windsor is optional. If Windsor is not connected, returns errors, or returns the+all-zero pattern, fall back to the free direct libraries:+`scripts/lib/ad-spend-aggregator.sh` (paid), `scripts/lib/ga4-data-api.sh`+(analytics), and `scripts/lib/organic-metrics-aggregator.sh` (organic + merchant).+See [docs/integrations/direct-channel-wiring.md](../../../docs/integrations/direct-channel-wiring.md).+Never present zeros from a dead source as real metrics.diff --git a/claude-ops/skills/ops-ecom/SKILL.md b/claude-ops/skills/ops-ecom/SKILL.mdindex 75020c33..28995216 100644--- a/claude-ops/skills/ops-ecom/SKILL.md+++ b/claude-ops/skills/ops-ecom/SKILL.md@@ -615,3 +615,10 @@ Data sanity: if Windsor returns only zeros across sources (Meta + Google spend/iInstagram reach all exactly 0 over 30d while accounts are connected), treat the data as unavailable —the plan may be expired (check `get_current_user` → `is_paid`) — warn the user, and never presentzeros as real metrics. `scripts/windsor-data-sanity.sh` automates the check.++Windsor is optional. If Windsor is not connected, returns errors, or returns the+all-zero pattern, fall back to the free direct libraries:+`scripts/lib/ad-spend-aggregator.sh` (paid), `scripts/lib/ga4-data-api.sh`+(analytics), and `scripts/lib/organic-metrics-aggregator.sh` (organic + merchant).+See [docs/integrations/direct-channel-wiring.md](../../../docs/integrations/direct-channel-wiring.md).+Never present zeros from a dead source as real metrics.diff --git a/claude-ops/skills/ops-marketing/SKILL.md b/claude-ops/skills/ops-marketing/SKILL.mdindex c06ca4ec..37b5c6a1 100644--- a/claude-ops/skills/ops-marketing/SKILL.md+++ b/claude-ops/skills/ops-marketing/SKILL.md@@ -2815,3 +2815,10 @@ Data sanity: if Windsor returns only zeros across sources (Meta + Google spend/iInstagram reach all exactly 0 over 30d while accounts are connected), treat the data as unavailable —the plan may be expired (check `get_current_user` → `is_paid`) — warn the user, and never presentzeros as real metrics. `scripts/windsor-data-sanity.sh` automates the check.++Windsor is optional. If Windsor is not connected, returns errors, or returns the+all-zero pattern, fall back to the free direct libraries:+`scripts/lib/ad-spend-aggregator.sh` (paid), `scripts/lib/ga4-data-api.sh`+(analytics), and `scripts/lib/organic-metrics-aggregator.sh` (organic + merchant).+See [docs/integrations/direct-channel-wiring.md](../../../docs/integrations/direct-channel-wiring.md).+Never present zeros from a dead source as real metrics.diff --git a/claude-ops/skills/ops-settings/SKILL.md b/claude-ops/skills/ops-settings/SKILL.mdindex c33156cd..cbd8ab06 100644--- a/claude-ops/skills/ops-settings/SKILL.md+++ b/claude-ops/skills/ops-settings/SKILL.md@@ -54,6 +54,10 @@ Display as a table:Klaviyo ⚠️ missing —Meta Ads ⚠️ missing —GA4 ⚠️ missing —+ Organic FB/IG ⚠️ missing —+ YouTube ⚠️ missing —+ Search Console ⚠️ missing —+ Merchant Center ⚠️ missing —ElevenLabs ⚠️ missing —Datadog ⚠️ missing —New Relic ⚠️ missing —@@ -109,6 +113,19 @@ When a specific integration is selected (via argument or user pick from dashboar| New Relic | `curl -s -H "Api-Key: ${new_key}" https://api.newrelic.com/v2/applications.json \| jq '.applications | length'` → numeric || Doppler MCP | `npx -y @dopplerhq/mcp-server --help 2>&1` with DOPPLER_TOKEN set | exits 0 |+**Direct marketing surfaces** (per-project keys under `.marketing.projects.<p>` — see+`docs/integrations/direct-channel-wiring.md` for the full key matrix). Status check:+key group present and non-empty → configured, else missing. Smoke test each via+`scripts/lib/organic-metrics-aggregator.sh` — a JSON object means live, `null` means+missing/broken creds (never render `null` as zeros):++| Surface | Prefs keys | Smoke test (after `. "${CLAUDE_PLUGIN_ROOT}/scripts/lib/organic-metrics-aggregator.sh"`) |+| -------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------- |+| Organic FB/IG | `meta.access_token` + `meta.page_id` / `meta.instagram_business_id` | `organic_meta <project> \| jq .` → object with `page_fans` / `ig_followers` |+| YouTube | `youtube.refresh_token/client_id/client_secret` | `organic_youtube <project> \| jq .` → object with `views` |+| Search Console | `gsc.site_url` (+ gcloud ADC or `$GOOGLE_ACCESS_TOKEN`) | `organic_searchconsole <project> \| jq .` → object with `clicks` |+| Merchant Center | `merchant_center.merchant_id` (+ Google auth) | `merchant_status <project> \| jq .` → object with `approved`/`disapproved` |+## Autopilot Studio (per-project)Lets an operator view and edit per-project autopilot config **without re-running setup**. See `skills/ops-marketing/SKILL.md` → `## autopilot` for the full field semantics.diff --git a/claude-ops/skills/ops-socials/SKILL.md b/claude-ops/skills/ops-socials/SKILL.mdindex 8199eb93..cb9d96cf 100644--- a/claude-ops/skills/ops-socials/SKILL.md+++ b/claude-ops/skills/ops-socials/SKILL.md@@ -302,3 +302,10 @@ Data sanity: if Windsor returns only zeros across sources (Meta + Google spend/iInstagram reach all exactly 0 over 30d while accounts are connected), treat the data as unavailable —the plan may be expired (check `get_current_user` → `is_paid`) — warn the user, and never presentzeros as real metrics. `scripts/windsor-data-sanity.sh` automates the check.++Windsor is optional. If Windsor is not connected, returns errors, or returns the+all-zero pattern, fall back to the free direct libraries:+`scripts/lib/ad-spend-aggregator.sh` (paid), `scripts/lib/ga4-data-api.sh`+(analytics), and `scripts/lib/organic-metrics-aggregator.sh` (organic + merchant).+See [docs/integrations/direct-channel-wiring.md](../../../docs/integrations/direct-channel-wiring.md).+Never present zeros from a dead source as real metrics.diff --git a/claude-ops/skills/setup/channels/marketing.md b/claude-ops/skills/setup/channels/marketing.mdindex 50eea203..e7ef64de 100644--- a/claude-ops/skills/setup/channels/marketing.md+++ b/claude-ops/skills/setup/channels/marketing.md@@ -1,4 +1,4 @@-### 3j — Marketing (Klaviyo, Meta Ads, GA4, Search Console)+### 3j — Marketing (Klaviyo, Meta Ads, GA4, Search Console, organic surfaces)> **Project slugs are the entry gate.** Every sub-step below writes under `marketing.projects.<slug>` in `$PREFS_PATH`. Those slugs (plus an optional flat `marketing.account_slugs[]` array) are the canonical source consumed by `ops-marketing-auth-prewarm.sh` for product-hint extraction. The prewarm script no longer ships a hardcoded slug list — if no projects/slugs exist in prefs it prints `no marketing accounts configured — run /ops:setup marketing` and exits 0. Make sure the user has at least one project slug picked before continuing.@@ -8,6 +8,7 @@# Shell envprintenv KLAVIYO_API_KEY KLAVIYO_PRIVATE_KEY META_ACCESS_TOKEN FACEBOOK_ACCESS_TOKEN META_AD_ACCOUNT_ID GA4_PROPERTY_ID GA_MEASUREMENT_ID 2>/dev/nullprintenv GOOGLE_ADS_DEVELOPER_TOKEN GOOGLE_ADS_CLIENT_ID GOOGLE_ADS_CLIENT_SECRET GOOGLE_ADS_REFRESH_TOKEN GOOGLE_ADS_CUSTOMER_ID 2>/dev/null+printenv META_PAGE_ID INSTAGRAM_BUSINESS_ID YOUTUBE_CHANNEL_ID YOUTUBE_REFRESH_TOKEN GOOGLE_MERCHANT_ID 2>/dev/null# Shell profilesgrep -h 'KLAVIYO\|META_\|FACEBOOK\|GA4\|GA_MEASUREMENT\|GOOGLE_ADS' ~/.zshrc ~/.bashrc ~/.zprofile ~/.envrc 2>/dev/null | grep -v '^#'@@ -47,7 +48,17 @@ If user selects `[More...]`, present **second call**:| Google Analytics 4 | ga4 | Web analytics — GA4 property ID || Google Search Console | gsc | SEO data — site URL (uses gcloud auth) || WhatsApp Business API | waba | Template messaging at scale — Business token + IDs |-| Skip | skip | Done with marketing setup |+| More... | more2 | Organic social, YouTube, Merchant Center |++If user selects the second `[More...]`, present **third call** (free direct surfaces —+read by `scripts/lib/organic-metrics-aggregator.sh`, no aggregator subscription needed):++| Option | Header | Description |+| ---------------------- | ------------ | ------------------------------------------------------ |+| Organic social (FB/IG) | meta-organic | Page fans + IG reach — reuses Meta token, page/IG IDs |+| YouTube | youtube | Views/watch time/subscribers — OAuth refresh token |+| Google Merchant Center | merchant | Product approval status — merchant ID + Google auth |+| Skip | skip | Done with marketing setup |Run the selected sub-step(s) below in the order selected.@@ -236,6 +247,127 @@ curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \"https://searchconsole.googleapis.com/webmasters/v3/sites" | jq '.siteEntry | length'```+Once `marketing.projects.<key>.gsc.site_url` is written, headless reads work via+`organic_searchconsole <key>` in `scripts/lib/organic-metrics-aggregator.sh`+(same gcloud-ADC / `$GOOGLE_ACCESS_TOKEN` auth as the smoke test above).++#### Organic social (Facebook Page + Instagram Business)++Free direct reads — no aggregator subscription needed. Reuses the Meta access+token from the Meta Ads sub-step (or `META_ACCESS_TOKEN` / `FACEBOOK_ACCESS_TOKEN`+from the auto-scan). Requires `marketing.projects.<key>.meta.access_token` to be+configured first.++If `META_PAGE_ID` or `INSTAGRAM_BUSINESS_ID` was found in the auto-scan, present+them. Otherwise auto-resolve from the token:++```bash+# Facebook Page ID (first managed page)+curl -s "https://graph.facebook.com/v18.0/me/accounts?access_token=$TOKEN" | jq -r '.data[0].id // empty'+# Instagram Business ID off that page+curl -s "https://graph.facebook.com/v18.0/$PAGE_ID?fields=instagram_business_account&access_token=$TOKEN" \+ | jq -r '.instagram_business_account.id // empty'+```++Save to `$PREFS_PATH` (merge — do not clobber existing `.meta` cred-refs):++```json+{+ "marketing": {+ "projects": {+ "<key>": {+ "meta": { "page_id": "<PAGE_ID>", "instagram_business_id": "<IG_ID>" }+ }+ }+ }+}+```++Smoke test (expects a JSON object with `page_fans` / `ig_followers`, `null` = creds missing):++```bash+. "${CLAUDE_PLUGIN_ROOT}/scripts/lib/organic-metrics-aggregator.sh"+organic_meta <key> | jq .+```++#### YouTube (organic)++YouTube Analytics API v2, same OAuth refresh-token pattern as Google Ads+(Desktop OAuth client + localhost capture — see the Google Ads manual fallback+path above), but with scopes+`https://www.googleapis.com/auth/yt-analytics.readonly` and+`https://www.googleapis.com/auth/youtube.readonly` instead of `adwords`.+No developer token needed.++Ask for (present auto-scan hits first): OAuth `client_id` + `client_secret`+(can reuse the Google Ads Desktop client), then run the consent flow with the+YouTube scopes to mint a dedicated `refresh_token`. `channel_id` is optional —+omitted means "the authorized channel".++Save to `$PREFS_PATH` (Doppler cred-refs preferred):++```json+{+ "marketing": {+ "projects": {+ "<key>": {+ "youtube": {+ "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/YOUTUBE_<PROJECT_UPPER>_REFRESH_TOKEN",+ "channel_id": "UCxxxxxxxxxxxxxxxxxxxxxx"+ }+ }+ }+ }+}+```++Smoke test:++```bash+. "${CLAUDE_PLUGIN_ROOT}/scripts/lib/organic-metrics-aggregator.sh"+organic_youtube <key> | jq .+```++Expect `views` / `subscribers_total` fields; `null` means creds missing or the+refresh token lacks the YouTube scopes (re-run consent with the right scopes).++#### Google Merchant Center++Content API v2.1 product-approval status (approved / pending / disapproved /+expiring). Ask for the Merchant ID (Merchant Center dashboard → top-right+account ID), or present `GOOGLE_MERCHANT_ID` from the auto-scan.++Auth: gcloud ADC with the `https://www.googleapis.com/auth/content` scope, or a+dedicated OAuth refresh token (same Desktop-client capture flow as YouTube above)+saved under `merchant_center.refresh_token` / `client_id` / `client_secret`.++Save to `$PREFS_PATH`:++```json+{+ "marketing": {+ "projects": {+ "<key>": { "merchant_center": { "merchant_id": "123456789" } }+ }+ }+}+```++Smoke test:++```bash+. "${CLAUDE_PLUGIN_ROOT}/scripts/lib/organic-metrics-aggregator.sh"+merchant_status <key> | jq .+```++Expect `approved` / `disapproved` counts; `null` means merchant ID or auth missing.++> Full key matrix per direct surface: `docs/integrations/direct-channel-wiring.md`+> (repo root). These surfaces double as the free fallback when Windsor.ai is not+> connected or returns dead zeros.+#### WhatsApp Business API**Separate from wacli personal WhatsApp.** Used for Business-to-customer template messaging at scale.diff --git a/claude-ops/tests/test-organic-metrics-aggregator.sh b/claude-ops/tests/test-organic-metrics-aggregator.shnew file mode 100755index 00000000..49e45810--- /dev/null+++ b/claude-ops/tests/test-organic-metrics-aggregator.sh@@ -0,0 +1,111 @@+#!/usr/bin/env bash+# test-organic-metrics-aggregator.sh — smoke tests for scripts/lib/organic-metrics-aggregator.sh+#+# Hermetic by default: uses a project key known to NOT exist in prefs so no network calls fire.+# Asserts:+# - lib sources without crashing+# - every organic_* / merchant_* function returns 0 + echoes `null` for an unknown project+# - organic_all returns a JSON object with empty surfaces array for an unknown project+# - stub surface emits configured_but_not_implemented when creds are declared+# - double-source guard works+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+LIB="$PLUGIN_ROOT/scripts/lib/organic-metrics-aggregator.sh"++pass=0; fail=0+ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1 — $2"; fail=$((fail+1)); }++echo "Testing $LIB"+echo ""++[ -f "$LIB" ] && ok "lib file exists" || { err "lib missing" "$LIB"; exit 1; }++# Use an isolated empty prefs file to guarantee no real config bleeds in.+TMP_PREFS="$(mktemp -t organic-prefs.XXXXXX.json)"+echo '{"marketing":{"projects":{}}}' > "$TMP_PREFS"+trap 'rm -f "$TMP_PREFS"' EXIT++FNS="organic_meta organic_youtube organic_searchconsole merchant_status organic_tiktok"++out="$(+ set +u+ export OPS_AUTOPILOT_PREFS="$TMP_PREFS"+ export OPS_DATA_DIR="$(dirname "$TMP_PREFS")"+ unset META_ACCESS_TOKEN FACEBOOK_ACCESS_TOKEN GOOGLE_ACCESS_TOKEN 2>/dev/null+ # shellcheck disable=SC1090+ . "$LIB"++ for fn in $FNS; do+ r="$($fn nonexistent-project 2>/dev/null)"+ rc=$?+ echo "${fn}_rc=${rc}"+ echo "${fn}_out=${r}"+ done++ r_all="$(organic_all nonexistent-project 2>/dev/null)"+ rc=$?+ echo "all_rc=${rc}"+ echo "all_out=${r_all}"+)"++for fn in $FNS; do+ echo "$out" | grep -q "^${fn}_rc=0$" \+ && ok "${fn} returns rc=0 for unknown project" \+ || err "${fn} rc" "got: $(echo "$out" | grep "^${fn}_rc=")"+ echo "$out" | grep -q "^${fn}_out=null$" \+ && ok "${fn} echoes 'null' for unknown project" \+ || err "${fn} out" "got: $(echo "$out" | grep "^${fn}_out=")"+done++echo "$out" | grep -q "^all_rc=0$" \+ && ok "organic_all returns rc=0" \+ || err "organic_all rc" "got: $(echo "$out" | grep '^all_rc=')"++# organic_all should emit a JSON object with surfaces:[] for unknown project.+all_json="$(echo "$out" | sed -n 's/^all_out=//p')"+if printf '%s' "$all_json" | jq -e '.surfaces | type == "array" and length == 0' >/dev/null 2>&1; then+ ok "organic_all emits JSON with empty .surfaces array"+else+ err "organic_all shape" "got: $all_json"+fi++# Stub sentinel: with tiktok_organic creds declared, organic_tiktok emits+# configured_but_not_implemented (no network needed for the stub).+# Note: _prefs_marketing reads ${OPS_DATA_DIR}/preferences.json, so the fixture+# must live at that exact path inside an isolated temp dir.+TMP_DIR2="$(mktemp -d -t organic-prefs2.XXXXXX)"+echo '{"marketing":{"projects":{"stub-project":{"tiktok_organic":{"access_token":"env:ORGANIC_TEST_UNSET_VAR"}}}}}' > "$TMP_DIR2/preferences.json"+stub_out="$(+ set +u+ export OPS_AUTOPILOT_PREFS="$TMP_DIR2/preferences.json"+ export OPS_DATA_DIR="$TMP_DIR2"+ # shellcheck disable=SC1090+ . "$LIB"+ organic_tiktok stub-project 2>/dev/null+)"+rm -rf "$TMP_DIR2"+if printf '%s' "$stub_out" | jq -e '.status == "configured_but_not_implemented" and .surface == "tiktok_organic"' >/dev/null 2>&1; then+ ok "organic_tiktok emits configured_but_not_implemented sentinel"+else+ err "organic_tiktok stub" "got: $stub_out"+fi++# Double-source guard+dbl="$(+ set +u+ export OPS_AUTOPILOT_PREFS="$TMP_PREFS"+ # shellcheck disable=SC1090+ . "$LIB"+ # shellcheck disable=SC1090+ . "$LIB"+ echo "ok"+)"+echo "$dbl" | grep -q '^ok$' \+ && ok "double-source guard works" \+ || err "double-source guard" "got: $dbl"++echo ""+echo "Results: $pass passed, $fail failed"+[ "$fail" -eq 0 ]diff --git a/docs/integrations/direct-channel-wiring.md b/docs/integrations/direct-channel-wiring.mdnew file mode 100644index 00000000..e0cdf226--- /dev/null+++ b/docs/integrations/direct-channel-wiring.md@@ -0,0 +1,75 @@+# Direct channel wiring — free API fallback for marketing data++The marketing-facing ops commands (`/ops:marketing`, `/ops:socials`,+`/ops:ecom`, `/ops:dash`) can read live channel data through+[Windsor.ai](windsor-ai.md), but Windsor is **optional and paid**. When a+Windsor plan lapses, the connectors keep answering with silent all-zero rows —+which can masquerade as "spend €0, reach 0" for weeks. Every major channel also+exposes a **free first-party API**, and this repo ships direct, registry-driven+libraries for them.++Use the direct libraries as a full alternative when Windsor is not connected,+or as a fallback when Windsor errors or returns the all-zero pattern. Never+present zeros from a dead source as real metrics.++This doc is **provider-agnostic and registry-driven**: all identifiers below+are placeholders — every user supplies their own via+`preferences.json` → `.marketing.projects.<project>.<channel>.*` (values may be+literals, `env:VAR_NAME`, or `doppler:project/config/SECRET` refs, resolved by+`scripts/lib/ga4-resolve.sh`).++## Channel matrix++| Channel | Direct library | Function | Status |+| --------------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------- | -------------------- |+| Meta Ads (paid) | [`scripts/lib/ad-spend-aggregator.sh`](../../claude-ops/scripts/lib/ad-spend-aggregator.sh) | `ad_spend_meta` | implemented |+| Google Ads (paid) | [`scripts/lib/ad-spend-aggregator.sh`](../../claude-ops/scripts/lib/ad-spend-aggregator.sh) | `ad_spend_google` | implemented |+| TikTok / LinkedIn / Reddit / Microsoft / Pinterest Ads | [`scripts/lib/ad-spend-aggregator.sh`](../../claude-ops/scripts/lib/ad-spend-aggregator.sh) | `ad_spend_tiktok` etc. | stub |+| GA4 (analytics) | [`scripts/lib/ga4-data-api.sh`](../../claude-ops/scripts/lib/ga4-data-api.sh) | `ga4_run_report` | implemented |+| Facebook Page + Instagram Business (organic) | [`scripts/lib/organic-metrics-aggregator.sh`](../../claude-ops/scripts/lib/organic-metrics-aggregator.sh) | `organic_meta` | implemented |+| YouTube (organic) | [`scripts/lib/organic-metrics-aggregator.sh`](../../claude-ops/scripts/lib/organic-metrics-aggregator.sh) | `organic_youtube` | implemented |+| Google Search Console | [`scripts/lib/organic-metrics-aggregator.sh`](../../claude-ops/scripts/lib/organic-metrics-aggregator.sh) | `organic_searchconsole` | implemented |+| Google Merchant Center | [`scripts/lib/organic-metrics-aggregator.sh`](../../claude-ops/scripts/lib/organic-metrics-aggregator.sh) | `merchant_status` | implemented |+| TikTok (organic) | [`scripts/lib/organic-metrics-aggregator.sh`](../../claude-ops/scripts/lib/organic-metrics-aggregator.sh) | `organic_tiktok` | stub (see below) |++All aggregator functions share the same contract: `curl -sS --max-time 12`,+errors swallowed, missing creds → `null`, configured-but-stubbed →+`{"status":"configured_but_not_implemented"}`, success → a JSON object with at+least `surface`, `project`, `window_days`. `ad_spend_all` and `organic_all`+fan out across surfaces and aggregate.++## Required keys per channel++Keys live under `preferences.json` → `.marketing.projects.<project>.<channel>`:++| Channel (prefs key) | Fields | Notes |+| --------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |+| `meta` (paid) | `access_token`, `ad_account_id`, `app_secret` (optional) | Marketing API; `appsecret_proof` sent when `app_secret` is present |+| `meta` (organic) | `access_token`, `page_id`, `instagram_business_id` | Same token can serve both; env fallback `META_ACCESS_TOKEN` / `FACEBOOK_ACCESS_TOKEN` |+| `google_ads` | `refresh_token`, `client_id`, `client_secret`, `developer_token`, `customer_id`, `login_customer_id` (optional) | OAuth helpers in `scripts/lib/google-ads-oauth.sh` |+| `ga4` | `property_id` (+ service-account key file, see `ga4-data-api.sh`) | Service-account JWT or gcloud ADC |+| `youtube` | `refresh_token`, `client_id`, `client_secret`, `channel_id` (optional) | Refresh token must carry `yt-analytics.readonly` (+ `youtube.readonly` for subscriber totals) |+| `gsc` | `site_url` (e.g. `sc-domain:example.com`) | Auth via gcloud ADC or `$GOOGLE_ACCESS_TOKEN` (same as `ops-cron-seo-blog-gen.sh`) |+| `merchant_center` | `merchant_id`, plus OAuth refresh creds (scope `content`) or gcloud ADC / `$GOOGLE_ACCESS_TOKEN` | Content API v2.1 `accountstatuses` — approved/pending/disapproved/expiring counts |+| `tiktok_organic` | `access_token` | **Stub** — TikTok requires an approved developer app; declared creds emit the sentinel |++## Usage++```bash+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+. "${PLUGIN_ROOT}/lib/registry-path.sh"+. "${PLUGIN_ROOT}/scripts/lib/ad-spend-aggregator.sh"+. "${PLUGIN_ROOT}/scripts/lib/organic-metrics-aggregator.sh"++ad_spend_all "<project>" # {"project":..,"total_spend_7d":..,"surfaces":[...]}+organic_all "<project>" # {"project":..,"window_days":7,"surfaces":[...]}+```++## Fallback routing (used by the skills)++1. Windsor connected and returning plausible, non-all-zero data → use Windsor+ (cross-channel blending, arbitrary fields).+2. Windsor missing / erroring / all-zero across surfaces that are known to be+ active → use the direct libraries above and label the source accordingly.+3. A surface with no creds in either path → report it as **not wired**, never+ as zero.