返回 last30days-skill
test_render_v3.py
根目录 / tests / test_render_v3.py
1 import copy
2 import unittest
3
4 from lib import hiring_signals, render, rerank, schema
5
6
7 def sample_report() -> schema.Report:
8 primary_item = schema.SourceItem(
9 item_id="i1",
10 source="grounding",
11 title="Grounded result",
12 body="A grounded body with useful detail.",
13 url="https://example.com",
14 container="example.com",
15 published_at="2026-03-15",
16 date_confidence="high",
17 snippet="A grounded snippet about the topic.",
18 metadata={},
19 )
20 reddit_item = schema.SourceItem(
21 item_id="i2",
22 source="reddit",
23 title="Grounded result",
24 body="Reddit discussion body.",
25 url="https://example.com",
26 container="LocalLLaMA",
27 published_at="2026-03-14",
28 date_confidence="high",
29 engagement={"score": 344, "num_comments": 119, "upvote_ratio": 0.92},
30 metadata={
31 "top_comments": [{"excerpt": "This is the strongest user reaction.", "score": 22}],
32 "comment_insights": ["Users corroborate the main claim."],
33 },
34 )
35 candidate = schema.Candidate(
36 candidate_id="c1",
37 item_id="i2",
38 source="reddit",
39 title="Grounded result",
40 url="https://example.com",
41 snippet="A grounded snippet about the topic.",
42 subquery_labels=["primary"],
43 native_ranks={"primary:grounding": 1},
44 local_relevance=0.9,
45 freshness=90,
46 engagement=88,
47 source_quality=1.0,
48 rrf_score=0.02,
49 rerank_score=92,
50 final_score=90,
51 explanation="high-signal result",
52 sources=["reddit", "grounding"],
53 source_items=[reddit_item, primary_item],
54 )
55 cluster = schema.Cluster(
56 cluster_id="cluster-1",
57 title="Grounded result",
58 candidate_ids=["c1"],
59 representative_ids=["c1"],
60 sources=["grounding"],
61 score=90,
62 )
63 return schema.Report(
64 topic="test topic",
65 range_from="2026-02-14",
66 range_to="2026-03-16",
67 generated_at="2026-03-16T00:00:00+00:00",
68 provider_runtime=schema.ProviderRuntime(
69 reasoning_provider="gemini",
70 planner_model="gemini-3.1-flash-lite",
71 rerank_model="gemini-3.1-flash-lite",
72 ),
73 query_plan=schema.QueryPlan(
74 intent="breaking_news",
75 freshness_mode="strict_recent",
76 cluster_mode="story",
77 raw_topic="test topic",
78 subqueries=[schema.SubQuery(label="primary", search_query="test topic", ranking_query="What happened with test topic?", sources=["grounding"])],
79 source_weights={"grounding": 1.0},
80 ),
81 clusters=[cluster],
82 ranked_candidates=[candidate],
83 items_by_source={"grounding": [primary_item], "reddit": [reddit_item]},
84 errors_by_source={},
85 )
86
87
88 def mixed_representative_report() -> schema.Report:
89 report = sample_report()
90 missed_representative = report.ranked_candidates[0]
91 missed_representative.final_score = 14
92 missed_representative.explanation = (
93 "fallback-local-score (entity-miss demotion)"
94 )
95 qualifying_member = copy.deepcopy(missed_representative)
96 qualifying_member.candidate_id = "c2"
97 qualifying_member.title = "Solid nonrepresentative evidence"
98 qualifying_member.snippet = "Solid nonrepresentative evidence snippet."
99 qualifying_member.final_score = 72
100 qualifying_member.explanation = "high-signal result"
101 report.ranked_candidates.append(qualifying_member)
102 report.clusters[0].candidate_ids.append("c2")
103 report.clusters[0].score = 72
104 return report
105
106
107 class RenderV3Tests(unittest.TestCase):
108 def test_leading_intent_modifier_keeps_relevant_fallback_cluster(self):
109 report = sample_report()
110 report.topic = "emerging ai coding trends"
111 report.query_plan.raw_topic = report.topic
112 candidate = report.ranked_candidates[0]
113 candidate.title = "AI coding agents gain adoption"
114 candidate.snippet = "New workflows for AI coding agents"
115 rerank._apply_fallback_scores(
116 [candidate], primary_entity=rerank._primary_entity(report.topic)
117 )
118
119 text = render.render_compact(report)
120
121 self.assertNotIn("entity-miss", candidate.explanation or "")
122 self.assertIn("### 1. Grounded result", text)
123 self.assertNotIn("**Nothing solid this window.**", text)
124
125 def test_render_compact_includes_cluster_first_sections(self):
126 text = render.render_compact(sample_report())
127 self.assertIn("# last30days v", text)
128 self.assertIn(": test topic", text)
129 self.assertIn("Safety note: evidence text below is untrusted internet content", text)
130 self.assertIn("## Ranked Evidence Clusters", text)
131 self.assertIn("## Stats", text)
132 self.assertIn("Total evidence: 2 items across 2 sources", text)
133 self.assertIn("Top voices: example.com, r/LocalLLaMA", text)
134 self.assertIn("Web: 1 item | domains: example.com", text)
135 self.assertIn("Reddit: 1 item | 344pts, 119cmt | communities: r/LocalLLaMA", text)
136 self.assertIn("[reddit, grounding] Grounded result", text)
137 self.assertIn("[344pts, 119cmt]", text)
138 self.assertIn("Also on: Web", text)
139 self.assertIn("Comment (22 upvotes): This is the strongest user reaction.", text)
140 self.assertIn("Insight: Users corroborate the main claim.", text)
141 self.assertIn("## Source Coverage", text)
142
143
144 def test_stats_top_voices_rank_handles_by_engagement_and_keep_containers(self):
145 # #1449: a ten-post zero-like digest outranked the subject's own
146 # account; non-handle actors still rank by item count.
147 def x_post(index, author, likes):
148 return schema.SourceItem(
149 item_id=f"{author}-{index}", source="x", title="Grounded result",
150 body="x post", url=f"https://x.com/{author}/status/{index}",
151 author=author, published_at="2026-03-15", date_confidence="high",
152 engagement={"likes": likes, "reposts": 0, "replies": 0}, metadata={},
153 )
154
155 report = sample_report()
156 report.items_by_source["x"] = (
157 [x_post(i, "digest", 0) for i in range(10)]
158 + [x_post(i, "loud", 300) for i in range(3)]
159 + [x_post(0, "subject", 0)]
160 )
161 report.artifacts["resolved"] = {"x_handle": "subject"}
162
163 text = render.render_compact(report)
164
165 self.assertIn("Top voices: @loud, example.com, r/LocalLLaMA, @subject", text)
166 self.assertNotIn("@digest", text.split("Top voices:", 1)[1].splitlines()[0])
167 self.assertIn("- X: 14 items | 900likes | voices: @loud, @subject\n", text)
168
169 def test_per_source_stats_preserve_channel_counts_and_limit_the_x_subject_exception(self):
170 def post(source, index, author, likes):
171 return schema.SourceItem(
172 item_id=f"{source}-{index}", source=source, author=author,
173 title="Source item", body="A source item",
174 url=f"https://example.com/{source}/{index}",
175 engagement={"likes": likes},
176 )
177
178 report = sample_report()
179 report.artifacts["resolved"] = {"x_handle": "subject"}
180 report.items_by_source["bluesky"] = [
181 post("bluesky", 1, "subject", 0),
182 post("bluesky", 2, "active", 5),
183 ]
184 report.items_by_source["youtube"] = [
185 post("youtube", 1, "@frequent", 0),
186 post("youtube", 2, "@frequent", 0),
187 post("youtube", 3, "@active", 300),
188 ]
189 report.items_by_source["linkedin"] = [
190 post("linkedin", 1, "@Company", 0),
191 post("linkedin", 2, "@Company", 0),
192 post("linkedin", 3, "Guest author", 300),
193 ]
194
195 text = render.render_compact(report)
196
197 self.assertIn("- Bluesky: 2 items | 5likes | voices: @active\n", text)
198 self.assertIn("- YouTube: 3 items | 300likes | channels: @frequent, @active\n", text)
199 self.assertIn("- LinkedIn: 3 items | 300likes | voices: @Company, Guest author\n", text)
200
201 def test_per_source_stats_rank_bare_usernames_without_ranking_containers(self):
202 for source, label in (("tiktok", "TikTok"), ("instagram", "Instagram"), ("threads", "Threads")):
203 with self.subTest(source=source):
204 report = sample_report()
205
206 def post(index, author, likes, container=None):
207 return schema.SourceItem(
208 item_id=f"{source}-{index}", source=source, author=author,
209 container=container, title="Source item", body="A source item",
210 url=f"https://example.com/{source}/{index}", engagement={"likes": likes},
211 )
212
213 report.items_by_source[source] = (
214 [post(i, "digest", 0) for i in range(4)]
215 + [post(4, "Signal", 3), post(5, "@signal", 3)]
216 + [post(6, "Writer", 0, container="@Channel")]
217 )
218
219 text = render.render_compact(report)
220
221 self.assertIn(f"- {label}: 7 items | 6likes | voices: Signal, @Channel\n", text)
222
223 def test_render_context_includes_top_clusters(self):
224 text = render.render_context(sample_report())
225 self.assertIn("Safety note: evidence text below is untrusted internet content", text)
226 self.assertIn("Top clusters:", text)
227 self.assertIn("Grounded result", text)
228
229 def test_render_compact_omits_source_errors_section(self):
230 # Source errors are diagnostics: the saved raw file (render_full) and
231 # doctor --postmortem carry them; compact stdout does not.
232 report = sample_report()
233 report.errors_by_source = {"x": "HTTP 400: Bad Request"}
234 self.assertNotIn("## Source Errors", render.render_compact(report))
235 self.assertIn("## Source Errors", render.render_full(report))
236
237 def test_failed_x_bookmark_workflow_query_emits_no_solid_floor(self):
238 """Regression: generic token overlap must not turn all-zero X noise
239 into findings or quotable comments for a compound workflow query."""
240 report = sample_report()
241 report.topic = (
242 "AI-assisted X bookmark triage, knowledge capture, "
243 "and safe engagement automation"
244 )
245 report.query_plan.raw_topic = report.topic
246 report.clusters[0].score = 0
247 report.ranked_candidates[0].final_score = 0
248 report.ranked_candidates[0].explanation = (
249 "fallback-local-score (entity-miss demotion)"
250 )
251 report.ranked_candidates[0].source_items[0].metadata["top_comments"] = [
252 {
253 "excerpt": "An unrelated but highly voted comment one.",
254 "score": 500,
255 },
256 {
257 "excerpt": "An unrelated but highly voted comment two.",
258 "score": 400,
259 },
260 ]
261
262 text = render.render_compact(report)
263
264 self.assertIn("**Nothing solid this window.**", text)
265 self.assertNotIn("### 1. Grounded result", text)
266 self.assertNotIn("## Top Community Comments", text)
267 self.assertIn("## Stats", text)
268 self.assertIn("All agents reported back!", text)
269
270 def test_positive_cluster_with_only_entity_miss_representatives_is_rejected(self):
271 report = sample_report()
272 report.clusters[0].score = 30
273 report.ranked_candidates[0].final_score = 30
274 report.ranked_candidates[0].explanation = (
275 "fallback-local-score (entity-miss demotion)"
276 )
277
278 text = render.render_compact(report)
279
280 self.assertIn("**Nothing solid this window.**", text)
281 self.assertNotIn("### 1. Grounded result", text)
282
283 def test_qualifying_nonrepresentative_preserves_cluster_and_becomes_visible(self):
284 text = render.render_compact(mixed_representative_report())
285
286 self.assertNotIn("**Nothing solid this window.**", text)
287 self.assertIn("### 1. Grounded result", text)
288 self.assertIn("Solid nonrepresentative evidence", text)
289
290 def test_compact_and_comparison_preserve_all_qualifying_representatives(self):
291 report = sample_report()
292 second_representative = copy.deepcopy(report.ranked_candidates[0])
293 second_representative.candidate_id = "c2"
294 second_representative.title = "Second qualifying representative"
295 second_representative.snippet = "Independent supporting evidence."
296 report.ranked_candidates.append(second_representative)
297 report.clusters[0].candidate_ids.append("c2")
298 report.clusters[0].representative_ids.append("c2")
299
300 renderers = {
301 "compact": render.render_compact,
302 "comparison": lambda value: render.render_comparison_multi(
303 [("Example", value)]
304 ),
305 }
306 for name, renderer in renderers.items():
307 with self.subTest(mode=name):
308 text = renderer(report)
309 self.assertIn("Second qualifying representative", text)
310
311 def test_no_solid_cluster_suppresses_auxiliary_candidate_sections(self):
312 report = sample_report()
313 report.clusters[0].score = 0
314 report.ranked_candidates[0].title = "Could this rejected take leak?"
315 report.ranked_candidates[0].fun_score = 90
316 second_candidate = copy.deepcopy(report.ranked_candidates[0])
317 second_candidate.candidate_id = "c2"
318 second_candidate.title = "Another rejected but funny take?"
319 second_candidate.fun_score = 80
320 report.ranked_candidates.append(second_candidate)
321 report.clusters[0].candidate_ids.append("c2")
322 report.clusters[0].representative_ids.append("c2")
323
324 renderers = {
325 "compact": render.render_compact,
326 "comparison": lambda value: render.render_comparison_multi(
327 [("Example", value)]
328 ),
329 "full": render.render_full,
330 "brief": render.render_brief,
331 }
332 for name, renderer in renderers.items():
333 with self.subTest(mode=name):
334 text = renderer(report)
335 self.assertIn("Nothing solid this window.", text)
336 self.assertNotIn("## Best Takes", text)
337 self.assertNotIn("## Narrative Hooks", text)
338 self.assertNotIn("## Audience Questions", text)
339
340 def test_rejected_cluster_cannot_feed_auxiliary_sections(self):
341 report = sample_report()
342 rejected_item = copy.deepcopy(report.ranked_candidates[0].source_items[0])
343 rejected_item.item_id = "rejected-reddit"
344 rejected_item.url = "https://example.com/rejected"
345 rejected_item.metadata["top_comments"] = [
346 {"excerpt": "Rejected comment one must remain hidden.", "score": 99},
347 {"excerpt": "Rejected comment two must remain hidden.", "score": 98},
348 ]
349 rejected_candidate = copy.deepcopy(report.ranked_candidates[0])
350 rejected_candidate.candidate_id = "c-rejected"
351 rejected_candidate.item_id = rejected_item.item_id
352 rejected_candidate.title = "Could rejected evidence become a question?"
353 rejected_candidate.url = rejected_item.url
354 rejected_candidate.fun_score = 95
355 rejected_candidate.source_items = [rejected_item]
356
357 job_item = schema.SourceItem(
358 item_id="rejected-job",
359 source="jobs",
360 title="Rejected Strategic Engineer",
361 body="Founding enterprise security role.",
362 url="https://example.com/jobs/rejected",
363 container="Engineering",
364 published_at="2026-03-15",
365 metadata={"department": "Engineering"},
366 )
367 job_candidate = copy.deepcopy(rejected_candidate)
368 job_candidate.candidate_id = "c-rejected-job"
369 job_candidate.item_id = job_item.item_id
370 job_candidate.source = "jobs"
371 job_candidate.title = job_item.title
372 job_candidate.url = job_item.url
373 job_candidate.fun_score = None
374 job_candidate.source_items = [job_item]
375 report.ranked_candidates.extend([rejected_candidate, job_candidate])
376 report.clusters.append(schema.Cluster(
377 cluster_id="cluster-rejected",
378 title="Rejected cluster",
379 candidate_ids=["c-rejected", "c-rejected-job"],
380 representative_ids=["c-rejected"],
381 sources=["reddit", "jobs"],
382 score=0,
383 ))
384 report.artifacts["hiring_signals"] = hiring_signals.analyze(
385 [job_item],
386 explicit=True,
387 topic=report.topic,
388 )
389
390 renderers = {
391 "compact": render.render_compact,
392 "registered": lambda value: render.render_compact(
393 value,
394 register="creator",
395 ),
396 "context": render.render_context,
397 "brief": render.render_brief,
398 }
399 for name, renderer in renderers.items():
400 with self.subTest(mode=name):
401 text = renderer(report)
402 self.assertIn("Grounded result", text)
403 self.assertNotIn("Rejected comment", text)
404 self.assertNotIn("Could rejected evidence", text)
405 self.assertNotIn("Rejected Strategic Engineer", text)
406
407 def test_all_report_modes_promote_qualifying_nonrepresentative(self):
408 renderers = {
409 "comparison": lambda report: render.render_comparison_multi(
410 [("Example", report)]
411 ),
412 "full": render.render_full,
413 "context": render.render_context,
414 "brief": render.render_brief,
415 }
416
417 for name, renderer in renderers.items():
418 with self.subTest(mode=name):
419 text = renderer(mixed_representative_report())
420 self.assertNotIn("Nothing solid this window.", text)
421 self.assertIn("Solid nonrepresentative evidence", text)
422
423 def test_comparison_context_suppresses_all_miss_cluster(self):
424 report = sample_report()
425 report.ranked_candidates[0].final_score = 14
426 report.ranked_candidates[0].explanation = (
427 "fallback-local-score (entity-miss demotion)"
428 )
429 report.clusters[0].score = 72
430
431 text = render.render_comparison_multi_context([("Example", report)])
432
433 self.assertIn("Nothing solid this window.", text)
434 self.assertNotIn("- Grounded result [", text)
435
436
437 class OutputEnvelopeTests(unittest.TestCase):
438 """LAW 6 envelopes: scope "pass through verbatim" unambiguously.
439
440 Added 2026-04-19 after the Hermes Agent Use Cases failure where two
441 consecutive runs dumped `## Ranked Evidence Clusters` as user output.
442 """
443
444 def test_evidence_for_synthesis_envelope_wraps_raw_evidence(self):
445 text = render.render_compact(sample_report())
446 self.assertIn("<!-- EVIDENCE FOR SYNTHESIS:", text)
447 self.assertIn("<!-- END EVIDENCE FOR SYNTHESIS -->", text)
448 # Opening comment must appear BEFORE the raw evidence block.
449 self.assertLess(
450 text.index("<!-- EVIDENCE FOR SYNTHESIS:"),
451 text.index("## Ranked Evidence Clusters"),
452 )
453 # Closing comment must appear AFTER Source Coverage.
454 self.assertGreater(
455 text.index("<!-- END EVIDENCE FOR SYNTHESIS -->"),
456 text.index("## Source Coverage"),
457 )
458
459 def test_pass_through_footer_envelope_wraps_emoji_tree(self):
460 text = render.render_compact(sample_report())
461 self.assertIn("```text\n---\n", text)
462 self.assertIn("\n---\n```\n\n---\n# END OF last30days CANONICAL OUTPUT", text)
463 self.assertNotIn("<!-- PASS-THROUGH FOOTER:", text)
464 self.assertNotIn("<!-- END PASS-THROUGH FOOTER -->", text)
465 # Emoji footer sits inside the fenced text block.
466 open_idx = text.index("```text\n---\n")
467 close_idx = text.index("\n---\n```\n\n---\n# END OF last30days CANONICAL OUTPUT")
468 self.assertIn("All agents reported back!", text[open_idx:close_idx])
469
470 def _perplexity_item(self, item_id: str, citations: int) -> schema.SourceItem:
471 return schema.SourceItem(
472 item_id=item_id,
473 source="perplexity",
474 title=f"Perplexity Agent: test topic ({item_id})",
475 body="AI synthesis body.",
476 url="",
477 container="perplexity.ai",
478 published_at="2026-03-16",
479 date_confidence="high",
480 engagement={"citations": citations},
481 metadata={},
482 )
483
484 def test_emoji_footer_includes_perplexity_when_present(self):
485 # Regression: Perplexity items survived retrieval/normalize/dedup but
486 # were dropped from the emoji-tree footer because _FOOTER_SOURCES
487 # omitted perplexity. The synthesis LLM that consumes the pass-through
488 # block then had no Perplexity signal, and users reasonably concluded
489 # the source was broken.
490 report = sample_report()
491 report.items_by_source["perplexity"] = [self._perplexity_item("px1", 7)]
492 text = render.render_compact(report)
493 self.assertIn("🧠 Perplexity:", text)
494 self.assertIn("7 citations", text)
495
496 def test_emoji_footer_perplexity_pluralizes_correctly(self):
497 # The footer line helper appends a literal "s" for plurals, so the
498 # item_word must pluralize regularly. Multi-item runs must produce
499 # "results", not "synthesiss" or other malformed forms.
500 report = sample_report()
501 report.items_by_source["perplexity"] = [
502 self._perplexity_item("px1", 4),
503 self._perplexity_item("px2", 3),
504 self._perplexity_item("px3", 2),
505 ]
506 text = render.render_compact(report)
507 self.assertIn("3 results", text)
508 self.assertNotIn("3 synthesiss", text)
509 self.assertNotIn("3 syntheses", text)
510 # Aggregate of all citation counts (4+3+2 = 9) — confirms multi-item
511 # engagement summation also lands correctly.
512 self.assertIn("9 citations", text)
513
514 def _linkedin_item(self, item_id: str, likes: int, comments: int) -> schema.SourceItem:
515 return schema.SourceItem(
516 item_id=item_id,
517 source="linkedin",
518 title=f"LinkedIn post about test topic ({item_id})",
519 body="LinkedIn post body.",
520 url="https://www.linkedin.com/posts/example",
521 container="LinkedIn",
522 published_at="2026-03-16",
523 date_confidence="high",
524 engagement={"likes": likes, "comments": comments},
525 metadata={},
526 )
527
528 def test_emoji_footer_includes_linkedin_when_present(self):
529 # Regression: LinkedIn items survived retrieval/normalize/dedup and
530 # were counted in ## Stats, but were dropped from the emoji-tree
531 # footer because _FOOTER_SOURCES omitted linkedin. The pass-through
532 # block users read then showed no LinkedIn line at all, so an 8-item
533 # LinkedIn run looked like the source never ran.
534 report = sample_report()
535 report.items_by_source["linkedin"] = [self._linkedin_item("li1", 140, 7)]
536 text = render.render_compact(report)
537 self.assertIn("👔 LinkedIn:", text)
538 self.assertIn("1 post", text)
539 self.assertIn("140 likes", text)
540 self.assertIn("7 comments", text)
541
542 def test_stats_linkedin_engagement_and_label(self):
543 # ENGAGEMENT_DISPLAY and SOURCE_LABELS also omitted linkedin, so the
544 # ## Stats line rendered as a bare title-cased "Linkedin: N items"
545 # with no engagement summary.
546 report = sample_report()
547 report.items_by_source["linkedin"] = [
548 self._linkedin_item("li1", 140, 7),
549 self._linkedin_item("li2", 57, 2),
550 ]
551 text = render.render_compact(report)
552 self.assertIn("- LinkedIn: 2 items", text)
553 self.assertIn("197likes", text)
554 self.assertIn("9cmt", text)
555 self.assertNotIn("- Linkedin:", text)
556
557 def test_canonical_boundary_ends_report_without_response_instructions(self):
558 text = render.render_compact(sample_report())
559 self.assertTrue(text.rstrip().endswith("# END OF last30days CANONICAL OUTPUT"))
560 self.assertIn("```text", text)
561 self.assertIn("### 1.", text)
562 self.assertNotIn("Pass through ONLY", text)
563
564 def test_envelopes_appear_in_md_emit_mode(self):
565 # --emit md and --emit compact both route to render_compact, so the
566 # same envelopes apply. Guard against future divergence.
567 text = render.render_compact(sample_report())
568 self.assertEqual(text.count("<!-- EVIDENCE FOR SYNTHESIS:"), 1)
569 self.assertEqual(text.count("<!-- END EVIDENCE FOR SYNTHESIS -->"), 1)
570 self.assertEqual(text.count("```text\n---\n"), 1)
571 self.assertEqual(
572 text.count("\n---\n```\n\n---\n# END OF last30days CANONICAL OUTPUT"),
573 1,
574 )
575
576 def test_no_dangling_envelope_open_without_close(self):
577 # Open/close counts must always match, even for empty clusters.
578 report = sample_report()
579 report.clusters = []
580 text = render.render_compact(report)
581 self.assertEqual(
582 text.count("<!-- EVIDENCE FOR SYNTHESIS:"),
583 text.count("<!-- END EVIDENCE FOR SYNTHESIS -->"),
584 )
585 self.assertEqual(text.count("```text\n---\n"), 1)
586 self.assertEqual(
587 text.count("\n---\n```\n\n---\n# END OF last30days CANONICAL OUTPUT"),
588 1,
589 )
590
591
592 class RenderTopCommentsTests(unittest.TestCase):
593 """Tests for the top-3 comments rendering in compact cluster view."""
594
595 def _make_report_with_comments(self, source="reddit", top_comments=None, comment_insights=None):
596 """Helper: build a report with a single candidate carrying given comments."""
597 item = schema.SourceItem(
598 item_id="i1",
599 source=source,
600 title="Test post",
601 body="Body text.",
602 url="https://reddit.com/r/test/comments/abc/test/",
603 container="test",
604 published_at="2026-03-15",
605 date_confidence="high",
606 engagement={"score": 100, "num_comments": 50},
607 metadata={
608 "top_comments": top_comments or [],
609 "comment_insights": comment_insights or [],
610 },
611 )
612 candidate = schema.Candidate(
613 candidate_id="c1",
614 item_id="i1",
615 source=source,
616 title="Test post",
617 url="https://reddit.com/r/test/comments/abc/test/",
618 snippet="A test snippet.",
619 subquery_labels=["primary"],
620 native_ranks={"primary:reddit": 1},
621 local_relevance=0.9,
622 freshness=90,
623 engagement=88,
624 source_quality=1.0,
625 rrf_score=0.02,
626 rerank_score=92,
627 final_score=90,
628 sources=[source],
629 source_items=[item],
630 )
631 cluster = schema.Cluster(
632 cluster_id="cluster-1",
633 title="Test cluster",
634 candidate_ids=["c1"],
635 representative_ids=["c1"],
636 sources=[source],
637 score=90,
638 )
639 return schema.Report(
640 topic="test topic",
641 range_from="2026-02-14",
642 range_to="2026-03-16",
643 generated_at="2026-03-16T00:00:00+00:00",
644 provider_runtime=schema.ProviderRuntime(
645 reasoning_provider="gemini",
646 planner_model="gemini-3.1-flash-lite",
647 rerank_model="gemini-3.1-flash-lite",
648 ),
649 query_plan=schema.QueryPlan(
650 intent="breaking_news",
651 freshness_mode="strict_recent",
652 cluster_mode="story",
653 raw_topic="test topic",
654 subqueries=[schema.SubQuery(label="primary", search_query="test", ranking_query="test?", sources=[source])],
655 source_weights={source: 1.0},
656 ),
657 clusters=[cluster],
658 ranked_candidates=[candidate],
659 items_by_source={source: [item]},
660 errors_by_source={},
661 )
662
663 def _diversity_candidate(self, source, item_id, comments):
664 item = schema.SourceItem(
665 item_id=item_id, source=source, title="t", body="b",
666 url=f"https://example.com/{item_id}", published_at="2026-03-15",
667 engagement={"views": 1000}, metadata={"top_comments": comments},
668 )
669 return schema.Candidate(
670 candidate_id=item_id, item_id=item_id, source=source, title="t",
671 url=f"https://example.com/{item_id}", snippet="s",
672 subquery_labels=["primary"], native_ranks={"primary:" + source: 1},
673 local_relevance=0.9, freshness=90, engagement=88, source_quality=1.0,
674 rrf_score=0.02, rerank_score=92, final_score=90, sources=[source],
675 source_items=[item],
676 )
677
678 def _diversity_report(self, candidates):
679 return schema.Report(
680 topic="t", range_from="2026-02-14", range_to="2026-03-16",
681 generated_at="2026-03-16T00:00:00+00:00",
682 provider_runtime=schema.ProviderRuntime(
683 reasoning_provider="gemini", planner_model="m", rerank_model="m"),
684 query_plan=schema.QueryPlan(
685 intent="breaking_news", freshness_mode="strict_recent",
686 cluster_mode="story", raw_topic="t",
687 subqueries=[schema.SubQuery(label="primary", search_query="t", ranking_query="t?", sources=["youtube"])],
688 source_weights={"youtube": 1.0}),
689 clusters=[], ranked_candidates=candidates,
690 items_by_source={}, errors_by_source={})
691
692 def test_top_comments_rank_based_diversity(self):
693 """A viral platform can't sweep the list: every item's top comment
694 comes before any item's #2, whatever the like counts. 4 YouTube videos
695 (3 high-vote comments each) + 1 TikTok video (2 low-vote comments)."""
696 yt_cands = []
697 for v in range(4):
698 comments = [
699 {"score": 3000 - v * 100 - i, "excerpt": f"youtube video {v} comment {i} text", "author": f"yt{v}{i}"}
700 for i in range(3)
701 ]
702 yt_cands.append(self._diversity_candidate("youtube", f"yt{v}", comments))
703 tt_cand = self._diversity_candidate("tiktok", "tt0", [
704 {"score": 50, "excerpt": "tiktok killer comment one text", "author": "ttA"},
705 {"score": 40, "excerpt": "tiktok killer comment two text", "author": "ttB"},
706 ])
707 report = self._diversity_report(yt_cands + [tt_cand])
708 lines = render._render_top_comments(report, limit=10)
709 blob = "\n".join(lines)
710 # Both low-vote TikTok comments surface despite 12 higher-vote YouTube ones.
711 self.assertIn("tiktok killer comment one text", blob)
712 self.assertIn("tiktok killer comment two text", blob)
713 # TikTok's top comment comes before any video's #2, and no #3 is listed.
714 self.assertLess(blob.index("tiktok killer comment one"), blob.index("comment 1 text"))
715 self.assertNotIn("comment 2 text", blob)
716 # Under a tighter limit the top comments are kept ahead of the #2s.
717 tight = "\n".join(render._render_top_comments(report, limit=6))
718 self.assertIn("tiktok killer comment one text", tight)
719 self.assertNotIn("tiktok killer comment two text", tight)
720
721 def test_reddit_5_comments_renders_top_3(self):
722 """Reddit candidate with 5 comments (scores 500, 200, 50, 8, 3) renders 3."""
723 comments = [
724 {"score": 500, "excerpt": "Comment with 500 upvotes", "author": "user1"},
725 {"score": 200, "excerpt": "Comment with 200 upvotes", "author": "user2"},
726 {"score": 50, "excerpt": "Comment with 50 upvotes", "author": "user3"},
727 {"score": 8, "excerpt": "Comment with 8 upvotes", "author": "user4"},
728 {"score": 3, "excerpt": "Comment with 3 upvotes", "author": "user5"},
729 ]
730 report = self._make_report_with_comments(top_comments=comments)
731 text = render.render_compact(report)
732 # Reddit authors render with u/ prefix now.
733 self.assertIn("u/user1 (500 upvotes):", text)
734 self.assertIn("u/user2 (200 upvotes):", text)
735 self.assertIn("u/user3 (50 upvotes):", text)
736 self.assertNotIn("u/user4 (8 upvotes):", text)
737 self.assertNotIn("u/user5 (3 upvotes):", text)
738
739 def test_reddit_1_comment_renders_1(self):
740 """Reddit candidate with 1 comment renders 1."""
741 comments = [{"score": 100, "excerpt": "Single comment", "author": "user1"}]
742 report = self._make_report_with_comments(top_comments=comments)
743 text = render.render_compact(report)
744 self.assertIn("u/user1 (100 upvotes): Single comment", text)
745
746 def test_reddit_0_comments_no_section(self):
747 """Reddit candidate with 0 comments renders no comment section."""
748 report = self._make_report_with_comments(top_comments=[])
749 text = render.render_compact(report)
750 self.assertNotIn("upvotes)", text)
751
752 def test_non_reddit_no_comments(self):
753 """Non-Reddit candidate doesn't render comments when metadata has none."""
754 report = self._make_report_with_comments(source="grounding", top_comments=[])
755 text = render.render_compact(report)
756 self.assertNotIn("upvotes)", text)
757 self.assertIn("Test cluster", text)
758
759 def test_all_comments_below_score_10_no_section(self):
760 """All comments below score 10 renders no comment section."""
761 comments = [
762 {"score": 9, "excerpt": "Low score 1", "author": "user1"},
763 {"score": 5, "excerpt": "Low score 2", "author": "user2"},
764 {"score": 1, "excerpt": "Low score 3", "author": "user3"},
765 ]
766 report = self._make_report_with_comments(top_comments=comments)
767 text = render.render_compact(report)
768 self.assertNotIn("upvotes)", text)
769
770 def test_youtube_comments_use_likes_label_and_50_threshold(self):
771 comments = [
772 {"score": 120, "excerpt": "legit fire tutorial", "author": "alice"},
773 {"score": 60, "excerpt": "saved me hours", "author": "bob"},
774 {"score": 20, "excerpt": "below threshold", "author": "carol"},
775 ]
776 report = self._make_report_with_comments(source="youtube", top_comments=comments)
777 text = render.render_compact(report)
778 # YouTube authors render with @ prefix; "likes" label.
779 self.assertIn("@alice (120 likes): legit fire tutorial", text)
780 self.assertIn("@bob (60 likes): saved me hours", text)
781 # The per-candidate CARD still applies the 50-like threshold: carol (20)
782 # does not appear on the card (colon-format line).
783 self.assertNotIn("@carol (20 likes):", text)
784 # The quote pool takes the video's top comment and its #2 with no
785 # 50-like floor, and nothing below them: carol is the video's #3.
786 self.assertIn('"legit fire tutorial" 🔴 @alice on YouTube · 120 likes', text)
787 self.assertIn('"saved me hours" 🔴 @bob on YouTube · 60 likes', text)
788 self.assertNotIn("@carol", text)
789
790 def test_reddit_comment_without_author_falls_back_to_legacy_label(self):
791 """When author is missing or [deleted], render falls back to 'Comment (...)'."""
792 comments = [
793 {"score": 500, "excerpt": "No author field", "author": ""},
794 {"score": 200, "excerpt": "Deleted user", "author": "[deleted]"},
795 {"score": 50, "excerpt": "Removed user", "author": "[removed]"},
796 ]
797 report = self._make_report_with_comments(top_comments=comments)
798 text = render.render_compact(report)
799 # Legacy format preserved - no u/ prefix leaks with empty/deleted handles.
800 self.assertIn("Comment (500 upvotes): No author field", text)
801 self.assertIn("Comment (200 upvotes): Deleted user", text)
802 self.assertIn("Comment (50 upvotes): Removed user", text)
803 self.assertNotIn("u/ (", text)
804 self.assertNotIn("u/[deleted]", text)
805 self.assertNotIn("u/[removed]", text)
806
807 def test_tiktok_comments_render_with_at_handle(self):
808 """TikTok source renders @handle attribution on comment lines."""
809 comments = [
810 {"score": 3986, "excerpt": "oh no. who's going to make the same phone every year now..", "author": "moosanoormahomed"},
811 {"score": 925, "excerpt": "This is either going to go so well or so bad", "author": "Muna9e"},
812 ]
813 report = self._make_report_with_comments(source="tiktok", top_comments=comments)
814 text = render.render_compact(report)
815 self.assertIn("@moosanoormahomed (3986 likes):", text)
816 self.assertIn("@Muna9e (925 likes):", text)
817 # Render must not silently label YT as upvotes.
818 self.assertNotIn("Comment (120 upvotes)", text)
819
820 def test_tiktok_comments_use_likes_label_and_500_threshold(self):
821 comments = [
822 {"score": 2000, "excerpt": "this aged well", "author": "a"},
823 {"score": 600, "excerpt": "so real", "author": "b"},
824 {"score": 400, "excerpt": "below tt threshold", "author": "c"},
825 {"score": 50, "excerpt": "way below", "author": "d"},
826 ]
827 report = self._make_report_with_comments(source="tiktok", top_comments=comments)
828 text = render.render_compact(report)
829 self.assertIn("@a (2000 likes): this aged well", text)
830 self.assertIn("@b (600 likes): so real", text)
831 # Card still applies the 500 threshold: c (400) not on the card.
832 self.assertNotIn("@c (400 likes):", text)
833 # The quote pool holds the video's top two quotable comments: "so
834 # real" is too short to quote, so c takes the #2 position, and d, the
835 # next one down, stays out.
836 self.assertIn('"this aged well" 🎵 @a on TikTok · 2,000 likes', text)
837 self.assertIn('"below tt threshold" 🎵 @c on TikTok · 400 likes', text)
838 self.assertNotIn("@b on TikTok", text)
839 self.assertNotIn("@d (50 likes)", text)
840 self.assertNotIn("@d on TikTok", text)
841
842
843 class RenderBestTakesCompactTests(unittest.TestCase):
844 """Tests for Best Takes section in compact output and fun tags on candidates."""
845
846 def _make_candidate(self, cid, fun_score=None, fun_explanation=None, final_score=80):
847 """Helper: build a candidate with a given fun_score."""
848 item = schema.SourceItem(
849 item_id=f"item-{cid}",
850 source="reddit",
851 title=f"Post {cid}",
852 body="Body text.",
853 url=f"https://reddit.com/r/test/comments/{cid}/",
854 container="test",
855 published_at="2026-03-15",
856 date_confidence="high",
857 engagement={"score": 200, "num_comments": 30},
858 metadata={
859 "top_comments": [{"excerpt": "Funny comment", "score": 50, "body": "lmao this is gold"}],
860 },
861 )
862 return schema.Candidate(
863 candidate_id=cid,
864 item_id=f"item-{cid}",
865 source="reddit",
866 title=f"Post {cid}",
867 url=f"https://reddit.com/r/test/comments/{cid}/",
868 snippet="A test snippet.",
869 subquery_labels=["primary"],
870 native_ranks={"primary:reddit": 1},
871 local_relevance=0.9,
872 freshness=90,
873 engagement=88,
874 source_quality=1.0,
875 rrf_score=0.02,
876 rerank_score=92,
877 final_score=final_score,
878 sources=["reddit"],
879 source_items=[item],
880 fun_score=fun_score,
881 fun_explanation=fun_explanation,
882 )
883
884 def _make_report_with_candidates(self, candidates):
885 """Helper: build a report with given candidates."""
886 items = []
887 for c in candidates:
888 items.extend(c.source_items)
889 cluster = schema.Cluster(
890 cluster_id="cluster-1",
891 title="Test cluster",
892 candidate_ids=[c.candidate_id for c in candidates],
893 representative_ids=[c.candidate_id for c in candidates],
894 sources=["reddit"],
895 score=90,
896 )
897 return schema.Report(
898 topic="test topic",
899 range_from="2026-02-14",
900 range_to="2026-03-16",
901 generated_at="2026-03-16T00:00:00+00:00",
902 provider_runtime=schema.ProviderRuntime(
903 reasoning_provider="gemini",
904 planner_model="gemini-3.1-flash-lite",
905 rerank_model="gemini-3.1-flash-lite",
906 ),
907 query_plan=schema.QueryPlan(
908 intent="breaking_news",
909 freshness_mode="strict_recent",
910 cluster_mode="story",
911 raw_topic="test topic",
912 subqueries=[schema.SubQuery(label="primary", search_query="test", ranking_query="test?", sources=["reddit"])],
913 source_weights={"reddit": 1.0},
914 ),
915 clusters=[cluster],
916 ranked_candidates=candidates,
917 items_by_source={"reddit": items},
918 errors_by_source={},
919 )
920
921 def test_compact_includes_best_takes_with_2_high_fun_candidates(self):
922 """Compact output includes Best Takes section when 2+ candidates score >= 70."""
923 candidates = [
924 self._make_candidate("c1", fun_score=85, fun_explanation="hilarious comment"),
925 self._make_candidate("c2", fun_score=75, fun_explanation="witty remark"),
926 self._make_candidate("c3", fun_score=40),
927 ]
928 report = self._make_report_with_candidates(candidates)
929 text = render.render_compact(report)
930 self.assertIn("## Best Takes", text)
931 # fun: tag may carry a " +crowd" suffix when votes lifted the ranking,
932 # so match the score substring rather than the exact closing paren.
933 self.assertIn("fun:85", text)
934 self.assertIn("fun:75", text)
935
936 def test_candidate_with_fun_score_85_shows_fun_tag(self):
937 """Candidate with fun_score=85 shows 'fun:85' in its detail line."""
938 candidates = [self._make_candidate("c1", fun_score=85)]
939 report = self._make_report_with_candidates(candidates)
940 text = render.render_compact(report)
941 self.assertIn("fun:85", text)
942
943 def test_candidate_with_fun_score_40_no_fun_tag(self):
944 """Candidate with fun_score=40 does NOT show fun tag (below 50 threshold)."""
945 candidates = [self._make_candidate("c1", fun_score=40)]
946 report = self._make_report_with_candidates(candidates)
947 text = render.render_compact(report)
948 self.assertNotIn("fun:40", text)
949 self.assertNotIn("fun:", text)
950
951 def test_no_best_takes_with_0_high_fun_candidates(self):
952 """No Best Takes section when 0 candidates above threshold."""
953 candidates = [
954 self._make_candidate("c1", fun_score=50),
955 self._make_candidate("c2", fun_score=40),
956 ]
957 report = self._make_report_with_candidates(candidates)
958 text = render.render_compact(report)
959 self.assertNotIn("## Best Takes", text)
960
961 def test_no_best_takes_with_1_high_fun_candidate(self):
962 """No Best Takes section when only 1 candidate above threshold."""
963 candidates = [
964 self._make_candidate("c1", fun_score=80),
965 self._make_candidate("c2", fun_score=50),
966 ]
967 report = self._make_report_with_candidates(candidates)
968 text = render.render_compact(report)
969 self.assertNotIn("## Best Takes", text)
970
971
972 class DegradedRunBannerTests(unittest.TestCase):
973 """Unit 1: DEGRADED RUN WARNING surfaces bare named-entity invocations
974 in user-visible stdout. LAW 7 backstop. 2026-04-19 Hermes Agent Use
975 Cases Run 1 failure mode.
976 """
977
978 def _bare_named_entity_report(self) -> schema.Report:
979 report = sample_report()
980 report.topic = "Hermes Agent"
981 report.artifacts["plan_source"] = "deterministic"
982 report.artifacts["pre_research_flags_present"] = False
983 return report
984
985 def test_banner_appears_on_bare_named_entity_deterministic_run(self):
986 text = render.render_compact(self._bare_named_entity_report())
987 self.assertIn("## DEGRADED RUN WARNING", text)
988 self.assertIn("<!-- USER-VISIBLE BANNER:", text)
989 self.assertIn("<!-- END USER-VISIBLE BANNER -->", text)
990 self.assertIn("No host-authored query plan", text)
991 # Runtime-agnostic enumeration: all host runtimes appear.
992 for runtime_name in ("Claude Code", "Codex", "Hermes", "Gemini"):
993 self.assertIn(runtime_name, text)
994
995 def test_banner_positioned_before_evidence_envelope(self):
996 text = render.render_compact(self._bare_named_entity_report())
997 banner_idx = text.index("## DEGRADED RUN WARNING")
998 envelope_idx = text.index("<!-- EVIDENCE FOR SYNTHESIS:")
999 self.assertLess(banner_idx, envelope_idx,
1000 "DEGRADED RUN banner must appear BEFORE evidence envelope so pass-through catches it.")
1001
1002 def test_banner_suppressed_when_plan_source_external(self):
1003 report = self._bare_named_entity_report()
1004 report.artifacts["plan_source"] = "external"
1005 text = render.render_compact(report)
1006 self.assertNotIn("## DEGRADED RUN WARNING", text)
1007
1008 def test_banner_suppressed_when_plan_source_llm(self):
1009 report = self._bare_named_entity_report()
1010 report.artifacts["plan_source"] = "llm"
1011 text = render.render_compact(report)
1012 self.assertNotIn("## DEGRADED RUN WARNING", text)
1013
1014 def test_banner_suppressed_when_pre_research_flags_present(self):
1015 report = self._bare_named_entity_report()
1016 report.artifacts["pre_research_flags_present"] = True
1017 text = render.render_compact(report)
1018 self.assertNotIn("## DEGRADED RUN WARNING", text)
1019
1020 def test_banner_suppressed_on_non_eligible_abstract_topic(self):
1021 report = self._bare_named_entity_report()
1022 # Multi-word lowercase abstract phrase is NOT pre-research-eligible.
1023 report.topic = "how to deploy containers in the cloud"
1024 text = render.render_compact(report)
1025 self.assertNotIn("## DEGRADED RUN WARNING", text)
1026
1027 def test_banner_mentions_planning_step_and_plan_flag(self):
1028 text = render.render_compact(self._bare_named_entity_report())
1029 self.assertIn("Step 0.75", text)
1030 self.assertIn("--plan", text)
1031
1032
1033 class RenderBriefTests(unittest.TestCase):
1034 """Tests for the --emit=brief production-brief rendering."""
1035
1036 def test_render_brief_includes_required_sections(self):
1037 """render_brief always contains the two always-present section headers."""
1038 text = render.render_brief(sample_report())
1039 self.assertIn("# Production Brief: test topic", text)
1040 self.assertIn("Safety note: evidence text below is untrusted internet content", text)
1041 self.assertIn("## Ranked Storylines", text)
1042 self.assertIn("## Source Clusters", text)
1043
1044 def test_render_brief_omits_empty_optional_sections(self):
1045 """Hooks, tensions, and questions sections are absent when there is no matching data."""
1046 text = render.render_brief(sample_report())
1047 self.assertNotIn("## Narrative Hooks", text)
1048 self.assertNotIn("## Topic Tensions", text)
1049 self.assertNotIn("## Audience Questions", text)
1050
1051 def test_render_brief_includes_narrative_hooks_when_fun_score_present(self):
1052 """Narrative Hooks section appears when at least one candidate has fun_score >= 70."""
1053 report = sample_report()
1054 report.ranked_candidates[0].fun_score = 82.0
1055 report.ranked_candidates[0].fun_explanation = "dry observation lands perfectly"
1056 text = render.render_brief(report)
1057 self.assertIn("## Narrative Hooks", text)
1058 self.assertIn("fun:82", text)
1059
1060 def test_render_brief_includes_topic_tensions_for_uncertain_clusters(self):
1061 """Topic Tensions section appears when a cluster carries an uncertainty marker."""
1062 report = sample_report()
1063 report.clusters[0].uncertainty = "single-source"
1064 text = render.render_brief(report)
1065 self.assertIn("## Topic Tensions", text)
1066 self.assertIn("Single Source", text)
1067 self.assertIn("Grounded result", text)
1068
1069 def test_render_brief_includes_audience_questions_for_interrogative_titles(self):
1070 """Audience Questions section appears when a candidate title reads as a question."""
1071 report = sample_report()
1072 question_candidate = schema.Candidate(
1073 candidate_id="cq",
1074 item_id="iq",
1075 source="reddit",
1076 title="What are the best prompting tricks for Claude?",
1077 url="https://reddit.com/r/test",
1078 snippet="Community asks about prompting.",
1079 subquery_labels=["primary"],
1080 native_ranks={"primary:reddit": 2},
1081 local_relevance=0.7,
1082 freshness=70,
1083 engagement=30,
1084 source_quality=0.8,
1085 rrf_score=0.01,
1086 final_score=70,
1087 sources=["reddit"],
1088 source_items=[],
1089 )
1090 report.ranked_candidates.append(question_candidate)
1091 report.clusters[0].candidate_ids.append("cq")
1092 text = render.render_brief(report)
1093 self.assertIn("## Audience Questions", text)
1094 self.assertIn("What are the best prompting tricks for Claude?", text)
1095
1096 def test_render_brief_empty_clusters_emits_section_headers(self):
1097 """Sections 1 and 5 always appear even when clusters is empty."""
1098 report = sample_report()
1099 report.clusters = []
1100 text = render.render_brief(report)
1101 self.assertIn("## Ranked Storylines", text)
1102 self.assertIn("## Source Clusters", text)
1103
1104 def test_render_brief_hooks_omit_heuristic_fallback_reason(self):
1105 """Narrative Hooks omit the reason string when fun_explanation is 'heuristic-fallback'."""
1106 report = sample_report()
1107 report.ranked_candidates[0].fun_score = 75.0
1108 report.ranked_candidates[0].fun_explanation = "heuristic-fallback"
1109 text = render.render_brief(report)
1110 self.assertIn("## Narrative Hooks", text)
1111 self.assertNotIn("heuristic-fallback", text)
1112
1113 def test_render_brief_audience_questions_are_deduped(self):
1114 """Duplicate question titles appear only once in the Audience Questions section."""
1115 report = sample_report()
1116 for i in range(2):
1117 report.ranked_candidates.append(schema.Candidate(
1118 candidate_id=f"cdup{i}", item_id=f"idup{i}", source="reddit",
1119 title="What is the best approach?",
1120 url="https://reddit.com/r/test", snippet="...",
1121 subquery_labels=["primary"], native_ranks={},
1122 local_relevance=0.7, freshness=70, engagement=30,
1123 source_quality=0.8, rrf_score=0.01, final_score=70,
1124 sources=["reddit"], source_items=[],
1125 ))
1126 report.clusters[0].candidate_ids.append(f"cdup{i}")
1127 text = render.render_brief(report)
1128 self.assertEqual(text.count("What is the best approach?"), 1)
1129
1130
1131 class YoutubeFooterTranscriptRatioTests(unittest.TestCase):
1132 """The YouTube footer line must surface the transcript-fetch ratio in all
1133 cases where videos were returned. Pre-fix the segment was suppressed when
1134 transcripts == 0, which converted the canonical stale-yt-dlp failure mode
1135 into a silent absence at the footer (the very surface users read for
1136 'did this work?'). Always-render the ratio so zero is loud.
1137 """
1138
1139 def _build_youtube_report(self, transcript_flags: list[bool]) -> schema.Report:
1140 """Build a Report with one YouTube item per entry in transcript_flags.
1141 True means the item has transcript data; False means it does not.
1142 """
1143 items = []
1144 for idx, has_transcript in enumerate(transcript_flags):
1145 metadata = {"views": 1000}
1146 if has_transcript:
1147 metadata["transcript_highlights"] = ["Some pre-extracted quote."]
1148 items.append(schema.SourceItem(
1149 item_id=f"yt{idx}",
1150 source="youtube",
1151 title=f"Video {idx}",
1152 body=f"Description for video {idx}.",
1153 url=f"https://youtube.com/watch?v=v{idx}",
1154 container="some-channel",
1155 published_at="2026-04-15",
1156 date_confidence="high",
1157 engagement={"views": 1000, "likes": 100},
1158 metadata=metadata,
1159 ))
1160 return schema.Report(
1161 topic="test topic",
1162 range_from="2026-04-01",
1163 range_to="2026-05-01",
1164 generated_at="2026-05-01T00:00:00+00:00",
1165 provider_runtime=schema.ProviderRuntime(
1166 reasoning_provider="gemini",
1167 planner_model="gemini",
1168 rerank_model="gemini",
1169 ),
1170 query_plan=schema.QueryPlan(
1171 intent="general",
1172 freshness_mode="balanced_recent",
1173 cluster_mode="none",
1174 raw_topic="test topic",
1175 subqueries=[schema.SubQuery(
1176 label="primary", search_query="test topic",
1177 ranking_query="What about test topic?", sources=["youtube"],
1178 )],
1179 source_weights={"youtube": 1.0},
1180 ),
1181 clusters=[],
1182 ranked_candidates=[],
1183 items_by_source={"youtube": items},
1184 errors_by_source={},
1185 )
1186
1187 def test_zero_transcripts_with_videos_present_renders_zero_over_total(self):
1188 # The canonical stale-yt-dlp case: 6 videos found, 0 transcripts captured.
1189 # Pre-fix the footer hid this entirely; post-fix it must say "0/6 with transcripts".
1190 report = self._build_youtube_report([False] * 6)
1191 text = render.render_compact(report)
1192 self.assertIn("0/6 with transcripts", text)
1193
1194 def test_partial_transcripts_renders_ratio(self):
1195 # 5 of 6 transcripts captured - shows ratio so user knows one was missed.
1196 report = self._build_youtube_report([True] * 5 + [False])
1197 text = render.render_compact(report)
1198 self.assertIn("5/6 with transcripts", text)
1199
1200 def test_full_transcripts_renders_ratio(self):
1201 # All 3 transcripts captured - still shows ratio for consistency.
1202 report = self._build_youtube_report([True] * 3)
1203 text = render.render_compact(report)
1204 self.assertIn("3/3 with transcripts", text)
1205
1206 def test_no_videos_no_transcript_segment(self):
1207 # When YouTube has no items at all, the YouTube footer line is
1208 # suppressed entirely (existing behavior) - the transcript segment
1209 # should not appear without a parent line.
1210 report = self._build_youtube_report([])
1211 text = render.render_compact(report)
1212 # No YouTube footer line at all - so no transcript segment either
1213 self.assertNotIn("with transcripts", text)
1214
1215
1216 class TranscriptCaveatTests(unittest.TestCase):
1217 """Transcript-derived text must be labelled as auto-generated wherever it
1218 is emitted, so the synthesizing model does not treat caption homophone
1219 errors (e.g. "basil fears" for "basal fears") as verbatim quotes (#82).
1220 """
1221
1222 def _youtube_item(self) -> schema.SourceItem:
1223 return schema.SourceItem(
1224 item_id="yt1",
1225 source="youtube",
1226 title="Interview video",
1227 body="Description.",
1228 url="https://youtube.com/watch?v=v1",
1229 container="some-channel",
1230 published_at="2026-04-15",
1231 date_confidence="high",
1232 engagement={"views": 1000, "likes": 100},
1233 metadata={
1234 "transcript_highlights": ["She identifies eight basil fears."],
1235 "transcript_snippet": "And basil you mean like of the body? " * 5,
1236 },
1237 )
1238
1239 def _report(self) -> schema.Report:
1240 return schema.Report(
1241 topic="test topic",
1242 range_from="2026-04-01",
1243 range_to="2026-05-01",
1244 generated_at="2026-05-01T00:00:00+00:00",
1245 provider_runtime=schema.ProviderRuntime(
1246 reasoning_provider="gemini",
1247 planner_model="gemini",
1248 rerank_model="gemini",
1249 ),
1250 query_plan=schema.QueryPlan(
1251 intent="general",
1252 freshness_mode="balanced_recent",
1253 cluster_mode="none",
1254 raw_topic="test topic",
1255 subqueries=[schema.SubQuery(
1256 label="primary", search_query="test topic",
1257 ranking_query="What about test topic?", sources=["youtube"],
1258 )],
1259 source_weights={"youtube": 1.0},
1260 ),
1261 clusters=[],
1262 ranked_candidates=[],
1263 items_by_source={"youtube": [self._youtube_item()]},
1264 errors_by_source={},
1265 )
1266
1267 def test_render_full_labels_highlights_and_transcript_as_auto_generated(self):
1268 text = render.render_full(self._report())
1269 self.assertIn(
1270 "Highlights (auto-generated transcript; may contain transcription errors):",
1271 text,
1272 )
1273 self.assertIn("auto-generated — may contain transcription errors)</summary>", text)
1274 self.assertNotIn("\n Highlights:\n", text)
1275
1276 def test_render_candidate_labels_highlights_as_auto_generated(self):
1277 item = self._youtube_item()
1278 candidate = schema.Candidate(
1279 candidate_id="c1",
1280 item_id=item.item_id,
1281 source="youtube",
1282 title=item.title,
1283 url=item.url,
1284 snippet="A snippet.",
1285 subquery_labels=["primary"],
1286 native_ranks={"youtube": 1},
1287 local_relevance=1.0,
1288 freshness=1,
1289 engagement=1000,
1290 source_quality=1.0,
1291 rrf_score=1.0,
1292 sources=["youtube"],
1293 source_items=[item],
1294 )
1295 lines = render._render_candidate(candidate, "1.")
1296 text = "\n".join(lines)
1297 self.assertIn(
1298 "Highlights (auto-generated transcript; may contain transcription errors):",
1299 text,
1300 )
1301
1302
1303 class TestUntrustedEvidenceSanitization(unittest.TestCase):
1304 """Scraped markdown must not mint structural ## headings in evidence (#874)."""
1305
1306 def test_format_untrusted_evidence_indents_and_escapes_headings(self):
1307 raw = (
1308 "Sales Operations Key Account Manager at Traeger Grills · JobsRadar\n"
1309 "\n"
1310 "Jobs› Companies› Traeger Grills\n"
1311 "\n"
1312 "## About this Sales Operations Key Account Manager role at Traeger Grills\n"
1313 "\n"
1314 "Traeger Grills · Onsite · Salt Lake City, UT"
1315 )
1316 formatted = render._format_untrusted_evidence(raw, 360)
1317 self.assertNotRegex(formatted, r"(?m)^## ")
1318 self.assertIn(r"\#\# About this Sales Operations", formatted)
1319 # Continuation lines stay under the Evidence bullet indent.
1320 for line in formatted.splitlines()[1:]:
1321 self.assertTrue(line.startswith(" ") or line == " ")
1322
1323 def test_render_candidate_evidence_has_no_column_zero_heading(self):
1324 item = schema.SourceItem(
1325 item_id="j1",
1326 source="jobs",
1327 title="Sales Operations Key Account Manager",
1328 body="body",
1329 url="https://jobs-radar.com/job/example",
1330 published_at="2026-07-01",
1331 date_confidence="high",
1332 engagement={},
1333 snippet=(
1334 "Sales Operations role\n\n"
1335 "## About this Sales Operations Key Account Manager role at Traeger Grills\n"
1336 "Welcome To The Traegerhood"
1337 ),
1338 )
1339 candidate = schema.Candidate(
1340 candidate_id="c1",
1341 item_id=item.item_id,
1342 source="jobs",
1343 title=item.title,
1344 url=item.url,
1345 snippet=item.snippet,
1346 subquery_labels=["primary"],
1347 native_ranks={"jobs": 1},
1348 local_relevance=1.0,
1349 freshness=1,
1350 engagement=1,
1351 source_quality=1.0,
1352 rrf_score=1.0,
1353 sources=["jobs"],
1354 source_items=[item],
1355 )
1356 text = "\n".join(render._render_candidate(candidate, "1."))
1357 self.assertIn(" - Evidence:", text)
1358 self.assertNotRegex(text, r"(?m)^## ")
1359 self.assertIn(r"\#\# About this Sales Operations", text)
1360
1361
1362 if __name__ == "__main__":
1363 unittest.main()
1364
1365
1366 class TestRenderTopCommentsBlock(unittest.TestCase):
1367 """U3: vote-ranked Top Community Comments across ALL candidates, inside the
1368 EVIDENCE envelope, so the funniest lines reach the synthesizing model even
1369 when Best Takes is empty (no LLM fun-scorer in the engine subprocess)."""
1370
1371 def _cand(self, cid, source, score, body, author="u1", url=None):
1372 u = url or f"https://example.com/{source}/{cid}"
1373 item = schema.SourceItem(
1374 item_id=f"i-{cid}", source=source, title=f"test Post {cid}", body="b", url=u,
1375 container="c", published_at="2026-03-15", date_confidence="high",
1376 engagement={"score": 100, "num_comments": 10},
1377 metadata={"top_comments": [
1378 {"score": score, "excerpt": body, "author": author, "depth": 0}]},
1379 )
1380 return schema.Candidate(
1381 candidate_id=cid, item_id=f"i-{cid}", source=source, title=f"Post {cid}", url=u,
1382 snippet="s", subquery_labels=["primary"], native_ranks={f"primary:{source}": 1},
1383 local_relevance=0.9, freshness=90, engagement=80, source_quality=1.0,
1384 rrf_score=0.02, rerank_score=90, final_score=85, sources=[source], source_items=[item],
1385 )
1386
1387 def _report(self, candidates, representative_ids):
1388 cluster = schema.Cluster(
1389 cluster_id="cl-1", title="Test cluster",
1390 candidate_ids=[c.candidate_id for c in candidates],
1391 representative_ids=representative_ids, sources=["reddit"], score=90,
1392 )
1393 return schema.Report(
1394 topic="test topic", range_from="2026-02-14", range_to="2026-03-16",
1395 generated_at="2026-03-16T00:00:00+00:00",
1396 provider_runtime=schema.ProviderRuntime(
1397 reasoning_provider="gemini", planner_model="m", rerank_model="m"),
1398 query_plan=schema.QueryPlan(
1399 intent="breaking_news", freshness_mode="strict_recent", cluster_mode="story",
1400 raw_topic="test topic",
1401 subqueries=[schema.SubQuery(label="primary", search_query="t",
1402 ranking_query="t?", sources=["reddit"])],
1403 source_weights={"reddit": 1.0}),
1404 clusters=[cluster], ranked_candidates=candidates,
1405 items_by_source={"reddit": [c.source_items[0] for c in candidates]},
1406 errors_by_source={},
1407 )
1408
1409 def test_block_renders_with_2plus_comments(self):
1410 report = self._report(
1411 [self._cand("a", "reddit", 500, "first funny line here"),
1412 self._cand("b", "reddit", 50, "second funny line here")],
1413 representative_ids=["a"])
1414 text = render.render_compact(report)
1415 self.assertIn("## Top Community Comments", text)
1416 self.assertIn("first funny line here", text)
1417
1418 def test_includes_comment_on_non_representative_candidate(self):
1419 """The headline fix: a funny comment on a candidate NOT chosen as the
1420 cluster representative still surfaces (the Kanye 'TurkiYe' case)."""
1421 rep = self._cand("rep", "reddit", 300, "boring representative comment")
1422 hidden = self._cand("hidden", "reddit", 1335, "Is anyone surprised it is called TurkiYe")
1423 report = self._report([rep, hidden], representative_ids=["rep"]) # hidden NOT a rep
1424 text = render.render_compact(report)
1425 block = text.split("## Top Community Comments", 1)[1]
1426 self.assertIn("TurkiYe", block)
1427
1428 def test_excludes_comments_from_entity_miss_candidate_in_mixed_report(self):
1429 missed = self._cand(
1430 "missed",
1431 "reddit",
1432 5000,
1433 "viral but unrelated entity-miss comment",
1434 )
1435 missed.final_score = 0
1436 missed.explanation = "fallback-local-score (entity-miss demotion)"
1437 report = self._report(
1438 [
1439 missed,
1440 self._cand("good-a", "reddit", 100, "first relevant comment here"),
1441 self._cand("good-b", "reddit", 90, "second relevant comment here"),
1442 ],
1443 representative_ids=["good-a"],
1444 )
1445
1446 block = "\n".join(render._render_top_comments(report))
1447
1448 self.assertNotIn("viral but unrelated", block)
1449 self.assertIn("first relevant comment", block)
1450 self.assertIn("second relevant comment", block)
1451
1452 def test_block_inside_evidence_envelope(self):
1453 report = self._report(
1454 [self._cand("a", "reddit", 500, "first funny line here"),
1455 self._cand("b", "reddit", 50, "second funny line here")],
1456 representative_ids=["a"])
1457 text = render.render_compact(report)
1458 open_i = text.index("EVIDENCE FOR SYNTHESIS: ranked source data.")
1459 end_i = text.index("END EVIDENCE FOR SYNTHESIS")
1460 blk_i = text.index("## Top Community Comments")
1461 self.assertTrue(open_i < blk_i < end_i, "block must sit inside the EVIDENCE envelope")
1462
1463 def test_sorted_by_normalized_vote_cross_platform(self):
1464 # Equal raw 600: Reddit normalizes higher than TikTok (smaller reference),
1465 # so the Reddit gem ranks above the TikTok line despite same raw count.
1466 # TikTok 600 is above its 500 min-score threshold so it isn't filtered.
1467 report = self._report(
1468 [self._cand("r", "reddit", 600, "reddit gem line here"),
1469 self._cand("t", "tiktok", 600, "low tiktok line here")],
1470 representative_ids=["r"])
1471 block = render.render_compact(report).split("## Top Community Comments", 1)[1]
1472 self.assertLess(block.index("reddit gem"), block.index("low tiktok"))
1473
1474 def test_entries_carry_url(self):
1475 report = self._report(
1476 [self._cand("a", "reddit", 500, "first funny line here", url="https://reddit.com/x"),
1477 self._cand("b", "reddit", 50, "second funny line here")],
1478 representative_ids=["a"])
1479 block = render.render_compact(report).split("## Top Community Comments", 1)[1]
1480 self.assertIn("https://reddit.com/x", block)
1481
1482 def test_omitted_when_fewer_than_two(self):
1483 report = self._report([self._cand("a", "reddit", 500, "only one comment line")],
1484 representative_ids=["a"])
1485 text = render.render_compact(report)
1486 self.assertNotIn("## Top Community Comments", text)
1487 # footer/envelope intact
1488 self.assertIn("END EVIDENCE FOR SYNTHESIS", text)
1489
1490 def test_dedupes_identical_comments(self):
1491 report = self._report(
1492 [self._cand("a", "reddit", 500, "duplicate line text here"),
1493 self._cand("b", "reddit", 400, "duplicate line text here"),
1494 self._cand("c", "reddit", 300, "a distinct third comment line")],
1495 representative_ids=["a"])
1496 block = render.render_compact(report).split("## Top Community Comments", 1)[1]
1497 self.assertEqual(block.count("duplicate line text here"), 1)
1498 self.assertIn("a distinct third comment line", block)
1499
1500
1501 class TestCommentAttributionPrefix(unittest.TestCase):
1502 def test_strips_existing_at_prefix_youtube(self):
1503 # YouTube/TikTok authors already carry '@' from enrichment -> no '@@'.
1504 self.assertEqual(render._comment_attribution("youtube", "@ml-dz9ww"), "@ml-dz9ww")
1505 self.assertEqual(render._comment_attribution("tiktok", "@creator"), "@creator")
1506
1507 def test_adds_prefix_when_missing(self):
1508 self.assertEqual(render._comment_attribution("youtube", "alice"), "@alice")
1509 self.assertEqual(render._comment_attribution("reddit", "bob"), "u/bob")
1510
1511 def test_deleted_author_is_comment(self):
1512 self.assertEqual(render._comment_attribution("reddit", "[deleted]"), "Comment")
1513 self.assertEqual(render._comment_attribution("reddit", None), "Comment")
1514
1515
1516 class TestShortenPolymarketTitle(unittest.TestCase):
1517 def test_fallback_strips_leading_article(self):
1518 # A long question that falls through to the 6-word fallback must not keep
1519 # a leading article -> avoids descriptors like "an Anthropic Claude model".
1520 title = "Will an Anthropic Claude model score at the top of the leaderboard?"
1521 result = render._shorten_polymarket_title(title)
1522 lower = result.lower()
1523 self.assertFalse(lower.startswith("a "))
1524 self.assertFalse(lower.startswith("an "))
1525 self.assertFalse(lower.startswith("the "))
1526
1527 def test_fallback_keeps_non_article_lead(self):
1528 title = "Anthropic releases a major Claude model update that changes everything soon"
1529 result = render._shorten_polymarket_title(title)
1530 self.assertTrue(result.lower().startswith("anthropic"))
1531
1532
1533 class TestPolymarketTopMarkets(unittest.TestCase):
1534 @staticmethod
1535 def _pm_item(question, outcome_name, price, volume=1000):
1536 return schema.SourceItem(
1537 item_id="pm1",
1538 source="polymarket",
1539 title=question,
1540 body="",
1541 url="https://polymarket.com/event/x",
1542 engagement={"volume": volume},
1543 metadata={
1544 "question": question,
1545 "outcome_prices": [(outcome_name, price)],
1546 },
1547 )
1548
1549 def test_article_outcome_is_suppressed(self):
1550 # The real-world mangled case: descriptor "...score at" + lead name "an".
1551 # The outcome label is an article -> render "<descriptor> <pct>", no ": an ".
1552 item = self._pm_item(
1553 "Will an Anthropic Claude model score at the top of the leaderboard?",
1554 "an",
1555 0.19,
1556 )
1557 lines = render._polymarket_top_markets([item])
1558 self.assertEqual(len(lines), 1)
1559 line = lines[0]
1560 self.assertNotIn(": an ", line)
1561 self.assertIn("19%", line)
1562
1563 def test_yes_outcome_is_suppressed(self):
1564 item = self._pm_item("Will the bill pass this session?", "Yes", 0.65)
1565 line = render._polymarket_top_markets([item])[0]
1566 self.assertNotIn(": Yes ", line)
1567 self.assertIn("65%", line)
1568
1569 def test_no_outcome_is_suppressed(self):
1570 item = self._pm_item("Will the bill pass this session?", "No", 0.30)
1571 line = render._polymarket_top_markets([item])[0]
1572 self.assertNotIn(": No ", line)
1573 self.assertIn("30%", line)
1574
1575 def test_redundant_lead_token_is_suppressed(self):
1576 # Outcome name duplicates the descriptor's first token -> no doubling.
1577 item = self._pm_item("Arizona wins the tournament", "Arizona", 0.42)
1578 line = render._polymarket_top_markets([item])[0]
1579 self.assertNotIn(": Arizona ", line)
1580 # Descriptor itself still carries the name once.
1581 self.assertIn("Arizona", line)
1582
1583 def test_named_outcome_is_kept(self):
1584 # A genuinely informative multi-way outcome name is preserved.
1585 item = self._pm_item("Who wins the primary?", "Kanye", 0.12)
1586 line = render._polymarket_top_markets([item])[0]
1587 self.assertIn(": Kanye ", line)
1588
1589
1590 class TestMarkdownUrlLinkSafety(unittest.TestCase):
1591 """Greptile follow-up on #886/#912: source URLs are untrusted API
1592 responses, not authored content -- must not be embedded verbatim into
1593 markdown link syntax without checking for characters/schemes that would
1594 corrupt or misuse it."""
1595
1596 def test_plain_https_url_becomes_a_link(self):
1597 self.assertEqual(
1598 render._markdown_url_link("https://example.com/thread"),
1599 "[https://example.com/thread](https://example.com/thread)",
1600 )
1601
1602 def test_url_with_closing_paren_falls_back_to_plain_text(self):
1603 # A `)` in the URL would prematurely close the markdown destination.
1604 url = "https://example.com/wiki/Foo_(bar)"
1605 result = render._markdown_url_link(url)
1606 self.assertEqual(result, r"https\://example\.com/wiki/Foo\_\(bar\)")
1607 self.assertNotIn("](", result)
1608
1609 def test_url_with_bracket_falls_back_to_plain_text(self):
1610 url = "https://example.com/search?q=[test]"
1611 self.assertEqual(
1612 render._markdown_url_link(url),
1613 r"https\://example\.com/search?q=\[test\]",
1614 )
1615
1616 def test_non_http_scheme_falls_back_to_plain_text(self):
1617 # Untrusted scheme (e.g. javascript:) must never become an active link.
1618 url = "javascript:alert(1)"
1619 self.assertEqual(render._markdown_url_link(url), r"javascript\:alert\(1\)")
1620
1621 def test_url_with_backslash_falls_back_to_plain_text(self):
1622 # A backslash can escape adjacent markdown delimiters.
1623 url = "https://example.com/\\]"
1624 result = render._markdown_url_link(url)
1625 self.assertEqual(result, "https\\://example\\.com/\\\\\\]")
1626 self.assertNotIn("](", result)
1627
1628 def test_embedded_markdown_link_is_escaped_as_plain_text(self):
1629 result = render._markdown_url_link("[click](javascript:alert)")
1630 self.assertEqual(result, r"\[click\]\(javascript\:alert\)")
1631 self.assertNotIn("[click](javascript:alert)", result)
1632
1633 def test_angle_autolink_and_raw_html_are_encoded(self):
1634 autolink = render._markdown_url_link("<javascript:alert(1)>")
1635 raw_html = render._markdown_url_link(
1636 '<a href="javascript:alert(1)">click</a>'
1637 )
1638 self.assertEqual(autolink, r"&lt;javascript\:alert\(1\)&gt;")
1639 self.assertNotIn("<a ", raw_html)
1640 self.assertIn("&lt;a href=", raw_html)
1641
1642 def test_http_url_with_raw_html_delimiters_is_plain_text(self):
1643 result = render._markdown_url_link("https://example.com/<script>")
1644 self.assertEqual(result, r"https\://example\.com/&lt;script&gt;")
1645 self.assertNotIn("](", result)
1646
1647 def test_embedded_newline_is_stripped_even_from_plain_text_fallback(self):
1648 """Greptile follow-up: an embedded newline/CR must not survive into
1649 the rendered line at all -- whether or not the URL becomes a link --
1650 since it could otherwise inject fabricated report structure (fake
1651 headings, list items) into the single-line output."""
1652 url = "https://example.com/x\n## Injected Heading\nmore"
1653 result = render._markdown_url_link(url)
1654 self.assertNotIn("\n", result)
1655 url_cr = "https://example.com/x\r\nmore"
1656 self.assertNotIn("\r", render._markdown_url_link(url_cr))
1657 self.assertNotIn("\n", render._markdown_url_link(url_cr))
1658 self.assertNotIn("##", result)
1659 self.assertNotEqual(result, url)
1660
1661 def test_url_with_controls_is_escaped_and_single_line(self):
1662 url = "https://example.com/x\t\x00\u2028more"
1663 result = render._markdown_url_link(url)
1664 self.assertNotEqual(result, url)
1665 self.assertNotIn("\t", result)
1666 self.assertNotIn("\x00", result)
1667 self.assertNotIn("](", result)
1668
1669 def test_safe_url_with_query_fragment_and_encoded_delimiters_stays_clickable(self):
1670 url = "https://example.com/search?q=one&other=two%28x%29#result"
1671 self.assertEqual(
1672 render._markdown_url_link(url),
1673 f"[{url}]({url})",
1674 )
1675
1676 def test_malformed_or_unsafe_destinations_are_escaped(self):
1677 for url in (
1678 "data:text/plain,hello",
1679 "vbscript:alert(1)",
1680 "file:///tmp/report.md",
1681 "mailto:user@example.com",
1682 "//evil.example/path",
1683 "https:example.com/path",
1684 " https://example.com/path ",
1685 ):
1686 with self.subTest(url=url):
1687 result = render._markdown_url_link(url)
1688 self.assertNotEqual(result, url)
1689 self.assertNotIn("](", result)
1690
1691 def test_empty_url_returns_empty_string(self):
1692 self.assertEqual(render._markdown_url_link(""), "")
1693 self.assertEqual(render._markdown_url_link(" \t\r\n"), "")
1694 self.assertEqual(render._markdown_url_link("\x00\u2028"), "")
1695
1696
1697 class TestSourceUrlsAreClickable(unittest.TestCase):
1698 """Regression for #886: source URLs rendered as plain text instead of
1699 markdown links in the saved raw report and internal evidence block."""
1700
1701 def test_all_items_by_source_url_is_markdown_link(self):
1702 text = render.render_full(sample_report())
1703 self.assertIn("[https://example.com](https://example.com)", text)
1704 # No bare unlinked URL line remains for the item that has one.
1705 self.assertNotIn("\n https://example.com\n", text)
1706
1707 def test_all_items_by_source_empty_url_renders_no_url_line(self):
1708 report = sample_report()
1709 empty_url_item = schema.SourceItem(
1710 item_id="i3",
1711 source="perplexity",
1712 title="Perplexity Agent: test topic",
1713 body="AI synthesis body.",
1714 url="",
1715 container="perplexity.ai",
1716 published_at="2026-03-16",
1717 date_confidence="high",
1718 engagement={"citations": 3},
1719 metadata={},
1720 )
1721 report.items_by_source["perplexity"] = [empty_url_item]
1722 text = render.render_full(report)
1723 self.assertNotIn("[]()", text)
1724
1725 def test_all_items_by_source_whitespace_url_renders_no_url_line(self):
1726 report = sample_report()
1727 report.items_by_source["grounding"][0].url = " \t\r\n"
1728 text = render.render_full(report)
1729 all_items = text.split("## All Items by Source", 1)[1]
1730 self.assertNotIn("URL:", all_items)
1731 self.assertNotIn("[]()", all_items)
1732
1733 def test_all_items_by_source_unsafe_url_is_escaped(self):
1734 report = sample_report()
1735 report.items_by_source["grounding"][0].url = "https://example.test/[click](javascript:alert(1))"
1736 text = render.render_full(report)
1737 all_items = text.split("## All Items by Source", 1)[1]
1738 url_lines = [line for line in all_items.splitlines() if "click" in line]
1739 self.assertEqual(len(url_lines), 1)
1740 self.assertNotIn("](", url_lines[0])
1741 self.assertIn(r"\[click\]\(javascript\:alert\(1\)\)", url_lines[0])
1742
1743 def test_all_items_by_source_newline_url_cannot_create_structure(self):
1744 report = sample_report()
1745 report.items_by_source["grounding"][0].url = "https://example.test/x\n## forged heading\n- forged item"
1746 text = render.render_full(report)
1747 self.assertNotIn("\n## forged heading", text)
1748 self.assertNotIn("\n- forged item", text)
1749 self.assertNotIn("\n https://example.test/x", text)
1750
1751 def test_all_items_by_source_rejected_url_is_inert_plain_text(self):
1752 report = sample_report()
1753 report.items_by_source["reddit"][0].url = "[click](javascript:alert)"
1754 text = render.render_full(report)
1755 self.assertIn(r" \[click\]\(javascript\:alert\)", text)
1756 self.assertNotIn("[click](javascript:alert)", text)
1757
1758 def test_render_candidate_url_is_markdown_link(self):
1759 candidate = schema.Candidate(
1760 candidate_id="c1", item_id="i1", source="reddit",
1761 title="Grounded result", url="https://example.com/thread",
1762 snippet="A snippet.", subquery_labels=["primary"],
1763 native_ranks={"reddit": 1}, local_relevance=1.0, freshness=1,
1764 engagement=100, source_quality=1.0, rrf_score=1.0,
1765 sources=["reddit"], source_items=[],
1766 )
1767 text = "\n".join(render._render_candidate(candidate, "1."))
1768 self.assertIn(
1769 "URL: [https://example.com/thread](https://example.com/thread)", text
1770 )
1771
1772 def test_render_candidate_rejected_url_is_inert_plain_text(self):
1773 candidate = schema.Candidate(
1774 candidate_id="c1", item_id="i1", source="reddit",
1775 title="Grounded result", url="<javascript:alert(1)>",
1776 snippet="A snippet.", subquery_labels=["primary"],
1777 native_ranks={"reddit": 1}, local_relevance=1.0, freshness=1,
1778 engagement=100, source_quality=1.0, rrf_score=1.0,
1779 sources=["reddit"], source_items=[],
1780 )
1781 text = "\n".join(render._render_candidate(candidate, "1."))
1782 self.assertIn(r"URL: &lt;javascript\:alert\(1\)&gt;", text)
1783 self.assertNotIn("<javascript:", text)
1784
1785 def test_render_candidate_empty_url_renders_no_url_line(self):
1786 """Regression: unlike the item-loop location, _render_candidate had
1787 no guard at all -- an empty candidate.url produced a broken `[]()`."""
1788 candidate = schema.Candidate(
1789 candidate_id="c1", item_id="i1", source="perplexity",
1790 title="Grounded result", url="",
1791 snippet="A snippet.", subquery_labels=["primary"],
1792 native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
1793 engagement=100, source_quality=1.0, rrf_score=1.0,
1794 sources=["perplexity"], source_items=[],
1795 )
1796 text = "\n".join(render._render_candidate(candidate, "1."))
1797 self.assertNotIn("[]()", text)
1798 self.assertNotIn("URL:", text)
1799
1800 def test_render_candidate_whitespace_url_renders_no_url_line(self):
1801 candidate = schema.Candidate(
1802 candidate_id="c1", item_id="i1", source="perplexity",
1803 title="Grounded result", url=" \t\r\n",
1804 snippet="A snippet.", subquery_labels=["primary"],
1805 native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
1806 engagement=100, source_quality=1.0, rrf_score=1.0,
1807 sources=["perplexity"], source_items=[],
1808 )
1809 text = "\n".join(render._render_candidate(candidate, "1."))
1810 self.assertNotIn("URL:", text)
1811 self.assertNotIn("[]()", text)
1812
1813 def test_render_candidate_unsafe_url_is_escaped(self):
1814 candidate = schema.Candidate(
1815 candidate_id="c1", item_id="i1", source="perplexity",
1816 title="Grounded result", url="javascript:alert(1)",
1817 snippet="A snippet.", subquery_labels=["primary"],
1818 native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
1819 engagement=100, source_quality=1.0, rrf_score=1.0,
1820 sources=["perplexity"], source_items=[],
1821 )
1822 text = "\n".join(render._render_candidate(candidate, "1."))
1823 self.assertIn(r"URL: javascript\:alert\(1\)", text)
1824 self.assertNotIn("](", text)
1825
1826 def test_render_candidate_newline_url_cannot_create_structure(self):
1827 candidate = schema.Candidate(
1828 candidate_id="c1", item_id="i1", source="perplexity",
1829 title="Grounded result", url="https://example.test/x\n## forged heading",
1830 snippet="A snippet.", subquery_labels=["primary"],
1831 native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
1832 engagement=100, source_quality=1.0, rrf_score=1.0,
1833 sources=["perplexity"], source_items=[],
1834 )
1835 text = "\n".join(render._render_candidate(candidate, "1."))
1836 self.assertNotIn("\n## forged heading", text)
1837 self.assertNotIn("URL: [", text)
1838
1839
1840 class FooterPluralizationTests(unittest.TestCase):
1841 def test_story_pluralizes_to_stories(self):
1842 self.assertEqual(
1843 render._footer_line_for_source("🟡", "HN", 15, "story", ""),
1844 "🟡 HN: 15 stories",
1845 )
1846 self.assertEqual(
1847 render._footer_line_for_source("🟡", "HN", 1, "story", ""),
1848 "🟡 HN: 1 story",
1849 )
1850
1851 def test_regular_nouns_keep_plain_s(self):
1852 self.assertEqual(
1853 render._footer_line_for_source("🟠", "Reddit", 2, "thread", "5 upvotes"),
1854 "🟠 Reddit: 2 threads │ 5 upvotes",
1855 )
1856 self.assertEqual(
1857 render._footer_line_for_source("🔵", "X", 1, "post", ""),
1858 "🔵 X: 1 post",
1859 )
1860 self.assertEqual(
1861 render._footer_line_for_source("🔴", "YouTube", 0, "video", ""),
1862 "🔴 YouTube: 0 videos",
1863 )
1864
1865 def test_every_footer_noun_pluralizes_sanely(self):
1866 for _key, _emoji, _label, noun, _eng in render._FOOTER_SOURCES:
1867 plural = render._footer_line_for_source("x", "L", 2, noun, "").split("2 ", 1)[1]
1868 if noun.endswith("y") and noun[-2] not in "aeiou":
1869 self.assertEqual(plural, noun[:-1] + "ies")
1870 else:
1871 self.assertEqual(plural, noun + "s")
1872
1872 lines PYTHON