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: expire html report cache safely
Trevin Chow136b4f90c1a8
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex fc696749..97452bb5 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -48,6 +48,8 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(The footer line `📎 Raw results saved to ${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}/<slug>-raw.md` is the canonical pointer; if it shows backslashes on Windows update past v3.1.1.+HTML follow-up renders also write a structured `last-report.json` cache beside `last-run.json` so `--emit=html --synthesis-file` can reuse the report metadata/footer without fetching sources again. Reuse is intentionally short-lived: `LAST30DAYS_REPORT_CACHE_TTL_SECONDS` defaults to `3600` (one hour). Set it to another integer number of seconds to tune the window, or `0` to disable report-cache reuse.+---## First-run onboardingdiff --git a/skills/last30days/references/save-html-brief.md b/skills/last30days/references/save-html-brief.mdindex 5a73eec5..96916ad2 100644--- a/skills/last30days/references/save-html-brief.md+++ b/skills/last30days/references/save-html-brief.md@@ -44,7 +44,9 @@ SYNTHESIS_EOF# 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+# without re-running source fetchers. That cache is intentionally short-lived+# (default: one hour; tune with LAST30DAYS_REPORT_CACHE_TTL_SECONDS, or set+# it to 0 to disable reuse). If the cache is stale, 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.@@ -94,7 +96,7 @@ 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.+The engine will try to reuse `~/.config/last30days/last-report.json` for that second invocation when it is still within `LAST30DAYS_REPORT_CACHE_TTL_SECONDS` (default: one hour). If stderr says it is reusing cached report data, continue normally. If stderr says no matching cache exists, the cache may be stale; 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 dodiff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 53174bfc..0485d292 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -603,6 +603,7 @@ def _show_runtime_ui(REPORT_CACHE_VERSION = "last30days-report-cache/v1"+DEFAULT_REPORT_CACHE_TTL_SECONDS = 3600def _last_report_cache_path() -> Path | None:@@ -611,6 +612,35 @@ def _last_report_cache_path() -> Path | None:return env.CONFIG_DIR / "last-report.json"+def _report_cache_ttl_seconds(config: dict[str, object]) -> int:+ raw = os.environ.get("LAST30DAYS_REPORT_CACHE_TTL_SECONDS")+ if raw is None:+ raw = config.get("LAST30DAYS_REPORT_CACHE_TTL_SECONDS")+ if raw is None or raw == "":+ return DEFAULT_REPORT_CACHE_TTL_SECONDS+ try:+ return max(0, int(raw))+ except (TypeError, ValueError):+ return DEFAULT_REPORT_CACHE_TTL_SECONDS+++def _is_report_cache_fresh(timestamp: object, ttl_seconds: int) -> bool:+ if ttl_seconds <= 0:+ return False+ if not isinstance(timestamp, str) or not timestamp:+ return False+ try:+ created_at = datetime.datetime.fromisoformat(timestamp)+ except ValueError:+ return False+ if created_at.tzinfo is None:+ created_at = created_at.replace(tzinfo=datetime.timezone.utc)+ age = datetime.datetime.now(datetime.timezone.utc) - created_at.astimezone(+ datetime.timezone.utc+ )+ return age.total_seconds() <= ttl_seconds++def _write_last_run(topic: str,report: "schema.Report",@@ -649,6 +679,7 @@ def _write_last_run(def _load_last_report_cache(topic: str,+ ttl_seconds: int = DEFAULT_REPORT_CACHE_TTL_SECONDS,) -> 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():@@ -657,6 +688,8 @@ def _load_last_report_cache(payload = json.loads(cache_path.read_text(encoding="utf-8"))if payload.get("schema") != REPORT_CACHE_VERSION:return None+ if not _is_report_cache_fresh(payload.get("timestamp"), ttl_seconds):+ return Nonecached_topic = str(payload.get("topic") or "").strip().lower()if cached_topic != topic.strip().lower():return None@@ -670,7 +703,11 @@ def _load_last_report_cache(]if not entity_reports:return None- if payload.get("comparison") and len(entity_reports) > 1:+ if payload.get("comparison"):+ if len(entity_reports) < 2:+ return None+ if len(entity_reports) != len(reports_payload):+ return Nonereturn entity_reports[0][1], entity_reports, cache_pathreturn entity_reports[0][1], None, cache_pathexcept Exception:@@ -918,7 +955,10 @@ def main() -> int:return 2if args.emit == "html" and synthesis_md is not None:- cached = _load_last_report_cache(topic)+ cached = _load_last_report_cache(+ topic,+ ttl_seconds=_report_cache_ttl_seconds(config),+ )if cached is not None:cached_report, cached_entity_reports, cache_path = cachedsys.stderr.write(diff --git a/tests/test_doc_flag_contract.py b/tests/test_doc_flag_contract.pyindex 968933d7..c9815e23 100644--- a/tests/test_doc_flag_contract.py+++ b/tests/test_doc_flag_contract.py@@ -49,3 +49,12 @@ def test_html_reference_documents_structured_cache_reuse():assert "~/.config/last30days/last-report.json" in textassert "without re-running source fetchers" in textassert "No matching cached report data" in text+ assert "LAST30DAYS_REPORT_CACHE_TTL_SECONDS" in text+ assert "default: one hour" in text+++def test_configuration_documents_report_cache_ttl():+ text = CONFIGURATION.read_text(encoding="utf-8")+ assert "LAST30DAYS_REPORT_CACHE_TTL_SECONDS" in text+ assert "defaults to `3600`" in text+ assert "`0` to disable report-cache reuse" in textdiff --git a/tests/test_last_run_state.py b/tests/test_last_run_state.pyindex 13f0edbe..af68c862 100644--- a/tests/test_last_run_state.py+++ b/tests/test_last_run_state.py@@ -119,6 +119,42 @@ class LastRunStateTests(unittest.TestCase):self.assertIsNone(entity_reports)self.assertEqual(config_dir / "last-report.json", cache_path)+ def test_last_report_cache_expires_after_ttl(self):+ with tempfile.TemporaryDirectory() as tmp:+ config_dir = Path(tmp) / "config"+ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):+ cli._write_last_run("OpenClaw", _report("OpenClaw"))+ cache_path = config_dir / "last-report.json"+ payload = json.loads(cache_path.read_text(encoding="utf-8"))+ payload["timestamp"] = "2026-01-01T00:00:00+00:00"+ cache_path.write_text(json.dumps(payload), encoding="utf-8")+ loaded = cli._load_last_report_cache("OpenClaw", ttl_seconds=3600)++ self.assertIsNone(loaded)++ def test_last_report_cache_ttl_zero_disables_reuse(self):+ with tempfile.TemporaryDirectory() as tmp:+ config_dir = Path(tmp) / "config"+ with mock.patch.object(cli.env, "CONFIG_DIR", config_dir):+ cli._write_last_run("OpenClaw", _report("OpenClaw"))+ loaded = cli._load_last_report_cache("OpenClaw", ttl_seconds=0)++ self.assertIsNone(loaded)++ def test_partial_comparison_cache_does_not_degrade_to_single_report(self):+ with tempfile.TemporaryDirectory() as tmp:+ config_dir = Path(tmp) / "config"+ 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)+ cache_path = config_dir / "last-report.json"+ payload = json.loads(cache_path.read_text(encoding="utf-8"))+ payload["reports"] = payload["reports"][:1]+ cache_path.write_text(json.dumps(payload), encoding="utf-8")+ loaded = cli._load_last_report_cache("Alpha vs Beta")++ self.assertIsNone(loaded)+def test_html_synthesis_reuses_cached_single_report_without_pipeline_run(self):with tempfile.TemporaryDirectory() as tmp:config_dir = Path(tmp) / "config"@@ -217,6 +253,42 @@ class LastRunStateTests(unittest.TestCase):self.assertIn("No matching cached report data", stderr.getvalue())self.assertIn("Cached synthesis body.", stdout.getvalue())+ def test_html_synthesis_falls_back_when_cache_is_stale(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"))+ cache_path = config_dir / "last-report.json"+ payload = json.loads(cache_path.read_text(encoding="utf-8"))+ payload["timestamp"] = "2026-01-01T00:00:00+00:00"+ cache_path.write_text(json.dumps(payload), encoding="utf-8")++ fresh_report = _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", return_value=fresh_report) as run_mock, \+ mock.patch.object(cli.ui, "ProgressDisplay"), \+ 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.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):with tempfile.TemporaryDirectory() as tmp: