Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat: Instagram comments + comments-by-default + rank-based comment diversity (#751)

Matt Van Horn9e00fe5b6d41
diff --git a/AGENTS.md b/AGENTS.md
index 3311fcf1..2b97a589 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -43,7 +43,7 @@ Python 3.12+ required. Use `uv` for the env; the venv lives at `.venv/`.
- Do not reduce `fail_under` in `pyproject.toml` (`[tool.coverage.report]`) without documenting why in the PR. The coverage gate is a floor meant to rise over time, not to be relaxed when new code is under-tested.
- Every `lib/*.py` call to `log.source_log(...)` must pass `tty_only=False`. The default is `True`, which silently drops every line when stderr isn't a TTY (Claude Code, Codex, CI, captured output) — turning source observability into invisible failure. Enforced by `tests/test_source_log_visibility.py`.
- **CLI-gated optional sources** (Digg via `digg-pp-cli`, YouTube via `yt-dlp`) activate only when `shutil.which` resolves the binary on the **agent subprocess PATH** — not merely when the file exists on disk. First-run setup installs Digg through `@mvanhorn/printing-press-library` (default `$HOME/.local/bin`); Hermes/OpenClaw gateways often need that directory on PATH. Setup must distinguish PATH-visible installs from off-PATH binaries and must not claim "now active" unless the engine gate would pass. See `docs/solutions/integration-issues/digg-cli-agent-path-setup-wizard.md`.
-- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth, and emitting the engine-owned welcome via `--welcome`) — it cannot prompt, so consent lives in `SKILL.md` Step 0. Two flows avoid model-authored prose that Claude Code folds or the model skips: in the **Modal Flow** the welcome pitch is embedded in the setup modal's question (the AskUserQuestion modal is the only always-fully-visible surface — a separate welcome message or `--welcome` Bash run gets buried behind "ctrl+o to expand"); the **Non-Modal Prose Flow** still uses `last30days.py --welcome` (relayed verbatim) since it has no modal. The GitHub device code is surfaced by a two-command split — `setup --github-start` returns the code fast (foreground, copies to clipboard) and `setup --github-poll` waits for authorization (`setup --github` still chains both for back-compat). Step 0 has TWO branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, and a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI). Both ask before reading cookies, surface the macOS Full Disk Access fix on permission-denied, and offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. The Step 5 source opt-in is two tiers: **Recommended** (TikTok + Instagram, on with the key) and **Everything** (also Threads, Pinterest, and YouTube/TikTok/Instagram comments via `INCLUDE_SOURCES`). Threads, Pinterest, and YouTube comments are opt-in (gated on `INCLUDE_SOURCES`), not auto-on with the key — they appear only in the Step 5 Everything option, never in the welcome or the Step 4 offer.
+- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth, and emitting the engine-owned welcome via `--welcome`) — it cannot prompt, so consent lives in `SKILL.md` Step 0. Two flows avoid model-authored prose that Claude Code folds or the model skips: in the **Modal Flow** the welcome pitch is embedded in the setup modal's question (the AskUserQuestion modal is the only always-fully-visible surface — a separate welcome message or `--welcome` Bash run gets buried behind "ctrl+o to expand"); the **Non-Modal Prose Flow** still uses `last30days.py --welcome` (relayed verbatim) since it has no modal. The GitHub device code is surfaced by a two-command split — `setup --github-start` returns the code fast (foreground, copies to clipboard) and `setup --github-poll` waits for authorization (`setup --github` still chains both for back-compat). Step 0 has TWO branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, and a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI). Both ask before reading cookies, surface the macOS Full Disk Access fix on permission-denied, and offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. The Step 5 source opt-in is two tiers, both comment-enabled: **Recommended** (TikTok + Instagram posts AND top comments, plus YouTube comments — `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments`) and **Everything** (also Threads + Pinterest). Comments are on by default (posts on → comments on for all three platforms); **Threads and Pinterest are the only opt-in extras**, appearing only in the Step 5 Everything option, never in the welcome or the Step 4 offer. Instagram comments are fetched via ScrapeCreators (`/v2/instagram/post/comments`, ranked by `comment_like_count`) with full vote-weighting parity to YouTube/TikTok (a dedicated `_instagram_engagement` carve-out, the `_VOTE_LOG_REFERENCE`/label/threshold entries). The cross-platform "Top Community Comments" list (`render._render_top_comments`) selects **round-robin by within-platform rank** (every platform's #1, then #2, then #3) so a viral platform can't crowd out a smaller one, and drops the per-platform absolute floor so a less-watched video's killer low-vote comment still surfaces.
## Security hygiene
- Never commit real API keys, browser cookies, auth tokens, app passwords, access tokens, or `.env` contents.
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 83fa4458..6ab3001e 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -68,7 +68,7 @@ Both share the same consent points:
1. **Browser cookies** - the model asks before reading anything. On yes it runs `setup --allow-browser-cookies`, which extracts Firefox/Safari cookies (never Chrome unless `FROM_BROWSER=auto` or a named Chromium browser is explicitly configured) to unlock X/Twitter and other logged-in sources, and installs yt-dlp + the keyless Digg CLI. On no it runs setup without `--allow-browser-cookies` (or with `FROM_BROWSER=off`), which skips all cookie reads and still installs the tools.
2. **Full Disk Access (macOS)** - if a cookie read is permission-denied, the model surfaces the System Settings > Privacy & Security > Full Disk Access fix and offers one retry.
-3. **ScrapeCreators GitHub signup** - offered on every first run (10,000 free calls). On consent it runs `setup --github`, which opens a browser for GitHub device-auth (or registers instantly via the `gh` CLI when installed) and, on success, **persists `SCRAPECREATORS_API_KEY` automatically** (0o600, masked in output) so TikTok, Instagram, and the SC Reddit/YouTube backups activate on the next run. Decline anytime; you can run it later by asking to set up ScrapeCreators. The Step 5 opt-in has two tiers: **Recommended** (TikTok + Instagram) and **Everything**, which also enables Threads, Pinterest, and YouTube/TikTok/Instagram comments via `INCLUDE_SOURCES`.
+3. **ScrapeCreators GitHub signup** - offered on every first run (10,000 free calls). On consent it runs `setup --github`, which opens a browser for GitHub device-auth (or registers instantly via the `gh` CLI when installed) and, on success, **persists `SCRAPECREATORS_API_KEY` automatically** (0o600, masked in output) so TikTok, Instagram, and the SC Reddit/YouTube backups activate on the next run. Decline anytime; you can run it later by asking to set up ScrapeCreators. The Step 5 opt-in has two tiers, both comment-enabled: **Recommended** (TikTok + Instagram posts AND top comments, plus YouTube comments — `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments`) and **Everything**, which also adds Threads + Pinterest. Comments are on by default; Threads and Pinterest are the only opt-in extras.
Re-run onboarding by deleting `~/.config/last30days/.env`. The mechanical work lives in `scripts/lib/setup_wizard.py`; the consent conversation and both host flows are specified in `skills/last30days/SKILL.md` Step 0. The original v3.0.0 wizard is captured at `docs/reference/old-nux-wizard-v3.0.0.md`.
@@ -97,7 +97,9 @@ The project-scoped file is useful for **intentional per-client setups**: drop a
| StockTwits | none | auto-on for ticker/crypto topics only (gated by symbol detection); never registered for non-financial topics | yes (public API, ~200 req/hr per IP) |
| GitHub | `gh` CLI installed (uses your GitHub auth) | always on if `gh` present | yes |
| YouTube | `yt-dlp` CLI installed; `SCRAPECREATORS_API_KEY` adds a server-side transcript fallback used only when yt-dlp fails (429 / bot-gate) | always on if `yt-dlp` present; SC transcript fallback default-on when key set (no credit spent unless yt-dlp fails) | yes |
-| YouTube comments | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `youtube_comments` (opt-in; part of the Step 5 Everything tier) | top comments on the top ~3 videos by engagement | ~3 calls/run; 10K free calls |
+| YouTube comments | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `youtube_comments` (**on by default** — written by the Step 5 Recommended tier) | top comments (by likes) on the top ~3 videos by engagement | ~3 calls/run; 10K free calls |
+| TikTok comments | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `tiktok_comments` (**on by default** — Step 5 Recommended tier) | top comments (by `digg_count`) on the top ~3 TikTok posts | ~3 calls/run; 10K free calls |
+| Instagram comments | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `instagram_comments` (**on by default** — Step 5 Recommended tier) | top comments (by `comment_like_count`) on the top ~3 Instagram posts, via `/v2/instagram/post/comments` | ~3 calls/run; 10K free calls |
| Digg | `digg-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install digg --cli-only`; binary defaults to `$HOME/.local/bin` — Hermes/OpenClaw agent subprocesses must inherit that dir on PATH for Digg to activate; prior pp-digg installs use the same path) | always on if `digg-pp-cli` on PATH | yes (free, keyless, read-only) |
| arXiv | `arxiv-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install arxiv --cli-only`) | always on if `arxiv-pp-cli` on PATH; fires on research/technical topics and stays quiet otherwise (relevance + 365-day recency gating) | yes (free, keyless) |
| Techmeme | `techmeme-pp-cli` on PATH (auto-installed via `... install techmeme --cli-only`) | always on if `techmeme-pp-cli` on PATH; syncs a local headline cache once per run, then searches | yes (free, keyless) |
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index d0f4dc66..24ff0d7f 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -452,7 +452,7 @@ The consented `setup --allow-browser-cookies` run extracts cookies (Chrome/Chrom
**Step 4: ScrapeCreators offer (every first run).** Show this as plain text, then a modal:
-ScrapeCreators adds TikTok and Instagram - 10,000 free calls, no credit card. Your key also acts as a backup that keeps your free sources working when they hit rate limits: it fetches Reddit if public Reddit gets blocked, and YouTube search/transcripts if yt-dlp gets throttled. (We don't get a cut.) You can add even more sources in the next step.
+ScrapeCreators adds TikTok and Instagram - posts AND top comments - plus YouTube comments, all on by default. 10,000 free calls, no credit card. Your key also auto-enriches Reddit (runs public + ScrapeCreators merged for wider coverage) and backstops YouTube search if yt-dlp gets throttled. (We don't get a cut.) You can widen coverage even further in the next step.
Before the modal, run `which gh` via Bash silently; store as gh_available.
@@ -474,15 +474,15 @@ Options:
- "I have a key" - accept the key, write to `.env`.
- "Skip for now" - proceed without ScrapeCreators. No TikTok/Instagram, and no ScrapeCreators backup if Reddit or YouTube get rate-limited (your free sources still work).
-**Step 5: Source opt-in (only if a ScrapeCreators key was saved, not if skipped).** Plain text then modal:
+**Step 5: Source opt-in (only if a ScrapeCreators key was saved, not if skipped).** Comments are the DEFAULT, never an opt-in - there is no posts-only tier. Plain text then modal:
-Your key is set - TikTok and Instagram are on for every run, plus the Reddit/YouTube backups. Want to add even more?
+Your key is set. On by default: TikTok + Instagram (posts AND top comments), YouTube comments, and Reddit auto-enrichment (public + ScrapeCreators). Want the widest net?
**Call AskUserQuestion:**
-Question: "Which ScrapeCreators sources do you want on?"
+Question: "Which ScrapeCreators sources?"
Options:
-- "TikTok + Instagram (recommended)" - the default: TikTok and Instagram on every run (~2-4 credits per run), plus the Reddit/YouTube rate-limit backups. Write NO `INCLUDE_SOURCES` line (TikTok/Instagram are on automatically with the key). Confirm: "TikTok and Instagram are on, plus the Reddit/YouTube backups if the free sources get rate-limited."
-- "Everything (Threads, Pinterest, comments)" - all of the above plus Threads, Pinterest, and YouTube + TikTok/Instagram comment sentiment. Widest coverage, more credits per run. Append `INCLUDE_SOURCES=tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments` to `~/.config/last30days/.env` (the list must include `tiktok,instagram` so they are not treated as excluded). Confirm: "Everything's on: TikTok, Instagram, Threads, Pinterest, and comment sentiment, plus the Reddit/YouTube backups."
+- "TikTok + Instagram + all comments (recommended)" - the default: posts AND top comments (ranked by votes) for TikTok + Instagram, plus YouTube comments. Reddit is auto-enriched too. Append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments` to `~/.config/last30days/.env` (the list must include `tiktok,instagram` so they are not treated as excluded). Confirm: "TikTok, Instagram, and top YouTube/TikTok/Instagram comments are on, plus Reddit auto-enrichment."
+- "Everything (also Threads + Pinterest)" - everything above plus Threads and Pinterest searches. Most coverage, most credits. Append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments,threads,pinterest`. Confirm: "Everything's on: posts + comments for TikTok/Instagram/YouTube, plus Threads and Pinterest."
**Step 6: First-topic picker.** Once `SETUP_COMPLETE=true` is written, **call AskUserQuestion:**
Question: "What do you want to research first?"
@@ -522,9 +522,9 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI
- On **timeout, or any other error** → tell the user it didn't complete and offer to retry or the web signup at scrapecreators.com.
- On **no** → note they can run it later by asking to set up ScrapeCreators, then continue.
-**5b. Source tier (only if a key was saved).** Your key runs TikTok and Instagram on every search plus the Reddit/YouTube backups. Ask whether they want more, e.g.: `Want just TikTok + Instagram (recommended), or Everything - also Threads, Pinterest, and comment sentiment (more credits per run)? (recommended / everything)` **Wait for the answer.**
- - On **recommended** → write NO `INCLUDE_SOURCES` line (TikTok/Instagram are already on with the key). Confirm TikTok and Instagram are on plus the backups.
- - On **everything** → append `INCLUDE_SOURCES=tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments` to `~/.config/last30days/.env` (include `tiktok,instagram` so they are not treated as excluded). Confirm Threads, Pinterest, and comment sentiment are now on too.
+**5b. Source tier (only if a key was saved).** Comments are the default, never opt-in. Your key runs TikTok + Instagram posts AND top comments, YouTube comments, and Reddit auto-enrichment. Ask whether they want the widest net, e.g.: `Recommended is TikTok + Instagram + all comments (posts and top comments for TikTok/Instagram plus YouTube comments). Or Everything - also Threads + Pinterest (more credits). (recommended / everything)` **Wait for the answer.**
+ - On **recommended** → append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments` to `~/.config/last30days/.env` (include `tiktok,instagram` so they are not treated as excluded). Confirm posts + top comments for TikTok/Instagram/YouTube are on, plus Reddit auto-enrichment.
+ - On **everything** → append `INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments,threads,pinterest`. Confirm Threads and Pinterest are on too.
**6. Complete.** Once `SETUP_COMPLETE=true` is written, briefly confirm which sources are now active (read the `setup --github` JSON `persisted` field, re-run `--preflight` for a human permission summary, or re-run safe `--diagnose` for JSON) and proceed to research. For Codex desktop, Cursor, Gemini CLI, and raw folder-mode hosts, hidden `.claude/last30days.env` project config is ignored unless `LAST30DAYS_TRUST_PROJECT_CONFIG=1` is set from the process environment or global config; do not tell the user a project file is active unless diagnose reports it as the config source.
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index be42fcf0..a2858382 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -764,12 +764,13 @@ def is_ytdlp_available() -> bool:
def is_youtube_comments_available(config: dict[str, Any]) -> bool:
"""Check if YouTube comment enrichment is available.
- Opt-in: requires SCRAPECREATORS_API_KEY AND ``youtube_comments`` in
+ Requires SCRAPECREATORS_API_KEY AND ``youtube_comments`` in
``INCLUDE_SOURCES`` (mirrors ``is_tiktok_comments_available``). Cost is
bounded by ``enrich_with_comments(max_videos=3)`` (~3 credits per run).
- Part of the onboarding "Everything" tier — the "Recommended" tier
- (TikTok/Instagram, no INCLUDE_SOURCES) does not fetch comments.
+ In the default onboarding tier: the Recommended tier now enables comments
+ (posts on -> comments on for TikTok/Instagram/YouTube), writing
+ ``youtube_comments`` into INCLUDE_SOURCES.
"""
if not config.get('SCRAPECREATORS_API_KEY'):
return False
@@ -788,6 +789,20 @@ def is_tiktok_comments_available(config: dict[str, Any]) -> bool:
return 'tiktok_comments' in include
+def is_instagram_comments_available(config: dict[str, Any]) -> bool:
+ """Check if Instagram comment enrichment is available.
+
+ Requires SCRAPECREATORS_API_KEY AND instagram_comments in INCLUDE_SOURCES.
+ Mirrors the youtube_comments / tiktok_comments opt-in pattern. Comments are
+ fetched via ScrapeCreators (GET /v2/instagram/post/comments) with each
+ comment's ``comment_like_count`` used as its vote for ranking. Part of the
+ default onboarding tier (posts on -> comments on for TikTok/Instagram/YouTube).
+ """
+ if not config.get('SCRAPECREATORS_API_KEY'):
+ return False
+ return 'instagram_comments' in _parse_include_sources(config)
+
+
def is_youtube_sc_available(config: dict[str, Any]) -> bool:
"""Check if ScrapeCreators YouTube search fallback is available.
diff --git a/skills/last30days/scripts/lib/instagram.py b/skills/last30days/scripts/lib/instagram.py
index 39eca7df..cb09d888 100644
--- a/skills/last30days/scripts/lib/instagram.py
+++ b/skills/last30days/scripts/lib/instagram.py
@@ -519,3 +519,114 @@ def parse_instagram_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
List of item dicts ready for normalization.
"""
return response.get("items", [])
+
+
+# ---------------------------------------------------------------------------
+# Comments (ScrapeCreators, opt-in via INCLUDE_SOURCES=instagram_comments)
+# ---------------------------------------------------------------------------
+
+
+def _ig_total_engagement(item: Dict[str, Any]) -> int:
+ """Sum an Instagram item's engagement for picking which posts to enrich."""
+ eng = item.get("engagement", {}) or {}
+ return (eng.get("views") or 0) + (eng.get("likes") or 0) + (eng.get("comments") or 0)
+
+
+def enrich_with_comments(
+ items: List[Dict[str, Any]],
+ token: str,
+ max_posts: int = 3,
+ max_comments: int = 5,
+) -> List[Dict[str, Any]]:
+ """Enrich top Instagram posts with comment data from ScrapeCreators.
+
+ Mirrors ``tiktok.enrich_with_comments`` / ``youtube_yt.enrich_with_comments``:
+ for the top N posts by engagement, fetch comments and attach them as a
+ ``top_comments`` field (highest-liked first). Failures never crash the run.
+ """
+ if not items or not token or max_posts <= 0:
+ return items
+
+ ranked = sorted(items, key=_ig_total_engagement, reverse=True)
+ top_items = ranked[:max_posts]
+ _log(f"Enriching comments for {len(top_items)} Instagram posts")
+
+ from concurrent.futures import ThreadPoolExecutor, as_completed
+
+ def _enrich_one(item: dict) -> bool:
+ post_url = item.get("url", "")
+ if not post_url:
+ return False
+ try:
+ comments = _fetch_post_comments(post_url, token, max_comments)
+ if comments:
+ item["top_comments"] = comments
+ return True
+ except Exception as exc:
+ _log(f"Comment enrichment failed for {post_url}: {exc}")
+ return False
+
+ enriched_count = 0
+ with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:
+ futures = {executor.submit(_enrich_one, item): item for item in top_items}
+ for future in as_completed(futures):
+ if future.result():
+ enriched_count += 1
+
+ _log(f"Enriched {enriched_count}/{len(top_items)} posts with comments")
+ return items
+
+
+def _fetch_post_comments(
+ post_url: str,
+ token: str,
+ max_comments: int = 5,
+) -> List[Dict[str, Any]]:
+ """Fetch comments for a single Instagram post/reel via ScrapeCreators.
+
+ SC endpoint: GET /v2/instagram/post/comments?url=<post_or_reel_url>
+ Response shape: { comments: [{text, comment_like_count, child_comment_count,
+ created_at, user{username, ...}}], cursor }
+
+ Returns:
+ List of comment dicts with author, text, comment_like_count (likes), date,
+ highest-liked first. Empty list on any error — never crashes the pipeline.
+ """
+ try:
+ data = http.get(
+ f"{SCRAPECREATORS_BASE}/v2/instagram/post/comments",
+ params={"url": post_url},
+ headers=http.scrapecreators_headers(token),
+ timeout=30,
+ retries=2,
+ )
+ except Exception as exc:
+ _log(f"Comment fetch error for {post_url}: {exc}")
+ return []
+
+ raw_comments = data.get("comments") or data.get("data") or []
+ # Sort by like count desc so normalize sees the highest-signal first.
+ raw_comments = sorted(
+ raw_comments,
+ key=lambda c: c.get("comment_like_count", 0) or 0,
+ reverse=True,
+ )
+ out: List[Dict[str, Any]] = []
+ for c in raw_comments[:max_comments]:
+ if not isinstance(c, dict):
+ continue
+ text = c.get("text") or ""
+ if not text:
+ continue
+ user = c.get("user") if isinstance(c.get("user"), dict) else {}
+ author = user.get("username") or ""
+ created_at = c.get("created_at") or ""
+ # created_at is ISO 8601 (e.g. "2026-07-04T14:27:58.000Z"); take the date.
+ date_str = created_at[:10] if isinstance(created_at, str) and len(created_at) >= 10 else ""
+ out.append({
+ "author": author,
+ "text": text[:400],
+ "comment_like_count": c.get("comment_like_count", 0) or 0,
+ "date": date_str,
+ })
+ return out
diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.py
index 569c2865..a1f62103 100644
--- a/skills/last30days/scripts/lib/normalize.py
+++ b/skills/last30days/scripts/lib/normalize.py
@@ -388,9 +388,10 @@ def _normalize_shortform_video(
"hashtags": item.get("hashtags") or [],
"top_comments": _remap_comments(
item.get("top_comments") or [],
- # TikTok uses digg_count as the vote field; Instagram has no
- # comment fetcher today so the key is harmlessly absent.
- score_keys=("score", "digg_count", "likes"),
+ # Instagram comments use comment_like_count as the vote field
+ # (ScrapeCreators /v2/instagram/post/comments); digg_count/likes
+ # kept for shape compatibility.
+ score_keys=("score", "comment_like_count", "digg_count", "likes"),
excerpt_keys=("excerpt", "text"),
),
},
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index da1aae78..0d0862e8 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -1492,7 +1492,12 @@ def _retrieve_stream(
token=env.get_instagram_token(config),
ig_creators=ig_creators,
)
- return instagram.parse_instagram_response(result), {}
+ items = instagram.parse_instagram_response(result)
+ if items and env.is_instagram_comments_available(config):
+ instagram.enrich_with_comments(
+ items, token=config.get("SCRAPECREATORS_API_KEY", ""),
+ )
+ return items, {}
if source == "linkedin":
token = config.get("SCRAPECREATORS_API_KEY", "")
result = linkedin.search_linkedin(
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index b66cf23b..3f9e2152 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -1890,6 +1890,7 @@ _TOP_COMMENT_MIN_SCORE: dict[str, int] = {
"reddit": 10,
"youtube": 50,
"tiktok": 500,
+ "instagram": 5,
"hackernews": 5,
}
_TOP_COMMENT_VOTE_LABEL: dict[str, str] = {
@@ -1897,6 +1898,7 @@ _TOP_COMMENT_VOTE_LABEL: dict[str, str] = {
"hackernews": "points",
"youtube": "likes",
"tiktok": "likes",
+ "instagram": "likes",
}
@@ -2095,9 +2097,12 @@ def _render_top_comments(report, limit: int = 8) -> list[str]:
scored: list[tuple[float, schema.Candidate, schema.SourceItem, dict, str]] = []
for cand in report.ranked_candidates:
for item in cand.source_items:
- # _top_comments_list applies the per-source min-score threshold and
- # the 3-per-item cap, so trivial comments don't surface here either.
- for tc in _top_comments_list(item):
+ # Pass min_score=0 here: the cross-platform list deliberately does
+ # NOT gate on the per-platform absolute floor, because a less-watched
+ # video's killer low-vote top comment is gold too. The 3-per-item cap
+ # still applies; cross-platform fairness is handled by the rank-based
+ # round-robin below, and the model makes the final quotable pick.
+ for tc in _top_comments_list(item, min_score=0):
if not isinstance(tc, dict):
continue
body = (tc.get("excerpt") or tc.get("text") or tc.get("body") or "").strip()
@@ -2111,9 +2116,28 @@ def _render_top_comments(report, limit: int = 8) -> list[str]:
scored.append((strength, cand, item, tc, body))
if len(scored) < 2:
return []
- scored.sort(key=lambda row: -row[0])
+ # Rank-based cross-platform diversity: group by platform, rank each
+ # platform's comments by within-platform vote strength, then interleave by
+ # rank -- every platform's #1, then every #2, then every #3, and so on. This
+ # makes the top-3-of-each-platform outrank the 4th-of-any and guarantees each
+ # platform's #1 a slot, instead of a global vote sort where one viral
+ # platform sweeps the list. Absolute vote counts are NOT compared across
+ # platforms (a less-watched video's killer 50-like comment is gold too);
+ # vote strength only orders comments *within* a platform and breaks ties
+ # among same-rank picks. The model still makes the final quotable pick.
+ by_source: dict[str, list] = {}
+ for row in scored:
+ by_source.setdefault(row[1].source, []).append(row)
+ for src_rows in by_source.values():
+ src_rows.sort(key=lambda row: -row[0])
+ ordered: list = []
+ deepest = max(len(rows) for rows in by_source.values())
+ for rank in range(deepest):
+ tier = [rows[rank] for rows in by_source.values() if len(rows) > rank]
+ tier.sort(key=lambda row: -row[0]) # among same-rank picks, strongest first
+ ordered.extend(tier)
lines = ["## Top Community Comments", ""]
- for _strength, cand, _item, tc, body in scored[:limit]:
+ for _strength, cand, _item, tc, body in ordered[:limit]:
score = tc.get("score", "")
vote_label = _vote_label_for(cand.source)
attribution = _comment_attribution(cand.source, tc.get("author"))
diff --git a/skills/last30days/scripts/lib/signals.py b/skills/last30days/scripts/lib/signals.py
index d610b25c..d49d689a 100644
--- a/skills/last30days/scripts/lib/signals.py
+++ b/skills/last30days/scripts/lib/signals.py
@@ -209,6 +209,19 @@ def _tiktok_engagement(item: schema.SourceItem) -> float | None:
return (0.45 * views) + (0.27 * likes) + (0.18 * comments) + (0.10 * top_comment)
+def _instagram_engagement(item: schema.SourceItem) -> float | None:
+ # Mirrors _tiktok_engagement: reels are video-shaped, and a highly-liked top
+ # comment carves out 10% of the signal (via comment_like_count -> score) so
+ # crowd-loved IG comments lift their post's ranking like YouTube/TikTok.
+ views = log1p_safe(item.engagement.get("views"))
+ likes = log1p_safe(item.engagement.get("likes"))
+ comments = log1p_safe(item.engagement.get("comments"))
+ top_comment = _top_comment_score(item)
+ if not any([views, likes, comments, top_comment]):
+ return None
+ return (0.45 * views) + (0.27 * likes) + (0.18 * comments) + (0.10 * top_comment)
+
+
def _generic_engagement(item: schema.SourceItem) -> float | None:
if not item.engagement:
return None
@@ -225,6 +238,8 @@ def engagement_raw(item: schema.SourceItem) -> float | None:
return _youtube_engagement(item)
if item.source == "tiktok":
return _tiktok_engagement(item)
+ if item.source == "instagram":
+ return _instagram_engagement(item)
weights = ENGAGEMENT_WEIGHTS.get(item.source)
if weights:
return _weighted_engagement(item, weights)
diff --git a/tests/test_instagram.py b/tests/test_instagram.py
index fbf9f80e..8056c999 100644
--- a/tests/test_instagram.py
+++ b/tests/test_instagram.py
@@ -40,6 +40,64 @@ class TestInstagramOwnerTypeSafety(unittest.TestCase):
self.assertEqual("fallbackuser", items[0]["author_name"])
+class TestInstagramComments(unittest.TestCase):
+ """U1: Instagram comment fetching via ScrapeCreators."""
+
+ def test_fetch_post_comments_parses_and_sorts_by_likes(self):
+ from unittest.mock import patch
+ from lib import instagram
+
+ fake = {
+ "success": True,
+ "comments": [
+ {"text": "mid", "comment_like_count": 3,
+ "created_at": "2026-07-04T14:27:58.000Z", "user": {"username": "bob"}},
+ {"text": "gold", "comment_like_count": 500,
+ "created_at": "2026-07-03T10:00:00.000Z", "user": {"username": "alice"}},
+ {"text": "", "comment_like_count": 999,
+ "created_at": "2026-07-02T10:00:00.000Z", "user": {"username": "skip"}},
+ ],
+ "cursor": None,
+ }
+ with patch.object(instagram.http, "get", return_value=fake):
+ out = instagram._fetch_post_comments(
+ "https://www.instagram.com/reel/ABC/", token="k", max_comments=5,
+ )
+ # Empty-text dropped; sorted desc by comment_like_count.
+ self.assertEqual([c["text"] for c in out], ["gold", "mid"])
+ self.assertEqual(out[0]["comment_like_count"], 500)
+ self.assertEqual(out[0]["author"], "alice")
+ self.assertEqual(out[0]["date"], "2026-07-03")
+
+ def test_fetch_post_comments_error_returns_empty(self):
+ from unittest.mock import patch
+ from lib import instagram
+
+ def _boom(*a, **k):
+ raise RuntimeError("network")
+
+ with patch.object(instagram.http, "get", side_effect=_boom):
+ out = instagram._fetch_post_comments("https://x/", token="k")
+ self.assertEqual(out, [])
+
+ def test_enrich_with_comments_no_token_or_items_noop(self):
+ from lib import instagram
+ self.assertEqual([], instagram.enrich_with_comments([], token="k"))
+ items = [{"url": "u", "engagement": {"likes": 5}}]
+ self.assertEqual(items, instagram.enrich_with_comments(items, token=""))
+ self.assertNotIn("top_comments", items[0])
+
+ def test_is_instagram_comments_available_gate(self):
+ from lib import env
+ self.assertFalse(env.is_instagram_comments_available({}))
+ self.assertFalse(env.is_instagram_comments_available(
+ {"SCRAPECREATORS_API_KEY": "k"})) # key but no INCLUDE_SOURCES
+ self.assertFalse(env.is_instagram_comments_available(
+ {"INCLUDE_SOURCES": "instagram_comments"})) # opt-in but no key
+ self.assertTrue(env.is_instagram_comments_available(
+ {"SCRAPECREATORS_API_KEY": "k", "INCLUDE_SOURCES": "tiktok,instagram_comments"}))
+
+
class TestExpandInstagramQueries(unittest.TestCase):
"""Tests for expand_instagram_queries() multi-query generation."""
diff --git a/tests/test_normalize_v3.py b/tests/test_normalize_v3.py
index f231c4d4..376a0f72 100644
--- a/tests/test_normalize_v3.py
+++ b/tests/test_normalize_v3.py
@@ -79,6 +79,33 @@ class NormalizeV3Tests(unittest.TestCase):
self.assertEqual(45, top[1]["score"])
self.assertEqual(7, top[2]["score"])
+ def test_instagram_comment_like_count_maps_to_score(self):
+ """U2: IG comments use comment_like_count as the vote; normalize must
+ carry it into the shared `score` field so it participates in ranking."""
+ items = [
+ {
+ "video_id": "ig-1",
+ "text": "reel caption",
+ "url": "https://www.instagram.com/reel/ABC/",
+ "author_name": "example",
+ "date": "2026-03-01",
+ "engagement": {"views": 10000, "likes": 500, "comments": 30},
+ "top_comments": [
+ {"author": "alice", "text": "gold take", "comment_like_count": 120, "date": "2026-03-02"},
+ {"author": "bob", "text": "mid", "comment_like_count": 5, "date": "2026-03-03"},
+ ],
+ }
+ ]
+ normalized = normalize.normalize_source_items(
+ "instagram", items, "2026-02-15", "2026-03-17",
+ )
+ self.assertEqual(1, len(normalized))
+ top = normalized[0].metadata.get("top_comments")
+ self.assertIsNotNone(top)
+ self.assertEqual(120, top[0]["score"])
+ self.assertEqual("gold take", top[0]["excerpt"])
+ self.assertEqual("alice", top[0]["author"])
+
def test_youtube_top_comments_empty_list_passes_through_cleanly(self):
items = [
{
diff --git a/tests/test_onboarding_contract.py b/tests/test_onboarding_contract.py
index 6177a848..ae4600dc 100644
--- a/tests/test_onboarding_contract.py
+++ b/tests/test_onboarding_contract.py
@@ -59,7 +59,7 @@ class TestOnboardingContract(unittest.TestCase):
"How would you like to set up?",
"your browser's x.com cookies", # cookie-consent modal
"Want to add TikTok and Instagram?", # SC offer
- "Which ScrapeCreators sources do you want on?", # source opt-in
+ "Which ScrapeCreators sources?", # source opt-in
"What do you want to research first?", # topic picker
]
idxs = [self.modal.find(a) for a in anchors]
@@ -180,10 +180,35 @@ class TestOnboardingContract(unittest.TestCase):
self.assertNotIn("Threads", before)
self.assertNotIn("Pinterest", before)
+ def test_offer_copy_names_comments_and_auto_enrichment(self):
+ """The Step 4 offer states comments are part of the default value and
+ describes the key's real auto-enrichment (Reddit merged + YouTube
+ backstop), not a vague 'backup'."""
+ before = self._modal_before_step5()
+ self.assertIn("comments", before.lower())
+ self.assertIn("Reddit", before)
+ self.assertIn("YouTube", before)
+ self.assertIn("10,000 free calls", before)
+
+ def test_recommended_tier_writes_comments_by_default(self):
+ """Comments are the DEFAULT: the recommended option enables YouTube +
+ TikTok + Instagram comments (posts on -> comments on)."""
+ step5 = self._modal_step5()
+ self.assertIn(
+ "INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments",
+ step5,
+ )
+ # There is no posts-only tier.
+ self.assertIn("recommended", step5.lower())
+ self.assertIn("comments", step5.lower())
+
def test_everything_tier_writes_full_include_sources(self):
- """The Everything option persists the full opt-in list (incl. tiktok,instagram)."""
+ """The Everything option persists the full list incl. Threads + Pinterest."""
step5 = self._modal_step5()
- self.assertIn("INCLUDE_SOURCES=tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments", step5)
+ self.assertIn(
+ "INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments,threads,pinterest",
+ step5,
+ )
# --- Chrome-first cookie scan (U2/U3) ---
diff --git a/tests/test_render_v3.py b/tests/test_render_v3.py
index d2db4a0f..419008d7 100644
--- a/tests/test_render_v3.py
+++ b/tests/test_render_v3.py
@@ -297,6 +297,59 @@ class RenderTopCommentsTests(unittest.TestCase):
errors_by_source={},
)
+ def _diversity_candidate(self, source, item_id, comments):
+ item = schema.SourceItem(
+ item_id=item_id, source=source, title="t", body="b",
+ url=f"https://example.com/{item_id}", published_at="2026-03-15",
+ engagement={"views": 1000}, metadata={"top_comments": comments},
+ )
+ return schema.Candidate(
+ candidate_id=item_id, item_id=item_id, source=source, title="t",
+ url=f"https://example.com/{item_id}", snippet="s",
+ subquery_labels=["primary"], native_ranks={"primary:" + source: 1},
+ local_relevance=0.9, freshness=90, engagement=88, source_quality=1.0,
+ rrf_score=0.02, rerank_score=92, final_score=90, sources=[source],
+ source_items=[item],
+ )
+
+ def _diversity_report(self, candidates):
+ return schema.Report(
+ topic="t", range_from="2026-02-14", range_to="2026-03-16",
+ generated_at="2026-03-16T00:00:00+00:00",
+ provider_runtime=schema.ProviderRuntime(
+ reasoning_provider="gemini", planner_model="m", rerank_model="m"),
+ query_plan=schema.QueryPlan(
+ intent="breaking_news", freshness_mode="strict_recent",
+ cluster_mode="story", raw_topic="t",
+ subqueries=[schema.SubQuery(label="primary", search_query="t", ranking_query="t?", sources=["youtube"])],
+ source_weights={"youtube": 1.0}),
+ clusters=[], ranked_candidates=candidates,
+ items_by_source={}, errors_by_source={})
+
+ def test_top_comments_rank_based_diversity(self):
+ """U3: a viral platform can't sweep the list -- top-3-of-each beats
+ 4th-of-any. 4 YouTube videos (3 high-vote comments each) + 1 TikTok video
+ (2 low-vote comments) must still surface BOTH TikTok comments."""
+ yt_cands = []
+ for v in range(4):
+ comments = [
+ {"score": 3000 - v * 100 - i, "excerpt": f"youtube video {v} comment {i} text", "author": f"yt{v}{i}"}
+ for i in range(3)
+ ]
+ yt_cands.append(self._diversity_candidate("youtube", f"yt{v}", comments))
+ tt_cand = self._diversity_candidate("tiktok", "tt0", [
+ {"score": 50, "excerpt": "tiktok killer comment one text", "author": "ttA"},
+ {"score": 40, "excerpt": "tiktok killer comment two text", "author": "ttB"},
+ ])
+ report = self._diversity_report(yt_cands + [tt_cand])
+ lines = render._render_top_comments(report, limit=8)
+ blob = "\n".join(lines)
+ # Both low-vote TikTok comments surface despite 12 higher-vote YouTube ones.
+ self.assertIn("tiktok killer comment one text", blob)
+ self.assertIn("tiktok killer comment two text", blob)
+ # TikTok's #1 appears before YouTube's 3rd-ranked comment (round-robin).
+ self.assertLess(blob.index("tiktok killer comment one"), blob.index("comment 2 text"))
+
def test_reddit_5_comments_renders_top_3(self):
"""Reddit candidate with 5 comments (scores 500, 200, 50, 8, 3) renders 3."""
comments = [
@@ -354,10 +407,15 @@ class RenderTopCommentsTests(unittest.TestCase):
]
report = self._make_report_with_comments(source="youtube", top_comments=comments)
text = render.render_compact(report)
- # YouTube authors render with @ prefix now.
+ # YouTube authors render with @ prefix; "likes" label.
self.assertIn("@alice (120 likes): legit fire tutorial", text)
self.assertIn("@bob (60 likes): saved me hours", text)
- self.assertNotIn("@carol (10 likes)", text)
+ # The per-candidate CARD still applies the 50-like threshold: carol (10)
+ # does not appear on the card (colon-format line).
+ self.assertNotIn("@carol (10 likes):", text)
+ # But the cross-platform Top Community Comments list surfaces her (U3:
+ # rank-based, no absolute floor -- a low-vote comment can be gold).
+ self.assertIn('"below threshold" — @carol (10 likes)', text)
def test_reddit_comment_without_author_falls_back_to_legacy_label(self):
"""When author is missing or [deleted], render falls back to 'Comment (...)'."""
@@ -400,7 +458,13 @@ class RenderTopCommentsTests(unittest.TestCase):
text = render.render_compact(report)
self.assertIn("@a (2000 likes): this aged well", text)
self.assertIn("@b (600 likes): so real", text)
- self.assertNotIn("@c (400 likes)", text)
+ # Card still applies the 500 threshold: c (400) not on the card.
+ self.assertNotIn("@c (400 likes):", text)
+ # Community list surfaces c (it's the item's #3, within the 3-per-item cap;
+ # U3 drops the absolute floor there).
+ self.assertIn('"below tt threshold" — @c (400 likes)', text)
+ # d (50) is the item's 4th comment -> dropped by the 3-per-item cap, so it
+ # never appears anywhere.
self.assertNotIn("@d (50 likes)", text)
diff --git a/tests/test_signals_v3.py b/tests/test_signals_v3.py
index 5ea65bdd..8c9b3648 100644
--- a/tests/test_signals_v3.py
+++ b/tests/test_signals_v3.py
@@ -86,6 +86,32 @@ class SignalsV3Tests(unittest.TestCase):
)
self.assertAlmostEqual(expected, signals.engagement_raw(item), places=6)
+ def test_instagram_engagement_adds_top_comment_slot(self):
+ """U2: IG gets the same 0.10 top-comment carve-out as TikTok, so a
+ highly-liked IG comment lifts its post's ranking."""
+ item = schema.SourceItem(
+ item_id="ig1",
+ source="instagram",
+ title="Title",
+ body="Body",
+ url="https://www.instagram.com/reel/ABC/",
+ engagement={"views": 100000, "likes": 5000, "comments": 500},
+ metadata={"top_comments": [{"score": 1200}]},
+ )
+ expected = (
+ 0.45 * math.log1p(100000)
+ + 0.27 * math.log1p(5000)
+ + 0.18 * math.log1p(500)
+ + 0.10 * math.log1p(1200)
+ )
+ self.assertAlmostEqual(expected, signals.engagement_raw(item), places=6)
+
+ def test_instagram_comment_vote_uses_instagram_reference(self):
+ """U2: normalized_comment_vote uses the instagram reference, not the default."""
+ strength = signals.normalized_comment_vote("instagram", 5000)
+ self.assertGreater(strength, 0.0)
+ self.assertLessEqual(strength, 1.0)
+
def test_youtube_ranking_promotes_viral_comment_thread(self):
"""A moderately-viewed YouTube video with a 10k-like comment should
outrank a slightly-higher-viewed video with no high-signal comments."""
@@ -385,10 +411,12 @@ class SignalsV3Tests(unittest.TestCase):
)
result = signals.engagement_raw(item)
self.assertIsNotNone(result)
+ # U2: IG now uses _instagram_engagement (video-shaped, with a 0.10
+ # top-comment carve-out); no top comment here so that term is 0.
expected = (
- 0.50 * math.log1p(8000)
- + 0.30 * math.log1p(1500)
- + 0.20 * math.log1p(100)
+ 0.45 * math.log1p(8000)
+ + 0.27 * math.log1p(1500)
+ + 0.18 * math.log1p(100)
)
self.assertAlmostEqual(expected, result)
@@ -408,7 +436,7 @@ class SignalsV3Tests(unittest.TestCase):
)
result = signals.engagement_raw(item)
self.assertIsNotNone(result)
- expected = 0.20 * math.log1p(50)
+ expected = 0.18 * math.log1p(50)
self.assertAlmostEqual(expected, result)
def test_hackernews_engagement_all_zero_returns_none(self):