AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(x): retrieve-judge-retry so X stays on-topic (#998)
Matt Van Hornab124fc8f9f9
diff --git a/changelog.d/+x-retrieve-judge-retry.added.md b/changelog.d/+x-retrieve-judge-retry.added.mdnew file mode 100644index 00000000..bfebf9e6--- /dev/null+++ b/changelog.d/+x-retrieve-judge-retry.added.md@@ -0,0 +1 @@+X search now judges corpus on-topic ratio and retries once with a wider AND query when the initial results are mostly off-topic (e.g., phrase-quoted "Rome Italy" returning AS Roma sports accounts). Multi-word search queries use unquoted AND as the primary variant instead of phrase-quoting. Handles extracted from entity_extract are now filtered for the from: lane based on whether their already-retrieved posts are on-topic (≥2 on-topic hits and ≥50% ratio), not just frequency. Extracted handles that qualify for the from: lane AND the topic into the query (`from:handle Rome`) to prevent off-topic timelines from filling the X budget. Explicit --x-handle and --x-related handles always get the from: lane without ANDing the topic. Source status reflects off-topic floods as a warning artifact, not a failure. First-party floor immunity remains conservative (explicit handles only, not promoted commentators).diff --git a/docs/plans/2026-08-14-feat-x-retrieve-judge-retry-plan.md b/docs/plans/2026-08-14-feat-x-retrieve-judge-retry-plan.mdnew file mode 100644index 00000000..bfb8e709--- /dev/null+++ b/docs/plans/2026-08-14-feat-x-retrieve-judge-retry-plan.md@@ -0,0 +1,71 @@+# Retrieve-Judge-Retry for X Search++**Date:** 2026-08-14+**Status:** Completed++## Problem Statement++X search results become off-topic when multi-word search queries are phrase-quoted. The Rome failure (2026-08-14) demonstrated this:++1. Planner generated `search_query: "Rome Italy"` (phrase-quoted)+2. Phrase-quoting returned thin hits with engagement bait (pretty-cities, geopolitics accounts)+3. `entity_extract` ranked off-topic handles (PrettyCitiesX, visegrad24) by frequency+4. `pipeline.py` promoted those handles to the FROM lane+5. FROM lane filled the 40-slot X budget with off-topic timelines++## Solution++Implement retrieve-judge-retry for X search:++1. **Query Compilation (R2):** X now uses `raw_topic` like Reddit/YouTube, not the planner's `search_query`+2. **Fanout Queries (R3):** Multi-word topics use unquoted AND as first variant; phrase-quote only for proper names+3. **Corpus Judging (R7):** New `x_judge.py` module evaluates corpus on-topic ratio after retrieval+4. **Retry (R1):** If off-topic flood detected (ratio < 0.4), retry ONCE with simplified keyword query inside the X stream (not `_retry_thin_sources`)+5. **Split FROM Promotion (R4):**+ - Explicit handles (--x-handle): always FROM, no AND topic+ - Extracted handles: FROM only if ≥2 on-topic hits AND ≥50% ratio, and they DO AND the topic+6. **First-Party Exemption (R5):** Floor immunity stays conservative (explicit handles only)+7. **Status Reporting (R6):** Off-topic floods emit artifact warning, not `record_failure(PARTIAL)`++## Implementation Details++### New Module: `x_judge.py`++- `judge_x_corpus(items, topic, ranking_query)`: Returns on_topic_ratio, is_off_topic_flood, on_topic_items, handle_stats+- `promotable_handles(items, topic, extracted_handles, explicit_handles)`: Returns (explicit_promotable, extracted_promotable)+- `should_retry_x_search(items, topic, depth)`: Returns True if retry warranted+- `prune_off_topic_items(items, topic)`: Returns only on-topic items++### Key Changes++- `grok_x._fanout_queries()`: No phrase-quote for place/disambiguation strings+- `grok_x._is_proper_name()`: Detects title-cased proper names for phrase-quoting+- `grok_x.search_handles()`: Added `and_topic` parameter (default False)+- `pipeline._fetch_x_backend()`: Accepts query directly, not subquery+- `pipeline._retrieve_stream_impl()`: X source uses raw_topic, judges corpus, retries if needed+- `pipeline._run_supplemental_searches()`: Uses `promotable_handles` for split FROM logic++### Tests++- `tests/test_x_judge.py`: New test file for x_judge module+- `tests/test_grok_x.py`: Added fanout and and_topic tests+- `tests/test_pipeline_v3.py`: Updated fixtures to have promotable content++## Success Criteria++- [ ] `_fanout_queries("Rome Italy")` has no `"Rome Italy"` variant+- [ ] `search_name("Peter Steinberger")` still phrase-quotes+- [ ] `search_handles(["steipete"], "topic")` does not AND topic by default+- [ ] `search_handles(["visegrad24"], "Rome", and_topic=True)` does AND Rome+- [ ] Explicit --x-handle always gets FROM lane+- [ ] Off-topic handles (visegrad24) not promoted to FROM lane+- [ ] On-topic handles (mamboitaliano__) promoted to FROM lane+- [ ] X source status is artifact warning, not PARTIAL failure+- [ ] All tests pass++## Out of Scope++- No live Grok calls in tests+- No auth/doctor touch+- No collision lexicon (AS Roma / Odunze still appear; judge + ranking_query drop them)+- bird_x quote-preserving `build_topic_query` (follow-up if needed)diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex eb7645cf..6fc96eb0 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -1394,6 +1394,7 @@ Only show lines for platforms where something was resolved. Skip empty lines. On- **CRITICAL: Your PRIMARY subquery MUST include ALL of these sources: reddit, x, youtube, tiktok, instagram, hackernews, polymarket.** Never omit reddit (highest-signal discussion) or youtube (unique transcripts + official content). Secondary subqueries can target specific platforms.- `search_query` should be concise and keyword-heavy - match how content is TITLED on platforms- `ranking_query` should read like a natural language question+- **X disambiguation:** express your disambiguation intent in `ranking_query` (e.g., "What are people saying about Rome the city in Italy, not AS Roma or Rome Odunze?") — do not phrase-quote `search_query` for X or invent X operators; the engine handles X query compilation internally.- **DISAMBIGUATION (mandatory for collision-prone names — the #1 cause of off-topic noise).** Anchor the `search_query` with the disambiguating context you resolved in Step 0.5 / 0.55 — the entity's company, role, or domain — when the topic name (a) is a common word or has non-product meanings ("Loom" = weaving tool, "Tella" = soccer player), OR (b) is a PERSON whose name collides with other public figures or common words. Apply the anchor to **EVERY subquery, not just the primary**, and mirror it in the `ranking_query`. Anchor on a SPECIFIC named entity (a company/product/firm), not a generic domain word. Examples: `"kevin rose digg founder"` not `"kevin rose"` (collides with Kevin Warsh / Leon Rose / Kevin Hart); `"lan xuezhao basis set ventures"` not `"lan xuezhao"` (collides with "Lanzhou" food, cdrama edits); `"trevin chow compound engineering"` not `"trevin chow"` (collides with Trevin Wax / Trevin Brown); `"tella screen recording"` not `"tella"`. The `ranking_query` carries the same anchor: `"ranking_query": "What has Kevin Rose, founder of Digg, been doing in the last 30 days?"`, not a bare `"...Kevin Rose..."`. A bare collision-prone name as a subquery is the named 2026-06-17 failure mode — "Kevin Rose" returned 55 items with ~0 about the actual founder until every subquery was anchored to "Digg founder". When the name is globally unambiguous (Kanye West, Nvidia, Peter Steinberger/OpenClaw), no anchor is needed.- **For comparison queries**, each subquery should include the product category: "tella screen recorder review" not just "tella review", "loom video tool pricing" not just "loom pricing".- NEVER include temporal phrases in search_query: no "last 30 days", "recent", month names, year numbersdiff --git a/skills/last30days/scripts/lib/grok_x.py b/skills/last30days/scripts/lib/grok_x.pyindex 8358cc8f..2d2ff179 100644--- a/skills/last30days/scripts/lib/grok_x.py+++ b/skills/last30days/scripts/lib/grok_x.py@@ -66,20 +66,58 @@ LANE_BUDGET_SECONDS = 150.0_MIN_USEFUL_CALL_SECONDS = 15+def _is_proper_name(topic: str) -> bool:+ """True when topic looks like a title-cased proper name (person/product).++ "Peter Steinberger" → True (phrase-quote in fanout)+ "Rome Italy" → False (no phrase-quote; place/disambiguation string)+ """+ words = topic.split()+ if len(words) < 2:+ return False+ # Title-cased: each word starts uppercase, rest lowercase+ # Place names like "Rome Italy" are title-cased but are NOT proper names+ # for phrase-quoting purposes. Heuristic: if ALL words are common place/+ # disambiguation words OR all-caps acronyms, don't phrase-quote.+ place_words = {+ "italy", "rome", "paris", "london", "berlin", "tokyo", "new", "york",+ "los", "angeles", "san", "francisco", "city", "country", "state",+ "north", "south", "east", "west", "united", "states", "kingdom",+ }+ lower_words = [w.lower() for w in words]+ if all(w in place_words or w.isupper() for w in lower_words):+ return False+ # Check for title case pattern (First Last, First Middle Last)+ return all(+ w[0].isupper() and (len(w) == 1 or w[1:].islower())+ for w in words+ if w.isalpha()+ )++def _fanout_queries(topic: str, from_date: str, to_date: str, calls: int) -> List[str]:"""Distinct query formulations for one topic, widest signal first.Each returns at most 10 posts, and the formulations surface differentsets -- Top vs Latest ordering, and an engagement-floored variant -- sofanning out adds coverage rather than repeating one result set.++ Multi-word topics are NOT phrase-quoted unless they look like proper names+ (person/product). "Rome Italy" → no phrase-quote (place/disambiguation).+ "Peter Steinberger" → phrase-quote in one variant (proper name)."""window = f"since:{from_date} until:{to_date}"+ # First variant: unquoted AND (multi-word topics naturally AND their terms)variants = [f"{topic} {window}",f"{topic} {window} min_faves:5",- f'"{topic}" {window}' if " " in topic else f"{topic} {window} filter:links",- f"{topic} {window} -filter:replies",]+ # Third variant: phrase-quote only for proper names, else filter:links+ if " " in topic and _is_proper_name(topic):+ variants.append(f'"{topic}" {window}')+ else:+ variants.append(f"{topic} {window} filter:links")+ variants.append(f"{topic} {window} -filter:replies")return variants[:calls]DEPTH_CONFIG = {@@ -800,11 +838,17 @@ def search_handles(*,count_per: int = 8,deadline: Optional[float] = None,+ and_topic: bool = False,) -> Tuple[List[Dict[str, Any]], bool]:"""BY lane: posts authored by each handle.``topic`` is used for relevance ranking only and is never ANDed into the- query -- doing so was a prior defect that emptied the lane.+ query by default -- doing so was a prior defect that emptied the lane+ (person posts omit their own name).++ When ``and_topic=True``, the topic IS ANDed into the query (e.g.,+ ``from:handle Rome``) to ensure extracted handles demonstrate on-topic+ content. This prevents off-topic timelines from filling the X budget.Returns (items, auth_revoked) so the pipeline can record AUTH_FAILED."""@@ -817,8 +861,13 @@ def search_handles(clean = _clean_handle(handle)if not clean:continue+ # AND topic only when explicitly requested (extracted handles)+ if and_topic and topic:+ query = f"from:{clean} {topic} since:{from_date} until:{to_date}"+ else:+ query = f"from:{clean} since:{from_date} until:{to_date}"items, _, revoked = _run_query(- f"from:{clean} since:{from_date} until:{to_date}",+ query,from_date, to_date, limit=count_per, relevance_topic=topic,attempts=1, deadline=deadline,)diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 13f8a23a..5c40da43 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -68,6 +68,7 @@ from . import (topic_shape,truthsocial,trustpilot,+ x_judge,xai_x,xiaohongshu_api,xquik,@@ -474,16 +475,12 @@ def _fetch_discovery_source(]return items, result.get("error")if source == "x":- subquery = schema.SubQuery(- label="discovery-listings",- search_query=plan.domain,- ranking_query=f"What is accelerating in {plan.domain}?",- sources=["x"],- )+ # Discovery uses domain directly as query (no planner search_query)+ query = plan.domainlast_error = ""for backend in env.x_backend_chain(config):items, error = _fetch_x_backend(- backend, subquery, from_date, to_date, depth, config,+ backend, query, from_date, to_date, depth, config,)if items:# Earlier failed-over backends' errors are observability, not@@ -3499,10 +3496,10 @@ def _run_supplemental_searches(# lane: the point is to bound the total, not each part.lane_deadline = time.monotonic() + grok_x.LANE_BUDGET_SECONDS- def _from_lane(hs: list, count: int) -> tuple[list, bool]:+ def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:items, revoked = grok_x.search_handles(hs, topic, from_date, to_date, count_per=count,- deadline=lane_deadline,+ deadline=lane_deadline, and_topic=and_topic,)return items, revoked@@ -3526,7 +3523,8 @@ def _run_supplemental_searches()return items, revokedelif primary == "bird":- def _from_lane(hs: list, count: int) -> tuple[list, bool]:+ def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:+ # bird_x.search_handles doesn't support and_topic yetreturn bird_x.search_handles(hs, topic, from_date, count_per=count), Falsedef _about_lane(hs: list, count: int) -> tuple[list, bool]:@@ -3534,7 +3532,8 @@ def _run_supplemental_searches(elif primary == "xquik":xquik_token = env.get_xquik_token(config)- def _from_lane(hs: list, count: int) -> tuple[list, bool]:+ def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:+ # xquik.search_handles doesn't support and_topic yetreturn xquik.search_handles(hs, topic, from_date, to_date, count_per=count, token=xquik_token), Falsedef _about_lane(hs: list, count: int) -> tuple[list, bool]:@@ -3557,40 +3556,79 @@ def _run_supplemental_searches(ranking_query = plan.subqueries[0].ranking_query if plan.subqueries else topicprimary_label = plan.subqueries[0].label if plan.subqueries else "primary"+ # Split FROM promotion: determine which handles get FROM lane and how.+ # - Primary explicit handle (--x-handle): always FROM, no AND topic, full weight+ # - x_related handles: searched separately with lower weight (0.3), kept in+ # related_handles variable for the supplemental-related section below+ # - Extracted handles: FROM only if ≥2 on-topic hits AND ratio ≥0.5,+ # and those pulls DO AND the topic (from:handle Rome)+ primary_explicit = [x_handle] if x_handle else []++ explicit_promotable, extracted_promotable = x_judge.promotable_handles(+ x_dicts, # Phase 1 X items for judging+ topic,+ handles, # entity_extract handles+ explicit_handles=primary_explicit,+ ranking_query=ranking_query,+ )++ # All promotable handles for ABOUT and NAME lanes (primary only, not related)+ all_promotable = list(set(explicit_promotable + extracted_promotable))+# Search primary handles (full weight): FROM lane (their own tweets) +# ABOUT lane (tweets mentioning them). Both engagement-weighted and deduped# by URL at normalize time.any_revoked = False # Track auth revocation across lanes- if handles:+ if all_promotable:# Independent try/except per lane so a failure in one does not discard# the other's already-computed results.from_items: list = []about_items: list = []- from_revoked = Falseabout_revoked = Falsename_revoked = False- try:- from_items, from_revoked = _from_lane(handles, FROM_LANE_COUNT_PER)- if from_revoked:- any_revoked = True++ # FROM lane: explicit handles without AND topic (person posts omit their own name)+ if explicit_promotable:+ try:+ explicit_items, explicit_revoked = _from_lane(explicit_promotable, FROM_LANE_COUNT_PER, and_topic=False)+ from_items.extend(explicit_items)+ if explicit_revoked:+ any_revoked = True+ bundle.record_failure(+ x_slug, schema.AUTH_FAILED,+ "Phase 2 FROM-lane (explicit): grok session expired or was revoked",+ attempted=True,+ )+ except Exception as exc:+ print(f"[Pipeline] Phase 2 FROM-lane (explicit) failed: {exc}", file=sys.stderr)+ state, attempted = _classify_source_failure(exc)bundle.record_failure(- x_slug, schema.AUTH_FAILED,- "Phase 2 FROM-lane: grok session expired or was revoked",- attempted=True,+ x_slug, state, f"Phase 2 FROM-lane (explicit): {exc}", attempted=attempted,)- except Exception as exc:- print(f"[Pipeline] Phase 2 FROM-lane search failed: {exc}", file=sys.stderr)- state, attempted = _classify_source_failure(exc)- bundle.record_failure(- x_slug,- state,- f"Phase 2 FROM-lane: {exc}",- attempted=attempted,- )- if not bundle.items_by_source.get(x_slug):- bundle.errors_by_source[x_slug] = f"Phase 2 FROM-lane: {exc}"++ # FROM lane: extracted handles WITH AND topic (from:handle Rome)+ if extracted_promotable:+ try:+ extracted_items, extracted_revoked = _from_lane(extracted_promotable, FROM_LANE_COUNT_PER, and_topic=True)+ from_items.extend(extracted_items)+ if extracted_revoked:+ any_revoked = True+ bundle.record_failure(+ x_slug, schema.AUTH_FAILED,+ "Phase 2 FROM-lane (extracted): grok session expired or was revoked",+ attempted=True,+ )+ except Exception as exc:+ print(f"[Pipeline] Phase 2 FROM-lane (extracted) failed: {exc}", file=sys.stderr)+ state, attempted = _classify_source_failure(exc)+ bundle.record_failure(+ x_slug, state, f"Phase 2 FROM-lane (extracted): {exc}", attempted=attempted,+ )+ if not bundle.items_by_source.get(x_slug):+ bundle.errors_by_source[x_slug] = f"Phase 2 FROM-lane: {exc}"+try:- about_items, about_revoked = _about_lane(handles, MENTION_LANE_COUNT_PER)+ about_items, about_revoked = _about_lane(all_promotable, MENTION_LANE_COUNT_PER)if about_revoked:any_revoked = Truebundle.record_failure(@@ -3610,7 +3648,7 @@ def _run_supplemental_searches(name_items: list = []if _name_lane is not None:try:- name_items, name_revoked = _name_lane(handles, MENTION_LANE_COUNT_PER)+ name_items, name_revoked = _name_lane(all_promotable, MENTION_LANE_COUNT_PER)if name_revoked:any_revoked = Truebundle.record_failure(@@ -3651,11 +3689,17 @@ def _run_supplemental_searches()if raw_items:+ # First-party handles: only primary explicit handle, not promoted commentators+ # (first-party exempts from relevance floor; granting to commentators+ # would let junk become un-prunable)+ first_party_for_normalize = list(set(+ h.lower().lstrip("@") for h in primary_explicit if h+ ))normalized = _normalize_score_dedupe(x_slug, raw_items, from_date, to_date,freshness_mode=plan.freshness_mode,ranking_query=ranking_query,- first_party_handles=handles,+ first_party_handles=first_party_for_normalize,)# Deduplicate against Phase 1 URLsnormalized = [item for item in normalized if item.url not in existing_urls]@@ -3667,9 +3711,10 @@ def _run_supplemental_searches(existing_urls.add(item.url)# Search related handles with lower weight (0.3)+ # Related handles are explicit (--x-related), so FROM without AND topic.if related_handles:try:- raw_items, rel_revoked = _from_lane(related_handles, RELATED_HANDLE_COUNT_PER)+ raw_items, rel_revoked = _from_lane(related_handles, RELATED_HANDLE_COUNT_PER, and_topic=False)if rel_revoked:any_revoked = Truebundle.record_failure(@@ -3860,7 +3905,7 @@ def _retry_thin_sources()-def _fetch_x_backend(backend, subquery, from_date, to_date, depth, config):+def _fetch_x_backend(backend, query, from_date, to_date, depth, config):"""Fetch X items from a single backend. Returns (items, error_str).Backends are tried in priority order by the caller (env.x_backend_chain);@@ -3870,8 +3915,11 @@ def _fetch_x_backend(backend, subquery, from_date, to_date, depth, config):For grok, auth_revoked signals mid-run session revocation: the errorstring includes "grok session expired" so _classify_source_failure mapsit to AUTH_FAILED with a proper fix hint, distinct from "never signed in".++ The ``query`` parameter is the compiled search query - typically+ ``raw_topic or topic`` (like Reddit/YouTube), NOT the planner's+ ``search_query`` which may contain operator strings like "Rome Italy"."""- query = subquery.search_queryif backend == "bird":result = bird_x.search_x(query, from_date, to_date, depth=depth)items = bird_x.parse_bird_response(result, query=query)@@ -4143,6 +4191,11 @@ def _retrieve_stream_impl()return merged, {}if source == "x":+ # Compile X query from raw_topic (like Reddit/YouTube), not planner's+ # search_query which may contain operator strings like "Rome Italy".+ x_query = raw_topic or topic or subquery.search_query+ ranking_query = subquery.ranking_query+# One X source, an ordered chain of interchangeable backends. Try the# primary; fall through to the next only if it returns nothing or errors.chain = env.x_backend_chain(config)@@ -4154,11 +4207,14 @@ def _retrieve_stream_impl(if not chain:raise RuntimeError("No X backend is available.")last_error = ""+ items = []+ used_backend = Nonefor i, backend in enumerate(chain):- items, err = _fetch_x_backend(backend, subquery, from_date, to_date, depth, config)+ items, err = _fetch_x_backend(backend, x_query, from_date, to_date, depth, config)if items:if i > 0:print(f"[X] primary backend(s) returned nothing; used fallback '{backend}'", file=sys.stderr)+ # Check for auth errors before proceeding to judge-retryif last_error:# Fallback succeeded after earlier backend failed. Classify# the original error: if it was AUTH_FAILED (grok revoked),@@ -4193,18 +4249,107 @@ def _retrieve_stream_impl(state,f"X returned {len(items)} items but also errored: {err}",)- return items, {}+ # No auth issues and no prior errors - proceed to judge-retry+ used_backend = backend+ breakif err:last_error = f"{backend}: {err}"print(f"[X] backend '{backend}' failed ({err}); trying next", file=sys.stderr)- if last_error:++ if not items and last_error:state = (bird_x.classify_run_failure(last_error)if last_error.startswith("bird:")else http.classify_failure(message=last_error))raise SourceRunError(f"All X backends failed — {last_error}", state)- return [], {}++ # Retrieve-judge-retry: judge corpus and retry if off-topic flood.+ # Skip retry on quick/mock (same as Phase 2).+ artifact = {}+ if items and depth != "quick" and not mock:+ items_for_judge = [+ {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}+ for it in items+ ]+ if x_judge.should_retry_x_search(items_for_judge, x_query, ranking_query=ranking_query, depth=depth):+ # Retry with cleaned query (1 retry, ≤2 extra grok calls)+ # Strip noise words but preserve all significant terms to avoid+ # losing disambiguating terms (e.g., "react server components")+ core_tokens = query.extract_core_subject(x_query)+ retry_query = core_tokens or x_query+ print(f"[X] corpus off-topic; retrying with '{retry_query}'", file=sys.stderr)++ if used_backend:+ retry_items, retry_err = _fetch_x_backend(+ used_backend, retry_query, from_date, to_date, depth, config+ )+ if retry_items:+ # Judge retry corpus+ retry_for_judge = [+ {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}+ for it in retry_items+ ]+ retry_judgment = x_judge.judge_x_corpus(+ retry_for_judge, x_query, ranking_query=ranking_query+ )+ orig_judgment = x_judge.judge_x_corpus(+ items_for_judge, x_query, ranking_query=ranking_query+ )+ # Use retry if better on-topic ratio+ if retry_judgment["on_topic_ratio"] > orig_judgment["on_topic_ratio"]:+ print(+ f"[X] retry improved on-topic ratio: "+ f"{orig_judgment['on_topic_ratio']:.0%} -> "+ f"{retry_judgment['on_topic_ratio']:.0%}",+ file=sys.stderr,+ )+ items = retry_items++ # Prune off-topic items before the pool. Eight on-topic → ok with 8.+ # Zero on-topic after retry → no-results, not ok with 40 junk.+ # Only prune items that have text to judge; items without text pass through.+ original_count = len(items)+ items_with_text = [(i, it) for i, it in enumerate(items) if it.get("text", "").strip()]++ if items_with_text:+ items_for_prune = [+ {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}+ for _, it in items_with_text+ ]+ judgment = x_judge.judge_x_corpus(+ items_for_prune, x_query, ranking_query=ranking_query+ )+ # Build set of indices for on-topic items+ on_topic_indices = set()+ for (orig_idx, _), pruned_item in zip(items_with_text, items_for_prune):+ if pruned_item in judgment["on_topic_items"]:+ on_topic_indices.add(orig_idx)++ # Keep items that are on-topic OR have no text (can't judge)+ items = [+ it for i, it in enumerate(items)+ if i in on_topic_indices or not it.get("text", "").strip()+ ]++ # Record warning if significant pruning occurred (artifact, not failure)+ if len(items) < original_count:+ pruned = original_count - len(items)+ artifact.setdefault("_warnings", []).append(+ f"X: pruned {pruned} off-topic items; {len(items)} on-topic remain"+ )++ if last_error and items:+ state = (+ bird_x.classify_run_failure(last_error)+ if last_error.startswith("bird:")+ else http.classify_failure(message=last_error)+ )+ return items, _outcome_artifact(+ state,+ f"X fallback '{used_backend}' returned {len(items)} items after {last_error}",+ )+ return items, artifactif source == "youtube":# Use raw_topic so expand_youtube_queries() generates diverse variants# from the original user topic, not the planner's narrowed search_query.diff --git a/skills/last30days/scripts/lib/x_judge.py b/skills/last30days/scripts/lib/x_judge.pynew file mode 100644index 00000000..d8f1ab79--- /dev/null+++ b/skills/last30days/scripts/lib/x_judge.py@@ -0,0 +1,292 @@+"""X corpus judging for retrieve-judge-retry.++No I/O: judges items already retrieved. Reuses relevance.token_overlap_relevance.++The judge detects off-topic floods and determines which extracted handles should+be promoted to the FROM lane based on on-topic post ratio, not frequency.+"""++from collections import Counter+from typing import Any, Dict, List, Optional, Set, Tuple++from . import relevance++# Minimum on-topic ratio for the overall corpus. Below this, the engine should+# retry with a wider keyword query. Rome measured ~0.2 (8/40 on-topic).+CORPUS_ON_TOPIC_FLOOR = 0.4++# Minimum on-topic ratio for a handle's posts to qualify for FROM promotion.+HANDLE_ON_TOPIC_FLOOR = 0.5++# Minimum on-topic keyword hits before a handle can be promoted to FROM lane.+# Prevents promoting handles that appeared in thin phrase hits with only 1 match.+MIN_ON_TOPIC_HITS = 2+++# Ambiguous short tokens that require case-sensitive matching to avoid+# pronoun/acronym collisions. E.g., "US" (country) vs "us" (pronoun).+# For these tokens, require the text to contain the uppercase form (acronym)+# rather than just the lowercase form (common word).+_CASE_SENSITIVE_ACRONYMS = frozenset({'us'})+++def _compute_relevance(query: str, text: str) -> float:+ """Compute relevance score for a post against the topic query.++ Returns 0.0 for empty/stopword-only queries to avoid treating all items+ as equally relevant (the shared relevance module returns 0.5 for empty+ queries as a neutral fallback, but x_judge needs strict filtering).++ Uses case-sensitive matching for ambiguous short tokens like 'us' to+ distinguish country acronym 'US' from pronoun 'us'.+ """+ import re+ if not query or not text:+ return 0.0++ q_tokens = relevance.tokenize(query)+ if not q_tokens:+ return 0.0 # All query tokens were stopwords++ # Check for ambiguous acronyms that need case-sensitive handling+ t_tokens = relevance.tokenize(text)+ filtered_q_tokens = set(q_tokens)+ for acronym in _CASE_SENSITIVE_ACRONYMS:+ if acronym in q_tokens and acronym in t_tokens:+ # Text has the token, but we need to check if it's the acronym (US)+ # or the common word (us). If text only has lowercase, don't count it.+ has_uppercase = bool(re.search(rf'\b{acronym.upper()}\b', text))+ has_lowercase = bool(re.search(rf'\b{acronym}\b', text))+ if has_lowercase and not has_uppercase:+ # Text only has lowercase version (pronoun) - don't count this+ # token in query overlap. This effectively removes "us" from+ # contributing to the score when text has only the pronoun.+ t_tokens = t_tokens - {acronym}+ # Also remove from query for this calculation to avoid+ # penalizing the overall coverage ratio+ filtered_q_tokens = filtered_q_tokens - {acronym}++ # If filtering removed all query tokens, fall back to 0+ if not filtered_q_tokens:+ return 0.0++ overlap_tokens = filtered_q_tokens & t_tokens+ if not overlap_tokens:+ return 0.0++ # Compute simplified relevance: coverage ratio+ # This is a simpler version of token_overlap_relevance that uses+ # the filtered tokens rather than re-tokenizing the original text+ coverage = len(overlap_tokens) / len(filtered_q_tokens)+ return coverage+++def judge_x_corpus(+ items: List[Dict[str, Any]],+ topic: str,+ *,+ ranking_query: str = "",+) -> Dict[str, Any]:+ """Judge the retrieved X corpus for on-topic ratio.++ Args:+ items: List of X items with 'author_handle' and 'text' fields+ topic: The user topic (e.g., "Rome")+ ranking_query: Optional ranking query for better relevance scoring++ Returns:+ Dict with:+ - on_topic_ratio: float, fraction of posts that are on-topic+ - is_off_topic_flood: bool, True if corpus fails the on-topic floor+ - on_topic_items: list, items that passed relevance check+ - off_topic_items: list, items that failed relevance check+ - handle_stats: dict, per-handle on-topic counts and totals+ """+ if not items:+ return {+ "on_topic_ratio": 1.0,+ "is_off_topic_flood": False,+ "on_topic_items": [],+ "off_topic_items": [],+ "handle_stats": {},+ }++ # Use ranking_query if provided, otherwise topic+ query = ranking_query or topic++ on_topic_items = []+ off_topic_items = []+ handle_stats: Dict[str, Dict[str, int]] = {}++ for item in items:+ handle = (item.get("author_handle") or "").lower()+ text = item.get("text") or ""+ score = _compute_relevance(query, text)++ # On-topic threshold: relevance.RELEVANCE_FLOOR is 0.1+ is_on_topic = score >= relevance.RELEVANCE_FLOOR++ if is_on_topic:+ on_topic_items.append(item)+ else:+ off_topic_items.append(item)++ if handle:+ if handle not in handle_stats:+ handle_stats[handle] = {"on_topic": 0, "total": 0}+ handle_stats[handle]["total"] += 1+ if is_on_topic:+ handle_stats[handle]["on_topic"] += 1++ on_topic_ratio = len(on_topic_items) / len(items) if items else 1.0++ # Check if top-3 frequency authors have poor on-topic ratio+ top_handles = sorted(+ handle_stats.items(),+ key=lambda x: x[1]["total"],+ reverse=True,+ )[:3]+ top_authors_off_topic = all(+ stats["on_topic"] / stats["total"] < HANDLE_ON_TOPIC_FLOOR+ for _, stats in top_handles+ if stats["total"] > 0+ ) if top_handles else False++ is_off_topic_flood = (+ on_topic_ratio < CORPUS_ON_TOPIC_FLOOR+ or (top_authors_off_topic and len(on_topic_items) < MIN_ON_TOPIC_HITS)+ )++ return {+ "on_topic_ratio": on_topic_ratio,+ "is_off_topic_flood": is_off_topic_flood,+ "on_topic_items": on_topic_items,+ "off_topic_items": off_topic_items,+ "handle_stats": handle_stats,+ }+++def promotable_handles(+ items: List[Dict[str, Any]],+ topic: str,+ extracted_handles: List[str],+ *,+ explicit_handles: Optional[List[str]] = None,+ ranking_query: str = "",+) -> Tuple[List[str], List[str]]:+ """Determine which handles should be promoted to the FROM lane.++ Split FROM promotion:+ - Explicit handles (--x-handle/--x-related): always promoted, no AND topic+ - Extracted handles: promoted only if:+ - ≥MIN_ON_TOPIC_HITS on-topic keyword hits AND+ - author on-topic ratio ≥ HANDLE_ON_TOPIC_FLOOR+ - These pulls AND the topic (from:handle Rome)++ Args:+ items: List of X items with 'author_handle' and 'text' fields+ topic: The user topic+ extracted_handles: Handles extracted from entity_extract+ explicit_handles: Explicit --x-handle/--x-related handles+ ranking_query: Optional ranking query for relevance scoring++ Returns:+ Tuple of (explicit_promotable, extracted_promotable):+ - explicit_promotable: handles that get FROM without AND topic+ - extracted_promotable: handles that get FROM with AND topic+ """+ explicit_set = {+ h.lower().lstrip("@")+ for h in (explicit_handles or [])+ if h and h.strip()+ }++ # Judge corpus to get handle stats+ judgment = judge_x_corpus(items, topic, ranking_query=ranking_query)+ handle_stats = judgment["handle_stats"]++ explicit_promotable = []+ extracted_promotable = []++ for handle in extracted_handles:+ handle_lower = handle.lower().lstrip("@")++ # Explicit handles always promoted (no AND topic)+ if handle_lower in explicit_set:+ explicit_promotable.append(handle)+ continue++ # Check if handle qualifies for extracted promotion+ stats = handle_stats.get(handle_lower, {"on_topic": 0, "total": 0})++ # Need ≥MIN_ON_TOPIC_HITS on-topic posts+ if stats["on_topic"] < MIN_ON_TOPIC_HITS:+ continue++ # Need ≥HANDLE_ON_TOPIC_FLOOR ratio+ if stats["total"] > 0:+ ratio = stats["on_topic"] / stats["total"]+ if ratio >= HANDLE_ON_TOPIC_FLOOR:+ extracted_promotable.append(handle)++ # Also check explicit handles not in extracted list+ for handle in (explicit_handles or []):+ handle_lower = handle.lower().lstrip("@")+ if handle_lower not in [h.lower() for h in explicit_promotable]:+ if handle_lower not in [h.lower() for h in extracted_handles]:+ explicit_promotable.append(handle)++ return explicit_promotable, extracted_promotable+++def should_retry_x_search(+ items: List[Dict[str, Any]],+ topic: str,+ *,+ ranking_query: str = "",+ depth: str = "default",+) -> bool:+ """Determine if X search should retry with wider keyword query.++ Skip retry on quick/mock (same as Phase 2).++ Args:+ items: Retrieved X items+ topic: The user topic+ ranking_query: Optional ranking query+ depth: Search depth ("quick", "default", "deep")++ Returns:+ True if retry is warranted+ """+ if depth == "quick":+ return False++ if not items:+ return False # Nothing to judge, no retry++ judgment = judge_x_corpus(items, topic, ranking_query=ranking_query)+ return judgment["is_off_topic_flood"]+++def prune_off_topic_items(+ items: List[Dict[str, Any]],+ topic: str,+ *,+ ranking_query: str = "",+) -> List[Dict[str, Any]]:+ """Prune off-topic items before the pool.++ Eight on-topic items with 32 pruned → ok with 8.+ Zero on-topic → no-results, not ok with 40 junk.++ Args:+ items: Retrieved X items+ topic: The user topic+ ranking_query: Optional ranking query++ Returns:+ Only on-topic items+ """+ judgment = judge_x_corpus(items, topic, ranking_query=ranking_query)+ return judgment["on_topic_items"]diff --git a/tests/test_grok_lanes_pipeline.py b/tests/test_grok_lanes_pipeline.pyindex fe35eeb4..edeb8a01 100644--- a/tests/test_grok_lanes_pipeline.py+++ b/tests/test_grok_lanes_pipeline.py@@ -74,14 +74,22 @@ def test_partial_coverage_is_recorded():)-def test_by_lane_does_not_and_the_topic_into_the_query():- """A prior defect emptied the from-lane by ANDing the topic into it."""+def test_by_lane_does_not_and_the_topic_by_default():+ """A prior defect emptied the from-lane by ANDing the topic into it.++ The `and_topic` parameter now exists for extracted handles that need to+ demonstrate on-topic content, but the default is False (no topic AND).+ """from lib import grok_xsig = inspect.signature(grok_x.search_handles)assert "topic" in sig.parameters+ # and_topic parameter should default to False+ assert "and_topic" in sig.parameters+ assert sig.parameters["and_topic"].default is Falsebody = inspect.getsource(grok_x.search_handles)assert "from:{clean}" in body- assert "{topic}" not in body+ # The default path (and_topic=False) should not include {topic} in the query+ assert 'query = f"from:{clean} since:{from_date}' in bodydiff --git a/tests/test_grok_x.py b/tests/test_grok_x.pyindex 3d5d3f54..b25d63c1 100644--- a/tests/test_grok_x.py+++ b/tests/test_grok_x.py@@ -653,3 +653,59 @@ def test_depth_drives_the_fanout_call_count():deep = grok_x._fanout_queries("t", "2026-07-14", "2026-08-13", 4)assert len(quick) == 1 and len(deep) == 4assert len(set(deep)) == 4, "fan-out variants must differ or they repeat one result set"+++def test_fanout_queries_no_phrase_quote_for_place_names():+ """_fanout_queries("Rome Italy") must not emit '"Rome Italy"' variant.++ This was the 2026-08-14 Rome failure: phrase-quoting "Rome Italy" returned+ thin hits that promoted off-topic accounts (PrettyCitiesX, visegrad24).+ """+ variants = grok_x._fanout_queries("Rome Italy", "2026-07-14", "2026-08-13", 4)+ for v in variants:+ assert '"Rome Italy"' not in v, (+ "Place/disambiguation strings must not be phrase-quoted; "+ f"got {v!r}"+ )+ # First variant should use unquoted AND+ assert "Rome Italy" in variants[0]+++def test_fanout_queries_proper_name_gets_phrase_quote():+ """Proper names like 'Peter Steinberger' should get phrase-quoted variant."""+ variants = grok_x._fanout_queries("Peter Steinberger", "2026-07-14", "2026-08-13", 4)+ # One of the variants should phrase-quote the proper name+ has_phrase = any('"Peter Steinberger"' in v for v in variants)+ assert has_phrase, (+ "Proper person names should have a phrase-quoted variant for exact match"+ )+++def test_search_handles_and_topic_false_does_not_add_topic(monkeypatch):+ """search_handles without and_topic should not AND the topic into query."""+ seen = {}+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")++ def fake_run(cmd, **kwargs):+ seen["prompt"] = cmd[2]+ return subprocess.CompletedProcess(cmd, 0, _block("2087568620465607078"), "")++ monkeypatch.setattr(grok_x.subprocess, "run", fake_run)+ grok_x.search_handles(["steipete"], "quantum widgets", *WINDOW, and_topic=False)+ assert "quantum widgets" not in seen["prompt"]+++def test_search_handles_and_topic_true_adds_topic_to_query(monkeypatch):+ """search_handles with and_topic=True should AND the topic into query."""+ seen = {}+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")++ def fake_run(cmd, **kwargs):+ seen["prompt"] = cmd[2]+ return subprocess.CompletedProcess(cmd, 0, _block("2087568620465607078"), "")++ monkeypatch.setattr(grok_x.subprocess, "run", fake_run)+ grok_x.search_handles(["visegrad24"], "Rome", *WINDOW, and_topic=True)+ assert "Rome" in seen["prompt"], (+ "Extracted handles should AND the topic to ensure on-topic results"+ )diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.pyindex 512f92e8..f0b13879 100644--- a/tests/test_pipeline_v3.py+++ b/tests/test_pipeline_v3.py@@ -925,9 +925,12 @@ class TestSupplementalSearches(unittest.TestCase):]bundle = schema.RetrievalBundle()+ # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITSbundle.items_by_source["x"] = [- _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="Some tweet about AI"),- _make_source_item("x", "X2", "https://x.com/reporter2/status/2", author="reporter2", body="AI analysis @expert3"),+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),+ _make_source_item("x", "X2", "https://x.com/analyst1/status/2", author="analyst1", body="AI safety research"),+ _make_source_item("x", "X3", "https://x.com/reporter2/status/3", author="reporter2", body="AI safety report"),+ _make_source_item("x", "X4", "https://x.com/reporter2/status/4", author="reporter2", body="AI safety news"),]plan = _make_plan("AI safety")@@ -954,9 +957,10 @@ class TestSupplementalSearches(unittest.TestCase):@patch("lib.env.x_backend_chain", return_value=["xquik"])@patch("lib.xquik.search_xquik", return_value={"items": []})- def test_x_topic_lane_uses_anchored_query_via_xquik(self, mock_search, _chain):- """The X topic lane (here resolved to the xquik backend) consumes the- anchored subquery.search_query (#611), not the bare raw_topic."""+ def test_x_topic_lane_uses_raw_topic_via_xquik(self, mock_search, _chain):+ """The X topic lane uses raw_topic (like Reddit/YouTube), not the+ planner's search_query. This avoids phrase-quoting issues like "Rome Italy"+ returning off-topic results. Disambiguation lives in ranking_query."""anchored = schema.SubQuery(label="primary", search_query="kevin rose digg founder",ranking_query="What has Kevin Rose, founder of Digg, been doing?",@@ -969,7 +973,8 @@ class TestSupplementalSearches(unittest.TestCase):mock=False, raw_topic="kevin rose",)mock_search.assert_called_once()- self.assertEqual("kevin rose digg founder", mock_search.call_args[0][0])+ # X now uses raw_topic, not search_query (like Reddit/YouTube)+ self.assertEqual("kevin rose", mock_search.call_args[0][0])@patch("lib.env.get_xquik_token", return_value="k")@patch("lib.env.x_backend_chain", return_value=["xquik"])@@ -989,8 +994,10 @@ class TestSupplementalSearches(unittest.TestCase):}]bundle = schema.RetrievalBundle()+ # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITSbundle.items_by_source["x"] = [- _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="tweet about AI"),+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),+ _make_source_item("x", "X2", "https://x.com/analyst1/status/2", author="analyst1", body="AI safety research"),]pipeline._run_supplemental_searches(@@ -1024,8 +1031,10 @@ class TestSupplementalSearches(unittest.TestCase):"engagement": {"likes": 5}, "relevance": 0.8, "why_relevant": "",}]bundle = schema.RetrievalBundle()+ # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITSbundle.items_by_source["x"] = [- _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="tweet"),+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),+ _make_source_item("x", "X2", "https://x.com/analyst1/status/2", author="analyst1", body="AI safety research"),]pipeline._run_supplemental_searches(topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},@@ -1093,8 +1102,10 @@ class TestSupplementalSearches(unittest.TestCase):mock_handles.return_value = []mock_mentions.return_value = []bundle = schema.RetrievalBundle()+ # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITSbundle.items_by_source["x"] = [- _make_source_item("x", "X1", "https://x.com/subject1/status/1", author="subject1", body="hi"),+ _make_source_item("x", "X1", "https://x.com/subject1/status/1", author="subject1", body="subject1 discussion"),+ _make_source_item("x", "X2", "https://x.com/subject1/status/2", author="subject1", body="subject1 update"),]pipeline._run_supplemental_searches(topic="subject1",diff --git a/tests/test_x_judge.py b/tests/test_x_judge.pynew file mode 100644index 00000000..d42c0694--- /dev/null+++ b/tests/test_x_judge.py@@ -0,0 +1,351 @@+"""Tests for x_judge.py — corpus judging for retrieve-judge-retry."""++import pytest++from skills.last30days.scripts.lib import x_judge+++class TestJudgeXCorpus:+ """Tests for judge_x_corpus."""++ def test_empty_corpus_returns_not_flood(self):+ """Empty corpus should not be flagged as off-topic flood."""+ result = x_judge.judge_x_corpus([], "Rome")+ assert result["on_topic_ratio"] == 1.0+ assert not result["is_off_topic_flood"]+ assert result["on_topic_items"] == []+ assert result["off_topic_items"] == []++ def test_on_topic_corpus_passes(self):+ """Corpus with mostly on-topic posts should pass."""+ items = [+ {"author_handle": "mamboitaliano__", "text": "Beautiful Rome sunset"},+ {"author_handle": "mamboitaliano__", "text": "Trevi Fountain in Rome"},+ {"author_handle": "mamboitaliano__", "text": "Rome Colosseum today"},+ {"author_handle": "turismoromaweb", "text": "Visit Rome Italy"},+ ]+ result = x_judge.judge_x_corpus(items, "Rome")+ assert result["on_topic_ratio"] >= 0.5+ assert not result["is_off_topic_flood"]+ assert len(result["on_topic_items"]) >= 3++ def test_off_topic_flood_detected(self):+ """Corpus with mostly off-topic posts should be flagged as flood."""+ # Rome fixture: 8 on-topic posts, 32 off-topic posts+ on_topic = [+ {"author_handle": "mamboitaliano__", "text": "Beautiful Rome sunset"},+ {"author_handle": "mamboitaliano__", "text": "Trevi Fountain in Rome"},+ {"author_handle": "mamboitaliano__", "text": "Rome Colosseum today"},+ {"author_handle": "turismoromaweb", "text": "Visit Rome Italy"},+ {"author_handle": "romecityphoto", "text": "Rome city at night"},+ {"author_handle": "visitrome", "text": "Rome vacation tips"},+ {"author_handle": "italytravel", "text": "Rome and Florence tour"},+ {"author_handle": "rometraveler", "text": "Rome landmarks to see"},+ ]+ off_topic = [+ {"author_handle": "visegrad24", "text": "Zelensky addresses NATO summit"},+ {"author_handle": "visegrad24", "text": "Poland border update"},+ {"author_handle": "visegrad24", "text": "Ukraine military news"},+ {"author_handle": "PrettyCitiesX", "text": "London bridge at sunset"},+ {"author_handle": "PrettyCitiesX", "text": "Paris Eiffel tower"},+ {"author_handle": "PrettyCitiesX", "text": "Tokyo skyline"},+ {"author_handle": "earthserenityy", "text": "Mountain landscape photo"},+ {"author_handle": "earthserenityy", "text": "Beach sunset vibes"},+ ]+ # Repeat off-topic to get 32 items+ all_off_topic = off_topic * 4+ items = on_topic + all_off_topic++ result = x_judge.judge_x_corpus(items, "Rome")+ assert result["on_topic_ratio"] < 0.4+ assert result["is_off_topic_flood"]+ assert len(result["on_topic_items"]) == 8++ def test_no_substring_collision_ai_in_said(self):+ """'AI' as a topic token should NOT match 'said' (no substring collisions).++ This verifies that topic judging uses proper word tokenization, not+ substring matching. If substring matching were used, 'ai' would match+ inside 'said', causing false positives.+ """+ items = [+ {"author_handle": "offtopic", "text": "He said something interesting"},+ {"author_handle": "offtopic", "text": "She said the weather was nice"},+ {"author_handle": "offtopic", "text": "They said it was great"},+ ]+ result = x_judge.judge_x_corpus(items, "AI")+ # None of these posts contain "AI" as a word, so all should be off-topic+ assert len(result["on_topic_items"]) == 0+ assert len(result["off_topic_items"]) == 3++ def test_no_substring_collision_rome_in_promoter(self):+ """'rome' as a topic token should NOT match 'promoter' (no substring collisions)."""+ items = [+ {"author_handle": "offtopic", "text": "A viral promoter of products"},+ {"author_handle": "offtopic", "text": "She is a band promoter"},+ ]+ result = x_judge.judge_x_corpus(items, "Rome")+ # None of these posts contain "Rome" as a word+ assert len(result["on_topic_items"]) == 0+ assert len(result["off_topic_items"]) == 2++ def test_us_pronoun_does_not_match_us_topic(self):+ """Lowercase 'us' pronoun should not match 'US' country topic."""+ items = [+ {"author_handle": "offtopic", "text": "Tell us what you think"},+ {"author_handle": "offtopic", "text": "Join us for the event"},+ ]+ # "US" topic vs "us" pronoun in text - case-sensitive check filters+ result = x_judge.judge_x_corpus(items, "US")+ assert len(result["on_topic_items"]) == 0+ assert len(result["off_topic_items"]) == 2++ def test_us_acronym_matches_us_topic(self):+ """Uppercase 'US' country acronym in text matches 'US' topic."""+ items = [+ {"author_handle": "ontopic", "text": "The US is expanding trade"},+ {"author_handle": "ontopic", "text": "US policy update"},+ ]+ result = x_judge.judge_x_corpus(items, "US")+ assert len(result["on_topic_items"]) == 2+ assert len(result["off_topic_items"]) == 0++ def test_us_with_context_matches(self):+ """'US economy' matches posts about US economy."""+ items = [+ {"author_handle": "ontopic", "text": "The US economy is growing"},+ {"author_handle": "ontopic", "text": "Economy news from America"},+ ]+ result = x_judge.judge_x_corpus(items, "US economy")+ # First post has "US" (acronym) and "economy" → on-topic+ # Second post has "economy" only → on-topic+ assert len(result["on_topic_items"]) >= 1++ def test_multi_token_us_query_with_pronoun(self):+ """'US economy' should NOT match text with pronoun 'us' and 'economy'."""+ items = [+ {"author_handle": "offtopic", "text": "Tell us about the economy"},+ {"author_handle": "offtopic", "text": "Let us discuss economy trends"},+ ]+ result = x_judge.judge_x_corpus(items, "US economy")+ # These have lowercase "us" (pronoun) not "US" (country)+ # Should match on "economy" alone (50% coverage), which may or may not+ # pass the relevance floor depending on thresholds+ # The key test is that "us" doesn't contribute to the match+ for item in result["on_topic_items"]:+ # If on-topic, it should be due to "economy" match only+ assert "economy" in item["text"].lower()++ def test_handle_stats_computed(self):+ """Handle stats should track on-topic and total counts."""+ items = [+ {"author_handle": "handle_a", "text": "Rome is beautiful"},+ {"author_handle": "handle_a", "text": "Paris is nice"},+ {"author_handle": "handle_b", "text": "Rome vacation"},+ {"author_handle": "handle_b", "text": "Rome food"},+ ]+ result = x_judge.judge_x_corpus(items, "Rome")+ assert result["handle_stats"]["handle_a"]["total"] == 2+ assert result["handle_stats"]["handle_b"]["total"] == 2+ # handle_b has 2 on-topic posts about Rome+ assert result["handle_stats"]["handle_b"]["on_topic"] == 2+++class TestPromotableHandles:+ """Tests for promotable_handles — split FROM promotion."""++ def test_explicit_handles_always_promoted(self):+ """Explicit handles (--x-handle) should always be promoted."""+ items = [+ {"author_handle": "steipete", "text": "random post about nothing"},+ ]+ explicit, extracted = x_judge.promotable_handles(+ items, "quantum widgets", ["steipete"], explicit_handles=["steipete"]+ )+ assert "steipete" in explicit+ assert "steipete" not in extracted++ def test_extracted_handle_promoted_with_on_topic_posts(self):+ """Extracted handle with ≥2 on-topic posts should be promoted."""+ items = [+ {"author_handle": "mamboitaliano__", "text": "Rome sunset beautiful"},+ {"author_handle": "mamboitaliano__", "text": "Rome Colosseum tour"},+ {"author_handle": "mamboitaliano__", "text": "Trevi Fountain Rome"},+ ]+ explicit, extracted = x_judge.promotable_handles(+ items, "Rome", ["mamboitaliano__"], explicit_handles=[]+ )+ assert "mamboitaliano__" in extracted+ assert len(explicit) == 0++ def test_extracted_handle_not_promoted_with_off_topic_posts(self):+ """Extracted handle with off-topic posts should not be promoted."""+ items = [+ {"author_handle": "visegrad24", "text": "Zelensky addresses summit"},+ {"author_handle": "visegrad24", "text": "Poland military update"},+ {"author_handle": "visegrad24", "text": "Ukraine border news"},+ # One post mentions Rome but mostly off-topic+ {"author_handle": "visegrad24", "text": "Rome, Italy in caption"},+ ]+ explicit, extracted = x_judge.promotable_handles(+ items, "Rome", ["visegrad24"], explicit_handles=[]+ )+ assert "visegrad24" not in extracted+ assert len(explicit) == 0++ def test_explicit_handle_not_in_extracted_still_promoted(self):+ """Explicit handle not in extracted list should still be promoted."""+ items = [] # No items for this handle+ explicit, extracted = x_judge.promotable_handles(+ items, "topic", [], explicit_handles=["explicit_handle"]+ )+ assert "explicit_handle" in explicit++ def test_min_hits_threshold(self):+ """Handle needs MIN_ON_TOPIC_HITS to be promoted."""+ items = [+ {"author_handle": "onepost", "text": "Rome is nice"}, # Only 1 on-topic+ ]+ explicit, extracted = x_judge.promotable_handles(+ items, "Rome", ["onepost"], explicit_handles=[]+ )+ # Not enough on-topic hits (needs ≥2)+ assert "onepost" not in extracted+++class TestShouldRetryXSearch:+ """Tests for should_retry_x_search."""++ def test_skip_retry_on_quick_depth(self):+ """Quick depth should skip retry."""+ items = [+ {"author_handle": "off_topic", "text": "completely unrelated content"},+ ] * 40+ assert not x_judge.should_retry_x_search(items, "Rome", depth="quick")++ def test_trigger_retry_on_off_topic_flood(self):+ """Off-topic flood should trigger retry."""+ off_topic = [+ {"author_handle": "off_topic", "text": "completely unrelated content"},+ ] * 40+ assert x_judge.should_retry_x_search(off_topic, "Rome", depth="default")++ def test_no_retry_on_good_corpus(self):+ """On-topic corpus should not trigger retry."""+ on_topic = [+ {"author_handle": "romefan", "text": "Rome vacation photos"},+ {"author_handle": "romefan", "text": "Rome colosseum visit"},+ {"author_handle": "romefan", "text": "Rome food tour"},+ {"author_handle": "romefan", "text": "Rome sunset beautiful"},+ ]+ assert not x_judge.should_retry_x_search(on_topic, "Rome", depth="default")+++class TestPruneOffTopicItems:+ """Tests for prune_off_topic_items."""++ def test_prunes_off_topic_keeps_on_topic(self):+ """Should prune off-topic items and keep on-topic ones."""+ items = [+ {"author_handle": "on", "text": "Rome vacation"},+ {"author_handle": "off", "text": "Paris travel"},+ {"author_handle": "on", "text": "Rome colosseum"},+ {"author_handle": "off", "text": "London sights"},+ ]+ result = x_judge.prune_off_topic_items(items, "Rome")+ assert len(result) == 2+ assert all("Rome" in item["text"] for item in result)++ def test_empty_after_prune_is_ok(self):+ """Pruning all items should return empty list."""+ items = [+ {"author_handle": "off", "text": "completely unrelated"},+ {"author_handle": "off", "text": "nothing to do with topic"},+ ]+ result = x_judge.prune_off_topic_items(items, "Rome")+ assert result == []+++class TestRomeScenario:+ """Integration tests for the Rome failure scenario from 2026-08-14."""++ @pytest.fixture+ def rome_off_topic_corpus(self):+ """The Rome failure corpus: 8 on-topic, 32 off-topic."""+ on_topic = [+ {"author_handle": "mamboitaliano__", "text": "Beautiful Rome sunset over the Tiber"},+ {"author_handle": "mamboitaliano__", "text": "Trevi Fountain in Rome today"},+ {"author_handle": "mamboitaliano__", "text": "Rome Colosseum morning visit"},+ {"author_handle": "Turismoromaweb", "text": "Visit Rome Italy for vacation"},+ {"author_handle": "romecityguide", "text": "Rome city center walking tour"},+ {"author_handle": "italyrome", "text": "Rome and Vatican day trip"},+ {"author_handle": "romephotos", "text": "Rome architecture stunning"},+ {"author_handle": "rometravel", "text": "Rome travel tips for tourists"},+ ]+ off_topic = [+ # visegrad24 - geopolitics account, thin Rome connection+ {"author_handle": "visegrad24", "text": "Zelensky addresses NATO summit"},+ {"author_handle": "visegrad24", "text": "Poland border security update"},+ {"author_handle": "visegrad24", "text": "Ukraine military operations today"},+ {"author_handle": "visegrad24", "text": "Russia sanctions news breaking"},+ # PrettyCitiesX - city aesthetics account, has other cities+ {"author_handle": "PrettyCitiesX", "text": "London bridge at sunset"},+ {"author_handle": "PrettyCitiesX", "text": "Paris Eiffel tower night"},+ {"author_handle": "PrettyCitiesX", "text": "Tokyo skyline beautiful"},+ {"author_handle": "PrettyCitiesX", "text": "New York Central Park"},+ # earthserenityy - nature photos, no Rome+ {"author_handle": "earthserenityy", "text": "Mountain landscape photography"},+ {"author_handle": "earthserenityy", "text": "Beach sunset vibes serene"},+ {"author_handle": "earthserenityy", "text": "Forest morning fog mystical"},+ {"author_handle": "earthserenityy", "text": "Ocean waves crashing shore"},+ # AS Roma sports content (Rome collision)+ {"author_handle": "asromafc", "text": "AS Roma match tonight Serie A"},+ {"author_handle": "asromafc", "text": "Roma vs Juventus preview"},+ {"author_handle": "asromafc", "text": "Forza Roma goal highlights"},+ {"author_handle": "asromafc", "text": "AS Roma transfer rumors"},+ # Rome Odunze collision+ {"author_handle": "nflupdates", "text": "Rome Odunze catches touchdown"},+ {"author_handle": "nflupdates", "text": "Bears WR Rome Odunze stats"},+ {"author_handle": "fantasyfb", "text": "Start Rome Odunze this week"},+ {"author_handle": "fantasyfb", "text": "Rome Odunze fantasy value"},+ ]+ # Duplicate off-topic to reach ~32 items+ return on_topic + off_topic + off_topic[:12]++ def test_rome_corpus_detected_as_off_topic(self, rome_off_topic_corpus):+ """Rome failure corpus should be detected as off-topic flood."""+ result = x_judge.judge_x_corpus(rome_off_topic_corpus, "Rome")+ # ~8/40 = 0.2, well below 0.4 threshold+ assert result["on_topic_ratio"] < 0.4+ assert result["is_off_topic_flood"]++ def test_mamboitaliano_promotable(self, rome_off_topic_corpus):+ """mamboitaliano__ with on-topic Rome posts should be promotable."""+ explicit, extracted = x_judge.promotable_handles(+ rome_off_topic_corpus,+ "Rome",+ ["mamboitaliano__", "visegrad24", "PrettyCitiesX"],+ explicit_handles=[],+ )+ assert "mamboitaliano__" in extracted++ def test_visegrad24_not_promotable(self, rome_off_topic_corpus):+ """visegrad24 with off-topic posts should NOT be promotable."""+ explicit, extracted = x_judge.promotable_handles(+ rome_off_topic_corpus,+ "Rome",+ ["mamboitaliano__", "visegrad24", "PrettyCitiesX"],+ explicit_handles=[],+ )+ assert "visegrad24" not in extracted+ assert "PrettyCitiesX" not in extracted++ def test_turismoromaweb_promotable_if_explicit(self, rome_off_topic_corpus):+ """Turismoromaweb should be promoted if explicitly specified."""+ explicit, extracted = x_judge.promotable_handles(+ rome_off_topic_corpus,+ "Rome",+ ["Turismoromaweb"],+ explicit_handles=["Turismoromaweb"],+ )+ assert "Turismoromaweb" in explicit