from datetime import datetime, timezone import math def compute_freshness(ts, half_life_days=30): """ Exponential decay score between 0 and 1. - 1.0 -> now - 0.5 -> half_life_days old - Approaches 0 -> when docs get very old """ if not ts: return 0.5 if isinstance(ts, str): ts = ts.replace("Z", "+00:00") try: ts = datetime.fromisoformat(ts) except Exception: return 0.5 if ts.tzinfo is None: ts = ts.replace(tzinfo=timezone.utc) age_days = (datetime.now(timezone.utc) - ts).total_seconds() / 86400.0 lam = math.log(2) / max(float(half_life_days), 1.0) return math.exp(-lam * age_days)