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(rank): keep out-of-window evidence out of the top ranks (#993)

Matt Van Hornddc761d2c287
diff --git a/changelog.d/+recency-contract.fixed.md b/changelog.d/+recency-contract.fixed.md
new file mode 100644
index 00000000..a76e63f3
--- /dev/null
+++ b/changelog.d/+recency-contract.fixed.md
@@ -0,0 +1 @@
+Out-of-window evidence no longer leads the ranked output. Items whose dates fall outside the run's window were flagged `[date:low]` but ranked normally, so a 2025-10 video took the #1 cluster in a 2026-07 brief and a 2025-12 one took #5. Candidates whose every dated item is out of window are now demoted in both the fusion sort and `_final_score`, so they still appear as evidence but never above in-window material; items with no date at all are untouched, since an unknown date is a coverage gap rather than a stale item. The freshness verdict ("only N of M dated items are from the last 7 days") also reaches the pass-through footer instead of only the report body.
diff --git a/skills/last30days/scripts/lib/cluster.py b/skills/last30days/scripts/lib/cluster.py
index d430c399..ac7627af 100644
--- a/skills/last30days/scripts/lib/cluster.py
+++ b/skills/last30days/scripts/lib/cluster.py
@@ -4,6 +4,18 @@ from __future__ import annotations
from . import dedupe, entity_extract, schema
+
+def _cluster_sort_key(candidate: schema.Candidate) -> tuple:
+ """Sort key that partitions stale candidates below fresh ones.
+
+ Stale items (all dated source_items outside the window) must never lead
+ cluster representatives or render as the cluster title.
+ """
+ return (
+ 1 if schema.candidate_out_of_window(candidate) else 0,
+ -candidate.final_score,
+ )
+
CLUSTERABLE_INTENTS = {"breaking_news", "opinion", "comparison", "prediction"}
def _candidate_text(candidate: schema.Candidate) -> str:
@@ -20,7 +32,7 @@ def _mmr_representatives(
remaining = list(candidates)
while remaining and len(selected) < limit:
if not selected:
- best = max(remaining, key=lambda candidate: candidate.final_score)
+ best = min(remaining, key=_cluster_sort_key)
selected.append(best)
remaining_set.discard(best.candidate_id)
remaining = [c for c in remaining if c.candidate_id in remaining_set]
@@ -28,12 +40,16 @@ def _mmr_representatives(
selected_preps = [text_cache[c.candidate_id] for c in selected]
- def score(candidate: schema.Candidate) -> float:
+ def score(candidate: schema.Candidate) -> tuple:
prep = text_cache[candidate.candidate_id]
diversity_penalty = max(
dedupe.prepared_similarity(prep, sp) for sp in selected_preps
)
- return (diversity_lambda * candidate.final_score) - ((1 - diversity_lambda) * diversity_penalty * 100)
+ base_score = (diversity_lambda * candidate.final_score) - ((1 - diversity_lambda) * diversity_penalty * 100)
+ return (
+ 0 if schema.candidate_out_of_window(candidate) else 1,
+ base_score,
+ )
best = max(remaining, key=score)
selected.append(best)
@@ -89,7 +105,7 @@ def cluster_candidates(
clusters: list[schema.Cluster] = []
for index, group in enumerate(groups, start=1):
- group.sort(key=lambda candidate: candidate.final_score, reverse=True)
+ group.sort(key=_cluster_sort_key)
cluster_id = f"cluster-{index}"
representatives = _mmr_representatives(group, text_cache)
for candidate in group:
@@ -197,7 +213,7 @@ def _merge_entity_clusters(
# Pick representatives from combined pool
combined_candidates = [candidate_map[cid] for cid in combined_cids if cid in candidate_map]
- combined_candidates.sort(key=lambda c: c.final_score, reverse=True)
+ combined_candidates.sort(key=_cluster_sort_key)
merge_text_cache = {
c.candidate_id: dedupe._PreparedText(_candidate_text(c))
for c in combined_candidates
diff --git a/skills/last30days/scripts/lib/fusion.py b/skills/last30days/scripts/lib/fusion.py
index 80959d5c..469d73ad 100644
--- a/skills/last30days/scripts/lib/fusion.py
+++ b/skills/last30days/scripts/lib/fusion.py
@@ -11,7 +11,18 @@ RRF_K = 60
def _candidate_sort_key(c: schema.Candidate) -> tuple:
- return (-c.rrf_score, -c.local_relevance, -c.freshness, schema.candidate_source_label(c), c.title)
+ # Out-of-window evidence sorts strictly below anything in the window. A
+ # "last 30 days" brief that ranks a nine-month-old video at #1 breaks its
+ # own contract, however relevant that video is; it still appears, just
+ # never above in-window evidence.
+ return (
+ 1 if schema.candidate_out_of_window(c) else 0,
+ -c.rrf_score,
+ -c.local_relevance,
+ -c.freshness,
+ schema.candidate_source_label(c),
+ c.title,
+ )
def _normalize_url(url: str) -> str:
@@ -112,8 +123,16 @@ def weighted_rrf(
plan: schema.QueryPlan,
*,
pool_limit: int,
+ range_from: str | None = None,
+ range_to: str | None = None,
) -> list[schema.Candidate]:
- """Fuse ranked lists into a single candidate pool."""
+ """Fuse ranked lists into a single candidate pool.
+
+ When ``range_from`` and ``range_to`` are provided, they are stored in each
+ candidate's metadata so ``candidate_out_of_window`` can compare the actual
+ date against the run window (instead of relying solely on adapter-provided
+ ``date_confidence``).
+ """
subqueries = {subquery.label: subquery for subquery in plan.subqueries}
candidates: dict[str, schema.Candidate] = {}
# Track (source, item_id) pairs already attached to each candidate for O(1) dedup.
@@ -129,6 +148,20 @@ def weighted_rrf(
item_freshness = item.freshness if item.freshness is not None else int(item.metadata.get("freshness", 0))
item_source_quality = item.source_quality if item.source_quality is not None else float(item.metadata.get("source_quality", 0.6))
if key not in candidates:
+ candidate_metadata: dict = {
+ "provenance": [
+ {
+ "source": source,
+ "subquery_label": label,
+ "native_rank": rank,
+ "item_id": item.item_id,
+ }
+ ]
+ }
+ if range_from:
+ candidate_metadata["range_from"] = range_from
+ if range_to:
+ candidate_metadata["range_to"] = range_to
candidates[key] = schema.Candidate(
candidate_id=key,
item_id=item.item_id,
@@ -145,16 +178,7 @@ def weighted_rrf(
rrf_score=score,
sources=[item.source],
source_items=[item],
- metadata={
- "provenance": [
- {
- "source": source,
- "subquery_label": label,
- "native_rank": rank,
- "item_id": item.item_id,
- }
- ]
- },
+ metadata=candidate_metadata,
)
seen_source_items[key] = {(item.source, item.item_id)}
continue
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index db191369..e44346c2 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -724,6 +724,7 @@ def nominate_topic_pool(
query_plan: schema.QueryPlan,
plan: schema.DiscoveryPlan,
*,
+ from_date: str,
to_date: str,
limit: int,
) -> list[tuple[Nomination, str]]:
@@ -755,7 +756,13 @@ def nominate_topic_pool(
confidence floor downstream decides whether what survived is worth
showing.
"""
- candidates = weighted_rrf(bundle.items_by_source_and_query, query_plan, pool_limit=80)
+ candidates = weighted_rrf(
+ bundle.items_by_source_and_query,
+ query_plan,
+ pool_limit=80,
+ range_from=from_date,
+ range_to=to_date,
+ )
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
@@ -824,6 +831,7 @@ def nominate_topics(
query_plan: schema.QueryPlan,
plan: schema.DiscoveryPlan,
*,
+ from_date: str,
to_date: str,
limit: int,
) -> list[Nomination]:
@@ -832,7 +840,7 @@ def nominate_topics(
return [
nomination
for nomination, _cluster_id in nominate_topic_pool(
- bundle, query_plan, plan, to_date=to_date, limit=limit,
+ bundle, query_plan, plan, from_date=from_date, to_date=to_date, limit=limit,
)
]
@@ -1179,6 +1187,7 @@ def run_discover_nominate(
)
pool = nominate_topic_pool(
sweep.bundle, sweep.query_plan, sweep.plan,
+ from_date=sweep.from_date,
to_date=sweep.to_date,
limit=rerank.JUDGE_POOL_LIMIT,
)
@@ -1454,6 +1463,7 @@ def run_discover(
topic_limit = max(5, min(10, limit))
nominations = nominate_topics(
sweep.bundle, sweep.query_plan, plan,
+ from_date=from_date,
to_date=to_date,
limit=ENRICH_LIMIT if enrich else topic_limit,
)
@@ -2426,7 +2436,13 @@ def run(
elapsed=time.monotonic() - run_started,
)
source_status = _finalize_source_status(bundle.source_status, items_by_source)
- candidates = weighted_rrf(bundle.items_by_source_and_query, plan, pool_limit=settings["pool_limit"])
+ candidates = weighted_rrf(
+ bundle.items_by_source_and_query,
+ plan,
+ pool_limit=settings["pool_limit"],
+ range_from=from_date,
+ range_to=to_date,
+ )
# Normalized set of handles this run resolved for the topic. A candidate
# authored by one of these is first-party and is exempted from the
# entity-miss demotion in rerank (a post never repeats its own author's
@@ -2475,6 +2491,7 @@ def run(
ranked_candidates = sorted(
[*ranked_public, *ranked_private],
key=lambda candidate: (
+ 1 if schema.candidate_out_of_window(candidate) else 0,
-candidate.final_score,
-(candidate.engagement or -1),
min(candidate.native_ranks.values(), default=999),
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 2df23fab..0094f801 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -2994,12 +2994,23 @@ def _render_emoji_footer(report: schema.Report, save_path: str | None) -> list[s
"""
source_lines = _build_source_footer_lines(report)
voices_line = _top_voices_footer_line(report)
+ # The freshness verdict is computed for the report body, but a reader who
+ # only scans this footer never sees it — and it is the one line that says
+ # how much of the evidence is actually recent.
+ freshness_warning = _assess_data_freshness(report)
+ freshness_line = f"🕒 {freshness_warning}" if freshness_warning else None
raw_line = f"📎 Raw results saved to {save_path}" if save_path else None
body: list[str] = []
body.extend(source_lines)
if voices_line:
body.append(voices_line)
+ # Append freshness whenever it would annotate something: either the body
+ # already has content, or the raw-results line will make the footer
+ # non-empty. An otherwise empty run stays silent rather than announcing
+ # its own emptiness.
+ if freshness_line and (body or raw_line):
+ body.append(freshness_line)
if raw_line:
body.append(raw_line)
diff --git a/skills/last30days/scripts/lib/rerank.py b/skills/last30days/scripts/lib/rerank.py
index eb04d3a2..9fe3db40 100644
--- a/skills/last30days/scripts/lib/rerank.py
+++ b/skills/last30days/scripts/lib/rerank.py
@@ -756,6 +756,15 @@ def prune_fallback_entity_misses(
#: the dilute penalty. This backstop makes the demotion actually decisive.
ENTITY_MISS_FINAL_PENALTY = 20.0
+#: Multiplier applied to a candidate whose every dated item falls outside the
+#: run's window. The tool's whole promise is the window, so a stale item must
+#: not lead the ranked clusters however relevant it reads — a 2025-10 video
+#: ranked #1 in a 2026-07 brief, and a 2025-12 one ranked #5, both correctly
+#: flagged [date:low] and both ranked anyway. Scaling rather than subtracting
+#: keeps the ordering *among* older items intact, so the "still worth reading"
+#: signal survives underneath the in-window evidence.
+OUT_OF_WINDOW_FINAL_MULTIPLIER = 0.35
+
def _final_score(candidate: schema.Candidate) -> float:
normalized_rrf = _normalized_rrf(candidate.rrf_score)
@@ -780,6 +789,9 @@ def _final_score(candidate: schema.Candidate) -> float:
# at final_score level so engagement signal can't mask the demotion.
if candidate.explanation and "entity-miss" in candidate.explanation:
base = max(0.0, base - ENTITY_MISS_FINAL_PENALTY)
+ # Recency contract: out-of-window evidence never leads the ranked output.
+ if schema.candidate_out_of_window(candidate):
+ base *= OUT_OF_WINDOW_FINAL_MULTIPLIER
return base
diff --git a/skills/last30days/scripts/lib/schema.py b/skills/last30days/scripts/lib/schema.py
index 4b860ced..d93481c7 100644
--- a/skills/last30days/scripts/lib/schema.py
+++ b/skills/last30days/scripts/lib/schema.py
@@ -576,6 +576,38 @@ def candidate_source_label(candidate: Candidate) -> str:
return ", ".join(sources) if sources else "unknown"
+def candidate_out_of_window(candidate: Candidate) -> bool:
+ """True when every dated item behind this candidate falls outside the window.
+
+ Window membership is derived from the actual ``published_at`` date compared
+ to the run's ``range_from``/``range_to`` (stored in candidate.metadata by
+ fusion.weighted_rrf). Some adapters provide ``date_confidence="high"`` for
+ old dates, so relying solely on adapter-provided confidence is insufficient.
+
+ Candidates with no dated item at all are not treated as out of window — an
+ unknown date is a coverage gap, not a stale item.
+ """
+ dated = [item for item in candidate.source_items if item.published_at]
+ if not dated:
+ return False
+
+ range_from = candidate.metadata.get("range_from")
+ range_to = candidate.metadata.get("range_to")
+ if range_from and range_to:
+ try:
+ start = datetime.fromisoformat(range_from).date()
+ end = datetime.fromisoformat(range_to).date()
+ for item in dated:
+ item_date = datetime.fromisoformat(item.published_at[:10]).date()
+ if start <= item_date <= end:
+ return False
+ return True
+ except (ValueError, TypeError):
+ pass
+
+ return all(item.date_confidence != "high" for item in dated)
+
+
def candidate_best_published_at(candidate: Candidate) -> str | None:
return max(
(item.published_at for item in candidate.source_items if item.published_at),
diff --git a/tests/test_cluster_v3.py b/tests/test_cluster_v3.py
index e85aaae5..f30b1534 100644
--- a/tests/test_cluster_v3.py
+++ b/tests/test_cluster_v3.py
@@ -170,6 +170,84 @@ class TestPolymarketIsolation(unittest.TestCase):
self.assertEqual(2, len(clusters[0].candidate_ids))
+class TestStaleClusterDemotion(unittest.TestCase):
+ """Stale candidates must never become cluster representatives or titles."""
+
+ def _plan(self):
+ return schema.QueryPlan(
+ intent="breaking_news",
+ freshness_mode="strict_recent",
+ cluster_mode="story",
+ raw_topic="test",
+ subqueries=[schema.SubQuery(label="primary", search_query="test", ranking_query="test", sources=["reddit", "x"])],
+ source_weights={"reddit": 0.5, "x": 0.5},
+ )
+
+ def _candidate_with_date(
+ self, candidate_id: str, source: str, title: str, score: float,
+ published_at: str, date_confidence: str, range_from: str, range_to: str,
+ ) -> schema.Candidate:
+ item = schema.SourceItem(
+ item_id=candidate_id,
+ source=source,
+ title=title,
+ body=title,
+ url=f"https://example.com/{candidate_id}",
+ published_at=published_at,
+ date_confidence=date_confidence,
+ )
+ return schema.Candidate(
+ candidate_id=candidate_id,
+ item_id=candidate_id,
+ source=source,
+ title=title,
+ url=f"https://example.com/{candidate_id}",
+ snippet=title,
+ subquery_labels=["primary"],
+ native_ranks={"primary:reddit": 1},
+ local_relevance=0.8,
+ freshness=80,
+ engagement=10,
+ source_quality=0.7,
+ rrf_score=0.02,
+ rerank_score=score,
+ final_score=score,
+ source_items=[item],
+ metadata={"range_from": range_from, "range_to": range_to},
+ )
+
+ def test_stale_candidate_not_cluster_representative(self):
+ """A stale item with higher final_score must not lead a cluster over a fresh item.
+
+ This guards against the issue where a 2025-10 video ranked #1 in a
+ 2026-07 brief because clustering re-sorted by final_score alone.
+ """
+ range_from = "2026-06-15"
+ range_to = "2026-07-15"
+ stale = self._candidate_with_date(
+ "stale", "reddit", "Model launch reactions discussion",
+ score=95.0,
+ published_at="2025-10-15",
+ date_confidence="low",
+ range_from=range_from,
+ range_to=range_to,
+ )
+ fresh = self._candidate_with_date(
+ "fresh", "x", "Model launch reactions update",
+ score=50.0,
+ published_at="2026-07-10",
+ date_confidence="high",
+ range_from=range_from,
+ range_to=range_to,
+ )
+ candidates = [stale, fresh]
+ clusters = cluster.cluster_candidates(candidates, self._plan())
+
+ self.assertEqual(1, len(clusters))
+ self.assertEqual("fresh", clusters[0].representative_ids[0])
+ self.assertEqual(fresh.title, clusters[0].title)
+
+
class TestClusterUncertainty(unittest.TestCase):
def test_single_source_returns_single_source(self):
candidates = [make_candidate("c1", "reddit", "Title", "Body", 80)]
diff --git a/tests/test_discover_nominate_topics.py b/tests/test_discover_nominate_topics.py
index 706a70b1..06b6a621 100644
--- a/tests/test_discover_nominate_topics.py
+++ b/tests/test_discover_nominate_topics.py
@@ -77,7 +77,7 @@ def test_nominations_ranked_by_seed_velocity():
]
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("AI", ["hackernews"]), _plan("AI", ["hackernews"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
assert nominations, "expected at least one nomination"
assert "GPT-6" in nominations[0].name
@@ -95,7 +95,7 @@ def test_nominations_dedupe_names_casefold():
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("AI agents", ["hackernews", "reddit"]),
_plan("AI agents", ["hackernews", "reddit"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
names = [nomination.name.casefold() for nomination in nominations]
assert len(names) == len(set(names))
@@ -109,7 +109,7 @@ def test_fewer_clusters_than_limit_returns_all_without_padding():
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("quantum", ["hackernews"]),
_plan("quantum", ["hackernews"]),
- to_date="2026-07-10", limit=8,
+ from_date="2026-06-10", to_date="2026-07-10", limit=8,
)
assert 1 <= len(nominations) < 8
@@ -122,7 +122,7 @@ def test_zero_velocity_clusters_are_dropped():
]
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("AI", ["hackernews"]), _plan("AI", ["hackernews"]),
- to_date="2026-07-10", limit=8,
+ from_date="2026-06-10", to_date="2026-07-10", limit=8,
)
assert nominations == []
@@ -145,7 +145,7 @@ def test_names_are_short_distilled_topics_not_raw_titles():
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("AI agents", ["hackernews"]),
_plan("AI agents", ["hackernews"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
assert nominations
name = nominations[0].name
@@ -169,7 +169,7 @@ def test_no_provider_names_are_distilled_and_deterministic():
return pipeline.nominate_topics(
bundle, _query_plan("AI agents", ["hackernews"]),
_plan("AI agents", ["hackernews"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
first, second = run(), run()
@@ -197,7 +197,7 @@ def test_nomination_carries_leader_summary_and_items():
]
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("Linux", ["hackernews"]), _plan("Linux", ["hackernews"]),
- to_date="2026-07-10", limit=8,
+ from_date="2026-06-10", to_date="2026-07-10", limit=8,
)
assert nominations
top = nominations[0]
@@ -226,7 +226,7 @@ def test_same_entity_clusters_disambiguate_instead_of_dropping():
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("AI agents", ["hackernews"]),
_plan("AI agents", ["hackernews"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
assert len(nominations) == 2
@@ -259,7 +259,7 @@ def test_third_same_entity_cluster_survives_via_successive_tokens():
nominations = pipeline.nominate_topics(
_bundle(items), _query_plan("AI agents", ["hackernews"]),
_plan("AI agents", ["hackernews"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
assert len(nominations) == 3
@@ -314,7 +314,7 @@ def test_indistinguishable_distinct_representative_clusters_still_dedupe():
_bundle(items),
_query_plan("AI agents", ["hackernews", "reddit"]),
_plan("AI agents", ["hackernews", "reddit"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
assert len(nominations) == 1
@@ -358,7 +358,7 @@ def test_clusters_sharing_a_representative_dedupe_to_one():
_bundle(items),
_query_plan("AI agents", ["hackernews", "reddit"]),
_plan("AI agents", ["hackernews", "reddit"]),
- to_date="2026-07-10", limit=10,
+ from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
assert len(nominations) == 1
@@ -381,10 +381,10 @@ def test_nominate_topic_pool_pairs_nominations_with_cluster_ids():
query_plan = _query_plan("AI", ["hackernews"])
plan = _plan("AI", ["hackernews"])
pool = pipeline.nominate_topic_pool(
- bundle, query_plan, plan, to_date="2026-07-10", limit=10,
+ bundle, query_plan, plan, from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
nominations = pipeline.nominate_topics(
- bundle, query_plan, plan, to_date="2026-07-10", limit=10,
+ bundle, query_plan, plan, from_date="2026-06-10", to_date="2026-07-10", limit=10,
)
assert [nomination for nomination, _cluster_id in pool] == nominations
cluster_ids = [cluster_id for _nomination, cluster_id in pool]
diff --git a/tests/test_fusion_v3.py b/tests/test_fusion_v3.py
index 8e357847..70d4778e 100644
--- a/tests/test_fusion_v3.py
+++ b/tests/test_fusion_v3.py
@@ -435,3 +435,86 @@ class TestUrlNormalization(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+
+
+class OutOfWindowSortTests(unittest.TestCase):
+ def _candidate(self, name: str, published_at: str | None, confidence: str, rrf: float) -> schema.Candidate:
+ item = schema.SourceItem(
+ item_id=name,
+ source="youtube",
+ title=name,
+ body="body",
+ url=f"https://youtube.com/watch?v={name}",
+ published_at=published_at,
+ date_confidence=confidence,
+ )
+ return schema.Candidate(
+ candidate_id=name,
+ item_id=name,
+ source="youtube",
+ title=name,
+ url=item.url,
+ snippet="snippet",
+ subquery_labels=["primary"],
+ native_ranks={"primary:youtube": 1},
+ local_relevance=0.9,
+ freshness=90,
+ engagement=60.0,
+ source_quality=0.85,
+ rrf_score=rrf,
+ source_items=[item],
+ )
+
+ def test_out_of_window_sorts_below_in_window(self):
+ stale = self._candidate("stale", "2025-10-15", "low", rrf=0.9)
+ fresh = self._candidate("fresh", "2026-07-20", "high", rrf=0.01)
+ ordered = sorted([stale, fresh], key=fusion._candidate_sort_key)
+ self.assertEqual(["fresh", "stale"], [c.candidate_id for c in ordered])
+
+ def test_undated_candidate_keeps_its_place(self):
+ undated = self._candidate("undated", None, "low", rrf=0.9)
+ dated = self._candidate("dated", "2026-07-20", "high", rrf=0.01)
+ ordered = sorted([dated, undated], key=fusion._candidate_sort_key)
+ self.assertEqual(["undated", "dated"], [c.candidate_id for c in ordered])
+
+ def test_adapter_high_confidence_outside_window_is_still_stale(self):
+ """Adapters may supply date_confidence='high' for old dates.
+
+ The window membership must be derived from the actual date compared to
+ the run window, not solely from adapter-provided date_confidence.
+ """
+ item = schema.SourceItem(
+ item_id="old_job",
+ source="jobs",
+ title="Old job posting",
+ body="body",
+ url="https://example.com/job",
+ published_at="2025-10-15",
+ date_confidence="high",
+ )
+ stale_with_high_confidence = schema.Candidate(
+ candidate_id="stale_high",
+ item_id="old_job",
+ source="jobs",
+ title="Old job posting",
+ url="https://example.com/job",
+ snippet="snippet",
+ subquery_labels=["primary"],
+ native_ranks={"primary:jobs": 1},
+ local_relevance=0.9,
+ freshness=90,
+ engagement=60.0,
+ source_quality=0.85,
+ rrf_score=0.9,
+ source_items=[item],
+ metadata={"range_from": "2026-06-15", "range_to": "2026-07-15"},
+ )
+ fresh = self._candidate("fresh", "2026-07-10", "high", rrf=0.01)
+ fresh.metadata["range_from"] = "2026-06-15"
+ fresh.metadata["range_to"] = "2026-07-15"
+
+ self.assertTrue(schema.candidate_out_of_window(stale_with_high_confidence))
+ self.assertFalse(schema.candidate_out_of_window(fresh))
+
+ ordered = sorted([stale_with_high_confidence, fresh], key=fusion._candidate_sort_key)
+ self.assertEqual(["fresh", "stale_high"], [c.candidate_id for c in ordered])
diff --git a/tests/test_render_footer.py b/tests/test_render_footer.py
index b072e163..d862768b 100644
--- a/tests/test_render_footer.py
+++ b/tests/test_render_footer.py
@@ -183,3 +183,74 @@ def test_footer_keeps_partial_populated_source_with_warning():
assert "📸 Instagram: 1 reel" in text
assert "⚠" in text # partial suffix preserved on the populated line
+
+
+def test_footer_carries_freshness_verdict():
+ """The freshness verdict reaches the footer, not just the report body."""
+ stale = [
+ schema.SourceItem(
+ item_id=f"r{i}",
+ source="reddit",
+ title=f"Old thread {i}",
+ body="body",
+ url=f"https://reddit.com/r/test/comments/{i}",
+ published_at="2026-06-12",
+ date_confidence="high",
+ )
+ for i in range(6)
+ ]
+ report = _report(
+ items_by_source={"reddit": stale},
+ source_status={
+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=6),
+ },
+ )
+
+ text = render.render_compact(report)
+
+ assert "🕒" in text
+ assert "from the last 7 days" in text
+
+
+def test_footer_freshness_line_absent_when_evidence_is_recent():
+ fresh = [
+ schema.SourceItem(
+ item_id=f"r{i}",
+ source="reddit",
+ title=f"Fresh thread {i}",
+ body="body",
+ url=f"https://reddit.com/r/test/comments/{i}",
+ published_at="2026-07-08",
+ date_confidence="high",
+ )
+ for i in range(6)
+ ]
+ report = _report(
+ items_by_source={"reddit": fresh},
+ source_status={
+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=6),
+ },
+ )
+
+ assert "🕒" not in render.render_compact(report)
+
+
+def test_raw_results_only_footer_includes_freshness_line():
+ """AE3: raw-results-only footer still includes the freshness line.
+
+ When every source returns zero items (so source_lines would be empty and
+ body starts empty) but a save_path is provided, the freshness verdict
+ must still appear alongside the raw-results line. Without the fix,
+ `if freshness_line and body:` would be False because body was empty.
+ """
+ report = _report(
+ items_by_source={},
+ source_status={},
+ )
+
+ footer = render._render_emoji_footer(report, "/tmp/l30d-scratch/topic-raw.md")
+ text = "\n".join(footer)
+
+ assert "🕒" in text
+ assert "no usable dated evidence" in text
+ assert "Raw results saved to /tmp/l30d-scratch/topic-raw.md" in text
diff --git a/tests/test_rerank_v3.py b/tests/test_rerank_v3.py
index 4eea29b2..0cc099f3 100644
--- a/tests/test_rerank_v3.py
+++ b/tests/test_rerank_v3.py
@@ -879,5 +879,89 @@ class InteractionSignalTests(unittest.TestCase):
self.assertEqual(80.0, c.final_score) # floor only lifts, never lowers
+class TestOutOfWindowDemotion(unittest.TestCase):
+ """A "last 30 days" brief must not rank stale evidence at the top."""
+
+ def _candidate(self, name: str, published_at: str, confidence: str) -> schema.Candidate:
+ item = schema.SourceItem(
+ item_id=name,
+ source="youtube",
+ title=name,
+ body="body",
+ url=f"https://youtube.com/watch?v={name}",
+ published_at=published_at,
+ date_confidence=confidence,
+ )
+ return schema.Candidate(
+ candidate_id=name,
+ item_id=name,
+ source="youtube",
+ title=name,
+ url=item.url,
+ snippet="snippet",
+ subquery_labels=["primary"],
+ native_ranks={"primary:youtube": 1},
+ local_relevance=0.9,
+ freshness=90,
+ engagement=60.0,
+ source_quality=0.85,
+ rrf_score=0.02,
+ source_items=[item],
+ )
+
+ def test_stale_candidate_cannot_outrank_an_in_window_one(self):
+ # The stale item is the *stronger* candidate on every other signal —
+ # exactly the 2025-10 video that ranked #1 in a 2026-07 brief.
+ stale = self._candidate("stale", "2025-10-15", "low")
+ stale.rerank_score = 95.0
+ fresh = self._candidate("fresh", "2026-07-20", "high")
+ fresh.rerank_score = 55.0
+
+ stale.final_score = rerank._final_score(stale)
+ fresh.final_score = rerank._final_score(fresh)
+
+ self.assertLess(stale.final_score, fresh.final_score)
+
+ def test_undated_candidate_is_not_demoted(self):
+ undated = self._candidate("undated", "", "low")
+ undated.source_items[0].published_at = None
+ undated.rerank_score = 60.0
+ dated = self._candidate("dated", "2026-07-20", "high")
+ dated.rerank_score = 60.0
+
+ self.assertEqual(rerank._final_score(undated), rerank._final_score(dated))
+
+ def test_stale_cannot_lead_in_final_sort_even_with_dominant_score(self):
+ """AE2: stale rerank_score=95 vs in-window rerank_score=10 — stale sorts below.
+
+ The 0.35 multiplier alone is not enough: stale 95 * 0.35 ≈ 33 still beats
+ fresh 10. The final sort key (the same as pipeline.run's final sort) must
+ partition stale below fresh, regardless of individual final_score values.
+ """
+ stale = self._candidate("stale", "2025-10-15", "low")
+ stale.rerank_score = 95.0
+ fresh = self._candidate("fresh", "2026-07-20", "high")
+ fresh.rerank_score = 10.0
+
+ stale.final_score = rerank._final_score(stale)
+ fresh.final_score = rerank._final_score(fresh)
+
+ self.assertGreater(stale.final_score, fresh.final_score)
+
+ sorted_candidates = sorted(
+ [stale, fresh],
+ key=lambda candidate: (
+ 1 if schema.candidate_out_of_window(candidate) else 0,
+ -candidate.final_score,
+ -(candidate.engagement or -1),
+ candidate.candidate_id,
+ ),
+ )
+ self.assertEqual(
+ ["fresh", "stale"],
+ [c.candidate_id for c in sorted_candidates],
+ )
+
+
if __name__ == "__main__":
unittest.main()