Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

feat(ops:marketing): conversion senders (GA4 MP + Meta CAPI + Stripe bridge + UTM lib) (#257)

Aurora Capital41533b5f7665
diff --git a/claude-ops/bin/ops-conversion-send b/claude-ops/bin/ops-conversion-send
new file mode 100755
index 00000000..ebe74540
--- /dev/null
+++ b/claude-ops/bin/ops-conversion-send
@@ -0,0 +1,208 @@
+#!/usr/bin/env bash
+# ops-conversion-send — GA4 Measurement Protocol conversion event sender
+#
+# Sends conversion events to the GA4 Measurement Protocol (mp/collect).
+# Credentials resolved from preferences.json marketing.projects.<key>.ga4.*
+# or doppler: / env: refs — zero hardcoded values (Rule 0).
+#
+# Subcommands:
+# ga4 --project <key> --event <name> --client-id <cid>
+# [--value <v>] [--currency <c>] [--transaction-id <tx>]
+# [--user-id <uid>] [--properties <json>]
+#
+# Environment:
+# OPS_DRY_RUN=1 Print planned curl + payload, exit 0 without network call
+# OPS_CONVERSION_DEBUG=1 Validate via debug endpoint before live send
+#
+# Supported event names: purchase, sign_up, generate_lead, add_to_cart, (custom)
+#
+# Returns non-zero on non-204 from GA4 API.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PLUGIN_ROOT="${SCRIPT_DIR}/.."
+OPS_PLUGIN_ROOT_FALLBACK="$PLUGIN_ROOT" . "${PLUGIN_ROOT}/lib/registry-path.sh"
+
+PREFS="${OPS_CONVERSION_PREFS:-${OPS_DATA_DIR}/preferences.json}"
+LOG_DIR="${OPS_DATA_DIR}/logs"
+mkdir -p "$LOG_DIR"
+LOG="${LOG_DIR}/conversion-send.log"
+
+log() { printf '%s [ops-conversion-send] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG" >&2; }
+
+# ── Cred resolver: env:VAR | doppler:proj/cfg/SECRET | inline literal ────────
+resolve_cred() {
+ local ref="${1:-}"
+ { [ -z "$ref" ] || [ "$ref" = "null" ]; } && return 0
+ case "$ref" in
+ env:*)
+ local var="${ref#env:}"; printf '%s' "${!var:-}" ;;
+ doppler:*)
+ local path="${ref#doppler:}" proj rest cfg secret
+ proj="${path%%/*}"; rest="${path#*/}"; cfg="${rest%%/*}"; secret="${rest#*/}"
+ { [ -z "$proj" ] || [ -z "$cfg" ] || [ -z "$secret" ]; } && return 0
+ doppler secrets get "$secret" --project "$proj" --config "$cfg" --plain 2>/dev/null || true ;;
+ *) printf '%s' "$ref" ;;
+ esac
+}
+
+# ── Read a field from preferences.json marketing.projects.<key>.ga4.<field> ──
+ga4_pref() {
+ local key="$1" field="$2"
+ [ -f "$PREFS" ] || { echo ""; return 0; }
+ jq -r --arg k "$key" --arg f "$field" \
+ '.marketing.projects[$k].ga4[$f] // empty' "$PREFS" 2>/dev/null || true
+}
+
+usage() {
+ cat >&2 <<'USAGE'
+ops-conversion-send — GA4 Measurement Protocol sender
+
+Usage:
+ ops-conversion-send ga4 --project <key> --event <name> --client-id <cid>
+ [--value <number>] [--currency <ISO4217>] [--transaction-id <tx>]
+ [--user-id <uid>] [--properties <json-object>]
+
+Supported event names:
+ purchase — e-commerce purchase (value + currency + transaction_id recommended)
+ sign_up — user registration
+ generate_lead — lead capture
+ add_to_cart — add-to-cart action
+ <custom> — any string accepted by GA4 (snake_case recommended)
+
+Credential resolution (preferences.json marketing.projects.<key>.ga4):
+ measurement_id — GA4 Measurement ID (e.g. G-XXXXXXXXXX)
+ api_secret — API secret; supports doppler:proj/cfg/SECRET or env:VAR refs
+
+Environment:
+ OPS_DRY_RUN=1 Print planned curl + payload; exit 0 without network call
+ OPS_CONVERSION_DEBUG=1 POST to debug endpoint first (returns validation JSON)
+
+Returns non-zero on non-204 from the GA4 API.
+USAGE
+ exit 1
+}
+
+# ── Subcommand dispatch ───────────────────────────────────────────────────────
+SUBCMD="${1:-}"
+shift || true
+
+case "$SUBCMD" in
+ ga4) ;;
+ --help|-h) usage ;;
+ "") echo "ops-conversion-send: subcommand required (ga4 | --help)" >&2; exit 1 ;;
+ *) echo "ops-conversion-send: unknown subcommand '$SUBCMD'" >&2; exit 1 ;;
+esac
+
+# ── Parse flags ───────────────────────────────────────────────────────────────
+PROJECT=""
+EVENT_NAME=""
+CLIENT_ID=""
+VALUE=""
+CURRENCY=""
+TRANSACTION_ID=""
+USER_ID=""
+EXTRA_PROPS="{}"
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --project) PROJECT="${2:-}"; shift 2 ;;
+ --event) EVENT_NAME="${2:-}"; shift 2 ;;
+ --client-id) CLIENT_ID="${2:-}"; shift 2 ;;
+ --value) VALUE="${2:-}"; shift 2 ;;
+ --currency) CURRENCY="${2:-}"; shift 2 ;;
+ --transaction-id) TRANSACTION_ID="${2:-}"; shift 2 ;;
+ --user-id) USER_ID="${2:-}"; shift 2 ;;
+ --properties) EXTRA_PROPS="${2:-}"; shift 2 ;;
+ --help|-h) usage ;;
+ *) echo "ops-conversion-send ga4: unknown flag '$1'" >&2; exit 1 ;;
+ esac
+done
+
+[ -z "$PROJECT" ] && { echo "ops-conversion-send: --project is required" >&2; exit 1; }
+[ -z "$EVENT_NAME" ] && { echo "ops-conversion-send: --event is required" >&2; exit 1; }
+[ -z "$CLIENT_ID" ] && { echo "ops-conversion-send: --client-id is required" >&2; exit 1; }
+
+# ── Resolve credentials ───────────────────────────────────────────────────────
+MEASUREMENT_ID="$(resolve_cred "$(ga4_pref "$PROJECT" "measurement_id")")"
+API_SECRET="$(resolve_cred "$(ga4_pref "$PROJECT" "api_secret")")"
+
+[ -z "$MEASUREMENT_ID" ] && {
+ log "ERROR: marketing.projects.${PROJECT}.ga4.measurement_id not found in ${PREFS}"
+ exit 1
+}
+[ -z "$API_SECRET" ] && {
+ log "ERROR: marketing.projects.${PROJECT}.ga4.api_secret not found in ${PREFS}"
+ exit 1
+}
+
+# ── Build event params ────────────────────────────────────────────────────────
+# Start from --properties JSON (user-supplied extra params), then overlay
+# the typed fields so they always take precedence.
+EVENT_PARAMS="$EXTRA_PROPS"
+
+# Overlay value/currency/transaction_id if provided
+if [ -n "$VALUE" ]; then
+ EVENT_PARAMS="$(printf '%s' "$EVENT_PARAMS" | jq --argjson v "$VALUE" '.value = $v')"
+fi
+if [ -n "$CURRENCY" ]; then
+ EVENT_PARAMS="$(printf '%s' "$EVENT_PARAMS" | jq --arg c "$CURRENCY" '.currency = $c')"
+fi
+if [ -n "$TRANSACTION_ID" ]; then
+ EVENT_PARAMS="$(printf '%s' "$EVENT_PARAMS" | jq --arg tx "$TRANSACTION_ID" '.transaction_id = $tx')"
+fi
+
+# ── Build full payload ────────────────────────────────────────────────────────
+PAYLOAD="$(jq -n \
+ --arg cid "$CLIENT_ID" \
+ --arg uid "$USER_ID" \
+ --arg ename "$EVENT_NAME" \
+ --argjson eparams "$EVENT_PARAMS" \
+ '{
+ client_id: $cid,
+ events: [{ name: $ename, params: $eparams }]
+ }
+ | if $uid != "" then .user_id = $uid else . end')"
+
+GA4_BASE="https://www.google-analytics.com/mp/collect"
+GA4_DEBUG_BASE="https://www.google-analytics.com/debug/mp/collect"
+QUERY="measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}"
+
+# ── Dry-run: print and exit ───────────────────────────────────────────────────
+if [ "${OPS_DRY_RUN:-0}" = "1" ]; then
+ echo "[DRY RUN] ops-conversion-send ga4"
+ echo " endpoint: ${GA4_BASE}?measurement_id=${MEASUREMENT_ID}&api_secret=<redacted>"
+ echo " payload: $(printf '%s' "$PAYLOAD" | jq -c .)"
+ echo " curl: curl -s -o /dev/null -w '%{http_code}' -X POST '${GA4_BASE}?measurement_id=${MEASUREMENT_ID}&api_secret=<redacted>' -H 'Content-Type: application/json' -d '<payload>'"
+ exit 0
+fi
+
+# ── Optional debug validation ─────────────────────────────────────────────────
+if [ "${OPS_CONVERSION_DEBUG:-0}" = "1" ]; then
+ log "Validating event via debug endpoint..."
+ debug_resp="$(curl -s -X POST \
+ "${GA4_DEBUG_BASE}?${QUERY}" \
+ -H "Content-Type: application/json" \
+ -d "$PAYLOAD" 2>/dev/null || true)"
+ log "Debug response: $(printf '%s' "$debug_resp" | jq -c . 2>/dev/null || echo "$debug_resp")"
+ validation_code="$(printf '%s' "$debug_resp" | jq -r '.validationMessages[0].validationCode // "VALID"' 2>/dev/null || echo "PARSE_ERROR")"
+ if [ "$validation_code" != "VALID" ] && [ "$validation_code" != "null" ]; then
+ log "ERROR: GA4 debug validation failed: $validation_code"
+ exit 1
+ fi
+fi
+
+# ── Live send ─────────────────────────────────────────────────────────────────
+log "Sending GA4 event '${EVENT_NAME}' for project '${PROJECT}' (client_id=${CLIENT_ID})"
+http_code="$(curl -s -o /dev/null -w '%{http_code}' -X POST \
+ "${GA4_BASE}?${QUERY}" \
+ -H "Content-Type: application/json" \
+ -d "$PAYLOAD" 2>/dev/null)"
+
+if [ "$http_code" = "204" ] || [ "$http_code" = "200" ]; then
+ log "OK: GA4 event '${EVENT_NAME}' accepted (HTTP ${http_code})"
+ exit 0
+else
+ log "ERROR: GA4 returned HTTP ${http_code} for event '${EVENT_NAME}'"
+ exit 1
+fi
diff --git a/claude-ops/bin/ops-meta-capi-send b/claude-ops/bin/ops-meta-capi-send
new file mode 100755
index 00000000..edf877d3
--- /dev/null
+++ b/claude-ops/bin/ops-meta-capi-send
@@ -0,0 +1,247 @@
+#!/usr/bin/env bash
+# ops-meta-capi-send — Meta Conversions API event sender
+#
+# Sends conversion events to the Meta Conversions API (CAPI).
+# Credentials resolved from preferences.json marketing.projects.<key>.meta.*
+# or doppler: / env: refs — zero hardcoded values (Rule 0).
+#
+# Subcommands:
+# event --project <key> --event-name <name> --event-time <epoch>
+# --action-source website --event-source-url <url>
+# [--email <e>] [--phone <p>] [--value <v>] [--currency <c>]
+# [--event-id <id>] — Meta event_id for server-side deduplication
+# [--fbp <fbp>] [--fbc <fbc>] [--client-ip <ip>] [--user-agent <ua>]
+#
+# Email and phone are SHA-256 hashed (lowercase-normalised) per Meta requirements.
+#
+# Environment:
+# OPS_DRY_RUN=1 Print planned curl + payload, exit 0 without network call
+#
+# Returns non-zero on non-200 from Meta Graph API; surfaces error.code on failure.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PLUGIN_ROOT="${SCRIPT_DIR}/.."
+OPS_PLUGIN_ROOT_FALLBACK="$PLUGIN_ROOT" . "${PLUGIN_ROOT}/lib/registry-path.sh"
+
+PREFS="${OPS_CONVERSION_PREFS:-${OPS_DATA_DIR}/preferences.json}"
+LOG_DIR="${OPS_DATA_DIR}/logs"
+mkdir -p "$LOG_DIR"
+LOG="${LOG_DIR}/meta-capi-send.log"
+
+log() { printf '%s [ops-meta-capi-send] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG" >&2; }
+
+# ── Cred resolver: env:VAR | doppler:proj/cfg/SECRET | inline literal ────────
+resolve_cred() {
+ local ref="${1:-}"
+ { [ -z "$ref" ] || [ "$ref" = "null" ]; } && return 0
+ case "$ref" in
+ env:*)
+ local var="${ref#env:}"; printf '%s' "${!var:-}" ;;
+ doppler:*)
+ local path="${ref#doppler:}" proj rest cfg secret
+ proj="${path%%/*}"; rest="${path#*/}"; cfg="${rest%%/*}"; secret="${rest#*/}"
+ { [ -z "$proj" ] || [ -z "$cfg" ] || [ -z "$secret" ]; } && return 0
+ doppler secrets get "$secret" --project "$proj" --config "$cfg" --plain 2>/dev/null || true ;;
+ *) printf '%s' "$ref" ;;
+ esac
+}
+
+# ── Read a field from preferences.json marketing.projects.<key>.meta.<field> ─
+meta_pref() {
+ local key="$1" field="$2"
+ [ -f "$PREFS" ] || { echo ""; return 0; }
+ jq -r --arg k "$key" --arg f "$field" \
+ '.marketing.projects[$k].meta[$f] // empty' "$PREFS" 2>/dev/null || true
+}
+
+# ── SHA-256 hash (lowercase-normalised) ─────────────────────────────────────
+sha256_hash() {
+ local input
+ input="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -d ' ')"
+ [ -z "$input" ] && { printf ''; return 0; }
+ printf '%s' "$input" | shasum -a 256 | awk '{print $1}'
+}
+
+usage() {
+ cat >&2 <<'USAGE'
+ops-meta-capi-send — Meta Conversions API sender
+
+Usage:
+ ops-meta-capi-send event \
+ --project <key> \
+ --event-name <name> \
+ --event-time <epoch-seconds> \
+ --action-source <website|app|email|phone_call|chat|physical_store|system_generated|other> \
+ --event-source-url <url> \
+ [--email <address>] \
+ [--phone <number>] \
+ [--value <number>] \
+ [--currency <ISO4217>] \
+ [--event-id <string>] \
+ [--fbp <_fbp-cookie-value>] \
+ [--fbc <_fbc-cookie-value>] \
+ [--client-ip <ip>] \
+ [--user-agent <ua-string>]
+
+Credential resolution (preferences.json marketing.projects.<key>.meta):
+ pixel_id — Meta Pixel ID (numeric string, e.g. <YOUR_PIXEL_ID>)
+ access_token — System user access token; supports doppler: or env: refs
+ test_event_code — Optional; if set, all events go to the test endpoint
+
+Email and phone are automatically SHA-256 hashed (Meta requirement).
+
+Environment:
+ OPS_DRY_RUN=1 Print planned payload and curl command; exit 0 without network call
+
+Returns non-zero on non-200; prints error.code if present in the response body.
+USAGE
+ exit 1
+}
+
+# ── Subcommand dispatch ───────────────────────────────────────────────────────
+SUBCMD="${1:-}"
+shift || true
+
+case "$SUBCMD" in
+ event) ;;
+ --help|-h) usage ;;
+ "") echo "ops-meta-capi-send: subcommand required (event | --help)" >&2; exit 1 ;;
+ *) echo "ops-meta-capi-send: unknown subcommand '$SUBCMD'" >&2; exit 1 ;;
+esac
+
+# ── Parse flags ───────────────────────────────────────────────────────────────
+PROJECT=""
+EVENT_NAME=""
+EVENT_TIME=""
+ACTION_SOURCE="website"
+EVENT_SOURCE_URL=""
+EMAIL=""
+PHONE=""
+VALUE=""
+CURRENCY=""
+EVENT_ID=""
+FBP=""
+FBC=""
+CLIENT_IP=""
+USER_AGENT=""
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --project) PROJECT="${2:-}"; shift 2 ;;
+ --event-name) EVENT_NAME="${2:-}"; shift 2 ;;
+ --event-time) EVENT_TIME="${2:-}"; shift 2 ;;
+ --action-source) ACTION_SOURCE="${2:-}"; shift 2 ;;
+ --event-source-url) EVENT_SOURCE_URL="${2:-}"; shift 2 ;;
+ --email) EMAIL="${2:-}"; shift 2 ;;
+ --phone) PHONE="${2:-}"; shift 2 ;;
+ --value) VALUE="${2:-}"; shift 2 ;;
+ --currency) CURRENCY="${2:-}"; shift 2 ;;
+ --event-id) EVENT_ID="${2:-}"; shift 2 ;;
+ --fbp) FBP="${2:-}"; shift 2 ;;
+ --fbc) FBC="${2:-}"; shift 2 ;;
+ --client-ip) CLIENT_IP="${2:-}"; shift 2 ;;
+ --user-agent) USER_AGENT="${2:-}"; shift 2 ;;
+ --help|-h) usage ;;
+ *) echo "ops-meta-capi-send event: unknown flag '$1'" >&2; exit 1 ;;
+ esac
+done
+
+[ -z "$PROJECT" ] && { echo "ops-meta-capi-send: --project is required" >&2; exit 1; }
+[ -z "$EVENT_NAME" ] && { echo "ops-meta-capi-send: --event-name is required" >&2; exit 1; }
+[ -z "$EVENT_TIME" ] && { echo "ops-meta-capi-send: --event-time is required (epoch seconds)" >&2; exit 1; }
+[ -z "$EVENT_SOURCE_URL" ] && { echo "ops-meta-capi-send: --event-source-url is required" >&2; exit 1; }
+
+# ── Resolve credentials ───────────────────────────────────────────────────────
+PIXEL_ID="$(resolve_cred "$(meta_pref "$PROJECT" "pixel_id")")"
+ACCESS_TOKEN="$(resolve_cred "$(meta_pref "$PROJECT" "access_token")")"
+TEST_EVENT_CODE="$(resolve_cred "$(meta_pref "$PROJECT" "test_event_code")")"
+
+[ -z "$PIXEL_ID" ] && {
+ log "ERROR: marketing.projects.${PROJECT}.meta.pixel_id not found in ${PREFS}"
+ exit 1
+}
+[ -z "$ACCESS_TOKEN" ] && {
+ log "ERROR: marketing.projects.${PROJECT}.meta.access_token not found in ${PREFS}"
+ exit 1
+}
+
+# ── Hash PII ──────────────────────────────────────────────────────────────────
+EMAIL_HASH=""
+PHONE_HASH=""
+[ -n "$EMAIL" ] && EMAIL_HASH="$(sha256_hash "$EMAIL")"
+[ -n "$PHONE" ] && PHONE_HASH="$(sha256_hash "$PHONE")"
+
+# ── Build user_data object ────────────────────────────────────────────────────
+USER_DATA="{}"
+[ -n "$EMAIL_HASH" ] && USER_DATA="$(printf '%s' "$USER_DATA" | jq --arg v "$EMAIL_HASH" '.em = [$v]')"
+[ -n "$PHONE_HASH" ] && USER_DATA="$(printf '%s' "$USER_DATA" | jq --arg v "$PHONE_HASH" '.ph = [$v]')"
+[ -n "$CLIENT_IP" ] && USER_DATA="$(printf '%s' "$USER_DATA" | jq --arg v "$CLIENT_IP" '.client_ip_address = $v')"
+[ -n "$USER_AGENT" ] && USER_DATA="$(printf '%s' "$USER_DATA" | jq --arg v "$USER_AGENT" '.client_user_agent = $v')"
+[ -n "$FBP" ] && USER_DATA="$(printf '%s' "$USER_DATA" | jq --arg v "$FBP" '.fbp = $v')"
+[ -n "$FBC" ] && USER_DATA="$(printf '%s' "$USER_DATA" | jq --arg v "$FBC" '.fbc = $v')"
+
+# ── Build custom_data object ──────────────────────────────────────────────────
+CUSTOM_DATA="{}"
+[ -n "$VALUE" ] && CUSTOM_DATA="$(printf '%s' "$CUSTOM_DATA" | jq --argjson v "$VALUE" '.value = $v')"
+[ -n "$CURRENCY" ] && CUSTOM_DATA="$(printf '%s' "$CUSTOM_DATA" | jq --arg v "$CURRENCY" '.currency = $v')"
+
+# ── Build full payload ────────────────────────────────────────────────────────
+EVENT_OBJECT="$(jq -n \
+ --arg ename "$EVENT_NAME" \
+ --argjson etime "$EVENT_TIME" \
+ --arg asrc "$ACTION_SOURCE" \
+ --arg esurl "$EVENT_SOURCE_URL" \
+ --argjson ud "$USER_DATA" \
+ --argjson cd "$CUSTOM_DATA" \
+ --arg eid "$EVENT_ID" \
+ '{
+ event_name: $ename,
+ event_time: $etime,
+ action_source: $asrc,
+ event_source_url: $esurl,
+ user_data: $ud,
+ custom_data: $cd
+ } | if ($eid | length) > 0 then . + {event_id: $eid} else . end')"
+
+PAYLOAD="$(jq -n \
+ --argjson ev "$EVENT_OBJECT" \
+ '{ data: [$ev] }')"
+
+# Inject test_event_code if present (never committed — comes from prefs/doppler)
+if [ -n "$TEST_EVENT_CODE" ] && [ "$TEST_EVENT_CODE" != "null" ]; then
+ PAYLOAD="$(printf '%s' "$PAYLOAD" | jq --arg tec "$TEST_EVENT_CODE" '.test_event_code = $tec')"
+fi
+
+GRAPH_URL="https://graph.facebook.com/v20.0/${PIXEL_ID}/events?access_token=${ACCESS_TOKEN}"
+GRAPH_URL_REDACTED="https://graph.facebook.com/v20.0/${PIXEL_ID}/events?access_token=<redacted>"
+
+# ── Dry-run: print and exit ───────────────────────────────────────────────────
+if [ "${OPS_DRY_RUN:-0}" = "1" ]; then
+ echo "[DRY RUN] ops-meta-capi-send event"
+ echo " endpoint: ${GRAPH_URL_REDACTED}"
+ echo " payload: $(printf '%s' "$PAYLOAD" | jq -c .)"
+ echo " user_data.em: ${EMAIL_HASH:-<not set>}"
+ echo " user_data.ph: ${PHONE_HASH:-<not set>}"
+ echo " curl: curl -s -X POST '<endpoint>' -H 'Content-Type: application/json' -d '<payload>'"
+ exit 0
+fi
+
+# ── Live send ─────────────────────────────────────────────────────────────────
+log "Sending Meta CAPI event '${EVENT_NAME}' for project '${PROJECT}' (pixel=${PIXEL_ID})"
+response="$(curl -s -X POST "$GRAPH_URL" \
+ -H "Content-Type: application/json" \
+ -d "$PAYLOAD" 2>/dev/null)"
+
+http_success="$(printf '%s' "$response" | jq -r '.events_received // empty' 2>/dev/null || true)"
+error_code="$(printf '%s' "$response" | jq -r '.error.code // empty' 2>/dev/null || true)"
+error_msg="$(printf '%s' "$response" | jq -r '.error.message // empty' 2>/dev/null || true)"
+
+if [ -n "$http_success" ]; then
+ log "OK: Meta CAPI event '${EVENT_NAME}' accepted (events_received=${http_success})"
+ exit 0
+else
+ log "ERROR: Meta CAPI rejected event '${EVENT_NAME}' — code=${error_code:-unknown} msg=${error_msg:-unknown}"
+ log "Full response: $(printf '%s' "$response" | jq -c . 2>/dev/null || echo "$response")"
+ exit 1
+fi
diff --git a/claude-ops/bin/ops-stripe-conversion-bridge.mjs b/claude-ops/bin/ops-stripe-conversion-bridge.mjs
new file mode 100755
index 00000000..0abdea8f
--- /dev/null
+++ b/claude-ops/bin/ops-stripe-conversion-bridge.mjs
@@ -0,0 +1,350 @@
+#!/usr/bin/env node
+// ops-stripe-conversion-bridge — Stripe webhook → GA4 + Meta CAPI fanout
+//
+// Listens for Stripe webhook events, validates the signature, and fans out
+// purchase conversion signals to GA4 Measurement Protocol and Meta CAPI by
+// shelling out to bin/ops-conversion-send and bin/ops-meta-capi-send.
+//
+// Supported events:
+// charge.succeeded
+// checkout.session.completed
+//
+// Metadata keys read from Stripe checkout.session.metadata / charge.metadata:
+// utm_source, utm_medium, utm_campaign, utm_term, utm_content
+// client_id — GA4 client_id (anonymous device identifier)
+// fbp — Meta _fbp browser cookie value
+// fbc — Meta _fbc browser cookie value
+// event_source_url — canonical page URL for CAPI
+//
+// For checkout.session, client_reference_id is also read as a fallback client_id.
+//
+// Environment:
+// OPS_STRIPE_BRIDGE_PORT — HTTP port (default: 8787)
+// STRIPE_WEBHOOK_SECRET — Stripe webhook signing secret (whsec_...)
+// OPS_CONVERSION_PROJECT — ops-conversion-send --project key
+// OPS_DATA_DIR — log directory root
+// OPS_DRY_RUN=1 — forwarded to child senders (no network calls)
+//
+// Rule 0: no hardcoded accounts, secrets, or personal data.
+
+import { createServer } from 'node:http';
+import { createHmac, timingSafeEqual } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, appendFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const PLUGIN_ROOT = resolve(__dirname, '..');
+
+const PORT = parseInt(process.env.OPS_STRIPE_BRIDGE_PORT ?? '8787', 10);
+const WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET ?? '';
+const PROJECT = process.env.OPS_CONVERSION_PROJECT ?? '';
+const DATA_DIR = process.env.OPS_DATA_DIR ?? `${process.env.HOME}/.claude/plugins/data/ops-ops-marketplace`;
+const LOG_DIR = resolve(DATA_DIR, 'logs');
+const LOG_FILE = resolve(LOG_DIR, 'stripe-bridge.log');
+
+/** ISO 4217 codes Stripe treats as zero-decimal (amount is already in major units). */
+const STRIPE_ZERO_DECIMAL = new Set([
+ 'bif',
+ 'clp',
+ 'djf',
+ 'gnf',
+ 'isk',
+ 'jpy',
+ 'kmf',
+ 'krw',
+ 'mga',
+ 'pyg',
+ 'rwf',
+ 'ugx',
+ 'uyi',
+ 'vnd',
+ 'vuv',
+ 'xaf',
+ 'xof',
+ 'xpf',
+]);
+
+if (!existsSync(LOG_DIR)) mkdirSync(LOG_DIR, { recursive: true });
+
+/** @param {string} msg */
+function log(msg) {
+ const line = `${new Date().toISOString()} [stripe-bridge] ${msg}\n`;
+ process.stderr.write(line);
+ try {
+ appendFileSync(LOG_FILE, line);
+ } catch {
+ /* non-fatal */
+ }
+}
+
+if (!WEBHOOK_SECRET) {
+ log('ERROR: STRIPE_WEBHOOK_SECRET is not set — refusing to start');
+ process.exit(1);
+}
+if (!PROJECT) {
+ log('ERROR: OPS_CONVERSION_PROJECT is not set — refusing to start');
+ process.exit(1);
+}
+
+// ── Stripe webhook signature verification ────────────────────────────────────
+// Implements the Stripe v1 HMAC-SHA256 scheme without the stripe npm package
+// so the bridge has zero npm dependencies beyond Node builtins.
+/**
+ * @param {string} payload raw request body string
+ * @param {string} sigHeader value of Stripe-Signature header
+ * @param {string} secret webhook signing secret (whsec_... or raw)
+ * @returns {{ valid: boolean, event: object | null }}
+ */
+function constructEvent(payload, sigHeader, secret) {
+ if (!sigHeader) return { valid: false, event: null };
+
+ // Stripe may send multiple v1= signatures during webhook secret rotation; collect all.
+ let ts = '';
+ const v1Signatures = [];
+ for (const pair of sigHeader.split(',')) {
+ const eq = pair.indexOf('=');
+ if (eq === -1) continue;
+ const k = pair.slice(0, eq).trim();
+ const v = pair.slice(eq + 1);
+ if (k === 't') ts = v;
+ else if (k === 'v1') v1Signatures.push(v);
+ }
+ if (!ts || v1Signatures.length === 0) return { valid: false, event: null };
+
+ // Stripe uses the full signing secret (including whsec_ prefix) as the UTF-8 HMAC key.
+ const signedPayload = `${ts}.${payload}`;
+ const expected = createHmac('sha256', secret).update(signedPayload).digest('hex');
+
+ const expectedBuf = Buffer.from(expected, 'hex');
+ let valid = false;
+ for (const v1 of v1Signatures) {
+ const v1Buf = Buffer.from(v1, 'hex');
+ if (expectedBuf.length === v1Buf.length && timingSafeEqual(expectedBuf, v1Buf)) {
+ valid = true;
+ break;
+ }
+ }
+
+ if (!valid) return { valid: false, event: null };
+
+ // Replay-attack window: reject events older than 5 minutes
+ const now = Math.floor(Date.now() / 1000);
+ if (Math.abs(now - parseInt(ts, 10)) > 300) return { valid: false, event: null };
+
+ try {
+ return { valid: true, event: JSON.parse(payload) };
+ } catch {
+ return { valid: false, event: null };
+ }
+}
+
+// ── Shell out to conversion senders ─────────────────────────────────────────
+const GA4_BIN = resolve(PLUGIN_ROOT, 'bin', 'ops-conversion-send');
+const CAPI_BIN = resolve(PLUGIN_ROOT, 'bin', 'ops-meta-capi-send');
+
+/**
+ * @param {string} bin
+ * @param {string[]} args
+ * @returns {boolean}
+ */
+function runSender(bin, args) {
+ if (!existsSync(bin)) {
+ log(`WARN: sender binary not found: ${bin}`);
+ return false;
+ }
+ const env = { ...process.env };
+ const result = spawnSync(bin, args, { encoding: 'utf8', env });
+ if (result.error) {
+ log(`ERROR: failed to spawn ${bin}: ${result.error.message}`);
+ return false;
+ }
+ const combined = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
+ if (result.status !== 0) {
+ log(`ERROR: ${bin} exited ${result.status} — ${combined}`);
+ return false;
+ }
+ log(`OK: ${bin} — ${combined.split('\n')[0] ?? 'success'}`);
+ return true;
+}
+
+/**
+ * @param {number} amount Stripe amount (minor units, or major for zero-decimal currencies)
+ * @param {string} currencyLower ISO 4217 lowercased
+ */
+function formatStripeAmount(amount, currencyLower) {
+ if (STRIPE_ZERO_DECIMAL.has(currencyLower)) {
+ return String(amount);
+ }
+ return (amount / 100).toFixed(2);
+}
+
+/**
+ * Extract metadata from a Stripe event object.
+ * Handles both charge.succeeded and checkout.session.completed shapes.
+ * @param {object} stripeObject event.data.object
+ * @returns {{ meta: object, amountDecimal: string | null, currency: string | null }}
+ */
+function extractMetadata(stripeObject) {
+ const meta = stripeObject.metadata ?? {};
+ let amountDecimal = null;
+ let currency = null;
+ const currencyLower = (stripeObject.currency ?? 'usd').toLowerCase();
+ const currencyUpper = currencyLower.toUpperCase();
+
+ // charge.succeeded / checkout.session: amount uses Stripe minor units except zero-decimal ISO codes
+ if (typeof stripeObject.amount === 'number') {
+ amountDecimal = formatStripeAmount(stripeObject.amount, currencyLower);
+ currency = currencyUpper;
+ }
+ if (typeof stripeObject.amount_total === 'number') {
+ amountDecimal = formatStripeAmount(stripeObject.amount_total, currencyLower);
+ currency = currencyUpper;
+ }
+
+ // client_reference_id as fallback client_id
+ if (!meta.client_id && stripeObject.client_reference_id) {
+ meta.client_id = stripeObject.client_reference_id;
+ }
+
+ return { meta, amountDecimal, currency };
+}
+
+/**
+ * Stable id for GA4 transaction_id / Meta event_id: shared across webhook types
+ * for the same Checkout payment (e.g. charge.succeeded vs checkout.session.completed).
+ * @param {object} stripeObject
+ * @param {string} fallbackWebhookEventId
+ * @returns {string}
+ */
+function stablePurchaseDedupId(stripeObject, fallbackWebhookEventId) {
+ const pi = stripeObject?.payment_intent;
+ if (typeof pi === 'string' && pi.length > 0) return pi;
+ if (pi && typeof pi === 'object' && typeof pi.id === 'string' && pi.id.length > 0) {
+ return pi.id;
+ }
+ return fallbackWebhookEventId;
+}
+
+/**
+ * Fan out a purchase event to GA4 + Meta CAPI.
+ * @param {object} stripeObject
+ * @param {string} conversionDedupId GA4 --transaction-id / Meta --event-id
+ */
+function fanoutPurchase(stripeObject, conversionDedupId) {
+ const { meta, amountDecimal, currency } = extractMetadata(stripeObject);
+ const eventTime = Math.floor(Date.now() / 1000).toString();
+ const eventSourceUrl = meta.event_source_url ?? 'https://<your-domain.com>';
+
+ log(`Fanning out purchase: dedup_id=${conversionDedupId} value=${amountDecimal} ${currency}`);
+
+ // ── GA4 ──────────────────────────────────────────────────────────────────
+ if (meta.client_id) {
+ const ga4Args = [
+ 'ga4',
+ '--project',
+ PROJECT,
+ '--event',
+ 'purchase',
+ '--client-id',
+ meta.client_id,
+ '--transaction-id',
+ conversionDedupId,
+ ];
+ if (amountDecimal) ga4Args.push('--value', amountDecimal);
+ if (currency) ga4Args.push('--currency', currency);
+ runSender(GA4_BIN, ga4Args);
+ } else {
+ log('WARN: no client_id in metadata — skipping GA4 fanout');
+ }
+
+ // ── Meta CAPI ─────────────────────────────────────────────────────────────
+ const capiArgs = [
+ 'event',
+ '--project',
+ PROJECT,
+ '--event-name',
+ 'Purchase',
+ '--event-time',
+ eventTime,
+ '--action-source',
+ 'website',
+ '--event-source-url',
+ eventSourceUrl,
+ ];
+ if (meta.fbp) capiArgs.push('--fbp', meta.fbp);
+ if (meta.fbc) capiArgs.push('--fbc', meta.fbc);
+ if (amountDecimal) capiArgs.push('--value', amountDecimal);
+ if (currency) capiArgs.push('--currency', currency);
+ capiArgs.push('--event-id', conversionDedupId);
+ runSender(CAPI_BIN, capiArgs);
+}
+
+// ── HTTP server ───────────────────────────────────────────────────────────────
+const server = createServer((req, res) => {
+ if (req.method === 'GET' && req.url === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ status: 'ok', project: PROJECT }));
+ return;
+ }
+
+ if (req.method !== 'POST') {
+ res.writeHead(405);
+ res.end('Method Not Allowed');
+ return;
+ }
+
+ /** @type {Buffer[]} */
+ const chunks = [];
+ req.on('data', (chunk) => chunks.push(chunk));
+ req.on('end', () => {
+ const body = Buffer.concat(chunks).toString('utf8');
+ const sigHeader = req.headers['stripe-signature'] ?? '';
+
+ const { valid, event } = constructEvent(body, sigHeader, WEBHOOK_SECRET);
+ if (!valid) {
+ log('WARN: invalid Stripe signature or replay — rejecting');
+ res.writeHead(400);
+ res.end('Bad Request');
+ return;
+ }
+
+ const eventType = event?.type ?? '';
+ const obj = event?.data?.object ?? {};
+ const webhookEventId = event?.id ?? `evt_${Date.now()}`;
+ const conversionDedupId = stablePurchaseDedupId(obj, webhookEventId);
+
+ log(`Received Stripe event: type=${eventType} id=${webhookEventId}`);
+
+ switch (eventType) {
+ case 'charge.succeeded':
+ case 'checkout.session.completed':
+ fanoutPurchase(obj, conversionDedupId);
+ break;
+ default:
+ log(`Ignoring unhandled event type: ${eventType}`);
+ }
+
+ res.writeHead(200);
+ res.end('OK');
+ });
+
+ req.on('error', (err) => {
+ log(`ERROR: request read error: ${err.message}`);
+ res.writeHead(500);
+ res.end('Internal Server Error');
+ });
+});
+
+server.listen(PORT, () => {
+ log(`Stripe conversion bridge listening on port ${PORT}`);
+ log(`Project: ${PROJECT} | Log: ${LOG_FILE}`);
+ log(`Dry-run: ${process.env.OPS_DRY_RUN === '1' ? 'YES' : 'no'}`);
+});
+
+server.on('error', (err) => {
+ log(`FATAL: server error: ${err.message}`);
+ process.exit(1);
+});
diff --git a/claude-ops/data/gtm/utm-attribution-standard.md b/claude-ops/data/gtm/utm-attribution-standard.md
new file mode 100644
index 00000000..f0c2ad71
--- /dev/null
+++ b/claude-ops/data/gtm/utm-attribution-standard.md
@@ -0,0 +1,86 @@
+# UTM Attribution Standard
+
+Opinionated naming convention for all campaigns tracked through GA4 and Meta CAPI.
+Validated at creation time by `scripts/lib/utm-validate.sh`.
+
+## Required dimensions
+
+| Parameter | Required | Notes |
+|-----------------|----------|---------------------------------------------------------|
+| `utm_source` | yes | Traffic origin: `meta`, `google`, `email`, `organic` |
+| `utm_medium` | yes | Channel type: `cpc`, `social`, `newsletter`, `display` |
+| `utm_campaign` | yes | Must follow `{name}_{variant}_{date}` format |
+| `utm_term` | optional | Keyword (search campaigns only) |
+| `utm_content` | optional | Creative/ad set identifier |
+
+## Naming regex
+
+All values are **lowercase only**. Tokens consist of `[a-z0-9_-]`, starting with an
+alphanumeric character.
+
+```
+utm_source : ^[a-z0-9][a-z0-9_-]*$
+utm_medium : ^[a-z0-9][a-z0-9_-]*$
+utm_campaign : ^[a-z0-9][a-z0-9_-]*_[a-z0-9][a-z0-9_-]*_[0-9]{8}$
+ └─── name ───┘ └── variant ──┘ └─ date ─┘
+ date = YYYYMMDD (e.g. 20260601)
+```
+
+## Examples
+
+### Valid
+
+```
+utm_source=meta utm_medium=cpc utm_campaign=summer-sale_v1_20260601
+utm_source=google utm_medium=cpc utm_campaign=brand-awareness_control_20260115
+utm_source=email utm_medium=newsletter utm_campaign=weekly-digest_promo_20260520
+utm_source=organic utm_medium=social utm_campaign=launch_a_20260301
+```
+
+### Invalid
+
+```
+utm_campaign=summer sale_v1_20260601 # spaces not allowed
+utm_campaign=summersale_20260601 # missing variant segment
+utm_campaign=v1_20260601 # missing name segment
+utm_campaign=sale_v1_2026 # date must be 8 digits (YYYYMMDD)
+utm_source=Meta # uppercase not allowed
+utm_medium=CPC # uppercase not allowed
+```
+
+## GA4 alignment notes
+
+- GA4 Measurement Protocol events populated by `bin/ops-conversion-send` forward
+ `utm_source`, `utm_medium`, and `utm_campaign` as session-scoped custom dimensions
+ when the `client_id` ties back to an active GA4 session.
+- Campaign names that violate this standard will appear as uncategorised traffic in
+ the "Session source / medium" report.
+- Measurement ID format: `G-XXXXXXXXXX`.
+
+## Meta CAPI alignment notes
+
+- Meta Conversions API events sent by `bin/ops-meta-capi-send` pass the campaign
+ name through `custom_data.campaign` so Meta can align offline signals to the
+ originating ad set.
+- `fbp` and `fbc` cookies are forwarded verbatim as `user_data.fbp` / `user_data.fbc`
+ for deduplication against browser-pixel events.
+- SHA-256 hashing of `email` and `phone` is mandatory (handled automatically by
+ `bin/ops-meta-capi-send`).
+
+## Validation hook integration point
+
+<!-- TODO(P3): wire utm_validate into ops-marketing-autopilot campaign-create paths:
+ - Meta /campaigns POST (near ops-marketing-autopilot:315): call
+ utm_validate "$utm_source" "$utm_medium" "$utm_campaign" before the API call;
+ refuse with non-zero exit and log the violation if validation fails.
+ - Google Ads campaigns:mutate (near ops-marketing-autopilot:1532): same gate.
+ This TODO is intentionally deferred to the P3 PR to avoid collision with
+ in-flight PRs #256 and feat/marketing-p1-expand. The library is ready to source.
+-->
+
+Source `scripts/lib/utm-validate.sh` and call:
+
+```bash
+utm_validate "$utm_source" "$utm_medium" "$utm_campaign" \
+ || { log "invalid UTM — refusing campaign create"; exit 1; }
+```
diff --git a/claude-ops/scripts/install-stripe-bridge.sh b/claude-ops/scripts/install-stripe-bridge.sh
new file mode 100755
index 00000000..898f3e3e
--- /dev/null
+++ b/claude-ops/scripts/install-stripe-bridge.sh
@@ -0,0 +1,100 @@
+#!/usr/bin/env bash
+# install-stripe-bridge.sh — Register ops-stripe-conversion-bridge as a daemon service
+#
+# Adds the stripe-conversion-bridge entry to daemon-services.default.json (if not
+# already present) and installs it into OPS_DATA_DIR/daemon-services.json.
+#
+# Usage:
+# bash scripts/install-stripe-bridge.sh [--enable]
+#
+# Flags:
+# --enable Set "enabled": true in the service entry (default: false — opt-in)
+#
+# Environment:
+# OPS_STRIPE_BRIDGE_PORT — forwarded to the service command (default 8787)
+# STRIPE_WEBHOOK_SECRET — must be set before daemon runs (not committed)
+# OPS_CONVERSION_PROJECT — ops project key for conversion fanout
+# OPS_DATA_DIR — plugin data dir
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PLUGIN_ROOT="${SCRIPT_DIR}/.."
+OPS_PLUGIN_ROOT_FALLBACK="$PLUGIN_ROOT" . "${PLUGIN_ROOT}/lib/registry-path.sh"
+
+ENABLE=false
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --enable) ENABLE=true; shift ;;
+ *) echo "install-stripe-bridge: unknown flag '$1'" >&2; exit 1 ;;
+ esac
+done
+
+DAEMON_DEFAULTS="${PLUGIN_ROOT}/scripts/daemon-services.default.json"
+DAEMON_LOCAL="${OPS_DATA_DIR}/daemon-services.json"
+PORT="${OPS_STRIPE_BRIDGE_PORT:-8787}"
+
+SERVICE_KEY="stripe-conversion-bridge"
+
+# ── Build service entry ───────────────────────────────────────────────────────
+SERVICE_JSON="$(jq -n \
+ --argjson enabled "$ENABLE" \
+ --arg port "$PORT" \
+ '{
+ enabled: $enabled,
+ command: "${CLAUDE_PLUGIN_ROOT}/bin/ops-stripe-conversion-bridge.mjs",
+ health_check: ("lsof -i :" + $port + " | grep LISTEN"),
+ restart_delay: 30,
+ max_restarts: 10,
+ _note: "Stripe webhook → GA4 MP + Meta CAPI fanout. Requires STRIPE_WEBHOOK_SECRET and OPS_CONVERSION_PROJECT in env. Enable with: bash scripts/install-stripe-bridge.sh --enable"
+ }')"
+
+# ── Merge into daemon-services.default.json ───────────────────────────────────
+if jq -e --arg k "$SERVICE_KEY" '.services[$k] != null' "$DAEMON_DEFAULTS" >/dev/null 2>&1; then
+ echo "install-stripe-bridge: '$SERVICE_KEY' already present in daemon-services.default.json — updating"
+else
+ echo "install-stripe-bridge: adding '$SERVICE_KEY' to daemon-services.default.json"
+fi
+
+TMP="$(mktemp)"
+jq --arg k "$SERVICE_KEY" --argjson svc "$SERVICE_JSON" \
+ '.services[$k] = $svc' "$DAEMON_DEFAULTS" > "$TMP"
+mv "$TMP" "$DAEMON_DEFAULTS"
+
+# ── Merge into live daemon-services.json (OPS_DATA_DIR) ───────────────────────
+if [ -f "$DAEMON_LOCAL" ]; then
+ # Only update if key is missing or entry differs — preserve user's enabled flag
+ # unless --enable was passed.
+ existing_entry="$(jq -r --arg k "$SERVICE_KEY" '.services[$k] // "null"' "$DAEMON_LOCAL" 2>/dev/null || echo "null")"
+ if [ "$existing_entry" = "null" ]; then
+ echo "install-stripe-bridge: adding entry to ${DAEMON_LOCAL}"
+ TMP2="$(mktemp)"
+ jq --arg k "$SERVICE_KEY" --argjson svc "$SERVICE_JSON" \
+ '.services[$k] = $svc' "$DAEMON_LOCAL" > "$TMP2"
+ mv "$TMP2" "$DAEMON_LOCAL"
+ elif $ENABLE; then
+ echo "install-stripe-bridge: setting enabled=true in ${DAEMON_LOCAL}"
+ TMP2="$(mktemp)"
+ jq --arg k "$SERVICE_KEY" '.services[$k].enabled = true' "$DAEMON_LOCAL" > "$TMP2"
+ mv "$TMP2" "$DAEMON_LOCAL"
+ else
+ echo "install-stripe-bridge: entry already exists in ${DAEMON_LOCAL} — skipping (use --enable to activate)"
+ fi
+else
+ echo "install-stripe-bridge: ${DAEMON_LOCAL} not found — skipping live config update (run /ops:setup daemon first)"
+fi
+
+echo ""
+echo "Stripe conversion bridge registered."
+echo ""
+echo "Required environment variables (set before starting the daemon):"
+echo " STRIPE_WEBHOOK_SECRET=whsec_<your-secret>"
+echo " OPS_CONVERSION_PROJECT=<your-project-key>"
+echo " OPS_STRIPE_BRIDGE_PORT=${PORT} (optional, default 8787)"
+echo ""
+if $ENABLE; then
+ echo "Service is ENABLED. Restart the ops daemon to activate:"
+ echo " bash scripts/ops-daemon-manager.sh restart"
+else
+ echo "Service is DISABLED (default). Enable it with:"
+ echo " bash scripts/install-stripe-bridge.sh --enable"
+fi
diff --git a/claude-ops/scripts/lib/utm-validate.sh b/claude-ops/scripts/lib/utm-validate.sh
new file mode 100644
index 00000000..8f8ecdcb
--- /dev/null
+++ b/claude-ops/scripts/lib/utm-validate.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+# scripts/lib/utm-validate.sh — UTM parameter enforcement library
+#
+# Source this file to get utm_validate.
+#
+# Usage:
+# . "${PLUGIN_ROOT}/scripts/lib/utm-validate.sh"
+# utm_validate "$utm_source" "$utm_medium" "$utm_campaign" || exit 1
+#
+# Conforms to the standard documented in data/gtm/utm-attribution-standard.md.
+# Returns 0 on valid input, 1 with a diagnostic on stderr on violation.
+#
+# Rule 0: public repo — no real project identifiers in this file.
+
+# Regex fragments (POSIX ERE)
+_UTM_TOKEN='[a-z0-9][a-z0-9_-]*' # single token: starts with alnum, continues with alnum/underscore/dash
+_UTM_SOURCE_RE="^${_UTM_TOKEN}$" # source: one token
+_UTM_MEDIUM_RE="^${_UTM_TOKEN}$" # medium: one token
+_UTM_CAMPAIGN_RE="^${_UTM_TOKEN}_${_UTM_TOKEN}_[0-9]{8}$" # campaign: token_token_YYYYMMDD
+
+# utm_validate <utm_source> <utm_medium> <utm_campaign>
+# Returns 0 if all three conform; 1 otherwise.
+# Writes diagnostic to stderr on failure.
+utm_validate() {
+ local source="${1:-}" medium="${2:-}" campaign="${3:-}"
+ local ok=0
+
+ if [ -z "$source" ]; then
+ echo "utm_validate: utm_source is required" >&2
+ ok=1
+ elif ! echo "$source" | grep -qE "$_UTM_SOURCE_RE"; then
+ echo "utm_validate: utm_source '${source}' invalid — must match ${_UTM_SOURCE_RE}" >&2
+ ok=1
+ fi
+
+ if [ -z "$medium" ]; then
+ echo "utm_validate: utm_medium is required" >&2
+ ok=1
+ elif ! echo "$medium" | grep -qE "$_UTM_MEDIUM_RE"; then
+ echo "utm_validate: utm_medium '${medium}' invalid — must match ${_UTM_MEDIUM_RE}" >&2
+ ok=1
+ fi
+
+ if [ -z "$campaign" ]; then
+ echo "utm_validate: utm_campaign is required" >&2
+ ok=1
+ elif ! echo "$campaign" | grep -qE "$_UTM_CAMPAIGN_RE"; then
+ echo "utm_validate: utm_campaign '${campaign}' invalid — must match <name>_<variant>_YYYYMMDD (e.g. summer-sale_v1_20260601)" >&2
+ ok=1
+ fi
+
+ return $ok
+}
diff --git a/claude-ops/tests/test-ops-conversion-send.sh b/claude-ops/tests/test-ops-conversion-send.sh
new file mode 100755
index 00000000..2a618d9a
--- /dev/null
+++ b/claude-ops/tests/test-ops-conversion-send.sh
@@ -0,0 +1,134 @@
+#!/usr/bin/env bash
+# test-ops-conversion-send.sh — Smoke tests for bin/ops-conversion-send
+#
+# Hermetic: OPS_DRY_RUN=1 throughout — zero network calls.
+# Asserts planned curl shape, flag validation, and credential wiring.
+set -euo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BIN="$PLUGIN_ROOT/bin/ops-conversion-send"
+
+pass=0; fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1 — $2"; fail=$((fail+1)); }
+
+echo "Testing $BIN"
+echo ""
+
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+export OPS_DATA_DIR="$WORK/data"
+export OPS_DRY_RUN=1
+export OPS_CONVERSION_PREFS="$WORK/preferences.json"
+mkdir -p "$OPS_DATA_DIR"
+
+write_prefs() { cat > "$OPS_CONVERSION_PREFS"; }
+
+# ── 1. Missing subcommand → non-zero ─────────────────────────────────────────
+set +e; "$BIN" 2>/dev/null; rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "no subcommand exits non-zero" || err "no subcommand" "expected non-zero"
+
+# ── 2. --help exits 1 without crash ──────────────────────────────────────────
+set +e; "$BIN" --help 2>/dev/null; rc=$?; set -e
+[ "$rc" -eq 1 ] && ok "--help exits 1" || err "--help" "expected exit 1, got $rc"
+
+# ── 3. ga4 missing --project → non-zero ──────────────────────────────────────
+set +e; "$BIN" ga4 --event purchase --client-id abc123 2>/dev/null; rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "ga4 missing --project exits non-zero" || err "ga4 missing --project" "expected non-zero"
+
+# ── 4. ga4 missing prefs file → non-zero ─────────────────────────────────────
+rm -f "$OPS_CONVERSION_PREFS"
+set +e; "$BIN" ga4 --project testproj --event purchase --client-id abc123 2>/dev/null; rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "ga4 missing prefs exits non-zero" || err "ga4 missing prefs" "expected non-zero"
+
+# ── 5. ga4 dry-run: measurement_id not set → non-zero ────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "testproj": { "ga4": {} } } } }
+JSON
+set +e; "$BIN" ga4 --project testproj --event purchase --client-id abc123 2>/dev/null; rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "ga4 empty measurement_id exits non-zero" || err "ga4 empty measurement_id" "expected non-zero"
+
+# ── 6. ga4 dry-run: api_secret not set → non-zero ────────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "testproj": { "ga4": { "measurement_id": "G-XXXXXXXXXX" } } } } }
+JSON
+set +e; "$BIN" ga4 --project testproj --event purchase --client-id abc123 2>/dev/null; rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "ga4 empty api_secret exits non-zero" || err "ga4 empty api_secret" "expected non-zero"
+
+# ── 7. ga4 dry-run: valid prefs → exit 0, correct output shape ───────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "testproj": {
+ "ga4": {
+ "measurement_id": "G-XXXXXXXXXX",
+ "api_secret": "test-api-secret-placeholder"
+ }
+} } } }
+JSON
+
+output="$("$BIN" ga4 --project testproj --event purchase --client-id abc123 \
+ --value 49.99 --currency USD --transaction-id tx_test_001 2>/dev/null)"
+rc=$?
+[ "$rc" -eq 0 ] && ok "ga4 dry-run exits 0" || err "ga4 dry-run exit" "rc=$rc"
+echo "$output" | grep -q '\[DRY RUN\]' \
+ && ok "output contains [DRY RUN]" || err "dry-run marker" "missing [DRY RUN]"
+echo "$output" | grep -q 'measurement_id=G-XXXXXXXXXX' \
+ && ok "output contains measurement_id" || err "measurement_id" "not in output"
+echo "$output" | grep -q 'api_secret=<redacted>' \
+ && ok "api_secret is redacted in output" || err "api_secret redaction" "api_secret not redacted"
+echo "$output" | grep -q '"name":"purchase"' \
+ && ok "output contains event name 'purchase'" || err "event name" "purchase not in payload"
+echo "$output" | grep -q '"value":49.99' \
+ && ok "output contains value 49.99" || err "value" "49.99 not in payload"
+echo "$output" | grep -q '"currency":"USD"' \
+ && ok "output contains currency USD" || err "currency" "USD not in payload"
+echo "$output" | grep -q '"transaction_id":"tx_test_001"' \
+ && ok "output contains transaction_id" || err "transaction_id" "tx_test_001 not in payload"
+
+# ── 8. ga4 dry-run: sign_up event ────────────────────────────────────────────
+output="$("$BIN" ga4 --project testproj --event sign_up --client-id abc123 2>/dev/null)"
+echo "$output" | grep -q '"name":"sign_up"' \
+ && ok "sign_up event name correct" || err "sign_up event" "name not in output"
+
+# ── 9. ga4 dry-run: generate_lead event ──────────────────────────────────────
+output="$("$BIN" ga4 --project testproj --event generate_lead --client-id abc123 2>/dev/null)"
+echo "$output" | grep -q '"name":"generate_lead"' \
+ && ok "generate_lead event name correct" || err "generate_lead event" "name not in output"
+
+# ── 10. ga4 dry-run: add_to_cart event ───────────────────────────────────────
+output="$("$BIN" ga4 --project testproj --event add_to_cart --client-id abc123 2>/dev/null)"
+echo "$output" | grep -q '"name":"add_to_cart"' \
+ && ok "add_to_cart event name correct" || err "add_to_cart event" "name not in output"
+
+# ── 11. ga4 dry-run: user-id is included when provided ───────────────────────
+output="$("$BIN" ga4 --project testproj --event purchase --client-id abc123 --user-id u_99 2>/dev/null)"
+echo "$output" | grep -q '"user_id":"u_99"' \
+ && ok "user_id present in payload" || err "user_id" "not in payload"
+
+# ── 12. ga4 dry-run: --properties merges into params ─────────────────────────
+output="$("$BIN" ga4 --project testproj --event purchase --client-id abc123 \
+ --properties '{"campaign":"summer_v1_20260601"}' 2>/dev/null)"
+echo "$output" | grep -q '"campaign":"summer_v1_20260601"' \
+ && ok "--properties merged into event params" || err "--properties" "not in payload"
+
+# ── 13. ga4 dry-run: env: cred ref resolved ──────────────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "envproj": {
+ "ga4": {
+ "measurement_id": "env:TEST_GA4_MID",
+ "api_secret": "env:TEST_GA4_SECRET"
+ }
+} } } }
+JSON
+export TEST_GA4_MID="G-ENVTEST00"
+export TEST_GA4_SECRET="env-secret-placeholder"
+output="$("$BIN" ga4 --project envproj --event purchase --client-id abc 2>/dev/null)"
+echo "$output" | grep -q 'measurement_id=G-ENVTEST00' \
+ && ok "env: ref for measurement_id resolved" || err "env: ref measurement_id" "not resolved"
+unset TEST_GA4_MID TEST_GA4_SECRET
+
+echo ""
+echo "---"
+echo "Results: $pass passed, $fail failed"
+(( fail == 0 )) || { echo "ACTION: fix failing tests above."; exit 1; }
+exit 0
diff --git a/claude-ops/tests/test-ops-meta-capi-send.sh b/claude-ops/tests/test-ops-meta-capi-send.sh
new file mode 100755
index 00000000..43e7d282
--- /dev/null
+++ b/claude-ops/tests/test-ops-meta-capi-send.sh
@@ -0,0 +1,211 @@
+#!/usr/bin/env bash
+# test-ops-meta-capi-send.sh — Smoke tests for bin/ops-meta-capi-send
+#
+# Hermetic: OPS_DRY_RUN=1 throughout — zero network calls.
+# Asserts payload shape, SHA-256 hashing of em/ph, and credential wiring.
+set -euo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BIN="$PLUGIN_ROOT/bin/ops-meta-capi-send"
+
+pass=0; fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1 — $2"; fail=$((fail+1)); }
+
+echo "Testing $BIN"
+echo ""
+
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+export OPS_DATA_DIR="$WORK/data"
+export OPS_DRY_RUN=1
+export OPS_CONVERSION_PREFS="$WORK/preferences.json"
+mkdir -p "$OPS_DATA_DIR"
+
+write_prefs() { cat > "$OPS_CONVERSION_PREFS"; }
+
+# Expected SHA-256 hashes for known test inputs (lowercase-normalised)
+# echo -n "[email protected]" | shasum -a 256 | awk '{print $1}'
+EXPECTED_EMAIL_HASH="b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514"
+# echo -n "+15551234567" | shasum -a 256 | awk '{print $1}'
+EXPECTED_PHONE_HASH="$(printf '%s' '+15551234567' | shasum -a 256 | awk '{print $1}')"
+
+# ── 1. Missing subcommand → non-zero ─────────────────────────────────────────
+set +e; "$BIN" 2>/dev/null; rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "no subcommand exits non-zero" || err "no subcommand" "expected non-zero"
+
+# ── 2. --help exits 1 ─────────────────────────────────────────────────────────
+set +e; "$BIN" --help 2>/dev/null; rc=$?; set -e
+[ "$rc" -eq 1 ] && ok "--help exits 1" || err "--help" "expected exit 1, got $rc"
+
+# ── 3. event missing --project → non-zero ────────────────────────────────────
+set +e
+"$BIN" event --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" 2>/dev/null
+rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "event missing --project exits non-zero" || err "missing --project" "expected non-zero"
+
+# ── 4. event missing prefs → non-zero ────────────────────────────────────────
+rm -f "$OPS_CONVERSION_PREFS"
+set +e
+"$BIN" event --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" 2>/dev/null
+rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "event missing prefs exits non-zero" || err "missing prefs" "expected non-zero"
+
+# ── 5. event missing pixel_id → non-zero ─────────────────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "testproj": { "meta": {} } } } }
+JSON
+set +e
+"$BIN" event --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" 2>/dev/null
+rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "event empty pixel_id exits non-zero" || err "empty pixel_id" "expected non-zero"
+
+# ── 6. event missing access_token → non-zero ─────────────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "testproj": { "meta": { "pixel_id": "<YOUR_PIXEL_ID>" } } } } }
+JSON
+set +e
+"$BIN" event --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" 2>/dev/null
+rc=$?; set -e
+[ "$rc" -ne 0 ] && ok "event empty access_token exits non-zero" || err "empty access_token" "expected non-zero"
+
+# ── Write valid prefs for remaining tests ─────────────────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "testproj": {
+ "meta": {
+ "pixel_id": "<YOUR_PIXEL_ID>",
+ "access_token": "test-access-token-placeholder"
+ }
+} } } }
+JSON
+
+# ── 7. dry-run Purchase event → exit 0, correct shape ────────────────────────
+output="$("$BIN" event \
+ --project testproj \
+ --event-name Purchase \
+ --event-time 1716000000 \
+ --action-source website \
+ --event-source-url "https://<your-domain.com>" \
+ --value 49.99 --currency USD 2>/dev/null)"
+rc=$?
+[ "$rc" -eq 0 ] && ok "dry-run exits 0" || err "dry-run exit" "rc=$rc"
+echo "$output" | grep -q '\[DRY RUN\]' \
+ && ok "output contains [DRY RUN]" || err "dry-run marker" "missing [DRY RUN]"
+echo "$output" | grep -q '"event_name":"Purchase"' \
+ && ok "payload contains event_name=Purchase" || err "event_name" "not in payload"
+echo "$output" | grep -q '"event_time":1716000000' \
+ && ok "payload contains event_time" || err "event_time" "not in payload"
+echo "$output" | grep -q '"action_source":"website"' \
+ && ok "payload contains action_source" || err "action_source" "not in payload"
+echo "$output" | grep -q '"value":49.99' \
+ && ok "payload contains value 49.99" || err "value" "not in payload"
+echo "$output" | grep -q '"currency":"USD"' \
+ && ok "payload contains currency USD" || err "currency" "not in payload"
+echo "$output" | grep -q 'access_token=<redacted>' \
+ && ok "access_token is redacted in output" || err "access_token redaction" "not redacted"
+
+# ── 8. SHA-256 hashing of email ───────────────────────────────────────────────
+output="$("$BIN" event \
+ --project testproj \
+ --event-name Purchase \
+ --event-time 1716000000 \
+ --action-source website \
+ --event-source-url "https://<your-domain.com>" \
+ --email "[email protected]" 2>/dev/null)"
+echo "$output" | grep -q "user_data.em: ${EXPECTED_EMAIL_HASH}" \
+ && ok "email SHA-256 hash correct (${EXPECTED_EMAIL_HASH:0:16}...)" \
+ || err "email SHA-256 hash" "expected ${EXPECTED_EMAIL_HASH:0:16}... got: $(echo "$output" | grep 'user_data.em' | head -1)"
+
+# ── 9. SHA-256 hashing of phone ───────────────────────────────────────────────
+output="$("$BIN" event \
+ --project testproj \
+ --event-name Purchase \
+ --event-time 1716000000 \
+ --action-source website \
+ --event-source-url "https://<your-domain.com>" \
+ --phone "+15551234567" 2>/dev/null)"
+echo "$output" | grep -q "user_data.ph: ${EXPECTED_PHONE_HASH}" \
+ && ok "phone SHA-256 hash correct (${EXPECTED_PHONE_HASH:0:16}...)" \
+ || err "phone SHA-256 hash" "expected ${EXPECTED_PHONE_HASH:0:16}... got: $(echo "$output" | grep 'user_data.ph' | head -1)"
+
+# ── 10. SHA-256: uppercase email normalised before hashing ───────────────────
+output_lower="$("$BIN" event \
+ --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" \
+ --email "[email protected]" 2>/dev/null)"
+output_upper="$("$BIN" event \
+ --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" \
+ --email "[email protected]" 2>/dev/null)"
+hash_lower="$(echo "$output_lower" | grep 'user_data.em:' | awk '{print $NF}')"
+hash_upper="$(echo "$output_upper" | grep 'user_data.em:' | awk '{print $NF}')"
+[ "$hash_lower" = "$hash_upper" ] && [ -n "$hash_lower" ] \
+ && ok "uppercase email normalised to same hash as lowercase" \
+ || err "case normalisation" "lower='$hash_lower' upper='$hash_upper'"
+
+# ── 11. fbp / fbc forwarded into user_data ───────────────────────────────────
+output="$("$BIN" event \
+ --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" \
+ --fbp "fb.1.1234567890.987654321" \
+ --fbc "fb.1.1234567890.AbCdEfGhIjKlMnOp" 2>/dev/null)"
+echo "$output" | grep -q '"fbp":"fb.1.1234567890.987654321"' \
+ && ok "fbp forwarded into user_data" || err "fbp" "not in payload"
+echo "$output" | grep -q '"fbc":"fb.1.1234567890.AbCdEfGhIjKlMnOp"' \
+ && ok "fbc forwarded into user_data" || err "fbc" "not in payload"
+
+# ── 12. client_ip and user_agent in user_data ────────────────────────────────
+output="$("$BIN" event \
+ --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" \
+ --client-ip "203.0.113.1" \
+ --user-agent "Mozilla/5.0 (compatible; test)" 2>/dev/null)"
+echo "$output" | grep -q '"client_ip_address":"203.0.113.1"' \
+ && ok "client_ip in user_data" || err "client_ip" "not in payload"
+echo "$output" | grep -q '"client_user_agent":"Mozilla/5.0 (compatible; test)"' \
+ && ok "user_agent in user_data" || err "user_agent" "not in payload"
+
+# ── 13. test_event_code injected when set in prefs ────────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "testproj": {
+ "meta": {
+ "pixel_id": "<YOUR_PIXEL_ID>",
+ "access_token": "test-access-token-placeholder",
+ "test_event_code": "TEST12345"
+ }
+} } } }
+JSON
+output="$("$BIN" event \
+ --project testproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" 2>/dev/null)"
+echo "$output" | grep -q '"test_event_code":"TEST12345"' \
+ && ok "test_event_code injected from prefs" || err "test_event_code" "not in payload"
+
+# ── 14. env: cred ref for access_token ───────────────────────────────────────
+write_prefs <<'JSON'
+{ "marketing": { "projects": { "envproj": {
+ "meta": {
+ "pixel_id": "env:TEST_META_PIXEL",
+ "access_token": "env:TEST_META_TOKEN"
+ }
+} } } }
+JSON
+export TEST_META_PIXEL="<YOUR_PIXEL_ID>"
+export TEST_META_TOKEN="env-token-placeholder"
+output="$("$BIN" event \
+ --project envproj --event-name Purchase --event-time 1716000000 \
+ --action-source website --event-source-url "https://<your-domain.com>" 2>/dev/null)"
+echo "$output" | grep -q 'access_token=<redacted>' \
+ && ok "env: ref for access_token resolved (and redacted)" || err "env: access_token" "not resolved or not redacted"
+unset TEST_META_PIXEL TEST_META_TOKEN
+
+echo ""
+echo "---"
+echo "Results: $pass passed, $fail failed"
+(( fail == 0 )) || { echo "ACTION: fix failing tests above."; exit 1; }
+exit 0
diff --git a/claude-ops/tests/test-utm-validate.sh b/claude-ops/tests/test-utm-validate.sh
new file mode 100755
index 00000000..aa93b345
--- /dev/null
+++ b/claude-ops/tests/test-utm-validate.sh
@@ -0,0 +1,89 @@
+#!/usr/bin/env bash
+# test-utm-validate.sh — Golden-table tests for scripts/lib/utm-validate.sh
+#
+# Runs a matrix of valid and invalid utm tuples and asserts correct exit codes.
+set -euo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+LIB="${PLUGIN_ROOT}/scripts/lib/utm-validate.sh"
+
+pass=0; fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1 — $2"; fail=$((fail+1)); }
+
+echo "Testing $LIB"
+echo ""
+
+# Source the library
+# shellcheck disable=SC1090
+. "$LIB"
+
+# Helper: assert utm_validate returns expected exit code
+# $1 expected (0=valid, 1=invalid), $2 description, $3 source, $4 medium, $5 campaign
+assert_utm() {
+ local expected="$1" desc="$2" src="$3" med="$4" cmp="$5"
+ set +e
+ utm_validate "$src" "$med" "$cmp" 2>/dev/null
+ local rc=$?
+ set -e
+ if [ "$rc" -eq "$expected" ]; then
+ ok "$desc"
+ else
+ err "$desc" "expected exit $expected got $rc (source='$src' medium='$med' campaign='$cmp')"
+ fi
+}
+
+echo "--- VALID tuples (expect exit 0) ---"
+assert_utm 0 "canonical example" "meta" "cpc" "summer-sale_v1_20260601"
+assert_utm 0 "google cpc" "google" "cpc" "brand-awareness_control_20260115"
+assert_utm 0 "email newsletter" "email" "newsletter" "weekly-digest_promo_20260520"
+assert_utm 0 "organic social" "organic" "social" "launch_a_20260301"
+assert_utm 0 "underscores in name" "meta" "cpc" "black_friday_control_20261129"
+assert_utm 0 "dashes in name" "google" "display" "spring-launch_v2_20260315"
+assert_utm 0 "single-char variant" "meta" "cpc" "sale_b_20260401"
+assert_utm 0 "numeric in source" "meta2" "cpc" "test_v1_20260101"
+assert_utm 0 "digits only date boundary" "meta" "cpc" "x_y_20260101"
+assert_utm 0 "hyphen in source" "meta-ig" "cpc" "test_v1_20260101"
+
+echo ""
+echo "--- INVALID tuples (expect exit 1) ---"
+
+# Missing fields
+assert_utm 1 "empty source" "" "cpc" "sale_v1_20260601"
+assert_utm 1 "empty medium" "meta" "" "sale_v1_20260601"
+assert_utm 1 "empty campaign" "meta" "cpc" ""
+
+# Uppercase violations
+assert_utm 1 "uppercase source" "Meta" "cpc" "sale_v1_20260601"
+assert_utm 1 "uppercase medium" "meta" "CPC" "sale_v1_20260601"
+assert_utm 1 "uppercase in campaign" "meta" "cpc" "Sale_v1_20260601"
+
+# Campaign format violations
+assert_utm 1 "campaign with spaces" "meta" "cpc" "summer sale_v1_20260601"
+assert_utm 1 "campaign missing variant" "meta" "cpc" "summersale_20260601"
+assert_utm 1 "campaign one segment only" "meta" "cpc" "sale"
+assert_utm 1 "campaign date too short" "meta" "cpc" "sale_v1_2026"
+assert_utm 1 "campaign date 6 digits" "meta" "cpc" "sale_v1_202601"
+assert_utm 1 "campaign date 10 digits" "meta" "cpc" "sale_v1_2026010101"
+assert_utm 1 "campaign no date segment" "meta" "cpc" "sale_v1"
+assert_utm 1 "source starts with dash" "-meta" "cpc" "sale_v1_20260601"
+assert_utm 1 "source with space" "meta ads" "cpc" "sale_v1_20260601"
+assert_utm 1 "medium with slash" "meta" "cpc/display" "sale_v1_20260601"
+
+echo ""
+echo "--- utm_validate writes diagnostics to stderr ---"
+msg="$(utm_validate "" "cpc" "sale_v1_20260601" 2>&1 || true)"
+echo "$msg" | grep -q "utm_source" \
+ && ok "empty source produces utm_source diagnostic" \
+ || err "utm_source diagnostic" "expected 'utm_source' in stderr: '$msg'"
+
+msg="$(utm_validate "meta" "cpc" "badcampaign" 2>&1 || true)"
+echo "$msg" | grep -q "utm_campaign" \
+ && ok "bad campaign produces utm_campaign diagnostic" \
+ || err "utm_campaign diagnostic" "expected 'utm_campaign' in stderr: '$msg'"
+
+echo ""
+echo "---"
+echo "Results: $pass passed, $fail failed"
+(( fail == 0 )) || { echo "ACTION: fix failing tests above."; exit 1; }
+exit 0