Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat: Add arXiv + Techmeme (default-on) and Trustpilot (opt-in) sources (#709)

Matt Van Horna9d2674147b8
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 12360d24..92be236f 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -94,6 +94,9 @@ The project-scoped file is useful for **intentional per-client setups**: drop a
| YouTube | `yt-dlp` CLI installed; `SCRAPECREATORS_API_KEY` adds a server-side transcript fallback used only when yt-dlp fails (429 / bot-gate) | always on if `yt-dlp` present; SC transcript fallback default-on when key set (no credit spent unless yt-dlp fails) | yes |
| YouTube comments | `SCRAPECREATORS_API_KEY` (default-on; suppress via `EXCLUDE_SOURCES=youtube_comments`) | top comments on the top ~3 videos by engagement | ~3 calls/run; 10K free calls |
| Digg | `digg-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install digg --cli-only`; binary defaults to `$HOME/.local/bin` — Hermes/OpenClaw agent subprocesses must inherit that dir on PATH for Digg to activate; prior pp-digg installs use the same path) | always on if `digg-pp-cli` on PATH | yes (free, keyless, read-only) |
+| arXiv | `arxiv-pp-cli` on PATH (auto-installed during first-run setup via `npx -y @mvanhorn/[email protected] install arxiv --cli-only`) | always on if `arxiv-pp-cli` on PATH; fires on research/technical topics and stays quiet otherwise (relevance + 365-day recency gating) | yes (free, keyless) |
+| Techmeme | `techmeme-pp-cli` on PATH (auto-installed via `... install techmeme --cli-only`) | always on if `techmeme-pp-cli` on PATH; syncs a local headline cache once per run, then searches | yes (free, keyless) |
+| Trustpilot | `trustpilot-pp-cli` on PATH (NOT auto-installed; install on demand via `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`) + `INCLUDE_SOURCES` contains `trustpilot` | **opt-in, off by default**; when enabled, activates only on company/brand topics. Does a one-time ~10s headless-Chrome WAF-cookie harvest on first company lookup (set `LAST30DAYS_TRUSTPILOT_NO_BROWSER=1` to disable in cron/CI) | yes (no API key; cookie-replay after the one-time harvest) |
| X / Twitter | one of: `AUTH_TOKEN` + `CT0` (browser cookies, Bird CLI), `XAI_API_KEY`, `XQUIK_API_KEY`, `SCRAPECREATORS_API_KEY`, or `FROM_BROWSER` (cookie-jar auth) | X items in results | cookie-jar / Bird = free; Xquik / xAI / ScrapeCreators = key-based |
| TikTok | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `tiktok` | TikTok items | 10K free calls |
| Instagram | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `instagram` | Instagram Reels | 10K free calls; raise `LAST30DAYS_TRANSCRIPT_TIMEOUT` (default 30s) if SC is slow on your network |
@@ -303,6 +306,7 @@ Relevant env vars:
| --- | --- |
| `LAST30DAYS_NATIVE_SEARCH=1` | Tells the engine your agent session has host-side web search; suppresses the keyless floor. Set automatically by the skill when web search is available. Leave unset when the agent has no web-search tool so the floor runs. |
| `LAST30DAYS_SEARXNG_URL=<base-url>` | Optional. A SearXNG instance used as the keyless-search fallback rung when DuckDuckGo returns nothing. |
+| `LAST30DAYS_TRUSTPILOT_NO_BROWSER=1` | Optional. Truthy value disables the Trustpilot source's one-time headless-Chrome WAF-cookie harvest, so an automated/headless run (cron, CI, the eval harness) never spawns a browser. Trustpilot still degrades to empty gracefully. |
Privacy note: the keyless floor sends the query (to DuckDuckGo / your SearXNG instance) and any fetched URL (to Jina Reader) to those third parties. It is intended for public-research use; results may be cached snapshots. It never runs when native search or a paid backend is in play.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index ab869d98..73d8ac3b 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -412,6 +412,8 @@ Auto setup gives you the core sources free in about 30 seconds:
- Reddit with comments - public JSON, no API key needed.
- YouTube search + transcripts - installs yt-dlp (open source, 190K+ GitHub stars).
- Digg - trending news, GitHub stars, and pipeline feeds - installs the free, keyless Digg CLI.
+- arXiv (📄) + Techmeme (📰) - research papers and tech-news headlines - install free, keyless Printing Press CLIs and run on any topic (arXiv is relevance + recency gated to research topics).
+- Trustpilot (⭐) - brand/company review sentiment - opt-in (add `trustpilot` to `INCLUDE_SOURCES`), off by default because it can do a one-time ~10s headless browser cookie step on first company lookup. Install with `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`.
- Hacker News + Polymarket + GitHub (auto-on if the `gh` CLI is installed) - always on, zero config.
Want TikTok and Instagram too? ScrapeCreators adds those (10,000 free calls, scrapecreators.com). No kickbacks, no affiliation.
diff --git a/skills/last30days/scripts/lib/arxiv.py b/skills/last30days/scripts/lib/arxiv.py
new file mode 100644
index 00000000..c333d715
--- /dev/null
+++ b/skills/last30days/scripts/lib/arxiv.py
@@ -0,0 +1,290 @@
+"""arXiv research-paper source for last30days.
+
+Shells out to ``arxiv-pp-cli`` (open Atom API, no auth) to surface recent
+research papers relevant to a topic. arXiv carries no engagement signal, so
+ranking leans on relevance (the CLI's own relevance sort plus token overlap)
+and recency.
+
+Activation gate: this source is only available when ``arxiv-pp-cli`` is on
+PATH. ``pipeline.available_sources`` checks ``shutil.which`` before including
+``arxiv``. The functions below also detect the missing-binary case defensively.
+
+Default-on safety (two gates, both required):
+ 1. Query construction. arXiv is queried with a *quoted* phrase and
+ ``--sort-by relevance``. Sorting by submitted-date instead returns the
+ newest cs.* papers regardless of topic -- topic-blind noise.
+ 2. Recency cutoff. Entries older than ``RECENCY_DAYS`` are dropped. Research
+ does not trend on a 30-day clock, so this window is wider than the social
+ sources' 30 days; it keeps arXiv current while dropping stale keyword
+ matches (e.g. a 2017 sports-statistics paper that an off-topic query like
+ "Golden State Warriors" would otherwise surface).
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional
+
+from . import log, subproc
+from .relevance import token_overlap_relevance
+
+
+CLI_BIN = "arxiv-pp-cli"
+
+# Per-depth result counts.
+DEPTH_CONFIG = {
+ "quick": 5,
+ "default": 10,
+ "deep": 20,
+}
+
+# Recency window for arXiv specifically. Papers do not trend daily; a year keeps
+# the source current (the off-topic 2017 paper still drops) without discarding
+# the genuinely-relevant work from the last few months.
+RECENCY_DAYS = 365
+
+SEARCH_TIMEOUT = 30
+
+
+def _log(msg: str) -> None:
+ log.source_log("arXiv", msg, tty_only=False)
+
+
+def _is_available() -> bool:
+ """True when the arxiv-pp-cli binary is on PATH."""
+ return shutil.which(CLI_BIN) is not None
+
+
+def _today() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _build_search_query(topic: str) -> str:
+ """Quote the topic so arXiv treats it as a phrase across all fields.
+
+ Inner double-quotes are stripped (arXiv has no phrase-escaping); the outer
+ quotes plus ``all:`` give a phrase-scoped relevance search.
+ """
+ return f'all:"{_clean_phrase(topic)}"'
+
+
+def _clean_phrase(topic: str) -> str:
+ """Strip quotes and collapse whitespace into a phrase for the query."""
+ return " ".join(topic.replace('"', " ").split())
+
+
+def _build_search_args(topic: str, limit: int) -> List[str]:
+ return [
+ CLI_BIN,
+ "query",
+ "--search-query",
+ _build_search_query(topic),
+ "--sort-by",
+ "relevance",
+ "--max-results",
+ str(limit),
+ "--agent",
+ ]
+
+
+def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
+ """Invoke arxiv-pp-cli and parse the JSON envelope.
+
+ arXiv returns ``{"meta": ..., "results": {"entries": [...]}}``. This
+ normalizes to ``{"results": [...entries...]}`` so the parse step sees a
+ flat list, matching the other sources' shape. Never raises.
+ """
+ if not _is_available():
+ return {"results": [], "error": f"{CLI_BIN} not on PATH"}
+ try:
+ result = subproc.run_with_timeout(cmd, timeout=timeout)
+ except subproc.SubprocTimeout as exc:
+ _log(f"Timeout: {exc}")
+ return {"results": [], "error": str(exc)}
+ except FileNotFoundError as exc:
+ _log(f"Binary missing: {exc}")
+ return {"results": [], "error": str(exc)}
+ except OSError as exc:
+ _log(f"Spawn failed: {exc}")
+ return {"results": [], "error": str(exc)}
+
+ if result.returncode != 0:
+ snippet = (result.stderr or "").strip().splitlines()[:1]
+ first = snippet[0] if snippet else f"exit {result.returncode}"
+ _log(f"CLI exit {result.returncode}: {first}")
+ return {"results": [], "error": first}
+
+ stdout = result.stdout or ""
+ if not stdout.strip():
+ return {"results": []}
+ try:
+ data = json.loads(stdout)
+ except json.JSONDecodeError as exc:
+ _log(f"JSON decode failed: {exc}")
+ return {"results": [], "error": f"json decode: {exc}"}
+
+ return {"results": _extract_entries(data)}
+
+
+def _extract_entries(data: Any) -> List[Dict[str, Any]]:
+ """Pull the entries list out of arXiv's nested envelope.
+
+ Tolerates ``{"results": {"entries": [...]}}`` (current shape),
+ ``{"entries": [...]}``, and a bare list.
+ """
+ if isinstance(data, list):
+ return [e for e in data if isinstance(e, dict)]
+ if isinstance(data, dict):
+ results = data.get("results")
+ if isinstance(results, dict):
+ entries = results.get("entries")
+ if isinstance(entries, list):
+ return [e for e in entries if isinstance(e, dict)]
+ if isinstance(results, list):
+ return [e for e in results if isinstance(e, dict)]
+ entries = data.get("entries")
+ if isinstance(entries, list):
+ return [e for e in entries if isinstance(e, dict)]
+ return []
+
+
+def search_arxiv(
+ topic: str,
+ from_date: str,
+ to_date: str,
+ depth: str = "default",
+) -> Dict[str, Any]:
+ """Search arXiv via arxiv-pp-cli using a quoted, relevance-sorted query.
+
+ Returns a dict with a flat ``results`` list of entry dicts. On failure,
+ ``results`` is empty and an ``error`` key carries a one-line description.
+ """
+ if not topic or not topic.strip():
+ return {"results": []}
+ # A topic of only quote characters cleans to an empty phrase (all:""),
+ # which is a topic-blind query; bail rather than search for nothing.
+ if not _clean_phrase(topic):
+ return {"results": []}
+ limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
+ cmd = _build_search_args(topic, limit)
+ _log(f"query '{topic}' (relevance, max={limit})")
+ response = _run_cli(cmd, timeout=SEARCH_TIMEOUT)
+ _log(f"found {len(response.get('results') or [])} entries")
+ return response
+
+
+def _parse_published(published: Optional[str]) -> Optional[datetime]:
+ """Parse an arXiv ``published`` timestamp (ISO 8601, e.g.
+ '2026-06-25T17:59:48Z') into an aware datetime. Returns None on failure."""
+ if not published or not isinstance(published, str):
+ return None
+ text = published.strip().replace("Z", "+00:00")
+ try:
+ dt = datetime.fromisoformat(text)
+ except ValueError:
+ return None
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ return dt
+
+
+def _alternate_url(entry: Dict[str, Any]) -> str:
+ """Return the human-facing abstract URL (rel=alternate), not the PDF."""
+ links = entry.get("links")
+ if isinstance(links, list):
+ for link in links:
+ if isinstance(link, dict) and link.get("rel") == "alternate":
+ href = str(link.get("href") or "").strip()
+ if href:
+ return href
+ # Fall back to the abstract URL derived from the entry id.
+ entry_id = str(entry.get("id") or "").strip()
+ if entry_id.startswith("http"):
+ return entry_id
+ return ""
+
+
+def _author_names(entry: Dict[str, Any]) -> List[str]:
+ authors = entry.get("authors")
+ out: List[str] = []
+ if isinstance(authors, list):
+ for a in authors:
+ if isinstance(a, dict):
+ name = str(a.get("name") or "").strip()
+ if name:
+ out.append(name)
+ return out
+
+
+def parse_arxiv_response(
+ response: Dict[str, Any],
+ query: str = "",
+ today: Optional[datetime] = None,
+) -> List[Dict[str, Any]]:
+ """Parse an arXiv envelope into normalized item dicts.
+
+ Applies the recency cutoff (drops entries older than ``RECENCY_DAYS`` and
+ entries with an unparseable date) and computes a token-overlap relevance
+ hint. Returns dicts ready for ``normalize._normalize_arxiv``.
+ """
+ raw = response.get("results") if isinstance(response, dict) else None
+ if not isinstance(raw, list):
+ return []
+
+ now = today or _today()
+ items: List[Dict[str, Any]] = []
+ for i, entry in enumerate(raw):
+ if not isinstance(entry, dict):
+ continue
+ title = " ".join(str(entry.get("title") or "").split()).strip()
+ if not title:
+ continue
+ published = _parse_published(entry.get("published") or entry.get("updated"))
+ if published is None:
+ # No usable date -> cannot honor the recency contract; drop.
+ continue
+ age_days = (now - published).days
+ # Allow a one-day grace on the future side: a paper announced later in
+ # the same UTC day yields age_days == -1 (timedelta.days floors toward
+ # negative); dropping it as "future" would discard the freshest work.
+ if age_days > RECENCY_DAYS or age_days < -1:
+ continue
+
+ summary = " ".join(str(entry.get("summary") or "").split()).strip()
+ authors = _author_names(entry)
+ url = _alternate_url(entry)
+
+ rank_decay = max(0.3, 1.0 - (i * 0.03))
+ if query:
+ content_score = token_overlap_relevance(query, f"{title} {summary}".strip())
+ else:
+ content_score = 0.5
+ relevance = min(1.0, 0.6 * rank_decay + 0.4 * content_score)
+
+ primary_author = authors[0] if authors else ""
+ author_label = primary_author
+ if len(authors) > 1:
+ author_label = f"{primary_author} et al."
+
+ items.append(
+ {
+ "id": str(entry.get("id") or url or f"AX{i + 1}"),
+ "title": title,
+ "url": url,
+ "summary": summary,
+ "author": author_label,
+ "authors": authors,
+ "date": published.date().isoformat(),
+ "engagement": {},
+ "relevance": round(relevance, 2),
+ "why_relevant": (
+ f"arXiv paper ({primary_author}, {published.date().isoformat()})"
+ if primary_author
+ else f"arXiv paper ({published.date().isoformat()})"
+ ),
+ }
+ )
+
+ return items
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index d49e5c68..d5eba52b 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -452,6 +452,9 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
('LAST30DAYS_NATIVE_SEARCH', None),
# Optional SearXNG instance for the keyless-search fallback rung.
('LAST30DAYS_SEARXNG_URL', None),
+ # Truthy -> disable Trustpilot's headless-Chrome WAF-cookie harvest in
+ # automated contexts (cron/CI/eval). Read by trustpilot._harvest_allowed.
+ ('LAST30DAYS_TRUSTPILOT_NO_BROWSER', None),
('FROM_BROWSER', None),
('LAST30DAYS_TRUST_PROJECT_CONFIG', None),
('SETUP_COMPLETE', None),
diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.py
index 958b9a57..a64a5d4f 100644
--- a/skills/last30days/scripts/lib/normalize.py
+++ b/skills/last30days/scripts/lib/normalize.py
@@ -50,6 +50,9 @@ def normalize_source_items(
"pinterest": _normalize_pinterest,
"polymarket": _normalize_polymarket,
"digg": _normalize_digg,
+ "arxiv": _normalize_arxiv,
+ "techmeme": _normalize_techmeme,
+ "trustpilot": _normalize_trustpilot,
"grounding": _normalize_grounding,
"xiaohongshu": _normalize_grounding,
"github": _normalize_github,
@@ -503,6 +506,121 @@ def _normalize_digg(
)
+def _normalize_arxiv(
+ source: str,
+ item: dict[str, Any],
+ index: int,
+ from_date: str,
+ to_date: str,
+) -> schema.SourceItem:
+ """Normalizer for arXiv papers.
+
+ The abstract (summary) is the body that feeds rerank and synthesis. arXiv
+ has no engagement signal, so engagement is empty and ranking leans on
+ relevance and recency.
+ """
+ title = str(item.get("title") or "").strip()
+ summary = str(item.get("summary") or "").strip()
+ body = "\n\n".join(part for part in [title, summary] if part)
+ authors = item.get("authors") or []
+ if not isinstance(authors, list):
+ authors = []
+ paper_id = str(item.get("id") or f"AX{index + 1}")
+ return _source_item(
+ item_id=paper_id,
+ source=source,
+ title=title or f"arXiv paper {index + 1}",
+ body=body,
+ url=str(item.get("url") or ""),
+ author=str(item.get("author") or "") or None,
+ container="arXiv",
+ published_at=item.get("date"),
+ date_confidence=_date_confidence(item, from_date, to_date, default="high"),
+ engagement={},
+ relevance_hint=item.get("relevance", 0.5),
+ why_relevant=str(item.get("why_relevant") or ""),
+ snippet=summary[:400],
+ metadata={
+ "authors": authors,
+ "summary": summary,
+ },
+ )
+
+
+def _normalize_techmeme(
+ source: str,
+ item: dict[str, Any],
+ index: int,
+ from_date: str,
+ to_date: str,
+) -> schema.SourceItem:
+ """Normalizer for Techmeme headlines.
+
+ The headline is both title and body (Techmeme carries no abstract). The
+ publication is the container/author. No engagement signal in the search
+ shape, so ranking leans on relevance and recency.
+ """
+ title = str(item.get("title") or "").strip()
+ source_name = str(item.get("source_name") or "").strip()
+ return _source_item(
+ item_id=str(item.get("id") or f"TM{index + 1}"),
+ source=source,
+ title=title or f"Techmeme headline {index + 1}",
+ body=title,
+ url=str(item.get("url") or ""),
+ author=source_name or None,
+ container=source_name or "Techmeme",
+ published_at=item.get("date"),
+ date_confidence=_date_confidence(item, from_date, to_date, default="low"),
+ engagement={},
+ relevance_hint=item.get("relevance", 0.5),
+ why_relevant=str(item.get("why_relevant") or ""),
+ snippet=title[:400],
+ metadata={
+ "publication": source_name,
+ },
+ )
+
+
+def _normalize_trustpilot(
+ source: str,
+ item: dict[str, Any],
+ index: int,
+ from_date: str,
+ to_date: str,
+) -> schema.SourceItem:
+ """Normalizer for Trustpilot company sentiment.
+
+ One item per company. The AI summary (already balanced positive/negative)
+ is the body. TrustScore and review count are engagement and metadata.
+ """
+ title = str(item.get("title") or "").strip()
+ name = str(item.get("name") or "").strip()
+ summary = str(item.get("summary") or "").strip()
+ body = "\n\n".join(part for part in [title, summary] if part)
+ return _source_item(
+ item_id=str(item.get("id") or f"TP{index + 1}"),
+ source=source,
+ title=title or (f"{name} on Trustpilot" if name else f"Trustpilot reviews {index + 1}"),
+ body=body,
+ url=str(item.get("url") or ""),
+ author=name or None,
+ container="Trustpilot",
+ published_at=item.get("date"),
+ date_confidence=_date_confidence(item, from_date, to_date, default="low"),
+ engagement=item.get("engagement") or {},
+ relevance_hint=item.get("relevance", 0.6),
+ why_relevant=str(item.get("why_relevant") or ""),
+ snippet=summary[:400],
+ metadata={
+ "name": name,
+ "trustScore": item.get("trustScore"),
+ "reviewCount": item.get("reviewCount"),
+ "aiSummary": summary,
+ },
+ )
+
+
def _normalize_polymarket(
source: str,
item: dict[str, Any],
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index c0809bc4..4e622a6c 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -12,6 +12,7 @@ from shutil import which
from typing import Any
from . import (
+ arxiv,
bird_x,
bluesky,
dates,
@@ -41,9 +42,11 @@ from . import (
schema,
signals,
snippet,
+ techmeme,
threads,
tiktok,
truthsocial,
+ trustpilot,
xai_x,
xiaohongshu_api,
xquik,
@@ -99,6 +102,9 @@ MOCK_AVAILABLE_SOURCES = [
"threads",
"pinterest",
"digg",
+ "arxiv",
+ "techmeme",
+ "trustpilot",
"jobs",
"linkedin",
]
@@ -147,6 +153,14 @@ def available_sources(
available.append("github")
if which("digg-pp-cli"):
available.append("digg")
+ # arXiv is default-on when its Printing Press CLI is installed (zero auth).
+ # The adapter relevance-and-recency gates so it stays quiet off-topic.
+ if which("arxiv-pp-cli"):
+ available.append("arxiv")
+ # Techmeme is default-on when its CLI is installed (zero auth; sub-second
+ # local sync before each run's first search).
+ if which("techmeme-pp-cli"):
+ available.append("techmeme")
if env.is_bluesky_available(config):
available.append("bluesky")
if env.is_truthsocial_available(config):
@@ -176,6 +190,14 @@ def available_sources(
"linkedin" in include_sources or (requested_sources and "linkedin" in requested_sources)
):
available.append("linkedin")
+ # Trustpilot: opt-in additive source via INCLUDE_SOURCES=trustpilot (same
+ # consent pattern as Perplexity/LinkedIn). Off by default -- unlike arXiv and
+ # Techmeme, which are zero-auth, it can spawn a one-time headless-Chrome WAF
+ # cookie harvest on a brand topic, so activating it is the user's choice.
+ if which("trustpilot-pp-cli") and (
+ "trustpilot" in include_sources or (requested_sources and "trustpilot" in requested_sources)
+ ):
+ available.append("trustpilot")
if requested_sources and "xiaohongshu" in requested_sources and env.is_xiaohongshu_available(config):
available.append("xiaohongshu")
if env.is_threads_available(config):
@@ -223,6 +245,9 @@ def diagnose(
external_commands = {
"yt-dlp": bool(which("yt-dlp")),
"digg-pp-cli": bool(which("digg-pp-cli")),
+ "arxiv-pp-cli": bool(which("arxiv-pp-cli")),
+ "techmeme-pp-cli": bool(which("techmeme-pp-cli")),
+ "trustpilot-pp-cli": bool(which("trustpilot-pp-cli")),
"gh": bool(which("gh")),
}
credential_destinations = {
@@ -1457,6 +1482,24 @@ def _retrieve_stream(
# _finalize_items_by_source so it runs on the items that actually
# survive dedupe rather than on top-K of the raw fanout.
return items, {}
+ if source == "arxiv":
+ result = arxiv.search_arxiv(subquery.search_query, from_date, to_date, depth=depth)
+ # Relevance keys off the stable research topic, not the per-subquery
+ # search_query, so off-topic narrowing does not let weak matches through.
+ relevance_topic = raw_topic or topic or subquery.search_query
+ return arxiv.parse_arxiv_response(result, query=relevance_topic), {}
+ if source == "techmeme":
+ result = techmeme.search_techmeme(subquery.search_query, from_date, to_date, depth=depth)
+ relevance_topic = raw_topic or topic or subquery.search_query
+ return techmeme.parse_techmeme_response(result, query=relevance_topic), {}
+ if source == "trustpilot":
+ # Brand-shape gate keys off the stable research topic, not the narrowed
+ # per-subquery search_query, so the company is detected consistently.
+ relevance_topic = raw_topic or topic or subquery.search_query
+ result = trustpilot.search_trustpilot(
+ relevance_topic, from_date, to_date, depth=depth, config=config
+ )
+ return trustpilot.parse_trustpilot_response(result, query=relevance_topic), {}
if source == "bluesky":
result = bluesky.search_bluesky(subquery.search_query, from_date, to_date, depth=depth, config=config)
return bluesky.parse_bluesky_response(result), {}
@@ -1596,6 +1639,47 @@ def _mock_stream_results(source: str, subquery: schema.SubQuery) -> tuple[list[d
"why_relevant": "Mock Digg cluster",
},
],
+ "arxiv": [
+ {
+ "id": "http://arxiv.org/abs/2606.00001v1",
+ "title": f"A Survey of {subquery.search_query}",
+ "url": "https://arxiv.org/abs/2606.00001v1",
+ "summary": f"We present a comprehensive study of {subquery.search_query} and its recent advances.",
+ "author": "Ada Lovelace et al.",
+ "authors": ["Ada Lovelace", "Alan Turing"],
+ "date": dates.get_date_range(20)[0],
+ "engagement": {},
+ "relevance": 0.86,
+ "why_relevant": "Mock arXiv paper",
+ },
+ ],
+ "techmeme": [
+ {
+ "id": "https://www.techmeme.com/260627/p1",
+ "title": f"Major development in {subquery.search_query} reshapes the industry",
+ "url": "https://www.techmeme.com/260627/p1",
+ "source_name": "techcrunch.com",
+ "date": dates.get_date_range(1)[0],
+ "engagement": {},
+ "relevance": 0.83,
+ "why_relevant": "Mock Techmeme headline",
+ },
+ ],
+ "trustpilot": [
+ {
+ "id": "example.com",
+ "title": f"{subquery.search_query}: TrustScore 3.4",
+ "url": "https://www.trustpilot.com/review/example.com",
+ "summary": f"Across recent reviews, customers were split on {subquery.search_query}: some praised support, others cited delays.",
+ "name": subquery.search_query,
+ "trustScore": 3.4,
+ "reviewCount": 128,
+ "date": dates.get_date_range(1)[0],
+ "engagement": {"reviews": 128, "trustScore": 3.4},
+ "relevance": 0.8,
+ "why_relevant": "Mock Trustpilot sentiment",
+ },
+ ],
"jobs": [
{
"id": "J1",
diff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.py
index 43538603..e2701def 100644
--- a/skills/last30days/scripts/lib/planner.py
+++ b/skills/last30days/scripts/lib/planner.py
@@ -78,6 +78,9 @@ SOURCE_CAPABILITIES = {
"truthsocial": {"discussion", "social"},
"polymarket": {"market"},
"digg": {"discussion", "social", "link"},
+ "arxiv": {"reference", "analysis", "link"},
+ "techmeme": {"discussion", "link", "reference"},
+ "trustpilot": {"reference", "company_signal", "social"},
"xiaohongshu": {"video", "video_shortform", "social"},
"github": {"discussion", "link"},
"grounding": {"web", "reference", "link"},
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index e3779c6e..b66cf23b 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -69,6 +69,9 @@ SOURCE_LABELS = {
"x": "X",
"github": "GitHub",
"digg": "Digg",
+ "arxiv": "arXiv",
+ "techmeme": "Techmeme",
+ "trustpilot": "Trustpilot",
"perplexity": "Perplexity",
"jobs": "Jobs",
}
@@ -1488,6 +1491,9 @@ _FOOTER_SOURCES: list[tuple[str, str, str, str, list[tuple[str, str]]]] = [
("truthsocial", "🇺🇸", "Truth Social", "post", [("likes", "likes"), ("reposts", "reposts")]),
("github", "🐙", "GitHub", "item", [("stars", "stars"), ("merged_prs", "merged"), ("reactions", "reactions"), ("comments", "comments")]),
("digg", "⛏️", "Digg", "cluster", [("postCount", "posts"), ("uniqueAuthors", "authors")]),
+ ("arxiv", "📄", "arXiv", "paper", []),
+ ("techmeme", "📰", "Techmeme", "headline", []),
+ ("trustpilot", "⭐", "Trustpilot", "review", [("reviews", "reviews")]),
# Jobs must appear so a scoped --hiring-signals run (jobs-only) still emits
# the LAW 5 footer; without it the footer was dropped entirely.
("jobs", "💼", "Jobs", "role", []),
@@ -1756,6 +1762,7 @@ ENGAGEMENT_DISPLAY: dict[str, list[tuple[str, str]]] = {
"github": [("stars", "stars"), ("merged_prs", "merged"), ("reactions", "react"), ("comments", "cmt")],
"perplexity": [("citations", "cite")],
"digg": [("postCount", "posts"), ("uniqueAuthors", "auth")],
+ "trustpilot": [("reviews", "reviews")],
}
diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.py
index 3fe19b99..c009e52f 100644
--- a/skills/last30days/scripts/lib/setup_wizard.py
+++ b/skills/last30days/scripts/lib/setup_wizard.py
@@ -105,6 +105,7 @@ def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = Fals
ytdlp_action = "no_homebrew"
digg_installed, digg_action, digg_stderr, digg_path = _install_digg_cli()
+ pp_sources = install_default_pp_sources()
results: Dict[str, Any] = {
"cookies_found": cookies_found,
@@ -112,6 +113,9 @@ def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = Fals
"ytdlp_action": ytdlp_action,
"digg_installed": digg_installed,
"digg_action": digg_action,
+ # Per-CLI status for the additional default-on Printing Press sources
+ # (arxiv, techmeme, trustpilot): {source: {installed, action, ...}}.
+ "pp_sources": pp_sources,
"env_written": False,
}
if ytdlp_action == "install_failed":
@@ -234,6 +238,106 @@ def _install_digg_cli() -> Tuple[bool, str, str, str]:
return False, "install_failed", stderr, ""
+# Additional default-on Printing Press sources installed the same way as Digg:
+# (engine source key, slug for `install <slug>`, binary name). These activate in
+# ``pipeline.available_sources()`` when ``shutil.which`` resolves the binary.
+# Trustpilot is intentionally NOT here: it is opt-in (INCLUDE_SOURCES=trustpilot)
+# because of its headless-Chrome cookie harvest, so auto-installing its binary
+# for a source that stays off by default would be wasted work. Opting in installs
+# it on demand via `npx ... install trustpilot --cli-only` (see CONFIGURATION.md).
+PP_DEFAULT_SOURCES: list[tuple[str, str, str]] = [
+ ("arxiv", "arxiv", "arxiv-pp-cli"),
+ ("techmeme", "techmeme", "techmeme-pp-cli"),
+]
+
+
+def _pp_bin_candidate_paths(bin_name: str) -> list[Path]:
+ """Known install locations for a Printing Press CLI binary (slug-parameterized
+ mirror of ``_digg_bin_candidate_paths``)."""
+ home = Path.home()
+ candidates: list[Path] = [home / ".local" / "bin" / bin_name]
+ gopath = os.environ.get("GOPATH")
+ if gopath:
+ candidates.append(Path(gopath) / "bin" / bin_name)
+ candidates.append(home / "go" / "bin" / bin_name)
+ if os.name == "nt":
+ local_app = os.environ.get("LOCALAPPDATA") or os.environ.get("LocalAppData")
+ if local_app:
+ candidates.append(
+ Path(local_app) / "Programs" / "PrintingPress" / "bin" / f"{bin_name}.exe"
+ )
+ return candidates
+
+
+def _pp_off_path_binary(bin_name: str) -> Optional[str]:
+ for candidate in _pp_bin_candidate_paths(bin_name):
+ if candidate.is_file() and os.access(candidate, os.X_OK):
+ return str(candidate)
+ return None
+
+
+def _install_pp_cli(slug: str, bin_name: str) -> Tuple[bool, str, str, str]:
+ """Best-effort install of a Printing Press CLI binary.
+
+ Slug-parameterized mirror of ``_install_digg_cli``: never raises, degrades
+ to recommend-only when the installer is unavailable. Returns
+ ``(engine_active, action, stderr, off_path_binary)`` with the same action
+ taxonomy: already_installed | installed | installed_off_path |
+ install_failed | no_npx.
+ """
+ on_path = shutil.which(bin_name)
+ if on_path:
+ return True, "already_installed", "", ""
+ off_path = _pp_off_path_binary(bin_name)
+ if off_path:
+ return False, "installed_off_path", "", off_path
+ if shutil.which("npx") is None:
+ return False, "no_npx", "", ""
+ try:
+ proc = subprocess.run(
+ ["npx", "-y", PRINTING_PRESS_NPM, "install", slug, "--cli-only"],
+ capture_output=True, text=True, timeout=DIGG_INSTALL_TIMEOUT,
+ )
+ except Exception as exc:
+ logger.warning("npx install %s exception: %s", slug, exc)
+ return False, "install_failed", str(exc), ""
+ if proc.returncode != 0:
+ stderr = proc.stderr or f"npx install {slug} exited {proc.returncode}"
+ logger.warning("npx install %s failed (rc=%s): %s", slug, proc.returncode, stderr)
+ return False, "install_failed", stderr, ""
+ on_path = shutil.which(bin_name)
+ if on_path:
+ return True, "installed", "", ""
+ off_path = _pp_off_path_binary(bin_name)
+ if off_path:
+ combined = (proc.stderr or "").strip()
+ if combined:
+ logger.warning("%s installed off PATH: %s", bin_name, combined)
+ return False, "installed_off_path", combined, off_path
+ stderr = proc.stderr or f"install completed but {bin_name} was not found"
+ logger.warning("npx install %s failed verification: %s", slug, stderr)
+ return False, "install_failed", stderr, ""
+
+
+def install_default_pp_sources() -> Dict[str, Dict[str, Any]]:
+ """Best-effort install of every additional default-on Printing Press source.
+
+ Returns ``{source_key: {installed, action, stderr?, path?}}`` so the wizard
+ can report per-CLI status alongside Digg without raising on any single
+ failure.
+ """
+ out: Dict[str, Dict[str, Any]] = {}
+ for source_key, slug, bin_name in PP_DEFAULT_SOURCES:
+ installed, action, stderr, off_path = _install_pp_cli(slug, bin_name)
+ entry: Dict[str, Any] = {"installed": installed, "action": action}
+ if action == "install_failed" and stderr:
+ entry["stderr"] = stderr
+ if off_path:
+ entry["path"] = off_path
+ out[source_key] = entry
+ return out
+
+
def _open_secret_append(path: Path):
"""Open ``path`` for appending as a 0o600 secret file with no readable window.
diff --git a/skills/last30days/scripts/lib/signals.py b/skills/last30days/scripts/lib/signals.py
index 81311219..d610b25c 100644
--- a/skills/last30days/scripts/lib/signals.py
+++ b/skills/last30days/scripts/lib/signals.py
@@ -13,6 +13,9 @@ SOURCE_QUALITY = {
"hackernews": 0.8,
"youtube": 0.85,
"digg": 0.85,
+ "arxiv": 0.9,
+ "techmeme": 0.85,
+ "trustpilot": 0.78,
"reddit": 0.6,
"x": 0.68,
"bluesky": 0.66,
@@ -162,6 +165,7 @@ ENGAGEMENT_WEIGHTS: dict[str, list[tuple[str, float]]] = {
"truthsocial": [("likes", 0.45), ("reposts", 0.30), ("replies", 0.25)],
"polymarket": [("volume", 0.60), ("liquidity", 0.40)],
"digg": [("postCount", 0.40), ("uniqueAuthors", 0.30), ("rank_score", 0.30)],
+ "trustpilot": [("reviews", 1.0)],
}
diff --git a/skills/last30days/scripts/lib/techmeme.py b/skills/last30days/scripts/lib/techmeme.py
new file mode 100644
index 00000000..5c5e8098
--- /dev/null
+++ b/skills/last30days/scripts/lib/techmeme.py
@@ -0,0 +1,239 @@
+"""Techmeme tech-news source for last30days.
+
+Shells out to ``techmeme-pp-cli`` (no auth) to surface current tech-news
+headlines relevant to a topic. Techmeme caches headlines locally, so the
+adapter ensures a one-time sync per run, then searches the cache.
+
+Activation gate: only available when ``techmeme-pp-cli`` is on PATH.
+``pipeline.available_sources`` checks ``shutil.which`` before including
+``techmeme``. The functions below also detect the missing-binary case.
+
+Surface choice: ``search "<topic>" --json`` (NOT ``--agent``). ``--agent``
+implies ``--compact``, which on older binaries stripped headline records to
+``{}`` (fixed upstream in printing-press-library PR #1383); ``--json`` without
+``--compact`` returns the populated ``{num, source, headline, link}`` shape on
+every binary version, so the adapter is robust regardless of the installed
+build.
+
+The search shape carries no per-item date or velocity, so headlines are dated
+to the sync time (Techmeme's cache is the current news cycle) and ranked on
+topic relevance plus source quality. Publication-name header rows (very short
+``headline`` values) are dropped.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import threading
+import time
+from datetime import datetime, timezone
+from typing import Any, Dict, List
+
+from . import log, subproc
+from .relevance import token_overlap_relevance
+
+
+CLI_BIN = "techmeme-pp-cli"
+
+DEPTH_CONFIG = {
+ "quick": 8,
+ "default": 16,
+ "deep": 30,
+}
+
+# A real story headline is a sentence; bare publication-name rows ("TechCrunch",
+# "New York Times") are section headers in the feed, not stories. Require at
+# least this many words to keep a record.
+MIN_HEADLINE_WORDS = 4
+
+SEARCH_TIMEOUT = 30
+SYNC_TIMEOUT = 40
+
+# Refresh the local cache at most once per TTL window, guarded by a lock so
+# concurrent fan-out threads do not double-sync (two processes writing the same
+# cache file). A monotonic timestamp -- not a bare bool -- so a long-lived host
+# process or multi-report fan-out re-syncs instead of serving a stale cache
+# indefinitely (headlines are dated to the sync time, so staleness would
+# misrepresent old news as current).
+_SYNC_LOCK = threading.Lock()
+_SYNC_TTL = 600.0 # seconds
+_LAST_SYNC = 0.0
+# Sentinel used by tests to force a sync regardless of the TTL window.
+_NEVER_SYNCED = float("-inf")
+
+
+def _log(msg: str) -> None:
+ log.source_log("Techmeme", msg, tty_only=False)
+
+
+def _is_available() -> bool:
+ """True when the techmeme-pp-cli binary is on PATH."""
+ return shutil.which(CLI_BIN) is not None
+
+
+def _today_iso() -> str:
+ return datetime.now(timezone.utc).date().isoformat()
+
+
+def _ensure_synced() -> None:
+ """Refresh the local headline cache at most once per TTL window.
+
+ Lock-guarded so concurrent fan-out threads do not double-sync. Best-effort:
+ a sync failure is logged and ignored (search can still run on an existing
+ cache), and the timestamp is stamped before the call so a failing sync does
+ not retry on every subquery within the window."""
+ global _LAST_SYNC
+ with _SYNC_LOCK:
+ if time.monotonic() - _LAST_SYNC < _SYNC_TTL:
+ return
+ _LAST_SYNC = time.monotonic() # stamp first: a failure does not retry
+ try:
+ subproc.run_with_timeout([CLI_BIN, "sync", "--agent"], timeout=SYNC_TIMEOUT)
+ _log("synced headline cache")
+ except (subproc.SubprocTimeout, FileNotFoundError, OSError) as exc:
+ _log(f"sync skipped: {exc}")
+
+
+def _build_search_args(topic: str) -> List[str]:
+ # --json (not --agent) avoids --compact, which blanks headline records on
+ # pre-PR-1383 binaries. Techmeme's `search` has no result-limit flag, so the
+ # depth cap is applied client-side after parsing.
+ return [CLI_BIN, "search", topic, "--json"]
+
+
+def _coerce_list(data: Any) -> List[Dict[str, Any]]:
+ """Techmeme search returns a bare JSON array; tolerate a results-wrapped
+ envelope too."""
+ if isinstance(data, list):
+ return [r for r in data if isinstance(r, dict)]
+ if isinstance(data, dict):
+ results = data.get("results")
+ if isinstance(results, list):
+ return [r for r in results if isinstance(r, dict)]
+ return []
+
+
+def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
+ """Invoke techmeme-pp-cli and return ``{"results": [...records...]}``.
+ Never raises."""
+ if not _is_available():
+ return {"results": [], "error": f"{CLI_BIN} not on PATH"}
+ try:
+ result = subproc.run_with_timeout(cmd, timeout=timeout)
+ except subproc.SubprocTimeout as exc:
+ _log(f"Timeout: {exc}")
+ return {"results": [], "error": str(exc)}
+ except FileNotFoundError as exc:
+ _log(f"Binary missing: {exc}")
+ return {"results": [], "error": str(exc)}
+ except OSError as exc:
+ _log(f"Spawn failed: {exc}")
+ return {"results": [], "error": str(exc)}
+
+ if result.returncode != 0:
+ snippet = (result.stderr or "").strip().splitlines()[:1]
+ first = snippet[0] if snippet else f"exit {result.returncode}"
+ _log(f"CLI exit {result.returncode}: {first}")
+ return {"results": [], "error": first}
+
+ stdout = result.stdout or ""
+ if not stdout.strip():
+ return {"results": []}
+ try:
+ data = json.loads(stdout)
+ except json.JSONDecodeError as exc:
+ _log(f"JSON decode failed: {exc}")
+ return {"results": [], "error": f"json decode: {exc}"}
+
+ return {"results": _coerce_list(data)}
+
+
+def search_techmeme(
+ topic: str,
+ from_date: str,
+ to_date: str,
+ depth: str = "default",
+) -> Dict[str, Any]:
+ """Search Techmeme headlines via techmeme-pp-cli.
+
+ Ensures a one-time cache sync, then searches. Returns a dict with a
+ ``results`` list of raw records. On failure, ``results`` is empty.
+ """
+ if not topic or not topic.strip():
+ return {"results": []}
+ if not _is_available():
+ return {"results": [], "error": f"{CLI_BIN} not on PATH"}
+ _ensure_synced()
+ limit = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
+ cmd = _build_search_args(topic)
+ _log(f"search '{topic}' (cap={limit})")
+ response = _run_cli(cmd, timeout=SEARCH_TIMEOUT)
+ # Techmeme returns all matches; apply the depth cap client-side.
+ records = response.get("results") or []
+ if isinstance(records, list) and len(records) > limit:
+ response["results"] = records[:limit]
+ _log(f"found {len(response.get('results') or [])} records")
+ return response
+
+
+def _is_story_headline(headline: str, source: str) -> bool:
+ """Reject bare publication-name header rows; keep sentence-shaped stories."""
+ if not headline:
+ return False
+ if len(headline.split()) < MIN_HEADLINE_WORDS:
+ return False
+ # A row whose headline is just the publication name is a header.
+ if source and headline.strip().lower() == source.strip().lower():
+ return False
+ return True
+
+
+def parse_techmeme_response(
+ response: Dict[str, Any],
+ query: str = "",
+) -> List[Dict[str, Any]]:
+ """Parse a Techmeme search envelope into normalized item dicts.
+
+ Drops publication-name header rows and records missing a link. Dates each
+ headline to today (the cache is the current news cycle) and computes a
+ token-overlap relevance hint. Returns dicts ready for
+ ``normalize._normalize_techmeme``.
+ """
+ raw = response.get("results") if isinstance(response, dict) else None
+ if not isinstance(raw, list):
+ return []
+
+ today = _today_iso()
+ items: List[Dict[str, Any]] = []
+ for i, rec in enumerate(raw):
+ if not isinstance(rec, dict):
+ continue
+ headline = " ".join(str(rec.get("headline") or "").split()).strip()
+ source_name = str(rec.get("source") or "").strip()
+ if not _is_story_headline(headline, source_name):
+ continue
+ link = str(rec.get("link") or "").strip()
+ if not link:
+ continue
+
+ rank_decay = max(0.3, 1.0 - (i * 0.03))
+ content_score = token_overlap_relevance(query, headline) if query else 0.5
+ relevance = min(1.0, 0.55 * rank_decay + 0.45 * content_score)
+
+ items.append(
+ {
+ "id": link,
+ "title": headline,
+ "url": link,
+ "source_name": source_name,
+ "date": today,
+ "engagement": {},
+ "relevance": round(relevance, 2),
+ "why_relevant": (
+ f"Techmeme headline ({source_name})" if source_name else "Techmeme headline"
+ ),
+ }
+ )
+
+ return items
diff --git a/skills/last30days/scripts/lib/trustpilot.py b/skills/last30days/scripts/lib/trustpilot.py
new file mode 100644
index 00000000..b809f28d
--- /dev/null
+++ b/skills/last30days/scripts/lib/trustpilot.py
@@ -0,0 +1,277 @@
+"""Trustpilot brand-sentiment source for last30days.
+
+Shells out to ``trustpilot-pp-cli`` to surface a company's TrustScore and
+Trustpilot's own AI review summary for brand/company topics. Trustpilot has no
+API key, but it sits behind AWS WAF: the CLI harvests an ``aws-waf-token`` via
+a one-time headless Chrome launch (~10s), then replays it over plain HTTP until
+it expires.
+
+Activation gate: only available when ``trustpilot-pp-cli`` is on PATH.
+``pipeline.available_sources`` checks ``shutil.which`` before including
+``trustpilot``.
+
+Default-on safety (three gates):
+ 1. Brand-shape gate. The CLI is invoked only when the topic resolves to a
+ company/brand -- a domain-like token, or a short (<=2-word) capitalized
+ proper noun. Generic phrases ("AI coding agents", "agent memory") and
+ longer multi-word phrases never call the CLI, so Trustpilot stays quiet --
+ and never harvests Chrome -- on non-company topics.
+ 2. Browser opt-out. Automated contexts (cron, CI, the eval harness) can set
+ ``LAST30DAYS_TRUSTPILOT_NO_BROWSER`` to disable the source entirely, so a
+ headless run never spawns the cookie harvest.
+ 3. Graceful degradation. Any CLI failure (no Chrome, expired cookie that
+ cannot re-harvest, timeout) degrades to empty results, never an error.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+from typing import Any, Dict, List, Optional
+
+from . import dates, log, subproc
+from .relevance import token_overlap_relevance
+
+
+CLI_BIN = "trustpilot-pp-cli"
+
+SEARCH_TIMEOUT = 75 # generous: a cold run may harvest a WAF cookie (~10s).
+
+NO_BROWSER_ENV = "LAST30DAYS_TRUSTPILOT_NO_BROWSER"
+
+# Domain-like token, e.g. "chownow.com", "nothing.tech".
+_DOMAIN_RE = re.compile(r"\b[a-z0-9][a-z0-9-]*\.(com|io|co|net|org|app|ai|dev|gg|tech|shop|store)\b")
+
+# Generic tokens that disqualify a short capitalized phrase from being a brand.
+_GENERIC_TOKENS = {
+ "ai", "best", "top", "vs", "review", "reviews", "guide", "tutorial",
+ "how", "what", "why", "agents", "agent", "memory", "tips", "news",
+}
+
+# Single-word programming languages, frameworks, runtimes, OSes, and dev tools.
+# A bare capitalized "Python"/"React"/"Docker" query is overwhelmingly about the
+# technology, not a company's customer reviews -- letting it through would both
+# trigger the Chrome harvest and risk surfacing an unrelated company that shares
+# the name. A user who genuinely wants the company can use its domain
+# (e.g. "docker.com"), which still passes via the domain branch.
+_TECH_TOKENS = {
+ "python", "javascript", "typescript", "java", "rust", "ruby", "php",
+ "kotlin", "scala", "golang", "swift", "elixir", "erlang", "haskell",
+ "react", "vue", "angular", "svelte", "django", "flask", "rails", "spring",
+ "node", "nodejs", "deno", "bun", "express", "nextjs", "nuxt",
+ "linux", "ubuntu", "debian", "fedora", "windows", "macos", "android",
+ "docker", "kubernetes", "k8s", "terraform", "ansible", "nginx",
+ "redis", "postgres", "postgresql", "mysql", "sqlite", "mongodb", "kafka",
+ "graphql", "webpack", "vite", "rust", "wasm",
+}
+
+
+def _log(msg: str) -> None:
+ log.source_log("Trustpilot", msg, tty_only=False)
+
+
+def _is_available() -> bool:
+ """True when the trustpilot-pp-cli binary is on PATH."""
+ return shutil.which(CLI_BIN) is not None
+
+
+def _truthy(value: Any) -> bool:
+ return str(value or "").strip().lower() in ("1", "true", "yes", "on")
+
+
+def _harvest_allowed(config: Optional[Dict[str, Any]]) -> bool:
+ """False when the browser opt-out is set (automated/headless contexts).
+
+ Reads the opt-out from the merged config AND directly from the process
+ environment. The env fallback is load-bearing: ``config`` is assembled from
+ an allowlist in ``env.get_config``, so a fallback here guarantees the
+ documented kill-switch works even when the key is not propagated into
+ config (e.g. a bare ``LAST30DAYS_TRUSTPILOT_NO_BROWSER=1`` in cron/CI).
+ """
+ if config and _truthy(config.get(NO_BROWSER_ENV)):
+ return False
+ if _truthy(os.environ.get(NO_BROWSER_ENV)):
+ return False
+ return True
+
+
+def is_brand_shaped(topic: str) -> bool:
+ """True when the topic looks like a company/brand Trustpilot can resolve.
+
+ A domain-like token always qualifies. Otherwise the topic must be a short
+ (<=2-word) capitalized proper noun with no generic tokens -- this lets
+ "ChowNow", "Nothing Phone", and "OpenAI" through while keeping "AI coding
+ agents", "agent memory", and "Golden State Warriors" out.
+ """
+ if not topic or not topic.strip():
+ return False
+ text = topic.strip()
+ if _DOMAIN_RE.search(text.lower()):
+ return True
+ words = text.split()
+ if len(words) > 2:
+ return False
+ if any(w.lower() in _GENERIC_TOKENS or w.lower() in _TECH_TOKENS for w in words):
+ return False
+ # At least one token must look like a proper noun (leading capital).
+ return any(w[:1].isupper() for w in words)
+
+
+def _company_identifier(topic: str) -> str:
+ """Pick the identifier to hand the CLI: a domain token if present, else the
+ cleaned topic string."""
+ m = _DOMAIN_RE.search(topic.lower())
+ if m:
+ return m.group(0)
+ return topic.strip()
+
+
+def _build_info_args(identifier: str) -> List[str]:
+ return [CLI_BIN, "info", identifier, "--agent"]
+
+
+def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
+ """Invoke trustpilot-pp-cli and parse the JSON object. Never raises."""
+ if not _is_available():
+ return {"error": f"{CLI_BIN} not on PATH"}
+ try:
+ result = subproc.run_with_timeout(cmd, timeout=timeout)
+ except subproc.SubprocTimeout as exc:
+ _log(f"Timeout: {exc}")
+ return {"error": str(exc)}
+ except FileNotFoundError as exc:
+ _log(f"Binary missing: {exc}")
+ return {"error": str(exc)}
+ except OSError as exc:
+ _log(f"Spawn failed: {exc}")
+ return {"error": str(exc)}
+
+ if result.returncode != 0:
+ snippet = (result.stderr or "").strip().splitlines()[:1]
+ first = snippet[0] if snippet else f"exit {result.returncode}"
+ _log(f"CLI exit {result.returncode}: {first}")
+ return {"error": first}
+
+ stdout = result.stdout or ""
+ if not stdout.strip():
+ return {}
+ try:
+ data = json.loads(stdout)
+ except json.JSONDecodeError as exc:
+ _log(f"JSON decode failed: {exc}")
+ return {"error": f"json decode: {exc}"}
+ return data if isinstance(data, dict) else {}
+
+
+def search_trustpilot(
+ topic: str,
+ from_date: str,
+ to_date: str,
+ depth: str = "default",
+ config: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+ """Look up a company's Trustpilot sentiment, gated on a brand-shaped topic.
+
+ Returns ``{"results": [info_dict]}`` for a resolved company, or
+ ``{"results": []}`` when the topic is not brand-shaped, the browser opt-out
+ is set, or the CLI fails.
+ """
+ if not is_brand_shaped(topic):
+ return {"results": []}
+ if not _is_available():
+ return {"results": [], "error": f"{CLI_BIN} not on PATH"}
+ if not _harvest_allowed(config):
+ _log("skipped: browser opt-out set")
+ return {"results": []}
+ identifier = _company_identifier(topic)
+ _log(f"info '{identifier}'")
+ data = _run_cli(_build_info_args(identifier), timeout=SEARCH_TIMEOUT)
+ if "error" in data or not data:
+ return {"results": []}
+ return {"results": [data]}
+
+
+def _coerce_float(value: Any) -> Optional[float]:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _coerce_int(value: Any) -> Optional[int]:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def parse_trustpilot_response(
+ response: Dict[str, Any],
+ query: str = "",
+) -> List[Dict[str, Any]]:
+ """Parse a Trustpilot ``info`` envelope into a single normalized item.
+
+ The AI summary is the body (it already balances positive and negative
+ sentiment). TrustScore and review count feed engagement and metadata.
+ Returns dicts ready for ``normalize._normalize_trustpilot``.
+ """
+ raw = response.get("results") if isinstance(response, dict) else None
+ if not isinstance(raw, list) or not raw:
+ return []
+ info = raw[0]
+ if not isinstance(info, dict):
+ return []
+
+ resolved_name = str(info.get("name") or info.get("displayName") or "").strip()
+ ai_summary = str(info.get("aiSummary") or info.get("summary") or "").strip()
+ trust_score = _coerce_float(info.get("trustScore") or info.get("score"))
+ review_count = _coerce_int(
+ info.get("reviewCount") or info.get("numberOfReviews") or info.get("total")
+ )
+ url = str(info.get("url") or "").strip()
+ domain = str(info.get("domain") or info.get("identifyingName") or "").strip()
+ if not url and domain:
+ url = f"https://www.trustpilot.com/review/{domain}"
+
+ # Require substantive content from the company record itself; do not
+ # fabricate an item from the query alone when the CLI returned nothing.
+ if not resolved_name and not ai_summary and trust_score is None and review_count is None:
+ return []
+
+ name = resolved_name or query.strip()
+
+ title = f"{name} on Trustpilot" if name else "Trustpilot reviews"
+ if trust_score is not None:
+ title = f"{name}: TrustScore {trust_score}" if name else title
+
+ engagement: Dict[str, float | int] = {}
+ if review_count is not None:
+ engagement["reviews"] = review_count
+ if trust_score is not None:
+ engagement["trustScore"] = trust_score
+
+ relevance = token_overlap_relevance(query, name) if (query and name) else 0.7
+
+ why = "Trustpilot brand sentiment"
+ if trust_score is not None and review_count is not None:
+ why = f"Trustpilot: TrustScore {trust_score} across {review_count} reviews"
+ elif trust_score is not None:
+ why = f"Trustpilot: TrustScore {trust_score}"
+
+ return [
+ {
+ "id": domain or name or "trustpilot",
+ "title": title,
+ "url": url,
+ "summary": ai_summary,
+ "name": name,
+ "trustScore": trust_score,
+ "reviewCount": review_count,
+ "date": dates.get_date_range(1)[0],
+ "engagement": engagement,
+ "relevance": round(min(1.0, max(0.4, relevance)), 2),
+ "why_relevant": why,
+ }
+ ]
diff --git a/skills/last30days/scripts/lib/ui.py b/skills/last30days/scripts/lib/ui.py
index 8a37afe9..0a166a0c 100644
--- a/skills/last30days/scripts/lib/ui.py
+++ b/skills/last30days/scripts/lib/ui.py
@@ -127,6 +127,9 @@ SOURCE_COMPLETION_ORDER = [
"grounding",
"xiaohongshu",
"digg",
+ "arxiv",
+ "techmeme",
+ "trustpilot",
]
SOURCE_COMPLETION_META = {
@@ -142,6 +145,9 @@ SOURCE_COMPLETION_META = {
"grounding": ("Web", "result", "results", Colors.GREEN),
"xiaohongshu": ("Xiaohongshu", "post", "posts", Colors.RED),
"digg": ("Digg", "cluster", "clusters", Colors.YELLOW),
+ "arxiv": ("arXiv", "paper", "papers", Colors.RED),
+ "techmeme": ("Techmeme", "headline", "headlines", Colors.CYAN),
+ "trustpilot": ("Trustpilot", "review", "reviews", Colors.GREEN),
}
diff --git a/tests/test_arxiv_source.py b/tests/test_arxiv_source.py
new file mode 100644
index 00000000..293f7e7e
--- /dev/null
+++ b/tests/test_arxiv_source.py
@@ -0,0 +1,167 @@
+"""Tests for the arXiv source adapter (lib/arxiv.py).
+
+Covers query construction (quoted phrase + relevance sort), the recency
+cutoff that doubles as off-topic gating, field mapping, and graceful
+degradation when the binary is absent.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+from lib import arxiv
+
+
+NOW = datetime(2026, 6, 27, tzinfo=timezone.utc)
+
+
+def _entry(title, published, summary="An abstract.", authors=("Ada Lovelace",), abs_url="https://arxiv.org/abs/2606.00001v1"):
+ return {
+ "id": "http://arxiv.org/abs/2606.00001v1",
+ "title": title,
+ "summary": summary,
+ "published": published,
+ "authors": [{"name": a} for a in authors],
+ "categories": [{"term": "cs.AI"}],
+ "links": [
+ {"rel": "alternate", "href": abs_url, "type": "text/html"},
+ {"rel": "related", "href": "https://arxiv.org/pdf/2606.00001v1", "title": "pdf"},
+ ],
+ }
+
+
+# ---- query construction ----
+
+def test_search_query_is_quoted_phrase_relevance_sorted():
+ args = arxiv._build_search_args("AI coding agents", 10)
+ joined = " ".join(args)
+ assert '--search-query' in args
+ assert 'all:"AI coding agents"' in args # quoted phrase
+ assert "--sort-by" in args and "relevance" in args # NOT submittedDate
+ assert "submittedDate" not in joined
+
+
+def test_search_query_strips_inner_quotes():
+ q = arxiv._build_search_query('say "hello" world')
+ assert q == 'all:"say hello world"'
+
+
+# ---- envelope extraction ----
+
+def test_extract_entries_handles_nested_results_envelope():
+ data = {"meta": {"source": "live"}, "results": {"entries": [{"title": "X"}]}}
+ entries = arxiv._extract_entries(data)
+ assert len(entries) == 1 and entries[0]["title"] == "X"
+
+
+# ---- happy path + field mapping ----
+
+def test_happy_path_maps_fields():
+ recent = (NOW - timedelta(days=10)).strftime("%Y-%m-%dT12:00:00Z")
+ resp = {"results": [_entry("Agent Memory as a Database", recent, authors=("A", "B"))]}
+ items = arxiv.parse_arxiv_response(resp, query="agent memory", today=NOW)
+ assert len(items) == 1
+ it = items[0]
+ assert it["title"] == "Agent Memory as a Database"
+ assert it["url"] == "https://arxiv.org/abs/2606.00001v1" # alternate, not pdf
+ assert it["date"] == (NOW - timedelta(days=10)).date().isoformat()
+ assert it["authors"] == ["A", "B"]
+ assert it["author"] == "A et al." # multi-author label
+
+
+def test_url_prefers_alternate_over_pdf():
+ recent = (NOW - timedelta(days=5)).strftime("%Y-%m-%dT12:00:00Z")
+ resp = {"results": [_entry("T", recent)]}
+ items = arxiv.parse_arxiv_response(resp, query="t", today=NOW)
+ assert "/pdf/" not in items[0]["url"]
+ assert "/abs/" in items[0]["url"]
+
+
+# ---- recency cutoff (also off-topic gating) ----
+
+def test_recency_cutoff_drops_stale_paper():
+ stale = (NOW - timedelta(days=arxiv.RECENCY_DAYS + 30)).strftime("%Y-%m-%dT12:00:00Z")
+ resp = {"results": [_entry("Old Paper", stale)]}
+ items = arxiv.parse_arxiv_response(resp, query="old paper", today=NOW)
+ assert items == []
+
+
+def test_off_topic_control_drops_via_recency():
+ # The "Golden State Warriors" keyword match is a 2017 stats paper -- the
+ # recency cutoff is what keeps arXiv quiet on non-research topics.
+ old = "2017-06-12T12:00:00Z"
+ resp = {"results": [_entry("Do Steph Curry and Klay Thompson Have Hot Hands?", old)]}
+ items = arxiv.parse_arxiv_response(resp, query="Golden State Warriors", today=NOW)
+ assert items == []
+
+
+def test_unparseable_or_missing_date_is_dropped():
+ resp = {"results": [_entry("No Date", None), _entry("Bad Date", "not-a-date")]}
+ items = arxiv.parse_arxiv_response(resp, query="x", today=NOW)
+ assert items == []
+
+
+def test_future_dated_entry_is_dropped():
+ future = (NOW + timedelta(days=5)).strftime("%Y-%m-%dT12:00:00Z")
+ resp = {"results": [_entry("Future", future)]}
+ items = arxiv.parse_arxiv_response(resp, query="future", today=NOW)
+ assert items == []
+
+
+# ---- error / degradation paths ----
+
+def test_binary_absent_returns_empty(monkeypatch):
+ monkeypatch.setattr(arxiv.shutil, "which", lambda _bin: None)
+ resp = arxiv.search_arxiv("anything", "2026-06-01", "2026-06-27")
+ assert resp["results"] == []
+ assert "error" in resp
+
+
+def test_empty_topic_returns_empty():
+ assert arxiv.search_arxiv(" ", "2026-06-01", "2026-06-27") == {"results": []}
+
+
+def test_parse_handles_non_list_results():
+ assert arxiv.parse_arxiv_response({"results": "oops"}, query="x", today=NOW) == []
+ assert arxiv.parse_arxiv_response({}, query="x", today=NOW) == []
+
+
+def test_quote_only_topic_returns_empty():
+ # A topic of only quote characters cleans to an empty phrase; don't search.
+ assert arxiv.search_arxiv('"', "2026-06-01", "2026-06-27") == {"results": []}
+
+
+def test_same_day_future_timestamp_is_kept():
+ # A paper announced later the same UTC day yields age_days == -1; the
+ # one-day grace keeps it rather than dropping it as "future".
+ later_today = NOW.replace(hour=23, minute=59).strftime("%Y-%m-%dT%H:%M:00Z")
+ resp = {"results": [_entry("Fresh paper", later_today)]}
+ items = arxiv.parse_arxiv_response(resp, query="fresh paper", today=NOW.replace(hour=1))
+ assert len(items) == 1
+
+
+class _Proc:
+ def __init__(self, rc, out, err=""):
+ self.returncode, self.stdout, self.stderr = rc, out, err
+
+
+def test_run_cli_flattens_nested_envelope(monkeypatch):
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ payload = '{"meta":{},"results":{"entries":[{"title":"X"}]}}'
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", lambda cmd, timeout: _Proc(0, payload))
+ resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
+ assert resp["results"] == [{"title": "X"}]
+
+
+def test_run_cli_nonzero_exit_returns_error(monkeypatch):
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", lambda cmd, timeout: _Proc(1, "", "boom\nmore"))
+ resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
+ assert resp["results"] == [] and "boom" in resp["error"]
+
+
+def test_run_cli_bad_json_returns_error(monkeypatch):
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", lambda cmd, timeout: _Proc(0, "not json"))
+ resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
+ assert resp["results"] == [] and "error" in resp
diff --git a/tests/test_new_sources_eval.py b/tests/test_new_sources_eval.py
new file mode 100644
index 00000000..4a6794a5
--- /dev/null
+++ b/tests/test_new_sources_eval.py
@@ -0,0 +1,134 @@
+"""Diverse-topic evaluation harness for the three default-on Printing Press
+sources (arxiv, techmeme, trustpilot).
+
+Two layers:
+
+1. Deterministic fire/quiet matrix over five diverse topics drawn from real
+ run history. Asserts each source's *gating* decision without calling any CLI
+ -- this is the part that proves "Trustpilot fires only on company topics" and
+ "arXiv stays quiet on stale/off-topic matches".
+
+2. Opt-in --live mode (set LAST30DAYS_EVAL_LIVE=1) that actually invokes the
+ installed CLIs against the same topics, prints a sample for human review, and
+ asserts the negative controls stay quiet. Skipped by default so CI stays
+ deterministic and offline.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from lib import arxiv, techmeme, trustpilot
+
+
+# Five diverse topics from real run history, with the expected fire/quiet call
+# for each source. None = "not asserted deterministically" (depends on live
+# corpus; checked only in --live mode).
+TOPICS = {
+ "AI coding agents": {"arxiv": True, "techmeme": True, "trustpilot": False},
+ "agent memory": {"arxiv": True, "techmeme": True, "trustpilot": False},
+ "Nothing Phone": {"arxiv": None, "techmeme": None, "trustpilot": True},
+ "ChowNow": {"arxiv": None, "techmeme": None, "trustpilot": True},
+ "Golden State Warriors": {"arxiv": False, "techmeme": None, "trustpilot": False},
+}
+
+NOW = datetime(2026, 6, 27, tzinfo=timezone.utc)
+
+
+# ---- Layer 1: deterministic gating matrix ----
+
[email protected]("topic,expected", [(t, e["trustpilot"]) for t, e in TOPICS.items()])
+def test_trustpilot_brand_gate_matrix(topic, expected):
+ """Trustpilot's brand-shape gate is the primary quiet-keeper."""
+ assert trustpilot.is_brand_shaped(topic) is expected
+
+
+def test_arxiv_quiet_on_offtopic_stale_match():
+ """The "Golden State Warriors" control resolves to a 2017 stats paper;
+ arXiv's recency cutoff drops it, keeping the source quiet off-topic."""
+ stale = "2017-06-12T12:00:00Z"
+ resp = {"results": [{
+ "id": "http://arxiv.org/abs/1706.03442v2",
+ "title": "Do Steph Curry and Klay Thompson Have Hot Hands?",
+ "summary": "An analysis of Golden State Warriors shooting.",
+ "published": stale,
+ "links": [{"rel": "alternate", "href": "https://arxiv.org/abs/1706.03442v2"}],
+ }]}
+ assert arxiv.parse_arxiv_response(resp, query="Golden State Warriors", today=NOW) == []
+
+
+def test_arxiv_fires_on_recent_ontopic():
+ recent = (NOW - timedelta(days=20)).strftime("%Y-%m-%dT12:00:00Z")
+ resp = {"results": [{
+ "id": "http://arxiv.org/abs/2606.1v1",
+ "title": "Is Agent Memory a Database?",
+ "summary": "Rethinking data foundations for long-term AI agent memory.",
+ "published": recent,
+ "authors": [{"name": "A"}],
+ "links": [{"rel": "alternate", "href": "https://arxiv.org/abs/2606.1v1"}],
+ }]}
+ items = arxiv.parse_arxiv_response(resp, query="agent memory", today=NOW)
+ assert len(items) == 1
+
+
+def test_techmeme_drops_header_rows_keeps_stories():
+ resp = {"results": [
+ {"num": 1, "source": "techcrunch.com", "headline": "TechCrunch", "link": "http://techcrunch.com/"},
+ {"num": 2, "source": "techcrunch.com",
+ "headline": "OpenAI ships a new coding agent for developers today",
+ "link": "https://www.techmeme.com/x"},
+ ]}
+ items = techmeme.parse_techmeme_response(resp, query="AI coding agents")
+ assert len(items) == 1
+ assert items[0]["title"].startswith("OpenAI")
+
+
+# ---- Layer 2: opt-in live exploration ----
+
+_LIVE = os.environ.get("LAST30DAYS_EVAL_LIVE", "").strip().lower() in ("1", "true", "yes")
+
+
+def _have(binary: str) -> bool:
+ return shutil.which(binary) is not None
+
+
[email protected](not _LIVE, reason="set LAST30DAYS_EVAL_LIVE=1 to run live source exploration")
+def test_live_fire_matrix(capsys):
+ """Live: run the real CLIs against the diverse topics, print samples, and
+ assert the negative controls stay quiet."""
+ fd, td = "2026-05-28", "2026-06-27"
+ lines = []
+ for topic, expected in TOPICS.items():
+ lines.append(f"\n=== {topic} ===")
+
+ if _have("arxiv-pp-cli"):
+ items = arxiv.parse_arxiv_response(
+ arxiv.search_arxiv(topic, fd, td), query=topic)
+ lines.append(f" arXiv: {len(items)} papers")
+ for it in items[:2]:
+ lines.append(f" - {it['title'][:80]}")
+ if expected["arxiv"] is False:
+ assert items == [], f"arXiv should stay quiet on {topic!r}"
+
+ if _have("techmeme-pp-cli"):
+ items = techmeme.parse_techmeme_response(
+ techmeme.search_techmeme(topic, fd, td), query=topic)
+ lines.append(f" Techmeme: {len(items)} headlines")
+ for it in items[:2]:
+ lines.append(f" - {it['title'][:80]}")
+
+ if _have("trustpilot-pp-cli"):
+ items = trustpilot.parse_trustpilot_response(
+ trustpilot.search_trustpilot(topic, fd, td), query=topic)
+ lines.append(f" Trustpilot: {len(items)} companies")
+ for it in items[:1]:
+ lines.append(f" - {it['title'][:80]}")
+ if expected["trustpilot"] is False:
+ assert items == [], f"Trustpilot should stay quiet on {topic!r}"
+
+ with capsys.disabled():
+ print("\n".join(lines))
diff --git a/tests/test_setup_wizard.py b/tests/test_setup_wizard.py
index fc3f9624..943b87fe 100644
--- a/tests/test_setup_wizard.py
+++ b/tests/test_setup_wizard.py
@@ -238,7 +238,10 @@ class TestDiggAutoInstall:
results = setup_wizard.run_auto_setup({})
- mock_subproc.assert_called_once_with(
+ # The wizard now also best-effort-installs the additional default-on
+ # Printing Press sources (arxiv/techmeme/trustpilot), so digg is one of
+ # several install calls rather than the only one.
+ mock_subproc.assert_any_call(
["npx", "-y", setup_wizard.PRINTING_PRESS_NPM, "install", "digg", "--cli-only"],
capture_output=True, text=True, timeout=setup_wizard.DIGG_INSTALL_TIMEOUT,
)
diff --git a/tests/test_setup_wizard_pp_sources.py b/tests/test_setup_wizard_pp_sources.py
new file mode 100644
index 00000000..8b7d5655
--- /dev/null
+++ b/tests/test_setup_wizard_pp_sources.py
@@ -0,0 +1,93 @@
+"""Tests for setup-wizard auto-install of the default-on Printing Press sources
+(arxiv, techmeme, trustpilot) -- lib/setup_wizard.py."""
+
+from __future__ import annotations
+
+import pytest
+
+from lib import setup_wizard as sw
+
+
+def no_off_path(monkeypatch):
+ # Default: no binary present on disk in known dirs.
+ monkeypatch.setattr(sw, "_pp_off_path_binary", lambda bin_name: None)
+
+
+def test_already_installed_when_on_path(monkeypatch):
+ monkeypatch.setattr(sw.shutil, "which", lambda name: f"/usr/bin/{name}")
+ installed, action, stderr, off = sw._install_pp_cli("arxiv", "arxiv-pp-cli")
+ assert installed is True
+ assert action == "already_installed"
+
+
+def test_installed_off_path(monkeypatch, no_off_path):
+ monkeypatch.setattr(sw.shutil, "which", lambda name: None)
+ monkeypatch.setattr(sw, "_pp_off_path_binary", lambda bin_name: "/home/u/.local/bin/" + bin_name)
+ installed, action, stderr, off = sw._install_pp_cli("techmeme", "techmeme-pp-cli")
+ assert installed is False
+ assert action == "installed_off_path"
+ assert off.endswith("techmeme-pp-cli")
+
+
+def test_no_npx(monkeypatch, no_off_path):
+ monkeypatch.setattr(sw.shutil, "which", lambda name: None) # neither bin nor npx
+ installed, action, stderr, off = sw._install_pp_cli("trustpilot", "trustpilot-pp-cli")
+ assert installed is False
+ assert action == "no_npx"
+
+
+def test_install_success(monkeypatch, no_off_path):
+ # npx present; binary absent before, resolves after the install.
+ calls = {"n": 0}
+
+ def fake_which(name):
+ if name == "npx":
+ return "/usr/bin/npx"
+ if name == "arxiv-pp-cli":
+ # absent on first check, present after install
+ calls["n"] += 1
+ return None if calls["n"] == 1 else "/home/u/.local/bin/arxiv-pp-cli"
+ return None
+
+ monkeypatch.setattr(sw.shutil, "which", fake_which)
+ monkeypatch.setattr(sw.subprocess, "run",
+ lambda *a, **k: type("P", (), {"returncode": 0, "stdout": "", "stderr": ""})())
+ installed, action, stderr, off = sw._install_pp_cli("arxiv", "arxiv-pp-cli")
+ assert installed is True
+ assert action == "installed"
+
+
+def test_install_failed_nonzero_rc(monkeypatch, no_off_path):
+ def fake_which(name):
+ return "/usr/bin/npx" if name == "npx" else None
+
+ monkeypatch.setattr(sw.shutil, "which", fake_which)
+ monkeypatch.setattr(sw.subprocess, "run",
+ lambda *a, **k: type("P", (), {"returncode": 1, "stdout": "", "stderr": "boom"})())
+ installed, action, stderr, off = sw._install_pp_cli("techmeme", "techmeme-pp-cli")
+ assert installed is False
+ assert action == "install_failed"
+ assert "boom" in stderr
+
+
+def test_install_default_pp_sources_covers_default_on_pair(monkeypatch):
+ # Only the zero-auth default-on sources are auto-installed. Trustpilot is
+ # opt-in (INCLUDE_SOURCES=trustpilot) and intentionally excluded here.
+ monkeypatch.setattr(sw.shutil, "which", lambda name: f"/usr/bin/{name}")
+ out = sw.install_default_pp_sources()
+ assert set(out.keys()) == {"arxiv", "techmeme"}
+ assert "trustpilot" not in out
+ for entry in out.values():
+ assert entry["action"] == "already_installed"
+ assert entry["installed"] is True
+
+
+def test_install_is_idempotent(monkeypatch):
+ monkeypatch.setattr(sw.shutil, "which", lambda name: f"/usr/bin/{name}")
+ run_calls = []
+ monkeypatch.setattr(sw.subprocess, "run", lambda *a, **k: run_calls.append(a))
+ sw.install_default_pp_sources()
+ sw.install_default_pp_sources()
+ # All already on PATH -> npx install never invoked.
+ assert run_calls == []
diff --git a/tests/test_techmeme_source.py b/tests/test_techmeme_source.py
new file mode 100644
index 00000000..2181bf81
--- /dev/null
+++ b/tests/test_techmeme_source.py
@@ -0,0 +1,158 @@
+"""Tests for the Techmeme source adapter (lib/techmeme.py).
+
+Covers the --json (not --agent) surface choice, header-row filtering,
+field mapping, the one-time sync guard, and graceful degradation.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from lib import techmeme
+
+
[email protected](autouse=True)
+def _reset_sync_flag():
+ techmeme._LAST_SYNC = techmeme._NEVER_SYNCED
+ yield
+ techmeme._LAST_SYNC = techmeme._NEVER_SYNCED
+
+
+# ---- surface choice ----
+
+def test_search_args_use_json_not_agent():
+ args = techmeme._build_search_args("AI agents")
+ assert "--json" in args
+ # --agent implies --compact, which blanked records pre-PR-1383.
+ assert "--agent" not in args
+ assert "--compact" not in args
+ # Techmeme `search` has no result-limit flag; --max-results breaks it.
+ assert "--max-results" not in args
+ assert "search" in args and "AI agents" in args
+
+
+# ---- header-row filtering ----
+
+def test_story_headline_accepts_sentence():
+ assert techmeme._is_story_headline("OpenAI ships a new coding agent today", "techcrunch.com")
+
+
+def test_story_headline_rejects_publication_name_rows():
+ # Short, publication-name-only rows are section headers, not stories.
+ assert not techmeme._is_story_headline("TechCrunch", "techcrunch.com")
+ assert not techmeme._is_story_headline("New York Times", "nytimes.com")
+
+
+def test_parse_drops_header_rows_keeps_stories():
+ resp = {
+ "results": [
+ {"num": 1, "source": "techcrunch.com", "headline": "TechCrunch", "link": "http://techcrunch.com/"},
+ {"num": 2, "source": "techcrunch.com",
+ "headline": "Sakana AI's Fugu claims to rival frontier models",
+ "link": "https://www.techmeme.com/260627/p2"},
+ ]
+ }
+ items = techmeme.parse_techmeme_response(resp, query="AI")
+ assert len(items) == 1
+ assert items[0]["title"].startswith("Sakana AI")
+ assert items[0]["url"] == "https://www.techmeme.com/260627/p2"
+ assert items[0]["source_name"] == "techcrunch.com"
+
+
+def test_parse_drops_records_without_link():
+ resp = {"results": [{"num": 1, "source": "x.com", "headline": "A real headline sentence here", "link": ""}]}
+ assert techmeme.parse_techmeme_response(resp, query="x") == []
+
+
+# ---- relevance ranking ----
+
+def test_more_relevant_headline_ranks_higher():
+ resp = {
+ "results": [
+ {"num": 1, "source": "a.com", "headline": "Unrelated quarterly earnings report released today", "link": "https://t.co/a"},
+ {"num": 2, "source": "b.com", "headline": "New AI agent framework launches for developers", "link": "https://t.co/b"},
+ ]
+ }
+ items = techmeme.parse_techmeme_response(resp, query="AI agent framework")
+ by_url = {it["url"]: it["relevance"] for it in items}
+ assert by_url["https://t.co/b"] > by_url["https://t.co/a"]
+
+
+# ---- envelope tolerance ----
+
+def test_coerce_list_handles_bare_array_and_wrapped():
+ assert techmeme._coerce_list([{"a": 1}]) == [{"a": 1}]
+ assert techmeme._coerce_list({"results": [{"a": 1}]}) == [{"a": 1}]
+ assert techmeme._coerce_list({"nope": 1}) == []
+
+
+# ---- sync guard + degradation ----
+
+def test_sync_runs_once_per_process(monkeypatch):
+ calls = []
+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)
+ monkeypatch.setattr(techmeme.subproc, "run_with_timeout",
+ lambda cmd, timeout: calls.append(cmd) or _FakeProc())
+ techmeme._ensure_synced()
+ techmeme._ensure_synced()
+ sync_calls = [c for c in calls if "sync" in c]
+ assert len(sync_calls) == 1
+
+
+def test_sync_failure_is_swallowed_and_latched(monkeypatch):
+ """A sync that raises must not propagate, and the TTL stamp must still latch
+ so search proceeds against the existing cache."""
+ def boom(cmd, timeout):
+ raise techmeme.subproc.SubprocTimeout("sync timed out")
+ monkeypatch.setattr(techmeme.subproc, "run_with_timeout", boom)
+ techmeme._ensure_synced() # must not raise
+ assert techmeme._LAST_SYNC != techmeme._NEVER_SYNCED # latched despite failure
+
+
[email protected]("depth,cap", [("quick", 8), ("default", 16), ("deep", 30)])
+def test_depth_cap_truncates_client_side(monkeypatch, depth, cap):
+ """Techmeme `search` has no limit flag, so the depth cap is applied after
+ parsing -- regression guard for the other half of the --max-results fix."""
+ records = [
+ {"num": i, "source": "x.com", "headline": f"A real headline sentence number {i}",
+ "link": f"https://t.co/{i}"}
+ for i in range(cap + 12)
+ ]
+ monkeypatch.setattr(techmeme, "_is_available", lambda: True)
+ monkeypatch.setattr(techmeme, "_ensure_synced", lambda: None)
+ monkeypatch.setattr(techmeme, "_run_cli", lambda cmd, timeout: {"results": list(records)})
+ out = techmeme.search_techmeme("topic", "2026-06-01", "2026-06-27", depth=depth)
+ assert len(out["results"]) == cap
+
+
[email protected]("words,expected", [(3, False), (4, True)])
+def test_story_headline_word_count_boundary(words, expected):
+ headline = " ".join(["word"] * words)
+ assert techmeme._is_story_headline(headline, "x.com") is expected
+
+
+def test_story_headline_rejects_when_equal_to_source():
+ # A >=4-word headline that exactly equals its source is still a header row.
+ assert not techmeme._is_story_headline("the daily example tribune", "the daily example tribune")
+
+
+def test_binary_absent_returns_empty(monkeypatch):
+ monkeypatch.setattr(techmeme.shutil, "which", lambda _bin: None)
+ resp = techmeme.search_techmeme("anything", "2026-06-01", "2026-06-27")
+ assert resp["results"] == []
+ assert "error" in resp
+
+
+def test_empty_topic_returns_empty():
+ assert techmeme.search_techmeme(" ", "2026-06-01", "2026-06-27") == {"results": []}
+
+
+def test_parse_handles_non_list_results():
+ assert techmeme.parse_techmeme_response({"results": "oops"}, query="x") == []
+ assert techmeme.parse_techmeme_response({}, query="x") == []
+
+
+class _FakeProc:
+ returncode = 0
+ stdout = "{}"
+ stderr = ""
diff --git a/tests/test_trustpilot_source.py b/tests/test_trustpilot_source.py
new file mode 100644
index 00000000..277ad331
--- /dev/null
+++ b/tests/test_trustpilot_source.py
@@ -0,0 +1,162 @@
+"""Tests for the Trustpilot source adapter (lib/trustpilot.py).
+
+Covers the brand-shape gate (the primary quiet-keeper), the browser opt-out,
+field mapping from the info envelope, and graceful degradation.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from lib import pipeline, trustpilot
+
+
+# ---- opt-in availability gating (off by default) ----
+
+def test_not_available_by_default(monkeypatch):
+ monkeypatch.setattr(pipeline, "which", lambda name: f"/usr/bin/{name}")
+ avail = pipeline.available_sources({})
+ assert "trustpilot" not in avail # opt-in: absent without INCLUDE_SOURCES
+ # the zero-auth pair stays default-on
+ assert "arxiv" in avail and "techmeme" in avail
+
+
+def test_available_when_included(monkeypatch):
+ monkeypatch.setattr(pipeline, "which", lambda name: f"/usr/bin/{name}")
+ avail = pipeline.available_sources({"INCLUDE_SOURCES": "trustpilot"})
+ assert "trustpilot" in avail
+
+
+def test_available_when_requested(monkeypatch):
+ monkeypatch.setattr(pipeline, "which", lambda name: f"/usr/bin/{name}")
+ avail = pipeline.available_sources({}, requested_sources=["trustpilot"])
+ assert "trustpilot" in avail
+
+
+# ---- brand-shape gate ----
+
[email protected]("topic", ["ChowNow", "chownow.com", "Nothing Phone", "OpenAI", "nothing.tech"])
+def test_brand_shaped_topics_fire(topic):
+ assert trustpilot.is_brand_shaped(topic)
+
+
+ "AI coding agents", # 3 words, generic
+ "agent memory", # lowercase, generic token
+ "Golden State Warriors", # 3 words -> not company-shaped
+ "best phones", # generic + lowercase
+ "how to use claude", # generic question
+ "", # empty
+])
+def test_non_brand_topics_stay_quiet(topic):
+ assert not trustpilot.is_brand_shaped(topic)
+
+
+ "Python", "React", "Docker", "Rust", "Linux", "Swift", "Java",
+ "Kubernetes", "PostgreSQL", "Node",
+])
+def test_single_word_tech_names_are_not_brands(topic):
+ # A bare capitalized language/framework/tool name is a technology query,
+ # not a company-review intent -- it must not trigger the Trustpilot CLI.
+ assert not trustpilot.is_brand_shaped(topic)
+
+
+def test_tech_company_still_reachable_by_domain():
+ # The conservative tech-token gate does not block explicit company intent:
+ # a domain still resolves (e.g. wanting docker.com's reviews specifically).
+ assert trustpilot.is_brand_shaped("docker.com")
+
+
+def test_company_identifier_prefers_domain():
+ assert trustpilot._company_identifier("reviews of chownow.com please") == "chownow.com"
+ assert trustpilot._company_identifier("ChowNow") == "ChowNow"
+
+
+# ---- gate short-circuits the CLI (no Chrome on non-brand topics) ----
+
+def test_non_brand_topic_never_calls_cli(monkeypatch):
+ called = []
+ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
+ monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {})
+ out = trustpilot.search_trustpilot("AI coding agents", "2026-06-01", "2026-06-27")
+ assert out == {"results": []}
+ assert called == [] # CLI (and any Chrome harvest) never invoked
+
+
+# ---- browser opt-out ----
+
+def test_browser_opt_out_skips_even_for_brand(monkeypatch):
+ called = []
+ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
+ monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {})
+ config = {trustpilot.NO_BROWSER_ENV: "1"}
+ out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27", config=config)
+ assert out == {"results": []}
+ assert called == [] # opt-out prevents the harvest-prone CLI call
+
+
+def test_browser_opt_out_via_env_var_no_config(monkeypatch):
+ """The production path: the env var is set but never propagated into the
+ config dict. The os.environ fallback must still skip the harvest."""
+ called = []
+ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
+ monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {})
+ monkeypatch.setenv(trustpilot.NO_BROWSER_ENV, "1")
+ # config is None / lacks the key, mirroring env.get_config's allowlist gap.
+ out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27", config=None)
+ assert out == {"results": []}
+ assert called == []
+
+
+# ---- happy path + field mapping ----
+
+def test_happy_path_maps_info_envelope():
+ info = {
+ "name": "ChowNow",
+ "trustScore": 1.2,
+ "reviewCount": 49,
+ "aiSummary": "Most reviewers were let down: food never arriving, wrong address.",
+ "domain": "chownow.com",
+ }
+ items = trustpilot.parse_trustpilot_response({"results": [info]}, query="ChowNow")
+ assert len(items) == 1
+ it = items[0]
+ assert it["name"] == "ChowNow"
+ assert it["trustScore"] == 1.2
+ assert it["reviewCount"] == 49
+ assert "food never arriving" in it["summary"]
+ assert it["engagement"]["reviews"] == 49
+ assert it["url"].endswith("chownow.com")
+
+
+def test_search_returns_info_for_brand(monkeypatch):
+ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
+ monkeypatch.setattr(
+ trustpilot, "_run_cli",
+ lambda *a, **k: {"name": "ChowNow", "trustScore": 1.2, "reviewCount": 49, "aiSummary": "Bad."},
+ )
+ out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27")
+ assert len(out["results"]) == 1
+ assert out["results"][0]["name"] == "ChowNow"
+
+
+# ---- degradation paths ----
+
+def test_cli_error_degrades_to_empty(monkeypatch):
+ monkeypatch.setattr(trustpilot, "_is_available", lambda: True)
+ monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: {"error": "no chrome"})
+ out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27")
+ assert out == {"results": []}
+
+
+def test_binary_absent_returns_empty(monkeypatch):
+ monkeypatch.setattr(trustpilot.shutil, "which", lambda _bin: None)
+ out = trustpilot.search_trustpilot("ChowNow", "2026-06-01", "2026-06-27")
+ assert out["results"] == []
+
+
+def test_parse_handles_empty_and_malformed():
+ assert trustpilot.parse_trustpilot_response({"results": []}, query="x") == []
+ assert trustpilot.parse_trustpilot_response({}, query="x") == []
+ assert trustpilot.parse_trustpilot_response({"results": [{}]}, query="x") == []