Skip to content

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

fix(polymarket): filter on stable topic and clean mangled market labels (#640)

Francesco7b4ae7afb80d
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 98d38172..e28af341 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -1246,7 +1246,12 @@ def _retrieve_stream(
return truthsocial.parse_truthsocial_response(result), {}
if source == "polymarket":
result = polymarket.search_polymarket(subquery.search_query, from_date, to_date, depth=depth)
- return polymarket.parse_polymarket_response(result, topic=subquery.search_query), {}
+ # Relevance filtering keys off the stable original research topic, not the
+ # per-subquery search_query (which narrows differently on each fanout pass
+ # and would let off-topic markets through on broad subqueries while dropping
+ # everything on narrow ones).
+ relevance_topic = raw_topic or topic or subquery.search_query
+ return polymarket.parse_polymarket_response(result, topic=relevance_topic), {}
if source == "github":
# Resolve once at the pipeline boundary so search and enrich
# share the result; otherwise each call would re-run the env
diff --git a/skills/last30days/scripts/lib/polymarket.py b/skills/last30days/scripts/lib/polymarket.py
index aef7eea3..eb32f226 100644
--- a/skills/last30days/scripts/lib/polymarket.py
+++ b/skills/last30days/scripts/lib/polymarket.py
@@ -493,8 +493,9 @@ def _shorten_question(question: str) -> str:
m = re.match(r"^Will\s+(.+?)\s+", q, re.IGNORECASE)
if m and len(m.group(1).split()) <= 4:
return m.group(1).strip()
- # Fallback: truncate
- return question[:40] if len(question) > 40 else question
+ # Fallback: truncate, dropping a leading article so the name doesn't read "an"/"the"
+ text = question[:40] if len(question) > 40 else question
+ return re.sub(r"^(?:a|an|the)\s+", "", text, flags=re.I)
def _compute_text_similarity(topic: str, title: str, outcomes: List[str] = None) -> float:
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index e80e2fec..c2fed043 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -1287,6 +1287,9 @@ def _shorten_polymarket_title(title: str) -> str:
words = t.split()
t = " ".join(words[:6])
+ # Drop a leading article so the descriptor doesn't read "an Anthropic Claude..."
+ t = re.sub(r"^(?:a|an|the)\s+", "", t, flags=re.I)
+
return t
@@ -1318,12 +1321,21 @@ def _polymarket_top_markets(items: list[schema.SourceItem], limit: int = 3) -> l
if not descriptor:
continue
- # For binary Yes/No markets (lead_name == "Yes"), the "Yes" is implicit - omit it.
- # For named outcomes (e.g. "Kanye" in a multi-way market), keep the outcome name.
- if lead_name.lower() == "yes":
+ # Append the outcome name only when it adds information. It's redundant when
+ # empty, a binary Yes/No proxy, a bare article ("an"/"the"), or already the
+ # leading token of the descriptor — appending it then yields noise like
+ # "...score at: an 19%" or a doubled token.
+ label = (lead_name or "").strip()
+ descriptor_lead = descriptor.split()[0].lower() if descriptor.split() else ""
+ redundant = (
+ not label
+ or label.lower() in ("yes", "no", "a", "an", "the")
+ or label.lower() == descriptor_lead
+ )
+ if redundant:
summaries.append(f"{descriptor} {pct}")
else:
- summaries.append(f"{descriptor}: {lead_name} {pct}")
+ summaries.append(f"{descriptor}: {label} {pct}")
return summaries
diff --git a/tests/test_polymarket.py b/tests/test_polymarket.py
index d514e277..4c4344fa 100644
--- a/tests/test_polymarket.py
+++ b/tests/test_polymarket.py
@@ -347,9 +347,32 @@ def test_shorten_question_long():
"""Test truncation of very long questions."""
long_q = "A" * 100
result = polymarket._shorten_question(long_q)
-
+
assert len(result) <= 40
+
+def test_shorten_question_fallback_strips_leading_article():
+ """The truncation fallback must not keep a leading article like 'an' or 'the'.
+
+ Without stripping, a question like 'an Anthropic Claude model scores...' yields
+ a lead name of just 'an', which renders as the mangled 'an 19%' footer fragment.
+ """
+ result = polymarket._shorten_question(
+ "an Anthropic Claude model scores at the top of the leaderboard this month"
+ )
+ lower = result.lower()
+ assert not lower.startswith("a ")
+ assert not lower.startswith("an ")
+ assert not lower.startswith("the ")
+
+
+def test_shorten_question_fallback_keeps_non_article_lead():
+ """Stripping only removes a leading article, not the first informative word."""
+ result = polymarket._shorten_question(
+ "Anthropic ships a major Claude model update before the end of this month"
+ )
+ assert result.lower().startswith("anthropic")
+
# === Tests for search_polymarket() ===
@@ -464,11 +487,51 @@ def test_parse_polymarket_response_engagement():
}
items = polymarket.parse_polymarket_response(response, topic="AI")
-
+
if items: # If not filtered
# Check for volume or liquidity fields
assert "volume24hr" in items[0] or "liquidity" in items[0] or isinstance(items[0], dict)
+
+def _claude_downtime_response():
+ """An off-topic Polymarket event that mentions only the generic word 'Claude'."""
+ return {
+ "events": [
+ create_mock_event(
+ event_id="evt-noise",
+ title="Will Claude go down 3-5 times in June?",
+ slug="claude-downtime",
+ ),
+ ]
+ }
+
+
+def test_parse_polymarket_response_filters_noise_on_full_subquery():
+ """A multi-word subquery filters off-topic 'Claude downtime' noise.
+
+ 'Claude Code subagents workflow' carries 3 informative words; the downtime
+ title matches only one ('claude'), so the min-2 rule drops it.
+ """
+ items = polymarket.parse_polymarket_response(
+ _claude_downtime_response(), topic="Claude Code subagents workflow"
+ )
+ assert items == []
+
+
+def test_parse_polymarket_response_narrow_subquery_leaks_noise():
+ """The SAME off-topic market leaks through a single-word subquery.
+
+ 'claude' has one informative word, so the min-match threshold drops to 1 and
+ the downtime market passes. Because the pipeline previously fed the per-subquery
+ search_query, filtering swung between these two outcomes across the fanout;
+ keying off the stable original topic makes it consistent. This pair pins that
+ threshold-by-word-count behavior the wiring fix depends on.
+ """
+ items = polymarket.parse_polymarket_response(
+ _claude_downtime_response(), topic="claude"
+ )
+ assert len(items) == 1
+
# === Tests for engagement scoring ===
diff --git a/tests/test_render_v3.py b/tests/test_render_v3.py
index 3f804399..d2db4a0f 100644
--- a/tests/test_render_v3.py
+++ b/tests/test_render_v3.py
@@ -989,3 +989,77 @@ class TestCommentAttributionPrefix(unittest.TestCase):
def test_deleted_author_is_comment(self):
self.assertEqual(render._comment_attribution("reddit", "[deleted]"), "Comment")
self.assertEqual(render._comment_attribution("reddit", None), "Comment")
+
+
+class TestShortenPolymarketTitle(unittest.TestCase):
+ def test_fallback_strips_leading_article(self):
+ # A long question that falls through to the 6-word fallback must not keep
+ # a leading article -> avoids descriptors like "an Anthropic Claude model".
+ title = "Will an Anthropic Claude model score at the top of the leaderboard?"
+ result = render._shorten_polymarket_title(title)
+ lower = result.lower()
+ self.assertFalse(lower.startswith("a "))
+ self.assertFalse(lower.startswith("an "))
+ self.assertFalse(lower.startswith("the "))
+
+ def test_fallback_keeps_non_article_lead(self):
+ title = "Anthropic releases a major Claude model update that changes everything soon"
+ result = render._shorten_polymarket_title(title)
+ self.assertTrue(result.lower().startswith("anthropic"))
+
+
+class TestPolymarketTopMarkets(unittest.TestCase):
+ @staticmethod
+ def _pm_item(question, outcome_name, price, volume=1000):
+ return schema.SourceItem(
+ item_id="pm1",
+ source="polymarket",
+ title=question,
+ body="",
+ url="https://polymarket.com/event/x",
+ engagement={"volume": volume},
+ metadata={
+ "question": question,
+ "outcome_prices": [(outcome_name, price)],
+ },
+ )
+
+ def test_article_outcome_is_suppressed(self):
+ # The real-world mangled case: descriptor "...score at" + lead name "an".
+ # The outcome label is an article -> render "<descriptor> <pct>", no ": an ".
+ item = self._pm_item(
+ "Will an Anthropic Claude model score at the top of the leaderboard?",
+ "an",
+ 0.19,
+ )
+ lines = render._polymarket_top_markets([item])
+ self.assertEqual(len(lines), 1)
+ line = lines[0]
+ self.assertNotIn(": an ", line)
+ self.assertIn("19%", line)
+
+ def test_yes_outcome_is_suppressed(self):
+ item = self._pm_item("Will the bill pass this session?", "Yes", 0.65)
+ line = render._polymarket_top_markets([item])[0]
+ self.assertNotIn(": Yes ", line)
+ self.assertIn("65%", line)
+
+ def test_no_outcome_is_suppressed(self):
+ item = self._pm_item("Will the bill pass this session?", "No", 0.30)
+ line = render._polymarket_top_markets([item])[0]
+ self.assertNotIn(": No ", line)
+ self.assertIn("30%", line)
+
+ def test_redundant_lead_token_is_suppressed(self):
+ # Outcome name duplicates the descriptor's first token -> no doubling.
+ item = self._pm_item("Arizona wins the tournament", "Arizona", 0.42)
+ line = render._polymarket_top_markets([item])[0]
+ self.assertNotIn(": Arizona ", line)
+ # Descriptor itself still carries the name once.
+ self.assertIn("Arizona", line)
+
+ def test_named_outcome_is_kept(self):
+ # A genuinely informative multi-way outcome name is preserved.
+ item = self._pm_item("Who wins the primary?", "Kanye", 0.12)
+ line = render._polymarket_top_markets([item])[0]
+ self.assertIn(": Kanye ", line)