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: reuse cached reports for html synthesis
Trevin Chow55f7aa585057
diff --git a/skills/last30days/references/save-html-brief.md b/skills/last30days/references/save-html-brief.mdindex 686f2bcf..5a73eec5 100644--- a/skills/last30days/references/save-html-brief.md+++ b/skills/last30days/references/save-html-brief.md@@ -41,12 +41,13 @@ SYNTHESIS_EOF# 2. Convert the synthesis to a self-contained HTML file via the engine.# REPLAY THE SAME SCOPE FLAGS as your original run (--plan, --hiring-signals,-# resolved --x-handle/--subreddits/etc). The engine re-runs the pipeline to-# build the badge metadata line and footer; if you omit the scope flags it-# takes the generic multi-source path and the artifact's footer/metadata will-# describe a DIFFERENT dataset than your synthesis body (observed: a 74s-# mismatched re-run on a --hiring-signals brief). Same flags = footer matches-# the brief.+# resolved --x-handle/--subreddits/etc). On a same-topic follow-up, the+# engine reuses the structured last-report cache at+# ~/.config/last30days/last-report.json to build badge metadata and footer+# without re-running source fetchers. If the cache is missing or for a+# different topic, stderr says "No matching cached report data" and the+# engine falls back to a fresh run; the same scope flags keep that fallback+# aligned with the synthesis body.SLUG=$(echo "$TOPIC" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//')HTML_PATH="${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief.html"# Collision guard: the `> "$HTML_PATH"` redirect below OVERWRITES - the engine@@ -93,6 +94,8 @@ Same flow when the topic is `X vs Y` (or `X vs Y vs Z`). The engine routes throuIf the user runs `/last30days OpenClaw` normally, sees the synthesis in chat, and THEN says "save that as HTML" or "give me a shareable version" in a follow-up turn, do the same save flow on the synthesis you wrote in the previous turn. Do not re-research; the synthesis is already in the conversation history. Just write it to the temp file and call the engine with `--emit=html --synthesis-file`.+The engine will try to reuse `~/.config/last30days/last-report.json` for that second invocation. If stderr says it is reusing cached report data, continue normally. If stderr says no matching cache exists, let the command finish only if you supplied the same scope flags as the original run; otherwise stop and re-run with the original flags so the HTML footer does not describe a different dataset.+## What NOT to do- Do NOT save HTML if the user didn't ask. The sparse mode (no synthesis) produces a thin file; not useful as a shareable.diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 5746a54c..53174bfc 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -602,7 +602,20 @@ def _show_runtime_ui(progress.show_promo(promo, diag=diag)-def _write_last_run(topic: str, report: "schema.Report") -> None:+REPORT_CACHE_VERSION = "last30days-report-cache/v1"+++def _last_report_cache_path() -> Path | None:+ if env.CONFIG_DIR is None:+ return None+ return env.CONFIG_DIR / "last-report.json"+++def _write_last_run(+ topic: str,+ report: "schema.Report",+ entity_reports: list[tuple[str, schema.Report]] | None = None,+) -> None:try:if env.CONFIG_DIR is None:return@@ -614,12 +627,124 @@ def _write_last_run(topic: str, report: "schema.Report") -> None:"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),"sources": counts,"total": sum(counts.values()),+ "report_cache": str(target / "last-report.json"),+ "comparison": bool(entity_reports),}(target / "last-run.json").write_text(json.dumps(payload, indent=2))+ cached_reports = entity_reports or [(report.topic, report)]+ cache_payload = {+ "schema": REPORT_CACHE_VERSION,+ "topic": topic,+ "timestamp": payload["timestamp"],+ "comparison": bool(entity_reports),+ "reports": [+ {"entity": label, "report": schema.to_dict(cached_report)}+ for label, cached_report in cached_reports+ ],+ }+ (target / "last-report.json").write_text(json.dumps(cache_payload, indent=2))except Exception:pass+def _load_last_report_cache(+ topic: str,+) -> tuple[schema.Report, list[tuple[str, schema.Report]] | None, Path] | None:+ cache_path = _last_report_cache_path()+ if cache_path is None or not cache_path.exists():+ return None+ try:+ payload = json.loads(cache_path.read_text(encoding="utf-8"))+ if payload.get("schema") != REPORT_CACHE_VERSION:+ return None+ cached_topic = str(payload.get("topic") or "").strip().lower()+ if cached_topic != topic.strip().lower():+ return None+ reports_payload = payload.get("reports") or []+ if not reports_payload:+ return None+ entity_reports = [+ (str(item.get("entity") or ""), schema.report_from_dict(item["report"]))+ for item in reports_payload+ if isinstance(item, dict) and isinstance(item.get("report"), dict)+ ]+ if not entity_reports:+ return None+ if payload.get("comparison") and len(entity_reports) > 1:+ return entity_reports[0][1], entity_reports, cache_path+ return entity_reports[0][1], None, cache_path+ except Exception:+ return None+++def _render_save_and_print(+ args: argparse.Namespace,+ report: schema.Report,+ entity_reports: list[tuple[str, schema.Report]] | None,+ synthesis_md: str | None,+ config: dict[str, object],+) -> int:+ fun_level = str(config.get("FUN_LEVEL", "medium")).lower()+ # Comparison HTML is the one case where the saved file's title and content+ # have to be overridden away from the leading entity's report. Compute the+ # gate once so the footer-display and save-output paths can't disagree.+ is_comparison_html = bool(entity_reports) and args.emit == "html"+ footer_save_path = None+ if args.output:+ footer_save_path = compute_output_path_display(args.output)+ elif args.save_dir:+ save_topic_for_display = comparison_topic(entity_reports) if is_comparison_html else report.topic+ footer_save_path = compute_save_path_display(+ args.save_dir, save_topic_for_display, args.save_suffix or "", args.emit+ )++ if entity_reports:+ rendered = emit_comparison_output(+ entity_reports,+ args.emit,+ fun_level=fun_level,+ save_path=footer_save_path,+ synthesis_md=synthesis_md,+ )+ else:+ rendered = emit_output(+ report,+ args.emit,+ fun_level=fun_level,+ save_path=footer_save_path,+ synthesis_md=synthesis_md,+ )+ if args.output:+ output_path = save_rendered_output(rendered, args.output)+ sys.stderr.write(f"[last30days] Saved output to {output_path}\n")+ sys.stderr.flush()+ if args.save_dir:+ # Save the main topic's raw file (single-entity or comparison main).+ save_path = save_output(+ report,+ args.emit,+ args.save_dir,+ suffix=args.save_suffix or "",+ synthesis_md=synthesis_md,+ topic_override=comparison_topic(entity_reports) if is_comparison_html else None,+ rendered_content=rendered if is_comparison_html else None,+ )+ sys.stderr.write(f"[last30days] Saved output to {save_path}\n")+ # Competitor / vs-mode: also save a per-entity raw file for each peer.+ # Matches historical vs-mode behavior (N passes -> N save files).+ if entity_reports and len(entity_reports) > 1:+ for label, entity_report in entity_reports[1:]:+ peer_path = save_output(+ entity_report, args.emit, args.save_dir,+ suffix=args.save_suffix or "",+ synthesis_md=synthesis_md,+ )+ sys.stderr.write(f"[last30days] Saved output to {peer_path}\n")+ sys.stderr.flush()+ print(rendered)+ return 0++def _propagate_config_to_environ(config: dict[str, object]) -> None:"""Push relevant env keys to os.environ so provider modules can read them.@@ -704,6 +829,7 @@ def main() -> int:os.environ["LAST30DAYS_DEBUG"] = "1"topic = " ".join(args.topic).strip()+ original_topic = topic_validate_extra_argv(parser, topic, extra_argv)config = env.get_config(policy=_config_policy_for_args(args, topic, extra_argv))_propagate_config_to_environ(config)@@ -791,6 +917,23 @@ def main() -> int:sys.stderr.write(refuse_msg)return 2+ if args.emit == "html" and synthesis_md is not None:+ cached = _load_last_report_cache(topic)+ if cached is not None:+ cached_report, cached_entity_reports, cache_path = cached+ sys.stderr.write(+ f"[last30days] Reusing cached report data from {cache_path}\n"+ )+ sys.stderr.flush()+ return _render_save_and_print(+ args, cached_report, cached_entity_reports, synthesis_md, config+ )+ sys.stderr.write(+ "[last30days] No matching cached report data for "+ "--emit=html --synthesis-file; running fresh research.\n"+ )+ sys.stderr.flush()+progress = ui.ProgressDisplay(topic, show_banner=True)progress.start_processing()@@ -1088,7 +1231,7 @@ def main() -> int:report, progress, diag,suppress_web_promo=bool(external_plan or comp_plan),)- _write_last_run(topic, report)+ _write_last_run(original_topic, report, entity_reports=entity_reports)# LAST30DAYS_STORE env var = persistence default-on. Read both os.environ# (for shell-exported users) and config (for users who set it in# ~/.config/last30days/.env, which env.py loads but does not propagate@@ -1152,20 +1295,6 @@ def main() -> int:except Exception:pass- fun_level = config.get("FUN_LEVEL", "medium").lower()- # Comparison HTML is the one case where the saved file's title and content- # have to be overridden away from the leading entity's report. Compute the- # gate once so the footer-display and save-output paths can't disagree.- is_comparison_html = bool(entity_reports) and args.emit == "html"- footer_save_path = None- if args.output:- footer_save_path = compute_output_path_display(args.output)- elif args.save_dir:- save_topic_for_display = comparison_topic(entity_reports) if is_comparison_html else report.topic- footer_save_path = compute_save_path_display(- args.save_dir, save_topic_for_display, args.save_suffix or "", args.emit- )-# Signal to render_compact whether pre-research flags were supplied.# Used to emit a Pre-Research Status warning when the model skipped# Step 0.5 / 0.55 and invoked the engine bare on an eligible topic.@@ -1180,51 +1309,7 @@ def main() -> int:)report.artifacts["pre_research_flags_present"] = pre_research_flags_present- if entity_reports:- rendered = emit_comparison_output(- entity_reports,- args.emit,- fun_level=fun_level,- save_path=footer_save_path,- synthesis_md=synthesis_md,- )- else:- rendered = emit_output(- report,- args.emit,- fun_level=fun_level,- save_path=footer_save_path,- synthesis_md=synthesis_md,- )- if args.output:- output_path = save_rendered_output(rendered, args.output)- sys.stderr.write(f"[last30days] Saved output to {output_path}\n")- sys.stderr.flush()- if args.save_dir:- # Save the main topic's raw file (single-entity or comparison main).- save_path = save_output(- report,- args.emit,- args.save_dir,- suffix=args.save_suffix or "",- synthesis_md=synthesis_md,- topic_override=comparison_topic(entity_reports) if is_comparison_html else None,- rendered_content=rendered if is_comparison_html else None,- )- sys.stderr.write(f"[last30days] Saved output to {save_path}\n")- # Competitor / vs-mode: also save a per-entity raw file for each peer.- # Matches historical vs-mode behavior (N passes → N save files).- if entity_reports and len(entity_reports) > 1:- for label, entity_report in entity_reports[1:]:- peer_path = save_output(- entity_report, args.emit, args.save_dir,- suffix=args.save_suffix or "",- synthesis_md=synthesis_md,- )- sys.stderr.write(f"[last30days] Saved output to {peer_path}\n")- sys.stderr.flush()- print(rendered)- return 0+ return _render_save_and_print(args, report, entity_reports, synthesis_md, config)if __name__ == "__main__":diff --git a/tests/test_doc_flag_contract.py b/tests/test_doc_flag_contract.pyindex 5858475b..968933d7 100644--- a/tests/test_doc_flag_contract.py+++ b/tests/test_doc_flag_contract.py@@ -9,6 +9,7 @@ import last30days as cliROOT = Path(__file__).resolve().parents[1]CONFIGURATION = ROOT / "CONFIGURATION.md"SKILL_MD = ROOT / "skills" / "last30days" / "SKILL.md"+HTML_REFERENCE = ROOT / "skills" / "last30days" / "references" / "save-html-brief.md"def _parser_flags() -> set[str]:@@ -41,3 +42,10 @@ def test_agent_is_documented_as_skill_argument_not_python_flag():agent_section = text[start:start + 2000]assert "If `--agent` appears in ARGUMENTS" in agent_sectionassert "Skill tool" in text+++def test_html_reference_documents_structured_cache_reuse():+ text = HTML_REFERENCE.read_text(encoding="utf-8")+ assert "~/.config/last30days/last-report.json" in text+ assert "without re-running source fetchers" in text+ assert "No matching cached report data" in textdiff --git a/tests/test_last_run_state.py b/tests/test_last_run_state.pyindex 986bb8c8..13f0edbe 100644--- a/tests/test_last_run_state.py+++ b/tests/test_last_run_state.py@@ -7,11 +7,12 @@ import sysimport shutilimport tempfileimport unittest-from contextlib import redirect_stderr+from contextlib import redirect_stderr, redirect_stdoutfrom pathlib import Pathfrom unittest import mockimport last30days as cli+from lib import schemaREPO_ROOT = Path(__file__).resolve().parents[1]LAST30DAYS_SCRIPT = REPO_ROOT / "skills" / "last30days" / "scripts" / "last30days.py"@@ -30,6 +31,51 @@ def run_last30days(topic: str, env: dict[str, str]) -> subprocess.CompletedProce)+def _report(topic: str) -> schema.Report:+ return schema.Report(+ topic=topic,+ range_from="2026-05-01",+ range_to="2026-05-31",+ generated_at="2026-05-31T00:00:00+00:00",+ provider_runtime=schema.ProviderRuntime(+ reasoning_provider="local",+ planner_model="mock-planner",+ rerank_model="mock-rerank",+ ),+ query_plan=schema.QueryPlan(+ intent="concept",+ freshness_mode="balanced_recent",+ cluster_mode="none",+ raw_topic=topic,+ subqueries=[+ schema.SubQuery(+ label="primary",+ search_query=topic,+ ranking_query=topic,+ sources=["grounding"],+ )+ ],+ source_weights={"grounding": 1.0},+ ),+ clusters=[],+ ranked_candidates=[],+ items_by_source={"grounding": []},+ errors_by_source={},+ )+++def _diag() -> dict[str, object]:+ return {+ "available_sources": ["grounding"],+ "providers": {"google": True, "openai": False, "xai": False},+ "x_backend": None,+ "bird_installed": True,+ "bird_authenticated": False,+ "bird_username": None,+ "native_web_backend": "brave",+ }++class LastRunStateTests(unittest.TestCase):def test_empty_config_override_disables_last_run_write(self):with tempfile.TemporaryDirectory() as tmp:@@ -56,6 +102,120 @@ class LastRunStateTests(unittest.TestCase):payload = json.loads((config_dir / "last-run.json").read_text())self.assertEqual(payload["topic"], "custom config query")self.assertGreaterEqual(payload["total"], 0)+ self.assertEqual(str(config_dir / "last-report.json"), payload["report_cache"])+ self.assertTrue((config_dir / "last-report.json").exists())++ def test_last_report_cache_round_trips_single_report(self):+ with tempfile.TemporaryDirectory() as tmp:+ config_dir = Path(tmp) / "config"+ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):+ report = _report("OpenClaw")+ cli._write_last_run("OpenClaw", report)+ loaded = cli._load_last_report_cache("OpenClaw")++ self.assertIsNotNone(loaded)+ cached_report, entity_reports, cache_path = loaded+ self.assertEqual("OpenClaw", cached_report.topic)+ self.assertIsNone(entity_reports)+ self.assertEqual(config_dir / "last-report.json", cache_path)++ def test_html_synthesis_reuses_cached_single_report_without_pipeline_run(self):+ with tempfile.TemporaryDirectory() as tmp:+ config_dir = Path(tmp) / "config"+ synthesis_path = Path(tmp) / "synthesis.md"+ synthesis_path.write_text("# OpenClaw\n\nCached synthesis body.", encoding="utf-8")+ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):+ cli._write_last_run("OpenClaw", _report("OpenClaw"))++ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \+ mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \+ mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("pipeline should not run")), \+ mock.patch.object(sys, "argv", [+ "last30days.py",+ "OpenClaw",+ "--emit=html",+ "--synthesis-file",+ str(synthesis_path),+ ]), \+ mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()++ self.assertEqual(0, rc)+ self.assertIn("Cached synthesis body.", stdout.getvalue())+ self.assertIn("Reusing cached report data", stderr.getvalue())++ def test_html_synthesis_reuses_cached_comparison_reports(self):+ with tempfile.TemporaryDirectory() as tmp:+ config_dir = Path(tmp) / "config"+ synthesis_path = Path(tmp) / "synthesis.md"+ synthesis_path.write_text(+ "# Alpha vs Beta\n\nCached comparison body.",+ encoding="utf-8",+ )+ reports = [("Alpha", _report("Alpha")), ("Beta", _report("Beta"))]+ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):+ cli._write_last_run("Alpha vs Beta", reports[0][1], entity_reports=reports)++ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \+ mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \+ mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("pipeline should not run")), \+ mock.patch.object(sys, "argv", [+ "last30days.py",+ "Alpha",+ "vs",+ "Beta",+ "--emit=html",+ "--synthesis-file",+ str(synthesis_path),+ ]), \+ mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()++ self.assertEqual(0, rc)+ self.assertIn("Cached comparison body.", stdout.getvalue())+ self.assertIn("last30days · Alpha vs Beta", stdout.getvalue())+ self.assertIn("Reusing cached report data", stderr.getvalue())++ def test_html_synthesis_warns_and_falls_back_when_cache_topic_misses(self):+ with tempfile.TemporaryDirectory() as tmp:+ config_dir = Path(tmp) / "config"+ synthesis_path = Path(tmp) / "synthesis.md"+ synthesis_path.write_text("Cached synthesis body.", encoding="utf-8")+ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):+ cli._write_last_run("OpenClaw", _report("OpenClaw"))++ fresh_report = _report("Different Topic")+ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \+ mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \+ mock.patch.object(cli.pipeline, "run", return_value=fresh_report) as run_mock, \+ mock.patch.object(cli.ui, "ProgressDisplay"), \+ mock.patch.object(sys, "argv", [+ "last30days.py",+ "Different",+ "Topic",+ "--emit=html",+ "--synthesis-file",+ str(synthesis_path),+ ]), \+ mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"}, clear=False):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()++ self.assertEqual(0, rc)+ self.assertTrue(run_mock.called)+ self.assertIn("No matching cached report data", stderr.getvalue())+ self.assertIn("Cached synthesis body.", stdout.getvalue())@unittest.skipIf(shutil.which("bash") is None, "bash not available")def test_hook_reads_last_run_from_custom_config_dir(self):