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 explicit output file option (#566)
Hiten Shahbad3ba97fa7d
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 5002a585..081a17c4 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -29,6 +29,7 @@ Each run produces one file per topic, slug-named:**Per-run overrides:**- `--save-dir <path>` - one-off output location.+- `--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`).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/README.md b/README.mdindex 10e468d1..13e2befe 100644--- a/README.md+++ b/README.md@@ -289,7 +289,7 @@ See [CONFIGURATION.md](CONFIGURATION.md) for the full per-source key matrix, reaTwo things you'll likely want to know on day one:-**Where research files are saved.** `LAST30DAYS_MEMORY_DIR` defaults to `~/Documents/Last30Days/` (Windows: `C:\Users\<you>\Documents\Last30Days\`). Override by setting that env var to any path in your shell, or `--save-dir <path>` per run. Use `--save-suffix=<name>` to keep multiple variations of the same topic separate (e.g. per client). Each run produces `<slug>-raw[-suffix].md`.+**Where research files are saved.** `LAST30DAYS_MEMORY_DIR` defaults to `~/Documents/Last30Days/` (Windows: `C:\Users\<you>\Documents\Last30Days\`). Override by setting that env var to any path in your shell, or `--save-dir <path>` per run. Use `--output <file>` when you need the rendered result at an exact path, using the format selected by `--emit`. Use `--save-suffix=<name>` to keep multiple variations of the same topic separate (e.g. per client). Each `--save-dir` run produces `<slug>-raw[-suffix].md`.**Trend monitoring across runs.** The default mode produces a fresh markdown snapshot per run. To accumulate findings over time, add `--store` to persist into a SQLite database, then use [`scripts/watchlist.py`](skills/last30days/scripts/watchlist.py) for scheduled runs (with optional Slack / webhook delivery on new findings) and [`scripts/briefing.py`](skills/last30days/scripts/briefing.py) for daily / weekly digests. The full cadence pattern is in [CONFIGURATION.md](CONFIGURATION.md#trend-monitoring-store--watchlist--briefings).diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 4d03f63f..750cb219 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -560,7 +560,7 @@ If `--agent` appears in ARGUMENTS (e.g., `/last30days plaud granola --agent`):5. **Skip** the follow-up invitation ("I'm now an expert on X...")6. **Output** the complete research report and stop - do not wait for further input-Agent mode saves raw research data to `LAST30DAYS_MEMORY_DIR` (defaults to `~/Documents/Last30Days`) automatically via `--save-dir` (handled by the script, no extra tool calls).+Agent mode saves raw research data to `LAST30DAYS_MEMORY_DIR` (defaults to `~/Documents/Last30Days`) automatically via `--save-dir` (handled by the script, no extra tool calls). Use `--output <file>` only when a caller needs the rendered stdout artifact at an exact path, with the format controlled by `--emit`.Agent mode report format:diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 1e698def..df5fb222 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -126,6 +126,13 @@ def save_output(return out_path+def save_rendered_output(rendered_content: str, output_file: str) -> Path:+ out_path = Path(output_file).expanduser().resolve()+ out_path.parent.mkdir(parents=True, exist_ok=True)+ out_path.write_text(rendered_content, encoding="utf-8")+ return out_path++def emit_output(report: schema.Report,emit: str,@@ -204,6 +211,17 @@ def compute_save_path_display(save_dir: str, topic: str, suffix: str, emit: str)return raw.as_posix()+def compute_output_path_display(output_file: str) -> str:+ """Compute the user-friendly explicit output path shown in render footers."""+ raw = Path(output_file).expanduser().resolve()+ try:+ home = Path.home().resolve()+ relative = raw.relative_to(home)+ return f"~/{relative.as_posix()}"+ except ValueError:+ return raw.as_posix()++def read_synthesis_file(path: str) -> str:try:return Path(path).expanduser().read_text(encoding="utf-8")@@ -246,6 +264,7 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--mock", action="store_true", help="Use mock retrieval fixtures")parser.add_argument("--diagnose", action="store_true", help="Print provider and source availability")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("--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")@@ -979,7 +998,9 @@ def main() -> int:# 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.save_dir:+ 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.topicfooter_save_path = compute_save_path_display(args.save_dir, save_topic_for_display, args.save_suffix or "", args.emit@@ -1015,6 +1036,10 @@ def main() -> int: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(diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.pyindex 46de3258..e3f7bf9d 100644--- a/tests/test_cli_v3.py+++ b/tests/test_cli_v3.py@@ -102,6 +102,15 @@ class CliV3Tests(unittest.TestCase):self.assertEqual(["biosecurity", "ai", "agents"], args.topic)self.assertEqual([], extra)+ def test_build_parser_accepts_explicit_output_file(self):+ parser = cli.build_parser()+ args, extra = parser.parse_known_args(+ ["--emit", "json", "--output", "results/run.json", "biosecurity"]+ )+ self.assertEqual("results/run.json", args.output)+ self.assertEqual(["biosecurity"], args.topic)+ self.assertEqual([], extra)+def test_ensure_supported_python_rejects_old_interpreter_with_actionable_error(self):stderr = io.StringIO()with redirect_stderr(stderr):@@ -161,6 +170,13 @@ class CliV3Tests(unittest.TestCase):_, kwargs = write_text.call_argsself.assertEqual("utf-8", kwargs.get("encoding"))+ def test_save_rendered_output_writes_exact_file_path(self):+ with tempfile.TemporaryDirectory() as tmp:+ out_path = Path(tmp) / "nested" / "results.json"+ saved = cli.save_rendered_output('{"ok": true}', str(out_path))+ self.assertEqual(out_path.resolve(), saved)+ self.assertEqual('{"ok": true}', out_path.read_text(encoding="utf-8"))+def test_compute_save_path_display_uses_posix_slashes_under_home(self):# Regression: f"~/{relative}" stringified pathlib.Path with the# OS-native separator, producing "~/Documents\\Last30Days\\..." on@@ -185,6 +201,18 @@ class CliV3Tests(unittest.TestCase):finally:shutil.rmtree(tmp_under_home, ignore_errors=True)+ def test_compute_output_path_display_uses_posix_slashes_under_home(self):+ real_home = Path.home()+ tmp_under_home = Path(tempfile.mkdtemp(prefix="l30d_output_path_", dir=str(real_home)))+ try:+ output_path = tmp_under_home / "Documents" / "Last30Days" / "run.json"+ display = cli.compute_output_path_display(str(output_path))+ self.assertTrue(display.startswith("~/"), f"Expected '~/' prefix, got: {display}")+ self.assertNotIn("\\", display, f"Backslash leaked into display: {display}")+ self.assertTrue(display.endswith("Documents/Last30Days/run.json"), display)+ finally:+ shutil.rmtree(tmp_under_home, ignore_errors=True)+def test_persist_report_updates_run_status_on_success_and_failure(self):report = self.make_report()@@ -257,6 +285,95 @@ class CliV3Tests(unittest.TestCase):fake_progress.show_promo.assert_called_once_with("both", diag=diag)self.assertIn("# rendered", stdout.getvalue())+ def test_main_writes_rendered_output_to_explicit_file(self):+ report = self.make_report()+ diag = {+ "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",+ }+ with tempfile.TemporaryDirectory() as tmp:+ output_path = Path(tmp) / "exports" / "run.json"+ 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='{"rendered": true}') as emit, \+ mock.patch.object(sys, "argv", [+ "last30days.py",+ "test",+ "topic",+ "--emit=json",+ "--output",+ str(output_path),+ ]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()+ self.assertEqual(0, rc)+ emit.assert_called_once()+ self.assertEqual('{"rendered": true}\n', stdout.getvalue())+ self.assertEqual('{"rendered": true}', output_path.read_text(encoding="utf-8"))+ self.assertIn(f"[last30days] Saved output to {output_path.resolve()}", stderr.getvalue())++ def test_main_combines_output_and_save_dir_for_comparison_html(self):+ report = self.make_report()+ diag = {+ "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",+ }+ fake_progress = mock.Mock()+ with tempfile.TemporaryDirectory() as tmp:+ output_path = Path(tmp) / "exports" / "comparison.html"+ save_dir = Path(tmp) / "saved"+ 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.ui, "ProgressDisplay", return_value=fake_progress), \+ mock.patch.object(+ cli, "emit_comparison_output", return_value="<html>comparison</html>"+ ) as emit_comparison, \+ mock.patch.object(cli, "emit_output", return_value="<html>peer</html>"), \+ mock.patch.object(sys, "argv", [+ "last30days.py",+ "Alpha",+ "vs",+ "Beta",+ "--mock",+ "--emit=html",+ "--output",+ str(output_path),+ "--save-dir",+ str(save_dir),+ ]):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()++ self.assertEqual(0, rc)+ output_display = cli.compute_output_path_display(str(output_path))+ _, kwargs = emit_comparison.call_args+ self.assertEqual(output_display, kwargs["save_path"])+ self.assertEqual("<html>comparison</html>\n", stdout.getvalue())+ self.assertEqual("<html>comparison</html>", output_path.read_text(encoding="utf-8"))+ comparison_saved = save_dir / "alpha-vs-beta-raw-html.html"+ self.assertEqual(+ "<html>comparison</html>",+ comparison_saved.read_text(encoding="utf-8"),+ )+ self.assertIn(f"[last30days] Saved output to {output_path.resolve()}", stderr.getvalue())+ self.assertIn(f"[last30days] Saved output to {comparison_saved.resolve()}", stderr.getvalue())+def test_main_canonicalizes_explicit_github_repo_flags(self):report = self.make_report()diag = {