返回 last30days-skill
signals.rs
根目录 / rust / crates / last30days-core / src / signals.rs
1 //! Reusable local scoring signals for pipeline stages.
2 //!
3 //! Mirrors `skills/last30days/scripts/lib/signals.py` and `dates.py:recency_score`.
4
5 use std::collections::BTreeMap;
6
7 use serde::{Deserialize, Serialize};
8
9 use crate::error::CoreError;
10 use crate::relevance::{self, PreparedQuery};
11
12 /// Freshness decay curve applied to item publication dates.
13 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
14 #[serde(rename_all = "snake_case")]
15 #[non_exhaustive]
16 pub enum FreshnessMode {
17 /// Full 0..100 recency decay (`int(score)`).
18 StrictRecent,
19 /// Compressed decay with a 40-point floor (`int(score * 0.6 + 40)`).
20 EvergreenOk,
21 /// Default balanced decay (`int(score * 0.8 + 10)`).
22 #[default]
23 BalancedRecent,
24 }
25
26 /// Whether an item's date represents a live repository snapshot rather than an event.
27 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
28 #[serde(rename_all = "snake_case")]
29 #[non_exhaustive]
30 pub enum DateKind {
31 /// Normal event or publication date.
32 #[default]
33 Event,
34 /// Snapshot date (e.g. a live GitHub repo card), ranked at freshness 50.
35 Snapshot,
36 }
37
38 /// Whether an item is exempt from lexical grounding checks.
39 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
40 #[serde(rename_all = "snake_case")]
41 #[non_exhaustive]
42 pub enum GroundingPolicy {
43 /// Standard lexical relevance scoring.
44 #[default]
45 Standard,
46 /// Exempt from low lexical overlap (minimum 0.8 relevance floor).
47 Exempt,
48 }
49
50 /// Whether a GitHub item is a pull request or a repository/issue record.
51 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
52 #[serde(rename_all = "snake_case")]
53 #[non_exhaustive]
54 pub enum GithubItemKind {
55 /// Issue, discussion, or non-PR record.
56 #[default]
57 Standard,
58 /// Pull request (`metadata.is_pr` is truthy).
59 PullRequest,
60 }
61
62 /// Minimal item projection needed to compute local scoring signals.
63 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
64 pub struct SignalItem {
65 /// Source platform identifier (e.g. `"reddit"`, `"youtube"`, `"github"`).
66 pub source: String,
67 /// Item title.
68 pub title: String,
69 /// Item body text.
70 pub body: String,
71 /// Item snippet text.
72 pub snippet: String,
73 /// Optional `YYYY-MM-DD` publication date.
74 pub published_at: Option<String>,
75 /// Event vs. snapshot date semantics.
76 #[serde(default)]
77 pub date_kind: DateKind,
78 /// Optional hashtags attached to the item (`TikTok` / Instagram).
79 #[serde(default)]
80 pub hashtags: Vec<String>,
81 /// Optional labels attached to the item (e.g. `"project-mode"`, `"velocity"`).
82 #[serde(default)]
83 pub labels: Vec<String>,
84 /// Grounding exemption policy.
85 #[serde(default)]
86 pub grounding: GroundingPolicy,
87 /// GitHub item kind for repo-snapshot detection.
88 #[serde(default)]
89 pub github_kind: GithubItemKind,
90 /// Numeric engagement counters (non-numeric or boolean values omitted by caller).
91 #[serde(default)]
92 pub engagement: BTreeMap<String, f64>,
93 /// Whether the original engagement map contained a `"stars"` key (even if null/0).
94 #[serde(default)]
95 pub has_stars_key: bool,
96 /// Raw numeric score of `metadata["top_comments"][0]["score"]` when present.
97 pub top_comment_score: Option<f64>,
98 }
99
100 /// Computed local scoring metadata for one item in [`annotate_stream`].
101 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102 pub struct AnnotatedSignal {
103 /// Original index of the item in the input slice.
104 pub index: usize,
105 /// Computed query-centric relevance in `[0.0, 1.0]`.
106 pub local_relevance: f64,
107 /// Computed freshness score in `0..=100`.
108 pub freshness: i32,
109 /// Absolute cross-stream engagement score in `0..=100`, or `None`.
110 pub engagement_score: Option<i32>,
111 /// Editorial source quality multiplier.
112 pub source_quality: f64,
113 /// Composite local ranking score used to sort the stream.
114 pub local_rank_score: f64,
115 }
116
117 const VIEW_ENGAGEMENT_LOG_FLOOR: f64 = 2.1;
118 const VIEW_ENGAGEMENT_LOG_REFERENCE: f64 = 11.5;
119
120 /// Returns the editorial signal-to-noise quality score for `source`.
121 pub fn source_quality(source: &str) -> f64 {
122 match source {
123 "arxiv" => 0.9,
124 "youtube" | "digg" | "techmeme" => 0.85,
125 "hackernews" | "amazon" => 0.8,
126 "devto" | "trustpilot" => 0.78,
127 "corpus" | "juejin" => 0.75,
128 "meta_ads" | "jobs" | "v2ex" => 0.72,
129 "xiaohongshu" => 0.7,
130 "x" => 0.68,
131 "bluesky" => 0.66,
132 "instagram" | "tiktok" => 0.58,
133 "news_rss" => 0.55,
134 "polymarket" => 0.5,
135 _ => 0.6,
136 }
137 }
138
139 /// Safe `ln(1 + x)` matching `signals.log1p_safe`.
140 #[inline]
141 pub fn log1p_safe(value: Option<f64>) -> f64 {
142 match value {
143 Some(v) if v.is_finite() && v > 0.0 => v.ln_1p(),
144 _ => 0.0,
145 }
146 }
147
148 fn is_no_engagement_score_source(source: &str) -> bool {
149 matches!(
150 source,
151 "jobs"
152 | "meta_ads"
153 | "grounding"
154 | "perplexity"
155 | "stocktwits"
156 | "telegram"
157 | "arxiv"
158 | "techmeme"
159 | "news_rss"
160 | "dripstack"
161 | "corpus"
162 )
163 }
164
165 fn is_view_engagement_source(source: &str) -> bool {
166 matches!(source, "youtube" | "tiktok" | "instagram")
167 }
168
169 fn engagement_log_reference(source: &str) -> Option<f64> {
170 match source {
171 "reddit" | "linkedin" | "linkedin_profile" => Some(7.6),
172 "hackernews" => Some(6.2),
173 "devto" => Some(3.0),
174 "youtube" | "tiktok" => Some(10.3),
175 "instagram" | "x" | "bluesky" | "truthsocial" | "threads" | "xiaohongshu" | "pinterest"
176 | "github" => Some(9.2),
177 "polymarket" => Some(15.2),
178 "digg" => Some(4.5),
179 "v2ex" => Some(5.0),
180 "juejin" => Some(3.3),
181 "trustpilot" | "amazon" => Some(11.5),
182 _ => None,
183 }
184 }
185
186 fn weighted_engagement(engagement: &BTreeMap<String, f64>, weights: &[(&str, f64)]) -> Option<f64> {
187 let mut any_positive = false;
188 let mut sum = 0.0;
189 for &(field, weight) in weights {
190 let val = log1p_safe(engagement.get(field).copied());
191 if val > 0.0 {
192 any_positive = true;
193 sum += val * weight;
194 }
195 }
196 any_positive.then_some(sum)
197 }
198
199 fn source_engagement_weights(source: &str) -> Option<&'static [(&'static str, f64)]> {
200 match source {
201 "x" | "threads" => Some(&[
202 ("likes", 0.55),
203 ("reposts", 0.25),
204 ("replies", 0.15),
205 ("quotes", 0.05),
206 ]),
207 "hackernews" => Some(&[("points", 0.55), ("comments", 0.45)]),
208 "devto" => Some(&[("reactions", 0.60), ("comments", 0.40)]),
209 "v2ex" => Some(&[("replies", 1.0)]),
210 "juejin" => Some(&[
211 ("likes", 0.40),
212 ("comments", 0.25),
213 ("saves", 0.15),
214 ("views", 0.20),
215 ]),
216 "bluesky" => Some(&[
217 ("likes", 0.40),
218 ("reposts", 0.30),
219 ("replies", 0.20),
220 ("quotes", 0.10),
221 ]),
222 "truthsocial" => Some(&[("likes", 0.45), ("reposts", 0.30), ("replies", 0.25)]),
223 "pinterest" => Some(&[("saves", 0.70), ("comments", 0.30)]),
224 "linkedin" => Some(&[("likes", 0.55), ("comments", 0.30), ("reposts", 0.15)]),
225 "linkedin_profile" => Some(&[("likes", 0.55), ("comments", 0.30), ("shares", 0.15)]),
226 "xiaohongshu" => Some(&[("likes", 0.50), ("favorites", 0.30), ("comments", 0.20)]),
227 "polymarket" => Some(&[("volume", 0.60), ("liquidity", 0.40)]),
228 "trustpilot" => Some(&[("reviews", 1.0)]),
229 "amazon" => Some(&[("ratings", 1.0)]),
230 "meta_ads" => Some(&[("variants", 1.0)]),
231 _ => None,
232 }
233 }
234
235 fn generic_engagement(engagement: &BTreeMap<String, f64>) -> Option<f64> {
236 if engagement.is_empty() {
237 return None;
238 }
239 let mut peak = 0.0_f64;
240 let mut sum = 0.0_f64;
241 let mut count = 0usize;
242 for &v in engagement.values() {
243 let logged = log1p_safe(Some(v));
244 if logged > 0.0 {
245 if logged > peak {
246 peak = logged;
247 }
248 sum += logged;
249 count += 1;
250 }
251 }
252 (count > 0).then_some(peak + 0.1 * (sum - peak))
253 }
254
255 /// Computes the raw source-specific log-weighted engagement score for `item`.
256 pub fn engagement_raw(item: &SignalItem) -> Option<f64> {
257 let top_comment = log1p_safe(item.top_comment_score);
258 match item.source.as_str() {
259 "reddit" => {
260 let score = log1p_safe(item.engagement.get("score").copied());
261 let comments = log1p_safe(item.engagement.get("num_comments").copied());
262 let ratio = item
263 .engagement
264 .get("upvote_ratio")
265 .copied()
266 .filter(|v| v.is_finite())
267 .unwrap_or(0.0);
268 if score == 0.0 && comments == 0.0 && ratio == 0.0 && top_comment == 0.0 {
269 return None;
270 }
271 Some(0.50 * score + 0.35 * comments + 0.05 * (ratio * 10.0) + 0.10 * top_comment)
272 }
273 "youtube" => {
274 let views = log1p_safe(item.engagement.get("views").copied());
275 let likes = log1p_safe(item.engagement.get("likes").copied());
276 let comments = log1p_safe(item.engagement.get("comments").copied());
277 if views == 0.0 && likes == 0.0 && comments == 0.0 && top_comment == 0.0 {
278 return None;
279 }
280 Some(0.45 * views + 0.32 * likes + 0.13 * comments + 0.10 * top_comment)
281 }
282 "tiktok" | "instagram" => {
283 let views = log1p_safe(item.engagement.get("views").copied());
284 let likes = log1p_safe(item.engagement.get("likes").copied());
285 let comments = log1p_safe(item.engagement.get("comments").copied());
286 if views == 0.0 && likes == 0.0 && comments == 0.0 && top_comment == 0.0 {
287 return None;
288 }
289 Some(0.45 * views + 0.27 * likes + 0.18 * comments + 0.10 * top_comment)
290 }
291 "digg" => {
292 if log1p_safe(item.engagement.get("digg_score").copied()) > 0.0 {
293 weighted_engagement(
294 &item.engagement,
295 &[
296 ("digg_score", 0.50),
297 ("postCount", 0.30),
298 ("uniqueAuthors", 0.20),
299 ],
300 )
301 } else {
302 weighted_engagement(
303 &item.engagement,
304 &[("postCount", 0.60), ("uniqueAuthors", 0.40)],
305 )
306 }
307 }
308 "github" => {
309 let is_velocity = item.labels.iter().any(|l| l == "velocity")
310 || item.engagement.contains_key("merged_prs")
311 || item.engagement.contains_key("total_prs");
312 if is_velocity {
313 weighted_engagement(
314 &item.engagement,
315 &[("merged_prs", 0.70), ("total_prs", 0.30)],
316 )
317 } else {
318 weighted_engagement(&item.engagement, &[("reactions", 0.60), ("comments", 0.40)])
319 }
320 }
321 other => source_engagement_weights(other).map_or_else(
322 || generic_engagement(&item.engagement),
323 |weights| weighted_engagement(&item.engagement, weights),
324 ),
325 }
326 }
327
328 /// Returns `true` when `item` is a GitHub repository snapshot card.
329 #[inline]
330 pub fn is_repo_snapshot(item: &SignalItem) -> bool {
331 item.source == "github"
332 && (item.has_stars_key || item.engagement.contains_key("stars"))
333 && item.github_kind != GithubItemKind::PullRequest
334 }
335
336 /// Computes the normalized cross-stream engagement score in `0..=100`, or `None`.
337 pub fn engagement_score(item: &SignalItem) -> Option<i32> {
338 if is_no_engagement_score_source(&item.source) || is_repo_snapshot(item) {
339 return None;
340 }
341 let reference = engagement_log_reference(&item.source)?;
342 let raw = engagement_raw(item)?;
343 let fraction = if is_view_engagement_source(&item.source) {
344 (raw - VIEW_ENGAGEMENT_LOG_FLOOR)
345 / (VIEW_ENGAGEMENT_LOG_REFERENCE - VIEW_ENGAGEMENT_LOG_FLOOR)
346 } else {
347 raw / reference
348 };
349 let clamped = (100.0 * fraction.clamp(0.0, 1.0)).round_ties_even();
350 Some(f64_to_i32_trunc(clamped))
351 }
352
353 #[inline]
354 #[expect(
355 clippy::as_conversions,
356 clippy::cast_possible_truncation,
357 reason = "values are clamped to [0.0, 100.0] before truncating to i32"
358 )]
359 fn f64_to_i32_trunc(value: f64) -> i32 {
360 value as i32
361 }
362
363 /// Parses a strict `YYYY-MM-DD` civil date into days since `1970-01-01`.
364 ///
365 /// Uses Howard Hinnant's Gregorian calendar algorithm and validates month/day
366 /// ranges including leap years.
367 ///
368 /// # Errors
369 ///
370 /// Returns [`CoreError::InvalidDate`] if `date_str` is not a valid `YYYY-MM-DD` date.
371 pub fn parse_ymd_days(date_str: &str) -> Result<i64, CoreError> {
372 let bytes = date_str.as_bytes();
373 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
374 return Err(CoreError::InvalidDate {
375 input: date_str.to_owned(),
376 });
377 }
378 if !bytes[0..4].iter().all(u8::is_ascii_digit)
379 || !bytes[5..7].iter().all(u8::is_ascii_digit)
380 || !bytes[8..10].iter().all(u8::is_ascii_digit)
381 {
382 return Err(CoreError::InvalidDate {
383 input: date_str.to_owned(),
384 });
385 }
386 let year: i64 = date_str[0..4].parse().map_err(|_| CoreError::InvalidDate {
387 input: date_str.to_owned(),
388 })?;
389 let month: u32 = date_str[5..7].parse().map_err(|_| CoreError::InvalidDate {
390 input: date_str.to_owned(),
391 })?;
392 let day: u32 = date_str[8..10]
393 .parse()
394 .map_err(|_| CoreError::InvalidDate {
395 input: date_str.to_owned(),
396 })?;
397 if year < 1 || !(1..=12).contains(&month) || day == 0 {
398 return Err(CoreError::InvalidDate {
399 input: date_str.to_owned(),
400 });
401 }
402 let is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
403 let max_day = match month {
404 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
405 4 | 6 | 9 | 11 => 30,
406 2 => {
407 if is_leap {
408 29
409 } else {
410 28
411 }
412 }
413 _ => unreachable!("month already validated to 1..=12"),
414 };
415 if day > max_day {
416 return Err(CoreError::InvalidDate {
417 input: date_str.to_owned(),
418 });
419 }
420 let m = i64::from(month);
421 let d = i64::from(day);
422 let y = year - i64::from(m <= 2);
423 let era = y.div_euclid(400);
424 let yoe = y - era * 400;
425 let mp = if m > 2 { m - 3 } else { m + 9 };
426 let doy = (153 * mp + 2) / 5 + d - 1;
427 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
428 Ok(era * 146_097 + doe - 719_468)
429 }
430
431 /// Calculates recency score (`0..=100`) relative to `reference_days`.
432 pub fn recency_score_from_days(
433 published_at: Option<&str>,
434 max_days: i64,
435 reference_days: i64,
436 ) -> i32 {
437 let Some(raw) = published_at else {
438 return 0;
439 };
440 let Ok(pub_days) = parse_ymd_days(raw) else {
441 return 0;
442 };
443 let age = reference_days - pub_days;
444 if age < 0 {
445 return 100;
446 }
447 if max_days <= 0 || age >= max_days {
448 return 0;
449 }
450 #[expect(
451 clippy::as_conversions,
452 clippy::cast_precision_loss,
453 reason = "age and max_days are small day counts"
454 )]
455 let fraction = 1.0 - (age as f64) / (max_days as f64);
456 f64_to_i32_trunc(100.0 * fraction)
457 }
458
459 /// Computes freshness score (`0..=100`) for `item`.
460 pub fn freshness_from_days(
461 item: &SignalItem,
462 mode: FreshnessMode,
463 reference_days: i64,
464 max_days: i64,
465 ) -> i32 {
466 if item.date_kind == DateKind::Snapshot {
467 return 50;
468 }
469 let score = f64::from(recency_score_from_days(
470 item.published_at.as_deref(),
471 max_days,
472 reference_days,
473 ));
474 match mode {
475 FreshnessMode::StrictRecent => f64_to_i32_trunc(score),
476 FreshnessMode::EvergreenOk => f64_to_i32_trunc((score * 0.6) + 40.0),
477 FreshnessMode::BalancedRecent => f64_to_i32_trunc((score * 0.8) + 10.0),
478 }
479 }
480
481 /// Computes local relevance for `item`, including `YouTube`, project-mode, and grounding-exempt floors.
482 pub fn local_relevance(item: &SignalItem, query: &PreparedQuery) -> f64 {
483 let mut combined =
484 String::with_capacity(item.title.len() + item.body.len() + item.snippet.len() + 2);
485 for part in [
486 item.title.as_str(),
487 item.body.as_str(),
488 item.snippet.as_str(),
489 ] {
490 if !part.is_empty() {
491 if !combined.is_empty() {
492 combined.push('\n');
493 }
494 combined.push_str(part);
495 }
496 }
497 let mut score = relevance::token_overlap_relevance(query, &combined, &item.hashtags);
498
499 if item.source == "youtube"
500 && item
501 .engagement
502 .get("views")
503 .copied()
504 .filter(|v| v.is_finite())
505 .unwrap_or(0.0)
506 > 100_000.0
507 {
508 score = score.max(0.3);
509 }
510 if item.labels.iter().any(|l| l == "project-mode") {
511 score = score.max(0.8);
512 }
513 if item.grounding == GroundingPolicy::Exempt {
514 score = score.max(0.8);
515 }
516 score
517 }
518
519 /// Annotates every item with local scoring signals and returns them stably sorted
520 /// descending by `local_rank_score`.
521 ///
522 /// # Errors
523 ///
524 /// Returns [`CoreError::InvalidDate`] if `reference_date` is not a valid `YYYY-MM-DD` date.
525 pub fn annotate_stream(
526 items: &[SignalItem],
527 ranking_query: &str,
528 freshness_mode: FreshnessMode,
529 reference_date: &str,
530 max_days: i64,
531 ) -> Result<Vec<AnnotatedSignal>, CoreError> {
532 let ref_days = parse_ymd_days(reference_date)?;
533 let prepared = PreparedQuery::new(ranking_query);
534 let mut out = Vec::with_capacity(items.len());
535
536 for (index, item) in items.iter().enumerate() {
537 let eng_score = engagement_score(item);
538 let rel = local_relevance(item, &prepared);
539 let fresh = freshness_from_days(item, freshness_mode, ref_days, max_days);
540 let src_qual = source_quality(&item.source);
541 let rank_score = 0.65 * rel
542 + 0.25 * (f64::from(fresh) / 100.0)
543 + 0.10 * (f64::from(eng_score.unwrap_or(0)) / 100.0);
544 out.push(AnnotatedSignal {
545 index,
546 local_relevance: rel,
547 freshness: fresh,
548 engagement_score: eng_score,
549 source_quality: src_qual,
550 local_rank_score: rank_score,
551 });
552 }
553
554 // Python's sorted(..., reverse=True) is stable: equal scores keep original order.
555 out.sort_by(|a, b| b.local_rank_score.total_cmp(&a.local_rank_score));
556 Ok(out)
557 }
558
558 lines RUST