Skip to content

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

feat(doctor): bounded live probe (--probe + no-run auto-fallback) (U5)

Matt Van Horne4f7e9b1759c
diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.py
index 8d1f7805..f1c2ca8f 100644
--- a/skills/last30days/scripts/lib/doctor.py
+++ b/skills/last30days/scripts/lib/doctor.py
@@ -48,6 +48,8 @@ import json
import os
import shutil
import sys
+import urllib.error
+import urllib.request
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
@@ -1456,6 +1458,126 @@ def _write_cache(report: Dict[str, Any], config: Dict[str, Any]) -> bool:
return False
+# ---------------------------------------------------------------------------
+# Live probe (U5 / R6)
+#
+# When there is no fresh run to learn from (or on explicit --probe), doctor
+# runs a BOUNDED live test so WORKING is verified, not guessed. Scope is
+# deliberate: free HTTP endpoints + keyless CLIs only. Credit-gated /
+# session-gated sources (x, tiktok, instagram, threads, ...) are NOT
+# live-probed - a health check must never spend ScrapeCreators credits or trip
+# auth rate limits; they stay UNVERIFIED with that noted. Every probe is capped
+# by a per-source deadline so a single slow source (YouTube's 120s search) can
+# never hang doctor.
+# ---------------------------------------------------------------------------
+
+# Free, keyless liveness endpoints (reachability check, tiny payload).
+_HTTP_PROBE_URLS = {
+ "reddit": "https://www.reddit.com/r/all/hot.json?limit=1",
+ "hackernews": "https://hn.algolia.com/api/v1/search?query=test&hitsPerPage=1",
+ "polymarket": "https://gamma-api.polymarket.com/events?limit=1",
+ "github": "https://api.github.com/rate_limit",
+}
+
+DEFAULT_PROBE_TIMEOUT_SECONDS = 10
+
+
+def probe_timeout_seconds(config: Dict[str, Any]) -> int:
+ """Per-source probe deadline; process env > config > default 10s."""
+ raw: Any = os.environ.get("LAST30DAYS_DOCTOR_PROBE_TIMEOUT")
+ if raw is None:
+ raw = (config or {}).get("LAST30DAYS_DOCTOR_PROBE_TIMEOUT")
+ if raw is None or raw == "":
+ return DEFAULT_PROBE_TIMEOUT_SECONDS
+ try:
+ return max(1, int(raw))
+ except (TypeError, ValueError):
+ return DEFAULT_PROBE_TIMEOUT_SECONDS
+
+
+def _probeable_sources() -> tuple:
+ """Sources doctor will live-probe: free HTTP endpoints + keyless CLIs.
+
+ github is HTTP-probed (its REST tier works without gh), so it is excluded
+ from the CLI-probe path even though gh is in CLI_DEPENDENCIES.
+ """
+ cli_only = [s for s in CLI_DEPENDENCIES if s not in _HTTP_PROBE_URLS]
+ return tuple(dict.fromkeys(list(_HTTP_PROBE_URLS) + cli_only))
+
+
+def _http_ok(url: str, timeout: float) -> tuple:
+ """Reachability check: a 4xx still means the endpoint responded; 5xx or a
+ connection/timeout error means it did not."""
+ try:
+ req = urllib.request.Request(
+ url, headers={"User-Agent": "last30days-doctor"}
+ )
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ code = getattr(resp, "status", 200) or 200
+ return code < 500, f"HTTP {code}"
+ except urllib.error.HTTPError as exc:
+ return exc.code < 500, f"HTTP {exc.code}"
+ except Exception as exc:
+ return False, f"{type(exc).__name__}: {exc}"
+
+
+def _probe_source(name: str, config: Dict[str, Any], timeout: float) -> Optional[Dict[str, Any]]:
+ url = _HTTP_PROBE_URLS.get(name)
+ if url:
+ ok, detail = _http_ok(url, timeout)
+ return {"ok": ok, "detail": detail, "probed": True}
+ cli = CLI_DEPENDENCIES.get(name)
+ if cli:
+ try:
+ probe = health.probe_dependency(cli)
+ except Exception as exc:
+ return {"ok": False, "detail": f"{type(exc).__name__}: {exc}", "probed": True}
+ return {"ok": bool(probe.ok), "detail": probe.detail, "probed": True}
+ return None
+
+
+def _probe_sources(config: Dict[str, Any], timeout: int) -> Dict[str, Dict[str, Any]]:
+ """Probe the probeable sources concurrently, each capped at ``timeout``.
+
+ A source that blows its deadline resolves to a probe-failure for that
+ source only (never a hung command); other probes are unaffected.
+ """
+ names = _probeable_sources()
+ results: Dict[str, Dict[str, Any]] = {}
+ with concurrent.futures.ThreadPoolExecutor(
+ max_workers=min(8, len(names) or 1)
+ ) as pool:
+ futures = {
+ name: pool.submit(_probe_source, name, config, timeout) for name in names
+ }
+ for name, fut in futures.items():
+ try:
+ res = fut.result(timeout=timeout + 1)
+ except concurrent.futures.TimeoutError:
+ res = {"ok": False, "detail": "probe exceeded deadline", "probed": True}
+ except Exception as exc:
+ res = {
+ "ok": False,
+ "detail": f"{type(exc).__name__}: {exc}",
+ "probed": True,
+ }
+ if res is not None:
+ results[name] = res
+ return results
+
+
+def _apply_probe(report: Dict[str, Any], probe_results: Dict[str, Dict[str, Any]]) -> None:
+ """Attach probe results and re-derive audit_state for probed sources."""
+ for name, res in probe_results.items():
+ record = (report.get("sources") or {}).get(name)
+ if record is None:
+ continue
+ record["probe"] = res
+ record["audit_state"] = audit_state(
+ name, record, record.get("run_outcome"), res
+ )
+
+
def run(
config: Dict[str, Any],
*,
@@ -1511,6 +1633,28 @@ def run(
report = build_report(config)
report["generated_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
report["from_cache"] = False
+
+ # U5: verify WORKING with a bounded live probe when asked (--probe) or when
+ # there is no fresh run to learn from ("if no recent runs, run a live
+ # test"). Scoped to free/CLI sources; credit-gated sources stay UNVERIFIED.
+ fresh_run = bool((report.get("run_evidence") or {}).get("fresh"))
+ if probe or not fresh_run:
+ timeout = probe_timeout_seconds(config)
+ probeable = _probeable_sources()
+ sys.stderr.write(
+ f"[last30days] doctor live probe: checking {len(probeable)} free/CLI "
+ f"sources ({timeout}s each; no credit-gated sources - x/tiktok/"
+ f"instagram/threads stay unverified)\n"
+ )
+ sys.stderr.flush()
+ try:
+ probe_results = _probe_sources(config, timeout)
+ except Exception:
+ probe_results = {}
+ _apply_probe(report, probe_results)
+ report["mode"] = "probe"
+ report["probe"] = {"ran": True, "timeout": timeout, "sources": list(probeable)}
+
_write_cache(report, config)
_emit(report)
return 0
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 7870132d..80a7fc00 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -470,6 +470,8 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
('LAST30DAYS_REDDIT_BACKEND', None),
# Doctor cache freshness window in seconds (doctor --cached).
('LAST30DAYS_DOCTOR_TTL', None),
+ # Per-source deadline (seconds) for doctor --probe live checks.
+ ('LAST30DAYS_DOCTOR_PROBE_TIMEOUT', None),
('LAST30DAYS_REDDIT_SC_MIN_ITEMS', None),
('LAST30DAYS_STORE', None),
# Opt-in strict exit: truthy -> CLI exits 3 when any source outcome is
diff --git a/tests/test_doctor.py b/tests/test_doctor.py
index 394aa16e..2fb1136b 100644
--- a/tests/test_doctor.py
+++ b/tests/test_doctor.py
@@ -117,6 +117,9 @@ class _Hermetic:
# Hermetic run-evidence: never read the user's real last-report.json.
# Tests that inject run evidence override this with a temp file.
mock.patch("lib.doctor._last_report_path", return_value=None),
+ # Hermetic live probe: never make a real network call. Tests that
+ # exercise probing override this with canned results.
+ mock.patch("lib.doctor._probe_sources", return_value={}),
# FTS5 is present on CI/dev SQLite; pin it so the library record's
# branch is deterministic regardless of the host's SQLite build.
mock.patch("lib.library_index.fts5_available", return_value=True),
@@ -875,6 +878,85 @@ class FourStateAudit(unittest.TestCase):
self.assertIn("13 items last run", text)
+class LiveProbe(unittest.TestCase):
+ """U5: bounded live probe (--probe / no-fresh-run auto-fallback)."""
+
+ def test_probeable_excludes_credit_gated(self):
+ probeable = set(doctor._probeable_sources())
+ for gated in ("x", "tiktok", "instagram", "threads", "linkedin"):
+ self.assertNotIn(gated, probeable, gated)
+ # free HTTP + keyless CLI sources ARE probeable
+ for free in ("reddit", "hackernews", "polymarket", "github", "youtube"):
+ self.assertIn(free, probeable, free)
+
+ def test_probe_source_http_reachable(self):
+ with mock.patch("lib.doctor._http_ok", return_value=(True, "HTTP 200")):
+ res = doctor._probe_source("hackernews", {}, 5)
+ self.assertTrue(res["ok"])
+ self.assertTrue(res["probed"])
+
+ def test_probe_source_credit_gated_returns_none(self):
+ self.assertIsNone(doctor._probe_source("tiktok", {}, 5))
+
+ def test_probe_failure_is_isolated(self):
+ def flaky(name, config, timeout):
+ if name == "reddit":
+ raise RuntimeError("boom")
+ return {"ok": True, "probed": True}
+
+ with mock.patch("lib.doctor._probe_source", flaky):
+ results = doctor._probe_sources({}, timeout=5)
+ self.assertFalse(results["reddit"]["ok"]) # isolated failure
+ self.assertIn("boom", results["reddit"]["detail"])
+ self.assertTrue(results["hackernews"]["ok"]) # others unaffected
+
+ def test_probe_deadline_never_hangs(self):
+ import time
+
+ def too_slow(name, config, timeout):
+ time.sleep(1.3) # exceeds the timeout(0)+1s result deadline
+ return {"ok": True, "probed": True}
+
+ with mock.patch("lib.doctor._probe_source", too_slow):
+ results = doctor._probe_sources({}, timeout=0)
+ self.assertTrue(results)
+ self.assertTrue(
+ any("deadline" in r.get("detail", "") for r in results.values())
+ )
+
+ def test_probe_result_flips_unverified_to_working(self):
+ rec = {"tier": "ok", "status": "ok", "audit_state": doctor.AUDIT_UNVERIFIED}
+ report = {"sources": {"hackernews": rec}}
+ doctor._apply_probe(report, {"hackernews": {"ok": True, "probed": True}})
+ self.assertEqual(doctor.AUDIT_WORKING, rec["audit_state"])
+ self.assertTrue(rec["probe"]["ok"])
+
+ def test_auto_probe_fires_when_no_fresh_run(self):
+ canned = {"hackernews": {"ok": True, "detail": "HTTP 200", "probed": True}}
+ with _Hermetic(), mock.patch(
+ "lib.doctor._probe_sources", return_value=canned
+ ) as probed:
+ out = io.StringIO()
+ err = io.StringIO()
+ with redirect_stdout(out), redirect_stderr(err):
+ rc = doctor.run({})
+ self.assertEqual(0, rc)
+ probed.assert_called() # auto-fired: no fresh run
+ self.assertIn("live probe", err.getvalue())
+
+ def test_no_auto_probe_when_fresh_run(self):
+ tmp = tempfile.mkdtemp()
+ path = _write_last_report(
+ tmp, source_status={"reddit": {"state": "ok", "items_returned": 5}}
+ )
+ with _Hermetic(), mock.patch(
+ "lib.doctor._last_report_path", return_value=path
+ ), mock.patch("lib.doctor._probe_sources") as probed:
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ doctor.run({})
+ probed.assert_not_called() # fresh run -> overlay, no probe
+
+
class Postmortem(unittest.TestCase):
"""U4: --postmortem reads the last run's per-source outcomes."""