| 1 | """Execute the documented comparison shell recipe up to its engine boundary.""" |
| 2 | |
| 3 | import json |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import re |
| 7 | import shlex |
| 8 | import shutil |
| 9 | import subprocess |
| 10 | import sys |
| 11 | |
| 12 | import last30days as cli |
| 13 | import pytest |
| 14 | from lib import planner |
| 15 | from tests.skill_contract import reference_text |
| 16 | |
| 17 | |
| 18 | def _command(text: str, heading: str) -> str: |
| 19 | section = text.split(f"### {heading}\n", 1)[1] |
| 20 | block = re.search(r"```bash\n(.*?)\n```", section, re.S) |
| 21 | assert block is not None |
| 22 | return block[1] |
| 23 | |
| 24 | |
| 25 | def test_host_comparison_plan_covers_only_the_main_entity(): |
| 26 | research = reference_text("research-runbook") |
| 27 | planning = research.split("## Step 0.75: Generate Query Plan", 1)[1].split( |
| 28 | "## Research Execution", 1, |
| 29 | )[0] |
| 30 | rule = next(line for line in planning.splitlines() if line.startswith('- For comparison (')) |
| 31 | assert "TOPIC_A only" in rule |
| 32 | assert "`comparison.md`" in rule |
| 33 | assert "peer sub-runs plan independently" in rule |
| 34 | assert "per-entity subqueries" not in planning |
| 35 | assert "head-to-head subquery" not in planning |
| 36 | |
| 37 | comparison = reference_text("comparison") |
| 38 | assert "for **TOPIC_A only**, not the whole vs-string" in comparison |
| 39 | assert "**When host web search is available, do WebSearch supplements**" in comparison |
| 40 | assert "`{TOPIC_A} vs {TOPIC_B} comparison {YEAR}`" in comparison |
| 41 | |
| 42 | |
| 43 | def test_comparison_command_preserves_stdin_plan_and_cleans_up_peer_plan(tmp_path): |
| 44 | text = reference_text("comparison") |
| 45 | marker = tmp_path / "must-not-execute" |
| 46 | untrusted = f"people's choice $(touch {shlex.quote(str(marker))})" |
| 47 | main_topic = f"McDonald's `Main Widget` $(touch {shlex.quote(str(marker))})" |
| 48 | quoted_context = 'The product says "zero setup" and uses C:\\docs' |
| 49 | main_plan = { |
| 50 | "intent": "general", |
| 51 | "freshness_mode": "balanced_recent", |
| 52 | "cluster_mode": "story", |
| 53 | "subqueries": [{ |
| 54 | "search_query": "Main Widget " + untrusted, |
| 55 | "ranking_query": "Main Widget people's experience", |
| 56 | "sources": ["reddit"], |
| 57 | }], |
| 58 | } |
| 59 | peer_plan = { |
| 60 | "Peer Widget": { |
| 61 | "x_handle": "peer_handle", "subreddits": ["peer_sub", "peer_extra"], |
| 62 | "github_user": "peer_github", "context": quoted_context + " " + untrusted, |
| 63 | }, |
| 64 | "Peer Three": { |
| 65 | "x_handle": "third_handle", "subreddits": ["third_sub"], |
| 66 | "github_user": "third_github", "context": "McDonald's `literal backticks`", |
| 67 | }, |
| 68 | } |
| 69 | replacements = { |
| 70 | "QUERY_PLAN_JSON": json.dumps(main_plan), |
| 71 | "COMPETITORS_PLAN_JSON": json.dumps(peer_plan), |
| 72 | "TOPIC_A": main_topic, "TOPIC_B": "Peer Widget", "TOPIC_C": "Peer Three", |
| 73 | "TOPIC_A_HANDLE": f"main_handle$(touch {shlex.quote(str(marker))})", |
| 74 | "TOPIC_A_RELATED": "main_partner", |
| 75 | "TOPIC_A_SUBS": "main_sub", |
| 76 | } |
| 77 | command = _command(text, "With host web search") |
| 78 | for name, value in replacements.items(): |
| 79 | command = command.replace("{" + name + "}", value) |
| 80 | assert not re.search(r"\{(?:TOPIC|QUERY_PLAN)_[A-Z_]+\}", command) |
| 81 | |
| 82 | installed = tmp_path / "installed skill" |
| 83 | (installed / "scripts").mkdir(parents=True) |
| 84 | (installed / "scripts" / "last30days.py").write_text("") |
| 85 | capture = tmp_path / "engine calls.jsonl" |
| 86 | interpreter = tmp_path / "engine capture" |
| 87 | interpreter.write_text( |
| 88 | f"#!{sys.executable}\n" |
| 89 | "import json, os, pathlib, sys\n" |
| 90 | "args = sys.argv[1:]\n" |
| 91 | "if args[:3] == ['-I', '-m', 'json.tool']:\n" |
| 92 | " os.execv(sys.executable, [sys.executable, *args])\n" |
| 93 | "peer_path = pathlib.Path(args[args.index('--competitors-plan') + 1])\n" |
| 94 | "record = {'args': args, 'plans': [json.load(sys.stdin), json.loads(peer_path.read_text())], 'peer_path': str(peer_path)}\n" |
| 95 | f"with open({str(capture)!r}, 'a') as out: out.write(json.dumps(record) + '\\n')\n" |
| 96 | ) |
| 97 | interpreter.chmod(0o755) |
| 98 | binaries = tmp_path / "bin" |
| 99 | binaries.mkdir() |
| 100 | mktemp = shutil.which("mktemp") |
| 101 | assert mktemp |
| 102 | (binaries / "mktemp").write_text( |
| 103 | "#!/bin/sh\n" |
| 104 | 'case "$1" in *XXXXXX) ;; *) echo "BSD mktemp requires trailing XXXXXX" >&2; exit 1;; esac\n' |
| 105 | f"exec {shlex.quote(mktemp)} \"$@\"\n" |
| 106 | ) |
| 107 | (binaries / "mktemp").chmod(0o755) |
| 108 | temporary = tmp_path / "temporary plans" |
| 109 | temporary.mkdir() |
| 110 | envelope_dir = tmp_path / "X envelopes" |
| 111 | envelope_dir.mkdir() |
| 112 | (envelope_dir / "main.json").write_text("{}", encoding="utf-8") |
| 113 | parent_trap_marker = tmp_path / "parent trap ran" |
| 114 | command = 'trap \'rm -rf "$X_POSTS_DIR"; touch "$PARENT_TRAP_MARKER"\' EXIT\n' + command |
| 115 | result = subprocess.run( |
| 116 | ["bash", "-eC", "-c", command], cwd=tmp_path, |
| 117 | env={ |
| 118 | "PATH": str(binaries) + os.pathsep + os.defpath, |
| 119 | "HOME": str(tmp_path / "home"), |
| 120 | "SKILL_DIR": str(installed), |
| 121 | "LAST30DAYS_PYTHON": str(interpreter), |
| 122 | "LAST30DAYS_MEMORY_DIR": str(tmp_path / "saved research"), |
| 123 | "TMPDIR": str(temporary), |
| 124 | "X_POSTS_DIR": str(envelope_dir), |
| 125 | "PARENT_TRAP_MARKER": str(parent_trap_marker), |
| 126 | }, |
| 127 | text=True, capture_output=True, timeout=15, |
| 128 | ) |
| 129 | assert not marker.exists(), "plan content executed as shell code" |
| 130 | assert result.returncode == 0, result.stderr |
| 131 | calls = [json.loads(line) for line in capture.read_text().splitlines()] |
| 132 | assert len(calls) == 1 |
| 133 | call = calls[0] |
| 134 | assert call["args"][0] == str(installed / "scripts" / "last30days.py") |
| 135 | assert call["args"][1] == main_topic + " vs Peer Widget vs Peer Three" |
| 136 | assert f"--x-handle=main_handle$(touch {shlex.quote(str(marker))})" in call["args"] |
| 137 | assert "--x-related=main_partner" in call["args"] |
| 138 | assert "--subreddits=main_sub" in call["args"] |
| 139 | parsed = cli.build_parser().parse_args(call["args"][1:]) |
| 140 | assert parsed.emit == "compact" |
| 141 | assert parsed.plan == "-" |
| 142 | assert parsed.competitors_plan == call["peer_path"] |
| 143 | assert call["plans"][0] == main_plan |
| 144 | planner.validate_external_plan(call["plans"][0]) |
| 145 | assert call["plans"][1] == peer_plan |
| 146 | assert not Path(call["peer_path"]).exists() |
| 147 | assert list(temporary.iterdir()) == [] |
| 148 | assert parent_trap_marker.exists() |
| 149 | assert not envelope_dir.exists() |
| 150 | parsed_peers = cli.parse_competitors_plan(json.dumps(call["plans"][1])) |
| 151 | assert set(parsed_peers) == {"peer widget", "peer three"} |
| 152 | assert parsed_peers["peer widget"]["context"] == quoted_context + " " + untrusted |
| 153 | |
| 154 | |
| 155 | @pytest.mark.parametrize("peers", [("Peer One",), ("Peer One", "Peer Two")]) |
| 156 | def test_no_web_search_comparison_command_uses_engine_planning(tmp_path, peers): |
| 157 | text = reference_text("comparison") |
| 158 | command = _command(text, "Without host web search") |
| 159 | marker = tmp_path / "must-not-execute" |
| 160 | topic = f"McDonald's `Main` $(touch {shlex.quote(str(marker))}) vs " + " vs ".join(peers) |
| 161 | command = command.replace("{TOPIC_A} vs {TOPIC_B} vs {TOPIC_C}", topic) |
| 162 | |
| 163 | installed = tmp_path / "installed skill" |
| 164 | (installed / "scripts").mkdir(parents=True) |
| 165 | (installed / "scripts" / "last30days.py").write_text("") |
| 166 | capture = tmp_path / "engine args.json" |
| 167 | interpreter = tmp_path / "engine capture" |
| 168 | interpreter.write_text( |
| 169 | f"#!{sys.executable}\n" |
| 170 | "import json, sys\n" |
| 171 | f"open({str(capture)!r}, 'w').write(json.dumps(sys.argv[1:]))\n" |
| 172 | ) |
| 173 | interpreter.chmod(0o755) |
| 174 | result = subprocess.run( |
| 175 | ["bash", "-ec", command], cwd=tmp_path, |
| 176 | env={ |
| 177 | "PATH": os.defpath, |
| 178 | "SKILL_DIR": str(installed), |
| 179 | "LAST30DAYS_PYTHON": str(interpreter), |
| 180 | "LAST30DAYS_MEMORY_DIR": str(tmp_path / "saved research"), |
| 181 | }, |
| 182 | text=True, capture_output=True, timeout=15, |
| 183 | ) |
| 184 | assert not marker.exists(), "comparison topic executed as shell code" |
| 185 | assert result.returncode == 0, result.stderr |
| 186 | args = json.loads(capture.read_text()) |
| 187 | assert args[1] == topic |
| 188 | parsed = cli.build_parser().parse_args(args[1:]) |
| 189 | assert parsed.auto_resolve is True |
| 190 | assert parsed.plan is None |
| 191 | assert parsed.competitors_plan is None |
| 192 | assert parsed.emit == "compact" |
| 193 | |
| 194 | |
| 195 | @pytest.mark.parametrize("host", ["grok-bot", None], ids=["grok-bot", "opencode"]) |
| 196 | def test_no_web_host_lane_comparison_passes_posts_without_host_plan(tmp_path, host): |
| 197 | text = reference_text("comparison") |
| 198 | command = _command(text, "Without host web search") |
| 199 | command = command.replace("{TOPIC_A} vs {TOPIC_B} vs {TOPIC_C}", "Main Brand vs Peer Brand") |
| 200 | envelope_dir = tmp_path / "X envelopes" |
| 201 | envelope_dir.mkdir() |
| 202 | main_posts = envelope_dir / "main.json" |
| 203 | peer_posts = envelope_dir / "peer.json" |
| 204 | for path in (main_posts, peer_posts): |
| 205 | path.write_text("{}", encoding="utf-8") |
| 206 | peer_plan = { |
| 207 | "Main Brand": { |
| 208 | "x_posts": str(main_posts), "x_handle": "main_brand", |
| 209 | "x_related": ["main_partner"], |
| 210 | }, |
| 211 | "Peer Brand": {"x_posts": str(peer_posts), "x_handle": "peer_brand"}, |
| 212 | } |
| 213 | command = command.replace("{COMPETITORS_PLAN_JSON}", json.dumps(peer_plan)) |
| 214 | command = command.replace("{TOPIC_A_HANDLE}", "main_brand") |
| 215 | command = command.replace("{TOPIC_A_RELATED}", "main_partner") |
| 216 | parent_trap_marker = tmp_path / "parent trap ran" |
| 217 | command = 'trap \'rm -rf "$X_POSTS_DIR"; touch "$PARENT_TRAP_MARKER"\' EXIT\n' + command |
| 218 | |
| 219 | installed = tmp_path / "installed skill" |
| 220 | (installed / "scripts").mkdir(parents=True) |
| 221 | (installed / "scripts" / "last30days.py").write_text("") |
| 222 | capture = tmp_path / "engine call.json" |
| 223 | interpreter = tmp_path / "engine capture" |
| 224 | interpreter.write_text( |
| 225 | f"#!{sys.executable}\n" |
| 226 | "import json, os, pathlib, sys\n" |
| 227 | "args = sys.argv[1:]\n" |
| 228 | "if args[:3] == ['-I', '-m', 'json.tool']:\n" |
| 229 | " os.execv(sys.executable, [sys.executable, *args])\n" |
| 230 | "plan_path = pathlib.Path(args[args.index('--competitors-plan') + 1])\n" |
| 231 | "record = {'args': args, 'plan': json.loads(plan_path.read_text()), 'path': str(plan_path)}\n" |
| 232 | f"pathlib.Path({str(capture)!r}).write_text(json.dumps(record))\n" |
| 233 | ) |
| 234 | interpreter.chmod(0o755) |
| 235 | temporary = tmp_path / "temporary plans" |
| 236 | temporary.mkdir() |
| 237 | env = { |
| 238 | "PATH": os.defpath, |
| 239 | "SKILL_DIR": str(installed), |
| 240 | "LAST30DAYS_PYTHON": str(interpreter), |
| 241 | "LAST30DAYS_MEMORY_DIR": str(tmp_path / "saved research"), |
| 242 | "LAST30DAYS_X_HOST_LANE": "1", |
| 243 | "X_POSTS_DIR": str(envelope_dir), |
| 244 | "PARENT_TRAP_MARKER": str(parent_trap_marker), |
| 245 | "TMPDIR": str(temporary), |
| 246 | } |
| 247 | if host is not None: |
| 248 | env["LAST30DAYS_HOST"] = host |
| 249 | result = subprocess.run( |
| 250 | ["bash", "-eC", "-c", command], cwd=tmp_path, |
| 251 | env=env, text=True, capture_output=True, timeout=15, |
| 252 | ) |
| 253 | assert result.returncode == 0, result.stderr |
| 254 | call = json.loads(capture.read_text()) |
| 255 | parsed = cli.build_parser().parse_args(call["args"][1:]) |
| 256 | assert parsed.auto_resolve is True |
| 257 | assert parsed.plan is None |
| 258 | assert parsed.x_posts is None |
| 259 | assert parsed.x_handle == "main_brand" |
| 260 | assert parsed.x_related == "main_partner" |
| 261 | assert parsed.competitors_plan == call["path"] |
| 262 | assert call["plan"] == peer_plan |
| 263 | assert not Path(call["path"]).exists() |
| 264 | assert list(temporary.iterdir()) == [] |
| 265 | assert parent_trap_marker.exists() |
| 266 | assert not envelope_dir.exists() |
| 267 |