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(x): honest --diagnose (real probe + true auth lane) + non-silent handle log (#609)

Matt Van Hornfbc828ad4aed
diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.py
index 91853488..b7ea5d34 100644
--- a/skills/last30days/scripts/lib/bird_x.py
+++ b/skills/last30days/scripts/lib/bird_x.py
@@ -115,6 +115,40 @@ def is_bird_authenticated() -> Optional[str]:
return None
+_probe_cache: Optional[Optional[bool]] = "unset" # "unset" | True | False | None
+
+
+def probe_works(timeout: int = 8) -> Optional[bool]:
+ """Cheap runtime check that X auth actually returns data.
+
+ Returns True when a 1-result probe comes back without an error, False on a
+ clear failure (auth error / generic search failure), and None when the
+ result is inconclusive (network timeout) so callers can fail open and keep
+ the static credential-presence status rather than reporting a false-down.
+ Cached per process so repeated diagnose calls don't re-probe.
+ """
+ global _probe_cache
+ if _probe_cache != "unset":
+ return _probe_cache # type: ignore[return-value]
+ if not (_has_injected_credentials() or _has_process_credentials()):
+ _probe_cache = False
+ return False
+ from datetime import datetime, timedelta, timezone
+ since = (datetime.now(timezone.utc) - timedelta(days=30)).strftime("%Y-%m-%d")
+ # @x (the platform's own account) posts frequently, so a no-error response
+ # means auth works even if this particular window is quiet.
+ resp = _run_bird_search(f"from:x since:{since}", count=1, timeout=timeout)
+ if isinstance(resp, dict) and resp.get("error"):
+ err = str(resp.get("error")).lower()
+ if "timed out" in err or "timeout" in err:
+ _probe_cache = None # inconclusive — don't downgrade on a transient timeout
+ return None
+ _probe_cache = False
+ return False
+ _probe_cache = True
+ return True
+
+
def check_npm_available() -> bool:
"""Check if npm is available (kept for API compatibility).
@@ -410,7 +444,11 @@ def search_handles(
except json.JSONDecodeError:
_log(f"Invalid JSON from handle search for @{handle}")
return []
- return parse_bird_response(response, query=core_topic)
+ items = parse_bird_response(response, query=core_topic)
+ # Log on success/empty too (not only on failure): a silent handle search
+ # made the from: query look like it never ran and caused wrong diagnoses.
+ _log(f"Searching: {query} -> {len(items)} results")
+ return items
from concurrent.futures import ThreadPoolExecutor, as_completed
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 8245254c..ba625ea5 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -833,9 +833,16 @@ def is_xiaohongshu_available(config: dict[str, Any]) -> bool:
is_apify_available = is_tiktok_available
-def get_x_source_status(config: dict[str, Any]) -> dict[str, Any]:
+def get_x_source_status(config: dict[str, Any], probe: bool = False) -> dict[str, Any]:
"""Get detailed X source status for UI decisions.
+ Args:
+ probe: when True, run a cheap 1-tweet bird probe and downgrade
+ ``bird_authenticated`` to False when X clearly returns nothing,
+ so ``--diagnose`` reflects runtime reality instead of static
+ credential presence. A transient timeout leaves the status
+ unchanged (fail open).
+
Returns:
Dict with keys: source, bird_installed, bird_authenticated,
bird_username, xai_available, can_install_bird
@@ -847,6 +854,19 @@ def get_x_source_status(config: dict[str, Any]) -> dict[str, Any]:
bird_status = bird_x.get_bird_status()
xai_available = bool(config.get('XAI_API_KEY'))
+ # Report the TRUE auth lane (browser / env / keychain) rather than the static
+ # "env AUTH_TOKEN" label — tokens usually come from live browser cookies, and
+ # mislabeling the lane sent past debugging down a 30-minute wrong path.
+ if bird_status["authenticated"]:
+ lane = config.get('_AUTH_TOKEN_SOURCE') or 'env'
+ bird_status["username"] = f"{lane} AUTH_TOKEN"
+
+ # Optional runtime probe: don't show X green when it's effectively dead.
+ if probe and bird_status["authenticated"]:
+ if bird_x.probe_works() is False:
+ bird_status["authenticated"] = False
+ bird_status["username"] = "probe failed (no working X auth)"
+
# Determine active source
if bird_status["authenticated"]:
source = 'bird'
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 8106b6cf..f7c02773 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -154,7 +154,7 @@ def available_sources(config: dict[str, Any], requested_sources: list[str] | Non
def diagnose(config: dict[str, Any], requested_sources: list[str] | None = None) -> dict[str, Any]:
requested_sources = normalize_requested_sources(requested_sources)
google_key = _google_key(config)
- x_status = env.get_x_source_status(config)
+ x_status = env.get_x_source_status(config, probe=True)
native_web_backend = None
if config.get("BRAVE_API_KEY"):
native_web_backend = "brave"
diff --git a/tests/test_bird_x.py b/tests/test_bird_x.py
index 92d6cdb7..bf64a276 100644
--- a/tests/test_bird_x.py
+++ b/tests/test_bird_x.py
@@ -304,6 +304,98 @@ if __name__ == "__main__":
unittest.main()
+class TestProbeAndDiagnoseHonesty(unittest.TestCase):
+ """U5: --diagnose probe + true auth lane; X is not reported green when dead."""
+
+ def setUp(self):
+ from lib import bird_x
+ bird_x._probe_cache = "unset"
+ bird_x._credentials = {"AUTH_TOKEN": "t", "CT0": "c"} # injected creds present
+
+ def tearDown(self):
+ from lib import bird_x
+ bird_x._probe_cache = "unset"
+ bird_x._credentials = {}
+
+ def test_probe_true_when_response_ok(self):
+ from unittest import mock
+ from lib import bird_x
+ with mock.patch.object(bird_x, "_run_bird_search", return_value={"items": [{"id": "1"}]}):
+ self.assertTrue(bird_x.probe_works())
+
+ def test_probe_false_on_auth_error(self):
+ from unittest import mock
+ from lib import bird_x
+ with mock.patch.object(bird_x, "_run_bird_search",
+ return_value={"error": "Missing auth_token", "items": []}):
+ self.assertIs(bird_x.probe_works(), False)
+
+ def test_probe_none_on_timeout_inconclusive(self):
+ from unittest import mock
+ from lib import bird_x
+ with mock.patch.object(bird_x, "_run_bird_search",
+ return_value={"error": "Search timed out after 8s", "items": []}):
+ self.assertIsNone(bird_x.probe_works())
+
+ def test_probe_false_when_no_credentials(self):
+ from unittest import mock
+ from lib import bird_x
+ bird_x._credentials = {}
+ with mock.patch.dict(os.environ, {}, clear=True):
+ self.assertIs(bird_x.probe_works(), False)
+
+ def test_probe_cached_per_process(self):
+ from unittest import mock
+ from lib import bird_x
+ with mock.patch.object(bird_x, "_run_bird_search",
+ return_value={"items": [{"id": "1"}]}) as m:
+ bird_x.probe_works()
+ bird_x.probe_works()
+ self.assertEqual(m.call_count, 1) # cached, not re-run
+
+ def test_get_x_source_status_reports_true_lane(self):
+ from unittest import mock
+ from lib import env, bird_x
+ cfg = {"AUTH_TOKEN": "t", "CT0": "c", "_AUTH_TOKEN_SOURCE": "browser"}
+ with mock.patch.object(bird_x, "get_bird_status",
+ return_value={"installed": True, "authenticated": True,
+ "username": "env AUTH_TOKEN", "can_install": True}):
+ status = env.get_x_source_status(cfg, probe=False)
+ self.assertEqual(status["bird_username"], "browser AUTH_TOKEN")
+
+ def test_diagnose_probe_downgrades_when_dead(self):
+ from unittest import mock
+ from lib import env, bird_x
+ cfg = {"AUTH_TOKEN": "t", "CT0": "c", "_AUTH_TOKEN_SOURCE": "browser"}
+ with mock.patch.object(bird_x, "get_bird_status",
+ return_value={"installed": True, "authenticated": True,
+ "username": "env AUTH_TOKEN", "can_install": True}), \
+ mock.patch.object(bird_x, "probe_works", return_value=False):
+ status = env.get_x_source_status(cfg, probe=True)
+ self.assertFalse(status["bird_authenticated"])
+ self.assertIn("no working X auth", status["bird_username"])
+
+
+class TestHandleSearchLogsOnSuccess(unittest.TestCase):
+ """U6: handle searches log query + count on success, not only on failure."""
+
+ def test_search_handles_logs_on_success(self):
+ from unittest import mock
+ from lib import bird_x
+
+ class _R:
+ returncode = 0
+ stdout = '{"items": [{"id": "1"}]}'
+ stderr = ""
+
+ logged = []
+ with mock.patch.object(bird_x.subproc, "run_with_timeout", return_value=_R()), \
+ mock.patch.object(bird_x, "_log", side_effect=lambda m: logged.append(m)):
+ bird_x.search_handles(["mvanhorn"], "matt van horn", "2026-05-19", count_per=1)
+ self.assertTrue(any("Searching:" in m for m in logged),
+ f"expected a Searching: log on success, got {logged}")
+
+
class TestStrongestTokenRetryAnchored(unittest.TestCase):
"""The last-chance retry must keep an entity anchor, not collapse to a bare
generic token (e.g. 'compound') that floods the X pool with off-topic noise.