Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(rerank): weigh real engagement in fallback ranking (#1270)

Matt Van Hornac2c8ec55ec9
diff --git a/changelog.d/+fallback-ranking.fixed.md b/changelog.d/+fallback-ranking.fixed.md
new file mode 100644
index 00000000..d8026f5e
--- /dev/null
+++ b/changelog.d/+fallback-ranking.fixed.md
@@ -0,0 +1 @@
+Ranking without an LLM reranker now weighs real engagement: a 380-point Hacker News story or a 254-upvote Reddit thread no longer ranks below 1-3-like posts that happen to be newer. Engagement is scored on an absolute per-platform scale instead of within each search's own results, freshness is counted once, the low-score cliff applies only to LLM-scored results, and first-party posts are lifted only when they are on topic (or the handle is the topic itself). The "All Items" list now shows real scores instead of 0 or 1. GitHub repo cards no longer count lifetime stars as engagement or take first-party credit, and YouTube, TikTok, and Instagram engagement is scored on a view scale so a few-hundred-view video no longer rates like a well-upvoted thread.
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 8b75896b..a9157afe 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -3066,6 +3066,7 @@ def run(
model=None if mock else runtime.rerank_model,
shortlist_size=settings["rerank_limit"],
resolved_handles=resolved_handles,
+ primary_handle=x_handle,
)
# Corpus titles/snippets must never enter a hosted reasoning prompt. Score
# every candidate carrying corpus evidence with the deterministic fallback,
@@ -3078,6 +3079,7 @@ def run(
model=None,
shortlist_size=settings["rerank_limit"],
resolved_handles=resolved_handles,
+ primary_handle=x_handle,
)
ranked_public = rerank.prune_fallback_entity_misses(ranked_public, topic=topic)
if hiring_summary:
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 29911f79..ee502b3b 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -1905,7 +1905,9 @@ def render_full(report: schema.Report, save_path: str | None = None) -> str:
lines.append(f"### {_source_label(source)} ({len(items)} items)")
lines.append("")
for item in items:
- score = item.local_rank_score if item.local_rank_score is not None else 0
+ # local_rank_score is 0..1; print it on the report's 0-100 scale
+ # (":.0f" of the raw value rendered every item as score:0 or 1).
+ score = (item.local_rank_score or 0) * 100.0
lines.append(
f"**{item.item_id}** (score:{score:.0f}) {item.author or ''} ({item.published_at or 'date unknown'}) [{_format_item_engagement(item)}]"
)
diff --git a/skills/last30days/scripts/lib/rerank.py b/skills/last30days/scripts/lib/rerank.py
index 041e49a2..4fd954a1 100644
--- a/skills/last30days/scripts/lib/rerank.py
+++ b/skills/last30days/scripts/lib/rerank.py
@@ -266,6 +266,7 @@ def rerank_candidates(
model: str | None,
shortlist_size: int,
resolved_handles: set[str] | None = None,
+ primary_handle: str | None = None,
) -> list[schema.Candidate]:
"""Rerank the fused shortlist, demoting candidates the reranker scored as irrelevant.
@@ -275,10 +276,15 @@ def rerank_candidates(
exempted from the entity-miss demotion in ``_fallback_tuple`` (a post almost
never repeats its own author's name, so the body-text grounding check would
otherwise bury the subject's own highest-signal posts).
+
+ ``primary_handle`` is the run's ``--x-handle``: the one handle in the
+ subject role. Only it can be the topic's own account (_subject_handles);
+ ``--x-related`` and discovered handles are first-party but never subjects.
"""
handles = resolved_handles or set()
shortlisted = candidates[:shortlist_size]
primary_entity = _primary_entity(topic)
+ subject = _subject_handles(primary_handle, topic)
if provider and model and shortlisted:
try:
response = provider.generate_json(
@@ -288,17 +294,32 @@ def rerank_candidates(
except (ValueError, KeyError, json.JSONDecodeError, OSError, http.HTTPError) as exc:
import sys
print(f"[Rerank] LLM reranking failed, using local fallback: {type(exc).__name__}: {exc}", file=sys.stderr)
- _apply_fallback_scores(shortlisted, primary_entity=primary_entity, resolved_handles=handles)
+ _apply_fallback_scores(
+ shortlisted, primary_entity=primary_entity, resolved_handles=handles, subject_handles=subject
+ )
else:
- _apply_fallback_scores(shortlisted, primary_entity=primary_entity, resolved_handles=handles)
+ _apply_fallback_scores(
+ shortlisted, primary_entity=primary_entity, resolved_handles=handles, subject_handles=subject
+ )
if len(candidates) > shortlist_size:
tail = candidates[shortlist_size:]
- _apply_fallback_scores(tail, primary_entity=primary_entity, resolved_handles=handles)
+ _apply_fallback_scores(
+ tail, primary_entity=primary_entity, resolved_handles=handles, subject_handles=subject
+ )
- _apply_first_party_floor(candidates, resolved_handles=handles)
- _apply_engagement_rescue(candidates, primary_entity=primary_entity, resolved_handles=handles)
- _apply_interaction_signal(candidates, resolved_handles=handles)
+ _apply_first_party_floor(
+ candidates, resolved_handles=handles, primary_entity=primary_entity, topic=topic,
+ primary_handle=primary_handle,
+ )
+ _apply_engagement_rescue(
+ candidates, primary_entity=primary_entity, resolved_handles=handles, topic=topic,
+ primary_handle=primary_handle,
+ )
+ _apply_interaction_signal(
+ candidates, resolved_handles=handles, primary_entity=primary_entity, topic=topic,
+ primary_handle=primary_handle,
+ )
return sorted(
candidates,
@@ -441,22 +462,36 @@ def _apply_llm_scores(
str(row.get("reason") or "").strip() or None,
)
for candidate in candidates:
- rerank_score, reason = scores.get(
- candidate.candidate_id, _fallback_tuple(candidate, resolved_handles=handles)
- )
+ if candidate.candidate_id in scores:
+ rerank_score, reason = scores[candidate.candidate_id]
+ provenance = RERANK_PROVENANCE_LLM
+ else:
+ rerank_score, reason = _fallback_tuple(candidate, resolved_handles=handles)
+ provenance = RERANK_PROVENANCE_FALLBACK
candidate.rerank_score = rerank_score
candidate.explanation = reason
+ _set_rerank_provenance(candidate, provenance)
candidate.final_score = _final_score(candidate)
def _apply_fallback_scores(
- candidates: list[schema.Candidate], *, primary_entity: str = "", resolved_handles: set[str] | None = None
+ candidates: list[schema.Candidate],
+ *,
+ primary_entity: str = "",
+ resolved_handles: set[str] | None = None,
+ subject_handles: set[str] | None = None,
) -> None:
handles = resolved_handles or set()
for candidate in candidates:
- rerank_score, reason = _fallback_tuple(candidate, primary_entity=primary_entity, resolved_handles=handles)
+ rerank_score, reason = _fallback_tuple(
+ candidate,
+ primary_entity=primary_entity,
+ resolved_handles=handles,
+ subject_handles=subject_handles,
+ )
candidate.rerank_score = rerank_score
candidate.explanation = reason
+ _set_rerank_provenance(candidate, RERANK_PROVENANCE_FALLBACK)
candidate.final_score = _final_score(candidate)
@@ -483,6 +518,112 @@ def _is_first_party(candidate: schema.Candidate, resolved_handles: set[str]) ->
return _candidate_author_handle(candidate) in resolved_handles
+def _handle_is_topic(handle: str, topic: str) -> bool:
+ """True when the handle names the topic itself, not someone near it.
+
+ Matches a handle that contains a topic word ("ghostty" for "Ghostty
+ terminal", "karpathy" for "Andrej Karpathy") or is spelled from prefixes
+ of distinct topic words ("steipete" = stei+pete for "Peter Steinberger",
+ "sama" for "Sam Altman"). A founder or commentator handle on a product
+ topic ("mitchellh" for "Ghostty terminal") does not match.
+ """
+ letters = re.sub(r"[^a-z]", "", (handle or "").lower())
+ if len(letters) < 3:
+ return False
+ words = [
+ word
+ for word in re.findall(r"[a-z]+", (topic or "").lower())
+ if len(word) >= 3
+ and word not in relevance.STOPWORDS
+ and word not in relevance.LOW_SIGNAL_QUERY_TOKENS
+ ]
+ if any(len(word) >= 4 and (word in letters or letters in word) for word in words):
+ return True
+ return _spelled_from_word_prefixes(letters, words, frozenset())
+
+
+def _spelled_from_word_prefixes(rest: str, words: list[str], used: frozenset[int]) -> bool:
+ """Whether ``rest`` splits into prefixes of distinct ``words``.
+
+ Every chunk but the last must be at least 3 letters, and a single chunk
+ alone never counts (that case is the containment test above).
+ """
+ if not rest:
+ return len(used) >= 2
+ for index, word in enumerate(words):
+ if index in used:
+ continue
+ for size in range(min(len(word), len(rest)), 0, -1):
+ if rest[:size] != word[:size]:
+ continue
+ remaining = rest[size:]
+ if size < 3 and remaining:
+ continue
+ if _spelled_from_word_prefixes(remaining, words, used | {index}):
+ return True
+ return False
+
+
+def _subject_handles(primary_handle: str | None, topic: str) -> set[str]:
+ """The topic's own account: the primary handle, when it names the topic.
+
+ Only ``--x-handle`` holds the subject role. A related handle is someone
+ near the topic, so it never qualifies, even when its letters happen to sit
+ inside a topic word ("art" in "Smart home"). The primary handle must still
+ name the topic (_handle_is_topic), so ``--x-handle mitchellh`` on
+ "Ghostty terminal" is a related voice, not the subject. Known false
+ negative: an alias handle that shares no letters with the name
+ ("mrbeast" for "Jimmy Donaldson") is not a subject; its on-topic posts
+ still earn the floors through grounding or relevance.
+ """
+ handle = (primary_handle or "").lstrip("@").strip().lower()
+ if handle and _handle_is_topic(handle, topic):
+ return {handle}
+ return set()
+
+
+def _is_repo_snapshot_candidate(candidate: schema.Candidate) -> bool:
+ """True when every source item is a GitHub repo card (signals.is_repo_snapshot)."""
+ return bool(candidate.source_items) and all(
+ signals.is_repo_snapshot(item) for item in candidate.source_items
+ )
+
+
+def _first_party_floor_eligible(
+ candidate: schema.Candidate,
+ *,
+ resolved_handles: set[str],
+ primary_entity: str = "",
+ subject_handles: set[str] | None = None,
+) -> bool:
+ """Whether a first-party post earns the authorship credit and floors.
+
+ First-party authorship always exempts a post from pruning, but the lift
+ into the visible band is reserved for posts that are on-topic (entity
+ grounded, or clearing the normal relevance floor) and for the topic's own
+ account, whose posts never name their author. A related handle's
+ off-topic reply ("@friend Nanit" on a Ghostty run) stays where its own
+ score puts it. With no primary entity every post counts as on-topic.
+
+ Grounding counts only when it is positively established. For a short
+ generic topic ("Go") _entity_grounded cannot test a match and passes
+ everything, so there the post must clear the relevance floor instead.
+ """
+ if not _is_first_party(candidate, resolved_handles):
+ return False
+ # A repo snapshot card's "author" is the repo owner or the --github-user,
+ # not someone posting in the window (and a project owner such as "sqlite"
+ # can match a topic-token handle), so it never earns the lift.
+ if _is_repo_snapshot_candidate(candidate):
+ return False
+ if subject_handles and _candidate_author_handle(candidate) in subject_handles:
+ return True
+ return (
+ _is_entity_positively_grounded(candidate, primary_entity)
+ or candidate.local_relevance >= relevance.RELEVANCE_FLOOR
+ )
+
+
def _is_x_candidate(candidate: schema.Candidate) -> bool:
"""True when the candidate originates from X (top-level or any source item)."""
if candidate.source == "x":
@@ -494,6 +635,20 @@ def _candidate_engagement(candidate: schema.Candidate) -> float:
return candidate.engagement if candidate.engagement is not None else 0.0
+def _is_entity_positively_grounded(candidate: schema.Candidate, primary_entity: str) -> bool:
+ """Like _is_entity_grounded, but False where grounding cannot be tested.
+
+ _entity_grounded passes every candidate when the entity offers no safe
+ anchor (a short generic topic such as "Go"); that keeps it from demoting,
+ but it is not evidence that a candidate is on topic. No primary entity
+ still counts as grounded, as in _is_entity_grounded.
+ """
+ if not primary_entity:
+ return True
+ haystack = _candidate_haystack(candidate)
+ return bool(haystack.strip()) and _entity_grounding_verdict(haystack, primary_entity) is True
+
+
def _is_entity_grounded(candidate: schema.Candidate, primary_entity: str) -> bool:
"""Whether the candidate plausibly mentions the primary entity in its text.
@@ -537,38 +692,60 @@ def _interaction_targets(candidate: schema.Candidate, resolved_handles: set[str]
def _apply_interaction_signal(
- candidates: list[schema.Candidate], *, resolved_handles: set[str]
+ candidates: list[schema.Candidate],
+ *,
+ resolved_handles: set[str],
+ primary_entity: str = "",
+ topic: str = "",
+ primary_handle: str | None = None,
) -> None:
"""Float and tag first-party posts directed at another account. The relational
tell (the subject personally engaging someone) is invisible to keyword and
engagement scoring, so these are floored into the visible band and tagged so
- synthesis reads them as signal."""
+ synthesis reads them as signal. The floor applies only where
+ _first_party_floor_eligible holds; an off-topic reply is tagged, not lifted."""
if not resolved_handles:
return
+ subject = _subject_handles(primary_handle, topic)
for c in candidates:
targets = _interaction_targets(c, resolved_handles)
if not targets:
continue
c.metadata = {**(c.metadata or {}), "interaction_targets": sorted(targets)}
+ if not _first_party_floor_eligible(
+ c, resolved_handles=resolved_handles, primary_entity=primary_entity, subject_handles=subject
+ ):
+ continue
if c.final_score < INTERACTION_FLOOR:
c.final_score = INTERACTION_FLOOR
def _apply_first_party_floor(
- candidates: list[schema.Candidate], *, resolved_handles: set[str]
+ candidates: list[schema.Candidate],
+ *,
+ resolved_handles: set[str],
+ primary_entity: str = "",
+ topic: str = "",
+ primary_handle: str | None = None,
) -> None:
- """Floor every first-party post above the zero band, on any scoring path.
+ """Floor on-topic first-party posts above the zero band, on any scoring path.
Backstops the LLM rerank path, where the grounding hint would otherwise cap
a first-party post (which never names its own author) at <=30 and re-bury
- it. Floor only lifts; it never lowers a post the scorer rated higher.
+ it. Floor only lifts; it never lowers a post the scorer rated higher. Only
+ posts passing _first_party_floor_eligible are lifted (the topic's own
+ account always is); every first-party post still has its entity-miss
+ marker cleared below, so none is pruned for omitting its author's name.
"""
if not resolved_handles:
return
+ subject = _subject_handles(primary_handle, topic)
for c in candidates:
if not _is_first_party(c, resolved_handles):
continue
- if c.final_score < FIRST_PARTY_FLOOR:
+ if c.final_score < FIRST_PARTY_FLOOR and _first_party_floor_eligible(
+ c, resolved_handles=resolved_handles, primary_entity=primary_entity, subject_handles=subject
+ ):
c.final_score = FIRST_PARTY_FLOOR
# Clear the entity-miss marker here, at the one site that knows the
# resolved handles. Downstream relevance gates key on the marker, not
@@ -581,19 +758,36 @@ def _apply_first_party_floor(
def _apply_engagement_rescue(
- candidates: list[schema.Candidate], *, primary_entity: str, resolved_handles: set[str]
+ candidates: list[schema.Candidate],
+ *,
+ primary_entity: str,
+ resolved_handles: set[str],
+ topic: str = "",
+ primary_handle: str | None = None,
) -> None:
- """Floor final_score for high-engagement X posts that are first-party or
- entity-grounded, so a viral on-topic post can't sit at ~0. Off-topic
- (entity-miss) collision posts are excluded, preserving noise suppression.
+ """Floor final_score for high-engagement X posts that are entity-grounded
+ or floor-eligible first-party (see _first_party_floor_eligible), so a viral
+ on-topic post can't sit at ~0. Off-topic (entity-miss) collision posts and
+ a related handle's off-topic posts are excluded, preserving noise
+ suppression.
"""
x_cands = [c for c in candidates if _is_x_candidate(c)]
if len(x_cands) < 2:
return
+ subject = _subject_handles(primary_handle, topic)
engagements = sorted(_candidate_engagement(c) for c in x_cands)
n = len(engagements)
for c in x_cands:
- if not (_is_first_party(c, resolved_handles) or _is_entity_grounded(c, primary_entity)):
+ # A first-party post qualifies only through _first_party_floor_eligible
+ # (which needs positive grounding); the bare grounding pass below would
+ # wave a related handle's off-topic post through on a short topic.
+ if _is_first_party(c, resolved_handles):
+ qualifies = _first_party_floor_eligible(
+ c, resolved_handles=resolved_handles, primary_entity=primary_entity, subject_handles=subject
+ )
+ else:
+ qualifies = _is_entity_grounded(c, primary_entity)
+ if not qualifies:
continue
e = _candidate_engagement(c)
# Percentile rank in [0, 1]: fraction of the X pool strictly below e.
@@ -650,10 +844,21 @@ def _entity_grounded(haystack: str, primary_entity: str) -> bool:
anchors. Short generic-headed topics remain a safe no-op so entities such as
"Go" are not falsely demoted.
"""
+ verdict = _entity_grounding_verdict(haystack, primary_entity)
+ return True if verdict is None else verdict
+
+
+def _entity_grounding_verdict(haystack: str, primary_entity: str) -> bool | None:
+ """_entity_grounded's test, with None where no safe anchor exists.
+
+ None means the entity cannot be checked (no tokens, a short generic-headed
+ topic, or no strong trailing anchor); _entity_grounded treats that as a
+ pass so it never demotes, and _is_entity_positively_grounded as a miss.
+ """
haystack = haystack.lower()
tokens = re.findall(r"\w+", primary_entity.lower())
if not tokens:
- return True
+ return None
head = tokens[0]
if len(head) > 3 and head not in relevance.LOW_SIGNAL_QUERY_TOKENS:
return head in haystack
@@ -662,7 +867,7 @@ def _entity_grounded(haystack: str, primary_entity: str) -> bool:
# word needs a stronger anchor. Short entity-like topics keep the historical
# safe no-op rather than risking false demotion.
if len(tokens) < _GENERIC_GROUNDING_MIN_TOKENS:
- return True
+ return None
anchors = [
token
for token in tokens[1:]
@@ -671,16 +876,22 @@ def _entity_grounded(haystack: str, primary_entity: str) -> bool:
and token not in _GROUNDING_LOW_SIGNAL_TOKENS
]
if not anchors:
- return True
+ return None
return any(re.search(rf"\b{re.escape(token)}", haystack) for token in anchors)
def _fallback_tuple(
- candidate: schema.Candidate, *, primary_entity: str = "", resolved_handles: set[str] | None = None
+ candidate: schema.Candidate,
+ *,
+ primary_entity: str = "",
+ resolved_handles: set[str] | None = None,
+ subject_handles: set[str] | None = None,
) -> tuple[float, str]:
+ # Relevance and source quality only. Freshness enters once, in
+ # _final_score; counting it here too gave it ~0.22 of the final score and
+ # let a 3-point story from today outrank a 380-point one from last week.
score = (
(candidate.local_relevance * 100.0 * 0.7)
- + (candidate.freshness * 0.2)
+ (candidate.source_quality * 100.0 * 0.1)
)
reason = "fallback-local-score"
@@ -693,8 +904,21 @@ def _fallback_tuple(
# _final_score's secondary penalty (which greps for it) is also skipped.
# A small bounded credit lifts a first-party post just off neutral without
# letting authorship alone outrank a genuinely strong on-topic third party.
+ # The credit, like the floors, goes only to on-topic posts or the topic's
+ # own account (_first_party_floor_eligible); an off-topic reply from a
+ # related handle keeps the exemption (so it is not pruned) but earns no lift.
if resolved_handles and _is_first_party(candidate, resolved_handles):
- score += FIRST_PARTY_AUTHOR_CREDIT
+ if _first_party_floor_eligible(
+ candidate,
+ resolved_handles=resolved_handles,
+ primary_entity=primary_entity,
+ subject_handles=subject_handles,
+ ):
+ score += FIRST_PARTY_AUTHOR_CREDIT
+ # A repo card keeps the exemption (a person-mode card never names the
+ # person) but is not authored in the window, so it is not labeled so.
+ if _is_repo_snapshot_candidate(candidate):
+ return max(0.0, min(100.0, score)), "fallback-local-score (repo snapshot)"
return max(0.0, min(100.0, score)), "fallback-local-score (first-party authorship)"
# Grounding-exempt evidence (currently Amazon): the adapter gated these
# against the model-supplied keyword before they existed, so the
@@ -824,23 +1048,60 @@ ENTITY_MISS_FINAL_PENALTY = 20.0
OUT_OF_WINDOW_FINAL_MULTIPLIER = 0.35
+#: Weight of engagement (0-100, absolute per-source log scale from
+#: signals.engagement_score) in _final_score. Its full range is worth 15
+#: points, nearly twice freshness's effective 8 (freshness spans 10-90), so a
+#: large engagement gap (a 380-point HN story vs a 3-point one, ~78 points ->
+#: ~12) can outweigh most of a month's age gap (~7), while a modest gap cannot.
+#: Relevance still dominates: one tenth of local relevance is worth 4.2 points
+#: through the fallback rerank score alone.
+ENGAGEMENT_FINAL_WEIGHT = 0.15
+
+
+#: Candidate.metadata key recording which path produced rerank_score. Set by
+#: _apply_fallback_scores and _apply_llm_scores; the explanation text is not
+#: provenance (an LLM reason may start with any word).
+RERANK_PROVENANCE_KEY = "rerank_provenance"
+RERANK_PROVENANCE_FALLBACK = "fallback"
+RERANK_PROVENANCE_LLM = "llm"
+
+
+def _set_rerank_provenance(candidate: schema.Candidate, provenance: str) -> None:
+ candidate.metadata = {**(candidate.metadata or {}), RERANK_PROVENANCE_KEY: provenance}
+
+
+def _is_fallback_scored(candidate: schema.Candidate) -> bool:
+ """True when rerank_score came from _fallback_tuple, not an LLM or host.
+
+ Reads the provenance the scoring path recorded. A candidate with none
+ recorded is treated as judge-scored, so the cliff still applies.
+ """
+ return (candidate.metadata or {}).get(RERANK_PROVENANCE_KEY) == RERANK_PROVENANCE_FALLBACK
+
+
def _final_score(candidate: schema.Candidate) -> float:
normalized_rrf = _normalized_rrf(candidate.rrf_score)
rerank_score = candidate.rerank_score or 0.0
- # Engagement bonus: high-engagement items (viral TikToks, popular YouTube videos)
- # get a boost so they aren't buried by lower-engagement but text-relevant items.
- # Engagement is log1p-normalized (0-100 range via signals.py), so a 2.5M-view
- # TikTok scores ~15 and a 1500-view one scores ~7. The 0.05 weight gives a
- # meaningful but not dominant boost.
+ # Engagement is already 0-100 on an absolute per-source log scale
+ # (signals.engagement_score): ~8 for a 3-like X post, ~50 for a 254-upvote
+ # Reddit thread, ~90 for a 380-point HN story.
engagement_val = candidate.engagement if candidate.engagement is not None else 0.0
base = (
0.60 * rerank_score
+ 0.20 * normalized_rrf
+ 0.10 * candidate.freshness
+ 0.05 * (candidate.source_quality * 100.0)
- + 0.05 * min(engagement_val * 6.0, 100.0)
+ + ENGAGEMENT_FINAL_WEIGHT * max(0.0, min(engagement_val, 100.0))
)
- if candidate.rerank_score is not None and candidate.rerank_score < 20.0:
+ # The cliff demotes items a judge explicitly called irrelevant. A fallback
+ # score below 20 only means weak lexical overlap, which the 0.60 weight
+ # already prices in; cliffing it too buried on-topic threads (a 254-upvote
+ # r/Ghostty post ranked last at score 7).
+ if (
+ candidate.rerank_score is not None
+ and candidate.rerank_score < 20.0
+ and not _is_fallback_scored(candidate)
+ ):
base *= 0.3
# Secondary entity-grounding penalty: when the fallback path flagged
# entity-miss via candidate.explanation, apply an additional penalty
diff --git a/skills/last30days/scripts/lib/signals.py b/skills/last30days/scripts/lib/signals.py
index 700554b4..daab2915 100644
--- a/skills/last30days/scripts/lib/signals.py
+++ b/skills/last30days/scripts/lib/signals.py
@@ -275,6 +275,112 @@ def engagement_raw(item: schema.SourceItem) -> float | None:
return _generic_engagement(item)
+# Per-source log reference for engagement_score, in each source's own units.
+# Same convention as _VOTE_LOG_REFERENCE (which it extends): the value is
+# engagement_raw for a "very high" item, so that item scores 100 and, the scale
+# being logarithmic, roughly its square root scores 50. Every source that can
+# reach engagement_raw is listed here or in _NO_ENGAGEMENT_SCORE_SOURCES; an
+# unlisted source gets no score rather than an assumed Reddit-vote scale.
+_ENGAGEMENT_LOG_REFERENCE: dict[str, float] = {
+ **_VOTE_LOG_REFERENCE,
+ # Microblog likes/reposts/replies run on X's scale (~10k likes is very high).
+ "truthsocial": 9.2, # ~log1p(10000)
+ "threads": 9.2, # ~log1p(10000)
+ # Likes/comments/favorites on an Instagram-like feed.
+ "xiaohongshu": 9.2, # ~log1p(10000)
+ # Saves on a viral pin reach ~10k.
+ "pinterest": 9.2, # ~log1p(10000)
+ # Reactions run like Reddit upvotes: a viral post has ~2k.
+ "linkedin": 7.6, # ~log1p(2000)
+ # Per-issue/PR reactions and comments (repo snapshot cards, whose counts
+ # are lifetime stars, get no score: see is_repo_snapshot). A
+ # ~100-reaction thread lands near 50.
+ "github": 9.2, # ~log1p(10000)
+ # Dollars, not votes. polymarket.py's own saturation anchors: $9M volume
+ # (log1p 16) and $1.2M liquidity (log1p 14), weighted 0.6/0.4 as in
+ # ENGAGEMENT_WEIGHTS: 0.6*16 + 0.4*14 = 15.2.
+ "polymarket": 15.2,
+ # A rank-1 cluster (rank_score 50) with ~100 posts from ~100 authors:
+ # 0.4*log1p(100) + 0.3*log1p(100) + 0.3*log1p(50) = 4.4.
+ "digg": 4.4,
+ # Lifetime totals for a whole company or product, not one post: big
+ # consumer brands and best-sellers carry ~100k, so ~300 lands near 50.
+ "trustpilot": 11.5, # ~log1p(100000) reviews
+ "amazon": 11.5, # ~log1p(100000) ratings
+}
+
+# Sources whose engagement fields are not an audience response, so no
+# engagement score is comparable with votes or likes:
+# jobs - a constant open_roles=1 per posting
+# meta_ads - variant count measures the advertiser's push, not reach
+# grounding, perplexity - web results; counts are citations, not readers
+# stocktwits - the author's follower count dominates sparse likes/reshares
+# telegram - the channel's subscriber count dominates per-post views
+# arxiv, techmeme, dripstack, corpus - no engagement fields at all
+_NO_ENGAGEMENT_SCORE_SOURCES = frozenset({
+ "jobs", "meta_ads", "grounding", "perplexity", "stocktwits", "telegram",
+ "arxiv", "techmeme", "dripstack", "corpus",
+})
+
+
+# YouTube, TikTok, and Instagram weight log1p(views) at 0.45 in
+# engagement_raw, and views run orders of magnitude above votes: any upload
+# collects ~100 passive feed views, so a 117-view, 1-like video already had raw
+# 2.4 (23 on the vote-style 10.3 reference, three times a 3-like X post).
+# These sources map raw linearly from a floor (an upload with ~100 views and no
+# reactions: 0.45*log1p(100) = 2.1) to a "very high" month-window post (~2-3M
+# views, ~100k likes, ~3k comments: 0.45*14.9 + 0.32*11.5 + 0.13*8.0 = 11.4).
+# Resulting scores: 117 views/1 like ~3, 655 views/17 likes ~17, 133k views/
+# 8.4k likes ~70, 726k views/13k likes ~85, 1M+ views ~90-100.
+_VIEW_ENGAGEMENT_SOURCES = frozenset({"youtube", "tiktok", "instagram"})
+_VIEW_ENGAGEMENT_LOG_FLOOR = 2.1
+_VIEW_ENGAGEMENT_LOG_REFERENCE = 11.5
+
+
+def is_repo_snapshot(item: schema.SourceItem) -> bool:
+ """True for a GitHub repo card (project mode, person-mode repo items).
+
+ Their engagement is lifetime stars and the open-issue count, a snapshot
+ of the repo's whole history rather than an audience response inside the
+ window. Issues and PRs carry reactions/comments, never stars.
+ """
+ return (
+ item.source == "github"
+ and "stars" in (item.engagement or {})
+ and not (item.metadata or {}).get("is_pr")
+ )
+
+
+def engagement_score(item: schema.SourceItem) -> int | None:
+ """Engagement on an absolute 0-100 scale, comparable across streams.
+
+ ``engagement_raw`` is a weighted mean of log1p counts, so dividing it by
+ the source's log reference (``_ENGAGEMENT_LOG_REFERENCE``, in that
+ source's own units) places a 250-upvote Reddit thread near 50 and a 3-like
+ X post near 8 no matter what else shares their stream. The per-stream
+ min-max rescale this replaces mapped every stream's best item to 100 and
+ a lone item to 50, so the score said nothing about actual engagement.
+ View-weighted sources (YouTube, TikTok, Instagram) use the view scale
+ (``_VIEW_ENGAGEMENT_LOG_FLOOR`` to ``_VIEW_ENGAGEMENT_LOG_REFERENCE``)
+ instead of their vote reference. Sources without a comparable audience
+ signal, and GitHub repo snapshots (lifetime stars), return None.
+ """
+ if item.source in _NO_ENGAGEMENT_SCORE_SOURCES or is_repo_snapshot(item):
+ return None
+ ref = _ENGAGEMENT_LOG_REFERENCE.get(item.source)
+ if ref is None:
+ return None
+ raw = engagement_raw(item)
+ if raw is None:
+ return None
+ if item.source in _VIEW_ENGAGEMENT_SOURCES:
+ floor = _VIEW_ENGAGEMENT_LOG_FLOOR
+ fraction = (raw - floor) / (_VIEW_ENGAGEMENT_LOG_REFERENCE - floor)
+ else:
+ fraction = raw / ref
+ return int(round(100.0 * max(0.0, min(1.0, fraction))))
+
+
def normalize(values: list[float | None]) -> list[int | None]:
valid = [value for value in values if value is not None]
if not valid:
@@ -300,8 +406,8 @@ def annotate_stream(
) -> list[schema.SourceItem]:
"""Attach local scoring metadata and return items sorted by local_rank_score."""
prepared_query = ranking_query if isinstance(ranking_query, relevance.PreparedQuery) else relevance.PreparedQuery(ranking_query)
- engagement_scores = normalize([engagement_raw(item) for item in items])
- for item, eng_score in zip(items, engagement_scores, strict=True):
+ for item in items:
+ eng_score = engagement_score(item)
item.local_relevance = local_relevance(item, prepared_query)
item.freshness = freshness(
item,
@@ -407,10 +513,9 @@ def prune_low_relevance(
rel = item.local_relevance if item.local_relevance is not None else 0.0
if rel < minimum:
return False
- # Key the stricter social gate on genuinely absent engagement, not on
- # the normalized score: signals.normalize is min-max over the batch, so
- # it maps the least-engaged item to exactly 0 even when that item has
- # thousands of likes.
+ # Key the stricter social gate on genuinely absent engagement (no
+ # counts at all), not on a rounded score: a handful of likes is still
+ # engagement even where the 0-100 scale rounds it low.
if item.source in _SOCIAL_SOURCES and not engagement_raw(item):
if rel < minimum * 1.5:
return False
diff --git a/tests/test_fallback_ranking.py b/tests/test_fallback_ranking.py
new file mode 100644
index 00000000..d05e6df6
--- /dev/null
+++ b/tests/test_fallback_ranking.py
@@ -0,0 +1,489 @@
+"""Fallback (no reasoning provider) ranking behavior.
+
+With no LLM reranker every candidate is scored by rerank._fallback_tuple +
+rerank._final_score. These tests pin the five fixes from the 2026-10-11 live
+traces (Ghostty, SQLite): engagement on an absolute per-source log scale with
+real weight, freshness counted once, the low-rerank cliff limited to LLM
+scores, the All Items dump printing a real score, and first-party floors
+limited to on-topic posts or the topic's own handle.
+"""
+
+from lib import fusion, planner, render, rerank, schema, signals
+
+TO = "2026-10-11"
+FROM = "2026-09-11"
+SOURCES = ["reddit", "x", "hackernews"]
+
+
+def _plan(topic: str) -> schema.QueryPlan:
+ return schema.QueryPlan(
+ intent="product",
+ freshness_mode="balanced_recent",
+ cluster_mode="none",
+ raw_topic=topic,
+ subqueries=[
+ schema.SubQuery(
+ label="primary", search_query=topic, ranking_query=topic,
+ sources=SOURCES, weight=1.0,
+ )
+ ],
+ source_weights=planner._normalize_weights({s: 1.0 for s in SOURCES}),
+ )
+
+
+def _item(item_id, source, title, date, engagement, author=None, mentions=()):
+ return schema.SourceItem(
+ item_id=item_id, source=source, title=title, body=title,
+ url=f"https://example.test/{source}/{item_id}", author=author,
+ published_at=date, date_confidence="high", engagement=engagement,
+ metadata={"mentioned_handles": list(mentions)} if mentions else {},
+ )
+
+
+def _rank(topic, streams, handles=frozenset()):
+ """Run the real annotate -> fuse -> fallback-rerank path; return ids in order."""
+ annotated = {
+ ("primary", source): signals.annotate_stream(
+ items, topic, "balanced_recent", reference_date=TO, max_days=30
+ )
+ for source, items in streams.items()
+ }
+ plan = _plan(topic)
+ candidates = fusion.weighted_rrf(
+ annotated, plan, pool_limit=40, range_from=FROM, range_to=TO,
+ first_party_handles=set(handles),
+ )
+ ranked = rerank.rerank_candidates(
+ topic=topic, plan=plan, candidates=candidates, provider=None, model=None,
+ shortlist_size=40, resolved_handles=set(handles),
+ )
+ return ranked
+
+
+# --- Fix 1: absolute per-source engagement scale with real weight -----------
+
+def test_engagement_score_is_absolute_not_stream_relative():
+ """A thread's engagement score must not depend on what else is in its stream."""
+ big = _item("big", "reddit", "Ghostty smooth cursor animation shader", "2026-09-14",
+ {"score": 254, "num_comments": 24})
+ alone = signals.annotate_stream([big], "ghostty", "balanced_recent", reference_date=TO)[0]
+ alone_score = alone.engagement_score
+ big2 = _item("big", "reddit", "Ghostty smooth cursor animation shader", "2026-09-14",
+ {"score": 254, "num_comments": 24})
+ huge = _item("huge", "reddit", "Ghostty 2.0 released", "2026-09-14",
+ {"score": 9000, "num_comments": 900})
+ mixed = signals.annotate_stream([big2, huge], "ghostty", "balanced_recent", reference_date=TO)
+ mixed_score = next(i for i in mixed if i.item_id == "big").engagement_score
+ assert alone_score == mixed_score
+ # A 3-like post must not be lifted to the stream midpoint just because it is alone.
+ tiny = _item("tiny", "x", "ghostty", TO, {"likes": 3})
+ tiny = signals.annotate_stream([tiny], "ghostty", "balanced_recent", reference_date=TO)[0]
+ assert tiny.engagement_score < 15
+
+
+def test_250_upvote_reddit_thread_outranks_3_like_x_post_at_equal_relevance():
+ title = "Ghostty smooth cursor animation shader"
+ ranked = _rank("Ghostty", {
+ "reddit": [_item("r", "reddit", title, "2026-10-09", {"score": 250, "num_comments": 24})],
+ "x": [_item("x", "x", title, "2026-10-09", {"likes": 3}, author="someone")],
+ })
+ assert [c.item_id for c in ranked] == ["r", "x"]
+
+
+def test_380_point_hn_story_from_26_days_ago_outranks_3_point_story_from_today():
+ title = "Show HN: Capsule - single-file web apps that save their data into SQLite"
+ ranked = _rank("SQLite", {
+ "hackernews": [
+ _item("old", "hackernews", title, "2026-09-15", {"points": 380, "comments": 166}),
+ _item("new", "hackernews", title, TO, {"points": 3}),
+ ],
+ })
+ assert [c.item_id for c in ranked] == ["old", "new"]
+
+
+# --- Fix 2: freshness enters the fallback score once -------------------------
+
+def _candidate(*, freshness=50, rel=0.5, sq=0.6, engagement=None, explanation=None,
+ author=None, text="SQLite note", mentions=(), source="x"):
+ item = schema.SourceItem(
+ item_id="i", source=source, title=text, body=text,
+ url="https://example.test/i", author=author, snippet=text,
+ metadata={"mentioned_handles": list(mentions)} if mentions else {},
+ )
+ c = schema.Candidate(
+ candidate_id=f"c-{author}-{freshness}-{text}", item_id="i", source=source,
+ title=text, url=item.url, snippet=text, subquery_labels=["primary"],
+ native_ranks={"primary:x": 1}, local_relevance=rel, freshness=freshness,
+ engagement=engagement, source_quality=sq, rrf_score=0.0, source_items=[item],
+ )
+ c.explanation = explanation
+ return c
+
+
+def test_fallback_rerank_score_does_not_include_freshness():
+ old = _candidate(freshness=10)
+ new = _candidate(freshness=90)
+ assert rerank._fallback_tuple(old)[0] == rerank._fallback_tuple(new)[0]
+
+
+def test_fallback_final_score_counts_freshness_once():
+ old = _candidate(freshness=10)
+ new = _candidate(freshness=90)
+ rerank._apply_fallback_scores([old, new])
+ # _final_score weights freshness at 0.10; 80 points of freshness is worth 8.
+ assert abs((new.final_score - old.final_score) - 8.0) < 1e-6
+
+
+# --- Fix 3: the <20 rerank cliff applies to LLM scores only -------------------
+
+def test_fallback_scored_candidate_below_20_is_not_cliffed():
+ fallback = _candidate(text="SQLite fallback")
+ rerank._apply_fallback_scores([fallback])
+ fallback.rerank_score = 18.0
+ llm = _candidate(text="SQLite judged")
+ rerank._apply_llm_scores(
+ [llm], {"scores": [{"candidate_id": llm.candidate_id, "relevance": 18, "reason": "weak match"}]}
+ )
+ assert abs(rerank._final_score(llm) - 0.3 * rerank._final_score(fallback)) < 1e-6
+
+
+def test_llm_scored_candidate_below_20_is_still_cliffed():
+ above = _candidate(explanation="ok")
+ above.rerank_score = 20.0
+ below = _candidate(explanation="weak")
+ below.rerank_score = 19.0
+ assert rerank._final_score(below) < 0.35 * rerank._final_score(above)
+
+
+# --- Fix 4: All Items by Source prints a real score --------------------------
+
+def test_all_items_by_source_prints_local_rank_score_on_a_100_scale():
+ item = _item("i1", "reddit", "SQLite 3.54.0 released", "2026-10-10",
+ {"score": 47, "num_comments": 6})
+ item.local_rank_score = 0.73
+ report = schema.Report(
+ topic="SQLite", range_from=FROM, range_to=TO,
+ generated_at="2026-10-11T00:00:00+00:00",
+ provider_runtime=schema.ProviderRuntime(
+ reasoning_provider="mock", planner_model="mock", rerank_model="mock",
+ ),
+ query_plan=_plan("SQLite"),
+ clusters=[], ranked_candidates=[],
+ items_by_source={"reddit": [item]}, errors_by_source={},
+ )
+ dump = render.render_full(report).split("## All Items by Source", 1)[1]
+ assert "**i1** (score:73)" in dump
+
+
+# --- Fix 5: first-party floors only for on-topic posts or the topic's handle --
+
+def _rerank_one_with_peers(topic, target, handles, primary_handle=None):
+ peers = [
+ _candidate(author=f"peer{i}", text=f"{topic} thoughts {i}", engagement=e, freshness=80)
+ for i, e in enumerate((1, 2))
+ ]
+ pool = [target, *peers]
+ for c in pool:
+ c.candidate_id = f"{c.candidate_id}-{id(c)}"
+ rerank.rerank_candidates(
+ topic=topic, plan=_plan(topic), candidates=pool, provider=None, model=None,
+ shortlist_size=10, resolved_handles=set(handles), primary_handle=primary_handle,
+ )
+ return target
+
+
+def test_off_topic_first_party_reply_is_not_floored():
+ nanit = _candidate(author="mitchellh", text="@johnsoncory_ Nanit", rel=0.0,
+ mentions=["johnsoncory_"], engagement=20, freshness=82)
+ # --x-handle mitchellh: the primary handle, but not the topic's own account.
+ _rerank_one_with_peers("Ghostty terminal", nanit, {"mitchellh"}, primary_handle="mitchellh")
+ # Its own score stands: no interaction / first-party / rescue floor lifted it.
+ assert nanit.final_score == rerank._final_score(nanit)
+ assert nanit.final_score < rerank.FIRST_PARTY_FLOOR
+ # Still protected from the entity-miss marker / visibility prune.
+ assert "entity-miss" not in (nanit.explanation or "")
+ assert rerank.prune_fallback_entity_misses([nanit], topic="Ghostty terminal") == [nanit]
+
+
+def test_off_topic_related_handle_post_is_not_rescued_by_engagement():
+ """Top of the X pool by engagement, but off-topic: the rescue must not lift it."""
+ shower = _candidate(author="simonw", text="Current iPhones are waterproof enough for the shower",
+ rel=0.0, engagement=24, freshness=87, mentions=["romanhotsiy"])
+ _rerank_one_with_peers("SQLite", shower, {"simonw"})
+ assert shower.final_score == rerank._final_score(shower)
+ assert shower.final_score < rerank.FIRST_PARTY_FLOOR
+
+
+def test_on_topic_first_party_reply_is_still_floored():
+ c = _candidate(author="mitchellh", text="@someone Ghostty 1.3 fixes that", rel=0.5,
+ mentions=["someone"])
+ c.final_score = 5.0
+ rerank._apply_interaction_signal(
+ [c], resolved_handles={"mitchellh"}, primary_entity="Ghostty terminal",
+ topic="Ghostty terminal",
+ )
+ assert c.final_score >= rerank.INTERACTION_FLOOR
+
+
+def test_person_topic_subject_reply_is_still_floored():
+ """214a8fa0's case: the subject's own reply never names them (--x-handle steipete)."""
+ c = _candidate(author="steipete", text="@someone thanks, shipping tonight", rel=0.0,
+ mentions=["someone"])
+ c.final_score = 5.0
+ rerank._apply_interaction_signal(
+ [c], resolved_handles={"steipete"}, primary_entity="Peter Steinberger",
+ topic="Peter Steinberger", primary_handle="steipete",
+ )
+ assert c.final_score >= rerank.INTERACTION_FLOOR
+ d = _candidate(author="steipete", text="shipping tonight", rel=0.0)
+ d.final_score = 2.0
+ rerank._apply_first_party_floor(
+ [d], resolved_handles={"steipete"}, primary_entity="Peter Steinberger",
+ topic="Peter Steinberger", primary_handle="steipete",
+ )
+ assert d.final_score >= rerank.FIRST_PARTY_FLOOR
+
+
+def test_person_topic_end_to_end_keeps_subject_reply_floored():
+ reply = _candidate(author="steipete", text="@someone thanks, shipping tonight", rel=0.0,
+ mentions=["someone"], engagement=1, freshness=80)
+ _rerank_one_with_peers("Peter Steinberger", reply, {"steipete"}, primary_handle="steipete")
+ assert reply.final_score >= rerank.INTERACTION_FLOOR
+
+
+def test_handle_is_topic_matching():
+ assert rerank._handle_is_topic("steipete", "Peter Steinberger")
+ assert rerank._handle_is_topic("sama", "Sam Altman")
+ assert rerank._handle_is_topic("mitchellh", "Mitchell Hashimoto")
+ assert rerank._handle_is_topic("karpathy", "Andrej Karpathy")
+ assert rerank._handle_is_topic("ghostty", "Ghostty terminal")
+ assert rerank._handle_is_topic("steipete", "Peter Steinberger steipete")
+ assert not rerank._handle_is_topic("mitchellh", "Ghostty terminal")
+ assert not rerank._handle_is_topic("simonw", "SQLite")
+ assert not rerank._handle_is_topic("", "SQLite")
+
+
+def test_off_topic_first_party_gets_no_authorship_credit():
+ off = _candidate(author="mitchellh", text="@johnsoncory_ Nanit", rel=0.0)
+ stranger = _candidate(author="stranger", text="@johnsoncory_ Nanit", rel=0.0)
+ off_score, off_reason = rerank._fallback_tuple(
+ off, primary_entity="Ghostty terminal", resolved_handles={"mitchellh"},
+ subject_handles=set(),
+ )
+ base, _ = rerank._fallback_tuple(stranger)
+ assert off_score == base
+ assert "entity-miss" not in off_reason
+
+
+# --- Review fixes: provenance, subject role, short topics, engagement units --
+
+def test_llm_reason_starting_with_fallback_is_still_cliffed():
+ """Provenance comes from the scoring path, not the explanation wording."""
+ tricky = _candidate(text="SQLite tricky")
+ plain = _candidate(text="SQLite plain")
+ payload = {"scores": [
+ {"candidate_id": tricky.candidate_id, "relevance": 10,
+ "reason": "fallback option only, barely related"},
+ {"candidate_id": plain.candidate_id, "relevance": 10, "reason": "barely related"},
+ ]}
+ rerank._apply_llm_scores([tricky, plain], payload)
+ assert tricky.explanation == "fallback option only, barely related"
+ assert abs(tricky.final_score - plain.final_score) < 1e-9
+
+
+def test_unscored_candidate_in_llm_batch_is_fallback_scored_and_not_cliffed():
+ missing = _candidate(rel=0.1, text="SQLite missing")
+ rerank._apply_llm_scores([missing], {"scores": []})
+ assert missing.rerank_score < 20.0
+ assert missing.explanation == "fallback-local-score"
+ assert rerank._is_fallback_scored(missing)
+
+
+def test_related_handle_inside_a_topic_word_is_not_a_subject():
+ """'art' sits inside 'smart', but a related handle is never the subject."""
+ reply = _candidate(author="art", text="@friend lunch was great", rel=0.0, mentions=["friend"])
+ reply.final_score = 5.0
+ rerank._apply_interaction_signal(
+ [reply], resolved_handles={"art"}, primary_entity="Smart home", topic="Smart home",
+ )
+ assert reply.final_score == 5.0
+ post = _candidate(author="art", text="lunch was great", rel=0.0)
+ post.final_score = 2.0
+ rerank._apply_first_party_floor(
+ [post], resolved_handles={"art"}, primary_entity="Smart home", topic="Smart home",
+ )
+ assert post.final_score == 2.0
+
+
+def test_related_handle_off_topic_post_end_to_end_gets_no_lift():
+ reply = _candidate(author="art", text="@friend lunch was great", rel=0.0,
+ mentions=["friend"], engagement=30, freshness=82)
+ _rerank_one_with_peers("Smart home", reply, {"art", "homeowner"}, primary_handle="homeowner")
+ assert reply.final_score == rerank._final_score(reply)
+ assert reply.final_score < rerank.FIRST_PARTY_FLOOR
+
+
+def test_primary_handle_must_still_name_the_topic():
+ assert rerank._subject_handles("steipete", "Peter Steinberger") == {"steipete"}
+ assert rerank._subject_handles("@SteiPete", "Peter Steinberger") == {"steipete"}
+ assert rerank._subject_handles("mitchellh", "Ghostty terminal") == set()
+ assert rerank._subject_handles(None, "Smart home") == set()
+
+
+def test_short_topic_related_handle_off_topic_post_is_not_floored():
+ """'Go' cannot be grounded safely, so the floors need real relevance."""
+ reply = _candidate(author="rob", text="@friend lunch was great", rel=0.0,
+ mentions=["friend"], engagement=30, freshness=82)
+ _rerank_one_with_peers("Go", reply, {"rob"})
+ assert reply.final_score == rerank._final_score(reply)
+ assert reply.final_score < rerank.FIRST_PARTY_FLOOR
+
+
+def test_short_topic_on_topic_first_party_post_is_still_floored():
+ c = _candidate(author="rob", text="@someone go 1.26 generics are great", rel=0.5,
+ mentions=["someone"])
+ c.final_score = 5.0
+ rerank._apply_interaction_signal(
+ [c], resolved_handles={"rob"}, primary_entity="Go", topic="Go",
+ )
+ assert c.final_score >= rerank.INTERACTION_FLOOR
+
+
+def test_polymarket_engagement_does_not_saturate_on_dollar_amounts():
+ pm = _item("pm", "polymarket", "Will SQLite 4 ship?", TO,
+ {"volume": 5678, "liquidity": 100000})
+ reddit = _item("r", "reddit", "SQLite thread", TO, {"score": 250, "num_comments": 24})
+ assert signals.engagement_score(reddit) == 51
+ # 0.6*log1p(5678) + 0.4*log1p(100000) over polymarket.py's own anchors
+ # (0.6*16 + 0.4*14 = 15.2): 9.79 / 15.2.
+ assert signals.engagement_score(pm) == 64
+
+
+def test_engagement_reference_units_per_source():
+ def score(source, engagement):
+ return signals.engagement_score(_item("i", source, "t", TO, engagement))
+
+ # Lifetime totals on a company or product: ~300 maps near 50, not 100.
+ assert score("trustpilot", {"reviews": 300, "trustScore": 4.2}) == 50
+ assert score("amazon", {"ratings": 300}) == 50
+ # A busy issue sits mid-scale; a repo snapshot's lifetime stars are not engagement.
+ assert 40 <= score("github", {"reactions": 50, "comments": 80}) <= 55
+ assert score("github", {"stars": 2000, "comments": 50}) is None
+ # A rank-1 Digg cluster with 15 posts is strong but not saturated.
+ assert 60 <= score("digg", {"postCount": 15, "uniqueAuthors": 10, "rank_score": 50}) <= 75
+ # No audience signal: no engagement score at all.
+ assert score("jobs", {"open_roles": 1}) is None
+ assert score("meta_ads", {"variants": 7}) is None
+ assert score("perplexity", {"citations": 12}) is None
+ assert score("grounding", {"citations": 3}) is None
+ assert score("stocktwits", {"likes": 0, "reshares": 0, "followers": 50000}) is None
+ assert score("telegram", {"views": 100, "reactions": 0, "subscribers": 1000000}) is None
+
+
+def test_every_source_declares_its_engagement_units():
+ from lib import pipeline
+
+ sources = set(pipeline.MOCK_AVAILABLE_SOURCES) | {"stocktwits"}
+ undeclared = {
+ s for s in sources
+ if s not in signals._ENGAGEMENT_LOG_REFERENCE
+ and s not in signals._NO_ENGAGEMENT_SCORE_SOURCES
+ }
+ assert undeclared == set()
+
+
+# --- Repo snapshot cards carry lifetime totals, not month-window engagement ---
+# 2026-10-11 e2e: --github-repo project cards ranked #1 in 3 of 4 runs
+# (Ghostty 62K stars, Bun 96K, SQLite 11K) on saturated engagement from
+# lifetime stars, and the SQLite card also took first-party authorship credit
+# because its owner ("sqlite") matched a topic-token handle.
+
+def _repo_snapshot(item_id, repo, stars, open_issues, author, labels=("project-mode",)):
+ return schema.SourceItem(
+ item_id=item_id, source="github",
+ title=f"{repo} ({stars // 1000}K stars) - {open_issues} open issues",
+ body=f"Project: {repo}", url=f"https://github.com/{repo}", author=author,
+ container=repo, published_at=TO, date_confidence="high",
+ engagement={"stars": stars, "comments": open_issues},
+ metadata={"labels": list(labels), "state": "open", "is_pr": False},
+ )
+
+
+def test_repo_snapshot_gets_no_engagement_score():
+ # Project mode (owner as author) and every person-mode repo card shape.
+ assert signals.engagement_score(_repo_snapshot("p", "oven-sh/bun", 96195, 9551, "oven-sh")) is None
+ for labels in (["person-profile", "own-repo"], ["person-profile", "external-repo"],
+ ["person-profile", "recent-push"]):
+ card = _repo_snapshot("o", "steipete/peekaboo", 3000, 12, "steipete", labels=labels)
+ assert signals.engagement_score(card) is None
+
+
+def test_github_issues_and_prs_keep_their_engagement():
+ issue = _item("i", "github", "SQLite WAL corruption", TO, {"reactions": 50, "comments": 80})
+ issue.metadata = {"labels": [], "state": "open", "is_pr": False}
+ pr = _item("p", "github", "Fix WAL checkpoint", TO, {"reactions": 12, "comments": 30})
+ pr.metadata = {"labels": [], "state": "closed", "is_pr": True}
+ assert 40 <= signals.engagement_score(issue) <= 55
+ assert signals.engagement_score(pr) > 0
+
+
+def test_repo_snapshot_gets_no_first_party_credit_or_floor():
+ # "sqlite" is a topic-token handle (pipeline._topic_first_party_candidates)
+ # and the project card's author is the repo owner, so it matched.
+ card = _repo_snapshot("g", "sqlite/sqlite", 96000, 24, "sqlite")
+ with_handle = _rank("SQLite", {"github": [card]}, handles={"sqlite"})[0]
+ card2 = _repo_snapshot("g", "sqlite/sqlite", 96000, 24, "sqlite")
+ without = _rank("SQLite", {"github": [card2]})[0]
+ assert "first-party" not in (with_handle.explanation or "")
+ assert with_handle.final_score == without.final_score
+
+
+def test_person_mode_repo_card_is_not_floored_but_not_pruned():
+ card = _repo_snapshot("o", "steipete/peekaboo", 3000, 12, "steipete",
+ labels=["person-profile", "own-repo"])
+ c = _candidate(author="steipete", text=card.title, rel=0.0, source="github")
+ c.source_items = [card]
+ _rerank_one_with_peers("Peter Steinberger", c, {"steipete"}, primary_handle="steipete")
+ assert c.final_score < rerank.FIRST_PARTY_FLOOR
+ assert "entity-miss" not in (c.explanation or "")
+ assert rerank.prune_fallback_entity_misses([c], topic="Peter Steinberger") == [c]
+
+
+def test_96k_star_repo_card_does_not_outrank_equally_relevant_380_point_hn_story():
+ title = "sqlite/sqlite SQLite source repository"
+ card = _repo_snapshot("g", "sqlite/sqlite", 96000, 24, "sqlite")
+ card.title = card.body = title
+ hn = _item("hn", "hackernews", title, "2026-10-09", {"points": 380, "comments": 166})
+ ranked = _rank("SQLite", {"github": [card], "hackernews": [hn]}, handles={"sqlite"})
+ assert [c.item_id for c in ranked] == ["hn", "g"]
+
+
+# --- View-weighted platforms are calibrated on a view scale -------------------
+# 2026-10-11 e2e: a 117-view YouTube video ranked #2 for SQLite, and 655-view
+# TikToks with 17 likes scored near a 9,676-upvote Reddit thread, because
+# log1p(views) dominates engagement_raw for YouTube/TikTok/Instagram while the
+# reference was calibrated like votes.
+
+def _score(source, engagement):
+ return signals.engagement_score(_item("i", source, "t", TO, engagement))
+
+
+def test_view_platform_scores_land_in_intended_bands():
+ # A barely-watched upload is near the bottom, like a 3-like X post (~8).
+ assert _score("youtube", {"views": 117, "likes": 1}) <= 10
+ assert _score("tiktok", {"views": 1000}) <= 15
+ # Hundreds of views and a few dozen likes: low, below a 50-upvote Reddit post.
+ assert 10 <= _score("tiktok", {"views": 655, "likes": 17}) <= 25
+ assert _score("tiktok", {"views": 655, "likes": 17}) < _score(
+ "reddit", {"score": 50, "num_comments": 20, "upvote_ratio": 0.9})
+ # A real hit is strong; ~1M+ views nears the top.
+ assert 60 <= _score("tiktok", {"views": 133690, "likes": 8441, "comments": 192}) <= 80
+ assert 75 <= _score("youtube", {"views": 726269, "likes": 13031, "comments": 1300}) <= 92
+ assert _score("youtube", {"views": 5_000_000, "likes": 150_000, "comments": 5000}) >= 95
+ assert _score("instagram", {"views": 1_000_000, "likes": 50_000, "comments": 1000}) >= 80
+
+
+def test_655_view_tiktok_scores_well_below_9676_upvote_reddit_thread():
+ tiktok = _score("tiktok", {"views": 655, "likes": 17})
+ reddit = _score("reddit", {"score": 9676, "num_comments": 455, "upvote_ratio": 0.95})
+ assert reddit - tiktok >= 60