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(marketing): v2.7.0 — marketing control center (prewarm + portfolio --live + KPI libs) (#267)
Aurora Capitaldfd5e2767f2e
diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.jsonindex f298c4a1..170d6194 100644--- a/claude-ops/.claude-plugin/plugin.json+++ b/claude-ops/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "ops",- "version": "2.6.0",+ "version": "2.7.0","description": "Business operations command center for Claude Code — 36 skills, 18 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /gtm go-to-market planner, /ops:projects portfolio dashboard, and YOLO mode for autonomous operation with 4 parallel C-suite agents.","author": {"name": "Lifecycle Innovations Limited",diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdindex f7d25931..0e11c10d 100644--- a/claude-ops/CHANGELOG.md+++ b/claude-ops/CHANGELOG.md@@ -1,6 +1,38 @@# ChangelogAll notable changes to this project will be documented in this file.+## [2.7.0] — 2026-05-20++`/ops:marketing` becomes the marketing control center. Every credential discoverable across Doppler/env/keychain auto-links into every project; live KPI rollup across all projects in one render; ad spend aggregated across every paid surface; Stripe revenue with UTM-attributed ROAS; Sentry crash-rate correlation flags ad-spend-at-risk projects.++Builds on v2.6.0 (`/ops:marketing <project>` point-and-go).++### Added++- **`marketing-auth-prewarm` daemon** (`scripts/ops-marketing-auth-prewarm.sh`) — nightly at 04:23 UTC, scans every Doppler project + env vars + shell profiles + macOS keychain + `~/.gcp/*.json` for marketing credentials. Classifies into 20 categories (ads_meta, ads_google, ads_tiktok, ads_linkedin, analytics_ga4, analytics_amplitude, analytics_posthog, email_resend, email_klaviyo, payments_stripe, ecommerce_shopify, fulfillment_shipbob, sms_twilio, errors_sentry, issues_linear, mta_appsflyer, prospect_apollo, infra_cloudflare, infra_vercel). Writes cache at `$OPS_DATA_DIR/marketing-auth-prewarm.json`. Initial scan across 47 Doppler projects found 19 active categories.++- **`bin/ops-marketing-link-prewarm`** — reads the prewarm cache and idempotently writes Doppler cred-refs into `marketing.projects.<key>.<category>.*` slots that are not yet configured. Modes: `--project <key>`, `--all-projects`, `--project <key> --category <cat>`. Atomic prefs writes; never overwrites existing values. Eliminates per-credential prompts during `/ops:marketing setup`.++- **`bin/ops-marketing-portfolio` extension** — new flags `--live`, `--kpis`, `--prewarm-status`. `--live` fans out in parallel to every signal source (Meta + Google Ads spend, Stripe revenue + MRR + UTM-attributed ROAS, GA4 sessions/conversions/CVR, Sentry crash-free-rate) and renders a unified KPI table. Mobile-aware per CLAUDE.md Rule 7. `--prewarm-status` surfaces untapped credentials (creds exist in Doppler but not linked to any project).++- **`scripts/lib/ad-spend-aggregator.sh`** — `ad_spend_meta`, `ad_spend_google`, `ad_spend_tiktok`, `ad_spend_linkedin`, `ad_spend_reddit`, `ad_spend_microsoft`, `ad_spend_pinterest`, `ad_spend_all`. Each normalizes to `{surface, project, spend, impressions, clicks, conversions, conversions_value, roas, window_days}`.++- **`scripts/lib/stripe-revenue.sh`** — `stripe_revenue_7d <project>` returns `{revenue_7d, charge_count, refund_count, active_mrr, active_sub_count, by_utm_source[]}`. UTM-attributed breakdown closes the ground-truth ROAS gap.++- **`scripts/lib/sentry-crash.sh`** — `sentry_crash_rate <project>` returns `{crash_free_7d, crash_free_24h, delta_dod, at_risk}`. When `at_risk == true` AND project has live ad spend, `portfolio --live` shows the project as "ad spend likely wasted today".++- **`scripts/lib/marketing-kpis.sh`** — pure functions: `kpi_roas`, `kpi_cac`, `kpi_ltv`, `kpi_payback_months`, `kpi_cvr`, `kpi_ctr`, `kpi_health_score`, `kpi_compute_all`. Derives metrics from already-fetched JSON — no external API calls.++- **`ops-marketing-provision provision-instagram` + `provision-google-ads`** verbs (from PR #266) — Meta token + page_id → IG Business Account ID auto-resolution with appsecret_proof signing; full 4-step Google Ads OAuth flow.++### Fixed++- `bin/ops-marketing-dash` — Meta + IG Graph API calls now compute and append `appsecret_proof` when `meta.app_secret` is configured. Previously the dash silently returned zeros for any project using a system-user token with "Require App Secret" enabled.++### Tests++107 tests passing across 6 test files: `test-ad-spend-aggregator.sh` (18), `test-stripe-revenue.sh` (6), `test-sentry-crash.sh` (2), `test-marketing-kpis.sh` (36), `test-ops-marketing-link-prewarm.sh` (15), `test-ops-marketing-auth-prewarm.sh` (1), plus all existing `test-ops-marketing-provision.sh` (11). Zero secrets leaked (`test-no-secrets.sh` 14/14 green).+## [2.6.0] — 2026-05-19diff --git a/claude-ops/bin/ops-marketing-link-prewarm b/claude-ops/bin/ops-marketing-link-prewarmnew file mode 100755index 00000000..7ea59a85--- /dev/null+++ b/claude-ops/bin/ops-marketing-link-prewarm@@ -0,0 +1,245 @@+#!/usr/bin/env bash+# bin/ops-marketing-link-prewarm — link prewarm cache creds into preferences.json+#+# Usage:+# ops-marketing-link-prewarm --project <key>+# ops-marketing-link-prewarm --all-projects+# ops-marketing-link-prewarm --project <key> --category <cat>+# OPS_MARKETING_DRY_RUN=1 ops-marketing-link-prewarm ...+# ops-marketing-link-prewarm --project <key> --dry-run+#+# PUBLIC REPO: no real project names, tokens, or paths.++set -uo pipefail++PREFS_PATH="${PREFS_PATH:-${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json}"+OPS_DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+PREWARM_CACHE="${OPS_DATA_DIR}/marketing-auth-prewarm.json"+DRY_RUN="${OPS_MARKETING_DRY_RUN:-0}"++# ── args ─────────────────────────────────────────────────────────────────────+TARGET_PROJECT=""+TARGET_CATEGORY=""+ALL_PROJECTS=0++while [[ $# -gt 0 ]]; do+ case "$1" in+ --project) TARGET_PROJECT="$2"; shift 2 ;;+ --category) TARGET_CATEGORY="$2"; shift 2 ;;+ --all-projects) ALL_PROJECTS=1; shift ;;+ --dry-run) DRY_RUN=1; shift ;;+ *) echo "Unknown flag: $1" >&2; exit 1 ;;+ esac+done++if [[ $ALL_PROJECTS -eq 0 && -z "$TARGET_PROJECT" ]]; then+ echo "Usage: ops-marketing-link-prewarm --project <key> | --all-projects [--category <cat>] [--dry-run]" >&2+ exit 1+fi++# ── prewarm cache check ───────────────────────────────────────────────────────+if [[ ! -f "$PREWARM_CACHE" ]]; then+ echo "Prewarm cache not found: ${PREWARM_CACHE}" >&2+ echo "Run: scripts/ops-marketing-auth-prewarm.sh" >&2+ exit 1+fi++if [[ ! -f "$PREFS_PATH" ]]; then+ echo "Preferences file not found: ${PREFS_PATH}" >&2+ exit 1+fi++# ── category → prefs path mapping ────────────────────────────────────────────+# Returns a list of "key_name:prefs_path" pairs for a given category.+# prefs_path is relative to .marketing.projects.<project>+category_mappings() {+ local cat="$1"+ case "$cat" in+ ads_meta)+ echo "access_token:meta.access_token"+ echo "app_secret:meta.app_secret"+ echo "app_id:meta.app_id"+ echo "ad_account_id:meta.ad_account_id"+ echo "page_id:meta.page_id"+ ;;+ ads_google)+ echo "developer_token:google_ads.developer_token"+ echo "client_id:google_ads.client_id"+ echo "client_secret:google_ads.client_secret"+ echo "refresh_token:google_ads.refresh_token"+ echo "customer_id:google_ads.customer_id"+ ;;+ analytics_ga4)+ echo "property_id:ga4.property_id"+ echo "measurement_id:ga4.measurement_id"+ echo "api_secret:ga4.api_secret"+ ;;+ analytics_amplitude)+ echo "api_key:amplitude.api_key"+ ;;+ analytics_posthog)+ echo "api_key:posthog.api_key"+ ;;+ email_resend)+ echo "api_key:email_marketing.resend.api_key"+ ;;+ email_klaviyo)+ echo "private_key:klaviyo.private_key"+ echo "api_key:klaviyo.api_key"+ ;;+ errors_sentry)+ echo "auth_token:sentry.auth_token"+ echo "org:sentry.org"+ ;;+ issues_linear)+ echo "api_key:linear.api_key"+ ;;+ mta_appsflyer)+ echo "api_key:appsflyer.api_key"+ ;;+ payments_stripe)+ echo "secret_key:stripe.secret_key"+ ;;+ prospect_apollo)+ echo "api_key:apollo.api_key"+ ;;+ ecommerce_shopify)+ echo "admin_token:shopify.admin_token"+ echo "store:shopify.store"+ ;;+ fulfillment_shipbob)+ echo "access_token:shipbob.access_token"+ ;;+ sms_twilio)+ echo "account_sid:twilio.account_sid"+ echo "auth_token:twilio.auth_token"+ echo "api_key_sid:twilio.api_key_sid"+ echo "api_key_secret:twilio.api_key_secret"+ ;;+ seo_ahrefs)+ echo "api_key:ahrefs.api_key"+ ;;+ *)+ # Unknown category — no mappings+ ;;+ esac+}++# ── link one project + one category ──────────────────────────────────────────+link_category() {+ local project="$1"+ local cat="$2"+ local linked_count=0++ # Get all entries for this project+category from prewarm cache+ local entries+ entries="$(jq -c --arg p "$project" --arg c "$cat" \+ '.by_project[$p][$c] // [] | .[]' "$PREWARM_CACHE" 2>/dev/null || true)"++ [[ -z "$entries" ]] && return 0++ # Build mapping of key_name → doppler_ref+ declare -A key_to_ref+ while IFS= read -r entry; do+ [[ -z "$entry" ]] && continue+ local entry_key entry_proj entry_config entry_doppler_key+ entry_key="$(echo "$entry" | jq -r '.key // ""' 2>/dev/null)"+ entry_proj="$(echo "$entry" | jq -r '.project // ""' 2>/dev/null)"+ entry_config="$(echo "$entry" | jq -r '.config // ""' 2>/dev/null)"+ entry_doppler_key="$(echo "$entry" | jq -r '.key // ""' 2>/dev/null)"+ [[ -z "$entry_key" ]] && continue+ key_to_ref["$entry_key"]="doppler:${entry_proj}/${entry_config}/${entry_doppler_key}"+ done <<< "$entries"++ # Apply mappings+ while IFS=: read -r key_name rel_path; do+ [[ -z "$key_name" || -z "$rel_path" ]] && continue+ local doppler_ref="${key_to_ref[$key_name]:-}"+ [[ -z "$doppler_ref" ]] && continue++ # Build full jq path+ local full_jq_path=".marketing.projects[\"${project}\"].${rel_path}"++ # Check existing value — never overwrite non-null+ local existing+ existing="$(jq -r "${full_jq_path} // \"null\"" "$PREFS_PATH" 2>/dev/null || echo "null")"+ if [[ "$existing" != "null" && -n "$existing" ]]; then+ [[ "$DRY_RUN" == "1" ]] && echo " [skip] ${project}.${rel_path} already set" >&2+ continue+ fi++ if [[ "$DRY_RUN" == "1" ]]; then+ echo " [would set] ${project}.${rel_path} = ${doppler_ref}" >&2+ (( linked_count++ )) || true+ continue+ fi++ # Atomic write: jq → tmp → mv+ local tmp+ tmp="$(mktemp "${PREFS_PATH}.tmp.XXXXXX")"+ # Build nested path dynamically from dot-separated rel_path+ local jq_expr+ jq_expr="$(echo "$rel_path" | awk -F. '{+ path = ".marketing.projects[\"'"$project"'\"]"+ for(i=1;i<=NF;i++) path = path "[\"" $i "\"]"+ print path " = $val"+ }')"+ if jq --arg val "$doppler_ref" "$jq_expr" "$PREFS_PATH" > "$tmp" 2>/dev/null; then+ mv "$tmp" "$PREFS_PATH"+ (( linked_count++ )) || true+ else+ rm -f "$tmp"+ echo " [error] failed to write ${project}.${rel_path}" >&2+ fi+ done < <(category_mappings "$cat")++ printf '%d' "$linked_count"+}++# ── link one project (all or filtered categories) ────────────────────────────+link_project() {+ local project="$1"+ local total_linked=0+ local total_cats=0++ # Get categories from prewarm cache for this project+ local cats+ cats="$(jq -r --arg p "$project" '.by_project[$p] // {} | keys[]' "$PREWARM_CACHE" 2>/dev/null || true)"++ if [[ -z "$cats" ]]; then+ echo "No prewarm data for project: ${project}"+ return 0+ fi++ while IFS= read -r cat; do+ [[ -z "$cat" ]] && continue+ # Filter by --category if specified+ if [[ -n "$TARGET_CATEGORY" && "$cat" != "$TARGET_CATEGORY" ]]; then+ continue+ fi+ local n+ n="$(link_category "$project" "$cat")"+ total_linked=$(( total_linked + n ))+ (( total_cats++ )) || true+ done <<< "$cats"++ local dry_prefix=""+ [[ "$DRY_RUN" == "1" ]] && dry_prefix="[dry-run] "+ echo "${dry_prefix}Linked ${total_linked} creds across ${total_cats} categories for project '${project}'."+}++# ── main ─────────────────────────────────────────────────────────────────────+if [[ $ALL_PROJECTS -eq 1 ]]; then+ # Get all projects from prewarm cache+ all_prewarm_projects="$(jq -r '(.by_project // {}) | keys[]' "$PREWARM_CACHE" 2>/dev/null || true)"+ if [[ -z "$all_prewarm_projects" ]]; then+ echo "No projects found in prewarm cache."+ exit 0+ fi+ while IFS= read -r proj; do+ [[ -z "$proj" ]] && continue+ link_project "$proj"+ done <<< "$all_prewarm_projects"+else+ link_project "$TARGET_PROJECT"+fidiff --git a/claude-ops/package.json b/claude-ops/package.jsonindex f6481904..273e031f 100644--- a/claude-ops/package.json+++ b/claude-ops/package.json@@ -1,6 +1,6 @@{"name": "claude-ops-bin",- "version": "2.6.0",+ "version": "2.7.0","private": true,"description": "Runtime dependencies for claude-ops bin scripts (ops-telegram-autolink.mjs, ops-slack-autolink.mjs). Installed separately from telegram-server/ so the .mjs scripts resolve modules from claude-ops/node_modules regardless of invocation cwd.","type": "module",diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.jsonindex b5da8e14..d34a1313 100644--- a/claude-ops/scripts/daemon-services.default.json+++ b/claude-ops/scripts/daemon-services.default.json@@ -85,6 +85,12 @@"cron": "0 9 * * 1","_note": "Weekly Autopilot Studio self-learning calibration (Monday 09:00 UTC ~= 11:00 Europe/Amsterdam, after the 08:00 daily pass). Joins each project's autopilot_state/<project>/creatives.jsonl pre-scores to realized KPIs (kpi.jsonl) and fits a monotone score->predicted_CPL calibrator.json consumed by the next daily pass. python3 stdlib only, no metered calls. Disabled by default; enabled alongside the autopilot block via /ops:setup marketing."},+ "marketing-auth-prewarm": {+ "enabled": true,+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-marketing-auth-prewarm.sh",+ "cron": "23 4 * * *",+ "_note": "Nightly at 04:23 UTC. Scans all Doppler projects + env + keychain for marketing creds and writes a cache at $OPS_DATA_DIR/marketing-auth-prewarm.json. /ops:marketing setup reads this to instantly auto-link new projects without per-credential prompts."+ },"marketing-health-check": {"enabled": false,"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-marketing-health-check.sh",diff --git a/claude-ops/scripts/lib/ad-spend-aggregator.sh b/claude-ops/scripts/lib/ad-spend-aggregator.shnew file mode 100644index 00000000..f4f83879--- /dev/null+++ b/claude-ops/scripts/lib/ad-spend-aggregator.sh@@ -0,0 +1,323 @@+#!/usr/bin/env bash+# scripts/lib/ad-spend-aggregator.sh — normalized ad-spend pulls across paid surfaces+#+# Public functions:+# ad_spend_meta <project> — Meta Marketing API (Graph v18.0) /insights, last_7d+# ad_spend_google <project> — Google Ads searchStream, LAST_7_DAYS+# ad_spend_tiktok <project> — stub (configured_but_not_implemented or null)+# ad_spend_linkedin <project> — stub+# ad_spend_reddit <project> — stub+# ad_spend_microsoft <project> — stub+# ad_spend_pinterest <project> — stub+# ad_spend_all <project> — fan out + aggregate to {"project","total_spend_7d","surfaces":[...]}+#+# Sourcing convention:+# PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+# . "${PLUGIN_ROOT}/lib/registry-path.sh"+# . "${PLUGIN_ROOT}/scripts/lib/ad-spend-aggregator.sh"+#+# Contract:+# - 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, spend, window_days.+# - PUBLIC REPO: no hardcoded project names / tokens / customer IDs.+#+# Requires: bash, jq, curl, openssl.++[ -n "${_AD_SPEND_AGGREGATOR_LOADED:-}" ] && return 0+_AD_SPEND_AGGREGATOR_LOADED=1++set -u++# Source resolve_cred + _prefs_marketing helpers from ga4-resolve.sh.+_AD_SPEND_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# shellcheck disable=SC1091+. "${_AD_SPEND_DIR}/ga4-resolve.sh"++# Source google-ads-oauth.sh if present (provides gads_refresh_access_token).+# Falls back to inline implementation when the lib has not been merged yet.+if [ -f "${_AD_SPEND_DIR}/google-ads-oauth.sh" ]; then+ # shellcheck disable=SC1091+ . "${_AD_SPEND_DIR}/google-ads-oauth.sh"+fi++# ── PREFS resolution ──────────────────────────────────────────────────────────+_ad_spend_prefs_path() {+ printf '%s' "${OPS_AUTOPILOT_PREFS:-${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json}"+}++# ── Inline Google Ads OAuth fallback ──────────────────────────────────────────+# Used only when google-ads-oauth.sh is not present in scripts/lib/.+if ! declare -f gads_refresh_access_token >/dev/null 2>&1; then+ gads_refresh_access_token() {+ local client_id="${1:-}" client_secret="${2:-}" refresh_token="${3:-}"+ if [ -z "$client_id" ] || [ -z "$client_secret" ] || [ -z "$refresh_token" ]; 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++# ── HMAC SHA256 helper (Meta appsecret_proof) ─────────────────────────────────+_ad_spend_hmac_sha256_hex() {+ local key="$1" data="$2"+ printf '%s' "$data" | openssl dgst -sha256 -hmac "$key" 2>/dev/null | awk '{print $NF}'+}++# ── Float-safe arithmetic (jq-based) ──────────────────────────────────────────+_ad_spend_num() {+ # Print 0 for empty/null/non-numeric, else the number as float string.+ local v="${1:-}"+ if [ -z "$v" ] || [ "$v" = "null" ]; then printf '0'; return; fi+ printf '%s' "$v" | jq -R 'tonumber? // 0' 2>/dev/null || printf '0'+}++_ad_spend_div2() {+ # $1 / $2 to 2 decimals, or 0.00 if denom is 0.+ local num denom+ num="$(_ad_spend_num "${1:-0}")"+ denom="$(_ad_spend_num "${2:-0}")"+ if [ "$(printf '%s' "$denom" | jq '. == 0')" = "true" ]; then+ printf '0.00'+ return+ fi+ jq -n --argjson n "$num" --argjson d "$denom" '($n / $d) | . * 100 | round / 100 | tostring' 2>/dev/null \+ | jq -r 'tonumber | . * 100 | round / 100 | tostring' 2>/dev/null \+ || printf '0.00'+}++# ── ad_spend_meta ─────────────────────────────────────────────────────────────+ad_spend_meta() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi++ local prefs; prefs="$(_ad_spend_prefs_path)"+ [ -f "$prefs" ] || { printf 'null'; return 0; }++ local tok_ref acct_ref sec_ref tok acct sec+ tok_ref="$(_prefs_marketing "$proj" "meta" "access_token")"+ acct_ref="$(_prefs_marketing "$proj" "meta" "ad_account_id")"+ sec_ref="$(_prefs_marketing "$proj" "meta" "app_secret")"++ tok="$(resolve_cred "$tok_ref")"+ acct="$(resolve_cred "$acct_ref")"+ sec="$(resolve_cred "$sec_ref")"++ if [ -z "$tok" ] || [ -z "$acct" ]; then+ printf 'null'+ return 0+ fi++ # Normalize ad_account_id — Meta expects "act_<id>" form.+ case "$acct" in+ act_*) : ;;+ *) acct="act_${acct}" ;;+ esac++ local proof=""+ if [ -n "$sec" ]; then+ proof="$(_ad_spend_hmac_sha256_hex "$sec" "$tok")"+ fi++ local url="https://graph.facebook.com/v18.0/${acct}/insights?fields=spend,impressions,clicks,actions,action_values&date_preset=last_7d&level=account&access_token=${tok}"+ [ -n "$proof" ] && url="${url}&appsecret_proof=${proof}"++ local resp+ resp="$(curl -gsS --max-time 12 "$url" 2>/dev/null || echo '{}')"++ # If error, return null.+ local err_code+ err_code="$(printf '%s' "$resp" | jq -r '.error.code // empty' 2>/dev/null || true)"+ if [ -n "$err_code" ]; then+ printf 'null'+ return 0+ fi++ # Extract first data entry (level=account → 1 row).+ local row+ row="$(printf '%s' "$resp" | jq -c '.data[0] // {}' 2>/dev/null || echo '{}')"+ if [ "$row" = "{}" ] || [ -z "$row" ]; then+ # No spend data — return zeroed object so the caller still sees the surface.+ printf '%s' "$(jq -nc --arg p "$proj" \+ '{surface:"meta", project:$p, spend:"0.00", impressions:"0", clicks:"0", purchases:"0", purchase_value:"0", roas:"0.00", window_days:7}')"+ return 0+ fi++ printf '%s' "$row" | jq -c --arg p "$proj" '+ def numstr(v): (v | tostring) // "0";+ def find_action(arr; t):+ (arr // []) | map(select(.action_type == t)) | (.[0].value // "0") | tostring;+ {+ surface: "meta",+ project: $p,+ spend: numstr(.spend // "0"),+ impressions: numstr(.impressions // "0"),+ clicks: numstr(.clicks // "0"),+ purchases: find_action(.actions; "purchase"),+ purchase_value: find_action(.action_values; "purchase"),+ window_days: 7+ }+ | .roas = (+ if ((.spend | tonumber? // 0) == 0) then "0.00"+ else (((.purchase_value | tonumber? // 0) / (.spend | tonumber? // 1)) * 100 | round / 100 | tostring)+ end+ )+ ' 2>/dev/null || printf 'null'+}++# ── ad_spend_google ───────────────────────────────────────────────────────────+ad_spend_google() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi++ local prefs; prefs="$(_ad_spend_prefs_path)"+ [ -f "$prefs" ] || { printf 'null'; return 0; }++ local refresh_token client_id client_secret developer_token customer_id login_customer_id+ refresh_token="$(resolve_cred "$(_prefs_marketing "$proj" "google_ads" "refresh_token")")"+ client_id="$(resolve_cred "$(_prefs_marketing "$proj" "google_ads" "client_id")")"+ client_secret="$(resolve_cred "$(_prefs_marketing "$proj" "google_ads" "client_secret")")"+ developer_token="$(resolve_cred "$(_prefs_marketing "$proj" "google_ads" "developer_token")")"+ customer_id="$(resolve_cred "$(_prefs_marketing "$proj" "google_ads" "customer_id")")"+ login_customer_id="$(resolve_cred "$(_prefs_marketing "$proj" "google_ads" "login_customer_id")")"++ if [ -z "$refresh_token" ] || [ -z "$client_id" ] || [ -z "$client_secret" ] \+ || [ -z "$developer_token" ] || [ -z "$customer_id" ]; then+ printf 'null'+ return 0+ fi++ local access_token+ access_token="$(gads_refresh_access_token "$client_id" "$client_secret" "$refresh_token" 2>/dev/null || true)"+ if [ -z "$access_token" ]; then+ printf 'null'+ return 0+ fi++ # Strip dashes from customer_id (Google Ads expects digits only).+ local cid="${customer_id//-/}"+ local login_cid="${login_customer_id//-/}"++ local query='SELECT metrics.cost_micros, metrics.impressions, metrics.clicks, metrics.conversions, metrics.conversions_value FROM customer WHERE segments.date DURING LAST_7_DAYS'+ local body+ body="$(jq -n --arg q "$query" '{query: $q}')"++ local hdr_login=()+ if [ -n "$login_cid" ]; then+ hdr_login=(-H "login-customer-id: ${login_cid}")+ fi++ local resp+ resp="$(curl -sS --max-time 12 -X POST \+ "https://googleads.googleapis.com/v17/customers/${cid}/googleAds:searchStream" \+ -H "Authorization: Bearer ${access_token}" \+ -H "developer-token: ${developer_token}" \+ -H "Content-Type: application/json" \+ "${hdr_login[@]}" \+ -d "$body" 2>/dev/null || echo '[]')"++ # Aggregate across all streamed result rows.+ local cost_micros impressions clicks conversions conv_value+ cost_micros="$(printf '%s' "$resp" | jq '[.[]?.results[]?.metrics.costMicros // 0 | tonumber? // 0] | add // 0' 2>/dev/null || echo 0)"+ impressions="$(printf '%s' "$resp" | jq '[.[]?.results[]?.metrics.impressions // 0 | tonumber? // 0] | add // 0' 2>/dev/null || echo 0)"+ clicks="$(printf '%s' "$resp" | jq '[.[]?.results[]?.metrics.clicks // 0 | tonumber? // 0] | add // 0' 2>/dev/null || echo 0)"+ conversions="$(printf '%s' "$resp" | jq '[.[]?.results[]?.metrics.conversions // 0 | tonumber? // 0] | add // 0' 2>/dev/null || echo 0)"+ conv_value="$(printf '%s' "$resp" | jq '[.[]?.results[]?.metrics.conversionsValue // 0 | tonumber? // 0] | add // 0' 2>/dev/null || echo 0)"++ jq -nc \+ --arg p "$proj" \+ --argjson cm "$cost_micros" \+ --argjson imp "$impressions" \+ --argjson clk "$clicks" \+ --argjson conv "$conversions" \+ --argjson cv "$conv_value" '+ {+ surface: "google_ads",+ project: $p,+ spend: (($cm / 1000000) * 100 | round / 100 | tostring),+ impressions: ($imp | tostring),+ clicks: ($clk | tostring),+ conversions: ($conv | tostring),+ conversions_value: ($cv | tostring),+ window_days: 7+ }+ | .roas = (+ if ($cm == 0) then "0.00"+ else (($cv / ($cm / 1000000)) * 100 | round / 100 | tostring)+ end+ )+ ' 2>/dev/null || printf 'null'+}++# ── Stubs: tiktok / linkedin / reddit / microsoft / pinterest ─────────────────+_ad_spend_stub_surface() {+ local surface="$1" proj="$2" field="$3"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi+ local prefs; prefs="$(_ad_spend_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+ # Configured but not yet implemented — emit a sentinel.+ jq -nc --arg s "$surface" --arg p "$proj" \+ '{surface:$s, project:$p, status:"configured_but_not_implemented"}' 2>/dev/null \+ || printf 'null'+}++ad_spend_tiktok() { _ad_spend_stub_surface "tiktok" "${1:-}" "access_token"; }+ad_spend_linkedin() { _ad_spend_stub_surface "linkedin" "${1:-}" "access_token"; }+ad_spend_reddit() { _ad_spend_stub_surface "reddit" "${1:-}" "access_token"; }+ad_spend_microsoft() { _ad_spend_stub_surface "microsoft" "${1:-}" "access_token"; }+ad_spend_pinterest() { _ad_spend_stub_surface "pinterest" "${1:-}" "access_token"; }++# ── ad_spend_all ──────────────────────────────────────────────────────────────+ad_spend_all() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then+ jq -nc '{project:"", total_spend_7d:"0.00", window_days:7, surfaces:[]}'+ return 0+ fi++ local results=()+ local out+ for fn in ad_spend_meta ad_spend_google ad_spend_tiktok ad_spend_linkedin ad_spend_reddit ad_spend_microsoft ad_spend_pinterest; do+ out="$("$fn" "$proj" 2>/dev/null || printf 'null')"+ [ -z "$out" ] && out="null"+ if [ "$out" != "null" ]; then+ results+=("$out")+ fi+ done++ # Build surfaces array via jq slurp.+ local surfaces_json="[]"+ if [ ${#results[@]} -gt 0 ]; then+ surfaces_json="$(printf '%s\n' "${results[@]}" | jq -s '.' 2>/dev/null || echo '[]')"+ fi++ # Sum .spend over surfaces (only those with a numeric .spend field).+ local total+ total="$(printf '%s' "$surfaces_json" | jq '[.[] | (.spend // "0") | tonumber? // 0] | add // 0 | . * 100 | round / 100' 2>/dev/null || echo 0)"++ jq -nc \+ --arg p "$proj" \+ --argjson surfaces "$surfaces_json" \+ --argjson total "$total" '+ {+ project: $p,+ total_spend_7d: ($total | tostring),+ window_days: 7,+ surfaces: $surfaces+ }+ ' 2>/dev/null || jq -nc --arg p "$proj" '{project:$p, total_spend_7d:"0.00", window_days:7, surfaces:[]}'+}diff --git a/claude-ops/scripts/lib/marketing-kpis.sh b/claude-ops/scripts/lib/marketing-kpis.shnew file mode 100755index 00000000..192e823f--- /dev/null+++ b/claude-ops/scripts/lib/marketing-kpis.sh@@ -0,0 +1,220 @@+#!/usr/bin/env bash+# scripts/lib/marketing-kpis.sh — Pure-bash KPI computation+#+# Source-able library. No external API calls. All functions:+# kpi_roas <spend> <revenue>+# kpi_cac <spend> <new_customers>+# kpi_ltv <aov> <repeat_purchase_rate> <gross_margin>+# kpi_payback_months <cac> <mrr>+# kpi_cvr <conversions> <sessions>+# kpi_ctr <clicks> <impressions>+# kpi_health_score <project_json>+# kpi_compute_all <project_data_json>+#+# set -u only — no set -e in libs++[ -n "${_MARKETING_KPIS_LOADED:-}" ] && return 0+_MARKETING_KPIS_LOADED=1++set -u++# ---------------------------------------------------------------------------+# kpi_roas <spend> <revenue>+# Returns ROAS as float (2dp). Empty string if both zero.+# ---------------------------------------------------------------------------+kpi_roas() {+ local spend="${1:-0}"+ local revenue="${2:-0}"+ local result+ result="$(awk "BEGIN {s=$spend+0; r=$revenue+0; if(s==0 && r==0) exit 1; if(s>0) printf \"%.2f\", r/s; else printf \"%.2f\", 0}")" || { printf ''; return 0; }+ printf '%s' "$result"+}++# ---------------------------------------------------------------------------+# kpi_cac <spend> <new_customers>+# Returns spend/customers (2dp). "—" if new_customers == 0.+# ---------------------------------------------------------------------------+kpi_cac() {+ local spend="${1:-0}"+ local customers="${2:-0}"+ local result+ result="$(awk "BEGIN {s=$spend+0; c=$customers+0; if(c==0) {print \"—\"; exit} printf \"%.2f\", s/c}")"+ printf '%s' "$result"+}++# ---------------------------------------------------------------------------+# kpi_ltv <aov> <repeat_purchase_rate> <gross_margin>+# Standard LTV = AOV × (1/(1-RPR)) × GM+# Returns "—" if any input is 0 or RPR >= 1.+# ---------------------------------------------------------------------------+kpi_ltv() {+ local aov="${1:-0}"+ local rpr="${2:-0}"+ local gm="${3:-0}"+ local result+ result="$(awk "BEGIN {+ a=$aov+0; r=$rpr+0; g=$gm+0;+ if(a==0 || r==0 || g==0 || r>=1) {print \"—\"; exit}+ printf \"%.2f\", a * (1/(1-r)) * g+ }")"+ printf '%s' "$result"+}++# ---------------------------------------------------------------------------+# kpi_payback_months <cac> <mrr>+# Returns cac/mrr (2dp). "—" if mrr == 0.+# ---------------------------------------------------------------------------+kpi_payback_months() {+ local cac="${1:-0}"+ local mrr="${2:-0}"+ local result+ result="$(awk "BEGIN {c=$cac+0; m=$mrr+0; if(m==0) {print \"—\"; exit} printf \"%.2f\", c/m}")"+ printf '%s' "$result"+}++# ---------------------------------------------------------------------------+# kpi_cvr <conversions> <sessions>+# Returns (conv/sessions)*100 (2dp). "—" if sessions == 0.+# ---------------------------------------------------------------------------+kpi_cvr() {+ local conversions="${1:-0}"+ local sessions="${2:-0}"+ local result+ result="$(awk "BEGIN {c=$conversions+0; s=$sessions+0; if(s==0) {print \"—\"; exit} printf \"%.2f\", (c/s)*100}")"+ printf '%s' "$result"+}++# ---------------------------------------------------------------------------+# kpi_ctr <clicks> <impressions>+# Returns (clicks/impressions)*100 (2dp). "—" if impressions == 0.+# ---------------------------------------------------------------------------+kpi_ctr() {+ local clicks="${1:-0}"+ local impressions="${2:-0}"+ local result+ result="$(awk "BEGIN {c=$clicks+0; i=$impressions+0; if(i==0) {print \"—\"; exit} printf \"%.2f\", (c/i)*100}")"+ printf '%s' "$result"+}++# ---------------------------------------------------------------------------+# kpi_health_score <project_json>+# Composite 0-100 score. Returns JSON: {"score":N,"label":"Healthy|Warning|Critical"}+# Scoring:+# ROAS: >=3 → +30, 1-3 → +15, else 0+# CVR: >=2% → +20, 1-2% → +10, else 0+# Crash: >=0.99 → +20, 0.95-0.99 → +10, <0.90 → -20, else 0+# Profit: revenue > ad_spend → +20+# Active: ad_spend > 0 → +10+# ---------------------------------------------------------------------------+kpi_health_score() {+ local data="${1:-{}}"++ local roas cvr crash_free ad_spend revenue+ roas="$(echo "$data" | jq -r '.roas // 0' 2>/dev/null | tr -d '\n' || echo 0)"+ cvr="$(echo "$data" | jq -r '.cvr // 0' 2>/dev/null | tr -d '\n' || echo 0)"+ crash_free="$(echo "$data" | jq -r '.crash_free_rate // 1' 2>/dev/null | tr -d '\n' || echo 1)"+ ad_spend="$(echo "$data" | jq -r '.ad_spend // 0' 2>/dev/null | tr -d '\n' || echo 0)"+ revenue="$(echo "$data" | jq -r '.revenue // 0' 2>/dev/null | tr -d '\n' || echo 0)"++ local score label+ score="$(awk "BEGIN {+ roas=$roas+0; cvr=$cvr+0; cf=$crash_free+0;+ spend=$ad_spend+0; rev=$revenue+0;+ s=0;+ # ROAS+ if (roas >= 3) s += 30;+ else if (roas >= 1) s += 15;+ # CVR+ if (cvr >= 2) s += 20;+ else if (cvr >= 1) s += 10;+ # Crash-free+ if (cf >= 0.99) s += 20;+ else if (cf >= 0.95) s += 10;+ else if (cf < 0.90) s -= 20;+ # Profitability+ if (rev > spend) s += 20;+ # Active campaigns+ if (spend > 0) s += 10;+ # Floor at 0+ if (s < 0) s = 0;+ print s+ }")"++ if [ "$score" -ge 70 ] 2>/dev/null; then+ label="Healthy"+ elif [ "$score" -ge 40 ] 2>/dev/null; then+ label="Warning"+ else+ label="Critical"+ fi++ jq -n --argjson score "$score" --arg label "$label" \+ '{"score": $score, "label": $label}'+}++# ---------------------------------------------------------------------------+# kpi_compute_all <project_data_json>+# Master function: enriches input JSON with all computed KPIs.+# ---------------------------------------------------------------------------+kpi_compute_all() {+ local data="${1:-{}}"++ local spend revenue impressions clicks conversions sessions+ local mrr new_customers crash_free aov rpr gm+ spend="$(echo "$data" | jq -r '.spend // 0' 2>/dev/null || echo 0)"+ revenue="$(echo "$data" | jq -r '.revenue // 0' 2>/dev/null || echo 0)"+ impressions="$(echo "$data" | jq -r '.impressions // 0' 2>/dev/null || echo 0)"+ clicks="$(echo "$data" | jq -r '.clicks // 0' 2>/dev/null || echo 0)"+ conversions="$(echo "$data" | jq -r '.conversions // 0' 2>/dev/null || echo 0)"+ sessions="$(echo "$data" | jq -r '.sessions // 0' 2>/dev/null || echo 0)"+ mrr="$(echo "$data" | jq -r '.mrr // 0' 2>/dev/null || echo 0)"+ new_customers="$(echo "$data" | jq -r '.new_customers // 0' 2>/dev/null || echo 0)"+ crash_free="$(echo "$data" | jq -r '.crash_free_rate // 1' 2>/dev/null || echo 1)"+ aov="$(echo "$data" | jq -r '.aov // 0' 2>/dev/null || echo 0)"+ rpr="$(echo "$data" | jq -r '.repeat_purchase_rate // 0' 2>/dev/null || echo 0)"+ gm="$(echo "$data" | jq -r '.gross_margin // 0' 2>/dev/null || echo 0)"++ local roas cac ltv payback cvr ctr+ roas="$(kpi_roas "$spend" "$revenue")"+ cac="$(kpi_cac "$spend" "$new_customers")"+ ltv="$(kpi_ltv "$aov" "$rpr" "$gm")"+ payback="$(kpi_payback_months "$cac" "$mrr")"+ cvr="$(kpi_cvr "$conversions" "$sessions")"+ ctr="$(kpi_ctr "$clicks" "$impressions")"++ # Build enriched data for health score (pass numeric roas/cvr)+ local health_input+ health_input="$(echo "$data" | jq \+ --arg roas "${roas:-0}" \+ --arg cvr "${cvr:-0}" \+ '. + {roas: ($roas | if . == "—" or . == "" then 0 else tonumber end),+ cvr: ($cvr | if . == "—" or . == "" then 0 else tonumber end)}' \+ 2>/dev/null || echo "$data")"++ local health+ health="$(kpi_health_score "$health_input")"++ local health_score health_label+ health_score="$(echo "$health" | jq -r '.score' 2>/dev/null || echo 0)"+ health_label="$(echo "$health" | jq -r '.label' 2>/dev/null || echo 'Unknown')"++ echo "$data" | jq \+ --arg roas "${roas:-}" \+ --arg cac "${cac:-}" \+ --arg ltv "${ltv:-}" \+ --arg payback "${payback:-}" \+ --arg cvr "${cvr:-}" \+ --arg ctr "${ctr:-}" \+ --argjson health_score "$health_score" \+ --arg health_label "$health_label" \+ '. + {+ roas: $roas,+ cac: $cac,+ ltv: $ltv,+ payback_months: $payback,+ cvr_pct: $cvr,+ ctr_pct: $ctr,+ health_score: $health_score,+ health_label: $health_label+ }' 2>/dev/null+}diff --git a/claude-ops/scripts/lib/sentry-crash.sh b/claude-ops/scripts/lib/sentry-crash.shnew file mode 100755index 00000000..516804a1--- /dev/null+++ b/claude-ops/scripts/lib/sentry-crash.sh@@ -0,0 +1,210 @@+#!/usr/bin/env bash+# scripts/lib/sentry-crash.sh — Sentry crash-free rate correlation+#+# Source-able library. Exports:+# sentry_crash_rate <project> — per-project crash-free rate JSON+# sentry_crash_all_projects — iterate all PREFS projects+#+# Requires: scripts/lib/ga4-resolve.sh (for resolve_cred)+# set -u only — no set -e in libs++[ -n "${_SENTRY_CRASH_LOADED:-}" ] && return 0+_SENTRY_CRASH_LOADED=1++set -u++# ---------------------------------------------------------------------------+# _sentry_token — resolve auth token from env or Doppler+# ---------------------------------------------------------------------------+_sentry_token() {+ local tok="${SENTRY_AUTH_TOKEN:-}"+ if [ -n "$tok" ]; then+ printf '%s' "$tok"+ return 0+ fi+ # Fallback: Doppler claude-ops/prd/SENTRY_AUTH_TOKEN+ doppler secrets get SENTRY_AUTH_TOKEN \+ --project claude-ops --config prd --plain 2>/dev/null || true+}++# ---------------------------------------------------------------------------+# _sentry_api <path> — authenticated GET against sentry.io API+# ---------------------------------------------------------------------------+_sentry_api() {+ local path="${1:-}"+ local tok+ tok="$(_sentry_token)"+ [ -z "$tok" ] && return 0+ curl -sS --max-time 10 \+ -H "Authorization: Bearer ${tok}" \+ "https://sentry.io/api/0${path}" 2>/dev/null || true+}++# ---------------------------------------------------------------------------+# sentry_crash_rate <project>+# Heuristically maps project name to Sentry project slugs, computes crash-free.+# Echoes JSON or "null" on no match / error. Always returns 0.+# ---------------------------------------------------------------------------+sentry_crash_rate() {+ local project="${1:-}"+ local org="${SENTRY_ORG:-my-project}"++ if [ -z "$project" ]; then+ echo "null"+ return 0+ fi++ # List all Sentry projects in the org+ local projects_json+ projects_json="$(_sentry_api "/organizations/${org}/projects/")"++ if [ -z "$projects_json" ] || ! echo "$projects_json" | jq -e 'type == "array"' >/dev/null 2>&1; then+ echo "null"+ return 0+ fi++ # Filter slugs matching the project name (substring, case-insensitive)+ local matched_slugs+ matched_slugs="$(echo "$projects_json" | jq -r \+ --arg stem "$project" \+ '[.[] | select(.slug | ascii_downcase | contains($stem | ascii_downcase)) | .slug] | .[]' \+ 2>/dev/null || true)"++ if [ -z "$matched_slugs" ]; then+ echo "null"+ return 0+ fi++ local slugs_array+ slugs_array="$(echo "$matched_slugs" | jq -R . | jq -s . 2>/dev/null)"++ # Aggregate crash-free rates across all matching slugs+ local total_sessions_7d=0+ local total_crashes_7d=0+ local total_sessions_24h=0+ local total_crashes_24h=0+ local today_sessions=0+ local today_crashes=0+ local yesterday_sessions=0+ local yesterday_crashes=0++ while IFS= read -r slug; do+ [ -z "$slug" ] && continue++ # 7-day sessions+ local resp_7d+ resp_7d="$(_sentry_api "/projects/${org}/${slug}/stats_v2/?stat=sum%28session%29&category=session&statsPeriod=7d&interval=1d")"++ # 7-day errors (crashes = sessions with crashed status)+ local resp_crash_7d+ resp_crash_7d="$(_sentry_api "/projects/${org}/${slug}/stats_v2/?stat=sum%28session%29&category=session&statsPeriod=7d&interval=1d&query=session.status%3Acreashed")"++ # 24h sessions+ local resp_24h+ resp_24h="$(_sentry_api "/projects/${org}/${slug}/stats_v2/?stat=sum%28session%29&category=session&statsPeriod=24h&interval=1h")"++ local resp_crash_24h+ resp_crash_24h="$(_sentry_api "/projects/${org}/${slug}/stats_v2/?stat=sum%28session%29&category=session&statsPeriod=24h&interval=1h&query=session.status%3Acrashed")"++ # Sum totals from groups[0].totals."sum(session)"+ local s7d c7d s24h c24h+ s7d="$(echo "$resp_7d" | jq -r '.groups[0].totals["sum(session)"] // 0' 2>/dev/null || echo 0)"+ c7d="$(echo "$resp_crash_7d" | jq -r '.groups[0].totals["sum(session)"] // 0' 2>/dev/null || echo 0)"+ s24h="$(echo "$resp_24h" | jq -r '.groups[0].totals["sum(session)"] // 0' 2>/dev/null || echo 0)"+ c24h="$(echo "$resp_crash_24h" | jq -r '.groups[0].totals["sum(session)"] // 0' 2>/dev/null || echo 0)"++ # For DoD: split 7d intervals into today (last) and yesterday (second to last)+ # intervals are oldest-first; last = today, second-to-last = yesterday+ local today_s yesterday_s today_c yesterday_c+ today_s="$(echo "$resp_7d" | jq -r 'if (.groups[0].series["sum(session)"] | length) > 0 then .groups[0].series["sum(session)"][-1] else 0 end' 2>/dev/null || echo 0)"+ yesterday_s="$(echo "$resp_7d" | jq -r 'if (.groups[0].series["sum(session)"] | length) > 1 then .groups[0].series["sum(session)"][-2] else 0 end' 2>/dev/null || echo 0)"+ today_c="$(echo "$resp_crash_7d" | jq -r 'if (.groups[0].series["sum(session)"] | length) > 0 then .groups[0].series["sum(session)"][-1] else 0 end' 2>/dev/null || echo 0)"+ yesterday_c="$(echo "$resp_crash_7d" | jq -r 'if (.groups[0].series["sum(session)"] | length) > 1 then .groups[0].series["sum(session)"][-2] else 0 end' 2>/dev/null || echo 0)"++ total_sessions_7d="$(awk "BEGIN {print $total_sessions_7d + $s7d}")"+ total_crashes_7d="$(awk "BEGIN {print $total_crashes_7d + $c7d}")"+ total_sessions_24h="$(awk "BEGIN {print $total_sessions_24h + $s24h}")"+ total_crashes_24h="$(awk "BEGIN {print $total_crashes_24h + $c24h}")"+ today_sessions="$(awk "BEGIN {print $today_sessions + $today_s}")"+ today_crashes="$(awk "BEGIN {print $today_crashes + $today_c}")"+ yesterday_sessions="$(awk "BEGIN {print $yesterday_sessions + $yesterday_s}")"+ yesterday_crashes="$(awk "BEGIN {print $yesterday_crashes + $yesterday_c}")"++ done <<< "$matched_slugs"++ # Compute rates+ local cf_7d cf_24h cf_today cf_yesterday delta_dod at_risk ad_risk_msg+ cf_7d="$(awk "BEGIN {s=$total_sessions_7d+0; c=$total_crashes_7d+0; if(s>0) printf \"%.4f\", (s-c)/s; else printf \"1.0\"}")"+ cf_24h="$(awk "BEGIN {s=$total_sessions_24h+0; c=$total_crashes_24h+0; if(s>0) printf \"%.4f\", (s-c)/s; else printf \"1.0\"}")"+ cf_today="$(awk "BEGIN {s=$today_sessions+0; c=$today_crashes+0; if(s>0) printf \"%.4f\", (s-c)/s; else printf \"1.0\"}")"+ cf_yesterday="$(awk "BEGIN {s=$yesterday_sessions+0; c=$yesterday_crashes+0; if(s>0) printf \"%.4f\", (s-c)/s; else printf \"1.0\"}")"+ delta_dod="$(awk "BEGIN {printf \"%.4f\", $cf_today - $cf_yesterday}")"++ at_risk="false"+ ad_risk_msg=""+ local delta_check+ delta_check="$(awk "BEGIN {print ($delta_dod < -0.05) ? \"yes\" : \"no\"}")"+ if [ "$delta_check" = "yes" ]; then+ at_risk="true"+ local pct+ pct="$(awk "BEGIN {printf \"%.2f\", -$delta_dod * 100}")"+ ad_risk_msg="AD SPEND AT RISK — crash-free rate dropped ${pct}pp DoD"+ fi++ jq -n \+ --arg surface "sentry" \+ --arg proj "$project" \+ --argjson slugs "$slugs_array" \+ --argjson cf7 "$cf_7d" \+ --argjson cf24 "$cf_24h" \+ --argjson dod "$delta_dod" \+ --argjson risk "$at_risk" \+ --arg msg "$ad_risk_msg" \+ '{+ surface: $surface,+ project: $proj,+ sentry_projects: $slugs,+ crash_free_7d: $cf7,+ crash_free_24h: $cf24,+ delta_dod: $dod,+ at_risk: $risk,+ ad_spend_risk: (if $msg != "" then $msg else null end)+ }'++ return 0+}++# ---------------------------------------------------------------------------+# sentry_crash_all_projects+# Iterates PREFS marketing projects and calls sentry_crash_rate for each.+# Echoes a JSON array. Always returns 0.+# ---------------------------------------------------------------------------+sentry_crash_all_projects() {+ local prefs="${OPS_DATA_DIR:-}/preferences.json"+ local results="[]"++ if [ ! -f "$prefs" ]; then+ echo "[]"+ return 0+ fi++ local projects+ projects="$(jq -r '.marketing.projects | keys[]' "$prefs" 2>/dev/null || true)"++ if [ -z "$projects" ]; then+ echo "[]"+ return 0+ fi++ while IFS= read -r proj; do+ [ -z "$proj" ] && continue+ local entry+ entry="$(sentry_crash_rate "$proj")"+ if [ -n "$entry" ] && [ "$entry" != "null" ]; then+ results="$(echo "$results" | jq --argjson e "$entry" '. + [$e]' 2>/dev/null || echo "$results")"+ fi+ done <<< "$projects"++ echo "$results"+ return 0+}diff --git a/claude-ops/scripts/lib/stripe-revenue.sh b/claude-ops/scripts/lib/stripe-revenue.shnew file mode 100644index 00000000..4a3e9b0e--- /dev/null+++ b/claude-ops/scripts/lib/stripe-revenue.sh@@ -0,0 +1,229 @@+#!/usr/bin/env bash+# scripts/lib/stripe-revenue.sh — normalized Stripe revenue pulls per project+#+# Public functions:+# stripe_revenue_7d <project> — 7-day revenue, MRR, UTM breakdown+# stripe_revenue_all_projects — fan out across configured projects+#+# Sourcing convention:+# PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+# . "${PLUGIN_ROOT}/lib/registry-path.sh"+# . "${PLUGIN_ROOT}/scripts/lib/stripe-revenue.sh"+#+# Contract:+# - All HTTP via `curl -sS --max-time 12 ...`. Every function returns 0.+# - Missing key -> echo `null`.+# - PUBLIC REPO: no hardcoded project names / tokens.+#+# Requires: bash, jq, curl. doppler optional (used by resolve_cred for doppler: refs).++[ -n "${_STRIPE_REVENUE_LOADED:-}" ] && return 0+_STRIPE_REVENUE_LOADED=1++set -u++_STRIPE_REV_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# shellcheck disable=SC1091+. "${_STRIPE_REV_DIR}/ga4-resolve.sh"++_stripe_prefs_path() {+ printf '%s' "${OPS_AUTOPILOT_PREFS:-${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json}"+}++# ── _stripe_resolve_key <project> ─────────────────────────────────────────────+# Resolution order:+# 1) marketing.projects.<p>.stripe.secret_key (via resolve_cred — env/doppler/literal)+# 2) Doppler key STRIPE_<PROJECT_UPPER>_SECRET_KEY (from any project/config the doppler CLI is configured for)+# 3) Doppler key STRIPE_<PROJECT_UPPER>_API_SECRET_KEY+# Echoes the key (or empty if none).+_stripe_resolve_key() {+ local proj="${1:-}"+ [ -z "$proj" ] && return 0++ local prefs; prefs="$(_stripe_prefs_path)"+ local key=""++ if [ -f "$prefs" ]; then+ local ref+ ref="$(_prefs_marketing "$proj" "stripe" "secret_key")"+ if [ -n "$ref" ] && [ "$ref" != "null" ]; then+ key="$(resolve_cred "$ref" 2>/dev/null || true)"+ fi+ fi++ if [ -n "$key" ]; then+ printf '%s' "$key"+ return 0+ fi++ # Doppler fallbacks. Project upper, dashes -> underscores.+ local upper+ upper="$(printf '%s' "$proj" | tr '[:lower:]' '[:upper:]' | tr '-' '_')"++ if command -v doppler >/dev/null 2>&1; then+ key="$(doppler secrets get "STRIPE_${upper}_SECRET_KEY" --plain 2>/dev/null || true)"+ if [ -n "$key" ] && [ "$key" != "null" ]; then+ printf '%s' "$key"+ return 0+ fi+ key="$(doppler secrets get "STRIPE_${upper}_API_SECRET_KEY" --plain 2>/dev/null || true)"+ if [ -n "$key" ] && [ "$key" != "null" ]; then+ printf '%s' "$key"+ return 0+ fi+ fi++ # Final env fallback.+ local env_a="STRIPE_${upper}_SECRET_KEY" env_b="STRIPE_${upper}_API_SECRET_KEY"+ if [ -n "${!env_a:-}" ]; then printf '%s' "${!env_a}"; return 0; fi+ if [ -n "${!env_b:-}" ]; then printf '%s' "${!env_b}"; return 0; fi+}++# ── stripe_revenue_7d <project> ───────────────────────────────────────────────+stripe_revenue_7d() {+ local proj="${1:-}"+ if [ -z "$proj" ]; then printf 'null'; return 0; fi++ local key+ key="$(_stripe_resolve_key "$proj" 2>/dev/null || true)"+ if [ -z "$key" ]; then+ printf 'null'+ return 0+ fi++ local now seven_days_ago+ now="$(date +%s)"+ seven_days_ago=$((now - 7 * 86400))++ # ── Charges (last 7d) ──+ local charges_resp+ charges_resp="$(curl -sS --max-time 12 -G "https://api.stripe.com/v1/charges" \+ --data-urlencode "created[gte]=${seven_days_ago}" \+ --data-urlencode "limit=100" \+ -u "${key}:" 2>/dev/null || echo '{}')"++ # Error check.+ local err_type+ err_type="$(printf '%s' "$charges_resp" | jq -r '.error.type // empty' 2>/dev/null || true)"+ if [ -n "$err_type" ]; then+ printf 'null'+ return 0+ fi++ local revenue_cents charge_count refund_count currency+ revenue_cents="$(printf '%s' "$charges_resp" | jq '[.data[]? | select(.status == "succeeded") | .amount // 0] | add // 0' 2>/dev/null || echo 0)"+ charge_count="$(printf '%s' "$charges_resp" | jq '[.data[]? | select(.status == "succeeded")] | length' 2>/dev/null || echo 0)"+ refund_count="$(printf '%s' "$charges_resp" | jq '[.data[]? | select(.refunded == true)] | length' 2>/dev/null || echo 0)"+ currency="$(printf '%s' "$charges_resp" | jq -r '.data[0].currency // "usd"' 2>/dev/null || echo 'usd')"++ # ── UTM breakdown ──+ # Group by metadata.utm_source (case-insensitive). Build [{utm_source,revenue,count}].+ local by_utm+ by_utm="$(printf '%s' "$charges_resp" | jq -c '+ [.data[]?+ | select(.status == "succeeded")+ | {+ utm_source: ((.metadata.utm_source // .metadata.UTM_SOURCE // "") | ascii_downcase),+ amount: (.amount // 0)+ }+ | select(.utm_source != "")+ ]+ | group_by(.utm_source)+ | map({+ utm_source: .[0].utm_source,+ revenue: ((map(.amount) | add // 0) / 100 | . * 100 | round / 100 | tostring),+ count: length+ })+ ' 2>/dev/null || echo '[]')"+ [ -z "$by_utm" ] && by_utm='[]'++ # ── Subscriptions (active) → MRR ──+ local subs_resp+ subs_resp="$(curl -sS --max-time 12 -G "https://api.stripe.com/v1/subscriptions" \+ --data-urlencode "status=active" \+ --data-urlencode "limit=100" \+ -u "${key}:" 2>/dev/null || echo '{}')"++ # MRR: for each subscription, sum items.data[].price.unit_amount * items.data[].quantity,+ # then normalize to monthly based on price.recurring.interval.+ local active_mrr_cents active_sub_count+ active_mrr_cents="$(printf '%s' "$subs_resp" | jq '+ def per_month(unit; qty; interval; count):+ (unit * qty) as $line+ | (count // 1) as $ic+ | if interval == "month" then ($line / $ic)+ elif interval == "year" then ($line / 12 / $ic)+ elif interval == "week" then ($line * 52 / 12 / $ic)+ elif interval == "day" then ($line * 30 / $ic)+ else 0+ end;+ [+ .data[]?+ | .items.data[]? as $it+ | per_month(+ ($it.price.unit_amount // 0);+ ($it.quantity // 1);+ ($it.price.recurring.interval // "month");+ ($it.price.recurring.interval_count // 1)+ )+ ] | add // 0 | round+ ' 2>/dev/null || echo 0)"+ active_sub_count="$(printf '%s' "$subs_resp" | jq '[.data[]?] | length' 2>/dev/null || echo 0)"++ jq -nc \+ --arg p "$proj" \+ --argjson rev_cents "$revenue_cents" \+ --argjson cnt "$charge_count" \+ --argjson refunds "$refund_count" \+ --argjson mrr_cents "$active_mrr_cents" \+ --argjson sub_cnt "$active_sub_count" \+ --argjson utm "$by_utm" \+ --arg ccy "$currency" '+ {+ surface: "stripe",+ project: $p,+ revenue_7d: (($rev_cents / 100) * 100 | round / 100 | tostring),+ charge_count: $cnt,+ refund_count: $refunds,+ active_mrr: (($mrr_cents / 100) * 100 | round / 100 | tostring),+ active_sub_count: $sub_cnt,+ by_utm_source: $utm,+ window_days: 7,+ currency: $ccy+ }+ ' 2>/dev/null || printf 'null'+}++# ── stripe_revenue_all_projects ───────────────────────────────────────────────+stripe_revenue_all_projects() {+ local prefs; prefs="$(_stripe_prefs_path)"+ if [ ! -f "$prefs" ]; then+ printf '[]'+ return 0+ fi++ # Enumerate marketing.projects.* — include those with EITHER:+ # - marketing.projects.<p>.stripe.secret_key declared in prefs, OR+ # - any other entry under marketing.projects.<p>.* (fallback: try Doppler key lookup).+ local projects+ projects="$(jq -r '.marketing.projects // {} | keys[]?' "$prefs" 2>/dev/null || true)"++ local results=()+ local p out+ while IFS= read -r p; do+ [ -z "$p" ] && continue+ out="$(stripe_revenue_7d "$p" 2>/dev/null || printf 'null')"+ [ -z "$out" ] && out="null"+ if [ "$out" != "null" ]; then+ results+=("$out")+ fi+ done <<EOF+${projects}+EOF++ if [ ${#results[@]} -eq 0 ]; then+ printf '[]'+ return 0+ fi+ printf '%s\n' "${results[@]}" | jq -sc '.' 2>/dev/null || printf '[]'+}diff --git a/claude-ops/scripts/ops-cron-marketing-auth-prewarm.sh b/claude-ops/scripts/ops-cron-marketing-auth-prewarm.shnew file mode 100755index 00000000..bc37a5c9--- /dev/null+++ b/claude-ops/scripts/ops-cron-marketing-auth-prewarm.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+LOG_FILE="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs/marketing-auth-prewarm.log"+mkdir -p "$(dirname "$LOG_FILE")"+echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] starting marketing-auth-prewarm" >> "$LOG_FILE"+"$SCRIPT_DIR/ops-marketing-auth-prewarm.sh" 2>> "$LOG_FILE"+echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] finished marketing-auth-prewarm (exit $?)" >> "$LOG_FILE"diff --git a/claude-ops/scripts/ops-marketing-auth-prewarm.sh b/claude-ops/scripts/ops-marketing-auth-prewarm.shnew file mode 100755index 00000000..c6f53863--- /dev/null+++ b/claude-ops/scripts/ops-marketing-auth-prewarm.sh@@ -0,0 +1,260 @@+#!/usr/bin/env bash+set -euo pipefail++# ops-marketing-auth-prewarm.sh+# Scans all Doppler projects + env + keychain for marketing credentials+# and writes a structured cache for /ops:marketing setup auto-linking.+#+# Env:+# OPS_DATA_DIR - override cache dir (default: ~/.claude/plugins/data/ops-ops-marketplace)+# OPS_PREWARM_DRY_RUN - if set to 1, print output to stderr only (no file write)++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+OUTPUT_FILE="$DATA_DIR/marketing-auth-prewarm.json"+GENERATED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"++# ── category regex patterns ────────────────────────────────────────────────────+MARKETING_PATTERN='KLAVIYO|META_|FACEBOOK|INSTAGRAM|TIKTOK|LINKEDIN|REDDIT|BING|APPLOVIN|TWITTER|PINTEREST|SNAPCHAT|YOUTUBE|GOOGLE_ADS|GADS|GA4|MEASUREMENT_PROTOCOL|GSC|SEARCH_CONSOLE|AHREFS|APOLLO|RESEND|MAILCHIMP|SENDGRID|POSTMARK|MAILGUN|CUSTOMER_IO|CUSTOMERIO|BRAZE|ITERABLE|SHOPIFY|RECHARGE|SHIPBOB|SHIPSTATION|HUBSPOT|SEGMENT|MIXPANEL|AMPLITUDE|POSTHOG|APPSFLYER|ADJUST|BRANCH_IO|SINGULAR|TWILIO|MAILERLITE|CONVERTKIT|ACTIVECAMPAIGN|TYPEFORM|CALENDLY|SALESFORCE|PIPEDRIVE|INTERCOM|ZENDESK|RUDDERSTACK|PLAUSIBLE|UMAMI|FATHOM|TRIPLEWHALE|NORTHBEAM|DUB_API|STRIPE_|SENTRY_AUTH|LINEAR_API|VERCEL_TOKEN|CLOUDFLARE_API_TOKEN'++# ── classify key → category ───────────────────────────────────────────────────+classify_key() {+ local key="${1^^}" # uppercase+ case "$key" in+ *META_*|*FACEBOOK*|*INSTAGRAM*) echo "ads_meta" ;;+ *GOOGLE_ADS*|*GADS*|*GA4*|*MEASUREMENT_PROTOCOL*|*GSC*|*SEARCH_CONSOLE*|*YOUTUBE*) echo "analytics_ga4" ;;+ *TIKTOK*) echo "ads_tiktok" ;;+ *LINKEDIN*) echo "ads_linkedin" ;;+ *REDDIT*) echo "ads_reddit" ;;+ *PINTEREST*) echo "ads_pinterest" ;;+ *BING*|*MICROSOFT*) echo "ads_microsoft" ;;+ *APPLOVIN*|*SNAPCHAT*|*TWITTER*) echo "ads_other" ;;+ *SEGMENT*|*RUDDERSTACK*) echo "analytics_segment" ;;+ *MIXPANEL*) echo "analytics_mixpanel" ;;+ *AMPLITUDE*) echo "analytics_amplitude" ;;+ *POSTHOG*|*PLAUSIBLE*|*UMAMI*|*FATHOM*) echo "analytics_posthog" ;;+ *RESEND*) echo "email_resend" ;;+ *KLAVIYO*) echo "email_klaviyo" ;;+ *MAILCHIMP*) echo "email_mailchimp" ;;+ *SENDGRID*) echo "email_sendgrid" ;;+ *POSTMARK*) echo "email_postmark" ;;+ *MAILGUN*) echo "email_mailgun" ;;+ *CUSTOMER_IO*|*CUSTOMERIO*) echo "email_customerio" ;;+ *BRAZE*) echo "email_braze" ;;+ *ITERABLE*) echo "email_iterable" ;;+ *MAILERLITE*|*CONVERTKIT*|*ACTIVECAMPAIGN*) echo "email_other" ;;+ *TWILIO*) echo "sms_twilio" ;;+ *STRIPE_*) echo "payments_stripe" ;;+ *SHOPIFY*) echo "ecommerce_shopify" ;;+ *RECHARGE*) echo "ecommerce_recharge" ;;+ *SHIPBOB*) echo "fulfillment_shipbob" ;;+ *SHIPSTATION*) echo "fulfillment_shipstation" ;;+ *HUBSPOT*) echo "crm_hubspot" ;;+ *SALESFORCE*) echo "crm_salesforce" ;;+ *PIPEDRIVE*) echo "crm_pipedrive" ;;+ *INTERCOM*) echo "crm_intercom" ;;+ *ZENDESK*) echo "support_zendesk" ;;+ *APPSFLYER*) echo "mta_appsflyer" ;;+ *ADJUST*) echo "mta_adjust" ;;+ *BRANCH_IO*) echo "mta_branch" ;;+ *SINGULAR*) echo "mta_singular" ;;+ *SENTRY_AUTH*) echo "errors_sentry" ;;+ *LINEAR_API*) echo "issues_linear" ;;+ *CLOUDFLARE_API_TOKEN*) echo "infra_cloudflare" ;;+ *VERCEL_TOKEN*) echo "infra_vercel" ;;+ *AHREFS*) echo "seo_ahrefs" ;;+ *APOLLO*) echo "prospect_apollo" ;;+ *TYPEFORM*|*CALENDLY*) echo "tools_forms" ;;+ *TRIPLEWHALE*|*NORTHBEAM*|*DUB_API*) echo "analytics_attribution" ;;+ *) echo "_unmatched" ;;+ esac+}++# ── extract project hint from doppler project name + key name ─────────────────+extract_project_hint() {+ local doppler_project="$1"+ local key="$2"+ local key_lower="${key,,}"+ local proj_lower="${doppler_project,,}"++ # strip common suffixes/prefixes from doppler project name to get product hint+ # e.g. "my-project-api" → "my-project", "claude-ops" → "claude-ops"+ local base_project+ base_project=$(echo "$proj_lower" | sed 's/-api$//' | sed 's/-backend$//' | sed 's/-frontend$//' | sed 's/-web$//' | sed 's/-app$//')++ # look for product name embedded in the key itself+ # e.g. META_MY-PROJECT_ACCESS_TOKEN → my-project+ local known_products=("my-project" "alwaysbright" "example-project" "inboxassist" "fiberinternet" "shannon" "talktoyourhouse" "claude-ops" "claudeops")+ for prod in "${known_products[@]}"; do+ local prod_stripped="${prod//-/}"+ if echo "$key_lower" | grep -qi "$prod_stripped"; then+ echo "$prod_stripped"+ return+ fi+ done++ # fall back to base doppler project name+ echo "$base_project"+}++# ── accumulate entries into a temp JSON lines file ────────────────────────────+TMP_ENTRIES="$(mktemp)"+trap 'rm -f "$TMP_ENTRIES"' EXIT++append_entry() {+ local source="$1"+ local doppler_project="$2"+ local config="$3"+ local key="$4"+ local category+ local project_hint+ category=$(classify_key "$key")+ project_hint=$(extract_project_hint "$doppler_project" "$key")+ printf '%s\n' "{\"source\":\"$source\",\"doppler_project\":\"$doppler_project\",\"config\":\"$config\",\"key\":\"$key\",\"category\":\"$category\",\"project\":\"$project_hint\"}" >> "$TMP_ENTRIES"+}++# ── 1. Doppler scan ───────────────────────────────────────────────────────────+DOPPLER_PROJECTS_SCANNED=0++if command -v doppler &>/dev/null; then+ projects_json=$(doppler projects --json 2>/dev/null || echo "[]")+ mapfile -t project_slugs < <(echo "$projects_json" | jq -r '.[].id // .[].slug' 2>/dev/null || true)++ DOPPLER_PROJECTS_SCANNED="${#project_slugs[@]}"++ for slug in "${project_slugs[@]}"; do+ echo "[prewarm] scanning doppler: $slug" >&2+ secrets_json=$(doppler secrets --project "$slug" --config prd --json 2>/dev/null || true)+ if [[ -z "$secrets_json" || "$secrets_json" == "null" ]]; then+ continue+ fi+ # extract key names that match the pattern+ while IFS= read -r key; do+ [[ -z "$key" ]] && continue+ append_entry "doppler" "$slug" "prd" "$key"+ done < <(echo "$secrets_json" | jq -r 'keys[]' 2>/dev/null | grep -iE "$MARKETING_PATTERN" || true)+ done+else+ echo "[prewarm] doppler CLI not found — skipping Doppler scan" >&2+fi++# ── 2. Environment variables scan ────────────────────────────────────────────+echo "[prewarm] scanning environment variables" >&2+while IFS= read -r line; do+ key="${line%%=*}"+ [[ -z "$key" ]] && continue+ append_entry "env" "_env" "" "$key"+done < <(printenv | grep -iE "^[A-Z_]*($MARKETING_PATTERN)[A-Z_0-9]*=" || true)++# ── 3. Shell profiles scan ────────────────────────────────────────────────────+echo "[prewarm] scanning shell profiles" >&2+profile_files=("$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.zprofile" "$HOME/.envrc")+for profile in "${profile_files[@]}"; do+ [[ -f "$profile" ]] || continue+ while IFS= read -r line; do+ # match export KEY=... or KEY=...+ if [[ "$line" =~ ^[[:space:]]*(export[[:space:]]+)?([A-Z_][A-Z0-9_]*)= ]]; then+ key="${BASH_REMATCH[2]}"+ if echo "$key" | grep -qiE "$MARKETING_PATTERN"; then+ append_entry "profile" "$(basename "$profile")" "" "$key"+ fi+ fi+ done < "$profile"+done++# ── 4. macOS Keychain scan ────────────────────────────────────────────────────+if command -v security &>/dev/null && [[ "$(uname -s)" == "Darwin" ]]; then+ echo "[prewarm] scanning keychain" >&2+ # known marketing tool service names in keychain+ keychain_services=(+ "klaviyo" "meta" "facebook" "tiktok" "linkedin" "google-ads"+ "shopify" "stripe" "hubspot" "salesforce" "segment" "mixpanel"+ "amplitude" "twilio" "sendgrid" "mailchimp" "resend" "postmark"+ "intercom" "zendesk" "appsflyer" "adjust" "branch.io" "sentry"+ "linear" "vercel" "cloudflare" "ahrefs" "apollo"+ )+ for svc in "${keychain_services[@]}"; do+ result=$(security find-generic-password -s "$svc" 2>/dev/null || true)+ if [[ -n "$result" ]]; then+ # derive a synthetic key name from service+ synthetic_key="${svc^^}"+ synthetic_key="${synthetic_key//-/_}"+ synthetic_key="${synthetic_key//./_}"+ synthetic_key="${synthetic_key}_TOKEN"+ append_entry "keychain" "_keychain" "" "$synthetic_key"+ fi+ done+fi++# ── 5. GCP service account / OAuth JSON scan ──────────────────────────────────+if [[ -d "$HOME/.gcp" ]]; then+ echo "[prewarm] scanning ~/.gcp/*.json" >&2+ while IFS= read -r gcp_file; do+ file_type=$(jq -r '.type // "unknown"' "$gcp_file" 2>/dev/null || echo "unknown")+ project_id=$(jq -r '.project_id // .client_id // "unknown"' "$gcp_file" 2>/dev/null || echo "unknown")+ key="GCP_${file_type^^}_${project_id^^}"+ key="${key// /_}"+ key="${key//-/_}"+ if echo "$key" | grep -qiE "OAUTH|SERVICE_ACCOUNT|GA4|GOOGLE"; then+ append_entry "gcp_json" "$(basename "$gcp_file")" "" "GCP_OAUTH_CLIENT"+ fi+ done < <(find "$HOME/.gcp" -name "*.json" -maxdepth 3 2>/dev/null || true)+fi++# ── build output JSON ─────────────────────────────────────────────────────────+echo "[prewarm] building output JSON" >&2++# read all entries (newline-delimited JSON objects) and build by_project + by_category+# wrap the NDJSON into a JSON array first, then process+output_json=$(+ (echo '['; sed '$!s/$/,/' "$TMP_ENTRIES"; echo ']') 2>/dev/null \+ | jq --arg gen "$GENERATED_AT" --argjson scanned "$DOPPLER_PROJECTS_SCANNED" '+ . as $all |++ # by_project: {project: {category: [{source,doppler_project,config,key}]}}+ (+ $all | group_by(.project) |+ [.[] | {+ key: .[0].project,+ value: (+ group_by(.category) |+ [.[] | {+ key: .[0].category,+ value: [.[] | {source, doppler_project, config, key}]+ }] | from_entries+ )+ }] | from_entries+ ) as $by_project |++ # by_category: {category: {project: count}}+ (+ $all | group_by(.category) |+ [.[] | {+ key: .[0].category,+ value: (+ group_by(.project) |+ [.[] | {key: .[0].project, value: length}] | from_entries+ )+ }] | from_entries+ ) as $by_category |++ {+ generated_at: $gen,+ doppler_projects_scanned: $scanned,+ by_project: $by_project,+ by_category: $by_category+ }+ ' 2>/dev/null \+ || echo '{"error":"jq build failed","generated_at":"'"$GENERATED_AT"'","doppler_projects_scanned":'"$DOPPLER_PROJECTS_SCANNED"',"by_project":{},"by_category":{}}'+)++# ── write or dry-run ──────────────────────────────────────────────────────────+if [[ "${OPS_PREWARM_DRY_RUN:-0}" == "1" ]]; then+ echo "[prewarm] DRY RUN — output:" >&2+ echo "$output_json" >&2+else+ mkdir -p "$DATA_DIR"+ echo "$output_json" > "$OUTPUT_FILE"+ echo "[prewarm] wrote $OUTPUT_FILE" >&2+ category_count=$(echo "$output_json" | jq '.by_category | length' 2>/dev/null || echo 0)+ echo "[prewarm] categories found: $category_count" >&2+fidiff --git a/claude-ops/skills/ops-marketing/SKILL.md b/claude-ops/skills/ops-marketing/SKILL.mdindex 3603b6bf..3cc37399 100644--- a/claude-ops/skills/ops-marketing/SKILL.md+++ b/claude-ops/skills/ops-marketing/SKILL.md@@ -381,6 +381,30 @@ Route `$ARGUMENTS` to the correct section below:| `autopilot kill <project>` | Set kill_switch for a project (see ## autopilot-kill section) || attribution | Unified attribution table (Meta + Google + Klaviyo + GA4) || setup | Configure API keys |+| `portfolio --live` | Live KPI rollup across all projects with non-zero spend or revenue |+| `portfolio --kpis` | Just the KPI section, no config-state table |+| `portfolio --prewarm-status` | Show what marketing creds exist in Doppler that aren't yet linked |++---++## Auto-link from prewarm cache++A background daemon (`marketing-auth-prewarm`, runs nightly at 04:23 UTC) scans every Doppler project + env + keychain + ~/.gcp for marketing credentials, classifies them into 20 categories (ads_meta, ads_google, analytics_ga4, payments_stripe, etc), and writes a cache at `$OPS_DATA_DIR/marketing-auth-prewarm.json`.++When setting up a new project, run:++```bash+ops-marketing-link-prewarm --project <name>+```++…and any auto-detectable creds get linked into `marketing.projects.<name>.<category>.*` as Doppler cred-refs in one shot. No per-credential prompts.++To see what would be linked without writing:++```bash+ops-marketing-portfolio --prewarm-status+OPS_MARKETING_DRY_RUN=1 ops-marketing-link-prewarm --project <name>+```---diff --git a/claude-ops/tests/test-ad-spend-aggregator.sh b/claude-ops/tests/test-ad-spend-aggregator.shnew file mode 100755index 00000000..8bfb3969--- /dev/null+++ b/claude-ops/tests/test-ad-spend-aggregator.sh@@ -0,0 +1,105 @@+#!/usr/bin/env bash+# test-ad-spend-aggregator.sh — smoke tests for scripts/lib/ad-spend-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 ad_spend_* function returns 0 + echoes `null` for an unknown project+# - ad_spend_all returns a JSON object with empty surfaces array for an unknown project+# - double-source guard works+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+LIB="$PLUGIN_ROOT/scripts/lib/ad-spend-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 ad-spend-prefs.XXXXXX.json)"+echo '{"marketing":{"projects":{}}}' > "$TMP_PREFS"+trap 'rm -f "$TMP_PREFS"' EXIT++out="$(+ set +u+ export OPS_AUTOPILOT_PREFS="$TMP_PREFS"+ export OPS_DATA_DIR="$(dirname "$TMP_PREFS")"+ # shellcheck disable=SC1090+ . "$LIB"++ for fn in ad_spend_meta ad_spend_google ad_spend_tiktok ad_spend_linkedin ad_spend_reddit ad_spend_microsoft ad_spend_pinterest; do+ r="$($fn nonexistent-project 2>/dev/null)"+ rc=$?+ echo "${fn}_rc=${rc}"+ echo "${fn}_out=${r}"+ done++ r_all="$(ad_spend_all nonexistent-project 2>/dev/null)"+ rc=$?+ echo "all_rc=${rc}"+ echo "all_out=${r_all}"+)"++for fn in ad_spend_meta ad_spend_google ad_spend_tiktok ad_spend_linkedin ad_spend_reddit ad_spend_microsoft ad_spend_pinterest; 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 "ad_spend_all returns rc=0" \+ || err "ad_spend_all rc" "got: $(echo "$out" | grep '^all_rc=')"++# ad_spend_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"' >/dev/null 2>&1; then+ ok "ad_spend_all emits JSON with .surfaces array"+else+ err "ad_spend_all shape" "got: $all_json"+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-sourcing is idempotent" \+ || err "double-source" "guard failed"++# ── Optional live smoke test ──+if [ "${AD_SPEND_LIVE_SMOKE:-0}" = "1" ] && [ -n "${AD_SPEND_LIVE_PROJECT:-}" ]; then+ echo ""+ echo " Running live smoke test for project: ${AD_SPEND_LIVE_PROJECT}"+ live="$(+ set +u+ # shellcheck disable=SC1090+ . "$LIB"+ ad_spend_all "$AD_SPEND_LIVE_PROJECT"+ )"+ if printf '%s' "$live" | jq -e '.total_spend_7d | test("^[0-9]+\\.[0-9]{2}$")' >/dev/null 2>&1; then+ ok "live ad_spend_all returns total_spend_7d as numeric string"+ else+ err "live smoke" "got: $live"+ fi+fi++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+(( fail == 0 )) || { echo "ACTION: fix failing tests above."; exit 1; }+exit 0diff --git a/claude-ops/tests/test-marketing-kpis.sh b/claude-ops/tests/test-marketing-kpis.shnew file mode 100755index 00000000..99e43272--- /dev/null+++ b/claude-ops/tests/test-marketing-kpis.sh@@ -0,0 +1,171 @@+#!/usr/bin/env bash+# tests/test-marketing-kpis.sh — Hermetic KPI engine tests (no API calls)+set -uo pipefail++REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++# Source libraries+. "${REPO_ROOT}/scripts/lib/ga4-resolve.sh"+. "${REPO_ROOT}/scripts/lib/marketing-kpis.sh"++echo "test-marketing-kpis.sh"+echo ""++# ---------------------------------------------------------------------------+# kpi_roas+# ---------------------------------------------------------------------------+echo "kpi_roas:"+r="$(kpi_roas 100 300)"+[ "$r" = "3.00" ] && ok "roas 300/100 = 3.00" || err "roas 300/100: expected 3.00, got $r"++r="$(kpi_roas 0 0)"+[ -z "$r" ] && ok "roas 0/0 = empty" || err "roas 0/0: expected empty, got '$r'"++r="$(kpi_roas 50 0)"+[ "$r" = "0.00" ] && ok "roas 0 revenue = 0.00" || err "roas 0 revenue: expected 0.00, got $r"++# ---------------------------------------------------------------------------+# kpi_cac+# ---------------------------------------------------------------------------+echo "kpi_cac:"+r="$(kpi_cac 300 3)"+[ "$r" = "100.00" ] && ok "cac 300/3 = 100.00" || err "cac 300/3: expected 100.00, got $r"++r="$(kpi_cac 300 0)"+[ "$r" = "—" ] && ok "cac div/0 = —" || err "cac div/0: expected —, got $r"++# ---------------------------------------------------------------------------+# kpi_ltv+# ---------------------------------------------------------------------------+echo "kpi_ltv:"+# AOV=50, RPR=0.3, GM=0.75 → 50 * (1/0.7) * 0.75 = 53.57+r="$(kpi_ltv 50 0.3 0.75)"+expected="53.57"+[ "$r" = "$expected" ] && ok "ltv 50/0.3/0.75 = $expected" || err "ltv: expected $expected, got $r"++r="$(kpi_ltv 0 0.3 0.75)"+[ "$r" = "—" ] && ok "ltv aov=0 = —" || err "ltv aov=0: expected —, got $r"++r="$(kpi_ltv 50 1 0.75)"+[ "$r" = "—" ] && ok "ltv rpr>=1 = —" || err "ltv rpr>=1: expected —, got $r"++r="$(kpi_ltv 50 0.3 0)"+[ "$r" = "—" ] && ok "ltv gm=0 = —" || err "ltv gm=0: expected —, got $r"++# ---------------------------------------------------------------------------+# kpi_payback_months+# ---------------------------------------------------------------------------+echo "kpi_payback_months:"+r="$(kpi_payback_months 100 25)"+[ "$r" = "4.00" ] && ok "payback 100/25 = 4.00" || err "payback 100/25: expected 4.00, got $r"++r="$(kpi_payback_months 100 0)"+[ "$r" = "—" ] && ok "payback div/0 = —" || err "payback div/0: expected —, got $r"++# ---------------------------------------------------------------------------+# kpi_cvr+# ---------------------------------------------------------------------------+echo "kpi_cvr:"+r="$(kpi_cvr 2 420)"+expected="0.48"+[ "$r" = "$expected" ] && ok "cvr 2/420 = $expected" || err "cvr 2/420: expected $expected, got $r"++r="$(kpi_cvr 10 500)"+[ "$r" = "2.00" ] && ok "cvr 10/500 = 2.00" || err "cvr 10/500: expected 2.00, got $r"++r="$(kpi_cvr 5 0)"+[ "$r" = "—" ] && ok "cvr div/0 = —" || err "cvr div/0: expected —, got $r"++# ---------------------------------------------------------------------------+# kpi_ctr+# ---------------------------------------------------------------------------+echo "kpi_ctr:"+r="$(kpi_ctr 110 2353)"+# 110/2353 * 100 = 4.674... → 4.67+expected="4.67"+[ "$r" = "$expected" ] && ok "ctr 110/2353 = $expected" || err "ctr 110/2353: expected $expected, got $r"++r="$(kpi_ctr 0 0)"+[ "$r" = "—" ] && ok "ctr div/0 = —" || err "ctr div/0: expected —, got $r"++# ---------------------------------------------------------------------------+# kpi_health_score+# ---------------------------------------------------------------------------+echo "kpi_health_score:"++# Healthy: ROAS>=3 (+30), CVR>=2% (+20), crash>=0.99 (+20), profitable (+20), active (+10) = 100+h="$(kpi_health_score '{"roas":4.0,"cvr":3.0,"crash_free_rate":0.995,"ad_spend":100,"revenue":500}')"+score="$(echo "$h" | jq -r '.score')"+label="$(echo "$h" | jq -r '.label')"+[ "$score" = "100" ] && ok "health Healthy score=100" || err "health Healthy: expected 100, got $score"+[ "$label" = "Healthy" ] && ok "health Healthy label" || err "health Healthy label: expected Healthy, got $label"++# Warning: ROAS=2 (+15), CVR=1.5 (+10), crash=0.97 (+10), not profitable (0), active (+10) = 45+h="$(kpi_health_score '{"roas":2.0,"cvr":1.5,"crash_free_rate":0.97,"ad_spend":100,"revenue":80}')"+score="$(echo "$h" | jq -r '.score')"+label="$(echo "$h" | jq -r '.label')"+[ "$score" -ge 40 ] && [ "$score" -lt 70 ] && ok "health Warning score in [40,70)" || err "health Warning: score $score not in [40,70)"+[ "$label" = "Warning" ] && ok "health Warning label" || err "health Warning label: expected Warning, got $label"++# Critical: ROAS=0 (0), CVR=0 (0), crash=0.88 (-20), not profitable (0), no spend (0) = 0 (floored)+h="$(kpi_health_score '{"roas":0,"cvr":0,"crash_free_rate":0.88,"ad_spend":0,"revenue":0}')"+score="$(echo "$h" | jq -r '.score')"+label="$(echo "$h" | jq -r '.label')"+[ "$score" -lt 40 ] && ok "health Critical score<40 ($score)" || err "health Critical: score $score not <40"+[ "$label" = "Critical" ] && ok "health Critical label" || err "health Critical label: expected Critical, got $label"++# Crash penalty only: ROAS=0 (0), CVR=0 (0), crash=0.89 (-20) → floored 0+h="$(kpi_health_score '{"roas":0,"cvr":0,"crash_free_rate":0.89,"ad_spend":0,"revenue":0}')"+score="$(echo "$h" | jq -r '.score')"+[ "$score" = "0" ] && ok "health crash penalty floored at 0" || err "health crash floor: expected 0, got $score"++# ---------------------------------------------------------------------------+# kpi_compute_all+# ---------------------------------------------------------------------------+echo "kpi_compute_all:"+sample='{"project":"my-project","spend":92.68,"revenue":150.50,"impressions":2353,"clicks":110,"conversions":2,"sessions":420,"mrr":2500,"new_customers":3,"crash_free_rate":0.99,"aov":50.17,"repeat_purchase_rate":0.30,"gross_margin":0.75}'++out="$(kpi_compute_all "$sample")"++# Check all KPI fields present+for field in roas cac ltv payback_months cvr_pct ctr_pct health_score health_label; do+ if echo "$out" | jq -e "has(\"$field\")" >/dev/null 2>&1; then+ ok "compute_all has field: $field"+ else+ err "compute_all missing field: $field"+ fi+done++# Check ROAS = 150.50 / 92.68 ≈ 1.62+roas_out="$(echo "$out" | jq -r '.roas')"+[ "$roas_out" = "1.62" ] && ok "compute_all roas=1.62" || err "compute_all roas: expected 1.62, got $roas_out"++# Check CAC = 92.68 / 3 ≈ 30.89+cac_out="$(echo "$out" | jq -r '.cac')"+[ "$cac_out" = "30.89" ] && ok "compute_all cac=30.89" || err "compute_all cac: expected 30.89, got $cac_out"++# Check CVR = (2/420)*100 ≈ 0.48+cvr_out="$(echo "$out" | jq -r '.cvr_pct')"+[ "$cvr_out" = "0.48" ] && ok "compute_all cvr=0.48" || err "compute_all cvr: expected 0.48, got $cvr_out"++# Check health_label is a string+hl="$(echo "$out" | jq -r '.health_label')"+[ -n "$hl" ] && [ "$hl" != "null" ] && ok "compute_all health_label present: $hl" || err "compute_all health_label missing"++# Check original fields preserved+proj="$(echo "$out" | jq -r '.project')"+[ "$proj" = "my-project" ] && ok "compute_all preserves original fields" || err "compute_all: project field lost, got $proj"++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++[ "$fail" -gt 0 ] && exit 1+exit 0diff --git a/claude-ops/tests/test-ops-marketing-auth-prewarm.sh b/claude-ops/tests/test-ops-marketing-auth-prewarm.shnew file mode 100755index 00000000..f58515b9--- /dev/null+++ b/claude-ops/tests/test-ops-marketing-auth-prewarm.sh@@ -0,0 +1,46 @@+#!/usr/bin/env bash+set -euo pipefail++# test-ops-marketing-auth-prewarm.sh+# Requires: doppler CLI, jq++command -v doppler &>/dev/null || { echo "SKIP: doppler not installed"; exit 0; }+command -v jq &>/dev/null || { echo "SKIP: jq not installed"; exit 0; }++SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"+TMP_DIR="$(mktemp -d)"+trap 'rm -rf "$TMP_DIR"' EXIT++echo "[test] running prewarm with OPS_DATA_DIR=$TMP_DIR"+OPS_DATA_DIR="$TMP_DIR" bash "$SCRIPT_DIR/scripts/ops-marketing-auth-prewarm.sh"++OUTPUT="$TMP_DIR/marketing-auth-prewarm.json"++if [[ ! -f "$OUTPUT" ]]; then+ echo "FAIL: output file not created at $OUTPUT"+ exit 1+fi++# validate JSON+if ! jq empty "$OUTPUT" 2>/dev/null; then+ echo "FAIL: output is not valid JSON"+ exit 1+fi++# check required top-level keys+for key in by_project by_category generated_at doppler_projects_scanned; do+ if ! jq -e "has(\"$key\")" "$OUTPUT" &>/dev/null; then+ echo "FAIL: missing top-level key: $key"+ exit 1+ fi+done++# verify at least one category was populated for at least one project+category_count=$(jq '.by_category | length' "$OUTPUT")+if [[ "$category_count" -lt 1 ]]; then+ echo "FAIL: by_category is empty — no marketing creds found in any source"+ exit 1+fi++echo "PASS: output valid, $category_count categories found"+exit 0diff --git a/claude-ops/tests/test-ops-marketing-link-prewarm.sh b/claude-ops/tests/test-ops-marketing-link-prewarm.shnew file mode 100755index 00000000..245acfba--- /dev/null+++ b/claude-ops/tests/test-ops-marketing-link-prewarm.sh@@ -0,0 +1,217 @@+#!/usr/bin/env bash+# tests/test-ops-marketing-link-prewarm.sh — hermetic tests for ops-marketing-link-prewarm+#+# PUBLIC REPO: no real project names, tokens, or paths.++set -uo pipefail++REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+BIN="${REPO_ROOT}/bin/ops-marketing-link-prewarm"++PASS=0+FAIL=0++_pass() { echo " PASS: $1"; (( PASS++ )) || true; }+_fail() { echo " FAIL: $1"; (( FAIL++ )) || true; }++# ── test setup ────────────────────────────────────────────────────────────────+TMPDIR_TEST="$(mktemp -d)"+trap 'rm -rf "$TMPDIR_TEST"' EXIT++FAKE_CACHE="${TMPDIR_TEST}/marketing-auth-prewarm.json"+FAKE_PREFS="${TMPDIR_TEST}/preferences.json"++# Minimal prewarm cache with test-fixture project+cat > "$FAKE_CACHE" <<'EOF'+{+ "generated_at": "2026-01-01T04:23:00Z",+ "by_project": {+ "test-fixture": {+ "analytics_ga4": [+ {"key": "property_id", "project": "test-fixture", "config": "prd"}+ ],+ "payments_stripe": [+ {"key": "secret_key", "project": "test-fixture", "config": "prd"}+ ],+ "analytics_amplitude": [+ {"key": "api_key", "project": "test-fixture", "config": "prd"}+ ],+ "ads_meta": [+ {"key": "access_token", "project": "test-fixture", "config": "prd"},+ {"key": "ad_account_id", "project": "test-fixture", "config": "prd"}+ ]+ }+ }+}+EOF++# Minimal prefs with empty marketing section+cat > "$FAKE_PREFS" <<'EOF'+{+ "marketing": {+ "projects": {}+ }+}+EOF++# ── test 1: dry-run prints planned writes, does NOT modify prefs ──────────────+echo "test 1: dry-run does not modify prefs"+prefs_before="$(cat "$FAKE_PREFS")"+out="$(OPS_DATA_DIR="$TMPDIR_TEST" PREFS_PATH="$FAKE_PREFS" OPS_MARKETING_DRY_RUN=1 \+ "$BIN" --project test-fixture 2>&1)"+prefs_after="$(cat "$FAKE_PREFS")"++if echo "$out" | grep -q "\[would set\]"; then+ _pass "dry-run output contains [would set] lines"+else+ _fail "dry-run output missing [would set] lines (got: $out)"+fi++if [[ "$prefs_before" == "$prefs_after" ]]; then+ _pass "dry-run did not modify preferences.json"+else+ _fail "dry-run modified preferences.json"+fi++if echo "$out" | grep -q "test-fixture.ga4.property_id"; then+ _pass "dry-run shows ga4.property_id mapping"+else+ _fail "dry-run missing ga4.property_id mapping (got: $out)"+fi++if echo "$out" | grep -q "test-fixture.stripe.secret_key"; then+ _pass "dry-run shows stripe.secret_key mapping"+else+ _fail "dry-run missing stripe.secret_key mapping (got: $out)"+fi++# ── test 2: --dry-run flag equivalent to env var ─────────────────────────────+echo "test 2: --dry-run flag"+out2="$(OPS_DATA_DIR="$TMPDIR_TEST" PREFS_PATH="$FAKE_PREFS" \+ "$BIN" --project test-fixture --dry-run 2>&1)"+if echo "$out2" | grep -q "\[would set\]"; then+ _pass "--dry-run flag produces [would set] output"+else+ _fail "--dry-run flag did not produce [would set] output (got: $out2)"+fi++# ── test 3: live run writes prefs atomically ──────────────────────────────────+echo "test 3: live run writes prefs"+OPS_DATA_DIR="$TMPDIR_TEST" PREFS_PATH="$FAKE_PREFS" \+ "$BIN" --project test-fixture > /dev/null 2>&1++ga4_val="$(jq -r '.marketing.projects["test-fixture"].ga4.property_id // "null"' "$FAKE_PREFS" 2>/dev/null)"+stripe_val="$(jq -r '.marketing.projects["test-fixture"].stripe.secret_key // "null"' "$FAKE_PREFS" 2>/dev/null)"+amplitude_val="$(jq -r '.marketing.projects["test-fixture"].amplitude.api_key // "null"' "$FAKE_PREFS" 2>/dev/null)"+meta_val="$(jq -r '.marketing.projects["test-fixture"].meta.access_token // "null"' "$FAKE_PREFS" 2>/dev/null)"++if [[ "$ga4_val" == "doppler:test-fixture/prd/property_id" ]]; then+ _pass "ga4.property_id written as doppler cred-ref"+else+ _fail "ga4.property_id wrong value: ${ga4_val}"+fi++if [[ "$stripe_val" == "doppler:test-fixture/prd/secret_key" ]]; then+ _pass "stripe.secret_key written as doppler cred-ref"+else+ _fail "stripe.secret_key wrong value: ${stripe_val}"+fi++if [[ "$amplitude_val" == "doppler:test-fixture/prd/api_key" ]]; then+ _pass "amplitude.api_key written as doppler cred-ref"+else+ _fail "amplitude.api_key wrong value: ${amplitude_val}"+fi++if [[ "$meta_val" == "doppler:test-fixture/prd/access_token" ]]; then+ _pass "meta.access_token written as doppler cred-ref"+else+ _fail "meta.access_token wrong value: ${meta_val}"+fi++# ── test 4: idempotency — re-run is a no-op ───────────────────────────────────+echo "test 4: idempotency"+prefs_after_first="$(cat "$FAKE_PREFS")"+OPS_DATA_DIR="$TMPDIR_TEST" PREFS_PATH="$FAKE_PREFS" \+ "$BIN" --project test-fixture > /dev/null 2>&1+prefs_after_second="$(cat "$FAKE_PREFS")"++if [[ "$prefs_after_first" == "$prefs_after_second" ]]; then+ _pass "second run is a no-op (idempotent)"+else+ _fail "second run modified prefs (not idempotent)"+fi++# ── test 5: --category filter only links requested category ──────────────────+echo "test 5: --category filter"+# Reset prefs+cat > "$FAKE_PREFS" <<'EOF'+{"marketing":{"projects":{}}}+EOF+OPS_DATA_DIR="$TMPDIR_TEST" PREFS_PATH="$FAKE_PREFS" \+ "$BIN" --project test-fixture --category analytics_ga4 > /dev/null 2>&1++ga4_after="$(jq -r '.marketing.projects["test-fixture"].ga4.property_id // "null"' "$FAKE_PREFS" 2>/dev/null)"+stripe_after="$(jq -r '.marketing.projects["test-fixture"].stripe.secret_key // "null"' "$FAKE_PREFS" 2>/dev/null)"++if [[ "$ga4_after" != "null" ]]; then+ _pass "--category analytics_ga4 writes ga4 slot"+else+ _fail "--category analytics_ga4 did not write ga4 slot"+fi++if [[ "$stripe_after" == "null" ]]; then+ _pass "--category analytics_ga4 skips stripe slot"+else+ _fail "--category analytics_ga4 incorrectly wrote stripe slot"+fi++# ── test 6: missing cache exits with error ────────────────────────────────────+echo "test 6: missing cache exits non-zero"+if ! OPS_DATA_DIR="/nonexistent_dir_$$" PREFS_PATH="$FAKE_PREFS" \+ "$BIN" --project test-fixture > /dev/null 2>&1; then+ _pass "missing cache exits non-zero"+else+ _fail "missing cache should have exited non-zero"+fi++# ── test 7: --all-projects links all prewarm projects ────────────────────────+echo "test 7: --all-projects"+# Add a second project to prewarm cache+jq '.by_project["second-fixture"] = {+ "payments_stripe": [{"key": "secret_key", "project": "second-fixture", "config": "prd"}]+}' "$FAKE_CACHE" > "${FAKE_CACHE}.tmp" && mv "${FAKE_CACHE}.tmp" "$FAKE_CACHE"++cat > "$FAKE_PREFS" <<'EOF'+{"marketing":{"projects":{}}}+EOF++OPS_DATA_DIR="$TMPDIR_TEST" PREFS_PATH="$FAKE_PREFS" \+ "$BIN" --all-projects > /dev/null 2>&1++second_stripe="$(jq -r '.marketing.projects["second-fixture"].stripe.secret_key // "null"' "$FAKE_PREFS" 2>/dev/null)"+if [[ "$second_stripe" == "doppler:second-fixture/prd/secret_key" ]]; then+ _pass "--all-projects links second project"+else+ _fail "--all-projects did not link second project: ${second_stripe}"+fi++# ── test 8: skip if lib files missing (graceful) ─────────────────────────────+echo "test 8: graceful if lib deps not present (portfolio --prewarm-status)"+PORTFOLIO="${REPO_ROOT}/bin/ops-marketing-portfolio"+if [[ -f "$PORTFOLIO" ]]; then+ out="$(OPS_DATA_DIR="$TMPDIR_TEST" PREFS_PATH="$FAKE_PREFS" \+ "$PORTFOLIO" --prewarm-status 2>&1)"+ if [[ $? -eq 0 ]]; then+ _pass "portfolio --prewarm-status exits 0 with fake cache"+ else+ _fail "portfolio --prewarm-status exited non-zero"+ fi+else+ echo " SKIP: ops-marketing-portfolio not found (other agent in-flight)"+fi++# ── summary ───────────────────────────────────────────────────────────────────+echo ""+echo "Results: ${PASS} passed, ${FAIL} failed"+[[ $FAIL -eq 0 ]]diff --git a/claude-ops/tests/test-ops-marketing-provision.sh b/claude-ops/tests/test-ops-marketing-provision.shindex bca28ee5..7c8b0c66 100755--- a/claude-ops/tests/test-ops-marketing-provision.sh+++ b/claude-ops/tests/test-ops-marketing-provision.sh@@ -257,12 +257,18 @@ unset FAKE_META_TOKEN# ---------------------------------------------------------------------------# 13. provision-google-ads dry-run writes pending state file+# Hermetic: point Doppler at a non-existent project so the scan returns empty+# even when GOOGLE_ADS_DEVELOPER_TOKEN exists in the real Doppler config.# ---------------------------------------------------------------------------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)"+# Also unset env vars that gads_scan_credential reads to avoid leaks from CI/local shell+gads_out="$(env -u GOOGLE_ADS_DEVELOPER_TOKEN -u GOOGLE_ADS_CLIENT_ID -u GOOGLE_ADS_CLIENT_SECRET -u GOOGLE_ADS_REFRESH_TOKEN \+ OPS_MARKETING_DOPPLER_PROJECT="nonexistent-fixture-$RANDOM" \+ OPS_MARKETING_DOPPLER_CONFIG="prd" \+ "$BIN" provision-google-ads --project acme 2>&1 || true)"if [ -f "$PENDING_FILE" ] && jq -e '.stage == "developer_token"' "$PENDING_FILE" >/dev/null 2>&1; thenok "provision-google-ads writes pending-state file with stage=developer_token"elsediff --git a/claude-ops/tests/test-sentry-crash.sh b/claude-ops/tests/test-sentry-crash.shnew file mode 100755index 00000000..2c3b081d--- /dev/null+++ b/claude-ops/tests/test-sentry-crash.sh@@ -0,0 +1,98 @@+#!/usr/bin/env bash+# tests/test-sentry-crash.sh — Sentry crash correlation lib tests+set -uo pipefail++REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++echo "test-sentry-crash.sh"+echo ""++# Skip if no token available+tok="${SENTRY_AUTH_TOKEN:-}"+if [ -z "$tok" ]; then+ tok="$(doppler secrets get SENTRY_AUTH_TOKEN --project claude-ops --config prd --plain 2>/dev/null || true)"+fi+if [ -z "$tok" ]; then+ echo " SKIP: SENTRY_AUTH_TOKEN not available — skipping live tests"+ echo ""+ echo "Results: 0 passed, 0 failed (skipped)"+ exit 0+fi++# Source the library+. "${REPO_ROOT}/scripts/lib/ga4-resolve.sh"+. "${REPO_ROOT}/scripts/lib/sentry-crash.sh"++# ── Test 1: nonexistent project returns null ──────────────────────────────+result="$(sentry_crash_rate "xnonexistent-project-zz9999")"+if [ "$result" = "null" ]; then+ ok "nonexistent project returns null"+else+ err "nonexistent project: expected null, got: $result"+fi++# ── Test 2: empty project returns null ───────────────────────────────────+result2="$(sentry_crash_rate "")"+if [ "$result2" = "null" ]; then+ ok "empty project returns null"+else+ err "empty project: expected null, got: $result2"+fi++# ── Test 3: real project returns valid JSON structure ────────────────────+# Use the SENTRY_TEST_PROJECT env var or default to "my-project" (public-safe)+test_project="${SENTRY_TEST_PROJECT:-}"+if [ -n "$test_project" ]; then+ result3="$(sentry_crash_rate "$test_project")"+ if echo "$result3" | jq -e '.crash_free_7d | type == "number"' >/dev/null 2>&1; then+ ok "live project returns JSON with numeric crash_free_7d"+ # Validate all expected fields present+ for field in surface project sentry_projects crash_free_7d crash_free_24h delta_dod at_risk; do+ if echo "$result3" | jq -e "has(\"$field\")" >/dev/null 2>&1; then+ ok "field present: $field"+ else+ err "field missing: $field"+ fi+ done+ # at_risk is boolean+ at_risk_type="$(echo "$result3" | jq -r '.at_risk | type' 2>/dev/null || echo "unknown")"+ if [ "$at_risk_type" = "boolean" ]; then+ ok "at_risk is boolean"+ else+ err "at_risk type: expected boolean, got $at_risk_type"+ fi+ elif [ "$result3" = "null" ]; then+ ok "live project: no matching Sentry projects (null) — acceptable"+ else+ err "live project: unexpected result: $result3"+ fi+else+ echo " SKIP: SENTRY_TEST_PROJECT not set — skipping live project test"+fi++# ── Test 4: sentry_crash_all_projects returns array ──────────────────────+# Only runs if OPS_DATA_DIR is set with a valid preferences.json+if [ -n "${OPS_DATA_DIR:-}" ] && [ -f "${OPS_DATA_DIR}/preferences.json" ]; then+ result4="$(sentry_crash_all_projects)"+ if echo "$result4" | jq -e 'type == "array"' >/dev/null 2>&1; then+ ok "sentry_crash_all_projects returns array"+ else+ err "sentry_crash_all_projects: expected array, got: $result4"+ fi+else+ echo " SKIP: OPS_DATA_DIR/preferences.json not available — skipping all_projects test"+fi++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++[ "$fail" -gt 0 ] && exit 1+exit 0diff --git a/claude-ops/tests/test-stripe-revenue.sh b/claude-ops/tests/test-stripe-revenue.shnew file mode 100755index 00000000..b7f95cd9--- /dev/null+++ b/claude-ops/tests/test-stripe-revenue.sh@@ -0,0 +1,122 @@+#!/usr/bin/env bash+# test-stripe-revenue.sh — smoke tests for scripts/lib/stripe-revenue.sh+#+# Hermetic by default: uses an isolated empty prefs file + a project key that is not configured.+# Asserts:+# - lib sources without crashing+# - stripe_revenue_7d returns `null` and rc=0 for an unknown project+# - stripe_revenue_all_projects returns "[]" when no project has stripe config+# - double-source guard works+# Live smoke (opt-in): set STRIPE_LIVE_SMOKE=1 and STRIPE_LIVE_PROJECT=<name>+# (with a corresponding STRIPE_<NAME>_SECRET_KEY or STRIPE_<NAME>_API_SECRET_KEY in env/Doppler).+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+LIB="$PLUGIN_ROOT/scripts/lib/stripe-revenue.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; }++TMP_PREFS="$(mktemp -t stripe-rev-prefs.XXXXXX.json)"+echo '{"marketing":{"projects":{}}}' > "$TMP_PREFS"+trap 'rm -f "$TMP_PREFS"' EXIT++out="$(+ set +u+ export OPS_AUTOPILOT_PREFS="$TMP_PREFS"+ export OPS_DATA_DIR="$(dirname "$TMP_PREFS")"+ # Ensure no Doppler key picks up stray env vars for nonexistent-project.+ unset STRIPE_NONEXISTENT_PROJECT_SECRET_KEY+ unset STRIPE_NONEXISTENT_PROJECT_API_SECRET_KEY+ # shellcheck disable=SC1090+ . "$LIB"++ r="$(stripe_revenue_7d nonexistent-project 2>/dev/null)"+ rc=$?+ echo "rev_rc=${rc}"+ echo "rev_out=${r}"++ r_all="$(stripe_revenue_all_projects 2>/dev/null)"+ rc=$?+ echo "all_rc=${rc}"+ echo "all_out=${r_all}"+)"++echo "$out" | grep -q '^rev_rc=0$' \+ && ok "stripe_revenue_7d returns rc=0 for unknown project" \+ || err "rev rc" "got: $(echo "$out" | grep '^rev_rc=')"++echo "$out" | grep -q '^rev_out=null$' \+ && ok "stripe_revenue_7d echoes 'null' for unknown project" \+ || err "rev out" "got: $(echo "$out" | grep '^rev_out=')"++echo "$out" | grep -q '^all_rc=0$' \+ && ok "stripe_revenue_all_projects returns rc=0" \+ || err "all rc" "got: $(echo "$out" | grep '^all_rc=')"++all_json="$(echo "$out" | sed -n 's/^all_out=//p')"+if printf '%s' "$all_json" | jq -e 'type == "array"' >/dev/null 2>&1; then+ ok "stripe_revenue_all_projects emits a JSON array"+else+ err "all shape" "got: $all_json"+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-sourcing is idempotent" \+ || err "double-source" "guard failed"++# ── Optional live smoke test ──+# Triggered if STRIPE_LIVE_SMOKE=1 + STRIPE_LIVE_PROJECT set, OR auto-detect a typical user-env var.+LIVE_PROJ="${STRIPE_LIVE_PROJECT:-}"+if [ -z "$LIVE_PROJ" ]; then+ # Try to autodetect from common env var patterns the user may have set.+ for v in $(env | awk -F= '/^STRIPE_[A-Z0-9_]+_(API_)?SECRET_KEY=/{print $1}' 2>/dev/null | head -1); do+ # STRIPE_MY-PROJECT_API_SECRET_KEY → MY-PROJECT_API → my-project-api+ candidate="${v#STRIPE_}"+ candidate="${candidate%_SECRET_KEY}"+ candidate="${candidate%_API}"+ candidate="$(printf '%s' "$candidate" | tr '[:upper:]_' '[:lower:]-')"+ if [ -n "$candidate" ] && [ "${STRIPE_LIVE_SMOKE:-0}" = "1" ]; then+ LIVE_PROJ="$candidate"+ break+ fi+ done+fi++if [ "${STRIPE_LIVE_SMOKE:-0}" = "1" ] && [ -n "$LIVE_PROJ" ]; then+ echo ""+ echo " Running live smoke test for project: ${LIVE_PROJ}"+ live="$(+ set +u+ # shellcheck disable=SC1090+ . "$LIB"+ stripe_revenue_7d "$LIVE_PROJ"+ )"+ if printf '%s' "$live" | jq -e '.revenue_7d | test("^[0-9]+\\.[0-9]{2}$")' >/dev/null 2>&1; then+ ok "live stripe_revenue_7d returns revenue_7d as numeric string"+ else+ err "live smoke" "got: $live"+ fi+fi++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+(( fail == 0 )) || { echo "ACTION: fix failing tests above."; exit 1; }+exit 0