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(digg): surface a live search that fell back to an empty local store (#1283)
yi111d95f0a8d4dd5
diff --git a/changelog.d/1281.fixed.md b/changelog.d/1281.fixed.mdnew file mode 100644index 00000000..bb762014--- /dev/null+++ b/changelog.d/1281.fixed.md@@ -0,0 +1 @@+Digg now reports an error instead of "no results" when `digg-pp-cli` falls back to its local store after a failed live search (last30days never runs `digg-pp-cli sync`, so the fallback store is always empty).diff --git a/skills/last30days/scripts/lib/digg.py b/skills/last30days/scripts/lib/digg.pyindex 1595331d..4697ea4d 100644--- a/skills/last30days/scripts/lib/digg.py+++ b/skills/last30days/scripts/lib/digg.py@@ -19,9 +19,10 @@ top-ranked X posts to each cluster's ``posts`` field.from __future__ import annotationsimport json+import reimport shutilfrom datetime import datetime, timedelta, timezone-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Tuplefrom urllib.parse import urlparsefrom . import log, subproc@@ -133,47 +134,104 @@ def _build_posts_args(cluster_url_id: str, posts_per: int) -> List[str]:]-def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:- """Invoke digg-pp-cli and parse the JSON envelope.+_LOCAL_FALLBACK_MARKER = "falling back to local FTS5:"+_FALLBACK_REASON_MAX = 200+++def _local_fallback_reason(stderr: str) -> str:+ """Extract the live-search failure from digg-pp-cli's fallback stderr.- Returns ``{"results": [...]}`` on success, ``{"results": [], "error": "..."}``- on failure. Never raises; the pipeline relies on shape consistency.+ The CLI prints ``falling back to local FTS5: <error>`` and the error can+ embed the full HTML body of a failed response, so the reason is cut at+ the HTTP status when present and length-bounded otherwise.+ """+ for line in (stderr or "").splitlines():+ _, marker, rest = line.partition(_LOCAL_FALLBACK_MARKER)+ if not marker:+ continue+ rest = rest.strip()+ status = re.match(r".*?\bHTTP \d{3}\b", rest)+ if status:+ return status.group(0)+ return rest[:_FALLBACK_REASON_MAX].rstrip()+ return ""+++def _empty_local_fallback_error(data: Dict[str, Any], stderr: str = "") -> Optional[str]:+ """Return an error when the CLI answered from an empty local store.++ ``digg-pp-cli search`` is live by default, but it falls back to its FTS5+ store on a network error and exits 0 with ``meta.source == "local"``.+ That store only holds rows for users who ran ``digg-pp-cli sync``+ themselves, which last30days never does - so a broken live search+ reaches the user as ``Digg: 0 items (no results)`` instead of an error.+ A non-empty local store is real data and is left alone.++ The CLI reports the live failure only on stderr; ``meta.reason`` is+ preferred if a future CLI release adds it to the envelope.+ """+ meta = data.get("meta")+ if not isinstance(meta, dict) or meta.get("source") != "local":+ return None+ if data.get("results"):+ return None+ reason = str(meta.get("reason") or "").strip()[:_FALLBACK_REASON_MAX]+ detail = (+ reason+ or _local_fallback_reason(stderr)+ or "live search fell back to an empty local store"+ )+ return f"live-search-unavailable: {detail}"+++def _invoke_cli(cmd: List[str], timeout: int) -> Tuple[Dict[str, Any], str]:+ """Invoke digg-pp-cli and return the parsed envelope with its stderr.++ The envelope is ``{"results": [...]}`` on success and+ ``{"results": [], "error": "..."}`` on failure. Never raises; the+ pipeline relies on shape consistency."""if not _is_available():- return {"results": [], "error": f"{CLI_BIN} not on PATH"}+ return {"results": [], "error": f"{CLI_BIN} not on PATH"}, ""try:result = subproc.run_with_timeout(cmd, timeout=timeout)except subproc.SubprocTimeout as exc:_log(f"Timeout: {exc}")- return {"results": [], "error": str(exc)}+ return {"results": [], "error": str(exc)}, ""except FileNotFoundError as exc:_log(f"Binary missing: {exc}")- return {"results": [], "error": str(exc)}+ return {"results": [], "error": str(exc)}, ""except OSError as exc:_log(f"Spawn failed: {exc}")- return {"results": [], "error": str(exc)}+ return {"results": [], "error": str(exc)}, ""+ stderr = result.stderr or ""if result.returncode != 0:- snippet = (result.stderr or "").strip().splitlines()[:1]+ snippet = stderr.strip().splitlines()[:1]first = snippet[0] if snippet else f"exit {result.returncode}"_log(f"CLI exit {result.returncode}: {first}")- return {"results": [], "error": first}+ return {"results": [], "error": first}, stderrstdout = result.stdout or ""if not stdout.strip():- return {"results": []}+ return {"results": []}, stderrtry:data = json.loads(stdout)except json.JSONDecodeError as exc:_log(f"JSON decode failed: {exc}")- return {"results": [], "error": f"json decode: {exc}"}+ return {"results": [], "error": f"json decode: {exc}"}, stderrif not isinstance(data, dict):- return {"results": []}+ return {"results": []}, stderrresults = data.get("results")if not isinstance(results, list):- return {"results": []}- return data+ return {"results": []}, stderr+ return data, stderr+++def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:+ """Invoke digg-pp-cli and return only the parsed envelope."""+ return _invoke_cli(cmd, timeout)[0]def search_digg(@@ -199,7 +257,11 @@ def search_digg(return {"results": []}cmd = _build_search_args(topic, limit)_log(f"search '{topic}' (limit={limit}, since=30d)")- response = _run_cli(cmd, timeout=SEARCH_TIMEOUT)+ response, stderr = _invoke_cli(cmd, timeout=SEARCH_TIMEOUT)+ fallback_error = _empty_local_fallback_error(response, stderr)+ if fallback_error:+ _log(fallback_error)+ return {"results": [], "error": fallback_error}n = len(response.get("results") or [])_log(f"found {n} clusters")return responsediff --git a/tests/test_digg.py b/tests/test_digg.pyindex e17d90df..397dce00 100644--- a/tests/test_digg.py+++ b/tests/test_digg.py@@ -313,6 +313,136 @@ def test_search_digg_empty_query_short_circuits(monkeypatch):assert out["results"] == []called.assert_not_called()++_REAL_FALLBACK_STDERR = (+ "falling back to local FTS5: GET https://di.gg/api/search/stories: HTTP 404: "+ '<!DOCTYPE html><html data-dpl-id="dpl_x" lang="en" class="font-sans">'+ + "x" * 500+ + "\n"+)+++def _real_fallback_result() -> subproc.SubprocResult:+ """digg-pp-cli 2026.9.1 output when the live API 404s: exit 0, no meta.reason."""+ return subproc.SubprocResult(+ returncode=0,+ stdout=json.dumps(+ {+ "meta": {+ "count": 0,+ "query": "openai",+ "since": "30d",+ "source": "local",+ },+ "results": [],+ }+ ),+ stderr=_REAL_FALLBACK_STDERR,+ )+++def test_search_digg_real_fallback_reports_stderr_reason(monkeypatch):+ """A live search that fell back to an empty local store is not 'no results'."""+ monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path")+ monkeypatch.setattr(+ digg.subproc, "run_with_timeout", lambda *a, **k: _real_fallback_result()+ )+ out = digg.search_digg("openai", "2026-04-09", "2026-05-09")+ assert out["results"] == []+ assert out["error"] == (+ "live-search-unavailable: GET https://di.gg/api/search/stories: HTTP 404"+ )+++def test_real_fallback_reason_reaches_source_outcome(monkeypatch):+ from lib import pipeline++ monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path")+ monkeypatch.setattr(+ digg.subproc, "run_with_timeout", lambda *a, **k: _real_fallback_result()+ )+ out = digg.search_digg("openai", "2026-04-09", "2026-05-09")+ outcome = pipeline._result_outcome_artifact("digg", out)["_source_outcome"]+ assert outcome["state"] == "error"+ assert "HTTP 404" in outcome["detail"]+ assert "<!DOCTYPE" not in outcome["detail"]+++def test_local_fallback_reason_bounds_non_http_errors():+ stderr = "noise\nfalling back to local FTS5: dial tcp: " + "y" * 1000 + "\n"+ reason = digg._local_fallback_reason(stderr)+ assert reason.startswith("dial tcp: ")+ assert len(reason) <= digg._FALLBACK_REASON_MAX+++def test_search_digg_empty_local_fallback_prefers_meta_reason(monkeypatch):+ """meta.reason is not emitted by digg-pp-cli 2026.9.1; prefer it if a later release adds it."""+ monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path")+ monkeypatch.setattr(+ digg.subproc,+ "run_with_timeout",+ lambda *a, **k: subproc.SubprocResult(+ returncode=0,+ stdout=json.dumps(+ {+ "meta": {+ "source": "local",+ "reason": "GET https://di.gg/api/search/stories: HTTP 404",+ },+ "results": [],+ }+ ),+ stderr="falling back to local FTS5: stderr reason\n",+ ),+ )+ out = digg.search_digg("openai", "2026-04-09", "2026-05-09")+ assert out["results"] == []+ assert out["error"] == (+ "live-search-unavailable: GET https://di.gg/api/search/stories: HTTP 404"+ )+++def test_search_digg_empty_local_fallback_without_reason_still_errors(monkeypatch):+ monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path")+ monkeypatch.setattr(+ digg.subproc,+ "run_with_timeout",+ lambda *a, **k: _stdout_for({"meta": {"source": "local"}, "results": []}),+ )+ out = digg.search_digg("openai", "2026-04-09", "2026-05-09")+ assert out["results"] == []+ assert "live-search-unavailable" in out["error"]+++def test_search_digg_local_fallback_with_rows_keeps_results(monkeypatch):+ """A user who ran `digg-pp-cli sync` still gets their local clusters."""+ monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path")+ monkeypatch.setattr(+ digg.subproc,+ "run_with_timeout",+ lambda *a, **k: _stdout_for(+ {"meta": {"source": "local"}, "results": [_cluster()]}+ ),+ )+ out = digg.search_digg("openai", "2026-04-09", "2026-05-09")+ assert len(out["results"]) == 1+ assert "error" not in out+++def test_search_digg_live_empty_is_still_no_results(monkeypatch):+ """A live search that genuinely found nothing stays a clean empty."""+ monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path")+ monkeypatch.setattr(+ digg.subproc,+ "run_with_timeout",+ lambda *a, **k: _stdout_for(+ {"meta": {"source": "live", "count": 0}, "results": []}+ ),+ )+ out = digg.search_digg("openai", "2026-04-09", "2026-05-09")+ assert out["results"] == []+ assert "error" not in out+# === enrich_with_top_posts ===