返回 last30days-skill
test_pr30_query_resolve_competitors_planner_handoff.py
根目录 / tests / test_pr30_query_resolve_competitors_planner_handoff.py
1 """Regression tests for PR 30 (HIGH-088, HIGH-089, HIGH-090, HIGH-092, HIGH-093).
2
3 Covers:
4 - HIGH-088: Word-bounded compound term extraction in query.py and short-entity
5 quoting in planner._keyword_query (no PascalCase mid-word slicing, no
6 verbatim quoting of full Title-Cased prompts).
7 - HIGH-089: Anchored subreddit, X/Twitter handle, and GitHub regexes in
8 resolve.py (no *x.com false positives, no email @handle leaks, no slash-pair
9 or non-Reddit /r/ false subreddits).
10 - HIGH-090: Aligned brand tokenization and stopword exclusion in competitors.py
11 so punctuated brands filter themselves without blacklisting real peers.
12 - HIGH-092: Requested/available source intersection and Hebrew grounding source
13 boundary enforcement in planner._fallback_plan.
14 - HIGH-093: Non-finite worthiness, invalid UTF-8 files, and malformed nested
15 bundle/pending fields in discovery_handoff.py.
16 """
17
18 from __future__ import annotations
19
20 import io
21 import json
22 import math
23 from contextlib import redirect_stderr
24 from datetime import datetime, timezone
25 from pathlib import Path
26 from unittest import mock
27
28 import pytest
29
30 from lib import competitors, discovery_handoff as handoff, pipeline, planner, query, resolve, schema
31
32
33 # ---------------------------------------------------------------------------
34 # HIGH-088: query.extract_compound_terms & planner._keyword_query
35 # ---------------------------------------------------------------------------
36
37
38 @pytest.mark.parametrize(
39 "topic,expected_phrase,forbidden_slice",
40 [
41 ("GitHub Actions", "GitHub Actions", "Hub Actions"),
42 ("YouTube Shorts", "YouTube Shorts", "Tube Shorts"),
43 ("TypeScript Compiler", "TypeScript Compiler", "Script Compiler"),
44 ("OpenClaw Agent", "OpenClaw Agent", "Claw Agent"),
45 ("LangChain Agents", "LangChain Agents", "Chain Agents"),
46 ("DeepSeek Coder", "DeepSeek Coder", "Seek Coder"),
47 ("MacBook Pro", "MacBook Pro", "Book Pro"),
48 ("LinkedIn Jobs", "LinkedIn Jobs", "In Jobs"),
49 ("PyTorch Lightning", "PyTorch Lightning", "Torch Lightning"),
50 ("OpenAI Codex", "OpenAI Codex", "AI Codex"),
51 ("iPhone Pro", "iPhone Pro", "Phone Pro"),
52 ("macOS Sequoia", "macOS Sequoia", "OS Sequoia"),
53 ("xAI Grok", "xAI Grok", "AI Grok"),
54 ],
55 )
56 def test_high088_pascal_and_camel_case_brands_never_split_mid_word(
57 topic: str, expected_phrase: str, forbidden_slice: str,
58 ):
59 compounds = query.extract_compound_terms(topic)
60 assert expected_phrase in compounds
61 assert forbidden_slice not in compounds
62
63 core = query.extract_core_subject(topic, max_words=6, strip_suffixes=True)
64 kw = planner._keyword_query(topic, core)
65 assert f'"{expected_phrase}"' in kw
66 assert f'"{forbidden_slice}"' not in kw
67 # Phrase words must not be duplicated unquoted alongside the quoted phrase.
68 assert kw == f'"{expected_phrase}"'
69
70
71 @pytest.mark.parametrize("brand", ["OpenAI", "GitHub", "MacBook", "DeepSeek", "iPhone"])
72 def test_high088_single_brand_token_yields_no_compound(brand: str):
73 assert query.extract_compound_terms(brand) == []
74 assert planner._keyword_query(brand, brand.lower()) == brand.lower()
75
76
77 @pytest.mark.parametrize(
78 "prompt",
79 [
80 "Best AI Coding Tools For Python Developers",
81 "Best AI Coding Tools for Python Developers",
82 "Hermes Agent Actual Use Cases",
83 "What Are The Best Claude Code Alternatives",
84 "What Are the Best Claude Code Alternatives",
85 "How To Use GitHub Actions Today",
86 "How to Build AI Agents with Python",
87 ],
88 )
89 def test_high088_full_title_cased_prompts_not_quoted_verbatim(prompt: str):
90 compounds = query.extract_compound_terms(prompt)
91 assert prompt not in compounds
92 assert compounds == []
93
94 core = query.extract_core_subject(prompt, max_words=6, strip_suffixes=True)
95 kw = planner._keyword_query(prompt, core)
96 assert f'"{prompt}"' not in kw
97 assert '"' not in kw
98
99
100 @pytest.mark.parametrize(
101 "topic,forbidden_slice",
102 [
103 ("Claude Résumé", "Claude R"),
104 ("OpenAI Café", "OpenAI Caf"),
105 ("Next.JS Framework", "JS Framework"),
106 ("OpenAI Next.JS", "OpenAI Next"),
107 ("Visual C++", "Visual C"),
108 ("Visual C#", "Visual C"),
109 ("O\u2019Reilly Media", "Reilly Media"),
110 ("O'Reilly Media", "Reilly Media"),
111 ("AT&T Wireless", "T Wireless"),
112 ],
113 )
114 def test_high088_unicode_dotted_curly_apostrophe_and_symbol_brands_never_sliced(
115 topic: str, forbidden_slice: str,
116 ):
117 compounds = query.extract_compound_terms(topic)
118 assert forbidden_slice not in compounds
119 assert compounds == []
120
121 core = query.extract_core_subject(topic, max_words=6, strip_suffixes=True)
122 kw = planner._keyword_query(topic, core)
123 assert f'"{forbidden_slice}"' not in kw
124
125
126 def test_high088_sentence_trailing_period_still_allows_valid_brand():
127 assert query.extract_compound_terms("Check out GitHub Actions.") == ["GitHub Actions"]
128 assert query.extract_compound_terms("DeepSeek R1") == ["DeepSeek R1"]
129
130
131 def test_high088_mixed_case_topics_strip_edge_noise_and_cap_length():
132 assert query.extract_compound_terms("Best GitHub Actions workflows for Python") == [
133 "GitHub Actions"
134 ]
135 assert query.extract_compound_terms("Claude Code Use Cases in production") == [
136 "Claude Code"
137 ]
138 assert query.extract_compound_terms("Best React Native Tips for beginners") == [
139 "React Native"
140 ]
141 assert query.extract_compound_terms("React Server Components vs Astro Islands") == [
142 "React Server Components",
143 "Astro Islands",
144 ]
145 # Runs longer than 3 words after edge trimming are not quoted as entities.
146 assert query.extract_compound_terms(
147 "Alpha Beta Gamma Delta Epsilon in lowercase text"
148 ) == []
149
150
151 def test_high088_hyphenated_compound_not_sliced_into_title_case_phrase():
152 compounds = query.extract_compound_terms("Multi-Agent Systems")
153 assert "Multi-Agent" in compounds
154 assert "Agent Systems" not in compounds
155 kw = planner._keyword_query("Multi-Agent Systems", "multi-agent systems")
156 assert '"Agent Systems"' not in kw
157 assert '"' not in kw
158
159
160 def test_high088_keyword_query_guards_against_overlong_or_hyphenated_compounds():
161 with mock.patch.object(
162 query,
163 "extract_compound_terms",
164 return_value=[
165 "Best AI Coding Tools For Python Developers",
166 "multi-agent",
167 "GitHub Actions",
168 ],
169 ):
170 kw = planner._keyword_query(
171 "GitHub Actions multi-agent",
172 "github actions multi-agent",
173 )
174 assert kw == '"GitHub Actions" multi-agent'
175
176
177 # ---------------------------------------------------------------------------
178 # HIGH-089: resolve.py anchored regexes
179 # ---------------------------------------------------------------------------
180
181
182 @pytest.mark.parametrize(
183 "item",
184 [
185 {"title": "Profile", "snippet": "user/foo editor/bar", "url": ""},
186 {"title": "Perf", "snippet": "server/client better/faster", "url": ""},
187 {"title": "User", "snippet": "", "url": "https://www.reddit.com/user/johndoe"},
188 {"title": "Repo", "snippet": "", "url": "https://github.com/owner/repo"},
189 {"title": "Tweet", "snippet": "", "url": "https://twitter.com/author/status/123"},
190 {"title": "FakePath", "snippet": "See https://twitter.com/r/python", "url": "https://twitter.com/r/notreddit"},
191 {"title": "OtherHost", "snippet": "Visit https://example.com/r/programming", "url": "https://notreddit.com/r/python"},
192 {"title": "PathSpoof", "snippet": "https://example.com/reddit.com/r/spoof", "url": "https://example.com/reddit.com/r/spoof"},
193 {"title": "Languages", "snippet": "Comparing R/Python for statistics", "url": ""},
194 {"title": "TooLong", "snippet": "r/abcdefghijklmnopqrstuvwxyz", "url": ""},
195 ],
196 )
197 def test_high089_extract_subreddits_rejects_false_positives(item: dict):
198 assert resolve._extract_subreddits([item]) == []
199
200
201 def test_high089_extract_subreddits_accepts_valid_prose_and_reddit_urls():
202 items = [
203 {
204 "title": "r/MachineLearning and /r/artificial",
205 "snippet": "Also (r/datascience), https://old.reddit.com/r/LocalLLaMA?sort=top",
206 "url": "https://www.reddit.com/r/python/comments/123/test",
207 },
208 {
209 "title": "Upper URL",
210 "snippet": "",
211 "url": "HTTPS://REDDIT.COM/r/rust/",
212 },
213 ]
214 assert resolve._extract_subreddits(items) == [
215 "MachineLearning",
216 "artificial",
217 "datascience",
218 "LocalLLaMA",
219 "python",
220 "rust",
221 ]
222
223
224 @pytest.mark.parametrize(
225 "url",
226 [
227 "https://netflix.com/watch/123",
228 "https://www.netflix.com/title/8123",
229 "https://dropbox.com/s/abc123",
230 "https://linux.com/news/kernel",
231 "https://firefox.com/en-US/download",
232 "https://spacex.com/launches",
233 "https://brex.com/product",
234 "https://roblox.com/games",
235 "https://fedex.com/tracking",
236 "https://fox.com/shows",
237 "https://example.com/x.com/spoof",
238 "https://my-twitter.com/spoof",
239 ],
240 )
241 def test_high089_extract_x_handle_rejects_suffix_x_domains(url: str):
242 items = [{"title": "Site page", "snippet": "Details", "url": url}]
243 assert resolve._extract_x_handle(items) == ""
244
245
246 @pytest.mark.parametrize(
247 "text",
248 [
249 "Contact foo@bar.com for support",
250 "Press inquiries: press@gmail.com",
251 "Send to first.last+tag@company.co",
252 "Reach user_1@sub.domain.org or a-b@x.com",
253 "Overlong handle @abcdefghijklmnop should not truncate",
254 ],
255 )
256 def test_high089_extract_x_handle_rejects_emails_and_overlong_handles(text: str):
257 items = [{"title": text, "snippet": text, "url": ""}]
258 assert resolve._extract_x_handle(items) == ""
259
260
261 def test_high089_extract_x_handle_accepts_valid_urls_and_mentions():
262 assert resolve._extract_x_handle([
263 {"title": "News", "snippet": "contact press@spacex.com", "url": "https://spacex.com/launches"},
264 {"title": "Official", "snippet": "Follow (@SpaceX).", "url": "https://mobile.x.com/SpaceX?s=20"},
265 ]) == "spacex"
266 assert resolve._extract_x_handle([
267 {"title": "", "snippet": "", "url": "HTTPS://WWW.TWITTER.COM/OpenAI/status/999"},
268 ]) == "openai"
269
270
271 def test_high089_github_extractors_reject_spoofed_hosts():
272 bad_items = [
273 {"title": "Mirror", "snippet": "notgithub.com/eviluser/repo", "url": "https://notgithub.com/eviluser/repo"},
274 {"title": "Archive", "snippet": "https://example.com/github.com/fake/repo", "url": "https://example.com/github.com/fake/repo"},
275 {"title": "Hyphen", "snippet": "my-github.com/fakeuser", "url": "https://my-github.com/fakeuser/proj"},
276 ]
277 assert resolve._extract_github_user(bad_items) == ""
278 assert resolve._extract_github_repos(bad_items) == []
279
280 good_items = [
281 {"title": "Repo", "snippet": "See github.com/anthropics", "url": "https://www.github.com/anthropics/claude-code/issues/1"},
282 ]
283 assert resolve._extract_github_user(good_items) == "anthropics"
284 assert resolve._extract_github_repos(good_items) == ["anthropics/claude-code"]
285
286
287 # ---------------------------------------------------------------------------
288 # HIGH-090: competitors.py tokenization & stopword filtering
289 # ---------------------------------------------------------------------------
290
291
292 @pytest.mark.parametrize(
293 "brand,self_variants,valid_peers",
294 [
295 ("AT&T", ["AT&T", "AT&T Wireless", "ATT", "AT T"], ["T-Mobile", "Verizon"]),
296 ("T-Mobile", ["T-Mobile", "T-Mobile Plans", "T Mobile"], ["AT&T", "Verizon", "Mint Mobile"]),
297 ("Node.js", ["Node.js", "NodeJS", "Node"], ["Next.js", "Deno", "Bun"]),
298 ("Next.js", ["Next.js", "NextJS", "Next"], ["Nuxt.js", "Node.js", "Remix"]),
299 ("Coca-Cola", ["Coca-Cola", "Coca-Cola Zero", "Coca Cola"], ["Pepsi", "Pepsi-Cola"]),
300 ("A&W", ["A&W", "A&W Restaurants"], ["Burger King", "B&H"]),
301 ("Booking.com", ["Booking.com", "Booking", "Booking Holdings"], ["Hotels.com", "Expedia.com"]),
302 ("Monday.com", ["Monday.com", "Monday"], ["Asana", "ClickUp"]),
303 ("C3.ai", ["C3.ai", "C3"], ["Scale AI", "Palantir AI"]),
304 ("Continue.dev", ["Continue.dev", "Continue"], ["Cursor", "Aider.dev"]),
305 ("Fly.io", ["Fly.io", "Fly"], ["Render.io", "Railway"]),
306 ("D-Wave", ["D-Wave", "D-Wave Quantum", "DWave"], ["IonQ", "Rigetti"]),
307 ],
308 )
309 def test_high090_punctuated_brands_filter_self_without_blocking_peers(
310 brand: str, self_variants: list[str], valid_peers: list[str],
311 ):
312 tokens = competitors._topic_tokens(brand)
313 for variant in self_variants:
314 assert not competitors._candidate_ok(variant, tokens), (
315 f"{variant!r} leaked past self-filter for topic {brand!r} (tokens={tokens})"
316 )
317 for peer in valid_peers:
318 assert competitors._candidate_ok(peer, tokens), (
319 f"Valid peer {peer!r} wrongly rejected for topic {brand!r} (tokens={tokens})"
320 )
321
322
323 def test_high090_stopwords_in_topic_do_not_blacklist_real_competitors():
324 scale_tokens = competitors._topic_tokens("Scale AI")
325 assert "ai" not in scale_tokens
326 assert competitors._candidate_ok("Mistral AI", scale_tokens)
327 assert competitors._candidate_ok("Meta AI", scale_tokens)
328 assert not competitors._candidate_ok("Scale AI", scale_tokens)
329 assert not competitors._candidate_ok("Scale", scale_tokens)
330
331 nyt_tokens = competitors._topic_tokens("The New York Times")
332 assert "the" not in nyt_tokens
333 assert competitors._candidate_ok("The Washington Post", nyt_tokens)
334 assert not competitors._candidate_ok("The New York Times", nyt_tokens)
335 assert not competitors._candidate_ok("New York Times", nyt_tokens)
336
337 # All-stopword topics fall back cleanly rather than returning an empty set.
338 assert competitors._topic_tokens("Top AI")
339
340
341 def test_high090_extract_peer_entities_never_returns_punctuated_brand_as_competitor():
342 serp = [
343 {"title": "AT&T vs Verizon vs T-Mobile", "snippet": "AT&T competes with Verizon and T-Mobile.", "url": "https://example.test/1"},
344 {"title": "Best AT&T Alternatives", "snippet": "AT&T customers switch to T-Mobile and Verizon.", "url": "https://example.test/2"},
345 ]
346 peers = competitors._extract_peer_entities(serp, "AT&T", limit=3)
347 assert "AT&T" not in peers
348 assert set(peers) >= {"Verizon", "T-Mobile"}
349
350 serp_ai = [
351 {"title": "Scale AI vs Mistral AI vs Labelbox", "snippet": "Mistral AI and Labelbox compete with Scale AI.", "url": "https://example.test/3"},
352 ]
353 ai_peers = competitors._extract_peer_entities(serp_ai, "Scale AI", limit=3)
354 assert "Scale AI" not in ai_peers
355 assert "Mistral AI" in ai_peers
356
357
358 # ---------------------------------------------------------------------------
359 # HIGH-092: planner._fallback_plan source intersection & Hebrew grounding
360 # ---------------------------------------------------------------------------
361
362
363 def test_high092_fallback_plan_intersects_requested_with_available_sources():
364 plan = planner._fallback_plan(
365 topic="Claude Code",
366 available_sources=["reddit", "hackernews", "grounding"],
367 requested_sources=["reddit", "x"],
368 depth="default",
369 )
370 assert "x" not in plan.source_weights
371 assert list(plan.source_weights) == ["reddit"]
372 for sq in plan.subqueries:
373 assert sq.sources == ["reddit"]
374
375
376 def test_high092_fallback_plan_disjoint_requested_sources_never_schedules_unavailable_or_unrequested():
377 plan = planner._fallback_plan(
378 topic="Claude Code",
379 available_sources=["reddit", "hackernews"],
380 requested_sources=["x", "youtube"],
381 depth="default",
382 )
383 assert plan.source_weights == {}
384 assert plan.subqueries == []
385
386
387 def test_high092_hebrew_explicit_search_does_not_inject_grounding_or_evict_quick_slots():
388 hebrew_topic = "קפה עלית חדשות"
389 for depth in ("quick", "default"):
390 plan = planner._fallback_plan(
391 topic=hebrew_topic,
392 available_sources=["reddit", "x", "grounding"],
393 requested_sources=["reddit", "x"],
394 depth=depth,
395 )
396 assert "grounding" not in plan.source_weights, f"grounding leaked in {depth}"
397 for sq in plan.subqueries:
398 assert "grounding" not in sq.sources
399 assert set(sq.sources) == {"reddit", "x"}
400
401
402 def test_high092_hebrew_elevates_grounding_only_when_auto_or_explicitly_requested_and_available():
403 hebrew_topic = "חדשות טכנולוגיה בישראל"
404
405 # Auto mode (no requested_sources): grounding available -> elevated to front.
406 auto_plan = planner._fallback_plan(
407 topic=hebrew_topic,
408 available_sources=["reddit", "x", "grounding"],
409 requested_sources=None,
410 depth="default",
411 )
412 assert list(auto_plan.source_weights)[0] == "grounding"
413 assert auto_plan.subqueries[0].sources[0] == "grounding"
414
415 # Explicit --search including available grounding: grounding elevated to front.
416 explicit_plan = planner._fallback_plan(
417 topic=hebrew_topic,
418 available_sources=["reddit", "x", "grounding"],
419 requested_sources=["reddit", "x", "grounding"],
420 depth="quick",
421 )
422 assert list(explicit_plan.source_weights)[0] == "grounding"
423 assert explicit_plan.subqueries[0].sources[0] == "grounding"
424 assert len(explicit_plan.subqueries[0].sources) == 2
425
426 # Explicit --search including UNAVAILABLE grounding: grounding must not be scheduled.
427 unavail_plan = planner._fallback_plan(
428 topic=hebrew_topic,
429 available_sources=["reddit", "x"],
430 requested_sources=["reddit", "grounding"],
431 depth="default",
432 )
433 assert "grounding" not in unavail_plan.source_weights
434 for sq in unavail_plan.subqueries:
435 assert sq.sources == ["reddit"]
436
437
438 # ---------------------------------------------------------------------------
439 # HIGH-093: discovery_handoff.py robustness & contract enforcement
440 # ---------------------------------------------------------------------------
441
442
443 def _sample_bundle(tmp_path: Path) -> handoff.NominationsBundle:
444 item = schema.SourceItem(
445 item_id="hn1",
446 source="hackernews",
447 title="Sample Story",
448 body="Sample Story",
449 url="https://hackernews.example/hn1",
450 published_at="2026-07-18",
451 engagement={"points": 100},
452 snippet="Snippet text",
453 metadata={},
454 )
455 nom = pipeline.Nomination(
456 name="Sample Story",
457 seed_score=42.0,
458 items=[item],
459 summary="Summary",
460 )
461 entry = handoff.PoolEntry(
462 nomination=nom,
463 cluster_id="c1",
464 heuristic_name="Sample Story",
465 heuristic_junk=False,
466 )
467 return handoff.write_nominations_bundle(
468 [entry],
469 domain="AI",
470 tier="deep",
471 from_date="2026-06-21",
472 to_date="2026-07-21",
473 lookback_days=30,
474 enrichment_source_boundary=None,
475 requested_sources=["hackernews"],
476 config_dir=tmp_path,
477 )
478
479
480 @pytest.mark.parametrize(
481 "bad_value",
482 [
483 float("nan"),
484 float("inf"),
485 float("-inf"),
486 "nan",
487 "NaN",
488 "inf",
489 "-inf",
490 "Infinity",
491 "-Infinity",
492 "1e400",
493 10**400,
494 True,
495 False,
496 None,
497 "not-a-number",
498 ],
499 )
500 def test_high093_clamped_worthiness_rejects_non_finite_and_invalid_values(bad_value):
501 assert handoff._clamped_worthiness(bad_value) is None
502
503
504 def test_high093_read_judgments_handles_non_finite_json_worthiness(tmp_path: Path):
505 bundle = _sample_bundle(tmp_path)
506 jpath = tmp_path / "judgments.json"
507 # Python's json.loads accepts bare NaN/Infinity tokens.
508 jpath.write_text(
509 '{"bundle_id": "' + bundle.bundle_id + '", "judgments": ['
510 '{"id": "n1", "name": "Valid Name", "worthiness": NaN}'
511 ']}',
512 encoding="utf-8",
513 )
514 judgments = handoff.read_judgments(jpath, bundle, config_dir=tmp_path)
515 assert judgments["n1"].name == "Valid Name"
516 assert judgments["n1"].worthiness is None
517
518 jpath.write_text(
519 '{"bundle_id": "' + bundle.bundle_id + '", "judgments": ['
520 '{"id": "n1", "worthiness": Infinity}'
521 ']}',
522 encoding="utf-8",
523 )
524 judgments_inf = handoff.read_judgments(jpath, bundle, config_dir=tmp_path)
525 assert judgments_inf["n1"].worthiness is None
526
527
528 def test_high093_non_utf8_files_raise_handoff_contract_error(tmp_path: Path):
529 bad_bytes = b"\xff\xfe\x00\x80not-utf8"
530
531 # Bundle file
532 bundle_path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
533 bundle_path.write_bytes(bad_bytes)
534 with pytest.raises(handoff.HandoffContractError):
535 handoff.read_nominations_bundle(config_dir=tmp_path)
536
537 # Pending report file
538 pending_path = tmp_path / handoff.PENDING_REPORT_FILENAME
539 pending_path.write_bytes(bad_bytes)
540 with pytest.raises(handoff.HandoffContractError):
541 handoff.read_pending_report(config_dir=tmp_path)
542
543 # Restore valid bundle to test host judgments & angles files
544 bundle = _sample_bundle(tmp_path)
545 bad_host = tmp_path / "bad-host.json"
546 bad_host.write_bytes(bad_bytes)
547 with pytest.raises(handoff.HandoffContractError):
548 handoff.read_judgments(bad_host, bundle, config_dir=tmp_path)
549 with pytest.raises(handoff.HandoffContractError):
550 handoff.read_angles(bad_host, bundle, config_dir=tmp_path)
551
552
553 @pytest.mark.parametrize("bad_context", ["bad", ["list"], 123, True])
554 def test_high093_bundle_non_dict_context_raises_contract_error(tmp_path: Path, bad_context):
555 _sample_bundle(tmp_path)
556 path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
557 payload = json.loads(path.read_text(encoding="utf-8"))
558 payload["context"] = bad_context
559 path.write_text(json.dumps(payload), encoding="utf-8")
560 with pytest.raises(handoff.HandoffContractError, match="context"):
561 handoff.read_nominations_bundle(config_dir=tmp_path)
562
563
564 @pytest.mark.parametrize(
565 "bad_lookback",
566 [0, -5, 1.5, 30.0, 99999, 10**400, True, False, "bad", "30", float("inf"), float("nan")],
567 )
568 def test_high093_bundle_invalid_lookback_days_raises_contract_error(tmp_path: Path, bad_lookback):
569 _sample_bundle(tmp_path)
570 path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
571 payload = json.loads(path.read_text(encoding="utf-8"))
572 payload["context"]["lookback_days"] = bad_lookback
573 path.write_text(json.dumps(payload), encoding="utf-8")
574 with pytest.raises(handoff.HandoffContractError, match="lookback_days"):
575 handoff.read_nominations_bundle(config_dir=tmp_path)
576
577
578 def test_high093_huge_json_int_literal_raises_contract_error(tmp_path: Path):
579 """Python 3.11+ raises ValueError (not JSONDecodeError) on >4300-digit ints."""
580 huge_int = "9" * 5000
581 bundle_path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
582 bundle_path.write_text(f'{{"lookback_days": {huge_int}}}', encoding="utf-8")
583 with pytest.raises(handoff.HandoffContractError, match="not valid JSON"):
584 handoff.read_nominations_bundle(config_dir=tmp_path)
585
586 bundle = _sample_bundle(tmp_path)
587 judgments_path = tmp_path / "huge-judgments.json"
588 judgments_path.write_text(
589 f'{{"bundle_id": "{bundle.bundle_id}", "judgments": [{{"id": "n1", "worthiness": {huge_int}}}]}}',
590 encoding="utf-8",
591 )
592 with pytest.raises(handoff.HandoffContractError, match="not valid JSON"):
593 handoff.read_judgments(judgments_path, bundle, config_dir=tmp_path)
594
595
596 @pytest.mark.parametrize("bad_mock", ["false", "true", 1, 0, []])
597 def test_high093_non_bool_mock_rejected_in_bundle_and_pending(tmp_path: Path, bad_mock):
598 _sample_bundle(tmp_path)
599 bundle_path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
600 payload = json.loads(bundle_path.read_text(encoding="utf-8"))
601 payload["mock"] = bad_mock
602 bundle_path.write_text(json.dumps(payload), encoding="utf-8")
603 with pytest.raises(handoff.HandoffContractError, match="mock"):
604 handoff.read_nominations_bundle(config_dir=tmp_path)
605
606 pending_path = tmp_path / handoff.PENDING_REPORT_FILENAME
607 pending_payload = {
608 "kind": schema.DISCOVERY_PENDING_KIND,
609 "schema_version": schema.DISCOVERY_PENDING_SCHEMA_VERSION,
610 "bundle_id": "abcd1234abcd1234",
611 "generated_at": datetime.now(timezone.utc).isoformat(),
612 "run_ref": "discover:AI:now",
613 "report": {"domain": "AI", "topics": []},
614 "angle_inputs": {},
615 "mock": bad_mock,
616 }
617 pending_path.write_text(json.dumps(pending_payload), encoding="utf-8")
618 with pytest.raises(handoff.HandoffContractError, match="mock"):
619 handoff.read_pending_report(config_dir=tmp_path)
620
621
622 def test_high093_bundle_duplicate_nomination_ids_rejected(tmp_path: Path):
623 _sample_bundle(tmp_path)
624 path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
625 payload = json.loads(path.read_text(encoding="utf-8"))
626 first_row = payload["nominations"][0]
627 payload["nominations"] = [dict(first_row, id="n1"), dict(first_row, id="n1")]
628 path.write_text(json.dumps(payload), encoding="utf-8")
629 with pytest.raises(handoff.HandoffContractError, match="duplicate nomination id"):
630 handoff.read_nominations_bundle(config_dir=tmp_path)
631
632
633 def test_high093_bundle_malformed_nested_row_fields_degrade_cleanly(tmp_path: Path):
634 _sample_bundle(tmp_path)
635 path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
636 payload = json.loads(path.read_text(encoding="utf-8"))
637 valid_row = payload["nominations"][0]
638
639 # Row with non-dict items element, row with non-dict nomination, row with
640 # non-finite seed_score, plus valid rows with malformed sources (int & str).
641 bad_items_row = {
642 "id": "nbad1",
643 "nomination": {"name": "Broken Items", "seed_score": 10.0, "items": ["not-a-dict"]},
644 }
645 non_dict_nom_row = {"id": "nbad2", "nomination": ["not-a-dict"]}
646 non_list_items_row = {
647 "id": "nbad3",
648 "nomination": {"name": "Str Items", "seed_score": 10.0, "items": "abc"},
649 }
650 nan_score_row = {
651 "id": "nbad4",
652 "nomination": {"name": "NaN Score", "seed_score": math.nan, "items": []},
653 }
654 int_sources_row = dict(valid_row, id="n_int_src", sources=123)
655 str_sources_row = dict(valid_row, id="n_str_src", sources="reddit")
656
657 payload["nominations"] = [
658 bad_items_row,
659 non_dict_nom_row,
660 non_list_items_row,
661 nan_score_row,
662 int_sources_row,
663 str_sources_row,
664 ]
665 path.write_text(json.dumps(payload), encoding="utf-8")
666
667 err = io.StringIO()
668 with redirect_stderr(err):
669 bundle = handoff.read_nominations_bundle(config_dir=tmp_path)
670
671 assert [row.nomination_id for row in bundle.nominations] == ["n_int_src", "n_str_src"]
672 # Neither int nor str sources crashes or splits into single characters.
673 assert bundle.nominations[0].sources == []
674 assert bundle.nominations[1].sources == []
675 warnings_out = err.getvalue()
676 assert "skipping unparseable nomination row 1" in warnings_out
677 assert "skipping unparseable nomination row 2" in warnings_out
678 assert "skipping unparseable nomination row 3" in warnings_out
679 assert "skipping unparseable nomination row 4" in warnings_out
680 assert "ignoring malformed sources list" in warnings_out
681
682
683 @pytest.mark.parametrize("field", ["enrichment_source_boundary", "requested_sources"])
684 @pytest.mark.parametrize("bad_val", ["reddit", 42, ["reddit", 7]])
685 def test_high093_bundle_malformed_context_source_lists_rejected(tmp_path: Path, field: str, bad_val):
686 _sample_bundle(tmp_path)
687 path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
688 payload = json.loads(path.read_text(encoding="utf-8"))
689 payload["context"][field] = bad_val
690 path.write_text(json.dumps(payload), encoding="utf-8")
691 with pytest.raises(handoff.HandoffContractError, match=field):
692 handoff.read_nominations_bundle(config_dir=tmp_path)
693
694
695 # ---------------------------------------------------------------------------
696 # Greptile Round 1 fixes (Findings 1-5)
697 # ---------------------------------------------------------------------------
698
699
700 def test_greptile_f1_lookback_days_3650_round_trips_and_over_limit_rejected_before_write_and_sweep(
701 tmp_path: Path,
702 ):
703 import argparse
704 import last30days as cli
705
706 # (a) Boundary value 3650 writes and reads back cleanly.
707 item = schema.SourceItem(
708 item_id="hn1",
709 source="hackernews",
710 title="Max Lookback Story",
711 body="Max Lookback Story",
712 url="https://hackernews.example/hn1",
713 published_at="2026-07-18",
714 engagement={"points": 100},
715 snippet="Snippet",
716 metadata={},
717 )
718 entry = handoff.PoolEntry(
719 nomination=pipeline.Nomination(
720 name="Max Lookback Story",
721 seed_score=42.0,
722 items=[item],
723 summary="Summary",
724 ),
725 cluster_id="c1",
726 heuristic_name="Max Lookback Story",
727 heuristic_junk=False,
728 )
729 written = handoff.write_nominations_bundle(
730 [entry],
731 domain="AI",
732 tier="deep",
733 from_date="2016-07-23",
734 to_date="2026-07-21",
735 lookback_days=handoff.MAX_LOOKBACK_DAYS,
736 enrichment_source_boundary=None,
737 requested_sources=["hackernews"],
738 config_dir=tmp_path,
739 )
740 reread = handoff.read_nominations_bundle(config_dir=tmp_path)
741 assert written.lookback_days == 3650
742 assert reread.lookback_days == 3650
743
744 # (b) Out-of-bounds / invalid lookback_days rejected before writing a bundle.
745 for bad_days in (4000, 0, -1, 1.5, True):
746 out_dir = tmp_path / f"bad_{type(bad_days).__name__}_{bad_days}"
747 with pytest.raises(handoff.HandoffContractError, match="lookback_days"):
748 handoff.write_nominations_bundle(
749 [entry],
750 domain="AI",
751 tier="deep",
752 from_date="2026-06-21",
753 to_date="2026-07-21",
754 lookback_days=bad_days, # type: ignore[arg-type]
755 enrichment_source_boundary=None,
756 requested_sources=["hackernews"],
757 config_dir=out_dir,
758 )
759 assert not (out_dir / handoff.NOMINATIONS_BUNDLE_FILENAME).exists()
760
761 # (c) CLI leg-1 entry rejects --days 4000 / 0 / -1 BEFORE running the sweep.
762 for bad_days in (4000, 0, -1):
763 args = argparse.Namespace(
764 discover="AI",
765 nominate_only=True,
766 judgments=None,
767 finalize=False,
768 lookback_days=bad_days,
769 deep=False,
770 quick=False,
771 mock=True,
772 subreddits=None,
773 as_of_date=None,
774 discover_shallow=False,
775 save_dir=str(tmp_path / "cli_reject"),
776 search=None,
777 exclude_sources=None,
778 )
779 err = io.StringIO()
780 with mock.patch.object(
781 cli, "_resolve_discovery_source_boundary", return_value=(None, None),
782 ), mock.patch.object(
783 cli.pipeline, "run_discover_nominate",
784 ) as mock_sweep, redirect_stderr(err):
785 rc = cli._run_discover_protocol_leg(args, {})
786 assert rc == 2
787 mock_sweep.assert_not_called()
788 assert "lookback_days" in err.getvalue()
789
790
791 @pytest.mark.parametrize(
792 "topic,expected_phrase",
793 [
794 ("New Balance", "New Balance"),
795 ("On Running", "On Running"),
796 ("Best Buy", "Best Buy"),
797 ("Best Buy earnings", "Best Buy"),
798 ("Best Buy layoffs", "Best Buy"),
799 ("Best Buy in 2026", "Best Buy"),
800 ("Best Buy for laptops", "Best Buy"),
801 ("Best Buy deals", "Best Buy"),
802 ("Best Buy vs Target", "Best Buy"),
803 ("Target vs Best Buy", "Best Buy"),
804 ("Best Egg loans", "Best Egg"),
805 ("Best Western", "Best Western"),
806 ("Fix Auto reviews", "Fix Auto"),
807 ("AWS Step Functions pricing", "AWS Step Functions"),
808 ("IBM Watson", "IBM Watson"),
809 ("Google AI", "Google AI"),
810 ("Open AI", "Open AI"),
811 ("The Verge", "The Verge"),
812 ("The Verge on AI", "The Verge"),
813 ("The Verge in 2026", "The Verge"),
814 ("The Verge review", "The Verge"),
815 ("The Verge layoffs", "The Verge"),
816 ("The Economist", "The Economist"),
817 ("The Atlantic", "The Atlantic"),
818 ("The Verge vs Wired", "The Verge"),
819 ("New Balance shoes", "New Balance"),
820 ("On Running review", "On Running"),
821 ("New York Times", "New York Times"),
822 ("On Running Cloudmonster", "On Running Cloudmonster"),
823 ],
824 )
825 def test_greptile_f2_query_preserves_noise_prefixed_brand_names(
826 topic: str, expected_phrase: str,
827 ):
828 compounds = query.extract_compound_terms(topic)
829 assert expected_phrase in compounds
830
831
832 def test_greptile_f2_query_still_strips_prompt_filler_and_keeps_brand_comparisons():
833 assert query.extract_compound_terms("what are the best Claude Code skills") == [
834 "Claude Code"
835 ]
836 assert query.extract_compound_terms("latest OpenClaw releases") == []
837 assert query.extract_compound_terms("Best GitHub Actions workflows for Python") == [
838 "GitHub Actions"
839 ]
840 assert query.extract_compound_terms("The Best Claude Code tips") == [
841 "Claude Code"
842 ]
843 assert query.extract_compound_terms("Best AI Tools") == []
844 assert query.extract_compound_terms("Best VPN for travel") == []
845 assert query.extract_compound_terms("Best VPN") == []
846 assert query.extract_compound_terms("Top CRM for startups") == []
847 assert query.extract_compound_terms("Top AI tools for coding") == []
848 assert query.extract_compound_terms("The best CRM for startups") == []
849 assert query.extract_compound_terms("The Best VPN for travel") == []
850 assert query.extract_compound_terms("The VPN") == []
851 assert query.extract_compound_terms("New VPN for travel") == []
852 assert query.extract_compound_terms("How to Install Docker") == []
853 assert query.extract_compound_terms("What Is Docker") == []
854 assert query.extract_compound_terms("New Balance vs On Running") == [
855 "New Balance",
856 "On Running",
857 ]
858
859
860 @pytest.mark.parametrize(
861 "topic,expected_search",
862 [
863 ("Best VPN for travel", "vpn travel"),
864 ("Best VPN", "vpn"),
865 ("Top CRM for startups", "crm startups"),
866 ("Top AI tools for coding", "ai coding"),
867 ("The best CRM for startups", "crm startups"),
868 ("The Best VPN for travel", "vpn travel"),
869 ("New VPN for travel", "vpn travel"),
870 ("How to Install Docker", "install docker"),
871 ],
872 )
873 def test_greptile_r2_f1_recommendation_prompts_never_quote_prompt_filler(
874 topic: str, expected_search: str,
875 ):
876 core = query.extract_core_subject(topic, max_words=6, strip_suffixes=True)
877 kw = planner._keyword_query(topic, core)
878 assert '"' not in kw
879 assert kw == expected_search
880
881 plan = planner._fallback_plan(
882 topic=topic,
883 available_sources=["reddit", "x"],
884 requested_sources=None,
885 depth="default",
886 )
887 assert plan.subqueries
888 assert plan.subqueries[0].search_query == expected_search
889
890
891 @pytest.mark.parametrize(
892 "topic,expected_search",
893 [
894 ("New Balance", '"New Balance"'),
895 ("On Running", '"On Running"'),
896 ("Best Buy", '"Best Buy"'),
897 ("Best Buy earnings", '"Best Buy" earnings'),
898 ("Best Buy layoffs", '"Best Buy" layoffs'),
899 ("Best Buy in 2026", '"Best Buy" 2026'),
900 ("Best Buy for laptops", '"Best Buy" laptops'),
901 ("Best Buy deals", '"Best Buy" deals'),
902 ("Best Egg loans", '"Best Egg" loans'),
903 ("Fix Auto reviews", '"Fix Auto"'),
904 ("AWS Step Functions pricing", '"AWS Step Functions" pricing'),
905 ("IBM Watson", '"IBM Watson"'),
906 ("Google AI", '"Google AI"'),
907 ("The Verge", '"The Verge"'),
908 ("The Verge on AI", '"The Verge" ai'),
909 ("The Verge in 2026", '"The Verge" 2026'),
910 ("The Verge review", '"The Verge"'),
911 ],
912 )
913 def test_greptile_f2_planner_keeps_full_brand_intact_in_fallback_queries(
914 topic: str, expected_search: str,
915 ):
916 core = query.extract_core_subject(topic, max_words=6, strip_suffixes=True)
917 kw = planner._keyword_query(topic, core)
918 assert kw == expected_search
919
920 plan = planner._fallback_plan(
921 topic=topic,
922 available_sources=["reddit", "x"],
923 requested_sources=None,
924 depth="default",
925 )
926 assert plan.subqueries
927 assert plan.subqueries[0].search_query == expected_search
928
929
930 def test_greptile_f3_competitors_filters_multiword_spaced_self_brand_variants():
931 coke_tokens = competitors._topic_tokens("Coca-Cola")
932 for self_variant in (
933 "Coca Cola Zero",
934 "Diet Coca Cola",
935 "CocaCola Zero",
936 "The Official Coca Cola Zero Beverage Company",
937 ):
938 assert not competitors._candidate_ok(self_variant, coke_tokens), (
939 f"Self-brand variant {self_variant!r} leaked for Coca-Cola"
940 )
941 assert competitors._candidate_ok("Pepsi", coke_tokens)
942 assert competitors._candidate_ok("Pepsi-Cola", coke_tokens)
943
944 serp = [
945 {
946 "title": "Coca Cola Zero vs Pepsi",
947 "snippet": "Coca Cola Zero and Pepsi compete for sugar-free soda drinkers.",
948 "url": "https://example.test/soda",
949 },
950 ]
951 peers = competitors._extract_peer_entities(serp, "Coca-Cola", limit=3)
952 assert "Coca Cola Zero" not in peers
953 assert "Pepsi" in peers
954
955 assert not competitors._candidate_ok("AT T Fiber", competitors._topic_tokens("AT&T"))
956 assert not competitors._candidate_ok(
957 "T Mobile Home Internet", competitors._topic_tokens("T-Mobile")
958 )
959 assert not competitors._candidate_ok("Node JS Runtime", competitors._topic_tokens("Node.js"))
960
961 # No substring false positives inside unrelated words.
962 on_tokens = competitors._topic_tokens("On")
963 assert competitors._candidate_ok("Notion", on_tokens)
964 assert competitors._candidate_ok("Discord", on_tokens)
965 assert competitors._candidate_ok("OpenAI", competitors._topic_tokens("Open"))
966
967
968 def test_greptile_f4_bad_item_source_null_row_skipped_without_crashing_resume(
969 tmp_path: Path,
970 ):
971 _sample_bundle(tmp_path)
972 path = tmp_path / handoff.NOMINATIONS_BUNDLE_FILENAME
973 payload = json.loads(path.read_text(encoding="utf-8"))
974 valid_row = payload["nominations"][0]
975 valid_item = valid_row["nomination"]["items"][0]
976
977 # Row with mixed null + string item.source (used to crash sorted(...) in
978 # resolve_name_collisions with TypeError).
979 null_source_row = {
980 "id": "n_bad_source",
981 "cluster_id": "c-bad",
982 "heuristic_name": "Broken Source Row",
983 "heuristic_junk": False,
984 "sources": ["reddit"],
985 "nomination": {
986 "name": "Broken Source Row",
987 "seed_score": 30.0,
988 "summary": "Summary",
989 "items": [
990 dict(valid_item, item_id="i1", source=None),
991 dict(valid_item, item_id="i2", source="reddit"),
992 ],
993 },
994 }
995 bad_title_row = {
996 "id": "n_bad_title",
997 "nomination": {
998 "name": "Bad Title Row",
999 "seed_score": 25.0,
1000 "items": [dict(valid_item, item_id="i3", title=123)],
1001 },
1002 }
1003 bad_summary_row = {
1004 "id": "n_bad_summary",
1005 "nomination": {
1006 "name": "Bad Summary Row",
1007 "seed_score": 20.0,
1008 "summary": ["not-a-str"],
1009 "items": [valid_item],
1010 },
1011 }
1012 bad_comments_row = {
1013 "id": "n_bad_comments",
1014 "nomination": {
1015 "name": "Bad Comments Row",
1016 "seed_score": 15.0,
1017 "items": [dict(valid_item, metadata={"top_comments": 42})],
1018 },
1019 }
1020
1021 payload["nominations"] = [
1022 null_source_row,
1023 bad_title_row,
1024 bad_summary_row,
1025 bad_comments_row,
1026 valid_row,
1027 ]
1028 path.write_text(json.dumps(payload), encoding="utf-8")
1029
1030 err = io.StringIO()
1031 with redirect_stderr(err):
1032 bundle = handoff.read_nominations_bundle(config_dir=tmp_path)
1033
1034 assert [row.nomination_id for row in bundle.nominations] == ["n1"]
1035 warnings_out = err.getvalue()
1036 assert "skipping unparseable nomination row 1" in warnings_out
1037 assert "skipping unparseable nomination row 2" in warnings_out
1038 assert "skipping unparseable nomination row 3" in warnings_out
1039 assert "skipping unparseable nomination row 4" in warnings_out
1040
1041 # Downstream resume helpers run cleanly over the surviving healthy rows.
1042 resolved = handoff.resolve_name_collisions(
1043 [(row.nomination, row.heuristic_name) for row in bundle.nominations]
1044 )
1045 assert resolved == ["Sample Story"]
1046 digest = handoff.build_host_digest(bundle)
1047 assert "Sample Story" in digest
1048
1049
1050 def test_greptile_f5_resolve_github_and_prose_url_segment_boundaries():
1051 # Dotted segment must NOT be truncated to "team".
1052 dotted_snippet = [
1053 {"title": "Docs", "snippet": "See https://github.com/team.example/project", "url": ""},
1054 ]
1055 dotted_url = [
1056 {"title": "Docs", "snippet": "", "url": "https://github.com/team.example/project"},
1057 ]
1058 assert resolve._extract_github_user(dotted_snippet) == ""
1059 assert resolve._extract_github_user(dotted_url) == ""
1060 assert resolve._extract_github_repos(dotted_snippet) == []
1061 assert resolve._extract_github_repos(dotted_url) == []
1062
1063 # Trailing prose punctuation and normal repo paths MUST still match "team".
1064 assert resolve._extract_github_user([
1065 {"title": "Profile", "snippet": "See https://github.com/team.", "url": ""},
1066 ]) == "team"
1067 assert resolve._extract_github_user([
1068 {"title": "Profile", "snippet": "(https://github.com/team)", "url": ""},
1069 ]) == "team"
1070 assert resolve._extract_github_user([
1071 {"title": "Repo", "snippet": "Check https://github.com/team/repo", "url": ""},
1072 ]) == "team"
1073 assert resolve._extract_github_repos([
1074 {"title": "Repo", "snippet": "Check https://github.com/team/repo.", "url": ""},
1075 ]) == ["team/repo"]
1076 assert resolve._extract_github_repos([
1077 {"title": "Repo", "snippet": "See https://github.com/vercel/next.js.", "url": ""},
1078 ]) == ["vercel/next.js"]
1079
1080 # Same path-segment discipline on Reddit prose URLs and dotted @handles.
1081 assert resolve._extract_subreddits([
1082 {"title": "Link", "snippet": "See https://reddit.com/r/team.example/comments/1", "url": ""},
1083 ]) == []
1084 assert resolve._extract_x_handle([
1085 {"title": "Bluesky", "snippet": "Follow @alice.bsky.social on Bluesky", "url": ""},
1086 ]) == ""
1087
1088 # Curly quotes around handles, subreddits, and GitHub links still extract cleanly.
1089 assert resolve._extract_x_handle([
1090 {"title": "Quote", "snippet": "Follow \u201c@SpaceX\u201d for launch updates", "url": ""},
1091 ]) == "spacex"
1092 assert resolve._extract_x_handle([
1093 {"title": "SingleQuote", "snippet": "Follow \u2018@SpaceX\u2019", "url": ""},
1094 ]) == "spacex"
1095 assert resolve._extract_x_handle([
1096 {"title": "QuotePeriod", "snippet": "Follow \u201c@SpaceX.\u201d", "url": ""},
1097 ]) == "spacex"
1098 assert resolve._extract_subreddits([
1099 {"title": "QuoteSub", "snippet": "Check \u201cr/python\u201d and \u2018r/rust\u2019", "url": ""},
1100 ]) == ["python", "rust"]
1101 assert resolve._extract_github_user([
1102 {"title": "QuoteGH", "snippet": "See \u201chttps://github.com/team\u201d", "url": ""},
1103 ]) == "team"
1104
1105
1105 lines PYTHON