| 1 | """Execute the documented save flow with a local renderer boundary.""" |
| 2 | |
| 3 | import os |
| 4 | from pathlib import Path |
| 5 | import subprocess |
| 6 | from tests.skill_contract import reference_text |
| 7 | import sys |
| 8 | |
| 9 | import pytest |
| 10 | |
| 11 | |
| 12 | ROOT = Path(__file__).resolve().parents[1] |
| 13 | REFERENCE = ROOT / "skills/last30days/references/save-html-brief.md" |
| 14 | |
| 15 | |
| 16 | @pytest.fixture |
| 17 | def save_command(tmp_path): |
| 18 | skill_root = tmp_path / "skill with spaces" |
| 19 | scripts = skill_root / "scripts" |
| 20 | scripts.mkdir(parents=True) |
| 21 | (scripts / "last30days.py").write_text( |
| 22 | """import os |
| 23 | from pathlib import Path |
| 24 | import sys |
| 25 | import time |
| 26 | |
| 27 | assert '--emit=html' in sys.argv |
| 28 | assert '--cached-report' in sys.argv |
| 29 | assert '--plan' not in sys.argv and '--competitors-plan' not in sys.argv |
| 30 | synthesis = Path(sys.argv[sys.argv.index('--synthesis-file') + 1]) |
| 31 | assert synthesis.parent == Path(os.environ['TMPDIR']) |
| 32 | assert synthesis.stat().st_mode & 0o777 == 0o600 |
| 33 | assert synthesis.read_text().startswith('Fixture synthesis') |
| 34 | if '--publish-html' in sys.argv: |
| 35 | assert Path(sys.argv[sys.argv.index('--output') + 1]) == Path(os.environ['HTML_PATH']) |
| 36 | Path(os.environ['PUBLISH_CAPTURE']).write_bytes(synthesis.read_bytes()) |
| 37 | if ready_dir := os.environ.get('RENDER_READY_DIR'): |
| 38 | ready = Path(ready_dir) |
| 39 | (ready / str(os.getpid())).touch() |
| 40 | deadline = time.monotonic() + 10 |
| 41 | while len(list(ready.iterdir())) < 4: |
| 42 | if time.monotonic() > deadline: |
| 43 | raise RuntimeError('concurrent renderers did not arrive') |
| 44 | time.sleep(0.01) |
| 45 | sys.stdout.write(os.environ['RENDER_CONTENT']) |
| 46 | sys.exit(int(os.environ.get('RENDER_EXIT', '0'))) |
| 47 | """, |
| 48 | encoding="utf-8", |
| 49 | ) |
| 50 | output_dir = tmp_path / "saved briefs" |
| 51 | output_dir.mkdir() |
| 52 | scratch = tmp_path / "private drafts" |
| 53 | scratch.mkdir() |
| 54 | env = { |
| 55 | **os.environ, |
| 56 | "LAST30DAYS_PYTHON": sys.executable, |
| 57 | "SKILL_DIR": str(skill_root), |
| 58 | "LAST30DAYS_MEMORY_DIR": str(output_dir), |
| 59 | "TMPDIR": str(scratch), |
| 60 | "TOPIC": "Shell Safety", |
| 61 | "RENDER_CONTENT": "<html>first report</html>", |
| 62 | } |
| 63 | env.pop("SKILL_ROOT", None) |
| 64 | text = reference_text("save-html-brief") |
| 65 | block = text.split("```bash\n", 1)[1].split("```", 1)[0] |
| 66 | command = ["bash", "-c", "set -euo pipefail\nset -o noclobber\numask 022\n" |
| 67 | + block.replace("\nWhat I learned:\n", "\nFixture synthesis\n", 1) |
| 68 | + '\nif [ "${HOLD_DRAFT:-0}" = 0 ]; then rm -f -- "$SYNTHESIS_FILE"; fi\n' |
| 69 | + 'printf "%s\\n%s\\n" "$HTML_PATH" "$SYNTHESIS_FILE"\n'] |
| 70 | return command, env, output_dir |
| 71 | |
| 72 | |
| 73 | def test_repeated_html_exports_preserve_all_previous_bytes(save_command): |
| 74 | command, env, output_dir = save_command |
| 75 | saved = {} |
| 76 | for index in range(4): |
| 77 | content = f"<html>unique report {index}</html>" |
| 78 | result = subprocess.run( |
| 79 | command, env={**env, "RENDER_CONTENT": content}, |
| 80 | text=True, capture_output=True, timeout=20, |
| 81 | ) |
| 82 | assert result.returncode == 0, result.stderr |
| 83 | path = Path(result.stdout.splitlines()[-2]) |
| 84 | assert path not in saved, f"reused existing artifact: {path}" |
| 85 | saved[path] = content |
| 86 | assert {path: path.read_text() for path in saved} == saved |
| 87 | assert output_dir / "shell-safety-brief.html" in saved |
| 88 | assert set(output_dir.iterdir()) == set(saved) |
| 89 | assert not list(Path(env["TMPDIR"]).iterdir()) |
| 90 | |
| 91 | |
| 92 | def test_failed_html_render_preserves_existing_artifacts(save_command): |
| 93 | command, env, output_dir = save_command |
| 94 | existing = output_dir / "shell-safety-brief.html" |
| 95 | existing.write_bytes(b"existing report must survive\n") |
| 96 | result = subprocess.run( |
| 97 | command, env={**env, "RENDER_CONTENT": "partial output", "RENDER_EXIT": "42"}, |
| 98 | text=True, capture_output=True, timeout=20, |
| 99 | ) |
| 100 | assert result.returncode == 42, result.stderr |
| 101 | assert existing.read_bytes() == b"existing report must survive\n" |
| 102 | assert list(output_dir.iterdir()) == [existing] |
| 103 | assert not result.stdout |
| 104 | assert not list(Path(env["TMPDIR"]).iterdir()) |
| 105 | |
| 106 | |
| 107 | def test_concurrent_html_exports_publish_distinct_complete_files(save_command, tmp_path): |
| 108 | command, env, output_dir = save_command |
| 109 | ready = tmp_path / "renderers ready" |
| 110 | ready.mkdir() |
| 111 | contents = {f"<html>concurrent report {index}</html>" for index in range(4)} |
| 112 | processes = [ |
| 113 | subprocess.Popen( |
| 114 | command, |
| 115 | env={**env, "RENDER_CONTENT": content, "RENDER_READY_DIR": str(ready)}, |
| 116 | text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 117 | ) |
| 118 | for content in contents |
| 119 | ] |
| 120 | saved = [] |
| 121 | try: |
| 122 | for process in processes: |
| 123 | stdout, stderr = process.communicate(timeout=20) |
| 124 | assert process.returncode == 0, stderr |
| 125 | saved.append(Path(stdout.splitlines()[-2])) |
| 126 | finally: |
| 127 | for process in processes: |
| 128 | if process.poll() is None: |
| 129 | process.kill() |
| 130 | process.communicate() |
| 131 | assert len(set(saved)) == 4 |
| 132 | assert set(output_dir.iterdir()) == set(saved) |
| 133 | assert {path.read_text() for path in saved} == contents |
| 134 | assert not list(Path(env["TMPDIR"]).iterdir()) |
| 135 | |
| 136 | |
| 137 | @pytest.mark.parametrize("collision", ["directory", "broken_symlink"]) |
| 138 | def test_html_export_does_not_replace_nonregular_paths(save_command, collision): |
| 139 | command, env, output_dir = save_command |
| 140 | occupied = output_dir / "shell-safety-brief.html" |
| 141 | if collision == "directory": |
| 142 | occupied.mkdir() |
| 143 | else: |
| 144 | occupied.symlink_to(output_dir / "absent-target") |
| 145 | result = subprocess.run(command, env=env, text=True, capture_output=True, timeout=20) |
| 146 | assert result.returncode == 0, result.stderr |
| 147 | assert occupied.is_dir() if collision == "directory" else occupied.is_symlink() |
| 148 | assert not (output_dir / "absent-target").exists() |
| 149 | artifact = Path(result.stdout.splitlines()[-2]) |
| 150 | assert artifact != occupied |
| 151 | assert artifact.read_text() == env["RENDER_CONTENT"] |
| 152 | |
| 153 | |
| 154 | @pytest.mark.parametrize("exit_code", [0, 42]) |
| 155 | def test_hosted_handoff_uses_exact_private_draft_and_cleans_up(save_command, tmp_path, exit_code): |
| 156 | command, env, _ = save_command |
| 157 | saved = subprocess.run( |
| 158 | command, env={**env, "HOLD_DRAFT": "1"}, check=True, |
| 159 | text=True, capture_output=True, timeout=20, |
| 160 | ) |
| 161 | html_path, draft_path = map(Path, saved.stdout.splitlines()[-2:]) |
| 162 | assert draft_path.stat().st_mode & 0o777 == 0o600 |
| 163 | synthesis = draft_path.read_bytes() |
| 164 | captures = tmp_path / "published synthesis" |
| 165 | reference = reference_text("save-html-brief") |
| 166 | publish_block = reference.split("```bash\n")[2].split("```", 1)[0] |
| 167 | |
| 168 | result = subprocess.run( |
| 169 | ["bash", "-c", "set -euo pipefail\n" + publish_block], |
| 170 | env={**env, "HTML_PATH": str(html_path), "SYNTHESIS_FILE": str(draft_path), |
| 171 | "PUBLISH_CAPTURE": str(captures), "RENDER_EXIT": str(exit_code)}, |
| 172 | text=True, capture_output=True, timeout=20, |
| 173 | ) |
| 174 | |
| 175 | assert result.returncode == exit_code, result.stderr |
| 176 | assert captures.read_bytes() == synthesis |
| 177 | assert html_path.read_text() == env["RENDER_CONTENT"] |
| 178 | assert not draft_path.exists() |
| 179 |