返回 last30days-skill
test_compact_report_writing.py
根目录 / tests / test_compact_report_writing.py
1 """Compact stdout carries what a report is written from, in copyable shape.
2
3 Three evidence blocks (the subject's own posts, the Polymarket markets with
4 each outcome's own label, and a quote pool whose every entry names its
5 platform, author, count and URL) plus the checklist the command line prints
6 after the canonical boundary of ``--emit=compact`` stdout and nowhere else.
7 """
8
9 import io
10 import json
11 import re
12 import tempfile
13 import types
14 from contextlib import redirect_stderr, redirect_stdout
15 from pathlib import Path
16
17 import pytest
18
19 import last30days as cli
20 from lib import html_render, render, report_checklist, schema
21
22
23 def _item(source, item_id, *, title="A post about Kanye West", body="", url=None,
24 author=None, container=None, engagement=None, metadata=None,
25 published_at="2026-11-05", snippet=""):
26 return schema.SourceItem(
27 item_id=item_id,
28 source=source,
29 title=title,
30 body=body or title,
31 url=url or f"https://example.com/{source}/{item_id}",
32 author=author,
33 container=container,
34 published_at=published_at,
35 date_confidence="high",
36 engagement=engagement or {},
37 snippet=snippet,
38 metadata=metadata or {},
39 )
40
41
42 def _candidate(item, *, extra_items=()):
43 return schema.Candidate(
44 candidate_id=f"c-{item.item_id}",
45 item_id=item.item_id,
46 source=item.source,
47 title=item.title,
48 url=item.url,
49 snippet="",
50 subquery_labels=["primary"],
51 native_ranks={f"primary:{item.source}": 1},
52 local_relevance=0.9,
53 freshness=80,
54 engagement=50,
55 source_quality=1.0,
56 rrf_score=0.02,
57 rerank_score=80,
58 final_score=70,
59 sources=[item.source],
60 source_items=[item, *extra_items],
61 )
62
63
64 def _report(candidates, *, clusters=None, extra_items=(), x_handle="kanyewest",
65 topic="Kanye West"):
66 items_by_source: dict[str, list] = {}
67 for candidate in candidates:
68 for item in candidate.source_items:
69 items_by_source.setdefault(item.source, []).append(item)
70 for item in extra_items:
71 items_by_source.setdefault(item.source, []).append(item)
72 if clusters is None:
73 clusters = [
74 schema.Cluster(
75 cluster_id=f"cl-{index}",
76 title=f"Story {index}",
77 candidate_ids=[candidate.candidate_id],
78 representative_ids=[candidate.candidate_id],
79 sources=[candidate.source],
80 score=90 - index,
81 )
82 for index, candidate in enumerate(candidates, start=1)
83 ]
84 artifacts = {"pre_research_flags_present": True}
85 if x_handle is not None:
86 artifacts["resolved"] = {"entity": topic, "x_handle": x_handle}
87 return schema.Report(
88 topic=topic,
89 range_from="2026-10-11",
90 range_to="2026-11-10",
91 generated_at="2026-11-10T00:00:00+00:00",
92 provider_runtime=schema.ProviderRuntime(
93 reasoning_provider="test", planner_model="test", rerank_model="test"
94 ),
95 query_plan=schema.QueryPlan(
96 intent="general",
97 freshness_mode="balanced_recent",
98 cluster_mode="story",
99 raw_topic=topic,
100 subqueries=[
101 schema.SubQuery(
102 label="primary", search_query=topic, ranking_query=topic,
103 sources=["reddit"],
104 )
105 ],
106 source_weights={"reddit": 1.0},
107 ),
108 clusters=clusters,
109 ranked_candidates=list(candidates),
110 items_by_source=items_by_source,
111 errors_by_source={},
112 artifacts=artifacts,
113 )
114
115
116 def _reddit_thread(index, comments):
117 return _item(
118 "reddit", f"r{index}", title=f"Kanye West Reddit thread number {index}",
119 url=f"https://www.reddit.com/r/hiphopheads/comments/t{index}/",
120 container="hiphopheads", engagement={"score": 500, "num_comments": 40},
121 metadata={"top_comments": comments},
122 )
123
124
125 def _own_post(index, likes, text=None):
126 return _item(
127 "x", f"own{index}",
128 title=text or f"Own post number {index} about the new album",
129 url=f"https://x.com/kanyewest/status/{1000 + index}",
130 author="kanyewest", engagement={"likes": likes, "reposts": 3},
131 published_at=f"2026-11-{index + 1:02d}",
132 )
133
134
135 def _section(text, heading):
136 assert f"\n{heading}\n" in text, text
137 body = text.split(f"\n{heading}\n", 1)[1]
138 return re.split(r"\n(?:## |<!-- END EVIDENCE)", body, maxsplit=1)[0]
139
140
141 def _entries(section):
142 return [line for line in section.splitlines() if line.startswith("- ")]
143
144
145 def _two_comment_candidates():
146 return [
147 _candidate(_reddit_thread(1, [
148 {"author": "CappaccinoJay", "score": 1315, "excerpt": "Internet feelings vs reality.",
149 "url": "https://reddit.com/r/hiphopheads/comments/t1/comment/abc/"},
150 ])),
151 _candidate(_reddit_thread(2, [
152 {"author": "CDC678", "score": 1186, "excerpt": "This stage allows for every seat to be sold."},
153 ])),
154 ]
155
156
157 # --- the subject's own posts -------------------------------------------------
158
159
160 def test_subject_posts_block_lists_the_handles_posts_most_liked_first():
161 own = [_own_post(index, likes) for index, likes in enumerate([40, 9000, 12, 700, 5, 3, 2, 1, 80, 60])]
162 other = _item("x", "fan1", title="A fan post about the album rollout", author="PopBase",
163 engagement={"likes": 99999})
164 report = _report(_two_comment_candidates(), extra_items=[*own, other])
165
166 text = render.render_compact(report)
167 entries = _entries(_section(text, "## Posts by @kanyewest"))
168
169 assert len(entries) == render.SUBJECT_POSTS_LIMIT == 8
170 assert entries[0] == (
171 '- "Own post number 1 about the new album" 🔵 @kanyewest on X · 9,000 likes'
172 " — 2026-11-02 — https://x.com/kanyewest/status/1001"
173 )
174 likes = [int(re.search(r"· ([\d,]+) likes", line).group(1).replace(",", "")) for line in entries]
175 assert likes == sorted(likes, reverse=True)
176 assert all("PopBase" not in line for line in entries)
177 assert all(re.search(r" — \d{4}-\d{2}-\d{2} — https://x\.com/kanyewest/status/\d+$", line) for line in entries)
178
179
180 def test_subject_posts_block_sits_inside_the_evidence_envelope():
181 report = _report(_two_comment_candidates(), extra_items=[_own_post(1, 50)])
182 text = render.render_compact(report)
183 assert (
184 text.index("<!-- EVIDENCE FOR SYNTHESIS")
185 < text.index("## Posts by @kanyewest")
186 < text.index("<!-- END EVIDENCE FOR SYNTHESIS -->")
187 )
188
189
190 def test_subject_posts_match_the_handle_whatever_its_case_or_at_sign():
191 post = _own_post(1, 50)
192 post.author = "@KanyeWest"
193 report = _report(_two_comment_candidates(), extra_items=[post])
194 assert "## Posts by @kanyewest" in render.render_compact(report)
195
196
197 def test_subject_post_text_is_one_line_and_bounded():
198 long_post = _own_post(1, 50, text="line one\n\nline two " + "word " * 200)
199 report = _report(_two_comment_candidates(), extra_items=[long_post])
200 (entry,) = _entries(_section(render.render_compact(report), "## Posts by @kanyewest"))
201 quote = entry.split('" 🔵', 1)[0]
202 assert "line one line two" in quote
203 assert len(quote) <= 290
204
205
206 @pytest.mark.parametrize("x_handle", [None, ""])
207 def test_no_subject_posts_block_without_a_resolved_handle(x_handle):
208 report = _report(_two_comment_candidates(), extra_items=[_own_post(1, 50)], x_handle=x_handle)
209 assert "## Posts by @" not in render.render_compact(report)
210
211
212 def test_no_subject_posts_block_when_the_handle_posted_nothing():
213 report = _report(_two_comment_candidates())
214 assert "## Posts by @" not in render.render_compact(report)
215
216
217 # --- Polymarket --------------------------------------------------------------
218
219
220 def _market(index, *, title, outcomes, movement="", question="", remaining=0,
221 end_date="2027-01-01", volume=1000.0):
222 return _item(
223 "polymarket", f"pm{index}", title=title,
224 url=f"https://polymarket.com/event/market-{index}", container="Polymarket",
225 engagement={"volume": volume, "liquidity": 50.0}, snippet=movement,
226 metadata={
227 "question": question or title,
228 "outcome_prices": outcomes,
229 "outcomes_remaining": remaining,
230 "end_date": end_date,
231 },
232 )
233
234
235 def test_polymarket_block_keeps_each_outcomes_own_label_price_movement_and_url():
236 binary = _market(
237 1, title="Will Kanye West and Bianca Censori separate in 2026?",
238 outcomes=[("Yes", 0.065), ("No", 0.94)], movement="down 2.5% this week",
239 )
240 ladder = _market(
241 2, title="Kanye West album first week sales?",
242 question="Will Kanye West sell 200-250K in the first week?",
243 outcomes=[("150-200K", 0.43), ("200-250K", 0.33), ("100-150K", 0.07)],
244 remaining=4, movement="up 13.0% today", volume=90000.0, end_date="2026-12-01",
245 )
246 report = _report(_two_comment_candidates(), extra_items=[binary, ladder])
247
248 entries = _entries(_section(render.render_compact(report), "## Polymarket Markets"))
249
250 # These items carry no stored odds summary (as one saved by an older
251 # build), so the line is built from the listed outcomes; a single
252 # market's own movement is reworded in points.
253 assert entries == [
254 "- 📊 Polymarket · Kanye West album first week sales: 150-200K at 43% · 200-250K at 33%"
255 " · 100-150K at 7.0% — https://polymarket.com/event/market-2 — closes 2026-12-01"
256 " — +4 more outcomes",
257 "- 📊 Polymarket · Kanye West and Bianca Censori separate in 2026: 6.5%"
258 " (down 2.5 pts this week) — https://polymarket.com/event/market-1 — closes 2027-01-01",
259 ]
260
261
262 def test_polymarket_block_prints_no_dollar_amounts():
263 market = _market(1, title="Will Kanye West tour in 2027?", outcomes=[("Yes", 0.5), ("No", 0.5)],
264 volume=123456.0)
265 section = _section(render.render_compact(_report(_two_comment_candidates(), extra_items=[market])),
266 "## Polymarket Markets")
267 assert "$" not in section
268 assert "123" not in section
269
270
271 def test_polymarket_block_is_bounded_and_skips_markets_that_do_not_name_the_topic():
272 markets = [
273 _market(index, title=f"Will Kanye West do thing {index}?", outcomes=[("Yes", 0.5), ("No", 0.5)],
274 volume=float(index))
275 for index in range(1, 12)
276 ]
277 off_topic = _market(99, title="Will Mae West be honored?", outcomes=[("Yes", 0.5), ("No", 0.5)],
278 volume=10_000_000.0)
279 report = _report(_two_comment_candidates(), extra_items=[*markets, off_topic])
280 entries = _entries(_section(render.render_compact(report), "## Polymarket Markets"))
281 assert len(entries) == render.POLYMARKET_MARKETS_LIMIT == 8
282 assert all("Mae West" not in line for line in entries)
283 assert "thing 11:" in entries[0]
284
285
286 def test_polymarket_snippet_that_is_not_a_movement_is_left_out():
287 market = _market(1, title="Will Kanye West tour in 2027?", outcomes=[("Yes", 0.5), ("No", 0.5)],
288 movement="Will Kanye West tour in 2027? Will Kanye West tour in 2027?")
289 (entry,) = _entries(_section(
290 render.render_compact(_report(_two_comment_candidates(), extra_items=[market])),
291 "## Polymarket Markets",
292 ))
293 assert entry == (
294 "- 📊 Polymarket · Kanye West tour in 2027: 50%"
295 " — https://polymarket.com/event/market-1 — closes 2027-01-01"
296 )
297
298
299 def test_no_polymarket_block_without_markets():
300 assert "## Polymarket Markets" not in render.render_compact(_report(_two_comment_candidates()))
301
302
303 # --- the quote pool ----------------------------------------------------------
304
305 QUOTE_ENTRY = re.compile(
306 r'^- "(?P<quote>.+)" (?P<dot>\S+) (?P<author>\S+) on (?P<place>r/\w+|[A-Z][\w. ]*?)'
307 r"(?: · (?P<count>[\d,]+) (?P<unit>upvotes|likes|points|replies|votes))?"
308 r" — (?P<url>https://\S+)(?: — (?:cluster \d+|re: .+))? — (?P<position>top comment|#2 comment|post)(?: — funny)?$"
309 )
310
311
312 def _mixed_pool_report():
313 youtube = _item(
314 "youtube", "yt1", title="Kanye's Yeezy show breakdown",
315 url="https://www.youtube.com/watch?v=gcv2gecR234", author="The Truth IS",
316 engagement={"views": 144689},
317 metadata={"top_comments": [
318 {"author": "@deesee6009", "score": 27, "excerpt": "Kanye a wolf in sheep's clothing"},
319 ]},
320 )
321 tiktok = _item(
322 "tiktok", "tt1", title="Ye being Ye", url="https://www.tiktok.com/@north/video/1",
323 author="yeniuswest",
324 metadata={"top_comments": [
325 {"author": "@haktimel2", "score": 825451, "excerpt": "Ofc shes literally him😭"},
326 ]},
327 )
328 instagram = _item(
329 "instagram", "ig1", title="Kanye in LA", url="https://www.instagram.com/reel/abc/",
330 author="iamkevinwong",
331 metadata={"top_comments": [
332 {"author": "glovejones", "score": 410, "excerpt": "He really walked out like that"},
333 ]},
334 )
335 hackernews = _item(
336 "hackernews", "42", title="Yeezy site rebuilt", url="https://example.com/article",
337 metadata={"hn_url": "https://news.ycombinator.com/item?id=42", "top_comments": [
338 {"author": "alice", "score": None, "excerpt": "The checkout flow is one page now."},
339 ]},
340 )
341 fan_post = _item(
342 "x", "fan1", title="Kanye sold out AT&T Stadium in nine minutes",
343 url="https://x.com/PopBase/status/77", author="PopBase", engagement={"likes": 48213},
344 )
345 candidates = [
346 *_two_comment_candidates(),
347 _candidate(youtube), _candidate(tiktok), _candidate(instagram),
348 _candidate(hackernews), _candidate(fan_post),
349 ]
350 return _report(candidates, extra_items=[_own_post(1, 50)])
351
352
353 def test_every_quote_pool_entry_has_dot_author_place_url_and_count_when_one_exists():
354 entries = _entries(_section(render.render_compact(_mixed_pool_report()), "## Top Community Comments"))
355 assert len(entries) == 7
356 parsed = {}
357 for entry in entries:
358 match = QUOTE_ENTRY.match(entry)
359 assert match, entry
360 parsed[match["author"]] = match
361 assert parsed["u/CappaccinoJay"]["place"] == "r/hiphopheads"
362 assert parsed["u/CappaccinoJay"]["count"] == "1,315"
363 assert parsed["u/CappaccinoJay"]["url"] == "https://reddit.com/r/hiphopheads/comments/t1/comment/abc/"
364 assert (parsed["@deesee6009"]["dot"], parsed["@deesee6009"]["place"]) == ("🔴", "YouTube")
365 assert (parsed["@deesee6009"]["count"], parsed["@deesee6009"]["unit"]) == ("27", "likes")
366 assert parsed["@deesee6009"]["url"] == "https://www.youtube.com/watch?v=gcv2gecR234"
367 assert parsed["@haktimel2"]["place"] == "TikTok"
368 assert parsed["@haktimel2"]["count"] == "825,451"
369 assert parsed["@glovejones"]["place"] == "Instagram"
370 assert parsed["alice"]["place"] == "Hacker News"
371 assert parsed["alice"]["count"] is None
372 assert parsed["alice"]["url"] == "https://news.ycombinator.com/item?id=42"
373 assert parsed["@PopBase"]["place"] == "X"
374 assert parsed["@PopBase"]["count"] == "48,213"
375 assert parsed["@PopBase"]["url"] == "https://x.com/PopBase/status/77"
376
377
378 def test_quote_pool_entry_copies_into_a_quote_line_with_no_em_dash():
379 entries = _entries(_section(render.render_compact(_mixed_pool_report()), "## Top Community Comments"))
380 (tiktok,) = [entry for entry in entries if "literally him" in entry]
381 assert tiktok.split(" — ", 1)[0] == '- "Ofc shes literally him😭" 🎵 @haktimel2 on TikTok · 825,451 likes'
382
383
384 def test_quote_pool_leaves_the_subjects_own_posts_to_their_block():
385 report = _mixed_pool_report()
386 own = _own_post(2, 999999, text="My own post that everyone liked a lot")
387 report.ranked_candidates.append(_candidate(own))
388 report.items_by_source["x"].append(own)
389 text = render.render_compact(report)
390 assert "My own post that everyone liked" in _section(text, "## Posts by @kanyewest")
391 assert "My own post that everyone liked" not in _section(text, "## Top Community Comments")
392
393
394 def test_comment_without_its_own_url_links_the_item_it_sits_on_not_another_one():
395 """A fused candidate's URL belongs to its first item; the comment's does not."""
396 reddit = _reddit_thread(1, [
397 {"author": "CappaccinoJay", "score": 1315, "excerpt": "Internet feelings vs reality."},
398 ])
399 youtube = _item(
400 "youtube", "yt9", title="A video", url="https://www.youtube.com/watch?v=VIDEO9",
401 metadata={"top_comments": [
402 {"author": "@soundsbyo", "score": 409, "excerpt": "this is so clear technology is insane"},
403 ]},
404 )
405 fused = _candidate(reddit, extra_items=[youtube])
406 lines = render._render_top_comments(_report([fused]))
407 (line,) = [line for line in lines if "soundsbyo" in line]
408 assert "https://www.youtube.com/watch?v=VIDEO9" in line
409 assert "reddit.com" not in line
410
411
412
413 def test_quote_pool_text_is_one_line():
414 candidates = _two_comment_candidates()
415 candidates[1].source_items[0].metadata["top_comments"][0]["excerpt"] = "It's back!\n\nAlso very sorry."
416 section = _section(render.render_compact(_report(candidates)), "## Top Community Comments")
417 assert '- "It\'s back! Also very sorry." 🟠 u/CDC678 on r/hiphopheads · 1,186 upvotes — ' in section
418
419
420 def test_nothing_solid_run_prints_none_of_the_three_blocks():
421 report = _mixed_pool_report()
422 market = _market(1, title="Will Kanye West tour in 2027?", outcomes=[("Yes", 0.5), ("No", 0.5)])
423 report.items_by_source["polymarket"] = [market]
424 for candidate in report.ranked_candidates:
425 candidate.final_score = 0
426 candidate.explanation = "fallback-local-score (entity-miss demotion)"
427 text = render.render_compact(report)
428 assert "Nothing solid this window" in text
429 for heading in ("## Posts by @", "## Polymarket Markets", "## Top Community Comments"):
430 assert heading not in text
431
432
433 # --- the checklist -----------------------------------------------------------
434
435
436 def _args(emit="compact", save_dir=None, output=None, **extra):
437 values = dict(
438 topic=["Kanye West"], competitors=None, competitors_list=None, competitors_plan=None,
439 drill=False, register=None, emit=emit, output=output, save_dir=save_dir, save_suffix="",
440 json_profile="agent", publish_html=False, hiring_signals=False,
441 )
442 values.update(extra)
443 return types.SimpleNamespace(**values)
444
445
446 def _stdout(report, monkeypatch, *, claude_code, emit="compact", save_dir=None, entity_reports=None,
447 no_checklist=False, entrypoint=None, **extra):
448 monkeypatch.delenv("CLAUDECODE", raising=False)
449 monkeypatch.delenv("CLAUDE_CODE_ENTRYPOINT", raising=False)
450 monkeypatch.delenv("LAST30DAYS_NO_REPORT_CHECKLIST", raising=False)
451 if claude_code:
452 monkeypatch.setenv("CLAUDECODE", "1")
453 if entrypoint is not None:
454 monkeypatch.setenv("CLAUDE_CODE_ENTRYPOINT", entrypoint)
455 if no_checklist:
456 monkeypatch.setenv("LAST30DAYS_NO_REPORT_CHECKLIST", "1")
457 out = io.StringIO()
458 with redirect_stdout(out), redirect_stderr(io.StringIO()):
459 rc = cli._render_save_and_print(
460 _args(emit=emit, save_dir=save_dir, **extra), report, entity_reports, None, {},
461 )
462 assert rc == 0
463 return out.getvalue()
464
465
466 def _checklist(stdout):
467 assert f"\n{report_checklist.HEADING}\n" in stdout
468 return stdout.split(f"\n{report_checklist.HEADING}\n", 1)[1]
469
470
471 def test_checklist_is_the_last_block_of_compact_stdout_after_the_boundary(monkeypatch):
472 stdout = _stdout(_mixed_pool_report(), monkeypatch, claude_code=False)
473 boundary = stdout.index("# END OF last30days CANONICAL OUTPUT")
474 heading = stdout.index(report_checklist.HEADING)
475 assert stdout.index("✅ All agents reported back!") < boundary < heading
476 assert stdout.count(report_checklist.HEADING) == 1
477 block = _checklist(stdout)
478 assert "\n## " not in block and "\n# " not in block
479 lines = [line for line in block.splitlines() if line.strip()]
480 assert len(lines) <= 8
481 assert stdout.endswith(lines[-1] + "\n")
482
483
484 def test_checklist_states_the_format_rules_as_facts(monkeypatch):
485 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=False))
486 assert "badge line" in block and "🌐 last30days" in block
487 assert "bold headline phrase" in block and "`**Headline** - text`" in block
488 assert '`> "quote" 🟠 u/author on r/sub · 1,315 upvotes`' in block
489 assert "`## Top Community Comments`" in block
490 assert "`## Posts by @kanyewest`" in block
491 assert "The report's best six quotes each get their own line under their paragraph" in block
492 assert "six in the whole report" in block
493 assert "Other good quotes may stay inside a paragraph, attributed and linked" in block
494 assert "no quote is used both ways" in block
495 assert "per story" not in block and "never inside a paragraph" not in block
496 assert "```text" in block and "fence included" in block
497 assert "I'm now an expert on" in block
498 assert "User and host instructions come first" in block
499
500
501 def test_checklist_mentions_lists_only_on_claude_code(monkeypatch):
502 plain = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=False))
503 for needle in ("markdown list", "Claude Code", "`1\\.`", "`•`"):
504 assert needle not in plain
505 on_claude_code = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=True))
506 assert "no markdown lists anywhere" in on_claude_code
507 # A note with bullets after the report breaks every link in the message.
508 assert "notes you add before or after it carry no bullets" in on_claude_code
509 assert "whenever you show the report in a later message" in on_claude_code
510 assert "`1\\.`" in on_claude_code and "`•`" in on_claude_code
511 assert "raw `name (url)` text" in on_claude_code
512 assert len([line for line in on_claude_code.splitlines() if line.strip()]) <= 8
513
514
515 def test_checklist_itself_holds_no_markdown_list(monkeypatch):
516 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=True))
517 for line in block.splitlines():
518 assert not re.match(r"\s*(?:[-*+] |\d+\. )", line), line
519
520
521 def test_checklist_jobs_line_follows_the_jobs_digest_block(monkeypatch):
522 from lib import jobs_digest
523
524 without = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=False))
525 assert "no `## Jobs Digest` block" in without
526 assert "no Jobs Page Secret Signals section" in without
527
528 raw = [
529 {"id": f"GH{index}", "title": f"Engineer {index}", "department": f"Dept {index}",
530 "location": "Remote", "url": f"https://boards.greenhouse.io/acme/jobs/{index}",
531 "description": f"Own system {index}.", "date": "2026-11-01", "posted_date_true": True}
532 for index in range(6)
533 ]
534 report = _mixed_pool_report()
535 report.artifacts["jobs"] = {
536 "tier": "ats", "provider": "greenhouse", "company": "Acme", "owned": True,
537 "open_roles": 6, "new_in_window": 6,
538 "digest": jobs_digest.build_digest(raw, jobs_digest.select_roles(raw)),
539 }
540 stdout = _stdout(report, monkeypatch, claude_code=False)
541 assert "\n## Jobs Digest\n" in stdout
542 with_digest = _checklist(stdout)
543 assert "has a `## Jobs Digest` block" in with_digest
544 assert "`hiring-signals.md`" in with_digest
545
546
547 def test_checklist_claims_no_precedence(monkeypatch):
548 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=True))
549 for pattern in (
550 r"\bSUPERSEDED\b", r"\bOVERRIDDEN\b", r"overrides", r"IGNORE", r"skill-specified rule wins",
551 r"\bMUST\b", r"\bYOU ARE\b", r"regardless of",
552 ):
553 assert not re.search(pattern, block), pattern
554
555
556 def test_exec_register_and_comparison_checklists_leave_out_the_quote_line(monkeypatch):
557 report = _mixed_pool_report()
558 exec_block = _checklist(_stdout(report, monkeypatch, claude_code=True, register="exec"))
559 comparison_block = _checklist(_stdout(
560 report, monkeypatch, claude_code=True,
561 entity_reports=[("Kanye West", report), ("Drake", report)],
562 ))
563 for block in (exec_block, comparison_block):
564 assert '> "quote"' not in block
565 assert "bold headline phrase" not in block
566 assert "badge line" in block
567 assert "no markdown lists anywhere" in block
568 assert "fence included" in block
569
570
571 def test_checklist_is_absent_from_the_saved_file_and_the_output_file(monkeypatch):
572 with tempfile.TemporaryDirectory() as tmp:
573 save_dir = Path(tmp) / "saved"
574 output = Path(tmp) / "out" / "report.md"
575 stdout = _stdout(
576 _mixed_pool_report(), monkeypatch, claude_code=True,
577 save_dir=str(save_dir), output=str(output),
578 )
579 assert report_checklist.HEADING in stdout
580 (saved,) = list(save_dir.glob("*.md"))
581 assert report_checklist.HEADING not in saved.read_text(encoding="utf-8")
582 assert report_checklist.HEADING not in output.read_text(encoding="utf-8")
583 # The saved file is still the full dump, with the footer citing it.
584 assert "## All Items by Source" in saved.read_text(encoding="utf-8")
585
586
587 @pytest.mark.parametrize("emit", ["md", "json", "html", "context", "brief"])
588 def test_checklist_is_absent_from_every_other_emit_mode(monkeypatch, emit):
589 stdout = _stdout(_mixed_pool_report(), monkeypatch, claude_code=True, emit=emit)
590 assert report_checklist.HEADING not in stdout
591 assert "Before you write" not in stdout
592 if emit == "json":
593 json.loads(stdout)
594
595
596 def test_checklist_is_absent_from_render_functions(monkeypatch):
597 monkeypatch.setenv("CLAUDECODE", "1")
598 report = _mixed_pool_report()
599 assert report_checklist.HEADING not in render.render_compact(report)
600 assert report_checklist.HEADING not in render.render_full(report, save_path="~/x.md")
601 assert report_checklist.HEADING not in html_render.render_html(report)
602 assert render.render_compact(report).rstrip().endswith("# END OF last30days CANONICAL OUTPUT")
603
604
605 def test_wrapper_env_var_turns_the_checklist_off(monkeypatch):
606 stdout = _stdout(_mixed_pool_report(), monkeypatch, claude_code=True, no_checklist=True)
607 assert report_checklist.HEADING not in stdout
608 assert stdout.rstrip().endswith("# END OF last30days CANONICAL OUTPUT")
609
610
611 def test_hiring_signals_run_prints_no_checklist(monkeypatch):
612 stdout = _stdout(_mixed_pool_report(), monkeypatch, claude_code=True, hiring_signals=True)
613 assert report_checklist.HEADING not in stdout
614
615
616 # --- quality floors (added last so the sections above stay readable) ----------
617
618
619 def test_subject_posts_block_leaves_out_reposts():
620 repost = _own_post(1, 0, text="RT @ComplexMusic: History was MADE in Houston tonight")
621 report = _report(_two_comment_candidates(), extra_items=[repost, _own_post(2, 40)])
622 (entry,) = _entries(_section(render.render_compact(report), "## Posts by @kanyewest"))
623 assert "Own post number 2" in entry
624
625
626 def test_quote_pool_takes_no_unliked_post_and_no_wordless_comment():
627 quiet_post = _item("x", "quiet", title="Como te amo Kanye West de verdade",
628 author="ordonena", engagement={"likes": 1})
629 emoji = _reddit_thread(3, [{"author": "hearts", "score": 900, "excerpt": "❤️❤️❤️❤️❤️❤️❤️❤️"}])
630 report = _report([*_two_comment_candidates(), _candidate(quiet_post), _candidate(emoji)])
631 section = _section(render.render_compact(report), "## Top Community Comments")
632 assert "ordonena" not in section
633 assert "u/hearts" not in section
634 assert len(_entries(section)) == 2
635
636
637
638
639 def test_quote_pool_keeps_hacker_news_comments_with_no_or_zero_points():
640 story = _item("hackernews", "42", title="A story", url="https://example.com/article", metadata={
641 "hn_url": "https://news.ycombinator.com/item?id=42",
642 "top_comments": [
643 {"author": "alice", "score": None, "excerpt": "The checkout flow is one page now."},
644 {"author": "bob", "score": 0, "excerpt": "A measured zero is still shown here."},
645 ],
646 })
647 report = _report([*_two_comment_candidates(), _candidate(story)])
648 section = _section(render.render_compact(report), "## Top Community Comments")
649 assert '" 🟡 alice on Hacker News — ' in section
650 assert '" 🟡 bob on Hacker News · 0 points — ' in section
651
652
653
654 # --- round 2: recommendation runs, copy wording, quote text, story floor ------
655
656
657 @pytest.mark.parametrize("topic", [
658 "best noise cancelling headphones", "Top AI coding agents", "what are the best CRMs for startups",
659 "what vector database should I use", "recommended standing desks",
660 ])
661 def test_recommendation_run_checklist_leaves_out_story_quote_and_headline_lines(monkeypatch, topic):
662 report = _mixed_pool_report()
663 report.topic = topic
664 report.query_plan.raw_topic = topic
665 block = _checklist(_stdout(report, monkeypatch, claude_code=True))
666 assert '> "quote"' not in block
667 assert "bold headline phrase" not in block
668 assert "story" not in block
669 for kept in ("badge line", "no markdown lists anywhere", "fence included", "I'm now an expert on"):
670 assert kept in block
671
672
673 @pytest.mark.parametrize(("topic", "intent"), [
674 ("Kanye West", "general"),
675 ("Sundar Pichai best moments", "opinion"),
676 # A name that opens "Top" or "Best", under a plan that says it is news.
677 ("Top Gun Maverick sequel news", "breaking_news"),
678 ("Best Buy earnings", "factual"),
679 ])
680 def test_ordinary_topics_keep_the_story_quote_line(monkeypatch, topic, intent):
681 report = _mixed_pool_report()
682 report.topic = topic
683 report.query_plan.raw_topic = topic
684 report.query_plan.intent = intent
685 assert '> "quote"' in _checklist(_stdout(report, monkeypatch, claude_code=False))
686
687
688 def test_checklist_says_copy_through_the_count_and_that_six_is_a_ceiling(monkeypatch):
689 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=False))
690 assert "Copy the entry through its count (through the platform name when it has no count)" in block
691 assert "up to its URL" not in block
692 assert "a ceiling, not a target" in block
693
694
695 @pytest.mark.parametrize("entrypoint", [None, "cli"])
696 def test_terminal_checklist_keeps_pseudo_lists_tight_with_hard_breaks(monkeypatch, entrypoint):
697 # cmux and other terminals report `cli`; older Claude Code builds set no entrypoint.
698 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=True,
699 entrypoint=entrypoint))
700 assert "KEY PATTERNS as `1\\.`, invitation lines as `•`" in block
701 # A trailing backslash is a hard line break: the terminal draws each item on
702 # its own row, and a markdown viewer (Remote Control, a phone) keeps them apart.
703 assert "end every line of the block except its last with `\\`" in block
704 assert "label line too" in block
705 assert "no blank line between" in block
706 assert "with a blank line between each" not in block
707
708
709 @pytest.mark.parametrize("entrypoint", ["sdk-ts", "claude-desktop", "claude-vscode"])
710 def test_app_checklist_asks_for_real_tight_lists(monkeypatch, entrypoint):
711 # T3 Code reports `sdk-ts`; apps render markdown themselves, so the terminal's
712 # streaming link redraw never happens there and real lists render cleanly.
713 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=True,
714 entrypoint=entrypoint))
715 assert "real numbered list" in block
716 assert "no blank line between items" in block
717 assert "`1\\.`" not in block
718 assert "no markdown lists anywhere" not in block
719 assert "raw `name (url)` text" not in block
720
721
722 def test_no_list_line_without_claude_code_even_with_an_entrypoint(monkeypatch):
723 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=False,
724 entrypoint="sdk-ts"))
725 for needle in ("markdown list", "real numbered list", "`1\\.`", "`•`"):
726 assert needle not in block
727
728
729 def test_posts_entry_ends_its_copyable_part_at_the_count():
730 report = _report(_two_comment_candidates(), extra_items=[_own_post(1, 108107)])
731 (entry,) = _entries(_section(render.render_compact(report), "## Posts by @kanyewest"))
732 copyable, date, url = entry.split(" — ")
733 assert copyable.endswith("🔵 @kanyewest on X · 108,107 likes")
734 assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", date)
735 assert url.startswith("https://x.com/kanyewest/status/")
736
737
738 def test_leading_reply_handles_are_stripped_from_post_text_only():
739 own = _own_post(1, 50, text="@yzyupdates @brazil_ye Bro This was a vibe, ask @north about it")
740 reply = _item("x", "fan2", title="@kanyewest @PopBase this is the best tour of the decade",
741 url="https://x.com/fan/status/9", author="fan", engagement={"likes": 400})
742 mention_only = _own_post(2, 900, text="@yzyupdates @brazil_ye")
743 comment = _reddit_thread(3, [
744 {"author": "replier", "score": 300, "excerpt": "@grok is this true or is it made up"},
745 ])
746 report = _report(
747 [*_two_comment_candidates(), _candidate(reply), _candidate(comment)],
748 extra_items=[own, mention_only],
749 )
750 text = render.render_compact(report)
751 (post,) = _entries(_section(text, "## Posts by @kanyewest"))
752 assert post.startswith('- "Bro This was a vibe, ask @north about it" 🔵 @kanyewest on X · 50 likes')
753 pool = _section(text, "## Top Community Comments")
754 assert '- "this is the best tour of the decade" 🔵 @fan on X · 400 likes' in pool
755 # A comment on another platform keeps its text as written.
756 assert '- "@grok is this true or is it made up" 🟠 u/replier' in pool
757
758
759 def test_quote_text_has_exactly_one_pair_of_outer_quotes():
760 candidates = _two_comment_candidates()
761 candidates[1].source_items[0].metadata["top_comments"][0]["excerpt"] = (
762 '"If you have 100 more kids..." 😂😂😂😂'
763 )
764 own = _own_post(1, 50, text='He said "no" and then "maybe" to the label')
765 text = render.render_compact(_report(candidates, extra_items=[own]))
766 assert "- \"'If you have 100 more kids...' 😂😂😂😂\" 🟠 u/CDC678" in _section(text, "## Top Community Comments")
767 assert "- \"He said 'no' and then 'maybe' to the label\" 🔵 @kanyewest" in _section(text, "## Posts by @kanyewest")
768 for line in _entries(_section(text, "## Top Community Comments")):
769 assert line.count('"') == 2, line
770
771
772 def test_long_quote_is_cut_at_a_sentence_end_when_one_fits():
773 long = "The satellites are already up. " + "They image through cloud at night. " + "filler " * 60
774 candidates = _two_comment_candidates()
775 candidates[1].source_items[0].metadata["top_comments"][0]["excerpt"] = long
776 section = _section(render.render_compact(_report(candidates)), "## Top Community Comments")
777 assert '- "The satellites are already up. They image through cloud at night." 🟠 u/CDC678' in section
778
779
780 def test_long_quote_with_no_sentence_end_is_cut_at_a_word_with_one_ellipsis():
781 long = " ".join(f"word{index}" for index in range(80))
782 candidates = _two_comment_candidates()
783 candidates[1].source_items[0].metadata["top_comments"][0]["excerpt"] = long
784 (line,) = [
785 line for line in _entries(_section(render.render_compact(_report(candidates)), "## Top Community Comments"))
786 if "word0" in line
787 ]
788 quote = line.split('" 🟠', 1)[0][3:]
789 assert len(quote) <= 240
790 assert quote.endswith("...") and not quote.endswith("....")
791 assert re.search(r"word\d+\.\.\.$", quote)
792 assert quote[:-3] == long[: len(quote) - 3]
793
794
795 def test_quote_text_carries_no_raw_url():
796 candidates = _two_comment_candidates()
797 candidates[1].source_items[0].metadata["top_comments"][0]["excerpt"] = (
798 "ICEYE already announced this: https://www.iceye.com/newsroom/press-releases/iceye-and-nokia "
799 "and see www.example.com/page too. Worth a read."
800 )
801 (line,) = [
802 line for line in _entries(_section(render.render_compact(_report(candidates)), "## Top Community Comments"))
803 if "ICEYE" in line
804 ]
805 quote = line.split('" 🟠', 1)[0]
806 assert "http" not in quote and "www." not in quote and "iceye.com" not in quote
807 assert quote == '- "ICEYE already announced this: and see too. Worth a read.'
808
809
810
811
812 # --- round 3: the pool is chosen and ordered by position, not by likes --------
813
814
815 def _thread(source, index, scores, *, container=None):
816 return _item(
817 source, f"{source}{index}", title=f"Kanye West {source} item {index}",
818 url=f"https://example.com/{source}/{index}", container=container,
819 metadata={"top_comments": [
820 {"author": f"{source}{index}rank{rank}", "score": score,
821 "excerpt": f"Rank {rank} remark on {source} item {index}."}
822 for rank, score in enumerate(scores, start=1)
823 ]},
824 )
825
826
827 def _cluster(index, candidates):
828 return schema.Cluster(
829 cluster_id=f"cl-{index}", title=f"Story {index}",
830 candidate_ids=[candidate.candidate_id for candidate in candidates],
831 representative_ids=[candidates[0].candidate_id],
832 sources=sorted({candidate.source for candidate in candidates}), score=90 - index,
833 )
834
835
836 def _pool_authors(lines):
837 return [re.search(r"(\w+rank\d)", line.split('" ', 1)[1]).group(1) for line in lines if "rank" in line]
838
839
840 def test_each_item_gives_its_top_two_comments_and_nothing_below():
841 report = _report([_candidate(_thread("reddit", 1, [900, 800, 700, 600], container="sub"))])
842 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
843 assert _pool_authors(entries) == ["reddit1rank1", "reddit1rank2"]
844 assert entries[0].endswith(" — cluster 1 — top comment")
845 assert entries[1].endswith(" — cluster 1 — #2 comment")
846 assert entries[0].split(" — ")[0].endswith("🟠 u/reddit1rank1 on r/sub · 900 upvotes")
847
848
849 def test_pool_runs_every_top_comment_in_story_order_then_every_second_never_by_likes():
850 quiet = _candidate(_thread("tiktok", 1, [1200, 40]))
851 loud = _candidate(_thread("reddit", 2, [20000, 19000, 18000, 17000, 16000], container="sub"))
852 video = _candidate(_thread("youtube", 3, [7, 3]))
853 report = _report([quiet, loud, video])
854 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
855 assert _pool_authors(entries) == [
856 "tiktok1rank1", "reddit2rank1", "youtube3rank1",
857 "tiktok1rank2", "reddit2rank2", "youtube3rank2",
858 ]
859 assert [line.rsplit(" — ", 1)[1] for line in entries] == ["top comment"] * 3 + ["#2 comment"] * 3
860 assert [re.search(r"cluster (\d)", line).group(1) for line in entries] == ["1", "2", "3", "1", "2", "3"]
861
862
863 def test_items_follow_their_clusters_rank_not_the_candidate_list():
864 first = _candidate(_thread("reddit", 1, [5, 4], container="sub"))
865 second = _candidate(_thread("youtube", 2, [50000, 40000]))
866 # Ranked candidates list the second story's item first; the clusters do not.
867 report = _report([second, first], clusters=[_cluster(1, [first]), _cluster(2, [second])])
868 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
869 assert _pool_authors(entries) == ["reddit1rank1", "youtube2rank1", "reddit1rank2", "youtube2rank2"]
870
871
872 def test_position_is_the_items_own_stored_order_not_a_resort_by_votes():
873 """YouTube and Hacker News store the platform's order, which is not by count."""
874 video = _candidate(_thread("youtube", 1, [12, 900, 5000]))
875 other = _candidate(_thread("reddit", 2, [30, 20], container="sub"))
876 entries = _entries(_section(render.render_compact(_report([video, other])), "## Top Community Comments"))
877 assert _pool_authors(entries) == ["youtube1rank1", "reddit2rank1", "youtube1rank2", "reddit2rank2"]
878
879
880 def test_posts_follow_the_top_comments_of_their_cluster_and_are_labelled_post():
881 thread = _candidate(_thread("reddit", 1, [300, 200], container="sub"))
882 post = _candidate(_item("x", "fan1", title="Kanye sold out AT&T Stadium in nine minutes",
883 url="https://x.com/PopBase/status/77", author="PopBase",
884 engagement={"likes": 48213}))
885 video = _candidate(_thread("youtube", 2, [90, 80]))
886 report = _report(
887 [post, thread, video],
888 clusters=[_cluster(1, [post, thread]), _cluster(2, [video])],
889 )
890 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
891 assert [line.rsplit(" — ", 1)[1] for line in entries] == [
892 "top comment", "post", "top comment", "#2 comment", "#2 comment",
893 ]
894 assert "u/reddit1rank1" in entries[0]
895 assert entries[1].endswith("🔵 @PopBase on X · 48,213 likes — https://x.com/PopBase/status/77 — cluster 1 — post")
896 assert "youtube2rank1" in entries[2]
897
898
899 def test_pool_covers_shown_clusters_before_other_items_within_the_cap():
900 shown = [_candidate(_thread("reddit", index, [30, 20], container="sub")) for index in range(1, 9)]
901 others = [_candidate(_thread("tiktok", index, [90000, 80000])) for index in range(9, 49)]
902 clusters = [_cluster(index, [candidate]) for index, candidate in enumerate([*shown, *others], start=1)]
903 report = _report([*shown, *others], clusters=clusters)
904 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
905 assert len(entries) == render.QUOTE_POOL_LIMIT == 40
906 authors = _pool_authors(entries)
907 # All sixteen comments of the eight shown stories are in, top and second.
908 # The other 24 places go to other items' top comments, in ranked order.
909 assert authors[:8] == [f"reddit{index}rank1" for index in range(1, 9)]
910 assert authors[8:32] == [f"tiktok{index}rank1" for index in range(9, 33)]
911 assert authors[32:] == [f"reddit{index}rank2" for index in range(1, 9)]
912 assert all(' — re: "Kanye West tiktok item' in line for line in entries[8:32])
913
914
915 @pytest.mark.parametrize(
916 "source", ["instagram", "tiktok", "youtube", "reddit", "threads", "bluesky", "linkedin", "x"]
917 )
918 def test_item_whose_top_comment_has_no_vote_gives_the_pool_nothing(source):
919 spam = _candidate(_thread(source, 1, [0, 5]))
920 unscored = _candidate(_thread(source, 2, [None, 5]))
921 partly = _candidate(_thread(source, 3, [6, 0]))
922 report = _report([*_two_comment_candidates(), spam, unscored, partly])
923 authors = _pool_authors(_entries(_section(render.render_compact(report), "## Top Community Comments")))
924 assert authors == [f"{source}3rank1"]
925
926
927 def test_hacker_news_gives_its_first_two_comments_by_thread_position():
928 story = _candidate(_thread("hackernews", 1, [None, 0, 400]))
929 report = _report([*_two_comment_candidates(), story])
930 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
931 assert _pool_authors(entries) == ["hackernews1rank1", "hackernews1rank2"]
932 (first,) = [line for line in entries if "hackernews1rank1" in line]
933 assert '" 🟡 hackernews1rank1 on Hacker News — ' in first
934
935
936 def test_unquotable_top_comment_gives_its_position_to_the_next():
937 thread = _thread("reddit", 1, [900, 800], container="sub")
938 thread.metadata["top_comments"][0]["excerpt"] = "😂😂😂😂😂😂😂😂😂😂😂😂"
939 report = _report([*_two_comment_candidates(), _candidate(thread)])
940 (entry,) = [
941 line for line in _entries(_section(render.render_compact(report), "## Top Community Comments"))
942 if "reddit1rank" in line
943 ]
944 assert "reddit1rank2" in entry and entry.endswith(" — top comment")
945
946
947 def test_duplicate_text_does_not_hide_the_copy_that_is_eligible():
948 """The first copy met is rejected (nobody voted for it); the later one stays."""
949 rejected = _thread("instagram", 1, [0, 0])
950 kept = _thread("reddit", 2, [500, 40], container="sub")
951 for item in (rejected, kept):
952 item.metadata["top_comments"][0]["excerpt"] = "He really said the quiet part out loud."
953 report = _report([*_two_comment_candidates(), _candidate(rejected), _candidate(kept)])
954 section = _section(render.render_compact(report), "## Top Community Comments")
955 assert section.count("He really said the quiet part out loud.") == 1
956 assert '"He really said the quiet part out loud." 🟠 u/reddit2rank1 on r/sub · 500 upvotes' in section
957
958
959 def test_checklist_and_rule_rank_by_position_not_likes(monkeypatch):
960 block = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=False))
961 assert "each thread's or video's top comment first, then its #2" in block
962 assert "like counts do not rank a comment from one place against another" in block
963 assert "a ceiling, not a target" in block
964 assert "highest-voted" not in block
965
966
967 def test_funny_candidates_lead_their_storys_position_and_are_tagged():
968 """The fun score belongs to the candidate, so its comments share the tag."""
969 plain = _candidate(_thread("reddit", 1, [900, 800], container="sub"))
970 funny = _candidate(_thread("youtube", 2, [40, 30]))
971 funny.fun_score = render._QUOTE_POOL_FUNNY_FLOOR
972 nearly = _candidate(_thread("tiktok", 3, [70, 60]))
973 nearly.fun_score = render._BEST_TAKE_FUNNY_FLOOR - 1
974 later = _candidate(_thread("instagram", 4, [9, 8]))
975 later.fun_score = 95.0
976 report = _report(
977 [plain, funny, nearly, later],
978 clusters=[_cluster(1, [plain, funny, nearly]), _cluster(2, [later])],
979 )
980 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
981 # Position still leads, and a funny entry never jumps to another story.
982 assert _pool_authors(entries) == [
983 "youtube2rank1", "reddit1rank1", "tiktok3rank1", "instagram4rank1",
984 "youtube2rank2", "reddit1rank2", "tiktok3rank2", "instagram4rank2",
985 ]
986 assert entries[0].endswith(" — cluster 1 — top comment — funny")
987 assert entries[4].endswith(" — cluster 1 — #2 comment — funny")
988 assert entries[3].endswith(" — cluster 2 — top comment — funny")
989 assert [line.endswith(" — funny") for line in entries] == [
990 True, False, False, True, True, False, False, True,
991 ]
992 assert entries[0].split(" — ")[0].endswith("🔴 @youtube2rank1 on YouTube · 40 likes")
993
994
995 def test_busy_story_does_not_use_the_slots_of_the_stories_after_it():
996 busy = [_candidate(_thread("reddit", index, [50, 40], container="sub")) for index in range(1, 46)]
997 second = _candidate(_thread("youtube", 60, [9, 8]))
998 third = _candidate(_thread("tiktok", 70, [7, 6]))
999 post = _candidate(_item("x", "fan70", title="A fan post about the third story tonight",
1000 url="https://x.com/fan/status/70", author="fan", engagement={"likes": 25}))
1001 clusters = [_cluster(1, busy), _cluster(2, [second]), _cluster(3, [third, post])]
1002 report = _report([*busy, second, third, post], clusters=clusters)
1003
1004 entries = _entries(_section(render.render_compact(report), "## Top Community Comments"))
1005
1006 assert len(entries) == render.QUOTE_POOL_LIMIT
1007 authors = _pool_authors(entries)
1008 assert "youtube60rank1" in authors and "tiktok70rank1" in authors
1009 # The busy story fills what is left after every story has its top comment,
1010 # in its own order, and the pool still prints story by story.
1011 assert authors[:38] == [f"reddit{index}rank1" for index in range(1, 39)]
1012 assert authors[38:] == ["youtube60rank1", "tiktok70rank1"]
1013 assert all(line.endswith(" — top comment") for line in entries)
1014
1015
1016 def test_each_shown_story_gets_one_slot_before_any_gets_two():
1017 stories = [
1018 [_candidate(_thread("reddit", 10 * story + index, [50, 40], container="sub")) for index in range(3)]
1019 for story in range(1, 4)
1020 ]
1021 clusters = [_cluster(number, members) for number, members in enumerate(stories, start=1)]
1022 report = _report([cand for members in stories for cand in members], clusters=clusters)
1023
1024 three = render._render_top_comments(report, limit=3, clusters=clusters)
1025 assert _pool_authors(three[2:]) == ["reddit10rank1", "reddit20rank1", "reddit30rank1"]
1026
1027 five = render._render_top_comments(report, limit=5, clusters=clusters)
1028 assert _pool_authors(five[2:]) == [
1029 "reddit10rank1", "reddit11rank1", "reddit20rank1", "reddit21rank1", "reddit30rank1",
1030 ]
1031
1032
1033 def test_second_comments_are_shared_round_by_round_once_top_comments_are_in():
1034 stories = [
1035 [_candidate(_thread("reddit", 10 * story + index, [50, 40], container="sub")) for index in range(2)]
1036 for story in range(1, 4)
1037 ]
1038 clusters = [_cluster(number, members) for number, members in enumerate(stories, start=1)]
1039 report = _report([cand for members in stories for cand in members], clusters=clusters)
1040 lines = render._render_top_comments(report, limit=9, clusters=clusters)
1041 authors = _pool_authors(lines[2:])
1042 assert authors[:6] == [f"reddit{n}rank1" for n in (10, 11, 20, 21, 30, 31)]
1043 # Three slots left for six second comments: one for each story.
1044 assert authors[6:] == ["reddit10rank2", "reddit20rank2", "reddit30rank2"]
1045
1046
1047 # --- round 5: what is not a community comment, and the item bar --------------
1048
1049
1050 def _comments_item(source, index, comments, *, author=None, container=None):
1051 return _item(
1052 source, f"{source}{index}", title=f"Kanye West {source} item {index}",
1053 url=f"https://example.com/{source}/{index}", author=author, container=container,
1054 metadata={"top_comments": comments},
1055 )
1056
1057
1058 def _pool(report):
1059 text = render.render_compact(report)
1060 if "\n## Top Community Comments\n" not in text:
1061 return []
1062 return _entries(_section(text, "## Top Community Comments"))
1063
1064
1065 def test_github_comment_needs_a_reaction_like_any_vote_counting_platform():
1066 issue = _comments_item("github", 1, [
1067 {"author": "Asif2BD", "score": 0, "excerpt": "This breaks on every install since Tuesday."},
1068 {"author": "helper", "score": 9, "excerpt": "Pinning the old version works around it."},
1069 ])
1070 entries = _pool(_report([*_two_comment_candidates(), _candidate(issue)]))
1071 assert not [line for line in entries if "GitHub" in line]
1072
1073
1074 @pytest.mark.parametrize(("author", "text"), [
1075 ("Asif2BD", "<!-- proskills:review v1 psk-id=abc --> **ProSkills automated review** (deterministic, no AI)."),
1076 ("Asif2BD", "<!- - proskills:review v1 - -> A review body that looks like a comment."),
1077 ("someone", "ProSkills Automated Review: three findings in this pull request."),
1078 ("dependabot[bot]", "Bumps the minor group with four updates to the lockfile."),
1079 ("github-actions", "Coverage went down by two percent on this branch."),
1080 ("AutoModerator", "Welcome to the sub! Please read the rules before posting."),
1081 ("review-bot", "Looks good to me, merging when the checks pass."),
1082 ("friendly", "I am a bot, and this action was performed automatically."),
1083 ])
1084 @pytest.mark.parametrize("source", ["github", "reddit", "youtube", "hackernews"])
1085 def test_bot_and_markup_comments_are_never_quoted(source, author, text):
1086 item = _comments_item(source, 1, [
1087 {"author": author, "score": 900, "excerpt": text},
1088 {"author": "person", "score": 40, "excerpt": "A real person's reaction to the thing."},
1089 ])
1090 entries = _pool(_report([*_two_comment_candidates(), _candidate(item)]))
1091 assert not [line for line in entries if author in line or text[:20] in line]
1092 # The next comment takes the position the bot comment held.
1093 (person,) = [line for line in entries if "person" in line]
1094 assert person.endswith(" — top comment")
1095
1096
1097 def test_usernames_that_only_contain_bot_are_people():
1098 item = _comments_item("reddit", 1, [
1099 {"author": "Talbot_Abbott", "score": 900, "excerpt": "Robots are not what this thread is about."},
1100 ], container="sub")
1101 entries = _pool(_report([*_two_comment_candidates(), _candidate(item)]))
1102 assert [line for line in entries if "u/Talbot_Abbott" in line]
1103
1104
1105 @pytest.mark.parametrize(("source", "item_author", "comment_author"), [
1106 ("youtube", "Engineering Explained", "@EngineeringExplained"),
1107 ("tiktok", "yeniuswest", "@YeniusWest"),
1108 ("instagram", "@iamkevinwong", "iamkevinwong"),
1109 ("reddit", "thread_op", "u/Thread_OP"),
1110 ("hackernews", "submitter", "Submitter"),
1111 ])
1112 def test_the_items_own_author_is_skipped_and_the_next_comment_takes_the_position(
1113 source, item_author, comment_author,
1114 ):
1115 item = _comments_item(source, 1, [
1116 {"author": comment_author, "score": 683, "excerpt": "Addressing technical questions from the video!"},
1117 {"author": "viewer1", "score": 120, "excerpt": "The best community reaction here."},
1118 {"author": "viewer2", "score": 60, "excerpt": "The second community reaction here."},
1119 {"author": "viewer3", "score": 30, "excerpt": "The third community reaction here."},
1120 ], author=item_author)
1121 entries = _pool(_report([_candidate(item)]))
1122 assert ["viewer1" in entries[0], "viewer2" in entries[1], len(entries)] == [True, True, 2]
1123 assert entries[0].endswith(" — top comment") and entries[1].endswith(" — #2 comment")
1124 assert "Addressing technical questions" not in "\n".join(entries)
1125
1126
1127 @pytest.mark.parametrize(
1128 "source", ["reddit", "youtube", "tiktok", "instagram", "github", "threads", "bluesky", "linkedin", "x"]
1129 )
1130 def test_item_joins_the_pool_only_when_its_top_community_comment_has_five_votes(source):
1131 small = _comments_item(source, 1, [
1132 {"author": "lol", "score": 1, "excerpt": "$500,000,000.00 on midterms LOL"},
1133 {"author": "also", "score": 1, "excerpt": "Another remark on the small thread."},
1134 ])
1135 four = _comments_item(source, 2, [{"author": "four", "score": 4, "excerpt": "Four people liked this remark."}])
1136 five = _comments_item(source, 3, [
1137 {"author": "five", "score": 5, "excerpt": "Five people liked this remark."},
1138 {"author": "one", "score": 1, "excerpt": "One person liked this second remark."},
1139 ])
1140 entries = _pool(_report([*_two_comment_candidates(), _candidate(small), _candidate(four), _candidate(five)]))
1141 joined = "\n".join(entries)
1142 assert "midterms" not in joined and "Another remark" not in joined and "Four people" not in joined
1143 # Past the bar, the item's #2 still needs only one vote.
1144 assert "Five people liked this remark." in joined and "One person liked this second remark." in joined
1145
1146
1147 def test_item_bar_does_not_apply_to_hacker_news():
1148 story = _comments_item("hackernews", 1, [
1149 {"author": "alice", "score": None, "excerpt": "The checkout flow is one page now."},
1150 {"author": "bob", "score": 0, "excerpt": "A measured zero is still shown here."},
1151 ])
1152 joined = "\n".join(_pool(_report([*_two_comment_candidates(), _candidate(story)])))
1153 assert "alice on Hacker News" in joined and "bob on Hacker News" in joined
1154
1155
1156 def test_markdown_emphasis_is_stripped_from_quote_text():
1157 item = _comments_item("youtube", 1, [
1158 {"author": "viewer", "score": 683,
1159 "excerpt": "*Addressing technical questions!* It is **really** __not__ a _torque_ thing, ~~sorry~~ ok. snake_case and 2 * 3 stay."},
1160 ])
1161 own = _own_post(1, 50, text="This is **the** best *show* yet")
1162 text = render.render_compact(_report([*_two_comment_candidates(), _candidate(item)], extra_items=[own]))
1163 assert (
1164 '- "Addressing technical questions! It is really not a torque thing, sorry ok. '
1165 'snake_case and 2 * 3 stay." 🔴 @viewer on YouTube · 683 likes'
1166 ) in _section(text, "## Top Community Comments")
1167 assert '- "This is the best show yet" 🔵 @kanyewest' in _section(text, "## Posts by @kanyewest")
1168
1169
1170 @pytest.mark.parametrize("marker", [">", "&gt;", "\\>", "> ", " >"])
1171 def test_quoted_parent_lines_are_dropped_and_the_commenters_words_kept(marker):
1172 item = _comments_item("reddit", 1, [
1173 {"author": "replier", "score": 300,
1174 "excerpt": f"{marker}Cybercab costs 20,000\n\nTesla does not have a US$20,000 car.\n{marker}second quoted line\nNot even close."},
1175 ], container="sub")
1176 (entry,) = [line for line in _pool(_report([*_two_comment_candidates(), _candidate(item)])) if "replier" in line]
1177 assert entry.startswith('- "Tesla does not have a US$20,000 car. Not even close." 🟠 u/replier on r/sub · 300 upvotes')
1178
1179
1180 def test_comment_that_only_quotes_its_parent_is_skipped_and_the_next_takes_its_position():
1181 item = _comments_item("reddit", 1, [
1182 {"author": "echo", "score": 900, "excerpt": "> Cybercab costs 20,000 and nothing else is said"},
1183 {"author": "emoji", "score": 800, "excerpt": "😂😂😂😂😂😂😂😂😂😂😂😂"},
1184 {"author": "person", "score": 700, "excerpt": "Tesla does not have a car at that price."},
1185 {"author": "fourth", "score": 600, "excerpt": "A second remark in the commenter's own words."},
1186 {"author": "fifth", "score": 500, "excerpt": "A third remark that stays out of the pool."},
1187 ], container="sub")
1188 entries = [line for line in _pool(_report([_candidate(item)]))]
1189 assert [re.search(r"u/(\w+)", line).group(1) for line in entries] == ["person", "fourth"]
1190 assert entries[0].endswith(" — top comment") and entries[1].endswith(" — #2 comment")
1191
1192
1193 # --- odds lines: the checklist names them only when the block is printed -----
1194
1195 ODDS_FACT = (
1196 "Polymarket odds for a story go on their own line under it: copy the whole odds "
1197 "line from `## Polymarket Markets`, up to the ` — ` before its URL (at most three "
1198 "in the report); "
1199 "the paragraph links the market and does not repeat the numbers."
1200 )
1201
1202
1203 def _report_with_market():
1204 report = _mixed_pool_report()
1205 report.items_by_source["polymarket"] = [
1206 _market(1, title="Will Kanye West tour in 2027?", outcomes=[("Yes", 0.5), ("No", 0.5)]),
1207 ]
1208 return report
1209
1210
1211 def test_checklist_has_the_odds_line_fact_only_when_the_block_is_printed(monkeypatch):
1212 with_block = _stdout(_report_with_market(), monkeypatch, claude_code=False)
1213 assert "\n## Polymarket Markets\n" in with_block
1214 assert ODDS_FACT in _checklist(with_block)
1215 assert "📊 Polymarket · " in _checklist(with_block)
1216 without = _checklist(_stdout(_mixed_pool_report(), monkeypatch, claude_code=False))
1217 assert "Polymarket" not in without
1218
1219
1220 def test_exec_recommendation_and_comparison_checklists_have_no_odds_line_fact(monkeypatch):
1221 report = _report_with_market()
1222 assert "Polymarket odds" not in _checklist(_stdout(report, monkeypatch, claude_code=False, register="exec"))
1223 assert "Polymarket odds" not in _checklist(_stdout(
1224 report, monkeypatch, claude_code=False,
1225 entity_reports=[("Kanye West", report), ("Drake", report)],
1226 ))
1227 picks = _report_with_market()
1228 picks.topic = picks.query_plan.raw_topic = "best Kanye West albums"
1229 assert "Polymarket odds" not in _checklist(_stdout(picks, monkeypatch, claude_code=False))
1230
1230 lines PYTHON