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: X first-party authorship grounding + interaction-signal ranking (#613)

Matt Van Horn214a8fa059fe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 10f3903d..156d6582 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **First-party X posts are no longer buried.** A post authored by one of the run's resolved handles (`--x-handle`, `--x-related`, the GitHub user) is now treated as first-class evidence: it is exempt from the entity-miss demotion (a post never repeats its own author's name, so the body-text grounding check used to zero out the subject's own highest-signal posts) and gets a small authorship credit. Third-party collision-noise suppression is unchanged.
+- **Engagement rescue for on-topic X posts.** A high-engagement X post that is first-party or entity-grounded gets a `final_score` floor scaled by its engagement percentile within the run's X pool, so a viral on-topic post can't sit at ~0. Off-topic name-collision posts are explicitly excluded.
+- **First-party interaction signal.** A first-party post directed at another account (a reply / leading @mention) is floated into the visible band regardless of like-count and tagged `interaction:→@handle` in the EVIDENCE block, so the synthesis reads it as a relationship signal rather than low-engagement noise. New **LAW 10** in SKILL.md teaches the model to surface first-party posts and read the interaction tag.
+
+### Changed
+
+- The X FROM lane (the subject's own timeline) now pulls up to 8 posts per handle (was 3); the about/related lanes stay modest.
+
## [3.5.0] - 2026-06-18
### Added
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 45fbbe5f..c4ac1c48 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -213,6 +213,8 @@ Named-entity topics (capitalized proper nouns, product names, person names, proj
**Observed LAW 9 need (2026-06-17):** five consecutive runs (Kanye, Steinberger, Kevin Rose, Lan Xuezhao, Matt-vs-Trevin) shipped news-shaped reports that missed every funny comment, fabricated one citation URL, and leaked tooling meta-commentary - because the comment-weaving rule lived at line ~1189/1245, below the chunked-read window, and `## Best Takes` was empty (no in-subprocess fun scorer). The fix is two-part: the engine now always surfaces `## Top Community Comments` regardless of fun scoring, and this LAW hoists the weave-the-comments gate into the guaranteed-loaded band. Same hoist that fixed LAW 8.
+**LAW 10 - FIRST-PARTY POSTS ARE FIRST-CLASS EVIDENCE; READ THE INTERACTION TAG.** On a person topic, the subject's OWN posts (the `from:{handle}` lane) are the single richest vein - they are now surfaced into the EVIDENCE block as ranked evidence, not buried. When the subject has posts in the evidence, quote and weigh them as primary signal; do not lean on third-party coverage (podcasts, articles) for the subject's voice when their own posts are present. An evidence line tagged `interaction:→@handle` is the subject's own post directed at another account (a reply/mention): treat it as a RELATIONSHIP signal worth reading even at near-zero engagement - who someone personally, repeatedly engages is meaningful, and engagement count does not capture it. Surface what the interaction shows about the subject; per LAW 9, never narrate the tag or the mechanism in the deliverable (no "the engine flagged an interaction" / no "scored as first-party") - just read the signal and write the substance.
+
End of OUTPUT CONTRACT. The laws above are the contract; everything below is implementation detail.
---
diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.py
index 41d61ddf..64c99efe 100644
--- a/skills/last30days/scripts/lib/bird_x.py
+++ b/skills/last30days/scripts/lib/bird_x.py
@@ -24,6 +24,24 @@ MAX_JSON_DECODE_RETRIES = 2
JSON_DECODE_RETRY_DELAY = 5.0 # seconds between retry attempts
+def _leading_mentions(text: str) -> list:
+ """Return the handles a post is directed at: the leading run of @mentions in the text.
+
+ X replies open with the target handle(s) (e.g. "@someone thanks!"), so the
+ leading run identifies who the post is addressed to. A mention later in the
+ body is not a reply target and is intentionally ignored. Returns normalized
+ (``@``-stripped, lowercased) handles, in order.
+ """
+ out: list = []
+ for token in (text or "").split():
+ tok = token.strip(",.:;!?")
+ if tok.startswith("@") and len(tok) > 1:
+ out.append(tok[1:].lower())
+ else:
+ break
+ return out
+
+
def _first_of(*values):
"""Return first value that is not None."""
for v in values:
@@ -608,11 +626,16 @@ def parse_bird_response(response: Dict[str, Any], query: str = "") -> List[Dict[
engagement[key] = None
# Build normalized item
+ text = str(tweet.get("text", tweet.get("full_text", ""))).strip()[:500]
item = {
"id": f"X{i+1}",
- "text": str(tweet.get("text", tweet.get("full_text", ""))).strip()[:500],
+ "text": text,
"url": url,
"author_handle": author_handle.lstrip("@"),
+ # Leading @mentions parsed from the post text identify who a reply is
+ # directed at (X replies open with the target handle(s)). Used by the
+ # interaction-signal classifier in rerank.
+ "mentioned_handles": _leading_mentions(text),
"date": date,
"engagement": engagement if any(v is not None for v in engagement.values()) else None,
"why_relevant": "", # Bird doesn't provide relevance explanations
diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.py
index 8a4a21a6..5bbfefe0 100644
--- a/skills/last30days/scripts/lib/normalize.py
+++ b/skills/last30days/scripts/lib/normalize.py
@@ -230,6 +230,7 @@ def _normalize_x(
to_date: str,
) -> schema.SourceItem:
text = str(item.get("text") or "").strip()
+ mentioned = item.get("mentioned_handles") or []
return _source_item(
item_id=str(item.get("id") or f"X{index + 1}"),
source=source,
@@ -242,6 +243,7 @@ def _normalize_x(
engagement=item.get("engagement") or {},
relevance_hint=item.get("relevance", 0.5),
why_relevant=str(item.get("why_relevant") or ""),
+ metadata={"mentioned_handles": list(mentioned)} if mentioned else {},
)
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index c8ae6335..9c6dbce2 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -68,6 +68,14 @@ SEARCH_ALIAS = {
MAX_SOURCE_FETCHES: dict[str, int] = {"x": 2, "jobs": 1}
+# Per-handle result caps for the X handle-search lanes. The FROM lane (the
+# subject's own timeline) is the single best source for a person topic, so it
+# gets the highest cap; the ABOUT (mention) and related-handle lanes stay
+# modest so total volume and request budget don't balloon.
+FROM_LANE_COUNT_PER = 8
+MENTION_LANE_COUNT_PER = 5
+RELATED_HANDLE_COUNT_PER = 3
+
MOCK_AVAILABLE_SOURCES = [
"reddit",
"x",
@@ -523,6 +531,16 @@ def run(
bundle.items_by_source, topic=topic, config=config, depth=depth, mock=mock,
)
candidates = weighted_rrf(bundle.items_by_source_and_query, plan, pool_limit=settings["pool_limit"])
+ # 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
+ # name, so the body-text grounding check would otherwise zero out the
+ # subject's own highest-signal posts).
+ resolved_handles = {
+ h.lstrip("@").strip().lower()
+ for h in ([x_handle, github_user, *(x_related or [])])
+ if h and h.strip()
+ }
ranked_candidates = rerank.rerank_candidates(
topic=topic,
plan=plan,
@@ -530,6 +548,7 @@ def run(
provider=None if mock else reasoning_provider,
model=None if mock else runtime.rerank_model,
shortlist_size=settings["rerank_limit"],
+ resolved_handles=resolved_handles,
)
rerank.score_fun(
topic=topic,
@@ -864,13 +883,13 @@ def _run_supplemental_searches(
from_items: list = []
about_items: list = []
try:
- from_items = bird_x.search_handles(handles, topic, from_date, count_per=3)
+ from_items = bird_x.search_handles(handles, topic, from_date, count_per=FROM_LANE_COUNT_PER)
except Exception as exc:
print(f"[Pipeline] Phase 2 FROM-lane search failed: {exc}", file=sys.stderr)
if not bundle.items_by_source.get("x"):
bundle.errors_by_source["x"] = f"Phase 2 FROM-lane: {exc}"
try:
- about_items = bird_x.search_mentions(handles, from_date, count_per=3)
+ about_items = bird_x.search_mentions(handles, from_date, count_per=MENTION_LANE_COUNT_PER)
except Exception as exc:
print(f"[Pipeline] Phase 2 ABOUT-lane search failed: {exc}", file=sys.stderr)
raw_items = from_items + about_items
@@ -894,7 +913,7 @@ def _run_supplemental_searches(
if related_handles:
try:
raw_items = bird_x.search_handles(
- related_handles, topic, from_date, count_per=3,
+ related_handles, topic, from_date, count_per=RELATED_HANDLE_COUNT_PER,
)
except Exception as exc:
print(f"[Pipeline] Phase 2 related handle search failed: {exc}", file=sys.stderr)
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 756ecb26..969d7434 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -1195,6 +1195,12 @@ def _render_candidate(candidate: schema.Candidate, prefix: str) -> list[str]:
]
if candidate.fun_score is not None and candidate.fun_score >= 50:
detail_parts.append(f"fun:{candidate.fun_score:.0f}")
+ # First-party interaction tag: this is the subject's own post directed at
+ # another account (a reply/mention). Signals a relationship the synthesis
+ # should read even at low engagement, not noise.
+ interaction_targets = (candidate.metadata or {}).get("interaction_targets")
+ if interaction_targets:
+ detail_parts.append("interaction:→@" + ",@".join(interaction_targets[:2]))
details = " | ".join(part for part in detail_parts if part)
lines = [
f"{prefix} [{schema.candidate_source_label(candidate)}] {candidate.title}",
diff --git a/skills/last30days/scripts/lib/rerank.py b/skills/last30days/scripts/lib/rerank.py
index 1e702ef6..11a8f3b6 100644
--- a/skills/last30days/scripts/lib/rerank.py
+++ b/skills/last30days/scripts/lib/rerank.py
@@ -17,6 +17,41 @@ from . import http, providers, query, schema, signals
# Hermes content.
ENTITY_MISS_PENALTY = 25.0
+# Small additive credit for a post authored by one of the run's resolved
+# handles (see rerank_candidates / _fallback_tuple). Deliberately small: the
+# goal is to stop *burying* first-party posts, not to auto-win the ranking on
+# authorship alone. A strong on-topic third-party item (high LLM relevance)
+# still outranks a thin first-party one; this only lifts first-party off the
+# neutral floor so it survives into the visible band.
+FIRST_PARTY_AUTHOR_CREDIT = 5.0
+
+# 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
+# adapts to each topic's engagement scale) and is bounded by RESCUE_FLOOR_MAX.
+# Critically it is NEVER applied to entity-miss-demoted (off-topic collision)
+# posts, so viral name-collision noise (Lanzhou clips, namesakes) stays buried.
+RESCUE_FLOOR_MAX = 40.0
+
+# Interaction signal: a first-party post directed AT another account (a reply /
+# leading @mention) carries relational signal — who the subject is personally
+# engaging — that no keyword or like-count surfaces. It is floated to a minimum
+# final_score so it survives into the visible band regardless of engagement,
+# and tagged (candidate.metadata["interaction_targets"]) so the synthesizing
+# model reads it as relational, not noise. Floor (not additive) so it composes
+# with the engagement rescue without unbounded stacking.
+INTERACTION_FLOOR = 35.0
+
+# First-party survival floor. A post authored by a resolved handle must clear
+# the zero band regardless of which scoring path ran. The fallback path already
+# exempts it from the entity-miss penalty, but on the LLM rerank path the model
+# is instructed to cap any candidate that doesn't name the entity at <=30 (and a
+# post never names its own author), which would re-bury plain low-engagement
+# first-party posts. This floor is the deterministic backstop; it is modest
+# (well below strong on-topic evidence at 50+) so authorship buys visibility,
+# not a win.
+FIRST_PARTY_FLOOR = 25.0
+
# Intent modifiers to strip before extracting the primary entity so that,
# for example, "Hermes Agent use cases" yields primary_entity="hermes agent"
# rather than "hermes agent use cases". Kept in sync with
@@ -83,24 +118,40 @@ def rerank_candidates(
provider: providers.ReasoningClient | None,
model: str | None,
shortlist_size: int,
+ resolved_handles: set[str] | None = None,
) -> list[schema.Candidate]:
- """Rerank the fused shortlist, demoting candidates the reranker scored as irrelevant."""
+ """Rerank the fused shortlist, demoting candidates the reranker scored as irrelevant.
+
+ ``resolved_handles`` is the normalized (``@``-stripped, lowercased) set of
+ handles the run resolved for the topic (``--x-handle``, ``--x-related``, and
+ the GitHub user). A candidate authored by one of these is first-party: it is
+ exempted from the entity-miss demotion in ``_fallback_tuple`` (a post almost
+ never repeats its own author's name, so the body-text grounding check would
+ otherwise bury the subject's own highest-signal posts).
+ """
+ handles = resolved_handles or set()
shortlisted = candidates[:shortlist_size]
primary_entity = _primary_entity(topic)
if provider and model and shortlisted:
try:
- response = provider.generate_json(model, _build_prompt(topic, plan, shortlisted, primary_entity))
- _apply_llm_scores(shortlisted, response)
+ response = provider.generate_json(
+ model, _build_prompt(topic, plan, shortlisted, primary_entity, resolved_handles=handles)
+ )
+ _apply_llm_scores(shortlisted, response, resolved_handles=handles)
except (ValueError, KeyError, json.JSONDecodeError, OSError, http.HTTPError) as exc:
import sys
print(f"[Rerank] LLM reranking failed, using local fallback: {type(exc).__name__}: {exc}", file=sys.stderr)
- _apply_fallback_scores(shortlisted, primary_entity=primary_entity)
+ _apply_fallback_scores(shortlisted, primary_entity=primary_entity, resolved_handles=handles)
else:
- _apply_fallback_scores(shortlisted, primary_entity=primary_entity)
+ _apply_fallback_scores(shortlisted, primary_entity=primary_entity, resolved_handles=handles)
if len(candidates) > shortlist_size:
tail = candidates[shortlist_size:]
- _apply_fallback_scores(tail, primary_entity=primary_entity)
+ _apply_fallback_scores(tail, primary_entity=primary_entity, resolved_handles=handles)
+
+ _apply_first_party_floor(candidates, resolved_handles=handles)
+ _apply_engagement_rescue(candidates, primary_entity=primary_entity, resolved_handles=handles)
+ _apply_interaction_signal(candidates, resolved_handles=handles)
return sorted(
candidates,
@@ -130,23 +181,39 @@ def _fenced_untrusted_content(candidate_block: str) -> str:
)
-def _build_prompt(topic: str, plan: schema.QueryPlan, candidates: list[schema.Candidate], primary_entity: str = "") -> str:
+def _build_prompt(
+ topic: str,
+ plan: schema.QueryPlan,
+ candidates: list[schema.Candidate],
+ primary_entity: str = "",
+ resolved_handles: set[str] | None = None,
+) -> str:
+ handles = resolved_handles or set()
ranking_queries = "\n".join(
f"- {subquery.label}: {subquery.ranking_query}"
for subquery in plan.subqueries
)
+
+ def _candidate_lines(candidate: schema.Candidate) -> list[str]:
+ author = _candidate_author_handle(candidate)
+ lines = [
+ f"- candidate_id: {candidate.candidate_id}",
+ f" sources: {schema.candidate_source_label(candidate)}",
+ f" title: {candidate.title[:220]}",
+ f" snippet: {candidate.snippet[:420]}",
+ f" date: {schema.candidate_best_published_at(candidate) or 'unknown'}",
+ f" matched_subqueries: {', '.join(candidate.subquery_labels)}",
+ ]
+ if author:
+ lines.append(f" author: @{author}")
+ # Flag first-party posts so the model does not apply the entity-grounding
+ # cap to the subject's own posts (which never name their own author).
+ if author and author in handles:
+ lines.append(" first_party: true (authored by the subject)")
+ return lines
+
candidate_block = "\n".join(
- "\n".join(
- [
- f"- candidate_id: {candidate.candidate_id}",
- f" sources: {schema.candidate_source_label(candidate)}",
- f" title: {candidate.title[:220]}",
- f" snippet: {candidate.snippet[:420]}",
- f" date: {schema.candidate_best_published_at(candidate) or 'unknown'}",
- f" matched_subqueries: {', '.join(candidate.subquery_labels)}",
- ]
- )
- for candidate in candidates
+ "\n".join(_candidate_lines(candidate)) for candidate in candidates
)
grounding_hint = ""
if primary_entity:
@@ -156,7 +223,10 @@ def _build_prompt(topic: str, plan: schema.QueryPlan, candidates: list[schema.Ca
"in its title or snippet should score no higher than 30, regardless of other "
"signals. Do not let a candidate match the topic vicinity without matching the "
"entity itself. 2026-04-19 Hermes Agent Use Cases failure: a Nate Herk video "
- "about Claude's Managed Agents scored 51 with zero Hermes content.\n"
+ "about Claude's Managed Agents scored 51 with zero Hermes content. "
+ "EXCEPTION: a candidate marked `first_party: true` is the subject's own post - "
+ "it is first-class evidence about the subject and is EXEMPT from this cap. Score "
+ "it on its own merits (a person rarely names themselves in their own post).\n"
)
return f"""
Judge search-result relevance for a last-30-days research pipeline.
@@ -187,7 +257,10 @@ Scoring guidance:
""".strip()
-def _apply_llm_scores(candidates: list[schema.Candidate], payload: dict) -> None:
+def _apply_llm_scores(
+ candidates: list[schema.Candidate], payload: dict, *, resolved_handles: set[str] | None = None
+) -> None:
+ handles = resolved_handles or set()
scores = {}
for row in payload.get("scores") or []:
if not isinstance(row, dict):
@@ -200,20 +273,158 @@ def _apply_llm_scores(candidates: list[schema.Candidate], payload: dict) -> None
str(row.get("reason") or "").strip() or None,
)
for candidate in candidates:
- rerank_score, reason = scores.get(candidate.candidate_id, _fallback_tuple(candidate))
+ rerank_score, reason = scores.get(
+ candidate.candidate_id, _fallback_tuple(candidate, resolved_handles=handles)
+ )
candidate.rerank_score = rerank_score
candidate.explanation = reason
candidate.final_score = _final_score(candidate)
-def _apply_fallback_scores(candidates: list[schema.Candidate], *, primary_entity: str = "") -> None:
+def _apply_fallback_scores(
+ candidates: list[schema.Candidate], *, primary_entity: str = "", resolved_handles: set[str] | None = None
+) -> None:
+ handles = resolved_handles or set()
for candidate in candidates:
- rerank_score, reason = _fallback_tuple(candidate, primary_entity=primary_entity)
+ rerank_score, reason = _fallback_tuple(candidate, primary_entity=primary_entity, resolved_handles=handles)
candidate.rerank_score = rerank_score
candidate.explanation = reason
candidate.final_score = _final_score(candidate)
+def _candidate_author_handle(candidate: schema.Candidate) -> str:
+ """Representative normalized author handle for a candidate, or '' if none.
+
+ Reads ``SourceItem.author`` (set from the X ``author_handle`` in
+ normalize._normalize_x, already ``@``-stripped) on the first authored
+ source item, falling back to that item's ``metadata.author_handle``.
+ Normalized ``@``-stripped + lowercased to match the resolved-handle set.
+ """
+ for item in candidate.source_items:
+ raw = item.author or (item.metadata or {}).get("author_handle") or ""
+ handle = str(raw).lstrip("@").strip().lower()
+ if handle:
+ return handle
+ return ""
+
+
+def _is_first_party(candidate: schema.Candidate, resolved_handles: set[str]) -> bool:
+ """True when the candidate is authored by one of the run's resolved handles."""
+ if not resolved_handles:
+ return False
+ return _candidate_author_handle(candidate) in resolved_handles
+
+
+def _is_x_candidate(candidate: schema.Candidate) -> bool:
+ """True when the candidate originates from X (top-level or any source item)."""
+ if candidate.source == "x":
+ return True
+ return any(getattr(item, "source", None) == "x" for item in candidate.source_items)
+
+
+def _candidate_engagement(candidate: schema.Candidate) -> float:
+ return candidate.engagement if candidate.engagement is not None else 0.0
+
+
+def _is_entity_grounded(candidate: schema.Candidate, primary_entity: str) -> bool:
+ """Whether the candidate plausibly mentions the primary entity in its text.
+
+ Mirrors the grounding gate used for the entity-miss demotion: no
+ primary_entity means everything is grounded; otherwise the candidate must
+ have text that contains the entity's head token.
+ """
+ if not primary_entity:
+ return True
+ haystack = _candidate_haystack(candidate)
+ return bool(haystack.strip()) and _entity_grounded(haystack, primary_entity)
+
+
+def _rescue_floor(percentile: float) -> float:
+ """Engagement rescue floor: 0 at/below the median, scaling linearly to
+ RESCUE_FLOOR_MAX at the top of the X pool."""
+ if percentile <= 0.5:
+ return 0.0
+ return ((percentile - 0.5) / 0.5) * RESCUE_FLOOR_MAX
+
+
+def _candidate_mentioned_handles(candidate: schema.Candidate) -> set[str]:
+ """Normalized handles the candidate's post is directed at (leading @mentions
+ parsed at ingest into source-item metadata)."""
+ handles: set[str] = set()
+ for item in candidate.source_items:
+ for h in (item.metadata or {}).get("mentioned_handles") or []:
+ norm = str(h).lstrip("@").strip().lower()
+ if norm:
+ handles.add(norm)
+ return handles
+
+
+def _interaction_targets(candidate: schema.Candidate, resolved_handles: set[str]) -> set[str]:
+ """Accounts a first-party post is directed at, excluding the subject's own
+ handles. Empty unless the candidate is first-party AND addresses someone
+ other than the subject."""
+ if not _is_first_party(candidate, resolved_handles):
+ return set()
+ return _candidate_mentioned_handles(candidate) - resolved_handles
+
+
+def _apply_interaction_signal(
+ candidates: list[schema.Candidate], *, resolved_handles: set[str]
+) -> None:
+ """Float and tag first-party posts directed at another account. The relational
+ tell (the subject personally engaging someone) is invisible to keyword and
+ engagement scoring, so these are floored into the visible band and tagged so
+ synthesis reads them as signal."""
+ if not resolved_handles:
+ return
+ for c in candidates:
+ targets = _interaction_targets(c, resolved_handles)
+ if not targets:
+ continue
+ c.metadata = {**(c.metadata or {}), "interaction_targets": sorted(targets)}
+ if c.final_score < INTERACTION_FLOOR:
+ c.final_score = INTERACTION_FLOOR
+
+
+def _apply_first_party_floor(
+ candidates: list[schema.Candidate], *, resolved_handles: set[str]
+) -> None:
+ """Floor every first-party post above the zero band, on any scoring path.
+
+ Backstops the LLM rerank path, where the grounding hint would otherwise cap
+ a first-party post (which never names its own author) at <=30 and re-bury
+ it. Floor only lifts; it never lowers a post the scorer rated higher.
+ """
+ if not resolved_handles:
+ return
+ for c in candidates:
+ if _is_first_party(c, resolved_handles) and c.final_score < FIRST_PARTY_FLOOR:
+ c.final_score = FIRST_PARTY_FLOOR
+
+
+def _apply_engagement_rescue(
+ candidates: list[schema.Candidate], *, primary_entity: str, resolved_handles: set[str]
+) -> None:
+ """Floor final_score for high-engagement X posts that are first-party or
+ entity-grounded, so a viral on-topic post can't sit at ~0. Off-topic
+ (entity-miss) collision posts are excluded, preserving noise suppression.
+ """
+ x_cands = [c for c in candidates if _is_x_candidate(c)]
+ if len(x_cands) < 2:
+ return
+ engagements = sorted(_candidate_engagement(c) for c in x_cands)
+ n = len(engagements)
+ for c in x_cands:
+ if not (_is_first_party(c, resolved_handles) or _is_entity_grounded(c, primary_entity)):
+ continue
+ e = _candidate_engagement(c)
+ # Percentile rank in [0, 1]: fraction of the X pool strictly below e.
+ percentile = sum(1 for v in engagements if v < e) / (n - 1)
+ floor = _rescue_floor(percentile)
+ if floor > c.final_score:
+ c.final_score = floor
+
+
def _candidate_haystack(candidate: schema.Candidate) -> str:
"""Build the lowercase text blob against which entity-grounding is checked.
@@ -271,13 +482,27 @@ def _entity_grounded(haystack: str, primary_entity: str) -> bool:
return tokens[0] in haystack
-def _fallback_tuple(candidate: schema.Candidate, *, primary_entity: str = "") -> tuple[float, str]:
+def _fallback_tuple(
+ candidate: schema.Candidate, *, primary_entity: str = "", resolved_handles: set[str] | None = None
+) -> tuple[float, str]:
score = (
(candidate.local_relevance * 100.0 * 0.7)
+ (candidate.freshness * 0.2)
+ (candidate.source_quality * 100.0 * 0.1)
)
reason = "fallback-local-score"
+ # First-party authorship grounding: a post authored by one of the run's
+ # resolved handles is first-class evidence about the subject and is exempt
+ # from the entity-miss demotion below. Nobody repeats their own name in
+ # their own post, so the body-text grounding check would otherwise bury the
+ # subject's own highest-signal posts (the single richest vein on X for a
+ # person topic). Because the reason string carries no "entity-miss" marker,
+ # _final_score's secondary penalty (which greps for it) is also skipped.
+ # A small bounded credit lifts a first-party post just off neutral without
+ # letting authorship alone outrank a genuinely strong on-topic third party.
+ if resolved_handles and _is_first_party(candidate, resolved_handles):
+ score += FIRST_PARTY_AUTHOR_CREDIT
+ return max(0.0, min(100.0, score)), "fallback-local-score (first-party authorship)"
# Entity-grounding demotion: subtract ENTITY_MISS_PENALTY when the candidate
# never mentions the primary entity's head token, across all text surfaces
# (title, snippet, transcript, transcript highlights, top comments,
diff --git a/tests/test_bird_x.py b/tests/test_bird_x.py
index 412b3c31..be859714 100644
--- a/tests/test_bird_x.py
+++ b/tests/test_bird_x.py
@@ -505,3 +505,32 @@ class TestStrongestTokenRetryAnchored(unittest.TestCase):
self.assertTrue(queries)
self.assertIn("agentcookie", queries[-1])
+
+
+class LeadingMentionsTests(unittest.TestCase):
+ """U5: leading @mentions parsed from post text identify reply targets."""
+
+ def test_single_leading_mention(self):
+ from lib import bird_x
+ self.assertEqual(["alpha"], bird_x._leading_mentions("@alpha thanks so much!"))
+
+ def test_multiple_leading_mentions(self):
+ from lib import bird_x
+ self.assertEqual(["alpha", "beta"], bird_x._leading_mentions("@alpha @beta hi"))
+
+ def test_in_body_mention_not_collected(self):
+ from lib import bird_x
+ self.assertEqual([], bird_x._leading_mentions("hello @gamma nice work"))
+
+ def test_punctuation_stripped(self):
+ from lib import bird_x
+ self.assertEqual(["alpha"], bird_x._leading_mentions("@alpha, nice"))
+
+ def test_empty_text(self):
+ from lib import bird_x
+ self.assertEqual([], bird_x._leading_mentions(""))
+ self.assertEqual([], bird_x._leading_mentions(None))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.py
index 67cc22fe..9a081c15 100644
--- a/tests/test_pipeline_v3.py
+++ b/tests/test_pipeline_v3.py
@@ -501,6 +501,35 @@ class TestSupplementalSearches(unittest.TestCase):
f"Duplicate URL found: {urls}",
)
+ @patch("lib.bird_x.search_mentions")
+ @patch("lib.bird_x.search_handles")
+ @patch("lib.entity_extract.extract_entities")
+ def test_from_lane_uses_raised_cap_mention_lane_modest(self, mock_extract, mock_handles, mock_mentions):
+ """U4: the FROM lane (subject's own timeline) uses the raised per-handle
+ cap; the mention lane stays modest."""
+ mock_extract.return_value = {"x_handles": ["subject1"], "x_hashtags": [], "reddit_subreddits": []}
+ mock_handles.return_value = []
+ mock_mentions.return_value = []
+ bundle = schema.RetrievalBundle()
+ bundle.items_by_source["x"] = [
+ _make_source_item("x", "X1", "https://x.com/subject1/status/1", author="subject1", body="hi"),
+ ]
+ pipeline._run_supplemental_searches(
+ topic="subject1",
+ bundle=bundle,
+ plan=_make_plan("subject1"),
+ config={},
+ depth="default",
+ date_range=("2026-02-15", "2026-03-17"),
+ runtime=_make_runtime("bird"),
+ mock=False,
+ rate_limited_sources=set(),
+ rate_limit_lock=threading.Lock(),
+ )
+ from_call = mock_handles.call_args_list[0]
+ self.assertEqual(pipeline.FROM_LANE_COUNT_PER, from_call.kwargs.get("count_per"))
+ self.assertEqual(pipeline.MENTION_LANE_COUNT_PER, mock_mentions.call_args.kwargs.get("count_per"))
+
def test_phase2_skipped_in_quick_mode(self):
"""_run_supplemental_searches should return immediately when depth='quick'."""
bundle = schema.RetrievalBundle()
diff --git a/tests/test_rerank_v3.py b/tests/test_rerank_v3.py
index c7efdc20..175b5605 100644
--- a/tests/test_rerank_v3.py
+++ b/tests/test_rerank_v3.py
@@ -404,5 +404,337 @@ class ExpandedHaystackTests(unittest.TestCase):
# should not fire; final_score reflects only base signal.
self.assertNotIn("entity-miss", on_topic.explanation or "")
+class FirstPartyAuthorshipTests(unittest.TestCase):
+ """U2: a post authored by one of the run's resolved handles is first-party
+ evidence and is exempt from the entity-miss demotion. Nobody repeats their
+ own name in their own post, so the body-text grounding check would
+ otherwise bury the subject's own highest-signal posts.
+ """
+
+ def _x_candidate(self, *, author: str | None, text: str) -> schema.Candidate:
+ item = schema.SourceItem(
+ item_id="x1",
+ source="x",
+ title=text,
+ body=text,
+ url="https://x.com/somebody/status/1",
+ author=author,
+ snippet=text,
+ )
+ return schema.Candidate(
+ candidate_id=f"x-{author or 'none'}",
+ item_id="x1",
+ source="x",
+ title=text,
+ url=item.url,
+ snippet=text,
+ subquery_labels=["primary"],
+ native_ranks={"primary:x": 1},
+ local_relevance=0.5,
+ freshness=80,
+ engagement=50,
+ source_quality=0.6,
+ rrf_score=0.02,
+ source_items=[item],
+ )
+
+ def test_first_party_post_exempt_from_entity_miss(self):
+ # The subject's own post that never repeats their name. Without the
+ # exemption this is the canonical score-0 failure; with it, no demotion.
+ c = self._x_candidate(author="mvanhorn", text="every agentic engineering hack I know")
+ rerank._apply_fallback_scores(
+ [c], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertIn("first-party", c.explanation or "")
+ self.assertNotIn("entity-miss", c.explanation or "")
+
+ def test_third_party_off_topic_still_demoted(self):
+ # Regression guard: collision-noise suppression is untouched. A stranger
+ # whose post omits the entity is still demoted even when handles resolve.
+ c = self._x_candidate(author="randomuser", text="some unrelated take about lunch")
+ rerank._apply_fallback_scores(
+ [c], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertIn("entity-miss", c.explanation or "")
+
+ def test_first_party_outscores_its_own_demoted_baseline(self):
+ # Same post, with vs without the exemption: the exempted score is higher
+ # (no -25 rerank / -20 final), lifting it out of the zero band.
+ text = "every agentic engineering hack I know"
+ exempt = self._x_candidate(author="mvanhorn", text=text)
+ demoted = self._x_candidate(author="stranger", text=text)
+ rerank._apply_fallback_scores(
+ [exempt], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ rerank._apply_fallback_scores(
+ [demoted], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertGreater(exempt.final_score, demoted.final_score)
+
+ def test_author_match_is_case_and_at_insensitive(self):
+ c = self._x_candidate(author="@MVanHorn", text="no entity name here")
+ rerank._apply_fallback_scores(
+ [c], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertIn("first-party", c.explanation or "")
+
+ def test_empty_author_behaves_as_before(self):
+ # No author -> not first-party; off-topic text -> demoted as it would be
+ # pre-change.
+ c = self._x_candidate(author=None, text="unrelated content")
+ rerank._apply_fallback_scores(
+ [c], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertIn("entity-miss", c.explanation or "")
+
+ def test_no_resolved_handles_is_pure_regression(self):
+ # Empty handle set -> first-party path never engages; identical to the
+ # prior behavior for the same off-topic post.
+ c = self._x_candidate(author="mvanhorn", text="unrelated content")
+ rerank._apply_fallback_scores([c], primary_entity="Matt Van Horn", resolved_handles=set())
+ self.assertIn("entity-miss", c.explanation or "")
+
+ def test_authorship_credit_does_not_outrank_strong_third_party(self):
+ # Authorship lifts off the floor but must not beat a genuinely strong
+ # on-topic third-party item (high LLM relevance).
+ first_party = self._x_candidate(author="mvanhorn", text="quick reply, no entity")
+ rerank._apply_fallback_scores(
+ [first_party], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ strong_third_party = self._x_candidate(author="press", text="Matt Van Horn ships Printing Press")
+ strong_third_party.rerank_score = 90.0
+ strong_third_party.explanation = "llm"
+ strong_third_party.final_score = rerank._final_score(strong_third_party)
+ self.assertGreater(strong_third_party.final_score, first_party.final_score)
+
+ def test_candidate_author_handle_helper(self):
+ c = self._x_candidate(author="@SomeOne", text="hi")
+ self.assertEqual("someone", rerank._candidate_author_handle(c))
+ self.assertTrue(rerank._is_first_party(c, {"someone"}))
+ self.assertFalse(rerank._is_first_party(c, {"other"}))
+ self.assertFalse(rerank._is_first_party(c, set()))
+
+
+class EngagementRescueTests(unittest.TestCase):
+ """U3: a high-engagement X post that is on-topic (first-party or grounded)
+ cannot sit at ~0; off-topic collision posts are NOT rescued."""
+
+ def _x(self, *, author, text, engagement, final_score, explanation):
+ item = schema.SourceItem(
+ item_id="x", source="x", title=text, body=text,
+ url="https://x.com/a/status/1", author=author, snippet=text,
+ )
+ c = schema.Candidate(
+ candidate_id=f"x-{author}-{engagement}",
+ item_id="x",
+ source="x",
+ title=text,
+ url=item.url,
+ snippet=text,
+ subquery_labels=["primary"],
+ native_ranks={"primary:x": 1},
+ local_relevance=0.5,
+ freshness=50,
+ engagement=engagement,
+ source_quality=0.6,
+ rrf_score=0.02,
+ source_items=[item],
+ )
+ c.final_score = final_score
+ c.explanation = explanation
+ return c
+
+ def test_top_engagement_first_party_is_floored(self):
+ low = self._x(author="other", text="Matt Van Horn news", engagement=1,
+ final_score=10, explanation="fallback-local-score")
+ mid = self._x(author="other2", text="Matt Van Horn update", engagement=50,
+ final_score=10, explanation="fallback-local-score")
+ top = self._x(author="mvanhorn", text="quick reply no entity", engagement=100,
+ final_score=3, explanation="fallback-local-score (first-party authorship)")
+ rerank._apply_engagement_rescue(
+ [low, mid, top], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertGreaterEqual(top.final_score, rerank.RESCUE_FLOOR_MAX - 0.001)
+
+ def test_top_engagement_entity_miss_is_not_rescued(self):
+ # Off-topic collision post with the highest engagement must stay buried.
+ grounded = self._x(author="x", text="Matt Van Horn ships", engagement=1,
+ final_score=20, explanation="fallback-local-score")
+ offtopic_top = self._x(author="namesake", text="totally different person lunch", engagement=100,
+ final_score=2,
+ explanation="fallback-local-score (entity-miss demotion)")
+ rerank._apply_engagement_rescue(
+ [grounded, offtopic_top], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertEqual(2, offtopic_top.final_score)
+
+ def test_median_engagement_not_meaningfully_floored(self):
+ low = self._x(author="a", text="Matt Van Horn", engagement=1,
+ final_score=8, explanation="fallback-local-score")
+ median = self._x(author="b", text="Matt Van Horn", engagement=50,
+ final_score=8, explanation="fallback-local-score")
+ high = self._x(author="c", text="Matt Van Horn", engagement=100,
+ final_score=8, explanation="fallback-local-score")
+ rerank._apply_engagement_rescue(
+ [low, median, high], primary_entity="Matt Van Horn", resolved_handles=set()
+ )
+ self.assertEqual(8, median.final_score) # percentile 0.5 -> floor 0
+
+ def test_non_x_candidate_unaffected(self):
+ reddit = make_candidate(4.0) # reddit candidate (module-level helper)
+ reddit.final_score = 3.0
+ x1 = self._x(author="mvanhorn", text="hi", engagement=1, final_score=3,
+ explanation="fallback-local-score (first-party authorship)")
+ x2 = self._x(author="mvanhorn", text="hi", engagement=100, final_score=3,
+ explanation="fallback-local-score (first-party authorship)")
+ rerank._apply_engagement_rescue(
+ [reddit, x1, x2], primary_entity="Matt Van Horn", resolved_handles={"mvanhorn"}
+ )
+ self.assertEqual(3.0, reddit.final_score)
+
+ def test_single_or_empty_x_pool_no_error(self):
+ rerank._apply_engagement_rescue([], primary_entity="x", resolved_handles=set())
+ solo = self._x(author="mvanhorn", text="hi", engagement=100, final_score=2,
+ explanation="fallback-local-score (first-party authorship)")
+ rerank._apply_engagement_rescue([solo], primary_entity="x", resolved_handles={"mvanhorn"})
+ self.assertEqual(2, solo.final_score) # pool < 2 -> no-op
+
+
+class FirstPartyFloorTests(unittest.TestCase):
+ """Greptile #613 follow-up: close the LLM-path gap. A first-party post that
+ the LLM rerank capped low must still clear the zero band, and the LLM prompt
+ must mark first-party posts so the model doesn't cap them."""
+
+ def _x(self, *, author, final_score):
+ item = schema.SourceItem(
+ item_id="x", source="x", title="t", body="t",
+ url="https://x.com/a/status/1", author=author, snippet="t",
+ )
+ c = schema.Candidate(
+ candidate_id=f"x-{author}-{final_score}",
+ item_id="x", source="x", title="t", url=item.url, snippet="t",
+ subquery_labels=["primary"], native_ranks={"primary:x": 1},
+ local_relevance=0.5, freshness=50, engagement=1, source_quality=0.6,
+ rrf_score=0.02, source_items=[item],
+ )
+ c.final_score = final_score
+ return c
+
+ def test_first_party_floored_even_when_llm_capped_low(self):
+ # Simulates the LLM path: a first-party post scored low (capped) lands
+ # below the floor; the backstop lifts it into the visible band.
+ c = self._x(author="subject", final_score=4.0)
+ rerank._apply_first_party_floor([c], resolved_handles={"subject"})
+ self.assertGreaterEqual(c.final_score, rerank.FIRST_PARTY_FLOOR)
+
+ def test_floor_never_lowers_a_higher_score(self):
+ c = self._x(author="subject", final_score=70.0)
+ rerank._apply_first_party_floor([c], resolved_handles={"subject"})
+ self.assertEqual(70.0, c.final_score)
+
+ def test_third_party_not_floored(self):
+ c = self._x(author="stranger", final_score=4.0)
+ rerank._apply_first_party_floor([c], resolved_handles={"subject"})
+ self.assertEqual(4.0, c.final_score)
+
+ def test_empty_handles_noop(self):
+ c = self._x(author="subject", final_score=4.0)
+ rerank._apply_first_party_floor([c], resolved_handles=set())
+ self.assertEqual(4.0, c.final_score)
+
+ def test_llm_prompt_marks_first_party_and_exempts_it(self):
+ item = schema.SourceItem(
+ item_id="x", source="x", title="quick reply", body="quick reply",
+ url="https://x.com/subject/status/1", author="subject", snippet="quick reply",
+ )
+ c = schema.Candidate(
+ candidate_id="x-subject", item_id="x", source="x", title="quick reply",
+ url=item.url, snippet="quick reply", subquery_labels=["primary"],
+ native_ranks={"primary:x": 1}, local_relevance=0.5, freshness=50,
+ engagement=1, source_quality=0.6, rrf_score=0.02, source_items=[item],
+ )
+ prompt = rerank._build_prompt(
+ "Matt Van Horn", make_plan(), [c], primary_entity="Matt Van Horn",
+ resolved_handles={"subject"},
+ )
+ self.assertIn("first_party: true (authored by the subject)", prompt)
+ self.assertIn("author: @subject", prompt)
+ self.assertIn("EXEMPT from this cap", prompt)
+
+ def test_llm_prompt_no_first_party_flag_for_third_party(self):
+ item = schema.SourceItem(
+ item_id="x", source="x", title="t", body="t",
+ url="https://x.com/other/status/1", author="other", snippet="t",
+ )
+ c = schema.Candidate(
+ candidate_id="x-other", item_id="x", source="x", title="t",
+ url=item.url, snippet="t", subquery_labels=["primary"],
+ native_ranks={"primary:x": 1}, local_relevance=0.5, freshness=50,
+ engagement=1, source_quality=0.6, rrf_score=0.02, source_items=[item],
+ )
+ prompt = rerank._build_prompt(
+ "Matt Van Horn", make_plan(), [c], primary_entity="Matt Van Horn",
+ resolved_handles={"subject"},
+ )
+ self.assertNotIn("first_party: true (authored by the subject)", prompt)
+
+
+class InteractionSignalTests(unittest.TestCase):
+ """U5: a first-party post directed at another account is tagged and floated
+ regardless of like-count. Synthetic handles only (R7)."""
+
+ def _x(self, *, author, mentioned, final_score=2.0):
+ item = schema.SourceItem(
+ item_id="x", source="x", title="t", body="t",
+ url="https://x.com/a/status/1", author=author, snippet="t",
+ metadata={"mentioned_handles": list(mentioned)} if mentioned else {},
+ )
+ c = schema.Candidate(
+ candidate_id=f"x-{author}-{'-'.join(mentioned) or 'none'}",
+ item_id="x", source="x", title="t", url=item.url, snippet="t",
+ subquery_labels=["primary"], native_ranks={"primary:x": 1},
+ local_relevance=0.5, freshness=50, engagement=1, source_quality=0.6,
+ rrf_score=0.02, source_items=[item],
+ )
+ c.final_score = final_score
+ return c
+
+ def test_first_party_reply_is_tagged_and_floated(self):
+ c = self._x(author="subject", mentioned=["beta"], final_score=2.0)
+ rerank._apply_interaction_signal([c], resolved_handles={"subject"})
+ self.assertEqual(["beta"], c.metadata.get("interaction_targets"))
+ self.assertGreaterEqual(c.final_score, rerank.INTERACTION_FLOOR)
+
+ def test_first_party_no_mentions_not_interaction(self):
+ c = self._x(author="subject", mentioned=[], final_score=2.0)
+ rerank._apply_interaction_signal([c], resolved_handles={"subject"})
+ self.assertNotIn("interaction_targets", c.metadata)
+ self.assertEqual(2.0, c.final_score)
+
+ def test_third_party_mentioning_subject_not_floated(self):
+ # A stranger @-ing the subject is not first-party; not an interaction here.
+ c = self._x(author="stranger", mentioned=["subject"], final_score=2.0)
+ rerank._apply_interaction_signal([c], resolved_handles={"subject"})
+ self.assertNotIn("interaction_targets", c.metadata)
+ self.assertEqual(2.0, c.final_score)
+
+ def test_self_mention_only_not_interaction(self):
+ # Subject addressing only their own (resolved) handles -> no other target.
+ c = self._x(author="subject", mentioned=["subject_alt"], final_score=2.0)
+ rerank._apply_interaction_signal([c], resolved_handles={"subject", "subject_alt"})
+ self.assertNotIn("interaction_targets", c.metadata)
+
+ def test_empty_resolved_handles_is_noop(self):
+ c = self._x(author="subject", mentioned=["beta"], final_score=2.0)
+ rerank._apply_interaction_signal([c], resolved_handles=set())
+ self.assertNotIn("interaction_targets", c.metadata)
+ self.assertEqual(2.0, c.final_score)
+
+ def test_float_does_not_lower_an_already_high_score(self):
+ c = self._x(author="subject", mentioned=["beta"], final_score=80.0)
+ rerank._apply_interaction_signal([c], resolved_handles={"subject"})
+ self.assertEqual(80.0, c.final_score) # floor only lifts, never lowers
+
+
if __name__ == "__main__":
unittest.main()