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 dev.to as an opt-in keyless source (#1271)

Ilia Alshanetsky0c030c821c3c
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index b20b44cd..1abf70fd 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -154,6 +154,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \
| Local corpus | `--corpus <dir>` or `LAST30DAYS_CORPUS_DIRS` | private `.md`/`.txt`; `.pdf` when `pdftotext` is on PATH | yes (offline) |
| Reddit (public) | none (default free keyless path). With `SCRAPECREATORS_API_KEY`: search backfill when the free path returns fewer than 5 items by default (`LAST30DAYS_REDDIT_SC_MIN_ITEMS=<N>` changes the floor, `LAST30DAYS_REDDIT_SC_MIN_ITEMS=0` backfills only when it returns nothing); `LAST30DAYS_REDDIT_BACKEND=scrapecreators` pins SC primary with free fallback. `LAST30DAYS_REDDIT_KEYLESS_RATE` paces unauthenticated reddit.com requests (default `1` req/sec) | always on; SC knobs require `SCRAPECREATORS_API_KEY` | yes |
| Hacker News | none | always on | yes |
+| dev.to | none | **off by default**, with no traffic to dev.to unless activated. `--devto-tags=<t1,t2>` (the host infers 1-3 tags for tech topics) turns it on for that run, like `--trustpilot-domain`. `INCLUDE_SOURCES=devto` or `--search devto` turns it on without tags, running only the keyword search. Queries up to 1/2/3 tags (quick/default/deep) plus one keyword search whose hits must pass relevance, then fetches comments for the top 3 surviving articles. Comments containing link shorteners are dropped as spam. `EXCLUDE_SOURCES=devto` wins | yes (public Forem API, no key) |
| Polymarket | none | always on | yes |
| StockTwits | none | auto-on for ticker/crypto topics only (gated by symbol detection); never registered for non-financial topics | yes (public API, ~200 req/hr per IP) |
| DripStack | none | opt-in only: per run with `--search dripstack`, or persistently with `INCLUDE_SOURCES=dripstack` in `.env`. Searches premium financial newsletters and analyst writeups via a free, public search API — no key needed. Never active without the opt-in. | yes when opted in (public API, no auth) |
diff --git a/changelog.d/+devto-source.added.md b/changelog.d/+devto-source.added.md
new file mode 100644
index 00000000..cc3630c0
--- /dev/null
+++ b/changelog.d/+devto-source.added.md
@@ -0,0 +1 @@
+Added dev.to as a free, keyless source. When you research a software or developer topic, the skill infers dev.to tags and adds dev.to articles ranked by reactions and comments, with top comments from the leading articles. It stays off for other topics, and `INCLUDE_SOURCES=devto` turns it on for every run.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 5f45d45d..3b30232b 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -49,6 +49,7 @@ metadata:
- instagram
- linkedin
- hackernews
+ - devto
- polymarket
- digg
- bluesky
@@ -232,6 +233,7 @@ After the response and required citations, stop and wait unless governing instru
- Sends search queries to X/Twitter via the official X API v2 (`api.x.com`, app-only bearer from `X_BEARER_TOKEN`, sent only in the Authorization header; the engine's default X path on a Grok Bot host next to xAI's API), optional user-provided `AUTH_TOKEN`/`CT0` env vars, explicit browser-cookie opt-in (`FROM_BROWSER` or setup consent), xAI's API (`api.x.ai` by default), Xquik's API (`xquik.com` by default), or the official X API v2 via xurl CLI (OAuth2, auto-detected when installed and authenticated)
- Accepts a host-provided `--x-posts` envelope (a `.json` file of posts the hosting model fetched through its own X connector) as untrusted input: it replaces the engine's X fetch for that run, every row is validated and its citation URL rebuilt from the post id, and no X backend is called
- Sends search queries to Algolia HN Search API (`hn.algolia.com`) for Hacker News story and comment discovery (free, no auth)
+- dev.to API only on `--devto-tags`/`INCLUDE_SOURCES=devto`
- Sends search queries to Polymarket Gamma API (`gamma-api.polymarket.com`) for prediction market discovery (free, no auth)
- Runs `yt-dlp` locally for YouTube search and transcript extraction (no API key, public data)
- Sends TikTok/Instagram search, YouTube search backfill below the configured floor (default 3; `LAST30DAYS_YT_SC_MIN_ITEMS=0` means empty-only), and transcripts to ScrapeCreators (`api.scrapecreators.com`); keyed calls spend credits (10,000 free, then PAYG).
diff --git a/skills/last30days/references/research-runbook.md b/skills/last30days/references/research-runbook.md
index 65b9b266..697ca5fb 100644
--- a/skills/last30days/references/research-runbook.md
+++ b/skills/last30days/references/research-runbook.md
@@ -166,6 +166,7 @@ Before running the engine, determine every applicable targeting flag and resolve
| `--meta-ads-page={page_id}` | Step 0.5f | Name-based advertiser resolution picked the wrong company, or the brand advertises only under product-line page names. Accepts a numeric Ad Library page id or an Ad Library URL with `view_all_page_id`; a facebook.com vanity URL is not a page id. Also add `meta_ads` to `--search` |
| `--subreddits={sub1,sub2,...}` | Step 0.55 | Always — almost every topic has active Reddit communities |
| `--tiktok-hashtags={h1,h2,...}` | Step 0.55 | Always — inferred from topic |
+| `--devto-tags={t1,t2}` | Step 0.55 | Tech topics: 1-3 lowercase tags (`claudecode,ai`); enables dev.to |
| `--tiktok-creators={c1,c2,...}` | Step 0.55 | Creator / influencer / brand topics |
| `--ig-creators={c1,c2,...}` | Step 0.55 | Creator / brand topics |
| `--web-backend brave` | Step 0.45 Class 5 | **MANDATORY** for non-Latin-script topics (Hebrew, Arabic, CJK, etc.) — Brave is the only source that indexes non-English web |
@@ -603,7 +604,7 @@ Store your plan as `QUERY_PLAN_JSON` - you'll pass it to the script in the next
**On hosts with web search, pass your QUERY_PLAN_JSON via the --plan flag.** This tells the Python script to use your plan instead of its internal planner. On hosts without web search, omit `--plan` and use `--auto-resolve`.
-**IMPORTANT: Include `--x-handle={RESOLVED_HANDLE}` in the command. For comparison mode, use the single parallel comparison invocation in `comparison.md`, with outer targeting for the main entity and per-peer targeting in `--competitors-plan`. Also include `--subreddits={RESOLVED_SUBREDDITS}`, `--tiktok-hashtags={RESOLVED_HASHTAGS}`, `--tiktok-creators={RESOLVED_TIKTOK_CREATORS}`, and `--ig-creators={RESOLVED_IG_CREATORS}` from Step 0.55. Omit any flag where the value was not resolved (empty).**
+**IMPORTANT: Include `--x-handle={RESOLVED_HANDLE}` in the command. For comparison mode, use the single parallel comparison invocation in `comparison.md`, with outer targeting for the main entity and per-peer targeting in `--competitors-plan`. Also include the resolved Step 0.55 flags listed below.**
Fill `{TOPIC}` below with the parsed topic as literal data, excluding skill-mode controls and engine CLI flags. Choose a quoted heredoc delimiter that does not occur as a line in the topic. Map recognized CLI flags separately to the engine command. Never evaluate raw slash-command text or depend on a shell `$ARGUMENTS` variable.
@@ -654,6 +655,7 @@ Then add to the engine command:
- `--subreddits={RESOLVED_SUBREDDITS}` (broad/category subs, from Step 0.55)
- `--dedicated-subreddits={RESOLVED_DEDICATED_SUBREDDITS}` (entity-home subs, from Step 0.55; pulled in full + floor-exempt)
- `--tiktok-hashtags={RESOLVED_HASHTAGS}` (from Step 0.55)
+- `--devto-tags={t1,t2}` (see flag table)
- `--tiktok-creators={RESOLVED_TIKTOK_CREATORS}` (from Step 0.55)
- `--ig-creators={RESOLVED_IG_CREATORS}` (from Step 0.55)
- `--github-user={RESOLVED_GITHUB_USER}` (from Step 0.5b, person topics only)
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index e1978379..6bc00cef 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -824,6 +824,7 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument("--save-suffix", help="Suffix for saved output filename (e.g., 'gemini' → kanye-west-raw-gemini.md)")
parser.add_argument("--subreddits", help="Comma-separated broad/category subreddit names to search (e.g., SaaS,Entrepreneur)")
parser.add_argument("--dedicated-subreddits", help="Comma-separated entity-home subreddit names (e.g., Kanye,WestSubEver). Pulled in full (top+hot+new) and exempt from the relevance floor since the whole sub is the topic.")
+ parser.add_argument("--devto-tags", help="Comma-separated dev.to tags, lowercase alphanumeric (e.g., claudecode,ai)")
parser.add_argument("--tiktok-hashtags", help="Comma-separated TikTok hashtags without # (e.g., tella,screenrecording)")
parser.add_argument("--tiktok-creators", help="Comma-separated TikTok creator handles (e.g., TellaHQ,taborplace)")
parser.add_argument("--ig-creators", help="Comma-separated Instagram creator handles (e.g., tella.tv,laborstories)")
@@ -3732,6 +3733,17 @@ def _main(
requested_sources,
channels=cli_telegram_sources,
)
+ # --devto-tags activates the off-by-default dev.to source for this run
+ # (the --trustpilot-domain pattern): carried on config for the dispatch,
+ # and appended to an explicit or default --search list so it is not
+ # filtered back out. EXCLUDE_SOURCES=devto still wins in the pipeline.
+ cli_devto_tags = [
+ t.strip() for t in (args.devto_tags or "").split(",") if t.strip()
+ ]
+ if cli_devto_tags:
+ config["_devto_tags"] = cli_devto_tags
+ if requested_sources is not None and "devto" not in requested_sources:
+ requested_sources = [*requested_sources, "devto"]
# Host-fetched X envelope: validated before diagnose so a present
# envelope plans X in (available_sources) and a bad one fails closed here.
x_posts_envelope: x_envelope.Envelope | None = None
@@ -4212,6 +4224,9 @@ def _main(
# so each peer derives its own keyword from its own topic; a
# per-entity keyword can ride in the --competitors-plan entry.
entity_config.pop("_amazon_query", None)
+ # dev.to tags describe the main topic; a peer falls back to
+ # the slug of its own name instead of a rival's tags.
+ entity_config.pop("_devto_tags", None)
# An advertiser page is per-entity state by definition: left in
# place it would render one brand's ads as every peer's.
entity_config.pop("_meta_ads_page", None)
diff --git a/skills/last30days/scripts/lib/devto.py b/skills/last30days/scripts/lib/devto.py
new file mode 100644
index 00000000..61c568fa
--- /dev/null
+++ b/skills/last30days/scripts/lib/devto.py
@@ -0,0 +1,313 @@
+"""dev.to (Forem) source for last30days.
+
+Uses the public Forem API at dev.to (no key):
+
+- ``/api/articles?tag=<tag>&top=<days>`` returns the most-engaged articles for
+ a tag in the window. Precise, but only as good as the tag.
+- ``/api/articles/search?q=<term>&top=<days>`` is free-text search sorted by
+ recency. Single distinctive terms match well; multi-word queries match
+ loosely, so every search hit must pass the engine's token-overlap relevance
+ check before it is kept.
+- ``/api/comments?a_id=<id>`` returns the comment tree for an article.
+
+The source is off by default. Host-inferred tags (``--devto-tags``) turn it
+on for a run; ``INCLUDE_SOURCES=devto`` or ``--search devto`` turn it on
+without tags, in which case only the keyword search runs. An unknown tag
+returns ``[]`` with HTTP 200, so a wrong tag stays quiet instead of failing.
+"""
+
+from __future__ import annotations
+
+import datetime
+import html
+import re
+import threading
+import time
+import urllib.parse
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from concurrent.futures import TimeoutError as FuturesTimeout
+from typing import Any
+
+from . import http, log
+from .relevance import token_overlap_relevance
+
+ARTICLES_URL = "https://dev.to/api/articles"
+SEARCH_URL = "https://dev.to/api/articles/search"
+COMMENTS_URL = "https://dev.to/api/comments"
+_SEARCH_HEADERS = {"Accept": "application/vnd.forem.api-v1+json"}
+
+TAG_LIMITS = {"quick": 1, "default": 2, "deep": 3}
+SEARCH_PER_PAGE = {"quick": 10, "default": 20, "deep": 30}
+TAG_PER_PAGE = 30
+ENRICH_LIMIT = 3
+MAX_COMMENTS = 5
+# Search hits below this token-overlap score are dropped. Same bar as the
+# keyless Reddit lane: it keeps "kubernetes" hits and drops the newest-posts
+# noise a loose multi-word query ("claude code") returns.
+SEARCH_RELEVANCE_FLOOR = 0.25
+# Total wall-clock cap per request. The socket timeout alone bounds each
+# read, so a response trickling in small chunks could otherwise run on.
+REQUEST_DEADLINE_SECONDS = 20.0
+ENRICH_WAIT_SECONDS = 25.0
+
+_TAG_RE = re.compile(r"[^a-z0-9]")
+# Bot comments on dev.to ("Official Platform Update ... tr.ee/dev-to") hide
+# phishing behind link shorteners; real discussion rarely needs one.
+_SHORTENER_RE = re.compile(
+ r"\b(?:bit\.ly|tinyurl\.com|tr\.ee|shorturl\.at|t\.co|rb\.gy|cutt\.ly|is\.gd|ow\.ly|tiny\.cc)/",
+ re.IGNORECASE,
+)
+
+
+def _log(msg: str) -> None:
+ log.source_log("dev.to", msg, tty_only=False)
+
+
+def normalize_tag(value: str) -> str:
+ return _TAG_RE.sub("", (value or "").lower().lstrip("#"))
+
+
+def resolve_tags(tags: list[str] | None, depth: str = "default") -> list[str]:
+ """Normalize and dedupe host-supplied tags, capped by depth."""
+ resolved: list[str] = []
+ for tag in (normalize_tag(t) for t in (tags or [])):
+ if tag and tag not in resolved:
+ resolved.append(tag)
+ return resolved[: TAG_LIMITS.get(depth, TAG_LIMITS["default"])]
+
+
+def _window_days(from_date: str | None, to_date: str | None) -> int:
+ try:
+ start = datetime.date.fromisoformat(from_date or "")
+ end = datetime.date.fromisoformat(to_date or "") if to_date else datetime.date.today()
+ return max(1, (end - start).days)
+ except ValueError:
+ return 30
+
+
+# The pipeline calls a source once per subquery, and the tag feed does not
+# depend on the subquery, so identical URLs are fetched once per process.
+_RESPONSE_CACHE: dict[str, list[dict[str, Any]]] = {}
+_URL_LOCKS: dict[str, threading.Lock] = {}
+_LOCKS_GUARD = threading.Lock()
+
+
+def clear_cache() -> None:
+ with _LOCKS_GUARD:
+ _RESPONSE_CACHE.clear()
+ _URL_LOCKS.clear()
+
+
+def _get_list(url: str, headers: dict[str, str] | None = None) -> list[dict[str, Any]]:
+ # Concurrent subquery streams can request the same URL; the per-URL lock
+ # makes the second caller wait for the first fetch instead of repeating it.
+ with _LOCKS_GUARD:
+ lock = _URL_LOCKS.setdefault(url, threading.Lock())
+ with lock:
+ if url not in _RESPONSE_CACHE:
+ data = http.request(
+ "GET", url, headers=headers, timeout=15, retries=2,
+ deadline_monotonic=time.monotonic() + REQUEST_DEADLINE_SECONDS,
+ owned_get=True,
+ )
+ if not isinstance(data, list):
+ # Forem list endpoints always return a JSON array; anything
+ # else is a changed or error response, not "no matches".
+ raise ValueError(f"unexpected dev.to response shape: {type(data).__name__}")
+ _RESPONSE_CACHE[url] = [row for row in data if isinstance(row, dict)]
+ return [dict(row) for row in _RESPONSE_CACHE[url]]
+
+
+def _in_window(article: dict[str, Any], from_date: str | None, to_date: str | None) -> bool:
+ published = str(article.get("published_at") or "")[:10]
+ if not published:
+ return True
+ if from_date and published < from_date:
+ return False
+ if to_date and published > to_date:
+ return False
+ return True
+
+
+def _article_text(article: dict[str, Any]) -> str:
+ tags = article.get("tag_list") or []
+ if isinstance(tags, str):
+ tags = [t.strip() for t in tags.split(",")]
+ return " ".join([str(article.get("title") or ""), str(article.get("description") or ""), " ".join(tags)])
+
+
+def search_devto(
+ topic: str,
+ from_date: str | None = None,
+ to_date: str | None = None,
+ *,
+ depth: str = "default",
+ tags: list[str] | None = None,
+ search_query: str | None = None,
+) -> dict[str, Any]:
+ """Fetch tag-feed and keyword-search articles for the topic.
+
+ Returns ``{"articles": [...], "tags": [...], "errors": [...]}``. A failed
+ endpoint is recorded in ``errors`` and the other endpoint still counts.
+ """
+ days = _window_days(from_date, to_date)
+ resolved_tags = resolve_tags(tags, depth)
+ articles: dict[int, dict[str, Any]] = {}
+ errors: list[str] = []
+
+ for tag in resolved_tags:
+ url = f"{ARTICLES_URL}?{urllib.parse.urlencode({'tag': tag, 'top': days, 'per_page': TAG_PER_PAGE})}"
+ try:
+ rows = _get_list(url)
+ except Exception as exc:
+ errors.append(f"tag {tag}: {exc}")
+ _log(f"tag feed failed for '{tag}': {exc}")
+ continue
+ kept = 0
+ for row in rows:
+ if row.get("id") is not None and _in_window(row, from_date, to_date):
+ row.setdefault("_devto_match", f"tag:{tag}")
+ articles.setdefault(row["id"], row)
+ kept += 1
+ _log(f"tag '{tag}': {kept} articles in window")
+
+ # Planner queries quote phrases for engines with phrase syntax; Forem
+ # search treats the quotes as literal characters.
+ query = (search_query or topic or "").replace('"', " ").strip()
+ query = " ".join(query.split())
+ if query:
+ params = {"q": query, "top": days, "per_page": SEARCH_PER_PAGE.get(depth, SEARCH_PER_PAGE["default"])}
+ url = f"{SEARCH_URL}?{urllib.parse.urlencode(params)}"
+ try:
+ rows = _get_list(url, headers=_SEARCH_HEADERS)
+ except Exception as exc:
+ errors.append(f"search: {exc}")
+ _log(f"search failed for '{query}': {exc}")
+ rows = []
+ kept = dropped = 0
+ for row in rows:
+ if row.get("id") is None or not _in_window(row, from_date, to_date):
+ continue
+ if token_overlap_relevance(topic or query, _article_text(row)) < SEARCH_RELEVANCE_FLOOR:
+ dropped += 1
+ continue
+ row.setdefault("_devto_match", "search")
+ articles.setdefault(row["id"], row)
+ kept += 1
+ _log(f"search '{query}': kept {kept}, dropped {dropped} off-topic")
+
+ result: dict[str, Any] = {"articles": list(articles.values()), "tags": resolved_tags, "errors": errors}
+ attempted = len(resolved_tags) + (1 if query else 0)
+ if attempted and len(errors) == attempted:
+ # Every endpoint failed: surface it so the run reports a source
+ # failure instead of a quiet empty result.
+ result["error"] = "; ".join(errors)
+ return result
+
+
+def parse_devto_response(response: dict[str, Any], query: str = "") -> list[dict[str, Any]]:
+ """Map Forem articles to engine item dicts (the HN item shape)."""
+ items: list[dict[str, Any]] = []
+ for article in response.get("articles") or []:
+ reactions = int(article.get("public_reactions_count") or article.get("positive_reactions_count") or 0)
+ comments = int(article.get("comments_count") or 0)
+ user = article.get("user") or {}
+ content_score = token_overlap_relevance(query, _article_text(article)) if query else 0.5
+ relevance = min(1.0, 0.7 * content_score + min(0.3, (reactions + comments) / 100))
+ tags = article.get("tag_list") or []
+ if isinstance(tags, str):
+ tags = [t.strip() for t in tags.split(",") if t.strip()]
+ items.append({
+ "id": str(article.get("id")),
+ "title": str(article.get("title") or "").strip(),
+ "url": str(article.get("url") or ""),
+ "author": str(user.get("username") or user.get("name") or ""),
+ "date": str(article.get("published_at") or "")[:10] or None,
+ "text": str(article.get("description") or "").strip(),
+ "engagement": {"reactions": reactions, "comments": comments},
+ "relevance": round(relevance, 2),
+ "why_relevant": f"dev.to article ({article.get('_devto_match', 'match')})",
+ "metadata": {
+ "tags": tags,
+ "reading_time_minutes": article.get("reading_time_minutes"),
+ "ai_disclosure_level": article.get("ai_disclosure_level"),
+ "match": article.get("_devto_match"),
+ },
+ })
+ return items
+
+
+def _strip_html(text: str) -> str:
+ text = re.sub(r"<(br|/p)\s*/?>", "\n", text or "", flags=re.IGNORECASE)
+ text = re.sub(r"<[^>]+>", "", text)
+ return html.unescape(text).strip()
+
+
+def _fetch_comments(article_id: str) -> list[dict[str, Any]]:
+ url = f"{COMMENTS_URL}?{urllib.parse.urlencode({'a_id': article_id})}"
+ try:
+ rows = _get_list(url)
+ except Exception as exc:
+ _log(f"comments failed for article {article_id}: {exc}")
+ return []
+ comments = []
+ for row in rows:
+ body_html = str(row.get("body_html") or "")
+ text = _strip_html(body_html)
+ # Check the raw HTML too: a shortener can hide in an href.
+ if not text or _SHORTENER_RE.search(html.unescape(body_html)):
+ continue
+ user = row.get("user") or {}
+ comments.append({
+ "author": str(user.get("username") or user.get("name") or ""),
+ "text": text[:300] + "..." if len(text) > 300 else text,
+ # The comments API exposes no like count; direct replies are the
+ # only engagement signal it returns.
+ "replies": len(row.get("children") or []),
+ "ai_disclosure_level": row.get("ai_disclosure_level"),
+ })
+ comments.sort(key=lambda c: c["replies"], reverse=True)
+ return comments[:MAX_COMMENTS]
+
+
+def enrich_source_items(items: list[Any], top_k: int = ENRICH_LIMIT) -> list[Any]:
+ """Attach top comments to the first ``top_k`` ranked SourceItems with comments.
+
+ Runs from ``_finalize_items_by_source`` so the comment calls land on the
+ articles that survived relevance pruning and dedupe, not on high-engagement
+ tag-feed articles the ranking later drops.
+ """
+ from .normalize import _remap_comments
+
+ targets = []
+ for item in items:
+ if len(targets) >= top_k:
+ break
+ if getattr(item, "source", None) != "devto":
+ continue
+ if (item.metadata or {}).get("top_comments"):
+ continue
+ if not (item.engagement or {}).get("comments"):
+ continue
+ targets.append(item)
+ if not targets:
+ return items
+ executor = ThreadPoolExecutor(max_workers=len(targets))
+ futures = {http.submit_with_context(executor, _fetch_comments, item.item_id): item for item in targets}
+ try:
+ for future in as_completed(futures, timeout=ENRICH_WAIT_SECONDS):
+ item = futures[future]
+ item.metadata["top_comments"] = _remap_comments(
+ future.result(),
+ score_keys=("replies",),
+ excerpt_keys=("text", "excerpt"),
+ preserve_absent_score=True,
+ )
+ except FuturesTimeout:
+ _log("comment enrichment hit its time limit; keeping the comments that arrived")
+ finally:
+ # Never block report finalization on a straggling comment fetch.
+ executor.shutdown(wait=False, cancel_futures=True)
+ attached = sum(1 for item in targets if item.metadata.get("top_comments"))
+ _log(f"attached comments to {attached} of {len(targets)} top articles")
+ return items
diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.py
index 9aac1ef3..0ea81d09 100644
--- a/skills/last30days/scripts/lib/doctor.py
+++ b/skills/last30days/scripts/lib/doctor.py
@@ -161,6 +161,7 @@ SOURCE_ORDER = (
"hackernews",
"polymarket",
"github",
+ "devto",
"digg",
"techmeme",
"arxiv",
@@ -674,6 +675,17 @@ def _hackernews_record(config):
return _record(status=health.OK, requires="none (free Algolia API)")
+def _devto_record(config):
+ requires = "none (public Forem API)"
+ if "devto" in env.include_sources(config):
+ return _record(status=health.OK, requires=requires)
+ return _record(
+ status="opt-in", requires=requires,
+ fix="add devto to INCLUDE_SOURCES (or request it via --search devto)",
+ note="off by default; --devto-tags activates it for a run",
+ )
+
+
def _polymarket_record(config):
return _record(status=health.OK, requires="none (public API)")
@@ -985,6 +997,7 @@ _SOURCE_BUILDERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {
"hackernews": _hackernews_record,
"polymarket": _polymarket_record,
"github": _github_record,
+ "devto": _devto_record,
"digg": _digg_record,
"techmeme": _techmeme_record,
"arxiv": _arxiv_record,
diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.py
index ebd39148..ab8bf231 100644
--- a/skills/last30days/scripts/lib/normalize.py
+++ b/skills/last30days/scripts/lib/normalize.py
@@ -52,6 +52,7 @@ def normalize_source_items(
s, i, idx, fd, td, "IG", "Instagram reel"
),
"hackernews": _normalize_hackernews,
+ "devto": _normalize_devto,
"stocktwits": _normalize_stocktwits,
"dripstack": _normalize_dripstack,
"bluesky": lambda s, i, idx, fd, td: _normalize_microblog(
@@ -528,6 +529,41 @@ def _normalize_pinterest(
)
+def _normalize_devto(
+ source: str,
+ item: dict[str, Any],
+ index: int,
+ from_date: str,
+ to_date: str,
+) -> schema.SourceItem:
+ top_comments = _remap_comments(
+ item.get("top_comments") or [],
+ score_keys=("replies",),
+ excerpt_keys=("text", "excerpt"),
+ preserve_absent_score=True,
+ )
+ comment_text = _join_comment_excerpts(top_comments, "excerpt")
+ title = str(item.get("title") or "").strip()
+ description = str(item.get("text") or "").strip()
+ body = "\n".join(part for part in [title, description, comment_text] if part)
+ return _source_item(
+ item_id=str(item.get("id") or f"DEV{index + 1}"),
+ source=source,
+ title=title or f"dev.to article {index + 1}",
+ body=body,
+ url=str(item.get("url") or ""),
+ author=str(item.get("author") or ""),
+ container="dev.to",
+ published_at=item.get("date"),
+ date_confidence=_date_confidence(item, from_date, to_date, default="high"),
+ engagement=item.get("engagement") or {},
+ relevance_hint=item.get("relevance", 0.5),
+ why_relevant=str(item.get("why_relevant") or ""),
+ snippet=description or comment_text,
+ metadata={**(item.get("metadata") or {}), "top_comments": top_comments},
+ )
+
+
def _normalize_hackernews(
source: str,
item: dict[str, Any],
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 678cff2d..46ed4243 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -29,6 +29,7 @@ from . import (
corpus,
dates,
dedupe,
+ devto,
digg,
dripstack,
entity_extract,
@@ -98,6 +99,7 @@ DEPTH_SETTINGS = {
SEARCH_ALIAS = {
"hn": "hackernews",
+ "dev.to": "devto",
"bsky": "bluesky",
"truth": "truthsocial",
"web": "grounding",
@@ -117,7 +119,7 @@ SEARCH_ALIAS = {
# resolved per run, so every subquery would issue the identical page fetch.
MAX_SOURCE_FETCHES: dict[str, int] = {
"x": 2, "jobs": 1, "linkedin": 1, "stocktwits": 1, "trustpilot": 1, "amazon": 1,
- "telegram": 1, "meta_ads": 1,
+ "telegram": 1, "meta_ads": 1, "devto": 1,
}
# Sources whose thin result is their normal success state, so the "<3 items"
@@ -324,6 +326,7 @@ MOCK_AVAILABLE_SOURCES = [
"corpus",
"dripstack",
"telegram",
+ "devto",
]
@@ -412,6 +415,15 @@ def available_sources(
requested_sources and "dripstack" in requested_sources
):
available.append("dripstack")
+ # dev.to follows the same default-off policy. Host-inferred tags
+ # (--devto-tags) activate it for that run, the --trustpilot-domain idiom,
+ # so tech topics get it without default runs sending every topic there.
+ if (
+ "devto" in include_sources
+ or (requested_sources and "devto" in requested_sources)
+ or config.get("_devto_tags")
+ ):
+ available.append("devto")
if which("digg-pp-cli"):
available.append("digg")
# arXiv is default-on when its Printing Press CLI is installed (zero auth).
@@ -2387,6 +2399,7 @@ def run(
# Drill plans re-fetch only the sources that contributed to the matched
# cluster; the company-topic jobs injection must not widen that set.
_ensure_jobs_in_plan(plan, available, explicit=hiring_signals_mode, topic=topic)
+ _ensure_devto_in_plan(plan, available)
if "corpus" in available and plan.subqueries:
# Corpus is deterministic and user-registered, so it always gets one
# bounded stream even when a quick/LLM plan omits it. Reuse the primary
@@ -3633,6 +3646,13 @@ def _finalize_items_by_source(
else:
digg.enrich_source_items(items, top_k=3)
http.fixture_source_record(enrichment_request, schema.to_dict(items))
+ if source == "devto" and items and not mock:
+ matched, replayed = http.fixture_source_replay(enrichment_request)
+ if matched:
+ items = _merge_replayed_enrichment(items, replayed)
+ else:
+ devto.enrich_source_items(items)
+ http.fixture_source_record(enrichment_request, schema.to_dict(items))
if source == "amazon" and items and not mock:
# Attach-if-missing: review enrichment now runs at search time in
# _retrieve_stream_impl, so items arriving here should already have
@@ -3697,6 +3717,24 @@ def _apply_hiring_signal_gate(
return summary
+def _ensure_devto_in_plan(plan: schema.QueryPlan, available: list[str]) -> None:
+ """Give an activated dev.to source the primary subquery.
+
+ dev.to is off by default, so a host plan built from the default source
+ list never names it. Once tags or INCLUDE_SOURCES turn it on, activation
+ must not be a no-op.
+ """
+ if "devto" not in available or not plan.subqueries:
+ return
+ # A plan that already routes dev.to keeps its route: MAX_SOURCE_FETCHES
+ # allows one dev.to fetch, and a second route would spend it first.
+ if not any("devto" in subquery.sources for subquery in plan.subqueries):
+ plan.subqueries[0].sources.append("devto")
+ if "devto" not in plan.source_weights:
+ plan.source_weights["devto"] = 1.0
+ plan.source_weights = planner._normalize_weights(plan.source_weights)
+
+
def _ensure_jobs_in_plan(
plan: schema.QueryPlan,
available: list[str],
@@ -5852,6 +5890,17 @@ def _retrieve_stream_impl(
# hackernews.ENRICH_LIMITS per depth).
items = hackernews.enrich_top_stories(items, depth=depth)
return items, _result_outcome_artifact(source, result)
+ if source == "devto":
+ relevance_topic = raw_topic or topic or subquery.search_query
+ result = devto.search_devto(
+ relevance_topic, from_date, to_date, depth=depth,
+ tags=(config or {}).get("_devto_tags"),
+ search_query=subquery.search_query,
+ )
+ items = devto.parse_devto_response(result, query=relevance_topic)
+ # Comment enrichment is deferred to _finalize_items_by_source so it
+ # lands on the articles that survive relevance pruning.
+ return items, _result_outcome_artifact(source, result)
if source == "stocktwits":
# Pass raw_topic so symbol detection sees the full topic, not the
# narrowed per-subquery search_query (same rationale as reddit).
diff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.py
index e108c800..de03832f 100644
--- a/skills/last30days/scripts/lib/planner.py
+++ b/skills/last30days/scripts/lib/planner.py
@@ -141,6 +141,7 @@ SOURCE_CAPABILITIES = {
"tiktok": {"video", "video_shortform", "social"},
"instagram": {"video", "video_shortform", "social"},
"hackernews": {"discussion", "link"},
+ "devto": {"discussion", "link", "reference"},
"bluesky": {"discussion", "social"},
"truthsocial": {"discussion", "social"},
"polymarket": {"market"},
diff --git a/skills/last30days/scripts/lib/registers.py b/skills/last30days/scripts/lib/registers.py
index 6a964e17..79b71abb 100644
--- a/skills/last30days/scripts/lib/registers.py
+++ b/skills/last30days/scripts/lib/registers.py
@@ -89,6 +89,7 @@ _REGISTERS = {
"github": 1.60,
"hackernews": 1.35,
"arxiv": 1.30,
+ "devto": 1.25,
"grounding": 1.10,
},
),
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 936d1035..1e9d3706 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -222,6 +222,7 @@ SOURCE_LABELS = {
"instagram": "Instagram",
"grounding": "Web",
"hackernews": "Hacker News",
+ "devto": "dev.to",
"truthsocial": "Truth Social",
"linkedin": "LinkedIn",
"xiaohongshu": "Xiaohongshu",
@@ -1874,6 +1875,7 @@ def render_full(report: schema.Report, save_path: str | None = None) -> str:
"threads",
"pinterest",
"hackernews",
+ "devto",
"bluesky",
"truthsocial",
"polymarket",
@@ -2836,6 +2838,7 @@ _FOOTER_SOURCES: list[tuple[str, str, str, str, list[tuple[str, str]]]] = [
"story",
[("points", "points"), ("comments", "comments")],
),
+ ("devto", "👩‍💻", "dev.to", "article", [("reactions", "reactions"), ("comments", "comments")]),
("bluesky", "🦋", "Bluesky", "post", [("likes", "likes"), ("reposts", "reposts")]),
(
"truthsocial",
@@ -3429,6 +3432,7 @@ ENGAGEMENT_DISPLAY: dict[str, list[tuple[str, str]]] = {
"threads": [("likes", "likes"), ("replies", "re")],
"pinterest": [("saves", "saves"), ("comments", "cmt")],
"hackernews": [("points", "pts"), ("comments", "cmt")],
+ "devto": [("reactions", "react"), ("comments", "cmt")],
"bluesky": [("likes", "likes"), ("reposts", "rt"), ("replies", "re")],
"truthsocial": [("likes", "likes"), ("reposts", "rt"), ("replies", "re")],
"linkedin": [("likes", "likes"), ("comments", "cmt")],
@@ -3580,10 +3584,14 @@ _TOP_COMMENT_MIN_SCORE: dict[str, int] = {
# for every comment child (only stories carry points), so any positive
# threshold here rejects the entire source rather than filtering it.
"hackernews": 0,
+ # Replies are the only comment signal the dev.to API exposes; most top
+ # comments have none, so any positive floor would drop the whole source.
+ "devto": 0,
}
_TOP_COMMENT_VOTE_LABEL: dict[str, str] = {
"reddit": "upvotes",
"hackernews": "points",
+ "devto": "replies",
"youtube": "likes",
"tiktok": "likes",
"instagram": "likes",
diff --git a/skills/last30days/scripts/lib/rerank.py b/skills/last30days/scripts/lib/rerank.py
index 0bf31535..041e49a2 100644
--- a/skills/last30days/scripts/lib/rerank.py
+++ b/skills/last30days/scripts/lib/rerank.py
@@ -42,6 +42,7 @@ FIRST_PARTY_AUTHOR_CREDIT = 5.0
_DISCOVERY_ENGAGEMENT_FIELDS = {
"reddit": ("score", "num_comments"),
"hackernews": ("points", "comments"),
+ "devto": ("reactions", "comments"),
"digg": ("postCount", "uniqueAuthors"),
"x": ("likes", "reposts", "replies", "quotes"),
}
diff --git a/skills/last30days/scripts/lib/signals.py b/skills/last30days/scripts/lib/signals.py
index 9d929854..700554b4 100644
--- a/skills/last30days/scripts/lib/signals.py
+++ b/skills/last30days/scripts/lib/signals.py
@@ -12,6 +12,7 @@ from . import dates, relevance, schema
SOURCE_QUALITY = {
"xiaohongshu": 0.7,
"hackernews": 0.8,
+ "devto": 0.78,
"youtube": 0.85,
"digg": 0.85,
"arxiv": 0.9,
@@ -129,6 +130,7 @@ def _top_comment_score(item: schema.SourceItem) -> float:
_VOTE_LOG_REFERENCE: dict[str, float] = {
"reddit": 7.6, # ~log1p(2000)
"hackernews": 6.2, # ~log1p(500)
+ "devto": 3.0, # ~log1p(20) direct replies; the API has no comment likes
"youtube": 10.3, # ~log1p(30000)
"tiktok": 10.3, # ~log1p(30000)
"instagram": 9.2, # ~log1p(10000)
@@ -181,6 +183,7 @@ ENGAGEMENT_WEIGHTS: dict[str, list[tuple[str, float]]] = {
"x": [("likes", 0.55), ("reposts", 0.25), ("replies", 0.15), ("quotes", 0.05)],
"instagram": [("views", 0.50), ("likes", 0.30), ("comments", 0.20)],
"hackernews": [("points", 0.55), ("comments", 0.45)],
+ "devto": [("reactions", 0.60), ("comments", 0.40)],
"bluesky": [("likes", 0.40), ("reposts", 0.30), ("replies", 0.20), ("quotes", 0.10)],
"truthsocial": [("likes", 0.45), ("reposts", 0.30), ("replies", 0.25)],
"polymarket": [("volume", 0.60), ("liquidity", 0.40)],
diff --git a/skills/last30days/scripts/lib/ui.py b/skills/last30days/scripts/lib/ui.py
index c3b888e9..1be6499e 100644
--- a/skills/last30days/scripts/lib/ui.py
+++ b/skills/last30days/scripts/lib/ui.py
@@ -121,6 +121,7 @@ SOURCE_COMPLETION_ORDER = [
"tiktok",
"instagram",
"hackernews",
+ "devto",
"bluesky",
"truthsocial",
"polymarket",
@@ -141,6 +142,7 @@ SOURCE_COMPLETION_META = {
"tiktok": ("TikTok", "video", "videos", Colors.PURPLE),
"instagram": ("Instagram", "reel", "reels", Colors.PURPLE),
"hackernews": ("HN", "story", "stories", Colors.YELLOW),
+ "devto": ("dev.to", "article", "articles", Colors.GREEN),
"bluesky": ("Bluesky", "post", "posts", Colors.BLUE),
"truthsocial": ("Truth Social", "post", "posts", Colors.CYAN),
"polymarket": ("Polymarket", "market", "markets", Colors.GREEN),
diff --git a/tests/test_devto.py b/tests/test_devto.py
new file mode 100644
index 00000000..e739ebbc
--- /dev/null
+++ b/tests/test_devto.py
@@ -0,0 +1,354 @@
+"""dev.to source: tag and search retrieval, relevance gating, comments."""
+
+import urllib.parse
+
+import pytest
+
+from lib import devto, normalize, pipeline
+
+
[email protected](autouse=True)
+def _fresh_cache():
+ devto.clear_cache()
+ yield
+ devto.clear_cache()
+
+
+def _article(article_id, title, *, tags=("ai",), published="2026-10-05T12:00:00Z", reactions=5, comments=2):
+ return {
+ "id": article_id,
+ "title": title,
+ "description": f"About {title}",
+ "url": f"https://dev.to/someone/post-{article_id}",
+ "published_at": published,
+ "public_reactions_count": reactions,
+ "comments_count": comments,
+ "reading_time_minutes": 4,
+ "tag_list": list(tags),
+ "user": {"username": f"user{article_id}", "name": "Someone"},
+ "ai_disclosure_level": "not_disclosed",
+ }
+
+
+class FakeApi:
+ def __init__(self, tags=None, search=None, comments=None, fail=()):
+ self.tags = tags or {}
+ self.search = search or []
+ self.comments = comments or {}
+ self.fail = set(fail)
+ self.calls = []
+
+ def __call__(self, method, url, headers=None, **kwargs):
+ self.calls.append(url)
+ parsed = urllib.parse.urlparse(url)
+ query = dict(urllib.parse.parse_qsl(parsed.query))
+ if parsed.path == "/api/articles":
+ if "tag" in self.fail:
+ raise OSError("tag feed down")
+ return self.tags.get(query["tag"], [])
+ if parsed.path == "/api/articles/search":
+ if "search" in self.fail:
+ raise OSError("search down")
+ assert headers and headers.get("Accept") == "application/vnd.forem.api-v1+json"
+ return self.search
+ if parsed.path == "/api/comments":
+ return self.comments.get(query["a_id"], [])
+ raise AssertionError(f"unexpected URL {url}")
+
+
+def _install(monkeypatch, api):
+ monkeypatch.setattr(devto.http, "request", api)
+ return api
+
+
+def test_devto_is_off_by_default():
+ assert "devto" not in pipeline.available_sources({}, None, x_pending=False)
+
+
+def test_devto_tags_include_sources_and_search_each_activate_it():
+ assert "devto" in pipeline.available_sources({"_devto_tags": ["rust"]}, None, x_pending=False)
+ assert "devto" in pipeline.available_sources({"INCLUDE_SOURCES": "devto"}, None, x_pending=False)
+ assert "devto" in pipeline.available_sources({}, ["devto"], x_pending=False)
+
+
+def test_search_alias_maps_dev_to():
+ assert pipeline.normalize_requested_sources(["dev.to"]) == ["devto"]
+
+
+def test_resolve_tags_normalizes_dedupes_and_caps_by_depth():
+ assert devto.resolve_tags(None) == []
+ assert devto.resolve_tags(["#Rust", "async", "rust", "web dev"], depth="deep") == ["rust", "async", "webdev"]
+ assert devto.resolve_tags(["a", "b", "c"], depth="quick") == ["a"]
+
+
+def test_without_tags_only_search_runs(monkeypatch):
+ api = _install(monkeypatch, FakeApi())
+ devto.search_devto("Claude Code", "2026-09-11", "2026-10-11")
+ assert not any("tag=" in url for url in api.calls)
+ assert sum("/search" in url for url in api.calls) == 1
+
+
+def test_tag_feed_and_search_merge_dedupe_and_filter(monkeypatch):
+ shared = _article(1, "Kubernetes autoscaling in practice", tags=("kubernetes",))
+ api = _install(monkeypatch, FakeApi(
+ tags={"kubernetes": [shared, _article(2, "Kubernetes operators", tags=("kubernetes",))]},
+ search=[
+ dict(shared),
+ _article(3, "Debugging Kubernetes pods", tags=("kubernetes", "devops")),
+ _article(4, "My favourite sourdough recipe", tags=("cooking",)),
+ ],
+ ))
+ result = devto.search_devto("kubernetes", "2026-09-11", "2026-10-11", tags=["kubernetes"])
+ ids = sorted(article["id"] for article in result["articles"])
+ assert ids == [1, 2, 3]
+ assert "error" not in result
+ tag_call = next(url for url in api.calls if "tag=" in url)
+ assert "top=30" in tag_call
+
+
+def test_articles_outside_the_window_are_dropped(monkeypatch):
+ _install(monkeypatch, FakeApi(tags={"rust": [
+ _article(1, "Rust async", tags=("rust",), published="2026-10-01T00:00:00Z"),
+ _article(2, "Rust async old", tags=("rust",), published="2026-08-01T00:00:00Z"),
+ ]}))
+ result = devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"], search_query="")
+ assert [article["id"] for article in result["articles"]] == [1]
+
+
+def test_unknown_tag_and_offtopic_search_stay_quiet(monkeypatch):
+ _install(monkeypatch, FakeApi(search=[_article(9, "Weekly frontend news", tags=("webdev",))]))
+ result = devto.search_devto("Taylor Swift", "2026-09-11", "2026-10-11")
+ assert result["articles"] == []
+ assert "error" not in result
+
+
+def test_planner_quotes_are_stripped_from_the_search_query(monkeypatch):
+ api = _install(monkeypatch, FakeApi())
+ devto.search_devto("Claude Code", "2026-09-11", "2026-10-11", search_query='"Claude Code"')
+ search_call = next(url for url in api.calls if "/search" in url)
+ assert dict(urllib.parse.parse_qsl(urllib.parse.urlparse(search_call).query))["q"] == "Claude Code"
+
+
+def test_partial_failure_keeps_results_and_total_failure_reports_error(monkeypatch):
+ _install(monkeypatch, FakeApi(search=[_article(1, "Rust async runtimes", tags=("rust",))], fail={"tag"}))
+ partial = devto.search_devto("rust async", "2026-09-11", "2026-10-11", tags=["rust"])
+ assert [a["id"] for a in partial["articles"]] == [1]
+ assert "error" not in partial
+
+ devto.clear_cache()
+ _install(monkeypatch, FakeApi(fail={"tag", "search"}))
+ failed = devto.search_devto("rust async", "2026-09-11", "2026-10-11", tags=["rust"])
+ assert failed["articles"] == []
+ assert "tag feed down" in failed["error"] and "search down" in failed["error"]
+
+
+def test_identical_requests_are_fetched_once(monkeypatch):
+ api = _install(monkeypatch, FakeApi(tags={"rust": [_article(1, "Rust", tags=("rust",))]}))
+ devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"], search_query="")
+ devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"], search_query="")
+ assert sum("tag=rust" in url for url in api.calls) == 1
+
+
+def test_parse_maps_engagement_and_metadata():
+ items = devto.parse_devto_response(
+ {"articles": [_article(7, "Rust async runtimes", tags=("rust",), reactions=40, comments=9)]},
+ query="rust async",
+ )
+ item = items[0]
+ assert item["id"] == "7"
+ assert item["engagement"] == {"reactions": 40, "comments": 9}
+ assert item["date"] == "2026-10-05"
+ assert item["author"] == "user7"
+ assert item["metadata"]["ai_disclosure_level"] == "not_disclosed"
+ assert 0 < item["relevance"] <= 1
+
+
+def _source_items(articles):
+ parsed = devto.parse_devto_response({"articles": articles}, query="rust")
+ return normalize.normalize_source_items("devto", parsed, "2026-09-11", "2026-10-11")
+
+
+def test_enrichment_targets_ranked_survivors_and_drops_spam(monkeypatch):
+ api = _install(monkeypatch, FakeApi(comments={
+ "1": [
+ {"body_html": "<p>Great &amp; useful</p>", "user": {"username": "alice"}, "children": [{}, {}]},
+ {"body_html": "<p>Official update tr.ee/dev-to</p>", "user": {"username": "bot"}, "children": []},
+ ],
+ "3": [{"body_html": "<p>Nice</p>", "user": {"username": "bob"}, "children": []}],
+ }))
+ items = _source_items([
+ _article(1, "Rust one", comments=4),
+ _article(2, "Rust two", comments=0),
+ _article(3, "Rust three", comments=1),
+ _article(4, "Rust four", comments=5),
+ ])
+ devto.enrich_source_items(items, top_k=2)
+
+ first = items[0].metadata["top_comments"]
+ assert [c["excerpt"] for c in first] == ["Great & useful"]
+ assert first[0]["score"] == 2 and first[0]["author"] == "alice"
+ assert not items[1].metadata.get("top_comments")
+ assert items[2].metadata["top_comments"][0]["excerpt"] == "Nice"
+ assert not items[3].metadata.get("top_comments")
+ assert not any("a_id=2" in url or "a_id=4" in url for url in api.calls)
+
+
+def test_normalized_item_carries_comments_into_snippet_and_container():
+ parsed = devto.parse_devto_response({"articles": [_article(5, "Rust five")]}, query="rust")
+ parsed[0]["top_comments"] = [{"author": "c", "text": "Solid write-up", "replies": 1}]
+ item = normalize.normalize_source_items("devto", parsed, "2026-09-11", "2026-10-11")[0]
+ assert item.container == "dev.to"
+ assert item.metadata["top_comments"][0]["excerpt"] == "Solid write-up"
+ assert "Solid write-up" in item.body
+
+
+def _diagnose_sources(argv, config=None):
+ import json
+
+ from tests.test_diagnose_compat import FAKE_KEYLESS_CONFIG, _run_cli
+
+ rc, out = _run_cli(["--diagnose", *argv], {**FAKE_KEYLESS_CONFIG, **(config or {})})
+ assert rc == 0
+ return json.loads(out)["available_sources"]
+
+
+def test_cli_devto_tags_activate_the_source_through_diagnose():
+ assert "devto" not in _diagnose_sources([])
+ assert "devto" in _diagnose_sources(["--devto-tags", "rust"])
+
+
+def test_cli_devto_tags_survive_an_explicit_search_list():
+ assert "devto" in _diagnose_sources(["--devto-tags", "rust", "--search", "reddit"])
+
+
+def test_exclude_sources_beats_devto_tags():
+ assert "devto" not in _diagnose_sources(["--devto-tags", "rust"], {"EXCLUDE_SOURCES": "devto"})
+
+
+def test_shortener_hidden_in_href_is_dropped(monkeypatch):
+ _install(monkeypatch, FakeApi(comments={"1": [
+ {"body_html": '<p><a href="https://tr.ee/dev-to">Official platform update</a></p>', "user": {"username": "bot"}, "children": []},
+ {"body_html": "<p>Real feedback</p>", "user": {"username": "dev"}, "children": []},
+ ]}))
+ assert [c["text"] for c in devto._fetch_comments("1")] == ["Real feedback"]
+
+
+def test_concurrent_misses_fetch_a_url_once(monkeypatch):
+ import threading
+ import time
+ from concurrent.futures import ThreadPoolExecutor
+
+ calls = []
+ lock = threading.Lock()
+
+ def slow_request(method, url, headers=None, **kwargs):
+ with lock:
+ calls.append(url)
+ time.sleep(0.05)
+ return [_article(1, "Rust", tags=("rust",))]
+
+ monkeypatch.setattr(devto.http, "request", slow_request)
+ with ThreadPoolExecutor(max_workers=4) as pool:
+ results = list(pool.map(lambda _: devto._get_list("https://dev.to/api/articles?tag=rust"), range(4)))
+ assert len(calls) == 1
+ assert all(r[0]["id"] == 1 for r in results)
+
+
+def test_doctor_reports_devto_as_opt_in_until_enabled():
+ from lib import doctor
+
+ assert doctor._devto_record({})["status"] == "opt-in"
+ assert doctor._devto_record({"INCLUDE_SOURCES": "devto"})["status"] == "ok"
+
+
+def _plan(sources):
+ from lib import schema
+
+ return schema.QueryPlan(
+ intent="concept",
+ freshness_mode="balanced_recent",
+ cluster_mode="none",
+ raw_topic="claude code",
+ subqueries=[schema.SubQuery(label="primary", search_query="claude code",
+ ranking_query="q", sources=list(sources), weight=1.0)],
+ source_weights={source: 1.0 for source in sources},
+ )
+
+
+def test_activated_devto_joins_a_host_plan_that_omits_it():
+ plan = _plan(["hackernews"])
+ pipeline._ensure_devto_in_plan(plan, ["hackernews", "devto"])
+ assert "devto" in plan.subqueries[0].sources
+ assert "devto" in plan.source_weights
+
+
+def test_inactive_devto_is_not_added_to_a_plan():
+ plan = _plan(["hackernews"])
+ pipeline._ensure_devto_in_plan(plan, ["hackernews"])
+ assert plan.subqueries[0].sources == ["hackernews"]
+
+
+def test_doctor_never_live_probes_devto():
+ from lib import doctor
+
+ assert "devto" not in doctor._probeable_sources()
+
+
+def test_unexpected_response_shape_is_an_error_not_an_empty_result(monkeypatch):
+ calls = []
+
+ def object_response(method, url, headers=None, **kwargs):
+ calls.append(url)
+ return {"error": "changed"}
+
+ monkeypatch.setattr(devto.http, "request", object_response)
+ result = devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"])
+ assert result["articles"] == []
+ assert "unexpected dev.to response shape" in result["error"]
+ devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"])
+ assert len(calls) == 4
+
+
+def test_requests_carry_a_total_deadline(monkeypatch):
+ seen = {}
+
+ def capture(method, url, headers=None, **kwargs):
+ seen.update(kwargs)
+ return []
+
+ monkeypatch.setattr(devto.http, "request", capture)
+ devto._get_list("https://dev.to/api/articles?tag=rust")
+ assert seen["owned_get"] is True
+ assert seen["deadline_monotonic"] is not None
+
+
+def test_enrichment_stops_waiting_at_its_time_limit(monkeypatch):
+ import threading
+ import time
+
+ release = threading.Event()
+
+ def stuck(article_id):
+ release.wait(5)
+ return [{"author": "a", "text": "late", "replies": 0}]
+
+ monkeypatch.setattr(devto, "_fetch_comments", stuck)
+ monkeypatch.setattr(devto, "ENRICH_WAIT_SECONDS", 0.2)
+ items = _source_items([_article(1, "Rust one", comments=3)])
+ started = time.monotonic()
+ devto.enrich_source_items(items)
+ elapsed = time.monotonic() - started
+ release.set()
+ assert elapsed < 2
+ assert not items[0].metadata.get("top_comments")
+
+
+def test_existing_devto_route_is_left_alone():
+ from lib import schema
+
+ plan = _plan(["hackernews"])
+ plan.subqueries.append(schema.SubQuery(label="focused", search_query="claude code hooks",
+ ranking_query="q", sources=["devto"], weight=1.0))
+ pipeline._ensure_devto_in_plan(plan, ["hackernews", "devto"])
+ assert plan.subqueries[0].sources == ["hackernews"]
+ assert plan.subqueries[1].sources == ["devto"]