返回 last30days-skill
test_pr27_cli_render_contracts_polymarket_quotes.py
根目录 / tests / test_pr27_cli_render_contracts_polymarket_quotes.py
1 """Regression tests for PR 27 CLI contracts and Polymarket/quote-pool rendering.
2
3 Covers:
4 - HIGH-008: `--search stocktwits` and `LAST30DAYS_DEFAULT_SEARCH=stocktwits`
5 - HIGH-009: `--emit=brief` rejected pre-run on comparison / competitor runs and cached freshness
6 - HIGH-010: comparison `--save-dir` saves full raw evidence to main `{slug}-raw.md`
7 - HIGH-012: normalized `DEFAULT_MEMORY_DIR` checks keep store, library search/feed/context, and save_output unified
8 - HIGH-041: `_polymarket_matched_part` label-first matching and displayed `[:3]` slice deduplication
9 - HIGH-042: `_polymarket_top_markets` skips unpriced/impossible_set/duplicate items before applying `limit`
10 - HIGH-043: `_render_top_comments` grounds on stripped quote text and exact whole-word matching for short comparison entities
11 """
12
13 from __future__ import annotations
14
15 import argparse
16 import json
17 import os
18 import sys
19 from pathlib import Path
20 from unittest import mock
21
22 import pytest
23
24 import last30days as cli
25 from lib import library, library_index, normalize, pipeline, polymarket, render, schema
26
27
28 def _make_item(
29 item_id: str,
30 *,
31 source: str = "reddit",
32 title: str = "Title",
33 url: str = "https://www.reddit.com/r/test/comments/abc/title/",
34 author: str = "op",
35 score: int = 500,
36 snippet: str = "Snippet text",
37 metadata: dict | None = None,
38 ) -> schema.SourceItem:
39 return schema.SourceItem(
40 item_id=item_id,
41 source=source,
42 title=title,
43 body=snippet,
44 url=url,
45 author=author,
46 container="test",
47 published_at="2026-11-10",
48 date_confidence="high",
49 engagement={"score": score},
50 snippet=snippet,
51 metadata=metadata or {},
52 )
53
54
55 def _make_candidate(
56 cand_id: str,
57 item: schema.SourceItem,
58 *,
59 final_score: float = 80.0,
60 ) -> schema.Candidate:
61 cand = schema.Candidate(
62 candidate_id=cand_id,
63 item_id=item.item_id,
64 source=item.source,
65 title=item.title,
66 url=item.url,
67 snippet=item.snippet,
68 subquery_labels=["primary"],
69 native_ranks={f"primary:{item.source}": 1},
70 local_relevance=0.9,
71 freshness=90,
72 engagement=80,
73 source_quality=0.8,
74 rrf_score=0.02,
75 sources=[item.source],
76 source_items=[item],
77 )
78 cand.final_score = final_score
79 return cand
80
81
82 def _make_report(
83 topic: str,
84 *,
85 candidates: list[schema.Candidate] | None = None,
86 clusters: list[schema.Cluster] | None = None,
87 items_by_source: dict[str, list[schema.SourceItem]] | None = None,
88 resolved: dict | None = None,
89 ) -> schema.Report:
90 report = schema.Report(
91 topic=topic,
92 range_from="2026-10-15",
93 range_to="2026-11-15",
94 generated_at="2026-11-15T12:00:00Z",
95 provider_runtime=schema.ProviderRuntime(
96 reasoning_provider="local",
97 planner_model="fixture",
98 rerank_model="fixture",
99 ),
100 query_plan=schema.QueryPlan(
101 intent="general",
102 freshness_mode="balanced_recent",
103 cluster_mode="story",
104 raw_topic=topic,
105 subqueries=[],
106 source_weights={},
107 ),
108 clusters=list(clusters or []),
109 ranked_candidates=list(candidates or []),
110 items_by_source=dict(items_by_source or {}),
111 errors_by_source={},
112 )
113 if resolved is not None:
114 report.artifacts["resolved"] = resolved
115 return report
116
117
118 # ---------------------------------------------------------------------------
119 # HIGH-008: --search stocktwits & LAST30DAYS_DEFAULT_SEARCH=stocktwits
120 # ---------------------------------------------------------------------------
121
122
123 class TestHigh008StocktwitsSearchFlag:
124 def test_parse_search_flag_accepts_stocktwits_alone_and_combined(self):
125 assert cli.parse_search_flag("stocktwits") == ["stocktwits"]
126 assert cli.parse_search_flag("reddit,stocktwits") == ["reddit", "stocktwits"]
127 assert cli.parse_search_flag("STOCKTWITS,hn") == ["stocktwits", "hackernews"]
128
129 def test_default_search_config_accepts_stocktwits(self):
130 resolved = cli.resolve_requested_sources(
131 None, {"LAST30DAYS_DEFAULT_SEARCH": "reddit,stocktwits"}
132 )
133 assert resolved == ["reddit", "stocktwits"]
134
135 def test_unknown_source_still_rejected(self):
136 with pytest.raises(SystemExit, match="Unknown search source in --search: bogus"):
137 cli.parse_search_flag("reddit,bogus")
138
139 def test_mock_available_sources_unchanged_without_stocktwits(self):
140 assert "stocktwits" in pipeline.KNOWN_SEARCH_SOURCES
141 assert "stocktwits" not in pipeline.MOCK_AVAILABLE_SOURCES
142
143
144 # ---------------------------------------------------------------------------
145 # HIGH-009: --emit=brief rejected pre-run on comparison / competitor runs
146 # ---------------------------------------------------------------------------
147
148
149 class TestHigh009ComparisonEmitBriefPreRunGate:
150 @pytest.mark.parametrize(
151 "argv",
152 [
153 ["OpenAI vs Anthropic", "--emit=brief"],
154 ["OpenAI", "--competitors", "2", "--emit=brief"],
155 ["OpenAI", "--competitors-list", "Anthropic,xAI", "--emit=brief"],
156 ["OpenAI", "--competitors-plan", '{"Anthropic":{}}', "--emit=brief"],
157 ],
158 )
159 def test_live_comparison_brief_fails_fast_before_pipeline(
160 self, argv: list[str], monkeypatch, capsys
161 ):
162 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
163 monkeypatch.setattr(cli.env, "get_config", lambda **_k: {})
164 monkeypatch.setattr(cli.env, "hosted_backend_configured", lambda: False)
165 monkeypatch.setattr(
166 cli.pipeline,
167 "diagnose",
168 lambda *a, **k: (_ for _ in ()).throw(AssertionError("diagnose must not run")),
169 )
170 monkeypatch.setattr(
171 cli.pipeline,
172 "run",
173 lambda *a, **k: (_ for _ in ()).throw(AssertionError("pipeline.run must not run")),
174 )
175 monkeypatch.setattr(sys, "argv", ["last30days.py", *argv])
176
177 rc = cli.main()
178
179 assert rc == 2
180 assert "--emit=brief is not supported for comparison" in capsys.readouterr().err
181
182 def test_cached_freshness_comparison_brief_fails_before_verify(
183 self, monkeypatch, capsys
184 ):
185 report_a = _make_report("OpenAI")
186 report_b = _make_report("Anthropic")
187 cached = cli._CachedReport(
188 report=report_a,
189 entity_reports=[("OpenAI", report_a), ("Anthropic", report_b)],
190 path=Path("/tmp/fake-last-report.json"),
191 x_envelope_sha256="",
192 fingerprint="a" * 32,
193 )
194 monkeypatch.setattr(cli, "_load_followup_report", lambda _a, _c: cached)
195 monkeypatch.setattr(
196 cli,
197 "_verify_report_set",
198 lambda *a, **k: (_ for _ in ()).throw(AssertionError("verify must not run")),
199 )
200 args = cli.build_parser().parse_args(["--verify-freshness", "--emit=brief"])
201
202 rc = cli._run_cached_freshness(args, {})
203
204 assert rc == 2
205 assert "--emit=brief is not supported for comparison" in capsys.readouterr().err
206
207 def test_render_save_and_print_comparison_brief_returns_exit_2(self, capsys):
208 report_a = _make_report("OpenAI")
209 report_b = _make_report("Anthropic")
210 args = cli.build_parser().parse_args(["OpenAI vs Anthropic", "--emit=brief"])
211
212 rc = cli._render_save_and_print(
213 args,
214 report_a,
215 [("OpenAI", report_a), ("Anthropic", report_b)],
216 None,
217 {},
218 )
219
220 assert rc == 2
221 assert "--emit=brief is not supported for comparison" in capsys.readouterr().err
222
223 def test_single_topic_brief_still_allowed(self, capsys):
224 report = _make_report("OpenAI")
225 args = cli.build_parser().parse_args(["OpenAI", "--emit=brief"])
226
227 rc = cli._render_save_and_print(args, report, None, None, {})
228
229 assert rc == 0
230 assert capsys.readouterr().out.strip()
231
232 def test_diagnose_with_vs_topic_and_brief_still_succeeds(self, monkeypatch, capsys):
233 monkeypatch.setattr(cli.env, "get_config", lambda **_k: {})
234 monkeypatch.setattr(cli.env, "hosted_backend_configured", lambda: False)
235 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *a, **k: {"available_sources": ["reddit"]})
236 monkeypatch.setattr(
237 sys, "argv", ["last30days.py", "OpenAI vs Anthropic", "--emit=brief", "--diagnose"]
238 )
239
240 rc = cli.main()
241
242 assert rc == 0
243 payload = json.loads(capsys.readouterr().out)
244 assert payload["available_sources"] == ["reddit"]
245
246
247 # ---------------------------------------------------------------------------
248 # HIGH-010: comparison --save-dir writes full raw evidence to main {slug}-raw.md
249 # ---------------------------------------------------------------------------
250
251
252 class TestHigh010ComparisonMainRawFullEvidence:
253 def _build_rich_entity_report(self, entity: str) -> schema.Report:
254 candidates: list[schema.Candidate] = []
255 clusters: list[schema.Cluster] = []
256 items: list[schema.SourceItem] = []
257 # Create 14 clusters/items so render_full carries items beyond compact truncation.
258 for idx in range(1, 15):
259 item = _make_item(
260 f"{entity.lower()}-item-{idx}",
261 title=f"{entity} exclusive story number {idx}",
262 url=f"https://www.reddit.com/r/tech/comments/{entity.lower()}{idx}/story/",
263 snippet=f"Detailed evidence body for {entity} item {idx}.",
264 )
265 cand = _make_candidate(
266 f"{entity.lower()}-cand-{idx}", item, final_score=100.0 - idx
267 )
268 cluster = schema.Cluster(
269 cluster_id=f"{entity.lower()}-cluster-{idx}",
270 title=f"{entity} storyline {idx}",
271 candidate_ids=[cand.candidate_id],
272 representative_ids=[cand.candidate_id],
273 sources=["reddit"],
274 score=100.0 - idx,
275 )
276 items.append(item)
277 candidates.append(cand)
278 clusters.append(cluster)
279 return _make_report(
280 entity,
281 candidates=candidates,
282 clusters=clusters,
283 items_by_source={"reddit": items},
284 resolved={
285 "entity": entity,
286 "x_handle": entity.lower(),
287 "subreddits": [entity.lower()],
288 "github_user": "",
289 "github_repos": [],
290 "trustpilot_domain": "",
291 "context": "",
292 },
293 )
294
295 @pytest.mark.parametrize("emit", ["compact", "md", "context"])
296 def test_comparison_markdown_save_writes_full_raw_for_main_and_comparison_to_stdout(
297 self, emit: str, tmp_path: Path, capsys
298 ):
299 main_report = self._build_rich_entity_report("OpenAI")
300 peer_report = self._build_rich_entity_report("Anthropic")
301 entity_reports = [("OpenAI", main_report), ("Anthropic", peer_report)]
302 args = cli.build_parser().parse_args(
303 ["OpenAI vs Anthropic", f"--emit={emit}", "--save-dir", str(tmp_path)]
304 )
305
306 rc = cli._render_save_and_print(args, main_report, entity_reports, None, {})
307 captured = capsys.readouterr()
308
309 assert rc == 0
310 main_file = tmp_path / "openai-raw.md"
311 peer_file = tmp_path / "anthropic-raw.md"
312 assert main_file.is_file()
313 assert peer_file.is_file()
314
315 main_text = main_file.read_text(encoding="utf-8")
316 peer_text = peer_file.read_text(encoding="utf-8")
317
318 # Main raw file carries full render_full evidence (matching peer raw file).
319 assert "## Resolved Entities" in main_text
320 assert "**OpenAI**" in main_text
321 assert "## All Items by Source" in main_text
322 assert "OpenAI exclusive story number 14" in main_text
323 assert "| Dimension | OpenAI | Anthropic |" not in main_text
324
325 assert "## Resolved Entities" in peer_text
326 assert "**Anthropic**" in peer_text
327 assert "Anthropic exclusive story number 14" in peer_text
328
329 # Stdout still renders the merged comparison output citing the saved path.
330 if emit == "context":
331 assert "Comparison: OpenAI vs Anthropic" in captured.out
332 else:
333 assert "| Dimension | OpenAI | Anthropic |" in captured.out
334 assert "openai-raw.md" in captured.out
335
336 def test_comparison_json_and_html_saves_preserve_wire_format(self, tmp_path: Path):
337 main_report = self._build_rich_entity_report("OpenAI")
338 peer_report = self._build_rich_entity_report("Anthropic")
339 entity_reports = [("OpenAI", main_report), ("Anthropic", peer_report)]
340
341 json_dir = tmp_path / "json_out"
342 args_json = cli.build_parser().parse_args(
343 ["OpenAI vs Anthropic", "--emit=json", "--save-dir", str(json_dir)]
344 )
345 assert cli._render_save_and_print(args_json, main_report, entity_reports, None, {}) == 0
346 saved_json = json.loads((json_dir / "openai-raw.json").read_text(encoding="utf-8"))
347 assert saved_json["comparison"] is True
348 assert saved_json["entities"] == ["OpenAI", "Anthropic"]
349
350 html_dir = tmp_path / "html_out"
351 args_html = cli.build_parser().parse_args(
352 ["OpenAI vs Anthropic", "--emit=html", "--save-dir", str(html_dir)]
353 )
354 assert cli._render_save_and_print(args_html, main_report, entity_reports, None, {}) == 0
355 saved_html = (html_dir / "openai-vs-anthropic-raw-html.html").read_text(encoding="utf-8")
356 assert "<html" in saved_html.lower()
357 assert "Anthropic" in saved_html
358
359
360 # ---------------------------------------------------------------------------
361 # HIGH-012: Normalized DEFAULT_MEMORY_DIR checks keep library/store unified
362 # ---------------------------------------------------------------------------
363
364
365 class TestHigh012DefaultMemoryDirNormalization:
366 def test_is_scoped_save_dir_normalizes_default_paths_and_symlinks(
367 self, tmp_path: Path, monkeypatch
368 ):
369 default_dir = tmp_path / "Documents" / "Last30Days"
370 default_dir.mkdir(parents=True)
371 symlink_dir = tmp_path / "link-to-default"
372 symlink_dir.symlink_to(default_dir)
373 scoped_dir = tmp_path / "client-a"
374 scoped_dir.mkdir()
375
376 monkeypatch.setattr(library, "DEFAULT_MEMORY_DIR", default_dir)
377
378 assert pipeline.is_scoped_save_dir(None) is False
379 assert pipeline.is_scoped_save_dir("") is False
380 assert pipeline.is_scoped_save_dir(" ") is True
381 assert pipeline.is_scoped_save_dir(default_dir) is False
382 assert pipeline.is_scoped_save_dir(str(default_dir) + os.sep) is False
383 assert pipeline.is_scoped_save_dir(str(default_dir / "." / ".." / "Last30Days")) is False
384 assert pipeline.is_scoped_save_dir(symlink_dir) is False
385 assert pipeline.is_scoped_save_dir(scoped_dir) is True
386
387 assert cli._scoped_store_db(argparse.Namespace(save_dir=str(default_dir))) is None
388 assert cli._scoped_store_db(argparse.Namespace(save_dir=str(symlink_dir))) is None
389 assert cli._scoped_store_db(argparse.Namespace(save_dir=str(scoped_dir))) == (
390 scoped_dir.resolve() / "research.db"
391 )
392
393 def test_library_context_index_path_and_loader_unify_default_memory_dir(
394 self, tmp_path: Path, monkeypatch
395 ):
396 default_dir = tmp_path / "Documents" / "Last30Days"
397 default_dir.mkdir(parents=True)
398 scoped_dir = tmp_path / "client-a"
399 scoped_dir.mkdir()
400
401 monkeypatch.setattr(library, "DEFAULT_MEMORY_DIR", default_dir)
402 cfg = {"LAST30DAYS_LIBRARY_CONTEXT": "on"}
403
404 non_canonical_default = str(default_dir / ".." / "Last30Days")
405 assert (
406 pipeline.library_context_index_path(cfg, non_canonical_default)
407 == library_index.DEFAULT_LIBRARY_DB
408 )
409 assert pipeline.library_context_index_path(cfg, str(scoped_dir)) == (
410 scoped_dir.resolve() / ".last30days-library.db"
411 )
412 assert pipeline.library_context_index_path(cfg, "") is None
413
414 sync_calls: list[tuple[Path, Path, Path]] = []
415 search_calls: list[tuple[Path, Path]] = []
416
417 def fake_sync(memory_dir, briefs_dir, *, db_path):
418 sync_calls.append((Path(memory_dir), Path(briefs_dir), Path(db_path)))
419
420 def fake_search(query_text, *, limit, db_path, store_db_path):
421 search_calls.append((Path(db_path), Path(store_db_path)))
422 return []
423
424 monkeypatch.setattr(pipeline.library_index, "sync_library", fake_sync)
425 monkeypatch.setattr(pipeline.library_index, "search", fake_search)
426
427 pipeline._load_library_context(
428 topic="MCP servers",
429 config=cfg,
430 mock=False,
431 internal_subrun=False,
432 x_handle=None,
433 github_user=None,
434 github_repos=None,
435 save_dir=non_canonical_default,
436 )
437
438 assert sync_calls == [
439 (
440 Path(non_canonical_default),
441 library.DEFAULT_BRIEFS_DIR,
442 library_index.DEFAULT_LIBRARY_DB,
443 )
444 ]
445 assert search_calls == [
446 (library_index.DEFAULT_LIBRARY_DB, library_index.DEFAULT_STORE_DB)
447 ]
448
449 def test_library_search_feed_and_save_output_unify_on_default_memory_dir(
450 self, tmp_path: Path, monkeypatch
451 ):
452 default_dir = tmp_path / "Documents" / "Last30Days"
453 default_dir.mkdir(parents=True)
454 non_canonical = str(default_dir / "." / ".." / "Last30Days")
455 monkeypatch.setattr(library, "DEFAULT_MEMORY_DIR", default_dir)
456
457 # 1. library search via LAST30DAYS_MEMORY_DIR == DEFAULT_MEMORY_DIR
458 search_kwargs: dict[str, Path] = {}
459
460 def fake_sync_and_search(query, *, memory_dir, briefs_dir, db_path, store_db_path):
461 search_kwargs["memory_dir"] = Path(memory_dir)
462 search_kwargs["briefs_dir"] = Path(briefs_dir)
463 search_kwargs["db_path"] = Path(db_path)
464 search_kwargs["store_db_path"] = Path(store_db_path)
465 return [], mock.Mock(notes=[], rebuilt=False)
466
467 monkeypatch.setattr(library_index, "sync_and_search", fake_sync_and_search)
468 monkeypatch.setenv("LAST30DAYS_MEMORY_DIR", non_canonical)
469 monkeypatch.setattr(cli.env, "get_config", lambda **_k: {})
470 monkeypatch.setattr(sys, "argv", ["last30days.py", "library", "search", "MCP"])
471 assert cli.main() == 0
472 assert search_kwargs["briefs_dir"] == library.DEFAULT_BRIEFS_DIR
473 assert search_kwargs["db_path"] == library_index.DEFAULT_LIBRARY_DB
474 assert search_kwargs["store_db_path"] == library_index.DEFAULT_STORE_DB
475
476 # 2. library feed with --save-dir == DEFAULT_MEMORY_DIR includes DEFAULT_BRIEFS_DIR
477 scanned_briefs: list[Path] = []
478
479 def fake_scan_library(memory_dir, briefs_dir):
480 scanned_briefs.append(Path(briefs_dir))
481 return [], []
482
483 monkeypatch.setattr(library, "scan_library", fake_scan_library)
484 args_feed = cli.build_parser().parse_args(
485 ["library", "feed", "--save-dir", non_canonical]
486 )
487 assert cli._run_library_feed(args_feed, {}) == 0
488 assert scanned_briefs == [library.DEFAULT_BRIEFS_DIR]
489
490 # 3. save_output into DEFAULT_MEMORY_DIR syncs default index (without scoped briefs override)
491 sync_calls: list[tuple] = []
492 monkeypatch.setattr(
493 library_index,
494 "sync_library",
495 lambda *a, **k: sync_calls.append((a, k)),
496 )
497 report = _make_report("Test Topic")
498 saved = cli.save_output(report, "md", non_canonical)
499 assert saved.is_file()
500 assert sync_calls == [((default_dir.resolve(),), {})]
501
502 def test_whitespace_only_save_dir_rejected_explicitly_and_never_uses_shared_data(
503 self, tmp_path: Path, monkeypatch, capsys
504 ):
505 from lib import env as env_mod
506 from lib import html_publish
507
508 default_dir = tmp_path / "Documents" / "Last30Days"
509 default_dir.mkdir(parents=True)
510 work_dir = tmp_path / "cwd"
511 work_dir.mkdir()
512 monkeypatch.chdir(work_dir)
513 monkeypatch.setattr(library, "DEFAULT_MEMORY_DIR", default_dir)
514 monkeypatch.setattr(cli.env, "get_config", lambda **_k: {})
515
516 # 1. Core helpers reject or fail closed on whitespace-only values.
517 assert pipeline.is_blank_save_dir(" ") is True
518 assert pipeline.is_blank_save_dir("") is False
519 assert pipeline.is_blank_save_dir(None) is False
520 assert pipeline.is_scoped_save_dir(" ") is True
521 assert (
522 pipeline.library_context_index_path({"LAST30DAYS_LIBRARY_CONTEXT": "on"}, " ")
523 is None
524 )
525 with pytest.raises(ValueError, match="whitespace-only"):
526 cli._scoped_store_db(argparse.Namespace(save_dir=" "))
527 with pytest.raises(ValueError, match="whitespace-only"):
528 env_mod.resolve_memory_dir(" ")
529 with pytest.raises(ValueError, match="non-empty save_dir"):
530 cli.save_output(_make_report("Blank"), "md", " ")
531 assert not (work_dir / " ").exists()
532
533 # 2. --resolve-save-dir rejects whitespace-only flag and env var with exit 2.
534 monkeypatch.setattr(
535 sys, "argv", ["last30days.py", "--resolve-save-dir", "--save-dir", " "]
536 )
537 assert cli.main() == 2
538 assert "whitespace-only" in capsys.readouterr().err
539
540 monkeypatch.setenv("LAST30DAYS_MEMORY_DIR", " ")
541 monkeypatch.setattr(sys, "argv", ["last30days.py", "--resolve-save-dir"])
542 assert cli.main() == 2
543 assert "whitespace-only" in capsys.readouterr().err
544
545 # 3. library search via LAST30DAYS_MEMORY_DIR=" " exits 2 without syncing/reading shared DB.
546 monkeypatch.setattr(
547 library_index,
548 "sync_and_search",
549 lambda *a, **k: (_ for _ in ()).throw(AssertionError("sync_and_search must not run")),
550 )
551 monkeypatch.setattr(sys, "argv", ["last30days.py", "library", "search", "MCP"])
552 assert cli.main() == 2
553 assert "whitespace-only" in capsys.readouterr().err
554
555 # 4. library feed --publish with --save-dir " " exits 2 and publishes/writes nothing.
556 monkeypatch.delenv("LAST30DAYS_MEMORY_DIR", raising=False)
557 monkeypatch.setattr(
558 library,
559 "scan_library",
560 lambda *a, **k: (_ for _ in ()).throw(AssertionError("scan_library must not run")),
561 )
562 monkeypatch.setattr(
563 html_publish,
564 "publish_html",
565 lambda *a, **k: (_ for _ in ()).throw(AssertionError("publish_html must not run")),
566 )
567 args_feed = cli.build_parser().parse_args(
568 ["library", "feed", "--publish", "--save-dir", " "]
569 )
570 assert cli._run_library_feed(args_feed, {}) == 2
571 assert "whitespace-only" in capsys.readouterr().err
572 assert not (default_dir / "index.html").exists()
573 assert not (work_dir / " ").exists()
574
575 # 5. library harvest with --save-dir " " exits 2.
576 args_harvest = cli.build_parser().parse_args(
577 ["library", "harvest", "--save-dir", " "]
578 )
579 assert cli._run_library_harvest(args_harvest, {}) == 2
580 assert "whitespace-only" in capsys.readouterr().err
581
582 # 6. _load_library_context with save_dir=" " is a safe no-op (never touches shared DB).
583 monkeypatch.setattr(
584 pipeline.library_index,
585 "sync_library",
586 lambda *a, **k: (_ for _ in ()).throw(AssertionError("sync_library must not run")),
587 )
588 contexts, err = pipeline._load_library_context(
589 topic="MCP",
590 config={"LAST30DAYS_LIBRARY_CONTEXT": "on"},
591 mock=False,
592 internal_subrun=False,
593 x_handle=None,
594 github_user=None,
595 github_repos=None,
596 save_dir=" ",
597 )
598 assert contexts == []
599 assert err is None
600
601 # 7. Research run with LAST30DAYS_MEMORY_DIR=" " exits 2 before pipeline.run.
602 monkeypatch.setenv("LAST30DAYS_MEMORY_DIR", " ")
603 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
604 monkeypatch.setattr(cli.env, "hosted_backend_configured", lambda: False)
605 monkeypatch.setattr(
606 cli.pipeline,
607 "run",
608 lambda *a, **k: (_ for _ in ()).throw(AssertionError("pipeline.run must not run")),
609 )
610 monkeypatch.setattr(sys, "argv", ["last30days.py", "OpenAI", "--mock"])
611 assert cli.main() == 2
612 assert "whitespace-only" in capsys.readouterr().err
613
614 def test_diagnostics_still_run_when_memory_dir_is_whitespace_only(
615 self, monkeypatch, capsys
616 ):
617 from lib import doctor as doctor_mod
618
619 monkeypatch.setenv("LAST30DAYS_MEMORY_DIR", " ")
620 monkeypatch.setattr(cli.env, "get_config", lambda **_k: {"LAST30DAYS_MEMORY_DIR": " "})
621 monkeypatch.setattr(cli.env, "hosted_backend_configured", lambda: False)
622
623 # 1. --diagnose succeeds with exit 0 and emits JSON.
624 monkeypatch.setattr(
625 cli.pipeline,
626 "diagnose",
627 lambda *a, **k: {"available_sources": ["reddit"]},
628 )
629 monkeypatch.setattr(sys, "argv", ["last30days.py", "--diagnose"])
630 assert cli.main() == 0
631 diag_out = json.loads(capsys.readouterr().out)
632 assert diag_out["available_sources"] == ["reddit"]
633
634 # 2. doctor --postmortem --json succeeds with exit 0 and reaches doctor.run.
635 doctor_calls: list[dict] = []
636
637 def fake_doctor_run(config, *, emit_json, cached, postmortem, probe):
638 doctor_calls.append(
639 {
640 "memory_dir": config.get("LAST30DAYS_MEMORY_DIR"),
641 "emit_json": emit_json,
642 "postmortem": postmortem,
643 }
644 )
645 print(json.dumps({"ok": True, "memory_dir": config.get("LAST30DAYS_MEMORY_DIR")}))
646 return 0
647
648 monkeypatch.setattr(doctor_mod, "run", fake_doctor_run)
649 monkeypatch.setattr(
650 sys, "argv", ["last30days.py", "doctor", "--postmortem", "--json"]
651 )
652 assert cli.main() == 0
653 doc_out = json.loads(capsys.readouterr().out)
654 assert doc_out == {"ok": True, "memory_dir": " "}
655 assert doctor_calls == [{"memory_dir": " ", "emit_json": True, "postmortem": True}]
656
657 def test_trailing_space_save_dir_preserved_verbatim(
658 self, tmp_path: Path, monkeypatch
659 ):
660 from lib import env as env_mod
661
662 default_dir = tmp_path / "Documents" / "Last30Days"
663 default_dir.mkdir(parents=True)
664 trailing_dir = tmp_path / "client dir "
665 stripped_dir = tmp_path / "client dir"
666 monkeypatch.setattr(library, "DEFAULT_MEMORY_DIR", default_dir)
667
668 raw = str(trailing_dir)
669 assert pipeline.is_blank_save_dir(raw) is False
670 assert pipeline.is_scoped_save_dir(raw) is True
671 assert env_mod.resolve_memory_dir(raw) == str(trailing_dir.absolute())
672 assert pipeline.scoped_store_db_path(raw) == trailing_dir.resolve() / "research.db"
673 assert pipeline.library_context_index_path(
674 {"LAST30DAYS_LIBRARY_CONTEXT": "on"}, raw
675 ) == trailing_dir.resolve() / ".last30days-library.db"
676
677 # Saving writes to the exact directory with the trailing space, not the stripped sibling.
678 monkeypatch.setattr(library_index, "sync_library", lambda *a, **k: None)
679 saved = cli.save_output(_make_report("Space Topic"), "md", raw)
680 assert saved.parent == trailing_dir.resolve()
681 assert saved.is_file()
682 assert not stripped_dir.exists()
683
684 # library feed scans and writes into the exact trailing-space directory as a scoped library.
685 scanned: list[tuple[Path, Path]] = []
686
687 def fake_scan(memory_dir, briefs_dir):
688 scanned.append((Path(memory_dir), Path(briefs_dir)))
689 return [], []
690
691 monkeypatch.setattr(library, "scan_library", fake_scan)
692 args_feed = cli.build_parser().parse_args(["library", "feed", "--save-dir", raw])
693 assert cli._run_library_feed(args_feed, {}) == 0
694 assert scanned == [(trailing_dir, trailing_dir / "briefings")]
695 assert (trailing_dir / "index.html").is_file()
696 assert not stripped_dir.exists()
697
698 def test_existing_legacy_default_memory_research_db_is_preserved_on_upgrade(
699 self, tmp_path: Path, monkeypatch
700 ):
701 default_dir = tmp_path / "Documents" / "Last30Days"
702 default_dir.mkdir(parents=True)
703 monkeypatch.setattr(library, "DEFAULT_MEMORY_DIR", default_dir)
704
705 # Clean DEFAULT_MEMORY_DIR without research.db -> unified shared store (None).
706 args = argparse.Namespace(save_dir=str(default_dir))
707 assert cli._scoped_store_db(args) is None
708
709 # Existing legacy DEFAULT_MEMORY_DIR/research.db -> preserved across store & search.
710 legacy_db = default_dir / "research.db"
711 legacy_db.write_bytes(b"")
712 assert cli._scoped_store_db(args) == legacy_db.resolve()
713
714 captured_store: list[Path] = []
715
716 def fake_sync_and_search(query, *, memory_dir, briefs_dir, db_path, store_db_path):
717 captured_store.append(Path(store_db_path))
718 return [], mock.Mock(notes=[], rebuilt=False)
719
720 monkeypatch.setattr(library_index, "sync_and_search", fake_sync_and_search)
721 search_args = cli.build_parser().parse_args(
722 ["library", "search", "MCP", "--save-dir", str(default_dir)]
723 )
724 assert cli._run_library_search(search_args, {}, "MCP") == 0
725 assert captured_store == [legacy_db.resolve()]
726
727
728 # ---------------------------------------------------------------------------
729 # HIGH-041: _polymarket_matched_part label-first match & displayed [:3] slice
730 # ---------------------------------------------------------------------------
731
732
733 class TestHigh041PolymarketMatchedPart:
734 def test_tied_price_contender_does_not_steal_rival_move_or_duplicate_self(self):
735 rival = {"label": "Kansas City Chiefs", "price": 0.14, "move": [3.5, "this week"]}
736 subject = {"label": "San Francisco 49ers", "price": 0.14, "move": [-1.5, "this week"]}
737 third = {"label": "Buffalo Bills", "price": 0.12, "move": None}
738 item = _make_item(
739 "pm-1",
740 source="polymarket",
741 title="Pro Football: 2027 Champion",
742 url="https://polymarket.com/event/pro-football-2027",
743 metadata={
744 "odds": {
745 "kind": "outcomes",
746 "subject": "Pro Football: 2027 Champion",
747 "parts": [rival, subject, third],
748 },
749 "matched_market": {
750 "label": "San Francisco 49ers",
751 "price": 0.14,
752 "contender": True,
753 "rank": 2,
754 "race_size": 32,
755 },
756 },
757 )
758
759 line = render._polymarket_odds_line(item, "2026")
760
761 assert line.count("San Francisco 49ers") == 1
762 assert "San Francisco 49ers 14%, #2 of 32 (down 1.5 pts this week)" in line
763 assert "Kansas City Chiefs at 14% (up 3.5 pts this week)" in line
764 assert "Buffalo Bills at 12%" in line
765
766 def test_tied_price_non_contender_outside_top3_not_suppressed_by_rival(self):
767 parts = [
768 {"label": "Kansas City Chiefs", "price": 0.14, "move": [2.0, "today"]},
769 {"label": "Buffalo Bills", "price": 0.12, "move": None},
770 {"label": "Detroit Lions", "price": 0.10, "move": None},
771 ]
772 item = _make_item(
773 "pm-2",
774 source="polymarket",
775 title="Pro Football: 2027 Champion",
776 url="https://polymarket.com/event/pro-football-2027",
777 metadata={
778 "odds": {
779 "kind": "outcomes",
780 "subject": "Pro Football: 2027 Champion",
781 "parts": parts,
782 },
783 "matched_market": {
784 "label": "Baltimore Ravens",
785 "price": 0.14,
786 "contender": False,
787 "rank": 4,
788 "race_size": 32,
789 },
790 },
791 )
792
793 matched = render._polymarket_matched_part(item, parts)
794 assert matched is not None
795 assert matched[0] == "Baltimore Ravens 14%"
796 assert matched[1] is None
797
798 line = render._polymarket_odds_line(item, "2026")
799 assert "Baltimore Ravens 14%" in line
800 assert "Kansas City Chiefs at 14% (up 2 pts today)" in line
801
802 def test_matched_outcome_at_index_3_not_dropped_by_pre_slice_check(self):
803 parts = [
804 {"label": "Team A", "price": 0.30, "move": None},
805 {"label": "Team B", "price": 0.25, "move": None},
806 {"label": "Team C", "price": 0.20, "move": None},
807 {"label": "Team D", "price": 0.10, "move": [1.0, "today"]},
808 ]
809 item = _make_item(
810 "pm-3",
811 source="polymarket",
812 title="Championship Winner",
813 url="https://polymarket.com/event/championship",
814 metadata={
815 "odds": {
816 "kind": "outcomes",
817 "subject": "Championship Winner",
818 "parts": parts,
819 },
820 "matched_market": {
821 "label": "Team D",
822 "price": 0.10,
823 "contender": False,
824 },
825 },
826 )
827
828 line = render._polymarket_odds_line(item, "2026")
829
830 assert "Team D 10%" in line
831 assert "Team A at 30%" in line
832 assert "Team B at 25%" in line
833
834 def test_casefold_whitespace_label_match_and_unlabeled_price_fallback(self):
835 # Case/whitespace difference on labeled entry still deduplicates.
836 entry_labeled = {"label": "San Francisco 49ers", "price": 0.145, "move": [1.0, "today"]}
837 item_labeled = _make_item(
838 "pm-4",
839 source="polymarket",
840 title="NFL Champion",
841 metadata={
842 "matched_market": {
843 "label": " san francisco 49ers ",
844 "price": 0.145,
845 "contender": True,
846 "rank": 1,
847 "race_size": 32,
848 }
849 },
850 )
851 matched = render._polymarket_matched_part(item_labeled, [entry_labeled])
852 assert matched is not None
853 assert matched[1] is entry_labeled
854 assert "(up 1 pt today)" in matched[0]
855
856 # Unlabeled single Yes/No entry still matches via price fallback.
857 entry_unlabeled = {"price": 0.74, "move": [2.0, "today"]}
858 item_single = _make_item(
859 "pm-5",
860 source="polymarket",
861 title="Will Waymo launch in Denver?",
862 metadata={"matched_market": {"label": "", "price": 0.74}},
863 )
864 assert render._polymarket_matched_part(item_single, [entry_unlabeled]) is None
865
866 def test_boolean_rank_and_size_rejected(self):
867 item = _make_item(
868 "pm-bool",
869 source="polymarket",
870 title="NFL Champion",
871 metadata={
872 "matched_market": {
873 "label": "49ers",
874 "price": 0.2,
875 "contender": True,
876 "rank": True,
877 "race_size": True,
878 }
879 },
880 )
881 matched = render._polymarket_matched_part(item, [])
882 assert matched is not None
883 assert "#True" not in matched[0]
884 assert matched[0] == "49ers 20%"
885 # Withheld odds path also rejects bool rank.
886 assert render._polymarket_odds_line(item, "2026") == ""
887
888 def test_49ers_win_total_alternate_label_prints_once_while_distinct_ids_stay_separate(
889 self,
890 ):
891 # Live parser flow: matched_market uses "San Francisco 49ers" while odds["parts"]
892 # labels the same outcome "O 10.5". Both share (market_id, outcome_id), so 93.5%/94%
893 # must NOT be printed twice.
894 event = {
895 "id": "totals",
896 "title": "Pro Football: 2026 Regular Season Win Totals",
897 "slug": "totals",
898 "active": True,
899 "closed": False,
900 "negRisk": False,
901 "volume1mo": 1000,
902 "liquidity": 10000,
903 "updatedAt": "2026-11-16T00:00:00Z",
904 "markets": [
905 {
906 "id": "m-ravens",
907 "question": "Will the Baltimore Ravens win more than 11.5 games in the 2026 NFL Regular Season?",
908 "groupItemTitle": "Baltimore Ravens",
909 "outcomes": '["O 11.5", "U 11.5"]',
910 "outcomePrices": '["0.0585", "0.9415"]',
911 "clobTokenIds": '["tok-rav-o", "tok-rav-u"]',
912 "volume": "8806.7",
913 "volumeNum": 8806.7,
914 "liquidity": "5000",
915 "endDate": "2027-03-01T00:00:00Z",
916 "active": True,
917 "closed": False,
918 },
919 {
920 "id": "m-49ers",
921 "question": "Will the San Francisco 49ers win more than 10.5 games in the 2026 NFL Regular Season?",
922 "groupItemTitle": "San Francisco 49ers",
923 "outcomes": '["O 10.5", "U 10.5"]',
924 "outcomePrices": '["0.935", "0.065"]',
925 "clobTokenIds": '["tok-sf-o", "tok-sf-u"]',
926 "volume": "3555.76",
927 "volumeNum": 3555.76,
928 "liquidity": "5000",
929 "endDate": "2027-03-01T00:00:00Z",
930 "active": True,
931 "closed": False,
932 },
933 ],
934 }
935 [parsed] = polymarket.parse_polymarket_response(
936 {"events": [event]},
937 topic="49ers",
938 to_date="2026-11-16",
939 hints=polymarket.PolymarketHints.coerce(
940 {"kind": "team", "aliases": ["San Francisco 49ers"]}
941 ),
942 )
943 assert parsed["matched_market"]["market_id"] == "m-49ers"
944 assert parsed["matched_market"]["outcome_id"] == "tok-sf-o"
945 assert parsed["odds"]["parts"][0]["market_id"] == "m-49ers"
946 assert parsed["odds"]["parts"][0]["outcome_id"] == "tok-sf-o"
947 assert parsed["odds"]["parts"][1]["outcome_id"] == "tok-sf-u"
948
949 [norm] = normalize.normalize_source_items(
950 "polymarket", [parsed], "2026-10-17", "2026-11-16"
951 )
952 line = render._polymarket_odds_line(norm, "2026")
953 assert "San Francisco 49ers 93.5%" not in line
954 assert "O 10.5 at 94%" in line
955 assert "U 10.5 at 6.5%" in line
956 assert line.count("94%") + line.count("93.5%") == 1
957
958 # Distinct markets with tied 25% prices and distinct IDs never collide.
959 tied_item = _make_item(
960 "pm-tied-ids",
961 source="polymarket",
962 title="Award Winner",
963 metadata={
964 "odds": {
965 "kind": "outcomes",
966 "subject": "Award Winner",
967 "parts": [
968 {"label": "Alice", "price": 0.25, "move": [4.0, "today"], "market_id": "m-alice"},
969 {"label": "Bob", "price": 0.25, "move": [-2.0, "today"], "market_id": "m-bob"},
970 ],
971 },
972 "matched_market": {
973 "label": "Bob",
974 "price": 0.25,
975 "contender": True,
976 "rank": 2,
977 "race_size": 10,
978 "market_id": "m-bob",
979 },
980 },
981 )
982 tied_line = render._polymarket_odds_line(tied_item, "2026")
983 assert tied_line.count("Bob") == 1
984 assert "Bob 25%, #2 of 10 (down 2 pts today)" in tied_line
985 assert "Alice at 25% (up 4 pts today)" in tied_line
986
987 # Same market with tied 50%/50% outcomes matches ONLY the matching outcome_id.
988 tied_outcomes = _make_item(
989 "pm-tied-outcomes",
990 source="polymarket",
991 title="Win Total",
992 metadata={
993 "odds": {
994 "kind": "outcomes",
995 "subject": "Win Total",
996 "parts": [
997 {"label": "U 10.5", "price": 0.50, "move": [-1.0, "today"], "market_id": "m-sf", "outcome_id": "tok-u"},
998 {"label": "O 10.5", "price": 0.50, "move": [1.0, "today"], "market_id": "m-sf", "outcome_id": "tok-o"},
999 ],
1000 },
1001 "matched_market": {
1002 "label": "San Francisco 49ers",
1003 "price": 0.50,
1004 "contender": True,
1005 "rank": 1,
1006 "race_size": 2,
1007 "market_id": "m-sf",
1008 "outcome_id": "tok-o",
1009 },
1010 },
1011 )
1012 outcomes_line = render._polymarket_odds_line(tied_outcomes, "2026")
1013 assert "San Francisco 49ers 50%, #1 of 2 (up 1 pt today)" in outcomes_line
1014 assert "U 10.5 at 50% (down 1 pt today)" in outcomes_line
1015 assert "O 10.5" not in outcomes_line
1016
1017 def test_49ers_win_total_without_ids_or_tokens_prints_once_and_tied_siblings_stay_separate(
1018 self,
1019 ):
1020 # Matches real eval fixtures (tests/eval/fixtures/entity-markets/http.json) where
1021 # markets carry NO id, conditionId, slug, or clobTokenIds.
1022 event = {
1023 "id": "totals-no-ids",
1024 "title": "Pro Football: 2026 Regular Season Win Totals",
1025 "slug": "totals-no-ids",
1026 "active": True,
1027 "closed": False,
1028 "negRisk": False,
1029 "volume1mo": 1000,
1030 "liquidity": 10000,
1031 "updatedAt": "2026-11-16T00:00:00Z",
1032 "markets": [
1033 {
1034 "question": "Will the Baltimore Ravens win more than 11.5 games in the 2026 NFL Regular Season?",
1035 "groupItemTitle": "Baltimore Ravens",
1036 "outcomes": '["O 11.5", "U 11.5"]',
1037 "outcomePrices": '["0.0585", "0.9415"]',
1038 "volume": 8806.7,
1039 "liquidity": 5000,
1040 "endDate": "2027-03-01T00:00:00Z",
1041 "active": True,
1042 "closed": False,
1043 },
1044 {
1045 "question": "Will the San Francisco 49ers win more than 10.5 games in the 2026 NFL Regular Season?",
1046 "groupItemTitle": "San Francisco 49ers",
1047 "outcomes": '["O 10.5", "U 10.5"]',
1048 "outcomePrices": '["0.935", "0.065"]',
1049 "volume": 3555.76,
1050 "liquidity": 5000,
1051 "endDate": "2027-03-01T00:00:00Z",
1052 "active": True,
1053 "closed": False,
1054 },
1055 ],
1056 }
1057 [parsed] = polymarket.parse_polymarket_response(
1058 {"events": [event]},
1059 topic="49ers",
1060 to_date="2026-11-16",
1061 hints=polymarket.PolymarketHints.coerce(
1062 {"kind": "team", "aliases": ["San Francisco 49ers"]}
1063 ),
1064 )
1065 assert parsed["matched_market"]["market_id"] == parsed["odds"]["parts"][0]["market_id"]
1066 assert parsed["matched_market"]["outcome_id"] == "O 10.5"
1067 assert parsed["odds"]["parts"][0]["outcome_id"] == "O 10.5"
1068 assert parsed["odds"]["parts"][1]["outcome_id"] == "U 10.5"
1069
1070 [norm] = normalize.normalize_source_items(
1071 "polymarket", [parsed], "2026-10-17", "2026-11-16"
1072 )
1073 line = render._polymarket_odds_line(norm, "2026")
1074 assert "San Francisco 49ers 93.5%" not in line
1075 assert "O 10.5 at 94%" in line
1076 assert "U 10.5 at 6.5%" in line
1077 assert line.count("94%") + line.count("93.5%") == 1
1078
1079 # Distinct sub-markets without id/conditionId tied at 50%/50% stay separate.
1080 tied_race = {
1081 "id": "race-no-ids",
1082 "title": "MVP Winner 2026",
1083 "slug": "mvp-2026",
1084 "active": True,
1085 "closed": False,
1086 "negRisk": True,
1087 "volume1mo": 50000,
1088 "liquidity": 20000,
1089 "updatedAt": "2026-11-16T00:00:00Z",
1090 "markets": [
1091 {
1092 "question": "Will Alice Smith win MVP 2026?",
1093 "groupItemTitle": "Alice Smith",
1094 "outcomes": '["Yes", "No"]',
1095 "outcomePrices": '["0.50", "0.50"]',
1096 "volume": 30000,
1097 "liquidity": 10000,
1098 "oneWeekPriceChange": 0.04,
1099 "endDate": "2027-03-01T00:00:00Z",
1100 "active": True,
1101 "closed": False,
1102 },
1103 {
1104 "question": "Will Bob Jones win MVP 2026?",
1105 "groupItemTitle": "Bob Jones",
1106 "outcomes": '["Yes", "No"]',
1107 "outcomePrices": '["0.50", "0.50"]',
1108 "volume": 20000,
1109 "liquidity": 10000,
1110 "oneWeekPriceChange": -0.02,
1111 "endDate": "2027-03-01T00:00:00Z",
1112 "active": True,
1113 "closed": False,
1114 },
1115 ],
1116 }
1117 [parsed_race] = polymarket.parse_polymarket_response(
1118 {"events": [tied_race]},
1119 topic="Bob Jones",
1120 to_date="2026-11-16",
1121 )
1122 [norm_race] = normalize.normalize_source_items(
1123 "polymarket", [parsed_race], "2026-10-17", "2026-11-16"
1124 )
1125 race_line = render._polymarket_odds_line(norm_race, "2026")
1126 assert race_line.count("Bob Jones") == 1
1127 assert "Bob Jones at 50% (down 2 pts this week)" in race_line
1128 assert "Alice Smith at 50% (up 4 pts this week)" in race_line
1129
1130
1131 # ---------------------------------------------------------------------------
1132 # HIGH-042: _polymarket_top_markets skips unpriced/impossible/dupes before limit
1133 # ---------------------------------------------------------------------------
1134
1135
1136 class TestHigh042PolymarketTopMarketsNoPreSlice:
1137 def _pm_item(
1138 self,
1139 item_id: str,
1140 question: str,
1141 *,
1142 outcome_prices=None,
1143 headline=None,
1144 volume: float = 100.0,
1145 ) -> schema.SourceItem:
1146 meta = {
1147 "question": question,
1148 "volume24hr": volume,
1149 "outcome_prices": [] if outcome_prices is None else outcome_prices,
1150 "headline": headline,
1151 }
1152 item = _make_item(
1153 item_id,
1154 source="polymarket",
1155 title=question,
1156 url=f"https://polymarket.com/event/{item_id}",
1157 metadata=meta,
1158 )
1159 item.engagement = {"volume": volume}
1160 return item
1161
1162 def test_unpriced_and_impossible_set_items_do_not_consume_footer_slots(self):
1163 # Deliberately unsorted input so polymarket.by_selection must sort by engagement["volume"].
1164 items = [
1165 self._pm_item(
1166 "priced-3",
1167 "Will Acme acquire Beta in 2026?",
1168 headline={"question": "Will Acme acquire Beta in 2026?", "price": 0.18, "label": ""},
1169 volume=400,
1170 ),
1171 self._pm_item("unpriced-2", "Will Acme hit ___?", outcome_prices=[], volume=800),
1172 self._pm_item(
1173 "priced-1",
1174 "Will Acme IPO in 2026?",
1175 headline={"question": "Will Acme IPO in 2026?", "price": 0.42, "label": ""},
1176 volume=600,
1177 ),
1178 self._pm_item("unpriced-1", "Will Acme close at ___?", outcome_prices=[], volume=900),
1179 self._pm_item(
1180 "priced-2",
1181 "Will Acme ship v2 in 2026?",
1182 headline={"question": "Will Acme ship v2 in 2026?", "price": 0.65, "label": ""},
1183 volume=500,
1184 ),
1185 self._pm_item("unpriced-3", "Will Acme trade at ___?", outcome_prices=[], volume=700),
1186 ]
1187
1188 summaries = render._polymarket_top_markets(items, limit=3)
1189
1190 assert summaries == [
1191 "Acme IPO in 2026 42%",
1192 "Acme ship v2 in 2026 65%",
1193 "Acme acquire Beta in 2026 18%",
1194 ]
1195
1196 def test_duplicate_and_malformed_entries_do_not_starve_later_valid_markets(self):
1197 # Shuffled order verifies engagement["volume"] sorting determines winners.
1198 items = [
1199 self._pm_item(
1200 "valid-3",
1201 "Will Acme open a Tokyo office?",
1202 outcome_prices=[("Yes", 0.29)],
1203 volume=600,
1204 ),
1205 self._pm_item(
1206 "dup-2",
1207 "Will Acme IPO in 2026?",
1208 outcome_prices=[("Yes", 0.40)],
1209 volume=850,
1210 ),
1211 self._pm_item(
1212 "bad-shape",
1213 "Will Acme crash?",
1214 outcome_prices=[("only-one",), ("Yes", True), ("a", 0.2, "extra")],
1215 volume=800,
1216 ),
1217 self._pm_item(
1218 "valid-2",
1219 "Will Acme beat Q4 earnings?",
1220 outcome_prices=[("Yes", 0.71)],
1221 volume=700,
1222 ),
1223 self._pm_item(
1224 "dup-1",
1225 "Will Acme IPO in 2026?",
1226 outcome_prices=[("Yes", 0.40)],
1227 volume=900,
1228 ),
1229 ]
1230
1231 summaries = render._polymarket_top_markets(items, limit=3)
1232
1233 assert len(summaries) == 3
1234 assert summaries[0].endswith("40%")
1235 assert summaries[1].endswith("71%")
1236 assert summaries[2].endswith("29%")
1237
1238 def test_unshown_fourth_market_does_not_expand_first_market_disambiguation(self):
1239 items = [
1240 self._pm_item(
1241 "m4",
1242 "Will Fed cut rates by June 30, 2027?",
1243 outcome_prices=[("Yes", 0.50)],
1244 volume=600,
1245 ),
1246 self._pm_item(
1247 "m2",
1248 "Will Nvidia launch Rubin in 2026?",
1249 outcome_prices=[("Yes", 0.60)],
1250 volume=800,
1251 ),
1252 self._pm_item(
1253 "m1",
1254 "Will Fed cut rates by March 31, 2027?",
1255 outcome_prices=[("Yes", 0.25)],
1256 volume=900,
1257 ),
1258 self._pm_item(
1259 "m3",
1260 "Will Apple release foldable iPhone in 2026?",
1261 outcome_prices=[("Yes", 0.15)],
1262 volume=700,
1263 ),
1264 ]
1265
1266 summaries = render._polymarket_top_markets(items, limit=3)
1267
1268 assert len(summaries) == 3
1269 assert "March 31, 2027" not in summaries[0]
1270
1271 def test_unpriced_count_series_item_does_not_block_priced_sibling_in_same_series(
1272 self,
1273 ):
1274 # Higher-volume unpriced weekly count market must NOT claim seen_series and
1275 # drop the priced weekly count market from the same series.
1276 unpriced_count = self._pm_item(
1277 "tweets-unpriced",
1278 "Elon Musk # tweets November 10 - November 17, 2026?",
1279 outcome_prices=[],
1280 volume=5000,
1281 )
1282 priced_count = self._pm_item(
1283 "tweets-priced",
1284 "Elon Musk # tweets November 17 - November 24, 2026?",
1285 headline={
1286 "question": "Elon Musk # tweets November 17 - November 24, 2026?",
1287 "price": 0.34,
1288 "label": "200-219",
1289 },
1290 volume=1000,
1291 )
1292 assert polymarket.is_count_series(unpriced_count.title, unpriced_count.title)
1293 assert polymarket.series_key(unpriced_count.title, unpriced_count.title) == (
1294 polymarket.series_key(priced_count.title, priced_count.title)
1295 )
1296
1297 summaries = render._polymarket_top_markets([priced_count, unpriced_count], limit=3)
1298
1299 assert len(summaries) == 1
1300 assert "200-219" in summaries[0]
1301 assert summaries[0].endswith("34%")
1302
1303
1304 # ---------------------------------------------------------------------------
1305 # HIGH-043: Comparison comment grounding (stripped body + short entities)
1306 # ---------------------------------------------------------------------------
1307
1308
1309 class TestHigh043ComparisonCommentGrounding:
1310 def _reddit_report(self, topic: str, title: str, comments: list[dict]) -> schema.Report:
1311 item = _make_item(
1312 "r-1",
1313 source="reddit",
1314 title=title,
1315 url="https://www.reddit.com/r/programming/comments/abc123/thread/",
1316 metadata={"top_comments": comments},
1317 )
1318 cand = _make_candidate("c-1", item)
1319 return _make_report(topic, candidates=[cand])
1320
1321 @pytest.mark.parametrize(
1322 ("topic", "short_entity", "long_entity", "long_only_comment", "substring_trap", "short_comment"),
1323 [
1324 (
1325 "Go vs Rust",
1326 "Go",
1327 "Rust",
1328 "Rust borrow checker caught three data races for us.",
1329 "I am going to move my Cargo project next quarter.",
1330 "Go compiles in seconds and goroutines keep services simple.",
1331 ),
1332 (
1333 "AWS vs Azure",
1334 "AWS",
1335 "Azure",
1336 "Azure AD integration is the reason enterprise teams pick it.",
1337 "There are obvious flaws in how billing alerts work here.",
1338 "AWS Lambda cold starts improved dramatically this year.",
1339 ),
1340 (
1341 "AMD vs Nvidia",
1342 "AMD",
1343 "Nvidia",
1344 "Nvidia CUDA tooling still dominates ML training clusters.",
1345 "Random unrelated remark about hardware availability today.",
1346 "AMD ROCm support has gotten much better on Linux lately.",
1347 ),
1348 (
1349 "OpenAI vs X",
1350 "X",
1351 "OpenAI",
1352 "OpenAI keeps expanding its enterprise agent API lineup.",
1353 "Extra context on latency benchmarks from yesterday evening.",
1354 "On X the developer community reacted immediately to the news.",
1355 ),
1356 ],
1357 )
1358 def test_short_entity_comparison_requires_whole_word_match(
1359 self,
1360 topic: str,
1361 short_entity: str,
1362 long_entity: str,
1363 long_only_comment: str,
1364 substring_trap: str,
1365 short_comment: str,
1366 ):
1367 report = self._reddit_report(
1368 topic,
1369 topic,
1370 [
1371 {"author": "u1", "score": 300, "depth": 0, "excerpt": long_only_comment},
1372 {"author": "u2", "score": 250, "depth": 0, "excerpt": substring_trap},
1373 {"author": "u3", "score": 200, "depth": 0, "excerpt": "Haha great post, totally agree!"},
1374 {"author": "u4", "score": 150, "depth": 0, "excerpt": short_comment},
1375 ],
1376 )
1377
1378 lines = render._render_top_comments(report)
1379 joined = "\n".join(lines)
1380
1381 assert "Haha great post" not in joined
1382 assert substring_trap[:20] not in joined
1383
1384 long_line = next(line for line in lines if long_only_comment[:20] in line)
1385 assert f"(about {long_entity})" in long_line
1386 assert short_entity not in long_line.split(" (about ")[-1]
1387
1388 short_line = next(line for line in lines if short_comment[:20] in line)
1389 assert f"(about {short_entity})" in short_line
1390 assert long_entity not in short_line.split(" (about ")[-1]
1391
1392 def test_parent_quote_and_raw_url_stripped_before_grounding(self):
1393 # Comparison: entity appears ONLY in stripped parent quote or stripped URL.
1394 comp_report = self._reddit_report(
1395 "Claude vs OpenAI",
1396 "Claude vs OpenAI coding benchmark",
1397 [
1398 {
1399 "author": "u1",
1400 "score": 400,
1401 "depth": 0,
1402 "excerpt": "> Claude is way faster on refactors\nLOL I completely agree with this!",
1403 },
1404 {
1405 "author": "u2",
1406 "score": 350,
1407 "depth": 0,
1408 "excerpt": "Check out this benchmark https://claude.ai/docs/overview right now!",
1409 },
1410 {
1411 "author": "u3",
1412 "score": 300,
1413 "depth": 0,
1414 "excerpt": "> OpenAI launched a new tier\nClaude handles large repos much better for me.",
1415 },
1416 {
1417 "author": "u4",
1418 "score": 250,
1419 "depth": 0,
1420 "excerpt": "OpenAI latency on streaming tool calls improved a lot this month.",
1421 },
1422 ],
1423 )
1424
1425 lines = render._render_top_comments(comp_report)
1426 joined = "\n".join(lines)
1427
1428 assert "LOL I completely agree" not in joined
1429 assert "Check out this benchmark" not in joined
1430 real_line = next(line for line in lines if "Claude handles large repos" in line)
1431 assert "(about Claude)" in real_line
1432 assert "OpenAI" not in real_line.split(" (about ")[-1]
1433
1434 # Single-topic deep reply (no title exemption): parent quote and URL must not ground it.
1435 single_report = self._reddit_report(
1436 "Claude",
1437 "Claude 4.7 discussion",
1438 [
1439 {
1440 "author": "u1",
1441 "score": 400,
1442 "depth": 2,
1443 "excerpt": "> Claude is faster\nTotally agree with your point here!",
1444 },
1445 {
1446 "author": "u2",
1447 "score": 350,
1448 "depth": 2,
1449 "excerpt": "Look at these numbers https://claude.ai/pricing from today.",
1450 },
1451 {
1452 "author": "u3",
1453 "score": 300,
1454 "depth": 2,
1455 "excerpt": "Claude code review catches edge cases reliably.",
1456 },
1457 {
1458 "author": "u4",
1459 "score": 250,
1460 "depth": 2,
1461 "excerpt": "Claude context window stayed coherent across ten files.",
1462 },
1463 ],
1464 )
1465 single_out = "\n".join(render._render_top_comments(single_report))
1466 assert "Totally agree with your point" not in single_out
1467 assert "Look at these numbers" not in single_out
1468 assert "Claude code review catches edge cases reliably." in single_out
1469
1469 lines PYTHON