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
plan(v1.5): executable plans for phases 10-15 marketing integrations
auroracapital575cdd22bd52
diff --git a/.planning/phases/phase-10/10-01-PLAN.md b/.planning/phases/phase-10/10-01-PLAN.mdnew file mode 100644index 00000000..e73574a1--- /dev/null+++ b/.planning/phases/phase-10/10-01-PLAN.md@@ -0,0 +1,149 @@+---+phase: "10-google-ads"+plan: "01"+subsystem: ops-marketing+tags: [google-ads, oauth2, credentials, setup-wizard, dashboard]+dependency_graph:+ requires: []+ provides: [google-ads-credential-resolution, google-ads-token-refresh, google-ads-setup-flow, google-ads-dashboard-gather]+ affects: [ops-marketing/SKILL.md, skills/setup/SKILL.md, bin/ops-marketing-dash]+---++# Phase 10 Plan 01: Google Ads Credential Foundation++## Goal++Wire Google Ads authentication into the ops-marketing skill via a 3-tier credential cascade (userConfig → env → Doppler), provide an OAuth2 setup flow in the setup wizard, and add a campaign pre-gather function to the marketing dashboard script. This plan establishes auth only; sub-command implementations follow in Plans 02 and 03.++## Requirements Addressed++- `GADS-07`: Credential resolution and token refresh for Google Ads API access+- Google Ads OAuth2 setup flow integrated into `/ops:setup` wizard++## Runtime Prerequisites++**STOP — Sam must provide the following before this plan can execute:**++| Credential | Where to get it |+|---|---|+| `GADS_DEV_TOKEN` | [Google Ads API Center](https://ads.google.com/aw/apicenter) → Developer token (requires approved API access) |+| `GADS_CLIENT_ID` | Google Cloud Console → APIs & Services → Credentials → OAuth 2.0 Client ID |+| `GADS_CLIENT_SECRET` | Same OAuth 2.0 Client ID entry in Google Cloud Console |+| `GADS_REFRESH_TOKEN` | Obtained via OAuth2 authorization flow (Plan 01 setup wizard generates this) |+| `GADS_CUSTOMER_ID` | Google Ads account → Settings → Account details (10-digit, format `123-456-7890`) |+| `GADS_LOGIN_CUSTOMER_ID` | Only required for MCC (manager) accounts; the MCC account ID |++**API approval note:** Google Ads API requires applying for access at https://developers.google.com/google-ads/api/docs/access-levels. Basic access is available immediately; Standard access requires application review.++## Deliverables++### Files to Modify++- `claude-ops/skills/ops-marketing/SKILL.md` — add `google_ads_*` keys to Runtime Context, add `### Google Ads` credential resolution block with 6-variable cascade, add access token refresh via `oauth2.googleapis.com/token`, add `## google-ads` section with routing table placeholder and credential guard+- `claude-ops/skills/setup/SKILL.md` — restructure marketing AskUserQuestion into two sequential calls (max 4 options per Rule 1), add `#### Google Ads` setup sub-section (Steps A–F: dev token → OAuth client → browser OAuth flow → customer ID discovery → smoke test → save to preferences.json)+- `claude-ops/bin/ops-marketing-dash` — add 6-var Google Ads credential resolution block, add `gather_google_ads()` stub function that returns `null` when unconfigured, add it to parallel execution block++## Task Breakdown++### Task 1: Add Google Ads credential resolution to ops-marketing/SKILL.md++**File**: `claude-ops/skills/ops-marketing/SKILL.md`++Add the following to the Runtime Context section:++```+google_ads_dev_token, google_ads_client_id, google_ads_client_secret,+google_ads_refresh_token, google_ads_customer_id, google_ads_login_customer_id+```++Add `### Google Ads` credential resolution block after the existing credential blocks:++```bash+# 6-variable cascade: preferences.json → env → Doppler+GADS_DEV_TOKEN="${google_ads_dev_token:-${GOOGLE_ADS_DEV_TOKEN:-$(doppler secrets get GOOGLE_ADS_DEV_TOKEN --plain 2>/dev/null)}}"+GADS_CLIENT_ID="${google_ads_client_id:-${GOOGLE_ADS_CLIENT_ID:-}}"+GADS_CLIENT_SECRET=${google_ads_client_secret:-${GOOGLE_ADS_CLIENT_SECRET:-}}+GADS_REFRESH_TOKEN="${google_ads_refresh_token:-${GOOGLE_ADS_REFRESH_TOKEN:-$(doppler secrets get GOOGLE_ADS_REFRESH_TOKEN --plain 2>/dev/null)}}"+GADS_CUSTOMER_ID="${google_ads_customer_id:-${GOOGLE_ADS_CUSTOMER_ID:-}}"+GADS_LOGIN_CUSTOMER_ID="${google_ads_login_customer_id:-${GOOGLE_ADS_LOGIN_CUSTOMER_ID:-}}"+# Strip dashes from customer ID+GADS_CUSTOMER_ID="${GADS_CUSTOMER_ID//-/}"+```++Add access token refresh:++```bash+# Refresh short-lived access token from refresh token+if [ -n "$GADS_REFRESH_TOKEN" ] && [ -n "$GADS_CLIENT_ID" ]; then+ GADS_ACCESS_TOKEN=$(curl -sf -X POST https://oauth2.googleapis.com/token \+ -d "client_id=${GADS_CLIENT_ID}&client_secret=${GADS_CLIENT_SECRET}&refresh_token=${GADS_REFRESH_TOKEN}&grant_type=refresh_token" \+ | jq -r '.access_token // empty')+fi+GADS_HEADERS=(-H "Authorization: Bearer $GADS_ACCESS_TOKEN" -H "developer-token: $GADS_DEV_TOKEN")+# Add login-customer-id header for MCC accounts+[ -n "$GADS_LOGIN_CUSTOMER_ID" ] && GADS_HEADERS+=(-H "login-customer-id: $GADS_LOGIN_CUSTOMER_ID")+```++Add routing table entry: `google-ads, gads` pointing to `## google-ads` section.++Add `## google-ads` section with credential guard and placeholder for Plans 02+03 sub-commands.++Add `google-ads` to `## setup` auto-scan patterns: `GOOGLE_ADS_*` env vars, shell profile grep, Doppler filter, Dashlane, keychain, Chrome history.++### Task 2: Add Google Ads setup flow to setup/SKILL.md and pre-gather to ops-marketing-dash++**File**: `claude-ops/skills/setup/SKILL.md`++Restructure the marketing service selection AskUserQuestion into two sequential calls (Rule 1: max 4 options per call):+- Call 1: Klaviyo | Meta Ads | Google Ads | More…+- Call 2 (if "More…"): GA4 | Google Search Console++Add `#### Google Ads` sub-section in Step 3j with the following steps:++- **Step A**: Dev token — show auto-scan result if found; AskUserQuestion to keep or reconfigure+- **Step B**: OAuth2 client ID + secret — prompt for Google Cloud Console OAuth credentials+- **Step C**: Browser OAuth flow — launch localhost:8080 redirect server (`run_in_background: true`), construct `accounts.google.com/o/oauth2/auth` URL with `https://www.googleapis.com/auth/adwords` scope, print URL for user to open, capture authorization code from redirect, exchange for refresh token via `oauth2.googleapis.com/token`+- **Step D**: Customer ID discovery — call `listAccessibleCustomers` to enumerate accounts; if multiple, AskUserQuestion to select; auto-detect MCC and set `GADS_LOGIN_CUSTOMER_ID`+- **Step E**: Smoke test — `listAccessibleCustomers` round-trip; print ✓ or error message+- **Step F**: Save to `preferences.json` under `marketing.google_ads.*`++Add `google-ads`, `gads` shortcuts to the setup routing table.++**File**: `claude-ops/bin/ops-marketing-dash`++After the existing credential blocks, add:++```bash+GADS_DEV_TOKEN="..." # 6-variable cascade (same as SKILL.md)+GADS_CUSTOMER_ID="${GADS_CUSTOMER_ID//-/}"+# Doppler fallback for refresh token+[ -z "$GADS_REFRESH_TOKEN" ] && GADS_REFRESH_TOKEN="$(doppler secrets get GOOGLE_ADS_REFRESH_TOKEN --plain 2>/dev/null)"+```++Add `gather_google_ads()` function:+- Guard: if `GADS_REFRESH_TOKEN` or `GADS_DEV_TOKEN` is empty, echo `null` and return+- Refresh access token via `oauth2.googleapis.com/token`+- GAQL `searchStream` query for campaign summary (last 7 days, top 20 by spend, status != REMOVED)+- Include optional `login-customer-id` header for MCC+- Return raw JSON++Add `GADS_DATA=$(gather_google_ads) &` to the parallel execution block.+Add `google_ads: $GADS_DATA` to the final JSON output.++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-10-01-01 | `refresh_token` written to `preferences.json` on disk | Preferences file is `~/.claude/plugins/.../preferences.json`, user-only permissions; document that backup tools should exclude it; never commit the file |+| T-10-01-02 | `localhost:8080` OAuth redirect server left running | Background server receives one request then exits; no persistent listener |+| T-10-01-03 | `access_token` in memory for session duration | Ephemeral, HTTPS-only transport; acceptable for CLI tool context |+| T-10-01-04 | `developer_token` visible in curl command output | Stored in preferences.json / env, never hardcoded in committed files; shell history is user's responsibility |++## Success Criteria (Self-Check)++- [ ] `grep -c "GADS_" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 20+- [ ] `grep "oauth2.googleapis.com/token" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "google-ads" claude-ops/skills/setup/SKILL.md` — PASS+- [ ] `grep "listAccessibleCustomers" claude-ops/skills/setup/SKILL.md` — PASS+- [ ] `grep "gather_google_ads" claude-ops/bin/ops-marketing-dash` — PASS+- [ ] `bash -n claude-ops/bin/ops-marketing-dash` exits 0diff --git a/.planning/phases/phase-10/10-02-PLAN.md b/.planning/phases/phase-10/10-02-PLAN.mdnew file mode 100644index 00000000..94feb1aa--- /dev/null+++ b/.planning/phases/phase-10/10-02-PLAN.md@@ -0,0 +1,153 @@+---+phase: "10-google-ads"+plan: "02"+subsystem: ops-marketing+tags: [google-ads, gaql, searchstream, campaign-dashboard, search-terms, budget-recommendations]+dependency_graph:+ requires: [google-ads-credential-resolution, google-ads-token-refresh]+ provides: [google-ads-dashboard, google-ads-search-terms-report, google-ads-budget-recommendations]+ affects: [ops-marketing/SKILL.md]+---++# Phase 10 Plan 02: Google Ads Read-Only Operations++## Goal++Implement three read-only Google Ads sub-commands in `ops-marketing/SKILL.md`: a campaign performance dashboard (last 7 days), a Search Terms Report with negative keyword candidates (last 30 days), and budget optimization recommendations — all using GAQL `searchStream` with monetary values converted from micros to dollars.++**Prerequisite**: Plan 01 must be complete (credential resolution and token refresh in place).++## Requirements Addressed++- `GADS-01`: Campaign performance dashboard+- `GADS-04`: Search Terms Report with negative keyword candidates+- `GADS-06`: Budget optimization recommendations++## Runtime Prerequisites++Same as Plan 01 — credentials must be configured via `/ops:setup google-ads`.++No additional credentials required for read-only operations.++## Deliverables++### Files to Modify++- `claude-ops/skills/ops-marketing/SKILL.md` — add routing table inside `## google-ads`, implement dashboard, search-terms, and budget-recs sub-commands++## Task Breakdown++### Task 1: Campaign Dashboard sub-command (GADS-01)++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## google-ads` section++Add sub-command routing table immediately after the credential/token guard:++| Input | Action |+|---|---|+| (empty), dashboard, overview | Campaign dashboard — last 7 days |+| search-terms, terms | Search Terms Report — last 30 days |+| budget-recs, recommendations, recs | Budget recommendations |+| campaigns, manage | Plan 03 |+| keywords, kw | Plan 03 |++Implement `### dashboard` sub-command:++**GAQL query** (POST to `https://googleads.googleapis.com/v23/customers/${GADS_CUSTOMER_ID}/googleAds:searchStream`):+```+SELECT campaign.id, campaign.name, campaign.status, campaign_budget.amount_micros,+ metrics.cost_micros, metrics.impressions, metrics.clicks, metrics.conversions,+ metrics.conversions_value+FROM campaign+WHERE segments.date DURING LAST_7_DAYS AND campaign.status != REMOVED+ORDER BY metrics.cost_micros DESC LIMIT 20+```++**Output format** (banner + summary header + per-campaign table):+- Banner: `══ GOOGLE ADS — Last 7 Days ══`+- Summary: Total Spend (`SUM(costMicros)/1e6` via awk), Total Conversions, Overall ROAS (`conversionsValue/spend` with zero-spend guard showing "—")+- Per-campaign table: `Campaign | Status | Budget/day | Spend | Impr | Clicks | CTR | Conv | ROAS`+- All monetary values: `costMicros / 1000000` via `awk printf "%.2f"`+- CTR: `clicks / impressions * 100` with zero-impressions guard+- Empty state: `No active campaigns found in the last 7 days.`+- Error: parse `.[0].error.message`, print with credential hint++**Implementation notes:**+- Use `jq @tsv + while IFS=$'\t' read` pipeline to avoid subshell output loss+- Render table using `printf "%-40s %-10s ..."` column format++### Task 2: Search Terms Report and Budget Recommendations (GADS-04, GADS-06)++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## google-ads` section++**Search Terms sub-command** (GADS-04):++GAQL query on `search_term_view` resource:+```+SELECT search_term_view.search_term, search_term_view.status,+ campaign.name, ad_group.name,+ metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions+FROM search_term_view+WHERE segments.date DURING LAST_30_DAYS AND metrics.impressions > 0+ORDER BY metrics.impressions DESC LIMIT 100+```++Status column mapping: `ADDED` → `✓ Added`, `EXCLUDED` → `✗ Excluded`, `NONE` → `○ New`++Per-term table: `Search Term | Status | Campaign | Ad Group | Impr | Clicks | Cost | Conv`++Negative keyword candidates section using inline `jq select()`:+- Filter: `conversions == 0 AND costMicros > 1000000` (>$1 spend, no conversions)+- Print as bullet list under `Negative keyword candidates:`++Empty state: `No search term data found for the last 30 days.`++**Budget Recommendations sub-command** (GADS-06):++GAQL query on `recommendation` resource:+```+SELECT recommendation.type, recommendation.campaign, recommendation.text,+ recommendation.campaign_budget_recommendation.current_budget_amount_micros,+ recommendation.campaign_budget_recommendation.recommended_budget_amount_micros,+ recommendation.campaign_budget_recommendation.base_metrics.impressions,+ recommendation.campaign_budget_recommendation.potential_metrics.impressions+FROM recommendation+WHERE recommendation.type IN (+ CAMPAIGN_BUDGET, MOVE_UNUSED_BUDGET,+ MARGINAL_ROI_CAMPAIGN_BUDGET, FORECASTING_CAMPAIGN_BUDGET+)+```++Type column human-readable labels:+- `CAMPAIGN_BUDGET` → `Budget Increase`+- `MOVE_UNUSED_BUDGET` → `Reallocate Budget`+- `MARGINAL_ROI_CAMPAIGN_BUDGET` → `Marginal ROI`+- `FORECASTING_CAMPAIGN_BUDGET` → `Forecast Boost`++Per-recommendation table: `Type | Campaign | Current Budget | Recommended | Impact`++Impact: percentage impressions increase `(potentialMetrics.impressions - baseMetrics.impressions) / baseMetrics.impressions * 100`; show `—` if base is 0.++Empty state: `No budget recommendations available. Google needs campaign data to generate recommendations.`++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-10-02-01 | GAQL responses expose campaign names and spend data in terminal | Accepted — terminal output is local; same exposure level as any CLI tool |+| T-10-02-02 | `searchStream` queries on large accounts returning excessive data | Mitigated — `LIMIT 20` on dashboard, `LIMIT 100` on search terms |+| T-10-02-03 | Division by zero in ROAS/CTR calculations | Mitigated — awk guards on all division operations |++## Dependencies++- **Requires**: Plan 01 complete (`GADS_ACCESS_TOKEN` available in `## google-ads` scope)+- **Provides**: `google-ads-dashboard`, `google-ads-search-terms-report`, `google-ads-budget-recommendations`++## Success Criteria (Self-Check)++- [ ] `grep "GOOGLE ADS.*Last 7 Days" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "SEARCH TERMS REPORT" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "BUDGET RECOMMENDATIONS" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep -c "searchStream" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 3+- [ ] `grep "Negative keyword candidates" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "recommendedBudgetAmountMicros" claude-ops/skills/ops-marketing/SKILL.md` — PASSdiff --git a/.planning/phases/phase-10/10-03-PLAN.md b/.planning/phases/phase-10/10-03-PLAN.mdnew file mode 100644index 00000000..8f7f7fb5--- /dev/null+++ b/.planning/phases/phase-10/10-03-PLAN.md@@ -0,0 +1,141 @@+---+phase: "10-google-ads"+plan: "03"+subsystem: ops-marketing+tags: [google-ads, campaign-management, keyword-planner, ad-groups, mutate-api, gaql]+dependency_graph:+ requires: [google-ads-credential-resolution, google-ads-token-refresh, google-ads-dashboard, google-ads-search-terms-report, google-ads-budget-recommendations]+ provides: [google-ads-campaign-management, google-ads-keyword-planner, google-ads-ad-group-management]+ affects: [ops-marketing/SKILL.md, docs/skills-reference.md]+---++# Phase 10 Plan 03: Google Ads Write Operations++## Goal++Implement mutating Google Ads operations in `ops-marketing/SKILL.md`: campaign management (list/create/pause/enable/budget), Keyword Planner (seed-to-ideas with volume/competition/bids), and ad group management (create groups, add/remove/update keywords). All destructive or financial operations gated via AskUserQuestion confirmation (Rule 5). Update skills reference documentation.++**Prerequisite**: Plans 01 and 02 must be complete.++## Requirements Addressed++- `GADS-02`: Campaign management (create, pause, enable, adjust budget)+- `GADS-03`: Keyword Planner — discover keywords with volume and bid data+- `GADS-05`: Ad group management (create groups, add/remove/bid-update keywords)++## Runtime Prerequisites++Same as Plans 01–02. No additional credentials required. All operations use the `campaigns:mutate`, `campaignBudgets:mutate`, `adGroups:mutate`, `adGroupCriteria:mutate`, and `:generateKeywordIdeas` endpoints under the same `googleads.googleapis.com/v23` base URL.++## Deliverables++### Files to Modify++- `claude-ops/skills/ops-marketing/SKILL.md` — replace Plan 02 "see Plan 03" routing placeholder rows with final entries; add campaign management, keyword planner, and ad group sub-sections+- `claude-ops/docs/skills-reference.md` — update `/ops:marketing` entry to include Google Ads; add 6 sub-command rows++## Task Breakdown++### Task 1: Campaign Management sub-commands (GADS-02)++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## google-ads` section++Replace placeholder routing rows with:++| Input | Action |+|---|---|+| campaigns, manage | Campaign management — list, create, pause, enable, adjust budget |+| keywords, kw, keyword-planner | Keyword Planner — discover keywords with volume and bid data |+| ad-groups, ag | Ad group management — list, create, add/remove keywords, adjust bids |++Implement `### campaigns` sub-section:++**List campaigns** (`campaigns` / `campaigns list`):+- GAQL `searchStream` selecting `campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign_budget.amount_micros`+- Output as banner + table: `ID | Name | Status | Type | Budget/day`++**Create campaign** (`campaigns create`):+- AskUserQuestion: campaign name, daily budget (USD), channel type (SEARCH/DISPLAY/SHOPPING/VIDEO)+- Two-step mutate:+ 1. POST to `campaignBudgets:mutate` — create budget resource, capture `results[0].resourceName`+ 2. POST to `campaigns:mutate` — create campaign with `status: PAUSED` (always starts paused for safety), linking the budget resource name+- Print created campaign ID; note that user must manually enable after review++**Pause campaign** (`campaigns pause <ID>`):+- AskUserQuestion confirmation (Rule 5) showing campaign name + ID+- POST to `campaigns:mutate` with `updateMask: "status"`, `status: PAUSED`++**Enable campaign** (`campaigns enable <ID>`):+- No confirmation needed (non-destructive)+- POST to `campaigns:mutate` with `updateMask: "status"`, `status: ENABLED`++**Adjust budget** (`campaigns budget <ID> <AMOUNT_USD>`):+- Fetch current budget resource name via `searchStream` on `campaign_budget` filtered by campaign ID+- AskUserQuestion confirmation (Rule 5) showing old amount → new amount+- POST to `campaignBudgets:mutate` with `updateMask: "amountMicros"`, converting USD to micros (`amount * 1000000`)++### Task 2: Keyword Planner and Ad Group Management (GADS-03, GADS-05)++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## google-ads` section++**Keyword Planner sub-section** (GADS-03):++- Collect seed keywords via AskUserQuestion (comma-separated, split to JSON array)+- POST to `:generateKeywordIdeas` on customer resource+- Defaults: `languageConstants/1000` (English), `geoTargetConstants/2840` (United States); document alternatives for UK/Canada/Australia+- Output table: `Keyword | Avg Monthly Searches | Competition | Low Bid | High Bid`+ - `lowTopOfPageBidMicros` and `highTopOfPageBidMicros` ÷ 1,000,000 → `$X.XX`+ - Sorted by `avgMonthlySearches` descending+- Empty state: `No keyword ideas found for these seeds. Try different or broader keywords.`++**Ad Group Management sub-section** (GADS-05):++- **List ad groups** (`ad-groups list <CAMPAIGN_ID>`): GAQL query filtered by `campaign.id`, status != REMOVED+- **Create ad group** (`ad-groups create <CAMPAIGN_ID>`):+ - AskUserQuestion: name, CPC bid (USD)+ - POST to `adGroups:mutate` with `type: SEARCH_STANDARD`, bid converted to micros+- **List keywords** (`ad-groups keywords <AD_GROUP_ID>`): GAQL on `ad_group_criterion` where type = KEYWORD+- **Add keyword** (`ad-groups add-keyword <AD_GROUP_ID>`):+ - AskUserQuestion: keyword text, match type (Broad/Phrase/Exact → BROAD/PHRASE/EXACT), optional CPC bid+ - POST to `adGroupCriteria:mutate` with create operation+ - Use bash conditional expansion for optional bid field+- **Remove keyword** (`ad-groups remove-keyword <AD_GROUP_ID> <CRITERION_ID>`):+ - AskUserQuestion confirmation (Rule 5)+ - POST to `adGroupCriteria:mutate` with remove operation, resource name `adGroupCriteria/{AD_GROUP_ID}~{CRITERION_ID}`+- **Update bid** (`ad-groups update-bid <AD_GROUP_ID> <CRITERION_ID> <BID_USD>`):+ - POST to `adGroupCriteria:mutate` with `updateMask: "cpcBidMicros"` only+ - Document keyword immutability: text and match type cannot be changed; require remove+recreate++### Task 3: Update skills reference documentation++**File**: `claude-ops/docs/skills-reference.md`++- Update `/ops:marketing` description to include `Google Ads` alongside existing channels+- Add 6 sub-command entries for Google Ads operations with descriptions matching SKILL.md implementation++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-10-03-01 | Campaign budget mutation without review | Mitigated — AskUserQuestion confirmation showing old→new amounts; new campaigns always start PAUSED |+| T-10-03-02 | Keyword removal is irreversible | Mitigated — AskUserQuestion confirmation per Rule 5 before any remove operation |+| T-10-03-03 | Enabling a campaign with unreviewed content | Accepted — budget was already set and reviewed at create time; user is explicitly choosing to enable |+| T-10-03-04 | Excessive keyword additions inflating spend | Accepted — Google Ads API has its own rate limits; plugin adds one keyword at a time |++## Dependencies++- **Requires**: Plans 01 and 02 complete+- **Provides**: `google-ads-campaign-management`, `google-ads-keyword-planner`, `google-ads-ad-group-management`++## Success Criteria (Self-Check)++- [ ] `grep -c "mutate" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 6+- [ ] `grep "generateKeywordIdeas" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep -c "AskUserQuestion" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 2+- [ ] `grep "google-ads" claude-ops/docs/skills-reference.md` returns ≥ 3 matches+- [ ] `grep "campaigns:mutate" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "campaignBudgets:mutate" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "adGroups:mutate" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "adGroupCriteria:mutate" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "Keywords are immutable" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "languageConstants/1000" claude-ops/skills/ops-marketing/SKILL.md` — PASSdiff --git a/.planning/phases/phase-11/11-01-PLAN.md b/.planning/phases/phase-11/11-01-PLAN.mdnew file mode 100644index 00000000..6f221366--- /dev/null+++ b/.planning/phases/phase-11/11-01-PLAN.md@@ -0,0 +1,180 @@+---+phase: "11-meta-ads"+plan: "01"+subsystem: ops-marketing+tags: [meta-ads, facebook-marketing-api, campaigns, ad-sets, creatives, automation-rules, audiences, advantage-plus]+dependency_graph:+ requires: []+ provides: [meta-ads-campaign-management, meta-ads-targeting, meta-ads-creatives, meta-ads-automation-rules, meta-ads-audiences, meta-ads-advantage-plus]+ affects: [ops-marketing/SKILL.md]+---++# Phase 11 Plan 01: Meta Ads Campaign Management++## Goal++Implement Meta Ads campaign management sub-commands in `ops-marketing/SKILL.md`: campaign creation (always PAUSED), ad set targeting, creative assembly, automation rules, audience management (Custom + Lookalike), and Advantage+ Shopping Campaigns. All financial and destructive operations gated via Rule 5 confirmation.++## Requirements Addressed++- Meta Ads campaign management via Facebook Marketing API v19++- All creative and campaign operations start in PAUSED/INACTIVE state for safety review++## Runtime Prerequisites++**STOP — the following credentials must be configured before this plan can execute:**++| Credential | Where to get it |+|---|---|+| `META_ACCESS_TOKEN` | [Meta for Developers](https://developers.facebook.com) → App → Tools → Graph API Explorer → Generate token with `ads_management`, `ads_read`, `pages_read_engagement` permissions; or via System User in Business Manager |+| `META_AD_ACCOUNT_ID` | Meta Business Manager → Accounts → Ad Accounts → Account ID (format `act_XXXXXXXXXX`) |+| `META_APP_ID` | Meta for Developers → App → App ID |+| `META_APP_SECRET` | Meta for Developers → App → Settings → Basic → App Secret |++**Token longevity note:** User access tokens expire in ~60 days. Use a System User token for production (non-expiring). Long-lived tokens obtained via `oauth/access_token?grant_type=fb_exchange_token`.++**API access note:** Standard access for Ads APIs may require app review for production use. Development mode allows testing with limited accounts.++## Deliverables++### Files to Modify++- `claude-ops/skills/ops-marketing/SKILL.md` — add `## meta` campaign management section with create-campaign, target, creative, rules, audiences, advantage sub-commands; credential resolution already wired; extend routing table++## Task Breakdown++### Task 1: Campaign Creation sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## meta` section++Implement `meta create-campaign` sub-command:++- AskUserQuestion: campaign name, objective (OUTCOME_AWARENESS / OUTCOME_TRAFFIC / OUTCOME_ENGAGEMENT / OUTCOME_LEADS / OUTCOME_APP_PROMOTION / OUTCOME_SALES), daily budget (USD), special ad category (NONE / CREDIT / EMPLOYMENT / HOUSING / ISSUES_ELECTIONS_POLITICS)+- POST to `https://graph.facebook.com/v19.0/{META_AD_ACCOUNT_ID}/campaigns`:+ ```json+ {+ "name": "<name>",+ "objective": "<objective>",+ "status": "PAUSED",+ "daily_budget": "<budget_cents>",+ "special_ad_categories": ["<category>"]+ }+ ```+- Always set `"status": "PAUSED"` — never create active campaigns (Rule 5 safety)+- Print created campaign ID; instruct user to create ad sets and enable after review++**Routing table additions** in `## meta`:++| Input | Action |+|---|---|+| create-campaign | Create new campaign (always PAUSED) |+| target \<ADSET_ID\> | Configure ad set targeting |+| creative \<CAMPAIGN_ID\> | Create ad creative and ad |+| rules | Create automation rules |+| audiences | Manage Custom and Lookalike audiences |+| advantage | Create Advantage+ Shopping Campaign |++### Task 2: Ad Set Targeting sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## meta` section++Implement `meta target <ADSET_ID>` sub-command:++- AskUserQuestion (multi-step): geo targeting (countries comma-separated), age min/max (18-65), gender (ALL/MALE/FEMALE), placement device (ALL/MOBILE/DESKTOP), placement positions (feed/stories/reels/search — comma-separated)+- Build targeting spec JSON:+ ```json+ {+ "geo_locations": {"countries": [...]},+ "age_min": N, "age_max": N,+ "genders": [1] or [2] or [],+ "device_platforms": [...],+ "publisher_platforms": ["facebook","instagram"],+ "facebook_positions": [...],+ "instagram_positions": [...]+ }+ ```+- PATCH to `https://graph.facebook.com/v19.0/{ADSET_ID}` with targeting spec+- Require AskUserQuestion confirmation (Rule 5) before applying++### Task 3: Creative Assembly sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## meta` section++Implement `meta creative <CAMPAIGN_ID>` sub-command (two paths):++**Image creative path:**+- AskUserQuestion: image source (URL or local file path), headline, primary text, description, destination URL, call-to-action type+- If local file: multipart POST to `/{META_AD_ACCOUNT_ID}/adimages` to upload, capture `images[].hash`+- If URL: POST to `/{META_AD_ACCOUNT_ID}/adimages?url=<url>`+- Create adcreative: POST to `/{META_AD_ACCOUNT_ID}/adcreatives` with `object_story_spec`+- Create ad: POST to `/{META_AD_ACCOUNT_ID}/ads` linking adset + creative; `status: PAUSED`++**Video creative path:**+- AskUserQuestion: video URL, thumbnail URL, headline, primary text, destination URL+- POST to `/{META_AD_ACCOUNT_ID}/advideos?file_url=<video_url>` (async upload)+- Poll `video_id` status until `ready == true` (max 10 polls, 3s intervals)+- Create adcreative and ad as above with `video_data` instead of `image_data`++### Task 4: Automation Rules sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## meta` section++Implement `meta rules` sub-command:++- AskUserQuestion: rule type (pause-underperformers / scale-winners / custom)+- **Pause underperformers** preset: ROAS < 1.0 for 3 days → pause ad set+- **Scale winners** preset: ROAS > 3.0 → increase budget 20%+- POST to `/{META_AD_ACCOUNT_ID}/adrules_library`+- AskUserQuestion confirmation (Rule 5) before creating any rule; show rule summary++### Task 5: Audience Management sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## meta` section++Implement `meta audiences` sub-command (two modes):++**Custom Audience (website pixel):**+- AskUserQuestion: audience name, pixel ID, rule (all website visitors / specific event / URL contains), lookback window (1-180 days)+- POST to `/{META_AD_ACCOUNT_ID}/customaudiences` with `pixel_rule` JSON++**Lookalike Audience:**+- AskUserQuestion: source audience ID, target country, lookalike size (1-10% of country population)+- POST to `/{META_AD_ACCOUNT_ID}/customaudiences` with `lookalike_spec`+- Note: Lookalike audience takes 1-6 hours to populate++### Task 6: Advantage+ Shopping Campaign sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## meta` section++Implement `meta advantage` sub-command:++- AskUserQuestion: campaign name, daily budget (USD), pixel ID, catalog ID (optional)+- POST to `/{META_AD_ACCOUNT_ID}/campaigns` with `objective: OUTCOME_SALES`, `smart_promotion_type: AUTOMATED_SHOPPING_ADS`, `status: PAUSED`+- Auto-create ad set with `destination_type: WEBSITE`, linking pixel+- Print campaign + ad set IDs; instruct user to add creatives before enabling+- AskUserQuestion confirmation (Rule 5) — note that Advantage+ uses Meta's full automation++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-11-01-01 | Access token with `ads_management` scope has broad account access | Mitigated — use System User token scoped to specific ad account; document minimum required permissions |+| T-11-01-02 | Campaign enable: financial impact without review | Mitigated — all new campaigns/ad sets created with `status: PAUSED`; user must explicitly enable |+| T-11-01-03 | Automation rule creates unintended spend changes | Mitigated — AskUserQuestion confirmation (Rule 5) showing full rule summary before creation |+| T-11-01-04 | Video upload URL leaks in curl command | Accepted — ephemeral S3 signed URL; visible in terminal only |+| T-11-01-05 | Lookalike audience creation uses customer PII indirectly | Accepted — pixel-based source; no PII leaves Meta's systems |++## Dependencies++- **Requires**: Meta Ads credentials configured (existing `## meta` credential resolution in ops-marketing)+- **Provides**: `meta-ads-campaign-management`, `meta-ads-targeting`, `meta-ads-creatives`, `meta-ads-automation-rules`, `meta-ads-audiences`, `meta-ads-advantage-plus`++## Success Criteria (Self-Check)++- [ ] `grep "create-campaign" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep -c "status.*PAUSED" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 3+- [ ] `grep "adrules_library" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "customaudiences" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "OUTCOME_SALES" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep -c "AskUserQuestion" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 5+- [ ] `grep "smart_promotion_type.*AUTOMATED_SHOPPING_ADS" claude-ops/skills/ops-marketing/SKILL.md` — PASSdiff --git a/.planning/phases/phase-12/12-01-PLAN.md b/.planning/phases/phase-12/12-01-PLAN.mdnew file mode 100644index 00000000..2a5b810a--- /dev/null+++ b/.planning/phases/phase-12/12-01-PLAN.md@@ -0,0 +1,156 @@+---+phase: "12-instagram"+plan: "01"+subsystem: ops-marketing+tags: [instagram, instagram-graph-api, publishing, reels, stories, insights, demographics]+dependency_graph:+ requires: [meta-ads-credential-resolution]+ provides: [instagram-post-publish, instagram-reel-publish, instagram-story-publish, instagram-insights, instagram-demographics]+ affects: [ops-marketing/SKILL.md]+---++# Phase 12 Plan 01: Instagram Publishing & Insights++## Goal++Add Instagram publishing and analytics sub-commands to `ops-marketing/SKILL.md` via the Instagram Graph API: publish feed posts, Reels (with async status poll), Stories, retrieve per-post insights, account-level insights, and demographics breakdowns. IG Account ID auto-resolved via `/me/accounts` and cached in plugin config.++## Requirements Addressed++- Instagram content publishing: feed posts, Reels, Stories+- Instagram Insights: per-post and account-level metrics+- Instagram demographics: age/gender and top location breakdowns++## Runtime Prerequisites++**STOP — the following credentials must be configured before this plan can execute:**++| Credential | Where to get it |+|---|---|+| `META_ACCESS_TOKEN` | Same token as Meta Ads — must additionally have `instagram_basic`, `instagram_content_publish`, `instagram_manage_insights` permissions |+| `INSTAGRAM_ACCOUNT_ID` | Auto-resolved via `/me/accounts?fields=instagram_business_account` (Plan caches on first run in plugin config) |+| Facebook Page linked to Instagram | Instagram must be a Professional (Business or Creator) account connected to a Facebook Page in Business Manager |++**Permission note:** `instagram_content_publish` requires app review for production use.++**Rate limit note:** 200 API calls per user per hour. One publish = 2 calls (container create + publish). Plan at ≤ 100 publishes/hour.++## Deliverables++### Files to Modify++- `claude-ops/skills/ops-marketing/SKILL.md` — add `## instagram` section with sub-command routing, INSTAGRAM_ACCOUNT_ID auto-resolution, post/reel/story/insights/account-insights/demographics sub-commands++## Task Breakdown++### Task 1: Credential Resolution and Account ID Auto-Discovery++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## instagram` section preamble++Add `INSTAGRAM_ACCOUNT_ID` resolution:++```bash+INSTAGRAM_ACCOUNT_ID="${instagram_account_id:-${INSTAGRAM_ACCOUNT_ID:-$(claude plugin config get instagram_account_id 2>/dev/null)}}"+if [ -z "$INSTAGRAM_ACCOUNT_ID" ] && [ -n "$META_ACCESS_TOKEN" ]; then+ INSTAGRAM_ACCOUNT_ID=$(curl -sf \+ "https://graph.facebook.com/v19.0/me/accounts?fields=instagram_business_account&access_token=${META_ACCESS_TOKEN}" \+ | jq -r '.data[].instagram_business_account.id // empty' | head -1)+ [ -n "$INSTAGRAM_ACCOUNT_ID" ] && claude plugin config set instagram_account_id "$INSTAGRAM_ACCOUNT_ID" 2>/dev/null+fi+```++Guard: if either token or account ID is empty after auto-discovery, print setup hint and stop.++Sub-command routing table:++| Input | Action |+|---|---|+| post \<IMAGE_URL\> \<CAPTION\> | Publish feed image post |+| reel \<VIDEO_URL\> \<CAPTION\> | Publish Reel (async poll until FINISHED) |+| story \<URL\> | Publish Story (image or video auto-detected) |+| insights \<MEDIA_ID\> | Per-post reach, saves, shares, plays |+| account-insights [days] | Account-level reach + impressions (48h delay note) |+| demographics | Age/gender + top cities/countries |++### Task 2: Publishing Sub-commands (post, reel, story)++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## instagram` section++**Feed Post** (`instagram post <IMAGE_URL> <CAPTION>`):++Two-step publish:+1. Create container: POST `/{INSTAGRAM_ACCOUNT_ID}/media` with `image_url` + `caption`; capture `creation_id`+2. Publish: POST `/{INSTAGRAM_ACCOUNT_ID}/media_publish` with `creation_id`; print media ID++AskUserQuestion confirmation (Rule 5) before publishing — show image URL and caption preview (first 80 chars).++**Reel** (`instagram reel <VIDEO_URL> <CAPTION>`):++1. Create container with `media_type=REELS&video_url=<URL>&caption=<CAPTION>`+2. Poll `/{creation_id}?fields=status_code` until `status_code == "FINISHED"` (max 20 polls, 5s intervals; print progress)+3. Publish when FINISHED; print media ID+4. Error handling: if `status_code == "ERROR"`, print error code + suggest H.264/MP4/720p/60s re-encode++**Story** (`instagram story <URL>`):++Auto-detect media type from URL extension (`.jpg|.png|.gif` → IMAGE, `.mp4|.mov` → VIDEO):+1. Create container with `media_type=STORIES` + appropriate URL field+2. For video: poll until FINISHED (same pattern as Reel)+3. Publish; print media ID+4. Note: Stories expire automatically after 24 hours++### Task 3: Insights Sub-commands (insights, account-insights, demographics)++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## instagram` section++**Per-Post Insights** (`instagram insights <MEDIA_ID>`):++GET `/{MEDIA_ID}/insights?metric=reach,saved,shares,video_views,likes,comments,impressions&access_token=<TOKEN>`++Output banner + metric list:+```+══ POST INSIGHTS ══+Reach: 12,345 Impressions: 18,901+Likes: 432 Comments: 18+Shares: 67 Saves: 89+Video Plays: N/A (image posts)+```++**Account-Level Insights** (`instagram account-insights [days]`):++Default `days=28`. GET `/{INSTAGRAM_ACCOUNT_ID}/insights` with `metric=reach,impressions,profile_views,website_clicks,follower_count`, `period=day`, date range from `days` ago.++Aggregate daily values; note 48-hour data delay in output.++**Demographics** (`instagram demographics`):++GET `/{INSTAGRAM_ACCOUNT_ID}/insights?metric=audience_gender_age,audience_city,audience_country&period=lifetime`++Two output sections:+1. Age/gender table (top 10 rows): `Age Range | Male% | Female%`+2. Top locations: top 5 cities + top 5 countries with percentage++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-12-01-01 | Publishing to wrong Instagram account | Mitigated — INSTAGRAM_ACCOUNT_ID shown in confirmation; AskUserQuestion before every publish |+| T-12-01-02 | Reel poll loop runs indefinitely | Mitigated — max 20 polls (100s timeout); print error and exit on EXPIRED/ERROR status |+| T-12-01-03 | Content published without review | Mitigated — Rule 5 AskUserQuestion with content preview before every publish |+| T-12-01-04 | Rate limit: 200 calls/hr | Accepted — CLI tool is low-volume; document rate limit; no automatic retry loops |+| T-12-01-05 | Demographics data exposed in terminal | Accepted — aggregate data only, no individual PII; local terminal |++## Dependencies++- **Requires**: `META_ACCESS_TOKEN` with Instagram permissions; Instagram Professional account linked to Facebook Page+- **Provides**: `instagram-post-publish`, `instagram-reel-publish`, `instagram-story-publish`, `instagram-insights`, `instagram-account-insights`, `instagram-demographics`++## Success Criteria (Self-Check)++- [ ] `grep "instagram post" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "media_publish" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "status_code.*FINISHED" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "INSTAGRAM_ACCOUNT_ID" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 3+- [ ] `grep "audience_gender_age" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "48.hour delay" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "200.*calls\|rate limit" claude-ops/skills/ops-marketing/SKILL.md` — PASSdiff --git a/.planning/phases/phase-13/13-01-PLAN.md b/.planning/phases/phase-13/13-01-PLAN.mdnew file mode 100644index 00000000..549c92a8--- /dev/null+++ b/.planning/phases/phase-13/13-01-PLAN.md@@ -0,0 +1,255 @@+---+phase: "13-ga4"+plan: "01"+subsystem: ops-marketing+tags: [ga4, google-analytics, realtime, funnel, cohort, audience, pivot, data-api]+dependency_graph:+ requires: []+ provides: [ga4-realtime, ga4-funnel, ga4-cohort, ga4-audience, ga4-pivot]+ affects: [ops-marketing/SKILL.md]+---++# Phase 13 Plan 01: GA4 Advanced Analytics++## Goal++Extend `ops-marketing/SKILL.md` with five advanced GA4 Data API sub-commands beyond the existing basic `ga4` overview: realtime active users + top pages/events, open/closed conversion funnels with completion/abandonment rates, weekly retention cohort grid by device category, async audience creation with status polling, and multi-dimensional channel × device × conversions pivot table.++## Requirements Addressed++- `GA4-01` through `GA4-05`: Advanced analytics surface beyond basic session/user counts++## Runtime Prerequisites++**STOP — the following credentials must be configured before this plan can execute:**++| Credential | Where to get it |+|---|---|+| `GA4_PROPERTY_ID` | GA4 Admin → Property Settings → Property ID (numeric, e.g. `123456789`) |+| `GA4_SERVICE_ACCOUNT_KEY` | Google Cloud Console → IAM → Service Accounts → create key (JSON format) for a service account granted `Viewer` role on the GA4 property; path stored in `preferences.json` as `analytics.ga4.service_account_key_path` |++**Alternative credential**: OAuth2 user token with `analytics.readonly` scope (same pattern as Google Ads OAuth — can reuse setup wizard pattern from Phase 10).++**API access note:** GA4 Data API v1beta is GA (stable). The v1alpha `runFunnelReport` and `createAudienceExport` endpoints are in Alpha — they require whitelisting for production. Document this limitation in the funnel and audience sub-commands.++## Deliverables++### Files to Modify++- `claude-ops/skills/ops-marketing/SKILL.md` — extend existing `## ga4` section with 5 new sub-command routes (realtime, funnel, cohort, audience, pivot); add authentication preamble for service account JWT flow++## Task Breakdown++### Task 0: GA4 Authentication Preamble++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## ga4` section preamble++Add service account JWT authentication (or fall through to OAuth token if already set):++```bash+GA4_PROPERTY_ID="${ga4_property_id:-${GA4_PROPERTY_ID:-}}"+GA4_KEY_PATH="${ga4_service_account_key_path:-${GOOGLE_APPLICATION_CREDENTIALS:-}}"++if [ -n "$GA4_ACCESS_TOKEN" ]; then+ : # already set (e.g. OAuth path)+elif [ -n "$GA4_KEY_PATH" ] && [ -f "$GA4_KEY_PATH" ]; then+ # Service account: generate JWT → exchange for access token+ GA4_ACCESS_TOKEN=$(python3 -c "+import json, time, base64, hashlib, hmac, urllib.request, urllib.parse+# ... JWT generation using RS256 from key file+# scope: https://www.googleapis.com/auth/analytics.readonly+" 2>/dev/null)+fi+```++Credential guard: if `GA4_PROPERTY_ID` or `GA4_ACCESS_TOKEN` empty, print setup hint and stop.++Extended routing table:++| Input | Action |+|---|---|+| (existing) overview / (empty) | Basic sessions, users, conversions |+| realtime | Active users (last 30 min) + top pages/events |+| funnel \<EVENT1,EVENT2,...\> | Open funnel with completion + abandonment rates |+| cohort [weeks] | Weekly retention cohort grid by device |+| audience \<AUDIENCE_NAME\> | Create audience export + poll status |+| pivot | Channel × device × conversions pivot |++### Task 1: Realtime Sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## ga4` section++POST to `https://analyticsdata.googleapis.com/v1beta/properties/{GA4_PROPERTY_ID}:runRealtimeReport`:++```json+{+ "dimensions": [{"name": "unifiedPagePathScreen"}],+ "metrics": [{"name": "activeUsers"}],+ "minuteRanges": [{"name": "last30min", "startMinutesAgo": 30, "endMinutesAgo": 0}],+ "limit": 10+}+```++Second call for top events (same minuteRange, dimension `eventName`, metric `eventCount`, limit 10).++Output:+```+══ REALTIME — Active Users Last 30 Min ══+Active Users: 247++Top Pages:+ /pricing 89 users+ /docs 45 users+ ...++Top Events:+ page_view 312+ scroll 198+ ...+```++### Task 2: Funnel Sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## ga4` section++Collect funnel steps via AskUserQuestion (comma-separated GA4 event names, e.g. `session_start,view_item,add_to_cart,purchase`).++POST to `https://analyticsdata.googleapis.com/v1alpha/properties/{GA4_PROPERTY_ID}:runFunnelReport`:++```json+{+ "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],+ "funnelDefinition": {+ "steps": [+ {"name": "Step 1", "filterExpression": {"funnelEventFilter": {"eventName": "session_start"}}},+ ...+ ]+ }+}+```++Output: per-step table showing users, completion rate vs. previous step, abandonment rate.++```+══ FUNNEL ANALYSIS — Last 30 Days ══+Step Users Completion Abandonment+session_start 45,231 — —+view_item 12,890 28.5% 71.5%+add_to_cart 3,412 7.5% 73.5%+purchase 891 2.0% 73.9%+```++Alpha API note: print warning if `v1alpha` returns 403 — link to GA4 alpha whitelist request.++### Task 3: Cohort Retention Sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## ga4` section++AskUserQuestion: number of weeks (default 6).++POST to `/v1beta/properties/{GA4_PROPERTY_ID}:runReport` with cohort spec:++```json+{+ "cohortSpec": {+ "cohorts": [/* one per week for last N weeks */],+ "cohortsRange": {"granularity": "WEEKLY", "startOffset": 0, "endOffset": N},+ "cohortReportSettings": {"accumulate": false}+ },+ "dimensions": [+ {"name": "cohort"},+ {"name": "cohortNthWeek"},+ {"name": "deviceCategory"}+ ],+ "metrics": [{"name": "cohortActiveUsers"}, {"name": "cohortTotalUsers"}]+}+```++Render weekly retention grid:++```+══ WEEKLY RETENTION COHORT ══+Cohort (Week) W0 W1 W2 W3 W4+2026-W01 100% 28.3% 18.1% 12.4% 9.2%+2026-W02 100% 31.2% 19.8% 13.1% —+...+```++### Task 4: Audience Export Sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## ga4` section++AskUserQuestion: audience name, dimension for export (e.g. `city`, `deviceCategory`).++POST to `https://analyticsdata.googleapis.com/v1alpha/properties/{GA4_PROPERTY_ID}/audienceExports`:++```json+{+ "audience": "properties/{GA4_PROPERTY_ID}/audiences/<AUDIENCE_ID>",+ "dimensions": [{"dimensionName": "<dimension>"}]+}+```++Poll `audienceExports/{exportId}:query` until `state == "ACTIVE"` (max 12 polls, 5s intervals). Once active, run query and display row count + sample rows.++Print note: Audience Export requires an audience to already exist in GA4 Admin. Document how to get audience IDs.++### Task 5: Pivot Sub-command++**File**: `claude-ops/skills/ops-marketing/SKILL.md` → `## ga4` section++POST to `/v1beta/properties/{GA4_PROPERTY_ID}:runPivotReport`:++```json+{+ "dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],+ "dimensions": [+ {"name": "sessionDefaultChannelGrouping"},+ {"name": "deviceCategory"}+ ],+ "metrics": [+ {"name": "sessions"},+ {"name": "conversions"},+ {"name": "totalRevenue"}+ ],+ "pivots": [+ {"fieldNames": ["sessionDefaultChannelGrouping"], "limit": 6},+ {"fieldNames": ["deviceCategory"], "limit": 3}+ ]+}+```++Render as cross-tab table with channel rows × device columns, showing conversions per cell:++```+══ PIVOT: Channel × Device × Conversions ══+Channel Desktop Mobile Tablet Total+Organic Search 1,234 891 123 2,248+Paid Search 456 312 45 813+Direct 234 567 34 835+...+```++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-13-01-01 | Service account key file on disk | Mitigated — path stored in prefs, file is user-owned; never committed; document backup exclusion |+| T-13-01-02 | v1alpha endpoints deprecated without notice | Documented — funnel and audience print alpha warning; note GA4 stable alternatives where available |+| T-13-01-03 | Cohort query on large properties may timeout | Mitigated — GA4 API has built-in 10-minute quota; no additional mitigation needed |+| T-13-01-04 | Audience export reveals user cohort info in terminal | Accepted — aggregate data only; no individual user PII; local terminal |++## Dependencies++- **Requires**: GA4 credentials configured (service account key or OAuth token); GA4 property with data+- **Provides**: `ga4-realtime`, `ga4-funnel`, `ga4-cohort`, `ga4-audience`, `ga4-pivot`++## Success Criteria (Self-Check)++- [ ] `grep "runRealtimeReport" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "runFunnelReport" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "cohortNthWeek" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "audienceExports" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "runPivotReport" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "v1alpha" claude-ops/skills/ops-marketing/SKILL.md` — PASS (alpha warning documented)+- [ ] `grep "GA4_PROPERTY_ID" claude-ops/skills/ops-marketing/SKILL.md` returns ≥ 5diff --git a/.planning/phases/phase-14/14-01-PLAN.md b/.planning/phases/phase-14/14-01-PLAN.mdnew file mode 100644index 00000000..3fb1e06a--- /dev/null+++ b/.planning/phases/phase-14/14-01-PLAN.md@@ -0,0 +1,238 @@+---+phase: "14-whatsapp-business"+plan: "01"+subsystem: ops-whatsapp-biz+tags: [whatsapp-business, waba, cloud-api, templates, catalog, setup]+dependency_graph:+ requires: []+ provides: [whatsapp-biz-template-send, whatsapp-biz-template-management, whatsapp-biz-catalog, whatsapp-biz-setup]+ affects: [skills/ops-whatsapp-biz/SKILL.md, skills/setup/SKILL.md]+---++# Phase 14 Plan 01: WhatsApp Business API++## Goal++Create a new `skills/ops-whatsapp-biz/SKILL.md` skill for the WhatsApp Business Cloud API (Meta Graph API), distinct from `wacli` personal WhatsApp. Implement approved template sends (single + bulk), template management (list/create/check status), product catalog viewer, and a guided setup wizard sub-flow integrated into `/ops:setup`. This is business-to-customer messaging at scale — not personal chat.++## Requirements Addressed++- WhatsApp Business Cloud API integration for outbound marketing and transactional messages+- Template management lifecycle (create → approval → send)+- Product catalog integration++## Runtime Prerequisites++**STOP — the following credentials must be configured before this plan can execute:**++| Credential | Where to get it |+|---|---|+| `WABA_TOKEN` | Meta Business Manager → WhatsApp → API Setup → Access Token (Permanent System User token recommended; temp tokens expire in 24h) |+| `WABA_PHONE_ID` | Meta Business Manager → WhatsApp → API Setup → Phone Number ID (numeric) |+| `WABA_ACCOUNT_ID` | Meta Business Manager → WhatsApp → Overview → WhatsApp Business Account ID |++**Account requirements:**+- WhatsApp Business Account (WABA) verified with Meta+- Phone number verified and registered in the WABA+- For production sends: business verification completed with Meta+- Templates must be pre-approved by Meta (2-24h review time) before sending++**Pricing note:** WhatsApp Business API charges per conversation, not per message. Marketing conversations: ~$0.0125/conversation (US). Display pricing note on send operations.++**Separate from wacli:** This skill uses the WhatsApp Business Cloud API (`graph.facebook.com/v19.0/{phone-number-id}/messages`). The personal `wacli` uses whatsmeow bridge. Different credentials, different phone numbers, different use cases. Never conflate the two.++## Deliverables++### Files to Create++- `claude-ops/skills/ops-whatsapp-biz/SKILL.md` — new skill: credential resolution, sub-command routing, send-template, list-templates, create-template, check-template, catalog, setup sub-commands++### Files to Modify++- `claude-ops/skills/setup/SKILL.md` — add WhatsApp Business API setup sub-flow in Step 3 marketing section++## Task Breakdown++### Task 1: Create ops-whatsapp-biz/SKILL.md skeleton + credential resolution++**File**: `claude-ops/skills/ops-whatsapp-biz/SKILL.md` (new)++YAML frontmatter:+```yaml+---+name: ops-whatsapp-biz+description: WhatsApp Business Cloud API — send approved template messages at scale, manage templates with approval tracking, and integrate product catalogs. Separate from wacli personal WhatsApp.+argument-hint: '[send-template|list-templates|create-template|check-template|catalog|setup]'+allowed-tools: [Bash, Read, Write, Grep, AskUserQuestion]+effort: medium+maxTurns: 30+---+```++**Key difference section** explaining separation from wacli (prominent, at top).++**Credential resolution** (3-tier: plugin config → env → Doppler):+```bash+PREFS_PATH="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"+WABA_TOKEN="${WHATSAPP_BUSINESS_TOKEN:-$(claude plugin config get whatsapp_business_token 2>/dev/null)}"+WABA_PHONE_ID="${WHATSAPP_PHONE_NUMBER_ID:-$(claude plugin config get whatsapp_phone_number_id 2>/dev/null)}"+WABA_ACCOUNT_ID="${WHATSAPP_BUSINESS_ACCOUNT_ID:-$(claude plugin config get whatsapp_business_account_id 2>/dev/null)}"+# Doppler fallbacks+[ -z "$WABA_TOKEN" ] && WABA_TOKEN="$(doppler secrets get WHATSAPP_BUSINESS_TOKEN --plain 2>/dev/null)"+[ -z "$WABA_PHONE_ID" ] && WABA_PHONE_ID="$(doppler secrets get WHATSAPP_PHONE_NUMBER_ID --plain 2>/dev/null)"+[ -z "$WABA_ACCOUNT_ID" ] && WABA_ACCOUNT_ID="$(doppler secrets get WHATSAPP_BUSINESS_ACCOUNT_ID --plain 2>/dev/null)"+```++Credential guard: if `WABA_TOKEN` or `WABA_PHONE_ID` empty, print setup hint and stop.++Sub-command routing table:++| Input | Action |+|---|---|+| (empty), list-templates | List all templates with approval status |+| send-template | Send an approved template message |+| create-template | Guided template creation wizard |+| check-template \<NAME\> | Poll approval status for a template |+| catalog | View linked product catalog |+| setup | Configure WhatsApp Business credentials |++### Task 2: Template Listing and Sending++**File**: `claude-ops/skills/ops-whatsapp-biz/SKILL.md`++**List Templates** (`list-templates` / empty):++GET `https://graph.facebook.com/v19.0/{WABA_ACCOUNT_ID}/message_templates?fields=name,status,category,language,components&access_token={WABA_TOKEN}`++Output table:+```+══ WHATSAPP TEMPLATES ══+Name Category Language Status+order_confirmation UTILITY en ✓ APPROVED+promo_offer MARKETING en ✗ REJECTED+shipping_update UTILITY nl … PENDING+```++Status mapping: `APPROVED` → `✓ APPROVED`, `REJECTED` → `✗ REJECTED`, `PENDING` → `… PENDING`, `DELETED` → `— DELETED`++Pricing note printed after table: `Note: WA Business API charges per conversation (~$0.0125 marketing, ~$0.005 utility, US).`++**Send Template** (`send-template`):++AskUserQuestion (multi-step):+- Step 1: template name (must be in APPROVED state)+- Step 2: recipient phone number(s) — single number or comma-separated list for bulk+- Step 3: template variable values (if template has `{{1}}`, `{{2}}` parameters — parse components from list-templates first)++For single send: POST to `/{WABA_PHONE_ID}/messages`:+```json+{+ "messaging_product": "whatsapp",+ "to": "<phone_e164>",+ "type": "template",+ "template": {+ "name": "<template_name>",+ "language": {"code": "en"},+ "components": [{"type": "body", "parameters": [{"type": "text", "text": "<value>"}]}]+ }+}+```++For bulk (comma-separated phones):+- AskUserQuestion confirmation (Rule 5): show recipient count + cost estimate (`count × $0.0125`)+- Loop sends with 100ms delay between each to avoid rate limits++Print message ID for each successful send.++### Task 3: Template Creation and Status Checking++**File**: `claude-ops/skills/ops-whatsapp-biz/SKILL.md`++**Create Template** (`create-template`) — guided wizard:++AskUserQuestion sequence:+- Template name (lowercase, underscores, max 512 chars)+- Category: UTILITY / MARKETING / AUTHENTICATION+- Language code (en / nl / es / de / fr — show common list)+- Header (optional): TEXT / IMAGE / VIDEO / DOCUMENT+- Body text (required): enter template text with `{{N}}` placeholders for variables+- Footer (optional): short text+- Buttons (optional): QUICK_REPLY / URL / PHONE_NUMBER++POST to `/{WABA_ACCOUNT_ID}/message_templates`:+```json+{+ "name": "<name>",+ "category": "<CATEGORY>",+ "language": "<code>",+ "components": [...]+}+```++Print template ID; note 2-24h review time. Run `check-template <name>` to monitor.++**Check Template Status** (`check-template <NAME>`):++GET `/{WABA_ACCOUNT_ID}/message_templates?name=<NAME>&fields=name,status,rejected_reason`++Print current status + reason if rejected:+```+Template: order_confirmation+Status: ✓ APPROVED+Language: en+```+If REJECTED: print `Rejected reason: <reason>` and suggest edits.++### Task 4: Product Catalog Sub-command++**File**: `claude-ops/skills/ops-whatsapp-biz/SKILL.md`++GET `https://graph.facebook.com/v19.0/{WABA_ACCOUNT_ID}?fields=message_template_namespace` to confirm linked Business Manager.++GET `/{catalog_id}/products?fields=retailer_id,name,price,currency,availability,condition&limit=20`++(Catalog ID resolved from Business Manager if not cached.)++Output table: `SKU | Name | Price | Currency | Availability | Condition`++Note: Catalog must be linked in Meta Commerce Manager. Suggest `meta catalog` for full catalog management.++### Task 5: Add WhatsApp Business setup sub-flow to setup/SKILL.md++**File**: `claude-ops/skills/setup/SKILL.md`++Add `#### WhatsApp Business API` sub-section in Step 3 (distinct from wacli personal WhatsApp):++- Step A: Explain difference from personal wacli+- Step B: WABA Token — AskUserQuestion (keep auto-scan result or reconfigure)+- Step C: Phone Number ID — from API Setup page+- Step D: WABA Account ID — from Overview page+- Step E: Smoke test — GET `/{WABA_ACCOUNT_ID}/message_templates` returns ≥ 0 templates+- Step F: Save to `preferences.json` under `whatsapp_business.*`++Add `whatsapp-biz`, `waba` shortcuts to setup routing table.++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-14-01-01 | Bulk send to unintended recipient list | Mitigated — AskUserQuestion (Rule 5) shows count + cost before bulk; requires explicit confirmation |+| T-14-01-02 | WABA Token in env/preferences has broad account access | Mitigated — use Permanent System User token scoped to WABA; store in preferences.json not source |+| T-14-01-03 | Sending unapproved template causes account suspension | Mitigated — skill checks template status before send; refuses to send non-APPROVED templates |+| T-14-01-04 | Message costs accumulate without visibility | Mitigated — cost estimate displayed before every send; pricing note on template list |+| T-14-01-05 | Conflation with wacli causing wrong account sends | Mitigated — prominent "Key difference" section at top of skill; separate credential variables |++## Dependencies++- **Requires**: WhatsApp Business Account (WABA) verified with Meta; at least one approved template to test sends+- **Provides**: `whatsapp-biz-template-send`, `whatsapp-biz-template-management`, `whatsapp-biz-catalog`, `whatsapp-biz-setup`++## Success Criteria (Self-Check)++- [ ] `claude-ops/skills/ops-whatsapp-biz/SKILL.md` exists and passes `bash -n` (after stripping SKILL frontmatter)+- [ ] `grep "WABA_TOKEN" claude-ops/skills/ops-whatsapp-biz/SKILL.md` returns ≥ 3+- [ ] `grep "messaging_product.*whatsapp" claude-ops/skills/ops-whatsapp-biz/SKILL.md` — PASS+- [ ] `grep "message_templates" claude-ops/skills/ops-whatsapp-biz/SKILL.md` returns ≥ 3+- [ ] `grep "cost estimate" claude-ops/skills/ops-whatsapp-biz/SKILL.md` — PASS+- [ ] `grep "whatsapp-biz\|waba" claude-ops/skills/setup/SKILL.md` — PASS+- [ ] `grep "Separate from wacli\|personal WhatsApp" claude-ops/skills/ops-whatsapp-biz/SKILL.md` — PASSdiff --git a/.planning/phases/phase-15/15-01-PLAN.md b/.planning/phases/phase-15/15-01-PLAN.mdnew file mode 100644index 00000000..18fd0222--- /dev/null+++ b/.planning/phases/phase-15/15-01-PLAN.md@@ -0,0 +1,222 @@+---+phase: "15-cross-platform-intelligence"+plan: "01"+subsystem: ops-marketing+tags: [cross-platform, blended-roas, attribution, marketing-intelligence, marketing-optimizer-agent, ops-go]+dependency_graph:+ requires: [google-ads-credential-resolution, meta-ads-credential-resolution, instagram-insights, ga4-realtime, whatsapp-biz-template-send]+ provides: [cross-platform-optimize, cross-platform-attribution, cross-platform-campaigns, blended-roas-dashboard, ops-go-marketing-section]+ affects: [ops-marketing/SKILL.md, agents/marketing-optimizer.md, bin/ops-marketing-dash, skills/ops-go/SKILL.md]+---++# Phase 15 Plan 01: Cross-Platform Marketing Intelligence++## Goal++Stitch together the per-platform integrations built in Phases 10–14 into a unified intelligence layer: a new `marketing-optimizer` sub-agent (claude-sonnet model) that computes blended ROAS and recommends budget shifts, a cross-platform `attribution` sub-command, a unified `campaigns` view across Google Ads + Meta + Klaviyo, a blended ROAS + health score in the dashboard script, and a MARKETING section in the `/ops:go` morning briefing.++**Prerequisite**: Phases 10–14 must be complete (credential blocks and gather functions in place).++## Requirements Addressed++- Cross-platform marketing intelligence synthesis+- Blended ROAS computation across Google Ads + Meta Ads+- Budget shift recommendations based on platform performance differential+- Morning briefing integration via `/ops:go`++## Runtime Prerequisites++No new credentials required. This phase assembles data from channels already configured in Phases 10–14. All channel data is optional — missing channels show as `null` in output, and the optimizer gracefully handles partial configurations.++## Deliverables++### Files to Create++- `claude-ops/agents/marketing-optimizer.md` — new sub-agent: reads ops-marketing-dash JSON, computes blended ROAS, produces budget recommendations++### Files to Modify++- `claude-ops/skills/ops-marketing/SKILL.md` — add `optimize` sub-command (dispatches marketing-optimizer agent), `attribution` sub-command (side-by-side table), extend `campaigns` sub-command to include Google Ads alongside Meta + Klaviyo+- `claude-ops/bin/ops-marketing-dash` — add Instagram gather, compute blended ROAS, compute 0-100 health score + status string+- `claude-ops/skills/ops-go/SKILL.md` — add MARKETING section to morning briefing (health score + blended ROAS + top action)++## Task Breakdown++### Task 1: Create marketing-optimizer agent++**File**: `claude-ops/agents/marketing-optimizer.md` (new)++YAML frontmatter:+```yaml+---+name: marketing-optimizer+description: Cross-platform ad budget optimization — reads Meta + Google Ads data, computes blended ROAS, and recommends specific budget shifts.+model: sonnet+---+```++**Agent instructions:**++Purpose: analyze ad performance across Meta Ads and Google Ads, compute blended ROAS, produce actionable budget recommendations.++**Input**: read pre-gathered data from ops-marketing-dash:+```bash+"${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/ops-ops-marketplace}/bin/ops-marketing-dash" 2>/dev/null+```++**JSON schema** that ops-marketing-dash v1.5+ emits (document fully):+- `meta` — account totals (last 7 days): `spend`, `impressions`, `clicks`, `ctr`, `purchases`, `purchase_value`, `roas` (all strings)+- `google_ads` — raw searchStream response (array of pages) or `null` if unconfigured+- `klaviyo` — `subscribers`, `last_campaign`, `last_campaign_status`, `open_rate`+- `ga4` — `sessions`, `users`, `conversions`, `revenue`, `cvr`+- `gsc` — `clicks`, `impressions`, `ctr`, `avg_position`+- `instagram` — `followers`, `media_count`, `reach_7d`+- Top-level: `blended_roas`, `health_score`, `health_status`, `date`++**Data extraction helpers** using null-safe jq:+- Google Ads spend: `(if type=="array" then [.[].results[]?.metrics.costMicros // "0" | tonumber] | add // 0 else 0 end) / 1000000`+- Google Ads conversions_value: same pattern with `conversionsValue`++**Analysis logic** (agent applies this reasoning):+1. Compute platform ROAS: `meta.roas` (already computed), Google ROAS from raw data+2. Compute blended ROAS: `(meta_spend * meta_roas + google_spend * google_roas) / (meta_spend + google_spend)`+3. Identify imbalance: if one platform ROAS > 20% above blended, recommend shifting budget toward it+4. Threshold: only recommend shifts > $50/day; include specific dollar amounts+5. Consider channel saturation: large share of budget on one platform may hit diminishing returns++**Output format**: structured recommendation with:+- Blended ROAS summary+- Per-platform performance table+- Specific budget shift recommendations (if any): `Move $X/day from Meta → Google Ads (Meta ROAS: 1.8x, Google ROAS: 3.2x)`+- Warning if total paid spend < $100/day (insufficient data for recommendations)++### Task 2: Add optimize and attribution sub-commands to ops-marketing/SKILL.md++**File**: `claude-ops/skills/ops-marketing/SKILL.md`++Add to routing table:+| Input | Action |+|---|---|+| optimize | Dispatch marketing-optimizer agent with unified data |+| attribution | Cross-platform attribution side-by-side table |++**optimize sub-command:**+```bash+claude --agent marketing-optimizer+```+(agent reads ops-marketing-dash data autonomously)++**attribution sub-command:**++Gather data from all configured channels in parallel (same pattern as ops-marketing-dash), then render side-by-side table:++```+══ ATTRIBUTION COMPARISON — Last 7 Days ══+Metric Meta Ads Google Ads Klaviyo GA4+Spend $1,234 $567 $89/mo —+Sessions 12,890 8,934 3,412 24,236+Conversions 89 45 12 156+Revenue $4,501 $3,201 $1,890 $9,592+ROAS 3.6x 5.6x — —+```++Each cell shows `—` for channels not configured or metrics not applicable.++**campaigns sub-command** (extend existing):++Add Google Ads campaign rows to existing `campaigns` view:+- Existing: Meta campaigns + Klaviyo campaigns+- Add: Google Ads campaigns (from searchStream, top 5 by spend)+- Label each row with channel prefix: `[META]`, `[GOOGLE]`, `[KV]`+- Sort all rows by spend descending++### Task 3: Extend ops-marketing-dash with Instagram gather, blended ROAS, health score++**File**: `claude-ops/bin/ops-marketing-dash`++**Instagram gather function** (`gather_instagram`):+- Credential guard: if `META_ACCESS_TOKEN` or `INSTAGRAM_ACCOUNT_ID` empty, return `null`+- GET `/{INSTAGRAM_ACCOUNT_ID}?fields=followers_count,media_count&access_token=<TOKEN>`+- GET `/{INSTAGRAM_ACCOUNT_ID}/insights?metric=reach&period=day&since=7daysAgo&until=today`+- Aggregate `reach` sum over 7 days+- Return: `{"followers": N, "media_count": N, "reach_7d": N}`++Add `INSTAGRAM_DATA=$(gather_instagram) &` to parallel execution block.++**Blended ROAS computation** (after all gathers complete):+```bash+META_SPEND=$(echo "$META_DATA" | jq -r '.spend // "0"')+META_CONV_VALUE=$(echo "$META_DATA" | jq -r '.purchase_value // "0"')+GOOGLE_SPEND=$(echo "$GADS_DATA" | jq '[.[].results[]?.metrics.costMicros // "0" | tonumber] | add // 0' 2>/dev/null | awk '{printf "%.2f", $1/1000000}')+GOOGLE_CONV_VALUE=$(echo "$GADS_DATA" | jq '[.[].results[]?.metrics.conversionsValue // "0" | tonumber] | add // 0' 2>/dev/null)+TOTAL_SPEND=$(awk "BEGIN{printf \"%.2f\", $META_SPEND + $GOOGLE_SPEND}")+TOTAL_VALUE=$(awk "BEGIN{printf \"%.2f\", $META_CONV_VALUE + $GOOGLE_CONV_VALUE}")+BLENDED_ROAS=$(awk "BEGIN{if ($TOTAL_SPEND > 0) printf \"%.2f\", $TOTAL_VALUE / $TOTAL_SPEND; else print \"0\"}")+```++**Health score computation** (0–100 composite):+- ROAS trend (0–40 pts): blended ROAS ≥ 3.0 → 40, ≥ 2.0 → 30, ≥ 1.5 → 20, ≥ 1.0 → 10, < 1.0 → 0+- Spend efficiency (0–30 pts): CTR ≥ 2% → 30, ≥ 1% → 20, ≥ 0.5% → 10+- Channel diversification (0–30 pts): 3+ channels with spend → 30, 2 channels → 20, 1 channel → 10+- `health_status`: score ≥ 80 → `"EXCELLENT"`, ≥ 60 → `"GOOD"`, ≥ 40 → `"FAIR"`, < 40 → `"POOR"`++Add to final JSON output:+```json+{+ "instagram": ...,+ "blended_roas": "2.84",+ "health_score": 73,+ "health_status": "GOOD",+ "date": "..."+}+```++### Task 4: Add MARKETING section to ops-go/SKILL.md++**File**: `claude-ops/skills/ops-go/SKILL.md`++Add `### MARKETING` section to morning briefing output (runs ops-marketing-dash in background, shows condensed result):++```bash+MKTG=$(timeout 10 "${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/ops-ops-marketplace}/bin/ops-marketing-dash" 2>/dev/null || echo '{}')+HEALTH_SCORE=$(echo "$MKTG" | jq -r '.health_score // "—"')+HEALTH_STATUS=$(echo "$MKTG" | jq -r '.health_status // "N/A"')+BLENDED_ROAS=$(echo "$MKTG" | jq -r '.blended_roas // "—"')+META_SPEND=$(echo "$MKTG" | jq -r '.meta.spend // "0"')+```++Display in briefing:+```+📊 MARKETING+ Health: 73/100 GOOD Blended ROAS: 2.84x+ Meta spend (7d): $1,234 Google Ads: $567+ ▶ /ops:marketing optimize for budget recommendations+```++`timeout 10` guard prevents marketing data from blocking the morning briefing if APIs are slow.++## Threat Model++| ID | Threat | Mitigation |+|---|---|---|+| T-15-01-01 | Marketing optimizer agent makes spend recommendations without guardrails | Mitigated — agent output is read-only recommendations; no mutating API calls from agent; user must manually apply via campaign management sub-commands |+| T-15-01-02 | ops-marketing-dash in ops-go blocks morning briefing | Mitigated — `timeout 10` guard; briefing shows `—` values if marketing data unavailable |+| T-15-01-03 | Blended ROAS division by zero when no spend | Mitigated — awk guard: `if ($TOTAL_SPEND > 0)` before division; shows `0` otherwise |+| T-15-01-04 | Instagram gather adds latency to dashboard | Mitigated — runs in parallel with other gathers via `&` background job |++## Dependencies++- **Requires**: At least Phases 10 (Google Ads) and existing Meta Ads integration functional; other channels optional+- **Provides**: `cross-platform-optimize`, `cross-platform-attribution`, `cross-platform-campaigns`, `blended-roas-dashboard`, `ops-go-marketing-section`++## Success Criteria (Self-Check)++- [ ] `claude-ops/agents/marketing-optimizer.md` exists+- [ ] `grep "blended_roas" claude-ops/bin/ops-marketing-dash` — PASS+- [ ] `grep "health_score" claude-ops/bin/ops-marketing-dash` — PASS+- [ ] `grep "gather_instagram" claude-ops/bin/ops-marketing-dash` — PASS+- [ ] `grep "attribution" claude-ops/skills/ops-marketing/SKILL.md` — PASS+- [ ] `grep "\[META\]\|\[GOOGLE\]" claude-ops/skills/ops-marketing/SKILL.md` — PASS (cross-channel campaigns view)+- [ ] `grep "MARKETING" claude-ops/skills/ops-go/SKILL.md` — PASS+- [ ] `grep "timeout 10" claude-ops/skills/ops-go/SKILL.md` — PASS (briefing guard)+- [ ] `bash -n claude-ops/bin/ops-marketing-dash` exits 0