Skip to content

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

fix(youtube): drop out-of-window videos on recent topics (#1266)

Matt Van Horn068591b56bd3
diff --git a/changelog.d/+youtube-date-window.fixed.md b/changelog.d/+youtube-date-window.fixed.md
new file mode 100644
index 00000000..0ac99547
--- /dev/null
+++ b/changelog.d/+youtube-date-window.fixed.md
@@ -0,0 +1 @@
+Recent-topic reports no longer include years-old YouTube videos when nothing on YouTube falls inside the date window; the YouTube section now comes back empty instead of padding the report with off-topic back-catalog videos. Evergreen and how-to topics still fall back to older videos when recent ones are scarce.
diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.py
index ab8bf231..a114f647 100644
--- a/skills/last30days/scripts/lib/normalize.py
+++ b/skills/last30days/scripts/lib/normalize.py
@@ -107,12 +107,14 @@ def normalize_source_items(
)
if filtered:
return filtered
- # YouTube search already keeps out-of-window videos when fewer than 3
- # are recent, then pays for transcripts. A second hard date filter here
- # dropped those transcribed items to zero (#1043). Keep transcript-backed
- # retrieved items instead of paying for transcripts that never appear in
- # the brief. Metadata-only / caption-failed videos are not that rescue.
- if source == "youtube" and normalized:
+ # For evergreen_ok, YouTube search keeps out-of-window videos when fewer
+ # than 3 are recent, then pays for transcripts. A second hard date filter
+ # here dropped those transcribed items to zero (#1043). Keep
+ # transcript-backed retrieved items instead of paying for transcripts that
+ # never appear in the brief. Metadata-only / caption-failed videos are not
+ # that rescue. Recent modes (strict_recent / balanced_recent) get no
+ # rescue: years-old videos on a recent topic are noise, not evidence.
+ if freshness_mode == "evergreen_ok" and source == "youtube" and normalized:
transcribed = [
item for item in normalized if str(item.snippet or "").strip()
]
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index a9157afe..584c3f12 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -2728,6 +2728,7 @@ def run(
trustpilot_domain=trustpilot_domain,
trustpilot_domain_is_hint=trustpilot_domain_is_hint,
run_started=run_started,
+ freshness_mode=plan.freshness_mode,
)
] = (subquery, source)
@@ -2793,6 +2794,7 @@ def run(
trustpilot_domain=trustpilot_domain,
trustpilot_domain_is_hint=trustpilot_domain_is_hint,
run_started=run_started,
+ freshness_mode=plan.freshness_mode,
)
retry_done, _ = _wait_for_research([retry_future], stream_config)
if not retry_done:
@@ -4868,6 +4870,7 @@ def _retry_thin_sources(
# pulls for ASINs already enriched in Phase 1. Finalize will enrich
# any genuinely new products that weren't in Phase 1.
skip_amazon_enrichment=True,
+ freshness_mode=plan.freshness_mode,
)
outcome_note = artifact.get("_source_outcome") if isinstance(artifact, dict) else None
detail_note = artifact.get("_source_outcome_detail") if isinstance(artifact, dict) else None
@@ -5387,6 +5390,7 @@ def _fetch_youtube_stream(
config: dict[str, Any],
*,
has_ytdlp: bool,
+ freshness_mode: str | None = None,
) -> tuple[list[dict], dict]:
"""Search, backfill, transcribe, and comment-enrich one YouTube query."""
result = None
@@ -5404,6 +5408,7 @@ def _fetch_youtube_stream(
try:
result = youtube_yt.search_and_transcribe(
yt_query, from_date, to_date, depth=depth, token=sc_token,
+ freshness_mode=freshness_mode,
)
if result.get("error"):
youtube_failure = str(result["error"])
@@ -5430,6 +5435,7 @@ def _fetch_youtube_stream(
sc_result = youtube_yt.search_youtube_sc(
yt_query, from_date, to_date, depth=depth, token=sc_token,
skip_transcript_ids=transcribed_free_ids,
+ freshness_mode=freshness_mode,
)
sc_error = str(sc_result["error"]) if sc_result.get("error") else None
if backfill_thin:
@@ -5538,6 +5544,7 @@ def _retrieve_stream_impl(
trustpilot_domain_is_hint: bool = False,
run_started: float | None = None,
skip_amazon_enrichment: bool = False,
+ freshness_mode: str | None = None,
) -> tuple[list[dict], dict]:
# Early exit if source was rate-limited by a sibling future
if rate_limited_sources is not None and source in rate_limited_sources:
@@ -5960,13 +5967,14 @@ def _retrieve_stream_impl(
# thin-source retry share one fetch (hosts without yt-dlp included).
return fetch_memo.fetch_once(
(
- "youtube", yt_query, from_date, to_date, depth, has_ytdlp,
+ "youtube", yt_query, from_date, to_date, depth, freshness_mode, has_ytdlp,
env.is_youtube_sc_available(config),
env.youtube_sc_min_items(config),
env.is_youtube_comments_available(config),
),
lambda: _fetch_youtube_stream(
yt_query, from_date, to_date, depth, config, has_ytdlp=has_ytdlp,
+ freshness_mode=freshness_mode,
),
timeout=_memo_wait_seconds(config),
cacheable=_clean_stream_result,
diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.py
index f12adec2..7c6ad664 100644
--- a/skills/last30days/scripts/lib/youtube_yt.py
+++ b/skills/last30days/scripts/lib/youtube_yt.py
@@ -480,11 +480,43 @@ def expand_youtube_queries(topic: str, depth: str) -> List[str]:
return queries[:cap]
+# Freshness modes where an out-of-window video is noise, not a fallback: a
+# recent topic with no in-range videos returns an honest empty result rather
+# than years-old, often off-topic matches.
+_RECENT_FRESHNESS_MODES = frozenset({"strict_recent", "balanced_recent"})
+
+
+def _apply_date_window(
+ items: List[Dict[str, Any]],
+ from_date: str,
+ freshness_mode: Optional[str],
+) -> List[Dict[str, Any]]:
+ """Prefer in-window videos; scope the keep-all fallback by freshness mode.
+
+ 3+ in-window videos: keep only those (every mode). Fewer: recent modes
+ keep only the in-window ones; evergreen_ok and unknown/None keep all so
+ evergreen topics can still fall back to older videos.
+ """
+ recent = [i for i in items if i["date"] and i["date"] >= from_date]
+ if len(recent) >= 3:
+ _log(f"Found {len(recent)} videos within date range")
+ return recent
+ if freshness_mode in _RECENT_FRESHNESS_MODES:
+ _log(
+ f"Found {len(items)} videos ({len(recent)} within date range, "
+ f"keeping only in-range for {freshness_mode})"
+ )
+ return recent
+ _log(f"Found {len(items)} videos ({len(recent)} within date range, keeping all)")
+ return items
+
+
def search_youtube(
topic: str,
from_date: str,
to_date: str,
depth: str = "default",
+ freshness_mode: Optional[str] = None,
) -> Dict[str, Any]:
"""Search YouTube via yt-dlp. No API key needed.
@@ -493,6 +525,8 @@ def search_youtube(
from_date: Start date (YYYY-MM-DD)
to_date: End date (YYYY-MM-DD)
depth: 'quick', 'default', or 'deep'
+ freshness_mode: Plan freshness mode; scopes the out-of-window
+ fallback (see _apply_date_window). None keeps the soft fallback.
Returns:
Dict with 'items' list of video metadata dicts.
@@ -502,7 +536,7 @@ def search_youtube(
count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
core_topic = _extract_core_subject(topic)
- cache_key = (core_topic, count, from_date)
+ cache_key = (core_topic, count, from_date, freshness_mode)
timeout = _search_timeout()
cached, event, slot, is_leader = _claim_search_slot(cache_key)
@@ -609,13 +643,9 @@ def search_youtube(
"description": description,
})
- # Soft date filter: prefer recent items but fall back to all if too few
- recent = [i for i in items if i["date"] and i["date"] >= from_date]
- if len(recent) >= 3:
- items = recent
- _log(f"Found {len(items)} videos within date range")
- else:
- _log(f"Found {len(items)} videos ({len(recent)} within date range, keeping all)")
+ # Date filter: prefer recent items; the keep-all fallback is scoped
+ # by freshness mode (evergreen only), see _apply_date_window.
+ items = _apply_date_window(items, from_date, freshness_mode)
# Sort by views descending
items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
@@ -1226,6 +1256,7 @@ def search_and_transcribe(
to_date: str,
depth: str = "default",
token: Optional[str] = None,
+ freshness_mode: Optional[str] = None,
) -> Dict[str, Any]:
"""Full YouTube search: find videos, then fetch transcripts for top results.
@@ -1239,6 +1270,7 @@ def search_and_transcribe(
depth: 'quick', 'default', or 'deep'
token: Optional ScrapeCreators key for the per-video transcript
fallback (threaded to fetch_transcripts_parallel).
+ freshness_mode: Plan freshness mode, threaded to search_youtube().
Returns:
Dict with 'items' list. Each item has a 'transcript_snippet' field.
@@ -1249,7 +1281,9 @@ def search_and_transcribe(
items: List[Dict[str, Any]] = []
search_error: Optional[str] = None
for q in queries:
- search_result = search_youtube(q, from_date, to_date, depth)
+ search_result = search_youtube(
+ q, from_date, to_date, depth, freshness_mode=freshness_mode,
+ )
err = search_result.get("error")
if err:
search_error = _prefer_search_error(search_error, str(err))
@@ -1558,6 +1592,7 @@ def search_youtube_sc(
depth: str = "default",
token: str = None,
skip_transcript_ids: Optional[Set[str]] = None,
+ freshness_mode: Optional[str] = None,
) -> Dict[str, Any]:
"""Search YouTube via ScrapeCreators when yt-dlp is absent, empty, or thin.
@@ -1571,6 +1606,8 @@ def search_youtube_sc(
depth: 'quick', 'default', or 'deep'
token: ScrapeCreators API key
skip_transcript_ids: Video IDs already transcribed by the free search
+ freshness_mode: Plan freshness mode; scopes the out-of-window
+ fallback (see _apply_date_window). None keeps the soft fallback.
Returns:
Dict with 'items' list of video metadata dicts.
@@ -1629,13 +1666,8 @@ def search_youtube_sc(
"description": description,
})
- # Soft date filter
- recent = [i for i in items if i["date"] and i["date"] >= from_date]
- if len(recent) >= 3:
- items = recent
- _log(f"Found {len(items)} videos within date range")
- else:
- _log(f"Found {len(items)} videos ({len(recent)} within date range, keeping all)")
+ # Date filter (keep-all fallback scoped by freshness mode)
+ items = _apply_date_window(items, from_date, freshness_mode)
# Sort by views
items.sort(key=lambda x: x["engagement"]["views"], reverse=True)
diff --git a/tests/test_normalize_v3.py b/tests/test_normalize_v3.py
index 9b1f68dc..c84de001 100644
--- a/tests/test_normalize_v3.py
+++ b/tests/test_normalize_v3.py
@@ -274,8 +274,31 @@ class NormalizeV3Tests(unittest.TestCase):
)
self.assertEqual([], normalized)
- def test_youtube_keeps_older_items_when_date_window_is_empty_even_without_evergreen(self):
- """#1043: search kept out-of-window videos so transcripts could run; normalize must not drop them."""
+ def test_youtube_recent_modes_drop_transcribed_older_items_when_date_window_is_empty(self):
+ """#1043 rescue is scoped to evergreen_ok: recent topics get an honest empty result."""
+ items = [
+ {
+ "video_id": "vid-old",
+ "title": "Ghost in the Shell review",
+ "url": "https://youtube.com/watch?v=vid-old",
+ "channel_name": "Example",
+ "date": "2017-03-01",
+ "transcript_snippet": "Fetched transcript about Ghost in the Shell.",
+ "engagement": {"views": 1000, "likes": 50, "comments": 10},
+ }
+ ]
+ for mode in ("balanced_recent", "strict_recent"):
+ normalized = normalize.normalize_source_items(
+ "youtube",
+ items,
+ "2026-02-15",
+ "2026-03-17",
+ freshness_mode=mode,
+ )
+ self.assertEqual([], normalized, mode)
+
+ def test_youtube_evergreen_keeps_transcribed_older_items_when_date_window_is_empty(self):
+ """#1043: evergreen search kept out-of-window videos so transcripts could run; normalize must not drop them."""
items = [
{
"video_id": "vid-old",
@@ -292,7 +315,7 @@ class NormalizeV3Tests(unittest.TestCase):
items,
"2026-02-15",
"2026-03-17",
- freshness_mode="balanced_recent",
+ freshness_mode="evergreen_ok",
)
self.assertEqual(1, len(normalized))
self.assertEqual("vid-old", normalized[0].item_id)
@@ -324,7 +347,7 @@ class NormalizeV3Tests(unittest.TestCase):
items,
"2026-02-15",
"2026-03-17",
- freshness_mode="balanced_recent",
+ freshness_mode="evergreen_ok",
)
self.assertEqual(1, len(normalized))
self.assertEqual("vid-old", normalized[0].item_id)
diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.py
index a1508224..1ca58025 100644
--- a/tests/test_pipeline_v3.py
+++ b/tests/test_pipeline_v3.py
@@ -2796,6 +2796,19 @@ class TestSourceFetchMemo:
assert items == [] and err
assert err_state == health.TIMEOUT
+ def test_youtube_memo_is_keyed_by_freshness_mode(self):
+ [subquery] = _memo_subqueries(["youtube"], labels=("price",))
+ with patch("lib.youtube_yt.search_and_transcribe", side_effect=_youtube_payload) as yt_search, \
+ patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
+ patch("lib.env.is_youtube_comments_available", return_value=False):
+ _memo_stream("youtube", subquery, {}, freshness_mode="evergreen_ok")
+ _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
+ _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
+ assert yt_search.call_count == 2
+ assert [c.kwargs["freshness_mode"] for c in yt_search.call_args_list] == [
+ "evergreen_ok", "balanced_recent",
+ ]
+
def _thin_youtube_retry(self, config):
plan = schema.QueryPlan(
intent="general", freshness_mode="balanced_recent", cluster_mode="topic",
@@ -2814,7 +2827,8 @@ class TestSourceFetchMemo:
with patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
patch("lib.youtube_yt.search_and_transcribe", side_effect=_youtube_payload) as yt_search, \
patch("lib.env.is_youtube_comments_available", return_value=False):
- _memo_stream("youtube", subquery, {})
+ # Same run, same plan freshness mode as the retry.
+ _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
self._thin_youtube_retry({})
assert yt_search.call_count == 1
@@ -2824,7 +2838,7 @@ class TestSourceFetchMemo:
with patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
patch("lib.youtube_yt.search_and_transcribe", side_effect=responses) as yt_search, \
patch("lib.env.is_youtube_comments_available", return_value=False):
- _items, artifact = _memo_stream("youtube", subquery, {})
+ _items, artifact = _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
assert artifact["_source_outcome"]["state"] == health.TIMEOUT
self._thin_youtube_retry({})
assert yt_search.call_count == 2
diff --git a/tests/test_youtube_backstop.py b/tests/test_youtube_backstop.py
index 49b87643..78510143 100644
--- a/tests/test_youtube_backstop.py
+++ b/tests/test_youtube_backstop.py
@@ -382,3 +382,43 @@ def test_ytdlp_bot_gate_and_paid_exception_do_not_retry_paid_search():
assert artifact["_source_outcome"]["state"] == health.PARTIAL
assert "not a bot" in artifact["_source_outcome"]["detail"]
assert "SC disconnected" in artifact["_source_outcome"]["detail"]
+
+
+def test_freshness_mode_reaches_both_youtube_searches():
+ """plan.freshness_mode is threaded into the yt-dlp and ScrapeCreators searches."""
+ free = {
+ "video_id": "free", "title": "Vuori review", "date": "2026-06-15",
+ "url": "https://www.youtube.com/watch?v=free", "transcript_snippet": "free transcript",
+ }
+ plan = {
+ "intent": "how_to", "freshness_mode": "evergreen_ok", "cluster_mode": "story",
+ "subqueries": [{
+ "label": "primary", "search_query": "Vuori", "ranking_query": "Vuori",
+ "sources": ["youtube"],
+ }],
+ "source_weights": {"youtube": 1.0},
+ }
+ retrieve = pipeline._retrieve_stream
+
+ def live_youtube(*args, **kwargs):
+ return retrieve(*args, **{**kwargs, "mock": False})
+
+ with (
+ mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"),
+ mock.patch.object(pipeline, "_retrieve_stream", side_effect=live_youtube),
+ mock.patch.object(
+ youtube_yt, "search_and_transcribe", return_value={"items": [free]},
+ ) as free_search,
+ mock.patch.object(youtube_yt, "search_youtube_sc", return_value={"items": []}) as sc_search,
+ mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False),
+ ):
+ pipeline.run(
+ topic="Vuori", config={"SCRAPECREATORS_API_KEY": "dummy-key"},
+ depth="default", requested_sources=["youtube"], mock=True,
+ external_plan=plan, as_of_date="2026-07-01",
+ )
+
+ assert free_search.call_count >= 1
+ assert sc_search.call_count >= 1
+ for call in free_search.call_args_list + sc_search.call_args_list:
+ assert call.kwargs.get("freshness_mode") == "evergreen_ok"
diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.py
index 533c157a..2d15d016 100644
--- a/tests/test_youtube_yt.py
+++ b/tests/test_youtube_yt.py
@@ -1853,5 +1853,110 @@ class TestYtdlpPlayerClient(unittest.TestCase):
self.assertEqual(youtube_yt._inject_youtube_player_client(cmd), cmd)
+class TestYouTubeDateWindowByFreshnessMode(unittest.TestCase):
+ """Out-of-window soft fallback is scoped to evergreen_ok (recent topics stay honest)."""
+
+ FROM = "2026-09-11"
+ TO = "2026-10-11"
+
+ def setUp(self):
+ youtube_yt.reset_search_cache()
+ self.addCleanup(youtube_yt.reset_search_cache)
+
+ def _ytdlp_stdout(self, dates):
+ videos = [
+ {
+ "id": f"v{i}", "title": f"Ghostty video {i}", "view_count": 100 + i,
+ "like_count": 1, "comment_count": 1, "upload_date": d.replace("-", ""),
+ "description": "desc",
+ }
+ for i, d in enumerate(dates)
+ ]
+ return "\n".join(json.dumps(v) for v in videos)
+
+ def _search(self, dates, freshness_mode):
+ from lib.subproc import SubprocResult
+ result = SubprocResult(returncode=0, stdout=self._ytdlp_stdout(dates), stderr="")
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=result):
+ return youtube_yt.search_youtube(
+ "Ghostty terminal", self.FROM, self.TO, freshness_mode=freshness_mode,
+ )
+
+ def test_ytdlp_balanced_recent_with_no_in_range_videos_keeps_nothing(self):
+ out = self._search(["2017-03-01", "2020-05-05"], "balanced_recent")
+ self.assertEqual(out["items"], [])
+
+ def test_ytdlp_strict_recent_keeps_only_in_range_videos(self):
+ out = self._search(["2026-10-01", "2017-03-01", "2020-05-05"], "strict_recent")
+ self.assertEqual([i["video_id"] for i in out["items"]], ["v0"])
+
+ def test_ytdlp_evergreen_ok_still_keeps_older_videos(self):
+ out = self._search(["2017-03-01", "2020-05-05"], "evergreen_ok")
+ self.assertEqual({i["video_id"] for i in out["items"]}, {"v0", "v1"})
+
+ def test_ytdlp_unknown_mode_keeps_todays_soft_fallback(self):
+ out = self._search(["2017-03-01", "2020-05-05"], None)
+ self.assertEqual({i["video_id"] for i in out["items"]}, {"v0", "v1"})
+
+ def test_ytdlp_in_range_path_unchanged_when_three_or_more_recent(self):
+ dates = ["2026-10-01", "2026-10-02", "2026-10-03", "2017-03-01"]
+ for mode in ("balanced_recent", "evergreen_ok", None):
+ youtube_yt.reset_search_cache()
+ out = self._search(dates, mode)
+ self.assertEqual({i["video_id"] for i in out["items"]}, {"v0", "v1", "v2"}, mode)
+
+ def test_ytdlp_search_cache_does_not_leak_across_freshness_modes(self):
+ dates = ["2017-03-01", "2020-05-05"]
+ self.assertEqual(len(self._search(dates, "evergreen_ok")["items"]), 2)
+ self.assertEqual(self._search(dates, "balanced_recent")["items"], [])
+
+ def test_search_and_transcribe_threads_freshness_mode(self):
+ from lib.subproc import SubprocResult
+ result = SubprocResult(
+ returncode=0, stdout=self._ytdlp_stdout(["2017-03-01", "2020-05-05"]), stderr="",
+ )
+ with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \
+ mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=result), \
+ mock.patch.object(youtube_yt, "fetch_transcripts_parallel", return_value={}):
+ recent = youtube_yt.search_and_transcribe(
+ "Ghostty terminal", self.FROM, self.TO, freshness_mode="balanced_recent",
+ )
+ youtube_yt.reset_search_cache()
+ evergreen = youtube_yt.search_and_transcribe(
+ "Ghostty terminal", self.FROM, self.TO, freshness_mode="evergreen_ok",
+ )
+ self.assertEqual(recent["items"], [])
+ self.assertEqual({i["video_id"] for i in evergreen["items"]}, {"v0", "v1"})
+
+ def _sc_search(self, dates, freshness_mode):
+ raw = [
+ {"id": f"s{i}", "title": f"Ghostty video {i}", "views": 100 + i, "upload_date": d}
+ for i, d in enumerate(dates)
+ ]
+ with mock.patch.object(youtube_yt, "_sc_youtube_search", return_value=raw), \
+ mock.patch.object(youtube_yt, "_sc_fetch_transcript", return_value="transcript"):
+ return youtube_yt.search_youtube_sc(
+ "Ghostty terminal", self.FROM, self.TO, token="dummy-key",
+ freshness_mode=freshness_mode,
+ )
+
+ def test_sc_balanced_recent_with_no_in_range_videos_keeps_nothing(self):
+ out = self._sc_search(["2017-03-01", "2020-05-05"], "balanced_recent")
+ self.assertEqual(out["items"], [])
+
+ def test_sc_strict_recent_keeps_only_in_range_videos(self):
+ out = self._sc_search(["2026-10-01", "2017-03-01"], "strict_recent")
+ self.assertEqual([i["video_id"] for i in out["items"]], ["s0"])
+
+ def test_sc_evergreen_ok_still_keeps_older_videos(self):
+ out = self._sc_search(["2017-03-01", "2020-05-05"], "evergreen_ok")
+ self.assertEqual({i["video_id"] for i in out["items"]}, {"s0", "s1"})
+
+ def test_sc_unknown_mode_keeps_todays_soft_fallback(self):
+ out = self._sc_search(["2017-03-01", "2020-05-05"], None)
+ self.assertEqual({i["video_id"] for i in out["items"]}, {"s0", "s1"})
+
+
if __name__ == "__main__":
unittest.main()