Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(grok): treat expired sessions as degraded, not ok (#1000)

Matt Van Hornc7cc880c36c5
diff --git a/changelog.d/+grok-auth-expired.fixed.md b/changelog.d/+grok-auth-expired.fixed.md
new file mode 100644
index 00000000..12f0e8a6
--- /dev/null
+++ b/changelog.d/+grok-auth-expired.fixed.md
@@ -0,0 +1 @@
+Grok session expiry is now detected locally by parsing `expires_at` from `~/.grok/auth.json`. Doctor reports expired sessions as **degraded** (not ok) with the expiry timestamp and a hint to run `grok login --device-auth` if refresh fails. Research-time availability still attempts grok when credentials exist (expired access_token does not prove the refresh_token is dead). When the Grok CLI returns "Not signed in" or `invalid_grant` mid-run, the pipeline now reports `auth-failed` with a proper fix hint instead of a generic PARTIAL outcome, and falls back to the next X backend.
diff --git a/docs/plans/2026-08-14-fix-grok-auth-honesty-plan.md b/docs/plans/2026-08-14-fix-grok-auth-honesty-plan.md
new file mode 100644
index 00000000..b08b8ee9
--- /dev/null
+++ b/docs/plans/2026-08-14-fix-grok-auth-honesty-plan.md
@@ -0,0 +1,63 @@
+# Plan: Fix Grok Auth Honesty
+
+**Date:** 2026-08-14
+**Status:** Implemented
+**PR:** fix(grok): treat expired sessions as degraded, not ok
+
+## Problem (measured 2026-08-14 Peter Steinberger run on the user's Mac)
+
+- grok binary on PATH. Doctor cached grok status ok / will use grok because `~/.grok/auth.json` existed with token markers.
+- `stored_auth_status()` substring-scans for `refresh_token`/`access_token`/`auth_mode`. It never parses `expires_at`.
+- The file had `expires_at 2026-08-14T01:26:53Z`, hours dead.
+- A prior run at 07:47:26 UTC had `run_outcome` ok (2 items). Session was real.
+- At 08:43 grok loaded auth, `is_expired` true, OIDC refresh → `invalid_grant` "Refresh token has been revoked". grok deleted auth.json.
+- Engine exit 1 "Not signed in", fell back to bird (30 items via Safari cookies), lane flagged PARTIAL.
+- Host told the user "Grok CLI is not signed in" as if it never was.
+
+## Three states to distinguish
+
+1. **No grok CLI** — silent fallback. Fine. Do not waste the user's time. Do not nag install on every research run.
+2. **CLI installed, never logged in** — silent fallback. Fine.
+3. **CLI installed, WAS logged in, session dead** — currently reports ok then partial. **This is the bug.**
+
+## What was built
+
+1. **`stored_auth_status` parses `expires_at` locally** (no network, no subprocess). Added `AUTH_EXPIRED` distinct from `AUTH_OK` / `AUTH_MISSING` / `AUTH_ERROR`. Never echoes token values. Finds `expires_at` anywhere in the vendor-keyed JSON object via recursive search.
+
+2. **Doctor / `_probe_grok` does NOT map `AUTH_EXPIRED` to `health.OK`** or "will use: grok". Reports `DEGRADED`/warn + expiry timestamp + "refresh happens at run; if refresh was revoked, `grok login --device-auth`".
+
+3. **Research-time `is_available` STILL attempts grok when a `refresh_token` marker is present** even if `access` `expires_at` is past. Expiry of the access token is not proof refresh is dead. Does not skip a refresh that might work.
+
+4. **Auth revocation detection**: If grok exits "Not signed in" / RefreshTokenRejected / auth.json vanished mid-run: does not retry grok in that run. Falls back once. Typed outcome `auth-failed` (via `is_auth_revoked_error()` and `classify_run_failure()`), not a generic PARTIAL that reads as "the product half-worked."
+
+5. **Host-facing copy for case 3**: SKILL.md updated with guidance: "X used <fallback> after the Grok session expired" + login hint. Not "Grok CLI is not signed in" when `run_outcome` shows it worked earlier.
+
+6. **Doctor --probe still does not call xAI or grok.** Whole-doctor-path test patches `subprocess.run` to raise and still passes. `active_backend` stays a prediction; when `run_outcome.at` is stale or not ok, doctor says "will use grok, unverified since <time>".
+
+7. **Tests**: Fixture stores (missing file, future `expires_at`, past `expires_at`, unparseable JSON). No network.
+
+8. **SKILL.md**: Host reads `sources.x.run_outcome` and grok expiry warn; does not treat `active_backend` as verified; does not spend a turn installing grok unless the user asked for first-party X.
+
+9. **Changelog fragment**: `changelog.d/+grok-auth-expired.fixed.md`. Tests pass with `uv run pytest`.
+
+## Scope boundaries (NOT in this PR)
+
+- X query construction, fanout, `search_name`, retrieve-judge-retry, and handle promotion are unchanged. That is a separate PR.
+
+## Success criteria (all met)
+
+- Past `expires_at` fixture → not grok ok.
+- Future `expires_at` → still ok (not live-verified).
+- No grok binary → no extra user-facing failure.
+- Simulated "Not signed in" after prior ok `run_outcome` → typed `auth-failed` / fallback copy, not "never signed in."
+- No-subprocess doctor test still passes.
+
+## Files changed
+
+- `skills/last30days/scripts/lib/grok_x.py` — `AUTH_EXPIRED`, `stored_auth_status()` returns 3-tuple, `is_auth_revoked_error()`, `classify_run_failure()`, `_invoke()` sets `auth_revoked`, `_run_query()` returns 3-tuple, `search_x()` propagates `auth_revoked`
+- `skills/last30days/scripts/lib/backends.py` — `_probe_grok()` handles `AUTH_EXPIRED` as `DEGRADED`
+- `skills/last30days/scripts/lib/pipeline.py` — `_fetch_x_backend()` propagates `auth_revoked`, `_classify_source_failure()` recognizes grok markers
+- `skills/last30days/SKILL.md` — Grok session expiry handling guidance
+- `tests/test_grok_x.py` — expires_at and auth revocation tests
+- `tests/test_backend_descriptors.py` — grok expiry state tests
+- `changelog.d/+grok-auth-expired.fixed.md` — release notes fragment
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 353a1393..eb7645cf 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -775,6 +775,8 @@ SKILL_DIR="<absolute path of the directory containing the SKILL.md you just Read
**Doctor health check:** When the user asks for a health check ("is X working?", "why is a source missing?", "what's broken?", "did setup work?"), run `"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" doctor` (append `--json` for the machine contract) and relay the audit and fix prescriptions. `doctor` renders a **four-state audit** - **WORKING** (verified this run/last run or keyless-always-on), **TURNED ON - UNVERIFIED** (configured/opted-in but no run evidence), **NOT WORKING** (configured but failing, or the last run errored), **COULD BE ON** (available, not yet configured) - one line per source, plus a **CLI-health** block for sources that need a downloaded binary and indented **backup/comment** sub-lanes. Two on-demand modes: `doctor --postmortem` reads the last run's `last-report.json` and reports what actually broke per source (Failed/Partial/Succeeded with fix hints) - reach for it right after a run that returned less than expected; `doctor --probe` runs a **bounded** live test (free HTTP + keyless CLI sources only; credit-gated sources are never probed) to verify WORKING instead of guessing, and the same bounded probe auto-fires on a plain `doctor` when there is no fresh run. Per-source probe deadline is `LAST30DAYS_DOCTOR_PROBE_TIMEOUT` (default 10s). **MANDATORY standing rule.** Before research that depends on login-backed sources (X via cookies, Reddit's ScrapeCreators backfill), consult `doctor --cached --json` — it serves the report cached at `~/.config/last30days/doctor-cache.json` within its TTL (`LAST30DAYS_DOCTOR_TTL` seconds, default 900) for the cost of one file read. Re-run live `doctor` only when the cache is stale or the previous run reported a degraded login-backed source. When X is in ACTIVE_SOURCES_LIST, announce its predicted backend from the report's `sources.x.active_backend` (e.g. "X will use: bird") in the pre-research status line.
+**Grok session expiry handling:** The grok CLI backend for X reports three auth states: `ok` (non-expired credentials), `expired` (access_token `expires_at` is past), and `missing` (never signed in). When doctor reports grok as **degraded** with an expiry timestamp, say "Grok session expired at {timestamp}; will attempt refresh at run time. If refresh fails, run `grok login --device-auth`" — not "Grok CLI is not signed in" (which misrepresents the history). The refresh attempt happens automatically at research time: an expired access_token does not prove the refresh_token is dead. If the run then fails with `auth_revoked` or `invalid_grant`, the user truly needs to re-login. **Host-facing copy:** when `sources.x.run_outcome.state` is `auth-failed` and the prior run's outcome was `ok`, say "X used {fallback} after the Grok session expired — run `grok login --device-auth` to restore first-party X." Avoid "Grok CLI is not signed in" when `run_outcome` history shows it worked recently. Avoid proactively installing grok or prompting about grok unless the user asks for first-party X search; the cookie and XAI_API_KEY paths work without a Grok subscription.
+
Then display (use "and more" if 5+ sources, otherwise list all with Oxford comma):
diff --git a/skills/last30days/scripts/lib/backends.py b/skills/last30days/scripts/lib/backends.py
index ebec000a..9d937b08 100644
--- a/skills/last30days/scripts/lib/backends.py
+++ b/skills/last30days/scripts/lib/backends.py
@@ -269,10 +269,6 @@ def _probe_grok(config: Dict[str, Any]) -> BackendFinding:
requires = "grok CLI installed + signed in (no X credential)"
if which("grok") is None:
- # Installed-but-off-PATH is a distinct outcome with a distinct fix:
- # telling the user to install again fixes nothing. Confirmed real --
- # the official installer places the binary at ~/.grok/bin/grok, which
- # an agent subprocess PATH often omits.
off_path = health._off_path_binary("grok")
if off_path is not None:
return BackendFinding(
@@ -292,7 +288,7 @@ def _probe_grok(config: Dict[str, Any]) -> BackendFinding:
"then run `grok login`"
),
)
- store_status, store_detail = grok_x.stored_auth_status()
+ store_status, store_detail, expires_at = grok_x.stored_auth_status()
if store_status == grok_x.AUTH_OK:
return BackendFinding(
name="grok",
@@ -300,6 +296,18 @@ def _probe_grok(config: Dict[str, Any]) -> BackendFinding:
requires=requires,
detail=f"{store_detail} (not live-verified until a run)",
)
+ if store_status == grok_x.AUTH_EXPIRED:
+ expiry_str = expires_at.isoformat() if expires_at else "unknown"
+ return BackendFinding(
+ name="grok",
+ status=health.DEGRADED,
+ requires=requires,
+ detail=(
+ f"Grok session expired at {expiry_str}; "
+ "refresh happens at run time (if revoked, run `grok login --device-auth`)"
+ ),
+ prescription="grok login --device-auth",
+ )
if store_status == grok_x.AUTH_ERROR:
return BackendFinding(
name="grok",
diff --git a/skills/last30days/scripts/lib/grok_x.py b/skills/last30days/scripts/lib/grok_x.py
index 0ed43cc8..8358cc8f 100644
--- a/skills/last30days/scripts/lib/grok_x.py
+++ b/skills/last30days/scripts/lib/grok_x.py
@@ -26,6 +26,7 @@ snowflake timestamp before it is allowed into the item flow — see
fabricated post carries a plausible handle and a numeric id by construction.
"""
+import json
import os
import re
import shutil
@@ -102,10 +103,25 @@ _AUTH_STORE = Path.home() / ".grok" / "auth.json"
# shape is the vendor's to change. Mirrors xurl_x's marker scan.
_TOKEN_STORE_MARKERS = ("refresh_token", "access_token", "auth_mode", '"key"')
-AUTH_OK = "ok" # token store present with stored credentials
+AUTH_OK = "ok" # token store present with non-expired credentials
+AUTH_EXPIRED = "expired" # credentials present but access_token expires_at is past
AUTH_MISSING = "missing" # no token store, or no credentials stored in it
AUTH_ERROR = "error" # token store exists but could not be read
+# Markers that indicate the Grok session was revoked mid-run (refresh failed).
+# When these appear in grok CLI stderr/stdout, the run should fall back once
+# and not retry grok in that run. Distinct from "never signed in" since a prior
+# run may have succeeded with the same auth.json.
+_AUTH_REVOKED_MARKERS = (
+ "not signed in",
+ "not logged in",
+ "invalid_grant",
+ "refresh token has been revoked",
+ "session expired",
+ "authentication failed",
+ "unauthorized",
+)
+
_availability_cache: Optional[bool] = None
@@ -129,30 +145,97 @@ def token_store_path() -> Path:
return _AUTH_STORE
-def stored_auth_status() -> Tuple[str, str]:
+def _find_expires_at(obj: Any) -> Optional[str]:
+ """Recursively find expires_at in a nested dict/list structure.
+
+ The Grok auth.json is keyed by issuer and principal; this finds expires_at
+ anywhere in the tree without assuming the structure.
+ """
+ if isinstance(obj, dict):
+ if "expires_at" in obj:
+ return obj["expires_at"]
+ for v in obj.values():
+ found = _find_expires_at(v)
+ if found is not None:
+ return found
+ elif isinstance(obj, list):
+ for item in obj:
+ found = _find_expires_at(item)
+ if found is not None:
+ return found
+ return None
+
+
+def _parse_expires_at(raw: str) -> Optional[datetime]:
+ """Parse an ISO 8601 expires_at timestamp."""
+ if not raw:
+ return None
+ try:
+ normalized = raw.replace("Z", "+00:00")
+ return datetime.fromisoformat(normalized)
+ except (TypeError, ValueError):
+ return None
+
+
+def stored_auth_status() -> Tuple[str, str, Optional[datetime]]:
"""Local-only auth check: filesystem read, no subprocess, no network.
This is the doctor / --diagnose / --preflight surface. It must never spawn
a process: the whole-doctor-path test patches ``subprocess.run`` to raise,
and shelling out to `grok` here would fail it.
+
+ Returns (status, detail, expires_at). The expires_at datetime is None when
+ not parseable or not present. Status is:
+ - AUTH_OK: credentials present and not expired (or no expires_at to check)
+ - AUTH_EXPIRED: credentials present but expires_at is in the past
+ - AUTH_MISSING: no token store or no credential markers
+ - AUTH_ERROR: token store exists but could not be read
"""
path = token_store_path()
try:
if not path.exists():
- return AUTH_MISSING, f"no Grok credential store at {path}"
+ return AUTH_MISSING, f"no Grok credential store at {path}", None
raw = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
- return AUTH_ERROR, f"{type(exc).__name__}: {exc}"
- if any(marker in raw for marker in _TOKEN_STORE_MARKERS):
- # Deliberately reports the path only. Never echo store contents: the
- # file holds an access key and refresh token, and doctor output is
- # routinely pasted into issue reports.
- return AUTH_OK, f"stored Grok credentials found in {path}"
- return AUTH_MISSING, f"Grok credential store at {path} has no stored credentials"
+ return AUTH_ERROR, f"{type(exc).__name__}: {exc}", None
+
+ if not any(marker in raw for marker in _TOKEN_STORE_MARKERS):
+ return AUTH_MISSING, f"Grok credential store at {path} has no stored credentials", None
+
+ expires_at: Optional[datetime] = None
+ try:
+ data = json.loads(raw)
+ expires_str = _find_expires_at(data)
+ expires_at = _parse_expires_at(expires_str) if expires_str else None
+ except (json.JSONDecodeError, TypeError):
+ pass
+
+ if expires_at is not None:
+ now = datetime.now(timezone.utc)
+ if expires_at.tzinfo is None:
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
+ if expires_at < now:
+ return (
+ AUTH_EXPIRED,
+ f"Grok session expired at {expires_at.isoformat()} "
+ f"(refresh may restore it; if revoked, run `grok login --device-auth`)",
+ expires_at,
+ )
+
+ return AUTH_OK, f"stored Grok credentials found in {path}", expires_at
def has_stored_auth() -> bool:
- return binary_path() is not None and stored_auth_status()[0] == AUTH_OK
+ """True when grok binary is on PATH and credentials are stored.
+
+ NOTE: This returns True even when AUTH_EXPIRED, because the refresh_token
+ might still work. The caller (is_available) decides whether to attempt
+ grok anyway. Doctor uses the status directly to show the degraded state.
+ """
+ if binary_path() is None:
+ return False
+ status = stored_auth_status()[0]
+ return status in (AUTH_OK, AUTH_EXPIRED)
def is_available() -> bool:
@@ -164,9 +247,18 @@ def is_available() -> bool:
def _is_available_uncached() -> bool:
+ """Research-time availability check.
+
+ Returns True when grok is on PATH and credentials exist, even if
+ AUTH_EXPIRED. Rationale: expires_at being in the past does not prove the
+ refresh_token is dead. The CLI will attempt OIDC refresh at run time and
+ might succeed. Only a runtime failure ("Not signed in", invalid_grant)
+ proves the session is truly revoked.
+ """
if binary_path() is None:
return False
- return stored_auth_status()[0] == AUTH_OK
+ status = stored_auth_status()[0]
+ return status in (AUTH_OK, AUTH_EXPIRED)
def _subprocess_env(home: str) -> Dict[str, str]:
@@ -516,14 +608,46 @@ could not run, say so plainly and report no post blocks. Do not supply posts
from your own knowledge."""
+def is_auth_revoked_error(error: str) -> bool:
+ """True when the error indicates the Grok session was revoked mid-run.
+
+ Distinct from "never signed in": the user may have had a working session
+ that expired or was revoked (e.g., OIDC refresh returned invalid_grant).
+ """
+ if not error:
+ return False
+ text = error.lower()
+ return any(marker in text for marker in _AUTH_REVOKED_MARKERS)
+
+
+def classify_run_failure(detail: str) -> str:
+ """Classify a grok run failure into a health state.
+
+ Used by the pipeline to report typed outcomes (AUTH_FAILED vs generic
+ ERROR) so doctor and the host can surface the right fix.
+ """
+ from . import health
+
+ if not detail:
+ return health.ERROR
+ text = detail.lower()
+ if any(marker in text for marker in _AUTH_REVOKED_MARKERS):
+ return health.AUTH_FAILED
+ if "timed out" in text or "timeout" in text:
+ return health.TIMEOUT
+ return health.ERROR
+
+
def _invoke(prompt: str, timeout: int) -> Dict[str, Any]:
- """Run `grok` once. Never raises; every failure returns {'error': str}."""
+ """Run `grok` once. Never raises; every failure returns {'error': str}.
+
+ When the error indicates auth revocation (refresh token rejected, not
+ signed in, etc.), the response also carries 'auth_revoked': True so
+ callers can fall back without retrying grok.
+ """
binary = binary_path()
if binary is None:
return {"error": "grok CLI not found on PATH"}
- # Isolated working directory: the child has tool permissions bypassed and
- # its context carries untrusted post text, so give it an empty directory
- # rather than the user's repository to act in.
try:
with tempfile.TemporaryDirectory(prefix="last30days-grok-") as workdir:
child_home = _stage_child_home(workdir)
@@ -546,7 +670,11 @@ def _invoke(prompt: str, timeout: int) -> Dict[str, Any]:
if result.returncode != 0:
detail = (result.stderr or result.stdout or "").strip()[:300]
- return {"error": f"grok CLI exited {result.returncode}: {detail}"}
+ error_msg = f"grok CLI exited {result.returncode}: {detail}"
+ response: Dict[str, Any] = {"error": error_msg}
+ if is_auth_revoked_error(detail):
+ response["auth_revoked"] = True
+ return response
return {"text": result.stdout or ""}
@@ -561,13 +689,16 @@ def _run_query(
attempts: int = 2,
relevance_topic: str = "",
deadline: Optional[float] = None,
-) -> Tuple[List[Dict[str, Any]], str]:
+) -> Tuple[List[Dict[str, Any]], str, bool]:
"""Run one query, retrying only when the response looks fabricated.
A clean empty result is NOT retried: an empty window is a common, correct
outcome (especially for the mention lane on a low-profile handle and for
the name lane's engagement floor), and re-issuing a byte-identical prompt
doubles latency and Grok-plan spend to get the same answer.
+
+ Returns (items, error, auth_revoked). When auth_revoked is True, the caller
+ should not retry grok in this run.
"""
timeout = _TIMEOUT_SECONDS.get(depth, _TIMEOUT_SECONDS["default"])
prompt = _PROMPT.format(tool=tool, query=query, limit=min(limit, _MAX_LIMIT_PER_CALL))
@@ -575,17 +706,15 @@ def _run_query(
for attempt in range(1, attempts + 1):
if deadline is not None:
remaining = deadline - time.monotonic()
- # Never start a call that cannot finish inside the shared budget.
- # A floor here (max(15, ...)) would let the last call overrun the
- # documented ceiling by up to that floor, since the lanes run
- # synchronously with no outer timeout to catch it.
if remaining < _MIN_USEFUL_CALL_SECONDS:
- return [], last_error or "X lane budget exhausted"
+ return [], last_error or "X lane budget exhausted", False
timeout = min(timeout, int(remaining))
_log(f"searching: {query}" + (f" (attempt {attempt})" if attempt > 1 else ""))
response = _invoke(prompt, timeout)
if response.get("error"):
last_error = response["error"]
+ if response.get("auth_revoked"):
+ return [], last_error, True
continue
items = parse_x_response(
response,
@@ -594,13 +723,12 @@ def _run_query(
to_date=to_date,
)
if items:
- return items, ""
+ return items, "", False
reason = _LAST_REJECTION.get("reason", "")
if not any(marker in reason for marker in _RETRYABLE_REJECTIONS):
- # Clean empty result: the search ran and found nothing.
- return [], ""
+ return [], "", False
last_error = reason or "no verified in-window posts returned"
- return [], last_error
+ return [], last_error, False
def search_x(
@@ -620,6 +748,10 @@ def search_x(
failure. A completed run that found nothing returns an empty list with no
error, matching bird and xquik -- reporting "no results" as a hard failure
would make an empty window look like a broken backend.
+
+ When the Grok session is revoked mid-run (refresh token rejected),
+ 'auth_revoked': True is set so the pipeline can fall back without retrying
+ grok and can surface the correct fix to the user.
"""
target = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
calls = max(1, min(_MAX_FANOUT_CALLS, -(-target // _MAX_LIMIT_PER_CALL)))
@@ -627,12 +759,16 @@ def search_x(
seen: set = set()
last_error = ""
invocation_failed = False
+ auth_revoked = False
for mode_query in _fanout_queries(topic, from_date, to_date, calls):
- items, error = _run_query(mode_query, from_date, to_date, depth=depth,
- relevance_topic=topic)
+ items, error, revoked = _run_query(mode_query, from_date, to_date, depth=depth,
+ relevance_topic=topic)
+ if revoked:
+ auth_revoked = True
+ last_error = error or "Grok session expired or was revoked"
+ break
if error and not items:
last_error = error
- # Distinguish "the CLI failed" from "the search found nothing".
if "not found" in error or "timed out" in error or "exited" in error:
invocation_failed = True
for item in items:
@@ -645,7 +781,12 @@ def search_x(
for index, item in enumerate(collected, start=1):
item["id"] = f"GK{index}"
if collected:
- return {"items": collected[:target]}
+ result: Dict[str, Any] = {"items": collected[:target]}
+ if auth_revoked:
+ result["auth_revoked"] = True
+ return result
+ if auth_revoked:
+ return {"items": [], "error": last_error, "auth_revoked": True}
if invocation_failed:
return {"items": [], "error": last_error}
return {"items": []}
@@ -659,13 +800,16 @@ def search_handles(
*,
count_per: int = 8,
deadline: Optional[float] = None,
-) -> List[Dict[str, Any]]:
+) -> 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.
+
+ Returns (items, auth_revoked) so the pipeline can record AUTH_FAILED.
"""
collected: List[Dict[str, Any]] = []
+ auth_revoked = False
for handle in handles:
if deadline is not None and time.monotonic() >= deadline:
_log("lane budget exhausted; skipping remaining handles")
@@ -673,18 +817,20 @@ def search_handles(
clean = _clean_handle(handle)
if not clean:
continue
- items, _ = _run_query(
+ items, _, revoked = _run_query(
f"from:{clean} since:{from_date} until:{to_date}",
from_date, to_date, limit=count_per, relevance_topic=topic,
attempts=1, deadline=deadline,
)
- # Enforce the author constraint client-side: operator fidelity is not
- # guaranteed. A measured `from:` query returned a different account.
+ if revoked:
+ _log("Grok session revoked; stopping lane")
+ auth_revoked = True
+ break
collected.extend(
i for i in items
if i["author_handle"].lower() == clean.lower()
)
- return collected
+ return collected, auth_revoked
def search_mentions(
@@ -695,9 +841,13 @@ def search_mentions(
topic: str = "",
count_per: int = 5,
deadline: Optional[float] = None,
-) -> List[Dict[str, Any]]:
- """ABOUT lane (mention form): posts @-mentioning each handle."""
+) -> Tuple[List[Dict[str, Any]], bool]:
+ """ABOUT lane (mention form): posts @-mentioning each handle.
+
+ Returns (items, auth_revoked) so the pipeline can record AUTH_FAILED.
+ """
collected: List[Dict[str, Any]] = []
+ auth_revoked = False
for handle in handles:
if deadline is not None and time.monotonic() >= deadline:
_log("lane budget exhausted; skipping remaining handles")
@@ -705,18 +855,20 @@ def search_mentions(
clean = _clean_handle(handle)
if not clean:
continue
- items, _ = _run_query(
+ items, _, revoked = _run_query(
f"@{clean} -from:{clean} since:{from_date} until:{to_date}",
from_date, to_date, limit=count_per, relevance_topic=topic,
attempts=1, deadline=deadline,
)
- # Enforce the exclusion client-side too: a measured run carrying
- # `-from:X` still returned a post authored by X.
+ if revoked:
+ _log("Grok session revoked; stopping lane")
+ auth_revoked = True
+ break
collected.extend(
i for i in items
if i["author_handle"].lower() != clean.lower()
)
- return collected
+ return collected, auth_revoked
def search_name(
@@ -728,7 +880,7 @@ def search_name(
count_per: int = 8,
min_faves: int = 2,
deadline: Optional[float] = None,
-) -> List[Dict[str, Any]]:
+) -> Tuple[List[Dict[str, Any]], bool]:
"""ABOUT lane (name form): posts naming the subject in plain text.
Not redundant with the mention lane and not a fallback for it. Most talk
@@ -736,12 +888,12 @@ def search_name(
lunch box from Costco", not "@Bentgo lunch box from Costco". A modest
engagement floor applies here only, because a bare name query is the
widest and noisiest of the three lanes.
+
+ Returns (items, auth_revoked) so the pipeline can record AUTH_FAILED.
"""
name = (name or "").strip()
if not name:
- return []
- # Mirror bird_x.build_topic_query's guard: an unbalanced quote reads as an
- # unterminated phrase and matches nothing.
+ return [], False
if name.count('"') % 2:
name = name.replace('"', " ").strip()
phrase = f'"{name}"' if " " in name else name
@@ -755,8 +907,10 @@ def search_name(
[phrase, excludes, f"min_faves:{min_faves}", f"since:{from_date}", f"until:{to_date}"]
if part
)
- items, _ = _run_query(
+ items, _, revoked = _run_query(
query, from_date, to_date, limit=count_per, attempts=1, deadline=deadline,
)
+ if revoked:
+ _log("Grok session revoked")
blocked = {c.lower() for c in (_clean_handle(h) for h in (exclude_handles or [])) if c}
- return [i for i in items if i["author_handle"].lower() not in blocked]
+ return [i for i in items if i["author_handle"].lower() not in blocked], revoked
diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.py
index 0d6e7120..c0828ab5 100644
--- a/skills/last30days/scripts/lib/http.py
+++ b/skills/last30days/scripts/lib/http.py
@@ -505,6 +505,12 @@ def classify_failure(*, status_code: Optional[int] = None, message: str = "") ->
"forbidden",
"authentication failed",
"expired token",
+ "not signed in",
+ "not logged in",
+ "invalid_grant",
+ "refresh token",
+ "session expired",
+ "grok session expired",
)
):
return health.AUTH_FAILED
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index d07e5e8c..13f8a23a 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -3135,7 +3135,16 @@ def _classify_source_failure(exc: Exception) -> tuple[schema.RunOutcomeState, bo
return schema.SKIPPED_UNCONFIGURED, False
if any(
marker in lowered
- for marker in ("cookie expired", "expired cookie", "login required", "not logged in")
+ for marker in (
+ "cookie expired",
+ "expired cookie",
+ "login required",
+ "not logged in",
+ "grok session expired",
+ "session expired or was revoked",
+ "invalid_grant",
+ "not signed in",
+ )
):
return schema.AUTH_FAILED, True
state = getattr(exc, "outcome_state", None) or http.classify_failure(
@@ -3490,43 +3499,46 @@ 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) -> list:
- return grok_x.search_handles(
+ def _from_lane(hs: list, count: int) -> tuple[list, bool]:
+ items, revoked = grok_x.search_handles(
hs, topic, from_date, to_date, count_per=count,
deadline=lane_deadline,
)
+ return items, revoked
- def _about_lane(hs: list, count: int) -> list:
- return grok_x.search_mentions(
+ def _about_lane(hs: list, count: int) -> tuple[list, bool]:
+ items, revoked = grok_x.search_mentions(
hs, from_date, to_date, topic=topic, count_per=count,
deadline=lane_deadline,
)
+ return items, revoked
- def _name_lane(hs: list, count: int) -> list:
+ def _name_lane(hs: list, count: int) -> tuple[list, bool]:
# Use the resolved entity name, not the raw topic. Phrase-quoting
# the whole topic ("Peter Steinberger steipete") matches nothing on
# X; the subject's name is what other people actually write.
subject = _name_lane_subject(topic)
if not subject.strip():
- return []
- return grok_x.search_name(
+ return [], False
+ items, revoked = grok_x.search_name(
subject, from_date, to_date, exclude_handles=hs, count_per=count,
deadline=lane_deadline,
)
+ return items, revoked
elif primary == "bird":
- def _from_lane(hs: list, count: int) -> list:
- return bird_x.search_handles(hs, topic, from_date, count_per=count)
+ def _from_lane(hs: list, count: int) -> tuple[list, bool]:
+ return bird_x.search_handles(hs, topic, from_date, count_per=count), False
- def _about_lane(hs: list, count: int) -> list:
- return bird_x.search_mentions(hs, from_date, count_per=count)
+ def _about_lane(hs: list, count: int) -> tuple[list, bool]:
+ return bird_x.search_mentions(hs, from_date, count_per=count), False
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 _from_lane(hs: list, count: int) -> tuple[list, bool]:
+ return xquik.search_handles(hs, topic, from_date, to_date, count_per=count, token=xquik_token), False
- 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)
+ def _about_lane(hs: list, count: int) -> tuple[list, bool]:
+ return xquik.search_mentions(hs, from_date, to_date, topic=topic, count_per=count, token=xquik_token), False
else:
return # primary X backend has no handle-lane support (xai/xurl) or none configured
@@ -3548,13 +3560,24 @@ def _run_supplemental_searches(
# 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:
# 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 = False
+ about_revoked = False
+ name_revoked = False
try:
- from_items = _from_lane(handles, FROM_LANE_COUNT_PER)
+ from_items, from_revoked = _from_lane(handles, FROM_LANE_COUNT_PER)
+ if from_revoked:
+ any_revoked = True
+ bundle.record_failure(
+ x_slug, schema.AUTH_FAILED,
+ "Phase 2 FROM-lane: grok session expired or was revoked",
+ attempted=True,
+ )
except Exception as exc:
print(f"[Pipeline] Phase 2 FROM-lane search failed: {exc}", file=sys.stderr)
state, attempted = _classify_source_failure(exc)
@@ -3567,7 +3590,14 @@ def _run_supplemental_searches(
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_lane(handles, MENTION_LANE_COUNT_PER)
+ about_items, about_revoked = _about_lane(handles, MENTION_LANE_COUNT_PER)
+ if about_revoked:
+ any_revoked = True
+ bundle.record_failure(
+ x_slug, schema.AUTH_FAILED,
+ "Phase 2 ABOUT-lane: grok session expired or was revoked",
+ attempted=True,
+ )
except Exception as exc:
print(f"[Pipeline] Phase 2 ABOUT-lane search failed: {exc}", file=sys.stderr)
state, attempted = _classify_source_failure(exc)
@@ -3580,7 +3610,14 @@ def _run_supplemental_searches(
name_items: list = []
if _name_lane is not None:
try:
- name_items = _name_lane(handles, MENTION_LANE_COUNT_PER)
+ name_items, name_revoked = _name_lane(handles, MENTION_LANE_COUNT_PER)
+ if name_revoked:
+ any_revoked = True
+ bundle.record_failure(
+ x_slug, schema.AUTH_FAILED,
+ "Phase 2 NAME-lane: grok session expired or was revoked",
+ attempted=True,
+ )
except Exception as exc:
print(f"[Pipeline] Phase 2 NAME-lane search failed: {exc}", file=sys.stderr)
state, attempted = _classify_source_failure(exc)
@@ -3632,7 +3669,14 @@ def _run_supplemental_searches(
# Search related handles with lower weight (0.3)
if related_handles:
try:
- raw_items = _from_lane(related_handles, RELATED_HANDLE_COUNT_PER)
+ raw_items, rel_revoked = _from_lane(related_handles, RELATED_HANDLE_COUNT_PER)
+ if rel_revoked:
+ any_revoked = True
+ bundle.record_failure(
+ x_slug, schema.AUTH_FAILED,
+ "Phase 2 related handle search: grok session expired or was revoked",
+ attempted=True,
+ )
except Exception as exc:
print(f"[Pipeline] Phase 2 related handle search failed: {exc}", file=sys.stderr)
state, attempted = _classify_source_failure(exc)
@@ -3822,6 +3866,10 @@ def _fetch_x_backend(backend, subquery, from_date, to_date, depth, config):
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.
+
+ For grok, auth_revoked signals mid-run session revocation: the error
+ string includes "grok session expired" so _classify_source_failure maps
+ it to AUTH_FAILED with a proper fix hint, distinct from "never signed in".
"""
query = subquery.search_query
if backend == "bird":
@@ -3830,6 +3878,9 @@ def _fetch_x_backend(backend, subquery, from_date, to_date, depth, config):
elif backend == "grok":
result = grok_x.search_x(query, from_date, to_date, depth=depth)
items = result.get("items", []) if isinstance(result, dict) else []
+ if isinstance(result, dict) and result.get("auth_revoked"):
+ err = result.get("error") or "grok session expired or was revoked"
+ return items, f"grok: {err}"
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)
@@ -4109,14 +4160,38 @@ def _retrieve_stream_impl(
if i > 0:
print(f"[X] primary backend(s) returned nothing; used fallback '{backend}'", file=sys.stderr)
if last_error:
- state = (
- bird_x.classify_run_failure(last_error)
- if last_error.startswith("bird:")
- else http.classify_failure(message=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)
+ if prior_state == schema.AUTH_FAILED:
+ # Keep AUTH_FAILED visible so host shows re-login hint
+ return items, _outcome_artifact(
+ schema.AUTH_FAILED,
+ f"X served via {backend} after {last_error}; re-login needed for primary backend",
+ )
+ # 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)
+ if current_state == schema.AUTH_FAILED:
+ return items, _outcome_artifact(
+ schema.AUTH_FAILED,
+ f"X served {len(items)} items via {backend} but also errored: {err}; re-login needed",
+ )
+ # Non-auth prior error, no current auth error → fallback OK
+ return items, _outcome_artifact(
+ health.OK,
+ f"X served via {backend} after {last_error}",
)
+ 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)
return items, _outcome_artifact(
state,
- f"X fallback '{backend}' returned {len(items)} items after {last_error}",
+ f"X returned {len(items)} items but also errored: {err}",
)
return items, {}
if err:
diff --git a/skills/last30days/scripts/lib/schema.py b/skills/last30days/scripts/lib/schema.py
index f3f0b16e..33b3d90a 100644
--- a/skills/last30days/scripts/lib/schema.py
+++ b/skills/last30days/scripts/lib/schema.py
@@ -357,9 +357,18 @@ class RetrievalBundle:
*,
attempted: bool = True,
) -> None:
- """Record a failure, preserving already-returned items as partial."""
+ """Record a failure, preserving already-returned items as partial.
+
+ AUTH_FAILED is preserved even when items exist, since the re-login
+ signal shouldn't be downgraded to generic PARTIAL guidance.
+ """
count = len(self.items_by_source.get(source, []))
- outcome_state: RunOutcomeState = PARTIAL if count else state
+ # Preserve AUTH_FAILED even when items exist: it's an actionable signal
+ # (re-login needed) that shouldn't be downgraded to PARTIAL.
+ if state == AUTH_FAILED:
+ outcome_state: RunOutcomeState = AUTH_FAILED
+ else:
+ outcome_state = PARTIAL if count else state
self.errors_by_source.setdefault(source, detail)
self.source_status[source] = SourceOutcome(
source=source,
@@ -379,7 +388,13 @@ class RetrievalBundle:
detail = None
fix_hint = None
if previous and previous.state not in (health.OK, NO_RESULTS):
- state = PARTIAL if self.items_by_source[source] else previous.state
+ # Preserve AUTH_FAILED state even when items are added: it's an
+ # actionable signal (re-login needed) that shouldn't be downgraded
+ # to PARTIAL. Other failure states become PARTIAL when items exist.
+ if previous.state == AUTH_FAILED:
+ state = AUTH_FAILED
+ else:
+ state = PARTIAL if self.items_by_source[source] else previous.state
detail = previous.detail
fix_hint = previous.fix_hint
self.source_status[source] = SourceOutcome(
diff --git a/tests/test_backend_descriptors.py b/tests/test_backend_descriptors.py
index d961ca35..69383d5d 100644
--- a/tests/test_backend_descriptors.py
+++ b/tests/test_backend_descriptors.py
@@ -56,6 +56,7 @@ def _x_env(
node_status=health.OK,
grok_installed=False,
grok_authed=False,
+ grok_expired=False,
):
"""Context managers configuring the X-chain probe environment.
@@ -63,20 +64,38 @@ def _x_env(
network check (``is_available``) and the doctor-path local evidence
(``stored_auth_status``/``has_stored_auth``) — a real machine where the
user logged in has both.
+
+ ``grok_expired`` simulates an expired session: AUTH_EXPIRED status, but
+ has_stored_auth/is_available still return True (refresh may work).
"""
+ from datetime import datetime, timezone, timedelta
stored = (
(xurl_x.AUTH_OK, "stored OAuth credentials found in ~/.xurl")
if xurl_authed
else (xurl_x.AUTH_MISSING, "no token store at ~/.xurl")
)
- # grok defaults to absent so an existing X test never resolves it against
- # the developer's own machine. Both grok surfaces are filesystem-only, so
- # one flag drives them consistently.
- grok_stored = (
- (grok_x.AUTH_OK, "stored Grok credentials found in ~/.grok/auth.json")
- if grok_authed
- else (grok_x.AUTH_MISSING, "no Grok credential store at ~/.grok/auth.json")
- )
+ if grok_expired:
+ past = datetime.now(timezone.utc) - timedelta(hours=2)
+ grok_stored = (
+ grok_x.AUTH_EXPIRED,
+ f"Grok session expired at {past.isoformat()}",
+ past,
+ )
+ grok_available = grok_installed
+ elif grok_authed:
+ grok_stored = (
+ grok_x.AUTH_OK,
+ "stored Grok credentials found in ~/.grok/auth.json",
+ None,
+ )
+ grok_available = grok_installed
+ else:
+ grok_stored = (
+ grok_x.AUTH_MISSING,
+ "no Grok credential store at ~/.grok/auth.json",
+ None,
+ )
+ grok_available = False
return (
mock.patch("lib.bird_x.is_bird_installed", return_value=bird_installed),
mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None),
@@ -92,9 +111,9 @@ def _x_env(
mock.patch("lib.grok_x.stored_auth_status", return_value=grok_stored),
mock.patch(
"lib.grok_x.has_stored_auth",
- return_value=grok_installed and grok_authed,
+ return_value=grok_installed and (grok_authed or grok_expired),
),
- mock.patch("lib.grok_x.is_available", return_value=grok_installed and grok_authed),
+ mock.patch("lib.grok_x.is_available", return_value=grok_available),
mock.patch("lib.health.probe_dependency", _probe_dep({"node": node_status})),
mock.patch("lib.xurl_x.stored_auth_status", return_value=stored),
mock.patch(
@@ -265,6 +284,75 @@ class TestXPrediction:
assert bird.status == health.BROKEN
assert "node" in bird.prescription.lower()
+ def test_grok_expired_is_degraded_not_ok(self):
+ """Expired grok session -> DEGRADED tier (warn), not OK."""
+ res = _resolve_x({}, grok_installed=True, grok_expired=True)
+ grok = next(f for f in res.findings if f.name == "grok")
+ assert grok.status == health.DEGRADED
+ assert grok.usable # DEGRADED is still usable (refresh may work)
+ assert "expired" in grok.detail.lower()
+ assert "grok login" in grok.prescription.lower()
+ # The chain resolution should still pick grok (degraded is usable).
+ assert res.active_backend == "grok"
+ assert res.tier == backends.TIER_WARN
+
+ def test_grok_expired_with_fallback_picks_fallback(self):
+ """When grok is expired AND a better backend is OK, pick the OK one."""
+ config = {"AUTH_TOKEN": "dummy-token", "CT0": "dummy-ct0"}
+ res = _resolve_x(config, grok_installed=True, grok_expired=True, bird_installed=True)
+ # Bird is OK, grok is DEGRADED. OK wins over DEGRADED.
+ assert res.active_backend == "bird"
+ assert res.tier == backends.TIER_OK
+
+ def test_grok_future_expires_at_is_ok(self):
+ """Grok with future expires_at reports OK."""
+ res = _resolve_x({}, grok_installed=True, grok_authed=True)
+ grok = next(f for f in res.findings if f.name == "grok")
+ assert grok.status == health.OK
+ assert "not live-verified" in grok.detail
+
+
+# ---------------------------------------------------------------------------
+# Grok session expiry: three states
+# ---------------------------------------------------------------------------
+
+class TestGrokExpiryStates:
+ """Test the three grok auth states from the plan:
+ 1. No grok CLI -> silent fallback
+ 2. CLI installed, never logged in -> silent fallback
+ 3. CLI installed, WAS logged in, session dead -> DEGRADED with expiry info
+ """
+
+ def test_no_grok_cli_is_missing(self):
+ """No grok CLI -> MISSING status, no extra failure noise."""
+ res = _resolve_x({}, grok_installed=False)
+ grok = next(f for f in res.findings if f.name == "grok")
+ assert grok.status == health.MISSING
+ assert "not found on PATH" in grok.detail
+
+ def test_grok_installed_never_logged_in_is_missing(self):
+ """CLI installed but never logged in -> MISSING with login hint."""
+ res = _resolve_x({}, grok_installed=True, grok_authed=False)
+ grok = next(f for f in res.findings if f.name == "grok")
+ assert grok.status == health.MISSING
+ assert "not signed in" in grok.detail
+ assert "grok login" in grok.prescription
+
+ def test_grok_session_expired_is_degraded_with_expiry(self):
+ """Session expired -> DEGRADED with timestamp and refresh hint."""
+ res = _resolve_x({}, grok_installed=True, grok_expired=True)
+ grok = next(f for f in res.findings if f.name == "grok")
+ assert grok.status == health.DEGRADED
+ assert "expired" in grok.detail.lower()
+ # The detail should include the expiry timestamp and hint
+ assert "refresh" in grok.detail.lower() or "login" in grok.prescription.lower()
+
+ def test_grok_healthy_session_is_ok(self):
+ """Non-expired credentials -> OK."""
+ res = _resolve_x({}, grok_installed=True, grok_authed=True)
+ grok = next(f for f in res.findings if f.name == "grok")
+ assert grok.status == health.OK
+
# ---------------------------------------------------------------------------
# Scenario 5: paid lanes probe key presence only — never network/subprocess
diff --git a/tests/test_grok_x.py b/tests/test_grok_x.py
index a75b3a90..3d5d3f54 100644
--- a/tests/test_grok_x.py
+++ b/tests/test_grok_x.py
@@ -240,8 +240,9 @@ def test_non_execution_is_retried(monkeypatch):
monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
- items, error = grok_x._run_query("steipete", *WINDOW)
+ items, error, auth_revoked = grok_x._run_query("steipete", *WINDOW)
assert calls["n"] == 2, "a provenance rejection must be retried once"
+ assert not auth_revoked
assert len(items) == 1 and not error
@@ -259,8 +260,9 @@ def test_stored_auth_status_makes_no_subprocess_or_network(monkeypatch):
def test_stored_auth_status_reports_missing_store(monkeypatch, tmp_path):
monkeypatch.setattr(grok_x, "token_store_path", lambda: tmp_path / "nope.json")
- status, detail = grok_x.stored_auth_status()
+ status, detail, expires_at = grok_x.stored_auth_status()
assert status == grok_x.AUTH_MISSING and "nope.json" in detail
+ assert expires_at is None
def test_stored_auth_status_detects_credentials(monkeypatch, tmp_path):
@@ -275,7 +277,7 @@ def test_stored_auth_status_never_echoes_store_contents(monkeypatch, tmp_path):
store = tmp_path / "auth.json"
store.write_text('{"key": "SUPER-SECRET-VALUE", "refresh_token": "ALSO-SECRET"}')
monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
- _, detail = grok_x.stored_auth_status()
+ _, detail, _ = grok_x.stored_auth_status()
assert "SUPER-SECRET-VALUE" not in detail and "ALSO-SECRET" not in detail
@@ -291,6 +293,129 @@ def test_unreadable_store_is_an_error(monkeypatch, tmp_path):
assert grok_x.stored_auth_status()[0] == grok_x.AUTH_ERROR
+# --- expires_at parsing -----------------------------------------------------
+
+def test_stored_auth_status_future_expires_at_is_ok(monkeypatch, tmp_path):
+ """Credentials with expires_at in the future report AUTH_OK."""
+ from datetime import datetime, timezone, timedelta
+ future = (datetime.now(timezone.utc) + timedelta(hours=2)).isoformat()
+ store = tmp_path / "auth.json"
+ store.write_text(f'{{"iss": {{"refresh_token": "tok", "expires_at": "{future}"}}}}')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ status, detail, expires_at = grok_x.stored_auth_status()
+ assert status == grok_x.AUTH_OK
+ assert expires_at is not None
+
+
+def test_stored_auth_status_past_expires_at_is_expired(monkeypatch, tmp_path):
+ """Credentials with expires_at in the past report AUTH_EXPIRED, not AUTH_OK."""
+ from datetime import datetime, timezone, timedelta
+ past = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
+ store = tmp_path / "auth.json"
+ store.write_text(f'{{"iss": {{"refresh_token": "tok", "expires_at": "{past}"}}}}')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ status, detail, expires_at = grok_x.stored_auth_status()
+ assert status == grok_x.AUTH_EXPIRED
+ assert "expired" in detail.lower()
+ assert expires_at is not None
+
+
+def test_stored_auth_status_no_expires_at_is_ok(monkeypatch, tmp_path):
+ """Credentials without expires_at default to AUTH_OK (legacy stores)."""
+ store = tmp_path / "auth.json"
+ store.write_text('{"iss": {"refresh_token": "tok"}}')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ status, _, expires_at = grok_x.stored_auth_status()
+ assert status == grok_x.AUTH_OK
+ assert expires_at is None
+
+
+def test_stored_auth_status_unparseable_json_is_ok_with_markers(monkeypatch, tmp_path):
+ """Malformed JSON with credential markers reports AUTH_OK (graceful degradation)."""
+ store = tmp_path / "auth.json"
+ store.write_text('{"refresh_token": "tok" this is not valid json')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ status, _, _ = grok_x.stored_auth_status()
+ assert status == grok_x.AUTH_OK
+
+
+def test_stored_auth_status_unparseable_expires_at_is_ok(monkeypatch, tmp_path):
+ """Malformed expires_at is ignored, status is AUTH_OK."""
+ store = tmp_path / "auth.json"
+ store.write_text('{"iss": {"refresh_token": "tok", "expires_at": "not-a-date"}}')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ status, _, expires_at = grok_x.stored_auth_status()
+ assert status == grok_x.AUTH_OK
+ assert expires_at is None
+
+
+def test_stored_auth_status_z_suffix_parses_correctly(monkeypatch, tmp_path):
+ """ISO 8601 timestamps with Z suffix parse correctly."""
+ from datetime import datetime, timezone, timedelta
+ past = (datetime.now(timezone.utc) - timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ store = tmp_path / "auth.json"
+ store.write_text(f'{{"iss": {{"refresh_token": "tok", "expires_at": "{past}"}}}}')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ status, _, _ = grok_x.stored_auth_status()
+ assert status == grok_x.AUTH_EXPIRED
+
+
+def test_has_stored_auth_true_when_expired(monkeypatch, tmp_path):
+ """has_stored_auth returns True even when expired (refresh may work)."""
+ from datetime import datetime, timezone, timedelta
+ past = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
+ store = tmp_path / "auth.json"
+ store.write_text(f'{{"iss": {{"refresh_token": "tok", "expires_at": "{past}"}}}}')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+ assert grok_x.has_stored_auth() is True
+
+
+def test_is_available_true_when_expired(monkeypatch, tmp_path):
+ """is_available returns True when expired (CLI will try refresh at runtime)."""
+ from datetime import datetime, timezone, timedelta
+ past = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
+ store = tmp_path / "auth.json"
+ store.write_text(f'{{"iss": {{"refresh_token": "tok", "expires_at": "{past}"}}}}')
+ monkeypatch.setattr(grok_x, "token_store_path", lambda: store)
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+ grok_x.clear_availability_cache()
+ assert grok_x.is_available() is True
+
+
+# --- auth revocation detection ----------------------------------------------
+
+def test_is_auth_revoked_error_detects_markers():
+ """Auth revocation markers are detected."""
+ assert grok_x.is_auth_revoked_error("Not signed in")
+ assert grok_x.is_auth_revoked_error("invalid_grant: Refresh token has been revoked")
+ assert grok_x.is_auth_revoked_error("Authentication failed")
+ assert grok_x.is_auth_revoked_error("grok CLI exited 1: not logged in")
+ assert not grok_x.is_auth_revoked_error("timed out after 30s")
+ assert not grok_x.is_auth_revoked_error("")
+
+
+def test_classify_run_failure_returns_auth_failed_for_revocation():
+ """classify_run_failure maps revocation errors to AUTH_FAILED."""
+ from lib import health
+ assert grok_x.classify_run_failure("Not signed in") == health.AUTH_FAILED
+ assert grok_x.classify_run_failure("invalid_grant") == health.AUTH_FAILED
+ assert grok_x.classify_run_failure("timed out") == health.TIMEOUT
+ assert grok_x.classify_run_failure("some other error") == health.ERROR
+
+
+def test_search_x_returns_auth_revoked_on_session_failure(monkeypatch):
+ """search_x returns auth_revoked when the session is revoked mid-run."""
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+ monkeypatch.setattr(
+ grok_x.subprocess, "run",
+ lambda cmd, **kw: subprocess.CompletedProcess(cmd, 1, "", "Not signed in"),
+ )
+ result = grok_x.search_x("test topic", *WINDOW)
+ assert result.get("auth_revoked") is True
+ assert "error" in result
+
+
def test_availability_cache_is_resettable(monkeypatch):
monkeypatch.setattr(grok_x, "_is_available_uncached", lambda: True)
assert grok_x.is_available() is True
@@ -314,12 +439,16 @@ def test_from_lane_filters_by_actual_author(monkeypatch):
"""Operator fidelity is not guaranteed: a measured from: query returned a
post by a different account."""
_stub_response(monkeypatch, _block("2087568620465607078", handle="leojr94_"))
- assert grok_x.search_handles(["steipete"], "topic", *WINDOW) == []
+ items, revoked = grok_x.search_handles(["steipete"], "topic", *WINDOW)
+ assert items == []
+ assert revoked is False
def test_from_lane_keeps_matching_author(monkeypatch):
_stub_response(monkeypatch, _block("2087568620465607078", handle="steipete"))
- assert len(grok_x.search_handles(["steipete"], "topic", *WINDOW)) == 1
+ items, revoked = grok_x.search_handles(["steipete"], "topic", *WINDOW)
+ assert len(items) == 1
+ assert revoked is False
def test_from_lane_does_not_and_the_topic_into_the_query(monkeypatch):
@@ -338,13 +467,16 @@ def test_from_lane_does_not_and_the_topic_into_the_query(monkeypatch):
def test_mention_lane_excludes_the_subject_client_side(monkeypatch):
"""A measured run carrying -from:X still returned a post authored by X."""
_stub_response(monkeypatch, _block("2087568620465607078", handle="GetEnergy_"))
- assert grok_x.search_mentions(["GetEnergy_"], *WINDOW) == []
+ items, revoked = grok_x.search_mentions(["GetEnergy_"], *WINDOW)
+ assert items == []
+ assert revoked is False
def test_name_lane_needs_no_handle(monkeypatch):
_stub_response(monkeypatch, _block("2087568620465607078", handle="iamcaroren"))
- items = grok_x.search_name("Bentgo", *WINDOW)
+ items, revoked = grok_x.search_name("Bentgo", *WINDOW)
assert len(items) == 1
+ assert revoked is False
def test_name_lane_quotes_multi_word_names(monkeypatch):
@@ -362,7 +494,9 @@ def test_name_lane_quotes_multi_word_names(monkeypatch):
def test_name_lane_excludes_subject_authored_posts(monkeypatch):
_stub_response(monkeypatch, _block("2087568620465607078", handle="Bentgo"))
- assert grok_x.search_name("Bentgo", *WINDOW, exclude_handles=["Bentgo"]) == []
+ items, revoked = grok_x.search_name("Bentgo", *WINDOW, exclude_handles=["Bentgo"])
+ assert items == []
+ assert revoked is False
def test_name_lane_applies_an_engagement_floor(monkeypatch):
@@ -381,6 +515,70 @@ def test_name_lane_applies_an_engagement_floor(monkeypatch):
)
+# --- lane revocation propagation -------------------------------------------
+
+def test_from_lane_returns_revoked_on_auth_failure(monkeypatch):
+ """search_handles should return (items, True) when auth is revoked mid-lane."""
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+
+ def fake_run(cmd, **kwargs):
+ return subprocess.CompletedProcess(cmd, 1, "", "Error: Not signed in")
+
+ monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
+ items, revoked = grok_x.search_handles(["steipete"], "topic", *WINDOW)
+ assert revoked is True
+ assert items == []
+
+
+def test_mention_lane_returns_revoked_on_auth_failure(monkeypatch):
+ """search_mentions should return (items, True) when auth is revoked."""
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+
+ def fake_run(cmd, **kwargs):
+ return subprocess.CompletedProcess(cmd, 1, "", "Error: Not signed in")
+
+ monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
+ items, revoked = grok_x.search_mentions(["steipete"], *WINDOW)
+ assert revoked is True
+ assert items == []
+
+
+def test_name_lane_returns_revoked_on_auth_failure(monkeypatch):
+ """search_name should return (items, True) when auth is revoked."""
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+
+ def fake_run(cmd, **kwargs):
+ return subprocess.CompletedProcess(cmd, 1, "", "Error: Not signed in")
+
+ monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
+ items, revoked = grok_x.search_name("Bentgo", *WINDOW)
+ assert revoked is True
+ assert items == []
+
+
+def test_from_lane_preserves_items_collected_before_revocation(monkeypatch):
+ """Items collected before auth revocation should be returned with revoked=True."""
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+ call_count = {"n": 0}
+
+ def fake_run(cmd, **kwargs):
+ call_count["n"] += 1
+ if call_count["n"] == 1:
+ # First handle succeeds
+ return subprocess.CompletedProcess(
+ cmd, 0, _block("2087568620465607078", handle="steipete"), ""
+ )
+ else:
+ # Second handle hits auth revocation
+ return subprocess.CompletedProcess(cmd, 1, "", "Error: Not signed in")
+
+ monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
+ items, revoked = grok_x.search_handles(["steipete", "other"], "topic", *WINDOW)
+ # Should return items from first successful call AND signal revocation
+ assert len(items) == 1
+ assert items[0]["author_handle"] == "steipete"
+ assert revoked is True
+
# --- fixes applied after review --------------------------------------------
diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.py
index a509d582..512f92e8 100644
--- a/tests/test_pipeline_v3.py
+++ b/tests/test_pipeline_v3.py
@@ -684,6 +684,217 @@ class TestXBackendChainAndFailover(unittest.TestCase):
self.assertNotIn("xquik", avail)
+class TestMixedResultRevocation(unittest.TestCase):
+ """Mixed-result revocation: when grok returns items AND an error, preserve both."""
+
+ @patch("lib.env.x_backend_chain", return_value=["grok"])
+ def test_items_with_auth_error_surfaces_error(self, _chain):
+ """Grok returns some items but then auth is revoked → error is surfaced."""
+ sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
+
+ def fake_fetch(backend, *a, **k):
+ if backend == "grok":
+ # Mixed result: got some items, but also hit auth revocation
+ return (
+ [{"id": "G1", "url": "https://x.com/a/status/1"}],
+ "grok: grok session expired or was revoked",
+ )
+ return ([], "")
+
+ with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
+ items, artifact = 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))
+ # The artifact should have _source_outcome with the error info
+ outcome = artifact.get("_source_outcome", {})
+ self.assertIn("grok session expired", outcome.get("detail", "").lower())
+ # State should be AUTH_FAILED since the error contains auth markers
+ self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
+
+ @patch("lib.env.x_backend_chain", return_value=["grok", "bird"])
+ def test_fallback_after_auth_failed_keeps_auth_failed_state(self, _chain):
+ """Grok auth fails → bird succeeds → state is AUTH_FAILED (not OK).
+
+ The user needs re-login guidance for grok even though fallback served items.
+ """
+ sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
+
+ def fake_fetch(backend, *a, **k):
+ if backend == "grok":
+ return ([], "grok: grok session expired or was revoked")
+ if backend == "bird":
+ return ([{"id": "B1", "url": "https://x.com/a/status/1"}], "")
+ return ([], "")
+
+ with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
+ items, artifact = 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))
+ outcome = artifact.get("_source_outcome", {})
+ # State should be AUTH_FAILED so user gets re-login guidance
+ self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
+ self.assertIn("re-login", outcome.get("detail", "").lower())
+
+ @patch("lib.env.x_backend_chain", return_value=["grok", "bird"])
+ def test_fallback_after_non_auth_error_is_ok(self, _chain):
+ """Grok fails with non-auth error → bird succeeds → state is OK."""
+ sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
+
+ def fake_fetch(backend, *a, **k):
+ if backend == "grok":
+ return ([], "grok: network timeout")
+ if backend == "bird":
+ return ([{"id": "B1", "url": "https://x.com/a/status/1"}], "")
+ return ([], "")
+
+ with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
+ items, artifact = 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))
+ outcome = artifact.get("_source_outcome", {})
+ # Non-auth error followed by fallback success is OK
+ self.assertEqual("ok", outcome.get("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):
+ """Bird non-auth fail → Grok items + revocation → AUTH_FAILED, items kept.
+
+ If an earlier backend fails for a non-auth reason and the current backend
+ returns items plus an auth revocation error, the outcome must be AUTH_FAILED
+ (not OK) so the user gets re-login guidance.
+ """
+ sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
+
+ def fake_fetch(backend, *a, **k):
+ if backend == "bird":
+ # Bird fails with a non-auth error
+ return ([], "bird: network timeout")
+ if backend == "grok":
+ # Grok returns items but also signals auth revocation
+ return (
+ [{"id": "G1", "url": "https://x.com/a/status/1"}],
+ "grok: grok session expired or was revoked",
+ )
+ return ([], "")
+
+ with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
+ items, artifact = 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,
+ )
+ # Items should be preserved
+ self.assertEqual(1, len(items))
+ outcome = artifact.get("_source_outcome", {})
+ # State must be AUTH_FAILED, not OK
+ self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
+ # Re-login guidance must be present
+ self.assertIn("re-login", outcome.get("detail", "").lower())
+
+ @patch("lib.env.x_backend_chain", return_value=["grok", "bird"])
+ def test_not_logged_in_triggers_auth_failed_fallback(self, _chain):
+ """Grok 'not logged in' → bird fallback → AUTH_FAILED state preserved.
+
+ The 'not logged in' message from Grok is a recognized revocation marker.
+ If Grok fails with this message and bird fallback succeeds, the outcome
+ must be AUTH_FAILED so the user gets re-login guidance.
+ """
+ sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
+
+ def fake_fetch(backend, *a, **k):
+ if backend == "grok":
+ # Grok fails with 'not logged in' error
+ return ([], "grok: not logged in")
+ if backend == "bird":
+ return ([{"id": "B1", "url": "https://x.com/a/status/1"}], "")
+ return ([], "")
+
+ with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
+ items, artifact = 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))
+ outcome = artifact.get("_source_outcome", {})
+ # State must be AUTH_FAILED because 'not logged in' is an auth marker
+ self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
+ self.assertIn("re-login", outcome.get("detail", "").lower())
+
+
+class TestRetrievalBundleAuthPreservation(unittest.TestCase):
+ """AUTH_FAILED state must be preserved through add_items.
+
+ When a lane records AUTH_FAILED before items are added, the state
+ must not be downgraded to PARTIAL by subsequent add_items calls.
+ """
+
+ def test_add_items_preserves_auth_failed_state(self):
+ """add_items should preserve AUTH_FAILED state, not downgrade to PARTIAL."""
+ bundle = schema.RetrievalBundle()
+ bundle.mark_attempted("x")
+ # First: record auth failure (no items yet)
+ bundle.record_failure("x", schema.AUTH_FAILED, "grok session expired", attempted=True)
+ # At this point, state should be AUTH_FAILED
+ self.assertEqual(schema.AUTH_FAILED, bundle.source_status["x"].state)
+
+ # Now add items
+ items = [_make_source_item("x", "X1", "https://x.com/a/status/1")]
+ bundle.add_items("primary", "x", items)
+
+ # State must still be AUTH_FAILED, not PARTIAL
+ self.assertEqual(schema.AUTH_FAILED, bundle.source_status["x"].state)
+ # Detail should be preserved
+ self.assertEqual("grok session expired", bundle.source_status["x"].detail)
+ # Items should be recorded
+ self.assertEqual(1, len(bundle.items_by_source["x"]))
+
+ def test_add_items_keeps_partial_for_non_auth_failures(self):
+ """For non-auth failures, add_items should still produce PARTIAL."""
+ bundle = schema.RetrievalBundle()
+ bundle.mark_attempted("x")
+ # Record a non-auth failure
+ bundle.record_failure("x", health.TIMEOUT, "request timed out", attempted=True)
+ self.assertEqual(health.TIMEOUT, bundle.source_status["x"].state)
+
+ # Add items
+ items = [_make_source_item("x", "X1", "https://x.com/a/status/1")]
+ bundle.add_items("primary", "x", items)
+
+ # State should become PARTIAL (not TIMEOUT)
+ self.assertEqual(schema.PARTIAL, bundle.source_status["x"].state)
+ # Detail should be preserved
+ self.assertEqual("request timed out", bundle.source_status["x"].detail)
+
+ def test_record_failure_preserves_auth_failed_when_items_exist(self):
+ """record_failure should preserve AUTH_FAILED even when items already exist.
+
+ When Phase 1 has already collected X posts and a supplemental Grok lane
+ reports revocation, record_failure must not convert AUTH_FAILED to PARTIAL.
+ """
+ bundle = schema.RetrievalBundle()
+ bundle.mark_attempted("x")
+
+ # Phase 1 already collected items
+ phase1_items = [_make_source_item("x", "X1", "https://x.com/a/status/1")]
+ bundle.add_items("primary", "x", phase1_items)
+ self.assertEqual(health.OK, bundle.source_status["x"].state)
+
+ # Supplemental lane reports auth failure
+ bundle.record_failure("x", schema.AUTH_FAILED, "grok session revoked", attempted=True)
+
+ # State must be AUTH_FAILED, not PARTIAL
+ self.assertEqual(schema.AUTH_FAILED, bundle.source_status["x"].state)
+ # Detail should be set
+ self.assertEqual("grok session revoked", bundle.source_status["x"].detail)
+ # Items should still be there
+ self.assertEqual(1, len(bundle.items_by_source["x"]))
+
+
class TestSupplementalSearches(unittest.TestCase):
"""R1: Phase 2 entity drilling should be wired into the pipeline."""
diff --git a/tests/test_x_chain_failover.py b/tests/test_x_chain_failover.py
index c01b0d9b..76d7dced 100644
--- a/tests/test_x_chain_failover.py
+++ b/tests/test_x_chain_failover.py
@@ -80,10 +80,11 @@ def test_lane_budget_stops_issuing_queries(monkeypatch):
monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
past = _time.monotonic() - 1
- got = grok_x.search_handles(
+ items, revoked = grok_x.search_handles(
["a", "b", "c"], "topic", "2026-07-14", "2026-08-13", deadline=past
)
- assert got == []
+ assert items == []
+ assert revoked is False
assert calls["n"] == 0, "an expired budget must stop the lane before any call"
@@ -103,9 +104,10 @@ def test_clean_empty_is_not_retried(monkeypatch):
return subprocess.CompletedProcess(cmd, 0, "The search returned no posts.", "")
monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
- items, error = grok_x._run_query("topic", "2026-07-14", "2026-08-13")
+ items, error, auth_revoked = grok_x._run_query("topic", "2026-07-14", "2026-08-13")
assert items == [] and error == ""
assert calls["n"] == 1, "a clean empty result must not be retried"
+ assert not auth_revoked
def test_fabricated_response_is_still_retried(monkeypatch):
@@ -185,9 +187,10 @@ def test_a_call_is_not_started_when_it_cannot_finish_in_budget(monkeypatch):
monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
# 5s left: below the minimum useful call, so nothing should start.
near = _time.monotonic() + 5
- items, error = grok_x._run_query("topic", "2026-07-14", "2026-08-13", deadline=near)
+ items, error, auth_revoked = grok_x._run_query("topic", "2026-07-14", "2026-08-13", deadline=near)
assert calls["n"] == 0
assert "budget exhausted" in error
+ assert not auth_revoked
def test_timeout_never_exceeds_the_remaining_budget(monkeypatch):