| 1 | """Digg source for last30days. |
| 2 | |
| 3 | Shells out to ``digg-pp-cli`` (read-only, no auth required) to surface |
| 4 | clustered stories from Digg. Each cluster carries a published TLDR, |
| 5 | Digg's own engagement numbers, and a list of X posts that can be fetched |
| 6 | as inline quotes. |
| 7 | |
| 8 | Activation gate: this source is only available when ``digg-pp-cli`` is |
| 9 | on PATH. ``pipeline.available_sources`` checks ``shutil.which`` before |
| 10 | including ``digg`` in the source list. The functions below also detect |
| 11 | the missing-binary case as a defensive fallback. |
| 12 | |
| 13 | Primary path: ``digg-pp-cli search <topic> --since 30d --agent --limit N``, |
| 14 | which searches every Digg topic live and returns stories with a canonical |
| 15 | ``url``, a ``diggScore`` and a ``publishedAt`` date. A research run at |
| 16 | default or deep depth follows it with the same call sorted by Digg Score |
| 17 | and merges the two answers, so the biggest stories are in hand even when |
| 18 | Digg ranks them far down for relevance. |
| 19 | |
| 20 | digg-pp-cli 2026.10.x is still supported. Its ``search`` covers only the |
| 21 | sections it is told to (default ``ai``) and rejects flags it does not |
| 22 | know, so the call is chosen up front by ``cli_searches_all_topics`` and |
| 23 | those installs keep the ``--topic ai,tech`` call. Their answers carry no |
| 24 | ``url`` and take the older parsing path; see ``upgrade_note``. When the |
| 25 | help text cannot be read the same call is made, since both CLIs accept it, |
| 26 | but the answer is not treated as an older CLI's. |
| 27 | |
| 28 | Global trending: ``digg-pp-cli top --agent --limit N`` lists the current top |
| 29 | stories of every topic by Digg Score (``top_stories``). It has no topic to |
| 30 | search for, and it is skipped on digg-pp-cli 2026.10.x. |
| 31 | |
| 32 | Story sources: ``digg-pp-cli posts <story UUID> --agent --limit 40`` for the |
| 33 | prominent stories (``apply_bar``) with the highest Digg Scores in |
| 34 | default/deep depth (``fetch_story_sources``). |
| 35 | The first X posts of each answer become the story's inline quotes, and every |
| 36 | source URL is turned into a match key so an item from another source that is |
| 37 | one of the story's sources can be marked as confirmed by it |
| 38 | (``tag_confirmed_candidates``). Clusters from digg-pp-cli 2026.10.x have no |
| 39 | UUID and keep ``posts <clusterUrlId> --agent --by rank --limit M`` for quotes |
| 40 | alone. |
| 41 | """ |
| 42 | |
| 43 | from __future__ import annotations |
| 44 | |
| 45 | import json |
| 46 | import os |
| 47 | import re |
| 48 | import shutil |
| 49 | import threading |
| 50 | import time |
| 51 | from concurrent.futures import ThreadPoolExecutor |
| 52 | from datetime import datetime, timedelta, timezone |
| 53 | from typing import Any, Dict, List, NamedTuple, Optional, Tuple |
| 54 | from urllib.parse import urlparse |
| 55 | |
| 56 | from . import health, log, subproc |
| 57 | from .fusion import _normalize_url |
| 58 | from .relevance import LOW_SIGNAL_QUERY_TOKENS, STOPWORDS, token_overlap_relevance |
| 59 | |
| 60 | |
| 61 | CLI_BIN = "digg-pp-cli" |
| 62 | |
| 63 | # Sections searched on digg-pp-cli 2026.10.x, whose search defaults to ai |
| 64 | # alone. Newer CLIs search every topic when no section is named. |
| 65 | SECTIONS = "ai,tech" |
| 66 | |
| 67 | # Outcome note for a search answered by digg-pp-cli 2026.10.x. Kept under |
| 68 | # the 140-character outcome note limit in render. |
| 69 | UPGRADE_NOTE = ( |
| 70 | f"this {CLI_BIN} searches only Digg's AI and tech sections; " |
| 71 | "upgrade it to search every Digg topic with engagement scores" |
| 72 | ) |
| 73 | |
| 74 | # Key set on a search answer that came from the ai,tech call. |
| 75 | _LEGACY_ANSWER_KEY = "legacy_cli" |
| 76 | |
| 77 | # Per-depth knobs. |
| 78 | DEPTH_CONFIG = { |
| 79 | "quick": 8, |
| 80 | "default": 20, |
| 81 | "deep": 50, |
| 82 | } |
| 83 | |
| 84 | # Stories asked for by each of a research search's two calls, the most |
| 85 | # relevant and the highest-scored. Quick depth is absent: it keeps the one |
| 86 | # DEPTH_CONFIG-sized call. |
| 87 | RESEARCH_SEARCH_SIZES = { |
| 88 | "default": 50, |
| 89 | "deep": 100, |
| 90 | } |
| 91 | |
| 92 | # Longest lookback a search asks Digg for, in days. |
| 93 | SEARCH_WINDOW_DAYS = 30 |
| 94 | |
| 95 | # Key set on a search answer whose highest-scored call failed, holding why. |
| 96 | _SCORE_PASS_ERROR_KEY = "score_pass_error" |
| 97 | |
| 98 | # Room left for the failure reason in the outcome note, which render cuts at |
| 99 | # 140 characters. |
| 100 | _SCORE_PASS_REASON_MAX = 60 |
| 101 | |
| 102 | # How many stories, highest Digg Score first, get their sources fetched, per |
| 103 | # depth. Quick mode fetches none to keep latency low (stories already carry |
| 104 | # a TLDR). |
| 105 | ENRICH_CONFIG = { |
| 106 | "quick": 0, |
| 107 | "default": 8, |
| 108 | "deep": 12, |
| 109 | } |
| 110 | |
| 111 | # How many of those ``posts`` calls run at once. |
| 112 | SOURCES_CONCURRENCY = 4 |
| 113 | |
| 114 | # X posts pulled per enriched cluster. Matches the 5-comment cap used by |
| 115 | # Reddit/HN/YouTube/TikTok/GitHub enrichment. |
| 116 | POSTS_PER_CLUSTER = 5 |
| 117 | |
| 118 | # Sources asked for per story. All of them can confirm another item; the |
| 119 | # first POSTS_PER_CLUSTER quotable ones are shown under the story. |
| 120 | SOURCES_PER_STORY = 40 |
| 121 | |
| 122 | # Candidate.metadata key naming the Digg story an item is a source of. |
| 123 | CONFIRMED_BY_KEY = "digg_story" |
| 124 | |
| 125 | # Item metadata key holding a story's UUID. Only stories from the all-topic |
| 126 | # search carry it, so its presence is what tells them from older-CLI clusters. |
| 127 | STORY_ID_KEY = "clusterId" |
| 128 | |
| 129 | # A story is prominent when its title names the run topic and it is at least |
| 130 | # this big: Digg Score and number of sources. |
| 131 | PROMINENT_MIN_SCORE = 40 |
| 132 | PROMINENT_MIN_SOURCES = 5 |
| 133 | |
| 134 | # A topic subject of up to this many words is treated as a name, which a |
| 135 | # story must carry in full; a longer one is a description. |
| 136 | SUBJECT_NAME_MAX_WORDS = 2 |
| 137 | |
| 138 | # Words dropped from the front of a topic to reach its subject. The first set |
| 139 | # goes wherever it leads; the second only once a word before it was dropped, |
| 140 | # so "what happened to Twitter" loses three words while "Will Smith" and |
| 141 | # "New York" lose none. |
| 142 | _TOPIC_LEAD_WORDS = frozenset({ |
| 143 | "what", "what's", "whats", "who", "who's", "whos", "why", "when", "where", |
| 144 | "how", "which", "the", "a", "an", "latest", "recent", |
| 145 | }) |
| 146 | _TOPIC_FOLLOW_WORDS = frozenset({ |
| 147 | "is", "are", "was", "were", "do", "does", "did", "has", "have", "had", |
| 148 | "can", "could", "should", "would", "will", |
| 149 | "to", "of", "in", "on", "for", "with", "about", "at", "from", "by", "up", |
| 150 | "happened", "happening", "going", "new", "news", |
| 151 | }) |
| 152 | # Words dropped from the end of a topic ("OpenAI news"). |
| 153 | _TOPIC_TAIL_WORDS = frozenset({ |
| 154 | "news", "latest", "update", "updates", "today", "lately", "recently", "now", |
| 155 | }) |
| 156 | _TOPIC_SIDE_SPLIT = re.compile(r"\s+(?:vs\.?|versus)\s+", re.IGNORECASE) |
| 157 | _TOPIC_WORD_EDGE = "?!.,:;\"'()" |
| 158 | |
| 159 | # On digg-pp-cli 2026.10.x a stale section makes the CLI fetch up to 8 live |
| 160 | # feed pages per section before answering (about 8s for ai,tech), well |
| 161 | # inside this budget. |
| 162 | SEARCH_TIMEOUT = 30 |
| 163 | |
| 164 | # The highest-scored call adds to a search that already has its most |
| 165 | # relevant stories, so it gets less time before the run moves on without it. |
| 166 | SCORE_SEARCH_TIMEOUT = 15 |
| 167 | # Seconds before the run's deadline by which the highest-scored call must be |
| 168 | # over, leaving time to hand back the stories the first call found. |
| 169 | SCORE_SEARCH_MARGIN = 5 |
| 170 | # How long a score call that overran gets to exit, once after the request to |
| 171 | # stop and once more after the kill. Twice this must fit inside the margin, |
| 172 | # or stopping a stuck call would itself run past the run's deadline. |
| 173 | SCORE_SEARCH_CLEANUP_GRACE = 1.0 |
| 174 | POSTS_TIMEOUT = 10 |
| 175 | HELP_TIMEOUT = 10 |
| 176 | |
| 177 | # Longest the story-sources fetch may take in total when the run itself has |
| 178 | # no deadline. |
| 179 | SOURCES_TOTAL_SECONDS = 40 |
| 180 | |
| 181 | # Query length the all-topic search accepts, in characters. |
| 182 | QUERY_MIN_CHARS = 3 |
| 183 | QUERY_MAX_CHARS = 120 |
| 184 | |
| 185 | # Whether the installed CLI searches every topic. None until first checked; |
| 186 | # the answer holds for the rest of the process. |
| 187 | _all_topic_search: Optional[bool] = None |
| 188 | _all_topic_search_lock = threading.Lock() |
| 189 | |
| 190 | # Strict allowlist for upstream Digg cluster IDs (short slugs and UUIDs). |
| 191 | # Must start with an alphanumeric character so IDs can never be option-shaped |
| 192 | # or inject path segments / query strings into https://digg.com/ai/{id}. |
| 193 | _CLUSTER_ID_RE = re.compile(r"\A[A-Za-z0-9][A-Za-z0-9_-]{0,127}\Z") |
| 194 | _KNOWN_SEARCH_FLAGS = frozenset({"--topic", "--since", "--agent", "--limit", "--sort"}) |
| 195 | _UNKNOWN_FLAG_RE = re.compile(r"unknown flag:\s*(--[a-z0-9-]+)", re.IGNORECASE) |
| 196 | _URL_USERINFO_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]{0,15}://)[^\s/?#]+@") |
| 197 | |
| 198 | |
| 199 | def _scrub_url_userinfo(text: str) -> str: |
| 200 | return _URL_USERINFO_RE.sub(r"\1", text) if text else text |
| 201 | |
| 202 | # Keep only OS, cache/config-dir, locale, TLS, and proxy settings. |
| 203 | # Never inherit unrelated provider secrets or runtime-injection vars like NODE_OPTIONS. |
| 204 | _CHILD_ENV_ALLOWLIST = frozenset({ |
| 205 | "PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA", |
| 206 | "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", |
| 207 | "XDG_STATE_HOME", "SYSTEMROOT", "WINDIR", "SYSTEMDRIVE", "COMSPEC", |
| 208 | "PATHEXT", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "LC_CTYPE", |
| 209 | "TZ", "NO_COLOR", "TERM", "SSL_CERT_FILE", "SSL_CERT_DIR", |
| 210 | "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", |
| 211 | }) |
| 212 | |
| 213 | |
| 214 | def _child_env() -> Dict[str, str]: |
| 215 | """Allowlisted child environment for digg-pp-cli.""" |
| 216 | return { |
| 217 | name: value |
| 218 | for name, value in os.environ.items() |
| 219 | if name.upper() in _CHILD_ENV_ALLOWLIST or name.upper().startswith("LC_") |
| 220 | } |
| 221 | |
| 222 | |
| 223 | def _is_valid_cluster_id(value: Any) -> bool: |
| 224 | """True when ``value`` is a safe Digg cluster slug or UUID.""" |
| 225 | return isinstance(value, str) and bool(_CLUSTER_ID_RE.fullmatch(value)) |
| 226 | |
| 227 | |
| 228 | def _log(msg: str) -> None: |
| 229 | log.source_log("Digg", msg, tty_only=False) |
| 230 | |
| 231 | |
| 232 | def _is_available() -> bool: |
| 233 | """True when the digg-pp-cli binary is on PATH.""" |
| 234 | return shutil.which(CLI_BIN) is not None |
| 235 | |
| 236 | |
| 237 | def _today() -> datetime: |
| 238 | return datetime.now(timezone.utc) |
| 239 | |
| 240 | |
| 241 | def _parse_first_post_age(age: Optional[str], today: Optional[datetime] = None) -> Optional[str]: |
| 242 | """Convert a digg firstPostAge token (e.g. '5d', '17d', '5h', '1w', '1m') |
| 243 | into a YYYY-MM-DD string. Returns None when the value is outside the |
| 244 | last-30-day window or cannot be parsed. |
| 245 | |
| 246 | Digg uses minutes-symbol-collision for 'months' (per agent-context: |
| 247 | 'Nh, Nd, Nw, Nm (e.g. 30d, 1w, 12h, 1m)'), so 'Nm' is months ~30 days. |
| 248 | """ |
| 249 | if not age or not isinstance(age, str): |
| 250 | return None |
| 251 | age = age.strip().lower() |
| 252 | if len(age) < 2: |
| 253 | return None |
| 254 | unit = age[-1] |
| 255 | try: |
| 256 | amount = int(age[:-1]) |
| 257 | except (ValueError, TypeError): |
| 258 | return None |
| 259 | if amount < 0: |
| 260 | return None |
| 261 | |
| 262 | base = today or _today() |
| 263 | |
| 264 | if unit == "h": |
| 265 | delta = timedelta(hours=amount) |
| 266 | elif unit == "d": |
| 267 | delta = timedelta(days=amount) |
| 268 | elif unit == "w": |
| 269 | delta = timedelta(weeks=amount) |
| 270 | elif unit == "m": |
| 271 | delta = timedelta(days=amount * 30) |
| 272 | else: |
| 273 | return None |
| 274 | |
| 275 | if delta > timedelta(days=30): |
| 276 | return None |
| 277 | |
| 278 | point = base - delta |
| 279 | return point.date().isoformat() |
| 280 | |
| 281 | |
| 282 | def _published_date(published_at: Any) -> Optional[str]: |
| 283 | """Convert a ``publishedAt`` timestamp into a UTC YYYY-MM-DD string.""" |
| 284 | if not isinstance(published_at, str) or not published_at.strip(): |
| 285 | return None |
| 286 | try: |
| 287 | parsed = datetime.fromisoformat(published_at.strip().replace("Z", "+00:00")) |
| 288 | except ValueError: |
| 289 | return None |
| 290 | if parsed.tzinfo is not None: |
| 291 | parsed = parsed.astimezone(timezone.utc) |
| 292 | return parsed.date().isoformat() |
| 293 | |
| 294 | |
| 295 | def cli_searches_all_topics() -> Optional[bool]: |
| 296 | """Whether the installed CLI's ``search`` covers every Digg topic. |
| 297 | |
| 298 | True for the newer CLI, False for digg-pp-cli 2026.10.x, and None when |
| 299 | the help text could not be read, which says nothing about the version. |
| 300 | |
| 301 | digg-pp-cli 2026.10.x defaults ``--topic`` to ``ai`` and rejects unknown |
| 302 | flags, so the call has to be chosen before it is made. The all-topic |
| 303 | search shipped together with ``--sort``, so its presence in |
| 304 | ``search --help`` identifies the newer CLI. The help text is read once |
| 305 | per process; a help call that fails is not an answer and is retried on |
| 306 | the next search. |
| 307 | """ |
| 308 | global _all_topic_search |
| 309 | with _all_topic_search_lock: |
| 310 | if _all_topic_search is not None: |
| 311 | return _all_topic_search |
| 312 | try: |
| 313 | result = subproc.run_with_timeout( |
| 314 | [CLI_BIN, "search", "--help"], timeout=HELP_TIMEOUT, env=_child_env() |
| 315 | ) |
| 316 | except (subproc.SubprocTimeout, OSError) as exc: |
| 317 | _log(f"search --help failed: {_scrub_url_userinfo(str(exc))}") |
| 318 | return None |
| 319 | if result.returncode != 0: |
| 320 | _log(f"search --help exit {result.returncode}") |
| 321 | return None |
| 322 | _all_topic_search = "--sort" in (result.stdout or "") |
| 323 | return _all_topic_search |
| 324 | |
| 325 | |
| 326 | def _fit_query(query: str) -> str: |
| 327 | """Fit a query to the 3 to 120 characters the all-topic search accepts. |
| 328 | |
| 329 | The newer CLI rejects anything outside that range with a usage error |
| 330 | before it searches. A shorter query ("AI", "Go") is repeated until it is |
| 331 | long enough, which searches for the same term. A longer one is cut at |
| 332 | the last word that fits. |
| 333 | """ |
| 334 | query = " ".join(query.split()) |
| 335 | if not query: |
| 336 | return query |
| 337 | if len(query) > QUERY_MAX_CHARS: |
| 338 | cut = query[: QUERY_MAX_CHARS + 1] |
| 339 | query = (cut.rsplit(" ", 1)[0] if " " in cut else cut)[:QUERY_MAX_CHARS].rstrip() |
| 340 | # After the cut, so a short word left in front of one long token |
| 341 | # ("AI <long URL>" cut to "AI") is still made long enough. |
| 342 | while len(query) < QUERY_MIN_CHARS: |
| 343 | query = f"{query} {query}" |
| 344 | return query |
| 345 | |
| 346 | |
| 347 | def _build_search_args( |
| 348 | query: str, |
| 349 | limit: int, |
| 350 | *, |
| 351 | all_topics: bool, |
| 352 | since_days: int = SEARCH_WINDOW_DAYS, |
| 353 | by_score: bool = False, |
| 354 | ) -> List[str]: |
| 355 | """Build the search call. |
| 356 | |
| 357 | The all-topic call names no section, and no sort order unless |
| 358 | ``by_score`` asks for the highest Digg Scores first: the newer CLI |
| 359 | defaults to every topic in relevance order. Ranking does not depend on |
| 360 | that order, since the position-based hint ``parse_digg_response`` sets is |
| 361 | replaced by a locally computed relevance before anything reads it. The |
| 362 | query is fitted to the length that CLI accepts; the older CLI has no |
| 363 | such limit and gets the query as given. |
| 364 | """ |
| 365 | sections = [] if all_topics else ["--topic", SECTIONS] |
| 366 | if all_topics: |
| 367 | query = _fit_query(query) |
| 368 | return [ |
| 369 | CLI_BIN, |
| 370 | "search", |
| 371 | *sections, |
| 372 | "--since", |
| 373 | f"{since_days}d", |
| 374 | "--agent", |
| 375 | "--limit", |
| 376 | str(limit), |
| 377 | *(["--sort", "score"] if by_score else []), |
| 378 | "--", |
| 379 | query, |
| 380 | ] |
| 381 | |
| 382 | |
| 383 | def _lookback_days(from_date: str) -> int: |
| 384 | """Days Digg is asked for so its answer covers ``from_date`` through today. |
| 385 | |
| 386 | ``--since Nd`` counts back from now and ``from_date`` is a calendar day, |
| 387 | so one extra day is asked for to include the whole first day. Between 1 |
| 388 | and the usual 30. |
| 389 | """ |
| 390 | try: |
| 391 | start = datetime.strptime(from_date, "%Y-%m-%d").date() |
| 392 | except (TypeError, ValueError): |
| 393 | return SEARCH_WINDOW_DAYS |
| 394 | return max(1, min(SEARCH_WINDOW_DAYS, (_today().date() - start).days + 1)) |
| 395 | |
| 396 | |
| 397 | def _story_key(story: Dict[str, Any]) -> str: |
| 398 | """A story's UUID, or its short id when the answer carries no UUID.""" |
| 399 | return str(story.get(STORY_ID_KEY) or story.get("clusterUrlId") or "") |
| 400 | |
| 401 | |
| 402 | def _merge_search_results(relevance: List[Any], by_score: List[Any]) -> List[Any]: |
| 403 | """Relevance-call stories in their order, then the stories only the score |
| 404 | call found, highest Digg Score first and by id among equals.""" |
| 405 | seen = {_story_key(story) for story in relevance if isinstance(story, dict)} |
| 406 | extra: Dict[str, Dict[str, Any]] = {} |
| 407 | for story in by_score: |
| 408 | if not isinstance(story, dict): |
| 409 | continue |
| 410 | key = _story_key(story) |
| 411 | if key and key not in seen: |
| 412 | extra.setdefault(key, story) |
| 413 | |
| 414 | def order(key: str) -> Tuple[float, str]: |
| 415 | score = extra[key].get("diggScore") |
| 416 | if isinstance(score, bool) or not isinstance(score, (int, float)): |
| 417 | score = 0 |
| 418 | return (-score, key) |
| 419 | |
| 420 | return [*relevance, *(extra[key] for key in sorted(extra, key=order))] |
| 421 | |
| 422 | |
| 423 | def _build_posts_args(cluster_url_id: str, posts_per: int) -> List[str]: |
| 424 | if not _is_valid_cluster_id(cluster_url_id): |
| 425 | raise ValueError(f"invalid Digg cluster_url_id: {cluster_url_id!r}") |
| 426 | return [ |
| 427 | CLI_BIN, |
| 428 | "posts", |
| 429 | "--agent", |
| 430 | "--by", |
| 431 | "rank", |
| 432 | "--limit", |
| 433 | str(posts_per), |
| 434 | "--", |
| 435 | cluster_url_id, |
| 436 | ] |
| 437 | |
| 438 | |
| 439 | _LOCAL_FALLBACK_MARKER = "falling back to local FTS5:" |
| 440 | _FALLBACK_REASON_MAX = 200 |
| 441 | |
| 442 | |
| 443 | def _local_fallback_reason(stderr: str) -> str: |
| 444 | """Extract the live-search failure from digg-pp-cli's fallback stderr. |
| 445 | |
| 446 | The CLI prints ``falling back to local FTS5: <error>`` and the error can |
| 447 | embed the full HTML body of a failed response, so the reason is cut at |
| 448 | the HTTP status when present and length-bounded otherwise. |
| 449 | """ |
| 450 | for line in (stderr or "").splitlines(): |
| 451 | _, marker, rest = line.partition(_LOCAL_FALLBACK_MARKER) |
| 452 | if not marker: |
| 453 | continue |
| 454 | rest = rest.strip() |
| 455 | status = re.match(r".*?\bHTTP \d{3}\b", rest) |
| 456 | if status: |
| 457 | return status.group(0) |
| 458 | return rest[:_FALLBACK_REASON_MAX].rstrip() |
| 459 | return "" |
| 460 | |
| 461 | |
| 462 | def _empty_local_fallback_error(data: Dict[str, Any], stderr: str = "") -> Optional[str]: |
| 463 | """Return an error when the CLI answered from an empty local store. |
| 464 | |
| 465 | ``digg-pp-cli search`` is live by default, but it falls back to its FTS5 |
| 466 | store on a network error and exits 0 with ``meta.source == "local"``. |
| 467 | That store only holds rows for users who ran ``digg-pp-cli sync`` |
| 468 | themselves, which last30days never does - so a broken live search |
| 469 | reaches the user as ``Digg: 0 items (no results)`` instead of an error. |
| 470 | A non-empty local store is real data and is left alone. |
| 471 | |
| 472 | CLI builds from 2026.10.1 always send ``meta.stale`` and exit non-zero |
| 473 | themselves when they have no usable data, so an empty local answer from |
| 474 | them is a real "no matches" and is left alone too. |
| 475 | |
| 476 | The CLI reports the live failure only on stderr; ``meta.reason`` is |
| 477 | preferred if a future CLI release adds it to the envelope. |
| 478 | """ |
| 479 | meta = data.get("meta") |
| 480 | if not isinstance(meta, dict) or meta.get("source") != "local": |
| 481 | return None |
| 482 | if "stale" in meta: |
| 483 | return None |
| 484 | if data.get("results"): |
| 485 | return None |
| 486 | reason = str(meta.get("reason") or "").strip()[:_FALLBACK_REASON_MAX] |
| 487 | detail = ( |
| 488 | reason |
| 489 | or _local_fallback_reason(stderr) |
| 490 | or "live search fell back to an empty local store" |
| 491 | ) |
| 492 | return f"live-search-unavailable: {detail}" |
| 493 | |
| 494 | |
| 495 | def outdated_cli_error(error: Optional[str]) -> Optional[str]: |
| 496 | """Name an outdated helper and its upgrade when ``error`` is an unknown flag. |
| 497 | |
| 498 | A digg-pp-cli older than both search generations rejects the flags the |
| 499 | engine sends (``unknown flag: --topic``). The outcome note then says so |
| 500 | and carries the pinned install command, which replaces the old binary. |
| 501 | Kept under the 140-character outcome note limit in render. |
| 502 | """ |
| 503 | match = _UNKNOWN_FLAG_RE.search(error or "") |
| 504 | if not match or match.group(1).lower() not in _KNOWN_SEARCH_FLAGS: |
| 505 | return None |
| 506 | return f"{CLI_BIN} is outdated and rejected the search; upgrade: {health.helper_upgrade_cmd('digg')}" |
| 507 | |
| 508 | |
| 509 | def _invoke_cli( |
| 510 | cmd: List[str], |
| 511 | timeout: float, |
| 512 | deadline: Optional[float] = None, |
| 513 | cancel: Optional[threading.Event] = None, |
| 514 | cleanup_grace: Optional[float] = None, |
| 515 | ) -> Tuple[Dict[str, Any], str]: |
| 516 | """Invoke digg-pp-cli and return the parsed envelope with its stderr. |
| 517 | |
| 518 | The envelope is ``{"results": [...]}`` on success and |
| 519 | ``{"results": [], "error": "..."}`` on failure. Never raises; the |
| 520 | pipeline relies on shape consistency. ``deadline`` (monotonic) and |
| 521 | ``cancel`` end a running call early; both surface as a timeout error. |
| 522 | ``cleanup_grace`` shortens how long a call that overran is given to |
| 523 | exit, first after the request to stop and again after the kill. |
| 524 | """ |
| 525 | if not _is_available(): |
| 526 | return {"results": [], "error": f"{CLI_BIN} not on PATH"}, "" |
| 527 | bounds: Dict[str, Any] = {} |
| 528 | if deadline is not None: |
| 529 | bounds["deadline_monotonic"] = deadline |
| 530 | if cancel is not None: |
| 531 | bounds["cancel"] = cancel |
| 532 | if cleanup_grace is not None: |
| 533 | bounds["cleanup_grace"] = cleanup_grace |
| 534 | try: |
| 535 | result = subproc.run_with_timeout(cmd, timeout=timeout, env=_child_env(), **bounds) |
| 536 | except subproc.SubprocTimeout as exc: |
| 537 | msg = _scrub_url_userinfo(str(exc)) |
| 538 | _log(f"Timeout: {msg}") |
| 539 | return {"results": [], "error": msg}, "" |
| 540 | except FileNotFoundError as exc: |
| 541 | msg = _scrub_url_userinfo(str(exc)) |
| 542 | _log(f"Binary missing: {msg}") |
| 543 | return {"results": [], "error": msg}, "" |
| 544 | except OSError as exc: |
| 545 | msg = _scrub_url_userinfo(str(exc)) |
| 546 | _log(f"Spawn failed: {msg}") |
| 547 | return {"results": [], "error": msg}, "" |
| 548 | |
| 549 | stderr = _scrub_url_userinfo(result.stderr or "") |
| 550 | if result.returncode != 0: |
| 551 | snippet = stderr.strip().splitlines()[:1] |
| 552 | first = snippet[0] if snippet else f"exit {result.returncode}" |
| 553 | _log(f"CLI exit {result.returncode}: {first}") |
| 554 | return {"results": [], "error": first}, stderr |
| 555 | |
| 556 | stdout = result.stdout or "" |
| 557 | if not stdout.strip(): |
| 558 | return {"results": []}, stderr |
| 559 | try: |
| 560 | data = json.loads(stdout) |
| 561 | except json.JSONDecodeError as exc: |
| 562 | msg = _scrub_url_userinfo(str(exc)) |
| 563 | _log(f"JSON decode failed: {msg}") |
| 564 | return {"results": [], "error": f"json decode: {msg}"}, stderr |
| 565 | |
| 566 | if not isinstance(data, dict): |
| 567 | return {"results": []}, stderr |
| 568 | results = data.get("results") |
| 569 | if not isinstance(results, list): |
| 570 | return {"results": []}, stderr |
| 571 | return data, stderr |
| 572 | |
| 573 | |
| 574 | def _run_cli( |
| 575 | cmd: List[str], |
| 576 | timeout: float, |
| 577 | deadline: Optional[float] = None, |
| 578 | cancel: Optional[threading.Event] = None, |
| 579 | ) -> Dict[str, Any]: |
| 580 | """Invoke digg-pp-cli and return only the parsed envelope.""" |
| 581 | return _invoke_cli(cmd, timeout, deadline=deadline, cancel=cancel)[0] |
| 582 | |
| 583 | |
| 584 | def search_digg( |
| 585 | topic: str, |
| 586 | from_date: str, |
| 587 | to_date: str, |
| 588 | depth: str = "default", |
| 589 | *, |
| 590 | include_top_scored: bool = False, |
| 591 | deadline: Optional[float] = None, |
| 592 | cancel: Optional[threading.Event] = None, |
| 593 | ) -> Dict[str, Any]: |
| 594 | """Search Digg clusters via digg-pp-cli. |
| 595 | |
| 596 | Args: |
| 597 | topic: search query. |
| 598 | from_date: YYYY-MM-DD start. Advisory for a single-call search, where |
| 599 | --since 30d is the actual filter; a two-call search asks Digg |
| 600 | for the days since it when that is under 30. |
| 601 | to_date: YYYY-MM-DD end (advisory). |
| 602 | depth: 'quick' | 'default' | 'deep'. |
| 603 | include_top_scored: set by a research run. At default and deep depth |
| 604 | on a CLI that searches every topic, the search becomes two calls |
| 605 | of ``RESEARCH_SEARCH_SIZES`` stories each, the most relevant and |
| 606 | the highest-scored, merged with each story once. Anywhere else |
| 607 | it stays the single call. |
| 608 | deadline: the run's monotonic deadline, handed to every call. |
| 609 | cancel: the run's cancel signal, handed to every call. |
| 610 | |
| 611 | Returns: |
| 612 | Dict with ``results`` list. On failure, ``results`` is empty and an |
| 613 | ``error`` key carries a one-line description. An answer from the |
| 614 | ai,tech call of digg-pp-cli 2026.10.x is marked for ``upgrade_note``. |
| 615 | When the CLI's help could not be read the ai,tech call is still |
| 616 | made, but its answer is not marked. When only the highest-scored |
| 617 | call fails, the most relevant stories are returned without an |
| 618 | ``error`` and the answer is marked for ``score_pass_note``. |
| 619 | """ |
| 620 | limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 621 | if not topic or not topic.strip(): |
| 622 | return {"results": []} |
| 623 | if not _is_available(): |
| 624 | return {"results": [], "error": f"{CLI_BIN} not on PATH"} |
| 625 | capability = cli_searches_all_topics() |
| 626 | all_topics = capability is True |
| 627 | two_calls = include_top_scored and all_topics and depth != "quick" |
| 628 | since_days = SEARCH_WINDOW_DAYS |
| 629 | if two_calls: |
| 630 | limit = RESEARCH_SEARCH_SIZES.get(depth, RESEARCH_SEARCH_SIZES["default"]) |
| 631 | since_days = _lookback_days(from_date) |
| 632 | cmd = _build_search_args(topic, limit, all_topics=all_topics, since_days=since_days) |
| 633 | scope = "all topics" if all_topics else f"sections={SECTIONS}" |
| 634 | _log(f"search '{topic}' ({scope}, limit={limit}, since={since_days}d)") |
| 635 | response, stderr = _invoke_cli( |
| 636 | cmd, timeout=SEARCH_TIMEOUT, deadline=deadline, cancel=cancel |
| 637 | ) |
| 638 | outdated = outdated_cli_error(response.get("error")) |
| 639 | if outdated: |
| 640 | _log(outdated) |
| 641 | return {"results": [], "error": outdated} |
| 642 | fallback_error = _empty_local_fallback_error(response, stderr) |
| 643 | if fallback_error: |
| 644 | _log(fallback_error) |
| 645 | return {"results": [], "error": fallback_error} |
| 646 | n = len(response.get("results") or []) |
| 647 | _log(f"found {n} clusters") |
| 648 | if capability is False and not response.get("error"): |
| 649 | response[_LEGACY_ANSWER_KEY] = True |
| 650 | _log(UPGRADE_NOTE) |
| 651 | if two_calls and not response.get("error"): |
| 652 | _add_top_scored( |
| 653 | response, topic, limit, since_days, deadline=deadline, cancel=cancel |
| 654 | ) |
| 655 | return response |
| 656 | |
| 657 | |
| 658 | def _add_top_scored( |
| 659 | response: Dict[str, Any], |
| 660 | topic: str, |
| 661 | limit: int, |
| 662 | since_days: int, |
| 663 | *, |
| 664 | deadline: Optional[float], |
| 665 | cancel: Optional[threading.Event], |
| 666 | ) -> None: |
| 667 | """Merge the highest-scored stories for ``topic`` into ``response``. |
| 668 | |
| 669 | A stopped run makes no call, and neither does one with under |
| 670 | ``SCORE_SEARCH_MARGIN`` seconds left. A call that fails leaves the |
| 671 | stories already in ``response`` as they are and marks it for |
| 672 | ``score_pass_note``. |
| 673 | """ |
| 674 | if cancel is not None and cancel.is_set(): |
| 675 | return |
| 676 | timeout: float = SCORE_SEARCH_TIMEOUT |
| 677 | if deadline is not None: |
| 678 | # This call ends early enough for the stories already in hand to be |
| 679 | # returned before the run's deadline. A call that ran up to the |
| 680 | # deadline would have the whole search abandoned as timed out. |
| 681 | deadline = deadline - SCORE_SEARCH_MARGIN |
| 682 | timeout = min(timeout, deadline - time.monotonic()) |
| 683 | if timeout <= 0: |
| 684 | return |
| 685 | cmd = _build_search_args( |
| 686 | topic, limit, all_topics=True, since_days=since_days, by_score=True |
| 687 | ) |
| 688 | _log(f"search '{topic}' (all topics, by score, limit={limit}, since={since_days}d)") |
| 689 | scored, stderr = _invoke_cli( |
| 690 | cmd, timeout=timeout, deadline=deadline, cancel=cancel, |
| 691 | cleanup_grace=SCORE_SEARCH_CLEANUP_GRACE, |
| 692 | ) |
| 693 | error = scored.get("error") or _empty_local_fallback_error(scored, stderr) |
| 694 | if error: |
| 695 | _log(f"highest-scored search failed: {error}") |
| 696 | response[_SCORE_PASS_ERROR_KEY] = str(error) |
| 697 | return |
| 698 | relevant = response.get("results") or [] |
| 699 | merged = _merge_search_results(relevant, scored.get("results") or []) |
| 700 | _log(f"found {len(merged) - len(relevant)} more clusters by score") |
| 701 | response["results"] = merged |
| 702 | |
| 703 | |
| 704 | def top_stories(depth: str = "default") -> Dict[str, Any]: |
| 705 | """Read Digg's current top stories across every topic via digg-pp-cli. |
| 706 | |
| 707 | ``digg-pp-cli top --agent --limit N`` reads all Digg topics live and |
| 708 | merges them by descending Digg Score, over the CLI's default 24-hour |
| 709 | range. digg-pp-cli 2026.10.x answers ``top`` from a local store that |
| 710 | last30days never fills, with rows that carry no titles, so it is not |
| 711 | called there and the answer is empty. The same holds when the CLI's |
| 712 | help could not be read, since the version is then unknown. |
| 713 | |
| 714 | Returns: |
| 715 | Dict with ``results`` list. On failure, ``results`` is empty and an |
| 716 | ``error`` key carries a one-line description. |
| 717 | """ |
| 718 | limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 719 | if not _is_available(): |
| 720 | return {"results": [], "error": f"{CLI_BIN} not on PATH"} |
| 721 | capability = cli_searches_all_topics() |
| 722 | if capability is not True: |
| 723 | reason = ( |
| 724 | f"this {CLI_BIN} has no live all-topic top" |
| 725 | if capability is False |
| 726 | else f"could not read {CLI_BIN} search --help" |
| 727 | ) |
| 728 | _log(f"top stories skipped: {reason}") |
| 729 | return {"results": []} |
| 730 | _log(f"top stories (all topics, limit={limit})") |
| 731 | response = _run_cli([CLI_BIN, "top", "--agent", "--limit", str(limit)], timeout=SEARCH_TIMEOUT) |
| 732 | _log(f"found {len(response.get('results') or [])} top stories") |
| 733 | return response |
| 734 | |
| 735 | |
| 736 | def upgrade_note(response: Dict[str, Any]) -> Optional[str]: |
| 737 | """Describe a search answered by digg-pp-cli 2026.10.x, else None. |
| 738 | |
| 739 | That CLI searches only the AI and tech sections, from a local feed copy |
| 740 | that can be stale, and reports no engagement score. Upgrading fixes all |
| 741 | three, so this one note stands in for the older stale-copy note. |
| 742 | """ |
| 743 | if not isinstance(response, dict) or response.get(_LEGACY_ANSWER_KEY) is not True: |
| 744 | return None |
| 745 | return UPGRADE_NOTE |
| 746 | |
| 747 | |
| 748 | def score_pass_note(response: Any) -> Optional[str]: |
| 749 | """Describe a search whose highest-scored call failed, else None. |
| 750 | |
| 751 | The stories Digg ranks most relevant were still returned, so this is a |
| 752 | note on a working source, not a failure of it. |
| 753 | """ |
| 754 | if not isinstance(response, dict) or not response.get(_SCORE_PASS_ERROR_KEY): |
| 755 | return None |
| 756 | reason = " ".join(str(response[_SCORE_PASS_ERROR_KEY]).split())[:_SCORE_PASS_REASON_MAX] |
| 757 | return f"highest-scored story search failed, biggest stories may be missing: {reason}" |
| 758 | |
| 759 | |
| 760 | def is_upgrade_note(detail: Optional[str]) -> bool: |
| 761 | """True when an outcome detail carries the upgrade note.""" |
| 762 | return bool(detail) and UPGRADE_NOTE in detail |
| 763 | |
| 764 | |
| 765 | def _build_url(cluster_url_id: str) -> str: |
| 766 | if not _is_valid_cluster_id(cluster_url_id): |
| 767 | raise ValueError(f"invalid Digg cluster_url_id: {cluster_url_id!r}") |
| 768 | return f"https://digg.com/ai/{cluster_url_id}" |
| 769 | |
| 770 | |
| 771 | def _rank_score(rank: Optional[int]) -> float: |
| 772 | """Convert Digg rank (lower is better, top 50 are notable) into a |
| 773 | positive engagement-style signal in [0, 50]. Anything off the top-50 |
| 774 | leaderboard contributes 0. |
| 775 | """ |
| 776 | if rank is None: |
| 777 | return 0.0 |
| 778 | try: |
| 779 | r = int(rank) |
| 780 | except (TypeError, ValueError): |
| 781 | return 0.0 |
| 782 | if r < 1 or r > 50: |
| 783 | return 0.0 |
| 784 | return float(51 - r) |
| 785 | |
| 786 | |
| 787 | def _position_relevance(position: int, query: str, text: str, rank_boost: float = 0.0) -> float: |
| 788 | """Relevance hint from result position, query overlap and a rank boost.""" |
| 789 | rank_decay = max(0.3, 1.0 - (position * 0.02)) |
| 790 | content_score = token_overlap_relevance(query, text.strip()) if query else 0.5 |
| 791 | return round(min(1.0, 0.55 * rank_decay + 0.35 * content_score + rank_boost), 2) |
| 792 | |
| 793 | |
| 794 | def _count(value: Any) -> int: |
| 795 | return int(value) if isinstance(value, (int, float)) else 0 |
| 796 | |
| 797 | |
| 798 | def _parse_story( |
| 799 | story: Dict[str, Any], |
| 800 | position: int, |
| 801 | query: str, |
| 802 | from_date: str, |
| 803 | ) -> Optional[Dict[str, Any]]: |
| 804 | """Parse one result of the all-topic search, which carries its own URL. |
| 805 | |
| 806 | Returns None for a story published before ``from_date`` or whose URL is |
| 807 | not a web link. |
| 808 | """ |
| 809 | cluster_url_id = str(story.get("clusterUrlId") or "").strip() |
| 810 | if not _is_valid_cluster_id(cluster_url_id): |
| 811 | _log(f"dropped story with invalid clusterUrlId: {cluster_url_id!r}") |
| 812 | return None |
| 813 | raw_cluster_id = str(story.get("clusterId") or "").strip() |
| 814 | if raw_cluster_id and not _is_valid_cluster_id(raw_cluster_id): |
| 815 | _log(f"dropped invalid clusterId: {raw_cluster_id!r}") |
| 816 | cluster_id = "" |
| 817 | else: |
| 818 | cluster_id = raw_cluster_id |
| 819 | url = str(story.get("url") or "").strip() |
| 820 | if not _is_safe_http_url(url): |
| 821 | # The URL is rendered into a link in the report, so a non-web |
| 822 | # scheme from upstream is dropped the same way an unsafe xUrl is. |
| 823 | _log(f"dropped story with unsafe url scheme: {url!r}") |
| 824 | return None |
| 825 | date_str = _published_date(story.get("publishedAt")) |
| 826 | if date_str is not None and date_str < from_date: |
| 827 | return None |
| 828 | |
| 829 | title = str(story.get("title") or "").strip() |
| 830 | tldr = str(story.get("tldr") or "").strip() |
| 831 | source_count = story.get("sourceCount") |
| 832 | if source_count is None: |
| 833 | source_count = story.get("postCount") |
| 834 | post_count = _count(source_count) |
| 835 | unique_authors = _count(story.get("uniqueAuthors")) |
| 836 | engagement: Dict[str, Any] = { |
| 837 | "postCount": post_count, |
| 838 | "uniqueAuthors": unique_authors, |
| 839 | } |
| 840 | counts = f"{post_count} posts, {unique_authors} authors" |
| 841 | digg_score = story.get("diggScore") |
| 842 | if isinstance(digg_score, (int, float)) and not isinstance(digg_score, bool): |
| 843 | engagement["digg_score"] = digg_score |
| 844 | counts = f"Digg Score {digg_score:g}, {counts}" |
| 845 | |
| 846 | return { |
| 847 | "id": cluster_url_id, |
| 848 | "cluster_id": cluster_id, |
| 849 | "topic": str(story.get("topic") or ""), |
| 850 | "title": title or f"Digg cluster {position + 1}", |
| 851 | "url": url, |
| 852 | "tldr": tldr, |
| 853 | "author": "", |
| 854 | "date": date_str, |
| 855 | "engagement": engagement, |
| 856 | "first_post_age": story.get("firstPostAge"), |
| 857 | "posts": [], |
| 858 | "relevance": _position_relevance(position, query, f"{title} {tldr}"), |
| 859 | "why_relevant": f"Digg cluster ({counts})", |
| 860 | } |
| 861 | |
| 862 | |
| 863 | def parse_digg_response( |
| 864 | response: Dict[str, Any], |
| 865 | query: str = "", |
| 866 | from_date: Optional[str] = None, |
| 867 | ) -> List[Dict[str, Any]]: |
| 868 | """Parse a digg search envelope into normalized item dicts. |
| 869 | |
| 870 | A result carrying ``url`` comes from the all-topic search: its link, |
| 871 | date and engagement are read from the story itself. Any other result |
| 872 | is a digg-pp-cli 2026.10.x cluster and keeps the older path, with a |
| 873 | ``digg.com/ai`` link and a date derived from ``firstPostAge``. |
| 874 | |
| 875 | Args: |
| 876 | response: payload from ``search_digg``. |
| 877 | query: original search query, used for token-overlap relevance. |
| 878 | from_date: YYYY-MM-DD start of the research window. Stories with a |
| 879 | ``publishedAt`` before it are dropped. Defaults to 30 days ago. |
| 880 | |
| 881 | Returns: |
| 882 | List of dicts ready for ``normalize._normalize_digg``. |
| 883 | """ |
| 884 | raw = response.get("results") if isinstance(response, dict) else None |
| 885 | if not isinstance(raw, list): |
| 886 | return [] |
| 887 | window_start = from_date or (_today() - timedelta(days=30)).date().isoformat() |
| 888 | |
| 889 | items: List[Dict[str, Any]] = [] |
| 890 | for i, cluster in enumerate(raw): |
| 891 | if not isinstance(cluster, dict): |
| 892 | continue |
| 893 | raw_cluster_url_id = cluster.get("clusterUrlId") |
| 894 | if not raw_cluster_url_id: |
| 895 | continue |
| 896 | cluster_url_id = str(raw_cluster_url_id).strip() |
| 897 | if not _is_valid_cluster_id(cluster_url_id): |
| 898 | _log(f"dropped cluster with invalid clusterUrlId: {raw_cluster_url_id!r}") |
| 899 | continue |
| 900 | if cluster.get("url"): |
| 901 | story = _parse_story(cluster, i, query, window_start) |
| 902 | if story is not None: |
| 903 | items.append(story) |
| 904 | continue |
| 905 | |
| 906 | title = str(cluster.get("title") or "").strip() |
| 907 | tldr = str(cluster.get("tldr") or "").strip() |
| 908 | rank = cluster.get("rank") |
| 909 | post_count = cluster.get("postCount") or 0 |
| 910 | unique_authors = cluster.get("uniqueAuthors") or 0 |
| 911 | first_post_age = cluster.get("firstPostAge") |
| 912 | date_str = _parse_first_post_age(first_post_age) |
| 913 | if date_str is None and first_post_age: |
| 914 | # firstPostAge present but outside 30d -> drop; last30days contract. |
| 915 | continue |
| 916 | |
| 917 | rank_boost = min(0.2, _rank_score(rank) / 250.0) |
| 918 | relevance = _position_relevance(i, query, f"{title} {tldr}", rank_boost) |
| 919 | |
| 920 | items.append( |
| 921 | { |
| 922 | "id": cluster_url_id, |
| 923 | "title": title or f"Digg cluster {i + 1}", |
| 924 | "url": _build_url(cluster_url_id), |
| 925 | "tldr": tldr, |
| 926 | "author": "", |
| 927 | "date": date_str, |
| 928 | "engagement": { |
| 929 | "postCount": int(post_count) if isinstance(post_count, (int, float)) else 0, |
| 930 | "uniqueAuthors": int(unique_authors) if isinstance(unique_authors, (int, float)) else 0, |
| 931 | "rank": int(rank) if isinstance(rank, (int, float)) else None, |
| 932 | "rank_score": _rank_score(rank), |
| 933 | }, |
| 934 | "first_post_age": first_post_age, |
| 935 | "posts": [], |
| 936 | "relevance": relevance, |
| 937 | "why_relevant": ( |
| 938 | f"Digg cluster (rank {rank}, {post_count} posts, {unique_authors} authors)" |
| 939 | if rank is not None |
| 940 | else f"Digg cluster ({post_count} posts, {unique_authors} authors)" |
| 941 | ), |
| 942 | } |
| 943 | ) |
| 944 | |
| 945 | return items |
| 946 | |
| 947 | |
| 948 | def parse_top_response( |
| 949 | response: Dict[str, Any], |
| 950 | from_date: Optional[str] = None, |
| 951 | ) -> List[Dict[str, Any]]: |
| 952 | """Parse a ``top_stories`` envelope into normalized item dicts. |
| 953 | |
| 954 | Top rows have the fields of an all-topic search story, so they take the |
| 955 | same path and come out with the same link, date and engagement keys. A |
| 956 | row without a title or a ``url`` is not a story a reader can act on and |
| 957 | is dropped. |
| 958 | """ |
| 959 | raw = response.get("results") if isinstance(response, dict) else None |
| 960 | if not isinstance(raw, list): |
| 961 | return [] |
| 962 | stories = [ |
| 963 | row |
| 964 | for row in raw |
| 965 | if isinstance(row, dict) and row.get("url") and str(row.get("title") or "").strip() |
| 966 | ] |
| 967 | return parse_digg_response({"results": stories}, from_date=from_date) |
| 968 | |
| 969 | |
| 970 | def _is_safe_http_url(url: str) -> bool: |
| 971 | """True iff ``url`` parses with an http or https scheme. |
| 972 | |
| 973 | Used to reject upstream-supplied post URLs whose scheme would be |
| 974 | dangerous in a rendered ``<a href>`` (``javascript:``, ``data:``, |
| 975 | ``file:``, ``vbscript:``, ``about:``). |
| 976 | """ |
| 977 | try: |
| 978 | scheme = urlparse(url).scheme.lower() |
| 979 | except ValueError: |
| 980 | return False |
| 981 | return scheme in ("http", "https") |
| 982 | |
| 983 | |
| 984 | def _parse_post(raw_post: Dict[str, Any]) -> Optional[Dict[str, Any]]: |
| 985 | """Reduce a digg post payload into the small dict render uses. |
| 986 | |
| 987 | We deliberately keep this minimal: an inline quote needs the author |
| 988 | handle, the body, the post type, and the X URL. |
| 989 | """ |
| 990 | if not isinstance(raw_post, dict): |
| 991 | return None |
| 992 | body = str(raw_post.get("body") or "").strip() |
| 993 | if not body: |
| 994 | return None |
| 995 | author = raw_post.get("author") or {} |
| 996 | if not isinstance(author, dict): |
| 997 | author = {} |
| 998 | username = str(author.get("username") or "").strip() |
| 999 | if not username: |
| 1000 | return None |
| 1001 | x_url = str(raw_post.get("xUrl") or "").strip() |
| 1002 | if not x_url: |
| 1003 | return None |
| 1004 | if not _is_safe_http_url(x_url): |
| 1005 | # Security-class drop: an upstream-supplied URL with a dangerous |
| 1006 | # scheme. Force tty_only=False so the rejection is visible in |
| 1007 | # non-interactive runs (Claude Code), which is the actual attack |
| 1008 | # surface — the default tty_only=True would suppress it there. |
| 1009 | log.source_log( |
| 1010 | "Digg", |
| 1011 | f"dropped post with unsafe xUrl scheme: {x_url!r}", |
| 1012 | tty_only=False, |
| 1013 | ) |
| 1014 | return None |
| 1015 | return { |
| 1016 | "username": username, |
| 1017 | "display_name": str(author.get("display_name") or "").strip() or username, |
| 1018 | "category": str(author.get("category") or "").strip(), |
| 1019 | "rank": author.get("rank"), |
| 1020 | "body": body, |
| 1021 | "post_type": str(raw_post.get("post_type") or "tweet").strip(), |
| 1022 | "x_url": x_url, |
| 1023 | "posted_at": raw_post.get("posted_at"), |
| 1024 | } |
| 1025 | |
| 1026 | |
| 1027 | def fetch_top_posts( |
| 1028 | cluster_url_id: str, |
| 1029 | posts_per: int = POSTS_PER_CLUSTER, |
| 1030 | *, |
| 1031 | deadline: Optional[float] = None, |
| 1032 | cancel: Optional[threading.Event] = None, |
| 1033 | ) -> List[Dict[str, Any]]: |
| 1034 | """Fetch top-ranked X posts attached to a cluster. |
| 1035 | |
| 1036 | Returns an empty list on any failure (timeout, missing cluster, JSON |
| 1037 | error). Never raises. |
| 1038 | """ |
| 1039 | if posts_per <= 0: |
| 1040 | return [] |
| 1041 | if cancel is not None and cancel.is_set(): |
| 1042 | return [] |
| 1043 | timeout: float = POSTS_TIMEOUT |
| 1044 | if deadline is not None: |
| 1045 | remaining = deadline - time.monotonic() |
| 1046 | if remaining <= 0: |
| 1047 | return [] |
| 1048 | timeout = min(timeout, remaining) |
| 1049 | cleaned_id = str(cluster_url_id or "").strip() |
| 1050 | if not _is_valid_cluster_id(cleaned_id): |
| 1051 | _log(f"skipping posts fetch for invalid cluster_url_id: {cluster_url_id!r}") |
| 1052 | return [] |
| 1053 | cmd = _build_posts_args(cleaned_id, posts_per) |
| 1054 | response = _run_cli(cmd, timeout=timeout, deadline=deadline, cancel=cancel) |
| 1055 | raw = response.get("results") or [] |
| 1056 | out: List[Dict[str, Any]] = [] |
| 1057 | for entry in raw: |
| 1058 | post = _parse_post(entry) |
| 1059 | if post is not None: |
| 1060 | out.append(post) |
| 1061 | return out |
| 1062 | |
| 1063 | |
| 1064 | def enrich_with_top_posts( |
| 1065 | items: List[Dict[str, Any]], |
| 1066 | top_k: int = 3, |
| 1067 | posts_per: int = POSTS_PER_CLUSTER, |
| 1068 | ) -> List[Dict[str, Any]]: |
| 1069 | """Attach top X posts to the first ``top_k`` clusters by Digg rank order. |
| 1070 | |
| 1071 | Mutates and returns the same list. Items that already have posts, or |
| 1072 | whose ``postCount`` is 0, are skipped. |
| 1073 | """ |
| 1074 | if top_k <= 0 or posts_per <= 0: |
| 1075 | return items |
| 1076 | enriched = 0 |
| 1077 | for item in items: |
| 1078 | if enriched >= top_k: |
| 1079 | break |
| 1080 | if item.get("posts"): |
| 1081 | continue |
| 1082 | engagement = item.get("engagement") or {} |
| 1083 | if not engagement.get("postCount"): |
| 1084 | continue |
| 1085 | cluster_url_id = item.get("id") |
| 1086 | if not cluster_url_id: |
| 1087 | continue |
| 1088 | posts = fetch_top_posts(str(cluster_url_id), posts_per=posts_per) |
| 1089 | item["posts"] = posts |
| 1090 | enriched += 1 |
| 1091 | if enriched: |
| 1092 | _log(f"enriched {enriched} clusters with X posts") |
| 1093 | return items |
| 1094 | |
| 1095 | |
| 1096 | def enrich_source_items( |
| 1097 | items: list, |
| 1098 | top_k: int = 3, |
| 1099 | posts_per: int = POSTS_PER_CLUSTER, |
| 1100 | *, |
| 1101 | deadline: Optional[float] = None, |
| 1102 | cancel: Optional[threading.Event] = None, |
| 1103 | ) -> list: |
| 1104 | """Attach top X posts to the first ``top_k`` SourceItems that survived dedupe. |
| 1105 | |
| 1106 | Reads ``metadata['clusterUrlId']`` and writes ``metadata['posts']`` in |
| 1107 | place. Skips items that already carry a non-empty ``metadata['posts']``, |
| 1108 | items whose engagement ``postCount`` is 0, items whose source is not |
| 1109 | 'digg', and stories from the all-topic search. Designed to run from |
| 1110 | `_finalize_items_by_source` so enrichment is spent on the items the brief |
| 1111 | actually shows. |
| 1112 | """ |
| 1113 | if top_k <= 0 or posts_per <= 0: |
| 1114 | return items |
| 1115 | enriched = 0 |
| 1116 | for item in items: |
| 1117 | if enriched >= top_k: |
| 1118 | break |
| 1119 | if cancel is not None and cancel.is_set(): |
| 1120 | break |
| 1121 | if deadline is not None and time.monotonic() >= deadline: |
| 1122 | break |
| 1123 | if getattr(item, "source", None) != "digg": |
| 1124 | continue |
| 1125 | metadata = getattr(item, "metadata", None) or {} |
| 1126 | if metadata.get(STORY_ID_KEY): |
| 1127 | # A story from the all-topic search: fetch_story_sources owns its |
| 1128 | # sources, under that fetch's own per-run budget. |
| 1129 | continue |
| 1130 | if metadata.get("posts"): |
| 1131 | continue |
| 1132 | engagement = getattr(item, "engagement", None) or {} |
| 1133 | if not engagement.get("postCount"): |
| 1134 | continue |
| 1135 | cluster_url_id = metadata.get("clusterUrlId") or item.item_id |
| 1136 | if not cluster_url_id: |
| 1137 | continue |
| 1138 | if deadline is not None or cancel is not None: |
| 1139 | posts = fetch_top_posts( |
| 1140 | str(cluster_url_id), posts_per=posts_per, deadline=deadline, cancel=cancel, |
| 1141 | ) |
| 1142 | else: |
| 1143 | posts = fetch_top_posts(str(cluster_url_id), posts_per=posts_per) |
| 1144 | if posts: |
| 1145 | metadata["posts"] = posts |
| 1146 | enriched += 1 |
| 1147 | if enriched: |
| 1148 | _log(f"post-dedupe enriched {enriched} clusters with X posts") |
| 1149 | return items |
| 1150 | |
| 1151 | |
| 1152 | _X_HOSTS = ("x.com", "twitter.com") |
| 1153 | _X_STATUS_PATH = re.compile(r"/status(?:es)?/(\d+)") |
| 1154 | |
| 1155 | |
| 1156 | def match_key(url: Any) -> Optional[str]: |
| 1157 | """Key under which a story source and another item count as the same thing. |
| 1158 | |
| 1159 | An X post keys on its numeric status id, so ``twitter.com`` and ``x.com``, |
| 1160 | handle case, share parameters and the ``x.com/i/status/<id>`` form all |
| 1161 | agree. Every other web URL keys on fusion's normalized URL. Matching is |
| 1162 | exact: a wrong confirmation is worse than a missed one. |
| 1163 | """ |
| 1164 | if not isinstance(url, str) or not _is_safe_http_url(url.strip()): |
| 1165 | return None |
| 1166 | url = url.strip() |
| 1167 | host = urlparse(url).netloc.lower() |
| 1168 | for prefix in ("www.", "mobile.", "m."): |
| 1169 | if host.startswith(prefix): |
| 1170 | host = host[len(prefix):] |
| 1171 | if host in _X_HOSTS: |
| 1172 | status = _X_STATUS_PATH.search(urlparse(url).path) |
| 1173 | if status: |
| 1174 | return f"x-status:{status.group(1)}" |
| 1175 | return _normalize_url(url) |
| 1176 | |
| 1177 | |
| 1178 | def _build_sources_args(cluster_id: str) -> List[str]: |
| 1179 | if not _is_valid_cluster_id(cluster_id): |
| 1180 | raise ValueError(f"invalid Digg cluster_id: {cluster_id!r}") |
| 1181 | return [CLI_BIN, "posts", "--agent", "--limit", str(SOURCES_PER_STORY), "--", cluster_id] |
| 1182 | |
| 1183 | |
| 1184 | def _digg_score(item: Any) -> Optional[float]: |
| 1185 | score = (getattr(item, "engagement", None) or {}).get("digg_score") |
| 1186 | if isinstance(score, (int, float)) and not isinstance(score, bool): |
| 1187 | return float(score) |
| 1188 | return None |
| 1189 | |
| 1190 | |
| 1191 | def story_budget(depth: str, entity_count: int = 1) -> int: |
| 1192 | """How many stories one run fetches sources for. |
| 1193 | |
| 1194 | None at quick depth, 8 at default and 12 at deep. A comparison runs the |
| 1195 | pipeline once per entity, so each of its runs takes that budget divided |
| 1196 | by the entity count, rounded up, and keeps at least one story. |
| 1197 | """ |
| 1198 | total = ENRICH_CONFIG.get(depth, ENRICH_CONFIG["default"]) |
| 1199 | if total <= 0 or entity_count <= 1: |
| 1200 | return total |
| 1201 | return max(1, -(-total // entity_count)) |
| 1202 | |
| 1203 | |
| 1204 | def fetch_story_sources( |
| 1205 | items: list, |
| 1206 | depth: str = "default", |
| 1207 | stopped: Any = None, |
| 1208 | *, |
| 1209 | deadline: Optional[float] = None, |
| 1210 | cancel: Optional[threading.Event] = None, |
| 1211 | entity_count: int = 1, |
| 1212 | budget: Optional[int] = None, |
| 1213 | ) -> Dict[str, Dict[str, Any]]: |
| 1214 | """Fetch the sources of the top stories by Digg Score, a few at a time. |
| 1215 | |
| 1216 | Covers ``story_budget`` stories, so a run makes at most that many |
| 1217 | ``posts`` calls, ``SOURCES_CONCURRENCY`` of them at once; ``budget`` |
| 1218 | lowers that for a later pass that spends what an earlier one left. Only |
| 1219 | stories from the all-topic search qualify: they carry the UUID the call |
| 1220 | takes and a Digg Score. The caller decides which of them to offer. |
| 1221 | |
| 1222 | ``stopped`` is asked before each call, and a call it answers true for |
| 1223 | is not made. ``deadline`` is the run's monotonic deadline and ``cancel`` |
| 1224 | its cancel signal: both reach every call, a call's timeout is capped at |
| 1225 | the time left, and no call starts once none is left or the signal is |
| 1226 | set. A run without a deadline gets ``SOURCES_TOTAL_SECONDS`` for the |
| 1227 | whole fetch. Every call has ended by the time this returns. |
| 1228 | |
| 1229 | Returns ``{story UUID: {"posts": [...], "source_urls": [...]}}`` in |
| 1230 | order of Digg Score, highest first, then story UUID, whatever order the |
| 1231 | calls finished in: ``posts`` holds the first ``POSTS_PER_CLUSTER`` |
| 1232 | quotable X posts and ``source_urls`` every source's web URL. A story |
| 1233 | whose call fails or returns nothing usable is left out. Never raises. |
| 1234 | """ |
| 1235 | full_budget = story_budget(depth, entity_count) |
| 1236 | budget = full_budget if budget is None else min(budget, full_budget) |
| 1237 | if budget <= 0: |
| 1238 | return {} |
| 1239 | fetch_deadline = ( |
| 1240 | deadline if deadline is not None else time.monotonic() + SOURCES_TOTAL_SECONDS |
| 1241 | ) |
| 1242 | scored: Dict[str, float] = {} |
| 1243 | for item in items: |
| 1244 | if getattr(item, "source", None) != "digg": |
| 1245 | continue |
| 1246 | cluster_id = (getattr(item, "metadata", None) or {}).get(STORY_ID_KEY) |
| 1247 | score = _digg_score(item) |
| 1248 | if cluster_id and score is not None: |
| 1249 | cleaned_id = str(cluster_id).strip() |
| 1250 | if not _is_valid_cluster_id(cleaned_id): |
| 1251 | _log(f"skipping sources fetch for invalid cluster_id: {cluster_id!r}") |
| 1252 | continue |
| 1253 | scored[cleaned_id] = max(score, scored.get(cleaned_id, score)) |
| 1254 | chosen = sorted(scored, key=lambda key: (-scored[key], key))[:budget] |
| 1255 | if not chosen: |
| 1256 | return {} |
| 1257 | |
| 1258 | # Set by the first call that fails. Digg stalls now and then, and a |
| 1259 | # stall hits every call alike, so the calls not yet started are skipped |
| 1260 | # instead of each waiting out its own timeout. |
| 1261 | failing = threading.Event() |
| 1262 | |
| 1263 | def fetch_one(cluster_id: str) -> Optional[Dict[str, Any]]: |
| 1264 | if failing.is_set(): |
| 1265 | return None |
| 1266 | if stopped is not None and stopped(): |
| 1267 | return None |
| 1268 | if cancel is not None and cancel.is_set(): |
| 1269 | return None |
| 1270 | remaining = fetch_deadline - time.monotonic() |
| 1271 | if remaining <= 0: |
| 1272 | return None |
| 1273 | response = _run_cli( |
| 1274 | _build_sources_args(cluster_id), |
| 1275 | timeout=min(POSTS_TIMEOUT, remaining), |
| 1276 | deadline=deadline, |
| 1277 | cancel=cancel, |
| 1278 | ) |
| 1279 | if response.get("error"): |
| 1280 | failing.set() |
| 1281 | return None |
| 1282 | posts: List[Dict[str, Any]] = [] |
| 1283 | source_urls: List[str] = [] |
| 1284 | for row in response.get("results") or []: |
| 1285 | if not isinstance(row, dict): |
| 1286 | continue |
| 1287 | url = str(row.get("xUrl") or "").strip() |
| 1288 | if _is_safe_http_url(url): |
| 1289 | source_urls.append(url) |
| 1290 | if len(posts) < POSTS_PER_CLUSTER: |
| 1291 | post = _parse_post(row) |
| 1292 | if post is not None: |
| 1293 | posts.append(post) |
| 1294 | if not source_urls: |
| 1295 | return None |
| 1296 | return {"posts": posts, "source_urls": source_urls} |
| 1297 | |
| 1298 | # Leaving the block waits for the workers. That wait is bounded: a call |
| 1299 | # under way ends at its timeout, the deadline or the cancel signal, and |
| 1300 | # a call not yet started checks all three first. |
| 1301 | with ThreadPoolExecutor( |
| 1302 | max_workers=min(SOURCES_CONCURRENCY, len(chosen)), |
| 1303 | thread_name_prefix="digg-sources", |
| 1304 | ) as pool: |
| 1305 | entries = list(pool.map(fetch_one, chosen)) |
| 1306 | fetched = { |
| 1307 | cluster_id: entry for cluster_id, entry in zip(chosen, entries) if entry is not None |
| 1308 | } |
| 1309 | if fetched: |
| 1310 | _log(f"fetched sources for {len(fetched)} stories") |
| 1311 | return fetched |
| 1312 | |
| 1313 | |
| 1314 | def apply_story_sources( |
| 1315 | items: list, |
| 1316 | fetched: Dict[str, Dict[str, Any]], |
| 1317 | ) -> Dict[str, List[Dict[str, Any]]]: |
| 1318 | """Attach fetched quotes to their stories and map match keys to stories. |
| 1319 | |
| 1320 | Every copy of a fetched story gets the quotes, so whichever copy |
| 1321 | survives de-duplication still shows them. The returned map goes from |
| 1322 | ``match_key`` of each source URL to the stories that cite it, highest |
| 1323 | Digg Score first, each as its title, URL, Digg Score, source count and |
| 1324 | 0-100 engagement score. Every citing story is kept so that a later |
| 1325 | filter (``surviving_stories``) can fall back to the next one. |
| 1326 | """ |
| 1327 | stories: Dict[str, List[Dict[str, Any]]] = {} |
| 1328 | for item in items: |
| 1329 | if getattr(item, "source", None) != "digg": |
| 1330 | continue |
| 1331 | entry = fetched.get((item.metadata or {}).get(STORY_ID_KEY)) |
| 1332 | if not isinstance(entry, dict): |
| 1333 | continue |
| 1334 | if entry.get("posts"): |
| 1335 | item.metadata["posts"] = entry["posts"] |
| 1336 | engagement = item.engagement or {} |
| 1337 | story = { |
| 1338 | "title": item.title, |
| 1339 | "url": item.url, |
| 1340 | "digg_score": engagement.get("digg_score"), |
| 1341 | "source_count": engagement.get("postCount"), |
| 1342 | "engagement": item.engagement_score or 0, |
| 1343 | } |
| 1344 | for url in entry.get("source_urls") or []: |
| 1345 | key = match_key(url) |
| 1346 | if key is None: |
| 1347 | continue |
| 1348 | citing = stories.setdefault(key, []) |
| 1349 | if all(other["url"] != story["url"] for other in citing): |
| 1350 | citing.append(story) |
| 1351 | for citing in stories.values(): |
| 1352 | citing.sort(key=_story_order) |
| 1353 | return stories |
| 1354 | |
| 1355 | |
| 1356 | def _story_order(story: Dict[str, Any]) -> Tuple[float, str]: |
| 1357 | """Sort key putting the story with the highest Digg Score first. |
| 1358 | |
| 1359 | The 0-100 engagement score reads 100 for every large story, so it cannot |
| 1360 | tell a 1286-score story from a 226-score one. Equal scores go by URL. |
| 1361 | """ |
| 1362 | return (-(story.get("digg_score") or 0), str(story.get("url") or "")) |
| 1363 | |
| 1364 | |
| 1365 | def merge_stories( |
| 1366 | stories: Dict[str, List[Dict[str, Any]]], more: Dict[str, List[Dict[str, Any]]], |
| 1367 | ) -> Dict[str, List[Dict[str, Any]]]: |
| 1368 | """Add a later pass's stories to ``stories`` in place, highest Digg Score first.""" |
| 1369 | for key, citing in more.items(): |
| 1370 | merged = stories.setdefault(key, []) |
| 1371 | merged.extend( |
| 1372 | story for story in citing |
| 1373 | if all(other["url"] != story["url"] for other in merged) |
| 1374 | ) |
| 1375 | merged.sort(key=_story_order) |
| 1376 | return stories |
| 1377 | |
| 1378 | |
| 1379 | def surviving_stories( |
| 1380 | stories: Dict[str, List[Dict[str, Any]]], items: list, |
| 1381 | ) -> Dict[str, List[Dict[str, Any]]]: |
| 1382 | """Keep only the stories that are still among ``items``. |
| 1383 | |
| 1384 | The map is built at retrieval, before the run's subject and identity |
| 1385 | filters reject items. A story they rejected must not come back as the |
| 1386 | confirmation of an item that survived. A source that a rejected story |
| 1387 | and a surviving one both cite keeps the surviving one. |
| 1388 | """ |
| 1389 | kept = {item.url for item in items if getattr(item, "source", None) == "digg"} |
| 1390 | surviving: Dict[str, List[Dict[str, Any]]] = {} |
| 1391 | for key, citing in stories.items(): |
| 1392 | still = [story for story in citing if story.get("url") in kept] |
| 1393 | if still: |
| 1394 | surviving[key] = still |
| 1395 | return surviving |
| 1396 | |
| 1397 | |
| 1398 | def tag_confirmed_candidates( |
| 1399 | candidates: list, stories: Dict[str, List[Dict[str, Any]]], |
| 1400 | ) -> int: |
| 1401 | """Mark each candidate that is a source of a fetched Digg story. |
| 1402 | |
| 1403 | A candidate matches when the URL of one of its non-Digg items has the |
| 1404 | same ``match_key`` as a story source. The matching story with the |
| 1405 | highest Digg Score is recorded under ``metadata[CONFIRMED_BY_KEY]``, where ranking |
| 1406 | and rendering read it. Returns how many candidates were marked. |
| 1407 | """ |
| 1408 | if not stories: |
| 1409 | return 0 |
| 1410 | tagged = 0 |
| 1411 | for candidate in candidates: |
| 1412 | best: Optional[Dict[str, Any]] = None |
| 1413 | for item in candidate.source_items: |
| 1414 | if item.source == "digg": |
| 1415 | continue |
| 1416 | key = match_key(item.url) |
| 1417 | # Each list is ordered highest Digg Score first. |
| 1418 | story = next(iter(stories.get(key) or []), None) if key else None |
| 1419 | if story and (best is None or _story_order(story) < _story_order(best)): |
| 1420 | best = story |
| 1421 | if best is not None: |
| 1422 | candidate.metadata[CONFIRMED_BY_KEY] = dict(best) |
| 1423 | tagged += 1 |
| 1424 | if tagged: |
| 1425 | _log(f"{tagged} items confirmed by a Digg story") |
| 1426 | return tagged |
| 1427 | |
| 1428 | |
| 1429 | class BarResult(NamedTuple): |
| 1430 | """Where the Digg bar put each story of one list. |
| 1431 | |
| 1432 | ``prominent`` is ordered by Digg Score, highest first, then story UUID. |
| 1433 | ``ordinary``, ``dropped`` and ``legacy`` keep the order they came in. |
| 1434 | """ |
| 1435 | |
| 1436 | prominent: list |
| 1437 | ordinary: list |
| 1438 | dropped: list |
| 1439 | legacy: list |
| 1440 | |
| 1441 | |
| 1442 | def _topic_subjects(topic: str) -> List[List[str]]: |
| 1443 | """The subjects a topic asks about, each as its lowercase words. |
| 1444 | |
| 1445 | A comparison ("X vs Y") has one subject per side. Returns an empty list |
| 1446 | when only question and filler words are left. |
| 1447 | """ |
| 1448 | subjects: List[List[str]] = [] |
| 1449 | for side in _TOPIC_SIDE_SPLIT.split(topic or ""): |
| 1450 | words = [word.strip(_TOPIC_WORD_EDGE) for word in side.lower().split()] |
| 1451 | words = [word for word in words if word] |
| 1452 | start = 0 |
| 1453 | while start < len(words) and ( |
| 1454 | words[start] in _TOPIC_LEAD_WORDS |
| 1455 | or (start > 0 and words[start] in _TOPIC_FOLLOW_WORDS) |
| 1456 | ): |
| 1457 | start += 1 |
| 1458 | words = words[start:] |
| 1459 | while words and words[-1] in _TOPIC_TAIL_WORDS: |
| 1460 | words.pop() |
| 1461 | if words and words not in subjects: |
| 1462 | subjects.append(words) |
| 1463 | return subjects |
| 1464 | |
| 1465 | |
| 1466 | def _whole_phrase(words: List[str]) -> "re.Pattern[str]": |
| 1467 | """Matches the words in order as whole tokens, any case. |
| 1468 | |
| 1469 | Spaces and hyphens inside the phrase match any run of either. The edges |
| 1470 | use lookarounds, not ``\\b``, so "C++" works and "AI" does not match |
| 1471 | inside "Maine". |
| 1472 | """ |
| 1473 | parts = [ |
| 1474 | re.escape(part) |
| 1475 | for word in words |
| 1476 | for part in re.split(r"-+", word) |
| 1477 | if part |
| 1478 | ] or [re.escape(word) for word in words] |
| 1479 | return re.compile(r"(?<!\w)" + r"[\s\-]+".join(parts) + r"(?!\w)", re.IGNORECASE) |
| 1480 | |
| 1481 | |
| 1482 | def _title_points_at(words: List[str], title: str, text: str) -> bool: |
| 1483 | """True when a title that does not name the subject whole is still about it. |
| 1484 | |
| 1485 | The title has to carry part of the subject. A story that names the |
| 1486 | subject only in its summary mentions it and is about something else: a |
| 1487 | tour story that lists other artists, a roundup, a rival's launch. |
| 1488 | |
| 1489 | - One word ("OpenAI"): the title either names it or it does not. |
| 1490 | - Two words, a name ("Sam Altman") or a subject and an aspect of it |
| 1491 | ("Tesla earnings"): the title has one of them and the other appears |
| 1492 | somewhere in the story ("Altman says ...", "Tesla reports record |
| 1493 | profit" with earnings in the summary). |
| 1494 | - Longer, a description ("why is Nvidia stock down"): a story on the |
| 1495 | subject rarely repeats it, so one of its telling words in the title |
| 1496 | is enough. |
| 1497 | """ |
| 1498 | if len(words) < SUBJECT_NAME_MAX_WORDS: |
| 1499 | return False |
| 1500 | if len(words) == SUBJECT_NAME_MAX_WORDS: |
| 1501 | in_title = [bool(_whole_phrase([word]).search(title)) for word in words] |
| 1502 | in_text = [bool(_whole_phrase([word]).search(text)) for word in words] |
| 1503 | return any(in_title) and all(in_text) |
| 1504 | telling = [ |
| 1505 | word for word in words |
| 1506 | if len(word) > 2 and word not in STOPWORDS and word not in LOW_SIGNAL_QUERY_TOKENS |
| 1507 | ] or words |
| 1508 | return any(_whole_phrase([word]).search(title) for word in telling) |
| 1509 | |
| 1510 | |
| 1511 | def _is_big(item: Any) -> bool: |
| 1512 | score = _digg_score(item) |
| 1513 | sources = (getattr(item, "engagement", None) or {}).get("postCount") |
| 1514 | return ( |
| 1515 | score is not None |
| 1516 | and score >= PROMINENT_MIN_SCORE |
| 1517 | and isinstance(sources, (int, float)) |
| 1518 | and sources >= PROMINENT_MIN_SOURCES |
| 1519 | ) |
| 1520 | |
| 1521 | |
| 1522 | def apply_bar(topic: str, items: list) -> BarResult: |
| 1523 | """Sort Digg stories into prominent, ordinary and dropped for a run topic. |
| 1524 | |
| 1525 | A story whose title names the topic's subject is prominent when it has a |
| 1526 | Digg Score of at least ``PROMINENT_MIN_SCORE`` and at least |
| 1527 | ``PROMINENT_MIN_SOURCES`` sources, and ordinary otherwise. A story whose |
| 1528 | title carries only part of the subject, by the test in |
| 1529 | ``_title_points_at``, is ordinary. Any other story is dropped, including |
| 1530 | one that names the subject only in its summary. Names are matched as |
| 1531 | whole words, any case. |
| 1532 | |
| 1533 | A topic with no subject left once its question and filler words are gone |
| 1534 | makes every story ordinary. Clusters from digg-pp-cli 2026.10.x, which |
| 1535 | have no story UUID, come back under ``legacy`` and are not judged. |
| 1536 | |
| 1537 | The verdict depends only on the topic and the story's own text and |
| 1538 | numbers, and nothing is written to the items, so asking again later with |
| 1539 | the same topic gives the same answer. |
| 1540 | """ |
| 1541 | subjects = _topic_subjects(topic) |
| 1542 | phrases = [_whole_phrase(words) for words in subjects] |
| 1543 | result = BarResult([], [], [], []) |
| 1544 | for item in items: |
| 1545 | if not (getattr(item, "metadata", None) or {}).get(STORY_ID_KEY): |
| 1546 | result.legacy.append(item) |
| 1547 | continue |
| 1548 | if not subjects: |
| 1549 | result.ordinary.append(item) |
| 1550 | continue |
| 1551 | title = str(getattr(item, "title", "") or "") |
| 1552 | if any(phrase.search(title) for phrase in phrases): |
| 1553 | (result.prominent if _is_big(item) else result.ordinary).append(item) |
| 1554 | continue |
| 1555 | text = "\n".join( |
| 1556 | str(getattr(item, name, "") or "") for name in ("title", "body", "snippet") |
| 1557 | ) |
| 1558 | if any(_title_points_at(words, title, text) for words in subjects): |
| 1559 | result.ordinary.append(item) |
| 1560 | else: |
| 1561 | result.dropped.append(item) |
| 1562 | result.prominent.sort( |
| 1563 | key=lambda item: (-(_digg_score(item) or 0.0), str(item.metadata[STORY_ID_KEY])) |
| 1564 | ) |
| 1565 | return result |
| 1566 |