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: apply Bird end dates to every X query (#1216)

Ilia Alshanetskyb50f06279267
diff --git a/changelog.d/+cr-014-bird-end-date.fixed.md b/changelog.d/+cr-014-bird-end-date.fixed.md
new file mode 100644
index 00000000..fc7bcdd7
--- /dev/null
+++ b/changelog.d/+cr-014-bird-end-date.fixed.md
@@ -0,0 +1 @@
+Honor the research end date in Bird X searches, including query retries, author timelines, and mentions, so newer posts cannot crowd out historical results.
diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.py
index 2fde220a..ca0361b9 100644
--- a/skills/last30days/scripts/lib/bird_x.py
+++ b/skills/last30days/scripts/lib/bird_x.py
@@ -13,7 +13,7 @@ import time
from pathlib import Path
from . import env, health, http, log, subproc
-from datetime import datetime
+from datetime import date, datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple
from .relevance import token_overlap_relevance as _compute_relevance
@@ -188,7 +188,22 @@ def _plain_query_tokens(text: str) -> list[str]:
_GROUPING_CHARS = "“”()[]{}"
-def build_topic_query(topic: str, from_date: str) -> str:
+def _date_filters(from_date: str, to_date: Optional[str] = None) -> str:
+ filters = f"since:{from_date}"
+ if to_date is not None:
+ end = date.fromisoformat(to_date)
+ if end == date.max:
+ # No supported post date lies beyond this inclusive upper bound.
+ return filters
+ # The research window includes to_date; X's until bound is exclusive.
+ until = end + timedelta(days=1)
+ filters += f" until:{until.isoformat()}"
+ return filters
+
+
+def build_topic_query(
+ topic: str, from_date: str, to_date: Optional[str] = None
+) -> str:
"""Build the X topic query, preserving quoted proper-noun phrases.
Previously the topic went through ``_plain_query_tokens``, which stripped
@@ -211,7 +226,7 @@ def build_topic_query(topic: str, from_date: str) -> str:
if (clean := token.strip("'‘’"))
]
core = " ".join(tokens).strip()
- return f"{core} since:{from_date}" if core else f"since:{from_date}"
+ return " ".join(part for part in (core, _date_filters(from_date, to_date)) if part)
def is_bird_installed() -> bool:
@@ -454,7 +469,7 @@ def search_x(
Args:
topic: Search topic
from_date: Start date (YYYY-MM-DD)
- to_date: End date (YYYY-MM-DD) - unused but kept for API compatibility
+ to_date: Inclusive end date (YYYY-MM-DD)
depth: Research depth - "quick", "default", or "deep"
Returns:
@@ -467,7 +482,8 @@ def search_x(
core_subject = _extract_core_subject(topic)
core_words = _plain_query_tokens(core_subject)
core_topic = " ".join(core_words)
- query = build_topic_query(core_subject, from_date)
+ query = build_topic_query(core_subject, from_date, to_date)
+ date_filters = _date_filters(from_date, to_date)
_log(f"Searching: {query}")
response = _run_bird_search(query, count, timeout)
@@ -484,7 +500,7 @@ def search_x(
# Build OR-group query: ("multi-agent" OR "agent simulation") since:DATE
or_parts = ' OR '.join(f'"{t}"' for t in compounds[:3])
_log(f"0 results for '{core_topic}', retrying with OR groups: {or_parts}")
- query = f"({or_parts}) since:{from_date}"
+ query = f"({or_parts}) {date_filters}"
response = _run_bird_search(query, count, timeout)
if not response.get("error"):
last_clean_response = response
@@ -494,7 +510,7 @@ def search_x(
if not items and len(core_words) > 2:
shorter = ' '.join(core_words[:2])
_log(f"0 results for '{core_topic}', retrying with '{shorter}'")
- query = f"{shorter} since:{from_date}"
+ query = f"{shorter} {date_filters}"
response = _run_bird_search(query, count, timeout)
if not response.get("error"):
last_clean_response = response
@@ -519,7 +535,7 @@ def search_x(
strongest = max(candidates, key=len)
retry_terms = anchor if strongest == anchor else f"{anchor} {strongest}"
_log(f"0 results for '{core_topic}', retrying anchored on '{retry_terms}'")
- query = f"{retry_terms} since:{from_date}"
+ query = f"{retry_terms} {date_filters}"
response = _run_bird_search(query, count, timeout)
if not response.get("error"):
last_clean_response = response
@@ -536,6 +552,8 @@ def search_handles(
from_date: str,
count_per: int = 5,
failure_out: Optional[List[str]] = None,
+ *,
+ to_date: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Search specific X handles for topic-related content.
@@ -553,11 +571,13 @@ def search_handles(
failure_out: When provided, a short reason is appended for every
per-handle failure branch, so the caller can distinguish a
transport failure from a handle that genuinely posted nothing.
+ to_date: Inclusive end date (YYYY-MM-DD), when supplied
Returns:
List of raw item dicts (same format as parse_bird_response output).
"""
core_topic = _extract_core_subject(topic) if topic else None
+ date_filters = _date_filters(from_date, to_date)
def _note(msg: str) -> None:
if failure_out is not None:
@@ -566,7 +586,7 @@ def search_handles(
def _search_one_handle(handle: str) -> List[Dict[str, Any]]:
handle = handle.lstrip("@")
# Always unfiltered: pull the timeline, rank by topic relevance below.
- query = f"from:{handle} since:{from_date}"
+ query = f"from:{handle} {date_filters}"
cmd = [
"node", str(_BIRD_SEARCH_MJS),
@@ -629,6 +649,8 @@ def search_mentions(
from_date: str,
count_per: int = 5,
failure_out: Optional[List[str]] = None,
+ *,
+ to_date: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Search for tweets ABOUT/TO each handle — the mention lane.
@@ -644,17 +666,20 @@ def search_mentions(
failure_out: When provided, a short reason is appended for every
per-handle failure branch, so the caller can distinguish a
transport failure from a handle nobody mentioned.
+ to_date: Inclusive end date (YYYY-MM-DD), when supplied
Returns:
List of raw item dicts (same format as parse_bird_response output).
"""
+ date_filters = _date_filters(from_date, to_date)
+
def _note(msg: str) -> None:
if failure_out is not None:
failure_out.append(msg)
def _search_one(handle: str) -> List[Dict[str, Any]]:
handle = handle.lstrip("@")
- query = f"@{handle} since:{from_date}"
+ query = f"@{handle} {date_filters}"
cmd = [
"node", str(_BIRD_SEARCH_MJS),
query,
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index e9b2e616..ac0794d7 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -4097,6 +4097,7 @@ def _run_supplemental_searches(
failures: list[str] = []
items = bird_x.search_handles(
hs, topic, from_date, count_per=count, failure_out=failures,
+ to_date=to_date,
)
return items, _record_handle_lane_failures("FROM", failures)
@@ -4104,6 +4105,7 @@ def _run_supplemental_searches(
failures: list[str] = []
items = bird_x.search_mentions(
hs, from_date, count_per=count, failure_out=failures,
+ to_date=to_date,
)
return items, _record_handle_lane_failures("ABOUT", failures)
elif primary == "xapi":
diff --git a/tests/test_bird_date_window.py b/tests/test_bird_date_window.py
new file mode 100644
index 00000000..f939f6b1
--- /dev/null
+++ b/tests/test_bird_date_window.py
@@ -0,0 +1,184 @@
+import json
+import threading
+from datetime import datetime, timedelta, timezone
+from unittest import mock
+
+import pytest
+
+import last30days
+from lib import bird_x, dates, pipeline, schema, subproc
+
+
+def _response(items):
+ return subproc.SubprocResult(
+ returncode=0, stdout=json.dumps({"items": items}), stderr=""
+ )
+
+
+def _tweet(post_id, created_at, author="analyst"):
+ return {
+ "id": post_id,
+ "url": f"https://x.com/{author}/status/{post_id}",
+ "author": {"username": author},
+ "text": "multi-agent autonomous systems",
+ "createdAt": created_at,
+ }
+
+
+def test_every_topic_retry_keeps_the_inclusive_end_date():
+ with mock.patch.object(
+ bird_x.subproc, "run_with_timeout", autospec=True, return_value=_response([])
+ ) as run:
+ result = bird_x.search_x(
+ "multi-agent autonomous systems", "2024-02-01", "2024-02-29"
+ )
+
+ queries = [call.args[0][2] for call in run.call_args_list]
+ assert result == {"items": []}
+ assert queries == [
+ "multi-agent autonomous systems since:2024-02-01 until:2024-03-01",
+ '("multi-agent") since:2024-02-01 until:2024-03-01',
+ "multi-agent autonomous since:2024-02-01 until:2024-03-01",
+ "multi-agent since:2024-02-01 until:2024-03-01",
+ ]
+
+
+def test_historical_search_retries_when_recent_posts_are_outside_the_window():
+ historical = _tweet("1", "2024-02-29T23:59:59Z")
+ recent = _tweet("2", "2026-10-04T12:00:00Z")
+
+ def search(cmd, **kwargs):
+ query = cmd[2]
+ if "until:2024-03-01" not in query:
+ return _response([recent])
+ if query.startswith("("):
+ return _response([historical])
+ return _response([])
+
+ with mock.patch.object(
+ bird_x.subproc, "run_with_timeout", autospec=True, side_effect=search
+ ) as run:
+ result = bird_x.search_x(
+ "multi-agent autonomous systems", "2024-02-01", "2024-02-29"
+ )
+
+ assert result["items"] == [historical]
+ assert run.call_count == 2
+
+
+def test_current_day_search_retains_posts_from_the_whole_end_date():
+ today = datetime.now(timezone.utc).date()
+ last_second = _tweet("3", f"{today.isoformat()}T23:59:59Z")
+ with mock.patch.object(
+ bird_x.subproc,
+ "run_with_timeout",
+ autospec=True,
+ return_value=_response([last_second]),
+ ) as run:
+ result = bird_x.search_x(
+ "multi-agent", (today - timedelta(days=30)).isoformat(), today.isoformat()
+ )
+
+ assert result["items"] == [last_second]
+ assert run.call_count == 1
+ assert f"until:{(today + timedelta(days=1)).isoformat()}" in run.call_args.args[0][2]
+
+
[email protected]("lane", ["topic", "from", "mentions"])
+ ("end_date", "expected_filters"),
+ [
+ ("9999-12-31", "since:9999-12-01"),
+ ("9999-12-30", "since:9999-11-30 until:9999-12-31"),
+ ],
+)
+def test_cli_maximum_end_dates_reach_every_bird_lane(lane, end_date, expected_filters):
+ args = last30days.build_parser().parse_args(["multi-agent", "--as-of", end_date])
+ from_date, to_date = dates.get_date_range(as_of_date=args.as_of_date)
+ topic = " ".join(args.topic)
+ tweet = _tweet("5", f"{end_date}T23:59:59Z")
+ with mock.patch.object(
+ bird_x.subproc,
+ "run_with_timeout",
+ autospec=True,
+ return_value=_response([tweet]),
+ ) as run:
+ if lane == "topic":
+ result = bird_x.search_x(topic, from_date, to_date)
+ items = bird_x.parse_bird_response(result, query=topic)
+ expected = topic
+ elif lane == "from":
+ items = bird_x.search_handles(["subject"], topic, from_date, to_date=to_date)
+ expected = "from:subject"
+ else:
+ items = bird_x.search_mentions(["subject"], from_date, to_date=to_date)
+ expected = "@subject"
+
+ assert [item["url"] for item in items] == [tweet["url"]]
+ assert [call.args[0][2] for call in run.call_args_list] == [
+ f"{expected} {expected_filters}"
+ ]
+
+
[email protected]("lane", ["from", "mentions"])
+def test_handle_lanes_bound_the_inclusive_end_date(lane):
+ tweet = _tweet("4", "2024-12-31T23:59:59Z")
+ with mock.patch.object(
+ bird_x.subproc,
+ "run_with_timeout",
+ autospec=True,
+ return_value=_response([tweet]),
+ ) as run:
+ if lane == "from":
+ items = bird_x.search_handles(
+ ["subject"], "multi-agent", "2024-12-01", to_date="2024-12-31"
+ )
+ expected = "from:subject"
+ else:
+ items = bird_x.search_mentions(
+ ["subject"], "2024-12-01", to_date="2024-12-31"
+ )
+ expected = "@subject"
+
+ assert [item["url"] for item in items] == [tweet["url"]]
+ assert run.call_args.args[0][2] == (
+ f"{expected} since:2024-12-01 until:2025-01-01"
+ )
+
+
+def test_pipeline_passes_the_end_date_to_both_bird_handle_lanes():
+ bundle = schema.RetrievalBundle()
+ plan = schema.QueryPlan(
+ intent="news",
+ freshness_mode="balanced_recent",
+ cluster_mode="timeline",
+ raw_topic="subject",
+ source_weights={"x": 1.0},
+ subqueries=[schema.SubQuery(
+ label="primary", search_query="subject", ranking_query="subject", sources=["x"]
+ )],
+ )
+ with mock.patch.object(
+ bird_x.subproc, "run_with_timeout", autospec=True, return_value=_response([])
+ ) as run:
+ pipeline._run_supplemental_searches(
+ topic="subject",
+ bundle=bundle,
+ plan=plan,
+ config={},
+ depth="default",
+ date_range=("2024-12-01", "2024-12-31"),
+ runtime=schema.ProviderRuntime(
+ reasoning_provider="local", planner_model="", rerank_model="",
+ x_search_backend="bird",
+ ),
+ mock=False,
+ rate_limited_sources=set(),
+ rate_limit_lock=threading.Lock(),
+ x_handle="subject",
+ )
+
+ assert sorted(call.args[0][2] for call in run.call_args_list) == [
+ "@subject since:2024-12-01 until:2025-01-01",
+ "from:subject since:2024-12-01 until:2025-01-01",
+ ]
diff --git a/tests/test_bird_x.py b/tests/test_bird_x.py
index 04bb621a..18adfa08 100644
--- a/tests/test_bird_x.py
+++ b/tests/test_bird_x.py
@@ -644,7 +644,7 @@ class TestBirdRetryQueryCorrectness(unittest.TestCase):
self.assertGreaterEqual(len(queries), 2)
self.assertEqual(
- "immobilienmakler berlin mixed-use since:2026-07-12",
+ "immobilienmakler berlin mixed-use since:2026-07-12 until:2026-07-20",
queries[0],
)
for query in queries: