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: add optional html publishing
Trevin Chow9b9439d25b9f
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex fc696749..89294892 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -45,6 +45,8 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--output <file>` - write the rendered output to an exact file path, using the format selected by `--emit`.- `--save-suffix <name>` - distinguish runs of the same topic (e.g. per client: `--save-suffix=acme`).- `--no-browser-cookies` - hard-disable browser-cookie extraction for this run, even when `FROM_BROWSER` is configured. MCP and folder-mode hosts use this for safe defaults.+- `--publish-html` - with `--emit=html`, publish the rendered HTML to `ht-ml.app` after local output/save-dir writes. This is explicit opt-in only; pages are public by default.+- `--publish-password <password>` - optional shared password for `--publish-html`. Use a unique non-personal password; never reuse the user's own password. The provider's update key is treated as secret and is not written to stdout, HTML, raw output, or `.publish.json` metadata.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.diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex cb15cd7c..33eb227f 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -1854,6 +1854,7 @@ Close with `I have all the links to the {N} {source list} I pulled from. Just as- Read `references/save-html-brief.md` BEFORE proceeding to WAIT FOR USER'S RESPONSE- Follow that file's instructions exactly - it is the canonical source for the save flow- Append the confirmation line (`📎 Shareable brief saved to <path>`) to your already-emitted chat response+- If the user explicitly asks for a hosted/shareable web link, follow the opt-in publishing instructions in the reference file. Never publish by default.**You MUST NOT:**@@ -1862,6 +1863,7 @@ Close with `I have all the links to the {N} {source list} I pulled from. Just as- Save to a different path than the reference specifies- Add data quality warnings, debug headers, or safety notes to the saved HTML- Re-research the topic for the HTML render - the engine cache covers the second invocation+- Upload or publish the HTML to a third-party host unless the user explicitly asked for hosted sharing and you have told them the link may be public/indexed unless password-protected**Why the directive is forceful:** the reference file is the only source of truth for the save flow. Skipping it produces broken artifacts - wrong path conventions, missing synthesis content, leaked engine debug output, or warnings that don't belong in shareable docs.diff --git a/skills/last30days/references/save-html-brief.md b/skills/last30days/references/save-html-brief.mdindex 686f2bcf..e76cbc9a 100644--- a/skills/last30days/references/save-html-brief.md+++ b/skills/last30days/references/save-html-brief.md@@ -72,6 +72,34 @@ fiecho "📎 Shareable brief saved to $HTML_PATH"```+## Optional hosted publishing++Only publish when the user explicitly asks for a hosted/shareable web link or confirms they want one after you offer it. Local HTML save remains the default.++Before publishing, tell the user:++- `ht-ml.app` publishes a public URL by default, and public pages may be crawled or indexed.+- A shared password can be set with `--publish-password`; use a unique non-personal password, not the user's real password.+- The local HTML file is still saved first. If upload fails, the local file remains usable.++Then ask whether they want password protection before uploading. Accept either branch:++- **Public link** - proceed with `--publish-html` only.+- **Password-protected link** - ask them to provide the shared password, then add `--publish-password "$PUBLISH_PASSWORD"`.++When the user opts in and answers the password-protection prompt, add `--publish-html` to the same `--emit=html` command. Add `--publish-password "$PUBLISH_PASSWORD"` only on the password-protected branch.++```bash+"${LAST30DAYS_PYTHON}" "${SKILL_ROOT}/scripts/last30days.py" "${TOPIC}" \+ --emit=html \+ --synthesis-file "$SYNTHESIS_FILE" \+ --publish-html \+ "${SCOPE_FLAGS[@]}" \+ >| "$HTML_PATH"+```++The hosted URL appears on stderr as `[last30days] Published HTML to https://...`. Append a second concise line to the chat response: `🌐 Hosted brief: <url>`. The provider may return an `update_key`; treat it as secret. The engine deliberately does not write the update key to stdout, the HTML artifact, or `.publish.json` companion metadata.+## What ends up in the HTML fileThe engine's `--emit=html` renderer combines:@@ -101,6 +129,8 @@ If the user runs `/last30days OpenClaw` normally, sees the synthesis in chat, an- Do NOT silently overwrite an existing file. The `--emit=html` output is written via a shell redirect (`>| "$HTML_PATH"`), which OVERWRITES the collision-guarded path — use `>|` not `>` because `set -o noclobber` refuses plain `>` when the file already exists. The collision guard in step 2 handles same-topic re-runs: if `{slug}-brief.html` already exists it date-suffixes to `{slug}-brief-YYYY-MM-DD.html`. Always print whichever path the redirect actually used.- Do NOT include the data quality warning text in the temp file or in your final chat line. Warnings are an engine-stderr concern, not an artifact concern.+- Do NOT publish to `ht-ml.app` merely because HTML was requested. Hosted publishing is a separate opt-in step.+- Do NOT paste or store the `update_key` in chat, Markdown, HTML, raw output, or companion metadata.## Edge casesdiff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 5746a54c..68db7f75 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -158,6 +158,34 @@ def save_rendered_output(rendered_content: str, output_file: str) -> Path:return out_path+def _publish_metadata_path(html_path: Path) -> Path:+ return html_path.with_name(f"{html_path.name}.publish.json")+++def _write_publish_metadata(html_path: Path, publish_result: dict[str, object]) -> None:+ payload = {+ "url": publish_result.get("url"),+ "site_id": publish_result.get("site_id"),+ "status": publish_result.get("status"),+ "published_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),+ }+ _publish_metadata_path(html_path).write_text(json.dumps(payload, indent=2), encoding="utf-8")+++def publish_rendered_html(+ rendered: str,+ *,+ password: str | None = None,+ companion_paths: list[Path] | None = None,+) -> dict[str, object]:+ from lib import html_publish++ result = html_publish.publish_html(rendered, password=password)+ for path in companion_paths or []:+ _write_publish_metadata(path, result)+ return result++def emit_output(report: schema.Report,emit: str,@@ -298,6 +326,10 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--save-dir", help="Optional directory for saving the rendered output")parser.add_argument("--output", help="Optional exact file path for saving the rendered output")parser.add_argument("--synthesis-file", help="Markdown synthesis to embed in --emit=html output")+ parser.add_argument("--publish-html", action="store_true",+ help="Publish --emit=html output to ht-ml.app (explicit opt-in; public by default)")+ parser.add_argument("--publish-password",+ help="Optional shared password for --publish-html")parser.add_argument("--store", action="store_true", help="Persist ranked findings to the SQLite research store")parser.add_argument("--x-handle", help="X handle for targeted supplemental search")parser.add_argument("--x-related", help="Comma-separated related X handles (searched with lower weight)")@@ -776,6 +808,9 @@ def main() -> int:if not topic:parser.print_usage(sys.stderr)return 2+ if args.publish_html and args.emit != "html":+ sys.stderr.write("[last30days] --publish-html requires --emit=html\n")+ return 2synthesis_md = Noneif args.synthesis_file:@@ -1196,8 +1231,11 @@ def main() -> int:save_path=footer_save_path,synthesis_md=synthesis_md,)+ publish_companion_paths: list[Path] = []if args.output:output_path = save_rendered_output(rendered, args.output)+ if args.emit == "html":+ publish_companion_paths.append(output_path)sys.stderr.write(f"[last30days] Saved output to {output_path}\n")sys.stderr.flush()if args.save_dir:@@ -1211,6 +1249,8 @@ def main() -> int:topic_override=comparison_topic(entity_reports) if is_comparison_html else None,rendered_content=rendered if is_comparison_html else None,)+ if args.emit == "html":+ publish_companion_paths.append(save_path)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).@@ -1223,6 +1263,23 @@ def main() -> int:)sys.stderr.write(f"[last30days] Saved output to {peer_path}\n")sys.stderr.flush()+ if args.publish_html:+ try:+ publish_result = publish_rendered_html(+ rendered,+ password=args.publish_password,+ companion_paths=publish_companion_paths,+ )+ sys.stderr.write(f"[last30days] Published HTML to {publish_result['url']}\n")+ if publish_result.get("update_key"):+ sys.stderr.write(+ "[last30days] ht-ml.app returned an update key; not writing it "+ "to stdout, HTML, or publish metadata.\n"+ )+ sys.stderr.flush()+ except Exception as exc:+ sys.stderr.write(f"[last30days] HTML publish failed: {exc}\n")+ sys.stderr.flush()print(rendered)return 0diff --git a/skills/last30days/scripts/lib/html_publish.py b/skills/last30days/scripts/lib/html_publish.pynew file mode 100644index 00000000..ae4d2a4c--- /dev/null+++ b/skills/last30days/scripts/lib/html_publish.py@@ -0,0 +1,71 @@+"""Optional hosted publishing for rendered HTML artifacts."""++from __future__ import annotations++import json+from typing import Any, Callable+from urllib.error import HTTPError, URLError+from urllib.request import Request, urlopen+++DEFAULT_ENDPOINT = "https://api.ht-ml.app/v1/sites"+++class HtmlPublishError(RuntimeError):+ """Raised when the hosted HTML publish endpoint rejects the artifact."""+++def publish_html(+ html_content: str,+ *,+ password: str | None = None,+ endpoint: str = DEFAULT_ENDPOINT,+ opener: Callable[..., Any] | None = None,+ timeout: int = 30,+) -> dict[str, Any]:+ """Publish a single HTML document and return the provider response."""+ if not html_content.strip():+ raise HtmlPublishError("HTML content is empty")++ payload: dict[str, str] = {"html_content": html_content}+ if password is not None:+ payload["password"] = password++ request = Request(+ endpoint,+ data=json.dumps(payload).encode("utf-8"),+ headers={"Content-Type": "application/json", "Accept": "application/json"},+ method="POST",+ )+ open_fn = opener or urlopen+ try:+ with open_fn(request, timeout=timeout) as response:+ body = response.read().decode("utf-8")+ except HTTPError as exc:+ detail = exc.read().decode("utf-8", errors="replace")+ raise HtmlPublishError(_error_message(exc.code, detail)) from exc+ except URLError as exc:+ raise HtmlPublishError(str(exc.reason)) from exc+ except OSError as exc:+ raise HtmlPublishError(str(exc)) from exc++ try:+ result = json.loads(body)+ except json.JSONDecodeError as exc:+ raise HtmlPublishError("publish endpoint returned non-JSON response") from exc++ url = result.get("url")+ if not isinstance(url, str) or not url.startswith("https://"):+ raise HtmlPublishError("publish endpoint response did not include a valid url")+ return result+++def _error_message(status: int, detail: str) -> str:+ try:+ payload = json.loads(detail)+ except json.JSONDecodeError:+ payload = {}+ message = payload.get("message") if isinstance(payload, dict) else None+ if message:+ return f"{status}: {message}"+ return f"{status}: {detail.strip() or 'publish failed'}"diff --git a/tests/test_doc_flag_contract.py b/tests/test_doc_flag_contract.pyindex 5858475b..1757a2e4 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]:@@ -26,6 +27,19 @@ def test_configuration_documents_new_safety_flags():assert "--no-browser-cookies" in textassert "--save-dir" in textassert "--output" in text+ assert "--publish-html" in flags+ assert "--publish-html" in text+ assert "--publish-password" in flags+ assert "--publish-password" in text+++def test_html_publish_reference_prompts_for_password_choice():+ text = HTML_REFERENCE.read_text(encoding="utf-8")+ publish_section = text[text.index("## Optional hosted publishing"):text.index("## What ends up in the HTML file")]+ assert "ask whether they want password protection before uploading" in publish_section+ assert "**Public link** - proceed with `--publish-html` only" in publish_section+ assert "**Password-protected link** - ask them to provide the shared password" in publish_section+ assert "Add `--publish-password \"$PUBLISH_PASSWORD\"` only on the password-protected branch" in publish_sectiondef test_save_is_not_documented_as_python_cli_flag():diff --git a/tests/test_html_publish.py b/tests/test_html_publish.pynew file mode 100644index 00000000..f9af70c6--- /dev/null+++ b/tests/test_html_publish.py@@ -0,0 +1,202 @@+"""Tests for optional hosted HTML publishing."""++from __future__ import annotations++import io+import json+import os+import sys+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from unittest import mock+from urllib.error import HTTPError++import last30days as cli+from lib import html_publish, schema+++def _report(topic: str = "OpenClaw") -> 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 _FakeResponse:+ def __init__(self, payload: dict[str, object]):+ self.payload = payload++ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ def read(self) -> bytes:+ return json.dumps(self.payload).encode("utf-8")+++class HtmlPublishModuleTests(unittest.TestCase):+ def test_publish_posts_html_and_password(self):+ captured = {}++ def opener(request, timeout):+ captured["timeout"] = timeout+ captured["url"] = request.full_url+ captured["headers"] = dict(request.header_items())+ captured["body"] = json.loads(request.data.decode("utf-8"))+ return _FakeResponse(+ {+ "url": "https://example.ht-ml.app",+ "site_id": "site_123",+ "status": "active",+ "update_key": "secret-update-key",+ }+ )++ result = html_publish.publish_html(+ "<html>ok</html>",+ password="share-pass",+ opener=opener,+ )++ self.assertEqual("https://api.ht-ml.app/v1/sites", captured["url"])+ self.assertEqual({"html_content": "<html>ok</html>", "password": "share-pass"}, captured["body"])+ self.assertEqual("https://example.ht-ml.app", result["url"])+ self.assertEqual("secret-update-key", result["update_key"])++ def test_publish_rejects_http_error_with_message(self):+ def opener(_request, timeout):+ raise HTTPError(+ "https://api.ht-ml.app/v1/sites",+ 400,+ "Bad Request",+ {},+ io.BytesIO(b'{"message":"HTML content is required"}'),+ )++ with self.assertRaisesRegex(html_publish.HtmlPublishError, "HTML content is required"):+ html_publish.publish_html("<html></html>", opener=opener)+++class HtmlPublishCliTests(unittest.TestCase):+ def test_publish_requires_html_emit(self):+ with mock.patch.object(sys, "argv", [+ "last30days.py",+ "OpenClaw",+ "--emit=md",+ "--publish-html",+ ]), mock.patch.object(cli.env, "get_config", return_value={}):+ stderr = io.StringIO()+ with redirect_stderr(stderr):+ rc = cli.main()+ self.assertEqual(2, rc)+ self.assertIn("--publish-html requires --emit=html", stderr.getvalue())++ def test_publish_writes_url_metadata_without_update_key(self):+ with tempfile.TemporaryDirectory() as tmp:+ output_path = Path(tmp) / "brief.html"+ with 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=_report()), \+ mock.patch.object(cli, "emit_output", return_value="<html>brief</html>"), \+ mock.patch.object(cli, "publish_rendered_html", wraps=cli.publish_rendered_html) as publish_wrapper, \+ mock.patch("lib.html_publish.publish_html", return_value={+ "url": "https://site.ht-ml.app",+ "site_id": "site_123",+ "status": "active",+ "update_key": "secret-update-key",+ }), \+ mock.patch.object(sys, "argv", [+ "last30days.py",+ "OpenClaw",+ "--emit=html",+ "--output",+ str(output_path),+ "--publish-html",+ ]), \+ 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)+ publish_wrapper.assert_called_once()+ self.assertEqual("<html>brief</html>", output_path.read_text(encoding="utf-8"))+ self.assertIn("Published HTML to https://site.ht-ml.app", stderr.getvalue())+ self.assertNotIn("secret-update-key", stdout.getvalue())+ self.assertNotIn("secret-update-key", stderr.getvalue())+ metadata = json.loads((Path(str(output_path) + ".publish.json")).read_text(encoding="utf-8"))+ self.assertEqual("https://site.ht-ml.app", metadata["url"])+ self.assertNotIn("update_key", metadata)++ def test_publish_failure_preserves_local_output(self):+ with tempfile.TemporaryDirectory() as tmp:+ output_path = Path(tmp) / "brief.html"+ with 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=_report()), \+ mock.patch.object(cli, "emit_output", return_value="<html>brief</html>"), \+ mock.patch("lib.html_publish.publish_html", side_effect=html_publish.HtmlPublishError("timeout")), \+ mock.patch.object(sys, "argv", [+ "last30days.py",+ "OpenClaw",+ "--emit=html",+ "--output",+ str(output_path),+ "--publish-html",+ ]), \+ 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.assertEqual("<html>brief</html>", output_path.read_text(encoding="utf-8"))+ self.assertIn("HTML publish failed: timeout", stderr.getvalue())+++if __name__ == "__main__":+ unittest.main()