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: preserve earlier HTML briefs during repeated exports (#1222)

Ilia Alshanetskydddf04e6253b
diff --git a/changelog.d/+cr-020-html-output-collisions.fixed.md b/changelog.d/+cr-020-html-output-collisions.fixed.md
new file mode 100644
index 00000000..0696c3e9
--- /dev/null
+++ b/changelog.d/+cr-020-html-output-collisions.fixed.md
@@ -0,0 +1 @@
+Preserve existing HTML briefs across repeated or concurrent exports, and publish a new local artifact only after rendering succeeds.
diff --git a/skills/last30days/references/save-html-brief.md b/skills/last30days/references/save-html-brief.md
index 2bfb2c4e..a29addd5 100644
--- a/skills/last30days/references/save-html-brief.md
+++ b/skills/last30days/references/save-html-brief.md
@@ -31,7 +31,7 @@ The contract has two modes:
SYNTHESIS_FILE="/tmp/last30days-synthesis-${CLAUDE_SESSION_ID}.md"
# >| not >: fixed path may already exist on a same-session re-run; a plain >
# is refused under `set -o noclobber`.
-cat >| "$SYNTHESIS_FILE" <<'SYNTHESIS_EOF'
+cat >| "${SYNTHESIS_FILE}" << 'SYNTHESIS_EOF'
What I learned:
**{First headline}** - {body with [name](url) inline citations}
@@ -57,20 +57,39 @@ SYNTHESIS_EOF
# 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
-# does NOT auto-date the brief (its date-suffix logic applies only to --save-dir
-# raw files, not to this redirected --emit=html stream). So if the clean name
-# already exists, date-suffix it here to avoid clobbering a prior brief.
-if [ -f "$HTML_PATH" ]; then
- HTML_PATH="${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief-$(date +%F).html"
-fi
-"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" "${TOPIC}" \
- --emit=html \
- --synthesis-file "$SYNTHESIS_FILE" \
- "${SCOPE_FLAGS[@]}" \
- >| "$HTML_PATH" # >| not >: noclobber-safe write to the collision-guarded path
+SLUG=$(printf '%s\n' "${TOPIC}" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//')
+# Render beside the destination, then create a new name atomically. The hard
+# link refuses existing paths even when another exporter wins the same name.
+HTML_PATH=$(
+ HTML_TMP=$(mktemp "${LAST30DAYS_MEMORY_DIR}/.last30days-html.XXXXXXXX") || exit "$?"
+ trap 'rm -f -- "${HTML_TMP}"' EXIT
+ "${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" "${TOPIC}" \
+ --emit=html \
+ --synthesis-file "${SYNTHESIS_FILE}" \
+ "${SCOPE_FLAGS[@]}" \
+ >| "${HTML_TMP}" || exit "$?"
+ "${LAST30DAYS_PYTHON}" - "${HTML_TMP}" "${LAST30DAYS_MEMORY_DIR}" "${SLUG}" << 'HTML_PATH_PY'
+from datetime import date
+import os
+from pathlib import Path
+import sys
+
+temporary, directory, slug = sys.argv[1:]
+base = Path(directory) / f"{slug}-brief"
+dated = f"{base}-{date.today().isoformat()}"
+candidate = Path(f"{base}.html")
+suffix = 1
+while True:
+ try:
+ os.link(temporary, candidate)
+ except FileExistsError:
+ candidate = Path(f"{dated}.html" if suffix == 1 else f"{dated}-{suffix}.html")
+ suffix += 1
+ else:
+ print(candidate)
+ break
+HTML_PATH_PY
+) || exit "$?"
# where SCOPE_FLAGS is the same array you passed the first time, e.g.
# SCOPE_FLAGS=(--hiring-signals --plan "$QUERY_PLAN_FILE" --x-handle=acme).
# For a scoped --hiring-signals brief, --hiring-signals MUST be here too so
@@ -189,7 +208,7 @@ The engine will try to reuse `~/.config/last30days/last-report.json` for that se
- Do NOT save HTML if the user didn't ask. The sparse mode (no synthesis) produces a thin file; not useful as a shareable.
- Do NOT add content to the temp file beyond your synthesis prose. The badge / footer / colophon come from the engine.
- Do NOT change the file path convention. `${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief.html` is the canonical location.
-- 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 report whichever path the redirect actually used in the chat handoff.
+- Do NOT overwrite an existing file. Step 2 renders to a private temporary file and links the completed output to a new name. If `{slug}-brief.html` exists, try `{slug}-brief-YYYY-MM-DD.html`, then `{slug}-brief-YYYY-MM-DD-2.html`, incrementing until a name is available. This also handles concurrent exporters without replacing files, directories, or symlinks. The temporary file is removed on success or failure. If rendering or linking fails, report the error instead of a successful save. Always report the path stored in `HTML_PATH` in the chat handoff.
- 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, upload, or send the HTML to a third-party service as part of the local save flow.
- Do NOT publish to any service merely because HTML was requested. Show the saved path and next-step choices first; publishing requires the user to choose a publish option.
diff --git a/tests/test_html_save_contract.py b/tests/test_html_save_contract.py
index 0643d964..cef10c99 100644
--- a/tests/test_html_save_contract.py
+++ b/tests/test_html_save_contract.py
@@ -72,4 +72,4 @@ def test_follow_up_turn_preserves_html_deliverable_mode():
text = SAVE_HTML.read_text(encoding="utf-8")
assert "explicitly refers back to that visible synthesis" in text
assert "treat it as HTML-as-deliverable mode" in text
- assert "Always report whichever path the redirect actually used in the chat handoff" in text
+ assert "Always report the path stored in `HTML_PATH` in the chat handoff" in text
diff --git a/tests/test_html_save_execution.py b/tests/test_html_save_execution.py
new file mode 100644
index 00000000..8b213c85
--- /dev/null
+++ b/tests/test_html_save_execution.py
@@ -0,0 +1,139 @@
+"""Execute the documented save flow with a local renderer boundary."""
+
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+REFERENCE = ROOT / "skills/last30days/references/save-html-brief.md"
+
+
+def save_command(tmp_path):
+ skill_root = tmp_path / "skill with spaces"
+ scripts = skill_root / "scripts"
+ scripts.mkdir(parents=True)
+ (scripts / "last30days.py").write_text(
+ """import os
+from pathlib import Path
+import sys
+import time
+
+assert '--emit=html' in sys.argv
+assert '--hiring-signals' in sys.argv
+if ready_dir := os.environ.get('RENDER_READY_DIR'):
+ ready = Path(ready_dir)
+ (ready / str(os.getpid())).touch()
+ deadline = time.monotonic() + 10
+ while len(list(ready.iterdir())) < 4:
+ if time.monotonic() > deadline:
+ raise RuntimeError('concurrent renderers did not arrive')
+ time.sleep(0.01)
+sys.stdout.write(os.environ['RENDER_CONTENT'])
+sys.exit(int(os.environ.get('RENDER_EXIT', '0')))
+""",
+ encoding="utf-8",
+ )
+ output_dir = tmp_path / "saved briefs"
+ output_dir.mkdir()
+ synthesis = tmp_path / "synthesis.md"
+ synthesis.write_text("Fixture synthesis", encoding="utf-8")
+ env = {
+ **os.environ,
+ "LAST30DAYS_PYTHON": sys.executable,
+ "SKILL_DIR": str(skill_root),
+ "LAST30DAYS_MEMORY_DIR": str(output_dir),
+ "SYNTHESIS_FILE": str(synthesis),
+ "TOPIC": "Shell Safety",
+ "RENDER_CONTENT": "<html>first report</html>",
+ }
+ env.pop("SKILL_ROOT", None)
+ text = REFERENCE.read_text(encoding="utf-8")
+ block = text.split("```bash\n", 1)[1].split("```", 1)[0]
+ flow = block[block.index("SLUG="):]
+ command = ["bash", "-c", "set -euo pipefail\nset -o noclobber\n"
+ "SCOPE_FLAGS=(--hiring-signals)\n" + flow
+ + '\nprintf "%s\\n" "$HTML_PATH"\n']
+ return command, env, output_dir
+
+
+def test_repeated_html_exports_preserve_all_previous_bytes(save_command):
+ command, env, output_dir = save_command
+ saved = {}
+ for index in range(4):
+ content = f"<html>unique report {index}</html>"
+ result = subprocess.run(
+ command, env={**env, "RENDER_CONTENT": content},
+ text=True, capture_output=True, timeout=20,
+ )
+ assert result.returncode == 0, result.stderr
+ path = Path(result.stdout.strip())
+ assert path not in saved, f"reused existing artifact: {path}"
+ saved[path] = content
+ assert {path: path.read_text() for path in saved} == saved
+ assert output_dir / "shell-safety-brief.html" in saved
+ assert set(output_dir.iterdir()) == set(saved)
+
+
+def test_failed_html_render_preserves_existing_artifacts(save_command):
+ command, env, output_dir = save_command
+ existing = output_dir / "shell-safety-brief.html"
+ existing.write_bytes(b"existing report must survive\n")
+ result = subprocess.run(
+ command, env={**env, "RENDER_CONTENT": "partial output", "RENDER_EXIT": "42"},
+ text=True, capture_output=True, timeout=20,
+ )
+ assert result.returncode == 42, result.stderr
+ assert existing.read_bytes() == b"existing report must survive\n"
+ assert list(output_dir.iterdir()) == [existing]
+ assert not result.stdout
+
+
+def test_concurrent_html_exports_publish_distinct_complete_files(save_command, tmp_path):
+ command, env, output_dir = save_command
+ ready = tmp_path / "renderers ready"
+ ready.mkdir()
+ contents = {f"<html>concurrent report {index}</html>" for index in range(4)}
+ processes = [
+ subprocess.Popen(
+ command,
+ env={**env, "RENDER_CONTENT": content, "RENDER_READY_DIR": str(ready)},
+ text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ )
+ for content in contents
+ ]
+ saved = []
+ try:
+ for process in processes:
+ stdout, stderr = process.communicate(timeout=20)
+ assert process.returncode == 0, stderr
+ saved.append(Path(stdout.strip()))
+ finally:
+ for process in processes:
+ if process.poll() is None:
+ process.kill()
+ process.communicate()
+ assert len(set(saved)) == 4
+ assert set(output_dir.iterdir()) == set(saved)
+ assert {path.read_text() for path in saved} == contents
+
+
[email protected]("collision", ["directory", "broken_symlink"])
+def test_html_export_does_not_replace_nonregular_paths(save_command, collision):
+ command, env, output_dir = save_command
+ occupied = output_dir / "shell-safety-brief.html"
+ if collision == "directory":
+ occupied.mkdir()
+ else:
+ occupied.symlink_to(output_dir / "absent-target")
+ result = subprocess.run(command, env=env, text=True, capture_output=True, timeout=20)
+ assert result.returncode == 0, result.stderr
+ assert occupied.is_dir() if collision == "directory" else occupied.is_symlink()
+ assert not (output_dir / "absent-target").exists()
+ artifact = Path(result.stdout.strip())
+ assert artifact != occupied
+ assert artifact.read_text() == env["RENDER_CONTENT"]