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(pipeline): --discover mode for topic-less trending discovery (#801)

Matt Van Horn298310ca34a5
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 0e4ca113..c5cc92fd 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -44,6 +44,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(
- `--save-dir <path>` - one-off output location. **Flag wins over env var.** If neither flag nor env var is set, the engine does not write a file (DB persistence is independent — see `LAST30DAYS_STORE` below).
- `--output <file>` - write the rendered output to an exact file path, using the format selected by `--emit`.
- `--json-profile {agent,raw}` - select the research JSON shape used with `--emit=json`. `agent` is the default, versioned workflow contract; `raw` preserves the full internal `Report` dump for debugging and power users. See the [JSON export reference](docs/reference/json-export.md).
+- `--discover <domain>` - topic-less trending discovery. Sweeps rising/top-week Reddit listings (category-mapped communities, with r/all as the uncategorized fallback), Hacker News front/best stories, Digg AI 1000 clusters when `digg-pp-cli` is on PATH, and broad X activity when an X backend is authenticated, then returns 5-10 engagement-velocity-ranked topics. Run without a positional topic; it is mutually exclusive with `--drill`. `--emit=json` uses the separate versioned discovery contract documented in the [JSON export reference](docs/reference/json-export.md).
- `--drill <target>` - deep follow-up over the fresh `~/.config/last30days/last-report.json` cache. Accepts a 1-based index (`--drill "cluster 3"` or `--drill "3"`) or a fuzzy cluster title/entity description. It re-fetches only sources that contributed to the matched cluster, enables their deep comment/transcript enrichment paths, merges/dedupes the evidence, and replaces the cache so drills can chain. Run it without a positional topic; if the cache is absent or expired, run a normal research pass first.
- `--save-suffix <name>` - distinguish runs of the same topic (e.g. per client: `--save-suffix=acme`).
- `--no-browser-cookies` - hard-disable browser-cookie extraction for this run, even when `FROM_BROWSER` is configured. MCP and folder-mode hosts use this for safe defaults.
diff --git a/README.md b/README.md
index 57ae8222..148011e0 100644
--- a/README.md
+++ b/README.md
@@ -93,6 +93,8 @@ The synthesis ranks by what real people actually engaged with. Social relevancy,
**To read hiring signals.** `/last30days Listen Labs --hiring-signals` - current jobs and careers pages become cited evidence for focus shifts: hiring into enterprise security, customer success, infrastructure, or product expansion. The report says what the hiring appears to signal, not what the roadmap will ship.
+**To find the topic before it peaks.** Ask `/last30days what's exploding in AI agents?` and the skill switches to discovery mode: it sweeps Reddit category listings, Hacker News front/best stories, Digg's AI 1000 feed, and X when authenticated, then returns 5-10 engagement-velocity-ranked topics. Every result includes cross-source numbers, a momentum label, and a ready-to-run `/last30days "<topic>"` follow-up.
+
**When something drops.** `/last30days Kanye West` - UK blocked his visa, Wireless Festival canceled, sponsors fled. But BULLY debuted #2 on Billboard. Fantano came back from his "Yay sabbatical" to review it (653K views). SoFi Homecoming brought out Lauryn Hill and Travis Scott for 44 songs. Polymarket: "Will Kanye tweet again?" 86% Yes. 23 Reddit threads, 17 YouTube videos, 86K upvotes.
**To compare tools.** `/last30days OpenClaw vs Hermes vs Paperclip` - "These aren't competitors, they're layers." OpenClaw is the executor (351K GitHub stars, live), Hermes is the self-improving brain (31K stars), Paperclip is the org chart (49K stars). Star counts pulled live from the GitHub API, not stale blog posts. Side-by-side table with architecture, memory, security, best-for. Per @IMJustinBrooke: "OpenClaw = Charmander, Hermes = Charizard."
@@ -320,6 +322,8 @@ Two things you'll likely want to know on day one:
**Structured output for agents and workflows.** Ask `/last30days` for machine-readable JSON to receive the stable, versioned agent profile. For direct engine use in scripts or development, run `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json`; add `--json-profile=raw` only when you need the unversioned internal `Report` dump. See the [JSON export field reference and versioning policy](docs/reference/json-export.md).
+**Topic-less discovery.** Ask `/last30days what's trending in AI agents?` to get a ranked discovery brief instead of researching a topic you already know. For direct engine use in scripts or development, run `python3 skills/last30days/scripts/last30days.py --discover "AI agents"`; add `--emit=json` for the versioned discovery contract. Discovery is mutually exclusive with a positional topic and `--drill`.
+
**Trend monitoring across runs.** The default mode produces a fresh markdown snapshot per run. To accumulate findings over time, add `--store` to persist into a SQLite database, then use [`scripts/watchlist.py`](skills/last30days/scripts/watchlist.py) for scheduled runs (with optional Slack / webhook delivery on new findings) and [`scripts/briefing.py`](skills/last30days/scripts/briefing.py) for daily / weekly digests. The full cadence pattern is in [CONFIGURATION.md](CONFIGURATION.md#trend-monitoring-store--watchlist--briefings).
Per-client wrapper scripts, custom category-peer subreddits, and the experimental beta channel for in-progress customizations are also documented in [CONFIGURATION.md](CONFIGURATION.md).
diff --git a/docs/reference/json-export.md b/docs/reference/json-export.md
index f7b6775c..136485ee 100644
--- a/docs/reference/json-export.md
+++ b/docs/reference/json-export.md
@@ -21,6 +21,16 @@ python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json -
The raw profile is intentionally unversioned and may change when pipeline internals change. It preserves the JSON serialization used before the agent profile was introduced.
+## Discovery export
+
+Discovery mode has a separate versioned contract so its topic results do not change the normal research export:
+
+```bash
+python3 skills/last30days/scripts/last30days.py --discover "AI agents" --emit=json
+```
+
+Its top level contains `schema_version` (`1.0`), `kind` (`"discovery"`), `domain`, `generated_at`, `window_days`, `source_status`, `feeds`, `results`, and `warnings`. Each ranked result contains `rank`, `topic`, `why_spiking`, `momentum` (`new-this-week` or `building`), `velocity_score`, `sources`, per-source native `engagement`, a ready-to-run `command`, and `evidence_urls`. The discovery contract follows the same versioning policy below but evolves independently of the normal agent export. `--json-profile=raw` returns the unversioned internal `DiscoveryReport` dataclass instead.
+
When `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` route a run through a configured remote API, the server does not return the local `Report` needed to build this profile. In that mode, `--json-profile=agent` exits with status 2 instead of emitting a misleading shape; use `--json-profile=raw` to retain the remote backend's existing server-response JSON contract.
## Top-level fields
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index ecbe4b2f..b8fd0d5b 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -124,6 +124,7 @@ Replace `{VERSION}` with the installed plugin version (`jq -r '.version' "$SKILL
**Placement by query type:**
- GENERAL / NEWS / PROMPTING / RECOMMENDATIONS: badge on line 1, blank line 2, `What I learned:` on line 3, then bold-lead-in paragraphs
- COMPARISON: badge on line 1, blank line 2, `# {TOPIC_A} vs {TOPIC_B} [vs {TOPIC_C}]: What the Community Says (/Last30Days)` on line 3, then Quick Verdict section
+- DISCOVERY: pass through the engine's topic-per-section discovery brief verbatim. Its ranked headings, momentum labels, evidence counters, and `/last30days "<topic>"` handoffs are engine-owned and are an explicit exception to the GENERAL synthesis template.
---
@@ -265,6 +266,7 @@ The single most common failure mode of this skill is the model reading this file
Branching rule:
+- **If the user asks what is trending, exploding, or worth covering in a domain** (for example, `/last30days what's exploding in AI agents?`): set `DISCOVERY_DOMAIN` to the domain phrase, complete the first-run wizard if needed, **and after the wizard finishes return to THIS branch with the saved `DISCOVERY_DOMAIN` (do NOT fall through to Parse User Intent / Step 0.45 / normal topic research - onboarding must not downgrade a discovery request into a topic run)**, then run `"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" --discover "${DISCOVERY_DOMAIN}" --emit=compact --save-dir="${LAST30DAYS_MEMORY_DIR}"`. Do not run Step 0.5, Step 0.55, Step 0.75, WebSearch supplements, or the normal synthesis pass; the listing sweep and topic-per-section brief are the complete discovery flow. Relay stdout verbatim. If no domain was supplied, ask one short question for the domain and wait.
- **If the user provided a topic** (e.g. `/last30days Kanye West`, `/last30days nvidia earnings`): confirm the first-run gate above passed (output `1`), then proceed to `## Step 0: First-Run Setup Wizard` (or skip it if already confirmed complete), then continue to Step 0.45 / Step 0.5 / Step 0.55 / Step 0.75 / Research Execution below. Do not skip straight to WebSearch. WebSearch is a **supplement after** the Python engine runs (see Step 2). It is **not a substitute**.
- **If the user provided no topic**: ask the user for a topic with a single short question. Do not run research. Do not run WebSearch. Wait.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 49e26302..9c86e2c3 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -376,6 +376,11 @@ def build_parser() -> argparse.ArgumentParser:
metavar="TARGET",
help="Deep follow-up on a cluster from the fresh last-report.json cache",
)
+ parser.add_argument(
+ "--discover",
+ metavar="DOMAIN",
+ help="Sweep category listings and rank 5-10 topics accelerating in a domain",
+ )
parser.add_argument("--debug", action="store_true", help="Enable HTTP debug logging")
parser.add_argument("--mock", action="store_true", help="Use mock retrieval fixtures")
parser.add_argument(
@@ -992,6 +997,126 @@ def _run_drill(
return _render_save_and_print(args, merged, None, synthesis_md, config)
+def _save_discovery_output(
+ rendered: str,
+ *,
+ domain: str,
+ emit: str,
+ save_dir: str,
+ suffix: str = "",
+) -> Path:
+ directory = Path(save_dir).expanduser().resolve()
+ directory.mkdir(parents=True, exist_ok=True)
+ extension = "json" if emit == "json" else "md"
+ suffix_part = f"-{suffix}" if suffix else ""
+ stem = f"{slugify(domain)}-discover-raw{suffix_part}"
+ date_str = datetime.datetime.now().strftime("%Y-%m-%d")
+ candidates = [directory / f"{stem}.{extension}", directory / f"{stem}-{date_str}.{extension}"]
+ candidates.extend(directory / f"{stem}-{date_str}-{index}.{extension}" for index in range(1, 100))
+ encoded = rendered.encode("utf-8")
+ for candidate in candidates:
+ try:
+ fd = os.open(candidate, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
+ except FileExistsError:
+ continue
+ with os.fdopen(fd, "wb") as output:
+ output.write(encoded)
+ return candidate
+ raise RuntimeError("Could not find a unique discovery output filename")
+
+
+def _run_discover(args: argparse.Namespace, config: dict[str, object]) -> int:
+ domain = " ".join(str(args.discover or "").split())
+ if not domain:
+ sys.stderr.write("[last30days] --discover requires a non-empty domain.\n")
+ return 2
+ if args.as_of_date:
+ sys.stderr.write(
+ "[last30days] --as-of cannot be used with --discover because discovery "
+ "sweeps current live listings.\n"
+ )
+ return 2
+ if args.emit == "html" or args.publish_html:
+ sys.stderr.write("[last30days] discovery mode does not support HTML publishing yet.\n")
+ return 2
+ if args.store:
+ sys.stderr.write("[last30days] Warning: --store is not used by discovery mode.\n")
+ if args.synthesis_file:
+ sys.stderr.write("[last30days] Warning: --synthesis-file is not used by discovery mode.\n")
+
+ requested_sources = resolve_requested_sources(args.search, config)
+ if requested_sources:
+ discovery_sources = [
+ source for source in requested_sources
+ if source in pipeline.DISCOVERY_SOURCES
+ ]
+ if not discovery_sources:
+ # A configured source boundary holds even when it leaves nothing
+ # to sweep: silently widening to all feeds would query sources
+ # the user filtered out.
+ origin = "--search" if args.search is not None else "LAST30DAYS_DEFAULT_SEARCH"
+ sys.stderr.write(
+ f"[last30days] {origin} has no discovery-capable sources "
+ f"(unsupported: {', '.join(requested_sources)}); discovery "
+ f"sweeps use: {', '.join(pipeline.DISCOVERY_SOURCES)}. Pass "
+ "--search with one of those (or clear the source filter) to "
+ "run a sweep.\n"
+ )
+ return 2
+ requested_sources = discovery_sources
+ subreddits = (
+ [value.strip().removeprefix("r/") for value in args.subreddits.split(",") if value.strip()]
+ if args.subreddits else None
+ )
+ depth = "deep" if args.deep else "quick" if args.quick else "default"
+ try:
+ report = pipeline.run_discover(
+ domain=domain,
+ config=config,
+ depth=depth,
+ requested_sources=requested_sources,
+ mock=args.mock,
+ subreddits=subreddits,
+ lookback_days=args.lookback_days or 30,
+ as_of_date=args.as_of_date,
+ )
+ except ValueError as exc:
+ sys.stderr.write(f"[last30days] {exc}\n")
+ return 2
+
+ if args.emit == "json":
+ payload = schema.to_dict(report) if args.json_profile == "raw" else schema.to_discovery_export(report)
+ rendered = json.dumps(payload, indent=2, sort_keys=True)
+ else:
+ rendered = render.render_discovery(report)
+
+ if args.output:
+ output_path = save_rendered_output(rendered, args.output)
+ sys.stderr.write(f"[last30days] Saved output to {output_path}\n")
+ if args.save_dir:
+ save_path = _save_discovery_output(
+ rendered,
+ domain=domain,
+ emit=args.emit,
+ save_dir=args.save_dir,
+ suffix=args.save_suffix or "",
+ )
+ sys.stderr.write(f"[last30days] Saved output to {save_path}\n")
+ print(rendered)
+
+ strict = str(config.get("LAST30DAYS_STRICT_EXIT") or "").strip().lower()
+ degraded = [
+ source for source, outcome in report.source_status.items()
+ if outcome.state not in _STRICT_EXIT_OK_STATES
+ ]
+ if strict in {"1", "true", "yes", "on"} and degraded:
+ sys.stderr.write(
+ f"[last30days] strict-exit: degraded sources: {', '.join(sorted(degraded))}\n"
+ )
+ return 3
+ return 0
+
+
_STRICT_EXIT_OK_STATES = {"ok", "no-results", "skipped-unconfigured"}
@@ -1362,6 +1487,18 @@ def _main(
sys.stderr.write(setup_wizard.get_setup_status_text(results) + "\n")
return 0
+ if args.discover:
+ if topic:
+ sys.stderr.write(
+ "[last30days] --discover supplies the domain and cannot be combined "
+ "with a positional topic.\n"
+ )
+ return 2
+ if args.drill:
+ sys.stderr.write("[last30days] --discover and --drill are mutually exclusive.\n")
+ return 2
+ return _run_discover(args, config)
+
if args.drill:
if topic:
sys.stderr.write(
diff --git a/skills/last30days/scripts/lib/categories.py b/skills/last30days/scripts/lib/categories.py
index f21f07c1..046b9c2c 100644
--- a/skills/last30days/scripts/lib/categories.py
+++ b/skills/last30days/scripts/lib/categories.py
@@ -23,6 +23,7 @@ before `ai_chat_model` so "gpt image 2" matches the image-gen category.
from __future__ import annotations
+import re
from typing import List, Optional, TypedDict
@@ -126,6 +127,8 @@ CATEGORY_PEERS: dict[str, _CategoryEntry] = {
},
"ai_agent_framework": {
"patterns": [
+ "ai agent",
+ "ai agents",
"agent framework",
"agentic framework",
"langchain",
@@ -264,7 +267,10 @@ def detect_category(topic: Optional[str]) -> Optional[str]:
lowered = topic.lower()
for category_id, entry in CATEGORY_PEERS.items():
for pattern in entry["patterns"]:
- if pattern in lowered:
+ # Word-boundary match: "ai agent" must not fire on "Dubai agents"
+ # or "Thai agents". Substring matching classified those as
+ # ai_agent_framework and routed discovery to LangChain subreddits.
+ if re.search(rf"(?<![a-z0-9]){re.escape(pattern)}(?![a-z0-9])", lowered):
return category_id
return None
diff --git a/skills/last30days/scripts/lib/cluster.py b/skills/last30days/scripts/lib/cluster.py
index 3360a034..d430c399 100644
--- a/skills/last30days/scripts/lib/cluster.py
+++ b/skills/last30days/scripts/lib/cluster.py
@@ -107,7 +107,11 @@ def cluster_candidates(
)
# Second pass: merge small clusters that share entities across sources.
- clusters = _merge_entity_clusters(clusters, candidates)
+ clusters = _merge_entity_clusters(
+ clusters,
+ candidates,
+ min_shared_entities=2 if "discover-mode" in plan.notes else 1,
+ )
return sorted(clusters, key=lambda cluster: cluster.score, reverse=True)
@@ -115,6 +119,8 @@ def cluster_candidates(
def _merge_entity_clusters(
clusters: list[schema.Cluster],
all_candidates: list[schema.Candidate],
+ *,
+ min_shared_entities: int = 1,
) -> list[schema.Cluster]:
"""Merge small clusters that cover the same story across different sources.
@@ -161,8 +167,9 @@ def _merge_entity_clusters(
if poly_i != poly_j:
continue
+ shared_entities = cluster_entities[i] & cluster_entities[j]
overlap = entity_extract.entity_overlap(cluster_entities[i], cluster_entities[j])
- if overlap >= 0.45:
+ if len(shared_entities) >= min_shared_entities and overlap >= 0.45:
merged_into[j] = i
if not merged_into:
diff --git a/skills/last30days/scripts/lib/hackernews.py b/skills/last30days/scripts/lib/hackernews.py
index 97164fd9..6dce6164 100644
--- a/skills/last30days/scripts/lib/hackernews.py
+++ b/skills/last30days/scripts/lib/hackernews.py
@@ -40,6 +40,8 @@ ENRICH_LIMITS = {
"deep": 10,
}
+DISCOVERY_LIMITS = {"quick": 20, "default": 40, "deep": 60}
+
def _log(msg: str):
log.source_log("HN", msg, tty_only=False)
@@ -145,6 +147,47 @@ def search_hackernews(
return response
+def fetch_discovery_listings(
+ from_date: str,
+ to_date: str,
+ depth: str = "default",
+) -> Dict[str, Any]:
+ """Fetch topic-less HN front-page and best-in-window story listings."""
+ limit = DISCOVERY_LIMITS.get(depth, DISCOVERY_LIMITS["default"])
+ from_ts = _date_to_unix(from_date)
+ to_ts = _date_to_unix(to_date) + 86400
+ from urllib.parse import urlencode
+
+ urls = [
+ f"{ALGOLIA_SEARCH_URL}?{urlencode({'tags': 'front_page', 'hitsPerPage': str(limit)})}",
+ f"{ALGOLIA_SEARCH_URL}?{urlencode({
+ 'tags': 'story',
+ 'numericFilters': f'created_at_i>{from_ts},created_at_i<{to_ts}',
+ 'hitsPerPage': str(limit),
+ })}",
+ ]
+ hits: list[dict[str, Any]] = []
+ errors: list[str] = []
+ for url in urls:
+ try:
+ response = http.request("GET", url, timeout=30)
+ hits.extend(response.get("hits") or [])
+ except Exception as exc:
+ errors.append(str(exc))
+
+ seen: set[str] = set()
+ unique_hits: list[dict[str, Any]] = []
+ for hit in hits:
+ object_id = str(hit.get("objectID") or "")
+ if not object_id or object_id in seen:
+ continue
+ seen.add(object_id)
+ unique_hits.append(hit)
+
+ items = parse_hackernews_response({"hits": unique_hits}, query="")
+ return {"items": items, "errors": errors}
+
+
_WORD_BOUNDARY_RE_CACHE: Dict[str, "re.Pattern[str]"] = {}
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index a2a3eeed..e974d387 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -3,12 +3,13 @@
from __future__ import annotations
import copy
+import math
import re
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
from shutil import which
from typing import Any
@@ -39,6 +40,7 @@ from . import (
providers,
query,
reddit,
+ reddit_listing,
reddit_public,
relevance,
rerank,
@@ -60,6 +62,11 @@ from . import (
from .cluster import cluster_candidates
from .fusion import weighted_rrf
+DISCOVERY_SOURCES = ("reddit", "hackernews", "digg", "x")
+_DISCOVERY_GENERIC_DOMAIN_TERMS = {
+ "ai", "artificial", "intelligence", "tech", "technology", "trending", "trend",
+}
+
DEPTH_SETTINGS = {
"quick": {"per_stream_limit": 6, "pool_limit": 15, "rerank_limit": 12},
"default": {"per_stream_limit": 12, "pool_limit": 40, "rerank_limit": 40},
@@ -240,6 +247,434 @@ def available_sources(
return available
+def _mock_discovery_items(
+ source: str,
+ domain: str,
+ to_date: str,
+) -> list[dict[str, Any]]:
+ """Deterministic listing fixtures for the public --mock CLI contract."""
+ labels = [
+ "Agent memory protocols",
+ "Browser-using agents",
+ "Local agent runtimes",
+ "Multi-agent orchestration",
+ "Agent security sandboxes",
+ "Voice agent latency",
+ ]
+ end = datetime.fromisoformat(to_date).date()
+ items: list[dict[str, Any]] = []
+ for index, label in enumerate(labels, start=1):
+ published = (end - timedelta(days=index)).isoformat()
+ slug = re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")
+ if source == "reddit":
+ items.append({
+ "id": f"discovery-r-{index}",
+ "title": label,
+ "url": f"https://reddit.com/r/example/comments/{slug}",
+ "subreddit": "example",
+ "date": published,
+ "engagement": {"score": 180 - index * 10, "num_comments": 30 + index},
+ "selftext": label,
+ "relevance": 0.9,
+ "why_relevant": "Mock discovery listing",
+ })
+ elif source == "hackernews":
+ items.append({
+ "id": f"discovery-hn-{index}",
+ "title": label,
+ "url": f"https://example.com/{slug}",
+ "hn_url": f"https://news.ycombinator.com/item?id={index}",
+ "author": f"example{index}",
+ "date": published,
+ "engagement": {"points": 120 - index * 8, "comments": 20 + index},
+ "relevance": 0.88,
+ "why_relevant": "Mock HN discovery listing",
+ })
+ elif source == "digg":
+ items.append({
+ "id": f"discovery-d-{index}",
+ "title": label,
+ "url": f"https://di.gg/ai/{slug}",
+ "tldr": label,
+ "date": published,
+ "engagement": {"postCount": 30 - index, "uniqueAuthors": 12 - index},
+ "relevance": 0.9,
+ "why_relevant": "Mock Digg discovery cluster",
+ })
+ elif source == "x":
+ items.append({
+ "id": f"discovery-x-{index}",
+ "text": label,
+ "url": f"https://x.com/example{index}/status/{index}",
+ "author_handle": f"example{index}",
+ "date": published,
+ "engagement": {"likes": 140 - index * 9, "reposts": 18 + index},
+ "relevance": 0.9,
+ "why_relevant": "Mock X discovery activity",
+ })
+ return items
+
+
+def _matches_discovery_domain(domain: str, text: str) -> bool:
+ """Require a distinctive domain term, not a generic token such as ``AI``."""
+ def terms(value: str) -> set[str]:
+ # Keep BOTH the surface form and the naive stem: replacing the token
+ # broke non-plurals ("bias" -> "bia", "crisis" -> "crisi") so in-domain
+ # listings stopped intersecting. The union preserves plural matching
+ # without corrupting the anchor.
+ words: set[str] = set()
+ for word in relevance.tokenize(value):
+ words.add(word)
+ if len(word) > 4 and word.endswith("s") and not word.endswith("ss"):
+ words.add(word[:-1])
+ return words
+
+ domain_terms = terms(domain)
+ anchors = domain_terms - _DISCOVERY_GENERIC_DOMAIN_TERMS
+ return bool((anchors or domain_terms) & terms(text))
+
+
+def _fetch_discovery_source(
+ source: str,
+ plan: schema.DiscoveryPlan,
+ *,
+ from_date: str,
+ to_date: str,
+ depth: str,
+ mock: bool,
+ config: dict[str, Any],
+) -> tuple[list[dict[str, Any]], str | None]:
+ if mock:
+ return _mock_discovery_items(source, plan.domain, to_date), None
+ if source == "reddit":
+ result = reddit_listing.fetch_discovery_listings(
+ plan.subreddits, depth=depth, query=plan.domain,
+ )
+ items = result.get("items") or []
+ items = [
+ item for item in items
+ if _matches_discovery_domain(
+ plan.domain,
+ f"{item.get('title') or ''} {item.get('selftext') or ''}",
+ )
+ ]
+ return items, "; ".join(result.get("errors") or []) or None
+ if source == "hackernews":
+ result = hackernews.fetch_discovery_listings(from_date, to_date, depth=depth)
+ items = result.get("items") or []
+ for item in items:
+ item["relevance"] = relevance.token_overlap_relevance(
+ plan.domain,
+ str(item.get("title") or ""),
+ )
+ # HN is a broad technology listing, so keep only domain-bearing stories.
+ items = [
+ item for item in items
+ if _matches_discovery_domain(plan.domain, str(item.get("title") or ""))
+ ]
+ errors = result.get("errors") or []
+ return items, "; ".join(errors) or None
+ if source == "digg":
+ result = digg.search_digg(plan.domain, from_date, to_date, depth=depth)
+ items = digg.parse_digg_response(result, query=plan.domain)
+ # Digg is an AI-focused broad listing, so keep only domain-bearing clusters.
+ items = [
+ item for item in items
+ if _matches_discovery_domain(plan.domain, str(item.get("title") or ""))
+ ]
+ return items, result.get("error")
+ if source == "x":
+ subquery = schema.SubQuery(
+ label="discovery-listings",
+ search_query=plan.domain,
+ ranking_query=f"What is accelerating in {plan.domain}?",
+ sources=["x"],
+ )
+ last_error = ""
+ for backend in env.x_backend_chain(config):
+ items, error = _fetch_x_backend(
+ backend, subquery, from_date, to_date, depth, config,
+ )
+ if items:
+ # Earlier failed-over backends' errors are observability, not
+ # degradation - but the producing backend's own error means
+ # these items are partial and must surface as such.
+ if last_error:
+ print(f"[x] earlier backend failed: {last_error}", file=sys.stderr)
+ return items, error or None
+ if error:
+ last_error = f"{backend}: {error}"
+ return [], last_error or None
+ raise ValueError(f"Unsupported discovery source: {source}")
+
+
+def discovery_topic_name(
+ cluster: schema.Cluster,
+ candidates: dict[str, schema.Candidate],
+ domain: str,
+) -> str:
+ """Turn a story cluster into a concise, reusable research topic."""
+ members = [candidates[cid] for cid in cluster.candidate_ids if cid in candidates]
+ leader = candidates.get(cluster.representative_ids[0]) if cluster.representative_ids else None
+ leader = leader or (members[0] if members else None)
+ if leader is None:
+ return domain
+ title = re.sub(r"^(?:show|ask|tell|launch) hn:\s*", "", leader.title, flags=re.I)
+ title = re.sub(r"^digg cluster (?:about|on)\s+", "", title, flags=re.I)
+ title = re.sub(r"\s*(?::|-)?\s*(?:discussion thread|gains momentum)$", "", title, flags=re.I)
+
+ if len(members) > 1:
+ entity_sets = [
+ entity_extract.extract_text_entities(f"{member.title} {member.snippet}")
+ for member in members
+ ]
+ shared = set.intersection(*entity_sets) if entity_sets else set()
+ shared_words = [
+ word.strip(".,:;!?()[]{}\"'")
+ for word in title.split()
+ if word.strip(".,:;!?()[]{}\"'").lower() in shared
+ ]
+ if 2 <= len(shared_words) <= 7:
+ title = " ".join(shared_words)
+
+ title = " ".join(title.split()).strip(" -:;,.\"'")
+ if len(title) > 96:
+ title = title[:93].rsplit(" ", 1)[0] + "..."
+ return title or domain
+
+
+def _discovery_engagement(
+ items: list[schema.SourceItem],
+) -> dict[str, dict[str, float | int]]:
+ totals: dict[str, dict[str, float | int]] = {}
+ for item in items:
+ bucket = totals.setdefault(item.source, {})
+ for field, value in item.engagement.items():
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ continue
+ # Rank/score/reach metadata is not additive engagement: summing
+ # Digg ranks across items fabricates a metric (agent-export uses
+ # the same counter-field rule).
+ if not schema._is_counter_field(field):
+ continue
+ bucket[field] = bucket.get(field, 0) + value
+ return {
+ source: dict(sorted(metrics.items()))
+ for source, metrics in sorted(totals.items())
+ }
+
+
+def _discovery_momentum(items: list[schema.SourceItem], to_date: str) -> str:
+ as_of = datetime.fromisoformat(to_date).date()
+ ages: list[int] = []
+ for item in items:
+ try:
+ published = datetime.fromisoformat((item.published_at or "").replace("Z", "+00:00")).date()
+ except (TypeError, ValueError):
+ continue
+ ages.append(max(0, (as_of - published).days))
+ return "new-this-week" if ages and max(ages) < 7 else "building"
+
+
+def run_discover(
+ *,
+ domain: str,
+ config: dict[str, Any],
+ depth: str = "default",
+ requested_sources: list[str] | None = None,
+ mock: bool = False,
+ subreddits: list[str] | None = None,
+ lookback_days: int = 30,
+ as_of_date: str | None = None,
+ limit: int = 10,
+) -> schema.DiscoveryReport:
+ """Sweep category listings and rank the topics gaining velocity."""
+ from_date, to_date = dates.get_date_range(lookback_days, as_of_date=as_of_date)
+ requested = normalize_requested_sources(requested_sources)
+ unsupported = sorted(set(requested or []) - set(DISCOVERY_SOURCES))
+ if unsupported:
+ raise ValueError(
+ "Discovery supports listing sources only: reddit, hackernews, digg "
+ f"(unsupported: {', '.join(unsupported)})"
+ )
+ available = list(DISCOVERY_SOURCES) if mock else [
+ source for source in available_sources(config, requested, x_pending=False)
+ if source in DISCOVERY_SOURCES
+ ]
+ if requested:
+ available = [source for source in available if source in requested]
+ plan = planner.build_discovery_plan(
+ domain,
+ available_sources=available,
+ subreddits=subreddits,
+ )
+
+ source_status: dict[str, schema.SourceOutcome] = {}
+ bundle = schema.RetrievalBundle()
+ query_plan = schema.QueryPlan(
+ intent="breaking_news",
+ freshness_mode="breaking",
+ cluster_mode="story",
+ raw_topic=plan.domain,
+ subqueries=[schema.SubQuery(
+ label="discovery-listings",
+ search_query=plan.domain,
+ ranking_query=f"What is accelerating in {plan.domain}?",
+ sources=list(plan.sources),
+ )],
+ source_weights={source: 1.0 for source in plan.sources},
+ notes=["discover-mode", "listing-sweep"],
+ )
+
+ with ThreadPoolExecutor(max_workers=len(plan.sources)) as executor:
+ futures = {
+ executor.submit(
+ _fetch_discovery_source,
+ source,
+ plan,
+ from_date=from_date,
+ to_date=to_date,
+ depth=depth,
+ mock=mock,
+ config=config,
+ ): source
+ for source in plan.sources
+ }
+ for future in as_completed(futures):
+ source = futures[future]
+ bundle.mark_attempted(source)
+ try:
+ raw_items, partial_error = future.result()
+ normalized = normalize.normalize_source_items(
+ source,
+ raw_items,
+ from_date,
+ to_date,
+ freshness_mode="breaking",
+ )
+ prepared = relevance.PreparedQuery(plan.domain)
+ normalized = signals.annotate_stream(
+ normalized,
+ prepared,
+ "breaking",
+ reference_date=to_date,
+ max_days=lookback_days,
+ )
+ normalized = dedupe.dedupe_items(normalized)
+ for item in normalized:
+ item.snippet = snippet.extract_best_snippet(item, prepared)
+ bundle.add_items("discovery-listings", source, normalized)
+ if partial_error:
+ failure_state = (
+ bird_x.classify_run_failure(partial_error)
+ if source == "x" and partial_error.startswith("bird:")
+ else http.classify_failure(message=partial_error)
+ )
+ bundle.record_failure(
+ source,
+ failure_state,
+ partial_error,
+ )
+ except Exception as exc:
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(source, state, str(exc), attempted=attempted)
+
+ for source in DISCOVERY_SOURCES:
+ if source in bundle.source_status:
+ continue
+ detail = (
+ "Source is not configured for discovery."
+ )
+ source_status[source] = schema.SourceOutcome(
+ source=source,
+ state=schema.SKIPPED_UNCONFIGURED,
+ attempted=False,
+ detail=detail,
+ fix_hint="doctor",
+ )
+ source_status.update(_finalize_source_status(bundle.source_status, bundle.items_by_source))
+
+ candidates = weighted_rrf(bundle.items_by_source_and_query, query_plan, pool_limit=80)
+ for candidate in candidates:
+ velocity = rerank.discovery_velocity_score(candidate.source_items, as_of_date=to_date)
+ candidate.final_score = min(100.0, 12.0 * math.log1p(velocity)) if velocity else 0.0
+ candidates.sort(key=lambda candidate: (-candidate.final_score, candidate.title.lower()))
+ clusters = cluster_candidates(candidates, query_plan)
+ candidate_map = {candidate.candidate_id: candidate for candidate in candidates}
+
+ ranked_clusters: list[tuple[float, schema.Cluster, list[schema.SourceItem]]] = []
+ for cluster in clusters:
+ cluster_items: list[schema.SourceItem] = []
+ for candidate_id in cluster.candidate_ids:
+ candidate = candidate_map.get(candidate_id)
+ if candidate:
+ cluster_items.extend(candidate.source_items)
+ score = rerank.discovery_velocity_score(cluster_items, as_of_date=to_date)
+ if score <= 0:
+ continue
+ ranked_clusters.append((score, cluster, cluster_items))
+ ranked_clusters.sort(key=lambda entry: (-entry[0], entry[1].title.lower()))
+
+ topic_limit = max(5, min(10, limit))
+ topics: list[schema.DiscoveryTopic] = []
+ seen_topic_names: set[str] = set()
+ for score, cluster, cluster_items in ranked_clusters:
+ name = discovery_topic_name(cluster, candidate_map, plan.domain)
+ name_key = name.casefold()
+ if name_key in seen_topic_names:
+ continue
+ seen_topic_names.add(name_key)
+ rank = len(topics) + 1
+ sources = sorted({item.source for item in cluster_items})
+ native_total = sum(rerank.discovery_engagement_total(item) for item in cluster_items)
+ source_phrase = ", ".join(sources[:-1]) + (
+ f" and {sources[-1]}" if len(sources) > 1 else (sources[0] if sources else "the listings")
+ )
+ leader = candidate_map.get(cluster.representative_ids[0]) if cluster.representative_ids else None
+ summary = (leader.snippet if leader else "") or (leader.title if leader else name)
+ why = (
+ f"{len(cluster_items)} listing item{'s' if len(cluster_items) != 1 else ''} on "
+ f"{source_phrase} generated {native_total:,.0f} native interactions. "
+ f"{summary[:220]}"
+ )
+ topics.append(schema.DiscoveryTopic(
+ rank=rank,
+ name=name,
+ why_spiking=why,
+ momentum=_discovery_momentum(cluster_items, to_date),
+ velocity_score=round(score, 2),
+ sources=sources,
+ engagement_by_source=_discovery_engagement(cluster_items),
+ command=f'/last30days "{name.replace(chr(34), chr(39))}"',
+ evidence_urls=list(dict.fromkeys(item.url for item in cluster_items if item.url))[:5],
+ ))
+ if len(topics) >= topic_limit:
+ break
+
+ warnings: list[str] = []
+ if len(topics) < 5:
+ warnings.append("Fewer than five topic clusters survived this domain sweep.")
+ if topics and all(len(topic.sources) == 1 for topic in topics):
+ warnings.append("Discovery evidence is single-source; configure Digg for broader confirmation.")
+ failed = [
+ source for source, outcome in source_status.items()
+ if outcome.state not in {health.OK, schema.NO_RESULTS, schema.SKIPPED_UNCONFIGURED}
+ ]
+ if failed:
+ warnings.append(f"Some discovery sources degraded: {', '.join(sorted(failed))}.")
+
+ return schema.DiscoveryReport(
+ domain=plan.domain,
+ range_from=from_date,
+ range_to=to_date,
+ generated_at=datetime.now(timezone.utc).isoformat(),
+ plan=plan,
+ topics=topics,
+ source_status=source_status,
+ warnings=warnings,
+ )
+
+
def diagnose(
config: dict[str, Any],
requested_sources: list[str] | None = None,
diff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.py
index 16fd9296..3ef9764b 100644
--- a/skills/last30days/scripts/lib/planner.py
+++ b/skills/last30days/scripts/lib/planner.py
@@ -7,16 +7,59 @@ import re
import unicodedata
from collections import Counter
-from . import entity_extract, http, providers, query, relevance, schema
+from . import categories, entity_extract, http, providers, query, relevance, schema
# Hebrew Unicode block: U+0590–U+05FF
_HEBREW_RE = re.compile(r'[\u0590-\u05FF]')
+DISCOVERY_SOURCE_ORDER = ("reddit", "hackernews", "digg", "x")
+
def detect_language(text: str) -> str | None:
"""Return 'he' if the text contains Hebrew characters, else None."""
return 'he' if _HEBREW_RE.search(text) else None
+
+def build_discovery_plan(
+ domain: str,
+ *,
+ available_sources: list[str] | None = None,
+ subreddits: list[str] | None = None,
+) -> schema.DiscoveryPlan:
+ """Resolve a domain to the existing category-peer community feeds."""
+ normalized_domain = " ".join(domain.split())
+ if not normalized_domain:
+ raise ValueError("Discovery domain cannot be empty")
+
+ category = categories.detect_category(normalized_domain)
+ candidate_subreddits = list(subreddits or categories.peer_subs_for(category))
+ seen_subreddits: set[str] = set()
+ resolved_subreddits: list[str] = []
+ for subreddit in candidate_subreddits:
+ normalized_subreddit = subreddit.removeprefix("r/").strip()
+ key = normalized_subreddit.lower()
+ if not normalized_subreddit or key in seen_subreddits:
+ continue
+ seen_subreddits.add(key)
+ resolved_subreddits.append(normalized_subreddit)
+ # The curated map intentionally stays small. Keep discovery's keyless floor
+ # for uncategorized domains by sweeping r/all and applying domain relevance
+ # during normalization instead of inventing a second category resolver.
+ if not resolved_subreddits:
+ resolved_subreddits = ["all"]
+
+ allowed = set(DISCOVERY_SOURCE_ORDER if available_sources is None else available_sources)
+ sources = [source for source in DISCOVERY_SOURCE_ORDER if source in allowed]
+ if not sources:
+ raise ValueError(f"No listing sources are available for {normalized_domain!r}")
+
+ return schema.DiscoveryPlan(
+ domain=normalized_domain,
+ category=category,
+ subreddits=resolved_subreddits,
+ sources=sources,
+ )
+
ALLOWED_INTENTS = {
"factual",
"product",
diff --git a/skills/last30days/scripts/lib/reddit_listing.py b/skills/last30days/scripts/lib/reddit_listing.py
index 5cda23a0..8061eb43 100644
--- a/skills/last30days/scripts/lib/reddit_listing.py
+++ b/skills/last30days/scripts/lib/reddit_listing.py
@@ -118,22 +118,42 @@ def parse_cards(html_text: str, query: str = "") -> List[Dict[str, Any]]:
return posts
-def _listing_url(subreddit: str, sort: str) -> str:
+def _listing_url(subreddit: str, sort: str, timeframe: str = TIMEFRAME) -> str:
sub = subreddit.removeprefix("r/").strip()
+ if sub.lower() == "all":
+ url = f"https://www.reddit.com/r/all/{sort}/"
+ if sort == "top":
+ url += f"?t={timeframe}"
+ return url
url = f"https://www.reddit.com/svc/shreddit/community-more-posts/{sort}/?name={sub}"
if sort == "top":
- url += f"&t={TIMEFRAME}"
+ url += f"&t={timeframe}"
return url
-def _fetch_one(subreddit: str, sort: str, query: str) -> List[Dict[str, Any]]:
+def _fetch_one(
+ subreddit: str,
+ sort: str,
+ query: str,
+ timeframe: str = TIMEFRAME,
+) -> List[Dict[str, Any]]:
+ items, _ = _fetch_one_with_status(subreddit, sort, query, timeframe)
+ return items
+
+
+def _fetch_one_with_status(
+ subreddit: str,
+ sort: str,
+ query: str,
+ timeframe: str = TIMEFRAME,
+) -> tuple[List[Dict[str, Any]], Optional[str]]:
try:
- text = http.reddit_keyless_get_text(_listing_url(subreddit, sort), timeout=LISTING_TIMEOUT,
+ text = http.reddit_keyless_get_text(_listing_url(subreddit, sort, timeframe), timeout=LISTING_TIMEOUT,
accept="text/html")
- return parse_cards(text, query) if text else []
+ return (parse_cards(text, query) if text else []), None
except Exception as e:
_log(f"listing fetch failed r/{subreddit} {sort}: {e}")
- return []
+ return [], str(e)
def fetch_listings(
@@ -141,6 +161,7 @@ def fetch_listings(
depth: str = "default",
query: str = "",
sorts: Optional[List[str]] = None,
+ timeframe: str = TIMEFRAME,
) -> List[Dict[str, Any]]:
"""Fetch scored post cards across subreddits × sorts.
@@ -157,7 +178,7 @@ def fetch_listings(
jobs = [(sub, sort) for sub in subreddits for sort in sorts]
all_posts: List[Dict[str, Any]] = []
with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs)) or 1) as executor:
- futures = {executor.submit(_fetch_one, sub, sort, query): (sub, sort)
+ futures = {executor.submit(_fetch_one, sub, sort, query, timeframe): (sub, sort)
for sub, sort in jobs}
for future in futures:
try:
@@ -174,6 +195,43 @@ def fetch_listings(
return unique
+def fetch_discovery_listings(
+ subreddits: List[str],
+ *,
+ query: str,
+ depth: str = "default",
+) -> Dict[str, Any]:
+ """Fetch rising/top-week listings while preserving per-feed failures."""
+ if not subreddits:
+ return {"items": [], "errors": []}
+ jobs = [(subreddit, sort) for subreddit in subreddits for sort in ("rising", "top")]
+ items: List[Dict[str, Any]] = []
+ errors: List[str] = []
+ with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs)) or 1) as executor:
+ futures = {
+ executor.submit(_fetch_one_with_status, subreddit, sort, query, "week"): (subreddit, sort)
+ for subreddit, sort in jobs
+ }
+ for future, (subreddit, sort) in futures.items():
+ try:
+ fetched, error = future.result(timeout=LISTING_TIMEOUT + 5)
+ except (Exception, FuturesTimeoutError) as exc:
+ errors.append(f"r/{subreddit} {sort}: {exc}")
+ continue
+ items.extend(fetched)
+ if error:
+ errors.append(f"r/{subreddit} {sort}: {error}")
+
+ seen: set[str] = set()
+ unique = []
+ for item in items:
+ if item["url"] in seen:
+ continue
+ seen.add(item["url"])
+ unique.append(item)
+ return {"items": unique, "errors": errors}
+
+
def score_index(subreddits: List[str], depth: str = "default") -> Dict[str, Dict[str, int]]:
"""Build a {post_id: {score, num_comments}} map from subreddit listings.
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 93723786..71807a26 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -61,6 +61,58 @@ def _render_badge() -> list[str]:
"",
]
+
+def _format_discovery_engagement(
+ engagement: dict[str, dict[str, float | int]],
+) -> str:
+ parts: list[str] = []
+ for source, metrics in engagement.items():
+ metric_parts = [
+ f"{field.replace('_', ' ')} {value:,.0f}"
+ for field, value in metrics.items()
+ if value
+ ]
+ if metric_parts:
+ parts.append(f"{SOURCE_LABELS.get(source, source.title())}: {', '.join(metric_parts)}")
+ return " · ".join(parts) or "No native engagement counters reported"
+
+
+def render_discovery(report: schema.DiscoveryReport) -> str:
+ """Render a compact topic-per-section discovery brief."""
+ lines = [
+ *_render_badge(),
+ f"# Trending discovery: {report.domain}",
+ "",
+ f"Window: {report.range_from} to {report.range_to}",
+ f"Feeds: {', '.join(report.plan.sources)}",
+ ]
+ if report.plan.subreddits:
+ lines.append("Communities: " + ", ".join(f"r/{sub}" for sub in report.plan.subreddits))
+ lines.append("")
+
+ if not report.topics:
+ lines.extend(["No trending topic clusters survived this sweep.", ""])
+ for topic in report.topics:
+ momentum = "New this week" if topic.momentum == "new-this-week" else "Building"
+ lines.extend([
+ f"## {topic.rank}. {topic.name}",
+ "",
+ f"**Momentum:** {momentum} · velocity {topic.velocity_score:,.2f}",
+ "",
+ topic.why_spiking,
+ "",
+ f"**Evidence:** {_format_discovery_engagement(topic.engagement_by_source)}",
+ "",
+ f"**Research next:** `{topic.command}`",
+ "",
+ ])
+
+ if report.warnings:
+ lines.extend(["### Coverage notes", ""])
+ lines.extend(f"- {warning}" for warning in report.warnings)
+ lines.append("")
+ return "\n".join(lines).rstrip() + "\n"
+
SOURCE_LABELS = {
"reddit": "Reddit",
"youtube": "YouTube",
diff --git a/skills/last30days/scripts/lib/rerank.py b/skills/last30days/scripts/lib/rerank.py
index 11a8f3b6..7c7defeb 100644
--- a/skills/last30days/scripts/lib/rerank.py
+++ b/skills/last30days/scripts/lib/rerank.py
@@ -3,7 +3,9 @@
from __future__ import annotations
import json
+import math
import re
+from datetime import datetime
from . import http, providers, query, schema, signals
@@ -25,6 +27,63 @@ ENTITY_MISS_PENALTY = 25.0
# neutral floor so it survives into the visible band.
FIRST_PARTY_AUTHOR_CREDIT = 5.0
+_DISCOVERY_ENGAGEMENT_FIELDS = {
+ "reddit": ("score", "num_comments"),
+ "hackernews": ("points", "comments"),
+ "digg": ("postCount", "uniqueAuthors"),
+ "x": ("likes", "reposts", "replies", "quotes"),
+}
+
+
+def discovery_engagement_total(item: schema.SourceItem) -> float:
+ """Return comparable native interaction counts for discovery evidence."""
+ fields = _DISCOVERY_ENGAGEMENT_FIELDS.get(item.source)
+ if fields is None:
+ fields = tuple(
+ field
+ for field in item.engagement
+ if field.lower() not in {"rank", "rank_score", "upvote_ratio", "rating"}
+ )
+ return sum(
+ float(item.engagement.get(field) or 0)
+ for field in fields
+ if isinstance(item.engagement.get(field), (int, float))
+ and not isinstance(item.engagement.get(field), bool)
+ )
+
+
+def engagement_velocity_score(
+ item: schema.SourceItem,
+ *,
+ as_of_date: str,
+) -> float:
+ """Weight native engagement by age, with an explicit first-week boost."""
+ engagement = discovery_engagement_total(item)
+ if engagement <= 0:
+ return 0.0
+ try:
+ published = datetime.fromisoformat((item.published_at or "").replace("Z", "+00:00")).date()
+ as_of = datetime.fromisoformat(as_of_date.replace("Z", "+00:00")).date()
+ age_days = max(0, (as_of - published).days)
+ except (TypeError, ValueError):
+ age_days = 30
+ recency_weight = 1.0 / math.sqrt(age_days + 1)
+ if age_days < 7:
+ recency_weight *= 1.5
+ return round(engagement * recency_weight, 4)
+
+
+def discovery_velocity_score(
+ items: list[schema.SourceItem],
+ *,
+ as_of_date: str,
+) -> float:
+ """Score a topic cluster and reward independent cross-source confirmation."""
+ raw = sum(engagement_velocity_score(item, as_of_date=as_of_date) for item in items)
+ source_count = len({item.source for item in items})
+ corroboration = 1.0 + (0.15 * max(0, source_count - 1))
+ return round(raw * corroboration, 4)
+
# Engagement rescue: a high-engagement X post that is on-topic (entity-grounded
# or first-party) cannot be fully zeroed by the other penalties. The floor is a
# function of the post's engagement percentile *within the run's X pool* (so it
diff --git a/skills/last30days/scripts/lib/schema.py b/skills/last30days/scripts/lib/schema.py
index 1e407499..31cbe976 100644
--- a/skills/last30days/scripts/lib/schema.py
+++ b/skills/last30days/scripts/lib/schema.py
@@ -225,6 +225,45 @@ class Report:
drill_of: str | None = None
+@dataclass(frozen=True)
+class DiscoveryPlan:
+ """Topic-less listing feeds selected for a domain sweep."""
+
+ domain: str
+ category: str | None
+ subreddits: list[str]
+ sources: list[str]
+
+
+@dataclass(frozen=True)
+class DiscoveryTopic:
+ """One engagement-ranked topic produced by a discovery sweep."""
+
+ rank: int
+ name: str
+ why_spiking: str
+ momentum: Literal["new-this-week", "building"]
+ velocity_score: float
+ sources: list[str]
+ engagement_by_source: dict[str, dict[str, float | int]]
+ command: str
+ evidence_urls: list[str] = field(default_factory=list)
+
+
+@dataclass
+class DiscoveryReport:
+ """Versioned result of a domain-level listing sweep."""
+
+ domain: str
+ range_from: str
+ range_to: str
+ generated_at: str
+ plan: DiscoveryPlan
+ topics: list[DiscoveryTopic]
+ source_status: dict[str, SourceOutcome] = field(default_factory=dict)
+ warnings: list[str] = field(default_factory=list)
+
+
@dataclass
class RetrievalBundle:
"""Structured retrieval output before global ranking."""
@@ -446,6 +485,7 @@ def candidate_primary_item(candidate: Candidate) -> SourceItem | None:
AGENT_EXPORT_SCHEMA_VERSION = "1.0"
+DISCOVERY_EXPORT_SCHEMA_VERSION = "1.0"
def _agent_summary(candidate: Candidate) -> str:
@@ -582,3 +622,40 @@ def to_agent_export(report: Report) -> dict[str, Any]:
"clusters": exported_clusters,
"results": results,
}
+
+
+def to_discovery_export(report: DiscoveryReport) -> dict[str, Any]:
+ """Serialize discovery output without changing the normal agent contract."""
+ start = datetime.fromisoformat(report.range_from).date()
+ end = datetime.fromisoformat(report.range_to).date()
+ return {
+ "schema_version": DISCOVERY_EXPORT_SCHEMA_VERSION,
+ "kind": "discovery",
+ "domain": report.domain,
+ "generated_at": _agent_generated_at(report.generated_at),
+ "window_days": max(0, (end - start).days),
+ "source_status": {
+ source: outcome.state
+ for source, outcome in sorted(report.source_status.items())
+ },
+ "feeds": {
+ "category": report.plan.category,
+ "subreddits": list(report.plan.subreddits),
+ "sources": list(report.plan.sources),
+ },
+ "results": [
+ {
+ "rank": topic.rank,
+ "topic": topic.name,
+ "why_spiking": topic.why_spiking,
+ "momentum": topic.momentum,
+ "velocity_score": topic.velocity_score,
+ "sources": list(topic.sources),
+ "engagement": topic.engagement_by_source,
+ "command": topic.command,
+ "evidence_urls": list(topic.evidence_urls),
+ }
+ for topic in report.topics
+ ],
+ "warnings": list(report.warnings),
+ }
diff --git a/tests/test_discover_mode.py b/tests/test_discover_mode.py
new file mode 100644
index 00000000..15af53b9
--- /dev/null
+++ b/tests/test_discover_mode.py
@@ -0,0 +1,662 @@
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+import last30days as cli
+from lib import pipeline, planner, reddit_listing, render, rerank, schema
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+
+
+def _item(
+ item_id: str,
+ source: str,
+ title: str,
+ *,
+ published_at: str = "2026-07-09",
+ engagement: dict[str, int | float] | None = None,
+) -> schema.SourceItem:
+ return schema.SourceItem(
+ item_id=item_id,
+ source=source,
+ title=title,
+ body=title,
+ url=f"https://{source}.example/{item_id}",
+ published_at=published_at,
+ engagement=engagement or {},
+ snippet=f"Evidence about {title}",
+ )
+
+
+def _candidate(item: schema.SourceItem) -> schema.Candidate:
+ return schema.Candidate(
+ candidate_id=f"candidate-{item.item_id}",
+ item_id=item.item_id,
+ source=item.source,
+ title=item.title,
+ url=item.url,
+ snippet=item.snippet,
+ subquery_labels=["discovery-listings"],
+ native_ranks={f"discovery-listings:{item.source}": 1},
+ local_relevance=0.9,
+ freshness=95,
+ engagement=100,
+ source_quality=0.8,
+ rrf_score=0.1,
+ sources=[item.source],
+ source_items=[item],
+ final_score=80,
+ )
+
+
+def test_discovery_plan_reuses_category_peer_mapping():
+ plan = planner.build_discovery_plan(
+ "AI agents",
+ available_sources=["reddit", "hackernews"],
+ )
+
+ assert plan.category == "ai_agent_framework"
+ assert plan.subreddits == ["LangChain", "LocalLLaMA", "AI_Agents", "MachineLearning"]
+ assert plan.sources == ["reddit", "hackernews"]
+
+
+def test_discovery_plan_keeps_keyless_reddit_for_unknown_domains():
+ plan = planner.build_discovery_plan(
+ "urban gardening",
+ available_sources=["reddit", "hackernews"],
+ )
+
+ assert plan.category is None
+ assert plan.subreddits == ["all"]
+ assert plan.sources == ["reddit", "hackernews"]
+
+
+def test_uncategorized_discovery_uses_parseable_r_all_listing_paths():
+ card = (
+ '<shreddit-post permalink="/r/gardening/comments/abc123/urban_garden/" '
+ 'post-title="Urban gardening is taking off" score="42" comment-count="7" '
+ 'author="gardener" subreddit-name="gardening" '
+ 'created-timestamp="2026-07-09T12:00:00+00:00">'
+ )
+ requested_urls: list[str] = []
+
+ def fake_get(url, **_kwargs):
+ requested_urls.append(url)
+ return card
+
+ with mock.patch.object(reddit_listing.http, "reddit_keyless_get_text", side_effect=fake_get):
+ result = reddit_listing.fetch_discovery_listings(
+ ["all"], query="urban gardening",
+ )
+
+ assert len(result["items"]) == 1
+ assert any("/r/all/rising/" in url for url in requested_urls)
+ assert any("/r/all/top/?t=week" in url for url in requested_urls)
+ assert all("name=all" not in url for url in requested_urls)
+
+
+def test_velocity_scoring_favors_a_recent_spike_over_static_bigness():
+ recent = _item(
+ "recent",
+ "reddit",
+ "Recent spike",
+ published_at="2026-07-09",
+ engagement={"score": 100, "num_comments": 10},
+ )
+ old = _item(
+ "old",
+ "reddit",
+ "Older large thread",
+ published_at="2026-06-20",
+ engagement={"score": 300, "num_comments": 10},
+ )
+
+ assert rerank.engagement_velocity_score(recent, as_of_date="2026-07-10") > (
+ rerank.engagement_velocity_score(old, as_of_date="2026-07-10")
+ )
+
+
+def test_domain_filter_ignores_generic_ai_only_matches():
+ assert pipeline._matches_discovery_domain(
+ "AI agents", "An AI agent bankrupted its operator"
+ )
+ assert not pipeline._matches_discovery_domain(
+ "AI agents", "Global dialogue on AI governance"
+ )
+
+
+ ("domain", "listing_title"),
+ [
+ ("城市园艺", "城市园艺技巧与社区花园"),
+ ("גינון עירוני", "מדריך חדש לגינון עירוני"),
+ ],
+)
+def test_domain_filter_tokenizes_non_latin_domains(domain, listing_title):
+ assert pipeline._matches_discovery_domain(domain, listing_title)
+
+
+def test_x_velocity_excludes_views_and_bookmarks():
+ xquik_item = _item(
+ "xquik",
+ "x",
+ "X backend reach",
+ engagement={
+ "likes": 10,
+ "reposts": 3,
+ "replies": 2,
+ "quotes": 1,
+ "views": 100_000,
+ "bookmarks": 5_000,
+ },
+ )
+ standard_item = _item(
+ "standard",
+ "x",
+ "X backend interactions",
+ engagement={"likes": 10, "reposts": 3, "replies": 2, "quotes": 1},
+ )
+
+ assert rerank.discovery_engagement_total(xquik_item) == 16
+ assert rerank.engagement_velocity_score(
+ xquik_item, as_of_date="2026-07-10"
+ ) == rerank.engagement_velocity_score(standard_item, as_of_date="2026-07-10")
+
+
+def test_discovery_topic_name_uses_entities_shared_across_sources():
+ reddit = _candidate(_item("r1", "reddit", "OpenAI Agent SDK launch details"))
+ hn = _candidate(_item("h1", "hackernews", "OpenAI Agent SDK reaches developers"))
+ candidates = {reddit.candidate_id: reddit, hn.candidate_id: hn}
+ cluster = schema.Cluster(
+ cluster_id="cluster-1",
+ title=reddit.title,
+ candidate_ids=list(candidates),
+ representative_ids=[reddit.candidate_id],
+ sources=["hackernews", "reddit"],
+ score=80,
+ )
+
+ assert pipeline.discovery_topic_name(cluster, candidates, "AI agents") == "OpenAI Agent SDK"
+
+
+def test_discovery_renderer_snapshot():
+ report = schema.DiscoveryReport(
+ domain="AI agents",
+ range_from="2026-06-10",
+ range_to="2026-07-10",
+ generated_at="2026-07-10T00:00:00+00:00",
+ plan=schema.DiscoveryPlan(
+ domain="AI agents",
+ category="ai_agent_framework",
+ subreddits=["AI_Agents"],
+ sources=["reddit", "hackernews"],
+ ),
+ topics=[schema.DiscoveryTopic(
+ rank=1,
+ name="Agent memory protocols",
+ why_spiking="Two independent listing items accelerated this week.",
+ momentum="new-this-week",
+ velocity_score=123.45,
+ sources=["hackernews", "reddit"],
+ engagement_by_source={
+ "reddit": {"score": 120, "num_comments": 30},
+ "hackernews": {"points": 80},
+ },
+ command='/last30days "Agent memory protocols"',
+ )],
+ )
+
+ with mock.patch.object(render, "_render_badge", return_value=["BADGE", ""]):
+ rendered = render.render_discovery(report)
+
+ assert rendered == (
+ "BADGE\n\n"
+ "# Trending discovery: AI agents\n\n"
+ "Window: 2026-06-10 to 2026-07-10\n"
+ "Feeds: reddit, hackernews\n"
+ "Communities: r/AI_Agents\n\n"
+ "## 1. Agent memory protocols\n\n"
+ "**Momentum:** New this week · velocity 123.45\n\n"
+ "Two independent listing items accelerated this week.\n\n"
+ "**Evidence:** Reddit: score 120, num comments 30 · Hacker News: points 80\n\n"
+ "**Research next:** `/last30days \"Agent memory protocols\"`\n"
+ )
+
+
+def test_keyless_discovery_degrades_without_digg():
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config):
+ return pipeline._mock_discovery_items(source, plan.domain, to_date), None
+
+ with mock.patch.object(pipeline, "available_sources", return_value=["reddit", "hackernews"]), \
+ mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=fake_fetch):
+ report = pipeline.run_discover(
+ domain="AI agents",
+ config={},
+ as_of_date="2026-07-10",
+ )
+
+ assert 5 <= len(report.topics) <= 10
+ assert report.source_status["reddit"].state == "ok"
+ assert report.source_status["hackernews"].state == "ok"
+ assert report.source_status["digg"].state == "skipped-unconfigured"
+ assert report.source_status["x"].state == "skipped-unconfigured"
+ assert all(topic.command.startswith('/last30days "') for topic in report.topics)
+
+
+def test_discovery_drops_zero_velocity_clusters():
+ raw_item = {
+ "id": "zero-engagement",
+ "text": "AI agent launch with no interactions",
+ "url": "https://x.com/example/status/1",
+ "author_handle": "example",
+ "date": "2026-07-09",
+ "engagement": {"likes": 0, "reposts": 0, "replies": 0, "quotes": 0},
+ "relevance": 0.9,
+ }
+
+ with mock.patch.object(pipeline, "available_sources", return_value=["x"]), \
+ mock.patch.object(pipeline, "_fetch_discovery_source", return_value=([raw_item], None)):
+ report = pipeline.run_discover(
+ domain="AI agents",
+ config={},
+ as_of_date="2026-07-10",
+ )
+
+ assert report.topics == []
+ assert "Fewer than five topic clusters survived this domain sweep." in report.warnings
+
+
+def test_explicit_unavailable_discovery_source_does_not_widen_to_other_sources():
+ with mock.patch.object(pipeline, "available_sources", return_value=[]), \
+ mock.patch.object(pipeline, "_fetch_discovery_source") as fetch:
+ with pytest.raises(ValueError, match="No listing sources are available"):
+ pipeline.run_discover(
+ domain="AI agents",
+ config={},
+ requested_sources=["digg"],
+ as_of_date="2026-07-10",
+ )
+
+ fetch.assert_not_called()
+
+
+def test_discovery_reads_browser_credentials_and_does_not_schedule_pending_x():
+ parser = cli.build_parser()
+ args, extra = parser.parse_known_args(["--discover", "AI agents"])
+ assert cli._config_policy_for_args(args, "", extra).browser_cookies == "read"
+
+ no_cookies_args, extra = parser.parse_known_args(
+ ["--no-browser-cookies", "--discover", "AI agents"]
+ )
+ assert cli._config_policy_for_args(no_cookies_args, "", extra).browser_cookies == "off"
+
+ fetched_sources: list[str] = []
+
+ def fake_available_sources(config, requested_sources, *, x_pending=None, local_only=False):
+ assert x_pending is False
+ return ["reddit", "hackernews"] + (["x"] if x_pending is not False else [])
+
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config):
+ fetched_sources.append(source)
+ return pipeline._mock_discovery_items(source, plan.domain, to_date), None
+
+ with mock.patch.object(pipeline, "available_sources", side_effect=fake_available_sources), \
+ mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=fake_fetch):
+ report = pipeline.run_discover(
+ domain="AI agents",
+ config={"FROM_BROWSER": "firefox", "_BROWSER_COOKIE_MODE": "plan_only"},
+ as_of_date="2026-07-10",
+ )
+
+ assert "x" not in fetched_sources
+ assert report.source_status["x"].state == "skipped-unconfigured"
+
+
+def test_authenticated_x_discovery_uses_available_backend():
+ plan = planner.build_discovery_plan(
+ "AI agents",
+ available_sources=["x"],
+ )
+ raw = pipeline._mock_discovery_items("x", plan.domain, "2026-07-10")
+ with mock.patch.object(pipeline.env, "x_backend_chain", return_value=["bird"]), \
+ mock.patch.object(pipeline, "_fetch_x_backend", return_value=(raw, "")) as fetch:
+ items, error = pipeline._fetch_discovery_source(
+ "x",
+ plan,
+ from_date="2026-06-10",
+ to_date="2026-07-10",
+ depth="default",
+ mock=False,
+ config={"AUTH_TOKEN": "dummy", "CT0": "dummy"},
+ )
+
+ assert error is None
+ assert len(items) == 6
+ fetch.assert_called_once()
+
+
+def test_listing_failure_is_not_reported_as_clean_no_results():
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config):
+ if source == "reddit":
+ return [], "connection timed out"
+ return pipeline._mock_discovery_items(source, plan.domain, to_date), None
+
+ with mock.patch.object(pipeline, "available_sources", return_value=["reddit", "hackernews"]), \
+ mock.patch.object(pipeline, "_fetch_discovery_source", side_effect=fake_fetch):
+ report = pipeline.run_discover(
+ domain="AI agents",
+ config={},
+ as_of_date="2026-07-10",
+ )
+
+ assert report.source_status["reddit"].state == "timeout"
+ assert report.source_status["reddit"].detail == "connection timed out"
+
+
+def test_reddit_discovery_adapter_preserves_partial_feed_errors():
+ item = {
+ "url": "https://reddit.com/r/example/comments/1",
+ "title": "AI agent launch",
+ }
+ with mock.patch.object(
+ reddit_listing,
+ "_fetch_one_with_status",
+ side_effect=[([], "rising timed out"), ([item], None)],
+ ):
+ result = reddit_listing.fetch_discovery_listings(
+ ["AI_Agents"], query="AI agents",
+ )
+
+ assert result["items"] == [item]
+ assert result["errors"] == ["r/AI_Agents rising: rising timed out"]
+
+
+def test_discovery_cli_json_contract_and_mutual_exclusion():
+ result = subprocess.run(
+ [
+ sys.executable,
+ "skills/last30days/scripts/last30days.py",
+ "--discover",
+ "AI agents",
+ "--mock",
+ "--emit=json",
+ ],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ payload = json.loads(result.stdout)
+ assert payload["schema_version"] == "1.0"
+ assert payload["kind"] == "discovery"
+ assert 5 <= len(payload["results"]) <= 10
+ assert payload["results"][0]["command"].startswith('/last30days "')
+
+ invalid = subprocess.run(
+ [
+ sys.executable,
+ "skills/last30days/scripts/last30days.py",
+ "topic",
+ "--discover",
+ "AI agents",
+ "--mock",
+ ],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert invalid.returncode == 2
+ assert "cannot be combined with a positional topic" in invalid.stderr
+
+ drill_conflict = subprocess.run(
+ [
+ sys.executable,
+ "skills/last30days/scripts/last30days.py",
+ "--discover",
+ "AI agents",
+ "--drill",
+ "1",
+ "--mock",
+ ],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert drill_conflict.returncode == 2
+ assert "mutually exclusive" in drill_conflict.stderr
+
+
+def test_discovery_cli_rejects_historical_as_of():
+ result = subprocess.run(
+ [
+ sys.executable,
+ "skills/last30days/scripts/last30days.py",
+ "--discover",
+ "AI agents",
+ "--as-of",
+ "2026-06-01",
+ "--mock",
+ ],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert result.returncode == 2
+ assert "--as-of cannot be used with --discover" in result.stderr
+ assert "current live listings" in result.stderr
+
+
+def test_discovery_filters_incompatible_default_sources_but_rejects_explicit_only():
+ default_result = subprocess.run(
+ [
+ sys.executable,
+ "skills/last30days/scripts/last30days.py",
+ "--discover",
+ "AI agents",
+ "--mock",
+ "--emit=json",
+ ],
+ cwd=REPO_ROOT,
+ env={**os.environ, "LAST30DAYS_DEFAULT_SEARCH": "reddit,x,youtube,hn"},
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert default_result.returncode == 0, default_result.stderr
+
+ explicit_result = subprocess.run(
+ [
+ sys.executable,
+ "skills/last30days/scripts/last30days.py",
+ "--discover",
+ "AI agents",
+ "--search=youtube",
+ "--mock",
+ ],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert explicit_result.returncode == 2
+ assert "unsupported: youtube" in explicit_result.stderr
+
+
+def test_detect_category_rejects_suffix_false_positives():
+ from lib import categories
+
+ assert categories.detect_category("Dubai agents") is None
+ assert categories.detect_category("Thai agents real estate") is None
+ assert categories.detect_category("AI agents") == "ai_agent_framework"
+ assert categories.detect_category("what's new in ai agent frameworks") == "ai_agent_framework"
+
+
+def test_discovery_engagement_excludes_rank_metadata():
+ from lib import pipeline, schema
+
+ items = [
+ schema.SourceItem(
+ item_id=f"digg-{i}", source="digg", title="t", body="b",
+ url=f"https://di.gg/{i}", published_at="2026-07-05", snippet="s",
+ engagement={"postCount": 5, "rank": 100 * (i + 1), "rank_score": 0.5},
+ )
+ for i in range(3)
+ ]
+ totals = pipeline._discovery_engagement(items)
+ assert totals["digg"]["postCount"] == 15
+ assert "rank" not in totals["digg"]
+ assert "rank_score" not in totals["digg"]
+
+
+def test_domain_matching_preserves_non_plural_anchors():
+ from lib import pipeline
+
+ assert pipeline._matches_discovery_domain("AI bias", "Addressing AI bias in models")
+ assert pipeline._matches_discovery_domain("supply chain crisis", "The crisis deepens for chip supply")
+ # Plural matching still works both directions.
+ assert pipeline._matches_discovery_domain("AI agents", "The best AI agent stacks")
+
+
+def test_x_fallback_success_is_clean(monkeypatch):
+ from lib import pipeline, env
+
+ calls = []
+
+ def fake_fetch(backend, subquery, from_date, to_date, depth, config):
+ calls.append(backend)
+ if backend == "bird":
+ return [], "cookie expired"
+ return [object()], None
+
+ monkeypatch.setattr(pipeline, "_fetch_x_backend", fake_fetch)
+ monkeypatch.setattr(env, "x_backend_chain", lambda config: ["bird", "xquik"])
+ plan = pipeline.schema.DiscoveryPlan(
+ domain="ai agents", category=None, subreddits=[], sources=["x"],
+ )
+ items, error = pipeline._fetch_discovery_source(
+ "x", plan,
+ from_date="2026-06-11", to_date="2026-07-11", depth="quick",
+ mock=False, config={},
+ )
+ assert error is None
+ assert len(items) == 1
+ assert calls == ["bird", "xquik"]
+
+
+def _digg_envelope(*clusters: dict) -> dict:
+ return {"results": list(clusters)}
+
+
+def _digg_cluster(cluster_id: str, title: str, tldr: str = "") -> dict:
+ return {
+ "clusterUrlId": cluster_id,
+ "title": title,
+ "tldr": tldr,
+ "rank": 5,
+ "postCount": 12,
+ "uniqueAuthors": 8,
+ }
+
+
+def test_digg_discovery_drops_off_domain_clusters(monkeypatch):
+ """Regression: a crypto sweep surfaced AI stories because the Digg
+ branch (an AI-only leaderboard feed) applied no domain filter."""
+ envelope = _digg_envelope(
+ _digg_cluster("c1", "Bitcoin crypto rally accelerates"),
+ _digg_cluster("c2", "OpenAI ships a new frontier model"),
+ )
+ monkeypatch.setattr(pipeline.digg, "search_digg", lambda *a, **k: envelope)
+ plan = schema.DiscoveryPlan(
+ domain="crypto", category=None, subreddits=[], sources=["digg"],
+ )
+ items, error = pipeline._fetch_discovery_source(
+ "digg", plan,
+ from_date="2026-06-11", to_date="2026-07-11", depth="quick",
+ mock=False, config={},
+ )
+ assert error is None
+ titles = [item["title"] for item in items]
+ assert titles == ["Bitcoin crypto rally accelerates"]
+
+
+def test_digg_discovery_keeps_domain_matching_clusters(monkeypatch):
+ envelope = _digg_envelope(
+ _digg_cluster("c1", "AI agents reshape support desks"),
+ _digg_cluster("c2", "The best AI agent stacks compared"),
+ )
+ monkeypatch.setattr(pipeline.digg, "search_digg", lambda *a, **k: envelope)
+ plan = schema.DiscoveryPlan(
+ domain="AI agents", category=None, subreddits=[], sources=["digg"],
+ )
+ items, error = pipeline._fetch_discovery_source(
+ "digg", plan,
+ from_date="2026-06-11", to_date="2026-07-11", depth="quick",
+ mock=False, config={},
+ )
+ assert error is None
+ assert len(items) == 2
+
+
+def test_digg_discovery_all_filtered_is_clean_no_results(monkeypatch):
+ envelope = _digg_envelope(
+ _digg_cluster("c1", "OpenAI ships a new frontier model"),
+ _digg_cluster("c2", "Anthropic updates its agent SDK"),
+ )
+ monkeypatch.setattr(pipeline.digg, "search_digg", lambda *a, **k: envelope)
+ plan = schema.DiscoveryPlan(
+ domain="crypto", category=None, subreddits=[], sources=["digg"],
+ )
+ items, error = pipeline._fetch_discovery_source(
+ "digg", plan,
+ from_date="2026-06-11", to_date="2026-07-11", depth="quick",
+ mock=False, config={},
+ )
+ assert error is None
+ assert items == []
+
+
+def test_x_discovery_preserves_producing_backends_own_error(monkeypatch):
+ """A backend that returns items plus its own error is a partial outcome;
+ only earlier failed-over backends' errors are observability-only."""
+ monkeypatch.setattr(
+ pipeline, "_fetch_x_backend",
+ lambda *a, **k: ([{"id": "x-1", "title": "t"}], "rate limited after page 1"),
+ )
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda config: ["bird"])
+ plan = schema.DiscoveryPlan(
+ domain="ai agents", category=None, subreddits=[], sources=["x"],
+ )
+ items, error = pipeline._fetch_discovery_source(
+ "x", plan,
+ from_date="2026-06-11", to_date="2026-07-11", depth="quick",
+ mock=False, config={},
+ )
+ assert len(items) == 1
+ assert error == "rate limited after page 1"
+
+
+def test_discovery_exits_when_configured_sources_have_no_discovery_feed(monkeypatch, capsys):
+ """A configured source boundary must hold: never silently widen a sweep
+ to feeds the user filtered out."""
+ monkeypatch.setattr(
+ cli.env, "get_config", lambda **_kwargs: {"LAST30DAYS_DEFAULT_SEARCH": "youtube"}
+ )
+ monkeypatch.setattr(sys, "argv", ["last30days.py", "--discover", "AI agents", "--mock"])
+ with mock.patch.object(pipeline, "run_discover") as run:
+ assert cli.main() == 2
+
+ run.assert_not_called()
+ err = capsys.readouterr().err
+ assert "no discovery-capable sources" in err
+ assert "reddit" in err