返回 last30days-skill
signals.py
根目录 / skills / last30days / scripts / lib / signals.py
1 """Reusable local scoring signals for v3 pipeline stages."""
2
3 from __future__ import annotations
4
5 import math
6 from collections.abc import Iterable, Mapping
7
8 from datetime import datetime, timezone
9
10 from . import cjk, dates, reddit_refs, relevance, rust_accel, schema
11
12 # Editorial signal-to-noise scores. Grounding (Google Search) is 1.0 baseline;
13 # social platforms discounted for noise.
14 SOURCE_QUALITY = {
15 "xiaohongshu": 0.7,
16 "hackernews": 0.8,
17 "devto": 0.78,
18 "v2ex": 0.72,
19 "juejin": 0.75,
20 "youtube": 0.85,
21 "digg": 0.85,
22 "arxiv": 0.9,
23 "techmeme": 0.85,
24 # Mainstream news/RSS augments social threads rather than outranking them:
25 # sits below reddit/x/youtube/hn so community discussion leads the front.
26 "news_rss": 0.55,
27 "trustpilot": 0.78,
28 # Verified-purchase reviews on a live aggregate rating: high-quality
29 # buyer evidence, a notch above Trustpilot's open review model.
30 "amazon": 0.8,
31 # Paid creative is first-party marketing copy: a reliable statement of
32 # what the brand is pushing, but not independent evidence about it, so it
33 # sits below the review-backed sources and above open social.
34 "meta_ads": 0.72,
35 "reddit": 0.6,
36 "x": 0.68,
37 "bluesky": 0.66,
38 "truthsocial": 0.6,
39 "polymarket": 0.5,
40 "instagram": 0.58,
41 "tiktok": 0.58,
42 "jobs": 0.72,
43 "corpus": 0.75,
44 }
45
46
47 def source_quality(source: str) -> float:
48 return SOURCE_QUALITY.get(source, 0.6)
49
50
51 def local_relevance(
52 item: schema.SourceItem,
53 ranking_query: "str | relevance.PreparedQuery",
54 ) -> float:
55 text = "\n".join(
56 part
57 for part in [item.title, item.body, item.snippet]
58 if part
59 )
60 hashtags = item.metadata.get("hashtags") if isinstance(item.metadata, dict) else None
61 score = relevance.token_overlap_relevance(ranking_query, text, hashtags=hashtags)
62
63 # High-engagement YouTube floor: official videos with millions of views
64 # often have titles that don't keyword-match the query (e.g., "YE - FATHER
65 # (feat. TRAVIS SCOTT)" doesn't match "kanye west"). The engagement signals
66 # say "this is important" even when text overlap is weak.
67 if item.source == "youtube" and (item.engagement.get("views") or 0) > 100_000:
68 score = max(score, 0.3)
69
70 # Project-mode GitHub floor: items fetched via --github-repo are explicitly
71 # requested by the user and relevant by construction. Without this floor,
72 # repos with low token diversity (e.g., "openclaw/openclaw" -> 1 unique token)
73 # get pruned despite being the primary search target.
74 labels = item.metadata.get("labels", []) if isinstance(item.metadata, dict) else []
75 if "project-mode" in labels:
76 score = max(score, 0.8)
77
78 # Grounding-exempt floor (currently Amazon): the adapter already gated
79 # these against the model-supplied product keyword before creating them,
80 # so they are relevant by construction. Their text is marketing copy plus
81 # buyer reviews, which rarely repeats the topic phrasing -- a "Weber
82 # Grills" run surfaces a product named "Spirit E-325" whose reviews talk
83 # about searing, not about Weber. Without the floor, correctly-retrieved
84 # evidence gets pruned for failing a keyword match it was never going to
85 # win. Mirrors the project-mode GitHub floor above.
86 if isinstance(item.metadata, dict) and item.metadata.get("grounding_exempt"):
87 score = max(score, 0.8)
88
89 return score
90
91
92 def freshness(
93 item: schema.SourceItem,
94 freshness_mode: str = "balanced_recent",
95 *,
96 reference_date: str | None = None,
97 max_days: int = 30,
98 ) -> int:
99 # A live repo snapshot dated to the window end (no in-window release) has a
100 # read time, not an event date: rank it at the scale's midpoint instead of
101 # maximum freshness, or every pinned repo card sorts to #1.
102 if isinstance(item.metadata, dict) and item.metadata.get("date_is_snapshot"):
103 return 50
104 score = dates.recency_score(
105 item.published_at,
106 max_days=max_days,
107 reference_date=reference_date,
108 )
109 if freshness_mode == "strict_recent":
110 return int(score)
111 if freshness_mode == "evergreen_ok":
112 return int((score * 0.6) + 40)
113 return int((score * 0.8) + 10)
114
115
116 def log1p_safe(value: float | int | None) -> float:
117 if value is None or isinstance(value, bool):
118 return 0.0
119 try:
120 numeric = float(value)
121 except (TypeError, ValueError, OverflowError):
122 return 0.0
123 if not math.isfinite(numeric) or numeric <= 0:
124 return 0.0
125 return math.log1p(numeric)
126
127
128 def _top_comment_score(item: schema.SourceItem) -> float:
129 if not isinstance(item.metadata, dict):
130 return 0.0
131 comments = item.metadata.get("top_comments")
132 if not isinstance(comments, (list, tuple)) or not comments or not isinstance(comments[0], dict):
133 return 0.0
134 return log1p_safe(comments[0].get("score"))
135
136
137 # Per-platform log-reference for normalizing a top comment's vote count into a
138 # [0,1] signal. Reddit upvotes run in the hundreds-to-thousands; YouTube/TikTok
139 # likes run 10-600x higher (and the top end is display-abbreviated: "39K" is
140 # stored as 39000). A raw or single-scale log compare would let YouTube/TikTok
141 # dominate purely by platform scale, not by being funnier. Each value is the
142 # log1p of a "very high" top-comment count for that platform, so dividing a
143 # comment's log1p(score) by it yields a comparable cross-platform strength.
144 _VOTE_LOG_REFERENCE: dict[str, float] = {
145 "reddit": 7.6, # ~log1p(2000)
146 "hackernews": 6.2, # ~log1p(500)
147 "devto": 3.0, # ~log1p(20) direct replies; the API has no comment likes
148 "youtube": 10.3, # ~log1p(30000)
149 "tiktok": 10.3, # ~log1p(30000)
150 "instagram": 9.2, # ~log1p(10000)
151 "x": 9.2, # ~log1p(10000)
152 "bluesky": 9.2, # ~log1p(10000); like X/IG, not the Reddit default
153 }
154 _VOTE_LOG_REFERENCE_DEFAULT = 7.6
155
156
157 def normalized_comment_vote(source: str, score: "float | int | None") -> float:
158 """Normalize a single comment's vote count to [0,1] within its platform.
159
160 Same per-platform reference as ``top_comment_vote_signal`` so a 22k-like
161 TikTok comment and a 600-upvote Reddit comment rank on a comparable scale.
162 Used to rank the cross-candidate Top Community Comments block.
163 """
164 base = log1p_safe(score)
165 if base <= 0.0:
166 return 0.0
167 ref = _VOTE_LOG_REFERENCE.get(source, _VOTE_LOG_REFERENCE_DEFAULT)
168 return max(0.0, min(1.0, base / ref))
169
170
171 def top_comment_vote_signal(candidate: schema.Candidate) -> float:
172 """Strength of a candidate's most-upvoted top comment, as [0,1].
173
174 Normalized *within the candidate's platform* (see ``_VOTE_LOG_REFERENCE``)
175 so a 22k-like TikTok comment and a 600-upvote Reddit comment land on a
176 comparable scale rather than letting raw counts dominate. Returns 0.0 when
177 no top comment carries votes. Used by the fun judge to amplify (never
178 drive) crowd-certified comments.
179 """
180 best_log = 0.0
181 for item in candidate.source_items:
182 if not isinstance(item.metadata, dict):
183 continue
184 comments = item.metadata.get("top_comments")
185 if not isinstance(comments, (list, tuple)):
186 continue
187 for comment in comments[:3]:
188 if isinstance(comment, dict):
189 best_log = max(best_log, log1p_safe(comment.get("score")))
190 if best_log <= 0.0:
191 return 0.0
192 ref = _VOTE_LOG_REFERENCE.get(candidate.source, _VOTE_LOG_REFERENCE_DEFAULT)
193 return max(0.0, min(1.0, best_log / ref))
194
195
196 # Per-source engagement weights: list of (field_name, weight) tuples.
197 # Reddit, YouTube, and TikTok use custom functions because they include
198 # a dedicated 10% top-comment-score slot (see _reddit_engagement,
199 # _youtube_engagement, _tiktok_engagement). Digg uses these weights only when
200 # the story carries a Digg Score (see _digg_engagement).
201 ENGAGEMENT_WEIGHTS: dict[str, list[tuple[str, float]]] = {
202 "x": [("likes", 0.55), ("reposts", 0.25), ("replies", 0.15), ("quotes", 0.05)],
203 "threads": [("likes", 0.55), ("reposts", 0.25), ("replies", 0.15), ("quotes", 0.05)],
204 "instagram": [("views", 0.50), ("likes", 0.30), ("comments", 0.20)],
205 "hackernews": [("points", 0.55), ("comments", 0.45)],
206 "devto": [("reactions", 0.60), ("comments", 0.40)],
207 "v2ex": [("replies", 1.0)],
208 "juejin": [("likes", 0.40), ("comments", 0.25), ("saves", 0.15), ("views", 0.20)],
209 "github": [("reactions", 0.60), ("comments", 0.40)],
210 "bluesky": [("likes", 0.40), ("reposts", 0.30), ("replies", 0.20), ("quotes", 0.10)],
211 "truthsocial": [("likes", 0.45), ("reposts", 0.30), ("replies", 0.25)],
212 "pinterest": [("saves", 0.70), ("comments", 0.30)],
213 "linkedin": [("likes", 0.55), ("comments", 0.30), ("reposts", 0.15)],
214 "linkedin_profile": [("likes", 0.55), ("comments", 0.30), ("shares", 0.15)],
215 "xiaohongshu": [("likes", 0.50), ("favorites", 0.30), ("comments", 0.20)],
216 "polymarket": [("volume", 0.60), ("liquidity", 0.40)],
217 "digg": [("digg_score", 0.50), ("postCount", 0.30), ("uniqueAuthors", 0.20)],
218 "trustpilot": [("reviews", 1.0)],
219 "amazon": [("ratings", 1.0)],
220 # Meta publishes reach and spend only for political and issue ads, so a
221 # commercial creative has no audience signal at all. How many variants a
222 # brand cut of one creative is the closest honest proxy for how hard it is
223 # pushing that message.
224 "meta_ads": [("variants", 1.0)],
225 }
226
227
228 def _weighted_engagement(item: schema.SourceItem, weights: list[tuple[str, float]]) -> float | None:
229 values = [(log1p_safe(item.engagement.get(field)), weight) for field, weight in weights]
230 if not any(v for v, _ in values):
231 return None
232 return sum(v * w for v, w in values)
233
234
235 # Digg stories from a CLI that reports no Digg Score: the two counts carry the
236 # whole signal, in the same 3:2 proportion they have beside a score.
237 _DIGG_COUNT_WEIGHTS: list[tuple[str, float]] = [("postCount", 0.60), ("uniqueAuthors", 0.40)]
238
239 # GitHub person-mode contribution velocity summaries report merged_prs and
240 # total_prs rather than issue/PR reactions and comments.
241 _GITHUB_VELOCITY_WEIGHTS: list[tuple[str, float]] = [("merged_prs", 0.70), ("total_prs", 0.30)]
242
243
244 def _digg_engagement(item: schema.SourceItem) -> float | None:
245 if log1p_safe(item.engagement.get("digg_score")) > 0:
246 return _weighted_engagement(item, ENGAGEMENT_WEIGHTS["digg"])
247 return _weighted_engagement(item, _DIGG_COUNT_WEIGHTS)
248
249
250 def _github_engagement(item: schema.SourceItem) -> float | None:
251 labels = item.metadata.get("labels", []) if isinstance(item.metadata, dict) else []
252 eng = item.engagement or {}
253 if "velocity" in labels or "merged_prs" in eng or "total_prs" in eng:
254 return _weighted_engagement(item, _GITHUB_VELOCITY_WEIGHTS)
255 return _weighted_engagement(item, ENGAGEMENT_WEIGHTS["github"])
256
257
258 def _reddit_engagement(item: schema.SourceItem) -> float | None:
259 score = log1p_safe(item.engagement.get("score"))
260 comments = log1p_safe(item.engagement.get("num_comments"))
261 ratio = float(item.engagement.get("upvote_ratio") or 0.0)
262 top_comment = _top_comment_score(item)
263 if not any([score, comments, ratio, top_comment]):
264 return None
265 return (0.50 * score) + (0.35 * comments) + (0.05 * (ratio * 10.0)) + (0.10 * top_comment)
266
267
268 def _youtube_engagement(item: schema.SourceItem) -> float | None:
269 views = log1p_safe(item.engagement.get("views"))
270 likes = log1p_safe(item.engagement.get("likes"))
271 comments = log1p_safe(item.engagement.get("comments"))
272 top_comment = _top_comment_score(item)
273 if not any([views, likes, comments, top_comment]):
274 return None
275 # Mirrors Reddit: carve out 10% for top-comment signal, keep view-weight
276 # dominant. Without comments, the pre-change weights (0.50/0.35/0.15)
277 # still govern relative ordering.
278 return (0.45 * views) + (0.32 * likes) + (0.13 * comments) + (0.10 * top_comment)
279
280
281 def _tiktok_engagement(item: schema.SourceItem) -> float | None:
282 views = log1p_safe(item.engagement.get("views"))
283 likes = log1p_safe(item.engagement.get("likes"))
284 comments = log1p_safe(item.engagement.get("comments"))
285 top_comment = _top_comment_score(item)
286 if not any([views, likes, comments, top_comment]):
287 return None
288 return (0.45 * views) + (0.27 * likes) + (0.18 * comments) + (0.10 * top_comment)
289
290
291 def _instagram_engagement(item: schema.SourceItem) -> float | None:
292 # Mirrors _tiktok_engagement: reels are video-shaped, and a highly-liked top
293 # comment carves out 10% of the signal (via comment_like_count -> score) so
294 # crowd-loved IG comments lift their post's ranking like YouTube/TikTok.
295 views = log1p_safe(item.engagement.get("views"))
296 likes = log1p_safe(item.engagement.get("likes"))
297 comments = log1p_safe(item.engagement.get("comments"))
298 top_comment = _top_comment_score(item)
299 if not any([views, likes, comments, top_comment]):
300 return None
301 return (0.45 * views) + (0.27 * likes) + (0.18 * comments) + (0.10 * top_comment)
302
303
304 def _generic_engagement(item: schema.SourceItem) -> float | None:
305 if not item.engagement:
306 return None
307 # Key-count-invariant peak + secondary bonus: adding optional keys (0, None,
308 # or positive) to a sparse dict is always non-decreasing.
309 pos = [logged for v in item.engagement.values() if (logged := log1p_safe(v)) > 0]
310 if not pos:
311 return None
312 peak = max(pos)
313 return peak + 0.1 * (sum(pos) - peak)
314
315
316 def engagement_raw(item: schema.SourceItem) -> float | None:
317 if item.source == "reddit":
318 return _reddit_engagement(item)
319 if item.source == "youtube":
320 return _youtube_engagement(item)
321 if item.source == "tiktok":
322 return _tiktok_engagement(item)
323 if item.source == "instagram":
324 return _instagram_engagement(item)
325 if item.source == "digg":
326 return _digg_engagement(item)
327 if item.source == "github":
328 return _github_engagement(item)
329 weights = ENGAGEMENT_WEIGHTS.get(item.source)
330 if weights:
331 return _weighted_engagement(item, weights)
332 return _generic_engagement(item)
333
334
335 # Per-source log reference for engagement_score, in each source's own units.
336 # Same convention as _VOTE_LOG_REFERENCE (which it extends): the value is
337 # engagement_raw for a "very high" item, so that item scores 100 and, the scale
338 # being logarithmic, roughly its square root scores 50. Every source that can
339 # reach engagement_raw is listed here or in _NO_ENGAGEMENT_SCORE_SOURCES; an
340 # unlisted source gets no score rather than an assumed Reddit-vote scale.
341 _ENGAGEMENT_LOG_REFERENCE: dict[str, float] = {
342 **_VOTE_LOG_REFERENCE,
343 # Microblog likes/reposts/replies run on X's scale (~10k likes is very high).
344 "truthsocial": 9.2, # ~log1p(10000)
345 "threads": 9.2, # ~log1p(10000)
346 # Likes/comments/favorites on an Instagram-like feed.
347 "xiaohongshu": 9.2, # ~log1p(10000)
348 # Topic reply counts. The V2EX hot list on 2026-11-26 ran 130, 97, 81 at
349 # the top and 57 at the median, so ~150 replies is a very busy topic.
350 "v2ex": 5.0, # ~log1p(150)
351 # Likes, comments, saves and views on the ENGAGEMENT_WEIGHTS mix. 467
352 # in-window articles across 8 topics on 2026-11-27 ran a weighted log
353 # mix of 0.76 at the median (no likes, ~35 views), 1.44 at p90, 2.86 at
354 # p99 (e.g. 8 likes, 3 comments, 4 saves, 1.2k views) and 4.08 at most,
355 # so the median article scores ~23 and the top percentile ~87.
356 "juejin": 3.3,
357 # Saves on a viral pin reach ~10k.
358 "pinterest": 9.2, # ~log1p(10000)
359 # Reactions run like Reddit upvotes: a viral post has ~2k.
360 "linkedin": 7.6, # ~log1p(2000)
361 "linkedin_profile": 7.6, # the person's own posts, same scale
362 # Per-issue/PR reactions and comments (repo snapshot cards, whose counts
363 # are lifetime stars, get no score: see is_repo_snapshot). A
364 # ~100-reaction thread lands near 50.
365 "github": 9.2, # ~log1p(10000)
366 # Dollars, not votes. polymarket.py's own saturation anchors: $9M volume
367 # (log1p 16) and $1.2M liquidity (log1p 14), weighted 0.6/0.4 as in
368 # ENGAGEMENT_WEIGHTS: 0.6*16 + 0.4*14 = 15.2.
369 "polymarket": 15.2,
370 # Digg Score, source count (stored as postCount) and unique authors.
371 # Calibrated on a 30-day search for "OpenAI" (99 stories, 2026-11-11):
372 # Digg Scores ran 1286, 473, 239, 227, 226, 218, 180, 169, 163, 150 across
373 # the top decile, ~38 at the median and 5 at the bottom; the two largest
374 # stories had 121-127 sources, the rest of the top decile 22-59. The
375 # reference is the middle of that decile (score 226, 44 sources, 30
376 # authors): 0.5*log1p(226) + 0.3*log1p(44) + 0.2*log1p(30) = 4.5. The
377 # decile then scores 92-100 (its tenth story, 150/27/22, scores 92), the
378 # median story ~61 and the smallest (5/2/2) 32. A story with no score,
379 # weighted on counts alone, saturates at ~100 sources from ~100 authors
380 # (log1p(100) = 4.6).
381 "digg": 4.5,
382 # Lifetime totals for a whole company or product, not one post: big
383 # consumer brands and best-sellers carry ~100k, so ~300 lands near 50.
384 "trustpilot": 11.5, # ~log1p(100000) reviews
385 "amazon": 11.5, # ~log1p(100000) ratings
386 }
387
388 # Sources whose engagement fields are not an audience response, so no
389 # engagement score is comparable with votes or likes:
390 # jobs - a constant open_roles=1 per posting
391 # meta_ads - variant count measures the advertiser's push, not reach
392 # grounding, perplexity - web results; counts are citations, not readers
393 # stocktwits - the author's follower count dominates sparse likes/reshares
394 # telegram - the channel's subscriber count dominates per-post views
395 # arxiv, techmeme, news_rss, dripstack, corpus - no engagement fields at all
396 _NO_ENGAGEMENT_SCORE_SOURCES = frozenset({
397 "jobs", "meta_ads", "grounding", "perplexity", "stocktwits", "telegram",
398 "arxiv", "techmeme", "news_rss", "dripstack", "corpus",
399 })
400
401
402 # YouTube, TikTok, and Instagram weight log1p(views) at 0.45 in
403 # engagement_raw, and views run orders of magnitude above votes: any upload
404 # collects ~100 passive feed views, so a 117-view, 1-like video already had raw
405 # 2.4 (23 on the vote-style 10.3 reference, three times a 3-like X post).
406 # These sources map raw linearly from a floor (an upload with ~100 views and no
407 # reactions: 0.45*log1p(100) = 2.1) to a "very high" month-window post (~2-3M
408 # views, ~100k likes, ~3k comments: 0.45*14.9 + 0.32*11.5 + 0.13*8.0 = 11.4).
409 # Resulting scores: 117 views/1 like ~3, 655 views/17 likes ~17, 133k views/
410 # 8.4k likes ~70, 726k views/13k likes ~85, 1M+ views ~90-100.
411 _VIEW_ENGAGEMENT_SOURCES = frozenset({"youtube", "tiktok", "instagram"})
412 _VIEW_ENGAGEMENT_LOG_FLOOR = 2.1
413 _VIEW_ENGAGEMENT_LOG_REFERENCE = 11.5
414
415
416 def is_repo_snapshot(item: schema.SourceItem) -> bool:
417 """True for a GitHub repo card (project mode, person-mode repo items).
418
419 Their engagement is lifetime stars and the open-issue count, a snapshot
420 of the repo's whole history rather than an audience response inside the
421 window. Issues and PRs carry reactions/comments, never stars.
422 """
423 repo_page = schema.github_repository_page(item)
424 if repo_page is not None:
425 return repo_page
426 # Keep recognizing older GitHub snapshots with a lifetime count and no canonical URL.
427 return "stars" in (item.engagement or {})
428
429
430 def engagement_score(item: schema.SourceItem) -> int | None:
431 """Engagement on an absolute 0-100 scale, comparable across streams.
432
433 ``engagement_raw`` is a weighted mean of log1p counts, so dividing it by
434 the source's log reference (``_ENGAGEMENT_LOG_REFERENCE``, in that
435 source's own units) places a 250-upvote Reddit thread near 50 and a 3-like
436 X post near 8 no matter what else shares their stream. The per-stream
437 min-max rescale this replaces mapped every stream's best item to 100 and
438 a lone item to 50, so the score said nothing about actual engagement.
439 View-weighted sources (YouTube, TikTok, Instagram) use the view scale
440 (``_VIEW_ENGAGEMENT_LOG_FLOOR`` to ``_VIEW_ENGAGEMENT_LOG_REFERENCE``)
441 instead of their vote reference. Sources without a comparable audience
442 signal, and GitHub repo snapshots (lifetime stars), return None.
443 """
444 if item.source in _NO_ENGAGEMENT_SCORE_SOURCES or is_repo_snapshot(item):
445 return None
446 ref = _ENGAGEMENT_LOG_REFERENCE.get(item.source)
447 if ref is None:
448 return None
449 raw = engagement_raw(item)
450 if raw is None:
451 return None
452 if item.source in _VIEW_ENGAGEMENT_SOURCES:
453 floor = _VIEW_ENGAGEMENT_LOG_FLOOR
454 fraction = (raw - floor) / (_VIEW_ENGAGEMENT_LOG_REFERENCE - floor)
455 else:
456 fraction = raw / ref
457 return int(round(100.0 * max(0.0, min(1.0, fraction))))
458
459
460 def normalize(values: list[float | None]) -> list[int | None]:
461 valid = [value for value in values if value is not None]
462 if not valid:
463 return [None for _ in values]
464 low = min(valid)
465 high = max(valid)
466 if math.isclose(low, high):
467 return [50 if value is not None else None for value in values]
468 return [
469 None
470 if value is None
471 else int(((value - low) / (high - low)) * 100)
472 for value in values
473 ]
474
475
476 def _finite_number(value: object) -> float | None:
477 if value is None or isinstance(value, bool):
478 return None
479 try:
480 numeric = float(value)
481 except (TypeError, ValueError, OverflowError):
482 return None
483 return numeric if math.isfinite(numeric) else None
484
485
486 def _item_to_rust_signal(item: schema.SourceItem) -> dict[str, object]:
487 meta = item.metadata if isinstance(item.metadata, dict) else {}
488 eng = item.engagement if isinstance(item.engagement, dict) else {}
489 clean_eng: dict[str, float] = {}
490 for k, v in eng.items():
491 num = _finite_number(v)
492 if num is not None:
493 clean_eng[str(k)] = num
494 top_comment_score: float | None = None
495 comments = meta.get("top_comments")
496 if isinstance(comments, (list, tuple)) and comments and isinstance(comments[0], dict):
497 top_comment_score = _finite_number(comments[0].get("score"))
498 raw_hashtags = meta.get("hashtags")
499 hashtags = [str(h) for h in raw_hashtags] if isinstance(raw_hashtags, (list, tuple)) else []
500 raw_labels = meta.get("labels")
501 labels = [str(lbl) for lbl in raw_labels] if isinstance(raw_labels, (list, tuple)) else []
502 return {
503 "source": item.source,
504 "title": item.title or "",
505 "body": item.body or "",
506 "snippet": item.snippet or "",
507 "published_at": item.published_at if isinstance(item.published_at, str) else None,
508 "date_kind": "snapshot" if meta.get("date_is_snapshot") else "event",
509 "hashtags": hashtags,
510 "labels": labels,
511 "grounding": "exempt" if meta.get("grounding_exempt") else "standard",
512 "github_kind": "pull_request" if meta.get("is_pr") else "standard",
513 "engagement": clean_eng,
514 "has_stars_key": "stars" in eng,
515 "top_comment_score": top_comment_score,
516 }
517
518
519 def annotate_stream(
520 items: list[schema.SourceItem],
521 ranking_query: "str | relevance.PreparedQuery",
522 freshness_mode: str,
523 reference_date: str | None = None,
524 max_days: int = 30,
525 ) -> list[schema.SourceItem]:
526 """Attach local scoring metadata and return items sorted by local_rank_score."""
527 mode = rust_accel.engine_mode()
528 if (mode == "rust" and items) or (mode == "auto" and len(items) >= 256):
529 raw_query = ranking_query.raw if isinstance(ranking_query, relevance.PreparedQuery) else ranking_query
530 jieba_active = cjk._jieba is not None
531 has_jieba_cjk = jieba_active and (
532 cjk.has_cjk(raw_query)
533 or any(
534 cjk.has_cjk(part)
535 for it in items
536 for part in (
537 it.title or "",
538 it.body or "",
539 it.snippet or "",
540 *(str(tag) for tag in ((it.metadata or {}).get("hashtags") or [])),
541 )
542 )
543 )
544 if not has_jieba_cjk:
545 ref_date = reference_date or datetime.now(timezone.utc).date().isoformat()
546 rust_mode = (
547 freshness_mode
548 if freshness_mode in {"strict_recent", "evergreen_ok", "balanced_recent"}
549 else "balanced_recent"
550 )
551 payload_items = [_item_to_rust_signal(item) for item in items]
552 annotated = rust_accel.annotate_stream(
553 payload_items, raw_query, rust_mode, ref_date, int(max_days)
554 )
555 if annotated is not None:
556 ordered: list[schema.SourceItem] = []
557 for entry in annotated:
558 item = items[entry["index"]]
559 item.local_relevance = float(entry["local_relevance"])
560 item.freshness = int(entry["freshness"])
561 eng_val = entry["engagement_score"]
562 item.engagement_score = int(eng_val) if eng_val is not None else None
563 item.source_quality = float(entry["source_quality"])
564 item.local_rank_score = float(entry["local_rank_score"])
565 ordered.append(item)
566 return ordered
567
568 prepared_query = ranking_query if isinstance(ranking_query, relevance.PreparedQuery) else relevance.PreparedQuery(ranking_query)
569 for item in items:
570 eng_score = engagement_score(item)
571 item.local_relevance = local_relevance(item, prepared_query)
572 item.freshness = freshness(
573 item,
574 freshness_mode,
575 reference_date=reference_date,
576 max_days=max_days,
577 )
578 item.engagement_score = eng_score
579 item.source_quality = source_quality(item.source)
580 item.local_rank_score = (
581 0.65 * item.local_relevance
582 + 0.25 * (item.freshness / 100.0)
583 + 0.10 * ((eng_score or 0) / 100.0)
584 )
585 return sorted(items, key=lambda item: item.local_rank_score or 0, reverse=True)
586
587
588 _SOCIAL_SOURCES = {"reddit", "x", "tiktok", "instagram", "bluesky", "truthsocial"}
589
590 # Minimum view count for short-video platforms. Items below this floor
591 # are typically spam reposts or low-effort clips that add no unique signal.
592 _VIDEO_ENGAGEMENT_FLOOR_SOURCES = {"tiktok", "instagram"}
593 _VIDEO_ENGAGEMENT_FLOOR_VIEWS = 1000
594
595
596 def _reported_views(item: schema.SourceItem) -> float | None:
597 """Return finite numeric view count when reported, or None when absent/unreported."""
598 if not item.engagement or "views" not in item.engagement:
599 return None
600 raw = item.engagement.get("views")
601 if raw is None or isinstance(raw, bool):
602 return None
603 try:
604 numeric = float(raw)
605 except (TypeError, ValueError, OverflowError):
606 return None
607 return numeric if math.isfinite(numeric) else None
608
609
610 def _passes_engagement_floor(item: schema.SourceItem) -> bool:
611 """Check whether a TikTok/Instagram item meets the minimum view floor.
612
613 Items from sources not in _VIDEO_ENGAGEMENT_FLOOR_SOURCES always pass.
614 Items with no reported view count (``views`` missing or ``None``) also pass
615 so reels/videos whose upstream omitted play counts are not silently dropped;
616 reported numeric counts (including measured ``0``) must clear the floor.
617 Empty-batch protection is handled by ``prune_low_relevance``'s cascaded
618 ``filtered or rel_filtered or items`` fallback rather than a per-source bypass.
619 """
620 if item.source not in _VIDEO_ENGAGEMENT_FLOOR_SOURCES:
621 return True
622 views = _reported_views(item)
623 if views is None:
624 return True
625 return views >= _VIDEO_ENGAGEMENT_FLOOR_VIEWS
626
627
628 def prune_low_relevance(
629 items: list[schema.SourceItem],
630 minimum: float = 0.15,
631 first_party_handles: Iterable[str] | None = None,
632 first_party_by_source: Mapping[str, Iterable[str]] | None = None,
633 passing_only: bool = False,
634 ) -> list[schema.SourceItem]:
635 """Drop weak lexical matches when stronger evidence exists.
636
637 ``passing_only`` returns just the items that pass, with no keep-all rescue
638 when none does: the count a caller needs to ask "how much of this batch is
639 on topic".
640
641 Social-source items with genuinely zero engagement get a stricter
642 threshold because zero engagement on a social platform is a strong noise
643 signal.
644
645 TikTok and Instagram items with fewer than 1000 views are pruned
646 (falling back to relevance-passing items when none meets the view floor,
647 or all items when none passes relevance, if ``passing_only`` is False).
648
649 ``first_party_handles`` names accounts this run is explicitly searching
650 (the subject of the topic). Their own posts are exempt from the floor: a
651 post almost never contains its own author's name, so lexical relevance
652 scores it at or near zero no matter how on-topic it is. Without the
653 exemption a mixed batch loses them silently, because the ``filtered or
654 items`` rescue below only fires when *every* item fails.
655
656 ``first_party_by_source`` scopes exemptions to one platform each (e.g.
657 ``--ig-creators`` names Instagram accounts). A creator flag must not
658 exempt a same-name account on a *different* platform: username reuse
659 across platforms is common, and an unrelated account would otherwise
660 bypass the relevance and engagement floors.
661
662 A Polymarket item carrying ``matched_market`` passed the entity matcher
663 at parse and is exempt the same way; ``polymarket.filter_items_against_topic``
664 is its topic bar.
665 """
666 first_party = {
667 h.strip().lstrip("@").lower()
668 for h in (first_party_handles or ())
669 if h and h.strip()
670 }
671 scoped_first_party = {
672 source: {
673 h.strip().lstrip("@").lower()
674 for h in handles
675 if h and h.strip()
676 }
677 for source, handles in (first_party_by_source or {}).items()
678 }
679
680 def _is_first_party(item: schema.SourceItem) -> bool:
681 if not item.author:
682 return False
683 author = item.author.strip().lstrip("@").lower()
684 if author in first_party:
685 return True
686 return author in scoped_first_party.get(item.source, frozenset())
687
688 def passes_relevance(item: schema.SourceItem) -> bool:
689 # YouTube items with successfully extracted transcripts should not
690 # be pruned by title-only relevance scoring — the transcript content
691 # already proves substantive topical coverage.
692 if item.source == "youtube" and item.snippet:
693 return True
694 # Posts by an account this run is explicitly searching are evidence by
695 # provenance, not by lexical overlap with the topic.
696 if _is_first_party(item):
697 return True
698 # A Polymarket market the entity matcher kept names the subject (or a
699 # related name the host supplied), judged on the stable research
700 # topic. Its token overlap with the planner's ranking query says
701 # nothing more: "Vikings vs. 49ers" scored 0.15-0.21 by phrasing.
702 if item.source == "polymarket" and item.metadata.get("matched_market"):
703 return True
704 rel = item.local_relevance if item.local_relevance is not None else 0.0
705 if rel < minimum:
706 return False
707 # Key the stricter social gate on genuinely absent engagement (no
708 # counts at all), not on a rounded score: a handful of likes is still
709 # engagement even where the 0-100 scale rounds it low.
710 # A Reddit thread whose score is pending has unknown engagement, not
711 # absent engagement.
712 if (
713 item.source in _SOCIAL_SOURCES
714 and not engagement_raw(item)
715 and not reddit_refs.score_pending(item.metadata)
716 ):
717 if rel < minimum * 1.5:
718 return False
719 return True
720
721 rel_filtered = [item for item in items if passes_relevance(item)]
722 filtered = [
723 item for item in rel_filtered
724 if _is_first_party(item) or _passes_engagement_floor(item)
725 ]
726 if passing_only:
727 return filtered
728 return filtered or rel_filtered or items
729
729 lines PYTHON