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
feat(doctor): overlay last-run source outcomes onto records (U1)
Matt Van Horn943e18d1c3e2
diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.pyindex fad38417..433e99c5 100644--- a/skills/last30days/scripts/lib/doctor.py+++ b/skills/last30days/scripts/lib/doctor.py@@ -589,6 +589,89 @@ _SOURCE_BUILDERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {}+# ---------------------------------------------------------------------------+# Run-evidence overlay (U1): read the engine's last-report.json+#+# doctor predicts config health; a research run records what ACTUALLY happened+# per source in Report.source_status. Reading the last run lets doctor tell+# "configured" from "working" (the four-state audit) and powers --postmortem.+# This is a read-only reuse of the engine's existing report cache - no new+# writer. The schema stamp + filename mirror REPORT_CACHE_VERSION /+# _last_report_cache_path() in last30days.py (the same mirror pattern the+# doctor-cache block below already uses for its own schema stamp).+# ---------------------------------------------------------------------------++REPORT_CACHE_SCHEMA_VERSION = "last30days-report-cache/v1"+REPORT_CACHE_FILENAME = "last-report.json"+DEFAULT_REPORT_CACHE_TTL_SECONDS = 3600+++def _last_report_path() -> Optional[Path]:+ """The engine's last-report.json, beside the doctor cache (None in clean mode)."""+ if env.CONFIG_DIR is None:+ return None+ return env.CONFIG_DIR / REPORT_CACHE_FILENAME+++def load_run_evidence(+ config: Dict[str, Any], ttl_seconds: int = DEFAULT_REPORT_CACHE_TTL_SECONDS+) -> Dict[str, Any]:+ """Return the last research run's per-source outcomes, read-only.++ Shape: ``{"outcomes": {source: {state, items_returned, detail, fix_hint,+ at}}, "topic": str|None, "at": str|None, "fresh": bool, "present": bool}``.++ Any failure mode - absent file, unreadable, invalid JSON, schema mismatch,+ wrong shape - yields the empty, not-present result and never raises+ (doctor's exit-0 contract is absolute). ``fresh`` reflects the report TTL:+ ``--postmortem`` reads regardless of freshness (labeling the age), while the+ plain-``doctor`` overlay consumes only fresh evidence so a week-old run+ cannot mislabel a source as WORKING today.+ """+ empty = {"outcomes": {}, "topic": None, "at": None, "fresh": False, "present": False}+ path = _last_report_path()+ if path is None or not path.exists():+ return empty+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ return empty+ if not isinstance(payload, dict):+ return empty+ if payload.get("schema") != REPORT_CACHE_SCHEMA_VERSION:+ return empty+ reports = payload.get("reports") or []+ if not reports or not isinstance(reports[0], dict):+ return empty+ report = reports[0].get("report")+ if not isinstance(report, dict):+ return empty+ raw_status = report.get("source_status") or {}+ outcomes: Dict[str, Any] = {}+ if isinstance(raw_status, dict):+ for source, outcome in raw_status.items():+ if not isinstance(outcome, dict):+ continue+ state = outcome.get("state")+ if not isinstance(state, str):+ continue+ outcomes[source] = {+ "state": state,+ "items_returned": int(outcome.get("items_returned") or 0),+ "detail": outcome.get("detail"),+ "fix_hint": outcome.get("fix_hint"),+ "at": outcome.get("at"),+ }+ timestamp = payload.get("timestamp")+ return {+ "outcomes": outcomes,+ "topic": payload.get("topic"),+ "at": timestamp or report.get("generated_at"),+ "fresh": bool(env.is_timestamp_fresh(timestamp, ttl_seconds)),+ "present": True,+ }++# ---------------------------------------------------------------------------# Aggregation# ---------------------------------------------------------------------------@@ -654,6 +737,12 @@ def build_report(config: Dict[str, Any]) -> Dict[str, Any]:zip(SOURCE_ORDER, pool.map(_build_one, SOURCE_ORDER)))+ # U1: overlay the last research run's per-source outcome onto each record+ # so the audit layer can tell "configured" from "actually working".+ evidence = load_run_evidence(config)+ for source, record in sources.items():+ record["run_outcome"] = evidence["outcomes"].get(source) if evidence["fresh"] else None+# Sequential on purpose: the permission preflight composes pipeline# diagnostics and must not race the source builders.try:@@ -670,6 +759,12 @@ def build_report(config: Dict[str, Any]) -> Dict[str, Any]:"setup": _setup_block(config),"permissions": permissions,"sources": sources,+ "run_evidence": {+ "present": evidence["present"],+ "fresh": evidence["fresh"],+ "topic": evidence["topic"],+ "at": evidence["at"],+ },}diff --git a/tests/test_doctor.py b/tests/test_doctor.pyindex 78185116..0a65406a 100644--- a/tests/test_doctor.py+++ b/tests/test_doctor.py@@ -15,12 +15,15 @@ Covers the plan's U4 scenarios:note, never a false-alarm error."""+import datetimeimport ioimport jsonimport osimport sys+import tempfileimport unittestfrom contextlib import redirect_stderr, redirect_stdout+from pathlib import Pathfrom unittest import mockimport last30days as cli@@ -111,6 +114,9 @@ class _Hermetic:# Hermetic library: never glob the user's real saved-research dir.# Tests that assert a specific brief count override this.mock.patch("lib.doctor._count_saved_briefs", return_value=0),+ # 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),# 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),@@ -693,5 +699,98 @@ class TextReport(unittest.TestCase):self.assertIn("will use: brave", text)+def _write_last_report(dir_path, *, source_status, topic="wordpress", fresh=True):+ """Write a minimal last-report.json the run-evidence loader can read."""+ ts = datetime.datetime.now(datetime.timezone.utc)+ if not fresh:+ ts = ts - datetime.timedelta(+ seconds=doctor.DEFAULT_REPORT_CACHE_TTL_SECONDS + 600+ )+ iso = ts.isoformat()+ payload = {+ "schema": doctor.REPORT_CACHE_SCHEMA_VERSION,+ "timestamp": iso,+ "topic": topic,+ "reports": [+ {+ "entity": "",+ "report": {+ "generated_at": iso,+ "source_status": {+ src: {+ "source": src,+ "state": st.get("state"),+ "items_returned": st.get("items_returned", 0),+ "detail": st.get("detail"),+ "at": iso,+ "fix_hint": st.get("fix_hint"),+ }+ for src, st in source_status.items()+ },+ },+ }+ ],+ }+ path = Path(dir_path) / doctor.REPORT_CACHE_FILENAME+ path.write_text(json.dumps(payload), encoding="utf-8")+ return path+++class RunEvidenceOverlay(unittest.TestCase):+ """U1: build_report overlays last-report.json per-source outcomes."""++ def _build_with_evidence(self, source_status, fresh=True):+ tmp = tempfile.mkdtemp()+ path = _write_last_report(tmp, source_status=source_status, fresh=fresh)+ with _Hermetic(), mock.patch(+ "lib.doctor._last_report_path", return_value=path+ ):+ return doctor.build_report({})++ def test_failed_source_outcome_overlaid(self):+ report = self._build_with_evidence(+ {+ "youtube": {"state": "error", "items_returned": 0, "detail": "HTTP 500"},+ "reddit": {"state": "ok", "items_returned": 13},+ }+ )+ yt = report["sources"]["youtube"]["run_outcome"]+ self.assertIsNotNone(yt)+ self.assertEqual("error", yt["state"])+ self.assertIn("HTTP 500", yt["detail"])+ self.assertEqual(+ 13, report["sources"]["reddit"]["run_outcome"]["items_returned"]+ )+ self.assertTrue(report["run_evidence"]["fresh"])+ self.assertTrue(report["run_evidence"]["present"])++ def test_no_cache_yields_no_outcomes(self):+ with _Hermetic(): # _last_report_path -> None+ report = doctor.build_report({})+ self.assertIsNone(report["sources"]["reddit"]["run_outcome"])+ self.assertFalse(report["run_evidence"]["present"])++ def test_corrupt_cache_treated_as_absent(self):+ tmp = tempfile.mkdtemp()+ path = Path(tmp) / doctor.REPORT_CACHE_FILENAME+ path.write_text("{not valid json", encoding="utf-8")+ with _Hermetic(), mock.patch(+ "lib.doctor._last_report_path", return_value=path+ ):+ report = doctor.build_report({})+ self.assertIsNone(report["sources"]["reddit"]["run_outcome"])+ self.assertFalse(report["run_evidence"]["present"])++ def test_stale_cache_present_but_not_overlaid(self):+ report = self._build_with_evidence(+ {"youtube": {"state": "error", "items_returned": 0}}, fresh=False+ )+ # Present but not fresh: overlay withheld from plain doctor (R4),+ # while --postmortem (U4) can still read it by age.+ self.assertIsNone(report["sources"]["youtube"]["run_outcome"])+ self.assertTrue(report["run_evidence"]["present"])+ self.assertFalse(report["run_evidence"]["fresh"])++if __name__ == "__main__":unittest.main()