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(x): keep the month's most-engaged Grok Bot X posts in the report (#1237)
Matt Van Hornf66affc6a532
diff --git a/changelog.d/+grok-bot-x-ranking.fixed.md b/changelog.d/+grok-bot-x-ranking.fixed.mdnew file mode 100644index 00000000..aca19ada--- /dev/null+++ b/changelog.d/+grok-bot-x-ranking.fixed.md@@ -0,0 +1 @@+On Grok Bot, the month's most-engaged on-topic X posts now reach the report: a host-fetched X stream holds half its slots for its most-engaged posts that name the topic, so the popular pass's big posts no longer lose to fresher low-engagement ones, and off-topic viral posts never take those slots. The footer's X line now names its source ("via Grok Bot X" or "via X connector"), and the Grok Bot X recipe gives discovered authors only topic-word lanes and uses the engine's UTC date for the window.diff --git a/skills/last30days/references/grok-bot-x.md b/skills/last30days/references/grok-bot-x.mdindex cdcddaaf..f8bd12b4 100644--- a/skills/last30days/references/grok-bot-x.md+++ b/skills/last30days/references/grok-bot-x.md@@ -9,12 +9,12 @@ Read only on an actual Grok Bot host. Browser sessions are never read on this ho2. The "X for Grok Bot" connector plugin's tools (`"provider": "x-connector"`; footer "X via X connector").Use the first lane present in the session that returns posts. If a lane errors or returns nothing, try the next one. Export `LAST30DAYS_X_HOST_LANE=1` and pass `--x-posts` only when a lane returned posts. When no lane did, run `unset LAST30DAYS_X_HOST_LANE` and the Step 1 command without `--x-posts`, so the engine's own X chain (`X_BEARER_TOKEN`, then `XAI_API_KEY`) can still run.-1. **Calls.** Window = the engine's date range (`--days`, default 30: `from` is today minus the day count, `to` is today). Depth count per query = 10 (`--quick`) / 30 (default) / 60 (`--deep`).+1. **Calls.** Window = the engine's date range, which uses the UTC date (`--days`, default 30: `from` is today's UTC date minus the day count, `to` is today's UTC date), even when the host's local date differs. Depth count per query = 10 (`--quick`) / 30 (default) / 60 (`--deep`).- **Topic.** One `topic` call per planned X query, at most 2: the topic itself, plus the second X subquery's search text when the plan has one. Build each query from the raw topic: multi-word topics go unquoted (every word must match), phrase-quote only proper names, and add `-is:retweet`. If fewer than half the posts on the first page mention the topic's main word, retry that query once with its two or three core words.- **Built-in `x` tools.** Pass `sort_order` `recency` (relevancy order skips high-engagement posts; the engine ranks by engagement itself), `start_time` / `end_time` for the window (`end_time` a minute before now), and `max_results` 25 (the tool's minimum is 10; ask for at least 10 and keep only the count you need). Follow `next_token` until the depth count is reached or no token comes back. Then run the **popular pass** for the first topic query only: split the window into 10 equal slices (5 on `--quick`; about 3 days each for the default 30) and fetch one page per slice with `sort_order` `relevancy` and that slice's `start_time` / `end_time`, so a busy topic still surfaces the month's most-engaged posts instead of only its last few minutes. Merge every page of one query, recency and popular, into ONE envelope call; pages can overlap, so keep the first copy of each id. The popular pages do not count toward the depth count. Request `post.fields=created_at,public_metrics,author_id,note_tweet`, `expansions=author_id`, and `user.fields=username`. Map `public_metrics` `like_count` / `retweet_count` / `reply_count` / `quote_count` to `likes` / `reposts` / `replies` / `quotes`, the expanded user's `username` to `author_handle`, and use `note_tweet.text` as `text` when present.- **Connector tools.** Pass the window and the depth count on each call.- - **Named handles.** Per `--x-handle` handle: one `from` call (`from:<handle> -is:retweet`, 8 posts) and one `mention` call (`@<handle> -is:retweet`, 5 posts). Per `--x-related` handle the user gave: one `related` call (`from:<handle> -is:retweet`, 3 posts).- - **Discovered authors.** From every topic post fetched (all pages, before trimming to the depth count), take up to 3 authors (not already an `--x-handle`) with at least 2 posts that are about the topic, most posts first. For each, one `from` call (`from:<handle>` plus the topic's core words, `-is:retweet`, 8 posts) and one `mention` call (`@<handle>` plus the topic's core words, `-is:retweet`, 5 posts), and add the handle to `--x-related`.+ - **Named handles.** Per `--x-handle` handle: one `from` call (`from:<handle> -is:retweet`, 8 posts) and one `mention` call (`@<handle> -is:retweet`, 5 posts). Per handle the user explicitly passed with `--x-related`: one `related` call (`from:<handle> -is:retweet`, 3 posts). A discovered author never gets a `related` call.+ - **Discovered authors.** From every topic post fetched (all pages, before trimming to the depth count), take up to 3 authors (not already an `--x-handle`) with at least 2 posts that are about the topic, most posts first. For each, one `from` call (`from:<handle>` plus the topic's core words, `-is:retweet`, 8 posts) and one `mention` call (`@<handle>` plus the topic's core words, `-is:retweet`, 5 posts), and add the handle to `--x-related` so those two calls keep their lanes. These are a discovered author's only calls.- If the tool rejects the window or count parameters, omit them, keep at most the depth count per query, and write `"status": "partial"` with `"error": "window-unsupported"`.- If a lane fails before returning any posts, move to the next lane (step 0). If posts came back and a later call failed, write `"status": "partial"` with a short category in `error`: `credits`, `not-connected`, or `unavailable` - never raw tool output, never an account or app id.2. **Envelope.** Exactly these top-level fields; every post carries the eight flat fields and nothing else (no URLs, media, or author objects); at most the depth count per query plus its popular pages. Keep the envelope inside the engine's limits or it is rejected: at most 500 posts per call, 1,000 posts and 20 calls in total. When a budget would be exceeded, drop discovered-author calls first, then popular pages; keep the recency pages and the user's own `--x-handle` / `--x-related` calls. A fresh `generated_at` (the engine rejects an envelope older than 6 hours), a `topic` identical to the engine's topic string, and the `provider` of the lane that served it:diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 8d6505b8..a7d850a2 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -2811,10 +2811,12 @@ def run(# together would have (per_stream_limit x the X fetch cap).if source != "jobs":stream_limit = settings["per_stream_limit"]- if source == "x" and config.get("_x_envelope") is not None:+ host_fetched_x = source == "x" and config.get("_x_envelope") is not None+ if host_fetched_x:stream_limit *= _source_fetch_cap("x", config) or 1normalized = _apply_reddit_stream_keepers(- source, normalized, stream_limit, topic+ source, normalized, stream_limit, topic,+ host_fetched_x=host_fetched_x, protected_authors=explicit_first_party,)bundle.add_items(subquery.label, source, normalized)if artifact:@@ -3312,35 +3314,78 @@ def _batch_subject_handles(raw_items: list[dict], *, top_n: int = 2) -> set[str]REDDIT_STREAM_KEEPERS = 3+def _x_raw_engagement(item: schema.SourceItem) -> float:+ """Likes, reposts, replies, and quotes as a plain number."""+ eng = item.engagement or {}+ return float(sum(+ value for key in ("likes", "reposts", "replies", "quotes")+ if isinstance(value := eng.get(key), (int, float)) and not isinstance(value, bool)+ ))+++def _x_post_qualifies(item: schema.SourceItem, entity: str, floor: float) -> bool:+ """On-topic enough for an engagement slot: clears the floor and names the entity."""+ if (item.local_relevance or 0.0) < floor or _x_raw_engagement(item) <= 0:+ return False+ if not entity:+ return True+ return rerank._entity_grounded(f"{item.title or ''} {item.body or ''}", entity)++def _apply_reddit_stream_keepers(source: str,items: list[schema.SourceItem],limit: int,topic: str,+ *,+ host_fetched_x: bool = False,+ protected_authors: Iterable[str] = (),) -> list[schema.SourceItem]:- """Truncate a stream to *limit*, holding slots for Reddit engagement keepers."""+ """Truncate a stream to *limit*, holding slots for engagement keepers.++ Reddit holds a few slots for its most-engaged on-topic threads. A+ host-fetched X stream holds half its slots for its most-engaged on-topic+ posts, because its popular pass reaches back across the whole window and+ those posts would otherwise lose to fresher low-engagement ones. Posts by+ ``protected_authors`` (the run's explicitly named handles) are never+ displaced, because the first-party relevance exemption runs after this cut.+ """kept = list(items[:limit])- if source != "reddit" or len(items) <= limit:+ if len(items) <= limit:return keptentity = rerank._primary_entity(topic or "") if topic else ""floor = fusion.relevance_floor_for_entity(entity)- keepers = [- item- for item in sorted(items, key=fusion.raw_engagement, reverse=True)- if fusion.reddit_thread_qualifies(item, entity, floor)- ][:REDDIT_STREAM_KEEPERS]+ if source == "reddit":+ keepers = [+ item+ for item in sorted(items, key=fusion.raw_engagement, reverse=True)+ if fusion.reddit_thread_qualifies(item, entity, floor)+ ][:REDDIT_STREAM_KEEPERS]+ elif source == "x" and host_fetched_x:+ keepers = [+ item+ for item in sorted(items, key=_x_raw_engagement, reverse=True)+ if _x_post_qualifies(item, entity, floor)+ ][: max(1, limit // 2)]+ else:+ return keptkeeper_ids = {id(item) for item in keepers}+ protected = {author.lstrip("@").lower() for author in protected_authors if author}for keeper in keepers:if any(item is keeper for item in kept):continue# Displace the lowest-ranked non-keeper so the slice stays at limit;- # when the slice is already all keepers there is nothing to trade.+ # when the slice is already all keepers or protected posts there is+ # nothing to trade.displaced = Falsefor index in range(len(kept) - 1, -1, -1):- if id(kept[index]) not in keeper_ids:- del kept[index]- displaced = True- break+ if id(kept[index]) in keeper_ids:+ continue+ if (kept[index].author or "").lstrip("@").lower() in protected:+ continue+ del kept[index]+ displaced = True+ breakif displaced or len(kept) < limit:kept.append(keeper)return kept[:limit]diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.pyindex 39b0ce0c..551e7c52 100644--- a/skills/last30days/scripts/lib/render.py+++ b/skills/last30days/scripts/lib/render.py@@ -2938,6 +2938,10 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:))parts.append(f"{with_transcripts}/{len(items)} with transcripts")+ provenance = report.artifacts.get("x_provenance") if source_key == "x" else None+ if provenance in x_envelope.PROVENANCE_LABELS:+ # Host-fetched X names its lane on the user-facing line too.+ parts.append(f"via {x_envelope.PROVENANCE_LABELS[provenance]}")stats = " │ ".join(parts)line = _footer_line_for_source(emoji, label, len(items), item_word, stats)# Counts only: run diagnostics live in doctor --postmortem, the saveddiff --git a/tests/test_grok_bot_host_contract.py b/tests/test_grok_bot_host_contract.pyindex f007387d..72bf502e 100644--- a/tests/test_grok_bot_host_contract.py+++ b/tests/test_grok_bot_host_contract.py@@ -324,6 +324,14 @@ class TestConnectorRecipe(unittest.TestCase):self.assertIn("5 posts", authors)self.assertIn("`--x-related`", authors)+ def test_related_calls_are_only_for_handles_the_user_passed(self):+ self.assertIn("Per handle the user explicitly passed with `--x-related`", self.recipe)+ self.assertIn("A discovered author never gets a `related` call.", self.recipe)+ self.assertIn("These are a discovered author's only calls.", self.recipe)++ def test_recipe_window_uses_the_engines_utc_date(self):+ self.assertIn("today's UTC date", self.recipe)+def test_recipe_exports_the_lane_only_after_posts_came_back(self):self.assertIn("only when a lane returned posts", self.recipe)self.assertIn("unset LAST30DAYS_X_HOST_LANE", self.recipe)diff --git a/tests/test_x_envelope.py b/tests/test_x_envelope.pyindex 477f4038..de7d966c 100644--- a/tests/test_x_envelope.py+++ b/tests/test_x_envelope.py@@ -841,6 +841,50 @@ class TestPipelineWiring:report = _run(envelope)assert len(report.items_by_source["x"]) == 9+ @staticmethod+ def _old_row(likes: int, handle: str, text: str, low: int) -> dict:+ day = _day(25)+ return {+ "id": _snowflake(day, hour=9, low=low), "author_handle": handle,+ "created_at": f"{day}T09:00:00Z", "text": text,+ "likes": likes, "reposts": likes // 10, "replies": likes // 20, "quotes": 0,+ }++ def test_old_high_engagement_post_survives_a_cap_full_of_fresh_posts(self, tmp_path):+ rows = self._many_topic_rows(57)+ viral = self._old_row(6749, "sawyer", "ai agents livestream building a whole company", 777001)+ envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[*rows, viral])])))+ report = _run(envelope)+ assert len(report.items_by_source["x"]) == 24+ kept_likes = {item.engagement.get("likes") for item in report.items_by_source["x"]}+ assert 6749 in kept_likes++ def test_engagement_keepers_never_evict_the_named_subjects_posts(self):+ def item(n, author, likes, text):+ return schema.SourceItem(+ item_id=f"X{n}", source="x", title=text, body=text,+ url=f"https://x.com/{author}/status/{1900000000000000000 + n}",+ author=author, engagement={"likes": likes}, local_relevance=0.9,+ )+ fresh = [item(i, f"user{i}", 1, f"ai agents fresh note {i}") for i in range(8)]+ subject = [item(20 + i, SUBJECT, 1, f"ai agents subject note {i}") for i in range(2)]+ viral = [item(40 + i, f"fan{i}", 5000 + i, f"ai agents viral thread {i}") for i in range(6)]+ ranked = [*fresh[:6], *subject, *fresh[6:], *viral]+ kept = pipeline._apply_reddit_stream_keepers(+ "x", ranked, 8, TOPIC, host_fetched_x=True, protected_authors={SUBJECT},+ )+ assert len(kept) == 8+ assert sum(1 for i in kept if i.author == SUBJECT) == 2+ assert sum(1 for i in kept if i.author.startswith("fan")) == 4++ def test_off_topic_viral_post_never_takes_an_engagement_slot(self, tmp_path):+ rows = self._many_topic_rows(57)+ off_topic = self._old_row(9000, "rocketco", "orbital launch window opens on friday", 777002)+ envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=[*rows, off_topic])])))+ report = _run(envelope)+ kept_likes = {item.engagement.get("likes") for item in report.items_by_source["x"]}+ assert 9000 not in kept_likes+def test_capped_topic_rows_keep_the_most_engaged_posts(self, tmp_path):rows = self._many_topic_rows(57)envelope = _read(_write(tmp_path, _envelope([_call("topic", posts=list(reversed(rows)))])))@@ -1007,6 +1051,20 @@ class TestPipelineWiring:assert "via Grok Bot X" in mdassert "via X connector" not in md+ @pytest.mark.parametrize(("provider", "label"), [("x-native", "via Grok Bot X"), ("x-connector", "via X connector")])+ def test_user_facing_footer_x_line_names_the_host_lane(self, tmp_path, provider, label):+ envelope = _read(_basic(tmp_path, provider=provider))+ report = _run(envelope, x_handle=SUBJECT)+ footer = [line for line in render._build_source_footer_lines(report) if line.startswith("🔵 X:")]+ assert footer and footer[0].endswith(label)++ def test_backend_footer_x_line_carries_no_host_label(self, tmp_path):+ envelope = _read(_basic(tmp_path))+ report = _run(envelope, x_handle=SUBJECT)+ report.artifacts.pop("x_provenance", None)+ footer = [line for line in render._build_source_footer_lines(report) if line.startswith("🔵 X:")]+ assert footer and "via " not in footer[0]+@pytest.mark.parametrize("provider", ["", "X-Native; rm -rf ~", "grok", "x-native-ish"])def test_unknown_provider_falls_back_to_connector_label(self, tmp_path, provider):envelope = _read(_basic(tmp_path, provider=provider))