Open-source SEO, GEO, and marketing skills for AI agents.
feat: add meta-ads/shared foundation (preamble, math, policy registry)
Yuting Zhonga2bd519a489c
diff --git a/meta-ads/shared/meta-math.md b/meta-ads/shared/meta-math.mdnew file mode 100644index 00000000..2a7e6c34--- /dev/null+++ b/meta-ads/shared/meta-math.md@@ -0,0 +1,148 @@+# Meta Ads Math — Profitability and Performance Calculators++Formulas and interpretation rules used throughout the Meta Ads skills. Load this when a finding needs dollar-denominated impact, profitability framing, or a forecast.++**Priority rule:** When `business-context.json` has `profit_margin` and `aov`, use break-even-based thresholds. Otherwise fall back to account-average heuristics. Never mix the two in a single finding — the framing should be consistent.++Meta is creative-led, paid-social, and bought on impressions, not clicks. CPM is a primary lever (creative quality drives it down); CTR alone is not a goal — landing-page conversion rate and ROAS are.++---++## Core Formulas++```+CPM = (Spend / Impressions) × 1000+CPC = Spend / Link Clicks (link clicks, NOT all clicks)+CTR (link) = Link Clicks / Impressions × 100 (use link CTR, not all-CTR)+Hook Rate = 3-Sec Video Views / Impressions × 100 (video creative)+Hold Rate = ThruPlays / 3-Sec Video Views × 100 (video creative)+CPA = Spend / Results (results = the optimization event)+ROAS = Purchase Conversion Value / Spend (ratio, e.g. 3.5x)+ROAS% = (Purchase Value - Spend) / Spend × 100+Frequency = Impressions / Reach+CVR (LP) = Landing Page Conversions / Landing Page Views × 100+```++**Always disambiguate "CTR" and "clicks" in Meta reports.** Meta surfaces both `clicks (all)` (which counts every click on the ad including profile, like, see-more) and `link clicks` (clicks that send the user to the destination). Optimization decisions use **link** clicks — total clicks are vanity. When pulling from `getInsights`, request `clicks`, `inline_link_clicks`, `cpc`, `ctr`, and the breakdown actions you need; treat `inline_link_clicks` as the real click count.++---++## Profitability Formulas (require margin + AOV)++```+Break-Even ROAS = 1 / Profit Margin+Break-Even CPA = AOV × Profit Margin+Max Profitable CPA = Break-Even CPA (bid up to this, no higher)+Unit Profit = AOV × Profit Margin - CPA+Headroom $ = (Break-Even CPA - Current CPA) × Monthly Conversions+```++**ROAS is the dominant frame for ecom.** Lead-gen and SaaS rely on CPA / CPL. For lead-gen, also compute `Lead-to-Customer Rate × AOV × Profit Margin` if the user has the lead-conversion data — the CPA off the platform is meaningless without a downstream rate.++| Headroom | Framing | Action |+|---|---|---|+| Negative | "Losing $X/month on this ad set" | Pause or restructure immediately |+| $0–$500/mo | "Barely break-even" | Refresh creative; tighten audience before scaling |+| $500–$2,000/mo | "Profitable but tight" | Selective scaling (CBO with cautious increments) |+| > $2,000/mo | "Strong unit economics" | Scale via duplication or +20% budget steps |++---++## LTV:CAC++```+CAC = Total Marketing Spend / New Customers Acquired+LTV = ARPU × Avg Customer Lifespan (or use business-context.json.ltv if set)+LTV:CAC = LTV / CAC+Payback = CAC / (ARPU × Gross Margin) (months to recover CAC)+```++| LTV:CAC | Interpretation |+|---|---|+| <1:1 | Losing money on every customer. Stop scaling immediately |+| 1:1–3:1 | Marginal. Viable only if payback period < 12 months |+| 3:1 | Healthy (SaaS / ecom benchmark) |+| 5:1+ | Under-investing in growth — you can afford to bid higher |++---++## Frequency, Saturation, and Audience Reach++```+Frequency Cap (cold) ≤ 2.0/week before fatigue+Frequency Cap (warm) 2.0–3.5/week is normal for retargeting+Frequency Cap (red flag) > 4.0/week on cold prospecting+Audience Saturation Reach / Estimated Audience Size+```++**Fatigue heuristic:** When a campaign's CPM rises ≥30% week-over-week with no creative change AND frequency > 3.0, the audience is saturated. The fix is fresh creative or a fresh audience — raising budget makes it worse.++**Audience size guidance:**++| Audience Size | Viability | Notes |+|---|---|---|+| < 1M | Too narrow for prospecting | Use as a custom-audience seed for lookalikes only |+| 1M–10M | Lookalike sweet spot | Most LAL 1–3% audiences land here |+| 10M–50M | Healthy interest / behavior cold audience | Allow Meta's algorithm room to optimize |+| > 50M | Broad targeting | Often the best for Advantage+ Shopping campaigns |++---++## Budget Forecasting++```+Projected Spend = Daily Budget × Days in Period+Projected Conversions = Projected Spend / Historical CPA+Projected Revenue = Projected Conversions × AOV+```++Present 3 scenarios, enforcing the **20% scaling rule** — Meta's learning phase resets when you change budget or targeting by more than ~20%, so larger steps cost a relearn:++| Scenario | Weekly Budget Increase | Caveat |+|---|---|---|+| Conservative | +20% | Stays out of significant edit territory; no relearn |+| Moderate | +50% over 3 weeks (+20%, +25%, +25% compounded) | Monitor CPA after each step; expect 3–7 days of noise |+| Aggressive | +100% over 5 weeks | Diminishing returns kick in; expect CPA to rise 15–25% |++Always show the **diminishing returns warning** for aggressive: "Doubling budget rarely doubles conversions on Meta — expect 1.5–1.7x conversions at 2x spend, plus a learning-phase reset that compresses signal for 3–7 days."++---++## MER (Marketing Efficiency Ratio)++```+MER = Total Business Revenue / Total Marketing Spend+```++Use MER when the user wants blended efficiency across Meta + other channels (Google, TikTok, organic). MER captures organic, brand, and retention — so it's higher than paid ROAS and should never be compared directly to in-platform ROAS.++| Industry | Typical MER | Excellent |+|---|---|---|+| Ecommerce | 3–5x | 8x+ |+| DTC subscription | 2–4x | 6x+ |+| Lead-gen B2C | 4–8x | 12x+ |++Meta's reported in-platform ROAS is increasingly higher than MER would suggest because attribution windows have narrowed (default 7-day click + 1-day view) while modeled conversions have grown. Always anchor scaling decisions on MER plus a holdout test where possible.++---++## Usage in Findings++**Before (account-average framing):**+> "Ad set 'LAL 3% — Skincare buyers' has a CPA of $42, which is 150% of account average."++**After (margin-aware framing, requires `margin=0.55`, `aov=$68` from business-context.json):**+> "Ad set 'LAL 3% — Skincare buyers' has CPA $42. Your Break-Even CPA is $37 (AOV $68 × 55% margin) — every conversion from this ad set is unprofitable by ~$5. ROAS is 1.62× vs. a Break-Even ROAS of 1.82×."++**Frequency-aware framing:**+> "Cold prospecting ad set 'LAL 1% — All buyers' is at frequency 4.6 with CPM up 38% week-over-week. The audience is saturated — refresh creative or rotate to a new lookalike seed before raising budget."++---++## Gates++1. **Never compute break-even without verified margin.** If `business-context.json.profit_margin` is missing or marked `inferred_from_template`, label the output "estimated from industry template (±20%)" and ask the user to confirm before any write operation.+2. **Never project conversions more than 2x current spend.** Diminishing returns make linear projections unreliable beyond that on Meta especially, where audience saturation is sharper than on Search.+3. **Never use MER in place of ROAS for individual-ad-set decisions.** MER is a blended portfolio metric; individual ad sets must clear ROAS or CPA targets.+4. **Always cite the attribution window when reporting ROAS.** "ROAS 3.2× (7-day click + 1-day view)" beats "ROAS 3.2×" — the window changes the number.+5. **Frequency > 3.5 with declining CTR is a creative problem, not a budget problem.** Refuse to recommend a budget increase under those conditions.diff --git a/meta-ads/shared/policy-registry.json b/meta-ads/shared/policy-registry.jsonnew file mode 100644index 00000000..652e78df--- /dev/null+++ b/meta-ads/shared/policy-registry.json@@ -0,0 +1,260 @@+{+ "$schema": "policy-registry/v1",+ "description": "Versioned registry of Meta Ads (Facebook + Instagram) policy and behavior assumptions used across toprank meta-ads skills. Each entry tracks a specific assumption, its volatility, verification source, and when it should be re-verified.",+ "last_full_review": "2026-05-01",+ "entries": [+ {+ "id": "meta-object-hierarchy",+ "category": "campaign-structure",+ "rule": "Meta Ads object hierarchy: Ad Account > Campaign > Ad Set > Ad. Objective and budget (when CBO is on) live at the campaign level; budget (when ABO), audience, placements, optimization event, and schedule live at the ad set level; creative lives at the ad level.",+ "volatility": "stable",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/613846972027099",+ "notes": "The hierarchy has been stable for years. Advantage+ Shopping flattens some of this (no manual ad set targeting) but the underlying objects still exist.",+ "stale_after_days": 365+ },+ {+ "id": "meta-metric-definitions",+ "category": "benchmarks",+ "rule": "CPM = (Spend / Impressions) × 1000. CTR (link) = Link Clicks / Impressions × 100. CPC (link) = Spend / Link Clicks. CPA = Spend / Results. ROAS = Purchase Conversion Value / Spend. Frequency = Impressions / Reach.",+ "volatility": "stable",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/235811013522940",+ "notes": "Meta surfaces both 'clicks (all)' and 'inline_link_clicks'. Toprank skills always use link clicks for CTR/CPC because all-clicks include profile/like/see-more clicks that aren't optimization-relevant.",+ "stale_after_days": 365+ },+ {+ "id": "meta-graph-api-stability",+ "category": "campaign-structure",+ "rule": "Meta Marketing API uses the Graph API surface — REST-style endpoints under /act_<account_id>/{campaigns,adsets,ads,insights}, plus per-object endpoints. Field selection is via the `fields` query parameter; insights breakdown via the `breakdowns` parameter.",+ "volatility": "stable",+ "last_verified": "2026-05-01",+ "source": "Meta Marketing API docs",+ "source_url": "https://developers.facebook.com/docs/marketing-apis/",+ "notes": "API versions are released regularly; field availability and naming can shift between versions. The `runScript` sandbox abstracts version selection but new fields require new versions.",+ "stale_after_days": 365+ },+ {+ "id": "ad-creative-character-limits",+ "category": "ad-creative",+ "rule": "Ad creative recommended limits: Primary text 125 chars before truncation (max 2200), Headline 27 chars before truncation (max 40), Description 27 chars (max 30 in feed, used in Audience Network), URL display path optional. Single image ratio 1:1 or 4:5. Reels / Stories video 9:16. Image min 1080x1080.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/ads-guide/",+ "notes": "The hard maximums are stable; the truncation thresholds (visible-without-See-More) shift with placement-layout changes. Always verify current truncation per surface before promising 'fully visible'.",+ "stale_after_days": 180+ },+ {+ "id": "meta-learning-phase",+ "category": "delivery",+ "rule": "An ad set enters Learning when newly created or significantly edited. It exits Learning after ~50 optimization events within ~7 days (the '50 in 7' rule of thumb). Performance during Learning is unstable — do not judge results or stack edits during this period. Significant edits include: targeting change, optimization event change, budget change > ~20%, schedule change, and creative replacement.",+ "volatility": "high",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/112167992830700",+ "notes": "The '50 conversions per ad set in 7 days' threshold is a published Meta heuristic; the underlying delivery system has changed materially with each iteration of Meta's bidding model. A 'Learning Limited' status can also stick after the 7-day window if conversion volume is too low.",+ "stale_after_days": 90+ },+ {+ "id": "meta-attribution-default",+ "category": "attribution",+ "rule": "Default attribution setting is 7-day click + 1-day view (7DC1DV). Available options: 1-day click, 7-day click, 1-day click + 1-day view, 7-day click + 1-day view. Attribution is set at the ad set level. View-through windows ≥ 1 day are no longer offered for new ad sets in some objectives.",+ "volatility": "high",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/458681590974355",+ "notes": "Post-iOS 14 the default narrowed from 28-day click + 1-day view down to 7-day click + 1-day view. Reported ROAS shifted accordingly; longer-window comparisons against pre-2021 numbers are not apples-to-apples.",+ "stale_after_days": 90+ },+ {+ "id": "meta-cbo-vs-abo",+ "category": "campaign-structure",+ "rule": "Campaign Budget Optimization (CBO / Advantage Campaign Budget): budget is set at campaign level and Meta distributes across ad sets in real time, optimizing for total events. Ad Set Budget Optimization (ABO): budget is set per ad set, giving the manager direct control. Meta increasingly defaults to CBO; ABO remains available for testing isolated audiences.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/153514848493595",+ "notes": "CBO is the recommended default for prospecting at scale because it lets Meta's bidding LLM allocate dynamically. ABO is preferred for clean A/B audience tests and for retargeting where you want guaranteed spend per audience.",+ "stale_after_days": 180+ },+ {+ "id": "meta-advantage-plus-shopping",+ "category": "campaign-structure",+ "rule": "Advantage+ Shopping Campaigns (ASC) consolidate prospecting and retargeting into a single campaign with broad targeting. Existing-customer cap (default 15%) controls how much budget can flow to existing customers. ASC tends to outperform manual prospecting at scale but reduces granular control.",+ "volatility": "high",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/3419259681456023",+ "notes": "ASC is rapidly evolving — placements, audience controls, and creative requirements have all changed within the last 12 months. Verify current capabilities before recommending a structure migration.",+ "stale_after_days": 90+ },+ {+ "id": "meta-frequency-fatigue",+ "category": "delivery",+ "rule": "Cold prospecting frequency above ~2.0/week and warm retargeting frequency above ~3.5/week correlate with creative fatigue: rising CPM, falling CTR, falling CVR. The fix is creative refresh or audience rotation — not budget changes.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "industry reports",+ "source_url": null,+ "notes": "Specific thresholds vary by audience size, vertical, and creative format. Video creative fatigues differently from static; UGC fatigues slower than studio. Use the trend (week-over-week CPM rise) more than the absolute number.",+ "stale_after_days": 180+ },+ {+ "id": "meta-audience-overlap-significance",+ "category": "audience",+ "rule": "Audience overlap above ~25% between active ad sets in the same campaign causes the same user to be eligible for multiple bids — Meta self-arbitrates but signal density is split, slowing learning. The Audience Overlap tool reports this. Overlap above ~50% is structurally problematic.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/213871055521091",+ "notes": "Within a campaign, Meta's auction de-duplicates so the user only sees one ad — but the inefficiency is in the LLM's signal allocation, not in waste. Across campaigns, overlap can cause genuine duplicate impressions.",+ "stale_after_days": 180+ },+ {+ "id": "meta-bid-strategies",+ "category": "bidding",+ "rule": "Available bid strategies: Highest Volume (default, no cap), Highest Value (auction value optimization, requires Conversions optimization with value), Cost per Result Goal (formerly Cost Cap — soft target), Bid Cap (hard ceiling — manual only), Minimum ROAS (Target ROAS equivalent for Sales objective).",+ "volatility": "high",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/1619591734742116",+ "notes": "Names and exact behaviors shift with each platform iteration. Cost-per-Result Goal was renamed from Cost Cap; Minimum ROAS replaced Target ROAS in the Sales objective. Verify current naming before guiding a strategy switch.",+ "stale_after_days": 90+ },+ {+ "id": "meta-ios-att-impact",+ "category": "attribution",+ "rule": "Apple's App Tracking Transparency (ATT) limits Meta's ability to attribute conversions on iOS users who decline tracking. Reported conversion volume is supplemented with modeled conversions; modeled conversions can introduce 15–30% variance vs. ground truth. Aggregated Event Measurement (AEM) is the post-ATT measurement framework.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/331612538028890",+ "notes": "Modeling improves over time but the gap to deterministic attribution remains. Always cross-check Meta-reported ROAS against an off-platform truth (Shopify, GA4, internal MMM) before scaling decisions.",+ "stale_after_days": 180+ },+ {+ "id": "meta-pixel-capi-required",+ "category": "tracking",+ "rule": "Meta Pixel + Conversions API (CAPI) deduplicated server-side events are the post-iOS-14 standard. Pixel-only setups lose ~15–25% of events relative to a Pixel + CAPI deployment. Without CAPI, Smart Bidding and lookalikes degrade.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/2861400507613887",+ "notes": "Event Match Quality (EMQ) score in Events Manager indicates how well Meta can match events to users — score below 7.0 means weak signal. Stripe, Shopify, and major CMSes have native CAPI integrations.",+ "stale_after_days": 180+ },+ {+ "id": "meta-creative-volume-recommendation",+ "category": "ad-creative",+ "rule": "Meta's published guidance is to refresh creative every 2–4 weeks for active ad sets, with at least 4–6 distinct creative concepts running concurrently per campaign for the algorithm to optimize. Same creative across multiple aspect ratios (1:1, 4:5, 9:16) counts as one concept, not three.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": null,+ "notes": "The pace varies by spend velocity — a $50/day account can run the same creative for 6+ weeks; a $5,000/day account fatigues a hero ad in 5–7 days. Use frequency trend, not calendar age, as the trigger.",+ "stale_after_days": 180+ },+ {+ "id": "meta-industry-cpm-cpc-benchmarks",+ "category": "benchmarks",+ "rule": "Industry benchmarks (2024–2025 vintage): Ecommerce CPM $9–14 / link CTR 1.0–1.6% / CPA $25–45, DTC subscription CPM $11–16 / CTR 0.9–1.4% / CPA $35–65, Lead-gen B2C CPM $7–11 / CTR 1.2–2.0% / CPA $12–28, B2B SaaS CPM $14–22 / CTR 0.6–1.0% / CPA $80–180. Q4 (Oct–Dec) inflates CPM 30–60%.",+ "volatility": "high",+ "last_verified": "2026-05-01",+ "source": "industry reports",+ "source_url": null,+ "notes": "Based on third-party reports (Varos, Madgicx, Common Thread). CPMs trend upward 8–15% YoY. Q4 inflation is the most reliable seasonal pattern. Adjust 2024–2025 figures upward 10–15% for 2026.",+ "stale_after_days": 90+ },+ {+ "id": "meta-creative-asset-ratios",+ "category": "ad-creative",+ "rule": "Creative aspect ratios — Feed: 1:1 or 4:5 (4:5 dominates mobile feed). Reels / Stories: 9:16 (full-bleed vertical). In-stream video: 16:9. Marketplace: 1:1. Right column (desktop): 1.91:1. Always upload all relevant ratios — Meta serves only the best fit per placement.",+ "volatility": "stable",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/ads-guide/image/facebook-feed",+ "notes": "Placement-by-placement ratio guidance is stable. The mix of placements served can shift with platform redesigns (e.g., Marketplace expansion), but the per-placement ratio doesn't change.",+ "stale_after_days": 365+ },+ {+ "id": "meta-significant-edit-relearn",+ "category": "delivery",+ "rule": "Significant edits trigger a Learning Phase reset: changing the optimization event, audience targeting, attribution window, ad creative, or budget by more than ~20%. Stacking edits within Learning compounds delivery instability — change one variable at a time and wait 3–5 days between edits.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/2331789754920189",+ "notes": "The ~20% budget threshold is a Meta-published heuristic; the actual trigger is opaque. Anecdotally, identical creative re-uploaded under a new ad ID also triggers re-learning. Optimization-event change is the most aggressive reset.",+ "stale_after_days": 180+ },+ {+ "id": "meta-policy-banned-content",+ "category": "policy",+ "rule": "Meta ad policies prohibit before/after imagery for body/health, sensational health claims, attribute targeting that implies a personal characteristic ('Are you struggling with X?'), unrealistic income claims, and most cryptocurrency / financial-product promotion without prior approval. Restricted categories (alcohol, dating, weight-loss) require additional approvals.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Advertising Standards",+ "source_url": "https://transparency.fb.com/policies/ad-standards/",+ "notes": "Personal-attribute policy is the most-violated and most-misunderstood — copy can describe the offering ('a diet plan') but cannot imply you know something about the viewer ('you struggle with weight'). Always cite the specific policy section when flagging a violation.",+ "stale_after_days": 180+ },+ {+ "id": "meta-special-ad-categories",+ "category": "policy",+ "rule": "Special Ad Categories (Credit, Employment, Housing, Social Issues / Elections / Politics) restrict targeting — no age / gender / detailed demographic targeting, geographic targeting limited to ≥15-mile radius. Misclassification or omission of a Special Ad Category is a takedown trigger.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/298000447747885",+ "notes": "If the user's vertical is in a Special Ad Category and they're running standard ads, that's a high-priority audit finding. The set of categories has expanded over time; Social Issues was the most recent addition.",+ "stale_after_days": 180+ },+ {+ "id": "meta-broad-targeting-recommendation",+ "category": "audience",+ "rule": "Meta's current published guidance favors broad targeting (no detailed-targeting layers, age 18–65+, both genders, country-level geo) for prospecting on Sales / Conversions objectives, letting the algorithm find buyers. Detailed targeting interest layers are increasingly redundant with the bidding LLM.",+ "volatility": "high",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": null,+ "notes": "This is a meaningful shift from pre-2022 best practice (narrow lookalikes + interest stacks). Newer accounts under $100/day still benefit from lookalike seeding; mature accounts > $1k/day usually outperform with broad targeting.",+ "stale_after_days": 90+ },+ {+ "id": "meta-creative-fatigue-signals",+ "category": "ad-creative",+ "rule": "Creative fatigue signals (in priority order): (1) link CTR drop ≥30% week-over-week, (2) CPM rise ≥30% week-over-week, (3) frequency > 3.0 with negative trend on (1) or (2), (4) hook rate (3-sec views / impressions) drop on video. The earliest signal usually leads the others by ~3–5 days.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "industry reports",+ "source_url": null,+ "notes": "Watch hook rate first on video creative — it leads CTR by roughly a week. For static, CTR is the primary leading indicator. CPM is a lagging indicator and confirms what CTR / hook already showed.",+ "stale_after_days": 180+ },+ {+ "id": "meta-ab-testing-min-volume",+ "category": "experiments",+ "rule": "Meta's A/B Test tool requires sufficient volume to declare a winner — practically, ≥ ~50 conversions per cell across the test window. Below that volume, prefer a structured creative round-robin (4–6 ads in one ad set, judged by ad-level CTR/CPA after 50+ events each) over a formal A/B test.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "Meta Business Help",+ "source_url": "https://www.facebook.com/business/help/433563588396484",+ "notes": "The platform's confidence calculation requires both volume and a meaningful effect size. The 50/50 traffic split also doubles the time-to-significance vs. running one well-tuned ad set.",+ "stale_after_days": 180+ },+ {+ "id": "meta-cpm-q4-seasonality",+ "category": "benchmarks",+ "rule": "Q4 CPM inflation: November (Black Friday week / Cyber Monday) is the single most expensive impression cohort of the year, typically 60–100% above September baseline. December tapers but stays 30–50% elevated until ~Dec 26. January CPMs collapse 20–30% below September baseline as ecom advertisers pull back.",+ "volatility": "moderate",+ "last_verified": "2026-05-01",+ "source": "industry reports",+ "source_url": null,+ "notes": "Pattern holds across most consumer verticals. B2B and SaaS see milder Q4 inflation (15–30%). DTC ecom should plan creative refresh and budget ramps accordingly — entering Black Friday with fatigued creative is a margin disaster.",+ "stale_after_days": 90+ }+ ]+}diff --git a/meta-ads/shared/preamble.md b/meta-ads/shared/preamble.mdnew file mode 100644index 00000000..713489cd--- /dev/null+++ b/meta-ads/shared/preamble.md@@ -0,0 +1,118 @@+# Meta Ads Shared Preamble++Every meta-ads skill reads this before doing anything else. Handles update checks, MCP detection, config resolution, and onboarding so individual skills don't repeat this logic.++## Step 0: Check for toprank updates++```bash+_UPD_BIN=$(ls ~/.claude/plugins/cache/nowork-studio/toprank/*/bin/toprank-update-check 2>/dev/null | head -1)+[ -n "$_UPD_BIN" ] && _UPD=$("$_UPD_BIN" 2>/dev/null || true) || _UPD=""+[ -n "$_UPD" ] && echo "$_UPD" || true+```++If the output contains `UPGRADE_AVAILABLE <old> <new>`: immediately follow the inline upgrade flow in the `/toprank-upgrade` skill (Step 1 onward) to auto-upgrade. After the upgrade completes, re-read the updated preamble from the new plugin cache and restart from Step 1.++If the output contains `JUST_UPGRADED <old> <new>`: mention "toprank upgraded from v{old} to v{new}" briefly, then continue to Step 1.++If neither: continue to Step 1 silently.++## Step 1: Resolve config++Read config from three locations and merge fields (first non-null, non-empty-string value wins per field):++1. **Project-level** — `.notfair.json` in the repository root+2. **Claude project-level** — `~/.claude/projects/{project-path}/notfair.json`+3. **Global fallback** — `~/.notfair/config.json`++Each file uses the same shared schema. The Meta-specific field is `metaAccountId` — the numeric Meta ad-account id (without the `act_` prefix; the Meta MCP wraps it automatically). This sits alongside `accountId` (Google Ads) in the same config file:++```json+{+ "accountId": "1234567890",+ "metaAccountId": "987654321098765"+}+```++Keeping both platforms in one config file means a user who has run both `/google-ads` and `/meta-ads` doesn't get prompted twice.++The MCP server authenticates via OAuth 2.1 — Claude Code's native HTTP transport opens a browser for sign-in on first use and stores the token in the OS keychain (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux). No API key, no `mcp-remote` bridge.++### Resolved data directory++Data files (business-context, personas, change-log, account-baseline) are stored project-locally when a project-level config exists:++- If `.notfair.json` exists in the current working directory → `{data_dir}` = `.notfair/` (relative to project root)+- Otherwise → `{data_dir}` = `~/.notfair/`++Create `{data_dir}` if it doesn't exist. Ensure `~/.notfair/` also exists (needed for the global config file regardless of `{data_dir}`). Throughout this document and all skills, `{data_dir}` refers to this resolved directory.++**Meta-specific data files** are namespaced under a `meta/` subdirectory — `{data_dir}/meta/business-context.json`, `{data_dir}/meta/personas/{accountId}.json`, `{data_dir}/meta/account-baseline.json` — so they don't collide with the Google Ads equivalents. The `business-context.json` schema is largely shared; the difference is which file the `/meta-ads-audit` skill reads and writes.++**Important:** If using project-local storage (`.notfair/`), ensure `.notfair.json` and `.notfair/` are in the project's `.gitignore` — they contain business-sensitive data that should not be committed.++Continue to Step 2 (MCP detection always runs).++## Step 2: MCP Server Detection++Always verify that a Meta Ads MCP server is available — the MCP server could be down, unauthorized, or misconfigured even with a saved `metaAccountId`.++1. Check for the NotFair Meta tools. The MCP server may be exposed under several different tool-name prefixes depending on the host:+ - `mcp__NotFair-MetaAds__*` / `mcp__notfair_metaads__*` / `mcp__NotFair_MetaAds__*` — Claude Code CLI (toprank plugin default; exact form depends on Claude Code's key sanitization)+ - `mcp__claude_ai_NotFair-MetaAds__*` / `mcp__claude_ai_NotFairMetaAds__*` — Claude Desktop / claude.ai plugin connector+ - any other prefix matching `mcp__.*([Nn]ot[Ff]air[-_]?[Mm]eta[Aa]ds?)__` (future hosts)++ **How to detect:** scan your available tool list for any tool whose name ends in `listAdAccounts` AND whose prefix references Meta (matches the regex above — do not pick a generic `listAdAccounts` from another platform's MCP). Take everything before `listAdAccounts` as the detected prefix. Save the prefix and the result for reuse in Steps 3 and 4.++2. If no NotFair-MetaAds variant exists, check for Meta's official MCP or community Meta MCP servers (any `mcp__.*meta.*ads__listAdAccounts`). If you find one, fall back to it but warn the user that toprank's heuristics are tuned for the NotFair surface (specifically `runScript`'s `ads.graphParallel`).++3. If none exists, guide the user:++> No Meta Ads MCP server detected.+>+> The toprank plugin registers the `NotFair-MetaAds` HTTP MCP server (`https://notfair.co/api/mcp/meta_ads`) in `.mcp.json`. Try restarting Claude Code — on first connection it opens a browser tab for OAuth sign-in to NotFair. You can also trigger sign-in manually with `/mcp`.+>+> If the problem persists, run `/toprank-upgrade` to make sure your plugin includes the Meta server registration, or configure a Meta Ads MCP server manually.++Stop here until the MCP server is available.++If `metaAccountId` was already resolved in Step 1, skip to Step 4. Otherwise, continue to Step 3.++## Step 3: Onboarding (only if metaAccountId is missing)++Use the `listAdAccounts` result from Step 2 (do not call it again):++1. **One ad account** → save automatically to the highest-priority config file that already exists (project > claude-project > global; if none, save to `~/.notfair/config.json`). Save as `metaAccountId` (without the `act_` prefix). Tell the user which was selected.+2. **Multiple accounts** → show a numbered list (id + name + currency + business name where available), ask the user to pick, save the choice.+3. **Zero accounts** → the user signed in successfully but has no Meta ad account on their Business Manager. Tell them:+ > "Your Meta account isn't linked to an ad account yet. Create or claim one in Meta Business Manager (https://business.facebook.com — Business Settings → Ad Accounts). Once it exists and your user has the 'Manage Campaigns' role on it, ask me to refresh and I'll pick it up automatically."+ On retry, call `listAdAccounts` again. If still empty, suggest they check Business Manager permissions — a common cause is being added to the business but not granted ad-account-level access.++### Switching accounts++If the user explicitly asks to switch accounts, run `listAdAccounts`, let them pick, then ask:++> "Save this account for this project only, or globally?"++- **Project** → write `metaAccountId` to `.notfair.json` in the current working directory (create the file if needed, preserving any existing fields like `accountId`)+- **Global** → write `metaAccountId` to `~/.notfair/config.json`++## Step 4: Calling tools++Use whichever MCP server prefix was detected in Step 2:++- **NotFair-MetaAds via Claude Code CLI:** `mcp__NotFair-MetaAds__<toolName>` (or whatever sanitized form the host emits)+- **NotFair-MetaAds via Claude Desktop / claude.ai plugin:** `mcp__claude_ai_NotFair-MetaAds__<toolName>` / `mcp__claude_ai_NotFairMetaAds__<toolName>`++Always call tools under the exact prefix detected in Step 2 — do not hardcode any prefix. The MCP server's `ads.activeAccountId` is the `act_<metaAccountId>` form derived from the saved `metaAccountId` (Step 1). For most tools you do not need to pass the account id explicitly (the server resolves it from the OAuth session); when a tool does take an `adAccountId` argument, pass `act_<metaAccountId>`.++### Reads vs. writes++The MCP server's own instructions are the canonical guide and are surfaced to the agent automatically:++- **Read-only questions** (analytics, audits, dashboards, diagnostics) go through `runScript`, which exposes `ads.graph(path, params)`, `ads.graphParallel([calls])`, `ads.insights(adAccountId?, options?)`, `ads.batch([requests])`, the `ads.fields.*` field bundles, and `ads.helpers.getDateRange(days)`. Fan out up to 20 Graph API calls in one request and correlate in-script — that's one tool call, not 20.+- **Mutations** go through dedicated write tools (`pauseAd`, `pauseAdSet`, `pauseCampaign`, `enableAd`, `enableAdSet`, `enableCampaign`, `renameCampaign`, `updateAdSetBudget`, `updateCampaignBudget`). Never wrap a mutation in `runScript`.+- **`suggestImprovement`** is the server's structured-recommendation endpoint — call it when you want the server's heuristic take alongside your own analysis, not as a substitute for the analytical work this skill describes.++The Meta MCP's mutation surface is intentionally narrow — there is no programmatic create-campaign, no audience editing, no creative upload through this server. When the user asks for an operation that lives outside the surface, say so plainly and point them to Meta Ads Manager rather than improvising with `runScript`.++Config is loaded. Hand control back to the invoking skill.