| 1 | """Techmeme tech-news source for last30days. |
| 2 | |
| 3 | Shells out to ``techmeme-pp-cli`` (no auth). The CLI's ``search`` command hits |
| 4 | Techmeme's live archive search endpoint (results back to ~2005) -- it never |
| 5 | reads the locally synced headline cache, so the adapter performs no ``sync``. |
| 6 | |
| 7 | Activation gate: only available when ``techmeme-pp-cli`` is on PATH. |
| 8 | ``pipeline.available_sources`` checks ``shutil.which`` before including |
| 9 | ``techmeme``. The functions below also detect the missing-binary case. |
| 10 | |
| 11 | Surface choice: ``search "<topic>" --json`` (NOT ``--agent``). ``--agent`` |
| 12 | implies ``--compact``, which on older binaries stripped headline records to |
| 13 | ``{}`` (fixed upstream in printing-press-library PR #1383); ``--json`` without |
| 14 | ``--compact`` returns the populated record shape on every binary version, so |
| 15 | the adapter is robust regardless of the installed build. |
| 16 | |
| 17 | Dates: current binaries emit ``{num, source, headline, link, date}`` where |
| 18 | ``date`` is ISO ``YYYY-MM-DD`` (or ``""`` when Techmeme's markup was |
| 19 | unparseable). The adapter windows records to the research range |
| 20 | (``from_date <= date <= to_date``) so archive hits from years past never |
| 21 | masquerade as current news. Records with no usable date -- old binaries emit |
| 22 | no ``date`` key at all -- are kept but flow downstream with no date, so |
| 23 | ``normalize._normalize_techmeme`` assigns ``date_confidence: low``. Headlines |
| 24 | are never stamped with today's date. (This deliberately diverges from |
| 25 | ``lib/arxiv.py``, which drops entries with unparseable dates -- arXiv's feed |
| 26 | reliably carries dates, so an unparseable one is anomalous; Techmeme's old |
| 27 | binaries emit no ``date`` key at all, so dropping would zero out the source |
| 28 | for every user on an old binary.) Old binaries also print prose |
| 29 | (``No results for "q"``) to stdout on zero hits; that parses as an empty |
| 30 | result set, not a decode failure. Publication-name header rows (very short |
| 31 | ``headline`` values) are dropped; ranking is topic relevance plus rank decay. |
| 32 | """ |
| 33 | |
| 34 | from __future__ import annotations |
| 35 | |
| 36 | import json |
| 37 | import os |
| 38 | import re |
| 39 | import shutil |
| 40 | from typing import Any, Dict, List |
| 41 | |
| 42 | from . import health, log, subproc |
| 43 | from .relevance import token_overlap_relevance |
| 44 | |
| 45 | |
| 46 | CLI_BIN = "techmeme-pp-cli" |
| 47 | |
| 48 | DEPTH_CONFIG = { |
| 49 | "quick": 8, |
| 50 | "default": 16, |
| 51 | "deep": 30, |
| 52 | } |
| 53 | |
| 54 | # A real story headline is a sentence; bare publication-name rows ("TechCrunch", |
| 55 | # "New York Times") are section headers in the feed, not stories. Require at |
| 56 | # least this many words to keep a record. |
| 57 | MIN_HEADLINE_WORDS = 4 |
| 58 | |
| 59 | SEARCH_TIMEOUT = 30 |
| 60 | # Techmeme's archive search returns 10 newest-first hits per page. Helpers |
| 61 | # from the printing-press-library release with `search --pages` read enough |
| 62 | # pages to fill the depth cap; each extra page gets this many more seconds. |
| 63 | SEARCH_PAGE_SIZE = 10 |
| 64 | SEARCH_PAGE_TIMEOUT = 10 |
| 65 | |
| 66 | # Old binaries print this prose to stdout (exit 0) on zero hits, even in JSON |
| 67 | # mode. It is a zero-result response, not malformed output. |
| 68 | _NO_RESULTS_PREFIX = "No results" |
| 69 | |
| 70 | _ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") |
| 71 | _UNKNOWN_PAGES_FLAG_RE = re.compile(r"unknown flag:\s*--pages(?:\s|$)") |
| 72 | _URL_USERINFO_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]{0,15}://)[^\s/?#]+@") |
| 73 | |
| 74 | |
| 75 | def _scrub_url_userinfo(text: str) -> str: |
| 76 | return _URL_USERINFO_RE.sub(r"\1", text) if text else text |
| 77 | |
| 78 | # Keep only OS, cache/config-dir, locale, TLS, and proxy settings. |
| 79 | # Never inherit unrelated provider secrets or runtime-injection vars like NODE_OPTIONS. |
| 80 | _CHILD_ENV_ALLOWLIST = frozenset({ |
| 81 | "PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA", |
| 82 | "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", |
| 83 | "XDG_STATE_HOME", "SYSTEMROOT", "WINDIR", "SYSTEMDRIVE", "COMSPEC", |
| 84 | "PATHEXT", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "LC_CTYPE", |
| 85 | "TZ", "NO_COLOR", "TERM", "SSL_CERT_FILE", "SSL_CERT_DIR", |
| 86 | "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", |
| 87 | }) |
| 88 | |
| 89 | |
| 90 | def _child_env() -> Dict[str, str]: |
| 91 | """Allowlisted child environment for techmeme-pp-cli.""" |
| 92 | return { |
| 93 | name: value |
| 94 | for name, value in os.environ.items() |
| 95 | if name.upper() in _CHILD_ENV_ALLOWLIST or name.upper().startswith("LC_") |
| 96 | } |
| 97 | |
| 98 | |
| 99 | def _log(msg: str) -> None: |
| 100 | log.source_log("Techmeme", msg, tty_only=False) |
| 101 | |
| 102 | |
| 103 | def _is_available() -> bool: |
| 104 | """True when the techmeme-pp-cli binary is on PATH.""" |
| 105 | return shutil.which(CLI_BIN) is not None |
| 106 | |
| 107 | |
| 108 | def _techmeme_date(iso: str) -> str | None: |
| 109 | """ISO YYYY-MM-DD as Techmeme's M/D/YY (no zero padding), else None.""" |
| 110 | if not isinstance(iso, str) or not _ISO_DATE_RE.match(iso.strip()): |
| 111 | return None |
| 112 | year, month, day = (int(part) for part in iso.strip().split("-")) |
| 113 | return f"{month}/{day}/{year % 100:02d}" |
| 114 | |
| 115 | |
| 116 | def _date_clause(from_date: str | None, to_date: str | None) -> str: |
| 117 | """Techmeme's server-side window operator, ``date:[M/D/YY TO M/D/YY]``. |
| 118 | |
| 119 | No space after the colon: that is the form verified live against |
| 120 | d3results.jsp. Empty when either bound is missing or malformed.""" |
| 121 | start = _techmeme_date(from_date) if from_date else None |
| 122 | end = _techmeme_date(to_date) if to_date else None |
| 123 | if not start or not end: |
| 124 | return "" |
| 125 | return f"date:[{start} TO {end}]" |
| 126 | |
| 127 | |
| 128 | def _pages_for(limit: int) -> int: |
| 129 | """Result pages needed to fill a depth cap of ``limit`` records.""" |
| 130 | return max(1, -(-limit // SEARCH_PAGE_SIZE)) |
| 131 | |
| 132 | |
| 133 | def _rejects_pages_flag(response: Dict[str, Any]) -> bool: |
| 134 | """The helper predates ``search --pages`` (cobra: ``unknown flag: --pages``).""" |
| 135 | error = str(response.get("error") or "") |
| 136 | return bool(_UNKNOWN_PAGES_FLAG_RE.search(error)) |
| 137 | |
| 138 | |
| 139 | def _build_search_args( |
| 140 | topic: str, |
| 141 | from_date: str | None = None, |
| 142 | to_date: str | None = None, |
| 143 | pages: int = 1, |
| 144 | ) -> List[str]: |
| 145 | # --json (not --agent) avoids --compact, which blanks headline records on |
| 146 | # pre-PR-1383 binaries. Techmeme's `search` has no result-limit flag and |
| 147 | # returns pages of 10 newest-first hits, so the run window goes into the |
| 148 | # query as Techmeme's `date:[...]` operator; otherwise narrow queries burn |
| 149 | # all 10 slots on years-old archive hits. The helper passes the operator |
| 150 | # through to Techmeme unchanged. The depth cap and the date window are |
| 151 | # still applied client-side as a backstop. ``pages`` above 1 adds |
| 152 | # ``--pages N`` so a busy topic's window is not capped at those 10. |
| 153 | query = topic |
| 154 | clause = _date_clause(from_date, to_date) |
| 155 | if clause and "date:" not in topic: |
| 156 | query = f"{topic} {clause}" |
| 157 | args = [CLI_BIN, "search", "--json"] |
| 158 | if pages > 1: |
| 159 | args += ["--pages", str(pages)] |
| 160 | args += ["--", query] |
| 161 | return args |
| 162 | |
| 163 | |
| 164 | def _coerce_list(data: Any) -> List[Dict[str, Any]]: |
| 165 | """Techmeme search returns a bare JSON array; tolerate a results-wrapped |
| 166 | envelope too.""" |
| 167 | if isinstance(data, list): |
| 168 | return [r for r in data if isinstance(r, dict)] |
| 169 | if isinstance(data, dict): |
| 170 | results = data.get("results") |
| 171 | if isinstance(results, list): |
| 172 | return [r for r in results if isinstance(r, dict)] |
| 173 | return [] |
| 174 | |
| 175 | |
| 176 | def _record_iso_date(rec: Dict[str, Any]) -> str | None: |
| 177 | """The record's ``date`` as a valid ISO YYYY-MM-DD string, else None. |
| 178 | |
| 179 | Old binaries emit no ``date`` key; current binaries emit ``""`` when |
| 180 | Techmeme's markup was unparseable. Anything that isn't a clean ISO date is |
| 181 | treated as absent.""" |
| 182 | value = rec.get("date") |
| 183 | if isinstance(value, str) and _ISO_DATE_RE.match(value.strip()): |
| 184 | return value.strip() |
| 185 | return None |
| 186 | |
| 187 | |
| 188 | def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]: |
| 189 | """Invoke techmeme-pp-cli and return ``{"results": [...records...]}``. |
| 190 | Never raises.""" |
| 191 | if not _is_available(): |
| 192 | return {"results": [], "error": f"{CLI_BIN} not on PATH"} |
| 193 | try: |
| 194 | result = subproc.run_with_timeout(cmd, timeout=timeout, env=_child_env()) |
| 195 | except subproc.SubprocTimeout as exc: |
| 196 | msg = _scrub_url_userinfo(str(exc)) |
| 197 | _log(f"Timeout: {msg}") |
| 198 | return {"results": [], "error": msg} |
| 199 | except FileNotFoundError as exc: |
| 200 | msg = _scrub_url_userinfo(str(exc)) |
| 201 | _log(f"Binary missing: {msg}") |
| 202 | return {"results": [], "error": msg} |
| 203 | except OSError as exc: |
| 204 | msg = _scrub_url_userinfo(str(exc)) |
| 205 | _log(f"Spawn failed: {msg}") |
| 206 | return {"results": [], "error": msg} |
| 207 | |
| 208 | if result.returncode != 0: |
| 209 | stderr = _scrub_url_userinfo(result.stderr or "") |
| 210 | snippet = stderr.strip().splitlines()[:1] |
| 211 | first = snippet[0] if snippet else f"exit {result.returncode}" |
| 212 | _log(f"CLI exit {result.returncode}: {first}") |
| 213 | return {"results": [], "error": first} |
| 214 | |
| 215 | stdout = result.stdout or "" |
| 216 | if not stdout.strip(): |
| 217 | return {"results": []} |
| 218 | # Old binaries print `No results for "q"` prose (exit 0) even in JSON |
| 219 | # mode: a legitimate zero-hit response, not a decode failure. |
| 220 | if stdout.strip().startswith(_NO_RESULTS_PREFIX): |
| 221 | return {"results": []} |
| 222 | try: |
| 223 | data = json.loads(stdout) |
| 224 | except json.JSONDecodeError as exc: |
| 225 | msg = _scrub_url_userinfo(str(exc)) |
| 226 | _log(f"JSON decode failed: {msg}") |
| 227 | return {"results": [], "error": f"json decode: {msg}"} |
| 228 | |
| 229 | if not isinstance(data, list) and not ( |
| 230 | isinstance(data, dict) and isinstance(data.get("results"), list) |
| 231 | ): |
| 232 | msg = "unexpected Techmeme response shape" |
| 233 | _log(msg) |
| 234 | return {"results": [], "error": msg} |
| 235 | return {"results": _coerce_list(data)} |
| 236 | |
| 237 | |
| 238 | def search_techmeme( |
| 239 | topic: str, |
| 240 | from_date: str, |
| 241 | to_date: str, |
| 242 | depth: str = "default", |
| 243 | ) -> Dict[str, Any]: |
| 244 | """Search Techmeme's live archive via techmeme-pp-cli. |
| 245 | |
| 246 | Windows records to ``from_date..to_date`` on each record's own ISO date |
| 247 | (lexicographic compare is exact for ISO strings). Records with no usable |
| 248 | date are kept -- their recency is resolved downstream as low confidence. |
| 249 | There is deliberately no keep-all fallback when nothing is in-window: |
| 250 | Techmeme's archive reaches back decades, so zero in-window records means |
| 251 | zero results, not "serve stale news". Returns a dict with a ``results`` |
| 252 | list of raw records; on failure ``results`` is empty. |
| 253 | """ |
| 254 | if not topic or not topic.strip(): |
| 255 | return {"results": []} |
| 256 | if not _is_available(): |
| 257 | return {"results": [], "error": f"{CLI_BIN} not on PATH"} |
| 258 | limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 259 | pages = _pages_for(limit) |
| 260 | cmd = _build_search_args(topic, from_date, to_date, pages=pages) |
| 261 | _log(f"search '{topic}' (cap={limit}, pages={pages})") |
| 262 | response = _run_cli( |
| 263 | cmd, timeout=SEARCH_TIMEOUT + SEARCH_PAGE_TIMEOUT * (pages - 1), |
| 264 | ) |
| 265 | if pages > 1 and _rejects_pages_flag(response): |
| 266 | # An older helper reads one page; upgrading it lifts the 10-hit cap. |
| 267 | _log( |
| 268 | "helper has no `search --pages`; reading one page of 10 (upgrade " |
| 269 | f"via `npx -y {health.PRINTING_PRESS_NPM} install techmeme " |
| 270 | "--cli-only`)" |
| 271 | ) |
| 272 | cmd = _build_search_args(topic, from_date, to_date) |
| 273 | response = _run_cli(cmd, timeout=SEARCH_TIMEOUT) |
| 274 | records = response.get("results") or [] |
| 275 | if isinstance(records, list): |
| 276 | # Hard date window: drop records whose date falls outside the research |
| 277 | # range; keep undated records (old binaries / unparseable markup). |
| 278 | dated_in_window = [] |
| 279 | undated = [] |
| 280 | dropped = 0 |
| 281 | for rec in records: |
| 282 | iso = _record_iso_date(rec) |
| 283 | if iso is None: |
| 284 | undated.append(rec) |
| 285 | elif from_date <= iso <= to_date: |
| 286 | dated_in_window.append(rec) |
| 287 | else: |
| 288 | dropped += 1 |
| 289 | if dropped: |
| 290 | _log(f"dropped {dropped} records outside {from_date}..{to_date}") |
| 291 | if records and not dated_in_window and not dropped: |
| 292 | # Every record lacks a usable date: old techmeme-pp-cli (no date |
| 293 | # key) or a Techmeme markup change upstream. Windowing is inactive. |
| 294 | _log( |
| 295 | "no records carry usable dates; date windowing inactive " |
| 296 | "(old techmeme-pp-cli binary or upstream markup change; upgrade " |
| 297 | f"via `npx -y {health.PRINTING_PRESS_NPM} install techmeme " |
| 298 | "--cli-only`)" |
| 299 | ) |
| 300 | # Techmeme returns all matches; apply the depth cap after windowing. |
| 301 | # Dated in-window records take cap slots first so undated archive |
| 302 | # hits can never evict confirmed-fresh stories; undated records fill |
| 303 | # whatever slots remain. |
| 304 | response["results"] = (dated_in_window + undated)[:limit] |
| 305 | _log(f"found {len(response.get('results') or [])} records") |
| 306 | return response |
| 307 | |
| 308 | |
| 309 | def _is_story_headline(headline: str, source: str) -> bool: |
| 310 | """Reject bare publication-name header rows; keep sentence-shaped stories.""" |
| 311 | if not headline: |
| 312 | return False |
| 313 | if len(headline.split()) < MIN_HEADLINE_WORDS: |
| 314 | return False |
| 315 | # A row whose headline is just the publication name is a header. |
| 316 | if source and headline.strip().lower() == source.strip().lower(): |
| 317 | return False |
| 318 | return True |
| 319 | |
| 320 | |
| 321 | def parse_techmeme_response( |
| 322 | response: Dict[str, Any], |
| 323 | query: str = "", |
| 324 | ) -> List[Dict[str, Any]]: |
| 325 | """Parse a Techmeme search envelope into normalized item dicts. |
| 326 | |
| 327 | Drops publication-name header rows and records missing a link. Each item |
| 328 | carries the record's own ISO date, or None when the record has no usable |
| 329 | date (never today's date -- undated items get ``date_confidence: low`` |
| 330 | downstream). Computes a token-overlap relevance hint. Returns dicts ready |
| 331 | for ``normalize._normalize_techmeme``. |
| 332 | """ |
| 333 | raw = response.get("results") if isinstance(response, dict) else None |
| 334 | if not isinstance(raw, list): |
| 335 | return [] |
| 336 | |
| 337 | items: List[Dict[str, Any]] = [] |
| 338 | for i, rec in enumerate(raw): |
| 339 | if not isinstance(rec, dict): |
| 340 | continue |
| 341 | headline = " ".join(str(rec.get("headline") or "").split()).strip() |
| 342 | source_name = str(rec.get("source") or "").strip() |
| 343 | if not _is_story_headline(headline, source_name): |
| 344 | continue |
| 345 | link = str(rec.get("link") or "").strip() |
| 346 | if not link: |
| 347 | continue |
| 348 | |
| 349 | rank_decay = max(0.3, 1.0 - (i * 0.03)) |
| 350 | content_score = token_overlap_relevance(query, headline) if query else 0.5 |
| 351 | relevance = min(1.0, 0.55 * rank_decay + 0.45 * content_score) |
| 352 | |
| 353 | items.append( |
| 354 | { |
| 355 | "id": link, |
| 356 | "title": headline, |
| 357 | "url": link, |
| 358 | "source_name": source_name, |
| 359 | "date": _record_iso_date(rec), |
| 360 | "engagement": {}, |
| 361 | "relevance": round(relevance, 2), |
| 362 | "why_relevant": ( |
| 363 | f"Techmeme headline ({source_name})" if source_name else "Techmeme headline" |
| 364 | ), |
| 365 | } |
| 366 | ) |
| 367 | |
| 368 | return items |
| 369 |