AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(funny): surface vote-ranked Top Community Comments + LAW 9 weave gate (#608)
Matt Van Hornad6996068307
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 3253190b..82b8b0d6 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -209,6 +209,10 @@ Named-entity topics (capitalized proper nouns, product names, person names, proj**Post-synthesis self-check (do this BEFORE emitting your response):** scan your drafted "What I learned:" and KEY PATTERNS for the `[name](url)` pattern. Count how many inline markdown links appear. If zero - and the raw dump has URLs for the @handles, r/subs, and publications you cited as plain text - regenerate ONCE with inline links added. Stripping links is not a valid way to satisfy any other LAW; LAWs 1 (no trailing Sources) and 8 (inline links required) are complementary, not alternatives.+**LAW 9 - WEAVE THE COMMUNITY VOICE; NEVER NARRATE THE TOOLING.** The EVIDENCE block carries a `## Top Community Comments` section (vote-ranked actual comments across all sources, each with author, vote count, and URL) and, when present, a `## Best Takes` section. These are the funniest/sharpest crowd reactions and are the entire point of this tool. **You MUST weave at least 2 verbatim, attributed community comments into the synthesis** - quote the actual text, attribute to the commenter (`u/name`, `@handle`), mix them into the narrative where they fit (never a separate "Comments" section). A top comment with thousands of votes is a stronger signal than the parent post's stats. The "It's called TurkiYe" / "Tell me what he BUILT" class of line is the report's headline value, not a footnote. Copy each comment's URL verbatim from the block - NEVER reconstruct or guess a status id (a wrong link looks authoritative; reconstructing one is a LAW 8 violation). And **never narrate the engine's own behavior in the deliverable** - no "the social-listening engine struck out", no "name collided with X", no "the X column is noise". Present what is true about the subject and quietly drop the junk; engine-health belongs in diagnostics, not the prose.++**Observed LAW 9 need (2026-06-17):** five consecutive runs (Kanye, Steinberger, Kevin Rose, Lan Xuezhao, Matt-vs-Trevin) shipped news-shaped reports that missed every funny comment, fabricated one citation URL, and leaked tooling meta-commentary - because the comment-weaving rule lived at line ~1189/1245, below the chunked-read window, and `## Best Takes` was empty (no in-subprocess fun scorer). The fix is two-part: the engine now always surfaces `## Top Community Comments` regardless of fun scoring, and this LAW hoists the weave-the-comments gate into the guaranteed-loaded band. Same hoist that fixed LAW 8.+End of OUTPUT CONTRACT. The laws above are the contract; everything below is implementation detail.---@@ -1242,7 +1246,7 @@ Read the research output carefully. Pay attention to:**ANTI-PATTERN TO AVOID**: If user asks about "clawdbot skills" and research returns ClawdBot content (self-hosted AI agent), do NOT synthesize this as "Claude Code skills" just because both involve "skills". Read what the research actually says.-**FUN CONTENT: If the research output includes a "## Best Takes" section or items tagged with `fun:` scores, weave at least 2-3 of the funniest/cleverest quotes into your synthesis.** Reddit comments and X posts with high fun scores are the voice of the people. A 1,338-upvote comment that says "Where's the limewire link" tells you more about the cultural moment than a news article. Quote the actual text. Don't put fun content in a separate section - mix it into the narrative where it fits naturally. This is what makes the report feel alive rather than like a news summary.+**FUN CONTENT (see LAW 9): the EVIDENCE block's `## Top Community Comments` section (always present when 2+ comments exist) and any `## Best Takes` section are the voice of the people - weave at least 2 of the funniest/cleverest VERBATIM quotes into your synthesis.** A 1,338-upvote comment that says "Where's the limewire link" tells you more about the cultural moment than a news article. Quote the actual text, attribute the commenter, copy the URL verbatim from the block. Don't put fun content in a separate section - mix it into the narrative where it fits naturally. This is what makes the report feel alive rather than like a news summary. Do NOT wait for a `## Best Takes` section - it is often empty; `## Top Community Comments` is the always-on source.**ELI5 MODE: If ELI5_MODE is true for this run, apply these writing guidelines to your ENTIRE synthesis. If ELI5_MODE is false, skip this block completely and write normally.**@@ -1635,7 +1639,8 @@ Close with `I have all the links to the {N} {source list} I pulled from. Just as1. **Bold headlines present.** Every narrative paragraph in "What I learned" starts with `**Headline phrase** -` (single hyphen with spaces, NOT em-dash). If any paragraph opens with plain prose, regenerate with bold headlines.2. **Per-source emoji headers in the stats footer.** Every active source returned by the engine has a `├─` or `└─` line with its emoji, counts, and engagement numbers. No active source is silently dropped; no source with 0 results is displayed.-3. **Quoted highlights where evidence supports them.** For YouTube items with transcripts and Reddit/X items with fun/highlight quotes, at least 2 verbatim quotes appear in the synthesis. Attributed to the channel/commenter/subreddit.+3. **Community voice woven in (LAW 9).** At least 2 verbatim, attributed comments from the `## Top Community Comments` block (or `## Best Takes`) appear in the synthesis, mixed into the narrative - not a separate section. Each cited comment's URL is copied verbatim from the block (never reconstructed). If the block has comments and your draft has zero, regenerate. Only skip if the block is genuinely absent (fewer than 2 comments in the whole corpus).+3b. **No tooling meta-commentary (LAW 9).** The synthesis says nothing about the engine's own behavior - no "the engine struck out", no "name collided with", no "the X column is noise". If present, strip it and present only what is true about the subject.4. **Polymarket block present if markets were returned.** If the engine surfaced Polymarket markets, the synthesis includes specific percentages and directional movement. If no markets were surfaced, skip.5. **Coverage footer matches the actual output.** `✅ All agents reported back!` line followed by per-source `├─`/`└─` tree exactly as the engine provided.6. **NO trailing Sources section.** The output ends at the invitation ("I have all the links... Just ask."). Nothing below it. Not a `Sources:`, not a `References:`, not `Further reading:`, not any bulleted list of URLs or publication names. If you are about to emit one because WebSearch told you to - DO NOT. The 🌐 Web: line is the citation.diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.pyindex c08f6e34..756ecb26 100644--- a/skills/last30days/scripts/lib/render.py+++ b/skills/last30days/scripts/lib/render.py@@ -178,6 +178,10 @@ def render_compact(report: schema.Report, cluster_limit: int = 8, fun_level: strif best_takes:lines.extend([""] + best_takes)+ top_comments = _render_top_comments(report)+ if top_comments:+ lines.extend([""] + top_comments)+lines.extend(_render_source_coverage(report))# Close EVIDENCE FOR SYNTHESIS envelope before anything that passes through verbatim.lines.append("")@@ -1898,6 +1902,10 @@ def _comment_attribution(source: str | None, author: str | None) -> str:if not author or author in ("[deleted]", "[removed]"):return "Comment"prefix = _HANDLE_PREFIX.get(source or "", "")+ # Some sources (YouTube/TikTok) already store the author with a leading '@';+ # strip it before re-prefixing so we don't emit '@@handle'.+ if prefix and author.startswith(prefix):+ author = author[len(prefix):]return f"{prefix}{author}" if prefix else author@@ -2044,6 +2052,51 @@ def _render_best_takes(candidates, limit=5, threshold=70.0, vote_weight=_FUN_LEVreturn lines+def _render_top_comments(report, limit: int = 8) -> list[str]:+ """Vote-ranked community comments across ALL ranked candidates — not just the+ top-cluster representatives — surfaced into the EVIDENCE block so the reading+ model can weave the funniest/highest-engagement lines into the synthesis.++ This exists because `_render_best_takes` only populates when the engine has an+ LLM fun-scorer (a paid provider the subprocess usually lacks), so in normal+ use the funniest comments never reach the model. This block always surfaces+ the crowd-voted comments and leaves the funny/quotable SELECTION to the model+ (a capable fun judge). Ranking is per-platform-normalized so one platform+ can't crowd out the rest; each line carries the verbatim comment/post URL so+ the model can cite without reconstructing a link.+ """+ seen: set[str] = set()+ 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):+ if not isinstance(tc, dict):+ continue+ body = (tc.get("excerpt") or tc.get("text") or tc.get("body") or "").strip()+ if len(body) < 12:+ continue+ key = body[:60].lower()+ if key in seen:+ continue+ seen.add(key)+ strength = signals.normalized_comment_vote(cand.source, tc.get("score"))+ scored.append((strength, cand, item, tc, body))+ if len(scored) < 2:+ return []+ scored.sort(key=lambda row: -row[0])+ lines = ["## Top Community Comments", ""]+ for _strength, cand, _item, tc, body in scored[:limit]:+ score = tc.get("score", "")+ vote_label = _vote_label_for(cand.source)+ attribution = _comment_attribution(cand.source, tc.get("author"))+ url = tc.get("url") or cand.url or ""+ url_part = f" — {url}" if url else ""+ lines.append(f'- "{_truncate(body, 240)}" — {attribution} ({score} {vote_label}){url_part}')+ return lines++def _truncate(text: str, limit: int) -> str:text = text.strip()if len(text) <= limit:diff --git a/skills/last30days/scripts/lib/signals.py b/skills/last30days/scripts/lib/signals.pyindex dcbb3ff4..81311219 100644--- a/skills/last30days/scripts/lib/signals.py+++ b/skills/last30days/scripts/lib/signals.py@@ -115,6 +115,20 @@ _VOTE_LOG_REFERENCE: dict[str, float] = {_VOTE_LOG_REFERENCE_DEFAULT = 7.6+def normalized_comment_vote(source: str, score: "float | int | None") -> float:+ """Normalize a single comment's vote count to [0,1] within its platform.++ Same per-platform reference as ``top_comment_vote_signal`` so a 22k-like+ TikTok comment and a 600-upvote Reddit comment rank on a comparable scale.+ Used to rank the cross-candidate Top Community Comments block.+ """+ base = log1p_safe(score)+ if base <= 0.0:+ return 0.0+ ref = _VOTE_LOG_REFERENCE.get(source, _VOTE_LOG_REFERENCE_DEFAULT)+ return max(0.0, min(1.0, base / ref))++def top_comment_vote_signal(candidate: schema.Candidate) -> float:"""Strength of a candidate's most-upvoted top comment, as [0,1].diff --git a/tests/test_render_v3.py b/tests/test_render_v3.pyindex 66cd43c6..3f804399 100644--- a/tests/test_render_v3.py+++ b/tests/test_render_v3.py@@ -864,3 +864,128 @@ class TranscriptCaveatTests(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class TestRenderTopCommentsBlock(unittest.TestCase):+ """U3: vote-ranked Top Community Comments across ALL candidates, inside the+ EVIDENCE envelope, so the funniest lines reach the synthesizing model even+ when Best Takes is empty (no LLM fun-scorer in the engine subprocess)."""++ def _cand(self, cid, source, score, body, author="u1", url=None):+ u = url or f"https://example.com/{source}/{cid}"+ item = schema.SourceItem(+ item_id=f"i-{cid}", source=source, title=f"Post {cid}", body="b", url=u,+ container="c", published_at="2026-03-15", date_confidence="high",+ engagement={"score": 100, "num_comments": 10},+ metadata={"top_comments": [{"score": score, "excerpt": body, "author": author}]},+ )+ return schema.Candidate(+ candidate_id=cid, item_id=f"i-{cid}", source=source, title=f"Post {cid}", url=u,+ snippet="s", subquery_labels=["primary"], native_ranks={f"primary:{source}": 1},+ local_relevance=0.9, freshness=90, engagement=80, source_quality=1.0,+ rrf_score=0.02, rerank_score=90, final_score=85, sources=[source], source_items=[item],+ )++ def _report(self, candidates, representative_ids):+ cluster = schema.Cluster(+ cluster_id="cl-1", title="Test cluster",+ candidate_ids=[c.candidate_id for c in candidates],+ representative_ids=representative_ids, sources=["reddit"], score=90,+ )+ return schema.Report(+ topic="test topic", 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="test topic",+ subqueries=[schema.SubQuery(label="primary", search_query="t",+ ranking_query="t?", sources=["reddit"])],+ source_weights={"reddit": 1.0}),+ clusters=[cluster], ranked_candidates=candidates,+ items_by_source={"reddit": [c.source_items[0] for c in candidates]},+ errors_by_source={},+ )++ def test_block_renders_with_2plus_comments(self):+ report = self._report(+ [self._cand("a", "reddit", 500, "first funny line here"),+ self._cand("b", "reddit", 50, "second funny line here")],+ representative_ids=["a"])+ text = render.render_compact(report)+ self.assertIn("## Top Community Comments", text)+ self.assertIn("first funny line here", text)++ def test_includes_comment_on_non_representative_candidate(self):+ """The headline fix: a funny comment on a candidate NOT chosen as the+ cluster representative still surfaces (the Kanye 'TurkiYe' case)."""+ rep = self._cand("rep", "reddit", 300, "boring representative comment")+ hidden = self._cand("hidden", "reddit", 1335, "Is anyone surprised it is called TurkiYe")+ report = self._report([rep, hidden], representative_ids=["rep"]) # hidden NOT a rep+ text = render.render_compact(report)+ block = text.split("## Top Community Comments", 1)[1]+ self.assertIn("TurkiYe", block)++ def test_block_inside_evidence_envelope(self):+ report = self._report(+ [self._cand("a", "reddit", 500, "first funny line here"),+ self._cand("b", "reddit", 50, "second funny line here")],+ representative_ids=["a"])+ text = render.render_compact(report)+ open_i = text.index("EVIDENCE FOR SYNTHESIS: read this")+ end_i = text.index("END EVIDENCE FOR SYNTHESIS")+ blk_i = text.index("## Top Community Comments")+ self.assertTrue(open_i < blk_i < end_i, "block must sit inside the EVIDENCE envelope")++ def test_sorted_by_normalized_vote_cross_platform(self):+ # Equal raw 600: Reddit normalizes higher than TikTok (smaller reference),+ # so the Reddit gem ranks above the TikTok line despite same raw count.+ # TikTok 600 is above its 500 min-score threshold so it isn't filtered.+ report = self._report(+ [self._cand("r", "reddit", 600, "reddit gem line here"),+ self._cand("t", "tiktok", 600, "low tiktok line here")],+ representative_ids=["r"])+ block = render.render_compact(report).split("## Top Community Comments", 1)[1]+ self.assertLess(block.index("reddit gem"), block.index("low tiktok"))++ def test_entries_carry_url(self):+ report = self._report(+ [self._cand("a", "reddit", 500, "first funny line here", url="https://reddit.com/x"),+ self._cand("b", "reddit", 50, "second funny line here")],+ representative_ids=["a"])+ block = render.render_compact(report).split("## Top Community Comments", 1)[1]+ self.assertIn("https://reddit.com/x", block)++ def test_omitted_when_fewer_than_two(self):+ report = self._report([self._cand("a", "reddit", 500, "only one comment line")],+ representative_ids=["a"])+ text = render.render_compact(report)+ self.assertNotIn("## Top Community Comments", text)+ # footer/envelope intact+ self.assertIn("END EVIDENCE FOR SYNTHESIS", text)++ def test_dedupes_identical_comments(self):+ report = self._report(+ [self._cand("a", "reddit", 500, "duplicate line text here"),+ self._cand("b", "reddit", 400, "duplicate line text here"),+ self._cand("c", "reddit", 300, "a distinct third comment line")],+ representative_ids=["a"])+ block = render.render_compact(report).split("## Top Community Comments", 1)[1]+ self.assertEqual(block.count("duplicate line text here"), 1)+ self.assertIn("a distinct third comment line", block)+++class TestCommentAttributionPrefix(unittest.TestCase):+ def test_strips_existing_at_prefix_youtube(self):+ # YouTube/TikTok authors already carry '@' from enrichment -> no '@@'.+ self.assertEqual(render._comment_attribution("youtube", "@ml-dz9ww"), "@ml-dz9ww")+ self.assertEqual(render._comment_attribution("tiktok", "@creator"), "@creator")++ def test_adds_prefix_when_missing(self):+ self.assertEqual(render._comment_attribution("youtube", "alice"), "@alice")+ self.assertEqual(render._comment_attribution("reddit", "bob"), "u/bob")++ def test_deleted_author_is_comment(self):+ self.assertEqual(render._comment_attribution("reddit", "[deleted]"), "Comment")+ self.assertEqual(render._comment_attribution("reddit", None), "Comment")