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
fix(x): show xAI key and model guidance for xAI failures (#1238)
Tivonsicoce0e7afa9bec
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex efe6b712..3d7a96c6 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -190,6 +190,8 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \**X backend priority (bird first).** The default X backend chain is bird (browser cookies) → xai (API key) → xurl (OAuth2 CLI) → xquik (API key). Cookies beat `XAI_API_KEY` when both are present. A leftover grok login never steals the X lane; see below. `xapi` (the official X API v2 with `X_BEARER_TOKEN`) is opt-in on these hosts (`LAST30DAYS_X_BACKEND=xapi`), so an ambient bearer never spends X API credits when the free path comes back empty. **Grok Bot exception.** On a Grok Bot host (`LAST30DAYS_HOST=grok-bot`) the unpinned chain is the official chain instead: xapi (`X_BEARER_TOKEN`) → xai (`XAI_API_KEY`) → xurl (the X API through X's CLI). When the bot fetched X itself (its built-in X tools, or the X connector), those results come first and the chain is not called at all; see [Grok Bot](#grok-bot) under Per-client patterns.+**xAI backend errors.** For an `xai:` authentication or model failure, check `XAI_API_KEY` and its chat/model permissions in console.x.ai. Set `LAST30DAYS_X_MODEL` to a model available to that key if the configured model is unavailable. For HTTP 402, check xAI billing and credits; for HTTP 429, wait for the xAI rate limit to reset; for a timeout, retry later. Logging into x.com or replacing `X_BEARER_TOKEN` does not repair the xAI API backend.+**Grok CLI (opt-in backup).** Install the Grok CLI (`curl -fsSL https://x.ai/cli/install.sh | bash`) and run `grok login`, and X can work with no X account, no browser cookies, and no `XAI_API_KEY`. However, grok is **opt-in only**: a leftover `~/.grok/auth.json` must never steal the X lane. Pin `LAST30DAYS_X_BACKEND=grok` to enable it. It is not "free" in the way the cookie path is: calls draw on your Grok plan, and depth costs several calls per run because the underlying tool caps each search at 10 posts. Results are validated before use — every returned post's ID is decoded to confirm it falls inside the requested date range, because the retrieval is performed by a language model and can otherwise return confident, well-formed posts that were never searched for.The Grok backend currently supports only `grok 1.0.46 (2765805b9442)`, optionally followed by `[stable]`, as reported by `grok --version`. Research runs with a generated agent profile that removes local tools, skill discovery, and inherited MCP access while retaining hosted X search. Other builds fail before credentials are staged or research starts; each build needs a tool-boundary audit. If your CLI build is unsupported, remove the `LAST30DAYS_X_BACKEND=grok` pin to use the normal X backend chain, or select another configured X backend. Updating Grok alone does not establish compatibility.diff --git a/changelog.d/1186.fixed.md b/changelog.d/1186.fixed.mdnew file mode 100644index 00000000..8a15f759--- /dev/null+++ b/changelog.d/1186.fixed.md@@ -0,0 +1 @@+X search failures attributed to the xAI backend now point to its credentials, billing, rate limit, or timeout remedy instead of browser login or an unrelated X API bearer.diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 5999438d..9616520f 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -3168,6 +3168,38 @@ def main() -> int:return _main(parser, args, extra_argv)+def _quality_research_results(report, diag, yt_fetch_stats):+ youtube_items = report.items_by_source.get("youtube") or []+ instagram_items = report.items_by_source.get("instagram") or []+ x_outcome = report.source_status.get("x")+ x_degraded_error = None+ if (+ report.items_by_source.get("x")+ and x_outcome is not None+ and x_outcome.detail+ and x_outcome.detail.startswith("X served via ")+ and " after xai:" in x_outcome.detail+ ):+ x_degraded_error = x_outcome.detail+ return {+ "active_sources": diag.get("available_sources") or [],+ "youtube_videos_count": len(youtube_items),+ "youtube_transcripts_count": sum(+ 1 for it in youtube_items+ if (it.metadata.get("transcript_highlights") or it.metadata.get("transcript_snippet"))+ ),+ "youtube_error": report.errors_by_source.get("youtube"),+ "x_error": report.errors_by_source.get("x"),+ "x_degraded_error": x_degraded_error,+ "youtube_captions_disabled_count": sum(+ 1 for it in youtube_items if it.metadata.get("captions_disabled")+ ),+ "youtube_transcript_fetch_attempts": yt_fetch_stats["attempts"],+ "youtube_transcript_fetch_failures": yt_fetch_stats["failures"],+ "instagram_items_count": len(instagram_items),+ }++def _main(parser: argparse.ArgumentParser,args: argparse.Namespace,@@ -4280,40 +4312,9 @@ def _main(try:from lib import quality_nudgefrom lib import youtube_yt as _youtube_yt- # Populate transcript-fetch ratio so quality_nudge can detect the- # degraded-YouTube failure mode (videos returned but transcripts- # silently failed - typically a stale yt-dlp binary).- youtube_items = report.items_by_source.get("youtube") or []- _yt_fetch_stats = _youtube_yt.get_transcript_fetch_stats()- instagram_items = report.items_by_source.get("instagram") or []- research_results = {- "active_sources": diag.get("available_sources") or [],- "youtube_videos_count": len(youtube_items),- "youtube_transcripts_count": sum(- 1 for it in youtube_items- if (it.metadata.get("transcript_highlights") or it.metadata.get("transcript_snippet"))- ),- "youtube_error": report.errors_by_source.get("youtube"),- "x_error": report.errors_by_source.get("x"),- # Captions-disabled videos can never produce a transcript regardless- # of yt-dlp version; subtract them from the degraded-ratio- # denominator so a single uploader-disabled video does not trip the- # "stale yt-dlp" nudge.- "youtube_captions_disabled_count": sum(- 1 for it in youtube_items if it.metadata.get("captions_disabled")- ),- # Actual yt-dlp fetch outcomes for this run. The counts above are- # computed from post-pruning items, so they can't tell "fetches- # failed (stale binary)" from "fetches succeeded but the videos- # were pruned downstream"; the latter was producing false- # stale-yt-dlp nudges (#531).- "youtube_transcript_fetch_attempts": _yt_fetch_stats["attempts"],- "youtube_transcript_fetch_failures": _yt_fetch_stats["failures"],- # Track Instagram returned-zero-items so quality_nudge can detect- # the silent-failure case (SC configured but the v2 reels endpoint- # 500'd through both the original query and the hashtag retry).- "instagram_items_count": len(instagram_items),- }+ research_results = _quality_research_results(+ report, diag, _youtube_yt.get_transcript_fetch_stats()+ )quality = quality_nudge.compute_quality_score(config, research_results)if quality.get("nudge_text"):sys.stderr.write(f"\n{quality['nudge_text']}\n")diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 6efa6fc6..b6fc6b28 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -679,7 +679,7 @@ def _fetch_discovery_source(if _research_stopped(config) or time.monotonic() >= chain_deadline:last_error = f"{last_error}; X chain budget exhausted (timed out or cancelled)".strip("; ")break- items, error = _fetch_x_backend(+ items, error, _ = _attempt_x_backend(backend, query, from_date, to_date, depth, config,warnings=x_warnings, deadline=chain_deadline,)@@ -2793,14 +2793,18 @@ def run()if isinstance(artifact, dict) and artifact.get("_source_outcome_detail"):artifact = dict(artifact)+ detail_rate_limited = _detail_rate_limits_source(source, artifact)lane_state = artifact.pop("_source_outcome_detail_state", None)+ detail_note = artifact.pop("_source_outcome_detail")bundle.record_detail(- source, artifact.pop("_source_outcome_detail"), state=lane_state+ source, detail_note, state=lane_state)- if lane_state == health.RATE_LIMITED:+ if detail_rate_limited:# Do not re-fan-out against a host still inside its window.with rate_limit_lock:rate_limited_sources.add(source)+ if isinstance(artifact, dict):+ artifact.pop("_x_backup_not_rate_limited", None)normalized = _normalize_score_dedupe(source, raw_items, from_date, to_date,freshness_mode=plan.freshness_mode,@@ -4916,6 +4920,33 @@ def _fetch_x_backend(backend, query, from_date, to_date, depth, config, warningsreturn items, (err or "")+def _attempt_x_backend(backend, query, from_date, to_date, depth, config, warnings=None, deadline=None):+ try:+ items, error = _fetch_x_backend(+ backend, query, from_date, to_date, depth, config,+ warnings=warnings, deadline=deadline,+ )+ except http.HTTPError as exc:+ detail = str(exc)+ cause = (+ f"HTTP {exc.status_code}"+ if exc.status_code is not None+ else {+ health.AUTH_FAILED: "authentication failed",+ health.PAYMENT_REQUIRED: "payment required",+ health.RATE_LIMITED: "rate limited",+ health.TIMEOUT: "timed out",+ health.UNREACHABLE: "connection error",+ health.SCHEMA_DRIFT: "invalid JSON",+ }.get(exc.outcome_state)+ )+ if cause and cause.lower() not in detail.lower():+ detail = f"{cause}: {detail}"+ return [], detail, exc.outcome_state+ detail = str(error or "")+ return items, detail, http.classify_failure(message=detail) if detail else None++def _reddit_post_key(item: dict) -> str:"""Stable per-thread dedupe key (base36 post id from the url/permalink)."""url = item.get("url") or item.get("permalink") or ""@@ -4939,6 +4970,12 @@ def _merge_reddit_items(free: list[dict], sc: list[dict]) -> list[dict]:return merged+def _detail_rate_limits_source(source: str, artifact: dict) -> bool:+ if artifact.get("_source_outcome_detail_state") != health.RATE_LIMITED:+ return False+ return source != "x" or not bool(artifact.get("_x_backup_not_rate_limited"))++def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:"""Run one stream and retain HTTP failures swallowed by source adapters."""# run_started is passed through but not used here; it goes to _retrieve_stream_impl@@ -4974,7 +5011,8 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:if matched:replay_artifact = replayed[1] or {}publish_rate_limit((replay_artifact.get("_source_outcome") or {}).get("state"))- publish_rate_limit(replay_artifact.get("_source_outcome_detail_state"))+ if _detail_rate_limits_source(source, replay_artifact):+ publish_rate_limit(health.RATE_LIMITED)return replayed[0], replayed[1]try:with http.capture_failures() as failures, \@@ -5035,7 +5073,8 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:states, key=lambda state: _FAILURE_SPECIFICITY.get(state, 9))publish_rate_limit((artifact.get("_source_outcome") or {}).get("state"))- publish_rate_limit(artifact.get("_source_outcome_detail_state"))+ if _detail_rate_limits_source(source, artifact):+ publish_rate_limit(health.RATE_LIMITED)if module_backed:http.fixture_source_record(fixture_request, [items, artifact])return items, artifact@@ -5393,7 +5432,8 @@ def _retrieve_stream_impl(schema.SKIPPED_UNCONFIGURED,)last_error = ""- chain_errors: list[str] = []+ chain_errors: list[tuple[str, schema.RunOutcomeState]] = []+ last_state = health.ERRORitems = []used_backend = Nonex_warnings: list[str] = []@@ -5402,13 +5442,15 @@ def _retrieve_stream_impl(if _research_stopped(config) or time.monotonic() >= chain_deadline:msg = "X chain budget exhausted (timed out or cancelled)"last_error = f"{last_error}; {msg}".strip("; ") if last_error else msg- chain_errors.append(msg)+ last_state = health.TIMEOUT+ chain_errors.append((msg, last_state))print("[X] chain budget exhausted; skipping remaining backends", file=sys.stderr)break- items, err = _fetch_x_backend(- backend, x_query, from_date, to_date, depth, config, warnings=x_warnings,- deadline=chain_deadline,- )+ with http.tee_failures() as backend_failures:+ items, err, err_state = _attempt_x_backend(+ backend, x_query, from_date, to_date, depth, config, warnings=x_warnings,+ deadline=chain_deadline,+ )if items:if i > 0:# xapi is metered: name the spend when it served as a backup.@@ -5419,35 +5461,50 @@ def _retrieve_stream_impl()# 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),- # preserve that state so user gets re-login guidance.- prior_state = http.classify_failure(message=last_error)+ # Preserve a prior auth failure even when the backup served+ # items. Session backends alone need re-login guidance.+ prior_state = last_state+ backup_rate_limited = err_state == health.RATE_LIMITED or any(+ failure.outcome_state == health.RATE_LIMITED for failure in backend_failures+ )+ detail = f"X served via {backend} after {last_error}"+ if err:+ detail += f"; {backend}: {err}"+ if backup_rate_limited and err_state != health.RATE_LIMITED:+ detail += f"; {backend} also rate-limited"if prior_state == schema.AUTH_FAILED:- # Keep AUTH_FAILED visible so host shows re-login hint- return items, _outcome_artifact(+ repair = (+ "; re-login needed for primary backend"+ if last_error.startswith(("grok:", "bird:")) else ""+ )+ artifact = _outcome_artifact(schema.AUTH_FAILED,- f"X served via {backend} after {last_error}; re-login needed for primary backend",+ f"{detail}{repair}",)+ if backup_rate_limited:+ artifact["_source_outcome_detail"] = f"{backend} also rate-limited"+ artifact["_source_outcome_detail_state"] = health.RATE_LIMITED+ return items, artifact# Prior error was non-auth. Check if *current* backend also# reported an error (e.g., grok returned items + revocation).if err:- current_state = http.classify_failure(message=err)+ current_state = err_stateif current_state == schema.AUTH_FAILED:+ repair = "; re-login needed" if backend in ("grok", "bird") else ""return items, _outcome_artifact(schema.AUTH_FAILED,- f"X served {len(items)} items via {backend} but also errored: {err}; re-login needed",+ f"X served {len(items)} items via {backend} but also errored: {err}{repair}",)- # Non-auth prior error, no current auth error → fallback OK- return items, _outcome_artifact(- health.OK,- f"X served via {backend} after {last_error}",- )+ return items, {+ "_source_outcome_detail": detail,+ "_source_outcome_detail_state": health.RATE_LIMITED if backup_rate_limited else prior_state,+ "_x_backup_not_rate_limited": not backup_rate_limited,+ }if err:# Mixed result: backend returned items BUT also hit an error# (e.g., grok got some posts then auth was revoked mid-fanout).# Surface the error so the user gets re-login guidance.- state = http.classify_failure(message=err)+ state = err_statereturn items, _outcome_artifact(state,f"X returned {len(items)} items but also errored: {err}",@@ -5457,23 +5514,24 @@ def _retrieve_stream_impl(breakif err:last_error = f"{backend}: {err}"- chain_errors.append(last_error)+ last_state = err_state+ chain_errors.append((last_error, last_state))print(f"[X] backend '{backend}' failed ({err}); trying next", file=sys.stderr)if not items and last_error:# A credit-exhaustion failure earlier in the chain is the most# specific outcome (top up, not re-authenticate); a later# backend's generic failure must not mask it.- for candidate in chain_errors:- if http.classify_failure(message=candidate) == health.PAYMENT_REQUIRED:- last_error = candidate+ for candidate, candidate_state in chain_errors:+ if candidate_state == health.PAYMENT_REQUIRED:+ last_error, last_state = candidate, candidate_statebreakstate = (health.TIMEOUTif _research_stopped(config) or time.monotonic() >= chain_deadlineelse bird_x.classify_run_failure(last_error)if last_error.startswith("bird:")- else http.classify_failure(message=last_error)+ else last_state)raise SourceRunError(f"All X backends failed — {last_error}", state)@@ -5502,7 +5560,7 @@ def _retrieve_stream_impl(if _research_stopped(config) or time.monotonic() >= chain_deadline:print("[X] chain budget exhausted; skipping judge retry", file=sys.stderr)else:- retry_items, retry_err = _fetch_x_backend(+ retry_items, retry_err, _ = _attempt_x_backend(used_backend, retry_query, from_date, to_date, depth, config,deadline=chain_deadline,)diff --git a/skills/last30days/scripts/lib/prescriptions.py b/skills/last30days/scripts/lib/prescriptions.pyindex 2a57066f..a5cfaf18 100644--- a/skills/last30days/scripts/lib/prescriptions.py+++ b/skills/last30days/scripts/lib/prescriptions.py@@ -91,6 +91,44 @@ REGISTRY: Dict[Tuple[str, str], Prescription] = dict((fix_cli=SETUP_BROWSER_COOKIES_CLI,anchor="api-keys-env",),+ _entry(+ "x", "xai_error",+ cause="the xAI X search backend failed this run",+ fix_nl=(+ "check XAI_API_KEY and its chat/model permissions in console.x.ai, "+ "confirm LAST30DAYS_X_MODEL names an available model, then re-run"+ ),+ fix_cli="XAI_API_KEY=<your-xai-key> LAST30DAYS_X_MODEL=<available-xai-model>",+ anchor="api-keys-env",+ ),+ _entry(+ "x", "xai_payment_required",+ cause="the xAI X search backend has no available credits",+ fix_nl="check xAI billing and credits in console.x.ai, then re-run",+ fix_cli=f'{ENGINE_CLI} "<topic>" --search x',+ anchor="api-keys-env",+ ),+ _entry(+ "x", "xai_rate_limited",+ cause="the xAI X search backend hit its rate limit",+ fix_nl="wait for the xAI rate limit to reset, then re-run",+ fix_cli=f'{ENGINE_CLI} "<topic>" --search x',+ anchor="api-keys-env",+ ),+ _entry(+ "x", "xai_timeout",+ cause="the xAI X search backend timed out",+ fix_nl="xAI timed out; retry the run or select another configured X backend",+ fix_cli=f'{ENGINE_CLI} "<topic>" --search x',+ anchor="api-keys-env",+ ),+ _entry(+ "x", "xai_unavailable",+ cause="the xAI X search backend failed this run",+ fix_nl="retry xAI later or select another configured X backend",+ fix_cli=f'{ENGINE_CLI} "<topic>" --search x',+ anchor="api-keys-env",+ ),_entry("x", "grok_cli_missing",cause="the Grok CLI is not installed, so the keyless X path is unavailable",diff --git a/skills/last30days/scripts/lib/quality_nudge.py b/skills/last30days/scripts/lib/quality_nudge.pyindex 826da8e1..2796337e 100644--- a/skills/last30days/scripts/lib/quality_nudge.py+++ b/skills/last30days/scripts/lib/quality_nudge.py@@ -63,16 +63,34 @@ def _has_x_credentials(config: dict) -> bool:def _x_error_prescription(config: dict, research_results: dict) -> prescriptions.Prescription:"""The fix for a configured X that errored, routed through the X policy.- On an official-only host a credit-exhaustion error asks for a top-up- (``payment_required``) and every other error asks for a valid bearer or- the connector (``cookies_expired`` maps to ``bearer_invalid`` there);- elsewhere the entry is today's ``cookies_expired``.+ The pipeline stamps the failed backend into ``x_error`` or+ ``x_degraded_error``, sometimes behind a simplified-query retry label.+ Use that runtime provenance before the host policy."""- message = str(research_results.get("x_error") or "")+ message = str(research_results.get("x_error") or research_results.get("x_degraded_error") or "")if message.startswith(x_envelope.DETAIL_NOT_PASSED):# The model declared the X connector lane and passed no envelope:# the fix is the connector, on any host.return prescriptions.for_x(config, "connector_missing")+ backend_error = message.removeprefix("Simplified-query retry failed: ")+ backend_error = backend_error.removeprefix("All X backends failed — ")+ if backend_error.startswith("X served via "):+ served_backend, separator, origin_error = backend_error.removeprefix("X served via ").partition(" after ")+ if separator:+ backend_error = origin_error.split(f"; {served_backend}", 1)[0]+ if backend_error.startswith("xai:"):+ state = http.classify_failure(message=backend_error)+ if state == health.PAYMENT_REQUIRED:+ failure = "xai_payment_required"+ elif state == health.RATE_LIMITED:+ failure = "xai_rate_limited"+ elif state == health.TIMEOUT:+ failure = "xai_timeout"+ elif state == health.AUTH_FAILED or "model" in backend_error.lower():+ failure = "xai_error"+ else:+ failure = "xai_unavailable"+ return prescriptions.for_x(config, failure)failure = "cookies_expired"if env.x_policy(config).hint_namespace == "official":if http.classify_failure(message=message) == health.PAYMENT_REQUIRED:@@ -193,7 +211,8 @@ def compute_quality_score(config: dict, research_results: dict) -> dict:degraded-YouTube detection (transcript-fetch ratio below threshold,or fallback/provider data returned without local yt-dlp).Optional key ``instagram_items_count`` enables silent-failure- detection for the bonus Instagram source.+ detection for the bonus Instagram source. ``x_degraded_error``+ carries a failed xAI lane when another backend served X items.Returns:{@@ -226,6 +245,8 @@ def compute_quality_score(config: dict, research_results: dict) -> dict:)if _is_x_active(config, research_results):core_active.append("x")+ if research_results.get("x_degraded_error"):+ core_degraded.append("x")elif x_configured and research_results.get("x_error"):core_missing.append("x")core_errored.append("x")@@ -270,7 +291,7 @@ def compute_quality_score(config: dict, research_results: dict) -> dict:has_sc = bool(config.get("SCRAPECREATORS_API_KEY"))active_sources = research_results.get("active_sources") or []- x_fix = _x_error_prescription(config, research_results) if "x" in core_errored else None+ x_fix = _x_error_prescription(config, research_results) if "x" in core_errored or "x" in core_degraded else Nonenudge_text = _build_nudge_text(core_missing,core_errored,@@ -350,6 +371,11 @@ def _build_nudge_text(x_fix = prescriptions.get("x", "cookies_expired")free_suggestions.append(f"X/Twitter errored - {x_fix.fix_nl}.")+ if "x" in core_degraded:+ if x_fix is None:+ x_fix = prescriptions.get("x", "cookies_expired")+ free_suggestions.append(f"X/Twitter used a backup - {x_fix.fix_nl}.")+if "youtube" in core_missing:if "youtube" in core_errored:yt_fix = prescriptions.get("youtube", "ytdlp_stale")diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.pyindex 967125e1..87f357a0 100644--- a/tests/test_pipeline_v3.py+++ b/tests/test_pipeline_v3.py@@ -1140,9 +1140,9 @@ class TestMixedResultRevocation(unittest.TestCase):date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,)self.assertEqual(1, len(items))- outcome = artifact.get("_source_outcome", {})- # Non-auth error followed by fallback success is OK- self.assertEqual("ok", outcome.get("state"))+ self.assertNotIn("_source_outcome", artifact)+ self.assertIn("grok: network timeout", artifact["_source_outcome_detail"])+ self.assertEqual(health.TIMEOUT, artifact["_source_outcome_detail_state"])@patch("lib.env.x_backend_chain", return_value=["bird", "grok"])def test_prior_non_auth_then_current_auth_fail_yields_auth_failed(self, _chain):diff --git a/tests/test_quality_nudge.py b/tests/test_quality_nudge.pyindex 5ca2dc4d..ac84bfc0 100644--- a/tests/test_quality_nudge.py+++ b/tests/test_quality_nudge.py@@ -6,6 +6,8 @@ trigger an authentication nudge.ScrapeCreators adds TikTok + Instagram as bonus sources, not core."""+import threading+import pytestfrom unittest.mock import patch@@ -819,3 +821,362 @@ class TestBearerCredential:)assert "top up" in q["nudge_text"].lower()assert "x.com" not in q["nudge_text"].lower()+++class TestXaiErrorRemediation:+ """The selected API backend must not prescribe a browser-cookie login."""++ @pytest.mark.parametrize("host", [None, "grok-bot"])+ @pytest.mark.parametrize("message", [+ "All X backends failed — xai: HTTP 403: Permission denied",+ "xai: HTTP 401: Unauthorized",+ "All X backends failed — xai: HTTP 404: Model not found",+ ])+ def test_runtime_xai_error_points_to_key_and_model_permissions(self, host, message):+ q = _compute(+ config_overrides={"XAI_API_KEY": "dummy-xai-key", "LAST30DAYS_HOST": host},+ result_overrides={"x_error": message},+ ytdlp_installed=True,+ )+ assert "XAI_API_KEY" in q["nudge_text"]+ assert "LAST30DAYS_X_MODEL" in q["nudge_text"]+ assert "console.x.ai" in q["nudge_text"]+ assert "log into x.com" not in q["nudge_text"]+ assert "X_BEARER_TOKEN" not in q["nudge_text"]++ def test_runtime_bird_error_is_not_changed_by_a_fallback_xai_key(self):+ q = _compute(+ config_overrides={"AUTH_TOKEN": "dummy-cookie", "CT0": "dummy-ct0", "XAI_API_KEY": "dummy-xai-key"},+ result_overrides={"x_error": "All X backends failed — bird: expired cookies"},+ ytdlp_installed=True,+ )+ assert "log into x.com" in q["nudge_text"]+ assert "console.x.ai" not in q["nudge_text"]++ @pytest.mark.parametrize("backend,credentials,error,expected,unexpected", [+ ("xai", {"XAI_API_KEY": "dummy-xai-key"}, "HTTP 403: Permission denied", "console.x.ai", "log into x.com"),+ ("bird", {"AUTH_TOKEN": "dummy-cookie", "CT0": "dummy-ct0"}, "expired cookies", "log into x.com", "console.x.ai"),+ ])+ def test_thin_retry_failure_preserves_backend_repair(self, backend, credentials, error, expected, unexpected):+ from lib import bird_x, pipeline, schema++ config = _base_config(**credentials)+ config["LAST30DAYS_X_BACKEND"] = backend+ plan = schema.QueryPlan(+ intent="breaking_news",+ freshness_mode="strict_recent",+ cluster_mode="story",+ raw_topic="OpenClaw",+ subqueries=[schema.SubQuery("primary", "OpenClaw", "Recent OpenClaw news", ["x"])],+ source_weights={"x": 1.0},+ )+ bundle = schema.RetrievalBundle()+ runtime = schema.ProviderRuntime("local", "", "", backend)++ with patch.object(bird_x, "is_bird_installed", return_value=True), \+ patch.object(pipeline, "_fetch_x_backend", return_value=([], error)):+ pipeline._retry_thin_sources(+ topic="OpenClaw",+ bundle=bundle,+ plan=plan,+ config=config,+ depth="default",+ date_range=("2026-09-01", "2026-09-30"),+ runtime=runtime,+ mock=False,+ rate_limited_sources=set(),+ rate_limit_lock=threading.Lock(),+ settings=pipeline.DEPTH_SETTINGS["default"],+ )++ assert bundle.errors_by_source["x"].startswith("Simplified-query retry failed: All X backends failed — ")+ q = _compute(config_overrides=config, result_overrides={"x_error": bundle.errors_by_source["x"]}, ytdlp_installed=True)+ assert expected in q["nudge_text"]+ assert unexpected not in q["nudge_text"]++ @pytest.mark.parametrize("status,message,expected_state,expected_fix", [+ (403, "Forbidden", "auth-failed", "console.x.ai"),+ (402, "Quota blocked", "payment-required", "billing"),+ (429, "Quota blocked", "rate-limited", "rate limit"),+ (None, "Request deadline exceeded", "timeout", "timed out"),+ ])+ def test_raised_xai_error_from_thin_retry_keeps_cause(self, status, message, expected_state, expected_fix):+ from lib import http, pipeline, schema, xai_x++ config = _base_config(XAI_API_KEY="dummy-xai-key")+ config["LAST30DAYS_X_BACKEND"] = "xai"+ plan = schema.QueryPlan(+ intent="breaking_news",+ freshness_mode="strict_recent",+ cluster_mode="story",+ raw_topic="OpenClaw",+ subqueries=[schema.SubQuery("primary", "OpenClaw", "Recent OpenClaw news", ["x"])],+ source_weights={"x": 1.0},+ )+ bundle = schema.RetrievalBundle()+ runtime = schema.ProviderRuntime("local", "", "", "xai")+ error = http.DeadlineExceeded() if status is None else http.HTTPError(message, status_code=status)++ with patch.object(xai_x, "search_x", side_effect=error):+ pipeline._retry_thin_sources(+ topic="OpenClaw",+ bundle=bundle,+ plan=plan,+ config=config,+ depth="default",+ date_range=("2026-09-01", "2026-09-30"),+ runtime=runtime,+ mock=False,+ rate_limited_sources=set(),+ rate_limit_lock=threading.Lock(),+ settings=pipeline.DEPTH_SETTINGS["default"],+ )++ assert bundle.errors_by_source["x"].startswith("Simplified-query retry failed: All X backends failed — xai:")+ assert bundle.source_status["x"].state == expected_state+ q = _compute(+ config_overrides=config,+ result_overrides={"x_error": bundle.errors_by_source["x"]},+ ytdlp_installed=True,+ )+ assert expected_fix in q["nudge_text"]+ assert "log into x.com" not in q["nudge_text"]++ def test_raised_xai_auth_error_still_uses_xquik_fallback(self):+ from lib import http, pipeline, schema, xai_x, xquik++ config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")+ plan = schema.QueryPlan(+ intent="breaking_news",+ freshness_mode="strict_recent",+ cluster_mode="story",+ raw_topic="OpenClaw",+ subqueries=[schema.SubQuery("primary", "OpenClaw", "Recent OpenClaw news", ["x"])],+ source_weights={"x": 1.0},+ )+ bundle = schema.RetrievalBundle()+ runtime = schema.ProviderRuntime("local", "", "", "xai")+ fallback_item = {+ "text": "Recent OpenClaw update",+ "url": "https://x.com/example/status/1234567890123456789",+ "author_handle": "example",+ "date": "2026-09-15",+ "engagement": {"likes": 2},+ "relevance": 0.9,+ }++ with patch.object(xai_x, "search_x", side_effect=http.HTTPError("Forbidden", status_code=403)), \+ patch.object(xquik, "search_xquik", return_value={"items": []}) as fallback_search, \+ patch.object(xquik, "parse_xquik_response", return_value=[fallback_item]):+ pipeline._retry_thin_sources(+ topic="OpenClaw",+ bundle=bundle,+ plan=plan,+ config=config,+ depth="default",+ date_range=("2026-09-01", "2026-09-30"),+ runtime=runtime,+ mock=False,+ rate_limited_sources=set(),+ rate_limit_lock=threading.Lock(),+ settings=pipeline.DEPTH_SETTINGS["default"],+ )++ fallback_search.assert_called_once()+ assert bundle.items_by_source["x"]+ assert bundle.errors_by_source["x"].startswith("X served via xquik after xai:")+ q = _compute(config_overrides=config, result_overrides={"x_error": bundle.errors_by_source["x"]}, ytdlp_installed=True)+ assert "console.x.ai" in q["nudge_text"]+ assert "log into x.com" not in q["nudge_text"]++ @pytest.mark.parametrize("status,message,expected_state,expected_fix", [+ (403, "Forbidden", "auth-failed", "console.x.ai"),+ (402, "Quota blocked", "ok", "billing"),+ (429, "Quota blocked", "ok", "rate limit"),+ (None, "Request deadline exceeded", "ok", "timed out"),+ ])+ def test_xai_fallback_keeps_repair_in_final_report(self, status, message, expected_state, expected_fix):+ import last30days as cli+ from lib import http, pipeline, providers, render, schema, xai_x, xquik++ config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")+ runtime = schema.ProviderRuntime("local", "", "", "xai")+ fallback_item = {+ "text": "Recent OpenClaw update",+ "url": "https://x.com/example/status/1234567890123456789",+ "author_handle": "example",+ "date": "2026-09-15",+ "engagement": {"likes": 2},+ "relevance": 0.9,+ }+ error = http.DeadlineExceeded() if status is None else http.HTTPError(message, status_code=status)+ with patch.object(providers, "resolve_runtime", return_value=(runtime, None)), \+ patch.object(xai_x, "search_x", side_effect=error), \+ patch.object(xquik, "search_xquik", return_value={"items": []}), \+ patch.object(xquik, "parse_xquik_response", return_value=[fallback_item]):+ report = pipeline.run(+ topic="OpenClaw", config=config, depth="default", mock=False,+ requested_sources=["x"], web_backend="none", as_of_date="2026-09-30",+ external_plan={+ "intent": "breaking_news", "freshness_mode": "strict_recent",+ "cluster_mode": "story",+ "subqueries": [{+ "label": "primary", "search_query": "OpenClaw",+ "ranking_query": "OpenClaw", "sources": ["x"],+ }],+ },+ )++ assert report.items_by_source["x"]+ assert "x" not in report.errors_by_source+ assert report.source_status["x"].state == expected_state+ assert "xai:" in report.source_status["x"].detail+ assert "re-login needed" not in report.source_status["x"].detail+ rendered = render.render_compact(report)+ if status == 403:+ assert "xai: HTTP 403" in rendered+ assert "re-login needed" not in rendered+ research_results = cli._quality_research_results(+ report, {"available_sources": ["x"]}, {"attempts": 0, "failures": 0}+ )+ assert research_results["x_error"] is None+ assert research_results["x_degraded_error"].startswith("X served via xquik after xai:")+ q = _compute(+ config_overrides=config,+ result_overrides=research_results,+ ytdlp_installed=True,+ )+ assert "x" in q["core_active"]+ assert "x" in q["core_degraded"]+ assert expected_fix in q["nudge_text"]+ assert "log into x.com" not in q["nudge_text"]++ def test_xai_rate_limit_does_not_skip_working_backup_on_later_x_subquery(self):+ import last30days as cli+ from lib import http, pipeline, providers, schema, xai_x, xquik++ config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")+ runtime = schema.ProviderRuntime("local", "", "", "xai")+ fallback_items = [+ [{+ "id": f"x{index}{slot}",+ "text": f"Recent OpenClaw update {index} {slot}",+ "url": f"https://x.com/example/status/12345678901234567{index}{slot}",+ "author_handle": "",+ "date": "2026-09-15",+ "engagement": {"likes": 2},+ "relevance": 0.9,+ } for slot in range(3)]+ for index in (0, 1, 2)+ ]+ second_query_items = []+ add_items = schema.RetrievalBundle.add_items++ def capture_items(bundle, label, source, items):+ if label == "second" and source == "x":+ second_query_items.extend(items)+ return add_items(bundle, label, source, items)++ with patch.object(providers, "resolve_runtime", return_value=(runtime, None)), \+ patch.object(pipeline, "_inner_max_workers", return_value=1), \+ patch.object(schema.RetrievalBundle, "add_items", new=capture_items), \+ patch.object(xai_x, "search_x", side_effect=http.HTTPError("Quota blocked", status_code=429)) as xai_search, \+ patch.object(xquik, "search_xquik", return_value={"items": []}) as fallback_search, \+ patch.object(xquik, "parse_xquik_response", side_effect=fallback_items):+ report = pipeline.run(+ topic="OpenClaw", config=config, depth="default", mock=False,+ requested_sources=["x"], web_backend="none", as_of_date="2026-09-30",+ external_plan={+ "intent": "breaking_news", "freshness_mode": "strict_recent",+ "cluster_mode": "story",+ "subqueries": [+ {+ "label": label, "search_query": f"OpenClaw {label}",+ "ranking_query": "OpenClaw", "sources": ["x"],+ }+ for label in ("first", "second")+ ],+ },+ )++ assert xai_search.call_count >= 2+ assert fallback_search.call_count >= 2+ assert any(+ "status/123456789012345671" in item.url+ for item in second_query_items+ )+ assert report.source_status["x"].lane_failure_state == schema.RATE_LIMITED+ research_results = cli._quality_research_results(+ report, {"available_sources": ["x"]}, {"attempts": 0, "failures": 0}+ )+ assert "HTTP 429" in research_results["x_degraded_error"]+ q = _compute(config_overrides=config, result_overrides=research_results, ytdlp_installed=True)+ assert "x" in q["core_degraded"]+ assert "rate limit" in q["nudge_text"]++ @pytest.mark.parametrize("xai_status,expected_state,expected_fix", [+ (429, "ok", "rate limit"),+ (403, "auth-failed", "console.x.ai"),+ ])+ def test_rate_limited_backup_stops_later_x_subqueries(self, xai_status, expected_state, expected_fix):+ import last30days as cli+ from lib import http, pipeline, providers, schema, xai_x, xquik++ config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")+ runtime = schema.ProviderRuntime("local", "", "", "xai")+ topic = "OpenClaw launch update"+ assert len(xquik.expand_xquik_queries(topic, "default")) == 2+ get_calls = 0++ def partial_xquik_response(*args, **kwargs):+ nonlocal get_calls+ get_calls += 1+ if get_calls == 1:+ return {"tweets": [{+ "id": "1234567890123456789",+ "author": {"username": "example"},+ "createdAt": "2026-09-15T12:00:00Z",+ "text": "Recent OpenClaw update",+ }]}+ http._raise(http.HTTPError("Too many requests", status_code=429))++ def rejected_xai_response(*args, **kwargs):+ message = "Forbidden" if xai_status == 403 else "Quota blocked"+ http._raise(http.HTTPError(message, status_code=xai_status))++ with patch.object(providers, "resolve_runtime", return_value=(runtime, None)), \+ patch.object(pipeline, "_inner_max_workers", return_value=1), \+ patch.object(xai_x, "search_x", wraps=xai_x.search_x) as xai_search, \+ patch.object(xquik, "search_xquik", wraps=xquik.search_xquik) as fallback_search, \+ patch.object(http, "post", side_effect=rejected_xai_response) as xai_post, \+ patch.object(http, "get", side_effect=partial_xquik_response):+ report = pipeline.run(+ topic=topic, config=config, depth="default", mock=False,+ requested_sources=["x"], web_backend="none", as_of_date="2026-09-30",+ external_plan={+ "intent": "breaking_news", "freshness_mode": "strict_recent",+ "cluster_mode": "story",+ "subqueries": [+ {+ "label": label, "search_query": f"OpenClaw {label}",+ "ranking_query": "OpenClaw", "sources": ["x"],+ }+ for label in ("first", "second")+ ],+ },+ )++ assert xai_search.call_count == 1+ assert xai_post.call_count == 1+ assert fallback_search.call_count == 1+ assert report.items_by_source["x"]+ assert report.source_status["x"].state == expected_state+ assert report.source_status["x"].lane_failure_state == schema.RATE_LIMITED+ assert "xquik also rate-limited" in report.source_status["x"].detail+ assert f"xai: HTTP {xai_status}" in report.source_status["x"].detail+ results = cli._quality_research_results(+ report, {"available_sources": ["x"]}, {"attempts": 0, "failures": 0}+ )+ q = _compute(config_overrides=config, result_overrides=results, ytdlp_installed=True)+ assert expected_fix in q["nudge_text"]+ assert "log into x.com" not in q["nudge_text"]