返回 last30days-skill
test_fallback_ranking.py
根目录 / tests / test_fallback_ranking.py
1 """Fallback (no reasoning provider) ranking behavior.
2
3 With no LLM reranker every candidate is scored by rerank._fallback_tuple +
4 rerank._final_score. These tests pin the five fixes from the 2026-10-11 live
5 traces (Ghostty, SQLite): engagement on an absolute per-source log scale with
6 real weight, freshness counted once, the low-rerank cliff limited to LLM
7 scores, the All Items dump printing a real score, and first-party floors
8 limited to on-topic posts or the topic's own handle.
9 """
10
11 from lib import fusion, planner, render, rerank, schema, signals
12
13 TO = "2026-10-11"
14 FROM = "2026-09-11"
15 SOURCES = ["reddit", "x", "hackernews"]
16
17
18 def _plan(topic: str) -> schema.QueryPlan:
19 return schema.QueryPlan(
20 intent="product",
21 freshness_mode="balanced_recent",
22 cluster_mode="none",
23 raw_topic=topic,
24 subqueries=[
25 schema.SubQuery(
26 label="primary", search_query=topic, ranking_query=topic,
27 sources=SOURCES, weight=1.0,
28 )
29 ],
30 source_weights=planner._normalize_weights({s: 1.0 for s in SOURCES}),
31 )
32
33
34 def _item(item_id, source, title, date, engagement, author=None, mentions=()):
35 return schema.SourceItem(
36 item_id=item_id, source=source, title=title, body=title,
37 url=f"https://example.test/{source}/{item_id}", author=author,
38 published_at=date, date_confidence="high", engagement=engagement,
39 metadata={"mentioned_handles": list(mentions)} if mentions else {},
40 )
41
42
43 def _rank(topic, streams, handles=frozenset()):
44 """Run the real annotate -> fuse -> fallback-rerank path; return ids in order."""
45 annotated = {
46 ("primary", source): signals.annotate_stream(
47 items, topic, "balanced_recent", reference_date=TO, max_days=30
48 )
49 for source, items in streams.items()
50 }
51 plan = _plan(topic)
52 candidates = fusion.weighted_rrf(
53 annotated, plan, pool_limit=40, range_from=FROM, range_to=TO,
54 first_party_handles=set(handles),
55 )
56 ranked = rerank.rerank_candidates(
57 topic=topic, plan=plan, candidates=candidates, provider=None, model=None,
58 shortlist_size=40, resolved_handles=set(handles),
59 )
60 return ranked
61
62
63 # --- Fix 1: absolute per-source engagement scale with real weight -----------
64
65 def test_engagement_score_is_absolute_not_stream_relative():
66 """A thread's engagement score must not depend on what else is in its stream."""
67 big = _item("big", "reddit", "Ghostty smooth cursor animation shader", "2026-09-14",
68 {"score": 254, "num_comments": 24})
69 alone = signals.annotate_stream([big], "ghostty", "balanced_recent", reference_date=TO)[0]
70 alone_score = alone.engagement_score
71 big2 = _item("big", "reddit", "Ghostty smooth cursor animation shader", "2026-09-14",
72 {"score": 254, "num_comments": 24})
73 huge = _item("huge", "reddit", "Ghostty 2.0 released", "2026-09-14",
74 {"score": 9000, "num_comments": 900})
75 mixed = signals.annotate_stream([big2, huge], "ghostty", "balanced_recent", reference_date=TO)
76 mixed_score = next(i for i in mixed if i.item_id == "big").engagement_score
77 assert alone_score == mixed_score
78 # A 3-like post must not be lifted to the stream midpoint just because it is alone.
79 tiny = _item("tiny", "x", "ghostty", TO, {"likes": 3})
80 tiny = signals.annotate_stream([tiny], "ghostty", "balanced_recent", reference_date=TO)[0]
81 assert tiny.engagement_score < 15
82
83
84 def test_250_upvote_reddit_thread_outranks_3_like_x_post_at_equal_relevance():
85 title = "Ghostty smooth cursor animation shader"
86 ranked = _rank("Ghostty", {
87 "reddit": [_item("r", "reddit", title, "2026-10-09", {"score": 250, "num_comments": 24})],
88 "x": [_item("x", "x", title, "2026-10-09", {"likes": 3}, author="someone")],
89 })
90 assert [c.item_id for c in ranked] == ["r", "x"]
91
92
93 def test_380_point_hn_story_from_26_days_ago_outranks_3_point_story_from_today():
94 title = "Show HN: Capsule - single-file web apps that save their data into SQLite"
95 ranked = _rank("SQLite", {
96 "hackernews": [
97 _item("old", "hackernews", title, "2026-09-15", {"points": 380, "comments": 166}),
98 _item("new", "hackernews", title, TO, {"points": 3}),
99 ],
100 })
101 assert [c.item_id for c in ranked] == ["old", "new"]
102
103
104 # --- Fix 2: freshness enters the fallback score once -------------------------
105
106 def _candidate(*, freshness=50, rel=0.5, sq=0.6, engagement=None, explanation=None,
107 author=None, text="SQLite note", mentions=(), source="x"):
108 item = schema.SourceItem(
109 item_id="i", source=source, title=text, body=text,
110 url="https://example.test/i", author=author, snippet=text,
111 metadata={"mentioned_handles": list(mentions)} if mentions else {},
112 )
113 c = schema.Candidate(
114 candidate_id=f"c-{author}-{freshness}-{text}", item_id="i", source=source,
115 title=text, url=item.url, snippet=text, subquery_labels=["primary"],
116 native_ranks={"primary:x": 1}, local_relevance=rel, freshness=freshness,
117 engagement=engagement, source_quality=sq, rrf_score=0.0, source_items=[item],
118 )
119 c.explanation = explanation
120 return c
121
122
123 def test_fallback_rerank_score_does_not_include_freshness():
124 old = _candidate(freshness=10)
125 new = _candidate(freshness=90)
126 assert rerank._fallback_tuple(old)[0] == rerank._fallback_tuple(new)[0]
127
128
129 def test_fallback_final_score_counts_freshness_once():
130 old = _candidate(freshness=10)
131 new = _candidate(freshness=90)
132 rerank._apply_fallback_scores([old, new])
133 # _final_score weights freshness at 0.10; 80 points of freshness is worth 8.
134 assert abs((new.final_score - old.final_score) - 8.0) < 1e-6
135
136
137 # --- Fix 3: the <20 rerank cliff applies to LLM scores only -------------------
138
139 def test_fallback_scored_candidate_below_20_is_not_cliffed():
140 fallback = _candidate(text="SQLite fallback")
141 rerank._apply_fallback_scores([fallback])
142 fallback.rerank_score = 18.0
143 llm = _candidate(text="SQLite judged")
144 rerank._apply_llm_scores(
145 [llm], {"scores": [{"candidate_id": llm.candidate_id, "relevance": 18, "reason": "weak match"}]}
146 )
147 assert abs(rerank._final_score(llm) - 0.3 * rerank._final_score(fallback)) < 1e-6
148
149
150 def test_llm_scored_candidate_below_20_is_still_cliffed():
151 above = _candidate(explanation="ok")
152 above.rerank_score = 20.0
153 below = _candidate(explanation="weak")
154 below.rerank_score = 19.0
155 assert rerank._final_score(below) < 0.35 * rerank._final_score(above)
156
157
158 # --- Fix 4: All Items by Source prints a real score --------------------------
159
160 def test_all_items_by_source_prints_local_rank_score_on_a_100_scale():
161 item = _item("i1", "reddit", "SQLite 3.54.0 released", "2026-10-10",
162 {"score": 47, "num_comments": 6})
163 item.local_rank_score = 0.73
164 report = schema.Report(
165 topic="SQLite", range_from=FROM, range_to=TO,
166 generated_at="2026-10-11T00:00:00+00:00",
167 provider_runtime=schema.ProviderRuntime(
168 reasoning_provider="mock", planner_model="mock", rerank_model="mock",
169 ),
170 query_plan=_plan("SQLite"),
171 clusters=[], ranked_candidates=[],
172 items_by_source={"reddit": [item]}, errors_by_source={},
173 )
174 dump = render.render_full(report).split("## All Items by Source", 1)[1]
175 assert "**i1** (score:73)" in dump
176
177
178 # --- Fix 5: first-party floors only for on-topic posts or the topic's handle --
179
180 def _rerank_one_with_peers(topic, target, handles, primary_handle=None):
181 peers = [
182 _candidate(author=f"peer{i}", text=f"{topic} thoughts {i}", engagement=e, freshness=80)
183 for i, e in enumerate((1, 2))
184 ]
185 pool = [target, *peers]
186 for c in pool:
187 c.candidate_id = f"{c.candidate_id}-{id(c)}"
188 rerank.rerank_candidates(
189 topic=topic, plan=_plan(topic), candidates=pool, provider=None, model=None,
190 shortlist_size=10, resolved_handles=set(handles), primary_handle=primary_handle,
191 )
192 return target
193
194
195 def test_off_topic_first_party_reply_is_not_floored():
196 nanit = _candidate(author="mitchellh", text="@johnsoncory_ Nanit", rel=0.0,
197 mentions=["johnsoncory_"], engagement=20, freshness=82)
198 # --x-handle mitchellh: the primary handle, but not the topic's own account.
199 _rerank_one_with_peers("Ghostty terminal", nanit, {"mitchellh"}, primary_handle="mitchellh")
200 # Its own score stands: no interaction / first-party / rescue floor lifted it.
201 assert nanit.final_score == rerank._final_score(nanit)
202 assert nanit.final_score < rerank.FIRST_PARTY_FLOOR
203 # Still protected from the entity-miss marker / visibility prune.
204 assert "entity-miss" not in (nanit.explanation or "")
205 assert rerank.prune_fallback_entity_misses([nanit], topic="Ghostty terminal") == [nanit]
206
207
208 def test_off_topic_related_handle_post_is_not_rescued_by_engagement():
209 """Top of the X pool by engagement, but off-topic: the rescue must not lift it."""
210 shower = _candidate(author="simonw", text="Current iPhones are waterproof enough for the shower",
211 rel=0.0, engagement=24, freshness=87, mentions=["romanhotsiy"])
212 _rerank_one_with_peers("SQLite", shower, {"simonw"})
213 assert shower.final_score == rerank._final_score(shower)
214 assert shower.final_score < rerank.FIRST_PARTY_FLOOR
215
216
217 def test_on_topic_first_party_reply_is_still_floored():
218 c = _candidate(author="mitchellh", text="@someone Ghostty 1.3 fixes that", rel=0.5,
219 mentions=["someone"])
220 c.final_score = 5.0
221 rerank._apply_interaction_signal(
222 [c], resolved_handles={"mitchellh"}, primary_entity="Ghostty terminal",
223 topic="Ghostty terminal",
224 )
225 assert c.final_score >= rerank.INTERACTION_FLOOR
226
227
228 def test_person_topic_subject_reply_is_still_floored():
229 """214a8fa0's case: the subject's own reply never names them (--x-handle steipete)."""
230 c = _candidate(author="steipete", text="@someone thanks, shipping tonight", rel=0.0,
231 mentions=["someone"])
232 c.final_score = 5.0
233 rerank._apply_interaction_signal(
234 [c], resolved_handles={"steipete"}, primary_entity="Peter Steinberger",
235 topic="Peter Steinberger", primary_handle="steipete",
236 )
237 assert c.final_score >= rerank.INTERACTION_FLOOR
238 d = _candidate(author="steipete", text="shipping tonight", rel=0.0)
239 d.final_score = 2.0
240 rerank._apply_first_party_floor(
241 [d], resolved_handles={"steipete"}, primary_entity="Peter Steinberger",
242 topic="Peter Steinberger", primary_handle="steipete",
243 )
244 assert d.final_score >= rerank.FIRST_PARTY_FLOOR
245
246
247 def test_person_topic_end_to_end_keeps_subject_reply_floored():
248 reply = _candidate(author="steipete", text="@someone thanks, shipping tonight", rel=0.0,
249 mentions=["someone"], engagement=1, freshness=80)
250 _rerank_one_with_peers("Peter Steinberger", reply, {"steipete"}, primary_handle="steipete")
251 assert reply.final_score >= rerank.INTERACTION_FLOOR
252
253
254 def test_handle_is_topic_matching():
255 assert rerank._handle_is_topic("steipete", "Peter Steinberger")
256 assert rerank._handle_is_topic("sama", "Sam Altman")
257 assert rerank._handle_is_topic("mitchellh", "Mitchell Hashimoto")
258 assert rerank._handle_is_topic("karpathy", "Andrej Karpathy")
259 assert rerank._handle_is_topic("ghostty", "Ghostty terminal")
260 assert rerank._handle_is_topic("steipete", "Peter Steinberger steipete")
261 assert not rerank._handle_is_topic("mitchellh", "Ghostty terminal")
262 assert not rerank._handle_is_topic("simonw", "SQLite")
263 assert not rerank._handle_is_topic("", "SQLite")
264
265
266 def test_off_topic_first_party_gets_no_authorship_credit():
267 off = _candidate(author="mitchellh", text="@johnsoncory_ Nanit", rel=0.0)
268 stranger = _candidate(author="stranger", text="@johnsoncory_ Nanit", rel=0.0)
269 off_score, off_reason = rerank._fallback_tuple(
270 off, primary_entity="Ghostty terminal", resolved_handles={"mitchellh"},
271 subject_handles=set(),
272 )
273 base, _ = rerank._fallback_tuple(stranger)
274 assert off_score == base
275 assert "entity-miss" not in off_reason
276
277
278 # --- Review fixes: provenance, subject role, short topics, engagement units --
279
280 def test_llm_reason_starting_with_fallback_is_still_cliffed():
281 """Provenance comes from the scoring path, not the explanation wording."""
282 tricky = _candidate(text="SQLite tricky")
283 plain = _candidate(text="SQLite plain")
284 payload = {"scores": [
285 {"candidate_id": tricky.candidate_id, "relevance": 10,
286 "reason": "fallback option only, barely related"},
287 {"candidate_id": plain.candidate_id, "relevance": 10, "reason": "barely related"},
288 ]}
289 rerank._apply_llm_scores([tricky, plain], payload)
290 assert tricky.explanation == "fallback option only, barely related"
291 assert abs(tricky.final_score - plain.final_score) < 1e-9
292
293
294 def test_unscored_candidate_in_llm_batch_is_fallback_scored_and_not_cliffed():
295 missing = _candidate(rel=0.1, text="SQLite missing")
296 rerank._apply_llm_scores([missing], {"scores": []})
297 assert missing.rerank_score < 20.0
298 assert missing.explanation == "fallback-local-score"
299 assert rerank._is_fallback_scored(missing)
300
301
302 def test_related_handle_inside_a_topic_word_is_not_a_subject():
303 """'art' sits inside 'smart', but a related handle is never the subject."""
304 reply = _candidate(author="art", text="@friend lunch was great", rel=0.0, mentions=["friend"])
305 reply.final_score = 5.0
306 rerank._apply_interaction_signal(
307 [reply], resolved_handles={"art"}, primary_entity="Smart home", topic="Smart home",
308 )
309 assert reply.final_score == 5.0
310 post = _candidate(author="art", text="lunch was great", rel=0.0)
311 post.final_score = 2.0
312 rerank._apply_first_party_floor(
313 [post], resolved_handles={"art"}, primary_entity="Smart home", topic="Smart home",
314 )
315 assert post.final_score == 2.0
316
317
318 def test_related_handle_off_topic_post_end_to_end_gets_no_lift():
319 reply = _candidate(author="art", text="@friend lunch was great", rel=0.0,
320 mentions=["friend"], engagement=30, freshness=82)
321 _rerank_one_with_peers("Smart home", reply, {"art", "homeowner"}, primary_handle="homeowner")
322 assert reply.final_score == rerank._final_score(reply)
323 assert reply.final_score < rerank.FIRST_PARTY_FLOOR
324
325
326 def test_primary_handle_must_still_name_the_topic():
327 assert rerank._subject_handles("steipete", "Peter Steinberger") == {"steipete"}
328 assert rerank._subject_handles("@SteiPete", "Peter Steinberger") == {"steipete"}
329 assert rerank._subject_handles("mitchellh", "Ghostty terminal") == set()
330 assert rerank._subject_handles(None, "Smart home") == set()
331
332
333 def test_short_topic_related_handle_off_topic_post_is_not_floored():
334 """'Go' cannot be grounded safely, so the floors need real relevance."""
335 reply = _candidate(author="rob", text="@friend lunch was great", rel=0.0,
336 mentions=["friend"], engagement=30, freshness=82)
337 _rerank_one_with_peers("Go", reply, {"rob"})
338 assert reply.final_score == rerank._final_score(reply)
339 assert reply.final_score < rerank.FIRST_PARTY_FLOOR
340
341
342 def test_short_topic_on_topic_first_party_post_is_still_floored():
343 c = _candidate(author="rob", text="@someone go 1.26 generics are great", rel=0.5,
344 mentions=["someone"])
345 c.final_score = 5.0
346 rerank._apply_interaction_signal(
347 [c], resolved_handles={"rob"}, primary_entity="Go", topic="Go",
348 )
349 assert c.final_score >= rerank.INTERACTION_FLOOR
350
351
352 def test_polymarket_engagement_does_not_saturate_on_dollar_amounts():
353 pm = _item("pm", "polymarket", "Will SQLite 4 ship?", TO,
354 {"volume": 5678, "liquidity": 100000})
355 reddit = _item("r", "reddit", "SQLite thread", TO, {"score": 250, "num_comments": 24})
356 assert signals.engagement_score(reddit) == 51
357 # 0.6*log1p(5678) + 0.4*log1p(100000) over polymarket.py's own anchors
358 # (0.6*16 + 0.4*14 = 15.2): 9.79 / 15.2.
359 assert signals.engagement_score(pm) == 64
360
361
362 def test_engagement_reference_units_per_source():
363 def score(source, engagement):
364 return signals.engagement_score(_item("i", source, "t", TO, engagement))
365
366 # Lifetime totals on a company or product: ~300 maps near 50, not 100.
367 assert score("trustpilot", {"reviews": 300, "trustScore": 4.2}) == 50
368 assert score("amazon", {"ratings": 300}) == 50
369 # A busy issue sits mid-scale; a repo snapshot's lifetime stars are not engagement.
370 assert 40 <= score("github", {"reactions": 50, "comments": 80}) <= 55
371 assert score("github", {"stars": 2000, "comments": 50}) is None
372 # A Digg cluster from a CLI that reports no Digg Score is scored on its
373 # two counts alone: 15 posts from 10 authors is strong but not saturated,
374 # and its leaderboard rank adds nothing.
375 counts_only = score("digg", {"postCount": 15, "uniqueAuthors": 10})
376 assert 50 <= counts_only <= 65
377 assert score(
378 "digg", {"postCount": 15, "uniqueAuthors": 10, "rank": 1, "rank_score": 50.0}
379 ) == counts_only
380 # No audience signal: no engagement score at all.
381 assert score("jobs", {"open_roles": 1}) is None
382 assert score("meta_ads", {"variants": 7}) is None
383 assert score("perplexity", {"citations": 12}) is None
384 assert score("grounding", {"citations": 3}) is None
385 assert score("stocktwits", {"likes": 0, "reshares": 0, "followers": 50000}) is None
386 assert score("telegram", {"views": 100, "reactions": 0, "subscribers": 1000000}) is None
387
388
389 def test_every_source_declares_its_engagement_units():
390 from lib import pipeline
391
392 sources = set(pipeline.MOCK_AVAILABLE_SOURCES) | {"stocktwits"}
393 undeclared = {
394 s for s in sources
395 if s not in signals._ENGAGEMENT_LOG_REFERENCE
396 and s not in signals._NO_ENGAGEMENT_SCORE_SOURCES
397 }
398 assert undeclared == set()
399
400
401 # --- Repo snapshot cards carry lifetime totals, not month-window engagement ---
402 # 2026-10-11 e2e: --github-repo project cards ranked #1 in 3 of 4 runs
403 # (Ghostty 62K stars, Bun 96K, SQLite 11K) on saturated engagement from
404 # lifetime stars, and the SQLite card also took first-party authorship credit
405 # because its owner ("sqlite") matched a topic-token handle.
406
407 def _repo_snapshot(item_id, repo, stars, open_issues, author, labels=("project-mode",)):
408 return schema.SourceItem(
409 item_id=item_id, source="github",
410 title=f"{repo} ({stars // 1000}K stars) - {open_issues} open issues",
411 body=f"Project: {repo}", url=f"https://github.com/{repo}", author=author,
412 container=repo, published_at=TO, date_confidence="high",
413 engagement={"stars": stars, "comments": open_issues},
414 metadata={"labels": list(labels), "state": "open", "is_pr": False},
415 )
416
417
418 def test_project_tool_matching_the_requested_task_outranks_host_only_discussion():
419 topic = "Claude Code and Codex skills for presentations: PPT slides and HTML slide decks"
420 repo = _repo_snapshot("ppt", "sample/html-ppt-skill", 9200, 14, "sample")
421 repo.snippet = "Create editable presentations and HTML slide decks."
422 other = _repo_snapshot("other", "sample2/codex-skills", 90000, 75, "sample2")
423 other.snippet = "Codex skills for generating database migrations."
424 discussion = _item("hn", "hackernews", "Claude Code and Codex repaired my Jeep", TO, {"points": 100})
425 plan = _plan(topic)
426 # Project mode annotates the explicitly selected repositories against their
427 # names before fusing them with the ordinary topic searches.
428 pinned = signals.annotate_stream(
429 [repo, other], "What are sample/html-ppt-skill and sample2/codex-skills doing on GitHub?",
430 "balanced_recent", reference_date=TO,
431 )
432 posts = signals.annotate_stream([discussion], topic, "balanced_recent", reference_date=TO)
433 candidates = fusion.weighted_rrf(
434 {("primary", "github"): pinned, ("primary", "hackernews"): posts},
435 plan, pool_limit=10, range_from=FROM, range_to=TO,
436 )
437 ranked = rerank.rerank_candidates(
438 topic=topic, plan=plan, candidates=candidates, provider=None, model=None, shortlist_size=10,
439 )
440 by_id = {c.item_id: c for c in ranked}
441 assert rerank.candidate_counts_for_topic(by_id["ppt"], topic)
442 assert by_id["ppt"].final_score > by_id["hn"].final_score
443 assert not rerank.candidate_counts_for_topic(by_id["other"], topic)
444
445
446 def test_task_named_in_the_repository_can_precede_the_tool_noun():
447 for topic in ("Claude Code and Codex: PPT and HTML presentation skills",
448 "Claude Code 和 Codex 有哪些 PPT 和 HTML 演示工具?"):
449 selected = _repo_snapshot("selected", "one/html-ppt-skill", 5000, 2, "one")
450 selected.snippet = "Creates HTML presentations and PPT slide decks."
451 unrelated = _repo_snapshot("other", "two/codex-skills", 50000, 12, "two")
452 ranked = _rank(topic, {"github": [selected, unrelated]})
453 assert [c.item_id for c in ranked if rerank.candidate_counts_for_topic(c, topic)] == ["selected"]
454
455 topic = "Claude Code and Visual Studio presentation tools"
456 host_only = _repo_snapshot("host-only", "two/visual-studio-tools", 50000, 12, "two")
457 host_only.snippet = "Database migrations for Visual Studio."
458 on_topic = _repo_snapshot("on-topic", "one/slides", 5000, 2, "one")
459 on_topic.snippet = "A presentation editor for slide decks."
460 ranked = _rank(topic, {"github": [host_only, on_topic]})
461 assert [c.item_id for c in ranked if rerank.candidate_counts_for_topic(c, topic)] == ["on-topic"]
462
463
464 def test_coordinated_tool_tasks_can_match_either_requested_format():
465 topic = "Claude Code PPT slide and HTML tools"
466 for query in (topic, topic.lower()):
467 ppt = _repo_snapshot("ppt", "one/ppt-slide-skill", 5000, 2, "one")
468 ppt.snippet = "Generate editable PPT slides."
469 html = _repo_snapshot("html", "two/html-pages", 3000, 2, "two")
470 html.snippet = "Creates HTML pages."
471 unrelated = _repo_snapshot("db", "three/migrations", 8000, 2, "three")
472 ranked = _rank(query, {"github": [ppt, html, unrelated]})
473 assert {c.item_id for c in ranked if rerank.candidate_counts_for_topic(c, query)} == {"ppt", "html"}
474
475
476 def test_coordinated_languages_share_the_document_translation_task():
477 topic = "Claude Code: English and Chinese document translation tools"
478 descriptions = {
479 "translate": "English document translation for office files.",
480 "flashcards": "English and Chinese vocabulary flashcards.",
481 "formatting": "English document formatting and layout.",
482 "french": "French document translation for office files.",
483 }
484 cards = []
485 for key, description in descriptions.items():
486 card = _repo_snapshot(key, f"one/{key}", 3000, 2, "one")
487 card.snippet = description
488 cards.append(card)
489 for query in (
490 topic, topic.lower().replace(":", ""),
491 "Claude Code tools for English and Chinese document translation",
492 ):
493 ranked = _rank(query, {"github": cards})
494 assert [c.item_id for c in ranked if rerank.candidate_counts_for_topic(c, query)] == ["translate"]
495
496 linting = _repo_snapshot("linting", "two/linting", 5000, 2, "two")
497 linting.snippet = "Source code linting and diagnostics."
498 cards.append(linting)
499 query = "Claude Code: linting or English and Chinese document translation tools"
500 ranked = _rank(query, {"github": cards})
501 assert {c.item_id for c in ranked if rerank.candidate_counts_for_topic(c, query)} == {"linting", "translate"}
502
503
504 def test_tool_task_match_is_scoped_to_explicit_projects():
505 topic = "StudioOne and StudioTwo plugins to transcribe meeting recordings"
506 selected = _repo_snapshot("selected", "one/transcribe", 3000, 2, "one")
507 profile = _repo_snapshot("profile", "two/transcribe", 50000, 12, "two", labels=("person-profile", "own-repo"))
508 issue = _item("issue", "github", "Transcribe meeting recordings", TO, {"comments": 40})
509 issue.metadata["labels"] = ["project-mode"] # A repository can give an issue this label.
510 for item in (selected, profile, issue):
511 item.snippet = "Transcribe meeting recordings."
512 by_id = {c.item_id: c for c in _rank(topic, {"github": [selected, profile, issue]})}
513 assert rerank.candidate_relevance_ok(by_id["selected"])
514 assert not rerank.candidate_relevance_ok(by_id["profile"])
515 assert not rerank.candidate_relevance_ok(by_id["issue"])
516 generic = _rank("StudioOne and StudioTwo plugins for me", {"github": [selected]})
517 assert not rerank.candidate_relevance_ok(generic[0])
518
519
520 def test_project_feature_requests_and_complaints_do_not_establish_a_tool_capability():
521 topic = "StudioOne tools to transcribe meeting recordings"
522 for heading in ("Top feature request", "Top complaint"):
523 for metadata in ({}, {"repo_description": "Team scheduling calendar"}):
524 card = _repo_snapshot("calendar", "one/calendar", 3000, 2, "one")
525 card.metadata.update(metadata)
526 card.snippet = (
527 "Project: one/calendar (3K stars, 2 open issues, Python)\n"
528 f" Team scheduling calendar\n {heading}: Transcribe meeting recordings"
529 )
530 ranked = _rank(topic, {"github": [card]})
531 assert not rerank.candidate_relevance_ok(ranked[0])
532 # Cached cards can use a top comment as the display snippet.
533 card.body = f"{card.title}\n{card.snippet}"
534 card.snippet = "Please transcribe meeting recordings."
535 assert not rerank.candidate_relevance_ok(_rank(topic, {"github": [card]})[0])
536
537
538 def test_repo_snapshot_gets_no_engagement_score():
539 # Project mode (owner as author) and every person-mode repo card shape.
540 assert signals.engagement_score(_repo_snapshot("p", "oven-sh/bun", 96195, 9551, "oven-sh")) is None
541 for labels in (["person-profile", "own-repo"], ["person-profile", "external-repo"],
542 ["person-profile", "recent-push"]):
543 card = _repo_snapshot("o", "steipete/peekaboo", 3000, 12, "steipete", labels=labels)
544 assert signals.engagement_score(card) is None
545
546
547 def test_missing_stars_do_not_hide_selected_tools_or_credit_repository_owners():
548 topic = "StudioOne and StudioTwo plugins to transcribe meeting recordings"
549 selected = _repo_snapshot("project", "alice/recorder", 0, 0, "alice")
550 selected.metadata["repo_description"] = "Transcribe meeting recordings."
551 for counters in ({}, {"open_issues": 4}, {"stars": 0}):
552 selected.engagement = counters
553 ranked = _rank(topic, {"github": [selected]})
554 assert rerank.candidate_counts_for_topic(ranked[0], topic)
555 selected.metadata["labels"] = "not-project-mode"
556 assert not rerank.candidate_counts_for_topic(_rank(topic, {"github": [selected]})[0], topic)
557 for kind in ("own-repo", "recent-push", "external-repo"):
558 card = _repo_snapshot("repo", "alice/recorder", 0, 0, "alice", labels=("person-profile", kind))
559 card.engagement = {"contributed_prs": 3} if kind == "external-repo" else {}
560 assert signals.is_repo_snapshot(card)
561 ranked = _rank("Alice", {"github": [card]}, handles={"alice"})
562 assert "first-party" not in (ranked[0].explanation or "")
563
564
565 def test_historical_project_card_recovers_description_past_notes_and_releases():
566 topic = "StudioOne and StudioTwo plugins to transcribe meeting recordings"
567 description = "Transcribe meeting recordings."
568 notes = (
569 "Repository counts, descriptions, README and issue status are current at retrieval.",
570 "Descriptions, README and issue status are current at retrieval.",
571 "Repository counts observed 2026-10-11 UTC. Descriptions, README and issue status are current at retrieval.",
572 )
573 for note in notes:
574 for release in ("No verified release evidence through 2026-10-11 is available for this card.",
575 "Latest release: v1 (2026-10-10) - Updated UI\nRelease notes continued",
576 "Latest release: v1 (2026-10-10) - Requests\n - Transcribe meeting recordings.",
577 "Release: v1 (2026-10-10)"):
578 card = _repo_snapshot("project", "alice/recorder", 1, 0, "alice")
579 header = f"Project: alice/recorder (1 star)\n {note}\n {release}"
580 card.body = f"{card.title}\n{header}\n {description}\n README: Setup"
581 card.snippet = "An unrelated comment."
582 assert rerank._project_description(card) == description
583 assert rerank.candidate_counts_for_topic(_rank(topic, {"github": [card]})[0], topic)
584 card.body = f"{card.title}\n{header}\n README: {description}"
585 assert not rerank.candidate_counts_for_topic(_rank(topic, {"github": [card]})[0], topic)
586
587
588 def test_github_issues_and_prs_keep_their_engagement():
589 issue = _item("i", "github", "SQLite WAL corruption", TO, {"reactions": 50, "comments": 80})
590 issue.metadata = {"labels": [], "state": "open", "is_pr": False}
591 pr = _item("p", "github", "Fix WAL checkpoint", TO, {"reactions": 12, "comments": 30})
592 pr.metadata = {"labels": [], "state": "closed", "is_pr": True}
593 assert 40 <= signals.engagement_score(issue) <= 55
594 assert signals.engagement_score(pr) > 0
595
596
597 def test_repo_snapshot_gets_no_first_party_credit_or_floor():
598 # "sqlite" is a topic-token handle (pipeline._topic_first_party_candidates)
599 # and the project card's author is the repo owner, so it matched.
600 card = _repo_snapshot("g", "sqlite/sqlite", 96000, 24, "sqlite")
601 with_handle = _rank("SQLite", {"github": [card]}, handles={"sqlite"})[0]
602 card2 = _repo_snapshot("g", "sqlite/sqlite", 96000, 24, "sqlite")
603 without = _rank("SQLite", {"github": [card2]})[0]
604 assert "first-party" not in (with_handle.explanation or "")
605 assert with_handle.final_score == without.final_score
606
607
608 def test_person_mode_repo_card_is_not_floored_but_not_pruned():
609 card = _repo_snapshot("o", "steipete/peekaboo", 3000, 12, "steipete",
610 labels=["person-profile", "own-repo"])
611 c = _candidate(author="steipete", text=card.title, rel=0.0, source="github")
612 c.source_items = [card]
613 _rerank_one_with_peers("Peter Steinberger", c, {"steipete"}, primary_handle="steipete")
614 assert c.final_score < rerank.FIRST_PARTY_FLOOR
615 assert "entity-miss" not in (c.explanation or "")
616 assert rerank.prune_fallback_entity_misses([c], topic="Peter Steinberger") == [c]
617
618
619 def test_96k_star_repo_card_does_not_outrank_equally_relevant_380_point_hn_story():
620 title = "sqlite/sqlite SQLite source repository"
621 card = _repo_snapshot("g", "sqlite/sqlite", 96000, 24, "sqlite")
622 card.title = card.body = title
623 hn = _item("hn", "hackernews", title, "2026-10-09", {"points": 380, "comments": 166})
624 ranked = _rank("SQLite", {"github": [card], "hackernews": [hn]}, handles={"sqlite"})
625 assert [c.item_id for c in ranked] == ["hn", "g"]
626
627
628 # --- View-weighted platforms are calibrated on a view scale -------------------
629 # 2026-10-11 e2e: a 117-view YouTube video ranked #2 for SQLite, and 655-view
630 # TikToks with 17 likes scored near a 9,676-upvote Reddit thread, because
631 # log1p(views) dominates engagement_raw for YouTube/TikTok/Instagram while the
632 # reference was calibrated like votes.
633
634 def _score(source, engagement):
635 return signals.engagement_score(_item("i", source, "t", TO, engagement))
636
637
638 def test_view_platform_scores_land_in_intended_bands():
639 # A barely-watched upload is near the bottom, like a 3-like X post (~8).
640 assert _score("youtube", {"views": 117, "likes": 1}) <= 10
641 assert _score("tiktok", {"views": 1000}) <= 15
642 # Hundreds of views and a few dozen likes: low, below a 50-upvote Reddit post.
643 assert 10 <= _score("tiktok", {"views": 655, "likes": 17}) <= 25
644 assert _score("tiktok", {"views": 655, "likes": 17}) < _score(
645 "reddit", {"score": 50, "num_comments": 20, "upvote_ratio": 0.9})
646 # A real hit is strong; ~1M+ views nears the top.
647 assert 60 <= _score("tiktok", {"views": 133690, "likes": 8441, "comments": 192}) <= 80
648 assert 75 <= _score("youtube", {"views": 726269, "likes": 13031, "comments": 1300}) <= 92
649 assert _score("youtube", {"views": 5_000_000, "likes": 150_000, "comments": 5000}) >= 95
650 assert _score("instagram", {"views": 1_000_000, "likes": 50_000, "comments": 1000}) >= 80
651
652
653 def test_655_view_tiktok_scores_well_below_9676_upvote_reddit_thread():
654 tiktok = _score("tiktok", {"views": 655, "likes": 17})
655 reddit = _score("reddit", {"score": 9676, "num_comments": 455, "upvote_ratio": 0.95})
656 assert reddit - tiktok >= 60
657
658
659 # --- Digg engagement follows Digg Score, source count and author count -------
660
661 def _digg_score(engagement):
662 return signals.engagement_score(_item("d", "digg", "t", TO, engagement))
663
664
665 def test_digg_story_with_a_top_score_saturates_and_a_small_one_does_not():
666 # The largest story of a 30-day sample, and one from its lower half.
667 big = _digg_score({"postCount": 120, "uniqueAuthors": 90, "digg_score": 1286})
668 small = _digg_score({"postCount": 5, "uniqueAuthors": 4, "digg_score": 30})
669 assert big >= 98
670 assert 40 <= small <= 65
671 # The tenth of 99 sampled stories (the top-decile boundary) sits near the top.
672 assert 88 <= _digg_score({"postCount": 27, "uniqueAuthors": 22, "digg_score": 150}) <= 100
673
674
675 def test_digg_stories_with_equal_counts_rank_by_digg_score():
676 counts = {"postCount": 20, "uniqueAuthors": 15}
677 quiet = _item("quiet", "digg", "SQLite 4 ships", TO, {**counts, "digg_score": 40})
678 loud = _item("loud", "digg", "SQLite 4 ships", TO, {**counts, "digg_score": 400})
679
680 assert signals.engagement_score(loud) > signals.engagement_score(quiet)
681 ranked = signals.annotate_stream(
682 [quiet, loud], "SQLite 4", "balanced_recent", reference_date=TO, max_days=30
683 )
684 assert [item.item_id for item in ranked] == ["loud", "quiet"]
685
686
687 def test_digg_cluster_without_a_score_still_scores_from_its_counts():
688 assert _digg_score({"postCount": 3, "uniqueAuthors": 2}) > 0
689 assert _digg_score({"postCount": 100, "uniqueAuthors": 100}) >= 98
690
690 lines PYTHON