AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(meta-ads): opt-in Meta Ad Library source for a brand's live paid creative (#1138)
Matt Van Horn4909c2efb2d9
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex ead33491..222ef7e8 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -114,6 +114,8 @@ The project-scoped file is useful for **intentional per-client setups**: drop a**`LAST30DAYS_AMAZON_DOMAIN`** - optional, default `https://www.amazon.com`. The marketplace the `amazon` source searches; set it to `https://www.amazon.co.uk`, `https://www.amazon.de`, and so on. Product URLs are validated against this host, so records from other marketplaces are rejected.+**`LAST30DAYS_META_ADS_COUNTRY`** - optional, default `US`. The Ad Library country the `meta_ads` source queries, as a two-letter code. The endpoint accepts exactly one country per call, so this selects it rather than widening it. There is deliberately no durable env form of the advertiser-page override: a page id belongs to one topic, and env values are inherited by every competitor sub-run in a comparison, which would render one brand's ads as every peer's. Use `--meta-ads-page` per run instead.+### Local corpus (your files)Register persistent directories with `LAST30DAYS_CORPUS_DIRS`. Separate paths with `:` on macOS/Linux (the platform path separator is `;` on Windows):@@ -159,6 +161,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \| Threads | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `threads` | Threads items | 10K free calls || Pinterest | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `pinterest` | Pinterest items | 10K free calls || LinkedIn | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `linkedin` | LinkedIn posts + articles (articles rank as high signal on person topics) | 10K free calls; power-user opt-in, not offered during first-run onboarding |+| Meta Ads | `SCRAPECREATORS_API_KEY` + (`INCLUDE_SOURCES` contains `meta_ads` **or** `--search` includes `meta_ads`) | **opt-in, off by default**; a brand's live Meta Ad Library creatives that *launched* inside the window, with ad copy, launch date, placements, CTA, landing product, any promo code, and spoken transcripts for the newest video ads. The 📣 footer names the advertiser page that was resolved, plus how much the brand is still running from before. Paid message only, never audience reaction: Meta publishes reach and spend for political ads alone, so commercial creatives carry no engagement. `--meta-ads-page=<page_id>` skips name-based resolution when it picks the wrong company or the brand advertises under product-line page names; `LAST30DAYS_META_ADS_COUNTRY` selects a non-US Ad Library (one country per call). `EXCLUDE_SOURCES=meta_ads` wins. Never auto-fires and never inferred from topic shape: on a non-brand topic, resolution returns unrelated advertisers | 10K free calls; a default run spends at most 7 (1 resolve, plus 1 more only when the first search finds no name match, + up to 2 creative pages + up to 3 transcripts), billed per request. Power-user opt-in, not offered during first-run onboarding || Telegram | `SCRAPECREATORS_API_KEY` + (`--telegram-sources=<handles>` **or** `TELEGRAM_SOURCES=<handles>` + `INCLUDE_SOURCES` contains `telegram`) | **opt-in, off by default**; public channel posts only (no keyword discovery). `--telegram-sources=aipost,durov` (or `TELEGRAM_SOURCES` env) auto-activates for that run like `--trustpilot-domain`. Accepts bare handle, `@handle`, `t.me/URL`, or `t.me/s/URL`; rejects joinchat links and numeric -100 IDs. `INCLUDE_SOURCES=telegram` or `--search telegram` without a channel list does not fetch. `EXCLUDE_SOURCES=telegram` wins. `TELEGRAM_MAX_PAGES` overrides page cap (quick=1, default=3, deep=6). Never on Recommended onboarding tier. | 1 credit per live posts page; 10K free calls || Xiaohongshu (RED) | logged-in x-mcp browser plugin or `xiaohongshu-mcp` service; optional `XIAOHONGSHU_API_BASE` for custom URLs | requested-only via `--search xhs` or `--search xiaohongshu`; auto-probes `http://localhost:18060` then `http://host.docker.internal:18060` | no last30days API key; depends on your local browser-session service || Bluesky | `BSKY_HANDLE` + `BSKY_APP_PASSWORD` | Bluesky items | yes (app password at bsky.app) |diff --git a/README.de.md b/README.de.mdindex b166a203..34a1b513 100644--- a/README.de.md+++ b/README.de.md@@ -80,6 +80,7 @@ Wenn du dich mit einem CEO triffst: Hast du alle Tweets und YouTube-Transkripte| **arXiv** | Die Fachartikel hinter dem Hype. Neue Forschung im Zeitfenster, kostenlos, ohne API-Schlüssel. Wird automatisch aktiv, sobald `arxiv-pp-cli` im PATH liegt (das Erst-Setup installiert es). || **Techmeme** | Die redaktionelle Ebene der Tech-News, begrenzt auf dein 30-Tage-Fenster. Kostenlos, ohne API-Schlüssel. Wird automatisch aktiv, sobald `techmeme-pp-cli` im PATH liegt (das Erst-Setup installiert es). || **LinkedIn** | Das berufliche Signal. Beiträge und Artikel, wobei Artikel als starkes Signal gewichtet werden. |+| **Meta Ads** | Wofür eine Marke bezahlt. Diesen Monat gestartete Meta-Werbemittel mit Anzeigentext, Gutscheincodes und Transkripten. || **StockTwits** | Die Stimmung der Trader. Aktiviert sich automatisch, wenn dein Thema ein Ticker oder eine Kryptowährung ist. || **Threads** | Die Textebene nach Twitter. Gespräche von Creators und Marken. || **Pinterest** | Visuelle Entdeckung. Pins, gespeicherte Beiträge und Kommentare zu Produkten und Ideen. |diff --git a/README.es.md b/README.es.mdindex eb3cafae..17381156 100644--- a/README.es.md+++ b/README.es.md@@ -80,6 +80,7 @@ Si te vas a reunir con un CEO, ¿te has leído todos sus tuits y todas sus trans| **arXiv** | Los artículos científicos que hay detrás del ruido. Investigación nueva dentro de la ventana, gratis y sin clave de API. Se activa solo cuando `arxiv-pp-cli` está en el PATH (la configuración inicial lo instala). || **Techmeme** | La capa editorial de la actualidad tecnológica, acotada a tu ventana de 30 días. Gratis y sin clave de API. Se activa solo cuando `techmeme-pp-cli` está en el PATH (la configuración inicial lo instala). || **LinkedIn** | La señal profesional. Publicaciones y artículos, con los artículos ponderados como señal fuerte. |+| **Meta Ads** | Lo que una marca paga por decir. Creatividades publicitarias de Meta lanzadas este mes, con texto, códigos promocionales y transcripciones. || **StockTwits** | El sentimiento de los traders. Se activa automáticamente cuando tu tema es un ticker o una criptomoneda. || **Threads** | La capa de texto posterior a Twitter. Conversaciones de creadores y marcas. || **Pinterest** | Descubrimiento visual. Pines, guardados y comentarios sobre productos e ideas. |diff --git a/README.fr.md b/README.fr.mdindex 04af0b6c..da0b186a 100644--- a/README.fr.md+++ b/README.fr.md@@ -80,6 +80,7 @@ Si vous rencontrez un PDG, avez-vous lu tous ses tweets et toutes ses transcript| **arXiv** | Les articles scientifiques derrière le battage médiatique. La recherche publiée dans la fenêtre, gratuit, sans clé API. Activé automatiquement quand `arxiv-pp-cli` est présent dans le PATH (la configuration initiale l'installe). || **Techmeme** | La couche éditoriale de l'actu tech, restreinte à votre fenêtre de 30 jours. Gratuit, sans clé API. Activé automatiquement quand `techmeme-pp-cli` est présent dans le PATH (la configuration initiale l'installe). || **LinkedIn** | Le signal professionnel. Posts et articles, les articles étant pondérés comme signal fort. |+| **Meta Ads** | Ce qu'une marque paie pour dire. Les créations publicitaires Meta lancées ce mois-ci, avec le texte, les codes promo et les transcriptions. || **StockTwits** | Le sentiment des traders. S'active automatiquement quand votre sujet est un ticker ou une crypto. || **Threads** | La couche texte de l'après-Twitter. Les conversations des créateurs et des marques. || **Pinterest** | La découverte visuelle. Épingles, enregistrements et commentaires sur des produits et des idées. |diff --git a/README.ja.md b/README.ja.mdindex cdb39663..2f27278c 100644--- a/README.ja.md+++ b/README.ja.md@@ -80,6 +80,7 @@ CEOと会うとして、直近30日間のツイートと YouTube の文字起こ| **arXiv** | 話題の裏側にある論文。対象期間に出た新しい研究が、無料・APIキーなしで手に入ります。`arxiv-pp-cli` が PATH にあると自動的に有効になります(初回セットアップでインストールされます)。 || **Techmeme** | テックニュースの編集レイヤーを、対象の30日間に絞って取得します。無料・APIキーなし。`techmeme-pp-cli` が PATH にあると自動的に有効になります(初回セットアップでインストールされます)。 || **LinkedIn** | ビジネス面のシグナル。投稿と記事を拾い、記事は強いシグナルとして重み付けします。 |+| **Meta Ads** | ブランドが費用を払って発信しているメッセージ。今月配信を開始した Meta 広告のコピー、プロモコード、音声の書き起こしを拾います。 || **StockTwits** | トレーダーの温度感。調べる対象が銘柄コードや暗号資産のときに自動で有効になります。 || **Threads** | Twitter 以後のテキストの層。クリエイターやブランドの会話です。 || **Pinterest** | ビジュアル起点の発見。プロダクトやアイデアに対するピン・保存・コメント。 |diff --git a/README.md b/README.mdindex 9fdba896..9adf87c5 100644--- a/README.md+++ b/README.md@@ -80,6 +80,7 @@ If you're meeting with a CEO, have you read all their tweets and YouTube transcr| **arXiv** | The papers behind the hype. New research in the window, free, no API key. Auto-enabled when `arxiv-pp-cli` is on PATH (first-run setup installs it). || **Techmeme** | The tech-news editorial layer, date-windowed to your 30 days. Free, no API key. Auto-enabled when `techmeme-pp-cli` is on PATH (first-run setup installs it). || **LinkedIn** | The professional signal. Posts and articles, with articles weighted as high signal. |+| **Meta Ads** | What a brand is paying to say. Live Meta ad creatives launched this month, with copy, promo codes, and spoken transcripts. || **StockTwits** | Trader sentiment. Auto-activates when your topic is a ticker or crypto. || **Threads** | The post-Twitter text layer. Conversations from creators and brands. || **Pinterest** | Visual discovery. Pins, saves, and comments on products and ideas. |diff --git a/README.pt-BR.md b/README.pt-BR.mdindex df6199dd..08d6ca23 100644--- a/README.pt-BR.md+++ b/README.pt-BR.md@@ -80,6 +80,7 @@ Se você vai se reunir com um CEO, já leu todos os tweets e todas as transcriç| **arXiv** | Os artigos científicos por trás do hype. Pesquisa nova dentro da janela, de graça e sem chave de API. Ativa sozinho quando `arxiv-pp-cli` está no PATH (a configuração inicial instala). || **Techmeme** | A camada editorial do noticiário de tecnologia, limitada à sua janela de 30 dias. De graça e sem chave de API. Ativa sozinho quando `techmeme-pp-cli` está no PATH (a configuração inicial instala). || **LinkedIn** | O sinal profissional. Publicações e artigos, com os artigos ponderados como sinal forte. |+| **Meta Ads** | O que uma marca paga para dizer. Criativos de anúncios da Meta lançados neste mês, com texto, códigos promocionais e transcrições. || **StockTwits** | O humor dos traders. Ativa automaticamente quando seu assunto é um ticker ou uma cripto. || **Threads** | A camada de texto do pós-Twitter. Conversas de criadores e marcas. || **Pinterest** | Descoberta visual. Pins, itens salvos e comentários sobre produtos e ideias. |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 8b382bc7..165ac220 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -83,6 +83,7 @@ Google 聚合编辑选出的内容,`/last30days` 搜索真实的人。| **arXiv** | 热点背后的论文。免费查找时间窗口内的新研究,无需 API 密钥。当 PATH 中存在 `arxiv-pp-cli` 时自动启用(首次配置会安装)。 || **Techmeme** | 科技新闻的编辑视角,并按你设定的 30 天窗口筛选。免费且无需 API 密钥。当 PATH 中存在 `techmeme-pp-cli` 时自动启用(首次配置会安装)。 || **LinkedIn** | 职业领域的信号。搜索帖子和文章,其中文章被视为高价值信号。 |+| **Meta Ads** | 品牌花钱在说什么。本月新投放的 Meta 广告创意,包含文案、优惠码和语音转写。 || **StockTwits** | 交易者情绪。当主题是股票代码或加密货币时自动启用。 || **Threads** | 后 Twitter 时代的文字内容层,汇集创作者和品牌的讨论。 || **Pinterest** | 视觉发现:围绕产品和创意的 Pin、收藏与评论。 |diff --git a/changelog.d/+meta-ads.added.md b/changelog.d/+meta-ads.added.mdnew file mode 100644index 00000000..ea038b4e--- /dev/null+++ b/changelog.d/+meta-ads.added.md@@ -0,0 +1,5 @@+**Meta Ads source** — a new opt-in research lane that surfaces what a brand is *paying* to say this month, alongside what everyone else is saying about it. It resolves the brand's advertiser page in the Meta Ad Library, pulls the creatives that launched inside your 30-day window, and reads back the ad copy, launch date, placements, call to action, landing product, any promo code, and the spoken transcript of the newest video ads. The 📣 footer line names the advertiser page it resolved, so a wrong-company match is visible rather than silent, and reports how much the brand is still running from before the window.++Paid message only, never audience reaction: Meta publishes reach and spend for political ads alone, so commercial creatives carry no engagement numbers.++Off by default and never inferred from topic shape. Turn it on per run with `--search meta_ads` or durably with `INCLUDE_SOURCES=meta_ads`; it needs `SCRAPECREATORS_API_KEY`. A default-depth run spends at most 7 of the 10,000 free calls. Use `--meta-ads-page=<page_id>` when a brand advertises under product-line page names, and `LAST30DAYS_META_ADS_COUNTRY` for a non-US Ad Library.diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex fa40aeef..f4db7b34 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -761,7 +761,7 @@ The magic of /last30days is Reddit comments + X posts together - and both are fr**Bonus: TikTok, Instagram, YouTube comments (ScrapeCreators):**- `SCRAPECREATORS_API_KEY=xxx` - 10,000 free calls at scrapecreators.com.-- After adding your key, set `INCLUDE_SOURCES=tiktok,instagram` to turn on the popular ones. (Threads, Pinterest, and LinkedIn are also available via `INCLUDE_SOURCES=threads,pinterest,linkedin` for power users.)+- After adding your key, set `INCLUDE_SOURCES=tiktok,instagram` to turn on the popular ones. (Threads, Pinterest, LinkedIn, and Meta Ads are also available via `INCLUDE_SOURCES=threads,pinterest,linkedin,meta_ads` for power users.)**Other optional sources (add anytime):**- `PERPLEXITY_API_KEY=xxx` - preferred Agent/Search API path with citations; set `INCLUDE_SOURCES=perplexity`. Existing `OPENROUTER_API_KEY` installs keep the synchronous Sonar fallback.@@ -824,7 +824,7 @@ SKILL_DIR="<absolute path of the directory containing the SKILL.md you just Read"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" --diagnose```-`--diagnose` prints JSON. `ACTIVE_SOURCES_LIST` is its `available_sources` array — the engine's authoritative source set, computed after credential resolution. Map the tokens to display names: `reddit`→Reddit, `hackernews`→Hacker News, `polymarket`→Polymarket, `github`→GitHub, `digg`→Digg, `x`→X, `youtube`→YouTube, `tiktok`→TikTok, `instagram`→Instagram, `threads`→Threads, `pinterest`→Pinterest, `linkedin`→LinkedIn, `bluesky`→Bluesky, `perplexity`→Perplexity, `grounding`→Web, `jobs`→Jobs, `corpus`→Your files, `dripstack`→DripStack.+`--diagnose` prints JSON. `ACTIVE_SOURCES_LIST` is its `available_sources` array — the engine's authoritative source set, computed after credential resolution. Map the tokens to display names: `reddit`→Reddit, `hackernews`→Hacker News, `polymarket`→Polymarket, `github`→GitHub, `digg`→Digg, `x`→X, `youtube`→YouTube, `tiktok`→TikTok, `instagram`→Instagram, `threads`→Threads, `pinterest`→Pinterest, `linkedin`→LinkedIn, `bluesky`→Bluesky, `perplexity`→Perplexity, `grounding`→Web, `jobs`→Jobs, `meta_ads`→Meta Ads, `corpus`→Your files, `dripstack`→DripStack.- If EXCLUDE_SOURCES is set (comma-separated, case-insensitive): drop any matching source from ACTIVE_SOURCES_LIST before displaying@@ -927,6 +927,7 @@ Before running the engine, determine which flags apply to this topic and resolve| `--github-repo={owner/repo}` | Step 0.5c | Topic is a product / project / open-source tool || `--trustpilot-domain={domain}` | Step 0.5d | Topic is a company / brand / service with a Trustpilot presence (passing the flag also auto-activates the opt-in Trustpilot source for this run) || `--amazon-query={keyword}` | Step 0.5e | Recent buyer sentiment would materially inform the report AND `brightdata` is on PATH and logged in. Keyword is brand-plus-category (`Weber grill`), and for a person topic it is their company's product line (`June Oven`), not their name. Also add `amazon` to `--search` |+| `--meta-ads-page={page_id}` | Step 0.5f | Name-based advertiser resolution picked the wrong company, or the brand advertises only under product-line page names. Accepts a numeric Ad Library page id or an Ad Library URL with `view_all_page_id`; a facebook.com vanity URL is not a page id. Also add `meta_ads` to `--search` || `--subreddits={sub1,sub2,...}` | Step 0.55 | Always — almost every topic has active Reddit communities || `--tiktok-hashtags={h1,h2,...}` | Step 0.55 | Always — inferred from topic || `--tiktok-creators={c1,c2,...}` | Step 0.55 | Creator / influencer / brand topics |@@ -1116,6 +1117,37 @@ Store: `AMAZON_QUERY = {product keyword or empty}` — pass as `--amazon-query="---+### Step 0.5f: Decide the Meta Ads Lane (if a ScrapeCreators key is set)++**Availability first.** This lane exists only when `SCRAPECREATORS_API_KEY` is configured (`--diagnose` reports `has_scrapecreators`). Without it the source does not exist, nothing changes, and you should skip this step entirely — do not mention it, do not suggest signing up mid-run.++**The one question to ask:** *is there a brand here whose own paid message is evidence?* This lane answers "what is this company paying to say right now" — its live creatives, the products it is pushing, the promo codes it is running, and what its video ads say out loud. It is not a conversation source: nothing here is what people think about the brand, only what the brand is telling them.++| Topic | Fires? | Why |+|---|---|---|+| A consumer-brand topic | Yes — the brand's own campaign is first-party evidence | Paid message next to customer reaction |+| A retailer or membership warehouse | Yes — current promotions and seasonal push | Live offers are the story |+| A direct-to-consumer startup | Yes — positioning shows up in ad copy first | Often the earliest signal of a repositioning |+| A person, an executive, a creator | No — people do not run Ad Library campaigns | Their company might; use the company as the topic |+| An AI tool, a framework, a developer product | No — resolution returns unrelated advertisers | A live check on one such topic returned 1,467 wrong-entity ads |+| A news, politics, or culture topic | No — nothing to resolve | The lane ends unresolved and spends a credit finding that out |++**Three mechanics that matter:**++1. **Resolution can pick the wrong company, and the footer tells you when it did.** The lane resolves the advertiser page by name from an ad search. The 📣 footer line always names the page it resolved, and says `matched by partial name` when it fell back to the weakest match, so check it. If the advertiser is not the brand you meant, find the real page id and re-run with `--meta-ads-page`: `WebSearch("{TOPIC} facebook ad library")`, open the Ad Library result, and take the digits from its `view_all_page_id=` parameter. A `facebook.com/<name>` vanity URL is not a page id and the flag rejects it.+2. **A brand that advertises under product-line names still resolves.** Matching works in both directions, so an umbrella topic finds a product-named page and vice versa. What does not resolve is a brand whose pages share no word with the topic; that is the override's main use.+3. **The window means launched, not running.** Items are creatives that *started* inside the last 30 days. Long-running creatives from before are counted on the footer but never ranked, because "still advertising" is not news and "just launched this" is.++**`--search` is replace-not-add.** Passing `--search` narrows the run to exactly the sources listed, so include the full intended set: `--search reddit,x,youtube,meta_ads` — never a bare `--search meta_ads`, which would silently drop every other source.++**Cost and latency, so you can set expectations:** one or two credits to resolve the advertiser (a second only when the first search finds no name match), up to two more for its creatives, and up to three for video transcripts — at most seven per default-depth run against a 10,000-call free tier. Transcripts add roughly 15 to 45 seconds. Quick depth pulls no transcripts at all, though it still spends the resolve and one page.++Store: `META_ADS_PAGE = {page id or empty}` — add `meta_ads` to `--search`, and pass `--meta-ads-page="{META_ADS_PAGE}"` only when you have a page id.++**Skip this step if:** no ScrapeCreators key is set, the topic has no brand whose advertising is evidence, or the user set `EXCLUDE_SOURCES=meta_ads`.++---+## Agent Mode (--agent flag)If `--agent` appears in ARGUMENTS (e.g., `/last30days plaud granola --agent`):@@ -1468,7 +1500,7 @@ Only show lines for platforms where something was resolved. Skip empty lines. On- For how_to: prioritize YouTube (tutorials) and Reddit (guides)- Primary subquery weight = 1.0, secondary = 0.6-0.8, peripheral = 0.3-0.5-**Available sources (include every active one in the primary subquery):** use the engine's `ACTIVE_SOURCES_LIST`. The normal candidates are reddit, x, youtube, tiktok, instagram, hackernews, and polymarket; X remains part of the normal set when active and is simply omitted when unavailable. Optional: bluesky, truthsocial, threads, pinterest, grounding (web search - only if user has Brave/Exa/Serper key), digg (Digg clusters - only if `digg-pp-cli` is on PATH), amazon (buyer reviews - only if `brightdata` is on PATH and logged in; see Step 0.5e)+**Available sources (include every active one in the primary subquery):** use the engine's `ACTIVE_SOURCES_LIST`. The normal candidates are reddit, x, youtube, tiktok, instagram, hackernews, and polymarket; X remains part of the normal set when active and is simply omitted when unavailable. Optional: bluesky, truthsocial, threads, pinterest, grounding (web search - only if user has Brave/Exa/Serper key), digg (Digg clusters - only if `digg-pp-cli` is on PATH), amazon (buyer reviews - only if `brightdata` is on PATH and logged in; see Step 0.5e), meta_ads (a brand's live Meta ad creatives - only if `SCRAPECREATORS_API_KEY` is set and the topic is a brand; see Step 0.5f)**Intent → freshness_mode mapping:**- breaking_news, prediction → `strict_recent`diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex b1e3989f..36f41276 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -83,6 +83,23 @@ def _cleanup_children() -> None:atexit.register(_cleanup_children)+def parse_meta_ads_page(raw: str) -> str:+ """Extract an Ad Library page id from a flag value, or "" if there is none.++ Accepts a bare numeric id or any Ad Library URL carrying+ ``view_all_page_id``. A ``facebook.com/<vanity>`` URL is deliberately+ rejected rather than guessed at: a vanity handle is not a page id, and one+ live check resolved a brand-looking handle to a private person's profile.+ """+ value = str(raw or "").strip()+ if not value:+ return ""+ if re.fullmatch(r"\d{5,20}", value):+ return value+ match = re.search(r"view_all_page_id=(\d{5,20})", value)+ return match.group(1) if match else ""++def parse_search_flag(raw: str, flag_name: str = "--search") -> list[str]:sources = []for source in raw.split(","):@@ -834,6 +851,17 @@ def build_parser() -> argparse.ArgumentParser:"Requires the brightdata CLI on PATH and logged in."),)+ parser.add_argument(+ "--meta-ads-page",+ help=(+ "Meta Ad Library page id for the topic's advertiser, when the meta_ads "+ "source is active. Skips name-based page resolution and its discovery "+ "credit. Accepts a bare numeric page id (e.g. 123456789012345) or an Ad "+ "Library URL carrying view_all_page_id. A facebook.com vanity URL is not "+ "a page id and is rejected. Use it when a brand advertises under product "+ "names, or when resolution picked the wrong company."+ ),+ )parser.add_argument("--telegram-sources",help=(@@ -3825,6 +3853,31 @@ def _main("or set INCLUDE_SOURCES=amazon. Ignoring the keyword.\n")+ # Advertiser page override for the meta_ads source. Same shape as+ # --amazon-query (config-carried, warn-not-activate) and for the same+ # reason: the lane spends metered credits per call.+ if getattr(args, "meta_ads_page", None):+ page_id = parse_meta_ads_page(args.meta_ads_page)+ if not page_id:+ sys.stderr.write(+ "[Meta Ads] --meta-ads-page must be a numeric Ad Library page id "+ "or an Ad Library URL containing view_all_page_id; a facebook.com "+ "vanity URL is not a page id. Ignoring the override.\n"+ )+ else:+ config["_meta_ads_page"] = page_id+ _meta_ads_requested = (+ (requested_sources and "meta_ads" in requested_sources)+ or "meta_ads" in str(config.get("INCLUDE_SOURCES") or "").lower()+ )+ if not _meta_ads_requested:+ sys.stderr.write(+ "[Meta Ads] --meta-ads-page was set but the meta_ads source "+ "was not requested; add it to --search (e.g. --search "+ "reddit,x,meta_ads) or set INCLUDE_SOURCES=meta_ads. "+ "Ignoring the page.\n"+ )+# vs-mode / plan routing: split a vs-topic into main + peers unless# discover-N or an explicit --competitors-list already decided who runs.topic, comp_enabled, comp_count, comp_explicit = apply_vs_competitor_routing(@@ -3961,6 +4014,9 @@ def _main(# so each peer derives its own keyword from its own topic; a# per-entity keyword can ride in the --competitors-plan entry.entity_config.pop("_amazon_query", None)+ # An advertiser page is per-entity state by definition: left in+ # place it would render one brand's ads as every peer's.+ entity_config.pop("_meta_ads_page", None)plan_entry = comp_plan.get(entity.strip().lower(), {})resolved = {"entity": entity,diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.pyindex f1ff6f7e..186ece5a 100644--- a/skills/last30days/scripts/lib/doctor.py+++ b/skills/last30days/scripts/lib/doctor.py@@ -166,6 +166,7 @@ SOURCE_ORDER = ("arxiv","trustpilot","amazon",+ "meta_ads","tiktok","instagram","threads",@@ -837,6 +838,10 @@ def _perplexity_record(config):)+def _meta_ads_record(config):+ return _sc_optin_record(config, "meta_ads", "Meta Ad Library")++def _linkedin_record(config):requires = "SCRAPECREATORS_API_KEY + INCLUDE_SOURCES=linkedin"if not config.get("SCRAPECREATORS_API_KEY"):@@ -959,6 +964,7 @@ _SOURCE_BUILDERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {"arxiv": _arxiv_record,"trustpilot": _trustpilot_record,"amazon": _amazon_record,+ "meta_ads": _meta_ads_record,"tiktok": _tiktok_record,"instagram": _instagram_record,"threads": _threads_record,diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex ce574131..99b0928d 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -647,6 +647,12 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:# Amazon marketplace the amazon source searches. Non-US users point# this at their own storefront (e.g. https://www.amazon.co.uk).('LAST30DAYS_AMAZON_DOMAIN', 'https://www.amazon.com'),+ # Ad Library country for the meta_ads source, as a two-letter code. The+ # endpoint takes exactly one country per call. There is deliberately no+ # durable env form of the advertiser-page override: a page id is+ # per-topic state, and env keys ride through the competitor runner's+ # config copy, which would attach one brand's ads to every peer.+ ('LAST30DAYS_META_ADS_COUNTRY', 'US'),# Host-native search signal: set by the SKILL.md agent-host path when the# invoking runtime has its own (better) web-search tool, so the engine's# keyless search floor stays off there. Defaults unset -> floor allowed.diff --git a/skills/last30days/scripts/lib/meta_ads.py b/skills/last30days/scripts/lib/meta_ads.pynew file mode 100644index 00000000..d2a76da9--- /dev/null+++ b/skills/last30days/scripts/lib/meta_ads.py@@ -0,0 +1,982 @@+"""Meta Ad Library source for last30days.++What a brand is *paying* to say this month, next to what everyone else is+saying about it in the other sources. Discovery resolves the advertiser page+behind a brand topic, enrichment pulls that page's creatives, and the newest+video creatives get their spoken script transcribed.++Two-stage shape, following the Amazon buyer-signal lane:++1. **Discovery** -- one keyword ad search resolves which advertiser page the+ topic actually belongs to. Ad-search-first, because the company-search+ endpoint misses brands whose pages carry product names rather than the+ corporate name. Company search is the fallback; an explicit page override+ skips both.+2. **Enrichment** -- the resolved page's ads inside the run window, cursor+ paginated under a depth cap, deduped to distinct creatives, then a small+ capped set of transcripts.++Metering: one credit per request regardless of records returned, so the caps+below bound paid *requests*, not records. A default-depth run is 1 discovery++ at most 1 company search + up to 2 enrichment pages + up to 3 transcripts,+so at most 7 credits. Every cap here counts requests issued, never results+obtained: an upstream that returns nothing still bills for being asked.++Two live-verified quirks drive the code:++* The keyword endpoint returns its rows under ``searchResults`` while the+ company endpoint returns the same shape under ``results``. Both are read+ tolerantly rather than by endpoint.+* ``status`` defaults to ACTIVE upstream. The window fetch overrides it, or a+ creative that launched inside the window and already ended -- a one-week+ promo push, exactly the signal this source exists for -- never comes back.++Meta exposes ``reach_estimate`` and ``spend`` only for political and issue+ads; both are null on commercial ads, so items carry no engagement beyond+the creative variant count.++Requires SCRAPECREATORS_API_KEY.+"""++from __future__ import annotations++import datetime+import re+import time+from typing import Any, Dict, List, Optional, Tuple++from . import dates, http, log++SC_BASE = "https://api.scrapecreators.com/v1/facebook/adLibrary"++SEARCH_ADS_URL = f"{SC_BASE}/search/ads"+SEARCH_COMPANIES_URL = f"{SC_BASE}/search/companies"+COMPANY_ADS_URL = f"{SC_BASE}/company/ads"+AD_TRANSCRIPT_URL = f"{SC_BASE}/ad/transcript"++DEFAULT_COUNTRY = "US"++# Discovery only needs live creatives to identify the advertiser, and asking+# for live ones keeps that call cheap and current. The window fetch is the+# opposite case: see the module docstring.+DISCOVERY_STATUS = "ACTIVE"+ENRICHMENT_STATUS = "ALL"++# Discovery deliberately uses the endpoint's default (unordered) search type.+# Exact-phrase mode narrows so hard that a brand advertising under a product+# name disappears from its own search.+DISCOVERY_SEARCH_TYPE = "keyword_unordered"++DEPTH_CONFIG: Dict[str, Dict[str, int]] = {+ "quick": {"pages": 1, "transcripts": 0},+ "default": {"pages": 2, "transcripts": 3},+ "deep": {"pages": 4, "transcripts": 5},+}++# Whole-lane wall clock. Pagination bounds the request COUNT, not time, so+# each request is additionally clamped to what is left of this.+LANE_BUDGET_SECONDS = 120.0+REQUEST_TIMEOUT = 30.0+MIN_REQUEST_TIMEOUT = 5.0++# Transcripts are slower than list calls: the live median was well over 15s.+TRANSCRIPT_TIMEOUT = 45.0++# Credential- or account-scoped failures. Retrying the next call would fail+# identically, and retrying a 429 deepens the limit already being hit.+FATAL_STATUS_CODES = frozenset({401, 402, 403, 429})++# Shortest token that may establish a name match. Below this, a topic ending+# in a short word ("... AI") matches every advertiser that shares it: a live+# probe returned 1,467 unrelated advertisers for one such topic.+MIN_MATCH_TOKEN = 4++# Absolute pagination bound, independent of the depth cap.+MAX_PAGES_HARD = 10++# Resolution outcomes carried on the tally so the footer can tell an honest+# empty from a wrong-entity match.+RESOLVED = "resolved"+UNRESOLVED = "unresolved"+NO_CANDIDATES = "no_candidates"++_TOKEN_RE = re.compile(r"[a-z0-9]+")++# A promo code is only recognized when the copy actually calls it one. Model+# numbers and SKUs ("E-325") share the token shape and must not match.+_PROMO_RE = re.compile(+ r"\b(?:promo|discount|coupon)?\s*code\s*[:\-]?\s*([A-Za-z0-9]{4,12})\b",+ re.IGNORECASE,+)+++def _log(msg: str) -> None:+ log.source_log("Meta Ads", msg, tty_only=False)+++# --------------------------------------------------------------- matching+++def _tokens(text: str) -> List[str]:+ return _TOKEN_RE.findall(str(text or "").lower())+++def _match_tokens(text: str) -> set[str]:+ """Tokens long enough to establish a match.++ Deliberately not ``relevance.tokenize``: that helper expands short tokens+ through a synonym table, which is right for scoring body text and wrong+ here -- it would let an advertiser sharing one short word pass as the+ topic's own brand.+ """+ return {tok for tok in _tokens(text) if len(tok) >= MIN_MATCH_TOKEN}+++def _compact(text: str) -> str:+ """Normalized form for exact-identity comparison ("Bright iQ" -> "brightiq")."""+ return "".join(_tokens(text))+++# How an advertiser page name matched the topic, strongest first. Resolution+# prefers a whole tier over ad volume: volume measures how much a page is+# spending, never whether it is the right company.+MATCH_EXACT = "exact"+MATCH_TOKEN = "token"+MATCH_CONTAINED = "contained"+MATCH_NONE = ""+++def match_strength(topic: str, name: str) -> str:+ """How strongly an advertiser page name belongs to the topic.++ Three tiers, because they are not equally trustworthy:++ * ``exact`` -- the normalized names are the same string. Unambiguous.+ * ``token`` -- they share a whole word of at least ``MIN_MATCH_TOKEN``.+ * ``contained`` -- a whole word of one appears inside the other's+ normalized form. This is what lets an umbrella topic find a brand+ advertising under product-line page names, and it is also the weakest+ signal: substring containment cannot distinguish a product line from a+ coincidence, so a short brand can be found inside an unrelated longer+ word. It is accepted only when no stronger tier matched, and the footer+ says when resolution rested on it.++ A topic whose every word is shorter than the token floor (an initialism+ brand) has no usable tokens at all, so it can only ever match exactly.+ Returning False for it outright would make such a brand unresolvable even+ against its own identically-named page.+ """+ topic_compact = _compact(topic)+ name_compact = _compact(name)+ if not topic_compact or not name_compact:+ return MATCH_NONE+ if topic_compact == name_compact:+ return MATCH_EXACT+ topic_tokens = _match_tokens(topic)+ name_tokens = _match_tokens(name)+ if not topic_tokens or not name_tokens:+ return MATCH_NONE+ if topic_tokens & name_tokens:+ return MATCH_TOKEN+ if any(tok in name_compact for tok in topic_tokens):+ return MATCH_CONTAINED+ if any(tok in topic_compact for tok in name_tokens):+ return MATCH_CONTAINED+ return MATCH_NONE+++def names_match(topic: str, name: str) -> bool:+ """True when an advertiser page name plausibly belongs to the topic."""+ return match_strength(topic, name) != MATCH_NONE+++def _group_advertisers(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """Collapse ad rows into advertiser pages, busiest first."""+ groups: Dict[str, Dict[str, Any]] = {}+ for row in rows:+ if not isinstance(row, dict):+ continue+ page_id = str(row.get("page_id") or "").strip()+ if not page_id:+ continue+ name = str(row.get("page_name") or "").strip()+ group = groups.setdefault(page_id, {"id": page_id, "name": name, "ads": 0})+ group["ads"] += 1+ if not group["name"] and name:+ group["name"] = name+ return sorted(+ groups.values(), key=lambda g: (-g["ads"], g["name"].lower(), g["id"])+ )+++def _token_spread(pages: List[Dict[str, Any]]) -> Dict[str, int]:+ """How many distinct advertisers in this result set carry each word."""+ spread: Dict[str, int] = {}+ for page in pages:+ for token in _match_tokens(page["name"]):+ spread[token] = spread.get(token, 0) + 1+ return spread+++def _match_rarity(topic: str, name: str, spread: Dict[str, int]) -> int:+ """How distinctive the word this page matched on is. Lower is better.++ A word carried by many advertisers in the same result set is a category,+ not an identity: "kitchen" sits in every kitchen brand's name, so matching+ on it resolves whoever is advertising hardest rather than the right+ company. A word carried by one advertiser names that advertiser.++ Rarity is measured against the candidates themselves rather than a fixed+ stopword list, because the same word can be a category in one search and+ the brand's own name in another. Counting alone would not separate those:+ an umbrella brand's name also appears across several of its product-line+ pages. What distinguishes them is that a *rarer* alternative exists --+ "Acme Kitchen" carries "acme" as well, while "Kitchen World" carries only+ the shared word -- so the best available word decides, not the fact of+ sharing.+ """+ topic_tokens = _match_tokens(topic)+ name_tokens = _match_tokens(name)+ shared = topic_tokens & name_tokens+ if not shared:+ # Containment match: score the word that did the containing.+ shared = {+ tok for tok in topic_tokens if tok in _compact(name)+ } | {tok for tok in name_tokens if tok in _compact(topic)}+ if not shared:+ return 0+ return min(spread.get(tok, 1) for tok in shared)+++def _matched_tokens(topic: str, name: str) -> set[str]:+ """Topic words that actually took part in the match.++ For a containment match the participating topic word has to be identified,+ not assumed: crediting every topic word whenever any page word appears+ somewhere in the topic would let "Grill World" claim "best Acme grills" on+ the strength of "grill", carrying the brand word along with it.+ """+ topic_tokens = _match_tokens(topic)+ name_tokens = _match_tokens(name)+ shared = topic_tokens & name_tokens+ if shared:+ return shared+ name_compact = _compact(name)+ topic_compact = _compact(topic)+ matched = {tok for tok in topic_tokens if tok in name_compact}+ for name_token in name_tokens:+ if name_token in topic_compact:+ matched |= {+ tok+ for tok in topic_tokens+ if name_token in tok or tok in name_token+ }+ return matched+++def _head_token(topic: str) -> str:+ """The leading word of the topic's primary entity.++ Brand names lead and category words trail: in "Acme Kitchen" the brand is+ "acme" and "kitchen" says what it sells. This mirrors the entity-grounding+ rule the engine already applies elsewhere, where grounding keys on the head+ token of the primary entity because trailing words are usually descriptors.++ A research topic does not always open with the brand, though: "best Acme+ grills" leads with an intent modifier, and treating "best" as the identity+ would reject the brand's own page. So the head is taken from the primary+ entity rather than the raw phrase, skipping the same descriptor vocabulary+ the engine's other adapters strip before searching.+ """+ from .query import NOISE_WORDS++ eligible = [tok for tok in _tokens(topic) if len(tok) >= MIN_MATCH_TOKEN]+ for token in eligible:+ if token not in NOISE_WORDS:+ return token+ # Every word was a descriptor, so there is no identity to key on; fall+ # back to the leading word rather than matching anything at all.+ return eligible[0] if eligible else ""+++def _name_covered_by_topic(topic: str, name: str) -> bool:+ """True when the topic spells out this advertiser's whole name.++ Whole means whole. Every word of the page name must appear in the topic as+ a word, short ones included and without dissolving word boundaries: an+ advertiser called "Acme AI" is not named by a topic about "Acme Kitchen"+ just because the two share "acme", and "Cart Wheel" is not named by "Acme+ Cartwheel" just because its letters appear inside a longer word. Ignoring+ either would let a fragment of one company's name stand in for another's.++ The name must also account for more than a single word of the topic, unless+ it accounts for the topic entirely, so a page called just "Kitchen" cannot+ claim a topic about "Acme Kitchen" on the category word alone.+ """+ topic_words = set(_tokens(topic))+ name_words = set(_tokens(name))+ if not topic_words or not name_words:+ return False+ if not name_words <= topic_words:+ return False+ topic_tokens = _match_tokens(topic)+ covered = topic_tokens & name_words+ return len(covered) >= 2 or (bool(covered) and covered == topic_tokens)+++def _is_category_only(topic: str, name: str, spread: Dict[str, int]) -> bool:+ """True when this page shares some of the topic's words but is not its brand.++ A single-word topic is its own identity, so any page carrying that word --+ including an umbrella brand's product-line page -- is the brand.++ A multi-word topic has to be matched as a name, not by one of its words. The+ page qualifies when the topic spells its name out, or when it carries every+ identifying word of the topic. Sharing only one of them is what a category+ lookalike and a same-word different-company both look like, and neither+ should have another firm's paid creatives attributed to it.+ """+ matched = _matched_tokens(topic, name)+ if not matched:+ return True+ topic_tokens = _match_tokens(topic)+ if len(topic_tokens) <= 1:+ return False+ if _name_covered_by_topic(topic, name):+ return False+ name_words = set(_tokens(name))+ name_compact = _compact(name)+ covered = {+ token+ for token in topic_tokens+ if token in name_words or token in name_compact+ }+ return covered != topic_tokens+++def resolve_page(+ topic: str, rows: List[Dict[str, Any]]+) -> Tuple[Optional[Dict[str, Any]], List[str], str, str]:+ """Pick the advertiser page for a topic from a list of ad rows.++ Strength decides before volume. Ad count only breaks ties *inside* the+ strongest tier that matched, because volume measures how much a page is+ spending and says nothing about whether it is the right company: a reseller+ or outlet page running more ads than the brand it resells would otherwise+ claim the brand's own topic.++ Returns ``(page, runner_up_names, top_unmatched_name, strength)``. ``page``+ is None when nothing matched, and ``top_unmatched_name`` is empty only when+ no rows came back at all, which is what separates "wrong advertiser" from+ "nothing there". ``strength`` is the tier that won, so the caller can tell+ the reader when resolution rested on the weakest one.+ """+ ordered = _group_advertisers(rows)+ spread = _token_spread(ordered)+ scored = [(match_strength(topic, g["name"]), g) for g in ordered]+ for tier in (MATCH_EXACT, MATCH_TOKEN, MATCH_CONTAINED):+ group = [+ g+ for strength, g in scored+ if strength == tier+ # An exact normalized-name match is unambiguous, so it is never+ # second-guessed: the guard below exists for the weaker tiers,+ # where a shared word is the only thing holding the match up.+ and (tier == MATCH_EXACT or not _is_category_only(topic, g["name"], spread))+ ]+ if not group:+ continue+ # Within a tier: the most distinctive matched word first, then the+ # page accounting for the most of the topic, and only then ad volume.+ # Two pages can share a brand word while one also matches the rest of+ # the topic, and that one is the better answer however much the other+ # is spending.+ group.sort(+ key=lambda g: (+ _match_rarity(topic, g["name"], spread),+ -len(_matched_tokens(topic, g["name"])),+ -g["ads"],+ g["id"],+ )+ )+ winner = group[0]+ # Runner-ups come from every tier that matched at all: a weaker+ # same-name-family page is exactly what a reader checking a+ # questionable resolution wants to see.+ runner_ups = [+ g["name"]+ for strength, g in scored+ if strength != MATCH_NONE and g["id"] != winner["id"]+ ][:2]+ return winner, runner_ups, "", tier+ return None, [], (ordered[0]["name"] if ordered else ""), MATCH_NONE+++# ----------------------------------------------------------- ad row fields+++def _envelope_rows(response: Any) -> List[Dict[str, Any]]:+ """Read ad rows from either endpoint's envelope."""+ if not isinstance(response, dict):+ return []+ for key in ("searchResults", "results", "ads", "data"):+ value = response.get(key)+ if isinstance(value, list):+ return [row for row in value if isinstance(row, dict)]+ return []+++def _envelope_total(response: Any) -> int:+ if not isinstance(response, dict):+ return 0+ try:+ return int(response.get("searchResultsCount") or 0)+ except (TypeError, ValueError):+ return 0+++def _envelope_cursor(response: Any) -> Optional[str]:+ if not isinstance(response, dict):+ return None+ cursor = response.get("cursor")+ if isinstance(cursor, (str, int)) and str(cursor).strip():+ return str(cursor)+ return None+++def _snapshot(row: Dict[str, Any]) -> Dict[str, Any]:+ snapshot = row.get("snapshot")+ return snapshot if isinstance(snapshot, dict) else {}+++def _body_text(snapshot: Dict[str, Any]) -> str:+ body = snapshot.get("body")+ if isinstance(body, dict):+ return str(body.get("text") or "").strip()+ return str(body or "").strip()+++def _cards(snapshot: Dict[str, Any]) -> List[Dict[str, Any]]:+ cards = snapshot.get("cards")+ if not isinstance(cards, list):+ return []+ return [card for card in cards if isinstance(card, dict)]+++def launch_date(row: Dict[str, Any]) -> Optional[str]:+ """YYYY-MM-DD the creative started running, or None."""+ raw = str(row.get("start_date_string") or "")[:10]+ try:+ datetime.date.fromisoformat(raw)+ return raw+ except ValueError:+ pass+ epoch = row.get("start_date")+ if isinstance(epoch, (int, float)) and epoch > 0:+ return dates.timestamp_to_date(epoch)+ return None+++def dedupe_key(row: Dict[str, Any]) -> str:+ """Identity for one creative.++ ``collation_id`` groups the variants of one creative, which is the unit a+ reader cares about. It is frequently absent though (9 of 30 ads on one+ live page carried none), and keying on it alone would collapse every such+ creative into a single item.+ """+ collation = str(row.get("collation_id") or "").strip()+ if collation:+ return f"collation:{collation}"+ return f"ad:{str(row.get('ad_archive_id') or '').strip()}"+++def has_video(row: Dict[str, Any]) -> bool:+ snapshot = _snapshot(row)+ videos = snapshot.get("videos")+ if isinstance(videos, list) and any(isinstance(v, dict) and v for v in videos):+ return True+ for card in _cards(snapshot):+ if card.get("video_hd_url") or card.get("video_sd_url"):+ return True+ return False+++def extract_promo_code(text: str) -> Optional[str]:+ """Return an uppercase promo code the copy explicitly labels as one."""+ for match in _PROMO_RE.finditer(str(text or "")):+ token = match.group(1)+ if token.isupper() and any(ch.isalpha() for ch in token):+ return token+ return None+++def _landing_url(snapshot: Dict[str, Any]) -> str:+ link = str(snapshot.get("link_url") or "").strip()+ if link:+ return link+ for card in _cards(snapshot):+ card_link = str(card.get("link_url") or "").strip()+ if card_link:+ return card_link+ return ""+++def _placements(row: Dict[str, Any]) -> List[str]:+ raw = row.get("publisher_platform")+ if not isinstance(raw, list):+ return []+ return [str(p).strip() for p in raw if str(p or "").strip()]+++def _variants(row: Dict[str, Any]) -> int:+ try:+ count = int(row.get("collation_count") or 0)+ except (TypeError, ValueError):+ count = 0+ return max(1, count)+++def build_item(row: Dict[str, Any], page: Dict[str, Any]) -> Dict[str, Any]:+ """Turn one ad row into a normalizer-ready item dict."""+ snapshot = _snapshot(row)+ body = _body_text(snapshot)+ title = str(snapshot.get("title") or "").strip()+ if not title:+ title = body.split("\n", 1)[0][:140]+ archive_id = str(row.get("ad_archive_id") or "").strip()+ url = str(row.get("url") or "").strip()+ if not url and archive_id:+ url = f"https://www.facebook.com/ads/library/?id={archive_id}"+ placements = _placements(row)+ return {+ "id": archive_id or dedupe_key(row),+ "title": title,+ "text": body,+ "url": url,+ "date": launch_date(row),+ "advertiser": page.get("name") or "",+ "page_id": page.get("id") or "",+ "is_active": bool(row.get("is_active")),+ "ended_on": str(row.get("end_date_string") or "")[:10] or None,+ "display_format": str(snapshot.get("display_format") or "").strip(),+ "cta": str(snapshot.get("cta_text") or "").strip(),+ "landing_url": _landing_url(snapshot),+ "placements": placements,+ "promo_code": extract_promo_code(body),+ "variants": _variants(row),+ "has_video": has_video(row),+ "transcript": "",+ }+++# ------------------------------------------------------------ HTTP helpers+++class _Budget:+ """Monotonic wall-clock budget shared by every call in one lane run."""++ def __init__(self, seconds: float = LANE_BUDGET_SECONDS) -> None:+ self.deadline = time.monotonic() + seconds++ @property+ def remaining(self) -> float:+ return self.deadline - time.monotonic()++ def exhausted(self) -> bool:+ return self.remaining <= 0++ def timeout(self, ceiling: float = REQUEST_TIMEOUT) -> float:+ return max(MIN_REQUEST_TIMEOUT, min(ceiling, self.remaining))+++class _Fatal(Exception):+ """A lane-ending failure: no further calls may be made."""++ def __init__(self, message: str, status: Optional[int] = None) -> None:+ super().__init__(message)+ self.status = status+++class _StopFetching(Exception):+ """Stop making calls, but keep whatever already came back.++ Distinct from ``_Fatal`` on purpose. A credential or account failure+ invalidates the lane itself, so its output is discarded. Running out of+ wall clock, or a transient upstream failure partway through pagination,+ only ends the *fetching*: the creatives already in hand are real evidence+ and are reported as a partial result rather than thrown away.+ """+++def _call(+ url: str,+ params: Dict[str, Any],+ token: str,+ budget: _Budget,+ ceiling: float = REQUEST_TIMEOUT,+) -> Dict[str, Any]:+ """One metered GET.++ ``max_429_retries=0`` matters: the shared client retries a 429 twice by+ default, which both contradicts the no-further-calls contract for a rate+ limit and spends the lane budget sleeping between attempts.+ """+ if budget.exhausted():+ raise _StopFetching("lane budget exhausted")+ try:+ response = http.get(+ url,+ params=params,+ headers=http.scrapecreators_headers(token),+ timeout=budget.timeout(ceiling),+ retries=1,+ max_429_retries=0,+ deadline_monotonic=budget.deadline,+ )+ except http.HTTPError as exc:+ status = exc.status_code+ message = f"HTTP {status}: {exc}" if status else str(exc)+ if status in FATAL_STATUS_CODES:+ # Credential- or account-scoped: every later call fails the same+ # way, so the lane ends and keeps nothing.+ raise _Fatal(message, status) from exc+ # Anything else (a 5xx, a bad gateway partway through pagination) is+ # about this one request. Stop fetching, but keep the creatives+ # already retrieved rather than discarding paid-for work.+ raise _StopFetching(message) from exc+ except Exception as exc: # noqa: BLE001 - an unclassifiable transport failure+ raise _Fatal(f"{type(exc).__name__}: {exc}") from exc+ return response if isinstance(response, dict) else {}+++# ------------------------------------------------------------ lane stages+++def _discover(+ topic: str, country: str, token: str, budget: _Budget+) -> Tuple[Optional[Dict[str, Any]], List[str], str, str, str]:+ """Resolve the advertiser page.++ Returns ``(page, runner_ups, top_unmatched, state, strength)``.+ """+ response = _call(+ SEARCH_ADS_URL,+ {+ "query": topic,+ "country": country,+ "status": DISCOVERY_STATUS,+ "search_type": DISCOVERY_SEARCH_TYPE,+ "trim": "true",+ },+ token,+ budget,+ )+ rows = _envelope_rows(response)+ page, runner_ups, top, strength = resolve_page(topic, rows)+ if page:+ _log(+ f"Resolved advertiser '{page['name']}' (page {page['id']}) "+ f"from ad search by {strength} name match"+ )+ return page, runner_ups, "", RESOLVED, strength++ companies = _call(SEARCH_COMPANIES_URL, {"query": topic}, token, budget)+ # Reshape company rows into the same shape resolve_page reads, so the+ # fallback gets the identical exact-before-partial tiering. Taking the+ # first name that merely matched would let this path resolve a lookalike+ # the primary path would have rejected.+ company_rows = [+ {"page_id": str(row.get("page_id") or "").strip(),+ "page_name": str(row.get("name") or "").strip()}+ for row in _envelope_rows(companies)+ if str(row.get("page_id") or "").strip()+ ]+ company_page, company_runner_ups, company_top, company_strength = resolve_page(+ topic, company_rows+ )+ if company_page:+ _log(+ f"Resolved advertiser '{company_page['name']}' "+ f"(page {company_page['id']}) from company search by "+ f"{company_strength} name match"+ )+ return company_page, company_runner_ups, "", RESOLVED, company_strength++ fallback_top = top or company_top+ if not rows and not company_rows:+ _log("No advertiser candidates returned by either search")+ return None, [], "", NO_CANDIDATES, MATCH_NONE+ _log(f"No advertiser matched '{topic}'; closest was '{fallback_top}'")+ return None, [], fallback_top, UNRESOLVED, MATCH_NONE+++def _fetch_window(+ page: Dict[str, Any],+ country: str,+ from_date: str,+ to_date: str,+ max_pages: int,+ token: str,+ budget: _Budget,+) -> Tuple[List[Dict[str, Any]], int, bool, str]:+ """Cursor-paginate the page's window ads.++ Returns ``(rows, endpoint_total, more_available, interruption)``, where+ ``interruption`` is the reason fetching stopped early (empty when it ran+ to its natural end). It is carried verbatim rather than summarized: a+ transient upstream failure and an exhausted clock produce the same partial+ shape, and reporting one as the other sends the reader to fix the wrong+ thing.+ """+ rows: List[Dict[str, Any]] = []+ total = 0+ cursor: Optional[str] = None+ prev_cursor: Optional[str] = None+ more = False+ interruption = ""+ pages = min(max_pages, MAX_PAGES_HARD)+ stop = "page cap reached"++ for _ in range(pages):+ params: Dict[str, Any] = {+ "pageId": page["id"],+ "country": country,+ "status": ENRICHMENT_STATUS,+ "start_date": from_date,+ "end_date": to_date,+ }+ if cursor:+ params["cursor"] = cursor+ try:+ response = _call(COMPANY_ADS_URL, params, token, budget)+ except (_Fatal, _StopFetching) as exc:+ # Whatever the reason, the creatives already fetched were paid for+ # and are valid: a rate limit or expired credential says "stop+ # calling", not "the pages that already returned 200 were wrong".+ stop = str(exc)+ interruption = str(exc)+ more = True+ break+ page_rows = _envelope_rows(response)+ total = _envelope_total(response) or total+ if not page_rows:+ stop = "empty page"+ break+ rows.extend(page_rows)+ cursor = _envelope_cursor(response)+ if not cursor:+ stop = "no cursor"+ break+ if cursor == prev_cursor:+ stop = "cursor stopped advancing"+ break+ prev_cursor = cursor+ else:+ more = bool(cursor)++ _log(f" fetched {len(rows)} ad rows of {total or len(rows)}, stopped: {stop}")+ return rows, total, more, interruption+++def _classify(+ rows: List[Dict[str, Any]],+ page: Dict[str, Any],+ from_date: str,+ to_date: str,+) -> Tuple[List[Dict[str, Any]], int]:+ """Split deduped rows into in-window items and a still-running tally.++ The endpoint's date filter returns everything *active during* the window,+ which on a busy page is mostly creatives launched months earlier. The+ last-30-days signal is what launched inside it; the rest are counted so+ the footer can say how much steady-state advertising sits behind them.+ """+ seen: set[str] = set()+ items: List[Dict[str, Any]] = []+ still_running = 0+ for row in rows:+ key = dedupe_key(row)+ if key in seen:+ continue+ seen.add(key)+ launched = launch_date(row)+ if launched and from_date <= launched <= to_date:+ items.append(build_item(row, page))+ else:+ still_running += 1+ items.sort(key=lambda item: item.get("date") or "", reverse=True)+ return items, still_running+++def _add_transcripts(+ items: List[Dict[str, Any]], cap: int, token: str, budget: _Budget+) -> Tuple[int, str]:+ """Transcribe the newest video creatives.++ Candidates are chosen from the whole fetched set, after every page is in,+ so a newer creative on page two is not passed over for an older one on+ page one. Returns ``(transcribed, interruption)``.+ """+ if cap <= 0:+ return 0, ""+ transcribed = 0+ # The cap bounds paid REQUESTS, not successes. Counting only successes+ # would keep calling for every remaining video creative whenever the+ # upstream has no transcript available -- each of those still costs a+ # credit, so a page of silent video ads would blow through the run's whole+ # documented credit ceiling while the tally still read zero.+ candidates = [item for item in items if item.get("has_video")][:cap]+ for item in candidates:+ try:+ response = _call(+ AD_TRANSCRIPT_URL,+ {"id": item["id"]},+ token,+ budget,+ ceiling=TRANSCRIPT_TIMEOUT,+ )+ except (_Fatal, _StopFetching) as exc:+ return transcribed, str(exc)+ if not response.get("transcript_available"):+ continue+ text = str(response.get("transcript") or "").strip()+ if not text:+ continue+ item["transcript"] = text+ transcribed += 1+ return transcribed, ""+++def _empty_tally(state: str, **extra: Any) -> Dict[str, Any]:+ tally = {+ "resolution": state,+ "launched_in_window": 0,+ "still_running": 0,+ "video": 0,+ "transcribed": 0,+ "fetched": 0,+ "endpoint_total": 0,+ "cursor_remaining": False,+ "placements": [],+ "promo_codes": [],+ "advertiser": "",+ "page_id": "",+ "top_candidate": "",+ "runner_ups": [],+ "match_strength": MATCH_NONE,+ }+ tally.update(extra)+ return tally+++# ------------------------------------------------------------ public entry+++def search_meta_ads(+ topic: str,+ from_date: str,+ to_date: str,+ depth: str = "default",+ token: str = "",+ country: str = DEFAULT_COUNTRY,+ page_override: str = "",+) -> Dict[str, Any]:+ """Resolve an advertiser and return its in-window creatives.++ Returns ``{"ads", "page", "tally", "partial"?, "error"?}``. ``ads`` are+ normalizer-ready item dicts; ``tally`` carries every count the footer+ renders, computed here rather than downstream because the pipeline+ truncates each source's stream to a per-depth limit before rendering.+ """+ topic = (topic or "").strip()+ if not token:+ _log("No SCRAPECREATORS_API_KEY - skipping")+ return {"ads": [], "page": None, "tally": _empty_tally(UNRESOLVED)}+ if not topic and not page_override:+ _log("Empty topic - skipping")+ return {"ads": [], "page": None, "tally": _empty_tally(UNRESOLVED)}++ cfg = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])+ country = (country or DEFAULT_COUNTRY).strip() or DEFAULT_COUNTRY+ budget = _Budget()++ try:+ if page_override:+ page: Optional[Dict[str, Any]] = {"id": page_override, "name": topic or page_override}+ runner_ups: List[str] = []+ top_candidate = ""+ state = RESOLVED+ strength = MATCH_EXACT+ _log(f"Using page override {page_override}")+ else:+ page, runner_ups, top_candidate, state, strength = _discover(+ topic, country, token, budget+ )++ if page is None:+ return {+ "ads": [],+ "page": None,+ "tally": _empty_tally(state, top_candidate=top_candidate),+ }++ rows, endpoint_total, more, interruption = _fetch_window(+ page, country, from_date, to_date, cfg["pages"], token, budget+ )+ items, still_running = _classify(rows, page, from_date, to_date)+ transcribed, transcript_interruption = _add_transcripts(+ items, cfg["transcripts"], token, budget+ )+ interruption = interruption or transcript_interruption+ except (_Fatal, _StopFetching) as exc:+ # Nothing was salvageable: either a credential/account failure, or the+ # clock ran out before the advertiser was even resolved.+ _log(f"Lane stopped: {exc}")+ return {+ "ads": [],+ "page": None,+ "tally": _empty_tally(UNRESOLVED),+ "error": str(exc),+ }++ placements: List[str] = []+ promo_codes: List[str] = []+ for item in items:+ for placement in item["placements"]:+ if placement not in placements:+ placements.append(placement)+ code = item.get("promo_code")+ if code and code not in promo_codes:+ promo_codes.append(code)++ tally = _empty_tally(+ RESOLVED,+ launched_in_window=len(items),+ still_running=still_running,+ video=sum(1 for item in items if item.get("has_video")),+ transcribed=transcribed,+ fetched=len(rows),+ endpoint_total=endpoint_total,+ cursor_remaining=more,+ placements=placements,+ promo_codes=promo_codes,+ advertiser=page.get("name") or "",+ page_id=page.get("id") or "",+ runner_ups=runner_ups,+ match_strength=strength,+ )++ result: Dict[str, Any] = {"ads": items, "page": page, "tally": tally}+ if interruption:+ # Keep what came back. Thin coverage caused by our own clock or one+ # failed request must not read as a finding about how much the+ # advertiser is running.+ result["partial"] = True+ result["error"] = interruption++ _log(+ f"{len(items)} creative(s) launched in window for '{page['name']}' "+ f"({still_running} still running from before, {transcribed} transcribed)"+ )+ return resultdiff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.pyindex 7490ba8e..352233f3 100644--- a/skills/last30days/scripts/lib/normalize.py+++ b/skills/last30days/scripts/lib/normalize.py@@ -69,6 +69,7 @@ def normalize_source_items("techmeme": _normalize_techmeme,"trustpilot": _normalize_trustpilot,"amazon": _normalize_amazon,+ "meta_ads": _normalize_meta_ads,"grounding": _normalize_grounding,"xiaohongshu": _normalize_grounding,"github": _normalize_github,@@ -718,6 +719,92 @@ def _normalize_techmeme()+def _normalize_meta_ads(+ source: str,+ item: dict[str, Any],+ index: int,+ from_date: str,+ to_date: str,+) -> schema.SourceItem:+ """Normalizer for Meta Ad Library creatives.++ One item per distinct creative launched inside the window. Identity is the+ Ad Library permalink, never the landing URL: many creatives for one product+ share a landing page, and fusion merges by normalized URL, so keying on the+ landing page would collapse a whole campaign into one candidate and lose+ every transcript but the first.++ Grounding-exempt on the Amazon precedent. Ad copy is written to sell, not+ to name the brand -- "Stop making boring drinks" never repeats the topic --+ and the advertiser page was already resolved by name before any of these+ were created, so they are on-entity by construction.+ """+ body = str(item.get("text") or "").strip()+ transcript = str(item.get("transcript") or "").strip()+ advertiser = str(item.get("advertiser") or "").strip()+ cta = str(item.get("cta") or "").strip()+ landing = str(item.get("landing_url") or "").strip()+ placements = [str(p) for p in (item.get("placements") or [])]+ promo = str(item.get("promo_code") or "").strip()++ # The spoken script is usually the sharper version of the pitch, so it+ # leads the evidence snippet when present.+ snippet_parts = [part for part in [body, transcript] if part]+ # The adapter deliberately keeps creatives that launched inside the window+ # and have since ended -- a one-week promo push is exactly the signal this+ # source exists for -- so the wording has to follow the stored state rather+ # than calling every creative active.+ running = bool(item.get("is_active"))+ ended_on = str(item.get("ended_on") or "").strip()+ if running:+ state_word = "Running paid creative"+ elif ended_on:+ state_word = f"Paid creative that ran until {ended_on}"+ else:+ state_word = "Paid creative that has since ended"+ default_why = f"{state_word} from {advertiser}" if advertiser else state_word+ context = " │ ".join(+ part+ for part in [+ cta or "",+ f"code {promo}" if promo else "",+ landing,+ ]+ if part+ )+ return _source_item(+ item_id=str(item.get("id") or f"MA{index + 1}"),+ source=source,+ title=str(item.get("title") or "").strip() or body[:140] or f"Meta ad {index + 1}",+ body=body,+ url=str(item.get("url") or "").strip(),+ author=advertiser,+ container="Meta Ad Library",+ published_at=item.get("date"),+ date_confidence=_date_confidence(item, from_date, to_date, default="high"),+ engagement={"variants": int(item.get("variants") or 1)},+ relevance_hint=0.8,+ why_relevant=str(item.get("why_relevant") or "") or default_why,+ snippet=" ".join(snippet_parts)[:400],+ metadata={+ "grounding_exempt": True,+ "advertiser": advertiser,+ "page_id": str(item.get("page_id") or ""),+ "is_active": bool(item.get("is_active")),+ "ended_on": item.get("ended_on"),+ "display_format": str(item.get("display_format") or ""),+ "placements": placements,+ "cta": cta,+ "landing_url": landing,+ "promo_code": promo,+ "variants": int(item.get("variants") or 1),+ "has_video": bool(item.get("has_video")),+ "transcript_snippet": transcript[:400],+ "ad_context": context,+ },+ )++def _normalize_trustpilot(source: str,item: dict[str, Any],diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex e1f352f4..15f991eb 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -45,6 +45,7 @@ from . import (library,library_index,log,+ meta_ads,normalize,permission_preflight,perplexity,@@ -100,6 +101,8 @@ SEARCH_ALIAS = {"truth": "truthsocial","web": "grounding","xhs": "xiaohongshu",+ "meta": "meta_ads",+ "meta-ads": "meta_ads","xquik": "x", # xquik is a backend of the single "x" source, not its own source}@@ -109,11 +112,43 @@ SEARCH_ALIAS = {# amazon is capped at 1 for the same reason as trustpilot: the model supplies# one product keyword for the run, so every subquery would issue the identical# product search. Extra streams would be pure redundancy at one credit each.+# meta_ads is capped at 1 for the same reason as amazon: one advertiser page is+# resolved per run, so every subquery would issue the identical page fetch.MAX_SOURCE_FETCHES: dict[str, int] = {"x": 2, "jobs": 1, "linkedin": 1, "stocktwits": 1, "trustpilot": 1, "amazon": 1,- "telegram": 1,+ "telegram": 1, "meta_ads": 1,}+# Sources whose thin result is their normal success state, so the "<3 items"+# retry would re-fetch them after every success -- bypassing+# MAX_SOURCE_FETCHES and, for the resolved-entity sources, re-resolving+# WITHOUT the caller's override (a lookalike-misattribution path).+# trustpilot returns at most ONE item by design.+# perplexity answers once per run.+# meta_ads resolves one advertiser page per run, so a brand that genuinely+# ran two creatives this month is complete; a retry would re-resolve the+# page and re-spend the discovery credit.+THIN_RETRY_EXEMPT: frozenset[str] = frozenset({"trustpilot", "perplexity", "meta_ads"})++# Stream-artifact keys promoted to named top-level report artifacts. A stream+# artifact only ever reaches the report as an anonymous entry in the grounding+# list, so anything the renderer needs by name has to be lifted out of it --+# most importantly on a zero-item run, which is exactly when naming the+# resolved advertiser and its counts matters most.+STREAM_ARTIFACT_LIFT_KEYS: tuple[str, ...] = ("meta_ads_page", "meta_ads_tally")+++def _lift_stream_artifacts(bundle) -> None:+ """Promote per-stream artifacts the renderer reads by name."""+ for stream_artifact in bundle.artifacts.get("grounding", []):+ if not isinstance(stream_artifact, dict):+ continue+ for key in STREAM_ARTIFACT_LIFT_KEYS:+ value = stream_artifact.get(key)+ if value:+ bundle.artifacts[key] = value++_FAILURE_SPECIFICITY = {health.AUTH_FAILED: 0,health.PAYMENT_REQUIRED: 1,@@ -217,6 +252,7 @@ MOCK_AVAILABLE_SOURCES = ["techmeme","trustpilot","amazon",+ "meta_ads","jobs","linkedin","corpus",@@ -366,6 +402,17 @@ def available_sources("amazon" in include_sources or (requested_sources and "amazon" in requested_sources)):available.append("amazon")+ # Meta Ads: opt-in additive source on the Amazon precedent. The+ # ScrapeCreators key must be present AND the run must ask for it -- the+ # model per-run via --search, or the user durably via+ # INCLUDE_SOURCES=meta_ads. Never inferred from topic shape: keyword ad+ # search on a non-brand topic returns a wrong-entity advertiser, and+ # auto-firing would spend credits resolving it.+ if config.get("SCRAPECREATORS_API_KEY") and (+ "meta_ads" in include_sources+ or (requested_sources and "meta_ads" in requested_sources)+ ):+ available.append("meta_ads")if ("xiaohongshu" in include_sourcesor (requested_sources and "xiaohongshu" in requested_sources)@@ -2814,10 +2861,16 @@ def run(# marking the source PARTIAL would trip LAST30DAYS_STRICT_EXIT on runs that# returned good X results.warnings.extend(bundle.artifacts.get("x_partial_coverage", []))- # Backend receipts that are not failures (xapi's truncated window).+ # Backend receipts that are not failures (xapi's truncated window), and+ # the Meta Ads footer inputs. A stream artifact only ever reaches the+ # report as an anonymous entry in this list, so the advertiser and the+ # pre-truncation counts have to be lifted to named top-level artifacts or+ # the footer cannot render them -- least of all on a zero-item run, which+ # is exactly when naming the advertiser matters most.for stream_artifact in bundle.artifacts.get("grounding", []):if isinstance(stream_artifact, dict):warnings.extend(stream_artifact.get("x_receipts", []))+ _lift_stream_artifacts(bundle)library_context, library_warning = _load_library_context(topic=topic,config=config,@@ -4259,12 +4312,7 @@ def _retry_thin_sources(for source in subquery.sources:if source not in planned_sources:planned_sources.append(source)- # trustpilot returns at most ONE item by design, so the "<3 items" rule- # would re-fetch it after every successful lookup -- bypassing- # MAX_SOURCE_FETCHES and re-resolving WITHOUT the caller's- # --trustpilot-domain (a lookalike-misattribution path). Its thin result- # is its normal success state; never retry it here.- _skip = (skip_sources or set()) | {"trustpilot", "perplexity"}+ _skip = (skip_sources or set()) | THIN_RETRY_EXEMPTthin_sources = [sourcefor source in planned_sources@@ -5219,6 +5267,42 @@ def _retrieve_stream_impl(}return enriched, artifact+ if source == "meta_ads":+ # The advertiser is resolved from the stable research topic, not the+ # narrowed per-subquery search_query: a subquery like "kettle reviews"+ # would resolve a different page than the brand the run is about.+ brand = raw_topic or topic or subquery.search_query+ result = meta_ads.search_meta_ads(+ brand,+ from_date,+ to_date,+ depth=depth,+ token=(config or {}).get("SCRAPECREATORS_API_KEY") or "",+ country=str(+ (config or {}).get("LAST30DAYS_META_ADS_COUNTRY")+ or meta_ads.DEFAULT_COUNTRY+ ),+ page_override=str((config or {}).get("_meta_ads_page") or "").strip(),+ )+ if result.get("partial"):+ # A partial lane carries `error` too, so the generic classifier+ # would run and have its verdict overwritten here regardless.+ artifact = {+ "_source_outcome": {+ "state": schema.PARTIAL,+ "detail": str(result.get("error") or "partial"),+ "attempted": True,+ }+ }+ else:+ artifact = dict(_result_outcome_artifact(source, result) or {})+ # The footer needs the resolved advertiser and the pre-truncation+ # counts even on a run that produced zero items, and stream artifacts+ # only reach the report through the grounding list, so they ride here+ # and are lifted to top-level artifacts after retrieval.+ artifact["meta_ads_page"] = result.get("page") or {}+ artifact["meta_ads_tally"] = result.get("tally") or {}+ return result.get("ads") or [], artifactif source == "bluesky":result = bluesky.search_bluesky(subquery.search_query, from_date, to_date, depth=depth, config=config)return bluesky.parse_bluesky_response(result), _result_outcome_artifact(source, result)diff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.pyindex 02a4cdd6..f0b1a703 100644--- a/skills/last30days/scripts/lib/planner.py+++ b/skills/last30days/scripts/lib/planner.py@@ -151,6 +151,7 @@ SOURCE_CAPABILITIES = {"techmeme": {"discussion", "link", "reference"},"trustpilot": {"reference", "company_signal", "social"},"amazon": {"reference", "company_signal", "product_signal"},+ "meta_ads": {"reference", "company_signal", "product_signal"},"xiaohongshu": {"video", "video_shortform", "social"},"telegram": {"discussion", "social"},"github": {"discussion", "link"},diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.pyindex d69e72bd..0cf07964 100644--- a/skills/last30days/scripts/lib/render.py+++ b/skills/last30days/scripts/lib/render.py@@ -15,6 +15,7 @@ from . import (health,hiring_signals,library_index,+ meta_ads,registers,relevance,rerank,@@ -229,6 +230,7 @@ SOURCE_LABELS = {"techmeme": "Techmeme","trustpilot": "Trustpilot","amazon": "Amazon",+ "meta_ads": "Meta Ads","perplexity": "Perplexity","jobs": "Jobs","corpus": "Your files",@@ -2877,6 +2879,10 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:if amazon_line:out.append(amazon_line)+ meta_ads_line = _meta_ads_footer_line(report)+ if meta_ads_line:+ out.append(meta_ads_line)+# Web (sources from grounding)web_items = report.items_by_source.get("grounding") or []if web_items:@@ -2992,6 +2998,145 @@ def _amazon_footer_line(report: schema.Report) -> str | None:return line+# Longest advertiser or candidate name the footer will print. The footer is one+# scannable line inside a box; an unbounded source-controlled name would push+# every other source's line out of view.+_META_ADS_NAME_MAX = 32+++def _footer_safe(value: str, limit: int = _META_ADS_NAME_MAX) -> str:+ """Make a source-controlled string safe to interpolate into a footer line.++ The advertiser name, the closest-candidate name, and the promo codes all+ come from the upstream API, so they are attacker-influenceable. Left raw, a+ name carrying a newline or the footer's own separator could forge extra+ footer rows in the passed-through emoji tree, which the model relays+ verbatim. Collapse control characters and the separator, then clip.+ """+ cleaned = _sanitize_url_for_single_line_output(str(value or "")).replace("│", "|")+ cleaned = " ".join(cleaned.split()).strip()+ if len(cleaned) > limit:+ cleaned = cleaned[:limit].rstrip() + "…"+ return cleaned+++_PLACEMENT_SHORT = {+ "FACEBOOK": "FB",+ "INSTAGRAM": "IG",+ "THREADS": "Threads",+ "MESSENGER": "Messenger",+ "WHATSAPP": "WhatsApp",+ "AUDIENCE_NETWORK": "Audience",+}+++def _meta_ads_footer_line(report: schema.Report) -> str | None:+ """Build the 📣 Meta Ads emoji-footer line.++ Every count comes from the adapter's tally, never from ``items_by_source``.+ The pipeline truncates each source's stream to a per-depth limit (12 at+ default) before rendering, so counting surviving items would report 12+ creatives for a page that ran thirty, and would under-count the video and+ transcript work that was actually paid for.++ Four shapes, because an empty line is never the right answer here -- if the+ lane ran and found nothing, the reader needs to know which nothing it was:++ * **Resolved with creatives** -- advertiser, what launched this window, and+ the paid-media detail (placements, promo codes, transcripts).+ * **Resolved, nothing new** -- name the advertiser and how much it is still+ running from before, so "no ads" is not confused with "not advertising".+ * **Unresolved** -- name the closest candidate and point at the override.+ * **Failed** -- name the outcome rather than implying an empty Ad Library.+ """+ tally = (report.artifacts or {}).get("meta_ads_tally") or {}+ page = (report.artifacts or {}).get("meta_ads_page") or {}+ outcome = report.source_status.get("meta_ads")+ if not tally and not page and outcome is None:+ return None++ # Three distinct states, and conflating any two of them misleads:+ # failed -- the lane could not run; say so, never "found nothing".+ # partial -- it ran and was cut short; its counts are a floor, so a+ # "nothing new" conclusion drawn from them would be a+ # claim the data does not support.+ # no results -- it ran to completion and the answer is genuinely empty.+ # NO_RESULTS is what the pipeline stamps on any zero-item source, so+ # treating it as failure would collapse every honest empty state below into+ # a generic "no ads pulled".+ state = getattr(outcome, "state", None)+ detail = str(getattr(outcome, "detail", "") or "").strip()+ if outcome and state not in (health.OK, schema.PARTIAL, schema.NO_RESULTS):+ return f"📣 Meta Ads: no ads pulled ({detail})" if detail else "📣 Meta Ads: no ads pulled"+ cut_short = state == schema.PARTIAL++ resolution = str(tally.get("resolution") or "")+ if resolution == meta_ads.NO_CANDIDATES:+ return "📣 Meta Ads: no advertiser candidates returned │ pass --meta-ads-page to target one"+ if resolution == meta_ads.UNRESOLVED or not page:+ candidate = _footer_safe(tally.get("top_candidate") or "")+ if candidate:+ return (+ f"📣 Meta Ads: no advertiser matched │ closest: {candidate} "+ f"│ pass --meta-ads-page to target one"+ )+ return "📣 Meta Ads: no advertiser matched │ pass --meta-ads-page to target one"++ advertiser = _footer_safe(page.get("name") or tally.get("advertiser") or "")+ launched = int(tally.get("launched_in_window") or 0)+ still = int(tally.get("still_running") or 0)++ if not launched:+ # A cut-short lane never reached the end of the page, so "no new+ # creatives" would state a conclusion its own data cannot support.+ if cut_short:+ head = f"📣 Meta Ads: {advertiser} │ incomplete".rstrip()+ parts = [head, "no new creatives seen before the run was cut short"]+ if detail:+ parts.append(_footer_safe(detail, 60))+ return " │ ".join(parts)+ parts = [f"📣 Meta Ads: no new creatives for {advertiser}".rstrip()]+ if still:+ parts.append(f"{still} still running from before")+ return " │ ".join(parts)++ fetched = int(tally.get("fetched") or 0)+ total = int(tally.get("endpoint_total") or 0)+ # A page bigger than the depth cap is a sample, and saying so is the+ # difference between "this brand launched 12 creatives" and "we looked at+ # 60 of its 222 live ads and 12 of those were new". The two numbers are+ # different units on purpose -- deduped creatives against raw ads -- so+ # both get named rather than sharing one bare noun.+ if tally.get("cursor_remaining") and total > fetched > 0:+ head = f"{launched} new of {fetched} ads fetched ({total:,} live)"+ else:+ head = f"{launched} new {'creative' if launched == 1 else 'creatives'}"++ parts = [f"📣 Meta Ads: {advertiser} │ {head}"] if advertiser else [f"📣 Meta Ads: {head}"]+ if cut_short:+ parts.append("incomplete")+ if still:+ parts.append(f"{still} running from before")+ # Resolution that rested on substring containment is the weakest tier the+ # resolver accepts, so the reader is told to check the advertiser rather+ # than left to assume the name was confirmed.+ if str(tally.get("match_strength") or "") == meta_ads.MATCH_CONTAINED:+ parts.append("matched by partial name")+ placements = [+ _PLACEMENT_SHORT.get(str(p).upper(), _footer_safe(p, 12))+ for p in (tally.get("placements") or [])+ ]+ if placements:+ parts.append(", ".join(placements))+ codes = [_footer_safe(c, 16) for c in (tally.get("promo_codes") or []) if c]+ if codes:+ parts.append(f"code {', '.join(codes)}")+ transcribed = int(tally.get("transcribed") or 0)+ if transcribed:+ parts.append(f"{transcribed} transcribed")+ return " │ ".join(parts)++def _top_voices_footer_line(report: schema.Report) -> str | None:"""Return the 🗣️ Top voices line or None if no meaningful voices exist.@@ -3210,6 +3355,7 @@ ENGAGEMENT_DISPLAY: dict[str, list[tuple[str, str]]] = {"digg": [("postCount", "posts"), ("uniqueAuthors", "auth")],"trustpilot": [("reviews", "reviews")],"amazon": [("ratings", "ratings")],+ "meta_ads": [("variants", "variants")],}diff --git a/skills/last30days/scripts/lib/signals.py b/skills/last30days/scripts/lib/signals.pyindex 6ae8518c..9d929854 100644--- a/skills/last30days/scripts/lib/signals.py+++ b/skills/last30days/scripts/lib/signals.py@@ -20,6 +20,10 @@ SOURCE_QUALITY = {# Verified-purchase reviews on a live aggregate rating: high-quality# buyer evidence, a notch above Trustpilot's open review model."amazon": 0.8,+ # Paid creative is first-party marketing copy: a reliable statement of+ # what the brand is pushing, but not independent evidence about it, so it+ # sits below the review-backed sources and above open social.+ "meta_ads": 0.72,"reddit": 0.6,"x": 0.68,"bluesky": 0.66,@@ -183,6 +187,11 @@ ENGAGEMENT_WEIGHTS: dict[str, list[tuple[str, float]]] = {"digg": [("postCount", 0.40), ("uniqueAuthors", 0.30), ("rank_score", 0.30)],"trustpilot": [("reviews", 1.0)],"amazon": [("ratings", 1.0)],+ # Meta publishes reach and spend only for political and issue ads, so a+ # commercial creative has no audience signal at all. How many variants a+ # brand cut of one creative is the closest honest proxy for how hard it is+ # pushing that message.+ "meta_ads": [("variants", 1.0)],}diff --git a/skills/last30days/scripts/lib/ui.py b/skills/last30days/scripts/lib/ui.pyindex bbac763b..c3b888e9 100644--- a/skills/last30days/scripts/lib/ui.py+++ b/skills/last30days/scripts/lib/ui.py@@ -131,6 +131,7 @@ SOURCE_COMPLETION_ORDER = ["techmeme","trustpilot","amazon",+ "meta_ads",]SOURCE_COMPLETION_META = {@@ -150,6 +151,7 @@ SOURCE_COMPLETION_META = {"techmeme": ("Techmeme", "headline", "headlines", Colors.CYAN),"trustpilot": ("Trustpilot", "review", "reviews", Colors.GREEN),"amazon": ("Amazon", "product", "products", Colors.YELLOW),+ "meta_ads": ("Meta Ads", "creative", "creatives", Colors.BLUE),}diff --git a/tests/test_meta_ads.py b/tests/test_meta_ads.pynew file mode 100644index 00000000..21ffb814--- /dev/null+++ b/tests/test_meta_ads.py@@ -0,0 +1,844 @@+"""Tests for the Meta Ad Library source.++Nothing here spawns a subprocess or touches the network. Fixture shapes mirror+live ScrapeCreators payloads captured 2026-09-14 (envelope keys, snapshot+fields, the searchResults/results asymmetry, null collation ids); brand names+are invented.+"""++import datetime+from unittest import mock++import pytest++from lib import meta_ads+from lib.meta_ads import (+ NO_CANDIDATES,+ RESOLVED,+ UNRESOLVED,+ build_item,+ dedupe_key,+ extract_promo_code,+ has_video,+ launch_date,+ names_match,+ resolve_page,+ search_meta_ads,+)++FROM_DATE = "2026-08-15"+TO_DATE = "2026-09-14"+TOKEN = "fake-sc-key"+++def ad_row(**over):+ """One ad row in the live shape (trimmed of media blobs)."""+ base = {+ "ad_archive_id": "1000000000000001",+ "collation_id": "col-1",+ "collation_count": 3,+ "page_id": "300000000000001",+ "page_name": "Brightpan",+ "is_active": True,+ "start_date_string": "2026-09-01T07:00:00.000Z",+ "end_date_string": "2026-09-14T07:00:00.000Z",+ "publisher_platform": ["FACEBOOK", "INSTAGRAM", "THREADS"],+ "url": "https://www.facebook.com/ads/library/?id=1000000000000001",+ "reach_estimate": None,+ "spend": None,+ "snapshot": {+ "body": {"text": "Better mornings start here. Shop the Brightpan kettle."},+ "title": "",+ "cta_text": "Shop now",+ "display_format": "DCO",+ "link_url": "https://brightpan.example/collections/kettles",+ "cards": [],+ "videos": [],+ },+ }+ base.update(over)+ return base+++def envelope(rows, key="searchResults", total=None, cursor=""):+ return {+ "success": True,+ "credits_remaining": 999,+ "credits_charged": 1,+ key: rows,+ "searchResultsCount": len(rows) if total is None else total,+ "cursor": cursor,+ }+++def company_row(page_id, name, likes=100):+ return {+ "page_id": page_id,+ "name": name,+ "likes": likes,+ "category": "Appliances",+ "verification": "NOT_VERIFIED",+ "ig_username": "",+ }+++class TestNameMatching:+ def test_exact_brand_matches(self):+ assert names_match("Brightpan", "Brightpan")++ def test_product_page_matches_umbrella_topic_by_shared_token(self):+ # The umbrella brand advertises under product-line pages; containment+ # in either direction is what resolves them.+ assert names_match("BrightpanCo", "Brightpan Kitchen")++ def test_short_token_never_matches(self):+ # "ai" is below the four-character floor, so an unrelated advertiser+ # that shares only that word must not match.+ assert not names_match("Vantage AI", "Jasper AI")++ def test_no_synonym_expansion(self):+ # The shared scoring tokenizer expands "ai" to artificial/intelligence.+ # Matching must not, or this pair would resolve as the same brand.+ assert not names_match("Vantage AI", "Artificial Intelligence Labs")++ def test_unrelated_names_do_not_match(self):+ assert not names_match("Brightpan", "Coastal Realty Group")++ def test_case_and_spacing_are_normalized(self):+ assert names_match("Bright iQ", "brightiq")+++class TestResolvePage:+ def test_umbrella_brand_resolves_dominant_product_page(self):+ rows = (+ [ad_row(page_id="1", page_name="Brightpan Kitchen") for _ in range(14)]+ + [ad_row(page_id="2", page_name="Brightpan Beauty") for _ in range(5)]+ + [ad_row(page_id="3", page_name="Brightpan Home") for _ in range(4)]+ + [ad_row(page_id="9", page_name="Unrelated Deals Co") for _ in range(20)]+ )+ page, runner_ups, top, _strength = resolve_page("BrightpanCo", rows)+ assert page["name"] == "Brightpan Kitchen"+ assert page["id"] == "1"+ assert runner_ups == ["Brightpan Beauty", "Brightpan Home"]+ assert top == ""++ def test_exact_name_beats_busier_partial_match(self):+ # A reseller running more ads than the brand must not claim the topic.+ rows = [ad_row(page_id="1", page_name="Brightpan") for _ in range(11)] + [+ ad_row(page_id="2", page_name="Brightpan Outlet") for _ in range(18)+ ]+ page, _runner_ups, _top, strength = resolve_page("Brightpan", rows)+ assert page["name"] == "Brightpan"+ assert page["id"] == "1"+ assert strength == meta_ads.MATCH_EXACT++ def test_no_match_returns_top_unmatched_candidate(self):+ rows = [ad_row(page_id="9", page_name="Jasper AI") for _ in range(30)]+ page, runner_ups, top, _strength = resolve_page("Vantage AI", rows)+ assert page is None+ assert runner_ups == []+ assert top == "Jasper AI"++ def test_no_rows_returns_no_candidate_name(self):+ page, runner_ups, top, _strength = resolve_page("Brightpan", [])+ assert page is None+ assert runner_ups == []+ assert top == ""++ def test_rows_without_page_id_are_ignored(self):+ page, _runner_ups, top, _strength = resolve_page(+ "Brightpan", [ad_row(page_id="", page_name="Brightpan")]+ )+ assert page is None+ assert top == ""+++class TestRowFields:+ def test_launch_date_from_iso_string(self):+ assert launch_date(ad_row()) == "2026-09-01"++ def test_launch_date_falls_back_to_epoch(self):+ epoch = int(+ datetime.datetime(2026, 9, 1, tzinfo=datetime.timezone.utc).timestamp()+ )+ row = ad_row(start_date_string="", start_date=epoch)+ assert launch_date(row) == "2026-09-01"++ def test_launch_date_missing_is_none(self):+ assert launch_date(ad_row(start_date_string="", start_date=None)) is None++ def test_dedupe_key_prefers_collation(self):+ assert dedupe_key(ad_row(collation_id="col-9")) == "collation:col-9"++ def test_dedupe_key_falls_back_to_archive_id(self):+ row = ad_row(collation_id=None, ad_archive_id="777")+ assert dedupe_key(row) == "ad:777"++ def test_has_video_detects_snapshot_videos(self):+ row = ad_row()+ row["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/v.mp4"}]+ assert has_video(row)++ def test_has_video_detects_card_video(self):+ row = ad_row()+ row["snapshot"]["cards"] = [{"video_sd_url": "https://cdn.example/v.mp4"}]+ assert has_video(row)++ def test_has_video_false_for_image_ad(self):+ assert not has_video(ad_row())++ def test_promo_code_found_after_code_keyword(self):+ assert extract_promo_code("Take 30% off sitewide. Use code SUMMER30.") == "SUMMER30"++ def test_promo_code_ignores_model_numbers(self):+ assert extract_promo_code("The Brightpan E-325 is here.") is None++ def test_promo_code_ignores_lowercase_words_after_code(self):+ assert extract_promo_code("Our code of conduct is published.") is None++ def test_build_item_carries_every_rendered_field(self):+ item = build_item(ad_row(), {"id": "300000000000001", "name": "Brightpan"})+ assert item["title"].startswith("Better mornings")+ assert item["date"] == "2026-09-01"+ assert item["cta"] == "Shop now"+ assert item["display_format"] == "DCO"+ assert item["landing_url"] == "https://brightpan.example/collections/kettles"+ assert item["placements"] == ["FACEBOOK", "INSTAGRAM", "THREADS"]+ assert item["variants"] == 3+ assert item["advertiser"] == "Brightpan"+ assert item["url"].endswith("id=1000000000000001")++ def test_build_item_uses_card_link_when_snapshot_link_absent(self):+ row = ad_row()+ row["snapshot"]["link_url"] = ""+ row["snapshot"]["cards"] = [{"link_url": "https://brightpan.example/p/1"}]+ item = build_item(row, {"id": "1", "name": "Brightpan"})+ assert item["landing_url"] == "https://brightpan.example/p/1"++ def test_build_item_synthesizes_permalink_when_url_missing(self):+ item = build_item(ad_row(url=""), {"id": "1", "name": "Brightpan"})+ assert item["url"] == "https://www.facebook.com/ads/library/?id=1000000000000001"+++class TestSearchMetaAds:+ def _run(self, responses, **kwargs):+ """Drive the lane with a scripted sequence of http.get returns."""+ calls = []++ def fake_get(url, **call_kwargs):+ calls.append((url, call_kwargs.get("params") or {}))+ nxt = responses.pop(0)+ if isinstance(nxt, Exception):+ raise nxt+ return nxt++ with mock.patch("lib.meta_ads.http.get", side_effect=fake_get):+ result = search_meta_ads(+ kwargs.pop("topic", "Brightpan"),+ FROM_DATE,+ TO_DATE,+ token=kwargs.pop("token", TOKEN),+ **kwargs,+ )+ return result, calls++ def test_missing_token_makes_no_calls(self):+ with mock.patch("lib.meta_ads.http.get") as get:+ result = search_meta_ads("Brightpan", FROM_DATE, TO_DATE, token="")+ get.assert_not_called()+ assert result["ads"] == []+ assert result["page"] is None++ def test_happy_path_resolves_and_classifies(self):+ discovery = envelope([ad_row() for _ in range(11)])+ window = envelope(+ [+ ad_row(ad_archive_id="1", collation_id="a", start_date_string="2026-09-01"),+ ad_row(ad_archive_id="2", collation_id="b", start_date_string="2026-08-20"),+ ad_row(ad_archive_id="3", collation_id="c", start_date_string="2026-04-03"),+ ],+ key="results",+ )+ result, calls = self._run([discovery, window])+ assert result["page"]["name"] == "Brightpan"+ assert [item["date"] for item in result["ads"]] == ["2026-09-01", "2026-08-20"]+ tally = result["tally"]+ assert tally["resolution"] == RESOLVED+ assert tally["launched_in_window"] == 2+ assert tally["still_running"] == 1+ assert tally["promo_codes"] == []+ assert tally["placements"] == ["FACEBOOK", "INSTAGRAM", "THREADS"]+ assert calls[0][0] == meta_ads.SEARCH_ADS_URL+ assert calls[1][0] == meta_ads.COMPANY_ADS_URL++ def test_window_fetch_requests_all_statuses(self):+ # Without this the endpoint's ACTIVE default hides creatives that+ # launched inside the window and already ended.+ result, calls = self._run(+ [envelope([ad_row()]), envelope([ad_row()], key="results")]+ )+ assert calls[1][1]["status"] == meta_ads.ENRICHMENT_STATUS+ assert calls[1][1]["start_date"] == FROM_DATE+ assert calls[1][1]["end_date"] == TO_DATE+ assert result["tally"]["launched_in_window"] == 1++ def test_ended_in_window_creative_is_kept_and_flagged(self):+ window = envelope(+ [ad_row(is_active=False, end_date_string="2026-09-05T07:00:00.000Z")],+ key="results",+ )+ result, _calls = self._run([envelope([ad_row()]), window])+ assert len(result["ads"]) == 1+ assert result["ads"][0]["is_active"] is False+ assert result["ads"][0]["ended_on"] == "2026-09-05"++ def test_company_search_fallback_resolves(self):+ discovery = envelope([ad_row(page_id="9", page_name="Unrelated Deals Co")])+ companies = envelope(+ [company_row("55", "Brightpan"), company_row("56", "Other Co")],+ key="results",+ )+ window = envelope([ad_row()], key="results")+ result, calls = self._run([discovery, companies, window])+ assert result["page"]["id"] == "55"+ assert calls[1][0] == meta_ads.SEARCH_COMPANIES_URL+ assert calls[2][1]["pageId"] == "55"++ def test_unresolved_names_top_candidate_and_skips_enrichment(self):+ discovery = envelope(+ [ad_row(page_id="9", page_name="Jasper AI") for _ in range(30)]+ )+ companies = envelope([company_row("7", "Jasper AI")], key="results")+ result, calls = self._run([discovery, companies], topic="Vantage AI")+ assert result["ads"] == []+ assert result["page"] is None+ assert result["tally"]["resolution"] == UNRESOLVED+ assert result["tally"]["top_candidate"] == "Jasper AI"+ assert all(call[0] != meta_ads.COMPANY_ADS_URL for call in calls)++ def test_zero_candidates_is_its_own_state(self):+ result, calls = self._run(+ [envelope([]), envelope([], key="results")], topic="Nonexistent Brand"+ )+ assert result["tally"]["resolution"] == NO_CANDIDATES+ assert result["tally"]["top_candidate"] == ""+ assert len(calls) == 2++ def test_page_override_skips_resolution(self):+ window = envelope([ad_row()], key="results")+ result, calls = self._run([window], page_override="300000000000001")+ assert len(calls) == 1+ assert calls[0][0] == meta_ads.COMPANY_ADS_URL+ assert result["page"]["id"] == "300000000000001"++ def test_variants_of_one_creative_collapse(self):+ window = envelope(+ [+ ad_row(ad_archive_id="1", collation_id="same", collation_count=4),+ ad_row(ad_archive_id="2", collation_id="same", collation_count=4),+ ],+ key="results",+ )+ result, _calls = self._run([envelope([ad_row()]), window])+ assert len(result["ads"]) == 1+ assert result["ads"][0]["variants"] == 4++ def test_null_collation_ids_stay_distinct(self):+ window = envelope(+ [+ ad_row(ad_archive_id="1", collation_id=None),+ ad_row(ad_archive_id="2", collation_id=None),+ ],+ key="results",+ )+ result, _calls = self._run([envelope([ad_row()]), window])+ assert len(result["ads"]) == 2++ def test_pagination_stops_at_depth_cap_and_flags_more(self):+ discovery = envelope([ad_row()])+ pages = [+ envelope([ad_row(ad_archive_id=str(i), collation_id=f"c{i}")],+ key="results", total=222, cursor=f"cur{i}")+ for i in range(5)+ ]+ result, calls = self._run([discovery] + pages, depth="default")+ window_calls = [c for c in calls if c[0] == meta_ads.COMPANY_ADS_URL]+ assert len(window_calls) == 2 # default depth cap+ assert result["tally"]["cursor_remaining"] is True+ assert result["tally"]["endpoint_total"] == 222++ def test_pagination_stops_when_cursor_repeats(self):+ discovery = envelope([ad_row()])+ repeated = envelope(+ [ad_row(ad_archive_id="1", collation_id="c1")], key="results", cursor="same"+ )+ result, calls = self._run([discovery, repeated, repeated, repeated], depth="deep")+ window_calls = [c for c in calls if c[0] == meta_ads.COMPANY_ADS_URL]+ assert len(window_calls) == 2+ assert result["tally"]["cursor_remaining"] is False++ def test_pagination_stops_on_empty_cursor(self):+ discovery = envelope([ad_row()])+ window = envelope([ad_row()], key="results", cursor="")+ _result, calls = self._run([discovery, window], depth="deep")+ assert len([c for c in calls if c[0] == meta_ads.COMPANY_ADS_URL]) == 1++ @pytest.mark.parametrize("status", [401, 402, 403, 429])+ def test_fatal_status_stops_the_lane(self, status):+ err = meta_ads.http.HTTPError(f"boom {status}", status_code=status)+ result, calls = self._run([err])+ assert len(calls) == 1+ assert result["ads"] == []+ assert str(status) in result["error"]++ def test_fatal_status_during_enrichment_reports_error(self):+ err = meta_ads.http.HTTPError("rate limited", status_code=429)+ result, calls = self._run([envelope([ad_row()]), err])+ assert len(calls) == 2+ assert "429" in result["error"]+ assert result["ads"] == []++ def test_empty_success_response_is_not_an_error(self):+ result, _calls = self._run([envelope([]), envelope([], key="results")])+ assert "error" not in result+ assert result["tally"]["resolution"] == NO_CANDIDATES++ def test_transcripts_cover_newest_videos_across_pages(self):+ discovery = envelope([ad_row()])+ older_video = ad_row(+ ad_archive_id="old", collation_id="old", start_date_string="2026-08-20"+ )+ older_video["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/a.mp4"}]+ newer_video = ad_row(+ ad_archive_id="new", collation_id="new", start_date_string="2026-09-10"+ )+ newer_video["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/b.mp4"}]+ page_one = envelope([older_video], key="results", cursor="c1")+ page_two = envelope([newer_video], key="results", cursor="")+ transcript = {"transcript_available": True, "transcript": "Say what you need to say."}+ result, calls = self._run(+ [discovery, page_one, page_two, transcript, transcript], depth="default"+ )+ transcript_calls = [c for c in calls if c[0] == meta_ads.AD_TRANSCRIPT_URL]+ # Newest first: the page-two creative is transcribed before the older one.+ assert transcript_calls[0][1]["id"] == "new"+ assert result["tally"]["transcribed"] == 2+ assert result["ads"][0]["transcript"].startswith("Say what")++ def test_unavailable_transcript_is_not_an_error(self):+ discovery = envelope([ad_row()])+ video = ad_row()+ video["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/a.mp4"}]+ window = envelope([video], key="results")+ result, _calls = self._run(+ [discovery, window, {"transcript_available": False, "transcript": None}]+ )+ assert "error" not in result+ assert result["tally"]["transcribed"] == 0+ assert result["ads"][0]["transcript"] == ""++ def test_quick_depth_pulls_no_transcripts(self):+ discovery = envelope([ad_row()])+ video = ad_row()+ video["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/a.mp4"}]+ _result, calls = self._run(+ [discovery, envelope([video], key="results")], depth="quick"+ )+ assert all(c[0] != meta_ads.AD_TRANSCRIPT_URL for c in calls)++ def test_rate_limit_retries_are_disabled_on_every_call(self):+ # The shared client retries a 429 twice by default, which would both+ # contradict the no-further-calls contract and burn the lane budget.+ _result, _calls = self._run(+ [envelope([ad_row()]), envelope([ad_row()], key="results")]+ )+ with mock.patch("lib.meta_ads.http.get") as get:+ get.return_value = envelope([])+ search_meta_ads("Brightpan", FROM_DATE, TO_DATE, token=TOKEN)+ assert get.call_args.kwargs["max_429_retries"] == 0+ assert get.call_args.kwargs["deadline_monotonic"] is not None++ def test_exhausted_budget_keeps_what_was_fetched_and_reports_partial(self):+ # Running out of time must not discard creatives already in hand: thin+ # coverage caused by our own clock would otherwise read as a finding+ # about how little the advertiser is running.+ discovery = envelope([ad_row()])+ window = envelope([ad_row()], key="results", cursor="more")+ ticks = {"n": 0}+ real_monotonic = meta_ads.time.monotonic++ def creeping_clock():+ ticks["n"] += 1+ # Jump past the lane budget once the first window page is in.+ return real_monotonic() + (0 if ticks["n"] < 6 else 10_000)++ with mock.patch("lib.meta_ads.time.monotonic", side_effect=creeping_clock):+ with mock.patch("lib.meta_ads.http.get", side_effect=[discovery, window]):+ result = search_meta_ads(+ "Brightpan", FROM_DATE, TO_DATE, token=TOKEN, depth="deep"+ )+ assert result.get("partial") is True+ assert "budget" in result["error"]+ assert len(result["ads"]) == 1+ assert result["page"]["name"] == "Brightpan"+ assert result["tally"]["cursor_remaining"] is True++ def test_country_override_is_passed_through(self):+ _result, calls = self._run(+ [envelope([ad_row()]), envelope([ad_row()], key="results")], country="GB"+ )+ assert calls[0][1]["country"] == "GB"+ assert calls[1][1]["country"] == "GB"+++class TestWindowBoundaries:+ def test_creative_launched_on_window_edges_is_included(self):+ window = envelope(+ [+ ad_row(ad_archive_id="1", collation_id="a", start_date_string=FROM_DATE),+ ad_row(ad_archive_id="2", collation_id="b", start_date_string=TO_DATE),+ ],+ key="results",+ )+ with mock.patch(+ "lib.meta_ads.http.get", side_effect=[envelope([ad_row()]), window]+ ):+ result = search_meta_ads("Brightpan", FROM_DATE, TO_DATE, token=TOKEN)+ assert result["tally"]["launched_in_window"] == 2++ def test_undated_creative_counts_as_still_running(self):+ window = envelope(+ [ad_row(start_date_string="", start_date=None)], key="results"+ )+ with mock.patch(+ "lib.meta_ads.http.get", side_effect=[envelope([ad_row()]), window]+ ):+ result = search_meta_ads("Brightpan", FROM_DATE, TO_DATE, token=TOKEN)+ assert result["ads"] == []+ assert result["tally"]["still_running"] == 1+++class TestTransientVersusFatal:+ """R11: only credential/account statuses discard the lane's work."""++ def _drive(self, responses, depth="default"):+ def fake_get(url, **kwargs):+ nxt = responses.pop(0)+ if isinstance(nxt, Exception):+ raise nxt+ return nxt++ with mock.patch("lib.meta_ads.http.get", side_effect=fake_get):+ return search_meta_ads(+ "Brightpan", FROM_DATE, TO_DATE, token=TOKEN, depth=depth+ )++ def test_transient_error_mid_pagination_keeps_fetched_creatives(self):+ # A 500 on page two must not throw away page one: those creatives were+ # already paid for and are real evidence.+ page_one = envelope([ad_row()], key="results", cursor="more")+ boom = meta_ads.http.HTTPError("upstream hiccup", status_code=500)+ result = self._drive([envelope([ad_row()]), page_one, boom], depth="deep")+ assert len(result["ads"]) == 1+ assert result["page"]["name"] == "Brightpan"+ assert result.get("partial") is True+ assert "500" in result["error"]++ def test_transient_error_during_transcripts_keeps_creatives(self):+ video = ad_row()+ video["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/a.mp4"}]+ boom = meta_ads.http.HTTPError("transcoder down", status_code=503)+ result = self._drive(+ [envelope([ad_row()]), envelope([video], key="results"), boom]+ )+ assert len(result["ads"]) == 1+ assert result.get("partial") is True++ def test_fatal_status_mid_enrichment_keeps_paid_creatives(self):+ # A rate limit or expired credential means "stop calling", not "the+ # pages that already returned 200 were wrong". Discarding them throws+ # away evidence the user already paid for.+ page_one = envelope([ad_row()], key="results", cursor="more")+ boom = meta_ads.http.HTTPError("rate limited", status_code=429)+ result = self._drive([envelope([ad_row()]), page_one, boom], depth="deep")+ assert len(result["ads"]) == 1+ assert result["page"]["name"] == "Brightpan"+ assert result.get("partial") is True+ assert "429" in result["error"]++ def test_fatal_status_during_discovery_has_nothing_to_keep(self):+ boom = meta_ads.http.HTTPError("rate limited", status_code=429)+ result = self._drive([boom])+ assert result["ads"] == []+ assert result["page"] is None+ assert "429" in result["error"]+++class TestShortBrandNames:+ """A brand whose every word is under the token floor must still resolve.++ The floor exists to stop a shared short word ("AI") from matching every+ advertiser that carries it. Applied without an exact-identity escape it+ also makes an initialism brand unresolvable against its own page, which+ fails the feature silently for a whole class of well-known names.+ """++ def test_initialism_brand_matches_its_own_page_exactly(self):+ assert names_match("KLM", "KLM")+ assert names_match("BMW", "bmw")++ def test_initialism_brand_still_rejects_an_unrelated_page(self):+ assert not names_match("KLM", "Kitchen Lighting Market")++ def test_initialism_resolves_through_the_exact_tier(self):+ rows = [ad_row(page_id="1", page_name="KLM") for _ in range(2)] + [+ ad_row(page_id="2", page_name="Unrelated Deals Co") for _ in range(30)+ ]+ page, _runner_ups, _top, strength = resolve_page("KLM", rows)+ assert page["name"] == "KLM"+ assert strength == meta_ads.MATCH_EXACT+++class TestResolutionStrength:+ def test_shared_whole_token_outranks_mere_containment(self):+ # "Brightpan Kitchen" shares the whole token; the containment-only+ # page must not win on ad volume alone.+ rows = [ad_row(page_id="1", page_name="Brightpan Kitchen") for _ in range(2)] + [+ ad_row(page_id="2", page_name="Superbrightpanel Co") for _ in range(40)+ ]+ page, _runner_ups, _top, strength = resolve_page("Brightpan", rows)+ assert page["name"] == "Brightpan Kitchen"+ assert strength == meta_ads.MATCH_TOKEN++ def test_containment_tier_is_reported_as_such(self):+ rows = [ad_row(page_id="1", page_name="Brightpan Kitchen") for _ in range(3)]+ _page, _runner_ups, _top, strength = resolve_page("BrightpanCo", rows)+ assert strength == meta_ads.MATCH_CONTAINED++ def test_transcript_cap_bounds_paid_requests_not_successes(self):+ # Every transcript call costs a credit whether or not one comes back,+ # so an upstream with no transcripts must not keep the lane calling.+ videos = []+ for i in range(10):+ row = ad_row(ad_archive_id=str(i), collation_id=f"c{i}")+ row["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/v.mp4"}]+ videos.append(row)+ unavailable = {"transcript_available": False, "transcript": None}+ responses = [envelope([ad_row()]), envelope(videos, key="results")] + [+ unavailable+ ] * 10+ calls = []++ def fake_get(url, **kwargs):+ calls.append(url)+ return responses.pop(0)++ with mock.patch("lib.meta_ads.http.get", side_effect=fake_get):+ result = search_meta_ads(+ "Brightpan", FROM_DATE, TO_DATE, token=TOKEN, depth="default"+ )+ transcript_calls = [c for c in calls if c == meta_ads.AD_TRANSCRIPT_URL]+ assert len(transcript_calls) == 3 # the default-depth cap, not 10+ assert result["tally"]["transcribed"] == 0++ def test_default_depth_run_stays_inside_its_documented_credit_ceiling(self):+ videos = []+ for i in range(10):+ row = ad_row(ad_archive_id=str(i), collation_id=f"c{i}")+ row["snapshot"]["videos"] = [{"video_hd_url": "https://cdn.example/v.mp4"}]+ videos.append(row)+ responses = [+ envelope([ad_row(page_id="9", page_name="Unrelated Deals Co")]),+ envelope([company_row("55", "Brightpan")], key="results"),+ envelope(videos, key="results", cursor="more"),+ envelope(videos, key="results", cursor="more"),+ ] + [{"transcript_available": True, "transcript": "hello"}] * 5+ calls = []++ def fake_get(url, **kwargs):+ calls.append(url)+ return responses.pop(0)++ with mock.patch("lib.meta_ads.http.get", side_effect=fake_get):+ search_meta_ads("Brightpan", FROM_DATE, TO_DATE, token=TOKEN, depth="default")+ # 1 discovery + 1 company fallback + 2 pages + 3 transcripts = 7+ assert len(calls) <= 7+++class TestGenericTokens:+ """A word several advertisers share is a category, not an identity."""++ def test_category_word_does_not_resolve_an_unrelated_advertiser(self):+ rows = (+ [ad_row(page_id="1", page_name="Acme Kitchen") for _ in range(3)]+ + [ad_row(page_id="2", page_name="Kitchen World") for _ in range(40)]+ + [ad_row(page_id="3", page_name="Kitchen Depot") for _ in range(20)]+ )+ page, _runner_ups, _top, _strength = resolve_page("Acme Kitchen", rows)+ assert page["name"] == "Acme Kitchen"++ def test_a_word_only_one_advertiser_uses_still_identifies(self):+ rows = [ad_row(page_id="1", page_name="Brightpan Supply") for _ in range(2)] + [+ ad_row(page_id="2", page_name="Unrelated Deals Co") for _ in range(40)+ ]+ page, _runner_ups, _top, strength = resolve_page("Brightpan Supply news", rows)+ assert page["name"] == "Brightpan Supply"+ assert strength == meta_ads.MATCH_TOKEN++ def test_shared_category_alone_resolves_nothing(self):+ rows = [ad_row(page_id="1", page_name="Kitchen World") for _ in range(30)] + [+ ad_row(page_id="2", page_name="Kitchen Depot") for _ in range(20)+ ]+ page, _runner_ups, top, _strength = resolve_page("Acme Kitchen", rows)+ assert page is None+ assert top == "Kitchen World"+++class TestHeadTokenIdentity:+ """A multi-word topic carries its identity in the leading word.++ Counting how many advertisers share a word cannot carry this: a result set+ holding one lookalike makes its category word look perfectly distinctive.+ """++ def test_lone_category_lookalike_resolves_nothing(self):+ rows = [ad_row(page_id="9", page_name="Kitchen World") for _ in range(30)]+ page, _runner_ups, top, _strength = resolve_page("Acme Kitchen", rows)+ assert page is None+ assert top == "Kitchen World"++ def test_brand_page_wins_over_a_busier_category_lookalike(self):+ rows = [ad_row(page_id="1", page_name="Acme Kitchen") for _ in range(3)] + [+ ad_row(page_id="9", page_name="Kitchen World") for _ in range(40)+ ]+ page, _runner_ups, _top, _strength = resolve_page("Acme Kitchen", rows)+ assert page["name"] == "Acme Kitchen"++ def test_a_page_sharing_only_the_brand_word_fails_closed(self):+ # "Acme Supply" may or may not belong to the brand behind "Acme+ # Kitchen"; the name alone cannot say. Resolving it would risk+ # attributing another firm's ads, so the lane declines and names the+ # candidate instead, which the page override recovers in one flag.+ rows = [ad_row(page_id="1", page_name="Acme Supply") for _ in range(3)]+ page, _runner_ups, top, _strength = resolve_page("Acme Kitchen", rows)+ assert page is None+ assert top == "Acme Supply"++ def test_single_word_topic_keeps_its_umbrella_reach(self):+ # Nothing to strip, so the whole name is the head and product-line+ # pages still resolve.+ rows = [ad_row(page_id="1", page_name="Brightpan Kitchen") for _ in range(14)]+ page, _runner_ups, _top, _strength = resolve_page("BrightpanCo", rows)+ assert page["name"] == "Brightpan Kitchen"+++class TestDescriptorLeadingTopics:+ """A research topic does not always open with the brand."""++ def test_intent_modifier_before_the_brand_still_resolves_it(self):+ rows = [ad_row(page_id="1", page_name="Acme Grills") for _ in range(5)]+ page, _runner_ups, _top, _strength = resolve_page("best Acme grills", rows)+ assert page["name"] == "Acme Grills"++ @pytest.mark.parametrize(+ "topic,page_name",+ [+ ("best Acme grills", "Acme Grills"),+ ("latest Acme cookware", "Acme Cookware"),+ ("top Acme deals", "Acme Deals"),+ ],+ )+ def test_common_descriptors_do_not_become_the_identity(self, topic, page_name):+ rows = [ad_row(page_id="1", page_name=page_name) for _ in range(5)]+ page, _runner_ups, _top, _strength = resolve_page(topic, rows)+ assert page["name"] == page_name++ def test_a_category_lookalike_is_still_rejected_under_a_descriptor(self):+ # "grill" appears inside "grills", but it is the category word, not+ # the brand, so it must not carry the whole topic with it.+ rows = [ad_row(page_id="9", page_name="Grill World") for _ in range(50)]+ page, _runner_ups, _top, _strength = resolve_page("best Acme grills", rows)+ assert page is None+++class TestBrandPositionIndependence:+ """The brand does not always lead the topic."""++ @pytest.mark.parametrize(+ "topic,page",+ [+ ("Kitchen by Crate and Barrel", "Crate and Barrel"),+ ("smart home Acme", "Acme Home"),+ ("cookware from Acme Supply", "Acme Supply"),+ ],+ )+ def test_a_topic_that_spells_out_the_name_resolves_it(self, topic, page):+ # The topic names the company outright, so where in the phrase that+ # name sits cannot decide the match.+ rows = [ad_row(page_id="1", page_name=page) for _ in range(6)]+ resolved, _runner_ups, _top, _strength = resolve_page(topic, rows)+ assert resolved["name"] == page++ def test_a_lookalike_is_still_rejected_because_the_topic_omits_a_word(self):+ # "Kitchen World" carries "world", which a topic about "Acme Kitchen"+ # never mentions, so the topic is not naming this company.+ rows = [ad_row(page_id="9", page_name="Kitchen World") for _ in range(30)]+ page, _runner_ups, _top, _strength = resolve_page("Acme Kitchen", rows)+ assert page is None+++class TestPartialNamesCannotClaimATopic:+ """A fragment of the topic is not an advertiser's whole name."""++ def test_a_page_named_only_the_category_word_is_rejected(self):+ # Trivially "covered" by the topic, but it accounts for one word of it+ # and none of the brand.+ rows = [ad_row(page_id="9", page_name="Kitchen") for _ in range(30)]+ page, _runner_ups, _top, _strength = resolve_page("Acme Kitchen", rows)+ assert page is None++ def test_a_page_named_the_whole_single_word_topic_still_resolves(self):+ rows = [ad_row(page_id="1", page_name="Acme Co") for _ in range(4)]+ page, _runner_ups, _top, _strength = resolve_page("Acme", rows)+ assert page["name"] == "Acme Co"++ def test_coverage_needs_more_than_one_topic_word(self):+ rows = [ad_row(page_id="9", page_name="Grills") for _ in range(30)]+ page, _runner_ups, _top, _strength = resolve_page("best Acme grills", rows)+ assert page is None+++class TestCoverageBeatsVolume:+ def test_the_page_matching_more_of_the_topic_wins(self):+ # Two pages share the brand word; the one that also matches the rest+ # of the topic is the better answer however much the other spends.+ rows = [ad_row(page_id="1", page_name="Acme Kitchen Co") for _ in range(2)] + [+ ad_row(page_id="9", page_name="Acme AI") for _ in range(80)+ ]+ page, _runner_ups, _top, _strength = resolve_page("Acme Kitchen", rows)+ assert page["name"] == "Acme Kitchen Co"+++class TestWholeNameRequired:+ """Greptile round 7: a partial name must not stand in for a whole one."""++ def test_a_page_with_a_word_the_topic_never_mentions_is_rejected(self):+ # "Acme AI" and the brand behind "Acme Kitchen" share one word and+ # nothing else; "ai" appears nowhere in the topic.+ rows = [ad_row(page_id="9", page_name="Acme AI") for _ in range(80)]+ page, _runner_ups, _top, _strength = resolve_page("Acme Kitchen", rows)+ assert page is None++ def test_short_words_of_the_page_name_are_counted(self):+ # The page name's short word is part of its identity, so ignoring it+ # would let the name look fully covered when it is not.+ rows = [ad_row(page_id="9", page_name="Acme AI") for _ in range(5)]+ page, _runner_ups, _top, _strength = resolve_page("Acme AI", rows)+ assert page["name"] == "Acme AI"++ def test_word_boundaries_are_respected_in_coverage(self):+ # "Cart Wheel" is not named by "Acme Cartwheel" merely because its+ # letters appear inside a longer word.+ rows = [ad_row(page_id="9", page_name="Cart Wheel") for _ in range(30)]+ page, _runner_ups, _top, _strength = resolve_page("Acme Cartwheel", rows)+ assert page is Nonediff --git a/tests/test_meta_ads_normalize.py b/tests/test_meta_ads_normalize.pynew file mode 100644index 00000000..59af8488--- /dev/null+++ b/tests/test_meta_ads_normalize.py@@ -0,0 +1,157 @@+"""Normalization, identity, and ranking behavior for Meta Ad Library items."""++from lib import fusion, normalize, planner, rerank, schema, signals++FROM_DATE = "2026-08-15"+TO_DATE = "2026-09-14"+++def raw_ad(**over):+ base = {+ "id": "1000000000000001",+ "title": "Better mornings start here.",+ "text": "Better mornings start here. Use code SUMMER30 on the Brightpan kettle.",+ "url": "https://www.facebook.com/ads/library/?id=1000000000000001",+ "date": "2026-09-01",+ "advertiser": "Brightpan",+ "page_id": "300000000000001",+ "is_active": True,+ "ended_on": None,+ "display_format": "DCO",+ "cta": "Shop now",+ "landing_url": "https://brightpan.example/collections/kettles",+ "placements": ["FACEBOOK", "INSTAGRAM"],+ "promo_code": "SUMMER30",+ "variants": 3,+ "has_video": False,+ "transcript": "",+ }+ base.update(over)+ return base+++def normalize_one(**over):+ items = normalize.normalize_source_items(+ "meta_ads", [raw_ad(**over)], FROM_DATE, TO_DATE+ )+ assert len(items) == 1+ return items[0]+++class TestNormalizer:+ def test_source_is_registered(self):+ # A missing dispatch entry raises "Unsupported source" at runtime.+ assert normalize.normalize_source_items("meta_ads", [], FROM_DATE, TO_DATE) == []++ def test_identity_is_the_ad_library_permalink(self):+ item = normalize_one()+ assert item.url.endswith("id=1000000000000001")+ assert item.metadata["landing_url"] == "https://brightpan.example/collections/kettles"++ def test_launch_date_is_the_published_date(self):+ assert normalize_one().published_at == "2026-09-01"++ def test_creative_fields_ride_in_metadata(self):+ meta = normalize_one().metadata+ assert meta["advertiser"] == "Brightpan"+ assert meta["cta"] == "Shop now"+ assert meta["promo_code"] == "SUMMER30"+ assert meta["display_format"] == "DCO"+ assert meta["placements"] == ["FACEBOOK", "INSTAGRAM"]+ assert meta["variants"] == 3++ def test_variant_count_is_the_engagement_proxy(self):+ assert normalize_one().engagement == {"variants": 3}++ def test_transcript_rides_on_the_item(self):+ item = normalize_one(has_video=True, transcript="Stop making boring drinks.")+ assert item.metadata["transcript_snippet"].startswith("Stop making")+ assert "Stop making boring drinks." in item.snippet++ def test_items_are_grounding_exempt(self):+ assert normalize_one().metadata["grounding_exempt"] is True++ def test_pre_window_creative_is_filtered_out(self):+ # The adapter already classifies, but the shared window filter is the+ # backstop and must agree with it rather than drop everything.+ items = normalize.normalize_source_items(+ "meta_ads", [raw_ad(date="2026-04-03")], FROM_DATE, TO_DATE+ )+ assert items == []++ def test_missing_advertiser_still_yields_a_reason(self):+ assert normalize_one(advertiser="").why_relevant == "Running paid creative"+++class TestIdentityThroughFusion:+ def test_creatives_sharing_a_landing_page_stay_distinct(self):+ # Ten creatives for one product commonly share a landing URL. Keying+ # identity on it would collapse the campaign into a single candidate.+ first = normalize_one(id="1", url="https://www.facebook.com/ads/library/?id=1")+ second = normalize_one(id="2", url="https://www.facebook.com/ads/library/?id=2")+ assert fusion.candidate_key(first) != fusion.candidate_key(second)++ def test_same_creative_from_two_streams_shares_one_key(self):+ one = normalize_one()+ two = normalize_one(variants=4)+ assert fusion.candidate_key(one) == fusion.candidate_key(two)+++class TestRankingRegistries:+ def test_grounding_exemption_skips_the_entity_miss_demotion(self):+ # Ad copy that never names the brand is the normal case, so the+ # entity-miss demotion must not reach these items.+ item = normalize_one(text="Stop making boring drinks.", title="Boring drinks")+ candidate = schema.Candidate(+ candidate_id="c1",+ item_id=item.item_id,+ source="meta_ads",+ title=item.title,+ url=item.url,+ snippet=item.snippet,+ subquery_labels=[],+ native_ranks={},+ local_relevance=0.1,+ freshness=1,+ engagement=None,+ source_quality=signals.source_quality("meta_ads"),+ rrf_score=0.0,+ source_items=[item],+ )+ assert rerank._is_grounding_exempt(candidate) is True++ def test_source_quality_is_registered(self):+ assert signals.source_quality("meta_ads") == 0.72++ def test_engagement_weights_use_variants(self):+ assert signals.ENGAGEMENT_WEIGHTS["meta_ads"] == [("variants", 1.0)]++ def test_planner_capabilities_are_pinned(self):+ assert planner.SOURCE_CAPABILITIES["meta_ads"] == {+ "reference",+ "company_signal",+ "product_signal",+ }+++class TestActivityWording:+ """Ended-in-window creatives are kept on purpose, so say so accurately."""++ def test_running_creative_reads_as_running(self):+ assert normalize_one(is_active=True).why_relevant.startswith(+ "Running paid creative"+ )++ def test_ended_creative_is_not_called_active(self):+ item = normalize_one(is_active=False, ended_on="2026-09-05")+ assert "Running" not in item.why_relevant+ assert "2026-09-05" in item.why_relevant++ def test_ended_creative_without_a_date_still_reads_as_ended(self):+ item = normalize_one(is_active=False, ended_on=None)+ assert "since ended" in item.why_relevant++ def test_activity_state_is_preserved_in_metadata(self):+ meta = normalize_one(is_active=False, ended_on="2026-09-05").metadata+ assert meta["is_active"] is False+ assert meta["ended_on"] == "2026-09-05"diff --git a/tests/test_meta_ads_pipeline.py b/tests/test_meta_ads_pipeline.pynew file mode 100644index 00000000..4d8e2d39--- /dev/null+++ b/tests/test_meta_ads_pipeline.py@@ -0,0 +1,254 @@+"""Pipeline gating, flag handling, and artifact wiring for the Meta Ads source."""++import sys+from unittest.mock import patch++import pytest++import last30days+from lib import env, pipeline+++class TestMetaAdsSourceGating:+ """Dual-gated on the Amazon precedent: key present AND the run asks."""++ def _config(self, include=""):+ return {"SCRAPECREATORS_API_KEY": "fake-key", "INCLUDE_SOURCES": include}++ def test_unavailable_without_a_key_even_when_requested(self):+ available = pipeline.available_sources(+ {"INCLUDE_SOURCES": "meta_ads"}, ["meta_ads"]+ )+ assert "meta_ads" not in available++ def test_unavailable_with_a_key_when_not_requested(self):+ # Holding a ScrapeCreators key for TikTok must not start spending+ # credits resolving advertisers.+ assert "meta_ads" not in pipeline.available_sources(self._config(), None)++ def test_available_via_per_run_request(self):+ assert "meta_ads" in pipeline.available_sources(self._config(), ["meta_ads"])++ def test_available_via_durable_include_sources(self):+ assert "meta_ads" in pipeline.available_sources(self._config("meta_ads"), None)++ def test_exclude_sources_wins_over_activation(self):+ config = self._config("meta_ads")+ config["EXCLUDE_SOURCES"] = "meta_ads"+ assert "meta_ads" not in pipeline.available_sources(config, ["meta_ads"])++ def test_never_inferred_from_a_brand_shaped_topic(self):+ # Topic shape must not activate it: keyword ad search on the wrong+ # topic resolves the wrong company at full credit cost.+ assert "meta_ads" not in pipeline.available_sources(self._config(), [])++ def test_capped_at_one_fetch_per_run(self):+ assert pipeline.MAX_SOURCE_FETCHES["meta_ads"] == 1++ def test_exempt_from_thin_source_retry(self):+ # A brand that genuinely ran two creatives is a complete result; a+ # retry would re-resolve the page and re-spend the discovery credit.+ assert "meta_ads" in pipeline.THIN_RETRY_EXEMPT+++class TestSearchFlag:+ def test_canonical_token_is_accepted(self):+ assert "meta_ads" in last30days.parse_search_flag("reddit,x,meta_ads")++ @pytest.mark.parametrize("alias", ["meta", "meta-ads"])+ def test_aliases_resolve(self, alias):+ assert "meta_ads" in last30days.parse_search_flag(f"reddit,{alias}")++ def test_source_is_in_the_known_source_registry(self):+ # parse_search_flag rejects any token absent from this list, so a+ # missing entry silently breaks the per-run activation path.+ assert "meta_ads" in pipeline.MOCK_AVAILABLE_SOURCES+++class TestPageOverrideParsing:+ def test_bare_numeric_page_id(self):+ assert last30days.parse_meta_ads_page("123456789012345") == "123456789012345"++ def test_ad_library_url(self):+ url = (+ "https://www.facebook.com/ads/library/"+ "?active_status=all&view_all_page_id=123456789012345"+ )+ assert last30days.parse_meta_ads_page(url) == "123456789012345"++ def test_vanity_url_is_rejected(self):+ # A vanity handle is not a page id: one live check resolved a+ # brand-looking handle to a private person's profile.+ assert last30days.parse_meta_ads_page("https://facebook.com/somebrand") == ""++ def test_blank_is_rejected(self):+ assert last30days.parse_meta_ads_page(" ") == ""++ def test_short_numeric_string_is_rejected(self):+ assert last30days.parse_meta_ads_page("42") == ""+++class TestEnvContract:+ def test_country_key_is_resolvable(self):+ config = env.get_config()+ assert "LAST30DAYS_META_ADS_COUNTRY" in config++ def test_country_defaults_to_us(self):+ assert env.get_config().get("LAST30DAYS_META_ADS_COUNTRY") == "US"++ def test_no_durable_page_override_key_exists(self):+ # A page id is per-topic state, and env keys ride through the+ # competitor runner's config copy.+ assert "LAST30DAYS_META_ADS_PAGE" not in env.get_config()+++class _FakeBundle:+ def __init__(self, artifacts):+ self.artifacts = artifacts+++class TestArtifactLift:+ """Stream artifacts only reach the report as anonymous grounding entries."""++ def test_footer_inputs_are_promoted_to_named_artifacts(self):+ bundle = _FakeBundle(+ {+ "grounding": [+ {"x_receipts": ["unrelated"]},+ {+ "meta_ads_page": {"id": "1", "name": "Brightpan"},+ "meta_ads_tally": {"launched_in_window": 7},+ },+ ]+ }+ )+ pipeline._lift_stream_artifacts(bundle)+ assert bundle.artifacts["meta_ads_page"]["name"] == "Brightpan"+ assert bundle.artifacts["meta_ads_tally"]["launched_in_window"] == 7++ def test_lift_survives_a_zero_item_run(self):+ # The advertiser must still be nameable when no creative landed.+ bundle = _FakeBundle(+ {"grounding": [{"meta_ads_page": {"id": "1", "name": "Brightpan"}}]}+ )+ pipeline._lift_stream_artifacts(bundle)+ assert bundle.artifacts["meta_ads_page"]["name"] == "Brightpan"++ def test_lift_ignores_non_dict_entries(self):+ bundle = _FakeBundle({"grounding": ["not a dict", None]})+ pipeline._lift_stream_artifacts(bundle)+ assert "meta_ads_page" not in bundle.artifacts++ def test_lift_is_a_no_op_without_grounding_artifacts(self):+ bundle = _FakeBundle({})+ pipeline._lift_stream_artifacts(bundle)+ assert bundle.artifacts == {}+++class TestRetrievalBranch:+ """The dispatch branch itself: brand resolution, config threading, outcome."""++ def _run(self, result, config=None, raw_topic="Brightpan", search_query="kettle reviews"):+ from lib import schema++ subquery = schema.SubQuery(+ label="primary",+ search_query=search_query,+ ranking_query="q",+ sources=["meta_ads"],+ )+ cfg = {"SCRAPECREATORS_API_KEY": "fake-key"}+ cfg.update(config or {})+ captured = {}++ def fake_search(topic, from_date, to_date, **kwargs):+ captured["topic"] = topic+ captured["from_date"] = from_date+ captured["to_date"] = to_date+ captured.update(kwargs)+ return result++ with patch.object(pipeline.meta_ads, "search_meta_ads", side_effect=fake_search):+ items, artifact = pipeline._retrieve_stream_impl(+ topic="Brightpan",+ subquery=subquery,+ source="meta_ads",+ config=cfg,+ depth="default",+ date_range=("2026-08-15", "2026-09-14"),+ runtime=schema.ProviderRuntime(+ reasoning_provider="none",+ planner_model="none",+ rerank_model="none",+ ),+ mock=False,+ raw_topic=raw_topic,+ )+ return items, artifact or {}, captured++ def _result(self, **over):+ base = {+ "ads": [{"id": "1"}],+ "page": {"id": "300", "name": "Brightpan"},+ "tally": {"launched_in_window": 1, "resolution": "resolved"},+ }+ base.update(over)+ return base++ def test_advertiser_resolves_from_the_research_topic_not_the_subquery(self):+ # A subquery like "kettle reviews" would resolve a different company+ # than the brand the run is actually about.+ _items, _artifact, captured = self._run(self._result())+ assert captured["topic"] == "Brightpan"++ def test_config_is_threaded_into_the_lane(self):+ _items, _artifact, captured = self._run(+ self._result(),+ config={+ "LAST30DAYS_META_ADS_COUNTRY": "GB",+ "_meta_ads_page": "123456789012345",+ },+ )+ assert captured["token"] == "fake-key"+ assert captured["country"] == "GB"+ assert captured["page_override"] == "123456789012345"++ def test_country_defaults_when_unset(self):+ _items, _artifact, captured = self._run(self._result())+ assert captured["country"] == pipeline.meta_ads.DEFAULT_COUNTRY++ def test_footer_inputs_ride_on_the_stream_artifact(self):+ _items, artifact, _captured = self._run(self._result())+ assert artifact["meta_ads_page"]["name"] == "Brightpan"+ assert artifact["meta_ads_tally"]["launched_in_window"] == 1++ def test_partial_result_forces_a_partial_outcome(self):+ from lib import schema++ _items, artifact, _captured = self._run(+ self._result(partial=True, error="lane budget of 120.0s exceeded")+ )+ assert artifact["_source_outcome"]["state"] == schema.PARTIAL+ assert "budget" in artifact["_source_outcome"]["detail"]++ def test_items_come_back_as_the_stream(self):+ items, _artifact, _captured = self._run(self._result())+ assert items == [{"id": "1"}]++ def test_zero_item_run_still_carries_the_advertiser(self):+ _items, artifact, _captured = self._run(+ self._result(ads=[], tally={"launched_in_window": 0, "resolution": "resolved"})+ )+ assert artifact["meta_ads_page"]["name"] == "Brightpan"+++class TestCompetitorIsolation:+ def test_page_override_is_dropped_for_competitor_sub_runs(self):+ # Left in place, one brand's advertiser page would be fetched for+ # every peer in a comparison and rendered as that peer's ads.+ import inspect++ import last30days as engine++ source = inspect.getsource(engine)+ assert 'entity_config.pop("_meta_ads_page", None)' in sourcediff --git a/tests/test_meta_ads_render.py b/tests/test_meta_ads_render.pynew file mode 100644index 00000000..4a51a401--- /dev/null+++ b/tests/test_meta_ads_render.py@@ -0,0 +1,287 @@+"""Footer rendering and display registries for the Meta Ads source."""++from lib import doctor, health, meta_ads, render, schema, ui+++def make_report(tally=None, page=None, status=None, items=None):+ return schema.Report(+ topic="Brightpan",+ range_from="2026-08-15",+ range_to="2026-09-14",+ generated_at="2026-09-14T00:00:00+00:00",+ provider_runtime=schema.ProviderRuntime(+ reasoning_provider="none", planner_model="none", rerank_model="none"+ ),+ query_plan=schema.QueryPlan(+ intent="general",+ freshness_mode="balanced_recent",+ cluster_mode="none",+ raw_topic="Brightpan",+ subqueries=[],+ source_weights={},+ ),+ clusters=[],+ ranked_candidates=[],+ items_by_source={"meta_ads": items or []},+ errors_by_source={},+ source_status=({"meta_ads": status} if status else {}),+ artifacts={+ "meta_ads_tally": tally or {},+ "meta_ads_page": page or {},+ },+ )+++def tally(**over):+ base = {+ "resolution": meta_ads.RESOLVED,+ "launched_in_window": 15,+ "still_running": 15,+ "video": 5,+ "transcribed": 3,+ "fetched": 30,+ "endpoint_total": 30,+ "cursor_remaining": False,+ "placements": ["FACEBOOK", "INSTAGRAM", "THREADS"],+ "promo_codes": ["SUMMER30"],+ "advertiser": "Brightpan",+ "page_id": "1",+ "top_candidate": "",+ "runner_ups": [],+ "match_strength": meta_ads.MATCH_EXACT,+ }+ base.update(over)+ return base+++def line(**kwargs):+ return render._meta_ads_footer_line(make_report(**kwargs))+++class TestResolvedLine:+ def test_full_line_carries_the_paid_media_detail(self):+ out = line(tally=tally(), page={"id": "1", "name": "Brightpan"})+ assert out.startswith("📣 Meta Ads: Brightpan")+ assert "15 new creatives" in out+ assert "15 running from before" in out+ assert "FB, IG, Threads" in out+ assert "code SUMMER30" in out+ assert "3 transcribed" in out++ def test_counts_come_from_the_tally_not_surviving_items(self):+ # The pipeline truncates each stream to 12 at default depth, so+ # counting items would report 12 for a page that ran thirty.+ out = line(+ tally=tally(launched_in_window=30),+ page={"id": "1", "name": "Brightpan"},+ items=[],+ )+ assert "30 new creatives" in out++ def test_sampled_page_says_so(self):+ out = line(+ tally=tally(+ launched_in_window=12, fetched=60, endpoint_total=222,+ cursor_remaining=True,+ ),+ page={"id": "1", "name": "Brightpan"},+ )+ assert "12 new of 60 ads fetched (222 live)" in out++ def test_singular_creative(self):+ out = line(+ tally=tally(launched_in_window=1, still_running=0, transcribed=0,+ promo_codes=[], placements=[]),+ page={"id": "1", "name": "Brightpan"},+ )+ assert "1 new creative" in out++ def test_optional_segments_are_omitted_when_empty(self):+ out = line(+ tally=tally(still_running=0, transcribed=0, promo_codes=[], placements=[]),+ page={"id": "1", "name": "Brightpan"},+ )+ assert "running from before" not in out+ assert "code" not in out+ assert "transcribed" not in out+++class TestEmptyStates:+ def test_resolved_but_nothing_new_names_the_advertiser(self):+ # "No ads" and "not advertising" are different facts about a brand.+ out = line(+ tally=tally(launched_in_window=0, still_running=20),+ page={"id": "1", "name": "Brightpan"},+ )+ assert "no new creatives for Brightpan" in out+ assert "20 still running from before" in out++ def test_unresolved_names_the_closest_candidate_and_the_override(self):+ out = line(tally=tally(resolution=meta_ads.UNRESOLVED, top_candidate="Jasper AI"))+ assert "no advertiser matched" in out+ assert "closest: Jasper AI" in out+ assert "--meta-ads-page" in out++ def test_zero_candidates_has_its_own_wording(self):+ out = line(tally=tally(resolution=meta_ads.NO_CANDIDATES))+ assert "no advertiser candidates returned" in out+ assert "closest" not in out+ assert "--meta-ads-page" in out++ def test_failed_lane_names_the_outcome(self):+ status = schema.SourceOutcome(+ source="meta_ads",+ state=health.RATE_LIMITED,+ detail="HTTP 429: rate limited",+ attempted=True,+ )+ out = line(tally={}, page={}, status=status)+ assert "no ads pulled" in out+ assert "429" in out++ def test_line_is_absent_when_the_lane_never_ran(self):+ assert line(tally={}, page={}) is None++ def test_zero_results_outcome_is_not_treated_as_failure(self):+ # The pipeline stamps NO_RESULTS on any zero-item source, so treating+ # it as failure would collapse every honest empty state into a generic+ # "no ads pulled" and lose which nothing it was.+ status = schema.SourceOutcome(+ source="meta_ads", state=schema.NO_RESULTS, attempted=True+ )+ out = line(+ tally=tally(launched_in_window=0, still_running=20),+ page={"id": "1", "name": "Brightpan"},+ status=status,+ )+ assert "no new creatives for Brightpan" in out+ assert "no ads pulled" not in out++ def test_zero_results_unresolved_keeps_its_specific_line(self):+ status = schema.SourceOutcome(+ source="meta_ads", state=schema.NO_RESULTS, attempted=True+ )+ out = line(+ tally=tally(resolution=meta_ads.UNRESOLVED, top_candidate="Jasper AI"),+ status=status,+ )+ assert "closest: Jasper AI" in out++ def test_cut_short_lane_never_concludes_nothing_new(self):+ # Partial data cannot support a definitive negative conclusion.+ status = schema.SourceOutcome(+ source="meta_ads",+ state=schema.PARTIAL,+ detail="lane budget of 120.0s exceeded",+ attempted=True,+ )+ out = line(+ tally=tally(launched_in_window=0, still_running=0),+ page={"id": "1", "name": "Brightpan"},+ status=status,+ )+ assert "incomplete" in out+ assert "no new creatives for" not in out++ def test_cut_short_lane_with_creatives_is_marked_incomplete(self):+ status = schema.SourceOutcome(+ source="meta_ads", state=schema.PARTIAL, detail="HTTP 429", attempted=True+ )+ out = line(+ tally=tally(launched_in_window=4),+ page={"id": "1", "name": "Brightpan"},+ status=status,+ )+ assert "4 new creatives" in out+ assert "incomplete" in out+++class TestUntrustedFooterText:+ """Advertiser names and promo codes are attacker-influenceable strings."""++ def test_newline_in_advertiser_name_cannot_forge_a_footer_row(self):+ out = line(+ tally=tally(advertiser="Evil\n└─ 🟠 Reddit: 9,999 threads"),+ page={"id": "1", "name": "Evil\n└─ 🟠 Reddit: 9,999 threads"},+ )+ assert "\n" not in out+ assert out.count("📣") == 1++ def test_separator_in_advertiser_name_cannot_forge_a_field(self):+ # The name keeps its text but loses the real separator, so it stays+ # one field instead of impersonating the counts field beside it.+ out = line(+ tally=tally(),+ page={"id": "1", "name": "Acme │ 500 new creatives"},+ )+ assert "Acme | 500 new creatives" in out+ assert out.split(" │ ")[0] == "📣 Meta Ads: Acme | 500 new creatives"++ def test_overlong_advertiser_name_is_clipped(self):+ out = line(+ tally=tally(), page={"id": "1", "name": "B" * 400}+ )+ assert len(out) < 300++ def test_hostile_promo_code_is_neutralized(self):+ out = line(+ tally=tally(promo_codes=["GOOD\n└─ fake"]),+ page={"id": "1", "name": "Brightpan"},+ )+ assert "\n" not in out++ def test_partial_name_match_is_disclosed(self):+ out = line(+ tally=tally(match_strength=meta_ads.MATCH_CONTAINED),+ page={"id": "1", "name": "Brightpan"},+ )+ assert "matched by partial name" in out++ def test_exact_match_is_not_annotated(self):+ out = line(+ tally=tally(match_strength=meta_ads.MATCH_EXACT),+ page={"id": "1", "name": "Brightpan"},+ )+ assert "partial name" not in out+++class TestDisplayRegistries:+ def test_stats_label_is_not_title_cased_source_key(self):+ assert render.SOURCE_LABELS["meta_ads"] == "Meta Ads"++ def test_engagement_display_uses_variants(self):+ assert render.ENGAGEMENT_DISPLAY["meta_ads"] == [("variants", "variants")]++ def test_ui_completion_meta_is_registered(self):+ assert ui.SOURCE_COMPLETION_META["meta_ads"][0] == "Meta Ads"++ def test_ui_completion_order_includes_the_source(self):+ assert "meta_ads" in ui.SOURCE_COMPLETION_ORDER+++class TestDoctorRecord:+ """Doctor must agree with the pipeline gate and never spend a credit."""++ def test_unconfigured_without_a_key(self):+ record = doctor._meta_ads_record({})+ assert record["status"] == "unconfigured"++ def test_opt_in_when_the_key_is_present_but_unrequested(self):+ record = doctor._meta_ads_record({"SCRAPECREATORS_API_KEY": "fake-key"})+ assert record["status"] == "opt-in"+ assert "INCLUDE_SOURCES" in record["fix"]++ def test_ok_when_opted_in(self):+ record = doctor._meta_ads_record(+ {"SCRAPECREATORS_API_KEY": "fake-key", "INCLUDE_SOURCES": "meta_ads"}+ )+ assert record["status"] == health.OK++ def test_source_order_and_builders_stay_in_sync(self):+ assert "meta_ads" in doctor.SOURCE_ORDER+ assert "meta_ads" in doctor._SOURCE_BUILDERS++ def test_never_live_probed(self):+ # Probing would spend a ScrapeCreators credit just to run doctor.+ assert "meta_ads" not in doctor.CLI_DEPENDENCIES+ assert "meta_ads" not in getattr(doctor, "_HTTP_PROBE_URLS", {})