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
fix: named creator accounts (--ig-creators / --creators) count as first-party provenance (#1104)
Saurabh3abba4483e9e
diff --git a/changelog.d/1101.fixed.md b/changelog.d/1101.fixed.mdnew file mode 100644index 00000000..0ffadffc--- /dev/null+++ b/changelog.d/1101.fixed.md@@ -0,0 +1 @@+Posts fetched via `--ig-creators` or TikTok `--creators` now reach the report: named creator accounts count as first-party provenance in the relevance prune, scoped to each flag's own platform so a same-name account elsewhere still faces the floor, and prune drops are logged per stream with the dropped count and floor.diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 731da254..e3242501 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -3,7 +3,7 @@from __future__ import annotationsimport copy-from collections.abc import Iterable+from collections.abc import Iterable, Mappingimport mathimport queueimport re@@ -78,6 +78,7 @@ from . import ()from .cluster import cluster_candidatesfrom . import fusion+from . import renderfrom .fusion import collapse_duplicate_urls, weighted_rrfDISCOVERY_SOURCES = ("reddit", "hackernews", "digg", "x")@@ -2173,6 +2174,15 @@ def run(for h in ([x_handle, github_user, *(x_related or [])])if h and h.strip()}+ # Creator accounts named via --ig-creators / --creators carry the same+ # explicit intent: the run is searching those accounts, and a creator's+ # caption rarely repeats the topic's literal tokens, so without an+ # exemption the relevance floor prunes them as third-party noise (issue+ # #1101: 36 creator reels fetched, 0 reported). The exemption is scoped+ # per platform, NOT merged into the global set: each flag names accounts+ # on one platform, and an unrelated same-name account elsewhere must not+ # bypass the floors.+ creator_first_party = _creator_first_party_by_source(tiktok_creators, ig_creators)# Real X handles: --x-handle, --x-related, or @mentions in the topic. These# determine whether the deferred X floor applies. Topic words like "peter"# are NOT real handles and should not trigger the floor — when no real@@ -2481,6 +2491,7 @@ def run(freshness_mode=plan.freshness_mode,ranking_query=subquery.ranking_query,first_party_handles=explicit_first_party,+ first_party_by_source=creator_first_party,# X defers its relevance floor until resolved_handles exists.# Everything else prunes here as before.defer_relevance_prune=(source == "x"),@@ -2539,6 +2550,7 @@ def run(tiktok_creators=tiktok_creators,ig_creators=ig_creators,first_party_handles=explicit_first_party,+ first_party_by_source=creator_first_party,run_started=run_started,)@@ -2578,7 +2590,13 @@ def run(h.lstrip("@").strip().lower()for h in supplemental_handlesif h and h.strip()- }+ } | {h for handles in creator_first_party.values() for h in handles}+ # resolved_handles feeds rerank/fusion, where the first-party marks only+ # resist demotion of items that already passed the inclusion floors and a+ # named account is treated as the subject across surfaces. The inclusion+ # gate (prune_low_relevance) instead gets the platform-scoped+ # creator_first_party map so a cross-platform name collision cannot+ # bypass the floors.# Real X handles from explicit flags, @mentions in topic, or Phase 2 discovery.# When no real handle is identified, skip the X floor entirely — a noisier# report beats losing the subject's evidence. Topic tokens like "peter" are@@ -2595,16 +2613,34 @@ def run(# shape it always has. Only applied when we have real X handles — topic# tokens alone cannot identify the subject.if real_x_handles:+ # IG/TikTok creator exemptions stay on their own platforms: a creator+ # handle must not exempt a same-name X account from this floor. Only+ # creator-ONLY handles are subtracted, where X provenance means+ # real_x_handles (explicit X flags, @mentions in the topic, Phase 2+ # discovery) - a plain topic token or --github-user match is NOT X+ # provenance and does not preserve the exemption.+ x_floor_handles = resolved_handles - _creator_only_handles(+ creator_first_party, real_x_handles+ )for key, stream in list(bundle.items_by_source_and_query.items()):if key[1] != "x" or not stream:continue- bundle.items_by_source_and_query[key] = signals.prune_low_relevance(- stream, first_party_handles=resolved_handles+ pruned = signals.prune_low_relevance(+ stream,+ first_party_handles=x_floor_handles,+ first_party_by_source=creator_first_party,)+ _log_prune_drop("x", len(stream), len(pruned), scope="per-query stream")+ bundle.items_by_source_and_query[key] = prunedif bundle.items_by_source.get("x"):- bundle.items_by_source["x"] = signals.prune_low_relevance(- bundle.items_by_source["x"], first_party_handles=resolved_handles+ x_stream = bundle.items_by_source["x"]+ pruned = signals.prune_low_relevance(+ x_stream,+ first_party_handles=x_floor_handles,+ first_party_by_source=creator_first_party,)+ _log_prune_drop("x", len(x_stream), len(pruned), scope="merged stream")+ bundle.items_by_source["x"] = prunedcandidates = weighted_rrf(bundle.items_by_source_and_query,@@ -2971,6 +3007,72 @@ def _apply_reddit_stream_keepers(return kept[:limit]++def _creator_first_party_by_source(+ tiktok_creators: Iterable[str] | None,+ ig_creators: Iterable[str] | None,+) -> dict[str, set[str]]:+ """Platform-scoped creator handles for the relevance prune.++ --ig-creators names Instagram accounts and --creators names TikTok+ accounts; each exemption applies only on its own platform. Merging both+ into one global handle set would let an unrelated same-name account on+ another platform bypass the relevance and engagement floors.+ """++ def _norm(handles: Iterable[str] | None) -> set[str]:+ return {+ h.lstrip("@").strip().lower()+ for h in (handles or [])+ if h and h.strip()+ }++ return {"instagram": _norm(ig_creators), "tiktok": _norm(tiktok_creators)}+++def _creator_only_handles(+ creator_first_party: Mapping[str, set[str]],+ *x_provenance_sets: Iterable[str],+) -> set[str]:+ """Creator handles that carry no X provenance.++ A handle named ONLY via --ig-creators / --creators must not exempt a+ same-name X account from the deferred X floor. But the same person is+ often named on both surfaces (--x-handle foo --ig-creators foo): the+ normalized sets collapse that to one string, so subtracting the whole+ creator set would strip the explicitly requested X exemption too. The+ subtraction therefore covers only handles absent from every+ X-provenance set (explicit flags, topic mentions, Phase 2 discovery).+ """+ creator_flat = {h for handles in creator_first_party.values() for h in handles}+ x_provenance = {h for handles in x_provenance_sets for h in handles}+ return creator_flat - x_provenance+++def _log_prune_drop(+ source: str, before: int, after: int, scope: str | None = None+) -> None:+ """Log when the relevance prune removes items from a stream.++ The prune is silent by design inside ``signals`` (a pure function), but a+ silent drop is invisible to the user: issue #1101 fetched 36 creator reels+ and reported zero with no line explaining why. Log the count and the reason+ class here, next to the other per-stream retrieval logs. The all-weak+ ``filtered or items`` rescue keeps the originals, so before == after and+ nothing is logged - a rescue is not a drop.+ """+ dropped = before - after+ if dropped <= 0:+ return+ scope_note = f" ({scope})" if scope else ""+ log.source_log(+ render.SOURCE_LABELS.get(source, source.capitalize()),+ f"relevance prune dropped {dropped} of {before} items below the "+ f"relevance/engagement floor{scope_note}",+ tty_only=False,+ )++def _normalize_score_dedupe(source: str,raw_items: list[dict],@@ -2979,6 +3081,7 @@ def _normalize_score_dedupe(freshness_mode: str,ranking_query: str,first_party_handles: Iterable[str] | None = None,+ first_party_by_source: Mapping[str, Iterable[str]] | None = None,defer_relevance_prune: bool = False,) -> list[schema.SourceItem]:"""Normalize, annotate, prune, dedupe, and extract snippets for a batch of raw items.@@ -3023,9 +3126,13 @@ def _normalize_score_dedupe(# case where the handle never appears in the topic at all# ("Peter Steinberger" -> @steipete).floor_handles |= _batch_subject_handles(raw_items)+ pre_prune_count = len(normalized)normalized = signals.prune_low_relevance(- normalized, first_party_handles=floor_handles+ normalized,+ first_party_handles=floor_handles,+ first_party_by_source=first_party_by_source,)+ _log_prune_drop(source, pre_prune_count, len(normalized))normalized = dedupe.dedupe_items(normalized)for item in normalized:item.snippet = snippet.extract_best_snippet(item, prepared_query)@@ -4008,6 +4115,7 @@ def _retry_thin_sources(tiktok_creators: list[str] | None = None,ig_creators: list[str] | None = None,first_party_handles: Iterable[str] | None = None,+ first_party_by_source: Mapping[str, Iterable[str]] | None = None,run_started: float | None = None,) -> None:"""Retry sources with thin results using simplified core subject query."""@@ -4092,6 +4200,7 @@ def _retry_thin_sources(freshness_mode=plan.freshness_mode,ranking_query=retry_subquery.ranking_query,first_party_handles=first_party_handles,+ first_party_by_source=first_party_by_source,# Match Phase 1: X defers its relevance floor until the run has# resolved handles. Applying it here would discard a subject-# authored post that does not repeat the subject's name, and thediff --git a/skills/last30days/scripts/lib/signals.py b/skills/last30days/scripts/lib/signals.pyindex b31a26e9..6ae8518c 100644--- a/skills/last30days/scripts/lib/signals.py+++ b/skills/last30days/scripts/lib/signals.py@@ -3,7 +3,7 @@from __future__ import annotationsimport math-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom . import dates, relevance, schema@@ -335,6 +335,7 @@ def prune_low_relevance(items: list[schema.SourceItem],minimum: float = 0.15,first_party_handles: Iterable[str] | None = None,+ first_party_by_source: Mapping[str, Iterable[str]] | None = None,) -> list[schema.SourceItem]:"""Drop weak lexical matches when stronger evidence exists.@@ -351,6 +352,12 @@ def prune_low_relevance(scores it at or near zero no matter how on-topic it is. Without theexemption a mixed batch loses them silently, because the ``filtered oritems`` rescue below only fires when *every* item fails.++ ``first_party_by_source`` scopes exemptions to one platform each (e.g.+ ``--ig-creators`` names Instagram accounts). A creator flag must not+ exempt a same-name account on a *different* platform: username reuse+ across platforms is common, and an unrelated account would otherwise+ bypass the relevance and engagement floors."""sources_present = {item.source for item in items}first_party = {@@ -358,11 +365,22 @@ def prune_low_relevance(for h in (first_party_handles or ())if h and h.strip()}+ scoped_first_party = {+ source: {+ h.strip().lstrip("@").lower()+ for h in handles+ if h and h.strip()+ }+ for source, handles in (first_party_by_source or {}).items()+ }def _is_first_party(item: schema.SourceItem) -> bool:- if not first_party or not item.author:+ if not item.author:return False- return item.author.strip().lstrip("@").lower() in first_party+ author = item.author.strip().lstrip("@").lower()+ if author in first_party:+ return True+ return author in scoped_first_party.get(item.source, frozenset())def passes(item: schema.SourceItem) -> bool:# YouTube items with successfully extracted transcripts should notdiff --git a/tests/test_creator_first_party.py b/tests/test_creator_first_party.pynew file mode 100644index 00000000..52d8ea26--- /dev/null+++ b/tests/test_creator_first_party.py@@ -0,0 +1,277 @@+"""Named creator accounts (--ig-creators / TikTok --creators) are first-party evidence.++The production failure this pins (issue #1101): creator reels are fetched and+merged into the stream correctly, but ``signals.prune_low_relevance`` then+drops them - a creator's caption rarely contains the topic's literal tokens,+so it scores under the relevance floor, and the first-party exemption covered+only --x-handle / --github-user / --x-related / topic-mention handles. A mixed+batch (keyword hits survive, creator reels fail) therefore loses every creator+item silently: the ``filtered or items`` rescue only fires when *everything*+fails, and no drop was logged.+"""++import contextlib+import io+from datetime import datetime, timezone+from unittest.mock import patch++import pytest++from lib import pipeline, schema, signals+++def _shortform_item(item_id, source, author, relevance, engagement=None):+ item = schema.SourceItem(+ item_id=item_id,+ source=source,+ title="",+ body="post body",+ url=f"https://{source}.com/{author}/{item_id}",+ author=author,+ engagement=engagement or {},+ )+ item.local_relevance = relevance+ return item+++def _annotate(items):+ """Populate engagement_score the way the real pipeline does."""+ scores = signals.normalize([signals.engagement_raw(i) for i in items])+ for item, score in zip(items, scores, strict=True):+ item.engagement_score = score+ return items+++def _mixed_ig_batch():+ """The named creator's reel scores 0.0 (a caption rarely repeats the+ topic's tokens) and sits under the 1000-view floor; the keyword hit and+ the X post clear their floors."""+ return [+ _shortform_item("ig-creator", "instagram", "linkuptv", 0.0,+ {"views": 400, "likes": 12, "comments": 1}),+ _shortform_item("ig-random", "instagram", "random_reposter", 0.02,+ {"views": 300, "likes": 4, "comments": 0}),+ _shortform_item("x-hit", "x", "someone", 0.4,+ {"likes": 90, "reposts": 9}),+ ]+++def test_named_ig_creator_survives_mixed_batch():+ items = _annotate(_mixed_ig_batch())+ kept = signals.prune_low_relevance(items, first_party_handles={"linkuptv"})+ ids = [item.item_id for item in kept]+ assert "ig-creator" in ids, (+ "a reel by an account named via --ig-creators is evidence by "+ "provenance; pruning it from a mixed batch is the #1101 defect"+ )+ assert "ig-random" not in ids, (+ "the exemption must stay scoped to named creators, not blanket-keep "+ "low-relevance reels"+ )+++def test_named_tiktok_creator_survives_mixed_batch():+ """TikTok --creators had the identical gap; tiktok author is the unique_id+ handle, so the normalized comparison is symmetric with Instagram."""+ items = _annotate([+ _shortform_item("tt-creator", "tiktok", "mixtapemadness", 0.0,+ {"views": 800, "likes": 30, "comments": 2}),+ _shortform_item("x-hit", "x", "someone", 0.4,+ {"likes": 90, "reposts": 9}),+ ])+ kept = signals.prune_low_relevance(items, first_party_handles={"mixtapemadness"})+ assert "tt-creator" in [item.item_id for item in kept]+++def test_named_creator_handle_normalization():+ """@ prefix and mixed case on either side must still match."""+ items = _annotate([+ _shortform_item("ig-creator", "instagram", "@LinkUpTV", 0.0,+ {"views": 400, "likes": 12, "comments": 1}),+ _shortform_item("x-hit", "x", "someone", 0.4,+ {"likes": 90, "reposts": 9}),+ ])+ kept = signals.prune_low_relevance(items, first_party_handles={"linkuptv"})+ assert "ig-creator" in [item.item_id for item in kept]+++def test_unnamed_creator_content_still_pruned():+ """Characterizes the defect: without the named-creator wiring the batch+ drops them. If this starts failing, the floor changed and the exemption's+ justification needs rechecking."""+ items = _annotate(_mixed_ig_batch())+ kept = signals.prune_low_relevance(items)+ assert all(item.author != "linkuptv" for item in kept)+++def test_creator_handles_scoped_to_their_platform():+ """The wiring this whole file depends on: creator flags must produce the+ platform-scoped exemption map the prunes receive, normalized the same way+ item authors are."""+ scoped = pipeline._creator_first_party_by_source(+ ["@MixtapeMadness", " "], ["LinkUpTV"]+ )+ assert scoped == {+ "instagram": {"linkuptv"},+ "tiktok": {"mixtapemadness"},+ }+++def test_ig_creator_does_not_exempt_same_name_tiktok_account():+ """An account named via --ig-creators is an Instagram account; a same-name+ TikTok account is a different person and gets no exemption."""+ items = _annotate([+ _shortform_item("tt-same-name", "tiktok", "linkuptv", 0.0,+ {"views": 800, "likes": 30, "comments": 2}),+ _shortform_item("x-hit", "x", "someone", 0.4,+ {"likes": 90, "reposts": 9}),+ ])+ kept = signals.prune_low_relevance(+ items, first_party_by_source={"instagram": {"linkuptv"}}+ )+ assert "tt-same-name" not in [item.item_id for item in kept]+++def test_scoped_exemption_keeps_creator_on_own_platform():+ items = _annotate(_mixed_ig_batch())+ kept = signals.prune_low_relevance(+ items, first_party_by_source={"instagram": {"linkuptv"}}+ )+ ids = [item.item_id for item in kept]+ assert "ig-creator" in ids+ assert "ig-random" not in ids+++def test_deferred_x_floor_ignores_creator_only_handles():+ """The deferred X prune receives resolved_handles minus the creator sets:+ an X account that merely shares a creator's handle still faces the floor."""+ items = _annotate([+ _shortform_item("x-same-name", "x", "linkuptv", 0.0, {"likes": 0}),+ _shortform_item("x-hit", "x", "someone", 0.4, {"likes": 90, "reposts": 9}),+ ])+ kept = signals.prune_low_relevance(+ items,+ first_party_handles=set(), # creator handles were subtracted out+ first_party_by_source={"instagram": {"linkuptv"}},+ )+ assert "x-same-name" not in [item.item_id for item in kept]+++def _raw_ig(item_id, author, text, views):+ return {+ "id": item_id,+ "text": text,+ "url": f"https://instagram.com/reel/{item_id}",+ "author_name": author,+ "date": "2026-09-01",+ "engagement": {"views": views, "likes": 3, "comments": 0},+ }+++def _normalize_quietly(raw, ranking_query="fly.io deploy guide"):+ buf = io.StringIO()+ with contextlib.redirect_stderr(buf):+ kept = pipeline._normalize_score_dedupe(+ "instagram",+ raw,+ "2026-08-06",+ "2026-09-05",+ freshness_mode="balanced_recent",+ ranking_query=ranking_query,+ )+ return kept, buf.getvalue()+++def test_prune_drop_is_logged_with_source_and_count():+ raw = [+ _raw_ig("keep1", "acct", "fly.io deploy guide walkthrough", 5000),+ _raw_ig("drop1", "acct2", "unrelated dance clip", 100),+ ]+ kept, logs = _normalize_quietly(raw)+ assert [item.item_id for item in kept] == ["keep1"], (+ "the off-topic low-engagement reel should still be pruned"+ )+ assert "prune" in logs.lower() and "1" in logs, (+ "a silent drop is the observability half of #1101: the reporter saw "+ "36 reels fetched, 0 reported, and no line explaining why"+ )+++def test_no_log_when_nothing_is_pruned():+ raw = [+ _raw_ig("keep1", "acct", "fly.io deploy guide walkthrough", 5000),+ _raw_ig("keep2", "acct2", "deploying on fly.io with a Dockerfile", 3000),+ ]+ kept, logs = _normalize_quietly(raw)+ assert len(kept) == 2+ assert "prune" not in logs.lower(), (+ "a clean stream must not emit a misleading drop line"+ )+++def test_all_weak_rescue_is_not_logged_as_a_drop():+ """When every item fails and prune_low_relevance keeps the originals, the+ stream lost nothing - logging a drop would be false."""+ raw = [+ _raw_ig("weak1", "acct", "unrelated clip one", 100),+ _raw_ig("weak2", "acct2", "unrelated clip two", 90),+ ]+ kept, logs = _normalize_quietly(raw)+ assert len(kept) == 2, "the filtered-or-items rescue keeps weak sole batches"+ assert "prune" not in logs.lower()+def test_creator_only_handles_preserves_x_provenance():+ """--x-handle foo --ig-creators foo names the same person twice; the X+ exemption must survive the creator-only subtraction (Greptile re-review+ on f49c7bf)."""+ creators = pipeline._creator_first_party_by_source([], ["Foo"])+ real_x = {"foo"} # normalized --x-handle / @mention / Phase 2 discovery+ creator_only = pipeline._creator_only_handles(creators, real_x)+ assert creator_only == set(), "foo has X provenance and is not creator-only"+ creators = pipeline._creator_first_party_by_source([], ["bar"])+ creator_only = pipeline._creator_only_handles(creators, real_x)+ assert creator_only == {"bar"}, "bar was named only as an IG creator"+++def test_topic_token_alone_is_not_x_provenance():+ """A creator handle that also appears as a plain topic token keeps no X+ exemption: X provenance is real_x_handles only (Greptile re-review on+ 2a62aea). The pipeline passes real_x_handles as the provenance set, so a+ topic-token-only handle lands in creator_only and out of x_floor_handles."""+ creators = pipeline._creator_first_party_by_source([], ["linkuptv"])+ # topic mention of "linkuptv" without an @ or X flag: not in real_x_handles+ creator_only = pipeline._creator_only_handles(creators, {"someone_else"})+ assert creator_only == {"linkuptv"}++[email protected]("depth", ["quick", "default"])+def test_creator_provenance_survives_pipeline_ranking(depth):+ raw = [+ _raw_ig("creator", "linkuptv", "an unrelated caption", 400),+ _raw_ig("keyword", "other", "fly.io deploy guide walkthrough", 5000),+ ]+ for item in raw:+ item["date"] = datetime.now(timezone.utc).date().isoformat()+ with patch.object(pipeline, "_retrieve_stream", return_value=(raw, {})), \+ patch.object(pipeline, "_normalize_score_dedupe", wraps=pipeline._normalize_score_dedupe) as normalize:+ report = pipeline.run(+ topic="fly.io deploy guide",+ config={},+ requested_sources=["instagram"],+ ig_creators=["linkuptv"],+ depth=depth,+ mock=True,+ web_backend="none",+ )+ assert normalize.call_args_list+ if depth == "default":+ assert len(normalize.call_args_list) >= 2, "thin retry must also carry the source map"+ assert all(+ call.kwargs["first_party_by_source"]["instagram"] == {"linkuptv"}+ for call in normalize.call_args_list+ )+ assert any(item.author == "linkuptv" for item in report.items_by_source["instagram"])+ assert any(+ item.author == "linkuptv"+ for candidate in report.ranked_candidates+ for item in candidate.source_items+ )