Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix: bind footer to actual saved report path

terry-li-hm472207164afc
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 528c3c84..750aed19 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
+# fmt: off
# ruff: noqa: E402
"""last30days CLI."""
@@ -15,6 +16,7 @@ import signal
import sqlite3
import sys
import threading
+from collections.abc import Callable
from pathlib import Path
MIN_PYTHON = (3, 12)
@@ -222,6 +224,7 @@ def save_output(
json_profile: str = "agent",
register: str = "default",
private: bool | None = None,
+ render_fn: Callable[[Path], str] | None = None,
) -> Path:
from datetime import datetime
path = Path(save_dir).expanduser().resolve()
@@ -237,21 +240,24 @@ def save_output(
candidates.append(path / f"{slug}-{raw_label}{suffix_part}-{date_str}-{i}.{extension}")
# Markdown saves keep the complete debug artifact. JSON and HTML preserve
# their requested wire format so file extensions match their content.
- if rendered_content is not None:
- content = rendered_content
- elif emit in {"json", "html"}:
- content = emit_output(
- report,
- emit,
- synthesis_md=synthesis_md,
- json_profile=json_profile,
- register=register,
- )
- else:
- content = render.render_full(report)
+ # When render_fn is supplied, content is produced after O_EXCL allocates
+ # the candidate. This lets the footer cite the file actually written
+ # without racing a separate filesystem probe.
+ if render_fn is None:
+ if rendered_content is not None:
+ static_content = rendered_content
+ elif emit in {"json", "html"}:
+ static_content = emit_output(
+ report,
+ emit,
+ synthesis_md=synthesis_md,
+ json_profile=json_profile,
+ register=register,
+ )
+ else:
+ static_content = render.render_full(report)
private_corpus = _report_has_private_corpus(report) or bool(private)
_ensure_output_directory(path, private=private_corpus)
- encoded = content.encode("utf-8")
for candidate in candidates:
try:
fd = os.open(
@@ -261,8 +267,18 @@ def save_output(
)
except FileExistsError:
continue
- with os.fdopen(fd, "wb") as f:
- f.write(encoded)
+ try:
+ with os.fdopen(fd, "wb") as f:
+ content = render_fn(candidate) if render_fn is not None else static_content
+ f.write(content.encode("utf-8"))
+ except BaseException:
+ # Deferred rendering happens after the candidate is reserved. Do
+ # not leave an empty or partial report if rendering or writing fails.
+ try:
+ candidate.unlink(missing_ok=True)
+ except OSError:
+ pass
+ raise
if candidate.suffix.lower() == ".md":
try:
from lib import library, library_index
@@ -2263,6 +2279,32 @@ def _render_save_and_print(
sys.stderr.flush()
if args.save_dir:
# Save the main topic's raw file (single-entity or comparison main).
+ # Bind the render to the path save_output actually allocates so the
+ # saved report and stdout agree even when collision fallback is used.
+ def _render_with_actual_path(actual_path: Path) -> str:
+ nonlocal rendered
+ display = compute_output_path_display(str(actual_path))
+ if entity_reports:
+ rendered = emit_comparison_output(
+ entity_reports,
+ args.emit,
+ fun_level=fun_level,
+ save_path=display,
+ synthesis_md=synthesis_md,
+ json_profile=args.json_profile,
+ )
+ else:
+ rendered = emit_output(
+ report,
+ args.emit,
+ fun_level=fun_level,
+ save_path=display,
+ synthesis_md=synthesis_md,
+ json_profile=args.json_profile,
+ register=audience.name,
+ )
+ return rendered
+
save_path = save_output(
report,
args.emit,
@@ -2270,10 +2312,10 @@ def _render_save_and_print(
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,
json_profile=args.json_profile,
register=audience.name,
private=private_saved_format,
+ render_fn=_render_with_actual_path,
)
if args.emit == "html":
publish_companion_paths.append(save_path)
diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.py
index 43ccd19f..c2a1d308 100644
--- a/tests/test_cli_v3.py
+++ b/tests/test_cli_v3.py
@@ -1,3 +1,4 @@
+# fmt: off
import contextlib
import json
import io
@@ -324,6 +325,84 @@ class CliV3Tests(unittest.TestCase):
self.assertEqual("dated content", dated.read_text(encoding="utf-8"))
self.assertTrue(saved.exists())
+ def test_save_output_render_fn_footer_names_actual_collision_path(self):
+ from lib import render as render_module
+
+ report = self.make_report()
+ with tempfile.TemporaryDirectory() as tmp:
+ save_dir = Path(tmp)
+ today = datetime.now().strftime("%Y-%m-%d")
+ base = save_dir / "openclaw-vs-nanoclaw-raw.md"
+ dated = save_dir / f"openclaw-vs-nanoclaw-raw-{today}.md"
+ base.write_text("base content", encoding="utf-8")
+ dated.write_text("dated content", encoding="utf-8")
+
+ def render_fn(actual_path: Path) -> str:
+ return render_module.render_compact(report, save_path=str(actual_path))
+
+ saved = cli.save_output(report, "md", tmp, render_fn=render_fn)
+
+ expected = (save_dir / f"openclaw-vs-nanoclaw-raw-{today}-1.md").resolve()
+ self.assertEqual(expected, saved.resolve())
+ content = saved.read_text(encoding="utf-8")
+ self.assertIn(f"Raw results saved to {saved}", content)
+ self.assertNotIn(f"Raw results saved to {base}", content)
+ self.assertNotIn(f"Raw results saved to {dated}", content)
+ self.assertEqual("base content", base.read_text(encoding="utf-8"))
+ self.assertEqual("dated content", dated.read_text(encoding="utf-8"))
+
+ def test_save_output_removes_reserved_candidate_when_deferred_render_fails(self):
+ report = self.make_report()
+ with tempfile.TemporaryDirectory() as tmp:
+ save_dir = Path(tmp)
+
+ def fail_render(_actual_path: Path) -> str:
+ raise RuntimeError("render failed")
+
+ with self.assertRaisesRegex(RuntimeError, "render failed"):
+ cli.save_output(report, "md", tmp, render_fn=fail_render)
+
+ self.assertEqual([], list(save_dir.iterdir()))
+
+ def test_render_save_and_print_uses_actual_collision_path_in_file_and_stdout(self):
+ report = self.make_report(topic="Collision Topic")
+ with tempfile.TemporaryDirectory() as tmp:
+ save_dir = Path(tmp)
+ today = datetime.now().strftime("%Y-%m-%d")
+ base = save_dir / "collision-topic-raw.md"
+ dated = save_dir / f"collision-topic-raw-{today}.md"
+ expected = save_dir / f"collision-topic-raw-{today}-1.md"
+ base.write_text("base content", encoding="utf-8")
+ dated.write_text("dated content", encoding="utf-8")
+ args = types.SimpleNamespace(
+ topic=["Collision Topic"],
+ competitors=None,
+ competitors_list=None,
+ competitors_plan=None,
+ drill=False,
+ register=None,
+ emit="compact",
+ output=None,
+ save_dir=str(save_dir),
+ save_suffix="",
+ json_profile="agent",
+ publish_html=False,
+ )
+ stdout = io.StringIO()
+ stderr = io.StringIO()
+
+ with redirect_stdout(stdout), redirect_stderr(stderr):
+ rc = cli._render_save_and_print(args, report, None, None, {})
+
+ self.assertEqual(0, rc)
+ expected_display = cli.compute_output_path_display(str(expected))
+ footer = f"Raw results saved to {expected_display}"
+ self.assertTrue(expected.exists())
+ self.assertIn(footer, expected.read_text(encoding="utf-8"))
+ self.assertIn(footer, stdout.getvalue())
+ self.assertEqual("base content", base.read_text(encoding="utf-8"))
+ self.assertEqual("dated content", dated.read_text(encoding="utf-8"))
+
def test_save_output_writes_utf8_encoded_markdown(self):
report = self.make_report()
with tempfile.TemporaryDirectory() as tmp:
@@ -531,11 +610,15 @@ class CliV3Tests(unittest.TestCase):
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"])
+ comparison_saved = save_dir / "alpha-vs-beta-raw-html.html"
+ self.assertEqual(2, emit_comparison.call_count)
+ first_kwargs = emit_comparison.call_args_list[0].kwargs
+ second_kwargs = emit_comparison.call_args_list[1].kwargs
+ self.assertEqual(output_display, first_kwargs["save_path"])
+ comparison_display = cli.compute_output_path_display(str(comparison_saved))
+ self.assertEqual(comparison_display, second_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"),