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): single X source with backend failover + xquik parity (#622)

Matt Van Horn03848365dd3e
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 6d9869a6..11aa4ad8 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -84,6 +84,8 @@ The project-scoped file is the cleanest pattern for **per-client setups**: drop
| Jobs / careers pages | none for public ATS pages; web backend improves fallback discovery | `--hiring-signals` and strong Hiring Signals in standard company reports | yes |
| Apify (alternate scraper) | `APIFY_API_TOKEN` | fallback for Reddit/TikTok/Instagram when ScrapeCreators is exhausted | yes (limited) |
+**X on cookie-less hosts.** Bird (the free X source) scrapes X using your logged-in browser cookies (`AUTH_TOKEN`/`CT0`), which agent hosts like OpenClaw, CI, or headless runs often can't supply — and scraping carries some account risk. On those, set `XQUIK_API_KEY` (or `XAI_API_KEY`) for full, ranked X coverage from a single API key: the same engagement-based ranking, first-party authorship, and handle (from/mentions) lanes the native X source gets. `--diagnose` reports whether the key is working (and flags an unpaid key).
+
**Example `.env` skeleton** (placeholders only - replace with your own values):
```bash
diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.py
index 64c99efe..3b41c7a6 100644
--- a/skills/last30days/scripts/lib/bird_x.py
+++ b/skills/last30days/scripts/lib/bird_x.py
@@ -25,21 +25,13 @@ 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.
+ """Leading-run @mention parse, shared with other X-shaped sources (xquik).
- 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.
+ Thin wrapper over ``query.leading_mentions`` so bird and xquik share one
+ implementation; kept here for existing call sites and tests.
"""
- 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
+ from .query import leading_mentions
+ return leading_mentions(text)
def _first_of(*values):
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 878057be..ab59f351 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -603,48 +603,63 @@ def get_reddit_source(config: dict[str, Any]) -> str | None:
return None
-def get_x_source(config: dict[str, Any]) -> str | None:
- """Determine the best available explicit X/Twitter source.
+# Default X backend priority. The first available backend is the primary X
+# source; the rest are ordered failover backups, tried only if the one before
+# returns nothing or errors. There is one X source ("x"); these are its
+# interchangeable backends, never run in parallel.
+# xai — xAI/Grok live search (XAI_API_KEY)
+# bird — X GraphQL scrape via the user's browser cookies (AUTH_TOKEN/CT0)
+# xurl — official X API v2 (xurl CLI, OAuth2)
+# xquik — key-based REST X search (XQUIK_API_KEY); keyless of browser cookies
+_X_BACKEND_ORDER = ("xai", "bird", "xurl", "xquik")
+
+
+def _x_backend_available(backend: str, config: dict[str, Any], has_bird_creds: bool) -> bool:
+ if backend == 'xai':
+ return bool(config.get('XAI_API_KEY'))
+ if backend == 'bird':
+ from . import bird_x
+ return has_bird_creds and bird_x.is_bird_installed()
+ if backend == 'xurl':
+ from . import xurl_x
+ return xurl_x.is_available()
+ if backend == 'xquik':
+ return is_xquik_available(config)
+ return False
- Priority: explicit backend pin, then xAI, then Bird with explicit cookies.
- Browser-cookie probing is intentionally not used here. Automatic Keychain
- access causes popups during normal pipeline runs. Bird is only considered
- available when AUTH_TOKEN and CT0 are present explicitly.
+def x_backend_chain(config: dict[str, Any]) -> list[str]:
+ """Ordered list of available X backends.
- Args:
- config: Configuration dict from get_config()
+ ``chain[0]`` is the default X source; the remaining entries are failover
+ backups, used only when the one before yields no items or errors. There is
+ exactly one X source — these are its backends, never fetched in parallel.
- Returns:
- 'bird' if Bird is installed and explicit cookies are configured,
- 'xai' if XAI_API_KEY is configured,
- 'xurl' if xurl CLI is installed and authenticated,
- None if no X source available.
+ A ``LAST30DAYS_X_BACKEND`` pin forces a single backend (no failover): the
+ user explicitly chose it. Browser-cookie probing is intentionally avoided
+ (automatic Keychain access causes popups); bird counts as available only
+ when AUTH_TOKEN and CT0 are present explicitly.
"""
- # Import here to avoid circular dependency
from . import bird_x
-
- preferred = (config.get('LAST30DAYS_X_BACKEND') or '').lower()
has_bird_creds = bool(config.get('AUTH_TOKEN') and config.get('CT0'))
if has_bird_creds:
bird_x.set_credentials(config.get('AUTH_TOKEN'), config.get('CT0'))
- if preferred == 'xai':
- return 'xai' if config.get('XAI_API_KEY') else None
- if preferred == 'bird':
- return 'bird' if has_bird_creds and bird_x.is_bird_installed() else None
+ preferred = (config.get('LAST30DAYS_X_BACKEND') or '').lower()
+ if preferred in _X_BACKEND_ORDER:
+ return [preferred] if _x_backend_available(preferred, config, has_bird_creds) else []
- if config.get('XAI_API_KEY'):
- return 'xai'
- if has_bird_creds and bird_x.is_bird_installed():
- return 'bird'
+ return [b for b in _X_BACKEND_ORDER if _x_backend_available(b, config, has_bird_creds)]
- # Fall back to xurl CLI (official X API v2, OAuth2, free developer app)
- from . import xurl_x
- if xurl_x.is_available():
- return 'xurl'
- return None
+def get_x_source(config: dict[str, Any]) -> str | None:
+ """The default (primary) X backend, or None if no X source is available.
+
+ Thin wrapper over ``x_backend_chain`` returning the first/primary backend;
+ callers that want failover should use ``x_backend_chain`` directly.
+ """
+ chain = x_backend_chain(config)
+ return chain[0] if chain else None
def is_ytdlp_available() -> bool:
@@ -890,15 +905,35 @@ def get_x_source_status(config: dict[str, Any], probe: bool = False) -> dict[str
bird_status["authenticated"] = False
bird_status["username"] = "probe failed (no working X auth)"
- # Determine active source
+ # Xquik: the key-based X source used when bird's cookie auth isn't available.
+ # Probe so --diagnose reports the true state — funded, or configured-but-
+ # unpaid (402) — instead of false-green on mere key presence.
+ xquik_available = is_xquik_available(config)
+ xquik_working: bool | None = None
+ xquik_status = ""
+ if xquik_available:
+ if probe:
+ from . import xquik
+ xquik_working = xquik.probe_works(get_xquik_token(config))
+ xquik_status = xquik.probe_reason()
+ else:
+ xquik_status = "configured (not probed)"
+
+ # Determine active source. bird (browser cookies) and xAI win when present;
+ # when neither is available, xquik is the active X source. A probe that
+ # clearly failed (False) means xquik is not actually usable.
if bird_status["authenticated"]:
source = 'bird'
elif xai_available:
source = 'xai'
else:
- # Fall back to xurl CLI
from . import xurl_x as _xurl_check
- source = 'xurl' if _xurl_check.is_available() else None
+ if _xurl_check.is_available():
+ source = 'xurl'
+ elif xquik_available and xquik_working is not False:
+ source = 'xquik'
+ else:
+ source = None
from . import xurl_x as _xurl_x
return {
@@ -908,6 +943,9 @@ def get_x_source_status(config: dict[str, Any], probe: bool = False) -> dict[str
"bird_username": bird_status["username"],
"xai_available": xai_available,
"xurl_available": _xurl_x.is_available(),
+ "xquik_available": xquik_available,
+ "xquik_working": xquik_working,
+ "xquik_status": xquik_status,
"can_install_bird": bird_status["can_install"],
}
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index e28af341..46a1851e 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -63,7 +63,7 @@ SEARCH_ALIAS = {
"truth": "truthsocial",
"web": "grounding",
"xhs": "xiaohongshu",
- "xquik": "xquik",
+ "xquik": "x", # xquik is a backend of the single "x" source, not its own source
}
MAX_SOURCE_FETCHES: dict[str, int] = {"x": 2, "jobs": 1}
@@ -96,7 +96,6 @@ MOCK_AVAILABLE_SOURCES = [
"perplexity",
"threads",
"pinterest",
- "xquik",
"digg",
"jobs",
]
@@ -155,8 +154,8 @@ def available_sources(config: dict[str, Any], requested_sources: list[str] | Non
available.append("threads")
if requested_sources and "pinterest" in requested_sources and env.is_pinterest_available(config):
available.append("pinterest")
- if env.is_xquik_available(config):
- available.append("xquik")
+ # xquik is a backend of the single "x" source (see env.x_backend_chain),
+ # not a separate parallel source — registered via the "x" entry above.
exclude = {s.strip().lower() for s in (config.get("EXCLUDE_SOURCES") or "").split(",") if s.strip()}
if exclude:
available = [s for s in available if s not in exclude]
@@ -194,6 +193,9 @@ def diagnose(config: dict[str, Any], requested_sources: list[str] | None = None)
"bird_installed": x_status["bird_installed"],
"bird_authenticated": x_status["bird_authenticated"],
"bird_username": x_status["bird_username"],
+ "xquik_available": x_status.get("xquik_available", False),
+ "xquik_working": x_status.get("xquik_working"),
+ "xquik_status": x_status.get("xquik_status", ""),
"native_web_backend": native_web_backend,
"native_search": env.is_native_search(config),
"has_scrapecreators": bool(config.get("SCRAPECREATORS_API_KEY")),
@@ -823,7 +825,9 @@ def _run_supplemental_searches(
from_date, to_date = date_range
- # Convert SourceItems to dicts for entity_extract
+ # Convert SourceItems to dicts for entity_extract. All X items (whatever
+ # backend fetched them — bird, xai, xurl, xquik) land under the single "x"
+ # slug, so this reads the whole X corpus.
x_dicts = [
{"author_handle": item.author or "", "text": item.body or ""}
for item in bundle.items_by_source.get("x", [])
@@ -869,13 +873,41 @@ def _run_supplemental_searches(
if not handles and not related_handles:
return
- # Check if X is rate-limited
- if "x" in rate_limited_sources:
- return
+ # Pick the X handle-search backend: the first handle-capable backend in the
+ # chain (bird or xquik). These supplemental from:/mentions lanes are
+ # complementary to the topic search, so when the topic primary can't run
+ # them (xai/xurl have no handle-lane implementation) but a capable backend
+ # is available, use it rather than skipping Phase 2. bird scrapes X GraphQL
+ # with the user's browser cookies; xquik runs the same lanes over its REST
+ # API. All items land under the single "x" slug.
+ x_slug = "x"
+ chain = env.x_backend_chain(config)
+ # Trust an explicit runtime backend as the head of the chain.
+ pinned = runtime.x_search_backend
+ if pinned:
+ chain = [pinned] + [b for b in chain if b != pinned]
+ primary = next((b for b in chain if b in ("bird", "xquik")), None)
+
+ if primary == "bird":
+ def _from_lane(hs: list, count: int) -> list:
+ return bird_x.search_handles(hs, topic, from_date, count_per=count)
+
+ def _about_lane(hs: list, count: int) -> list:
+ return bird_x.search_mentions(hs, from_date, count_per=count)
+ elif primary == "xquik":
+ xquik_token = env.get_xquik_token(config)
+
+ def _from_lane(hs: list, count: int) -> list:
+ return xquik.search_handles(hs, topic, from_date, to_date, count_per=count, token=xquik_token)
+
+ def _about_lane(hs: list, count: int) -> list:
+ return xquik.search_mentions(hs, from_date, to_date, topic=topic, count_per=count, token=xquik_token)
+ else:
+ return # primary X backend has no handle-lane support (xai/xurl) or none configured
- backend = runtime.x_search_backend or env.get_x_source(config)
- if backend != "bird":
- return # Handle search only works with Bird CLI
+ # Skip if the X source is rate-limited.
+ if x_slug in rate_limited_sources:
+ return
# Collect existing URLs for deduplication
existing_urls = {
@@ -897,27 +929,27 @@ def _run_supplemental_searches(
from_items: list = []
about_items: list = []
try:
- from_items = bird_x.search_handles(handles, topic, from_date, count_per=FROM_LANE_COUNT_PER)
+ from_items = _from_lane(handles, 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}"
+ if not bundle.items_by_source.get(x_slug):
+ bundle.errors_by_source[x_slug] = f"Phase 2 FROM-lane: {exc}"
try:
- about_items = bird_x.search_mentions(handles, from_date, count_per=MENTION_LANE_COUNT_PER)
+ about_items = _about_lane(handles, 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
if raw_items:
normalized = _normalize_score_dedupe(
- "x", raw_items, from_date, to_date,
+ x_slug, raw_items, from_date, to_date,
freshness_mode=plan.freshness_mode,
ranking_query=ranking_query,
)
# Deduplicate against Phase 1 URLs
normalized = [item for item in normalized if item.url not in existing_urls]
if normalized:
- bundle.add_items(primary_label, "x", normalized)
+ bundle.add_items(primary_label, x_slug, normalized)
# Update existing URLs for related-handle dedup
for item in normalized:
if item.url:
@@ -926,16 +958,14 @@ def _run_supplemental_searches(
# Search related handles with lower weight (0.3)
if related_handles:
try:
- raw_items = bird_x.search_handles(
- related_handles, topic, from_date, count_per=RELATED_HANDLE_COUNT_PER,
- )
+ raw_items = _from_lane(related_handles, RELATED_HANDLE_COUNT_PER)
except Exception as exc:
print(f"[Pipeline] Phase 2 related handle search failed: {exc}", file=sys.stderr)
raw_items = []
if raw_items:
normalized = _normalize_score_dedupe(
- "x", raw_items, from_date, to_date,
+ x_slug, raw_items, from_date, to_date,
freshness_mode=plan.freshness_mode,
ranking_query=ranking_query,
)
@@ -944,7 +974,7 @@ def _run_supplemental_searches(
if normalized:
# Use a separate subquery label with lower weight so RRF
# scores related-handle results below primary results.
- bundle.add_items("supplemental-related", "x", normalized)
+ bundle.add_items("supplemental-related", x_slug, normalized)
# Register the supplemental-related label in the plan for fusion
if not any(sq.label == "supplemental-related" for sq in plan.subqueries):
plan.subqueries.append(
@@ -952,7 +982,7 @@ def _run_supplemental_searches(
label="supplemental-related",
search_query=", ".join(related_handles),
ranking_query=ranking_query,
- sources=["x"],
+ sources=[x_slug],
weight=0.3,
)
)
@@ -1061,6 +1091,33 @@ def _retry_thin_sources(
print(f"[Pipeline] Retry failed for {source}: {type(exc).__name__}: {exc}", file=sys.stderr)
+def _fetch_x_backend(backend, subquery, 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);
+ a non-empty error_str signals a hard failure (auth/payment/etc.) so the
+ caller can fail over to the next backend or surface the error honestly.
+ """
+ query = subquery.search_query
+ if backend == "bird":
+ result = bird_x.search_x(query, from_date, to_date, depth=depth)
+ items = bird_x.parse_bird_response(result, query=query)
+ elif backend == "xai":
+ model = config.get("LAST30DAYS_X_MODEL") or config.get("XAI_MODEL_PIN") or providers.XAI_DEFAULT
+ result = xai_x.search_x(config["XAI_API_KEY"], model, query, from_date, to_date, depth=depth)
+ items = xai_x.parse_x_response(result)
+ elif backend == "xurl":
+ result = xurl_x.search_x(query, depth=depth)
+ items = xurl_x.parse_x_response(result, topic=query)
+ elif backend == "xquik":
+ result = xquik.search_xquik(query, from_date, to_date, depth=depth, token=env.get_xquik_token(config))
+ items = xquik.parse_xquik_response(result)
+ else:
+ return [], f"unknown X backend: {backend}"
+ err = result.get("error") if isinstance(result, dict) else ""
+ return items, (err or "")
+
+
def _retrieve_stream(
*,
topic: str,
@@ -1137,25 +1194,29 @@ def _retrieve_stream(
)
return [], {}
if source == "x":
- backend = runtime.x_search_backend or env.get_x_source(config)
- if backend == "bird":
- result = bird_x.search_x(subquery.search_query, from_date, to_date, depth=depth)
- return bird_x.parse_bird_response(result, query=subquery.search_query), {}
- if backend == "xai":
- model = config.get("LAST30DAYS_X_MODEL") or config.get("XAI_MODEL_PIN") or providers.XAI_DEFAULT
- result = xai_x.search_x(
- config["XAI_API_KEY"],
- model,
- subquery.search_query,
- from_date,
- to_date,
- depth=depth,
- )
- return xai_x.parse_x_response(result), {}
- if backend == "xurl":
- result = xurl_x.search_x(subquery.search_query, depth=depth)
- return xurl_x.parse_x_response(result, topic=subquery.search_query), {}
- raise RuntimeError("No X backend is available.")
+ # 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)
+ # Trust an explicit runtime backend as the primary (already resolved as
+ # available), keeping the rest of the chain as failover backups.
+ pinned = runtime.x_search_backend
+ if pinned:
+ chain = [pinned] + [b for b in chain if b != pinned]
+ if not chain:
+ raise RuntimeError("No X backend is available.")
+ last_error = ""
+ for i, backend in enumerate(chain):
+ items, err = _fetch_x_backend(backend, subquery, 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)
+ return items, {}
+ if err:
+ last_error = f"{backend}: {err}"
+ print(f"[X] backend '{backend}' failed ({err}); trying next", file=sys.stderr)
+ if last_error:
+ raise RuntimeError(f"All X backends failed — {last_error}")
+ return [], {}
if source == "youtube":
# Use raw_topic so expand_youtube_queries() generates diverse variants
# from the original user topic, not the planner's narrowed search_query.
@@ -1282,13 +1343,6 @@ def _retrieve_stream(
), {}
if source == "perplexity":
return perplexity.search(subquery.search_query, date_range, config, deep=config.get("_deep_research", False))
- if source == "xquik":
- result = xquik.search_xquik(
- subquery.search_query, from_date, to_date,
- depth=depth,
- token=env.get_xquik_token(config),
- )
- return xquik.parse_xquik_response(result), {}
raise RuntimeError(f"Unsupported source: {source}")
diff --git a/skills/last30days/scripts/lib/query.py b/skills/last30days/scripts/lib/query.py
index e735e623..f3a4f97b 100644
--- a/skills/last30days/scripts/lib/query.py
+++ b/skills/last30days/scripts/lib/query.py
@@ -181,3 +181,22 @@ def extract_compound_terms(topic: str) -> List[str]:
terms.append(match.group())
return terms
+
+
+def leading_mentions(text: Optional[str]) -> List[str]:
+ """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. Shared by every X-shaped
+ source adapter (bird, xquik) so leading-mention parsing has one definition.
+ """
+ out: List[str] = []
+ 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
diff --git a/skills/last30days/scripts/lib/xquik.py b/skills/last30days/scripts/lib/xquik.py
index 80b6ae3f..26fdb806 100644
--- a/skills/last30days/scripts/lib/xquik.py
+++ b/skills/last30days/scripts/lib/xquik.py
@@ -8,11 +8,15 @@ bookmarks). Requires an API key from xquik.com.
from __future__ import annotations
from datetime import datetime
-from typing import Any, Dict, List
+from typing import Any, Dict, List, Optional
from . import http, log
from .relevance import token_overlap_relevance as _compute_relevance
+# Per-process probe cache: (state, reason). state is "unset" until probed, then
+# True (funded/working) | False (auth/payment failure) | None (inconclusive).
+_probe_cache: tuple = ("unset", "")
+
# Depth configurations: number of results to request per query
DEPTH_CONFIG = {
"quick": {"limit": 10, "queries": 1},
@@ -44,6 +48,12 @@ def expand_xquik_queries(topic: str, depth: str) -> List[str]:
List of query strings (1 for quick, 2 for default, 3 for deep).
"""
core = _extract_core_subject(topic)
+ # Anti-bare-generic guard (#607): never let the core collapse to a single
+ # bare token when the topic carries more — a lone generic word floods X with
+ # off-topic collisions. Fall back to the full multi-word topic as the anchor.
+ topic_clean = topic.strip()
+ if len(core.split()) <= 1 and len(topic_clean.split()) > 1 and core.lower() != topic_clean.lower():
+ core = topic_clean
queries = [core]
# Add original topic if meaningfully different
@@ -90,48 +100,209 @@ def search_xquik(
seen_ids: set[str] = set()
for query_text in queries:
- try:
- url = f"{_BASE_URL}/x/tweets/search"
- # Build query with date filter
- q = f"{query_text} since:{from_date} until:{to_date}"
- params = f"q={_url_encode(q)}&queryType=Top&limit={cfg['limit']}"
- full_url = f"{url}?{params}"
-
- _log(f"Searching: {query_text}")
- response = http.get(
- full_url,
- headers={"X-Api-Key": token},
- timeout=30,
- retries=2,
- )
-
- tweets = response.get("tweets", [])
- if not isinstance(tweets, list):
- continue
-
- for i, tweet in enumerate(tweets):
- if not isinstance(tweet, dict):
- continue
- tweet_id = str(tweet.get("id", ""))
- if tweet_id in seen_ids:
- continue
- seen_ids.add(tweet_id)
-
- item = _parse_tweet(tweet, i + len(all_items), query_text)
- if item:
- all_items.append(item)
-
- except http.HTTPError as exc:
- status = getattr(exc, "status_code", None)
- if status in (401, 403):
- return {"items": [], "error": f"Xquik auth failed ({status})"}
- _log(f"HTTP error for query '{query_text}': {exc}")
- except Exception as exc:
- _log(f"Error for query '{query_text}': {exc}")
+ q = f"{query_text} since:{from_date} until:{to_date}"
+ items, auth_error = _execute_search(
+ q, cfg["limit"], token,
+ label=query_text, id_prefix="XQ",
+ seen_ids=seen_ids, relevance_query=query_text,
+ index_offset=len(all_items),
+ )
+ if auth_error:
+ # Auth/payment failure is fatal for the whole source (e.g. 401/403,
+ # and 402-unpaid surfaced via U5 diagnose) — return it so the caller
+ # settles honestly instead of silently empty.
+ return {"items": [], "error": auth_error}
+ all_items.extend(items)
return {"items": all_items}
+def _execute_search(
+ q: str,
+ limit: int,
+ token: str,
+ *,
+ label: str,
+ id_prefix: str,
+ seen_ids: set[str],
+ relevance_query: str,
+ index_offset: int = 0,
+) -> tuple[List[Dict[str, Any]], str | None]:
+ """Run one Xquik search call and parse its tweets.
+
+ Returns ``(items, auth_error)``. ``auth_error`` is a non-empty string only
+ on a fatal auth/payment failure (401/403); transient/HTTP errors log and
+ return ``([], None)`` so one bad lane never discards another's results.
+ ``relevance_query`` (the topic) is what items are scored against — for the
+ handle lanes that differs from the search query (``from:handle``).
+ ``index_offset`` keeps item ids unique across multiple calls that share an
+ accumulator (multi-query topic search, per-handle lanes).
+ """
+ full_url = f"{_BASE_URL}/x/tweets/search?q={_url_encode(q)}&queryType=Top&limit={limit}"
+ _log(f"Searching: {label}")
+ try:
+ response = http.get(full_url, headers={"X-Api-Key": token}, timeout=30, retries=2)
+ except http.HTTPError as exc:
+ status = getattr(exc, "status_code", None)
+ if status == 402:
+ # Unpaid key — fatal for the source, and surfaced on the real search
+ # path (not just --diagnose) so a live run reports it instead of
+ # settling silently empty.
+ return [], "Xquik key unpaid (402)"
+ if status in (401, 403):
+ return [], f"Xquik auth failed ({status})"
+ _log(f"HTTP error for '{label}': {exc}")
+ return [], None
+ except Exception as exc:
+ _log(f"Error for '{label}': {exc}")
+ return [], None
+
+ tweets = response.get("tweets", [])
+ if not isinstance(tweets, list):
+ return [], None
+ items: List[Dict[str, Any]] = []
+ for tweet in tweets:
+ if not isinstance(tweet, dict):
+ continue
+ tweet_id = str(tweet.get("id", ""))
+ if tweet_id in seen_ids:
+ continue
+ seen_ids.add(tweet_id)
+ item = _parse_tweet(tweet, index_offset + len(items), relevance_query, id_prefix=id_prefix)
+ if item:
+ items.append(item)
+ return items, None
+
+
+def _is_own(url: str, handle: str) -> bool:
+ """True when a tweet URL is authored by ``handle`` (their own post).
+
+ Used by the ABOUT lane to drop the subject's own tweets so only mentions
+ *by others* remain. Handles both x.com and twitter.com permalinks.
+ """
+ u = (url or "").lower()
+ h = handle.lower().lstrip("@").strip()
+ return bool(h) and (f"x.com/{h}/status" in u or f"twitter.com/{h}/status" in u)
+
+
+def search_handles(
+ handles: List[str],
+ topic: str,
+ from_date: str,
+ to_date: str,
+ *,
+ count_per: int = 8,
+ token: str = "",
+) -> List[Dict[str, Any]]:
+ """FROM lane: tweets authored BY each handle (their own timeline).
+
+ The topic is NOT AND'd into the query (that was the from:-AND bug, #610) —
+ we pull the raw timeline and use ``topic`` for relevance ranking only.
+ Returns a flat list of item dicts (mirrors ``bird_x.search_handles``).
+ """
+ if not token or not handles:
+ return []
+ items: List[Dict[str, Any]] = []
+ seen_ids: set[str] = set()
+ for raw in handles:
+ handle = str(raw).lstrip("@").strip()
+ if not handle:
+ continue
+ q = f"from:{handle} since:{from_date} until:{to_date}"
+ got, auth_error = _execute_search(
+ q, count_per, token,
+ label=f"from:{handle}", id_prefix="XF",
+ seen_ids=seen_ids, relevance_query=topic,
+ index_offset=len(items),
+ )
+ if auth_error:
+ break # fatal auth/payment failure — stop, keep what we have
+ items.extend(got)
+ return items
+
+
+def search_mentions(
+ handles: List[str],
+ from_date: str,
+ to_date: str,
+ *,
+ topic: str = "",
+ count_per: int = 5,
+ token: str = "",
+) -> List[Dict[str, Any]]:
+ """ABOUT lane: tweets mentioning each handle, authored by OTHERS.
+
+ Queries ``@handle`` then drops the handle's own tweets (``_is_own``) so only
+ third-party mentions remain. Returns a flat list of item dicts.
+ """
+ if not token or not handles:
+ return []
+ items: List[Dict[str, Any]] = []
+ seen_ids: set[str] = set()
+ for raw in handles:
+ handle = str(raw).lstrip("@").strip()
+ if not handle:
+ continue
+ q = f"@{handle} since:{from_date} until:{to_date}"
+ got, auth_error = _execute_search(
+ q, count_per, token,
+ label=f"@{handle}", id_prefix="XA",
+ seen_ids=seen_ids, relevance_query=topic,
+ index_offset=len(items),
+ )
+ if auth_error:
+ break
+ items.extend(it for it in got if not _is_own(it.get("url", ""), handle))
+ return items
+
+
+def probe_works(token: str, timeout: int = 8) -> Optional[bool]:
+ """Cheap runtime check that the xquik key actually returns data.
+
+ Mirrors ``bird_x.probe_works`` for the key-based X path so ``--diagnose``
+ reflects reality instead of static key presence. Returns True
+ (funded/working), False (a clear auth/payment failure — 401/403, or 402
+ when the key is configured but unpaid), or None (inconclusive: timeout /
+ transient HTTP) so callers fail open.
+ The human-readable reason is available via ``probe_reason()``. Cached per
+ process so repeated diagnose calls don't re-probe.
+ """
+ global _probe_cache
+ if _probe_cache[0] != "unset":
+ return _probe_cache[0]
+ if not token:
+ _probe_cache = (False, "no XQUIK_API_KEY configured")
+ return False
+ from datetime import timedelta, timezone
+ since = (datetime.now(timezone.utc) - timedelta(days=30)).strftime("%Y-%m-%d")
+ # @x (the platform's own account) posts frequently, so a no-error response
+ # means the key works even if this particular window is quiet.
+ q = f"from:x since:{since}"
+ full_url = f"{_BASE_URL}/x/tweets/search?q={_url_encode(q)}&queryType=Top&limit=1"
+ try:
+ http.get(full_url, headers={"X-Api-Key": token}, timeout=timeout, retries=0)
+ except http.HTTPError as exc:
+ status = getattr(exc, "status_code", None)
+ if status == 402:
+ _probe_cache = (False, "xquik key unpaid (402)")
+ elif status in (401, 403):
+ _probe_cache = (False, f"xquik auth failed ({status})")
+ else:
+ # 5xx / unexpected status — inconclusive, don't report a false-down.
+ _probe_cache = (None, f"xquik probe inconclusive ({status})")
+ return _probe_cache[0]
+ except Exception as exc:
+ _probe_cache = (None, f"xquik probe inconclusive ({type(exc).__name__})")
+ return None
+ _probe_cache = (True, "ok")
+ return True
+
+
+def probe_reason() -> str:
+ """Human-readable reason for the last ``probe_works`` result (or '')."""
+ return _probe_cache[1]
+
+
def search_and_enrich(
topic: str,
from_date: str,
@@ -160,7 +331,7 @@ def parse_xquik_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
def _parse_tweet(
- tweet: Dict[str, Any], index: int, query: str
+ tweet: Dict[str, Any], index: int, query: str, id_prefix: str = "XQ"
) -> Dict[str, Any] | None:
"""Parse a single tweet from the API response into the standard item format."""
author = tweet.get("author") or {}
@@ -189,6 +360,11 @@ def _parse_tweet(
text = str(tweet.get("text", "")).strip()[:500]
+ # Leading-run @mentions = who the post is directed at (reply target). Shared
+ # parser with bird so the first-party interaction signal fires for xquik too.
+ from .query import leading_mentions
+ mentioned_handles = leading_mentions(text)
+
# Build engagement dict with full metrics
engagement = {
"likes": _safe_int(tweet.get("likeCount")),
@@ -200,12 +376,13 @@ def _parse_tweet(
}
return {
- "id": f"XQ{index + 1}",
+ "id": f"{id_prefix}{index + 1}",
"text": text,
"url": url,
"author_handle": username,
"date": date,
"engagement": engagement,
+ "mentioned_handles": mentioned_handles,
"relevance": _compute_relevance(query, text) if query else 0.7,
"why_relevant": "",
}
diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.py
index 0afe66aa..9f55e638 100644
--- a/tests/test_pipeline_v3.py
+++ b/tests/test_pipeline_v3.py
@@ -397,6 +397,62 @@ def _make_source_item(source, item_id, url, author=None, body="", container=None
)
+class TestXBackendChainAndFailover(unittest.TestCase):
+ """One X source, an ordered backend chain with failover; never parallel."""
+
+ @patch("lib.xurl_x.is_available", return_value=False)
+ def test_chain_orders_by_priority(self, _xurl):
+ from lib import env
+ chain = env.x_backend_chain({"XAI_API_KEY": "k", "XQUIK_API_KEY": "q"})
+ self.assertEqual(["xai", "xquik"], chain) # xai primary, xquik backup
+
+ @patch("lib.xurl_x.is_available", return_value=False)
+ def test_pin_forces_single_backend(self, _xurl):
+ from lib import env
+ chain = env.x_backend_chain(
+ {"XAI_API_KEY": "k", "XQUIK_API_KEY": "q", "LAST30DAYS_X_BACKEND": "xquik"}
+ )
+ self.assertEqual(["xquik"], chain) # pin = no failover
+
+ @patch("lib.xurl_x.is_available", return_value=False)
+ def test_chain_empty_when_nothing_configured(self, _xurl):
+ from lib import env
+ self.assertEqual([], env.x_backend_chain({}))
+
+ @patch("lib.env.x_backend_chain", return_value=["bird", "xquik"])
+ def test_failover_to_next_backend_on_empty(self, _chain):
+ sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
+
+ def fake_fetch(backend, *a, **k):
+ if backend == "xquik":
+ return ([{"id": "XQ1", "url": "https://x.com/a/status/1"}], "")
+ return ([], "") # bird returns nothing
+
+ with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
+ items, _ = pipeline._retrieve_stream(
+ topic="q", subquery=sq, source="x", config={}, depth="default",
+ date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
+ )
+ self.assertEqual(1, len(items))
+ self.assertEqual("XQ1", items[0]["id"])
+
+ @patch("lib.env.x_backend_chain", return_value=["xquik"])
+ def test_sole_backend_error_raises_honestly(self, _chain):
+ sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
+ with patch("lib.pipeline._fetch_x_backend", return_value=([], "Xquik key unpaid (402)")):
+ with self.assertRaises(RuntimeError):
+ pipeline._retrieve_stream(
+ topic="q", subquery=sq, source="x", config={}, depth="default",
+ date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
+ )
+
+ def test_xquik_is_not_a_separate_source(self):
+ # xquik registers only as a backend of "x", never its own source.
+ avail = pipeline.available_sources({"XQUIK_API_KEY": "k"})
+ self.assertIn("x", avail)
+ self.assertNotIn("xquik", avail)
+
+
class TestSupplementalSearches(unittest.TestCase):
"""R1: Phase 2 entity drilling should be wired into the pipeline."""
@@ -454,6 +510,91 @@ class TestSupplementalSearches(unittest.TestCase):
x_urls = {item.url for item in bundle.items_by_source.get("x", [])}
self.assertIn("https://x.com/analyst1/status/999", x_urls)
+ @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."""
+ anchored = schema.SubQuery(
+ label="primary", search_query="kevin rose digg founder",
+ ranking_query="What has Kevin Rose, founder of Digg, been doing?",
+ sources=["x"],
+ )
+ pipeline._retrieve_stream(
+ topic="kevin rose digg founder", subquery=anchored, source="x",
+ config={"XQUIK_API_KEY": "k"}, depth="default",
+ date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None),
+ mock=False, raw_topic="kevin rose",
+ )
+ mock_search.assert_called_once()
+ self.assertEqual("kevin rose digg founder", mock_search.call_args[0][0])
+
+ @patch("lib.env.get_xquik_token", return_value="k")
+ @patch("lib.env.x_backend_chain", return_value=["xquik"])
+ @patch("lib.xquik.search_mentions", return_value=[])
+ @patch("lib.xquik.search_handles")
+ @patch("lib.entity_extract.extract_entities")
+ def test_handle_lanes_route_to_xquik_when_primary(
+ self, mock_extract, mock_xq_handles, mock_xq_mentions, *_patches
+ ):
+ """When xquik is the primary X backend, the FROM/ABOUT handle lanes run
+ via xquik and items land under the single 'x' slug."""
+ mock_extract.return_value = {"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}
+ mock_xq_handles.return_value = [{
+ "id": "XF1", "text": "from analyst1", "url": "https://x.com/analyst1/status/777",
+ "author_handle": "analyst1", "date": "2026-03-15",
+ "engagement": {"likes": 30}, "relevance": 0.8, "why_relevant": "",
+ }]
+
+ bundle = schema.RetrievalBundle()
+ bundle.items_by_source["x"] = [
+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="tweet about AI"),
+ ]
+
+ pipeline._run_supplemental_searches(
+ topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},
+ depth="default", date_range=("2026-02-15", "2026-03-17"),
+ runtime=_make_runtime(None), mock=False,
+ rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
+ )
+
+ mock_xq_handles.assert_called_once()
+ x_urls = {item.url for item in bundle.items_by_source.get("x", [])}
+ self.assertIn("https://x.com/analyst1/status/777", x_urls)
+ # There is no separate 'xquik' source — everything is under 'x'.
+ self.assertNotIn("xquik", bundle.items_by_source)
+
+ @patch("lib.env.get_xquik_token", return_value="k")
+ @patch("lib.env.x_backend_chain", return_value=["xai", "xquik"])
+ @patch("lib.xquik.search_mentions", return_value=[])
+ @patch("lib.xquik.search_handles")
+ @patch("lib.entity_extract.extract_entities")
+ def test_handle_lanes_use_xquik_when_xai_is_primary(
+ self, mock_extract, mock_xq_handles, *_patches
+ ):
+ """When xAI is the topic primary but xquik is in the chain, the
+ supplemental handle lanes still run via xquik (first handle-capable
+ backend) rather than being skipped."""
+ mock_extract.return_value = {"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}
+ mock_xq_handles.return_value = [{
+ "id": "XF1", "text": "from analyst1", "url": "https://x.com/analyst1/status/888",
+ "author_handle": "analyst1", "date": "2026-03-15",
+ "engagement": {"likes": 5}, "relevance": 0.8, "why_relevant": "",
+ }]
+ bundle = schema.RetrievalBundle()
+ bundle.items_by_source["x"] = [
+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="tweet"),
+ ]
+ pipeline._run_supplemental_searches(
+ topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},
+ depth="default", date_range=("2026-02-15", "2026-03-17"),
+ runtime=_make_runtime("xai"), mock=False,
+ rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
+ )
+ mock_xq_handles.assert_called_once()
+ x_urls = {item.url for item in bundle.items_by_source.get("x", [])}
+ self.assertIn("https://x.com/analyst1/status/888", x_urls)
+
@patch("lib.bird_x.search_handles")
@patch("lib.entity_extract.extract_entities")
def test_supplemental_items_deduplicated_by_url(self, mock_extract, mock_handles):
diff --git a/tests/test_xquik.py b/tests/test_xquik.py
index 149641fc..f08fab7f 100644
--- a/tests/test_xquik.py
+++ b/tests/test_xquik.py
@@ -239,6 +239,16 @@ class TestSearchXquik(unittest.TestCase):
self.assertEqual(result["items"], [])
self.assertIn("auth failed", result.get("error", ""))
+ @patch("lib.xquik.http.get")
+ def test_unpaid_402_surfaces_error_on_real_path(self, mock_get):
+ # An unpaid key (402) must surface an error on the normal search path,
+ # not settle silently empty — diagnose is opt-in.
+ from lib import http as http_mod
+ mock_get.side_effect = http_mod.HTTPError("Payment Required", status_code=402)
+ result = search_xquik("test", "2026-01-01", "2026-03-01", token="unpaid-key")
+ self.assertEqual(result["items"], [])
+ self.assertIn("unpaid", result.get("error", "").lower())
+
@patch("lib.xquik.http.get")
def test_empty_tweets_list(self, mock_get):
mock_get.return_value = {"tweets": []}
@@ -266,5 +276,212 @@ class TestDepthConfig(unittest.TestCase):
def test_deep_has_most_queries(self):
self.assertGreater(DEPTH_CONFIG["deep"]["queries"], DEPTH_CONFIG["quick"]["queries"])
+class TestIsOwn(unittest.TestCase):
+ def test_own_tweet_detected(self):
+ from lib.xquik import _is_own
+ self.assertTrue(_is_own("https://x.com/elonmusk/status/123", "elonmusk"))
+ self.assertTrue(_is_own("https://twitter.com/elonmusk/status/123", "@elonmusk"))
+
+ def test_other_author_not_own(self):
+ from lib.xquik import _is_own
+ self.assertFalse(_is_own("https://x.com/someoneelse/status/123", "elonmusk"))
+
+ def test_empty_handle_or_url(self):
+ from lib.xquik import _is_own
+ self.assertFalse(_is_own("", "elonmusk"))
+ self.assertFalse(_is_own("https://x.com/a/status/1", ""))
+
+
+class TestFromLane(unittest.TestCase):
+ def _resp(self, username, tid="1"):
+ return {"tweets": [{
+ "id": tid, "text": "anything", "createdAt": "2026-06-15T12:00:00Z",
+ "likeCount": 10, "author": {"username": username},
+ }]}
+
+ def test_from_query_shape_and_no_topic_anded(self):
+ from lib import xquik
+ with patch("lib.xquik.http.get", return_value=self._resp("elonmusk")) as m:
+ items = xquik.search_handles(["@elonmusk"], "Grok 4", "2026-05-19", "2026-06-18",
+ count_per=8, token="k")
+ url = m.call_args[0][0]
+ self.assertIn("from%3Aelonmusk", url) # from:elonmusk url-encoded
+ self.assertIn("since%3A2026-05-19", url)
+ self.assertNotIn("Grok", url) # topic must NOT be AND'd into query
+ self.assertEqual(1, len(items))
+ self.assertEqual("XF1", items[0]["id"]) # FROM-lane id prefix
+
+ def test_no_token_or_no_handles_returns_empty(self):
+ from lib import xquik
+ self.assertEqual([], xquik.search_handles(["@x"], "t", "a", "b", token=""))
+ self.assertEqual([], xquik.search_handles([], "t", "a", "b", token="k"))
+
+ def test_item_ids_unique_across_handles(self):
+ # Different tweets across two handles must not collide on item id.
+ from lib import xquik
+ responses = [
+ {"tweets": [{"id": "1", "text": "a", "createdAt": "2026-06-15T12:00:00Z",
+ "author": {"username": "h1"}}]},
+ {"tweets": [{"id": "2", "text": "b", "createdAt": "2026-06-15T12:00:00Z",
+ "author": {"username": "h2"}}]},
+ ]
+ with patch("lib.xquik.http.get", side_effect=responses):
+ items = xquik.search_handles(["h1", "h2"], "topic", "2026-05-19", "2026-06-18", token="k")
+ ids = [it["id"] for it in items]
+ self.assertEqual(len(ids), len(set(ids)))
+
+
+class TestAboutLane(unittest.TestCase):
+ def test_mentions_drop_own_tweets(self):
+ from lib import xquik
+ resp = {"tweets": [
+ {"id": "1", "text": "@elonmusk nice", "createdAt": "2026-06-15T12:00:00Z",
+ "author": {"username": "fan"}},
+ {"id": "2", "text": "my own post", "createdAt": "2026-06-15T12:00:00Z",
+ "author": {"username": "elonmusk"}},
+ ]}
+ with patch("lib.xquik.http.get", return_value=resp) as m:
+ items = xquik.search_mentions(["elonmusk"], "2026-05-19", "2026-06-18",
+ topic="Grok 4", count_per=5, token="k")
+ url = m.call_args[0][0]
+ self.assertIn("%40elonmusk", url) # @elonmusk url-encoded
+ authors = {it["author_handle"] for it in items}
+ self.assertIn("fan", authors)
+ self.assertNotIn("elonmusk", authors) # own tweet dropped
+
+
+class TestExpandGuard(unittest.TestCase):
+ @patch("lib.xquik._extract_core_subject", return_value="news")
+ def test_bare_generic_core_falls_back_to_topic(self, _m):
+ # #607: a single bare generic core must not be the query for a
+ # multi-word topic — fall back to the full topic.
+ qs = expand_xquik_queries("Grok 4 news", "quick")
+ self.assertEqual(["Grok 4 news"], qs)
+
+ @patch("lib.xquik._extract_core_subject", return_value="Grok 4")
+ def test_multiword_core_kept(self, _m):
+ qs = expand_xquik_queries("Grok 4 latest", "quick")
+ self.assertEqual(["Grok 4"], qs)
+
+
+class TestProbeWorks(unittest.TestCase):
+ """U5: honest diagnose probe — tri-state, surfaces the unpaid (402) case."""
+
+ def setUp(self):
+ import lib.xquik as xq
+ xq._probe_cache = ("unset", "")
+
+ @patch("lib.xquik.http.get")
+ def test_funded_key_works(self, mock_get):
+ from lib import xquik
+ mock_get.return_value = {"tweets": [{"id": "1"}]}
+ self.assertIs(True, xquik.probe_works("k"))
+ self.assertEqual("ok", xquik.probe_reason())
+
+ @patch("lib.xquik.http.get")
+ def test_unpaid_402_is_false_with_reason(self, mock_get):
+ from lib import xquik, http as http_mod
+ mock_get.side_effect = http_mod.HTTPError("Payment Required", status_code=402)
+ self.assertIs(False, xquik.probe_works("k"))
+ self.assertIn("unpaid", xquik.probe_reason())
+
+ @patch("lib.xquik.http.get")
+ def test_auth_401_is_false(self, mock_get):
+ from lib import xquik, http as http_mod
+ mock_get.side_effect = http_mod.HTTPError("Unauthorized", status_code=401)
+ self.assertIs(False, xquik.probe_works("k"))
+ self.assertIn("auth failed", xquik.probe_reason())
+
+ @patch("lib.xquik.http.get")
+ def test_timeout_is_inconclusive_fail_open(self, mock_get):
+ from lib import xquik
+ mock_get.side_effect = TimeoutError("timed out")
+ self.assertIsNone(xquik.probe_works("k"))
+
+ def test_no_token_is_false(self):
+ from lib import xquik
+ self.assertIs(False, xquik.probe_works(""))
+ self.assertIn("no XQUIK_API_KEY", xquik.probe_reason())
+
+ @patch("lib.xquik.http.get")
+ def test_result_is_cached(self, mock_get):
+ from lib import xquik
+ mock_get.return_value = {"tweets": [{"id": "1"}]}
+ xquik.probe_works("k")
+ xquik.probe_works("k")
+ self.assertEqual(1, mock_get.call_count)
+
+
+class TestDiagnoseSurfacesXquik(unittest.TestCase):
+ """U5: get_x_source_status reports xquik as the active X source when bird/
+ xAI/xurl are absent, and surfaces the probe reason."""
+
+ def setUp(self):
+ import lib.xquik as xq
+ xq._probe_cache = ("unset", "")
+
+ @patch("lib.xquik.http.get")
+ @patch("lib.xurl_x.is_available", return_value=False)
+ @patch("lib.bird_x.get_bird_status")
+ def test_xquik_is_active_x_source_when_only_key(self, mock_bird, _xurl, mock_get):
+ from lib import env
+ mock_bird.return_value = {"installed": False, "authenticated": False,
+ "username": "", "can_install": False}
+ mock_get.return_value = {"tweets": [{"id": "1"}]}
+ status = env.get_x_source_status({"XQUIK_API_KEY": "k"}, probe=True)
+ self.assertEqual("xquik", status["source"])
+ self.assertTrue(status["xquik_available"])
+ self.assertIs(True, status["xquik_working"])
+
+ @patch("lib.xurl_x.is_available", return_value=False)
+ @patch("lib.bird_x.get_bird_status")
+ def test_unpaid_xquik_not_active_source(self, mock_bird, _xurl):
+ from lib import env, http as http_mod
+ import lib.xquik as xq
+ mock_bird.return_value = {"installed": False, "authenticated": False,
+ "username": "", "can_install": False}
+ with patch("lib.xquik.http.get", side_effect=http_mod.HTTPError("pay", status_code=402)):
+ status = env.get_x_source_status({"XQUIK_API_KEY": "k"}, probe=True)
+ self.assertIsNone(status["source"]) # unpaid key is not a usable X source
+ self.assertIs(False, status["xquik_working"])
+ self.assertIn("unpaid", status["xquik_status"])
+
+
+class TestMentionedHandles(unittest.TestCase):
+ """U3: xquik items carry leading-run @mentions so the first-party
+ interaction signal fires (shared parser with bird)."""
+
+ def _tweet(self, text):
+ return {
+ "id": "1", "text": text, "createdAt": "2026-06-15T12:00:00Z",
+ "author": {"username": "subject"},
+ }
+
+ def test_leading_mentions_captured(self):
+ item = _parse_tweet(self._tweet("@jack @pmarca thoughts on this"), 0, "topic")
+ self.assertEqual(["jack", "pmarca"], item["mentioned_handles"])
+
+ def test_midbody_mention_ignored(self):
+ item = _parse_tweet(self._tweet("I think @jack is right"), 0, "topic")
+ self.assertEqual([], item["mentioned_handles"])
+
+ def test_no_mentions(self):
+ item = _parse_tweet(self._tweet("Grok 4 just shipped"), 0, "topic")
+ self.assertEqual([], item["mentioned_handles"])
+
+
+class TestNormalizePropagatesMentions(unittest.TestCase):
+ """U3: _normalize_x carries xquik mentioned_handles into metadata so rerank
+ can read them."""
+
+ def test_mentioned_handles_reach_metadata(self):
+ from lib import normalize
+ item = _parse_tweet(
+ {"id": "1", "text": "@jack hi", "createdAt": "2026-06-15T12:00:00Z",
+ "author": {"username": "subject"}}, 0, "topic")
+ normalized = normalize.normalize_source_items("xquik", [item], "2026-05-19", "2026-06-18")
+ self.assertEqual(["jack"], normalized[0].metadata.get("mentioned_handles"))
+
+
if __name__ == "__main__":
unittest.main()